From 42ab67f5cad679232280464980480a43469a7e6d Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Tue, 8 Oct 2024 11:06:27 -0400 Subject: [PATCH 01/24] Updgrade to TS5 --- .vscode/launch.json | 18 + e2e/package.json | 2 +- integration/compat-interop/package.json | 2 +- integration/compat-typings/package.json | 2 +- integration/firebase/package.json | 2 +- package.json | 4 +- packages/analytics-compat/package.json | 2 +- packages/analytics-interop-types/package.json | 2 +- packages/analytics-types/package.json | 2 +- packages/analytics/package.json | 2 +- packages/app-check-compat/package.json | 2 +- packages/app-check-interop-types/package.json | 2 +- packages/app-check-types/package.json | 2 +- packages/app-check/package.json | 2 +- packages/app-compat/package.json | 2 +- packages/app-types/package.json | 2 +- packages/app/package.json | 2 +- packages/auth-compat/demo/package.json | 2 +- packages/auth-compat/package.json | 2 +- packages/auth-interop-types/package.json | 2 +- packages/auth-types/package.json | 2 +- packages/auth/package.json | 2 +- packages/auth/src/api/index.ts | 6 +- .../recaptcha_enterprise_verifier.ts | 2 +- packages/component/package.json | 2 +- packages/database-compat/package.json | 2 +- packages/database-types/package.json | 2 +- packages/database/package.json | 2 +- packages/firestore-compat/package.json | 2 +- packages/firestore/package.json | 2 +- packages/firestore/scripts/build-bundle.js | 2 +- packages/firestore/scripts/remove-asserts.js | 2 +- packages/firestore/scripts/remove-asserts.ts | 6 +- .../firestore/scripts/rename-internals.js | 2 +- .../firestore/scripts/rename-internals.ts | 2 +- packages/firestore/scripts/run-tests.js | 17 + .../platform/browser/byte_stream_reader.ts | 2 +- .../platform/browser/webchannel_connection.ts | 2 +- .../src/platform/byte_stream_reader.ts | 2 +- .../src/platform/node/byte_stream_reader.ts | 2 +- .../firestore/src/util/bundle_reader_impl.ts | 4 +- packages/firestore/src/util/byte_stream.ts | 2 +- .../firestore/test/unit/util/bundle.test.ts | 2 +- packages/functions-compat/package.json | 2 +- packages/functions-types/package.json | 2 +- packages/functions/package.json | 2 +- packages/installations-compat/package.json | 2 +- packages/installations-types/package.json | 2 +- packages/installations/package.json | 2 +- packages/logger/package.json | 2 +- packages/messaging-compat/package.json | 2 +- packages/messaging-interop-types/package.json | 2 +- packages/messaging/package.json | 2 +- .../interfaces/internal-message-payload.ts | 24 +- packages/performance-compat/package.json | 2 +- packages/performance-types/package.json | 2 +- packages/performance/package.json | 2 +- .../performance/src/utils/attributes_utils.ts | 17 +- packages/remote-config-compat/package.json | 2 +- packages/remote-config-types/package.json | 2 +- packages/remote-config/package.json | 2 +- .../rules-unit-testing/src/impl/discovery.ts | 2 +- packages/storage-compat/package.json | 2 +- packages/storage-types/package.json | 2 +- packages/storage/package.json | 2 +- packages/template-types/package.json | 2 +- packages/template/package.json | 2 +- packages/util/package.json | 2 +- packages/vertexai/package.json | 2 +- packages/webchannel-wrapper/package.json | 2 +- repo-scripts/changelog-generator/package.json | 4 +- .../new-tests/data-connect.input.d.ts | 455 + .../new-tests/data-connect.output.d.ts | 316 + .../prune-dts/new-tests/database.input.d.ts | 3207 +++++++ .../prune-dts/new-tests/database.output.d.ts | 1584 ++++ .../prune-dts/new-tests/firestore.input.d.ts | 8410 +++++++++++++++++ .../prune-dts/new-tests/firestore.output.d.ts | 3475 +++++++ .../prune-dts/new-tests/messaging.input.d.ts | 223 + .../prune-dts/new-tests/messaging.output.d.ts | 210 + .../new-tests/storage-public.input.d.ts | 1080 +++ .../new-tests/storage-public.output.d.ts | 796 ++ repo-scripts/prune-dts/prune-dts.test.ts | 2 +- repo-scripts/prune-dts/prune-dts.ts | 267 +- .../prune-dts/subtests/app.input.d.ts | 576 ++ .../prune-dts/subtests/app.output.d.ts | 470 + ...es-generics-through-inheritance.input.d.ts | 25 - ...s-generics-through-inheritance.output.d.ts | 24 - repo-scripts/prune-dts/tsconfig.json | 3 +- repo-scripts/size-analysis/package.json | 2 +- repo-scripts/size-analysis/rollup.config.js | 4 +- yarn.lock | 55 +- 91 files changed, 21182 insertions(+), 226 deletions(-) create mode 100644 packages/firestore/scripts/run-tests.js create mode 100644 repo-scripts/prune-dts/new-tests/data-connect.input.d.ts create mode 100644 repo-scripts/prune-dts/new-tests/data-connect.output.d.ts create mode 100644 repo-scripts/prune-dts/new-tests/database.input.d.ts create mode 100644 repo-scripts/prune-dts/new-tests/database.output.d.ts create mode 100644 repo-scripts/prune-dts/new-tests/firestore.input.d.ts create mode 100644 repo-scripts/prune-dts/new-tests/firestore.output.d.ts create mode 100644 repo-scripts/prune-dts/new-tests/messaging.input.d.ts create mode 100644 repo-scripts/prune-dts/new-tests/messaging.output.d.ts create mode 100644 repo-scripts/prune-dts/new-tests/storage-public.input.d.ts create mode 100644 repo-scripts/prune-dts/new-tests/storage-public.output.d.ts create mode 100644 repo-scripts/prune-dts/subtests/app.input.d.ts create mode 100644 repo-scripts/prune-dts/subtests/app.output.d.ts delete mode 100644 repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts delete mode 100644 repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts diff --git a/.vscode/launch.json b/.vscode/launch.json index 37e64370169..e0a16340123 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,6 +4,24 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Prune .d.ts", + "program": "${workspaceRoot}/repo-scripts/prune-dts/node_modules/.bin/_mocha", + "cwd": "${workspaceRoot}/repo-scripts/prune-dts", + "args": [ + "--require", + "ts-node/register", + "--timeout", + "5000", + "${workspaceFolder}/repo-scripts/prune-dts/*.test.ts" + ], + "env": { + "TS_NODE_COMPILER_OPTIONS" : "{\"module\":\"commonjs\"}" + }, + "sourceMaps": true, + }, { "type": "node", "request": "launch", diff --git a/e2e/package.json b/e2e/package.json index 676498d6142..7641562cd5b 100644 --- a/e2e/package.json +++ b/e2e/package.json @@ -34,7 +34,7 @@ "karma-typescript": "5.5.4", "karma-typescript-es6-transform": "5.5.4", "mocha": "9.2.2", - "typescript": "4.7.4", + "typescript": "5.5.4", "webpack": "5.76.0", "webpack-cli": "4.10.0", "webpack-dev-server": "4.11.1" diff --git a/integration/compat-interop/package.json b/integration/compat-interop/package.json index 1a29321d4cb..538d9e34a30 100644 --- a/integration/compat-interop/package.json +++ b/integration/compat-interop/package.json @@ -24,7 +24,7 @@ "@firebase/remote-config-compat": "0.2.9" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" }, "engines": { "node": ">=18.0.0" diff --git a/integration/compat-typings/package.json b/integration/compat-typings/package.json index 9c0802f888d..45ed087a0d7 100644 --- a/integration/compat-typings/package.json +++ b/integration/compat-typings/package.json @@ -10,7 +10,7 @@ "firebase": "*" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" }, "engines": { "node": ">=18.0.0" diff --git a/integration/firebase/package.json b/integration/firebase/package.json index 464307cbada..b3f2de729d8 100644 --- a/integration/firebase/package.json +++ b/integration/firebase/package.json @@ -20,7 +20,7 @@ "karma-typescript": "5.5.4", "mocha": "9.2.2", "npm-run-all": "4.1.5", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "engines": { "node": ">=18.0.0" diff --git a/package.json b/package.json index a2e85a8f4fb..d7493067196 100644 --- a/package.json +++ b/package.json @@ -80,7 +80,7 @@ "@types/long": "4.0.2", "@types/mocha": "9.1.1", "@types/mz": "2.7.8", - "@types/node": "16.18.68", + "@types/node": "22.7.5", "@types/request": "2.48.12", "@types/sinon": "9.0.11", "@types/sinon-chai": "3.2.12", @@ -156,7 +156,7 @@ "tsec": "0.2.8", "tslint": "6.1.3", "typedoc": "0.16.11", - "typescript": "4.7.4", + "typescript": "5.5.4", "watch": "1.0.2", "webpack": "5.76.0", "yargs": "17.7.2" diff --git a/packages/analytics-compat/package.json b/packages/analytics-compat/package.json index 6d29aa1a946..211a6943692 100644 --- a/packages/analytics-compat/package.json +++ b/packages/analytics-compat/package.json @@ -26,7 +26,7 @@ "rollup": "2.79.1", "@rollup/plugin-json": "4.1.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/analytics-compat", diff --git a/packages/analytics-interop-types/package.json b/packages/analytics-interop-types/package.json index 79526603147..f0a988897d9 100644 --- a/packages/analytics-interop-types/package.json +++ b/packages/analytics-interop-types/package.json @@ -20,6 +20,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/analytics-types/package.json b/packages/analytics-types/package.json index 4b9452848f0..26ac177f142 100644 --- a/packages/analytics-types/package.json +++ b/packages/analytics-types/package.json @@ -20,6 +20,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/analytics/package.json b/packages/analytics/package.json index 1aac69cbcb7..983e1f01a88 100644 --- a/packages/analytics/package.json +++ b/packages/analytics/package.json @@ -53,7 +53,7 @@ "@rollup/plugin-json": "4.1.0", "@rollup/plugin-node-resolve": "13.3.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/analytics", diff --git a/packages/app-check-compat/package.json b/packages/app-check-compat/package.json index eea726966fe..b0c38d00cef 100644 --- a/packages/app-check-compat/package.json +++ b/packages/app-check-compat/package.json @@ -49,7 +49,7 @@ "@rollup/plugin-json": "4.1.0", "@rollup/plugin-node-resolve": "13.3.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/app-check", diff --git a/packages/app-check-interop-types/package.json b/packages/app-check-interop-types/package.json index 983eca2a748..333ca0649af 100644 --- a/packages/app-check-interop-types/package.json +++ b/packages/app-check-interop-types/package.json @@ -20,6 +20,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/app-check-types/package.json b/packages/app-check-types/package.json index fdc130f4281..16a3692e2de 100644 --- a/packages/app-check-types/package.json +++ b/packages/app-check-types/package.json @@ -20,6 +20,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/app-check/package.json b/packages/app-check/package.json index 2426cd1f61b..0a982277c11 100644 --- a/packages/app-check/package.json +++ b/packages/app-check/package.json @@ -50,7 +50,7 @@ "@rollup/plugin-json": "4.1.0", "@rollup/plugin-node-resolve": "13.3.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/app-check", diff --git a/packages/app-compat/package.json b/packages/app-compat/package.json index 1d9793f9a7e..2cd7fa719c4 100644 --- a/packages/app-compat/package.json +++ b/packages/app-compat/package.json @@ -48,7 +48,7 @@ "@rollup/plugin-json": "4.1.0", "rollup-plugin-replace": "2.2.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/app-compat", diff --git a/packages/app-types/package.json b/packages/app-types/package.json index cd2e3ce4533..9edbf4b1290 100644 --- a/packages/app-types/package.json +++ b/packages/app-types/package.json @@ -24,6 +24,6 @@ "@firebase/logger": "0.2.6" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/app/package.json b/packages/app/package.json index 4e9f15e976e..1ce35460f93 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -50,7 +50,7 @@ "rollup-plugin-replace": "2.2.0", "rollup-plugin-typescript2": "0.31.2", "rollup-plugin-dts": "5.3.1", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/app", diff --git a/packages/auth-compat/demo/package.json b/packages/auth-compat/demo/package.json index 098a3ad3007..b6cc9d3c142 100644 --- a/packages/auth-compat/demo/package.json +++ b/packages/auth-compat/demo/package.json @@ -34,7 +34,7 @@ "rollup-plugin-sourcemaps": "0.6.3", "rollup-plugin-typescript2": "0.31.2", "rollup-plugin-uglify": "6.0.4", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/auth-compat/demo", diff --git a/packages/auth-compat/package.json b/packages/auth-compat/package.json index 654e52f1f0b..d6c43056adc 100644 --- a/packages/auth-compat/package.json +++ b/packages/auth-compat/package.json @@ -63,7 +63,7 @@ "rollup-plugin-replace": "2.2.0", "rollup-plugin-typescript2": "0.31.2", "selenium-webdriver": "4.8.0", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/auth-compat", diff --git a/packages/auth-interop-types/package.json b/packages/auth-interop-types/package.json index ed0f01f6f09..9cfc47fad7a 100644 --- a/packages/auth-interop-types/package.json +++ b/packages/auth-interop-types/package.json @@ -20,6 +20,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/auth-types/package.json b/packages/auth-types/package.json index c8ec943e011..f1e8cf3fae6 100644 --- a/packages/auth-types/package.json +++ b/packages/auth-types/package.json @@ -24,6 +24,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/auth/package.json b/packages/auth/package.json index 2139a5e506f..c014d2ff14f 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -141,7 +141,7 @@ "rollup-plugin-typescript2": "0.31.2", "selenium-webdriver": "4.8.0", "totp-generator": "0.0.14", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/auth", diff --git a/packages/auth/src/api/index.ts b/packages/auth/src/api/index.ts index d0b21252edb..4813ace9507 100644 --- a/packages/auth/src/api/index.ts +++ b/packages/auth/src/api/index.ts @@ -241,20 +241,20 @@ export async function _performSignInRequest( request?: T, customErrorMap: Partial> = {} ): Promise { - const serverResponse = (await _performApiRequest( + const serverResponse = await _performApiRequest( auth, method, path, request, customErrorMap - )) as V; + ); if ('mfaPendingCredential' in serverResponse) { _fail(auth, AuthErrorCode.MFA_REQUIRED, { _serverResponse: serverResponse }); } - return serverResponse; + return serverResponse as V; } export function _getFinalTarget( diff --git a/packages/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts b/packages/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts index d6074775fef..0543c030682 100644 --- a/packages/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts +++ b/packages/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts @@ -162,7 +162,7 @@ export class RecaptchaEnterpriseVerifier { } } -export async function injectRecaptchaFields( +export async function injectRecaptchaFields( auth: AuthInternal, request: T, action: RecaptchaActionName, diff --git a/packages/component/package.json b/packages/component/package.json index 1f3b8ad51a8..b04bbe7002b 100644 --- a/packages/component/package.json +++ b/packages/component/package.json @@ -38,7 +38,7 @@ "devDependencies": { "rollup": "2.79.1", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/component", diff --git a/packages/database-compat/package.json b/packages/database-compat/package.json index ba403db1fe3..6ddefe98fba 100644 --- a/packages/database-compat/package.json +++ b/packages/database-compat/package.json @@ -58,7 +58,7 @@ }, "devDependencies": { "@firebase/app-compat": "0.2.43", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/database-compat", diff --git a/packages/database-types/package.json b/packages/database-types/package.json index 76191ca33dd..a12dffc2f87 100644 --- a/packages/database-types/package.json +++ b/packages/database-types/package.json @@ -24,6 +24,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/database/package.json b/packages/database/package.json index 78d82b163e8..487f1e9547b 100644 --- a/packages/database/package.json +++ b/packages/database/package.json @@ -60,7 +60,7 @@ "@firebase/app": "0.10.13", "rollup": "2.79.1", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/database", diff --git a/packages/firestore-compat/package.json b/packages/firestore-compat/package.json index 48b1d9ad679..9363cb1211f 100644 --- a/packages/firestore-compat/package.json +++ b/packages/firestore-compat/package.json @@ -61,7 +61,7 @@ "rollup-plugin-typescript2": "0.31.2", "@rollup/plugin-node-resolve": "13.3.0", "ts-node": "10.9.1", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "license": "Apache-2.0", "typings": "dist/src/index.d.ts", diff --git a/packages/firestore/package.json b/packages/firestore/package.json index b6201cd501d..6152d27cc33 100644 --- a/packages/firestore/package.json +++ b/packages/firestore/package.json @@ -125,7 +125,7 @@ "rollup-plugin-typescript2": "0.31.2", "rollup-plugin-dts": "5.3.1", "ts-node": "10.9.1", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/firestore", diff --git a/packages/firestore/scripts/build-bundle.js b/packages/firestore/scripts/build-bundle.js index e7d1fdf5145..b44311571e3 100644 --- a/packages/firestore/scripts/build-bundle.js +++ b/packages/firestore/scripts/build-bundle.js @@ -14,4 +14,4 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]=0){var method=declaration.name.text;if(method==="debugAssert"){updatedNode=ts.createOmittedExpression()}else if(method==="hardAssert"){updatedNode=ts.createCall(declaration.name,undefined,[node.arguments[0]])}else if(method==="fail"){updatedNode=ts.createCall(declaration.name,undefined,[])}}}}if(updatedNode){ts.setSourceMapRange(updatedNode,ts.getSourceMapRange(node));return updatedNode}else{return node}};return RemoveAsserts}(); + */exports.__esModule=true;exports.removeAsserts=void 0;var ts=require("typescript");var ASSERT_LOCATION="packages/firestore/src/util/assert.ts";function removeAsserts(program){var removeAsserts=new RemoveAsserts(program.getTypeChecker());return function(context){return function(file){return removeAsserts.visitNodeAndChildren(file,context)}}}exports.removeAsserts=removeAsserts;var RemoveAsserts=function(){function RemoveAsserts(typeChecker){this.typeChecker=typeChecker}RemoveAsserts.prototype.visitNodeAndChildren=function(node,context){var _this=this;return ts.visitEachChild(this.visitNode(node),(function(childNode){return _this.visitNodeAndChildren(childNode,context)}),context)};RemoveAsserts.prototype.visitNode=function(node){var updatedNode=null;if(ts.isCallExpression(node)){var signature=this.typeChecker.getResolvedSignature(node);if(signature&&signature.declaration&&signature.declaration.kind===ts.SyntaxKind.FunctionDeclaration){var declaration=signature.declaration;if(declaration&&declaration.getSourceFile().fileName.indexOf(ASSERT_LOCATION)>=0){var method=declaration.name.text;if(method==="debugAssert"){updatedNode=ts.factory.createOmittedExpression()}else if(method==="hardAssert"){updatedNode=ts.factory.createCallExpression(declaration.name,undefined,[node.arguments[0]])}else if(method==="fail"){updatedNode=ts.factory.createCallExpression(declaration.name,undefined,[])}}}}if(updatedNode){ts.setSourceMapRange(updatedNode,ts.getSourceMapRange(node));return updatedNode}else{return node}};return RemoveAsserts}(); \ No newline at end of file diff --git a/packages/firestore/scripts/remove-asserts.ts b/packages/firestore/scripts/remove-asserts.ts index f195f7bd2ab..fb3e2af6a34 100644 --- a/packages/firestore/scripts/remove-asserts.ts +++ b/packages/firestore/scripts/remove-asserts.ts @@ -64,17 +64,17 @@ class RemoveAsserts { ) { const method = declaration.name!.text; if (method === 'debugAssert') { - updatedNode = ts.createOmittedExpression(); + updatedNode = ts.factory.createOmittedExpression(); } else if (method === 'hardAssert') { // Remove the log message but keep the assertion - updatedNode = ts.createCall( + updatedNode = ts.factory.createCallExpression( declaration.name!, /*typeArgs*/ undefined, [node.arguments[0]] ); } else if (method === 'fail') { // Remove the log message - updatedNode = ts.createCall( + updatedNode = ts.factory.createCallExpression( declaration.name!, /*typeArgs*/ undefined, [] diff --git a/packages/firestore/scripts/rename-internals.js b/packages/firestore/scripts/rename-internals.js index 6015ec0540a..fa8394a2261 100644 --- a/packages/firestore/scripts/rename-internals.js +++ b/packages/firestore/scripts/rename-internals.js @@ -14,4 +14,4 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */exports.__esModule=true;exports.renameInternals=void 0;var ts=require("typescript");var ignoredIdentifiers=["undefined"];var RenameInternals=function(){function RenameInternals(publicApi,prefix){this.publicApi=publicApi;this.prefix=prefix}RenameInternals.prototype.visitNodeAndChildren=function(node,context){var _this=this;return ts.visitEachChild(this.visitNode(node),(function(childNode){return _this.visitNodeAndChildren(childNode,context)}),context)};RenameInternals.prototype.visitNode=function(node){if(ts.isIdentifier(node)){var name_1=node.escapedText.toString();if(!this.publicApi.has(name_1)&&ignoredIdentifiers.indexOf(node.escapedText.toString())===-1){var newIdentifier=ts.createIdentifier(this.prefix+name_1);ts.setSourceMapRange(newIdentifier,ts.getSourceMapRange(node));return newIdentifier}}return node};return RenameInternals}();var DEFAULT_PREFIX="_";function renameInternals(program,config){var _a;var prefix=(_a=config.prefix)!==null&&_a!==void 0?_a:DEFAULT_PREFIX;var renamer=new RenameInternals(config.publicIdentifiers,prefix);return function(context){return function(file){return renamer.visitNodeAndChildren(file,context)}}}exports.renameInternals=renameInternals; \ No newline at end of file + */exports.__esModule=true;exports.renameInternals=void 0;var ts=require("typescript");var ignoredIdentifiers=["undefined"];var RenameInternals=function(){function RenameInternals(publicApi,prefix){this.publicApi=publicApi;this.prefix=prefix}RenameInternals.prototype.visitNodeAndChildren=function(node,context){var _this=this;return ts.visitEachChild(this.visitNode(node),(function(childNode){return _this.visitNodeAndChildren(childNode,context)}),context)};RenameInternals.prototype.visitNode=function(node){if(ts.isIdentifier(node)){var name_1=node.escapedText.toString();if(!this.publicApi.has(name_1)&&ignoredIdentifiers.indexOf(node.escapedText.toString())===-1){var newIdentifier=ts.factory.createIdentifier(this.prefix+name_1);ts.setSourceMapRange(newIdentifier,ts.getSourceMapRange(node));return newIdentifier}}return node};return RenameInternals}();var DEFAULT_PREFIX="_";function renameInternals(program,config){var _a;var prefix=(_a=config.prefix)!==null&&_a!==void 0?_a:DEFAULT_PREFIX;var renamer=new RenameInternals(config.publicIdentifiers,prefix);return function(context){return function(file){return renamer.visitNodeAndChildren(file,context)}}}exports.renameInternals=renameInternals; \ No newline at end of file diff --git a/packages/firestore/scripts/rename-internals.ts b/packages/firestore/scripts/rename-internals.ts index dfe691e1913..985c50d7249 100644 --- a/packages/firestore/scripts/rename-internals.ts +++ b/packages/firestore/scripts/rename-internals.ts @@ -48,7 +48,7 @@ class RenameInternals { !this.publicApi.has(name) && ignoredIdentifiers.indexOf(node.escapedText.toString()) === -1 ) { - const newIdentifier = ts.createIdentifier(this.prefix + name); + const newIdentifier = ts.factory.createIdentifier(this.prefix + name); ts.setSourceMapRange(newIdentifier, ts.getSourceMapRange(node)); return newIdentifier; } diff --git a/packages/firestore/scripts/run-tests.js b/packages/firestore/scripts/run-tests.js new file mode 100644 index 00000000000..88b9f05ee55 --- /dev/null +++ b/packages/firestore/scripts/run-tests.js @@ -0,0 +1,17 @@ +"use strict"; +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */exports.__esModule=true;var path_1=require("path");var child_process_promise_1=require("child-process-promise");var yargs=require("yargs");var argv=yargs.options({main:{type:"string",demandOption:true},platform:{type:"string",default:"node"},emulator:{type:"boolean"},persistence:{type:"boolean"},databaseId:{type:"string"}}).parseSync();var nyc=(0,path_1.resolve)(__dirname,"../../../node_modules/.bin/nyc");var mocha=(0,path_1.resolve)(__dirname,"../../../node_modules/.bin/mocha");var babel=(0,path_1.resolve)(__dirname,"../babel-register.js");process.env.NO_TS_NODE="true";process.env.TEST_PLATFORM=argv.platform;var args=["--reporter","lcovonly",mocha,"--require",babel,"--require",argv.main,"--config","../../config/mocharc.node.js"];if(argv.emulator){process.env.FIRESTORE_TARGET_BACKEND="emulator"}if(argv.persistence){process.env.USE_MOCK_PERSISTENCE="YES";args.push("--require","test/util/node_persistence.ts")}if(argv.databaseId){process.env.FIRESTORE_TARGET_DB_ID=argv.databaseId}args=args.concat(argv._);var childProcess=(0,child_process_promise_1.spawn)(nyc,args,{stdio:"inherit",cwd:process.cwd()}).childProcess;process.once("exit",(function(){return childProcess.kill()}));process.once("SIGINT",(function(){return childProcess.kill("SIGINT")}));process.once("SIGTERM",(function(){return childProcess.kill("SIGTERM")})); \ No newline at end of file diff --git a/packages/firestore/src/platform/browser/byte_stream_reader.ts b/packages/firestore/src/platform/browser/byte_stream_reader.ts index 65875d4b225..82a4138218a 100644 --- a/packages/firestore/src/platform/browser/byte_stream_reader.ts +++ b/packages/firestore/src/platform/browser/byte_stream_reader.ts @@ -24,7 +24,7 @@ import { toByteStreamReaderHelper } from '../../util/byte_stream'; export function toByteStreamReader( source: BundleSource, bytesPerRead: number -): ReadableStreamReader { +): ReadableStreamDefaultReader { if (source instanceof Uint8Array) { return toByteStreamReaderHelper(source, bytesPerRead); } diff --git a/packages/firestore/src/platform/browser/webchannel_connection.ts b/packages/firestore/src/platform/browser/webchannel_connection.ts index 83e8faef88a..6813b88f65a 100644 --- a/packages/firestore/src/platform/browser/webchannel_connection.ts +++ b/packages/firestore/src/platform/browser/webchannel_connection.ts @@ -359,7 +359,7 @@ export class WebChannelConnection extends RestConnection { // Use any because msgData.error is not typed. const msgDataOrError: WebChannelError | object = msgData; const error = - msgDataOrError.error || + (msgDataOrError as WebChannelError)?.error || (msgDataOrError as WebChannelError[])[0]?.error; if (error) { logDebug( diff --git a/packages/firestore/src/platform/byte_stream_reader.ts b/packages/firestore/src/platform/byte_stream_reader.ts index c66d19ee354..1442c0df294 100644 --- a/packages/firestore/src/platform/byte_stream_reader.ts +++ b/packages/firestore/src/platform/byte_stream_reader.ts @@ -27,7 +27,7 @@ import * as rn from './rn/byte_stream_reader'; export function toByteStreamReader( source: BundleSource, bytesPerRead: number = DEFAULT_BYTES_PER_READ -): ReadableStreamReader { +): ReadableStreamDefaultReader { if (isNode()) { return node.toByteStreamReader(source, bytesPerRead); } else if (isReactNative()) { diff --git a/packages/firestore/src/platform/node/byte_stream_reader.ts b/packages/firestore/src/platform/node/byte_stream_reader.ts index 9add9ce3cc9..507f13dfc21 100644 --- a/packages/firestore/src/platform/node/byte_stream_reader.ts +++ b/packages/firestore/src/platform/node/byte_stream_reader.ts @@ -26,7 +26,7 @@ import { valueDescription } from '../../util/input_validation'; export function toByteStreamReader( source: BundleSource, bytesPerRead: number -): ReadableStreamReader { +): ReadableStreamDefaultReader { if (!(source instanceof Uint8Array)) { throw new FirestoreError( Code.INVALID_ARGUMENT, diff --git a/packages/firestore/src/util/bundle_reader_impl.ts b/packages/firestore/src/util/bundle_reader_impl.ts index 05875fce1af..1e8890bf5a9 100644 --- a/packages/firestore/src/util/bundle_reader_impl.ts +++ b/packages/firestore/src/util/bundle_reader_impl.ts @@ -42,7 +42,7 @@ class BundleReaderImpl implements BundleReader { constructor( /** The reader to read from underlying binary bundle data source. */ - private reader: ReadableStreamReader, + private reader: ReadableStreamDefaultReader, readonly serializer: JsonProtoSerializer ) { this.textDecoder = newTextDecoder(); @@ -192,7 +192,7 @@ class BundleReaderImpl implements BundleReader { } export function newBundleReader( - reader: ReadableStreamReader, + reader: ReadableStreamDefaultReader, serializer: JsonProtoSerializer ): BundleReader { return new BundleReaderImpl(reader, serializer); diff --git a/packages/firestore/src/util/byte_stream.ts b/packages/firestore/src/util/byte_stream.ts index 0b65823ac91..1950ef1d316 100644 --- a/packages/firestore/src/util/byte_stream.ts +++ b/packages/firestore/src/util/byte_stream.ts @@ -33,7 +33,7 @@ export const DEFAULT_BYTES_PER_READ = 10240; export function toByteStreamReaderHelper( source: Uint8Array, bytesPerRead: number = DEFAULT_BYTES_PER_READ -): ReadableStreamReader { +): ReadableStreamDefaultReader { debugAssert( bytesPerRead > 0, `toByteStreamReader expects positive bytesPerRead, but got ${bytesPerRead}` diff --git a/packages/firestore/test/unit/util/bundle.test.ts b/packages/firestore/test/unit/util/bundle.test.ts index b32ca0842b7..13647efa470 100644 --- a/packages/firestore/test/unit/util/bundle.test.ts +++ b/packages/firestore/test/unit/util/bundle.test.ts @@ -59,7 +59,7 @@ const encoder = newTextEncoder(); export function byteStreamReaderFromString( content: string, bytesPerRead: number -): ReadableStreamReader { +): ReadableStreamDefaultReader { const data = encoder.encode(content); return toByteStreamReader(data, bytesPerRead); } diff --git a/packages/functions-compat/package.json b/packages/functions-compat/package.json index e5687ed0006..5e822a20a89 100644 --- a/packages/functions-compat/package.json +++ b/packages/functions-compat/package.json @@ -33,7 +33,7 @@ "rollup": "2.79.1", "@rollup/plugin-json": "4.1.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/functions-compat", diff --git a/packages/functions-types/package.json b/packages/functions-types/package.json index 9c59d3f954a..b237ffcf752 100644 --- a/packages/functions-types/package.json +++ b/packages/functions-types/package.json @@ -20,6 +20,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/functions/package.json b/packages/functions/package.json index 7669d53c755..931ce836b68 100644 --- a/packages/functions/package.json +++ b/packages/functions/package.json @@ -53,7 +53,7 @@ "rollup": "2.79.1", "@rollup/plugin-json": "4.1.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/functions", diff --git a/packages/installations-compat/package.json b/packages/installations-compat/package.json index 2be8f15d00b..12f7199ed72 100644 --- a/packages/installations-compat/package.json +++ b/packages/installations-compat/package.json @@ -51,7 +51,7 @@ "@rollup/plugin-node-resolve": "13.3.0", "rollup-plugin-typescript2": "0.31.2", "rollup-plugin-uglify": "6.0.4", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "peerDependencies": { "@firebase/app-compat": "0.x" diff --git a/packages/installations-types/package.json b/packages/installations-types/package.json index f2f06145f52..7647ad385c8 100644 --- a/packages/installations-types/package.json +++ b/packages/installations-types/package.json @@ -23,6 +23,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/installations/package.json b/packages/installations/package.json index aaac492b3c2..66556af5942 100644 --- a/packages/installations/package.json +++ b/packages/installations/package.json @@ -56,7 +56,7 @@ "@rollup/plugin-node-resolve": "13.3.0", "rollup-plugin-typescript2": "0.31.2", "rollup-plugin-uglify": "6.0.4", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "peerDependencies": { "@firebase/app": "0.x" diff --git a/packages/logger/package.json b/packages/logger/package.json index 14131f73258..5b66720c021 100644 --- a/packages/logger/package.json +++ b/packages/logger/package.json @@ -37,7 +37,7 @@ "devDependencies": { "rollup": "2.79.1", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/logger", diff --git a/packages/messaging-compat/package.json b/packages/messaging-compat/package.json index 258455c0a96..4b460d785c3 100644 --- a/packages/messaging-compat/package.json +++ b/packages/messaging-compat/package.json @@ -48,7 +48,7 @@ "@rollup/plugin-json": "4.1.0", "rollup-plugin-typescript2": "0.31.2", "ts-essentials": "9.3.0", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/messaging", diff --git a/packages/messaging-interop-types/package.json b/packages/messaging-interop-types/package.json index 0de782552ff..2defbc5076f 100644 --- a/packages/messaging-interop-types/package.json +++ b/packages/messaging-interop-types/package.json @@ -20,6 +20,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/messaging/package.json b/packages/messaging/package.json index 1b56371b35b..8f0f53b694b 100644 --- a/packages/messaging/package.json +++ b/packages/messaging/package.json @@ -65,7 +65,7 @@ "rollup-plugin-typescript2": "0.31.2", "@rollup/plugin-json": "4.1.0", "ts-essentials": "9.3.0", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/messaging", diff --git a/packages/messaging/src/interfaces/internal-message-payload.ts b/packages/messaging/src/interfaces/internal-message-payload.ts index 823959e9544..f0a0f99b1d4 100644 --- a/packages/messaging/src/interfaces/internal-message-payload.ts +++ b/packages/messaging/src/interfaces/internal-message-payload.ts @@ -33,7 +33,29 @@ export interface MessagePayloadInternal { collapse_key: string; } -export interface NotificationPayloadInternal extends NotificationOptions { +// https://developer.mozilla.org/en-US/docs/Web/API/Notification/actions +interface NotificationAction { + action: string; + icon?: string; + title: string; +} + +/** + * This interface defines experimental properties of NotificationOptions, that are not part of + * the interface in the generated DOM types at https://github.com/microsoft/TypeScript-DOM-lib-generator/blob/179bdd84a944933a3103f29c2274c9f5a857b693/baselines/dom.generated.d.ts#L1012 + * https://developer.mozilla.org/en-US/docs/Web/API/Notification + */ +interface NotificationOptionsExperimental extends NotificationOptions { + readonly maxActions?: number; + readonly actions?: NotificationAction[]; + readonly image?: string; + readonly renotify?: boolean; + readonly timestamp?: EpochTimeStamp; + readonly vibrate?: VibratePattern; +} + +export interface NotificationPayloadInternal + extends NotificationOptionsExperimental { title: string; // Supported in the Legacy Send API. // See:https://firebase.google.com/docs/cloud-messaging/xmpp-server-ref. diff --git a/packages/performance-compat/package.json b/packages/performance-compat/package.json index 856c57b39e8..28e020cab3c 100644 --- a/packages/performance-compat/package.json +++ b/packages/performance-compat/package.json @@ -50,7 +50,7 @@ "@rollup/plugin-json": "4.1.0", "rollup-plugin-replace": "2.2.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4", + "typescript": "5.5.4", "@firebase/app-compat": "0.2.43" }, "repository": { diff --git a/packages/performance-types/package.json b/packages/performance-types/package.json index 7bfe59f1e95..8bc3fd83093 100644 --- a/packages/performance-types/package.json +++ b/packages/performance-types/package.json @@ -12,7 +12,7 @@ "index.d.ts" ], "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/performance-types", diff --git a/packages/performance/package.json b/packages/performance/package.json index c55805ddefc..1921fdd6e0b 100644 --- a/packages/performance/package.json +++ b/packages/performance/package.json @@ -50,7 +50,7 @@ "rollup": "2.79.1", "@rollup/plugin-json": "4.1.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/performance", diff --git a/packages/performance/src/utils/attributes_utils.ts b/packages/performance/src/utils/attributes_utils.ts index 294881a99d4..81bb2234bfe 100644 --- a/packages/performance/src/utils/attributes_utils.ts +++ b/packages/performance/src/utils/attributes_utils.ts @@ -39,14 +39,27 @@ const enum EffectiveConnectionType { CONNECTION_4G = 4 } +type ConnectionType = + | 'bluetooth' + | 'cellular' + | 'ethernet' + | 'mixed' + | 'none' + | 'other' + | 'unknown' + | 'wifi'; + /** * NetworkInformation + * This API is not well supported in all major browsers, so TypeScript does not provide types for it. * * ref: https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation */ +interface NetworkInformation extends EventTarget { + readonly type: ConnectionType; +} + interface NetworkInformationWithEffectiveType extends NetworkInformation { - // `effectiveType` is an experimental property and not included in - // TypeScript's typings for the native NetworkInformation interface readonly effectiveType?: 'slow-2g' | '2g' | '3g' | '4g'; } diff --git a/packages/remote-config-compat/package.json b/packages/remote-config-compat/package.json index 1b991c7b929..688a8bf17ba 100644 --- a/packages/remote-config-compat/package.json +++ b/packages/remote-config-compat/package.json @@ -49,7 +49,7 @@ "@rollup/plugin-json": "4.1.0", "rollup-plugin-replace": "2.2.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4", + "typescript": "5.5.4", "@firebase/app-compat": "0.2.43" }, "repository": { diff --git a/packages/remote-config-types/package.json b/packages/remote-config-types/package.json index 29b39d10900..7d83613b25c 100644 --- a/packages/remote-config-types/package.json +++ b/packages/remote-config-types/package.json @@ -20,6 +20,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/remote-config/package.json b/packages/remote-config/package.json index 5049ef00db5..56588b9fea9 100644 --- a/packages/remote-config/package.json +++ b/packages/remote-config/package.json @@ -51,7 +51,7 @@ "@firebase/app": "0.10.13", "rollup": "2.79.1", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/remote-config", diff --git a/packages/rules-unit-testing/src/impl/discovery.ts b/packages/rules-unit-testing/src/impl/discovery.ts index 3c7c20fedad..4d57660aa60 100644 --- a/packages/rules-unit-testing/src/impl/discovery.ts +++ b/packages/rules-unit-testing/src/impl/discovery.ts @@ -87,7 +87,7 @@ export function getEmulatorHostAndPort( conf?: EmulatorConfig, discovered?: DiscoveredEmulators ) { - if (conf && ('host' in conf || 'port' in conf)) { + if (conf && 'host' in conf && 'port' in conf) { const { host, port } = conf; if (host || port) { if (!host || !port) { diff --git a/packages/storage-compat/package.json b/packages/storage-compat/package.json index d3ed249c331..4eccfbfaa12 100644 --- a/packages/storage-compat/package.json +++ b/packages/storage-compat/package.json @@ -49,7 +49,7 @@ "rollup": "2.79.1", "@rollup/plugin-json": "4.1.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "files": [ "dist" diff --git a/packages/storage-types/package.json b/packages/storage-types/package.json index 1ace578c836..b27148fa740 100644 --- a/packages/storage-types/package.json +++ b/packages/storage-types/package.json @@ -24,6 +24,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/storage/package.json b/packages/storage/package.json index ffc36afb242..8aaad9abab0 100644 --- a/packages/storage/package.json +++ b/packages/storage/package.json @@ -60,7 +60,7 @@ "@rollup/plugin-alias": "5.1.0", "@rollup/plugin-json": "4.1.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/storage", diff --git a/packages/template-types/package.json b/packages/template-types/package.json index 4929e4ec907..d1925c4d409 100644 --- a/packages/template-types/package.json +++ b/packages/template-types/package.json @@ -21,6 +21,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" } } diff --git a/packages/template/package.json b/packages/template/package.json index a2b19546440..3f44e6a86ba 100644 --- a/packages/template/package.json +++ b/packages/template/package.json @@ -51,7 +51,7 @@ "@firebase/app": "0.10.13", "rollup": "2.79.1", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/template", diff --git a/packages/util/package.json b/packages/util/package.json index fa30ebd15d9..743e108debc 100644 --- a/packages/util/package.json +++ b/packages/util/package.json @@ -47,7 +47,7 @@ "devDependencies": { "rollup": "2.79.1", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/util", diff --git a/packages/vertexai/package.json b/packages/vertexai/package.json index ecee29e5852..185c5ff1dde 100644 --- a/packages/vertexai/package.json +++ b/packages/vertexai/package.json @@ -61,7 +61,7 @@ "rollup": "2.79.1", "rollup-plugin-replace": "2.2.0", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/vertexai", diff --git a/packages/webchannel-wrapper/package.json b/packages/webchannel-wrapper/package.json index 5e483417c95..27ef190d5ef 100644 --- a/packages/webchannel-wrapper/package.json +++ b/packages/webchannel-wrapper/package.json @@ -37,7 +37,7 @@ "rollup-plugin-copy": "3.5.0", "rollup-plugin-sourcemaps": "0.6.3", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/webchannel-wrapper", diff --git a/repo-scripts/changelog-generator/package.json b/repo-scripts/changelog-generator/package.json index 09313c27ed6..99247b61085 100644 --- a/repo-scripts/changelog-generator/package.json +++ b/repo-scripts/changelog-generator/package.json @@ -19,11 +19,11 @@ "dependencies": { "@changesets/types": "3.3.0", "@changesets/get-github-info": "0.5.2", - "@types/node": "20.8.10" + "@types/node": "22.7.5" }, "license": "Apache-2.0", "devDependencies": { - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "repo-scripts/changelog-generator", diff --git a/repo-scripts/prune-dts/new-tests/data-connect.input.d.ts b/repo-scripts/prune-dts/new-tests/data-connect.input.d.ts new file mode 100644 index 00000000000..cdf53da36c3 --- /dev/null +++ b/repo-scripts/prune-dts/new-tests/data-connect.input.d.ts @@ -0,0 +1,455 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Firebase Data Connect + * + * @packageDocumentation + */ + +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { AppCheckTokenListener } from '@firebase/app-check-interop-types'; +import { AppCheckTokenResult } from '@firebase/app-check-interop-types'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { FirebaseAuthTokenData } from '@firebase/auth-interop-types'; +import { FirebaseError } from '@firebase/util'; +import { LogLevelString } from '@firebase/logger'; +import { Provider } from '@firebase/component'; + +/* Excluded from this release type: AppCheckTokenProvider */ + +declare type AuthTokenListener = (token: string | null) => void; + +declare interface AuthTokenProvider { + getToken(forceRefresh: boolean): Promise; + addTokenChangeListener(listener: AuthTokenListener): void; +} + +export declare interface CancellableOperation + extends PromiseLike<{ + data: T; + }> { + cancel: () => void; +} + +/** + * Connect to the DataConnect Emulator + * @param dc Data Connect instance + * @param host host of emulator server + * @param port port of emulator server + * @param sslEnabled use https + */ +export declare function connectDataConnectEmulator( + dc: DataConnect, + host: string, + port?: number, + sslEnabled?: boolean +): void; + +/** + * Connector Config for calling Data Connect backend. + */ +export declare interface ConnectorConfig { + location: string; + connector: string; + service: string; +} + +/** + * Class representing Firebase Data Connect + */ +export declare class DataConnect { + readonly app: FirebaseApp; + private readonly dataConnectOptions; + private readonly _authProvider; + private readonly _appCheckProvider; + _queryManager: QueryManager; + _mutationManager: MutationManager; + isEmulator: boolean; + _initialized: boolean; + private _transport; + private _transportClass; + private _transportOptions?; + private _authTokenProvider?; + _isUsingGeneratedSdk: boolean; + private _appCheckTokenProvider?; + constructor( + app: FirebaseApp, + dataConnectOptions: DataConnectOptions, + _authProvider: Provider, + _appCheckProvider: Provider + ); + _useGeneratedSdk(): void; + _delete(): Promise; + getSettings(): ConnectorConfig; + setInitialized(): void; + enableEmulator(transportOptions: TransportOptions): void; +} + +/** An error returned by a DataConnect operation. */ +declare class DataConnectError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: DataConnectErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: DataConnectErrorCode, + /** + * A custom error description. + */ + message: string + ); +} + +declare type DataConnectErrorCode = + | 'other' + | 'already-initialized' + | 'not-initialized' + | 'not-supported' + | 'invalid-argument' + | 'partial-error' + | 'unauthorized'; + +/** + * DataConnectOptions including project id + */ +export declare interface DataConnectOptions extends ConnectorConfig { + projectId: string; +} + +export declare interface DataConnectResult + extends OpResult { + ref: OperationRef; +} + +/** + * Representation of user provided subscription options. + */ +export declare interface DataConnectSubscription { + userCallback: OnResultSubscription; + errCallback?: (e?: DataConnectError) => void; + unsubscribe: () => void; +} + +/* Excluded from this release type: DataConnectTransport */ + +export declare type DataSource = typeof SOURCE_CACHE | typeof SOURCE_SERVER; + +/** + * Execute Mutation + * @param mutationRef mutation to execute + * @returns `MutationRef` + */ +export declare function executeMutation( + mutationRef: MutationRef +): MutationPromise; + +/** + * Execute Query + * @param queryRef query to execute. + * @returns `QueryPromise` + */ +export declare function executeQuery( + queryRef: QueryRef +): QueryPromise; + +/** + * Initialize DataConnect instance + * @param options ConnectorConfig + */ +export declare function getDataConnect(options: ConnectorConfig): DataConnect; + +/** + * Initialize DataConnect instance + * @param app FirebaseApp to initialize to. + * @param options ConnectorConfig + */ +export declare function getDataConnect( + app: FirebaseApp, + options: ConnectorConfig +): DataConnect; + +export declare const MUTATION_STR = 'mutation'; + +/* Excluded from this release type: MutationManager */ + +/** + * Mutation return value from `executeMutation` + */ +export declare interface MutationPromise + extends PromiseLike> {} + +export declare interface MutationRef + extends OperationRef { + refType: typeof MUTATION_STR; +} + +/** + * Creates a `MutationRef` + * @param dcInstance Data Connect instance + * @param mutationName name of mutation + */ +export declare function mutationRef( + dcInstance: DataConnect, + mutationName: string +): MutationRef; + +/** + * + * @param dcInstance Data Connect instance + * @param mutationName name of mutation + * @param variables variables to send with mutation + */ +export declare function mutationRef( + dcInstance: DataConnect, + mutationName: string, + variables: Variables +): MutationRef; + +/** + * Mutation Result from `executeMutation` + */ +export declare interface MutationResult + extends DataConnectResult { + ref: MutationRef; +} + +/** + * `OnCompleteSubscription` + */ +export declare type OnCompleteSubscription = () => void; + +/** + * Signature for `OnErrorSubscription` for `subscribe` + */ +export declare type OnErrorSubscription = (err?: DataConnectError) => void; + +/** + * Signature for `OnResultSubscription` for `subscribe` + */ +export declare type OnResultSubscription = ( + res: QueryResult +) => void; + +export declare interface OperationRef<_Data, Variables> { + name: string; + variables: Variables; + refType: ReferenceType; + dataConnect: DataConnect; +} + +export declare interface OpResult { + data: Data; + source: DataSource; + fetchTime: string; +} + +declare interface ParsedArgs { + dc: DataConnect; + vars: Variables; +} + +/* Excluded from this release type: parseOptions */ + +export declare const QUERY_STR = 'query'; + +declare class QueryManager { + private transport; + _queries: Map>; + constructor(transport: DataConnectTransport); + track( + queryName: string, + variables: Variables, + initialCache?: OpResult + ): TrackedQuery; + addSubscription( + queryRef: OperationRef, + onResultCallback: OnResultSubscription, + onErrorCallback?: OnErrorSubscription, + initialCache?: OpResult + ): () => void; + executeQuery( + queryRef: QueryRef + ): QueryPromise; + enableEmulator(host: string, port: number): void; +} + +/** + * Promise returned from `executeQuery` + */ +export declare interface QueryPromise + extends PromiseLike> {} + +/** + * QueryRef object + */ +export declare interface QueryRef + extends OperationRef { + refType: typeof QUERY_STR; +} + +/** + * Execute Query + * @param dcInstance Data Connect instance to use. + * @param queryName Query to execute + * @returns `QueryRef` + */ +export declare function queryRef( + dcInstance: DataConnect, + queryName: string +): QueryRef; + +/** + * Execute Query + * @param dcInstance Data Connect instance to use. + * @param queryName Query to execute + * @param variables Variables to execute with + * @returns `QueryRef` + */ +export declare function queryRef( + dcInstance: DataConnect, + queryName: string, + variables: Variables +): QueryRef; + +/** + * Result of `executeQuery` + */ +export declare interface QueryResult + extends DataConnectResult { + ref: QueryRef; + toJSON: () => SerializedRef; +} + +/** + * Signature for unsubscribe from `subscribe` + */ +export declare type QueryUnsubscribe = () => void; + +export declare type ReferenceType = typeof QUERY_STR | typeof MUTATION_STR; + +/** + * Serialized RefInfo as a result of `QueryResult.toJSON().refInfo` + */ +export declare interface RefInfo { + name: string; + variables: Variables; + connectorConfig: DataConnectOptions; +} + +/** + * Serialized Ref as a result of `QueryResult.toJSON()` + */ +export declare interface SerializedRef extends OpResult { + refInfo: RefInfo; +} + +export declare function setLogLevel(logLevel: LogLevelString): void; + +export declare const SOURCE_CACHE = 'CACHE'; + +export declare const SOURCE_SERVER = 'SERVER'; + +/** + * Subscribe to a `QueryRef` + * @param queryRefOrSerializedResult query ref or serialized result. + * @param observer observer object to use for subscribing. + * @returns `SubscriptionOptions` + */ +export declare function subscribe( + queryRefOrSerializedResult: + | QueryRef + | SerializedRef, + observer: SubscriptionOptions +): QueryUnsubscribe; + +/** + * Subscribe to a `QueryRef` + * @param queryRefOrSerializedResult query ref or serialized result. + * @param onNext Callback to call when result comes back. + * @param onError Callback to call when error gets thrown. + * @param onComplete Called when subscription completes. + * @returns `SubscriptionOptions` + */ +export declare function subscribe( + queryRefOrSerializedResult: + | QueryRef + | SerializedRef, + onNext: OnResultSubscription, + onError?: OnErrorSubscription, + onComplete?: OnCompleteSubscription +): QueryUnsubscribe; + +/** + * Representation of full observer options in `subscribe` + */ +export declare interface SubscriptionOptions { + onNext?: OnResultSubscription; + onErr?: OnErrorSubscription; + onComplete?: OnCompleteSubscription; +} + +/** + * Delete DataConnect instance + * @param dataConnect DataConnect instance + * @returns + */ +export declare function terminate(dataConnect: DataConnect): Promise; + +/** + * Converts serialized ref to query ref + * @param serializedRef ref to convert to `QueryRef` + * @returns `QueryRef` + */ +export declare function toQueryRef( + serializedRef: SerializedRef +): QueryRef; + +declare interface TrackedQuery { + ref: Omit, 'dataConnect'>; + subscriptions: Array>; + currentCache: OpResult | null; + lastError: DataConnectError | null; +} + +/* Excluded from this release type: TransportClass */ + +/** + * Options to connect to emulator + */ +export declare interface TransportOptions { + host: string; + sslEnabled?: boolean; + port?: number; +} + +/* Excluded from this release type: validateArgs */ + +/* Excluded from this release type: validateDCOptions */ + +export {}; diff --git a/repo-scripts/prune-dts/new-tests/data-connect.output.d.ts b/repo-scripts/prune-dts/new-tests/data-connect.output.d.ts new file mode 100644 index 00000000000..cc4926d649d --- /dev/null +++ b/repo-scripts/prune-dts/new-tests/data-connect.output.d.ts @@ -0,0 +1,316 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Firebase Data Connect + * + * @packageDocumentation + */ +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { AppCheckTokenListener } from '@firebase/app-check-interop-types'; +import { AppCheckTokenResult } from '@firebase/app-check-interop-types'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { FirebaseAuthTokenData } from '@firebase/auth-interop-types'; +import { FirebaseError } from '@firebase/util'; +import { LogLevelString } from '@firebase/logger'; +import { Provider } from '@firebase/component'; +export declare interface CancellableOperation + extends PromiseLike<{ + data: T; + }> { + cancel: () => void; +} +/** + * Connect to the DataConnect Emulator + * @param dc Data Connect instance + * @param host host of emulator server + * @param port port of emulator server + * @param sslEnabled use https + */ +export declare function connectDataConnectEmulator( + dc: DataConnect, + host: string, + port?: number, + sslEnabled?: boolean +): void; +/** + * Connector Config for calling Data Connect backend. + */ +export declare interface ConnectorConfig { + location: string; + connector: string; + service: string; +} +/** + * Class representing Firebase Data Connect + */ +export declare class DataConnect { + readonly app: FirebaseApp; + private readonly dataConnectOptions; + isEmulator: boolean; + constructor( + app: FirebaseApp, + dataConnectOptions: DataConnectOptions, + _authProvider: Provider, + _appCheckProvider: Provider + ); + getSettings(): ConnectorConfig; + setInitialized(): void; + enableEmulator(transportOptions: TransportOptions): void; +} +/** + * DataConnectOptions including project id + */ +export declare interface DataConnectOptions extends ConnectorConfig { + projectId: string; +} +export declare interface DataConnectResult + extends OpResult { + ref: OperationRef; +} +/** + * Representation of user provided subscription options. + */ +export declare interface DataConnectSubscription { + userCallback: OnResultSubscription; + errCallback?: (e?: FirebaseError) => void; + unsubscribe: () => void; +} +/* Excluded from this release type: DataConnectTransport */ +export declare type DataSource = typeof SOURCE_CACHE | typeof SOURCE_SERVER; +/** + * Execute Mutation + * @param mutationRef mutation to execute + * @returns `MutationRef` + */ +export declare function executeMutation( + mutationRef: MutationRef +): MutationPromise; +/** + * Execute Query + * @param queryRef query to execute. + * @returns `QueryPromise` + */ +export declare function executeQuery( + queryRef: QueryRef +): QueryPromise; +/** + * Initialize DataConnect instance + * @param options ConnectorConfig + */ +export declare function getDataConnect(options: ConnectorConfig): DataConnect; +/** + * Initialize DataConnect instance + * @param app FirebaseApp to initialize to. + * @param options ConnectorConfig + */ +export declare function getDataConnect( + app: FirebaseApp, + options: ConnectorConfig +): DataConnect; +export declare const MUTATION_STR = 'mutation'; +/* Excluded from this release type: MutationManager */ +/** + * Mutation return value from `executeMutation` + */ +export declare interface MutationPromise + extends PromiseLike> {} +export declare interface MutationRef + extends OperationRef { + refType: typeof MUTATION_STR; +} +/** + * Creates a `MutationRef` + * @param dcInstance Data Connect instance + * @param mutationName name of mutation + */ +export declare function mutationRef( + dcInstance: DataConnect, + mutationName: string +): MutationRef; +/** + * + * @param dcInstance Data Connect instance + * @param mutationName name of mutation + * @param variables variables to send with mutation + */ +export declare function mutationRef( + dcInstance: DataConnect, + mutationName: string, + variables: Variables +): MutationRef; +/** + * Mutation Result from `executeMutation` + */ +export declare interface MutationResult + extends DataConnectResult { + ref: MutationRef; +} +/** + * `OnCompleteSubscription` + */ +export declare type OnCompleteSubscription = () => void; +/** + * Signature for `OnErrorSubscription` for `subscribe` + */ +export declare type OnErrorSubscription = (err?: FirebaseError) => void; +/** + * Signature for `OnResultSubscription` for `subscribe` + */ +export declare type OnResultSubscription = ( + res: QueryResult +) => void; +export declare interface OperationRef<_Data, Variables> { + name: string; + variables: Variables; + refType: ReferenceType; + dataConnect: DataConnect; +} +export declare interface OpResult { + data: Data; + source: DataSource; + fetchTime: string; +} +/* Excluded from this release type: parseOptions */ +export declare const QUERY_STR = 'query'; +/** + * Promise returned from `executeQuery` + */ +export declare interface QueryPromise + extends PromiseLike> {} +/** + * QueryRef object + */ +export declare interface QueryRef + extends OperationRef { + refType: typeof QUERY_STR; +} +/** + * Execute Query + * @param dcInstance Data Connect instance to use. + * @param queryName Query to execute + * @returns `QueryRef` + */ +export declare function queryRef( + dcInstance: DataConnect, + queryName: string +): QueryRef; +/** + * Execute Query + * @param dcInstance Data Connect instance to use. + * @param queryName Query to execute + * @param variables Variables to execute with + * @returns `QueryRef` + */ +export declare function queryRef( + dcInstance: DataConnect, + queryName: string, + variables: Variables +): QueryRef; +/** + * Result of `executeQuery` + */ +export declare interface QueryResult + extends DataConnectResult { + ref: QueryRef; + toJSON: () => SerializedRef; +} +/** + * Signature for unsubscribe from `subscribe` + */ +export declare type QueryUnsubscribe = () => void; +export declare type ReferenceType = typeof QUERY_STR | typeof MUTATION_STR; +/** + * Serialized RefInfo as a result of `QueryResult.toJSON().refInfo` + */ +export declare interface RefInfo { + name: string; + variables: Variables; + connectorConfig: DataConnectOptions; +} +/** + * Serialized Ref as a result of `QueryResult.toJSON()` + */ +export declare interface SerializedRef extends OpResult { + refInfo: RefInfo; +} +export declare function setLogLevel(logLevel: LogLevelString): void; +export declare const SOURCE_CACHE = 'CACHE'; +export declare const SOURCE_SERVER = 'SERVER'; +/** + * Subscribe to a `QueryRef` + * @param queryRefOrSerializedResult query ref or serialized result. + * @param observer observer object to use for subscribing. + * @returns `SubscriptionOptions` + */ +export declare function subscribe( + queryRefOrSerializedResult: + | QueryRef + | SerializedRef, + observer: SubscriptionOptions +): QueryUnsubscribe; +/** + * Subscribe to a `QueryRef` + * @param queryRefOrSerializedResult query ref or serialized result. + * @param onNext Callback to call when result comes back. + * @param onError Callback to call when error gets thrown. + * @param onComplete Called when subscription completes. + * @returns `SubscriptionOptions` + */ +export declare function subscribe( + queryRefOrSerializedResult: + | QueryRef + | SerializedRef, + onNext: OnResultSubscription, + onError?: OnErrorSubscription, + onComplete?: OnCompleteSubscription +): QueryUnsubscribe; +/** + * Representation of full observer options in `subscribe` + */ +export declare interface SubscriptionOptions { + onNext?: OnResultSubscription; + onErr?: OnErrorSubscription; + onComplete?: OnCompleteSubscription; +} +/** + * Delete DataConnect instance + * @param dataConnect DataConnect instance + * @returns + */ +export declare function terminate(dataConnect: DataConnect): Promise; +/** + * Converts serialized ref to query ref + * @param serializedRef ref to convert to `QueryRef` + * @returns `QueryRef` + */ +export declare function toQueryRef( + serializedRef: SerializedRef +): QueryRef; +/* Excluded from this release type: TransportClass */ +/** + * Options to connect to emulator + */ +export declare interface TransportOptions { + host: string; + sslEnabled?: boolean; + port?: number; +} +/* Excluded from this release type: validateArgs */ +/* Excluded from this release type: validateDCOptions */ +export {}; diff --git a/repo-scripts/prune-dts/new-tests/database.input.d.ts b/repo-scripts/prune-dts/new-tests/database.input.d.ts new file mode 100644 index 00000000000..6ea85f3e7da --- /dev/null +++ b/repo-scripts/prune-dts/new-tests/database.input.d.ts @@ -0,0 +1,3207 @@ +/** + * Firebase Realtime Database + * + * @packageDocumentation + */ + +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { AppCheckTokenListener } from '@firebase/app-check-interop-types'; +import { AppCheckTokenResult } from '@firebase/app-check-interop-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseApp as FirebaseApp_2 } from '@firebase/app-types'; +import { FirebaseAppCheckInternal } from '@firebase/app-check-interop-types'; +import { FirebaseAuthInternal } from '@firebase/auth-interop-types'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { FirebaseAuthTokenData } from '@firebase/app-types/private'; +import { Provider } from '@firebase/component'; + +/** + * Abstraction around AppCheck's token fetching capabilities. + */ +declare class AppCheckTokenProvider { + private appName_; + private appCheckProvider?; + private appCheck?; + constructor( + appName_: string, + appCheckProvider?: Provider + ); + getToken(forceRefresh?: boolean): Promise; + addTokenChangeListener(listener: AppCheckTokenListener): void; + notifyForInvalidToken(): void; +} + +declare interface AuthTokenProvider { + getToken(forceRefresh: boolean): Promise; + addTokenChangeListener(listener: (token: string | null) => void): void; + removeTokenChangeListener(listener: (token: string | null) => void): void; + notifyForInvalidToken(): void; +} + +/** + * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully + * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. + * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks + * whether a node potentially had children removed due to a filter. + */ +declare class CacheNode { + private node_; + private fullyInitialized_; + private filtered_; + constructor(node_: Node_2, fullyInitialized_: boolean, filtered_: boolean); + /** + * Returns whether this node was fully initialized with either server data or a complete overwrite by the client + */ + isFullyInitialized(): boolean; + /** + * Returns whether this node is potentially missing children due to a filter applied to the node + */ + isFiltered(): boolean; + isCompleteForPath(path: Path): boolean; + isCompleteForChild(key: string): boolean; + getNode(): Node_2; +} + +declare class CancelEvent implements Event_2 { + eventRegistration: EventRegistration; + error: Error; + path: Path; + constructor(eventRegistration: EventRegistration, error: Error, path: Path); + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} + +declare interface Change { + /** @param type - The event type */ + type: ChangeType; + /** @param snapshotNode - The data */ + snapshotNode: Node_2; + /** @param childName - The name for this child, if it's a child even */ + childName?: string; + /** @param oldSnap - Used for intermediate processing of child changed events */ + oldSnap?: Node_2; + /** * @param prevName - The name for the previous child, if applicable */ + prevName?: string | null; +} + +declare const enum ChangeType { + /** Event type for a child added */ + CHILD_ADDED = 'child_added', + /** Event type for a child removed */ + CHILD_REMOVED = 'child_removed', + /** Event type for a child changed */ + CHILD_CHANGED = 'child_changed', + /** Event type for a child moved */ + CHILD_MOVED = 'child_moved', + /** Event type for a value change */ + VALUE = 'value' +} + +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +export declare function child( + parent: DatabaseReference, + path: string +): DatabaseReference; + +declare class ChildChangeAccumulator { + private readonly changeMap; + trackChildChange(change: Change): void; + getChanges(): Change[]; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @fileoverview Implementation of an immutable SortedMap using a Left-leaning + * Red-Black Tree, adapted from the implementation in Mugs + * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen + * (mads379\@gmail.com). + * + * Original paper on Left-leaning Red-Black Trees: + * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf + * + * Invariant 1: No red node has a red child + * Invariant 2: Every leaf path has the same number of black nodes + * Invariant 3: Only the left child can be red (left leaning) + */ +declare type Comparator = (key1: K, key2: K) => number; + +/** + * Since updates to filtered nodes might require nodes to be pulled in from "outside" the node, this interface + * can help to get complete children that can be pulled in. + * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from + * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view. + * + * @interface + */ +declare interface CompleteChildSource { + getCompleteChild(childKey: string): Node_2 | null; + getChildAfterChild( + index: Index, + child: NamedNode, + reverse: boolean + ): NamedNode | null; +} + +/** + * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with + * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write + * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write + * to reflect the write added. + */ +declare class CompoundWrite { + writeTree_: ImmutableTree; + constructor(writeTree_: ImmutableTree); + static empty(): CompoundWrite; +} + +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +export declare function connectDatabaseEmulator( + db: Database, + host: string, + port: number, + options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + } +): void; + +/** + * Class representing a Firebase Realtime Database. + */ +export declare class Database implements _FirebaseService { + _repoInternal: Repo; + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + readonly app: FirebaseApp; + /** Represents a `Database` instance. */ + readonly 'type' = 'database'; + /** Track if the instance has been used (root or repo accessed) */ + _instanceStarted: boolean; + /** Backing state for root_ */ + private _rootInternal?; + /** @hideconstructor */ + constructor( + _repoInternal: Repo, + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + app: FirebaseApp + ); + get _repo(): Repo; + get _root(): _ReferenceImpl; + _delete(): Promise; + _checkNotDeleted(apiName: string): void; +} + +/** + * A `DatabaseReference` represents a specific location in your Database and can be used + * for reading or writing data to that Database location. + * + * You can reference the root or child location in your Database by calling + * `ref()` or `ref("child/path")`. + * + * Writing is done with the `set()` method and reading can be done with the + * `on*()` method. See {@link + * https://firebase.google.com/docs/database/web/read-and-write} + */ +export declare interface DatabaseReference extends Query { + /** + * The last part of the `DatabaseReference`'s path. + * + * For example, `"ada"` is the key for + * `https://.firebaseio.com/users/ada`. + * + * The key of a root `DatabaseReference` is `null`. + */ + readonly key: string | null; + /** + * The parent location of a `DatabaseReference`. + * + * The parent of a root `DatabaseReference` is `null`. + */ + readonly parent: DatabaseReference | null; + /** The root `DatabaseReference` of the Database. */ + readonly root: DatabaseReference; +} + +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +export declare class DataSnapshot { + readonly _node: Node_2; + /** + * The location of this DataSnapshot. + */ + readonly ref: DatabaseReference; + readonly _index: Index; + /** + * @param _node - A SnapshotNode to wrap. + * @param ref - The location this snapshot came from. + * @param _index - The iteration order for this snapshot + * @hideconstructor + */ + constructor( + _node: Node_2, + /** + * The location of this DataSnapshot. + */ + ref: DatabaseReference, + _index: Index + ); + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority(): string | number | null; + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key(): string | null; + /** Returns the number of child properties of this `DataSnapshot`. */ + get size(): number; + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path: string): DataSnapshot; + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists(): boolean; + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + exportVal(): any; + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean; + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path: string): boolean; + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren(): boolean; + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON(): object | null; + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + val(): any; +} +export { EmulatorMockTokenOptions }; + +/** + * Logs debugging information to the console. + * + * @param enabled - Enables logging if `true`, disables logging if `false`. + * @param persistent - Remembers the logging state between page refreshes if + * `true`. + */ +export declare function enableLogging( + enabled: boolean, + persistent?: boolean +): any; + +/** + * Logs debugging information to the console. + * + * @param logger - A custom logger function to control how things get logged. + */ +export declare function enableLogging( + logger: (message: string) => unknown +): any; + +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +export declare function endAt( + value: number | string | boolean | null, + key?: string +): QueryConstraint; + +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function endBefore( + value: number | string | boolean | null, + key?: string +): QueryConstraint; + +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function equalTo( + value: number | string | boolean | null, + key?: string +): QueryConstraint; + +/** + * Encapsulates the data needed to raise an event + * @interface + */ +declare interface Event_2 { + getPath(): Path; + getEventType(): string; + getEventRunner(): () => void; + toString(): string; +} + +/** + * An EventGenerator is used to convert "raw" changes (Change) as computed by the + * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() + * for details. + * + */ +declare class EventGenerator { + query_: QueryContext; + index_: Index; + constructor(query_: QueryContext); +} + +declare interface EventList { + events: Event_2[]; + path: Path; +} + +/** + * The event queue serves a few purposes: + * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more + * events being queued. + * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, + * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call + * left off, ensuring that the events are still raised synchronously and in order. + * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued + * events are raised synchronously. + * + * NOTE: This can all go away if/when we move to async events. + * + */ +declare class EventQueue { + eventLists_: EventList[]; + /** + * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. + */ + recursionDepth_: number; +} + +/** + * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback + * to be notified of that type of event. + * + * That said, it can also contain a cancel callback to be notified if the event is canceled. And + * currently, this code is organized around the idea that you would register multiple child_ callbacks + * together, as a single EventRegistration. Though currently we don't do that. + */ +declare interface EventRegistration { + /** + * True if this container has a callback to trigger for this event type + */ + respondsTo(eventType: string): boolean; + createEvent(change: Change, query: QueryContext): Event_2; + /** + * Given event data, return a function to trigger the user's callback + */ + getEventRunner(eventData: Event_2): () => void; + createCancelEvent(error: Error, path: Path): CancelEvent | null; + matches(other: EventRegistration): boolean; + /** + * False basically means this is a "dummy" callback container being used as a sentinel + * to remove all callback containers of a particular type. (e.g. if the user does + * ref.off('value') without specifying a specific callback). + * + * (TODO: Rework this, since it's hacky) + * + */ + hasAnyCallback(): boolean; +} + +/** + * One of the following strings: "value", "child_added", "child_changed", + * "child_removed", or "child_moved." + */ +export declare type EventType = + | 'value' + | 'child_added' + | 'child_changed' + | 'child_moved' + | 'child_removed'; + +/* Excluded from this release type: _FirebaseService */ + +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +export declare function forceLongPolling(): void; + +/** + * Force the use of websockets instead of longPolling. + */ +export declare function forceWebSockets(): void; + +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +export declare function get(query: Query): Promise; + +/** + * Returns the instance of the Realtime Database SDK that is associated with the provided + * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if + * no instance exists or if the existing instance uses a custom database URL. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime + * Database instance is associated with. + * @param url - The URL of the Realtime Database instance to connect to. If not + * provided, the SDK connects to the default instance of the Firebase App. + * @returns The `Database` instance of the provided app. + */ +export declare function getDatabase(app?: FirebaseApp, url?: string): Database; + +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +export declare function goOffline(db: Database): void; + +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +export declare function goOnline(db: Database): void; + +/** + * A tree with immutable elements. + */ +declare class ImmutableTree { + readonly value: T | null; + readonly children: SortedMap>; + static fromObject(obj: { [k: string]: T }): ImmutableTree; + constructor(value: T | null, children?: SortedMap>); + /** + * True if the value is empty and there are no children + */ + isEmpty(): boolean; + /** + * Given a path and predicate, return the first node and the path to that node + * where the predicate returns true. + * + * TODO Do a perf test -- If we're creating a bunch of `{path: value:}` + * objects on the way back out, it may be better to pass down a pathSoFar obj. + * + * @param relativePath - The remainder of the path + * @param predicate - The predicate to satisfy to return a node + */ + findRootMostMatchingPathAndValue( + relativePath: Path, + predicate: (a: T) => boolean + ): { + path: Path; + value: T; + } | null; + /** + * Find, if it exists, the shortest subpath of the given path that points a defined + * value in the tree + */ + findRootMostValueAndPath(relativePath: Path): { + path: Path; + value: T; + } | null; + /** + * @returns The subtree at the given path + */ + subtree(relativePath: Path): ImmutableTree; + /** + * Sets a value at the specified path. + * + * @param relativePath - Path to set value at. + * @param toSet - Value to set. + * @returns Resulting tree. + */ + set(relativePath: Path, toSet: T | null): ImmutableTree; + /** + * Removes the value at the specified path. + * + * @param relativePath - Path to value to remove. + * @returns Resulting tree. + */ + remove(relativePath: Path): ImmutableTree; + /** + * Gets a value from the tree. + * + * @param relativePath - Path to get value for. + * @returns Value at path, or null. + */ + get(relativePath: Path): T | null; + /** + * Replace the subtree at the specified path with the given new tree. + * + * @param relativePath - Path to replace subtree for. + * @param newTree - New tree. + * @returns Resulting tree. + */ + setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree; + /** + * Performs a depth first fold on this tree. Transforms a tree into a single + * value, given a function that operates on the path to a node, an optional + * current value, and a map of child names to folded subtrees + */ + fold( + fn: ( + path: Path, + value: T, + children: { + [k: string]: V; + } + ) => V + ): V; + /** + * Recursive helper for public-facing fold() method + */ + private fold_; + /** + * Find the first matching value on the given path. Return the result of applying f to it. + */ + findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null; + private findOnPath_; + foreachOnPath( + path: Path, + f: (path: Path, value: T) => void + ): ImmutableTree; + private foreachOnPath_; + /** + * Calls the given function for each node in the tree that has a value. + * + * @param f - A function to be called with the path from the root of the tree to + * a node, and the value at that node. Called in depth-first order. + */ + foreach(f: (path: Path, value: T) => void): void; + private foreach_; + foreachChild(f: (name: string, value: T) => void): void; +} + +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +export declare function increment(delta: number): object; + +declare abstract class Index { + abstract compare(a: NamedNode, b: NamedNode): number; + abstract isDefinedOn(node: Node_2): boolean; + /** + * @returns A standalone comparison function for + * this index + */ + getCompare(): Comparator; + /** + * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, + * it's possible that the changes are isolated to parts of the snapshot that are not indexed. + * + * + * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode + */ + indexedValueChanged(oldNode: Node_2, newNode: Node_2): boolean; + /** + * @returns a node wrapper that will sort equal to or less than + * any other node wrapper, using this index + */ + minPost(): NamedNode; + /** + * @returns a node wrapper that will sort greater than or equal to + * any other node wrapper, using this index + */ + abstract maxPost(): NamedNode; + abstract makePost(indexValue: unknown, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + abstract toString(): string; +} + +/* Excluded from this release type: _initStandalone */ + +/** + * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined. + */ +export declare interface IteratedDataSnapshot extends DataSnapshot { + key: string; +} + +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToFirst(limit: number): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToLast(limit: number): QueryConstraint; + +/** An options objects that can be used to customize a listener. */ +export declare interface ListenOptions { + /** Whether to remove the listener after its first invocation. */ + readonly onlyOnce?: boolean; +} + +declare interface ListenProvider { + startListening( + query: QueryContext, + tag: number | null, + hashFn: () => string, + onComplete: (a: string, b?: unknown) => Event_2[] + ): Event_2[]; + stopListening(a: QueryContext, b: number | null): void; +} + +/** + * Represents an empty node (a leaf node in the Red-Black Tree). + */ +declare class LLRBEmptyNode { + key: K; + value: V; + left: LLRBNode | LLRBEmptyNode; + right: LLRBNode | LLRBEmptyNode; + color: boolean; + /** + * Returns a copy of the current node. + * + * @returns The node copy. + */ + copy( + key: K | null, + value: V | null, + color: boolean | null, + left: LLRBNode | LLRBEmptyNode | null, + right: LLRBNode | LLRBEmptyNode | null + ): LLRBEmptyNode; + /** + * Returns a copy of the tree, with the specified key/value added. + * + * @param key - Key to be added. + * @param value - Value to be added. + * @param comparator - Comparator. + * @returns New tree, with item added. + */ + insert(key: K, value: V, comparator: Comparator): LLRBNode; + /** + * Returns a copy of the tree, with the specified key removed. + * + * @param key - The key to remove. + * @param comparator - Comparator. + * @returns New tree, with item removed. + */ + remove(key: K, comparator: Comparator): LLRBEmptyNode; + /** + * @returns The total number of nodes in the tree. + */ + count(): number; + /** + * @returns True if the tree is empty. + */ + isEmpty(): boolean; + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + minKey(): null; + maxKey(): null; + check_(): number; + /** + * @returns Whether this node is red. + */ + isRed_(): boolean; +} + +/** + * Represents a node in a Left-leaning Red-Black tree. + */ +declare class LLRBNode { + key: K; + value: V; + color: boolean; + left: LLRBNode | LLRBEmptyNode; + right: LLRBNode | LLRBEmptyNode; + /** + * @param key - Key associated with this node. + * @param value - Value associated with this node. + * @param color - Whether this node is red. + * @param left - Left child. + * @param right - Right child. + */ + constructor( + key: K, + value: V, + color: boolean | null, + left?: LLRBNode | LLRBEmptyNode | null, + right?: LLRBNode | LLRBEmptyNode | null + ); + static RED: boolean; + static BLACK: boolean; + /** + * Returns a copy of the current node, optionally replacing pieces of it. + * + * @param key - New key for the node, or null. + * @param value - New value for the node, or null. + * @param color - New color for the node, or null. + * @param left - New left child for the node, or null. + * @param right - New right child for the node, or null. + * @returns The node copy. + */ + copy( + key: K | null, + value: V | null, + color: boolean | null, + left: LLRBNode | LLRBEmptyNode | null, + right: LLRBNode | LLRBEmptyNode | null + ): LLRBNode; + /** + * @returns The total number of nodes in the tree. + */ + count(): number; + /** + * @returns True if the tree is empty. + */ + isEmpty(): boolean; + /** + * Traverses the tree in key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the tree in reverse key order and calls the specified action function + * for each node. + * + * @param action - Callback function to be called for each + * node. If it returns true, traversal is aborted. + * @returns True if traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + /** + * @returns The minimum node in the tree. + */ + private min_; + /** + * @returns The maximum key in the tree. + */ + minKey(): K; + /** + * @returns The maximum key in the tree. + */ + maxKey(): K; + /** + * @param key - Key to insert. + * @param value - Value to insert. + * @param comparator - Comparator. + * @returns New tree, with the key/value added. + */ + insert(key: K, value: V, comparator: Comparator): LLRBNode; + /** + * @returns New tree, with the minimum key removed. + */ + private removeMin_; + /** + * @param key - The key of the item to remove. + * @param comparator - Comparator. + * @returns New tree, with the specified item removed. + */ + remove( + key: K, + comparator: Comparator + ): LLRBNode | LLRBEmptyNode; + /** + * @returns Whether this is a RED node. + */ + isRed_(): boolean; + /** + * @returns New tree after performing any needed rotations. + */ + private fixUp_; + /** + * @returns New tree, after moveRedLeft. + */ + private moveRedLeft_; + /** + * @returns New tree, after moveRedRight. + */ + private moveRedRight_; + /** + * @returns New tree, after rotateLeft. + */ + private rotateLeft_; + /** + * @returns New tree, after rotateRight. + */ + private rotateRight_; + /** + * @returns Newt ree, after colorFlip. + */ + private colorFlip_; + /** + * For testing. + * + * @returns True if all is well. + */ + private checkMaxDepth_; + check_(): number; +} + +declare class NamedNode { + name: string; + node: Node_2; + constructor(name: string, node: Node_2); + static Wrap(name: string, node: Node_2): NamedNode; +} + +/** + * Node is an interface defining the common functionality for nodes in + * a DataSnapshot. + * + * @interface + */ +declare interface Node_2 { + /** + * Whether this node is a leaf node. + * @returns Whether this is a leaf node. + */ + isLeafNode(): boolean; + /** + * Gets the priority of the node. + * @returns The priority of the node. + */ + getPriority(): Node_2; + /** + * Returns a duplicate node with the new priority. + * @param newPriorityNode - New priority to set for the node. + * @returns Node with new priority. + */ + updatePriority(newPriorityNode: Node_2): Node_2; + /** + * Returns the specified immediate child, or null if it doesn't exist. + * @param childName - The name of the child to retrieve. + * @returns The retrieved child, or an empty node. + */ + getImmediateChild(childName: string): Node_2; + /** + * Returns a child by path, or null if it doesn't exist. + * @param path - The path of the child to retrieve. + * @returns The retrieved child or an empty node. + */ + getChild(path: Path): Node_2; + /** + * Returns the name of the child immediately prior to the specified childNode, or null. + * @param childName - The name of the child to find the predecessor of. + * @param childNode - The node to find the predecessor of. + * @param index - The index to use to determine the predecessor + * @returns The name of the predecessor child, or null if childNode is the first child. + */ + getPredecessorChildName( + childName: string, + childNode: Node_2, + index: Index + ): string | null; + /** + * Returns a duplicate node, with the specified immediate child updated. + * Any value in the node will be removed. + * @param childName - The name of the child to update. + * @param newChildNode - The new child node + * @returns The updated node. + */ + updateImmediateChild(childName: string, newChildNode: Node_2): Node_2; + /** + * Returns a duplicate node, with the specified child updated. Any value will + * be removed. + * @param path - The path of the child to update. + * @param newChildNode - The new child node, which may be an empty node + * @returns The updated node. + */ + updateChild(path: Path, newChildNode: Node_2): Node_2; + /** + * True if the immediate child specified exists + */ + hasChild(childName: string): boolean; + /** + * @returns True if this node has no value or children. + */ + isEmpty(): boolean; + /** + * @returns The number of children of this node. + */ + numChildren(): number; + /** + * Calls action for each child. + * @param action - Action to be called for + * each child. It's passed the child name and the child node. + * @returns The first truthy value return by action, or the last falsey one + */ + forEachChild(index: Index, action: (a: string, b: Node_2) => void): unknown; + /** + * @param exportFormat - True for export format (also wire protocol format). + * @returns Value of this node as JSON. + */ + val(exportFormat?: boolean): unknown; + /** + * @returns hash representing the node contents. + */ + hash(): string; + /** + * @param other - Another node + * @returns -1 for less than, 0 for equal, 1 for greater than other + */ + compareTo(other: Node_2): number; + /** + * @returns Whether or not this snapshot equals other + */ + equals(other: Node_2): boolean; + /** + * @returns This node, with the specified index now available + */ + withIndex(indexDefinition: Index): Node_2; + isIndexed(indexDefinition: Index): boolean; +} + +/** + * NodeFilter is used to update nodes and complete children of nodes while applying queries on the fly and keeping + * track of any child changes. This class does not track value changes as value changes depend on more + * than just the node itself. Different kind of queries require different kind of implementations of this interface. + * @interface + */ +declare interface NodeFilter_2 { + /** + * Update a single complete child in the snap. If the child equals the old child in the snap, this is a no-op. + * The method expects an indexed snap. + */ + updateChild( + snap: Node_2, + key: string, + newChild: Node_2, + affectedPath: Path, + source: CompleteChildSource, + optChangeAccumulator: ChildChangeAccumulator | null + ): Node_2; + /** + * Update a node in full and output any resulting change from this complete update. + */ + updateFullNode( + oldSnap: Node_2, + newSnap: Node_2, + optChangeAccumulator: ChildChangeAccumulator | null + ): Node_2; + /** + * Update the priority of the root node + */ + updatePriority(oldSnap: Node_2, newPriority: Node_2): Node_2; + /** + * Returns true if children might be filtered due to query criteria + */ + filtersNodes(): boolean; + /** + * Returns the index filter that this filter uses to get a NodeFilter that doesn't filter any children. + */ + getIndexedFilter(): NodeFilter_2; + /** + * Returns the index that this filter uses + */ + getIndex(): Index; +} + +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +export declare function off( + query: Query, + eventType?: EventType, + callback?: ( + snapshot: DataSnapshot, + previousChildName?: string | null + ) => unknown +): void; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName?: string | null + ) => unknown, + cancelCallback?: (error: Error) => unknown +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + options: ListenOptions +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + cancelCallback: (error: Error) => unknown, + options: ListenOptions +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + cancelCallback?: (error: Error) => unknown +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + options: ListenOptions +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + cancelCallback: (error: Error) => unknown, + options: ListenOptions +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + cancelCallback?: (error: Error) => unknown +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + options: ListenOptions +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + cancelCallback: (error: Error) => unknown, + options: ListenOptions +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + cancelCallback?: (error: Error) => unknown +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + options: ListenOptions +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + cancelCallback: (error: Error) => unknown, + options: ListenOptions +): Unsubscribe; + +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +export declare class OnDisconnect { + private _repo; + private _path; + /** @hideconstructor */ + constructor(_repo: Repo, _path: Path); + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel(): Promise; + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove(): Promise; + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value: unknown): Promise; + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority( + value: unknown, + priority: number | string | null + ): Promise; + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values: object): Promise; +} + +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +export declare function onDisconnect(ref: DatabaseReference): OnDisconnect; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + cancelCallback?: (error: Error) => unknown +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + options: ListenOptions +): Unsubscribe; + +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + cancelCallback: (error: Error) => unknown, + options: ListenOptions +): Unsubscribe; + +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +export declare function orderByChild(path: string): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByKey(): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +export declare function orderByPriority(): QueryConstraint; + +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByValue(): QueryConstraint; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a parsed path. It's immutable so that you + * can pass them around to other functions without worrying about them changing + * it. + */ +declare class Path { + pieces_: string[]; + pieceNum_: number; + /** + * @param pathOrString - Path string to parse, or another path, or the raw + * tokens array + */ + constructor(pathOrString: string | string[], pieceNum?: number); + toString(): string; +} + +/** + * Firebase connection. Abstracts wire protocol and handles reconnecting. + * + * NOTE: All JSON objects sent to the realtime connection must have property names enclosed + * in quotes to make sure the closure compiler does not minify them. + */ +declare class PersistentConnection extends ServerActions { + private repoInfo_; + private applicationId_; + private onDataUpdate_; + private onConnectStatus_; + private onServerInfoUpdate_; + private authTokenProvider_; + private appCheckTokenProvider_; + private authOverride_?; + id: number; + private log_; + private interruptReasons_; + private readonly listens; + private outstandingPuts_; + private outstandingGets_; + private outstandingPutCount_; + private outstandingGetCount_; + private onDisconnectRequestQueue_; + private connected_; + private reconnectDelay_; + private maxReconnectDelay_; + private securityDebugCallback_; + lastSessionId: string | null; + private establishConnectionTimer_; + private visible_; + private requestCBHash_; + private requestNumber_; + private realtime_; + private authToken_; + private appCheckToken_; + private forceTokenRefresh_; + private invalidAuthTokenCount_; + private invalidAppCheckTokenCount_; + private firstConnection_; + private lastConnectionAttemptTime_; + private lastConnectionEstablishedTime_; + private static nextPersistentConnectionId_; + /** + * Counter for number of connections created. Mainly used for tagging in the logs + */ + private static nextConnectionId_; + /** + * @param repoInfo_ - Data about the namespace we are connecting to + * @param applicationId_ - The Firebase App ID for this project + * @param onDataUpdate_ - A callback for new data from the server + */ + constructor( + repoInfo_: RepoInfo, + applicationId_: string, + onDataUpdate_: ( + a: string, + b: unknown, + c: boolean, + d: number | null + ) => void, + onConnectStatus_: (a: boolean) => void, + onServerInfoUpdate_: (a: unknown) => void, + authTokenProvider_: AuthTokenProvider, + appCheckTokenProvider_: AppCheckTokenProvider, + authOverride_?: object | null + ); + protected sendRequest( + action: string, + body: unknown, + onResponse?: (a: unknown) => void + ): void; + get(query: QueryContext): Promise; + listen( + query: QueryContext, + currentHashFn: () => string, + tag: number | null, + onComplete: (a: string, b: unknown) => void + ): void; + private sendGet_; + private sendListen_; + private static warnOnListenWarnings_; + refreshAuthToken(token: string): void; + private reduceReconnectDelayIfAdminCredential_; + refreshAppCheckToken(token: string | null): void; + /** + * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like + * a auth revoked (the connection is closed). + */ + tryAuth(): void; + /** + * Attempts to authenticate with the given token. If the authentication + * attempt fails, it's triggered like the token was revoked (the connection is + * closed). + */ + tryAppCheck(): void; + /** + * @inheritDoc + */ + unlisten(query: QueryContext, tag: number | null): void; + private sendUnlisten_; + onDisconnectPut( + pathString: string, + data: unknown, + onComplete?: (a: string, b: string) => void + ): void; + onDisconnectMerge( + pathString: string, + data: unknown, + onComplete?: (a: string, b: string) => void + ): void; + onDisconnectCancel( + pathString: string, + onComplete?: (a: string, b: string) => void + ): void; + private sendOnDisconnect_; + put( + pathString: string, + data: unknown, + onComplete?: (a: string, b: string) => void, + hash?: string + ): void; + merge( + pathString: string, + data: unknown, + onComplete: (a: string, b: string | null) => void, + hash?: string + ): void; + putInternal( + action: string, + pathString: string, + data: unknown, + onComplete: (a: string, b: string | null) => void, + hash?: string + ): void; + private sendPut_; + reportStats(stats: { [k: string]: unknown }): void; + private onDataMessage_; + private onDataPush_; + private onReady_; + private scheduleConnect_; + private initConnection_; + private onVisible_; + private onOnline_; + private onRealtimeDisconnect_; + private establishConnection_; + interrupt(reason: string): void; + resume(reason: string): void; + private handleTimestamp_; + private cancelSentTransactions_; + private onListenRevoked_; + private removeListen_; + private onAuthRevoked_; + private onAppCheckRevoked_; + private onSecurityDebugPacket_; + private restoreState_; + /** + * Sends client stats for first connection + */ + private sendConnectStats_; + private shouldReconnect_; +} + +declare class PriorityIndex extends Index { + compare(a: NamedNode, b: NamedNode): number; + isDefinedOn(node: Node_2): boolean; + indexedValueChanged(oldNode: Node_2, newNode: Node_2): boolean; + minPost(): NamedNode; + maxPost(): NamedNode; + makePost(indexValue: unknown, name: string): NamedNode; + /** + * @returns String representation for inclusion in a query spec + */ + toString(): string; +} + +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +export declare function push( + parent: DatabaseReference, + value?: unknown +): ThenableReference; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` sorts and filters the data at a Database location so only a subset + * of the child data is included. This can be used to order a collection of + * data by some attribute (for example, height of dinosaurs) as well as to + * restrict a large list of items (for example, chat messages) down to a number + * suitable for synchronizing to the client. Queries are created by chaining + * together one or more of the filter methods defined here. + * + * Just as with a `DatabaseReference`, you can receive data from a `Query` by using the + * `on*()` methods. You will only receive events and `DataSnapshot`s for the + * subset of the data that matches your query. + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data} + * for more information. + */ +export declare interface Query extends QueryContext { + /** The `DatabaseReference` for the `Query`'s location. */ + readonly ref: DatabaseReference; + /** + * Returns whether or not the current and provided queries represent the same + * location, have the same query parameters, and are from the same instance of + * `FirebaseApp`. + * + * Two `DatabaseReference` objects are equivalent if they represent the same location + * and are from the same instance of `FirebaseApp`. + * + * Two `Query` objects are equivalent if they represent the same location, + * have the same query parameters, and are from the same instance of + * `FirebaseApp`. Equivalent queries share the same sort order, limits, and + * starting and ending points. + * + * @param other - The query to compare against. + * @returns Whether or not the current and provided queries are equivalent. + */ + isEqual(other: Query | null): boolean; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): string; + /** + * Gets the absolute URL for this location. + * + * The `toString()` method returns a URL that is ready to be put into a + * browser, curl command, or a `refFromURL()` call. Since all of those expect + * the URL to be url-encoded, `toString()` returns an encoded URL. + * + * Append '.json' to the returned URL when typed into a browser to download + * JSON-formatted data. If the location is secured (that is, not publicly + * readable), you will get a permission-denied error. + * + * @returns The absolute URL for this location. + */ + toString(): string; +} + +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query( + query: Query, + ...queryConstraints: QueryConstraint[] +): Query; + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint { + /** The type of this query constraints */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided `Query` and returns a copy of the `Query` with this + * `QueryConstraint` applied. + */ + abstract _apply(query: _QueryImpl): _QueryImpl; +} + +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = + | 'endAt' + | 'endBefore' + | 'startAt' + | 'startAfter' + | 'limitToFirst' + | 'limitToLast' + | 'orderByChild' + | 'orderByKey' + | 'orderByPriority' + | 'orderByValue' + | 'equalTo'; + +declare interface QueryContext { + readonly _queryIdentifier: string; + readonly _queryObject: object; + readonly _repo: Repo; + readonly _path: Path; + readonly _queryParams: _QueryParams; +} + +/* Excluded from this release type: _QueryImpl */ + +/* Excluded from this release type: _QueryParams */ + +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +export declare function ref(db: Database, path?: string): DatabaseReference; + +/* Excluded from this release type: _ReferenceImpl */ + +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +export declare function refFromURL( + db: Database, + url: string +): DatabaseReference; + +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +export declare function remove(ref: DatabaseReference): Promise; + +/** + * A connection to a single data repository. + */ +declare class Repo { + repoInfo_: RepoInfo; + forceRestClient_: boolean; + authTokenProvider_: AuthTokenProvider; + appCheckProvider_: AppCheckTokenProvider; + /** Key for uniquely identifying this repo, used in RepoManager */ + readonly key: string; + dataUpdateCount: number; + infoSyncTree_: SyncTree; + serverSyncTree_: SyncTree; + stats_: StatsCollection; + statsListener_: StatsListener | null; + eventQueue_: EventQueue; + nextWriteId_: number; + server_: ServerActions; + statsReporter_: StatsReporter; + infoData_: SnapshotHolder; + interceptServerDataCallback_: ((a: string, b: unknown) => void) | null; + /** A list of data pieces and paths to be set when this client disconnects. */ + onDisconnect_: SparseSnapshotTree; + /** Stores queues of outstanding transactions for Firebase locations. */ + transactionQueueTree_: Tree; + persistentConnection_: PersistentConnection | null; + constructor( + repoInfo_: RepoInfo, + forceRestClient_: boolean, + authTokenProvider_: AuthTokenProvider, + appCheckProvider_: AppCheckTokenProvider + ); + /** + * @returns The URL corresponding to the root of this Firebase. + */ + toString(): string; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that holds metadata about a Repo object + */ +declare class RepoInfo { + readonly secure: boolean; + readonly namespace: string; + readonly webSocketOnly: boolean; + readonly nodeAdmin: boolean; + readonly persistenceKey: string; + readonly includeNamespaceInQueryParams: boolean; + readonly isUsingEmulator: boolean; + private _host; + private _domain; + internalHost: string; + /** + * @param host - Hostname portion of the url for the repo + * @param secure - Whether or not this repo is accessed over ssl + * @param namespace - The namespace represented by the repo + * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest). + * @param nodeAdmin - Whether this instance uses Admin SDK credentials + * @param persistenceKey - Override the default session persistence storage key + */ + constructor( + host: string, + secure: boolean, + namespace: string, + webSocketOnly: boolean, + nodeAdmin?: boolean, + persistenceKey?: string, + includeNamespaceInQueryParams?: boolean, + isUsingEmulator?: boolean + ); + isCacheableHost(): boolean; + isCustomHost(): boolean; + get host(): string; + set host(newHost: string); + toString(): string; + toURLString(): string; +} + +/* Excluded from this release type: _repoManagerDatabaseFromApp */ + +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +export declare function runTransaction( + ref: DatabaseReference, + transactionUpdate: (currentData: any) => unknown, + options?: TransactionOptions +): Promise; + +/** + * Interface defining the set of actions that can be performed against the Firebase server + * (basically corresponds to our wire protocol). + * + * @interface + */ +declare abstract class ServerActions { + abstract listen( + query: QueryContext, + currentHashFn: () => string, + tag: number | null, + onComplete: (a: string, b: unknown) => void + ): void; + /** + * Remove a listen. + */ + abstract unlisten(query: QueryContext, tag: number | null): void; + /** + * Get the server value satisfying this query. + */ + abstract get(query: QueryContext): Promise; + put( + pathString: string, + data: unknown, + onComplete?: (a: string, b: string) => void, + hash?: string + ): void; + merge( + pathString: string, + data: unknown, + onComplete: (a: string, b: string | null) => void, + hash?: string + ): void; + /** + * Refreshes the auth token for the current connection. + * @param token - The authentication token + */ + refreshAuthToken(token: string): void; + /** + * Refreshes the app check token for the current connection. + * @param token The app check token + */ + refreshAppCheckToken(token: string): void; + onDisconnectPut( + pathString: string, + data: unknown, + onComplete?: (a: string, b: string) => void + ): void; + onDisconnectMerge( + pathString: string, + data: unknown, + onComplete?: (a: string, b: string) => void + ): void; + onDisconnectCancel( + pathString: string, + onComplete?: (a: string, b: string) => void + ): void; + reportStats(stats: { [k: string]: unknown }): void; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +export declare function serverTimestamp(): object; + +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +export declare function set( + ref: DatabaseReference, + value: unknown +): Promise; + +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setPriority( + ref: DatabaseReference, + priority: string | number | null +): Promise; + +/* Excluded from this release type: _setSDKVersion */ + +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setWithPriority( + ref: DatabaseReference, + value: unknown, + priority: string | number | null +): Promise; + +/** + * Mutable object which basically just stores a reference to the "latest" immutable snapshot. + */ +declare class SnapshotHolder { + private rootNode_; + getNode(path: Path): Node_2; + updateSnapshot(path: Path, newSnapshotNode: Node_2): void; +} + +/** + * An immutable sorted map implementation, based on a Left-leaning Red-Black + * tree. + */ +declare class SortedMap { + private comparator_; + private root_; + /** + * Always use the same empty node, to reduce memory. + */ + static EMPTY_NODE: LLRBEmptyNode; + /** + * @param comparator_ - Key comparator. + * @param root_ - Optional root node for the map. + */ + constructor( + comparator_: Comparator, + root_?: LLRBNode | LLRBEmptyNode + ); + /** + * Returns a copy of the map, with the specified key/value added or replaced. + * (TODO: We should perhaps rename this method to 'put') + * + * @param key - Key to be added. + * @param value - Value to be added. + * @returns New map, with item added. + */ + insert(key: K, value: V): SortedMap; + /** + * Returns a copy of the map, with the specified key removed. + * + * @param key - The key to remove. + * @returns New map, with item removed. + */ + remove(key: K): SortedMap; + /** + * Returns the value of the node with the given key, or null. + * + * @param key - The key to look up. + * @returns The value of the node with the given key, or null if the + * key doesn't exist. + */ + get(key: K): V | null; + /** + * Returns the key of the item *before* the specified key, or null if key is the first item. + * @param key - The key to find the predecessor of + * @returns The predecessor key. + */ + getPredecessorKey(key: K): K | null; + /** + * @returns True if the map is empty. + */ + isEmpty(): boolean; + /** + * @returns The total number of nodes in the map. + */ + count(): number; + /** + * @returns The minimum key in the map. + */ + minKey(): K | null; + /** + * @returns The maximum key in the map. + */ + maxKey(): K | null; + /** + * Traverses the map in key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns The first truthy value returned by action, or the last falsey + * value returned by action + */ + inorderTraversal(action: (k: K, v: V) => unknown): boolean; + /** + * Traverses the map in reverse key order and calls the specified action function + * for each key/value pair. + * + * @param action - Callback function to be called + * for each key/value pair. If action returns true, traversal is aborted. + * @returns True if the traversal was aborted. + */ + reverseTraversal(action: (k: K, v: V) => void): boolean; + /** + * Returns an iterator over the SortedMap. + * @returns The iterator. + */ + getIterator( + resultGenerator?: (k: K, v: V) => T + ): SortedMapIterator; + getIteratorFrom( + key: K, + resultGenerator?: (k: K, v: V) => T + ): SortedMapIterator; + getReverseIteratorFrom( + key: K, + resultGenerator?: (k: K, v: V) => T + ): SortedMapIterator; + getReverseIterator( + resultGenerator?: (k: K, v: V) => T + ): SortedMapIterator; +} + +/** + * An iterator over an LLRBNode. + */ +declare class SortedMapIterator { + private isReverse_; + private resultGenerator_; + private nodeStack_; + /** + * @param node - Node to iterate. + * @param isReverse_ - Whether or not to iterate in reverse + */ + constructor( + node: LLRBNode | LLRBEmptyNode, + startKey: K | null, + comparator: Comparator, + isReverse_: boolean, + resultGenerator_?: ((k: K, v: V) => T) | null + ); + getNext(): T; + hasNext(): boolean; + peek(): T; +} + +/** + * Helper class to store a sparse set of snapshots. + */ +declare interface SparseSnapshotTree { + value: Node_2 | null; + readonly children: Map; +} + +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAfter( + value: number | string | boolean | null, + key?: string +): QueryConstraint; + +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAt( + value?: number | string | boolean | null, + key?: string +): QueryConstraint; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Tracks a collection of stats. + */ +declare class StatsCollection { + private counters_; + incrementCounter(name: string, amount?: number): void; + get(): { + [k: string]: number; + }; +} + +/** + * Returns the delta from the previous call to get stats. + * + * @param collection_ - The collection to "listen" to. + */ +declare class StatsListener { + private collection_; + private last_; + constructor(collection_: StatsCollection); + get(): { + [k: string]: number; + }; +} + +declare class StatsReporter { + private server_; + private statsListener_; + statsToReport_: { + [k: string]: boolean; + }; + constructor(collection: StatsCollection, server_: ServerActions); + private reportStats_; +} + +/** + * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to + * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes + * and user writes (set, transaction, update). + * + * It's responsible for: + * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). + * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, + * applyUserOverwrite, etc.) + */ +declare class SyncPoint { + /** + * The Views being tracked at this location in the tree, stored as a map where the key is a + * queryId and the value is the View for that query. + * + * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). + */ + readonly views: Map; +} + +/** + * SyncTree is the central class for managing event callback registration, data caching, views + * (query processing), and event generation. There are typically two SyncTree instances for + * each Repo, one for the normal Firebase data, and one for the .info data. + * + * It has a number of responsibilities, including: + * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). + * - Applying and caching data changes for user set(), transaction(), and update() calls + * (applyUserOverwrite(), applyUserMerge()). + * - Applying and caching data changes for server data changes (applyServerOverwrite(), + * applyServerMerge()). + * - Generating user-facing events for server and user changes (all of the apply* methods + * return the set of events that need to be raised as a result). + * - Maintaining the appropriate set of server listens to ensure we are always subscribed + * to the correct set of paths and queries to satisfy the current set of user event + * callbacks (listens are started/stopped using the provided listenProvider). + * + * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual + * events are returned to the caller rather than raised synchronously. + * + */ +declare class SyncTree { + listenProvider_: ListenProvider; + /** + * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. + */ + syncPointTree_: ImmutableTree; + /** + * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). + */ + pendingWriteTree_: WriteTree; + readonly tagToQueryMap: Map; + readonly queryToTagMap: Map; + /** + * @param listenProvider_ - Used by SyncTree to start / stop listening + * to server data. + */ + constructor(listenProvider_: ListenProvider); +} + +/* Excluded from this release type: _TEST_ACCESS_forceRestClient */ + +/* Excluded from this release type: _TEST_ACCESS_hijackHash */ + +/** + * A `Promise` that can also act as a `DatabaseReference` when returned by + * {@link push}. The reference is available immediately and the `Promise` resolves + * as the write to the backend completes. + */ +export declare interface ThenableReference + extends DatabaseReference, + Pick, 'then' | 'catch'> {} + +declare interface Transaction { + path: Path; + update: (a: unknown) => unknown; + onComplete: ( + error: Error | null, + committed: boolean, + node: Node_2 | null + ) => void; + status: TransactionStatus; + order: number; + applyLocally: boolean; + retryCount: number; + unwatcher: () => void; + abortReason: string | null; + currentWriteId: number; + currentInputSnapshot: Node_2 | null; + currentOutputSnapshotRaw: Node_2 | null; + currentOutputSnapshotResolved: Node_2 | null; +} + +/** An options object to configure transactions. */ +export declare interface TransactionOptions { + /** + * By default, events are raised each time the transaction update function + * runs. So if it is run multiple times, you may see intermediate states. You + * can set this to false to suppress these intermediate states and instead + * wait until the transaction has completed before events are raised. + */ + readonly applyLocally?: boolean; +} + +/** + * A type for the resolve value of {@link runTransaction}. + */ +export declare class TransactionResult { + /** Whether the transaction was successfully committed. */ + readonly committed: boolean; + /** The resulting data snapshot. */ + readonly snapshot: DataSnapshot; + /** @hideconstructor */ + constructor( + /** Whether the transaction was successfully committed. */ + committed: boolean, + /** The resulting data snapshot. */ + snapshot: DataSnapshot + ); + /** Returns a JSON-serializable representation of this object. */ + toJSON(): object; +} + +declare const enum TransactionStatus { + RUN = 0, + SENT = 1, + COMPLETED = 2, + SENT_NEEDS_ABORT = 3, + NEEDS_ABORT = 4 +} + +/** + * A light-weight tree, traversable by path. Nodes can have both values and children. + * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty + * children. + */ +declare class Tree { + readonly name: string; + readonly parent: Tree | null; + node: TreeNode; + /** + * @param name - Optional name of the node. + * @param parent - Optional parent node. + * @param node - Optional node to wrap. + */ + constructor(name?: string, parent?: Tree | null, node?: TreeNode); +} + +/** + * Node in a Tree. + */ +declare interface TreeNode { + children: Record>; + childCount: number; + value?: T; +} + +/** A callback that can invoked to remove a listener. */ +export declare type Unsubscribe = () => void; + +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +export declare function update( + ref: DatabaseReference, + values: object +): Promise; + +/* Excluded from this release type: _UserCallback */ + +/* Excluded from this release type: _validatePathString */ + +/* Excluded from this release type: _validateWritablePath */ + +/** + * A view represents a specific location and query that has 1 or more event registrations. + * + * It does several things: + * - Maintains the list of event registrations for this location/query. + * - Maintains a cache of the data visible for this location/query. + * - Applies new operations (via applyOperation), updates the cache, and based on the event + * registrations returns the set of events to be raised. + */ +declare class View { + private query_; + processor_: ViewProcessor; + viewCache_: ViewCache; + eventRegistrations_: EventRegistration[]; + eventGenerator_: EventGenerator; + constructor(query_: QueryContext, initialViewCache: ViewCache); + get query(): QueryContext; +} + +/** + * Stores the data we have cached for a view. + * + * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes). + */ +declare interface ViewCache { + readonly eventCache: CacheNode; + readonly serverCache: CacheNode; +} + +declare interface ViewProcessor { + readonly filter: NodeFilter_2; +} + +/** + * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In + * the case of a set() or transaction, snap will be non-null. In the case of an update(), children will be non-null. + */ +declare interface WriteRecord { + writeId: number; + path: Path; + snap?: Node_2 | null; + children?: { + [k: string]: Node_2; + } | null; + visible: boolean; +} + +/** + * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them + * with underlying server data (to create "event cache" data). Pending writes are added with addOverwrite() + * and addMerge(), and removed with removeWrite(). + */ +declare interface WriteTree { + /** + * A tree tracking the result of applying all visible writes. This does not include transactions with + * applyLocally=false or writes that are completely shadowed by other writes. + */ + visibleWrites: CompoundWrite; + /** + * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary + * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also + * used by transactions). + */ + allWrites: WriteRecord[]; + lastWriteId: number; +} + +export {}; diff --git a/repo-scripts/prune-dts/new-tests/database.output.d.ts b/repo-scripts/prune-dts/new-tests/database.output.d.ts new file mode 100644 index 00000000000..8c0d0bd4f77 --- /dev/null +++ b/repo-scripts/prune-dts/new-tests/database.output.d.ts @@ -0,0 +1,1584 @@ +/** + * Firebase Realtime Database + * + * @packageDocumentation + */ +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { AppCheckTokenListener } from '@firebase/app-check-interop-types'; +import { AppCheckTokenResult } from '@firebase/app-check-interop-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseApp as FirebaseApp_2 } from '@firebase/app-types'; +import { FirebaseAppCheckInternal } from '@firebase/app-check-interop-types'; +import { FirebaseAuthInternal } from '@firebase/auth-interop-types'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { FirebaseAuthTokenData } from '@firebase/app-types/private'; +import { Provider } from '@firebase/component'; +/** + * Gets a `Reference` for the location at the specified relative path. + * + * The relative path can either be a simple child name (for example, "ada") or + * a deeper slash-separated path (for example, "ada/name/first"). + * + * @param parent - The parent location. + * @param path - A relative path from this location to the desired child + * location. + * @returns The specified child location. + */ +export declare function child( + parent: DatabaseReference, + path: string +): DatabaseReference; +/** + * Modify the provided instance to communicate with the Realtime Database + * emulator. + * + *

Note: This method must be called before performing any other operation. + * + * @param db - The instance to modify. + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 8080) + * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules + */ +export declare function connectDatabaseEmulator( + db: Database, + host: string, + port: number, + options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + } +): void; +/** + * Class representing a Firebase Realtime Database. + */ +export declare class Database { + /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ + readonly app: FirebaseApp; + /** Represents a `Database` instance. */ + readonly 'type' = 'database'; + private constructor(); +} +/** + * A `DatabaseReference` represents a specific location in your Database and can be used + * for reading or writing data to that Database location. + * + * You can reference the root or child location in your Database by calling + * `ref()` or `ref("child/path")`. + * + * Writing is done with the `set()` method and reading can be done with the + * `on*()` method. See {@link + * https://firebase.google.com/docs/database/web/read-and-write} + */ +export declare interface DatabaseReference extends Query { + /** + * The last part of the `DatabaseReference`'s path. + * + * For example, `"ada"` is the key for + * `https://.firebaseio.com/users/ada`. + * + * The key of a root `DatabaseReference` is `null`. + */ + readonly key: string | null; + /** + * The parent location of a `DatabaseReference`. + * + * The parent of a root `DatabaseReference` is `null`. + */ + readonly parent: DatabaseReference | null; + /** The root `DatabaseReference` of the Database. */ + readonly root: DatabaseReference; +} +/** + * A `DataSnapshot` contains data from a Database location. + * + * Any time you read data from the Database, you receive the data as a + * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach + * with `on()` or `once()`. You can extract the contents of the snapshot as a + * JavaScript object by calling the `val()` method. Alternatively, you can + * traverse into the snapshot by calling `child()` to return child snapshots + * (which you could then call `val()` on). + * + * A `DataSnapshot` is an efficiently generated, immutable copy of the data at + * a Database location. It cannot be modified and will never change (to modify + * data, you always call the `set()` method on a `Reference` directly). + */ +export declare class DataSnapshot { + /** + * The location of this DataSnapshot. + */ + readonly ref: DatabaseReference; + private constructor(); + /** + * Gets the priority value of the data in this `DataSnapshot`. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data} + * ). + */ + get priority(): string | number | null; + /** + * The key (last part of the path) of the location of this `DataSnapshot`. + * + * The last token in a Database location is considered its key. For example, + * "ada" is the key for the /users/ada/ node. Accessing the key on any + * `DataSnapshot` will return the key for the location that generated it. + * However, accessing the key on the root URL of a Database will return + * `null`. + */ + get key(): string | null; + /** Returns the number of child properties of this `DataSnapshot`. */ + get size(): number; + /** + * Gets another `DataSnapshot` for the location at the specified relative path. + * + * Passing a relative path to the `child()` method of a DataSnapshot returns + * another `DataSnapshot` for the location at the specified relative path. The + * relative path can either be a simple child name (for example, "ada") or a + * deeper, slash-separated path (for example, "ada/name/first"). If the child + * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot` + * whose value is `null`) is returned. + * + * @param path - A relative path to the location of child data. + */ + child(path: string): DataSnapshot; + /** + * Returns true if this `DataSnapshot` contains any data. It is slightly more + * efficient than using `snapshot.val() !== null`. + */ + exists(): boolean; + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + * + * The `exportVal()` method is similar to `val()`, except priority information + * is included (if available), making it suitable for backing up your data. + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + exportVal(): any; + /** + * Enumerates the top-level children in the `IteratedDataSnapshot`. + * + * Because of the way JavaScript objects work, the ordering of data in the + * JavaScript object returned by `val()` is not guaranteed to match the + * ordering on the server nor the ordering of `onChildAdded()` events. That is + * where `forEach()` comes in handy. It guarantees the children of a + * `DataSnapshot` will be iterated in their query order. + * + * If no explicit `orderBy*()` method is used, results are returned + * ordered by key (unless priorities are used, in which case, results are + * returned by priority). + * + * @param action - A function that will be called for each child DataSnapshot. + * The callback can return true to cancel further enumeration. + * @returns true if enumeration was canceled due to your callback returning + * true. + */ + forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean; + /** + * Returns true if the specified child path has (non-null) data. + * + * @param path - A relative path to the location of a potential child. + * @returns `true` if data exists at the specified child path; else + * `false`. + */ + hasChild(path: string): boolean; + /** + * Returns whether or not the `DataSnapshot` has any non-`null` child + * properties. + * + * You can use `hasChildren()` to determine if a `DataSnapshot` has any + * children. If it does, you can enumerate them using `forEach()`. If it + * doesn't, then either this snapshot contains a primitive value (which can be + * retrieved with `val()`) or it is empty (in which case, `val()` will return + * `null`). + * + * @returns true if this snapshot has any children; else false. + */ + hasChildren(): boolean; + /** + * Returns a JSON-serializable representation of this object. + */ + toJSON(): object | null; + /** + * Extracts a JavaScript value from a `DataSnapshot`. + * + * Depending on the data in a `DataSnapshot`, the `val()` method may return a + * scalar type (string, number, or boolean), an array, or an object. It may + * also return null, indicating that the `DataSnapshot` is empty (contains no + * data). + * + * @returns The DataSnapshot's contents as a JavaScript value (Object, + * Array, string, number, boolean, or `null`). + */ + val(): any; +} +export { EmulatorMockTokenOptions }; +/** + * Logs debugging information to the console. + * + * @param enabled - Enables logging if `true`, disables logging if `false`. + * @param persistent - Remembers the logging state between page refreshes if + * `true`. + */ +export declare function enableLogging( + enabled: boolean, + persistent?: boolean +): any; +/** + * Logs debugging information to the console. + * + * @param logger - A custom logger function to control how things get logged. + */ +export declare function enableLogging( + logger: (message: string) => unknown +): any; +/** + * Creates a `QueryConstraint` with the specified ending point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name less than or equal + * to the specified key. + * + * You can read more about `endAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to end at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end at, among the children with the previously + * specified priority. This argument is only allowed if ordering by child, + * value, or priority. + */ +export declare function endAt( + value: number | string | boolean | null, + key?: string +): QueryConstraint; +/** + * Creates a `QueryConstraint` with the specified ending point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The ending point is exclusive. If only a value is provided, children + * with a value less than the specified value will be included in the query. + * If a key is specified, then children must have a value less than or equal + * to the specified value and a key name less than the specified key. + * + * @param value - The value to end before. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to end before, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function endBefore( + value: number | string | boolean | null, + key?: string +): QueryConstraint; +/** + * Creates a `QueryConstraint` that includes children that match the specified + * value. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The optional key argument can be used to further limit the range of the + * query. If it is specified, then children that have exactly the specified + * value must also have exactly the specified key as their key name. This can be + * used to filter result sets with many matches for the same value. + * + * You can read more about `equalTo()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to match for. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at, among the children with the + * previously specified priority. This argument is only allowed if ordering by + * child, value, or priority. + */ +export declare function equalTo( + value: number | string | boolean | null, + key?: string +): QueryConstraint; +/** + * One of the following strings: "value", "child_added", "child_changed", + * "child_removed", or "child_moved." + */ +export declare type EventType = + | 'value' + | 'child_added' + | 'child_changed' + | 'child_moved' + | 'child_removed'; +/* Excluded from this release type: _FirebaseService */ +/** + * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL. + */ +export declare function forceLongPolling(): void; +/** + * Force the use of websockets instead of longPolling. + */ +export declare function forceWebSockets(): void; +/** + * Gets the most up-to-date result for this query. + * + * @param query - The query to run. + * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is + * available, or rejects if the client is unable to return a value (e.g., if the + * server is unreachable and there is nothing cached). + */ +export declare function get(query: Query): Promise; +/** + * Returns the instance of the Realtime Database SDK that is associated with the provided + * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if + * no instance exists or if the existing instance uses a custom database URL. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime + * Database instance is associated with. + * @param url - The URL of the Realtime Database instance to connect to. If not + * provided, the SDK connects to the default instance of the Firebase App. + * @returns The `Database` instance of the provided app. + */ +export declare function getDatabase(app?: FirebaseApp, url?: string): Database; +/** + * Disconnects from the server (all Database operations will be completed + * offline). + * + * The client automatically maintains a persistent connection to the Database + * server, which will remain active indefinitely and reconnect when + * disconnected. However, the `goOffline()` and `goOnline()` methods may be used + * to control the client connection in cases where a persistent connection is + * undesirable. + * + * While offline, the client will no longer receive data updates from the + * Database. However, all Database operations performed locally will continue to + * immediately fire events, allowing your application to continue behaving + * normally. Additionally, each operation performed locally will automatically + * be queued and retried upon reconnection to the Database server. + * + * To reconnect to the Database and begin receiving remote events, see + * `goOnline()`. + * + * @param db - The instance to disconnect. + */ +export declare function goOffline(db: Database): void; +/** + * Reconnects to the server and synchronizes the offline Database state + * with the server state. + * + * This method should be used after disabling the active connection with + * `goOffline()`. Once reconnected, the client will transmit the proper data + * and fire the appropriate events so that your client "catches up" + * automatically. + * + * @param db - The instance to reconnect. + */ +export declare function goOnline(db: Database): void; +/** + * Returns a placeholder value that can be used to atomically increment the + * current database value by the provided delta. + * + * @param delta - the amount to modify the current value atomically. + * @returns A placeholder value for modifying data atomically server-side. + */ +export declare function increment(delta: number): object; +/* Excluded from this release type: _initStandalone */ +/** + * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined. + */ +export declare interface IteratedDataSnapshot extends DataSnapshot { + key: string; +} +/** + * Creates a new `QueryConstraint` that if limited to the first specific number + * of children. + * + * The `limitToFirst()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the first 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToFirst()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToFirst(limit: number): QueryConstraint; +/** + * Creates a new `QueryConstraint` that is limited to return only the last + * specified number of children. + * + * The `limitToLast()` method is used to set a maximum number of children to be + * synced for a given callback. If we set a limit of 100, we will initially only + * receive up to 100 `child_added` events. If we have fewer than 100 messages + * stored in our Database, a `child_added` event will fire for each message. + * However, if we have over 100 messages, we will only receive a `child_added` + * event for the last 100 ordered messages. As items change, we will receive + * `child_removed` events for each item that drops out of the active list so + * that the total number stays at 100. + * + * You can read more about `limitToLast()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param limit - The maximum number of nodes to include in this query. + */ +export declare function limitToLast(limit: number): QueryConstraint; +/** An options objects that can be used to customize a listener. */ +export declare interface ListenOptions { + /** Whether to remove the listener after its first invocation. */ + readonly onlyOnce?: boolean; +} +/** + * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener. + * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from + * the respective `on*` callbacks. + * + * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener + * will not automatically remove listeners registered on child nodes, `off()` + * must also be called on any child listeners to remove the callback. + * + * If a callback is not specified, all callbacks for the specified eventType + * will be removed. Similarly, if no eventType is specified, all callbacks + * for the `Reference` will be removed. + * + * Individual listeners can also be removed by invoking their unsubscribe + * callbacks. + * + * @param query - The query that the listener was registered with. + * @param eventType - One of the following strings: "value", "child_added", + * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks + * for the `Reference` will be removed. + * @param callback - The callback function that was passed to `on()` or + * `undefined` to remove all callbacks. + */ +export declare function off( + query: Query, + eventType?: EventType, + callback?: ( + snapshot: DataSnapshot, + previousChildName?: string | null + ) => unknown +): void; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName?: string | null + ) => unknown, + cancelCallback?: (error: Error) => unknown +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + options: ListenOptions +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildAdded` event will be triggered once for each initial child at this + * location, and it will be triggered again every time a new child is added. The + * `DataSnapshot` passed into the callback will reflect the data for the + * relevant child. For ordering purposes, it is passed a second argument which + * is a string containing the key of the previous sibling child by sort order, + * or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildAdded( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + cancelCallback: (error: Error) => unknown, + options: ListenOptions +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + cancelCallback?: (error: Error) => unknown +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + options: ListenOptions +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildChanged` event will be triggered when the data stored in a child + * (or any of its descendants) changes. Note that a single `child_changed` event + * may represent multiple changes to the child. The `DataSnapshot` passed to the + * callback will contain the new child contents. For ordering purposes, the + * callback is also passed a second argument which is a string containing the + * key of the previous sibling child by sort order, or `null` if it is the first + * child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildChanged( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + cancelCallback: (error: Error) => unknown, + options: ListenOptions +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + cancelCallback?: (error: Error) => unknown +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + options: ListenOptions +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildMoved` event will be triggered when a child's sort order changes + * such that its position relative to its siblings changes. The `DataSnapshot` + * passed to the callback will be for the data of the child that has moved. It + * is also passed a second argument which is a string containing the key of the + * previous sibling child by sort order, or `null` if it is the first child. + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildMoved( + query: Query, + callback: ( + snapshot: DataSnapshot, + previousChildName: string | null + ) => unknown, + cancelCallback: (error: Error) => unknown, + options: ListenOptions +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + cancelCallback?: (error: Error) => unknown +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + options: ListenOptions +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onChildRemoved` event will be triggered once every time a child is + * removed. The `DataSnapshot` passed into the callback will be the old data for + * the child that was removed. A child will get removed when either: + * + * - a client explicitly calls `remove()` on that child or one of its ancestors + * - a client calls `set(null)` on that child or one of its ancestors + * - that child has all of its children removed + * - there is a query in effect which now filters out the child (because it's + * sort order changed or the max limit was hit) + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. + * The callback will be passed a DataSnapshot and a string containing the key of + * the previous child, by sort order, or `null` if it is the first child. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onChildRemoved( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + cancelCallback: (error: Error) => unknown, + options: ListenOptions +): Unsubscribe; +/** + * The `onDisconnect` class allows you to write or clear data when your client + * disconnects from the Database server. These updates occur whether your + * client disconnects cleanly or not, so you can rely on them to clean up data + * even if a connection is dropped or a client crashes. + * + * The `onDisconnect` class is most commonly used to manage presence in + * applications where it is useful to detect how many clients are connected and + * when other clients disconnect. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * To avoid problems when a connection is dropped before the requests can be + * transferred to the Database server, these functions should be called before + * writing any data. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time you reconnect. + */ +export declare class OnDisconnect { + private constructor(); + /** + * Cancels all previously queued `onDisconnect()` set or update events for this + * location and all children. + * + * If a write has been queued for this location via a `set()` or `update()` at a + * parent location, the write at this location will be canceled, though writes + * to sibling locations will still occur. + * + * @returns Resolves when synchronization to the server is complete. + */ + cancel(): Promise; + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + * + * @returns Resolves when synchronization to the server is complete. + */ + remove(): Promise; + /** + * Ensures the data at this location is set to the specified value when the + * client is disconnected (due to closing the browser, navigating to a new page, + * or network issues). + * + * `set()` is especially useful for implementing "presence" systems, where a + * value should be changed or cleared when a user disconnects so that they + * appear "offline" to other users. See + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information. + * + * Note that `onDisconnect` operations are only triggered once. If you want an + * operation to occur each time a disconnect occurs, you'll need to re-establish + * the `onDisconnect` operations each time. + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + set(value: unknown): Promise; + /** + * Ensures the data at this location is set to the specified value and priority + * when the client is disconnected (due to closing the browser, navigating to a + * new page, or network issues). + * + * @param value - The value to be written to this location on disconnect (can + * be an object, array, string, number, boolean, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when synchronization to the Database is complete. + */ + setWithPriority( + value: unknown, + priority: number | string | null + ): Promise; + /** + * Writes multiple values at this location when the client is disconnected (due + * to closing the browser, navigating to a new page, or network issues). + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, "name/first") + * from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * @param values - Object containing multiple values. + * @returns Resolves when synchronization to the Database is complete. + */ + update(values: object): Promise; +} +/** + * Returns an `OnDisconnect` object - see + * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript} + * for more information on how to use it. + * + * @param ref - The reference to add OnDisconnect triggers for. + */ +export declare function onDisconnect(ref: DatabaseReference): OnDisconnect; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + cancelCallback?: (error: Error) => unknown +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + options: ListenOptions +): Unsubscribe; +/** + * Listens for data changes at a particular location. + * + * This is the primary way to read data from a Database. Your callback + * will be triggered for the initial data and again whenever the data changes. + * Invoke the returned unsubscribe callback to stop receiving updates. See + * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web} + * for more details. + * + * An `onValue` event will trigger once with the initial data stored at this + * location, and then trigger again each time the data changes. The + * `DataSnapshot` passed to the callback will be for the location at which + * `on()` was called. It won't trigger until the entire contents has been + * synchronized. If the location has no data, it will be triggered with an empty + * `DataSnapshot` (`val()` will return `null`). + * + * @param query - The query to run. + * @param callback - A callback that fires when the specified event occurs. The + * callback will be passed a DataSnapshot. + * @param cancelCallback - An optional callback that will be notified if your + * event subscription is ever canceled because your client does not have + * permission to read this data (or it had permission but has now lost it). + * This callback will be passed an `Error` object indicating why the failure + * occurred. + * @param options - An object that can be used to configure `onlyOnce`, which + * then removes the listener after its first invocation. + * @returns A function that can be invoked to remove the listener. + */ +export declare function onValue( + query: Query, + callback: (snapshot: DataSnapshot) => unknown, + cancelCallback: (error: Error) => unknown, + options: ListenOptions +): Unsubscribe; +/** + * Creates a new `QueryConstraint` that orders by the specified child key. + * + * Queries can only order by one key at a time. Calling `orderByChild()` + * multiple times on the same query is an error. + * + * Firebase queries allow you to order your data by any child key on the fly. + * However, if you know in advance what your indexes will be, you can define + * them via the .indexOn rule in your Security Rules for better performance. See + * the{@link https://firebase.google.com/docs/database/security/indexing-data} + * rule for more information. + * + * You can read more about `orderByChild()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + * + * @param path - The path to order by. + */ +export declare function orderByChild(path: string): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by the key. + * + * Sorts the results of a query by their (ascending) key values. + * + * You can read more about `orderByKey()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByKey(): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by priority. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data} + * for alternatives to priority. + */ +export declare function orderByPriority(): QueryConstraint; +/** + * Creates a new `QueryConstraint` that orders by value. + * + * If the children of a query are all scalar values (string, number, or + * boolean), you can order the results by their (ascending) values. + * + * You can read more about `orderByValue()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}. + */ +export declare function orderByValue(): QueryConstraint; +/** + * Generates a new child location using a unique key and returns its + * `Reference`. + * + * This is the most common pattern for adding data to a collection of items. + * + * If you provide a value to `push()`, the value is written to the + * generated location. If you don't pass a value, nothing is written to the + * database and the child remains empty (but you can use the `Reference` + * elsewhere). + * + * The unique keys generated by `push()` are ordered by the current time, so the + * resulting list of items is chronologically sorted. The keys are also + * designed to be unguessable (they contain 72 random bits of entropy). + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}. + * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}. + * + * @param parent - The parent location. + * @param value - Optional value to be written at the generated location. + * @returns Combined `Promise` and `Reference`; resolves when write is complete, + * but can be used immediately as the `Reference` to the child location. + */ +export declare function push( + parent: DatabaseReference, + value?: unknown +): ThenableReference; +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` sorts and filters the data at a Database location so only a subset + * of the child data is included. This can be used to order a collection of + * data by some attribute (for example, height of dinosaurs) as well as to + * restrict a large list of items (for example, chat messages) down to a number + * suitable for synchronizing to the client. Queries are created by chaining + * together one or more of the filter methods defined here. + * + * Just as with a `DatabaseReference`, you can receive data from a `Query` by using the + * `on*()` methods. You will only receive events and `DataSnapshot`s for the + * subset of the data that matches your query. + * + * See {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data} + * for more information. + */ +export declare interface Query { + /** The `DatabaseReference` for the `Query`'s location. */ + readonly ref: DatabaseReference; + /** + * Returns whether or not the current and provided queries represent the same + * location, have the same query parameters, and are from the same instance of + * `FirebaseApp`. + * + * Two `DatabaseReference` objects are equivalent if they represent the same location + * and are from the same instance of `FirebaseApp`. + * + * Two `Query` objects are equivalent if they represent the same location, + * have the same query parameters, and are from the same instance of + * `FirebaseApp`. Equivalent queries share the same sort order, limits, and + * starting and ending points. + * + * @param other - The query to compare against. + * @returns Whether or not the current and provided queries are equivalent. + */ + isEqual(other: Query | null): boolean; + /** + * Returns a JSON-serializable representation of this object. + * + * @returns A JSON-serializable representation of this object. + */ + toJSON(): string; + /** + * Gets the absolute URL for this location. + * + * The `toString()` method returns a URL that is ready to be put into a + * browser, curl command, or a `refFromURL()` call. Since all of those expect + * the URL to be url-encoded, `toString()` returns an encoded URL. + * + * Append '.json' to the returned URL when typed into a browser to download + * JSON-formatted data. If the location is secured (that is, not publicly + * readable), you will get a permission-denied error. + * + * @returns The absolute URL for this location. + */ + toString(): string; +} +/** + * Creates a new immutable instance of `Query` that is extended to also include + * additional query constraints. + * + * @param query - The Query instance to use as a base for the new constraints. + * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query( + query: Query, + ...queryConstraints: QueryConstraint[] +): Query; +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Database query. `QueryConstraint`s are created by invoking {@link endAt}, + * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link + * limitToFirst}, {@link limitToLast}, {@link orderByChild}, + * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} , + * {@link orderByValue} or {@link equalTo} and + * can then be passed to {@link query} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint { + /** The type of this query constraints */ + abstract readonly type: QueryConstraintType; +} +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = + | 'endAt' + | 'endBefore' + | 'startAt' + | 'startAfter' + | 'limitToFirst' + | 'limitToLast' + | 'orderByChild' + | 'orderByKey' + | 'orderByPriority' + | 'orderByValue' + | 'equalTo'; +/* Excluded from this release type: _QueryImpl */ +/* Excluded from this release type: _QueryParams */ +/** + * + * Returns a `Reference` representing the location in the Database + * corresponding to the provided path. If no path is provided, the `Reference` + * will point to the root of the Database. + * + * @param db - The database instance to obtain a reference for. + * @param path - Optional path representing the location the returned + * `Reference` will point. If not provided, the returned `Reference` will + * point to the root of the Database. + * @returns If a path is provided, a `Reference` + * pointing to the provided path. Otherwise, a `Reference` pointing to the + * root of the Database. + */ +export declare function ref(db: Database, path?: string): DatabaseReference; +/* Excluded from this release type: _ReferenceImpl */ +/** + * Returns a `Reference` representing the location in the Database + * corresponding to the provided Firebase URL. + * + * An exception is thrown if the URL is not a valid Firebase Database URL or it + * has a different domain than the current `Database` instance. + * + * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored + * and are not applied to the returned `Reference`. + * + * @param db - The database instance to obtain a reference for. + * @param url - The Firebase URL at which the returned `Reference` will + * point. + * @returns A `Reference` pointing to the provided + * Firebase URL. + */ +export declare function refFromURL( + db: Database, + url: string +): DatabaseReference; +/** + * Removes the data at this Database location. + * + * Any data at child locations will also be deleted. + * + * The effect of the remove will be visible immediately and the corresponding + * event 'value' will be triggered. Synchronization of the remove to the + * Firebase servers will also be started, and the returned Promise will resolve + * when complete. If provided, the onComplete callback will be called + * asynchronously after synchronization has finished. + * + * @param ref - The location to remove. + * @returns Resolves when remove on server is complete. + */ +export declare function remove(ref: DatabaseReference): Promise; +/* Excluded from this release type: _repoManagerDatabaseFromApp */ +/** + * Atomically modifies the data at this location. + * + * Atomically modify the data at this location. Unlike a normal `set()`, which + * just overwrites the data regardless of its previous value, `runTransaction()` is + * used to modify the existing value to a new value, ensuring there are no + * conflicts with other clients writing to the same location at the same time. + * + * To accomplish this, you pass `runTransaction()` an update function which is + * used to transform the current value into a new value. If another client + * writes to the location before your new value is successfully written, your + * update function will be called again with the new current value, and the + * write will be retried. This will happen repeatedly until your write succeeds + * without conflict or you abort the transaction by not returning a value from + * your update function. + * + * Note: Modifying data with `set()` will cancel any pending transactions at + * that location, so extreme care should be taken if mixing `set()` and + * `runTransaction()` to update the same data. + * + * Note: When using transactions with Security and Firebase Rules in place, be + * aware that a client needs `.read` access in addition to `.write` access in + * order to perform a transaction. This is because the client-side nature of + * transactions requires the client to read the data in order to transactionally + * update it. + * + * @param ref - The location to atomically modify. + * @param transactionUpdate - A developer-supplied function which will be passed + * the current data stored at this location (as a JavaScript object). The + * function should return the new value it would like written (as a JavaScript + * object). If `undefined` is returned (i.e. you return with no arguments) the + * transaction will be aborted and the data at this location will not be + * modified. + * @param options - An options object to configure transactions. + * @returns A `Promise` that can optionally be used instead of the `onComplete` + * callback to handle success and failure. + */ +export declare function runTransaction( + ref: DatabaseReference, + transactionUpdate: (currentData: any) => unknown, + options?: TransactionOptions +): Promise; +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a placeholder value for auto-populating the current timestamp (time + * since the Unix epoch, in milliseconds) as determined by the Firebase + * servers. + */ +export declare function serverTimestamp(): object; +/** + * Writes data to this Database location. + * + * This will overwrite any data at this location and all child locations. + * + * The effect of the write will be visible immediately, and the corresponding + * events ("value", "child_added", etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * Passing `null` for the new value is equivalent to calling `remove()`; namely, + * all data at this location and all child locations will be deleted. + * + * `set()` will remove any priority stored at this location, so if priority is + * meant to be preserved, you need to use `setWithPriority()` instead. + * + * Note that modifying data with `set()` will cancel any pending transactions + * at that location, so extreme care should be taken if mixing `set()` and + * `transaction()` to modify the same data. + * + * A single `set()` will generate a single "value" event at the location where + * the `set()` was performed. + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @returns Resolves when write to server is complete. + */ +export declare function set( + ref: DatabaseReference, + value: unknown +): Promise; +/** + * Sets a priority for the data at this Database location. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setPriority( + ref: DatabaseReference, + priority: string | number | null +): Promise; +/* Excluded from this release type: _setSDKVersion */ +/** + * Writes data the Database location. Like `set()` but also specifies the + * priority for that data. + * + * Applications need not use priority but can order collections by + * ordinary properties (see + * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data} + * ). + * + * @param ref - The location to write to. + * @param value - The value to be written (string, number, boolean, object, + * array, or null). + * @param priority - The priority to be written (string, number, or null). + * @returns Resolves when write to server is complete. + */ +export declare function setWithPriority( + ref: DatabaseReference, + value: unknown, + priority: string | number | null +): Promise; +/** + * Creates a `QueryConstraint` with the specified starting point (exclusive). + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is exclusive. If only a value is provided, children + * with a value greater than the specified value will be included in the query. + * If a key is specified, then children must have a value greater than or equal + * to the specified value and a a key name greater than the specified key. + * + * @param value - The value to start after. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start after. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAfter( + value: number | string | boolean | null, + key?: string +): QueryConstraint; +/** + * Creates a `QueryConstraint` with the specified starting point. + * + * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()` + * allows you to choose arbitrary starting and ending points for your queries. + * + * The starting point is inclusive, so children with exactly the specified value + * will be included in the query. The optional key argument can be used to + * further limit the range of the query. If it is specified, then children that + * have exactly the specified value must also have a key name greater than or + * equal to the specified key. + * + * You can read more about `startAt()` in + * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}. + * + * @param value - The value to start at. The argument type depends on which + * `orderBy*()` function was used in this query. Specify a value that matches + * the `orderBy*()` type. When used in combination with `orderByKey()`, the + * value must be a string. + * @param key - The child key to start at. This argument is only allowed if + * ordering by child, value, or priority. + */ +export declare function startAt( + value?: number | string | boolean | null, + key?: string +): QueryConstraint; +/* Excluded from this release type: _TEST_ACCESS_forceRestClient */ +/* Excluded from this release type: _TEST_ACCESS_hijackHash */ +/** + * A `Promise` that can also act as a `DatabaseReference` when returned by + * {@link push}. The reference is available immediately and the `Promise` resolves + * as the write to the backend completes. + */ +export declare interface ThenableReference + extends DatabaseReference, + Pick, 'then' | 'catch'> {} +/** An options object to configure transactions. */ +export declare interface TransactionOptions { + /** + * By default, events are raised each time the transaction update function + * runs. So if it is run multiple times, you may see intermediate states. You + * can set this to false to suppress these intermediate states and instead + * wait until the transaction has completed before events are raised. + */ + readonly applyLocally?: boolean; +} +/** + * A type for the resolve value of {@link runTransaction}. + */ +export declare class TransactionResult { + /** Whether the transaction was successfully committed. */ + readonly committed: boolean; + /** The resulting data snapshot. */ + readonly snapshot: DataSnapshot; + private constructor(); + /** Returns a JSON-serializable representation of this object. */ + toJSON(): object; +} +/** A callback that can invoked to remove a listener. */ +export declare type Unsubscribe = () => void; +/** + * Writes multiple values to the Database at once. + * + * The `values` argument contains multiple property-value pairs that will be + * written to the Database together. Each child property can either be a simple + * property (for example, "name") or a relative path (for example, + * "name/first") from the current location to the data to update. + * + * As opposed to the `set()` method, `update()` can be use to selectively update + * only the referenced properties at the current location (instead of replacing + * all the child properties at the current location). + * + * The effect of the write will be visible immediately, and the corresponding + * events ('value', 'child_added', etc.) will be triggered. Synchronization of + * the data to the Firebase servers will also be started, and the returned + * Promise will resolve when complete. If provided, the `onComplete` callback + * will be called asynchronously after synchronization has finished. + * + * A single `update()` will generate a single "value" event at the location + * where the `update()` was performed, regardless of how many children were + * modified. + * + * Note that modifying data with `update()` will cancel any pending + * transactions at that location, so extreme care should be taken if mixing + * `update()` and `transaction()` to modify the same data. + * + * Passing `null` to `update()` will remove the data at this location. + * + * See + * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}. + * + * @param ref - The location to write to. + * @param values - Object containing multiple values. + * @returns Resolves when update on server is complete. + */ +export declare function update( + ref: DatabaseReference, + values: object +): Promise; +export {}; diff --git a/repo-scripts/prune-dts/new-tests/firestore.input.d.ts b/repo-scripts/prune-dts/new-tests/firestore.input.d.ts new file mode 100644 index 00000000000..a69b8be42de --- /dev/null +++ b/repo-scripts/prune-dts/new-tests/firestore.input.d.ts @@ -0,0 +1,8410 @@ +/** + * Cloud Firestore + * + * @packageDocumentation + */ + +import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseError } from '@firebase/util'; +import { LogLevelString as LogLevel } from '@firebase/logger'; +import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; + +/* Excluded from this release type: AbstractUserDataWriter */ + +/** + * Describes a map whose keys are active target ids. We do not care about the type of the + * values. + */ +declare type ActiveTargets = SortedMap; + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ +export declare function addDoc( + reference: CollectionReference, + data: WithFieldValue +): Promise>; + +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys< + Prefix extends string, + T extends Record +> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; + +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + readonly _internalFieldPath?: _FieldPath | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = 'AggregateField'; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /* Excluded from this release type: __constructor */ +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual( + left: AggregateField, + right: AggregateField +): boolean; + +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = + | ReturnType + | ReturnType + | ReturnType; + +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot< + AggregateSpecType extends AggregateSpec, + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = 'AggregateQuerySnapshot'; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor( + query: Query, + _userDataWriter: AbstractUserDataWriter, + _data: ApiClientObjectMap + ); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual< + AggregateSpecType extends AggregateSpec, + AppModelType, + DbModelType extends DocumentData +>( + left: AggregateQuerySnapshot, + right: AggregateQuerySnapshot +): boolean; + +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} + +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; + +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and( + ...queryConstraints: QueryFilterConstraint[] +): QueryCompositeFilterConstraint; + +declare interface ApiClientObjectMap { + [k: string]: T; +} + +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply( + query: Query + ): Query; +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; + +declare interface AsyncQueue { + readonly isShuttingDown: boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + /** + * Regardless if the queue has initialized shutdown, adds a new operation to the + * queue without waiting for it to complete (i.e. we ignore the Promise result). + */ + enqueueAndForgetEvenWhileRestricted( + op: () => Promise + ): void; + /** + * Initialize the shutdown of this queue. Once this method is called, the + * only possible way to request running an operation is through + * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. + */ + enterRestrictedMode(purgeExistingTasks?: boolean): void; + /** + * Adds a new operation to the queue. Returns a promise that will be resolved + * when the promise returned by the new operation is (with its value). + */ + enqueue(op: () => Promise): Promise; + /** + * Enqueue a retryable operation. + * + * A retryable operation is rescheduled with backoff if it fails with a + * IndexedDbTransactionError (the error type used by SimpleDb). All + * retryable operations are executed in order and only run if all prior + * operations were retried successfully. + */ + enqueueRetryable(op: () => Promise): void; + /** + * Schedules an operation to be queued on the AsyncQueue once the specified + * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel + * or fast-forward the operation prior to its running. + */ + enqueueAfterDelay( + timerId: TimerId, + delayMs: number, + op: () => Promise + ): DelayedOperation; + /** + * Verifies there's an operation currently in-progress on the AsyncQueue. + * Unfortunately we can't verify that the running code is in the promise chain + * of that operation, so this isn't a foolproof check, but it should be enough + * to catch some bugs. + */ + verifyOperationInProgress(): void; +} + +/* Excluded from this release type: AuthTokenFactory */ + +/* Excluded from this release type: _AutoId */ + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average( + field: string | FieldPath +): AggregateField; + +/** + * Path represents an ordered sequence of string segments. + */ +declare abstract class BasePath> { + private segments; + private offset; + private len; + constructor(segments: string[], offset?: number, length?: number); + /** + * Abstract constructor method to construct an instance of B with the given + * parameters. + */ + protected abstract construct( + segments: string[], + offset?: number, + length?: number + ): B; + /** + * Returns a String representation. + * + * Implementing classes are required to provide deterministic implementations as + * the String representation is used to obtain canonical Query IDs. + */ + abstract toString(): string; + get length(): number; + isEqual(other: B): boolean; + child(nameOrPath: string | B): B; + /** The index of one past the last segment of the path. */ + private limit; + popFirst(size?: number): B; + popLast(): B; + firstSegment(): string; + lastSegment(): string; + get(index: number): string; + isEmpty(): boolean; + isPrefixOf(other: this): boolean; + isImmediateParentOf(potentialChild: this): boolean; + forEach(fn: (segment: string) => void): void; + toArray(): string[]; + static comparator>( + p1: BasePath, + p2: BasePath + ): number; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * BatchID is a locally assigned ID for a batch of mutations that have been + * applied. + */ +declare type BatchId = number; + +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +declare class Bound { + readonly position: Value[]; + readonly inclusive: boolean; + constructor(position: Value[], inclusive: boolean); +} + +/** + * Provides interfaces to save and read Firestore bundles. + */ +declare interface BundleCache { + /** + * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined + * if no bundle metadata is found under the given id. + */ + getBundleMetadata( + transaction: PersistenceTransaction, + bundleId: string + ): PersistencePromise; + /** + * Saves a `BundleMetadata` from a bundle into local storage, using its id as + * the persistent key. + */ + saveBundleMetadata( + transaction: PersistenceTransaction, + metadata: BundleMetadata_2 + ): PersistencePromise; + /** + * Gets a saved `NamedQuery` for the given query name. Returns undefined if + * no queries are found under the given name. + */ + getNamedQuery( + transaction: PersistenceTransaction, + queryName: string + ): PersistencePromise; + /** + * Saves a `NamedQuery` from a bundle, using its name as the persistent key. + */ + saveNamedQuery( + transaction: PersistenceTransaction, + query: NamedQuery_2 + ): PersistencePromise; +} + +/** Properties of a BundledQuery. */ +declare interface BundledQuery { + /** BundledQuery parent */ + parent?: string | null; + /** BundledQuery structuredQuery */ + structuredQuery?: StructuredQuery | null; + /** BundledQuery limitType */ + limitType?: LimitType_2 | null; +} + +/** + * Represents a Firestore bundle saved by the SDK in its local storage. + */ +declare interface BundleMetadata { + /** + * Id of the bundle. It is used together with `createTime` to determine if a + * bundle has been loaded by the SDK. + */ + readonly id: string; + /** Schema version of the bundle. */ + readonly version: number; + /** + * Set to the snapshot version of the bundle if created by the Server SDKs. + * Otherwise set to SnapshotVersion.MIN. + */ + readonly createTime: SnapshotVersion; +} + +/** Properties of a BundleMetadata. */ +declare interface BundleMetadata_2 { + /** BundleMetadata id */ + id?: string | null; + /** BundleMetadata createTime */ + createTime?: Timestamp_2 | null; + /** BundleMetadata version */ + version?: number | null; + /** BundleMetadata totalDocuments */ + totalDocuments?: number | null; + /** BundleMetadata totalBytes */ + totalBytes?: number | null; +} + +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + _byteString: _ByteString; + /** @hideconstructor */ + constructor(byteString: _ByteString); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; +} + +/* Excluded from this release type: _ByteString */ + +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ +export declare const CACHE_SIZE_UNLIMITED = -1; + +/* Excluded from this release type: _cast */ + +declare const enum ChangeType { + Added = 0, + Removed = 1, + Modified = 2, + Metadata = 3 +} + +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record< + string, + unknown +> + ? AddPrefixToKeys> + : never; + +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ +export declare function clearIndexedDbPersistence( + firestore: Firestore +): Promise; + +/** + * A randomly-generated key assigned to each Firestore instance at startup. + */ +declare type ClientId = string; + +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection( + firestore: Firestore_2, + path: string, + ...pathSegments: string[] +): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection< + AppModelType, + DbModelType extends DocumentData +>( + reference: CollectionReference, + path: string, + ...pathSegments: string[] +): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + path: string, + ...pathSegments: string[] +): CollectionReference; + +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup( + firestore: Firestore_2, + collectionId: string +): Query; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> extends Query { + readonly _path: _ResourcePath; + /** The type of this Firestore reference. */ + readonly type = 'collection'; + /** @hideconstructor */ + constructor( + firestore: Firestore_2, + converter: FirestoreDataConverter_2 | null, + _path: _ResourcePath + ); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData + >( + converter: FirestoreDataConverter_2 + ): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter( + converter: null + ): CollectionReference; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type Comparator = (key1: K, key2: K) => number; + +declare interface ComponentConfiguration { + asyncQueue: AsyncQueue; + databaseInfo: DatabaseInfo; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; + clientId: ClientId; + initialUser: User; + maxConcurrentLimboResolutions: number; +} + +declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; + +declare const enum CompositeOperator { + OR = 'or', + AND = 'and' +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator( + firestore: Firestore_2, + host: string, + port: number, + options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + } +): void; + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; + +/** + * A Listener for credential change events. The listener should fetch a new + * token and may need to invalidate other state if the current user has also + * changed. + */ +declare type CredentialChangeListener = (credential: T) => Promise; + +/** + * Provides methods for getting the uid and token for the current user and + * listening for changes. + */ +declare interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start( + asyncQueue: AsyncQueue, + changeListener: CredentialChangeListener + ): void; + /** Requests a token for the current user. */ + getToken(): Promise; + /** + * Marks the last retrieved token as invalid, making the next GetToken request + * force-refresh the token. + */ + invalidateToken(): void; + shutdown(): void; +} + +/** Settings for private credentials */ +declare type CredentialsSettings = + | FirstPartyCredentialsSettings + | ProviderCredentialsSettings; + +/* Excluded from this release type: _DatabaseId */ + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare class DatabaseInfo { + readonly databaseId: _DatabaseId; + readonly appId: string; + readonly persistenceKey: string; + readonly host: string; + readonly ssl: boolean; + readonly forceLongPolling: boolean; + readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor( + databaseId: _DatabaseId, + appId: string, + persistenceKey: string, + host: string, + ssl: boolean, + forceLongPolling: boolean, + autoDetectLongPolling: boolean, + longPollingOptions: ExperimentalLongPollingOptions, + useFetchStreams: boolean + ); +} + +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +declare abstract class Datastore { + abstract terminate(): void; + abstract serializer: JsonProtoSerializer; +} + +/* Excluded from this release type: _debugAssert */ + +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +declare class DelayedOperation implements PromiseLike { + private readonly asyncQueue; + readonly timerId: TimerId; + readonly targetTimeMs: number; + private readonly op; + private readonly removalCallback; + private timerHandle; + private readonly deferred; + private constructor(); + get promise(): Promise; + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule( + asyncQueue: AsyncQueue, + timerId: TimerId, + delayMs: number, + op: () => Promise, + removalCallback: (op: DelayedOperation) => void + ): DelayedOperation; + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + private start; + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay(): void; + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason?: string): void; + then: ( + onfulfilled?: + | ((value: T) => TResult1 | PromiseLike) + | null + | undefined, + onrejected?: + | ((reason: any) => TResult2 | PromiseLike) + | null + | undefined + ) => Promise; + private handleDelayElapsed; + private clearTimeout; +} + +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +export declare function deleteAllPersistentCacheIndexes( + indexManager: PersistentCacheIndexManager +): void; + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ +export declare function deleteDoc< + AppModelType, + DbModelType extends DocumentData +>(reference: DocumentReference): Promise; + +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; + +/** + * The direction of sorting in an order by. + */ +declare const enum Direction { + ASCENDING = 'asc', + DESCENDING = 'desc' +} + +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ +export declare function disableNetwork(firestore: Firestore): Promise; + +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +export declare function disablePersistentCacheIndexAutoCreation( + indexManager: PersistentCacheIndexManager +): void; + +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc( + firestore: Firestore_2, + path: string, + ...pathSegments: string[] +): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc( + reference: CollectionReference, + path?: string, + ...pathSegments: string[] +): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc( + reference: DocumentReference, + path: string, + ...pathSegments: string[] +): DocumentReference; + +/** + * Represents a document in Firestore with a key, version, data and whether the + * data has local mutations applied to it. + */ +declare interface Document_2 { + /** The key for this document */ + readonly key: _DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ + readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ + readonly hasCommittedMutations: boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; + toString(): string; +} + +/** + * A `DocumentChange` represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + */ +export declare 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; +} + +/** + * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. + */ +export declare type DocumentChangeType = 'added' | 'removed' | 'modified'; + +declare type DocumentComparator = ( + doc1: Document_2, + doc2: Document_2 +) => number; + +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export declare interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; + +/* Excluded from this release type: _DocumentKey */ + +declare type DocumentKeyMap = ObjectMap<_DocumentKey, T>; + +declare type DocumentKeySet = SortedSet<_DocumentKey>; + +declare type DocumentMap = SortedMap<_DocumentKey, Document_2>; + +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +declare interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay( + transaction: PersistenceTransaction, + key: _DocumentKey + ): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays( + transaction: PersistenceTransaction, + keys: _DocumentKey[] + ): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays( + transaction: PersistenceTransaction, + largestBatchId: number, + overlays: MutationMap + ): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId( + transaction: PersistenceTransaction, + documentKeys: DocumentKeySet, + batchId: number + ): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection( + transaction: PersistenceTransaction, + collection: _ResourcePath, + sinceBatchId: number + ): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup( + transaction: PersistenceTransaction, + collectionGroup: string, + sinceBatchId: number, + count: number + ): PersistencePromise; +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter_2< + AppModelType, + DbModelType + > | null; + readonly _key: _DocumentKey; + /** The type of this Firestore reference. */ + readonly type = 'document'; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore_2; + /** @hideconstructor */ + constructor( + firestore: Firestore_2, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter_2 | null, + _key: _DocumentKey + ); + get _path(): _ResourcePath; + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData + >( + converter: FirestoreDataConverter_2 + ): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; +} + +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +declare class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet: DocumentSet): DocumentSet; + private comparator; + private keyedMap; + private sortedSet; + /** The default ordering is by key if the comparator is omitted */ + constructor(comp?: DocumentComparator); + has(key: _DocumentKey): boolean; + get(key: _DocumentKey): Document_2 | null; + first(): Document_2 | null; + last(): Document_2 | null; + isEmpty(): boolean; + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key: _DocumentKey): number; + get size(): number; + /** Iterates documents in order defined by "comparator" */ + forEach(cb: (doc: Document_2) => void): void; + /** Inserts or updates a document with the same key */ + add(doc: Document_2): DocumentSet; + /** Deletes a document with a given key */ + delete(key: _DocumentKey): DocumentSet; + isEqual(other: DocumentSet | null | undefined): boolean; + toString(): string; + private copy; +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> extends DocumentSnapshot_2 { + readonly _firestore: Firestore; + private readonly _firestoreImpl; + /** + * Metadata about the `DocumentSnapshot`, including information about its + * source and local modifications. + */ + readonly metadata: SnapshotMetadata; + /** @hideconstructor protected */ + constructor( + _firestore: Firestore, + userDataWriter: AbstractUserDataWriter, + key: _DocumentKey, + document: Document_2 | null, + metadata: SnapshotMetadata, + converter: UntypedFirestoreDataConverter | null + ); + /** + * Returns whether or not the data exists. True if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ + data(options?: SnapshotOptions): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +declare class DocumentSnapshot_2< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + _firestore: Firestore_2; + _userDataWriter: AbstractUserDataWriter; + _key: _DocumentKey; + _document: Document_2 | null; + _converter: UntypedFirestoreDataConverter | null; + /** @hideconstructor protected */ + constructor( + _firestore: Firestore_2, + _userDataWriter: AbstractUserDataWriter, + _key: _DocumentKey, + _document: Document_2 | null, + _converter: UntypedFirestoreDataConverter | null + ); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot_2; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} + +declare type DocumentVersionMap = SortedMap<_DocumentKey, SnapshotVersion>; + +declare interface DocumentViewChange { + type: ChangeType; + doc: Document_2; +} + +/* Excluded from this release type: _EmptyAppCheckTokenProvider */ + +/* Excluded from this release type: _EmptyAuthCredentialsProvider */ +export { EmulatorMockTokenOptions }; + +/** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableIndexedDbPersistence( + firestore: Firestore, + persistenceSettings?: PersistenceSettings +): Promise; + +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableMultiTabIndexedDbPersistence( + firestore: Firestore +): Promise; + +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ +export declare function enableNetwork(firestore: Firestore): Promise; + +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +export declare function enablePersistentCacheIndexAutoCreation( + indexManager: PersistentCacheIndexManager +): void; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt( + snapshot: DocumentSnapshot_2 +): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore< + AppModelType, + DbModelType extends DocumentData +>( + snapshot: DocumentSnapshot_2 +): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore( + ...fieldValues: unknown[] +): QueryEndAtConstraint; + +/* Excluded from this release type: ensureFirestoreConfigured */ + +declare interface Entry { + key: K; + value: V; +} + +/** + * EventManager is responsible for mapping queries to query event emitters. + * It handles "fan-out". -- Identical queries will re-use the same watch on the + * backend. + * + * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be + * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This + * allows users to tree-shake the Watch logic. + */ +declare interface EventManager { + onListen?: ( + query: Query_2, + enableRemoteListen: boolean + ) => Promise; + onUnlisten?: (query: Query_2, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query_2) => Promise; + onLastRemoteStoreUnlisten?: (query: Query_2) => Promise; + terminate(): void; +} + +/* Excluded from this release type: executeWrite */ + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +export declare interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} + +declare class FieldFilter extends Filter { + readonly field: _FieldPath; + readonly op: Operator; + readonly value: Value; + protected constructor(field: _FieldPath, op: Operator, value: Value); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: _FieldPath, op: Operator, value: Value): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document_2): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} + +declare type FieldFilterOp = + | 'OPERATOR_UNSPECIFIED' + | 'LESS_THAN' + | 'LESS_THAN_OR_EQUAL' + | 'GREATER_THAN' + | 'GREATER_THAN_OR_EQUAL' + | 'EQUAL' + | 'NOT_EQUAL' + | 'ARRAY_CONTAINS' + | 'IN' + | 'ARRAY_CONTAINS_ANY' + | 'NOT_IN'; + +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState + ); +} + +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +declare class FieldMask { + readonly fields: _FieldPath[]; + constructor(fields: _FieldPath[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: _FieldPath[]): FieldMask; + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath: _FieldPath): boolean; + isEqual(other: FieldMask): boolean; +} + +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** Internal representation of a Firestore field path. */ + readonly _internalPath: _FieldPath; + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} + +/* Excluded from this release type: _FieldPath */ + +/** A field path and the TransformOperation to perform upon it. */ +declare class FieldTransform { + readonly field: _FieldPath; + readonly transform: TransformOperation; + constructor(field: _FieldPath, transform: TransformOperation); +} + +declare type FieldTransformSetToServerValue = + | 'SERVER_VALUE_UNSPECIFIED' + | 'REQUEST_TIME'; + +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + _methodName: string; + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; + abstract _toFieldTransform(context: ParseContext): FieldTransform | null; +} + +declare abstract class Filter { + abstract matches(doc: Document_2): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; +} + +/* Excluded from this release type: _FirebaseService */ + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore extends Firestore_2 { + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + _queue: AsyncQueue; + readonly _persistenceKey: string; + _firestoreClient: FirestoreClient | undefined; + _componentsProvider?: { + _offline: OfflineComponentProviderFactory; + _online: OnlineComponentProviderFactory; + }; + /** @hideconstructor */ + constructor( + authCredentialsProvider: CredentialsProvider, + appCheckCredentialsProvider: CredentialsProvider, + databaseId: _DatabaseId, + app?: FirebaseApp + ); + protected _terminate(): Promise; +} + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +declare class Firestore_2 implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: _DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + readonly _persistenceKey: string; + private _settings; + private _settingsFrozen; + private _terminateTask; + /** @hideconstructor */ + constructor( + _authCredentials: CredentialsProvider, + _appCheckCredentials: CredentialsProvider, + _databaseId: _DatabaseId, + _app?: FirebaseApp | undefined + ); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + get _initialized(): boolean; + get _terminated(): boolean; + _setSettings(settings: PrivateSettings): void; + _getSettings(): FirestoreSettingsImpl; + _freezeSettings(): FirestoreSettingsImpl; + _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + protected _terminate(): Promise; +} + +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +declare class FirestoreClient { + private authCredentials; + private appCheckCredentials; + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue; + private databaseInfo; + private user; + private readonly clientId; + private authCredentialListener; + private appCheckCredentialListener; + _uninitializedComponentsProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }; + _offlineComponents?: OfflineComponentProvider; + _onlineComponents?: OnlineComponentProvider; + constructor( + authCredentials: CredentialsProvider, + appCheckCredentials: CredentialsProvider, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue, + databaseInfo: DatabaseInfo, + componentProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + } + ); + get configuration(): ComponentConfiguration; + setCredentialChangeListener(listener: (user: User) => Promise): void; + setAppCheckTokenChangeListener( + listener: (appCheckToken: string, user: User) => Promise + ): void; + terminate(): Promise; +} + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export declare interface FirestoreDataConverter< + AppModelType, + DbModelType extends DocumentData = DocumentData +> extends FirestoreDataConverter_2 { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. To use `set()` + * with `merge` and `mergeFields`, `toFirestore()` must be defined with + * `PartialWithFieldValue`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore( + modelObject: WithFieldValue + ): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and + * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore( + modelObject: PartialWithFieldValue, + options: SetOptions + ): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data(options)`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. + * @param options - The `SnapshotOptions` from the initial call to `data()`. + */ + fromFirestore( + snapshot: QueryDocumentSnapshot, + options?: SnapshotOptions + ): AppModelType; +} + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +declare interface FirestoreDataConverter_2< + 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`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore( + modelObject: WithFieldValue + ): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore( + modelObject: PartialWithFieldValue, + options: SetOptions + ): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore( + snapshot: QueryDocumentSnapshot_2 + ): AppModelType; +} + +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode, + /** + * A custom error description. + */ + message: string + ); +} + +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export declare type FirestoreErrorCode = + | 'cancelled' + | 'unknown' + | 'invalid-argument' + | 'deadline-exceeded' + | 'not-found' + | 'already-exists' + | 'permission-denied' + | 'resource-exhausted' + | 'failed-precondition' + | 'aborted' + | 'out-of-range' + | 'unimplemented' + | 'internal' + | 'unavailable' + | 'data-loss' + | 'unauthenticated'; + +/** + * Union type from all supported SDK cache layer. + */ +export declare type FirestoreLocalCache = + | MemoryLocalCache + | PersistentLocalCache; + +/** + * An interface implemented by FirebaseFirestore that provides compatibility + * with the usage in this file. + * + * This interface mainly exists to remove a cyclic dependency. + */ +declare interface FirestoreService extends _FirebaseService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + _persistenceKey: string; + _databaseId: _DatabaseId; + _terminated: boolean; + _freezeSettings(): FirestoreSettingsImpl; +} + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface FirestoreSettings extends FirestoreSettings_2 { + /** + * NOTE: This field will be deprecated in a future major release. Use `cache` field + * instead to specify cache size, and other cache configurations. + * + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The size is not a guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` + * and `PersistentLocalCache`, each with different configuration options. + * + * When unspecified, `MemoryLocalCache` will be used by default. + * + * NOTE: setting this field and `cacheSizeBytes` at the same time will throw + * exception during SDK initialization. Instead, using the configuration in + * the `FirestoreLocalCache` object to specify the cache size. + */ + localCache?: FirestoreLocalCache; + /** + * Forces the SDK’s underlying network transport (WebChannel) to use + * long-polling. Each response from the backend will be closed immediately + * after the backend sends data (by default responses are kept open in + * case the backend has more data to send). This avoids incompatibility + * issues with certain proxies, antivirus software, etc. that incorrectly + * buffer traffic indefinitely. Use of this option will cause some + * performance degradation though. + * + * This setting cannot be used with `experimentalAutoDetectLongPolling` and + * may be removed in a future release. If you find yourself using it to + * work around a specific network reliability issue, please tell us about + * it in https://github.com/firebase/firebase-js-sdk/issues/1674. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalForceLongPolling?: boolean; + /** + * Configures the SDK's underlying transport (WebChannel) to automatically + * detect if long-polling should be used. This is very similar to + * `experimentalForceLongPolling`, but only uses long-polling if required. + * + * After having had a default value of `false` since its inception in 2019, + * the default value of this setting was changed in May 2023 to `true` in + * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long + * polling is now enabled by default. To disable it, set this setting to + * `false`, and please open a GitHub issue to share the problems that + * motivated you disabling long-polling auto-detection. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalAutoDetectLongPolling?: boolean; + /** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * These options are only used if `experimentalForceLongPolling` is true or if + * `experimentalAutoDetectLongPolling` is true and the auto-detection + * determined that long-polling was needed. Otherwise, these options have no + * effect. + */ + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; +} + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +declare interface FirestoreSettings_2 { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} + +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +declare class FirestoreSettingsImpl { + /** The hostname to connect to. */ + readonly host: string; + /** Whether to use SSL when connecting. */ + readonly ssl: boolean; + readonly cacheSizeBytes: number; + readonly experimentalForceLongPolling: boolean; + readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; + readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; + credentials?: any; + constructor(settings: PrivateSettings); + isEqual(other: FirestoreSettingsImpl): boolean; +} + +declare namespace firestoreV1ApiClientInterfaces { + interface ArrayValue { + values?: Value[]; + } + interface BatchGetDocumentsRequest { + database?: string; + documents?: string[]; + mask?: DocumentMask; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface BatchGetDocumentsResponse { + found?: Document; + missing?: string; + transaction?: string; + readTime?: string; + } + interface BeginTransactionRequest { + options?: TransactionOptions; + } + interface BeginTransactionResponse { + transaction?: string; + } + interface CollectionSelector { + collectionId?: string; + allDescendants?: boolean; + } + interface CommitRequest { + database?: string; + writes?: Write[]; + transaction?: string; + } + interface CommitResponse { + writeResults?: WriteResult[]; + commitTime?: string; + } + interface CompositeFilter { + op?: CompositeFilterOp; + filters?: Filter[]; + } + interface Cursor { + values?: Value[]; + before?: boolean; + } + interface Document { + name?: string; + fields?: ApiClientObjectMap; + createTime?: Timestamp_2; + updateTime?: Timestamp_2; + } + interface DocumentChange { + document?: Document; + targetIds?: number[]; + removedTargetIds?: number[]; + } + interface DocumentDelete { + document?: string; + removedTargetIds?: number[]; + readTime?: Timestamp_2; + } + interface DocumentMask { + fieldPaths?: string[]; + } + interface DocumentRemove { + document?: string; + removedTargetIds?: number[]; + readTime?: string; + } + interface DocumentTransform { + document?: string; + fieldTransforms?: FieldTransform[]; + } + interface DocumentsTarget { + documents?: string[]; + } + interface Empty {} + interface ExistenceFilter { + targetId?: number; + count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; + } + interface FieldFilter { + field?: FieldReference; + op?: FieldFilterOp; + value?: Value; + } + interface FieldReference { + fieldPath?: string; + } + interface FieldTransform { + fieldPath?: string; + setToServerValue?: FieldTransformSetToServerValue; + appendMissingElements?: ArrayValue; + removeAllFromArray?: ArrayValue; + increment?: Value; + } + interface Filter { + compositeFilter?: CompositeFilter; + fieldFilter?: FieldFilter; + unaryFilter?: UnaryFilter; + } + interface Index { + name?: string; + collectionId?: string; + fields?: IndexField[]; + state?: IndexState_2; + } + interface IndexField { + fieldPath?: string; + mode?: IndexFieldMode; + } + interface LatLng { + latitude?: number; + longitude?: number; + } + interface ListCollectionIdsRequest { + pageSize?: number; + pageToken?: string; + } + interface ListCollectionIdsResponse { + collectionIds?: string[]; + nextPageToken?: string; + } + interface ListDocumentsResponse { + documents?: Document[]; + nextPageToken?: string; + } + interface ListIndexesResponse { + indexes?: Index[]; + nextPageToken?: string; + } + interface ListenRequest { + addTarget?: Target; + removeTarget?: number; + labels?: ApiClientObjectMap; + } + interface ListenResponse { + targetChange?: TargetChange; + documentChange?: DocumentChange; + documentDelete?: DocumentDelete; + documentRemove?: DocumentRemove; + filter?: ExistenceFilter; + } + interface MapValue { + fields?: ApiClientObjectMap; + } + interface Operation { + name?: string; + metadata?: ApiClientObjectMap; + done?: boolean; + error?: Status; + response?: ApiClientObjectMap; + } + interface Order { + field?: FieldReference; + direction?: OrderDirection; + } + interface Precondition { + exists?: boolean; + updateTime?: Timestamp_2; + } + interface Projection { + fields?: FieldReference[]; + } + interface QueryTarget { + parent?: string; + structuredQuery?: StructuredQuery; + } + interface ReadOnly { + readTime?: string; + } + interface ReadWrite { + retryTransaction?: string; + } + interface RollbackRequest { + transaction?: string; + } + interface RunQueryRequest { + parent?: string; + structuredQuery?: StructuredQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunQueryResponse { + transaction?: string; + document?: Document; + readTime?: string; + skippedResults?: number; + } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } + interface Status { + code?: number; + message?: string; + details?: Array>; + } + interface StructuredQuery { + select?: Projection; + from?: CollectionSelector[]; + where?: Filter; + orderBy?: Order[]; + startAt?: Cursor; + endAt?: Cursor; + offset?: number; + limit?: + | number + | { + value: number; + }; + } + interface Target { + query?: QueryTarget; + documents?: DocumentsTarget; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + targetId?: number; + once?: boolean; + expectedCount?: + | number + | { + value: number; + }; + } + interface TargetChange { + targetChangeType?: TargetChangeTargetChangeType; + targetIds?: number[]; + cause?: Status; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + } + interface TransactionOptions { + readOnly?: ReadOnly; + readWrite?: ReadWrite; + } + interface UnaryFilter { + op?: UnaryFilterOp; + field?: FieldReference; + } + interface Value { + nullValue?: ValueNullValue; + booleanValue?: boolean; + integerValue?: string | number; + doubleValue?: string | number; + timestampValue?: Timestamp_2; + stringValue?: string; + bytesValue?: string | Uint8Array; + referenceValue?: string; + geoPointValue?: LatLng; + arrayValue?: ArrayValue; + mapValue?: MapValue; + } + interface Write { + update?: Document; + delete?: string; + verify?: string; + transform?: DocumentTransform; + updateMask?: DocumentMask; + updateTransforms?: FieldTransform[]; + currentDocument?: Precondition; + } + interface WriteRequest { + streamId?: string; + writes?: Write[]; + streamToken?: string | Uint8Array; + labels?: ApiClientObjectMap; + } + interface WriteResponse { + streamId?: string; + streamToken?: string | Uint8Array; + writeResults?: WriteResult[]; + commitTime?: Timestamp_2; + } + interface WriteResult { + updateTime?: Timestamp_2; + transformResults?: Value[]; + } +} + +/* Excluded from this release type: FirstPartyCredentialsSettings */ + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type FulfilledHandler = + | ((result: T) => R | PersistencePromise) + | null; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + private _lat; + private _long; + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** Returns a JSON-serializable representation of this GeoPoint. */ + toJSON(): { + latitude: number; + longitude: number; + }; + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other: GeoPoint): number; +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregateFromServer< + AggregateSpecType extends AggregateSpec, + AppModelType, + DbModelType extends DocumentData +>( + query: Query, + aggregateSpec: AggregateSpecType +): Promise< + AggregateQuerySnapshot +>; + +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCountFromServer< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise< + AggregateQuerySnapshot< + { + count: AggregateField; + }, + AppModelType, + DbModelType + > +>; + +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDoc( + reference: DocumentReference +): Promise>; + +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromCache< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference +): Promise>; + +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromServer< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference +): Promise>; + +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocs( + query: Query +): Promise>; + +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromCache< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise>; + +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromServer< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise>; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The default {@link Firestore} instance of the default app. + */ +export declare function getFirestore(): Firestore; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The default {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; + +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the default app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; + +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore( + app: FirebaseApp, + databaseId: string +): Firestore; + +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +export declare function getPersistentCacheIndexManager( + firestore: Firestore +): PersistentCacheIndexManager | null; + +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. + */ +declare interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken( + transaction: PersistenceTransaction + ): PersistencePromise<_ByteString>; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken( + transaction: PersistenceTransaction, + sessionToken: _ByteString + ): PersistencePromise; +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; + +/** + * The SDK definition of a Firestore index. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface Index { + /** The ID of the collection to index. */ + readonly collectionGroup: string; + /** A list of fields to index. */ + readonly fields?: IndexField[]; + [key: string]: unknown; +} + +/** + * A list of Firestore indexes to speed up local query execution. + * + * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} + * for a description of the format of the index definition. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexConfiguration { + /** A list of all Firestore indexes. */ + readonly indexes?: Index[]; + [key: string]: unknown; +} + +/** + * A single field element in an index configuration. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexField { + /** The field path to index. */ + readonly fieldPath: string; + /** + * What type of array index to create. Set to `CONTAINS` for `array-contains` + * and `array-contains-any` indexes. + * + * Only one of `arrayConfig` or `order` should be set; + */ + readonly arrayConfig?: 'CONTAINS'; + /** + * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for + * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. + * + * Only one of `arrayConfig` or `order` should be set. + */ + readonly order?: 'ASCENDING' | 'DESCENDING'; + [key: string]: unknown; +} + +declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** The type of the index, e.g. for which type of query it can be used. */ +declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} + +/** + * Represents a set of indexes that are used to execute queries efficiently. + * + * Currently the only index is a [collection id] => [parent path] index, used + * to execute Collection Group queries. + */ +declare interface IndexManager { + /** + * Creates an index entry mapping the collectionId (last segment of the path) + * to the parent path (either the containing document location or the empty + * path for root-level collections). Index entries can be retrieved via + * getCollectionParents(). + * + * NOTE: Currently we don't remove index entries. If this ends up being an + * issue we can devise some sort of GC strategy. + */ + addToCollectionParentIndex( + transaction: PersistenceTransaction, + collectionPath: _ResourcePath + ): PersistencePromise; + /** + * Retrieves all parent locations containing the given collectionId, as a + * list of paths (each path being either a document location or the empty + * path for a root-level collection). + */ + getCollectionParents( + transaction: PersistenceTransaction, + collectionId: string + ): PersistencePromise<_ResourcePath[]>; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex( + transaction: PersistenceTransaction, + index: FieldIndex + ): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex( + transaction: PersistenceTransaction, + index: FieldIndex + ): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes( + transaction: PersistenceTransaction + ): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes( + transaction: PersistenceTransaction, + target: Target + ): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes( + transaction: PersistenceTransaction, + collectionGroup: string + ): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes( + transaction: PersistenceTransaction + ): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType( + transaction: PersistenceTransaction, + target: Target + ): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget( + transaction: PersistenceTransaction, + target: Target + ): PersistencePromise<_DocumentKey[] | null>; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate( + transaction: PersistenceTransaction + ): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup( + transaction: PersistenceTransaction, + collectionGroup: string, + offset: IndexOffset + ): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries( + transaction: PersistenceTransaction, + documents: DocumentMap + ): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset( + transaction: PersistenceTransaction, + target: Target + ): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup( + transaction: PersistenceTransaction, + collectionGroup: string + ): PersistencePromise; +} + +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: _DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: _DocumentKey, + largestBatchId: number + ); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} + +/** An index component consisting of field path and index type. */ +declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: _FieldPath; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: _FieldPath, + /** The fields sorting order. */ + kind: IndexKind + ); +} + +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset + ); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} + +declare type IndexState_2 = + | 'STATE_UNSPECIFIED' + | 'CREATING' + | 'READY' + | 'ERROR'; + +/** Represents the index state as it relates to a particular target. */ +declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 +} + +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ +export declare function initializeFirestore( + app: FirebaseApp, + settings: FirestoreSettings, + databaseId?: string +): Firestore; + +/* Excluded from this release type: _internalAggregationQueryToProtoRunAggregationQueryRequest */ + +/* Excluded from this release type: _internalQueryToProtoQueryTarget */ + +/* Excluded from this release type: _isBase64Available */ + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +declare class JsonProtoSerializer implements Serializer { + readonly databaseId: _DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: _DatabaseId, useProto3Json: boolean); +} + +declare type Kind = 'memory' | 'persistent'; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; + +declare const enum LimitType { + First = 'F', + Last = 'L' +} + +/** LimitType enum. */ +declare type LimitType_2 = 'FIRST' | 'LAST'; + +declare type ListenSequenceNumber = number; + +/** + * Describe the source a query listens to. + * + * Set to `default` to listen to both cache and server changes. Set to `cache` + * to listen to changes in cache only. + */ +export declare type ListenSource = 'default' | 'cache'; + +declare class LLRBEmptyNode { + get key(): never; + get value(): never; + get color(): never; + get left(): never; + get right(): never; + size: number; + copy( + key: K | null, + value: V | null, + color: boolean | null, + left: LLRBNode | LLRBEmptyNode | null, + right: LLRBNode | LLRBEmptyNode | null + ): LLRBEmptyNode; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + remove(key: K, comparator: Comparator): LLRBEmptyNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => boolean): boolean; + reverseTraversal(action: (k: K, v: V) => boolean): boolean; + minKey(): K | null; + maxKey(): K | null; + isRed(): boolean; + checkMaxDepth(): boolean; + protected check(): 0; +} + +declare class LLRBNode { + key: K; + value: V; + readonly color: boolean; + readonly left: LLRBNode | LLRBEmptyNode; + readonly right: LLRBNode | LLRBEmptyNode; + readonly size: number; + static EMPTY: LLRBEmptyNode; + static RED: boolean; + static BLACK: boolean; + constructor( + key: K, + value: V, + color?: boolean, + left?: LLRBNode | LLRBEmptyNode, + right?: LLRBNode | LLRBEmptyNode + ); + copy( + key: K | null, + value: V | null, + color: boolean | null, + left: LLRBNode | LLRBEmptyNode | null, + right: LLRBNode | LLRBEmptyNode | null + ): LLRBNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => T): T; + reverseTraversal(action: (k: K, v: V) => T): T; + private min; + minKey(): K | null; + maxKey(): K | null; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + private removeMin; + remove( + key: K, + comparator: Comparator + ): LLRBNode | LLRBEmptyNode; + isRed(): boolean; + private fixUp; + private moveRedLeft; + private moveRedRight; + private rotateLeft; + private rotateRight; + private colorFlip; + checkMaxDepth(): boolean; + protected check(): number; +} + +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ +export declare function loadBundle( + firestore: Firestore, + bundleData: ReadableStream | ArrayBuffer | string +): LoadBundleTask; + +/** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ +export declare class LoadBundleTask + implements PromiseLike +{ + private _progressObserver; + private _taskCompletionResolver; + private _lastProgress; + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ + onProgress( + next?: (progress: LoadBundleTaskProgress) => unknown, + error?: (err: Error) => unknown, + complete?: () => void + ): void; + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ + catch( + onRejected: (a: Error) => R | PromiseLike + ): Promise; + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ + then( + onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike, + onRejected?: (a: Error) => R | PromiseLike + ): Promise; + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ + _completeWith(progress: LoadBundleTaskProgress): void; + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ + _failWith(error: FirestoreError): void; + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ + _updateProgress(progress: LoadBundleTaskProgress): void; +} + +/** + * Represents a progress update or a final state from loading bundles. + */ +export declare interface LoadBundleTaskProgress { + /** How many documents have been loaded. */ + documentsLoaded: number; + /** How many documents are in the bundle being loaded. */ + totalDocuments: number; + /** How many bytes have been loaded. */ + bytesLoaded: number; + /** How many bytes are in the bundle being loaded. */ + totalBytes: number; + /** Current task state. */ + taskState: TaskState; +} + +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor( + remoteDocumentCache: RemoteDocumentCache, + mutationQueue: MutationQueue, + documentOverlayCache: DocumentOverlayCache, + indexManager: IndexManager + ); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument( + transaction: PersistenceTransaction, + key: _DocumentKey + ): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments( + transaction: PersistenceTransaction, + keys: DocumentKeySet + ): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments( + transaction: PersistenceTransaction, + docs: MutableDocumentMap, + existenceStateChanged?: DocumentKeySet + ): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments( + transaction: PersistenceTransaction, + docs: MutableDocumentMap + ): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews( + transaction: PersistenceTransaction, + docs: MutableDocumentMap, + overlays: OverlayMap, + existenceStateChanged: DocumentKeySet + ): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys( + transaction: PersistenceTransaction, + documentKeys: DocumentKeySet + ): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery( + transaction: PersistenceTransaction, + query: Query_2, + offset: IndexOffset, + context?: QueryContext + ): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

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

    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +export declare function setLogLevel(logLevel: LogLevel): void; + +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export declare type SetOptions = + | { + readonly merge?: boolean; + } + | { + readonly mergeFields?: Array; + }; + +/** + * A `SharedClientState` keeps track of the global state of the mutations + * and query targets for all active clients with the same persistence key (i.e. + * project ID and FirebaseApp name). It relays local changes to other clients + * and updates its local state as new state is observed. + * + * `SharedClientState` is primarily used for synchronization in Multi-Tab + * environments. Each tab is responsible for registering its active query + * targets and mutations. `SharedClientState` will then notify the listener + * assigned to `.syncEngine` for updates to mutations and queries that + * originated in other clients. + * + * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be + * assigned before calling `start()`. + */ +declare interface SharedClientState { + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: + | ((sequenceNumber: ListenSequenceNumber) => void) + | null; + /** Registers the Mutation Batch ID of a newly pending mutation. */ + addPendingMutation(batchId: BatchId): void; + /** + * Records that a pending mutation has been acknowledged or rejected. + * Called by the primary client to notify secondary clients of mutation + * results as they come back from the backend. + */ + updateMutationState( + batchId: BatchId, + state: 'acknowledged' | 'rejected', + error?: FirestoreError + ): void; + /** + * Associates a new Query Target ID with the local Firestore client. Returns + * the new query state for the query (which can be 'current' if the query is + * already associated with another tab). + * + * If the target id is already associated with local client, the method simply + * returns its `QueryTargetState`. + */ + addLocalQueryTarget( + targetId: TargetId, + addToActiveTargetIds?: boolean + ): QueryTargetState; + /** Removes the Query Target ID association from the local client. */ + removeLocalQueryTarget(targetId: TargetId): void; + /** Checks whether the target is associated with the local client. */ + isLocalQueryTarget(targetId: TargetId): boolean; + /** + * Processes an update to a query target. + * + * Called by the primary client to notify secondary clients of document + * changes or state transitions that affect the provided query target. + */ + updateQueryState( + targetId: TargetId, + state: QueryTargetState, + error?: FirestoreError + ): void; + /** + * Removes the target's metadata entry. + * + * Called by the primary client when all clients stopped listening to a query + * target. + */ + clearQueryState(targetId: TargetId): void; + /** + * Gets the active Query Targets IDs for all active clients. + * + * The implementation for this may require O(n) runtime, where 'n' is the size + * of the result set. + */ + getAllActiveQueryTargets(): SortedSet; + /** + * Checks whether the provided target ID is currently being listened to by + * any of the active clients. + * + * The implementation may require O(n*log m) runtime, where 'n' is the number + * of clients and 'm' the number of targets. + */ + isActiveQueryTarget(targetId: TargetId): boolean; + /** + * Starts the SharedClientState, reads existing client data and registers + * listeners for updates to new and existing clients. + */ + start(): Promise; + /** Shuts down the `SharedClientState` and its listeners. */ + shutdown(): void; + /** + * Changes the active user and removes all existing user-specific data. The + * user change does not call back into SyncEngine (for example, no mutations + * will be marked as removed). + */ + handleUserChange( + user: User, + removedBatchIds: BatchId[], + addedBatchIds: BatchId[] + ): void; + /** Changes the shared online state of all clients. */ + setOnlineState(onlineState: OnlineState): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + /** + * Notifies other clients when remote documents have changed due to loading + * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. + */ + notifyBundleLoaded(collectionGroups: Set): void; +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual< + AppModelType, + DbModelType extends DocumentData +>( + left: + | DocumentSnapshot + | QuerySnapshot, + right: + | DocumentSnapshot + | QuerySnapshot +): boolean; + +/** + * An options object that can be passed to {@link (onSnapshot:1)} and {@link + * QuerySnapshot.docChanges} to control which types of changes to include in the + * result set. + */ +export declare interface SnapshotListenOptions { + /** + * Include a change even if only the metadata of the query or of a document + * changed. Default is false. + */ + readonly includeMetadataChanges?: boolean; + /** + * Set the source the query listens to. Default to "default", which + * listens to both cache and server. + */ + readonly source?: ListenSource; +} + +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ +export declare class SnapshotMetadata { + /** + * True if the snapshot contains the result of local writes (for example + * `set()` or `update()` calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * `SnapshotListenOptions`) you will receive another snapshot with + * `hasPendingWrites` equal to false once the writes have been committed to + * the backend. + */ + readonly hasPendingWrites: boolean; + /** + * True if the snapshot was created from cached data rather than guaranteed + * up-to-date server data. If your listener has opted into metadata updates + * (via `SnapshotListenOptions`) you will receive another snapshot with + * `fromCache` set to false once the client has received up-to-date data from + * the backend. + */ + readonly fromCache: boolean; + /** @hideconstructor */ + constructor(hasPendingWrites: boolean, fromCache: boolean); + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other: SnapshotMetadata): boolean; +} + +/** + * Options that configure how data is retrieved from a `DocumentSnapshot` (for + * example the desired behavior for server timestamps that have not yet been set + * to their final value). + */ +export declare interface SnapshotOptions { + /** + * If set, controls the return value for server timestamps that have not yet + * been set to their final value. + * + * By specifying 'estimate', pending server timestamps return an estimate + * based on the local clock. This estimate will differ from the final value + * and cause these values to change once the server result becomes available. + * + * By specifying 'previous', pending timestamps will be ignored and return + * their previous value instead. + * + * If omitted or set to 'none', `null` will be returned by default until the + * server value becomes available. + */ + readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; +} + +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +declare class SnapshotVersion { + private timestamp; + static fromTimestamp(value: Timestamp): SnapshotVersion; + static min(): SnapshotVersion; + static max(): SnapshotVersion; + private constructor(); + compareTo(other: SnapshotVersion): number; + isEqual(other: SnapshotVersion): boolean; + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds(): number; + toString(): string; + toTimestamp(): Timestamp; +} + +declare class SortedMap { + comparator: Comparator; + root: LLRBNode | LLRBEmptyNode; + constructor( + comparator: Comparator, + root?: LLRBNode | LLRBEmptyNode + ); + insert(key: K, value: V): SortedMap; + remove(key: K): SortedMap; + get(key: K): V | null; + indexOf(key: K): number; + isEmpty(): boolean; + get size(): number; + minKey(): K | null; + maxKey(): K | null; + inorderTraversal(action: (k: K, v: V) => T): T; + forEach(fn: (k: K, v: V) => void): void; + toString(): string; + reverseTraversal(action: (k: K, v: V) => T): T; + getIterator(): SortedMapIterator; + getIteratorFrom(key: K): SortedMapIterator; + getReverseIterator(): SortedMapIterator; + getReverseIteratorFrom(key: K): SortedMapIterator; +} + +declare class SortedMapIterator { + private isReverse; + private nodeStack; + constructor( + node: LLRBNode | LLRBEmptyNode, + startKey: K | null, + comparator: Comparator, + isReverse: boolean + ); + getNext(): Entry; + hasNext(): boolean; + peek(): Entry | null; +} + +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +declare class SortedSet { + private comparator; + private data; + constructor(comparator: (left: T, right: T) => number); + has(elem: T): boolean; + first(): T | null; + last(): T | null; + get size(): number; + indexOf(elem: T): number; + /** Iterates elements in order defined by "comparator" */ + forEach(cb: (elem: T) => void): void; + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range: [T, T], cb: (elem: T) => void): void; + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb: (elem: T) => boolean, start?: T): void; + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem: T): T | null; + getIterator(): SortedSetIterator; + getIteratorFrom(key: T): SortedSetIterator; + /** Inserts or updates an element */ + add(elem: T): SortedSet; + /** Deletes an element */ + delete(elem: T): SortedSet; + isEmpty(): boolean; + unionWith(other: SortedSet): SortedSet; + isEqual(other: SortedSet): boolean; + toArray(): T[]; + toString(): string; + private copy; +} + +declare class SortedSetIterator { + private iter; + constructor(iter: SortedMapIterator); + getNext(): T; + hasNext(): boolean; +} + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter< + AppModelType, + DbModelType extends DocumentData +>( + snapshot: DocumentSnapshot_2 +): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter( + ...fieldValues: unknown[] +): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt( + snapshot: DocumentSnapshot_2 +): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt( + ...fieldValues: unknown[] +): QueryStartAtConstraint; + +declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; + +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SyncEngine is the central controller in the client SDK architecture. It is + * the glue code between the EventManager, LocalStore, and RemoteStore. Some of + * SyncEngine's responsibilities include: + * 1. Coordinating client requests and remote events between the EventManager + * and the local and remote data stores. + * 2. Managing a View object for each query, providing the unified view between + * the local and remote data stores. + * 3. Notifying the RemoteStore when the LocalStore has new mutations in its + * queue that need sending to the backend. + * + * The SyncEngine’s methods should only ever be called by methods running in the + * global async queue. + * + * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() + * function. Instead, it directly depends on EventManager's tree-shakeable API + * (via `ensureWatchStream()`). + */ +declare interface SyncEngine { + isPrimaryClient: boolean; +} + +/** + * A Target represents the WatchTarget representation of a Query, which is used + * by the LocalStore and the RemoteStore to keep track of and to execute + * backend queries. While a Query can represent multiple Targets, each Targets + * maps to a single WatchTarget in RemoteStore and a single TargetData entry + * in persistence. + */ +declare interface Target { + readonly path: _ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * Represents cached targets received from the remote backend. + * + * The cache is keyed by `Target` and entries in the cache are `TargetData` + * instances. + */ +declare interface TargetCache { + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for targets + * resumed with a resume_token) should be suppressed (buffered) until the + * backend has caught up to this snapshot version again. This prevents our + * cache from ever going backwards in time. + * + * This is updated whenever our we get a TargetChange with a read_time and + * empty target_ids. + */ + getLastRemoteSnapshotVersion( + transaction: PersistenceTransaction + ): PersistencePromise; + /** + * @returns The highest sequence number observed, including any that might be + * persisted on-disk. + */ + getHighestSequenceNumber( + transaction: PersistenceTransaction + ): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget( + txn: PersistenceTransaction, + f: (q: TargetData) => void + ): PersistencePromise; + /** + * Set the highest listen sequence number and optionally updates the + * snapshot version of the last consistent snapshot received from the backend + * (see getLastRemoteSnapshotVersion() for more details). + * + * @param highestListenSequenceNumber - The new maximum listen sequence number. + * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. + */ + setTargetsMetadata( + transaction: PersistenceTransaction, + highestListenSequenceNumber: number, + lastRemoteSnapshotVersion?: SnapshotVersion + ): PersistencePromise; + /** + * Adds an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The key must not already + * exist in the cache. + * + * @param targetData - A TargetData instance to put in the cache. + */ + addTargetData( + transaction: PersistenceTransaction, + targetData: TargetData + ): PersistencePromise; + /** + * Updates an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The entry must already + * exist in the cache, and it will be replaced. + * @param targetData - The TargetData to be replaced into the cache. + */ + updateTargetData( + transaction: PersistenceTransaction, + targetData: TargetData + ): PersistencePromise; + /** + * Removes the cached entry for the given target data. It is an error to remove + * a target data that does not exist. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeTargetData( + transaction: PersistenceTransaction, + targetData: TargetData + ): PersistencePromise; + /** + * The number of targets currently in the cache. + */ + getTargetCount( + transaction: PersistenceTransaction + ): PersistencePromise; + /** + * Looks up a TargetData entry by target. + * + * @param target - The query target corresponding to the entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetData( + transaction: PersistenceTransaction, + target: Target + ): PersistencePromise; + /** + * Adds the given document keys to cached query results of the given target + * ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + addMatchingKeys( + transaction: PersistenceTransaction, + keys: DocumentKeySet, + targetId: TargetId + ): PersistencePromise; + /** + * Removes the given document keys from the cached query results of the + * given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeys( + transaction: PersistenceTransaction, + keys: DocumentKeySet, + targetId: TargetId + ): PersistencePromise; + /** + * Removes all the keys in the query results of the given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeysForTargetId( + transaction: PersistenceTransaction, + targetId: TargetId + ): PersistencePromise; + /** + * Returns the document keys that match the provided target ID. + */ + getMatchingKeysForTargetId( + transaction: PersistenceTransaction, + targetId: TargetId + ): PersistencePromise; + /** + * Returns a new target ID that is higher than any query in the cache. If + * there are no queries in the cache, returns the first valid target ID. + * Allocated target IDs are persisted and `allocateTargetId()` will never + * return the same ID twice. + */ + allocateTargetId( + transaction: PersistenceTransaction + ): PersistencePromise; + containsKey( + transaction: PersistenceTransaction, + key: _DocumentKey + ): PersistencePromise; +} + +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +declare class TargetChange { + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + readonly resumeToken: _ByteString; + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + readonly current: boolean; + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + readonly addedDocuments: DocumentKeySet; + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + readonly modifiedDocuments: DocumentKeySet; + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + readonly removedDocuments: DocumentKeySet; + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken: _ByteString, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current: boolean, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments: DocumentKeySet, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments: DocumentKeySet, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments: DocumentKeySet + ); + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange( + targetId: TargetId, + current: boolean, + resumeToken: _ByteString + ): TargetChange; +} + +declare type TargetChangeTargetChangeType = + | 'NO_CHANGE' + | 'ADD' + | 'REMOVE' + | 'CURRENT' + | 'RESET'; + +/** + * An immutable set of metadata that the local store tracks for each target. + */ +declare class TargetData { + /** The target being listened to. */ + readonly target: Target; + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + readonly targetId: TargetId; + /** The purpose of the target. */ + readonly purpose: TargetPurpose; + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + readonly sequenceNumber: ListenSequenceNumber; + /** The latest snapshot version seen for this target. */ + readonly snapshotVersion: SnapshotVersion; + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + readonly lastLimboFreeSnapshotVersion: SnapshotVersion; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + readonly resumeToken: _ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; + constructor( + /** The target being listened to. */ + target: Target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId: TargetId, + /** The purpose of the target. */ + purpose: TargetPurpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber: ListenSequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion?: SnapshotVersion, + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion?: SnapshotVersion, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: _ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null + ); + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber: number): TargetData; + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken( + resumeToken: _ByteString, + snapshotVersion: SnapshotVersion + ): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion( + lastLimboFreeSnapshotVersion: SnapshotVersion + ): TargetData; +} + +/** + * A locally-assigned ID used to refer to a target being watched via the + * Watch service. + */ +declare type TargetId = number; + +/** An enumeration of the different purposes we have for targets. */ +declare const enum TargetPurpose { + /** A regular, normal query target. */ + Listen = 'TargetPurposeListen', + /** + * The query target was used to refill a query after an existence filter + * mismatch. + */ + ExistenceFilterMismatch = 'TargetPurposeExistenceFilterMismatch', + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = 'TargetPurposeExistenceFilterMismatchBloom', + /** The query target was used to resolve a limbo document. */ + LimboResolution = 'TargetPurposeLimboResolution' +} + +/** + * Represents the state of bundle loading tasks. + * + * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will + * be no more updates after they are reported. + */ +export declare type TaskState = 'Error' | 'Running' | 'Success'; + +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; + +/* Excluded from this release type: _TestingHooks */ + +/* Excluded from this release type: _TestingHooksExistenceFilterMismatchCallback */ + +/* Excluded from this release type: _TestingHooksExistenceFilterMismatchInfo */ + +/** + * Wellknown "timer" IDs used when scheduling delayed operations on the + * AsyncQueue. These IDs can then be used from tests to check for the presence + * of operations or to run them early. + * + * The string values are used when encoding these timer IDs in JSON spec tests. + */ +declare const enum TimerId { + /** All can be used with runDelayedOperationsEarly() to run all timers. */ + All = 'all', + /** + * The following 5 timers are used in persistent_stream.ts for the listen and + * write streams. The "Idle" timer is used to close the stream due to + * inactivity. The "ConnectionBackoff" timer is used to restart a stream once + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. + */ + ListenStreamIdle = 'listen_stream_idle', + ListenStreamConnectionBackoff = 'listen_stream_connection_backoff', + WriteStreamIdle = 'write_stream_idle', + WriteStreamConnectionBackoff = 'write_stream_connection_backoff', + HealthCheckTimeout = 'health_check_timeout', + /** + * A timer used in online_state_tracker.ts to transition from + * OnlineState.Unknown to Offline after a set timeout, rather than waiting + * indefinitely for success or failure. + */ + OnlineStateTimeout = 'online_state_timeout', + /** + * A timer used to update the client metadata in IndexedDb, which is used + * to determine the primary leaseholder. + */ + ClientMetadataRefresh = 'client_metadata_refresh', + /** A timer used to periodically attempt LRU Garbage collection */ + LruGarbageCollection = 'lru_garbage_collection', + /** + * A timer used to retry transactions. Since there can be multiple concurrent + * transactions, multiple of these may be in the queue at a given time. + */ + TransactionRetry = 'transaction_retry', + /** + * A timer used to retry operations scheduled via retryable AsyncQueue + * operations. + */ + AsyncQueueRetry = 'async_queue_retry', + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = 'index_backfill' +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number + ); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + _compareTo(other: Timestamp): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + /** Returns a JSON-serializable representation of this `Timestamp`. */ + toJSON(): { + seconds: number; + nanoseconds: number; + }; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} + +declare type Timestamp_2 = + | string + | { + seconds?: string | number; + nanos?: number; + }; + +declare interface Token { + /** Type of token. */ + type: TokenType; + /** + * The user with which the token is associated (used for persisting user + * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. + */ + user?: User; + /** Header values to set for this token */ + headers: Map; +} + +declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction extends Transaction_2 { + protected readonly _firestore: Firestore; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: Transaction_3); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get( + documentRef: DocumentReference + ): Promise>; +} + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +declare class Transaction_2 { + protected readonly _firestore: Firestore_2; + private readonly _transaction; + private readonly _dataReader; + /** @hideconstructor */ + constructor(_firestore: Firestore_2, _transaction: Transaction_3); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get( + documentRef: DocumentReference + ): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: WithFieldValue + ): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, + options: SetOptions + ): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + data: UpdateData + ): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + field: string | FieldPath, + value: unknown, + ...moreFieldsAndValues: unknown[] + ): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete( + documentRef: DocumentReference + ): this; +} + +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +declare class Transaction_3 { + private datastore; + private readVersions; + private mutations; + private committed; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + private lastTransactionError; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + private writtenDocs; + constructor(datastore: Datastore); + lookup(keys: _DocumentKey[]): Promise; + set(key: _DocumentKey, data: ParsedSetData): void; + update(key: _DocumentKey, data: ParsedUpdateData): void; + delete(key: _DocumentKey): void; + commit(): Promise; + private recordVersion; + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + private precondition; + /** + * Returns the precondition for a document if the operation is an update. + */ + private preconditionForUpdate; + private write; + private ensureCommitNotCalled; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} + +/** Used to represent a field transform on a mutation. */ +declare class TransformOperation { + private _; +} + +declare type UnaryFilterOp = + | 'OPERATOR_UNSPECIFIED' + | 'IS_NAN' + | 'IS_NULL' + | 'IS_NOT_NAN' + | 'IS_NOT_NULL'; + +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = ( + U extends unknown ? (k: U) => void : never +) extends (k: infer I) => void + ? I + : never; + +/** + * A function returned by `onSnapshot()` that removes the listener when invoked. + */ +export declare interface Unsubscribe { + /** Removes the listener when invoked. */ + (): void; +} + +/** + * An untyped Firestore Data Converter interface that is shared between the + * lite, firestore-exp and classic SDK. + */ +declare interface UntypedFirestoreDataConverter< + AppModelType, + DbModelType extends DocumentData_2 = DocumentData_2 +> { + toFirestore( + modelObject: WithFieldValue + ): WithFieldValue; + toFirestore( + modelObject: PartialWithFieldValue, + options: SetOptions_2 + ): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; +} + +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export declare type UpdateData = T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]?: UpdateData | FieldValue; + } & NestedUpdateFields + : Partial; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + data: UpdateData +): Promise; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + field: string | FieldPath, + value: unknown, + ...moreFieldsAndValues: unknown[] +): Promise; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +declare class User { + readonly uid: string | null; + /** A user with a null UID. */ + static readonly UNAUTHENTICATED: User; + static readonly GOOGLE_CREDENTIALS: User; + static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; + constructor(uid: string | null); + isAuthenticated(): boolean; + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey(): string; + isEqual(otherUser: User): boolean; +} + +/* Excluded from this release type: _validateIsNotUsedTogether */ + +declare type Value = firestoreV1ApiClientInterfaces.Value; + +declare type ValueNullValue = 'NULL_VALUE'; + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link FieldValue.vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + private readonly _values; + /* Excluded from this release type: __constructor */ + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; +} + +declare class ViewSnapshot { + readonly query: Query_2; + readonly docs: DocumentSet; + readonly oldDocs: DocumentSet; + readonly docChanges: DocumentViewChange[]; + readonly mutatedKeys: DocumentKeySet; + readonly fromCache: boolean; + readonly syncStateChanged: boolean; + readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; + constructor( + query: Query_2, + docs: DocumentSet, + oldDocs: DocumentSet, + docChanges: DocumentViewChange[], + mutatedKeys: DocumentKeySet, + fromCache: boolean, + syncStateChanged: boolean, + excludesMetadataChanges: boolean, + hasCachedResults: boolean + ); + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments( + query: Query_2, + documents: DocumentSet, + mutatedKeys: DocumentKeySet, + fromCache: boolean, + hasCachedResults: boolean + ): ViewSnapshot; + get hasPendingWrites(): boolean; + isEqual(other: ViewSnapshot): boolean; +} + +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ +export declare function waitForPendingWrites( + firestore: Firestore +): Promise; + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where( + fieldPath: string | FieldPath, + opStr: WhereFilterOp, + value: unknown +): QueryFieldFilterConstraint; + +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export declare type WhereFilterOp = + | '<' + | '<=' + | '==' + | '!=' + | '>=' + | '>' + | 'array-contains' + | 'in' + | 'array-contains-any' + | 'not-in'; + +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = + | T + | (T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]: WithFieldValue | FieldValue; + } + : never); + +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private readonly _firestore; + private readonly _commitHandler; + private readonly _dataReader; + private _mutations; + private _committed; + /** @hideconstructor */ + constructor( + _firestore: Firestore_2, + _commitHandler: (m: Mutation[]) => Promise + ); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: WithFieldValue + ): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, + options: SetOptions + ): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + data: UpdateData + ): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + field: string | FieldPath, + value: unknown, + ...moreFieldsAndValues: unknown[] + ): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete( + documentRef: DocumentReference + ): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; + private _verifyNotCommitted; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; + +export {}; diff --git a/repo-scripts/prune-dts/new-tests/firestore.output.d.ts b/repo-scripts/prune-dts/new-tests/firestore.output.d.ts new file mode 100644 index 00000000000..33048292e38 --- /dev/null +++ b/repo-scripts/prune-dts/new-tests/firestore.output.d.ts @@ -0,0 +1,3475 @@ +/** + * Cloud Firestore + * + * @packageDocumentation + */ +import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseError } from '@firebase/util'; +import { LogLevelString as LogLevel } from '@firebase/logger'; +import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ +export declare function addDoc( + reference: CollectionReference, + data: WithFieldValue +): Promise>; +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys< + Prefix extends string, + T extends Record +> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + /** A type string to uniquely identify instances of this class. */ + readonly type = 'AggregateField'; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; +} +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual( + left: AggregateField, + right: AggregateField +): boolean; +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = + | ReturnType + | ReturnType + | ReturnType; +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot< + AggregateSpecType extends AggregateSpec, + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + /** A type string to uniquely identify instances of this class. */ + readonly type = 'AggregateQuerySnapshot'; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + private constructor(); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual< + AggregateSpecType extends AggregateSpec, + AppModelType, + DbModelType extends DocumentData +>( + left: AggregateQuerySnapshot, + right: AggregateQuerySnapshot +): boolean; +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and( + ...queryConstraints: QueryFilterConstraint[] +): QueryCompositeFilterConstraint; +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; +/* Excluded from this release type: AuthTokenFactory */ +/* Excluded from this release type: _AutoId */ +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average( + field: string | FieldPath +): AggregateField; +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + private constructor(); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; +} +/* Excluded from this release type: _ByteString */ +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ +export declare const CACHE_SIZE_UNLIMITED = -1; +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record< + string, + unknown +> + ? AddPrefixToKeys> + : never; +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ +export declare function clearIndexedDbPersistence( + firestore: Firestore +): Promise; +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection( + firestore: Firestore, + path: string, + ...pathSegments: string[] +): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection< + AppModelType, + DbModelType extends DocumentData +>( + reference: CollectionReference, + path: string, + ...pathSegments: string[] +): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + path: string, + ...pathSegments: string[] +): CollectionReference; +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup( + firestore: Firestore, + collectionId: string +): Query; +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> extends Query { + /** The type of this Firestore reference. */ + readonly type = 'collection'; + private constructor(); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData + >( + converter: FirestoreDataConverter + ): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter( + converter: null + ): CollectionReference; +} +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator( + firestore: Firestore, + host: string, + port: number, + options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + } +): void; +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +export declare function deleteAllPersistentCacheIndexes( + indexManager: PersistentCacheIndexManager +): void; +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ +export declare function deleteDoc< + AppModelType, + DbModelType extends DocumentData +>(reference: DocumentReference): Promise; +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ +export declare function disableNetwork(firestore: Firestore): Promise; +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +export declare function disablePersistentCacheIndexAutoCreation( + indexManager: PersistentCacheIndexManager +): void; +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc( + firestore: Firestore, + path: string, + ...pathSegments: string[] +): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc( + reference: CollectionReference, + path?: string, + ...pathSegments: string[] +): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc( + reference: DocumentReference, + path: string, + ...pathSegments: string[] +): DocumentReference; +/** + * A `DocumentChange` represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + */ +export declare 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; +} +/** + * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. + */ +export declare type DocumentChangeType = 'added' | 'removed' | 'modified'; +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export declare interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + /** The type of this Firestore reference. */ + readonly type = 'document'; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore; + private constructor(); + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData + >( + converter: FirestoreDataConverter + ): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + /** + * Metadata about the `DocumentSnapshot`, including information about its + * source and local modifications. + */ + readonly metadata: SnapshotMetadata; + protected constructor(); + /** + * Returns whether or not the data exists. True if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ + data(options?: SnapshotOptions): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; + /** + * Property of the `DocumentSnapshot` that provides the document's ID. + */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; +} +/* Excluded from this release type: _EmptyAppCheckTokenProvider */ +/* Excluded from this release type: _EmptyAuthCredentialsProvider */ +export { EmulatorMockTokenOptions }; +/** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableIndexedDbPersistence( + firestore: Firestore, + persistenceSettings?: PersistenceSettings +): Promise; +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableMultiTabIndexedDbPersistence( + firestore: Firestore +): Promise; +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ +export declare function enableNetwork(firestore: Firestore): Promise; +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +export declare function enablePersistentCacheIndexAutoCreation( + indexManager: PersistentCacheIndexManager +): void; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt( + snapshot: DocumentSnapshot +): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore< + AppModelType, + DbModelType extends DocumentData +>(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore( + ...fieldValues: unknown[] +): QueryEndAtConstraint; +/* Excluded from this release type: executeWrite */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +export declare interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + private constructor(); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; +} +/* Excluded from this release type: _FirebaseService */ +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore { + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + private constructor(); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + /** + * Returns a JSON-serializable representation of this `Firestore` instance. + */ + toJSON(): object; +} +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export declare interface FirestoreDataConverter< + 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 + * `PartialWithFieldValue`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore( + modelObject: WithFieldValue + ): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and + * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore( + modelObject: PartialWithFieldValue, + options: SetOptions + ): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data(options)`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. + * @param options - The `SnapshotOptions` from the initial call to `data()`. + */ + fromFirestore( + snapshot: QueryDocumentSnapshot, + options?: SnapshotOptions + ): AppModelType; +} +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + private constructor(); +} +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export declare type FirestoreErrorCode = + | 'cancelled' + | 'unknown' + | 'invalid-argument' + | 'deadline-exceeded' + | 'not-found' + | 'already-exists' + | 'permission-denied' + | 'resource-exhausted' + | 'failed-precondition' + | 'aborted' + | 'out-of-range' + | 'unimplemented' + | 'internal' + | 'unavailable' + | 'data-loss' + | 'unauthenticated'; +/** + * Union type from all supported SDK cache layer. + */ +export declare type FirestoreLocalCache = + | MemoryLocalCache + | PersistentLocalCache; +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface FirestoreSettings { + /** + * NOTE: This field will be deprecated in a future major release. Use `cache` field + * instead to specify cache size, and other cache configurations. + * + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The size is not a guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` + * and `PersistentLocalCache`, each with different configuration options. + * + * When unspecified, `MemoryLocalCache` will be used by default. + * + * NOTE: setting this field and `cacheSizeBytes` at the same time will throw + * exception during SDK initialization. Instead, using the configuration in + * the `FirestoreLocalCache` object to specify the cache size. + */ + localCache?: FirestoreLocalCache; + /** + * Forces the SDK’s underlying network transport (WebChannel) to use + * long-polling. Each response from the backend will be closed immediately + * after the backend sends data (by default responses are kept open in + * case the backend has more data to send). This avoids incompatibility + * issues with certain proxies, antivirus software, etc. that incorrectly + * buffer traffic indefinitely. Use of this option will cause some + * performance degradation though. + * + * This setting cannot be used with `experimentalAutoDetectLongPolling` and + * may be removed in a future release. If you find yourself using it to + * work around a specific network reliability issue, please tell us about + * it in https://github.com/firebase/firebase-js-sdk/issues/1674. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalForceLongPolling?: boolean; + /** + * Configures the SDK's underlying transport (WebChannel) to automatically + * detect if long-polling should be used. This is very similar to + * `experimentalForceLongPolling`, but only uses long-polling if required. + * + * After having had a default value of `false` since its inception in 2019, + * the default value of this setting was changed in May 2023 to `true` in + * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long + * polling is now enabled by default. To disable it, set this setting to + * `false`, and please open a GitHub issue to share the problems that + * motivated you disabling long-polling auto-detection. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalAutoDetectLongPolling?: boolean; + /** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * These options are only used if `experimentalForceLongPolling` is true or if + * `experimentalAutoDetectLongPolling` is true and the auto-detection + * determined that long-polling was needed. Otherwise, these options have no + * effect. + */ + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; + /** + * The hostname to connect to. + */ + host?: string; + /** + * Whether to use SSL when connecting. + */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** Returns a JSON-serializable representation of this GeoPoint. */ + toJSON(): { + latitude: number; + longitude: number; + }; +} +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregateFromServer< + AggregateSpecType extends AggregateSpec, + AppModelType, + DbModelType extends DocumentData +>( + query: Query, + aggregateSpec: AggregateSpecType +): Promise< + AggregateQuerySnapshot +>; +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCountFromServer< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise< + AggregateQuerySnapshot< + { + count: AggregateField; + }, + AppModelType, + DbModelType + > +>; +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDoc( + reference: DocumentReference +): Promise>; +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromCache< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference +): Promise>; +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromServer< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference +): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocs( + query: Query +): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromCache< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromServer< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise>; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The default {@link Firestore} instance of the default app. + */ +export declare function getFirestore(): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The default {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the default app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore( + app: FirebaseApp, + databaseId: string +): Firestore; +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +export declare function getPersistentCacheIndexManager( + firestore: Firestore +): PersistentCacheIndexManager | null; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; +/** + * The SDK definition of a Firestore index. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface Index { + /** The ID of the collection to index. */ + readonly collectionGroup: string; + /** A list of fields to index. */ + readonly fields?: IndexField[]; + [key: string]: unknown; +} +/** + * A list of Firestore indexes to speed up local query execution. + * + * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} + * for a description of the format of the index definition. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexConfiguration { + /** A list of all Firestore indexes. */ + readonly indexes?: Index[]; + [key: string]: unknown; +} +/** + * A single field element in an index configuration. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexField { + /** The field path to index. */ + readonly fieldPath: string; + /** + * What type of array index to create. Set to `CONTAINS` for `array-contains` + * and `array-contains-any` indexes. + * + * Only one of `arrayConfig` or `order` should be set; + */ + readonly arrayConfig?: 'CONTAINS'; + /** + * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for + * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. + * + * Only one of `arrayConfig` or `order` should be set. + */ + readonly order?: 'ASCENDING' | 'DESCENDING'; + [key: string]: unknown; +} +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ +export declare function initializeFirestore( + app: FirebaseApp, + settings: FirestoreSettings, + databaseId?: string +): Firestore; +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; +/** + * Describe the source a query listens to. + * + * Set to `default` to listen to both cache and server changes. Set to `cache` + * to listen to changes in cache only. + */ +export declare type ListenSource = 'default' | 'cache'; +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ +export declare function loadBundle( + firestore: Firestore, + bundleData: ReadableStream | ArrayBuffer | string +): LoadBundleTask; +/** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ +export declare class LoadBundleTask + implements PromiseLike +{ + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ + onProgress( + next?: (progress: LoadBundleTaskProgress) => unknown, + error?: (err: Error) => unknown, + complete?: () => void + ): void; + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ + catch( + onRejected: (a: Error) => R | PromiseLike + ): Promise; + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ + then( + onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike, + onRejected?: (a: Error) => R | PromiseLike + ): Promise; +} +/** + * Represents a progress update or a final state from loading bundles. + */ +export declare interface LoadBundleTaskProgress { + /** How many documents have been loaded. */ + documentsLoaded: number; + /** How many documents are in the bundle being loaded. */ + totalDocuments: number; + /** How many bytes have been loaded. */ + bytesLoaded: number; + /** How many bytes are in the bundle being loaded. */ + totalBytes: number; + /** Current task state. */ + taskState: TaskState; +} +export { LogLevel }; +/** + * An settings object to configure an `MemoryLocalCache` instance. + */ +export declare type MemoryCacheSettings = { + /** + * The garbage collector to use, for the memory cache layer. + * A `MemoryEagerGarbageCollector` is used when this is undefined. + */ + garbageCollector?: MemoryGarbageCollector; +}; +/** + * A garbage collector deletes documents whenever they are not part of any + * active queries, and have no local mutations attached to them. + * + * This collector tries to ensure lowest memory footprints from the SDK, + * at the risk of documents not being cached for offline queries or for + * direct queries to the cache. + * + * Use factory function {@link memoryEagerGarbageCollector()} to create an + * instance of this collector. + */ +export declare type MemoryEagerGarbageCollector = { + kind: 'memoryEager'; +}; +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector; +/** + * Union type from all support garbage collectors for memory local cache. + */ +export declare type MemoryGarbageCollector = + | MemoryEagerGarbageCollector + | MemoryLruGarbageCollector; +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare type MemoryLocalCache = { + kind: 'memory'; +}; +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +export declare function memoryLocalCache( + settings?: MemoryCacheSettings +): MemoryLocalCache; +/** + * A garbage collector deletes Least-Recently-Used documents in multiple + * batches. + * + * This collector is configured with a target size, and will only perform + * collection when the cached documents exceed the target size. It avoids + * querying backend repeated for the same query or document, at the risk + * of having a larger memory footprint. + * + * Use factory function {@link memoryLruGarbageCollector()} to create a + * instance of this collector. + */ +export declare type MemoryLruGarbageCollector = { + kind: 'memoryLru'; +}; +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +export declare function memoryLruGarbageCollector(settings?: { + cacheSizeBytes?: number; +}): MemoryLruGarbageCollector; +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ +export declare function namedQuery( + firestore: Firestore, + name: string +): Promise; +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = + UnionToIntersection< + { + [K in keyof T & string]: ChildUpdateFields; + }[keyof T & string] + >; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass + * individual `onNext` and `onError` callbacks or pass a single observer + * object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will + * never be called because the snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; + } +): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass + * individual `onNext` and `onError` callbacks or pass a single observer + * object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will + * never be called because the snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + options: SnapshotListenOptions, + observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; + } +): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass + * individual `onNext` and `onError` callbacks or pass a single observer + * object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will + * never be called because the snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` + * is available. + * @param onError - A callback to be called if the listen fails or is + * cancelled. No further callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are + * never ending. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + onNext: (snapshot: DocumentSnapshot) => void, + onError?: (error: FirestoreError) => void, + onCompletion?: () => void +): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass + * individual `onNext` and `onError` callbacks or pass a single observer + * object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will + * never be called because the snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` + * is available. + * @param onError - A callback to be called if the listen fails or is + * cancelled. No further callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are + * never ending. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + options: SnapshotListenOptions, + onNext: (snapshot: DocumentSnapshot) => void, + onError?: (error: FirestoreError) => void, + onCompletion?: () => void +): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass + * individual `onNext` and `onError` callbacks or pass a single observer + * object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will + * never be called because the snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, + observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; + } +): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass + * individual `onNext` and `onError` callbacks or pass a single observer + * object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will + * never be called because the snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, + options: SnapshotListenOptions, + observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; + } +): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass + * individual `onNext` and `onError` callbacks or pass a single observer + * object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will + * never be called because the snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param onNext - A callback to be called every time a new `QuerySnapshot` + * is available. + * @param onCompletion - Can be provided, but will not be called since streams are + * never ending. + * @param onError - A callback to be called if the listen fails or is + * cancelled. No further callbacks will occur. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, + onNext: (snapshot: QuerySnapshot) => void, + onError?: (error: FirestoreError) => void, + onCompletion?: () => void +): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass + * individual `onNext` and `onError` callbacks or pass a single observer + * object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will + * never be called because the snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` + * is available. + * @param onCompletion - Can be provided, but will not be called since streams are + * never ending. + * @param onError - A callback to be called if the listen fails or is + * cancelled. No further callbacks will occur. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, + options: SnapshotListenOptions, + onNext: (snapshot: QuerySnapshot) => void, + onError?: (error: FirestoreError) => void, + onCompletion?: () => void +): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use SnapshotMetadata in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The instance of Firestore for synchronizing snapshots. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync( + firestore: Firestore, + observer: { + next?: (value: void) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; + } +): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use `SnapshotMetadata` in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The `Firestore` instance for synchronizing snapshots. + * @param onSync - A callback to be called every time all snapshot listeners are + * in sync with each other. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync( + firestore: Firestore, + onSync: () => void +): Unsubscribe; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or( + ...queryConstraints: QueryFilterConstraint[] +): QueryCompositeFilterConstraint; +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy( + fieldPath: string | FieldPath, + directionStr?: OrderByDirection +): QueryOrderByConstraint; +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export declare type OrderByDirection = 'desc' | 'asc'; +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = + | Partial + | (T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; + } + : never); +/** + * Settings that can be passed to `enableIndexedDbPersistence()` to configure + * Firestore persistence. + * + * Persistence cannot be used in a Node.js environment. + */ +export declare interface PersistenceSettings { + /** + * Whether to force enable persistence for the client. This cannot be used + * with multi-tab synchronization and is primarily intended for use with Web + * Workers. Setting this to `true` will enable persistence, but cause other + * tabs using persistence to fail. + */ + forceOwnership?: boolean; +} +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +export declare class PersistentCacheIndexManager { + /** A type string to uniquely identify instances of this class. */ + readonly type: 'PersistentCacheIndexManager'; + private constructor(); +} +/** + * An settings object to configure an `PersistentLocalCache` instance. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare type PersistentCacheSettings = { + /** + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The SDK does not guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies how multiple tabs/windows will be managed by the SDK. + */ + tabManager?: PersistentTabManager; +}; +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare type PersistentLocalCache = { + kind: 'persistent'; +}; +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare function persistentLocalCache( + settings?: PersistentCacheSettings +): PersistentLocalCache; +/** + * A tab manager supporting multiple tabs. SDK will synchronize queries and + * mutations done across all tabs using the SDK. + */ +export declare type PersistentMultipleTabManager = { + kind: 'PersistentMultipleTab'; +}; +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +export declare function persistentMultipleTabManager(): PersistentMultipleTabManager; +/** + * A tab manager supporting only one tab, no synchronization will be + * performed across tabs. + */ +export declare type PersistentSingleTabManager = { + kind: 'persistentSingleTab'; +}; +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +export declare function persistentSingleTabManager( + settings: PersistentSingleTabManagerSettings | undefined +): PersistentSingleTabManager; +/** + * Type to configure an `PersistentSingleTabManager` instance. + */ +export declare type PersistentSingleTabManagerSettings = { + /** + * Whether to force-enable persistent (IndexedDB) cache for the client. This + * cannot be used with multi-tab synchronization and is primarily intended for + * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause + * other tabs using IndexedDB cache to fail. + */ + forceOwnership?: boolean; +}; +/** + * A union of all available tab managers. + */ +export declare type PersistentTabManager = + | PersistentSingleTabManager + | PersistentMultipleTabManager; +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + protected constructor(); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData + >( + converter: FirestoreDataConverter + ): Query; +} +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query( + query: Query, + compositeFilter: QueryCompositeFilterConstraint, + ...queryConstraints: QueryNonFilterConstraint[] +): Query; +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query( + query: Query, + ...queryConstraints: QueryConstraint[] +): Query; +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; +} +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = + | 'where' + | 'orderBy' + | 'limit' + | 'limitToLast' + | 'startAt' + | 'startAfter' + | 'endAt' + | 'endBefore'; +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(options?: SnapshotOptions): AppModelType; +} +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; +} +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual< + AppModelType, + DbModelType extends DocumentData +>( + left: Query, + right: Query +): boolean; +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type = 'where'; +} +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = + | QueryFieldFilterConstraint + | QueryCompositeFilterConstraint; +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; +} +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = + | QueryOrderByConstraint + | QueryLimitConstraint + | QueryStartAtConstraint + | QueryEndAtConstraint; +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type = 'orderBy'; +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + /** + * Metadata about this snapshot, concerning its source and if it has local + * modifications. + */ + readonly metadata: SnapshotMetadata; + /** + * The query on which you called `get` or `onSnapshot` in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + private constructor(); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach( + callback: ( + result: QueryDocumentSnapshot + ) => void, + thisArg?: unknown + ): void; + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ + docChanges( + options?: SnapshotListenOptions + ): Array>; +} +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; +} +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual< + AppModelType, + DbModelType extends DocumentData +>( + left: + | DocumentReference + | CollectionReference, + right: + | DocumentReference + | CollectionReference +): boolean; +/* Excluded from this release type: _ResourcePath */ +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction( + firestore: Firestore, + updateFunction: (transaction: Transaction) => Promise, + options?: TransactionOptions +): Promise; +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; +/** + * Writes to the document referred to by this `DocumentReference`. If the + * document does not yet exist, it will be created. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc( + reference: DocumentReference, + data: WithFieldValue +): Promise; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @returns A Promise resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc( + reference: DocumentReference, + data: PartialWithFieldValue, + options: SetOptions +): Promise; +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. If IndexedDb is not + * enabled, any index configuration is ignored. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param configuration -The index definition. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration( + firestore: Firestore, + configuration: IndexConfiguration +): Promise; +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. Invoke either + * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()` + * before setting an index configuration. If IndexedDb is not enabled, any + * index configuration is ignored. + * + * The method accepts the JSON format exported by the Firebase CLI (`firebase + * firestore:indexes`). If the JSON format is invalid, this method throws an + * error. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param json -The JSON format exported by the Firebase CLI. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration( + firestore: Firestore, + json: string +): Promise; +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +export declare function setLogLevel(logLevel: LogLevel): void; +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export declare type SetOptions = + | { + readonly merge?: boolean; + } + | { + readonly mergeFields?: Array; + }; +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual< + AppModelType, + DbModelType extends DocumentData +>( + left: + | DocumentSnapshot + | QuerySnapshot, + right: + | DocumentSnapshot + | QuerySnapshot +): boolean; +/** + * An options object that can be passed to {@link (onSnapshot:1)} and {@link + * QuerySnapshot.docChanges} to control which types of changes to include in the + * result set. + */ +export declare interface SnapshotListenOptions { + /** + * Include a change even if only the metadata of the query or of a document + * changed. Default is false. + */ + readonly includeMetadataChanges?: boolean; + /** + * Set the source the query listens to. Default to "default", which + * listens to both cache and server. + */ + readonly source?: ListenSource; +} +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ +export declare class SnapshotMetadata { + /** + * True if the snapshot contains the result of local writes (for example + * `set()` or `update()` calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * `SnapshotListenOptions`) you will receive another snapshot with + * `hasPendingWrites` equal to false once the writes have been committed to + * the backend. + */ + readonly hasPendingWrites: boolean; + /** + * True if the snapshot was created from cached data rather than guaranteed + * up-to-date server data. If your listener has opted into metadata updates + * (via `SnapshotListenOptions`) you will receive another snapshot with + * `fromCache` set to false once the client has received up-to-date data from + * the backend. + */ + readonly fromCache: boolean; + private constructor(); + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other: SnapshotMetadata): boolean; +} +/** + * Options that configure how data is retrieved from a `DocumentSnapshot` (for + * example the desired behavior for server timestamps that have not yet been set + * to their final value). + */ +export declare interface SnapshotOptions { + /** + * If set, controls the return value for server timestamps that have not yet + * been set to their final value. + * + * By specifying 'estimate', pending server timestamps return an estimate + * based on the local clock. This estimate will differ from the final value + * and cause these values to change once the server result becomes available. + * + * By specifying 'previous', pending timestamps will be ignored and return + * their previous value instead. + * + * If omitted or set to 'none', `null` will be returned by default until the + * server value becomes available. + */ + readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; +} +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter< + AppModelType, + DbModelType extends DocumentData +>( + snapshot: DocumentSnapshot +): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter( + ...fieldValues: unknown[] +): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt( + snapshot: DocumentSnapshot +): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt( + ...fieldValues: unknown[] +): QueryStartAtConstraint; +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; +/** + * Represents the state of bundle loading tasks. + * + * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will + * be no more updates after they are reported. + */ +export declare type TaskState = 'Error' | 'Running' | 'Success'; +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number + ); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + /** Returns a JSON-serializable representation of this `Timestamp`. */ + toJSON(): { + seconds: number; + nanoseconds: number; + }; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction { + private constructor(); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get( + documentRef: DocumentReference + ): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: WithFieldValue + ): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, + options: SetOptions + ): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + data: UpdateData + ): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + field: string | FieldPath, + value: unknown, + ...moreFieldsAndValues: unknown[] + ): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete( + documentRef: DocumentReference + ): this; +} +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = ( + U extends unknown ? (k: U) => void : never +) extends (k: infer I) => void + ? I + : never; +/** + * A function returned by `onSnapshot()` that removes the listener when invoked. + */ +export declare interface Unsubscribe { + /** Removes the listener when invoked. */ + (): void; +} +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export declare type UpdateData = T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]?: UpdateData | FieldValue; + } & NestedUpdateFields + : Partial; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + data: UpdateData +): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + field: string | FieldPath, + value: unknown, + ...moreFieldsAndValues: unknown[] +): Promise; +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link FieldValue.vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + /* Excluded from this release type: __constructor */ + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; +} +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ +export declare function waitForPendingWrites( + firestore: Firestore +): Promise; +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where( + fieldPath: string | FieldPath, + opStr: WhereFilterOp, + value: unknown +): QueryFieldFilterConstraint; +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export declare type WhereFilterOp = + | '<' + | '<=' + | '==' + | '!=' + | '>=' + | '>' + | 'array-contains' + | 'in' + | 'array-contains-any' + | 'not-in'; +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = + | T + | (T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]: WithFieldValue | FieldValue; + } + : never); +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private constructor(); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: WithFieldValue + ): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, + options: SetOptions + ): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + data: UpdateData + ): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + field: string | FieldPath, + value: unknown, + ...moreFieldsAndValues: unknown[] + ): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete( + documentRef: DocumentReference + ): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; +} +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; +export {}; diff --git a/repo-scripts/prune-dts/new-tests/messaging.input.d.ts b/repo-scripts/prune-dts/new-tests/messaging.input.d.ts new file mode 100644 index 00000000000..f25b27fc1f7 --- /dev/null +++ b/repo-scripts/prune-dts/new-tests/messaging.input.d.ts @@ -0,0 +1,223 @@ +/** + * The Firebase Cloud Messaging Web SDK. + * This SDK does not work in a Node.js environment. + * + * @packageDocumentation + */ + +import { FirebaseApp } from '@firebase/app'; +import { NextFn } from '@firebase/util'; +import { Observer } from '@firebase/util'; +import { Unsubscribe } from '@firebase/util'; + +/** + * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes + * the {@link Messaging} instance from the push subscription. + * + * @param messaging - The {@link Messaging} instance. + * + * @returns The promise resolves when the token has been successfully deleted. + * + * @public + */ +export declare function deleteToken(messaging: Messaging): Promise; + +/** + * Options for features provided by the FCM SDK for Web. See {@link + * https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushfcmoptions | + * WebpushFcmOptions}. + * + * @public + */ +export declare interface FcmOptions { + /** + * The link to open when the user clicks on the notification. + */ + link?: string; + /** + * The label associated with the message's analytics data. + */ + analyticsLabel?: string; +} + +/* Excluded from this release type: _FirebaseMessagingName */ + +/** + * Retrieves a Firebase Cloud Messaging instance. + * + * @returns The Firebase Cloud Messaging instance associated with the provided firebase app. + * + * @public + */ +export declare function getMessaging(app?: FirebaseApp): Messaging; + +/** + * Subscribes the {@link Messaging} instance to push notifications. Returns a Firebase Cloud + * Messaging registration token that can be used to send push messages to that {@link Messaging} + * instance. + * + * If notification permission isn't already granted, this method asks the user for permission. The + * returned promise rejects if the user does not allow the app to show notifications. + * + * @param messaging - The {@link Messaging} instance. + * @param options - Provides an optional vapid key and an optional service worker registration. + * + * @returns The promise resolves with an FCM registration token. + * + * @public + */ +export declare function getToken( + messaging: Messaging, + options?: GetTokenOptions +): Promise; + +/** + * Options for {@link getToken}. + * + * @public + */ +export declare interface GetTokenOptions { + /** + * The public server key provided to push services. The key is used to + * authenticate push subscribers to receive push messages only from sending servers that hold + * the corresponding private key. If it is not provided, a default VAPID key is used. Note that some + * push services (Chrome Push Service) require a non-default VAPID key. Therefore, it is recommended + * to generate and import a VAPID key for your project with + * {@link https://firebase.google.com/docs/cloud-messaging/js/client#configure_web_credentials_in_your_app | Configure Web Credentials with FCM}. + * See + * {@link https://developers.google.com/web/fundamentals/push-notifications/web-push-protocol | The Web Push Protocol} + * for details on web push services. + */ + vapidKey?: string; + /** + * The service worker registration for receiving push + * messaging. If the registration is not provided explicitly, you need to have a + * `firebase-messaging-sw.js` at your root location. See + * {@link https://firebase.google.com/docs/cloud-messaging/js/client#access_the_registration_token | Access the registration token} + * for more details. + */ + serviceWorkerRegistration?: ServiceWorkerRegistration; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Checks if all required APIs exist in the browser. + * @returns a Promise that resolves to a boolean. + * + * @public + */ +export declare function isSupported(): Promise; + +/** + * Message payload that contains the notification payload that is represented with + * {@link NotificationPayload} and the data payload that contains an arbitrary + * number of key-value pairs sent by developers through the + * {@link https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification | Send API}. + * + * @public + */ +export declare interface MessagePayload { + /** + * {@inheritdoc NotificationPayload} + */ + notification?: NotificationPayload; + /** + * Arbitrary key/value payload. + */ + data?: { + [key: string]: string; + }; + /** + * {@inheritdoc FcmOptions} + */ + fcmOptions?: FcmOptions; + /** + * The sender of this message. + */ + from: string; + /** + * The collapse key of the message. See + * {@link https://firebase.google.com/docs/cloud-messaging/concept-options#collapsible_and_non-collapsible_messages | Non-collapsible and collapsible messages} + */ + collapseKey: string; + /** + * The message ID of a message. + */ + messageId: string; +} + +/** + * Public interface of the Firebase Cloud Messaging SDK. + * + * @public + */ +export declare interface Messaging { + /** + * The {@link @firebase/app#FirebaseApp} this `Messaging` instance is associated with. + */ + app: FirebaseApp; +} +export { NextFn }; + +/** + * Display notification details. Details are sent through the + * {@link https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification | Send API}. + * + * @public + */ +export declare interface NotificationPayload { + /** + * The notification's title. + */ + title?: string; + /** + * The notification's body text. + */ + body?: string; + /** + * The URL of an image that is downloaded on the device and displayed in the notification. + */ + image?: string; + /** + * The URL to use for the notification's icon. If you don't send this key in the request, + * FCM displays the launcher icon specified in your app manifest. + */ + icon?: string; +} +export { Observer }; + +/** + * When a push message is received and the user is currently on a page for your origin, the + * message is passed to the page and an `onMessage()` event is dispatched with the payload of + * the push message. + * + * + * @param messaging - The {@link Messaging} instance. + * @param nextOrObserver - This function, or observer object with `next` defined, + * is called when a message is received and the user is currently viewing your page. + * @returns To stop listening for messages execute this returned function. + * + * @public + */ +export declare function onMessage( + messaging: Messaging, + nextOrObserver: NextFn | Observer +): Unsubscribe; +export { Unsubscribe }; + +export {}; diff --git a/repo-scripts/prune-dts/new-tests/messaging.output.d.ts b/repo-scripts/prune-dts/new-tests/messaging.output.d.ts new file mode 100644 index 00000000000..8b2fb30d5b9 --- /dev/null +++ b/repo-scripts/prune-dts/new-tests/messaging.output.d.ts @@ -0,0 +1,210 @@ +/** + * The Firebase Cloud Messaging Web SDK. + * This SDK does not work in a Node.js environment. + * + * @packageDocumentation + */ +import { FirebaseApp } from '@firebase/app'; +import { NextFn } from '@firebase/util'; +import { Observer } from '@firebase/util'; +import { Unsubscribe } from '@firebase/util'; +/** + * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes + * the {@link Messaging} instance from the push subscription. + * + * @param messaging - The {@link Messaging} instance. + * + * @returns The promise resolves when the token has been successfully deleted. + * + * @public + */ +export declare function deleteToken(messaging: Messaging): Promise; +/** + * Options for features provided by the FCM SDK for Web. See {@link + * https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushfcmoptions | + * WebpushFcmOptions}. + * + * @public + */ +export declare interface FcmOptions { + /** + * The link to open when the user clicks on the notification. + */ + link?: string; + /** + * The label associated with the message's analytics data. + */ + analyticsLabel?: string; +} +/* Excluded from this release type: _FirebaseMessagingName */ +/** + * Retrieves a Firebase Cloud Messaging instance. + * + * @returns The Firebase Cloud Messaging instance associated with the provided firebase app. + * + * @public + */ +export declare function getMessaging(app?: FirebaseApp): Messaging; +/** + * Subscribes the {@link Messaging} instance to push notifications. Returns a Firebase Cloud + * Messaging registration token that can be used to send push messages to that {@link Messaging} + * instance. + * + * If notification permission isn't already granted, this method asks the user for permission. The + * returned promise rejects if the user does not allow the app to show notifications. + * + * @param messaging - The {@link Messaging} instance. + * @param options - Provides an optional vapid key and an optional service worker registration. + * + * @returns The promise resolves with an FCM registration token. + * + * @public + */ +export declare function getToken( + messaging: Messaging, + options?: GetTokenOptions +): Promise; +/** + * Options for {@link getToken}. + * + * @public + */ +export declare interface GetTokenOptions { + /** + * The public server key provided to push services. The key is used to + * authenticate push subscribers to receive push messages only from sending servers that hold + * the corresponding private key. If it is not provided, a default VAPID key is used. Note that some + * push services (Chrome Push Service) require a non-default VAPID key. Therefore, it is recommended + * to generate and import a VAPID key for your project with + * {@link https://firebase.google.com/docs/cloud-messaging/js/client#configure_web_credentials_in_your_app | Configure Web Credentials with FCM}. + * See + * {@link https://developers.google.com/web/fundamentals/push-notifications/web-push-protocol | The Web Push Protocol} + * for details on web push services. + */ + vapidKey?: string; + /** + * The service worker registration for receiving push + * messaging. If the registration is not provided explicitly, you need to have a + * `firebase-messaging-sw.js` at your root location. See + * {@link https://firebase.google.com/docs/cloud-messaging/js/client#access_the_registration_token | Access the registration token} + * for more details. + */ + serviceWorkerRegistration?: ServiceWorkerRegistration; +} +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Checks if all required APIs exist in the browser. + * @returns a Promise that resolves to a boolean. + * + * @public + */ +export declare function isSupported(): Promise; +/** + * Message payload that contains the notification payload that is represented with + * {@link NotificationPayload} and the data payload that contains an arbitrary + * number of key-value pairs sent by developers through the + * {@link https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification | Send API}. + * + * @public + */ +export declare interface MessagePayload { + /** + * {@inheritdoc NotificationPayload} + */ + notification?: NotificationPayload; + /** + * Arbitrary key/value payload. + */ + data?: { + [key: string]: string; + }; + /** + * {@inheritdoc FcmOptions} + */ + fcmOptions?: FcmOptions; + /** + * The sender of this message. + */ + from: string; + /** + * The collapse key of the message. See + * {@link https://firebase.google.com/docs/cloud-messaging/concept-options#collapsible_and_non-collapsible_messages | Non-collapsible and collapsible messages} + */ + collapseKey: string; + /** + * The message ID of a message. + */ + messageId: string; +} +/** + * Public interface of the Firebase Cloud Messaging SDK. + * + * @public + */ +export declare interface Messaging { + /** + * The {@link @firebase/app#FirebaseApp} this `Messaging` instance is associated with. + */ + app: FirebaseApp; +} +export { NextFn }; +/** + * Display notification details. Details are sent through the + * {@link https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification | Send API}. + * + * @public + */ +export declare interface NotificationPayload { + /** + * The notification's title. + */ + title?: string; + /** + * The notification's body text. + */ + body?: string; + /** + * The URL of an image that is downloaded on the device and displayed in the notification. + */ + image?: string; + /** + * The URL to use for the notification's icon. If you don't send this key in the request, + * FCM displays the launcher icon specified in your app manifest. + */ + icon?: string; +} +export { Observer }; +/** + * When a push message is received and the user is currently on a page for your origin, the + * message is passed to the page and an `onMessage()` event is dispatched with the payload of + * the push message. + * + * + * @param messaging - The {@link Messaging} instance. + * @param nextOrObserver - This function, or observer object with `next` defined, + * is called when a message is received and the user is currently viewing your page. + * @returns To stop listening for messages execute this returned function. + * + * @public + */ +export declare function onMessage( + messaging: Messaging, + nextOrObserver: NextFn | Observer +): Unsubscribe; +export { Unsubscribe }; +export {}; diff --git a/repo-scripts/prune-dts/new-tests/storage-public.input.d.ts b/repo-scripts/prune-dts/new-tests/storage-public.input.d.ts new file mode 100644 index 00000000000..8c9ae2ca7f3 --- /dev/null +++ b/repo-scripts/prune-dts/new-tests/storage-public.input.d.ts @@ -0,0 +1,1080 @@ +/** + * Cloud Storage for Firebase + * + * @packageDocumentation + */ + +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { CompleteFn } from '@firebase/util'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { FirebaseError } from '@firebase/util'; +import { NextFn } from '@firebase/util'; +import { Provider } from '@firebase/component'; +import { Subscribe } from '@firebase/util'; +import { Unsubscribe } from '@firebase/util'; + +/** + * A function that is called if the event stream ends normally. + */ +declare type CompleteFn_2 = () => void; + +/** + * A lightweight wrapper around XMLHttpRequest with a + * goog.net.XhrIo-like interface. + * + * You can create a new connection by invoking `newTextConnection()`, + * `newBytesConnection()` or `newStreamConnection()`. + */ +declare interface Connection { + /** + * Sends a request to the provided URL. + * + * This method never rejects its promise. In case of encountering an error, + * it sets an error code internally which can be accessed by calling + * getErrorCode() by callers. + */ + send( + url: string, + method: string, + body?: ArrayBufferView | Blob | string | null, + headers?: Headers_2 + ): Promise; + getErrorCode(): ErrorCode; + getStatus(): number; + getResponse(): T; + getErrorText(): string; + /** + * Abort the request. + */ + abort(): void; + getResponseHeader(header: string): string | null; + addUploadProgressListener(listener: (p1: ProgressEvent) => void): void; + removeUploadProgressListener(listener: (p1: ProgressEvent) => void): void; +} + +/** Response type exposed by the networking APIs. */ +declare type ConnectionType = + | string + | ArrayBuffer + | Blob + | ReadableStream; + +/** + * Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator. + * + * @param storage - The {@link FirebaseStorage} instance + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 5001) + * @param options - Emulator options. `options.mockUserToken` is the mock auth + * token to use for unit testing Security Rules. + * @public + */ +export declare function connectStorageEmulator( + storage: FirebaseStorage, + host: string, + port: number, + options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + } +): void; + +/* Excluded from this release type: _dataFromString */ + +/** + * Deletes the object at this location. + * @public + * @param ref - {@link StorageReference} for object to delete. + * @returns A `Promise` that resolves if the deletion succeeds. + */ +export declare function deleteObject(ref: StorageReference): Promise; +export { EmulatorMockTokenOptions }; + +/** + * Error codes for requests made by the XhrIo wrapper. + */ +declare enum ErrorCode { + NO_ERROR = 0, + NETWORK_ERROR = 1, + ABORT = 2 +} + +/** + * A function that is called with a `StorageError` + * if the event stream ends due to an error. + */ +declare type ErrorFn = (error: StorageError) => void; + +/** A function to handle an error. */ +declare type ErrorHandler = ( + connection: Connection, + response: StorageError +) => StorageError; + +/* Excluded from this release type: _FbsBlob */ + +/* Excluded from this release type: _FirebaseService */ + +/** + * A Firebase Storage instance. + * @public + */ +export declare interface FirebaseStorage extends _FirebaseService { + /** + * The {@link @firebase/app#FirebaseApp} associated with this `FirebaseStorage` instance. + */ + readonly app: FirebaseApp; + /** + * The maximum time to retry uploads in milliseconds. + */ + maxUploadRetryTime: number; + /** + * The maximum time to retry operations other than uploads or downloads in + * milliseconds. + */ + maxOperationRetryTime: number; +} + +/* Excluded from this release type: _FirebaseStorageImpl */ + +/** + * The full set of object metadata, including read-only properties. + * @public + */ +export declare interface FullMetadata extends UploadMetadata { + /** + * The bucket this object is contained in. + */ + bucket: string; + /** + * The full path of this object. + */ + fullPath: string; + /** + * The object's generation. + * {@link https://cloud.google.com/storage/docs/metadata#generation-number} + */ + generation: string; + /** + * The object's metageneration. + * {@link https://cloud.google.com/storage/docs/metadata#generation-number} + */ + metageneration: string; + /** + * The short name of this object, which is the last component of the full path. + * For example, if fullPath is 'full/path/image.png', name is 'image.png'. + */ + name: string; + /** + * The size of this object, in bytes. + */ + size: number; + /** + * A date string representing when this object was created. + */ + timeCreated: string; + /** + * A date string representing when this object was last updated. + */ + updated: string; + /** + * Tokens to allow access to the download URL. + */ + downloadTokens: string[] | undefined; + /** + * `StorageReference` associated with this upload. + */ + ref?: StorageReference | undefined; +} + +/** + * Downloads the data at the object's location. Returns an error if the object + * is not found. + * + * To use this functionality, you have to whitelist your app's origin in your + * Cloud Storage bucket. See also + * https://cloud.google.com/storage/docs/configuring-cors + * + * This API is not available in Node. + * + * @public + * @param ref - StorageReference where data should be downloaded. + * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to + * retrieve. + * @returns A Promise that resolves with a Blob containing the object's bytes + */ +export declare function getBlob( + ref: StorageReference, + maxDownloadSizeBytes?: number +): Promise; + +/** + * Downloads the data at the object's location. Returns an error if the object + * is not found. + * + * To use this functionality, you have to whitelist your app's origin in your + * Cloud Storage bucket. See also + * https://cloud.google.com/storage/docs/configuring-cors + * + * @public + * @param ref - StorageReference where data should be downloaded. + * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to + * retrieve. + * @returns A Promise containing the object's bytes + */ +export declare function getBytes( + ref: StorageReference, + maxDownloadSizeBytes?: number +): Promise; + +/* Excluded from this release type: _getChild */ + +/** + * Returns the download URL for the given {@link StorageReference}. + * @public + * @param ref - {@link StorageReference} to get the download URL for. + * @returns A `Promise` that resolves with the download + * URL for this object. + */ +export declare function getDownloadURL(ref: StorageReference): Promise; + +/** + * A `Promise` that resolves with the metadata for this object. If this + * object doesn't exist or metadata cannot be retrieved, the promise is + * rejected. + * @public + * @param ref - {@link StorageReference} to get metadata from. + */ +export declare function getMetadata( + ref: StorageReference +): Promise; + +/** + * Gets a {@link FirebaseStorage} instance for the given Firebase app. + * @public + * @param app - Firebase app to get {@link FirebaseStorage} instance for. + * @param bucketUrl - The gs:// url to your Firebase Storage Bucket. + * If not passed, uses the app's default Storage Bucket. + * @returns A {@link FirebaseStorage} instance. + */ +export declare function getStorage( + app?: FirebaseApp, + bucketUrl?: string +): FirebaseStorage; + +/** + * Downloads the data at the object's location. Raises an error event if the + * object is not found. + * + * This API is only available in Node. + * + * @public + * @param ref - StorageReference where data should be downloaded. + * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to + * retrieve. + * @returns A stream with the object's data as bytes + */ +export declare function getStream( + ref: StorageReference, + maxDownloadSizeBytes?: number +): ReadableStream; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Network headers */ +declare type Headers_2 = Record; + +/** + * Internal enum for task state. + */ +declare const enum InternalTaskState { + RUNNING = 'running', + PAUSING = 'pausing', + PAUSED = 'paused', + SUCCESS = 'success', + CANCELING = 'canceling', + CANCELED = 'canceled', + ERROR = 'error' +} + +/* Excluded from this release type: _invalidArgument */ + +/* Excluded from this release type: _invalidRootOperation */ + +/** + * List items (files) and prefixes (folders) under this storage reference. + * + * List API is only available for Firebase Rules Version 2. + * + * GCS is a key-blob store. Firebase Storage imposes the semantic of '/' + * delimited folder structure. + * Refer to GCS's List API if you want to learn more. + * + * To adhere to Firebase Rules's Semantics, Firebase Storage does not + * support objects whose paths end with "/" or contain two consecutive + * "/"s. Firebase Storage List API will filter these unsupported objects. + * list() may fail if there are too many unsupported objects in the bucket. + * @public + * + * @param ref - {@link StorageReference} to get list from. + * @param options - See {@link ListOptions} for details. + * @returns A `Promise` that resolves with the items and prefixes. + * `prefixes` contains references to sub-folders and `items` + * contains references to objects in this folder. `nextPageToken` + * can be used to get the rest of the results. + */ +export declare function list( + ref: StorageReference, + options?: ListOptions +): Promise; + +/** + * List all items (files) and prefixes (folders) under this storage reference. + * + * This is a helper method for calling list() repeatedly until there are + * no more results. The default pagination size is 1000. + * + * Note: The results may not be consistent if objects are changed while this + * operation is running. + * + * Warning: `listAll` may potentially consume too many resources if there are + * too many results. + * @public + * @param ref - {@link StorageReference} to get list from. + * + * @returns A `Promise` that resolves with all the items and prefixes under + * the current storage reference. `prefixes` contains references to + * sub-directories and `items` contains references to objects in this + * folder. `nextPageToken` is never returned. + */ +export declare function listAll(ref: StorageReference): Promise; + +/** + * The options `list()` accepts. + * @public + */ +export declare interface ListOptions { + /** + * If set, limits the total number of `prefixes` and `items` to return. + * The default and maximum maxResults is 1000. + */ + maxResults?: number | null; + /** + * The `nextPageToken` from a previous call to `list()`. If provided, + * listing is resumed from the previous position. + */ + pageToken?: string | null; +} + +/** + * Result returned by list(). + * @public + */ +export declare interface ListResult { + /** + * References to prefixes (sub-folders). You can call list() on them to + * get its contents. + * + * Folders are implicit based on '/' in the object paths. + * For example, if a bucket has two objects '/a/b/1' and '/a/b/2', list('/a') + * will return '/a/b' as a prefix. + */ + prefixes: StorageReference[]; + /** + * Objects in this directory. + * You can call getMetadata() and getDownloadUrl() on them. + */ + items: StorageReference[]; + /** + * If set, there might be more results for this list. Use this token to resume the list. + */ + nextPageToken?: string; +} + +/* Excluded from this release type: _Location */ + +/** + * @fileoverview Documentation for the metadata format. + */ +/** + * The full set of object metadata, including read-only properties. + */ +declare interface Metadata extends FullMetadata { + [prop: string]: unknown; +} + +/** + * Function that is called once for each value in a stream of values. + */ +declare type NextFn_2 = (value: T) => void; + +/** + * Returns a {@link StorageReference} for the given url. + * @param storage - {@link FirebaseStorage} instance. + * @param url - URL. If empty, returns root reference. + * @public + */ +export declare function ref( + storage: FirebaseStorage, + url?: string +): StorageReference; + +/** + * Returns a {@link StorageReference} for the given path in the + * default bucket. + * @param storageOrRef - {@link FirebaseStorage} or {@link StorageReference}. + * @param pathOrUrlStorage - path. If empty, returns root reference (if {@link FirebaseStorage} + * instance provided) or returns same reference (if {@link StorageReference} provided). + * @public + */ +export declare function ref( + storageOrRef: FirebaseStorage | StorageReference, + path?: string +): StorageReference; + +/* Excluded from this release type: _Reference */ + +declare interface Request_2 { + getPromise(): Promise; + /** + * Cancels the request. IMPORTANT: the promise may still be resolved with an + * appropriate value (if the request is finished before you call this method, + * but the promise has not yet been resolved), so don't just assume it will be + * rejected if you call this function. + * @param appDelete - True if the cancelation came from the app being deleted. + */ + cancel(appDelete?: boolean): void; +} + +/** + * A function that converts a server response to the API type expected by the + * SDK. + * + * @param I - the type of the backend's network response + * @param O - the output response type used by the rest of the SDK. + */ +declare type RequestHandler = ( + connection: Connection, + response: I +) => O; + +/** + * Contains a fully specified request. + * + * @param I - the type of the backend's network response. + * @param O - the output response type used by the rest of the SDK. + */ +declare class RequestInfo_2 { + url: string; + method: string; + /** + * Returns the value with which to resolve the request's promise. Only called + * if the request is successful. Throw from this function to reject the + * returned Request's promise with the thrown error. + * Note: The XhrIo passed to this function may be reused after this callback + * returns. Do not keep a reference to it in any way. + */ + handler: RequestHandler; + timeout: number; + urlParams: UrlParams; + headers: Headers_2; + body: Blob | string | Uint8Array | null; + errorHandler: ErrorHandler | null; + /** + * Called with the current number of bytes uploaded and total size (-1 if not + * computable) of the request body (i.e. used to report upload progress). + */ + progressCallback: ((p1: number, p2: number) => void) | null; + successCodes: number[]; + additionalRetryCodes: number[]; + constructor( + url: string, + method: string, + /** + * Returns the value with which to resolve the request's promise. Only called + * if the request is successful. Throw from this function to reject the + * returned Request's promise with the thrown error. + * Note: The XhrIo passed to this function may be reused after this callback + * returns. Do not keep a reference to it in any way. + */ + handler: RequestHandler, + timeout: number + ); +} + +/** + * Object metadata that can be set at any time. + * @public + */ +export declare interface SettableMetadata { + /** + * Served as the 'Cache-Control' header on object download. + */ + cacheControl?: string | undefined; + /** + * Served as the 'Content-Disposition' header on object download. + */ + contentDisposition?: string | undefined; + /** + * Served as the 'Content-Encoding' header on object download. + */ + contentEncoding?: string | undefined; + /** + * Served as the 'Content-Language' header on object download. + */ + contentLanguage?: string | undefined; + /** + * Served as the 'Content-Type' header on object download. + */ + contentType?: string | undefined; + /** + * Additional user-defined custom metadata. + */ + customMetadata?: + | { + [key: string]: string; + } + | undefined; +} + +/** + * An error returned by the Firebase Storage SDK. + * @public + */ +export declare class StorageError extends FirebaseError { + private status_; + private readonly _baseMessage; + /** + * Stores custom error data unique to the `StorageError`. + */ + customData: { + serverResponse: string | null; + }; + /** + * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and + * added to the end of the message. + * @param message - Error message. + * @param status_ - Corresponding HTTP Status Code + */ + constructor(code: StorageErrorCode, message: string, status_?: number); + get status(): number; + set status(status: number); + /** + * Compares a `StorageErrorCode` against this error's code, filtering out the prefix. + */ + _codeEquals(code: StorageErrorCode): boolean; + /** + * Optional response message that was added by the server. + */ + get serverResponse(): null | string; + set serverResponse(serverResponse: string | null); +} + +/** + * @public + * Error codes that can be attached to `StorageError` objects. + */ +export declare enum StorageErrorCode { + UNKNOWN = 'unknown', + OBJECT_NOT_FOUND = 'object-not-found', + BUCKET_NOT_FOUND = 'bucket-not-found', + PROJECT_NOT_FOUND = 'project-not-found', + QUOTA_EXCEEDED = 'quota-exceeded', + UNAUTHENTICATED = 'unauthenticated', + UNAUTHORIZED = 'unauthorized', + UNAUTHORIZED_APP = 'unauthorized-app', + RETRY_LIMIT_EXCEEDED = 'retry-limit-exceeded', + INVALID_CHECKSUM = 'invalid-checksum', + CANCELED = 'canceled', + INVALID_EVENT_NAME = 'invalid-event-name', + INVALID_URL = 'invalid-url', + INVALID_DEFAULT_BUCKET = 'invalid-default-bucket', + NO_DEFAULT_BUCKET = 'no-default-bucket', + CANNOT_SLICE_BLOB = 'cannot-slice-blob', + SERVER_FILE_WRONG_SIZE = 'server-file-wrong-size', + NO_DOWNLOAD_URL = 'no-download-url', + INVALID_ARGUMENT = 'invalid-argument', + INVALID_ARGUMENT_COUNT = 'invalid-argument-count', + APP_DELETED = 'app-deleted', + INVALID_ROOT_OPERATION = 'invalid-root-operation', + INVALID_FORMAT = 'invalid-format', + INTERNAL_ERROR = 'internal-error', + UNSUPPORTED_ENVIRONMENT = 'unsupported-environment' +} + +/** + * A stream observer for Firebase Storage. + * @public + */ +export declare interface StorageObserver { + next?: NextFn | null; + error?: (error: StorageError) => void | null; + complete?: CompleteFn | null; +} + +/** + * An observer identical to the `Observer` defined in packages/util except the + * error passed into the ErrorFn is specifically a `StorageError`. + */ +declare interface StorageObserver_2 { + /** + * Function that is called once for each value in the event stream. + */ + next?: NextFn_2; + /** + * A function that is called with a `StorageError` + * if the event stream ends due to an error. + */ + error?: ErrorFn; + /** + * A function that is called if the event stream ends normally. + */ + complete?: CompleteFn_2; +} + +/** + * Represents a reference to a Google Cloud Storage object. Developers can + * upload, download, and delete objects, as well as get/set object metadata. + * @public + */ +export declare interface StorageReference { + /** + * Returns a gs:// URL for this object in the form + * `gs://///` + * @returns The gs:// URL. + */ + toString(): string; + /** + * A reference to the root of this object's bucket. + */ + root: StorageReference; + /** + * The name of the bucket containing this reference's object. + */ + bucket: string; + /** + * The full path of this object. + */ + fullPath: string; + /** + * The short name of this object, which is the last component of the full path. + * For example, if fullPath is 'full/path/image.png', name is 'image.png'. + */ + name: string; + /** + * The {@link FirebaseStorage} instance associated with this reference. + */ + storage: FirebaseStorage; + /** + * A reference pointing to the parent location of this reference, or null if + * this reference is the root. + */ + parent: StorageReference | null; +} + +declare class StringData { + data: Uint8Array; + contentType: string | null; + constructor(data: Uint8Array, contentType?: string | null); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An enumeration of the possible string formats for upload. + * @public + */ +export declare type StringFormat = + (typeof StringFormat)[keyof typeof StringFormat]; + +/** + * An enumeration of the possible string formats for upload. + * @public + */ +export declare const StringFormat: { + /** + * Indicates the string should be interpreted "raw", that is, as normal text. + * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte + * sequence. + * Example: The string 'Hello! \\ud83d\\ude0a' becomes the byte sequence + * 48 65 6c 6c 6f 21 20 f0 9f 98 8a + */ + readonly RAW: 'raw'; + /** + * Indicates the string should be interpreted as base64-encoded data. + * Padding characters (trailing '='s) are optional. + * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence + * ad 69 8e fb e1 3a b7 bf eb 97 + */ + readonly BASE64: 'base64'; + /** + * Indicates the string should be interpreted as base64url-encoded data. + * Padding characters (trailing '='s) are optional. + * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence + * ad 69 8e fb e1 3a b7 bf eb 97 + */ + readonly BASE64URL: 'base64url'; + /** + * Indicates the string is a data URL, such as one obtained from + * canvas.toDataURL(). + * Example: the string 'data:application/octet-stream;base64,aaaa' + * becomes the byte sequence + * 69 a6 9a + * (the content-type "application/octet-stream" is also applied, but can + * be overridden in the metadata object). + */ + readonly DATA_URL: 'data_url'; +}; + +/** + * Subscribes to an event stream. + */ +declare type Subscribe_2 = ( + next?: NextFn_2 | StorageObserver_2, + error?: ErrorFn, + complete?: CompleteFn_2 +) => Unsubscribe_2; + +/** + * An event that is triggered on a task. + * @public + */ +export declare type TaskEvent = 'state_changed'; + +/* Excluded from this release type: _TaskEvent */ + +/** + * Represents the current state of a running upload. + * @public + */ +export declare type TaskState = + | 'running' + | 'paused' + | 'success' + | 'canceled' + | 'error'; + +/* Excluded from this release type: _TaskState */ + +/** + * Unsubscribes from a stream. + */ +declare type Unsubscribe_2 = () => void; + +/** + * Updates the metadata for this object. + * @public + * @param ref - {@link StorageReference} to update metadata for. + * @param metadata - The new metadata for the object. + * Only values that have been explicitly set will be changed. Explicitly + * setting a value to null will remove the metadata. + * @returns A `Promise` that resolves with the new metadata for this object. + */ +export declare function updateMetadata( + ref: StorageReference, + metadata: SettableMetadata +): Promise; + +/** + * Uploads data to this object's location. + * The upload is not resumable. + * @public + * @param ref - {@link StorageReference} where data should be uploaded. + * @param data - The data to upload. + * @param metadata - Metadata for the data to upload. + * @returns A Promise containing an UploadResult + */ +export declare function uploadBytes( + ref: StorageReference, + data: Blob | Uint8Array | ArrayBuffer, + metadata?: UploadMetadata +): Promise; + +/** + * Uploads data to this object's location. + * The upload can be paused and resumed, and exposes progress updates. + * @public + * @param ref - {@link StorageReference} where data should be uploaded. + * @param data - The data to upload. + * @param metadata - Metadata for the data to upload. + * @returns An UploadTask + */ +export declare function uploadBytesResumable( + ref: StorageReference, + data: Blob | Uint8Array | ArrayBuffer, + metadata?: UploadMetadata +): UploadTask; + +/** + * Object metadata that can be set at upload. + * @public + */ +export declare interface UploadMetadata extends SettableMetadata { + /** + * A Base64-encoded MD5 hash of the object being uploaded. + */ + md5Hash?: string | undefined; +} + +/** + * Result returned from a non-resumable upload. + * @public + */ +export declare interface UploadResult { + /** + * Contains the metadata sent back from the server. + */ + readonly metadata: FullMetadata; + /** + * The reference that spawned this upload. + */ + readonly ref: StorageReference; +} + +/** + * Uploads a string to this object's location. + * The upload is not resumable. + * @public + * @param ref - {@link StorageReference} where string should be uploaded. + * @param value - The string to upload. + * @param format - The format of the string to upload. + * @param metadata - Metadata for the string to upload. + * @returns A Promise containing an UploadResult + */ +export declare function uploadString( + ref: StorageReference, + value: string, + format?: StringFormat, + metadata?: UploadMetadata +): Promise; + +/** + * Represents the process of uploading an object. Allows you to monitor and + * manage the upload. + * @public + */ +export declare interface UploadTask { + /** + * Cancels a running task. Has no effect on a complete or failed task. + * @returns True if the cancel had an effect. + */ + cancel(): boolean; + /** + * Equivalent to calling `then(null, onRejected)`. + */ + catch(onRejected: (error: StorageError) => unknown): Promise; + /** + * Listens for events on this task. + * + * Events have three callback functions (referred to as `next`, `error`, and + * `complete`). + * + * If only the event is passed, a function that can be used to register the + * callbacks is returned. Otherwise, the callbacks are passed after the event. + * + * Callbacks can be passed either as three separate arguments or as the + * `next`, `error`, and `complete` properties of an object. Any of the three + * callbacks is optional, as long as at least one is specified. In addition, + * when you add your callbacks, you get a function back. You can call this + * function to unregister the associated callbacks. + * + * @example **Pass callbacks separately or in an object.** + * ```javascript + * var next = function(snapshot) {}; + * var error = function(error) {}; + * var complete = function() {}; + * + * // The first example. + * uploadTask.on( + * firebase.storage.TaskEvent.STATE_CHANGED, + * next, + * error, + * complete); + * + * // This is equivalent to the first example. + * uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, { + * 'next': next, + * 'error': error, + * 'complete': complete + * }); + * + * // This is equivalent to the first example. + * var subscribe = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED); + * subscribe(next, error, complete); + * + * // This is equivalent to the first example. + * var subscribe = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED); + * subscribe({ + * 'next': next, + * 'error': error, + * 'complete': complete + * }); + * ``` + * + * @example **Any callback is optional.** + * ```javascript + * // Just listening for completion, this is legal. + * uploadTask.on( + * firebase.storage.TaskEvent.STATE_CHANGED, + * null, + * null, + * function() { + * console.log('upload complete!'); + * }); + * + * // Just listening for progress/state changes, this is legal. + * uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, function(snapshot) { + * var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100; + * console.log(percent + "% done"); + * }); + * + * // This is also legal. + * uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, { + * 'complete': function() { + * console.log('upload complete!'); + * } + * }); + * ``` + * + * @example **Use the returned function to remove callbacks.** + * ```javascript + * var unsubscribe = uploadTask.on( + * firebase.storage.TaskEvent.STATE_CHANGED, + * function(snapshot) { + * var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100; + * console.log(percent + "% done"); + * // Stop after receiving one update. + * unsubscribe(); + * }); + * + * // This code is equivalent to the above. + * var handle = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED); + * unsubscribe = handle(function(snapshot) { + * var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100; + * console.log(percent + "% done"); + * // Stop after receiving one update. + * unsubscribe(); + * }); + * ``` + * + * @param event - The type of event to listen for. + * @param nextOrObserver - + * The `next` function, which gets called for each item in + * the event stream, or an observer object with some or all of these three + * properties (`next`, `error`, `complete`). + * @param error - A function that gets called with a `StorageError` + * if the event stream ends due to an error. + * @param completed - A function that gets called if the + * event stream ends normally. + * @returns + * If only the event argument is passed, returns a function you can use to + * add callbacks (see the examples above). If more than just the event + * argument is passed, returns a function you can call to unregister the + * callbacks. + */ + on( + event: TaskEvent, + nextOrObserver?: + | StorageObserver + | null + | ((snapshot: UploadTaskSnapshot) => unknown), + error?: ((a: StorageError) => unknown) | null, + complete?: Unsubscribe | null + ): Unsubscribe | Subscribe; + /** + * Pauses a currently running task. Has no effect on a paused or failed task. + * @returns True if the operation took effect, false if ignored. + */ + pause(): boolean; + /** + * Resumes a paused task. Has no effect on a currently running or failed task. + * @returns True if the operation took effect, false if ignored. + */ + resume(): boolean; + /** + * A snapshot of the current task state. + */ + snapshot: UploadTaskSnapshot; + /** + * This object behaves like a Promise, and resolves with its snapshot data + * when the upload completes. + * @param onFulfilled - The fulfillment callback. Promise chaining works as normal. + * @param onRejected - The rejection callback. + */ + then( + onFulfilled?: ((snapshot: UploadTaskSnapshot) => unknown) | null, + onRejected?: ((error: StorageError) => unknown) | null + ): Promise; +} + +/* Excluded from this release type: _UploadTask */ + +/** + * Holds data about the current state of the upload task. + * @public + */ +export declare interface UploadTaskSnapshot { + /** + * The number of bytes that have been successfully uploaded so far. + */ + bytesTransferred: number; + /** + * Before the upload completes, contains the metadata sent to the server. + * After the upload completes, contains the metadata sent back from the server. + */ + metadata: FullMetadata; + /** + * The reference that spawned this snapshot's upload task. + */ + ref: StorageReference; + /** + * The current state of the task. + */ + state: TaskState; + /** + * The task of which this is a snapshot. + */ + task: UploadTask; + /** + * The total number of bytes to be uploaded. + */ + totalBytes: number; +} + +/** + * Type for url params stored in RequestInfo. + */ +declare interface UrlParams { + [name: string]: string | number; +} + +export {}; diff --git a/repo-scripts/prune-dts/new-tests/storage-public.output.d.ts b/repo-scripts/prune-dts/new-tests/storage-public.output.d.ts new file mode 100644 index 00000000000..10b4c2a5237 --- /dev/null +++ b/repo-scripts/prune-dts/new-tests/storage-public.output.d.ts @@ -0,0 +1,796 @@ +/** + * Cloud Storage for Firebase + * + * @packageDocumentation + */ +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { CompleteFn } from '@firebase/util'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { FirebaseError } from '@firebase/util'; +import { NextFn } from '@firebase/util'; +import { Provider } from '@firebase/component'; +import { Subscribe } from '@firebase/util'; +import { Unsubscribe } from '@firebase/util'; +/** + * Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator. + * + * @param storage - The {@link FirebaseStorage} instance + * @param host - The emulator host (ex: localhost) + * @param port - The emulator port (ex: 5001) + * @param options - Emulator options. `options.mockUserToken` is the mock auth + * token to use for unit testing Security Rules. + * @public + */ +export declare function connectStorageEmulator( + storage: FirebaseStorage, + host: string, + port: number, + options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + } +): void; +/* Excluded from this release type: _dataFromString */ +/** + * Deletes the object at this location. + * @public + * @param ref - {@link StorageReference} for object to delete. + * @returns A `Promise` that resolves if the deletion succeeds. + */ +export declare function deleteObject(ref: StorageReference): Promise; +export { EmulatorMockTokenOptions }; +/* Excluded from this release type: _FbsBlob */ +/* Excluded from this release type: _FirebaseService */ +/** + * A Firebase Storage instance. + * @public + */ +export declare interface FirebaseStorage { + /** + * The {@link @firebase/app#FirebaseApp} associated with this `FirebaseStorage` instance. + */ + readonly app: FirebaseApp; + /** + * The maximum time to retry uploads in milliseconds. + */ + maxUploadRetryTime: number; + /** + * The maximum time to retry operations other than uploads or downloads in + * milliseconds. + */ + maxOperationRetryTime: number; +} +/* Excluded from this release type: _FirebaseStorageImpl */ +/** + * The full set of object metadata, including read-only properties. + * @public + */ +export declare interface FullMetadata extends UploadMetadata { + /** + * The bucket this object is contained in. + */ + bucket: string; + /** + * The full path of this object. + */ + fullPath: string; + /** + * The object's generation. + * {@link https://cloud.google.com/storage/docs/metadata#generation-number} + */ + generation: string; + /** + * The object's metageneration. + * {@link https://cloud.google.com/storage/docs/metadata#generation-number} + */ + metageneration: string; + /** + * The short name of this object, which is the last component of the full path. + * For example, if fullPath is 'full/path/image.png', name is 'image.png'. + */ + name: string; + /** + * The size of this object, in bytes. + */ + size: number; + /** + * A date string representing when this object was created. + */ + timeCreated: string; + /** + * A date string representing when this object was last updated. + */ + updated: string; + /** + * Tokens to allow access to the download URL. + */ + downloadTokens: string[] | undefined; + /** + * `StorageReference` associated with this upload. + */ + ref?: StorageReference | undefined; +} +/** + * Downloads the data at the object's location. Returns an error if the object + * is not found. + * + * To use this functionality, you have to whitelist your app's origin in your + * Cloud Storage bucket. See also + * https://cloud.google.com/storage/docs/configuring-cors + * + * This API is not available in Node. + * + * @public + * @param ref - StorageReference where data should be downloaded. + * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to + * retrieve. + * @returns A Promise that resolves with a Blob containing the object's bytes + */ +export declare function getBlob( + ref: StorageReference, + maxDownloadSizeBytes?: number +): Promise; +/** + * Downloads the data at the object's location. Returns an error if the object + * is not found. + * + * To use this functionality, you have to whitelist your app's origin in your + * Cloud Storage bucket. See also + * https://cloud.google.com/storage/docs/configuring-cors + * + * @public + * @param ref - StorageReference where data should be downloaded. + * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to + * retrieve. + * @returns A Promise containing the object's bytes + */ +export declare function getBytes( + ref: StorageReference, + maxDownloadSizeBytes?: number +): Promise; +/* Excluded from this release type: _getChild */ +/** + * Returns the download URL for the given {@link StorageReference}. + * @public + * @param ref - {@link StorageReference} to get the download URL for. + * @returns A `Promise` that resolves with the download + * URL for this object. + */ +export declare function getDownloadURL(ref: StorageReference): Promise; +/** + * A `Promise` that resolves with the metadata for this object. If this + * object doesn't exist or metadata cannot be retrieved, the promise is + * rejected. + * @public + * @param ref - {@link StorageReference} to get metadata from. + */ +export declare function getMetadata( + ref: StorageReference +): Promise; +/** + * Gets a {@link FirebaseStorage} instance for the given Firebase app. + * @public + * @param app - Firebase app to get {@link FirebaseStorage} instance for. + * @param bucketUrl - The gs:// url to your Firebase Storage Bucket. + * If not passed, uses the app's default Storage Bucket. + * @returns A {@link FirebaseStorage} instance. + */ +export declare function getStorage( + app?: FirebaseApp, + bucketUrl?: string +): FirebaseStorage; +/** + * Downloads the data at the object's location. Raises an error event if the + * object is not found. + * + * This API is only available in Node. + * + * @public + * @param ref - StorageReference where data should be downloaded. + * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to + * retrieve. + * @returns A stream with the object's data as bytes + */ +export declare function getStream( + ref: StorageReference, + maxDownloadSizeBytes?: number +): ReadableStream; +/* Excluded from this release type: _invalidArgument */ +/* Excluded from this release type: _invalidRootOperation */ +/** + * List items (files) and prefixes (folders) under this storage reference. + * + * List API is only available for Firebase Rules Version 2. + * + * GCS is a key-blob store. Firebase Storage imposes the semantic of '/' + * delimited folder structure. + * Refer to GCS's List API if you want to learn more. + * + * To adhere to Firebase Rules's Semantics, Firebase Storage does not + * support objects whose paths end with "/" or contain two consecutive + * "/"s. Firebase Storage List API will filter these unsupported objects. + * list() may fail if there are too many unsupported objects in the bucket. + * @public + * + * @param ref - {@link StorageReference} to get list from. + * @param options - See {@link ListOptions} for details. + * @returns A `Promise` that resolves with the items and prefixes. + * `prefixes` contains references to sub-folders and `items` + * contains references to objects in this folder. `nextPageToken` + * can be used to get the rest of the results. + */ +export declare function list( + ref: StorageReference, + options?: ListOptions +): Promise; +/** + * List all items (files) and prefixes (folders) under this storage reference. + * + * This is a helper method for calling list() repeatedly until there are + * no more results. The default pagination size is 1000. + * + * Note: The results may not be consistent if objects are changed while this + * operation is running. + * + * Warning: `listAll` may potentially consume too many resources if there are + * too many results. + * @public + * @param ref - {@link StorageReference} to get list from. + * + * @returns A `Promise` that resolves with all the items and prefixes under + * the current storage reference. `prefixes` contains references to + * sub-directories and `items` contains references to objects in this + * folder. `nextPageToken` is never returned. + */ +export declare function listAll(ref: StorageReference): Promise; +/** + * The options `list()` accepts. + * @public + */ +export declare interface ListOptions { + /** + * If set, limits the total number of `prefixes` and `items` to return. + * The default and maximum maxResults is 1000. + */ + maxResults?: number | null; + /** + * The `nextPageToken` from a previous call to `list()`. If provided, + * listing is resumed from the previous position. + */ + pageToken?: string | null; +} +/** + * Result returned by list(). + * @public + */ +export declare interface ListResult { + /** + * References to prefixes (sub-folders). You can call list() on them to + * get its contents. + * + * Folders are implicit based on '/' in the object paths. + * For example, if a bucket has two objects '/a/b/1' and '/a/b/2', list('/a') + * will return '/a/b' as a prefix. + */ + prefixes: StorageReference[]; + /** + * Objects in this directory. + * You can call getMetadata() and getDownloadUrl() on them. + */ + items: StorageReference[]; + /** + * If set, there might be more results for this list. Use this token to resume the list. + */ + nextPageToken?: string; +} +/** + * Returns a {@link StorageReference} for the given url. + * @param storage - {@link FirebaseStorage} instance. + * @param url - URL. If empty, returns root reference. + * @public + */ +export declare function ref( + storage: FirebaseStorage, + url?: string +): StorageReference; +/** + * Returns a {@link StorageReference} for the given path in the + * default bucket. + * @param storageOrRef - {@link FirebaseStorage} or {@link StorageReference}. + * @param pathOrUrlStorage - path. If empty, returns root reference (if {@link FirebaseStorage} + * instance provided) or returns same reference (if {@link StorageReference} provided). + * @public + */ +export declare function ref( + storageOrRef: FirebaseStorage | StorageReference, + path?: string +): StorageReference; +/** + * Object metadata that can be set at any time. + * @public + */ +export declare interface SettableMetadata { + /** + * Served as the 'Cache-Control' header on object download. + */ + cacheControl?: string | undefined; + /** + * Served as the 'Content-Disposition' header on object download. + */ + contentDisposition?: string | undefined; + /** + * Served as the 'Content-Encoding' header on object download. + */ + contentEncoding?: string | undefined; + /** + * Served as the 'Content-Language' header on object download. + */ + contentLanguage?: string | undefined; + /** + * Served as the 'Content-Type' header on object download. + */ + contentType?: string | undefined; + /** + * Additional user-defined custom metadata. + */ + customMetadata?: + | { + [key: string]: string; + } + | undefined; +} +/** + * An error returned by the Firebase Storage SDK. + * @public + */ +export declare class StorageError extends FirebaseError { + private status_; + /** + * Stores custom error data unique to the `StorageError`. + */ + customData: { + serverResponse: string | null; + }; + /** + * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and + * added to the end of the message. + * @param message - Error message. + * @param status_ - Corresponding HTTP Status Code + */ + constructor(code: StorageErrorCode, message: string, status_?: number); + get status(): number; + set status(status: number); + /** + * Optional response message that was added by the server. + */ + get serverResponse(): null | string; + set serverResponse(serverResponse: string | null); +} +/** + * @public + * Error codes that can be attached to `StorageError` objects. + */ +export declare enum StorageErrorCode { + UNKNOWN = 'unknown', + OBJECT_NOT_FOUND = 'object-not-found', + BUCKET_NOT_FOUND = 'bucket-not-found', + PROJECT_NOT_FOUND = 'project-not-found', + QUOTA_EXCEEDED = 'quota-exceeded', + UNAUTHENTICATED = 'unauthenticated', + UNAUTHORIZED = 'unauthorized', + UNAUTHORIZED_APP = 'unauthorized-app', + RETRY_LIMIT_EXCEEDED = 'retry-limit-exceeded', + INVALID_CHECKSUM = 'invalid-checksum', + CANCELED = 'canceled', + INVALID_EVENT_NAME = 'invalid-event-name', + INVALID_URL = 'invalid-url', + INVALID_DEFAULT_BUCKET = 'invalid-default-bucket', + NO_DEFAULT_BUCKET = 'no-default-bucket', + CANNOT_SLICE_BLOB = 'cannot-slice-blob', + SERVER_FILE_WRONG_SIZE = 'server-file-wrong-size', + NO_DOWNLOAD_URL = 'no-download-url', + INVALID_ARGUMENT = 'invalid-argument', + INVALID_ARGUMENT_COUNT = 'invalid-argument-count', + APP_DELETED = 'app-deleted', + INVALID_ROOT_OPERATION = 'invalid-root-operation', + INVALID_FORMAT = 'invalid-format', + INTERNAL_ERROR = 'internal-error', + UNSUPPORTED_ENVIRONMENT = 'unsupported-environment' +} +/** + * A stream observer for Firebase Storage. + * @public + */ +export declare interface StorageObserver { + next?: NextFn | null; + error?: (error: StorageError) => void | null; + complete?: CompleteFn | null; +} +/** + * Represents a reference to a Google Cloud Storage object. Developers can + * upload, download, and delete objects, as well as get/set object metadata. + * @public + */ +export declare interface StorageReference { + /** + * Returns a gs:// URL for this object in the form + * `gs://///` + * @returns The gs:// URL. + */ + toString(): string; + /** + * A reference to the root of this object's bucket. + */ + root: StorageReference; + /** + * The name of the bucket containing this reference's object. + */ + bucket: string; + /** + * The full path of this object. + */ + fullPath: string; + /** + * The short name of this object, which is the last component of the full path. + * For example, if fullPath is 'full/path/image.png', name is 'image.png'. + */ + name: string; + /** + * The {@link FirebaseStorage} instance associated with this reference. + */ + storage: FirebaseStorage; + /** + * A reference pointing to the parent location of this reference, or null if + * this reference is the root. + */ + parent: StorageReference | null; +} +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An enumeration of the possible string formats for upload. + * @public + */ +export declare type StringFormat = + (typeof StringFormat)[keyof typeof StringFormat]; +/** + * An enumeration of the possible string formats for upload. + * @public + */ +export declare const StringFormat: { + /** + * Indicates the string should be interpreted "raw", that is, as normal text. + * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte + * sequence. + * Example: The string 'Hello! \\ud83d\\ude0a' becomes the byte sequence + * 48 65 6c 6c 6f 21 20 f0 9f 98 8a + */ + readonly RAW: 'raw'; + /** + * Indicates the string should be interpreted as base64-encoded data. + * Padding characters (trailing '='s) are optional. + * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence + * ad 69 8e fb e1 3a b7 bf eb 97 + */ + readonly BASE64: 'base64'; + /** + * Indicates the string should be interpreted as base64url-encoded data. + * Padding characters (trailing '='s) are optional. + * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence + * ad 69 8e fb e1 3a b7 bf eb 97 + */ + readonly BASE64URL: 'base64url'; + /** + * Indicates the string is a data URL, such as one obtained from + * canvas.toDataURL(). + * Example: the string 'data:application/octet-stream;base64,aaaa' + * becomes the byte sequence + * 69 a6 9a + * (the content-type "application/octet-stream" is also applied, but can + * be overridden in the metadata object). + */ + readonly DATA_URL: 'data_url'; +}; +/** + * An event that is triggered on a task. + * @public + */ +export declare type TaskEvent = 'state_changed'; +/* Excluded from this release type: _TaskEvent */ +/** + * Represents the current state of a running upload. + * @public + */ +export declare type TaskState = + | 'running' + | 'paused' + | 'success' + | 'canceled' + | 'error'; +/** + * Updates the metadata for this object. + * @public + * @param ref - {@link StorageReference} to update metadata for. + * @param metadata - The new metadata for the object. + * Only values that have been explicitly set will be changed. Explicitly + * setting a value to null will remove the metadata. + * @returns A `Promise` that resolves with the new metadata for this object. + */ +export declare function updateMetadata( + ref: StorageReference, + metadata: SettableMetadata +): Promise; +/** + * Uploads data to this object's location. + * The upload is not resumable. + * @public + * @param ref - {@link StorageReference} where data should be uploaded. + * @param data - The data to upload. + * @param metadata - Metadata for the data to upload. + * @returns A Promise containing an UploadResult + */ +export declare function uploadBytes( + ref: StorageReference, + data: Blob | Uint8Array | ArrayBuffer, + metadata?: UploadMetadata +): Promise; +/** + * Uploads data to this object's location. + * The upload can be paused and resumed, and exposes progress updates. + * @public + * @param ref - {@link StorageReference} where data should be uploaded. + * @param data - The data to upload. + * @param metadata - Metadata for the data to upload. + * @returns An UploadTask + */ +export declare function uploadBytesResumable( + ref: StorageReference, + data: Blob | Uint8Array | ArrayBuffer, + metadata?: UploadMetadata +): UploadTask; +/** + * Object metadata that can be set at upload. + * @public + */ +export declare interface UploadMetadata extends SettableMetadata { + /** + * A Base64-encoded MD5 hash of the object being uploaded. + */ + md5Hash?: string | undefined; +} +/** + * Result returned from a non-resumable upload. + * @public + */ +export declare interface UploadResult { + /** + * Contains the metadata sent back from the server. + */ + readonly metadata: FullMetadata; + /** + * The reference that spawned this upload. + */ + readonly ref: StorageReference; +} +/** + * Uploads a string to this object's location. + * The upload is not resumable. + * @public + * @param ref - {@link StorageReference} where string should be uploaded. + * @param value - The string to upload. + * @param format - The format of the string to upload. + * @param metadata - Metadata for the string to upload. + * @returns A Promise containing an UploadResult + */ +export declare function uploadString( + ref: StorageReference, + value: string, + format?: StringFormat, + metadata?: UploadMetadata +): Promise; +/** + * Represents the process of uploading an object. Allows you to monitor and + * manage the upload. + * @public + */ +export declare interface UploadTask { + /** + * Cancels a running task. Has no effect on a complete or failed task. + * @returns True if the cancel had an effect. + */ + cancel(): boolean; + /** + * Equivalent to calling `then(null, onRejected)`. + */ + catch(onRejected: (error: StorageError) => unknown): Promise; + /** + * Listens for events on this task. + * + * Events have three callback functions (referred to as `next`, `error`, and + * `complete`). + * + * If only the event is passed, a function that can be used to register the + * callbacks is returned. Otherwise, the callbacks are passed after the event. + * + * Callbacks can be passed either as three separate arguments or as the + * `next`, `error`, and `complete` properties of an object. Any of the three + * callbacks is optional, as long as at least one is specified. In addition, + * when you add your callbacks, you get a function back. You can call this + * function to unregister the associated callbacks. + * + * @example **Pass callbacks separately or in an object.** + * ```javascript + * var next = function(snapshot) {}; + * var error = function(error) {}; + * var complete = function() {}; + * + * // The first example. + * uploadTask.on( + * firebase.storage.TaskEvent.STATE_CHANGED, + * next, + * error, + * complete); + * + * // This is equivalent to the first example. + * uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, { + * 'next': next, + * 'error': error, + * 'complete': complete + * }); + * + * // This is equivalent to the first example. + * var subscribe = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED); + * subscribe(next, error, complete); + * + * // This is equivalent to the first example. + * var subscribe = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED); + * subscribe({ + * 'next': next, + * 'error': error, + * 'complete': complete + * }); + * ``` + * + * @example **Any callback is optional.** + * ```javascript + * // Just listening for completion, this is legal. + * uploadTask.on( + * firebase.storage.TaskEvent.STATE_CHANGED, + * null, + * null, + * function() { + * console.log('upload complete!'); + * }); + * + * // Just listening for progress/state changes, this is legal. + * uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, function(snapshot) { + * var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100; + * console.log(percent + "% done"); + * }); + * + * // This is also legal. + * uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, { + * 'complete': function() { + * console.log('upload complete!'); + * } + * }); + * ``` + * + * @example **Use the returned function to remove callbacks.** + * ```javascript + * var unsubscribe = uploadTask.on( + * firebase.storage.TaskEvent.STATE_CHANGED, + * function(snapshot) { + * var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100; + * console.log(percent + "% done"); + * // Stop after receiving one update. + * unsubscribe(); + * }); + * + * // This code is equivalent to the above. + * var handle = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED); + * unsubscribe = handle(function(snapshot) { + * var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100; + * console.log(percent + "% done"); + * // Stop after receiving one update. + * unsubscribe(); + * }); + * ``` + * + * @param event - The type of event to listen for. + * @param nextOrObserver - + * The `next` function, which gets called for each item in + * the event stream, or an observer object with some or all of these three + * properties (`next`, `error`, `complete`). + * @param error - A function that gets called with a `StorageError` + * if the event stream ends due to an error. + * @param completed - A function that gets called if the + * event stream ends normally. + * @returns + * If only the event argument is passed, returns a function you can use to + * add callbacks (see the examples above). If more than just the event + * argument is passed, returns a function you can call to unregister the + * callbacks. + */ + on( + event: TaskEvent, + nextOrObserver?: + | StorageObserver + | null + | ((snapshot: UploadTaskSnapshot) => unknown), + error?: ((a: StorageError) => unknown) | null, + complete?: Unsubscribe | null + ): Unsubscribe | Subscribe; + /** + * Pauses a currently running task. Has no effect on a paused or failed task. + * @returns True if the operation took effect, false if ignored. + */ + pause(): boolean; + /** + * Resumes a paused task. Has no effect on a currently running or failed task. + * @returns True if the operation took effect, false if ignored. + */ + resume(): boolean; + /** + * A snapshot of the current task state. + */ + snapshot: UploadTaskSnapshot; + /** + * This object behaves like a Promise, and resolves with its snapshot data + * when the upload completes. + * @param onFulfilled - The fulfillment callback. Promise chaining works as normal. + * @param onRejected - The rejection callback. + */ + then( + onFulfilled?: ((snapshot: UploadTaskSnapshot) => unknown) | null, + onRejected?: ((error: StorageError) => unknown) | null + ): Promise; +} +/* Excluded from this release type: _UploadTask */ +/** + * Holds data about the current state of the upload task. + * @public + */ +export declare interface UploadTaskSnapshot { + /** + * The number of bytes that have been successfully uploaded so far. + */ + bytesTransferred: number; + /** + * Before the upload completes, contains the metadata sent to the server. + * After the upload completes, contains the metadata sent back from the server. + */ + metadata: FullMetadata; + /** + * The reference that spawned this snapshot's upload task. + */ + ref: StorageReference; + /** + * The current state of the task. + */ + state: TaskState; + /** + * The task of which this is a snapshot. + */ + task: UploadTask; + /** + * The total number of bytes to be uploaded. + */ + totalBytes: number; +} +export {}; diff --git a/repo-scripts/prune-dts/prune-dts.test.ts b/repo-scripts/prune-dts/prune-dts.test.ts index ba770e43cd9..0e08de0078f 100644 --- a/repo-scripts/prune-dts/prune-dts.test.ts +++ b/repo-scripts/prune-dts/prune-dts.test.ts @@ -23,7 +23,7 @@ import { expect } from 'chai'; import { describe, it } from 'mocha'; import { pruneDts } from './prune-dts'; -const testCasesDir = path.resolve(__dirname, 'tests'); +const testCasesDir = path.resolve(__dirname, 'new-tests'); const tmpDir = os.tmpdir(); const testDataFilter = /(.*).input.d.ts/; diff --git a/repo-scripts/prune-dts/prune-dts.ts b/repo-scripts/prune-dts/prune-dts.ts index dfd83a62a91..acd132623fe 100644 --- a/repo-scripts/prune-dts/prune-dts.ts +++ b/repo-scripts/prune-dts/prune-dts.ts @@ -19,6 +19,7 @@ import * as yargs from 'yargs'; import * as ts from 'typescript'; import * as fs from 'fs'; import { ESLint } from 'eslint'; +import { assert } from 'console'; /** * Prunes a DTS file based on three main rules: @@ -155,16 +156,19 @@ function maybeHideConstructor( ?.find(t => t.tagName.escapedText === 'hideconstructor'); if (hideConstructorTag) { - const modifier = ts.createModifier( + assert( + !ts.canHaveDecorators(node), + 'Constructor should not have decorators' + ); + const hideConstructorModifier = ts.factory.createModifier( hideConstructorTag.comment === 'protected' ? ts.SyntaxKind.ProtectedKeyword : ts.SyntaxKind.PrivateKeyword ); - return ts.createConstructor( - node.decorators, - [modifier], - /*parameters=*/ [], - /* body= */ undefined + return ts.factory.createConstructorDeclaration( + [...(ts.getModifiers(node) ?? []), hideConstructorModifier], + [], + undefined ); } else { return node; @@ -192,7 +196,6 @@ function maybeHideConstructor( function prunePrivateImports< T extends ts.InterfaceDeclaration | ts.ClassDeclaration >( - factory: ts.NodeFactory, program: ts.Program, host: ts.CompilerHost, sourceFile: ts.SourceFile, @@ -204,8 +207,8 @@ function prunePrivateImports< const prunedHeritageClauses: ts.HeritageClause[] = []; // Additional members that are copied from the private symbols into the public // symbols - const additionalMembers: ts.Node[] = []; - + const inheritedInterfaceProperties: ts.TypeElement[] = []; + const inheritedClassMembers: ts.ClassElement[] = []; for (const heritageClause of node.heritageClauses || []) { const exportedTypes: ts.ExpressionWithTypeArguments[] = []; for (const type of heritageClause.types) { @@ -217,53 +220,53 @@ function prunePrivateImports< } else { // Hide the type we are inheriting from and merge its declarations // into the current class. - // TODO: We really only need to do this when the type that is extended - // is a class. We should skip this for interfaces. const privateType = typeChecker.getTypeAtLocation(type); - additionalMembers.push( - ...convertPropertiesForEnclosingClass( - program, - host, - sourceFile, - privateType.getProperties(), - node - ) - ); + if (ts.isClassDeclaration(node)) { + inheritedClassMembers.push( + ...convertPropertiesForEnclosingDeclaration< + ts.ClassDeclaration, + ts.ClassElement + >(program, host, sourceFile, privateType.getProperties(), node) + ); + } else if (ts.isInterfaceDeclaration(node)) { + inheritedInterfaceProperties.push( + ...convertPropertiesForEnclosingDeclaration< + ts.InterfaceDeclaration, + ts.TypeElement + >(program, host, sourceFile, privateType.getProperties(), node) + ); + } } } if (exportedTypes.length > 0) { prunedHeritageClauses.push( - factory.updateHeritageClause(heritageClause, exportedTypes) + ts.factory.updateHeritageClause(heritageClause, exportedTypes) ); } } if (ts.isClassDeclaration(node)) { - return factory.updateClassDeclaration( + const modifiersAndDecorators = [ + ...(ts.getModifiers(node) ?? []), + ...(ts.getDecorators(node) ?? []) + ]; + return ts.factory.updateClassDeclaration( node, - node.decorators, - node.modifiers, + modifiersAndDecorators, node.name, node.typeParameters, prunedHeritageClauses, - [ - ...(node.members as ts.NodeArray), - ...(additionalMembers as ts.ClassElement[]) - ] + [...node.members, ...inheritedClassMembers] ) as T; } else if (ts.isInterfaceDeclaration(node)) { - return factory.updateInterfaceDeclaration( + return ts.factory.updateInterfaceDeclaration( node, - node.decorators, node.modifiers, node.name, node.typeParameters, prunedHeritageClauses, - [ - ...(node.members as ts.NodeArray), - ...(additionalMembers as ts.TypeElement[]) - ] + [...node.members, ...inheritedInterfaceProperties] ) as T; } else { throw new Error('Only classes or interfaces are supported'); @@ -271,7 +274,7 @@ function prunePrivateImports< } /** - * Iterates the provided symbols and returns named declarations for these + * Iterates over the provided symbols and returns named declarations for these * symbols if they are missing from `currentClass`. This allows us to merge * class hierarchies for classes whose inherited types are not part of the * public API. @@ -283,9 +286,9 @@ function convertPropertiesForEnclosingClass( host: ts.CompilerHost, sourceFile: ts.SourceFile, parentClassSymbols: ts.Symbol[], - currentClass: ts.ClassDeclaration | ts.InterfaceDeclaration -): ts.Node[] { - const newMembers: ts.Node[] = []; + currentClass: ts.ClassDeclaration +): ts.ClassElement[] { + const newMembers: ts.ClassElement[] = []; // The `codefix` package is not public but it does exactly what we want. It's // the same package that is used by VSCode to fill in missing members, which // is what we are using it for in this script. `codefix` handles missing @@ -304,12 +307,78 @@ function convertPropertiesForEnclosingClass( symbol.escapedName == (missingMember.name as ts.Identifier).escapedText ); - const jsDocComment = originalSymbol - ? extractJSDocComment(originalSymbol, newMembers) - : undefined; - if (jsDocComment) { - newMembers.push(jsDocComment, missingMember); - } else { + if (originalSymbol) { + const jsDocComment = extractJSDocComment(originalSymbol, newMembers); + if (jsDocComment) { + ts.setSyntheticLeadingComments(missingMember, [ + { + kind: ts.SyntaxKind.MultiLineCommentTrivia, + text: `*\n${jsDocComment}\n`, + hasTrailingNewLine: true, + pos: -1, + end: -1 + } + ]); + } + + newMembers.push(missingMember); + } + } + ); + return newMembers; +} + +/** + * Iterates over the provided symbols and returns named declarations for these + * symbols if they are missing from `currentInterface`. This allows us to merge + * interface hierarchies for interfaces whose inherited properties are not part of the + * public API. + * + * This method relies on a private API in TypeScript's `codefix` package. + */ +function convertPropertiesForEnclosingDeclaration< + T extends ts.ClassDeclaration | ts.InterfaceDeclaration, + U extends ts.ClassElement | ts.TypeElement +>( + program: ts.Program, + host: ts.CompilerHost, + sourceFile: ts.SourceFile, + parentClassSymbols: ts.Symbol[], + currentDeclaration: T +): U[] { + const newMembers: U[] = []; + // The `codefix` package is not public but it does exactly what we want. It's + // the same package that is used by VSCode to fill in missing members, which + // is what we are using it for in this script. `codefix` handles missing + // properties, methods and correctly deduces generics. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (ts as any).codefix.createMissingMemberNodes( + currentDeclaration, + parentClassSymbols, + sourceFile, + { program, host }, + /* userPreferences= */ {}, + /* importAdder= */ undefined, + (missingMember: U) => { + const originalSymbol = parentClassSymbols.find( + symbol => + symbol.escapedName == + (missingMember.name as ts.Identifier).escapedText + ); + if (originalSymbol) { + const jsDocComment = extractJSDocComment(originalSymbol, newMembers); + if (jsDocComment) { + ts.setSyntheticLeadingComments(missingMember, [ + { + kind: ts.SyntaxKind.MultiLineCommentTrivia, + text: `*\n${jsDocComment}\n`, + hasTrailingNewLine: true, + pos: -1, + end: -1 + } + ]); + } + newMembers.push(missingMember); } } @@ -321,7 +390,7 @@ function convertPropertiesForEnclosingClass( function extractJSDocComment( symbol: ts.Symbol, alreadyAddedMembers: ts.Node[] -): ts.Node | null { +): string | null { const overloadCount = alreadyAddedMembers.filter( node => ts.isClassElement(node) && @@ -330,37 +399,69 @@ function extractJSDocComment( // Extract the comment from the overload that we are currently processing. let targetIndex = 0; - const comments = symbol.getDocumentationComment(undefined).filter(symbol => { - // Overload comments are separated by line breaks. - if (symbol.kind == 'lineBreak') { - ++targetIndex; - return false; - } else { - return overloadCount == targetIndex; - } - }); + const commentParts = symbol + .getDocumentationComment(undefined) + .filter(symbol => { + // Overload comments are separated by line breaks. + if (symbol.kind == 'lineBreak') { + ++targetIndex; + return false; + } else { + return overloadCount == targetIndex; + } + }); + + const comment = commentParts + .map(commentPart => { + if (commentPart.kind === 'linkText') { + /** + * Some links will be spread across more than one line. For example: + * {@link + * DocumentReference} + * In this case, we want to remove the leading ' * ' without removing the newline. + */ + const leadingStar = /(?!\n)\s*\* /; + /** + * For some reason, this text will also have a trailing space (the above example would give + * us 'DocumentReference '), so we trim that from the end of the string. + */ + const trailingSpaces = / *$/; + + return commentPart.text + .replace(leadingStar, '\n') + .replace(trailingSpaces, ''); + } else { + return commentPart.text; + } + }) + .join(''); - if (comments.length > 0 && symbol.declarations) { - const jsDocTags = ts.getJSDocTags(symbol.declarations[overloadCount]); - const maybeNewline = jsDocTags?.length > 0 ? '\n' : ''; - const joinedComments = comments - .map(comment => { - if (comment.kind === 'linkText') { - return comment.text.trim(); - } - return comment.text; - }) - .join(''); - const formattedComments = joinedComments - .replace('*', '\n') - .replace(' \n', '\n') - .replace('\n ', '\n'); - return ts.factory.createJSDocComment( - formattedComments + maybeNewline, - jsDocTags - ); + if (!comment || !symbol.declarations) { + return null; } - return null; + + const declaration = symbol.declarations[overloadCount]; + const jsDocTags = ts + .getJSDocTags(declaration) + .map(tag => + tag + .getFullText() + .split('\n') + .map(line => line.replace('*', '').trim()) + .filter(line => line !== '') // Remove empty lines + .map(text => text.replace(/s*\* /, '')) // Remove the '*' prefix from all lines + .join('\n') + ) + .join('\n'); + const maybeNewline = jsDocTags?.length > 0 ? '\n' : ''; + + const commentAndTags = `${comment}\n${maybeNewline}${jsDocTags}`.trim(); + const formattedJSDocComment = commentAndTags + .split('\n') + .map(line => ` * ${line.trim()}`) + .join('\n'); + + return formattedJSDocComment; } /** @@ -468,7 +569,7 @@ function dropPrivateApiTransformer( context: ts.TransformationContext ): ts.Transformer { const typeChecker = program.getTypeChecker(); - const { factory } = context; + // const { factory } = context; return (sourceFile: ts.SourceFile) => { function visit(node: ts.Node): ts.Node { @@ -483,9 +584,11 @@ function dropPrivateApiTransformer( ) { // Remove any types that are not exported. if ( - !node.modifiers?.find(m => m.kind === ts.SyntaxKind.ExportKeyword) + !ts + .getModifiers(node) + ?.find(m => m.kind === ts.SyntaxKind.ExportKeyword) ) { - return factory.createNotEmittedStatement(node); + return ts.factory.createNotEmittedStatement(node); } } @@ -498,7 +601,7 @@ function dropPrivateApiTransformer( ) { // Remove any imports that reference internal APIs, while retaining // their public members. - return prunePrivateImports(factory, program, host, sourceFile, node); + return prunePrivateImports(program, host, sourceFile, node); } else if ( ts.isPropertyDeclaration(node) || ts.isMethodDeclaration(node) || @@ -507,7 +610,9 @@ function dropPrivateApiTransformer( // Remove any class and interface members that are prefixed with // underscores. if (hasPrivatePrefix(node.name as ts.Identifier)) { - return factory.createNotEmittedStatement(node); + const notEmittedStatement = + ts.factory.createNotEmittedStatement(node); + return notEmittedStatement; } } else if (ts.isTypeReferenceNode(node)) { // For public types that refer internal types, find a public type that @@ -518,9 +623,9 @@ function dropPrivateApiTransformer( node.typeName ); return publicName - ? factory.updateTypeReferenceNode( + ? ts.factory.updateTypeReferenceNode( node, - factory.createIdentifier(publicName.name), + ts.factory.createIdentifier(publicName.name), node.typeArguments ) : node; diff --git a/repo-scripts/prune-dts/subtests/app.input.d.ts b/repo-scripts/prune-dts/subtests/app.input.d.ts new file mode 100644 index 00000000000..a0181b92462 --- /dev/null +++ b/repo-scripts/prune-dts/subtests/app.input.d.ts @@ -0,0 +1,576 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Firebase App + * + * @remarks This package coordinates the communication between the different Firebase components + * @packageDocumentation + */ + +import { Component } from '@firebase/component'; +import { ComponentContainer } from '@firebase/component'; +import { FirebaseError } from '@firebase/util'; +import { LogCallback } from '@firebase/logger'; +import { LogLevelString } from '@firebase/logger'; +import { LogOptions } from '@firebase/logger'; +import { Name } from '@firebase/component'; +import { Provider } from '@firebase/component'; + +/** + * @param component - the component being added to this app's container + * + * @internal + */ +export declare function _addComponent( + app: FirebaseApp, + component: Component +): void; + +/** + * + * @internal + */ +export declare function _addOrOverwriteComponent( + app: FirebaseApp, + component: Component +): void; + +/** + * @internal + */ +export declare const _apps: Map; + +/** + * Test only + * + * @internal + */ +export declare function _clearComponents(): void; + +/** + * Registered components. + * + * @internal + */ +export declare const _components: Map>; + +/** + * The default app name + * + * @internal + */ +export declare const _DEFAULT_ENTRY_NAME = '[DEFAULT]'; + +/** + * Renders this app unusable and frees the resources of all associated + * services. + * + * @example + * ```javascript + * deleteApp(app) + * .then(function() { + * console.log("App deleted successfully"); + * }) + * .catch(function(error) { + * console.log("Error deleting app:", error); + * }); + * ``` + * + * @public + */ +export declare function deleteApp(app: FirebaseApp): Promise; + +/** + * A {@link @firebase/app#FirebaseApp} holds the initialization information for a collection of + * services. + * + * Do not call this constructor directly. Instead, use + * {@link (initializeApp:1) | initializeApp()} to create an app. + * + * @public + */ +export declare interface FirebaseApp { + /** + * The (read-only) name for this app. + * + * The default app's name is `"[DEFAULT]"`. + * + * @example + * ```javascript + * // The default app's name is "[DEFAULT]" + * const app = initializeApp(defaultAppConfig); + * console.log(app.name); // "[DEFAULT]" + * ``` + * + * @example + * ```javascript + * // A named app's name is what you provide to initializeApp() + * const otherApp = initializeApp(otherAppConfig, "other"); + * console.log(otherApp.name); // "other" + * ``` + */ + readonly name: string; + /** + * The (read-only) configuration options for this app. These are the original + * parameters given in {@link (initializeApp:1) | initializeApp()}. + * + * @example + * ```javascript + * const app = initializeApp(config); + * console.log(app.options.databaseURL === config.databaseURL); // true + * ``` + */ + readonly options: FirebaseOptions; + /** + * The settable config flag for GDPR opt-in/opt-out + */ + automaticDataCollectionEnabled: boolean; +} + +/** + * @internal + */ +export declare interface _FirebaseAppInternal extends FirebaseApp { + container: ComponentContainer; + isDeleted: boolean; + checkDestroyed(): void; +} + +/** + * @public + * + * Configuration options given to {@link (initializeApp:1) | initializeApp()} + */ +export declare interface FirebaseAppSettings { + /** + * custom name for the Firebase App. + * The default value is `"[DEFAULT]"`. + */ + name?: string; + /** + * The settable config flag for GDPR opt-in/opt-out + */ + automaticDataCollectionEnabled?: boolean; +} +export { FirebaseError }; + +/** + * @public + * + * Firebase configuration object. Contains a set of parameters required by + * services in order to successfully communicate with Firebase server APIs + * and to associate client data with your Firebase project and + * Firebase application. Typically this object is populated by the Firebase + * console at project setup. See also: + * {@link https://firebase.google.com/docs/web/setup#config-object | Learn about the Firebase config object}. + */ +export declare interface FirebaseOptions { + /** + * An encrypted string used when calling certain APIs that don't need to + * access private user data + * (example value: `AIzaSyDOCAbC123dEf456GhI789jKl012-MnO`). + */ + apiKey?: string; + /** + * Auth domain for the project ID. + */ + authDomain?: string; + /** + * Default Realtime Database URL. + */ + databaseURL?: string; + /** + * The unique identifier for the project across all of Firebase and + * Google Cloud. + */ + projectId?: string; + /** + * The default Cloud Storage bucket name. + */ + storageBucket?: string; + /** + * Unique numerical value used to identify each sender that can send + * Firebase Cloud Messaging messages to client apps. + */ + messagingSenderId?: string; + /** + * Unique identifier for the app. + */ + appId?: string; + /** + * An ID automatically created when you enable Analytics in your + * Firebase project and register a web app. In versions 7.20.0 + * and higher, this parameter is optional. + */ + measurementId?: string; +} + +/** + * A {@link @firebase/app#FirebaseServerApp} holds the initialization information + * for a collection of services running in server environments. + * + * Do not call this constructor directly. Instead, use + * {@link (initializeServerApp:1) | initializeServerApp()} to create + * an app. + * + * @public + */ +export declare interface FirebaseServerApp extends FirebaseApp { + /** + * There is no `getApp()` operation for `FirebaseServerApp`, so the name is not relevant for + * applications. However, it may be used internally, and is declared here so that + * `FirebaseServerApp` conforms to the `FirebaseApp` interface. + */ + name: string; + /** + * The (read-only) configuration settings for this server app. These are the original + * parameters given in {@link (initializeServerApp:1) | initializeServerApp()}. + * + * @example + * ```javascript + * const app = initializeServerApp(settings); + * console.log(app.settings.authIdToken === options.authIdToken); // true + * ``` + */ + readonly settings: FirebaseServerAppSettings; +} + +/** + * @public + * + * Configuration options given to {@link (initializeServerApp:1) | initializeServerApp()} + */ +export declare interface FirebaseServerAppSettings + extends Omit { + /** + * An optional Auth ID token used to resume a signed in user session from a client + * runtime environment. + * + * Invoking `getAuth` with a `FirebaseServerApp` configured with a validated `authIdToken` + * causes an automatic attempt to sign in the user that the `authIdToken` represents. The token + * needs to have been recently minted for this operation to succeed. + * + * If the token fails local verification, or if the Auth service has failed to validate it when + * the Auth SDK is initialized, then a warning is logged to the console and the Auth SDK will not + * sign in a user on initialization. + * + * If a user is successfully signed in, then the Auth instance's `onAuthStateChanged` callback + * is invoked with the `User` object as per standard Auth flows. However, `User` objects + * created via an `authIdToken` do not have a refresh token. Attempted `refreshToken` + * operations fail. + */ + authIdToken?: string; + /** + * An optional object. If provided, the Firebase SDK uses a `FinalizationRegistry` + * object to monitor the garbage collection status of the provided object. The + * Firebase SDK releases its reference on the `FirebaseServerApp` instance when the + * provided `releaseOnDeref` object is garbage collected. + * + * You can use this field to reduce memory management overhead for your application. + * If provided, an app running in a SSR pass does not need to perform + * `FirebaseServerApp` cleanup, so long as the reference object is deleted (by falling out of + * SSR scope, for instance.) + * + * If an object is not provided then the application must clean up the `FirebaseServerApp` + * instance by invoking `deleteApp`. + * + * If the application provides an object in this parameter, but the application is + * executed in a JavaScript engine that predates the support of `FinalizationRegistry` + * (introduced in node v14.6.0, for instance), then an error is thrown at `FirebaseServerApp` + * initialization. + */ + releaseOnDeref?: object; +} + +/** + * @internal + */ +export declare interface _FirebaseService { + app: FirebaseApp; + /** + * Delete the service and free it's resources - called from + * {@link @firebase/app#deleteApp | deleteApp()} + */ + _delete(): Promise; +} + +/** + * Retrieves a {@link @firebase/app#FirebaseApp} instance. + * + * When called with no arguments, the default app is returned. When an app name + * is provided, the app corresponding to that name is returned. + * + * An exception is thrown if the app being retrieved has not yet been + * initialized. + * + * @example + * ```javascript + * // Return the default app + * const app = getApp(); + * ``` + * + * @example + * ```javascript + * // Return a named app + * const otherApp = getApp("otherApp"); + * ``` + * + * @param name - Optional name of the app to return. If no name is + * provided, the default is `"[DEFAULT]"`. + * + * @returns The app corresponding to the provided app name. + * If no app name is provided, the default app is returned. + * + * @public + */ +export declare function getApp(name?: string): FirebaseApp; + +/** + * A (read-only) array of all initialized apps. + * @public + */ +export declare function getApps(): FirebaseApp[]; + +/** + * + * @param app - FirebaseApp instance + * @param name - service name + * + * @returns the provider for the service with the matching name + * + * @internal + */ +export declare function _getProvider( + app: FirebaseApp, + name: T +): Provider; + +/** + * Creates and initializes a {@link @firebase/app#FirebaseApp} instance. + * + * See + * {@link + * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app + * | Add Firebase to your app} and + * {@link + * https://firebase.google.com/docs/web/setup#multiple-projects + * | Initialize multiple projects} for detailed documentation. + * + * @example + * ```javascript + * + * // Initialize default app + * // Retrieve your own options values by adding a web app on + * // https://console.firebase.google.com + * initializeApp({ + * apiKey: "AIza....", // Auth / General Use + * authDomain: "YOUR_APP.firebaseapp.com", // Auth with popup/redirect + * databaseURL: "https://YOUR_APP.firebaseio.com", // Realtime Database + * storageBucket: "YOUR_APP.appspot.com", // Storage + * messagingSenderId: "123456789" // Cloud Messaging + * }); + * ``` + * + * @example + * ```javascript + * + * // Initialize another app + * const otherApp = initializeApp({ + * databaseURL: "https://.firebaseio.com", + * storageBucket: ".appspot.com" + * }, "otherApp"); + * ``` + * + * @param options - Options to configure the app's services. + * @param name - Optional name of the app to initialize. If no name + * is provided, the default is `"[DEFAULT]"`. + * + * @returns The initialized app. + * + * @public + */ +export declare function initializeApp( + options: FirebaseOptions, + name?: string +): FirebaseApp; + +/** + * Creates and initializes a FirebaseApp instance. + * + * @param options - Options to configure the app's services. + * @param config - FirebaseApp Configuration + * + * @public + */ +export declare function initializeApp( + options: FirebaseOptions, + config?: FirebaseAppSettings +): FirebaseApp; + +/** + * Creates and initializes a FirebaseApp instance. + * + * @public + */ +export declare function initializeApp(): FirebaseApp; + +/** + * Creates and initializes a {@link @firebase/app#FirebaseServerApp} instance. + * + * The `FirebaseServerApp` is similar to `FirebaseApp`, but is intended for execution in + * server side rendering environments only. Initialization will fail if invoked from a + * browser environment. + * + * See + * {@link + * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app + * | Add Firebase to your app} and + * {@link + * https://firebase.google.com/docs/web/setup#multiple-projects + * | Initialize multiple projects} for detailed documentation. + * + * @example + * ```javascript + * + * // Initialize an instance of `FirebaseServerApp`. + * // Retrieve your own options values by adding a web app on + * // https://console.firebase.google.com + * initializeServerApp({ + * apiKey: "AIza....", // Auth / General Use + * authDomain: "YOUR_APP.firebaseapp.com", // Auth with popup/redirect + * databaseURL: "https://YOUR_APP.firebaseio.com", // Realtime Database + * storageBucket: "YOUR_APP.appspot.com", // Storage + * messagingSenderId: "123456789" // Cloud Messaging + * }, + * { + * authIdToken: "Your Auth ID Token" + * }); + * ``` + * + * @param options - `Firebase.AppOptions` to configure the app's services, or a + * a `FirebaseApp` instance which contains the `AppOptions` within. + * @param config - `FirebaseServerApp` configuration. + * + * @returns The initialized `FirebaseServerApp`. + * + * @public + */ +export declare function initializeServerApp( + options: FirebaseOptions | FirebaseApp, + config: FirebaseServerAppSettings +): FirebaseServerApp; + +/** + * + * @param obj - an object of type FirebaseApp or FirebaseOptions. + * + * @returns true if the provide object is of type FirebaseApp. + * + * @internal + */ +export declare function _isFirebaseApp( + obj: FirebaseApp | FirebaseOptions +): obj is FirebaseApp; + +/** + * + * @param obj - an object of type FirebaseApp. + * + * @returns true if the provided object is of type FirebaseServerAppImpl. + * + * @internal + */ +export declare function _isFirebaseServerApp( + obj: FirebaseApp | FirebaseServerApp +): obj is FirebaseServerApp; + +/** + * Sets log handler for all Firebase SDKs. + * @param logCallback - An optional custom log handler that executes user code whenever + * the Firebase SDK makes a logging call. + * + * @public + */ +export declare function onLog( + logCallback: LogCallback | null, + options?: LogOptions +): void; + +/** + * + * @param component - the component to register + * @returns whether or not the component is registered successfully + * + * @internal + */ +export declare function _registerComponent( + component: Component +): boolean; + +/** + * Registers a library's name and version for platform logging purposes. + * @param library - Name of 1p or 3p library (e.g. firestore, angularfire) + * @param version - Current version of that library. + * @param variant - Bundle variant, e.g., node, rn, etc. + * + * @public + */ +export declare function registerVersion( + libraryKeyOrName: string, + version: string, + variant?: string +): void; + +/** + * + * @param app - FirebaseApp instance + * @param name - service name + * @param instanceIdentifier - service instance identifier in case the service supports multiple instances + * + * @internal + */ +export declare function _removeServiceInstance( + app: FirebaseApp, + name: T, + instanceIdentifier?: string +): void; + +/** + * The current SDK version. + * + * @public + */ +export declare const SDK_VERSION: string; + +/** + * @internal + */ +export declare const _serverApps: Map; + +/** + * Sets log level for all Firebase SDKs. + * + * All of the log types above the current log level are captured (i.e. if + * you set the log level to `info`, errors are logged, but `debug` and + * `verbose` logs are not). + * + * @public + */ +export declare function setLogLevel(logLevel: LogLevelString): void; + +export {}; diff --git a/repo-scripts/prune-dts/subtests/app.output.d.ts b/repo-scripts/prune-dts/subtests/app.output.d.ts new file mode 100644 index 00000000000..a988662d4bf --- /dev/null +++ b/repo-scripts/prune-dts/subtests/app.output.d.ts @@ -0,0 +1,470 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Firebase App + * + * @remarks This package coordinates the communication between the different Firebase components + * @packageDocumentation + */ + +import { Component } from '@firebase/component'; +import { ComponentContainer } from '@firebase/component'; +import { FirebaseError } from '@firebase/util'; +import { LogCallback } from '@firebase/logger'; +import { LogLevelString } from '@firebase/logger'; +import { LogOptions } from '@firebase/logger'; +import { Name } from '@firebase/component'; +import { Provider } from '@firebase/component'; + +/* Excluded from this release type: _addComponent */ + +/* Excluded from this release type: _addOrOverwriteComponent */ + +/* Excluded from this release type: _apps */ + +/* Excluded from this release type: _clearComponents */ + +/* Excluded from this release type: _components */ + +/* Excluded from this release type: _DEFAULT_ENTRY_NAME */ + +/** + * Renders this app unusable and frees the resources of all associated + * services. + * + * @example + * ```javascript + * deleteApp(app) + * .then(function() { + * console.log("App deleted successfully"); + * }) + * .catch(function(error) { + * console.log("Error deleting app:", error); + * }); + * ``` + * + * @public + */ +export declare function deleteApp(app: FirebaseApp): Promise; + +/** + * A {@link @firebase/app#FirebaseApp} holds the initialization information for a collection of + * services. + * + * Do not call this constructor directly. Instead, use + * {@link (initializeApp:1) | initializeApp()} to create an app. + * + * @public + */ +export declare interface FirebaseApp { + /** + * The (read-only) name for this app. + * + * The default app's name is `"[DEFAULT]"`. + * + * @example + * ```javascript + * // The default app's name is "[DEFAULT]" + * const app = initializeApp(defaultAppConfig); + * console.log(app.name); // "[DEFAULT]" + * ``` + * + * @example + * ```javascript + * // A named app's name is what you provide to initializeApp() + * const otherApp = initializeApp(otherAppConfig, "other"); + * console.log(otherApp.name); // "other" + * ``` + */ + readonly name: string; + /** + * The (read-only) configuration options for this app. These are the original + * parameters given in {@link (initializeApp:1) | initializeApp()}. + * + * @example + * ```javascript + * const app = initializeApp(config); + * console.log(app.options.databaseURL === config.databaseURL); // true + * ``` + */ + readonly options: FirebaseOptions; + /** + * The settable config flag for GDPR opt-in/opt-out + */ + automaticDataCollectionEnabled: boolean; +} + +/* Excluded from this release type: _FirebaseAppInternal */ + +/** + * @public + * + * Configuration options given to {@link (initializeApp:1) | initializeApp()} + */ +export declare interface FirebaseAppSettings { + /** + * custom name for the Firebase App. + * The default value is `"[DEFAULT]"`. + */ + name?: string; + /** + * The settable config flag for GDPR opt-in/opt-out + */ + automaticDataCollectionEnabled?: boolean; +} +export { FirebaseError }; + +/** + * @public + * + * Firebase configuration object. Contains a set of parameters required by + * services in order to successfully communicate with Firebase server APIs + * and to associate client data with your Firebase project and + * Firebase application. Typically this object is populated by the Firebase + * console at project setup. See also: + * {@link https://firebase.google.com/docs/web/setup#config-object | Learn about the Firebase config object}. + */ +export declare interface FirebaseOptions { + /** + * An encrypted string used when calling certain APIs that don't need to + * access private user data + * (example value: `AIzaSyDOCAbC123dEf456GhI789jKl012-MnO`). + */ + apiKey?: string; + /** + * Auth domain for the project ID. + */ + authDomain?: string; + /** + * Default Realtime Database URL. + */ + databaseURL?: string; + /** + * The unique identifier for the project across all of Firebase and + * Google Cloud. + */ + projectId?: string; + /** + * The default Cloud Storage bucket name. + */ + storageBucket?: string; + /** + * Unique numerical value used to identify each sender that can send + * Firebase Cloud Messaging messages to client apps. + */ + messagingSenderId?: string; + /** + * Unique identifier for the app. + */ + appId?: string; + /** + * An ID automatically created when you enable Analytics in your + * Firebase project and register a web app. In versions 7.20.0 + * and higher, this parameter is optional. + */ + measurementId?: string; +} + +/** + * A {@link @firebase/app#FirebaseServerApp} holds the initialization information + * for a collection of services running in server environments. + * + * Do not call this constructor directly. Instead, use + * {@link (initializeServerApp:1) | initializeServerApp()} to create + * an app. + * + * @public + */ +export declare interface FirebaseServerApp extends FirebaseApp { + /** + * There is no `getApp()` operation for `FirebaseServerApp`, so the name is not relevant for + * applications. However, it may be used internally, and is declared here so that + * `FirebaseServerApp` conforms to the `FirebaseApp` interface. + */ + name: string; + /** + * The (read-only) configuration settings for this server app. These are the original + * parameters given in {@link (initializeServerApp:1) | initializeServerApp()}. + * + * @example + * ```javascript + * const app = initializeServerApp(settings); + * console.log(app.settings.authIdToken === options.authIdToken); // true + * ``` + */ + readonly settings: FirebaseServerAppSettings; +} + +/** + * @public + * + * Configuration options given to {@link (initializeServerApp:1) | initializeServerApp()} + */ +export declare interface FirebaseServerAppSettings + extends Omit { + /** + * An optional Auth ID token used to resume a signed in user session from a client + * runtime environment. + * + * Invoking `getAuth` with a `FirebaseServerApp` configured with a validated `authIdToken` + * causes an automatic attempt to sign in the user that the `authIdToken` represents. The token + * needs to have been recently minted for this operation to succeed. + * + * If the token fails local verification, or if the Auth service has failed to validate it when + * the Auth SDK is initialized, then a warning is logged to the console and the Auth SDK will not + * sign in a user on initialization. + * + * If a user is successfully signed in, then the Auth instance's `onAuthStateChanged` callback + * is invoked with the `User` object as per standard Auth flows. However, `User` objects + * created via an `authIdToken` do not have a refresh token. Attempted `refreshToken` + * operations fail. + */ + authIdToken?: string; + /** + * An optional object. If provided, the Firebase SDK uses a `FinalizationRegistry` + * object to monitor the garbage collection status of the provided object. The + * Firebase SDK releases its reference on the `FirebaseServerApp` instance when the + * provided `releaseOnDeref` object is garbage collected. + * + * You can use this field to reduce memory management overhead for your application. + * If provided, an app running in a SSR pass does not need to perform + * `FirebaseServerApp` cleanup, so long as the reference object is deleted (by falling out of + * SSR scope, for instance.) + * + * If an object is not provided then the application must clean up the `FirebaseServerApp` + * instance by invoking `deleteApp`. + * + * If the application provides an object in this parameter, but the application is + * executed in a JavaScript engine that predates the support of `FinalizationRegistry` + * (introduced in node v14.6.0, for instance), then an error is thrown at `FirebaseServerApp` + * initialization. + */ + releaseOnDeref?: object; +} + +/* Excluded from this release type: _FirebaseService */ + +/** + * Retrieves a {@link @firebase/app#FirebaseApp} instance. + * + * When called with no arguments, the default app is returned. When an app name + * is provided, the app corresponding to that name is returned. + * + * An exception is thrown if the app being retrieved has not yet been + * initialized. + * + * @example + * ```javascript + * // Return the default app + * const app = getApp(); + * ``` + * + * @example + * ```javascript + * // Return a named app + * const otherApp = getApp("otherApp"); + * ``` + * + * @param name - Optional name of the app to return. If no name is + * provided, the default is `"[DEFAULT]"`. + * + * @returns The app corresponding to the provided app name. + * If no app name is provided, the default app is returned. + * + * @public + */ +export declare function getApp(name?: string): FirebaseApp; + +/** + * A (read-only) array of all initialized apps. + * @public + */ +export declare function getApps(): FirebaseApp[]; + +/* Excluded from this release type: _getProvider */ + +/** + * Creates and initializes a {@link @firebase/app#FirebaseApp} instance. + * + * See + * {@link + * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app + * | Add Firebase to your app} and + * {@link + * https://firebase.google.com/docs/web/setup#multiple-projects + * | Initialize multiple projects} for detailed documentation. + * + * @example + * ```javascript + * + * // Initialize default app + * // Retrieve your own options values by adding a web app on + * // https://console.firebase.google.com + * initializeApp({ + * apiKey: "AIza....", // Auth / General Use + * authDomain: "YOUR_APP.firebaseapp.com", // Auth with popup/redirect + * databaseURL: "https://YOUR_APP.firebaseio.com", // Realtime Database + * storageBucket: "YOUR_APP.appspot.com", // Storage + * messagingSenderId: "123456789" // Cloud Messaging + * }); + * ``` + * + * @example + * ```javascript + * + * // Initialize another app + * const otherApp = initializeApp({ + * databaseURL: "https://.firebaseio.com", + * storageBucket: ".appspot.com" + * }, "otherApp"); + * ``` + * + * @param options - Options to configure the app's services. + * @param name - Optional name of the app to initialize. If no name + * is provided, the default is `"[DEFAULT]"`. + * + * @returns The initialized app. + * + * @public + */ +export declare function initializeApp( + options: FirebaseOptions, + name?: string +): FirebaseApp; + +/** + * Creates and initializes a FirebaseApp instance. + * + * @param options - Options to configure the app's services. + * @param config - FirebaseApp Configuration + * + * @public + */ +export declare function initializeApp( + options: FirebaseOptions, + config?: FirebaseAppSettings +): FirebaseApp; + +/** + * Creates and initializes a FirebaseApp instance. + * + * @public + */ +export declare function initializeApp(): FirebaseApp; + +/** + * Creates and initializes a {@link @firebase/app#FirebaseServerApp} instance. + * + * The `FirebaseServerApp` is similar to `FirebaseApp`, but is intended for execution in + * server side rendering environments only. Initialization will fail if invoked from a + * browser environment. + * + * See + * {@link + * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app + * | Add Firebase to your app} and + * {@link + * https://firebase.google.com/docs/web/setup#multiple-projects + * | Initialize multiple projects} for detailed documentation. + * + * @example + * ```javascript + * + * // Initialize an instance of `FirebaseServerApp`. + * // Retrieve your own options values by adding a web app on + * // https://console.firebase.google.com + * initializeServerApp({ + * apiKey: "AIza....", // Auth / General Use + * authDomain: "YOUR_APP.firebaseapp.com", // Auth with popup/redirect + * databaseURL: "https://YOUR_APP.firebaseio.com", // Realtime Database + * storageBucket: "YOUR_APP.appspot.com", // Storage + * messagingSenderId: "123456789" // Cloud Messaging + * }, + * { + * authIdToken: "Your Auth ID Token" + * }); + * ``` + * + * @param options - `Firebase.AppOptions` to configure the app's services, or a + * a `FirebaseApp` instance which contains the `AppOptions` within. + * @param config - `FirebaseServerApp` configuration. + * + * @returns The initialized `FirebaseServerApp`. + * + * @public + */ +export declare function initializeServerApp( + options: FirebaseOptions | FirebaseApp, + config: FirebaseServerAppSettings +): FirebaseServerApp; + +/* Excluded from this release type: _isFirebaseApp */ + +/* Excluded from this release type: _isFirebaseServerApp */ + +/** + * Sets log handler for all Firebase SDKs. + * @param logCallback - An optional custom log handler that executes user code whenever + * the Firebase SDK makes a logging call. + * + * @public + */ +export declare function onLog( + logCallback: LogCallback | null, + options?: LogOptions +): void; + +/* Excluded from this release type: _registerComponent */ + +/** + * Registers a library's name and version for platform logging purposes. + * @param library - Name of 1p or 3p library (e.g. firestore, angularfire) + * @param version - Current version of that library. + * @param variant - Bundle variant, e.g., node, rn, etc. + * + * @public + */ +export declare function registerVersion( + libraryKeyOrName: string, + version: string, + variant?: string +): void; + +/* Excluded from this release type: _removeServiceInstance */ + +/** + * The current SDK version. + * + * @public + */ +export declare const SDK_VERSION: string; + +/* Excluded from this release type: _serverApps */ + +/** + * Sets log level for all Firebase SDKs. + * + * All of the log types above the current log level are captured (i.e. if + * you set the log level to `info`, errors are logged, but `debug` and + * `verbose` logs are not). + * + * @public + */ +export declare function setLogLevel(logLevel: LogLevelString): void; + +export {}; diff --git a/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts b/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts deleted file mode 100644 index 7208f2cf528..00000000000 --- a/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -declare class A { - a: T; -} -export class B extends A { - b: T; -} -export class C extends A {} -export {}; diff --git a/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts b/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts deleted file mode 100644 index 3dca92f7d56..00000000000 --- a/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -export class B { - b: T; - a: string; -} -export class C { - a: T; -} -export {}; diff --git a/repo-scripts/prune-dts/tsconfig.json b/repo-scripts/prune-dts/tsconfig.json index 236dfb5b9d8..14618a434b0 100644 --- a/repo-scripts/prune-dts/tsconfig.json +++ b/repo-scripts/prune-dts/tsconfig.json @@ -8,7 +8,8 @@ "target": "es2017", "esModuleInterop": true, "declaration": true, - "strict": true + "strict": true, + "sourceMap": true }, "exclude": ["dist/**/*"] } diff --git a/repo-scripts/size-analysis/package.json b/repo-scripts/size-analysis/package.json index b5cbfcc2eec..1023b1f4756 100644 --- a/repo-scripts/size-analysis/package.json +++ b/repo-scripts/size-analysis/package.json @@ -32,7 +32,7 @@ "child-process-promise": "2.2.1", "memfs": "3.5.3", "tmp": "0.2.1", - "typescript": "4.7.4", + "typescript": "5.5.4", "terser": "5.16.1", "yargs": "17.7.2", "@firebase/util": "1.10.0", diff --git a/repo-scripts/size-analysis/rollup.config.js b/repo-scripts/size-analysis/rollup.config.js index 2796accc3a9..505596e3d2e 100644 --- a/repo-scripts/size-analysis/rollup.config.js +++ b/repo-scripts/size-analysis/rollup.config.js @@ -42,7 +42,7 @@ export default [ tsconfigOverride: { compilerOptions: { target: 'es2017', - module: 'es2017' + module: 'es2015' } } }), @@ -67,7 +67,7 @@ export default [ tsconfigOverride: { compilerOptions: { target: 'es2017', - module: 'es2017' + module: 'es2015' } } }), diff --git a/yarn.lock b/yarn.lock index efe9f901666..a7b37931fd9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1639,6 +1639,28 @@ resolved "https://registry.npmjs.org/@eslint/js/-/js-8.56.0.tgz#ef20350fec605a7f7035a01764731b2de0f3782b" integrity sha512-gMsVel9D7f2HLkBma9VbtzZRehRogVRfbr++f06nL2vnCGCNlzOD+/MUov/F4p8myyAHspEhVobgjpX64q5m6A== +"@firebase/app-compat@0.2.41": + version "0.2.41" + resolved "https://registry.npmjs.org/@firebase/app-compat/-/app-compat-0.2.41.tgz#6cdc0b5c3248e8e04dcfa373e4895d5785e94f2b" + integrity sha512-ktJcObWKjlIWq31kXu6sHoqWlhQD5rx0a2F2ZC2JVuEE5A5f7F43VO1Z6lfeRZXMFZbGG/aqIfXqgsP3zD2JYg== + dependencies: + "@firebase/app" "0.10.11" + "@firebase/component" "0.6.9" + "@firebase/logger" "0.4.2" + "@firebase/util" "1.10.0" + tslib "^2.1.0" + +"@firebase/app@0.10.11": + version "0.10.11" + resolved "https://registry.npmjs.org/@firebase/app/-/app-0.10.11.tgz#25547f5bf815896dc08023f97138487948522092" + integrity sha512-DuI8c+p/ndPmV6V0i+mcSuaU9mK9Pi9h76WOYFkPNsbmkblEy8bpTOazjG7tnfar6Of1Wn5ohvyOHSRqnN6flQ== + dependencies: + "@firebase/component" "0.6.9" + "@firebase/logger" "0.4.2" + "@firebase/util" "1.10.0" + idb "7.1.1" + tslib "^2.1.0" + "@gar/promisify@^1.0.1": version "1.1.2" resolved "https://registry.npmjs.org/@gar/promisify/-/promisify-1.1.2.tgz" @@ -3490,17 +3512,12 @@ resolved "https://registry.npmjs.org/@types/node/-/node-10.17.13.tgz" integrity sha512-pMCcqU2zT4TjqYFrWtYHKal7Sl30Ims6ulZ4UFXxI4xbtQqK/qqKwkDoBFCfooRqqmRu9vY3xaJRwxSh673aYg== -"@types/node@16.18.68": - version "16.18.68" - resolved "https://registry.npmjs.org/@types/node/-/node-16.18.68.tgz#3155f64a961b3d8d10246c80657f9a7292e3421a" - integrity sha512-sG3hPIQwJLoewrN7cr0dwEy+yF5nD4D/4FxtQpFciRD/xwUzgD+G05uxZHv5mhfXo4F9Jkp13jjn0CC2q325sg== - -"@types/node@20.8.10": - version "20.8.10" - resolved "https://registry.npmjs.org/@types/node/-/node-20.8.10.tgz#a5448b895c753ae929c26ce85cab557c6d4a365e" - integrity sha512-TlgT8JntpcbmKUFzjhsyhGfP2fsiz1Mv56im6enJ905xG1DAYesxJaeSbGqQmAw8OWPdhyJGhGSQGKRNJ45u9w== +"@types/node@22.7.5": + version "22.7.5" + resolved "https://registry.npmjs.org/@types/node/-/node-22.7.5.tgz#cfde981727a7ab3611a481510b473ae54442b92b" + integrity sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ== dependencies: - undici-types "~5.26.4" + undici-types "~6.19.2" "@types/node@>=12.12.47": version "16.9.6" @@ -3651,9 +3668,9 @@ integrity sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw== "@types/vinyl@^2.0.4": - version "2.0.6" - resolved "https://registry.npmjs.org/@types/vinyl/-/vinyl-2.0.6.tgz" - integrity sha512-ayJ0iOCDNHnKpKTgBG6Q6JOnHTj9zFta+3j2b8Ejza0e4cvRyMn0ZoLEmbPrTHe5YYRlDYPvPWVdV4cTaRyH7g== + version "2.0.12" + resolved "https://registry.npmjs.org/@types/vinyl/-/vinyl-2.0.12.tgz#17642ca9a8ae10f3db018e9f885da4188db4c6e6" + integrity sha512-Sr2fYMBUVGYq8kj3UthXFAu5UN6ZW+rYr4NACjZQJvHvj+c8lYv0CahmZ2P/r7iUkN44gGUBwqxZkrKXYPb7cw== dependencies: "@types/expect" "^1.20.4" "@types/node" "*" @@ -17297,9 +17314,14 @@ typescript@4.2.2: typescript@4.7.4: version "4.7.4" - resolved "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz" + resolved "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz#1a88596d1cf47d59507a1bcdfb5b9dfe4d488235" integrity sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ== +typescript@5.5.4: + version "5.5.4" + resolved "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz#d9852d6c82bad2d2eda4fd74a5762a8f5909e9ba" + integrity sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q== + typescript@~4.1.3: version "4.1.6" resolved "https://registry.npmjs.org/typescript/-/typescript-4.1.6.tgz" @@ -17395,6 +17417,11 @@ undici-types@~5.26.4: resolved "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617" integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA== +undici-types@~6.19.2: + version "6.19.8" + resolved "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz#35111c9d1437ab83a7cdc0abae2f26d88eda0a02" + integrity sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw== + unicode-canonical-property-names-ecmascript@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.0.tgz" From 7aa5fa2b1d931c77ad13e13432aaf330a8dac539 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Wed, 9 Oct 2024 14:08:35 -0400 Subject: [PATCH 02/24] Remove passes of decorators to TS factory functions --- scripts/build/create-overloads.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/scripts/build/create-overloads.ts b/scripts/build/create-overloads.ts index b3a9ada28e7..cb813beadb1 100644 --- a/scripts/build/create-overloads.ts +++ b/scripts/build/create-overloads.ts @@ -149,8 +149,10 @@ function keepPublicFunctionsTransformer( ) { return factory.updateParameterDeclaration( param, - param.decorators, - param.modifiers, + [ + ...(ts.getDecorators(param) || []), + ...(ts.getModifiers(param) || []), + ], param.dotDotDotToken, param.name, param.questionToken, @@ -176,8 +178,7 @@ function keepPublicFunctionsTransformer( overloads.push( factory.updateFunctionDeclaration( node, - node.decorators, - [], + ts.getModifiers(node), node.asteriskToken, node.name, node.typeParameters, @@ -216,7 +217,6 @@ function keepPublicFunctionsTransformer( // hardcode adding `import { FirebaseApp as FirebaseAppCompat } from '@firebase/app-compat'` const appCompatImport = factory.createImportDeclaration( - undefined, undefined, factory.createImportClause( false, @@ -233,7 +233,6 @@ function keepPublicFunctionsTransformer( ); const importStatement = factory.createImportDeclaration( - undefined, undefined, factory.createImportClause( false, @@ -251,7 +250,6 @@ function keepPublicFunctionsTransformer( factory.createStringLiteral(moduleNameToEnhance) ); const moduleToEnhance = factory.createModuleDeclaration( - undefined, [factory.createModifier(ts.SyntaxKind.DeclareKeyword)], factory.createStringLiteral(moduleNameToEnhance), factory.createModuleBlock(overloads) From df4da35ea497519070065ed881d386f9855c0063 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Wed, 9 Oct 2024 14:13:06 -0400 Subject: [PATCH 03/24] Format --- scripts/build/create-overloads.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build/create-overloads.ts b/scripts/build/create-overloads.ts index cb813beadb1..a66bda6dfe0 100644 --- a/scripts/build/create-overloads.ts +++ b/scripts/build/create-overloads.ts @@ -151,7 +151,7 @@ function keepPublicFunctionsTransformer( param, [ ...(ts.getDecorators(param) || []), - ...(ts.getModifiers(param) || []), + ...(ts.getModifiers(param) || []) ], param.dotDotDotToken, param.name, From d93358aa716b001c4f2a8195f56dc472bab664c4 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Wed, 9 Oct 2024 14:30:07 -0400 Subject: [PATCH 04/24] Update TS in packages that used older TS versions --- integration/firestore/package.json | 2 +- packages/data-connect/package.json | 2 +- packages/firebase/package.json | 2 +- packages/firestore-types/package.json | 2 +- yarn.lock | 10 ---------- 5 files changed, 4 insertions(+), 14 deletions(-) diff --git a/integration/firestore/package.json b/integration/firestore/package.json index 2f0f9f893c7..3dd5dfb0fc6 100644 --- a/integration/firestore/package.json +++ b/integration/firestore/package.json @@ -29,7 +29,7 @@ "karma-spec-reporter": "0.0.36", "mocha": "9.2.2", "ts-loader": "9.5.1", - "typescript": "4.2.2", + "typescript": "5.5.4", "webpack": "5.76.0", "webpack-stream": "7.0.0" }, diff --git a/packages/data-connect/package.json b/packages/data-connect/package.json index c6df2dc5ac3..111764af732 100644 --- a/packages/data-connect/package.json +++ b/packages/data-connect/package.json @@ -58,7 +58,7 @@ "@firebase/app": "0.10.13", "rollup": "2.79.1", "rollup-plugin-typescript2": "0.31.2", - "typescript": "4.7.4" + "typescript": "5.5.4" }, "repository": { "directory": "packages/data-connect", diff --git a/packages/firebase/package.json b/packages/firebase/package.json index 37c1339774e..3bf31d42c12 100644 --- a/packages/firebase/package.json +++ b/packages/firebase/package.json @@ -439,7 +439,7 @@ "gulp": "4.0.2", "gulp-sourcemaps": "3.0.0", "gulp-replace": "1.1.4", - "typescript": "4.2.2", + "typescript": "5.5.4", "rollup-plugin-license": "3.0.1" }, "components": [ diff --git a/packages/firestore-types/package.json b/packages/firestore-types/package.json index b797abb86dd..9a21e29e803 100644 --- a/packages/firestore-types/package.json +++ b/packages/firestore-types/package.json @@ -24,6 +24,6 @@ "url": "https://github.com/firebase/firebase-js-sdk/issues" }, "devDependencies": { - "typescript": "4.2.2" + "typescript": "5.5.4" } } diff --git a/yarn.lock b/yarn.lock index a7b37931fd9..fd8e1512b09 100644 --- a/yarn.lock +++ b/yarn.lock @@ -17307,16 +17307,6 @@ typescript@3.7.x: resolved "https://registry.npmjs.org/typescript/-/typescript-3.7.7.tgz" integrity sha512-MmQdgo/XenfZPvVLtKZOq9jQQvzaUAUpcKW8Z43x9B2fOm4S5g//tPtMweZUIP+SoBqrVPEIm+dJeQ9dfO0QdA== -typescript@4.2.2: - version "4.2.2" - resolved "https://registry.npmjs.org/typescript/-/typescript-4.2.2.tgz" - integrity sha512-tbb+NVrLfnsJy3M59lsDgrzWIflR4d4TIUjz+heUnHZwdF7YsrMTKoRERiIvI2lvBG95dfpLxB21WZhys1bgaQ== - -typescript@4.7.4: - version "4.7.4" - resolved "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz#1a88596d1cf47d59507a1bcdfb5b9dfe4d488235" - integrity sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ== - typescript@5.5.4: version "5.5.4" resolved "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz#d9852d6c82bad2d2eda4fd74a5762a8f5909e9ba" From c58e63b1b124e8a520202da7b66720495688d8e6 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Thu, 10 Oct 2024 12:16:02 -0400 Subject: [PATCH 05/24] Convert `EmulatorConfig`'s `HostAndPort` to be an optional property --- .../rules-unit-testing/src/impl/discovery.ts | 33 +++++++------------ packages/rules-unit-testing/src/initialize.ts | 2 +- .../src/public_types/index.ts | 11 +++++-- .../test/impl/discovery.test.ts | 28 +++------------- 4 files changed, 25 insertions(+), 49 deletions(-) diff --git a/packages/rules-unit-testing/src/impl/discovery.ts b/packages/rules-unit-testing/src/impl/discovery.ts index 4d57660aa60..a3bcb85bd92 100644 --- a/packages/rules-unit-testing/src/impl/discovery.ts +++ b/packages/rules-unit-testing/src/impl/discovery.ts @@ -84,29 +84,20 @@ export interface DiscoveredEmulators { */ export function getEmulatorHostAndPort( emulator: keyof DiscoveredEmulators, - conf?: EmulatorConfig, + endpoint?: HostAndPort, discovered?: DiscoveredEmulators -) { - if (conf && 'host' in conf && 'port' in conf) { - const { host, port } = conf; - if (host || port) { - if (!host || !port) { - throw new Error( - `Invalid configuration ${emulator}.host=${host} and ${emulator}.port=${port}. ` + - 'If either parameter is supplied, both must be defined.' - ); - } - if (discovered && !discovered[emulator]) { - console.warn( - `Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` + - 'reports it as not running. This may lead to errors such as connection refused.' - ); - } - return { - host: fixHostname(conf.host, discovered?.hub?.host), - port: conf.port - }; +): HostAndPort | undefined { + if (endpoint) { + if (discovered && !discovered[emulator]) { + console.warn( + `Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` + + 'reports it as not running. This may lead to errors such as connection refused.' + ); } + return { + host: fixHostname(endpoint.host, discovered?.hub?.host), + port: endpoint.port + }; } const envVar = EMULATOR_HOST_ENV_VARS[emulator]; const fallback = discovered?.[emulator] || emulatorFromEnvVar(envVar); diff --git a/packages/rules-unit-testing/src/initialize.ts b/packages/rules-unit-testing/src/initialize.ts index d0442e24524..80eb13373c9 100644 --- a/packages/rules-unit-testing/src/initialize.ts +++ b/packages/rules-unit-testing/src/initialize.ts @@ -73,7 +73,7 @@ export async function initializeTestEnvironment( for (const emulator of SUPPORTED_EMULATORS) { const hostAndPort = getEmulatorHostAndPort( emulator, - config[emulator], + config[emulator]?.endpoint, discovered ); if (hostAndPort) { diff --git a/packages/rules-unit-testing/src/public_types/index.ts b/packages/rules-unit-testing/src/public_types/index.ts index 060e8b8f15b..fd3ac67d2ff 100644 --- a/packages/rules-unit-testing/src/public_types/index.ts +++ b/packages/rules-unit-testing/src/public_types/index.ts @@ -128,7 +128,7 @@ export interface TestEnvironmentConfig { * An object containing the hostname and port number of an emulator. * @public */ -export interface HostAndPort { +export type HostAndPort = { /** * The host of the emulator. Can be omitted if discovered automatically through the hub or * specified via environment variables. See `TestEnvironmentConfig` for details. @@ -140,7 +140,7 @@ export interface HostAndPort { * specified via environment variables. See `TestEnvironmentConfig` for details. */ port: number; -} +}; /** * Configuration for a given emulator. @@ -149,7 +149,12 @@ export interface HostAndPort { export type EmulatorConfig = { /** The security rules source code under test for this emulator. Strongly recommended. */ rules?: string; -} & (HostAndPort | {}); // Both or none of host and port should be specified. + /** + * Endpoint of the emulator. Can be omitted if discovered automatically through the hub. + * See `TestEnvironmentConfig` for details. + */ + endpoint?: HostAndPort; +}; /** * An object used to control the rules unit test environment. Can be used to create RulesTestContext diff --git a/packages/rules-unit-testing/test/impl/discovery.test.ts b/packages/rules-unit-testing/test/impl/discovery.test.ts index 39b5628ddc2..95d008c1466 100644 --- a/packages/rules-unit-testing/test/impl/discovery.test.ts +++ b/packages/rules-unit-testing/test/impl/discovery.test.ts @@ -22,7 +22,7 @@ import { EMULATOR_HOST_ENV_VARS, getEmulatorHostAndPort } from '../../src/impl/discovery'; -import { HostAndPort } from '../../src/public_types'; +import { EmulatorConfig, HostAndPort } from '../../src/public_types'; import { restoreEnvVars, stashEnvVars } from '../test_utils'; describe('discoverEmulators()', () => { @@ -106,10 +106,8 @@ describe('getEmulatorHostAndPort()', () => { expect(result).to.be.undefined; }); - it('returns undefined if config option does not contain host/port', async () => { - const result = getEmulatorHostAndPort('hub', { - rules: '/* security rules only, no host/port */' - }); + it('returns undefined if endpoint is undefined', async () => { + const result = getEmulatorHostAndPort('hub'); expect(result).to.be.undefined; }); @@ -123,22 +121,6 @@ describe('getEmulatorHostAndPort()', () => { expect(result?.host).to.equal('::1'); }); - it('throws if only host is present', async () => { - expect(() => - getEmulatorHostAndPort('hub', { - host: '[::1]' - } as HostAndPort) - ).to.throw(/hub.port=undefined/); - }); - - it('throws if only port is present', async () => { - expect(() => - getEmulatorHostAndPort('database', { - port: 1234 - } as HostAndPort) - ).to.throw(/Invalid configuration database.host=undefined/); - }); - it('connect to 127.0.0.1 if host is wildcard 0.0.0.0', async () => { const result = getEmulatorHostAndPort('hub', { host: '0.0.0.0', @@ -304,9 +286,7 @@ describe('getEmulatorHostAndPort()', () => { it('takes host and port from env var if config has no host/port', async () => { process.env[EMULATOR_HOST_ENV_VARS.hub] = '127.0.0.1:3445'; - const result = getEmulatorHostAndPort('hub', { - rules: '/* security rules only, no host/port */' - }); + const result = getEmulatorHostAndPort('hub'); expect(result?.host).to.equal('127.0.0.1'); expect(result?.port).to.equal(3445); From 195c230e15f2bdd3e52ce4ad1da95019d991e6a8 Mon Sep 17 00:00:00 2001 From: dlarocque Date: Wed, 16 Oct 2024 19:29:18 +0000 Subject: [PATCH 06/24] Update API reports --- common/api-review/rules-unit-testing.api.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/common/api-review/rules-unit-testing.api.md b/common/api-review/rules-unit-testing.api.md index e0a646d01bd..f2d4a34d464 100644 --- a/common/api-review/rules-unit-testing.api.md +++ b/common/api-review/rules-unit-testing.api.md @@ -16,13 +16,14 @@ export function assertSucceeds(pr: Promise): Promise; // @public export type EmulatorConfig = { rules?: string; -} & (HostAndPort | {}); + endpoint?: HostAndPort; +}; // @public -export interface HostAndPort { +export type HostAndPort = { host: string; port: number; -} +}; // @public export function initializeTestEnvironment(config: TestEnvironmentConfig): Promise; From 353229bb2dcf5d5e4dbb3eea3ffccbc3c7d14f16 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Wed, 16 Oct 2024 15:42:38 -0400 Subject: [PATCH 07/24] Update yarn.lock --- yarn.lock | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/yarn.lock b/yarn.lock index fd8e1512b09..5de8c6a62a5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1639,28 +1639,6 @@ resolved "https://registry.npmjs.org/@eslint/js/-/js-8.56.0.tgz#ef20350fec605a7f7035a01764731b2de0f3782b" integrity sha512-gMsVel9D7f2HLkBma9VbtzZRehRogVRfbr++f06nL2vnCGCNlzOD+/MUov/F4p8myyAHspEhVobgjpX64q5m6A== -"@firebase/app-compat@0.2.41": - version "0.2.41" - resolved "https://registry.npmjs.org/@firebase/app-compat/-/app-compat-0.2.41.tgz#6cdc0b5c3248e8e04dcfa373e4895d5785e94f2b" - integrity sha512-ktJcObWKjlIWq31kXu6sHoqWlhQD5rx0a2F2ZC2JVuEE5A5f7F43VO1Z6lfeRZXMFZbGG/aqIfXqgsP3zD2JYg== - dependencies: - "@firebase/app" "0.10.11" - "@firebase/component" "0.6.9" - "@firebase/logger" "0.4.2" - "@firebase/util" "1.10.0" - tslib "^2.1.0" - -"@firebase/app@0.10.11": - version "0.10.11" - resolved "https://registry.npmjs.org/@firebase/app/-/app-0.10.11.tgz#25547f5bf815896dc08023f97138487948522092" - integrity sha512-DuI8c+p/ndPmV6V0i+mcSuaU9mK9Pi9h76WOYFkPNsbmkblEy8bpTOazjG7tnfar6Of1Wn5ohvyOHSRqnN6flQ== - dependencies: - "@firebase/component" "0.6.9" - "@firebase/logger" "0.4.2" - "@firebase/util" "1.10.0" - idb "7.1.1" - tslib "^2.1.0" - "@gar/promisify@^1.0.1": version "1.1.2" resolved "https://registry.npmjs.org/@gar/promisify/-/promisify-1.1.2.tgz" From a96166d10596816a09b1b06a75f420e520ad8ae0 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Wed, 16 Oct 2024 15:59:48 -0400 Subject: [PATCH 08/24] Cleanup --- packages/firestore/scripts/run-tests.js | 17 ------------- .../new-tests/data-connect.output.d.ts | 1 - repo-scripts/prune-dts/prune-dts.ts | 6 ----- ...es-generics-through-inheritance.input.d.ts | 25 +++++++++++++++++++ ...s-generics-through-inheritance.output.d.ts | 24 ++++++++++++++++++ 5 files changed, 49 insertions(+), 24 deletions(-) delete mode 100644 packages/firestore/scripts/run-tests.js create mode 100644 repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts create mode 100644 repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts diff --git a/packages/firestore/scripts/run-tests.js b/packages/firestore/scripts/run-tests.js deleted file mode 100644 index 88b9f05ee55..00000000000 --- a/packages/firestore/scripts/run-tests.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */exports.__esModule=true;var path_1=require("path");var child_process_promise_1=require("child-process-promise");var yargs=require("yargs");var argv=yargs.options({main:{type:"string",demandOption:true},platform:{type:"string",default:"node"},emulator:{type:"boolean"},persistence:{type:"boolean"},databaseId:{type:"string"}}).parseSync();var nyc=(0,path_1.resolve)(__dirname,"../../../node_modules/.bin/nyc");var mocha=(0,path_1.resolve)(__dirname,"../../../node_modules/.bin/mocha");var babel=(0,path_1.resolve)(__dirname,"../babel-register.js");process.env.NO_TS_NODE="true";process.env.TEST_PLATFORM=argv.platform;var args=["--reporter","lcovonly",mocha,"--require",babel,"--require",argv.main,"--config","../../config/mocharc.node.js"];if(argv.emulator){process.env.FIRESTORE_TARGET_BACKEND="emulator"}if(argv.persistence){process.env.USE_MOCK_PERSISTENCE="YES";args.push("--require","test/util/node_persistence.ts")}if(argv.databaseId){process.env.FIRESTORE_TARGET_DB_ID=argv.databaseId}args=args.concat(argv._);var childProcess=(0,child_process_promise_1.spawn)(nyc,args,{stdio:"inherit",cwd:process.cwd()}).childProcess;process.once("exit",(function(){return childProcess.kill()}));process.once("SIGINT",(function(){return childProcess.kill("SIGINT")}));process.once("SIGTERM",(function(){return childProcess.kill("SIGTERM")})); \ No newline at end of file diff --git a/repo-scripts/prune-dts/new-tests/data-connect.output.d.ts b/repo-scripts/prune-dts/new-tests/data-connect.output.d.ts index cc4926d649d..de070520b03 100644 --- a/repo-scripts/prune-dts/new-tests/data-connect.output.d.ts +++ b/repo-scripts/prune-dts/new-tests/data-connect.output.d.ts @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - /** * Firebase Data Connect * diff --git a/repo-scripts/prune-dts/prune-dts.ts b/repo-scripts/prune-dts/prune-dts.ts index acd132623fe..1654e0fa6cc 100644 --- a/repo-scripts/prune-dts/prune-dts.ts +++ b/repo-scripts/prune-dts/prune-dts.ts @@ -19,7 +19,6 @@ import * as yargs from 'yargs'; import * as ts from 'typescript'; import * as fs from 'fs'; import { ESLint } from 'eslint'; -import { assert } from 'console'; /** * Prunes a DTS file based on three main rules: @@ -156,10 +155,6 @@ function maybeHideConstructor( ?.find(t => t.tagName.escapedText === 'hideconstructor'); if (hideConstructorTag) { - assert( - !ts.canHaveDecorators(node), - 'Constructor should not have decorators' - ); const hideConstructorModifier = ts.factory.createModifier( hideConstructorTag.comment === 'protected' ? ts.SyntaxKind.ProtectedKeyword @@ -569,7 +564,6 @@ function dropPrivateApiTransformer( context: ts.TransformationContext ): ts.Transformer { const typeChecker = program.getTypeChecker(); - // const { factory } = context; return (sourceFile: ts.SourceFile) => { function visit(node: ts.Node): ts.Node { diff --git a/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts b/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts new file mode 100644 index 00000000000..90c1d70b0ea --- /dev/null +++ b/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare class A { + a: T; +} +export class B extends A { + b: T; +} +export class C extends A {} +export {}; \ No newline at end of file diff --git a/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts b/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts new file mode 100644 index 00000000000..b14555d6c52 --- /dev/null +++ b/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + export class B { + b: T; + a: string; +} +export class C { + a: T; +} +export {}; \ No newline at end of file From 40b09303370f686b2e218b71266d56700d677a0a Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Wed, 16 Oct 2024 16:02:57 -0400 Subject: [PATCH 09/24] Upgrade ts-essentials to latest --- packages/messaging/package.json | 2 +- yarn.lock | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/messaging/package.json b/packages/messaging/package.json index 8f0f53b694b..dabcc2955e3 100644 --- a/packages/messaging/package.json +++ b/packages/messaging/package.json @@ -64,7 +64,7 @@ "rollup": "2.79.1", "rollup-plugin-typescript2": "0.31.2", "@rollup/plugin-json": "4.1.0", - "ts-essentials": "9.3.0", + "ts-essentials": "10.0.2", "typescript": "5.5.4" }, "repository": { diff --git a/yarn.lock b/yarn.lock index 5de8c6a62a5..73f6c60a2fa 100644 --- a/yarn.lock +++ b/yarn.lock @@ -16981,6 +16981,11 @@ ts-api-utils@^1.0.1, ts-api-utils@^1.3.0: resolved "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.3.0.tgz#4b490e27129f1e8e686b45cc4ab63714dc60eea1" integrity sha512-UQMIo7pb8WRomKR1/+MFVLTroIvDVtMX3K6OUir8ynLyzB8Jeriont2bTAtmNPa1ekAgN7YPDyf6V+ygrdU+eQ== +ts-essentials@10.0.2: + version "10.0.2" + resolved "https://registry.npmjs.org/ts-essentials/-/ts-essentials-10.0.2.tgz#8c7aa74ed79580ffe49df5ca28d06cc6bea0ff3c" + integrity sha512-Xwag0TULqriaugXqVdDiGZ5wuZpqABZlpwQ2Ho4GDyiu/R2Xjkp/9+zcFxL7uzeLl/QCPrflnvpVYyS3ouT7Zw== + ts-essentials@9.3.0: version "9.3.0" resolved "https://registry.npmjs.org/ts-essentials/-/ts-essentials-9.3.0.tgz" From f1116fa47ecb3d5336db5e0909e55be8da97c59f Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Wed, 16 Oct 2024 16:07:14 -0400 Subject: [PATCH 10/24] Format and move prune-dts test folder --- .../prune-dts/new-tests/firestore.input.d.ts | 8410 ----------------- .../prune-dts/new-tests/firestore.output.d.ts | 3475 ------- repo-scripts/prune-dts/prune-dts.test.ts | 2 +- .../prune-dts/subtests/app.input.d.ts | 576 -- .../prune-dts/subtests/app.output.d.ts | 470 - .../data-connect.input.d.ts | 0 .../data-connect.output.d.ts | 0 .../{new-tests => tests}/database.input.d.ts | 0 .../{new-tests => tests}/database.output.d.ts | 0 .../prune-dts/tests/firestore.input.d.ts | 4587 +++++++-- .../prune-dts/tests/firestore.output.d.ts | 2317 ++++- .../{new-tests => tests}/messaging.input.d.ts | 0 .../messaging.output.d.ts | 0 ...es-generics-through-inheritance.input.d.ts | 2 +- ...s-generics-through-inheritance.output.d.ts | 48 +- .../storage-public.input.d.ts | 0 .../storage-public.output.d.ts | 0 17 files changed, 5492 insertions(+), 14395 deletions(-) delete mode 100644 repo-scripts/prune-dts/new-tests/firestore.input.d.ts delete mode 100644 repo-scripts/prune-dts/new-tests/firestore.output.d.ts delete mode 100644 repo-scripts/prune-dts/subtests/app.input.d.ts delete mode 100644 repo-scripts/prune-dts/subtests/app.output.d.ts rename repo-scripts/prune-dts/{new-tests => tests}/data-connect.input.d.ts (100%) rename repo-scripts/prune-dts/{new-tests => tests}/data-connect.output.d.ts (100%) rename repo-scripts/prune-dts/{new-tests => tests}/database.input.d.ts (100%) rename repo-scripts/prune-dts/{new-tests => tests}/database.output.d.ts (100%) rename repo-scripts/prune-dts/{new-tests => tests}/messaging.input.d.ts (100%) rename repo-scripts/prune-dts/{new-tests => tests}/messaging.output.d.ts (100%) rename repo-scripts/prune-dts/{new-tests => tests}/storage-public.input.d.ts (100%) rename repo-scripts/prune-dts/{new-tests => tests}/storage-public.output.d.ts (100%) diff --git a/repo-scripts/prune-dts/new-tests/firestore.input.d.ts b/repo-scripts/prune-dts/new-tests/firestore.input.d.ts deleted file mode 100644 index a69b8be42de..00000000000 --- a/repo-scripts/prune-dts/new-tests/firestore.input.d.ts +++ /dev/null @@ -1,8410 +0,0 @@ -/** - * Cloud Firestore - * - * @packageDocumentation - */ - -import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; -import { EmulatorMockTokenOptions } from '@firebase/util'; -import { FirebaseApp } from '@firebase/app'; -import { FirebaseError } from '@firebase/util'; -import { LogLevelString as LogLevel } from '@firebase/logger'; -import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; - -/* Excluded from this release type: AbstractUserDataWriter */ - -/** - * Describes a map whose keys are active target ids. We do not care about the type of the - * values. - */ -declare type ActiveTargets = SortedMap; - -/** - * Add a new document to specified `CollectionReference` with the given data, - * assigning it a document ID automatically. - * - * @param reference - A reference to the collection to add this document to. - * @param data - An Object containing the data for the new document. - * @returns A `Promise` resolved with a `DocumentReference` pointing to the - * newly created document after it has been written to the backend (Note that it - * won't resolve while you're offline). - */ -export declare function addDoc( - reference: CollectionReference, - data: WithFieldValue -): Promise>; - -/** - * Returns a new map where every key is prefixed with the outer key appended - * to a dot. - */ -export declare type AddPrefixToKeys< - Prefix extends string, - T extends Record -> = { - [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; -}; - -/** - * Represents an aggregation that can be performed by Firestore. - */ -export declare class AggregateField { - readonly _internalFieldPath?: _FieldPath | undefined; - /** A type string to uniquely identify instances of this class. */ - readonly type = 'AggregateField'; - /** Indicates the aggregation operation of this AggregateField. */ - readonly aggregateType: AggregateType; - /* Excluded from this release type: __constructor */ -} - -/** - * Compares two 'AggregateField` instances for equality. - * - * @param left Compare this AggregateField to the `right`. - * @param right Compare this AggregateField to the `left`. - */ -export declare function aggregateFieldEqual( - left: AggregateField, - right: AggregateField -): boolean; - -/** - * The union of all `AggregateField` types that are supported by Firestore. - */ -export declare type AggregateFieldType = - | ReturnType - | ReturnType - | ReturnType; - -/** - * The results of executing an aggregation query. - */ -export declare class AggregateQuerySnapshot< - AggregateSpecType extends AggregateSpec, - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> { - private readonly _userDataWriter; - private readonly _data; - /** A type string to uniquely identify instances of this class. */ - readonly type = 'AggregateQuerySnapshot'; - /** - * The underlying query over which the aggregations recorded in this - * `AggregateQuerySnapshot` were performed. - */ - readonly query: Query; - /** @hideconstructor */ - constructor( - query: Query, - _userDataWriter: AbstractUserDataWriter, - _data: ApiClientObjectMap - ); - /** - * Returns the results of the aggregations performed over the underlying - * query. - * - * The keys of the returned object will be the same as those of the - * `AggregateSpec` object specified to the aggregation method, and the values - * will be the corresponding aggregation result. - * - * @returns The results of the aggregations performed over the underlying - * query. - */ - data(): AggregateSpecData; -} - -/** - * Compares two `AggregateQuerySnapshot` instances for equality. - * - * Two `AggregateQuerySnapshot` instances are considered "equal" if they have - * underlying queries that compare equal, and the same data. - * - * @param left - The first `AggregateQuerySnapshot` to compare. - * @param right - The second `AggregateQuerySnapshot` to compare. - * - * @returns `true` if the objects are "equal", as defined above, or `false` - * otherwise. - */ -export declare function aggregateQuerySnapshotEqual< - AggregateSpecType extends AggregateSpec, - AppModelType, - DbModelType extends DocumentData ->( - left: AggregateQuerySnapshot, - right: AggregateQuerySnapshot -): boolean; - -/** - * Specifies a set of aggregations and their aliases. - */ -export declare interface AggregateSpec { - [field: string]: AggregateFieldType; -} - -/** - * A type whose keys are taken from an `AggregateSpec`, and whose values are the - * result of the aggregation performed by the corresponding `AggregateField` - * from the input `AggregateSpec`. - */ -export declare type AggregateSpecData = { - [P in keyof T]: T[P] extends AggregateField ? U : never; -}; - -/** - * Union type representing the aggregate type to be performed. - */ -export declare type AggregateType = 'count' | 'avg' | 'sum'; - -/** - * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of - * the given filter constraints. A conjunction filter includes a document if it - * satisfies all of the given filters. - * - * @param queryConstraints - Optional. The list of - * {@link QueryFilterConstraint}s to perform a conjunction for. These must be - * created with calls to {@link where}, {@link or}, or {@link and}. - * @returns The newly created {@link QueryCompositeFilterConstraint}. - */ -export declare function and( - ...queryConstraints: QueryFilterConstraint[] -): QueryCompositeFilterConstraint; - -declare interface ApiClientObjectMap { - [k: string]: T; -} - -/** - * An `AppliableConstraint` is an abstraction of a constraint that can be applied - * to a Firestore query. - */ -declare abstract class AppliableConstraint { - /** - * Takes the provided {@link Query} and returns a copy of the {@link Query} with this - * {@link AppliableConstraint} applied. - */ - abstract _apply( - query: Query - ): Query; -} - -/** - * Returns a special value that can be used with {@link (setDoc:1)} or {@link - * updateDoc:1} that tells the server to remove the given elements from any - * array value that already exists on the server. All instances of each element - * specified will be removed from the array. If the field being modified is not - * already an array it will be overwritten with an empty array. - * - * @param elements - The elements to remove from the array. - * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or - * `updateDoc()` - */ -export declare function arrayRemove(...elements: unknown[]): FieldValue; - -/** - * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link - * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array - * value that already exists on the server. Each specified element that doesn't - * already exist in the array will be added to the end. If the field being - * modified is not already an array it will be overwritten with an array - * containing exactly the specified elements. - * - * @param elements - The elements to union into the array. - * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or - * `updateDoc()`. - */ -export declare function arrayUnion(...elements: unknown[]): FieldValue; - -declare interface AsyncQueue { - readonly isShuttingDown: boolean; - /** - * Adds a new operation to the queue without waiting for it to complete (i.e. - * we ignore the Promise result). - */ - enqueueAndForget(op: () => Promise): void; - /** - * Regardless if the queue has initialized shutdown, adds a new operation to the - * queue without waiting for it to complete (i.e. we ignore the Promise result). - */ - enqueueAndForgetEvenWhileRestricted( - op: () => Promise - ): void; - /** - * Initialize the shutdown of this queue. Once this method is called, the - * only possible way to request running an operation is through - * `enqueueEvenWhileRestricted()`. - * - * @param purgeExistingTasks Whether already enqueued tasked should be - * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults - * to false. - */ - enterRestrictedMode(purgeExistingTasks?: boolean): void; - /** - * Adds a new operation to the queue. Returns a promise that will be resolved - * when the promise returned by the new operation is (with its value). - */ - enqueue(op: () => Promise): Promise; - /** - * Enqueue a retryable operation. - * - * A retryable operation is rescheduled with backoff if it fails with a - * IndexedDbTransactionError (the error type used by SimpleDb). All - * retryable operations are executed in order and only run if all prior - * operations were retried successfully. - */ - enqueueRetryable(op: () => Promise): void; - /** - * Schedules an operation to be queued on the AsyncQueue once the specified - * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel - * or fast-forward the operation prior to its running. - */ - enqueueAfterDelay( - timerId: TimerId, - delayMs: number, - op: () => Promise - ): DelayedOperation; - /** - * Verifies there's an operation currently in-progress on the AsyncQueue. - * Unfortunately we can't verify that the running code is in the promise chain - * of that operation, so this isn't a foolproof check, but it should be enough - * to catch some bugs. - */ - verifyOperationInProgress(): void; -} - -/* Excluded from this release type: AuthTokenFactory */ - -/* Excluded from this release type: _AutoId */ - -/** - * Create an AggregateField object that can be used to compute the average of - * a specified field over a range of documents in the result set of a query. - * @param field Specifies the field to average across the result set. - */ -export declare function average( - field: string | FieldPath -): AggregateField; - -/** - * Path represents an ordered sequence of string segments. - */ -declare abstract class BasePath> { - private segments; - private offset; - private len; - constructor(segments: string[], offset?: number, length?: number); - /** - * Abstract constructor method to construct an instance of B with the given - * parameters. - */ - protected abstract construct( - segments: string[], - offset?: number, - length?: number - ): B; - /** - * Returns a String representation. - * - * Implementing classes are required to provide deterministic implementations as - * the String representation is used to obtain canonical Query IDs. - */ - abstract toString(): string; - get length(): number; - isEqual(other: B): boolean; - child(nameOrPath: string | B): B; - /** The index of one past the last segment of the path. */ - private limit; - popFirst(size?: number): B; - popLast(): B; - firstSegment(): string; - lastSegment(): string; - get(index: number): string; - isEmpty(): boolean; - isPrefixOf(other: this): boolean; - isImmediateParentOf(potentialChild: this): boolean; - forEach(fn: (segment: string) => void): void; - toArray(): string[]; - static comparator>( - p1: BasePath, - p2: BasePath - ): number; -} - -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * BatchID is a locally assigned ID for a batch of mutations that have been - * applied. - */ -declare type BatchId = number; - -/** - * Represents a bound of a query. - * - * The bound is specified with the given components representing a position and - * whether it's just before or just after the position (relative to whatever the - * query order is). - * - * The position represents a logical index position for a query. It's a prefix - * of values for the (potentially implicit) order by clauses of a query. - * - * Bound provides a function to determine whether a document comes before or - * after a bound. This is influenced by whether the position is just before or - * just after the provided values. - */ -declare class Bound { - readonly position: Value[]; - readonly inclusive: boolean; - constructor(position: Value[], inclusive: boolean); -} - -/** - * Provides interfaces to save and read Firestore bundles. - */ -declare interface BundleCache { - /** - * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined - * if no bundle metadata is found under the given id. - */ - getBundleMetadata( - transaction: PersistenceTransaction, - bundleId: string - ): PersistencePromise; - /** - * Saves a `BundleMetadata` from a bundle into local storage, using its id as - * the persistent key. - */ - saveBundleMetadata( - transaction: PersistenceTransaction, - metadata: BundleMetadata_2 - ): PersistencePromise; - /** - * Gets a saved `NamedQuery` for the given query name. Returns undefined if - * no queries are found under the given name. - */ - getNamedQuery( - transaction: PersistenceTransaction, - queryName: string - ): PersistencePromise; - /** - * Saves a `NamedQuery` from a bundle, using its name as the persistent key. - */ - saveNamedQuery( - transaction: PersistenceTransaction, - query: NamedQuery_2 - ): PersistencePromise; -} - -/** Properties of a BundledQuery. */ -declare interface BundledQuery { - /** BundledQuery parent */ - parent?: string | null; - /** BundledQuery structuredQuery */ - structuredQuery?: StructuredQuery | null; - /** BundledQuery limitType */ - limitType?: LimitType_2 | null; -} - -/** - * Represents a Firestore bundle saved by the SDK in its local storage. - */ -declare interface BundleMetadata { - /** - * Id of the bundle. It is used together with `createTime` to determine if a - * bundle has been loaded by the SDK. - */ - readonly id: string; - /** Schema version of the bundle. */ - readonly version: number; - /** - * Set to the snapshot version of the bundle if created by the Server SDKs. - * Otherwise set to SnapshotVersion.MIN. - */ - readonly createTime: SnapshotVersion; -} - -/** Properties of a BundleMetadata. */ -declare interface BundleMetadata_2 { - /** BundleMetadata id */ - id?: string | null; - /** BundleMetadata createTime */ - createTime?: Timestamp_2 | null; - /** BundleMetadata version */ - version?: number | null; - /** BundleMetadata totalDocuments */ - totalDocuments?: number | null; - /** BundleMetadata totalBytes */ - totalBytes?: number | null; -} - -/** - * An immutable object representing an array of bytes. - */ -export declare class Bytes { - _byteString: _ByteString; - /** @hideconstructor */ - constructor(byteString: _ByteString); - /** - * Creates a new `Bytes` object from the given Base64 string, converting it to - * bytes. - * - * @param base64 - The Base64 string used to create the `Bytes` object. - */ - static fromBase64String(base64: string): Bytes; - /** - * Creates a new `Bytes` object from the given Uint8Array. - * - * @param array - The Uint8Array used to create the `Bytes` object. - */ - static fromUint8Array(array: Uint8Array): Bytes; - /** - * Returns the underlying bytes as a Base64-encoded string. - * - * @returns The Base64-encoded string created from the `Bytes` object. - */ - toBase64(): string; - /** - * Returns the underlying bytes in a new `Uint8Array`. - * - * @returns The Uint8Array created from the `Bytes` object. - */ - toUint8Array(): Uint8Array; - /** - * Returns a string representation of the `Bytes` object. - * - * @returns A string representation of the `Bytes` object. - */ - toString(): string; - /** - * Returns true if this `Bytes` object is equal to the provided one. - * - * @param other - The `Bytes` object to compare against. - * @returns true if this `Bytes` object is equal to the provided one. - */ - isEqual(other: Bytes): boolean; -} - -/* Excluded from this release type: _ByteString */ - -/** - * Constant used to indicate the LRU garbage collection should be disabled. - * Set this value as the `cacheSizeBytes` on the settings passed to the - * {@link Firestore} instance. - */ -export declare const CACHE_SIZE_UNLIMITED = -1; - -/* Excluded from this release type: _cast */ - -declare const enum ChangeType { - Added = 0, - Removed = 1, - Modified = 2, - Metadata = 3 -} - -/** - * Helper for calculating the nested fields for a given type T1. This is needed - * to distribute union types such as `undefined | {...}` (happens for optional - * props) or `{a: A} | {b: B}`. - * - * In this use case, `V` is used to distribute the union types of `T[K]` on - * `Record`, since `T[K]` is evaluated as an expression and not distributed. - * - * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types - */ -export declare type ChildUpdateFields = V extends Record< - string, - unknown -> - ? AddPrefixToKeys> - : never; - -/** - * Clears the persistent storage. This includes pending writes and cached - * documents. - * - * Must be called while the {@link Firestore} instance is not started (after the app is - * terminated or when the app is first initialized). On startup, this function - * must be called before other functions (other than {@link - * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} - * instance is still running, the promise will be rejected with the error code - * of `failed-precondition`. - * - * Note: `clearIndexedDbPersistence()` is primarily intended to help write - * reliable tests that use Cloud Firestore. It uses an efficient mechanism for - * dropping existing data but does not attempt to securely overwrite or - * otherwise make cached data unrecoverable. For applications that are sensitive - * to the disclosure of cached data in between user sessions, we strongly - * recommend not enabling persistence at all. - * - * @param firestore - The {@link Firestore} instance to clear persistence for. - * @returns A `Promise` that is resolved when the persistent storage is - * cleared. Otherwise, the promise is rejected with an error. - */ -export declare function clearIndexedDbPersistence( - firestore: Firestore -): Promise; - -/** - * A randomly-generated key assigned to each Firestore instance at startup. - */ -declare type ClientId = string; - -/** - * Gets a `CollectionReference` instance that refers to the collection at - * the specified absolute path. - * - * @param firestore - A reference to the root `Firestore` instance. - * @param path - A slash-separated path to a collection. - * @param pathSegments - Additional path segments to apply relative to the first - * argument. - * @throws If the final path has an even number of segments and does not point - * to a collection. - * @returns The `CollectionReference` instance. - */ -export declare function collection( - firestore: Firestore_2, - path: string, - ...pathSegments: string[] -): CollectionReference; - -/** - * Gets a `CollectionReference` instance that refers to a subcollection of - * `reference` at the specified relative path. - * - * @param reference - A reference to a collection. - * @param path - A slash-separated path to a collection. - * @param pathSegments - Additional path segments to apply relative to the first - * argument. - * @throws If the final path has an even number of segments and does not point - * to a collection. - * @returns The `CollectionReference` instance. - */ -export declare function collection< - AppModelType, - DbModelType extends DocumentData ->( - reference: CollectionReference, - path: string, - ...pathSegments: string[] -): CollectionReference; - -/** - * Gets a `CollectionReference` instance that refers to a subcollection of - * `reference` at the specified relative path. - * - * @param reference - A reference to a Firestore document. - * @param path - A slash-separated path to a collection. - * @param pathSegments - Additional path segments that will be applied relative - * to the first argument. - * @throws If the final path has an even number of segments and does not point - * to a collection. - * @returns The `CollectionReference` instance. - */ -export declare function collection< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference, - path: string, - ...pathSegments: string[] -): CollectionReference; - -/** - * Creates and returns a new `Query` instance that includes all documents in the - * database that are contained in a collection or subcollection with the - * given `collectionId`. - * - * @param firestore - A reference to the root `Firestore` instance. - * @param collectionId - Identifies the collections to query over. Every - * collection or subcollection with this ID as the last segment of its path - * will be included. Cannot contain a slash. - * @returns The created `Query`. - */ -export declare function collectionGroup( - firestore: Firestore_2, - collectionId: string -): Query; - -/** - * A `CollectionReference` object can be used for adding documents, getting - * document references, and querying for documents (using {@link (query:1)}). - */ -export declare class CollectionReference< - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> extends Query { - readonly _path: _ResourcePath; - /** The type of this Firestore reference. */ - readonly type = 'collection'; - /** @hideconstructor */ - constructor( - firestore: Firestore_2, - converter: FirestoreDataConverter_2 | null, - _path: _ResourcePath - ); - /** The collection's identifier. */ - get id(): string; - /** - * A string representing the path of the referenced collection (relative - * to the root of the database). - */ - get path(): string; - /** - * A reference to the containing `DocumentReference` if this is a - * subcollection. If this isn't a subcollection, the reference is null. - */ - get parent(): DocumentReference | null; - /** - * Applies a custom data converter to this `CollectionReference`, allowing you - * to use your own custom model objects with Firestore. When you call {@link - * addDoc} with the returned `CollectionReference` instance, the provided - * converter will convert between Firestore data of type `NewDbModelType` and - * your custom type `NewAppModelType`. - * - * @param converter - Converts objects to and from Firestore. - * @returns A `CollectionReference` that uses the provided converter. - */ - withConverter< - NewAppModelType, - NewDbModelType extends DocumentData = DocumentData - >( - converter: FirestoreDataConverter_2 - ): CollectionReference; - /** - * Removes the current converter. - * - * @param converter - `null` removes the current converter. - * @returns A `CollectionReference` that does not - * use a converter. - */ - withConverter( - converter: null - ): CollectionReference; -} - -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -declare type Comparator = (key1: K, key2: K) => number; - -declare interface ComponentConfiguration { - asyncQueue: AsyncQueue; - databaseInfo: DatabaseInfo; - authCredentials: CredentialsProvider; - appCheckCredentials: CredentialsProvider; - clientId: ClientId; - initialUser: User; - maxConcurrentLimboResolutions: number; -} - -declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; - -declare const enum CompositeOperator { - OR = 'or', - AND = 'and' -} - -/** - * Modify this instance to communicate with the Cloud Firestore emulator. - * - * Note: This must be called before this instance has been used to do any - * operations. - * - * @param firestore - The `Firestore` instance to configure to connect to the - * emulator. - * @param host - the emulator host (ex: localhost). - * @param port - the emulator port (ex: 9000). - * @param options.mockUserToken - the mock auth token to use for unit testing - * Security Rules. - */ -export declare function connectFirestoreEmulator( - firestore: Firestore_2, - host: string, - port: number, - options?: { - mockUserToken?: EmulatorMockTokenOptions | string; - } -): void; - -/** - * Create an AggregateField object that can be used to compute the count of - * documents in the result set of a query. - */ -export declare function count(): AggregateField; - -/** - * A Listener for credential change events. The listener should fetch a new - * token and may need to invalidate other state if the current user has also - * changed. - */ -declare type CredentialChangeListener = (credential: T) => Promise; - -/** - * Provides methods for getting the uid and token for the current user and - * listening for changes. - */ -declare interface CredentialsProvider { - /** - * Starts the credentials provider and specifies a listener to be notified of - * credential changes (sign-in / sign-out, token changes). It is immediately - * called once with the initial user. - * - * The change listener is invoked on the provided AsyncQueue. - */ - start( - asyncQueue: AsyncQueue, - changeListener: CredentialChangeListener - ): void; - /** Requests a token for the current user. */ - getToken(): Promise; - /** - * Marks the last retrieved token as invalid, making the next GetToken request - * force-refresh the token. - */ - invalidateToken(): void; - shutdown(): void; -} - -/** Settings for private credentials */ -declare type CredentialsSettings = - | FirstPartyCredentialsSettings - | ProviderCredentialsSettings; - -/* Excluded from this release type: _DatabaseId */ - -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -declare class DatabaseInfo { - readonly databaseId: _DatabaseId; - readonly appId: string; - readonly persistenceKey: string; - readonly host: string; - readonly ssl: boolean; - readonly forceLongPolling: boolean; - readonly autoDetectLongPolling: boolean; - readonly longPollingOptions: ExperimentalLongPollingOptions; - readonly useFetchStreams: boolean; - /** - * Constructs a DatabaseInfo using the provided host, databaseId and - * persistenceKey. - * - * @param databaseId - The database to use. - * @param appId - The Firebase App Id. - * @param persistenceKey - A unique identifier for this Firestore's local - * storage (used in conjunction with the databaseId). - * @param host - The Firestore backend host to connect to. - * @param ssl - Whether to use SSL when connecting. - * @param forceLongPolling - Whether to use the forceLongPolling option - * when using WebChannel as the network transport. - * @param autoDetectLongPolling - Whether to use the detectBufferingProxy - * option when using WebChannel as the network transport. - * @param longPollingOptions Options that configure long-polling. - * @param useFetchStreams Whether to use the Fetch API instead of - * XMLHTTPRequest - */ - constructor( - databaseId: _DatabaseId, - appId: string, - persistenceKey: string, - host: string, - ssl: boolean, - forceLongPolling: boolean, - autoDetectLongPolling: boolean, - longPollingOptions: ExperimentalLongPollingOptions, - useFetchStreams: boolean - ); -} - -/** - * Datastore and its related methods are a wrapper around the external Google - * Cloud Datastore grpc API, which provides an interface that is more convenient - * for the rest of the client SDK architecture to consume. - */ -declare abstract class Datastore { - abstract terminate(): void; - abstract serializer: JsonProtoSerializer; -} - -/* Excluded from this release type: _debugAssert */ - -/** - * Represents an operation scheduled to be run in the future on an AsyncQueue. - * - * It is created via DelayedOperation.createAndSchedule(). - * - * Supports cancellation (via cancel()) and early execution (via skipDelay()). - * - * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type - * in newer versions of TypeScript defines `finally`, which is not available in - * IE. - */ -declare class DelayedOperation implements PromiseLike { - private readonly asyncQueue; - readonly timerId: TimerId; - readonly targetTimeMs: number; - private readonly op; - private readonly removalCallback; - private timerHandle; - private readonly deferred; - private constructor(); - get promise(): Promise; - /** - * Creates and returns a DelayedOperation that has been scheduled to be - * executed on the provided asyncQueue after the provided delayMs. - * - * @param asyncQueue - The queue to schedule the operation on. - * @param id - A Timer ID identifying the type of operation this is. - * @param delayMs - The delay (ms) before the operation should be scheduled. - * @param op - The operation to run. - * @param removalCallback - A callback to be called synchronously once the - * operation is executed or canceled, notifying the AsyncQueue to remove it - * from its delayedOperations list. - * PORTING NOTE: This exists to prevent making removeDelayedOperation() and - * the DelayedOperation class public. - */ - static createAndSchedule( - asyncQueue: AsyncQueue, - timerId: TimerId, - delayMs: number, - op: () => Promise, - removalCallback: (op: DelayedOperation) => void - ): DelayedOperation; - /** - * Starts the timer. This is called immediately after construction by - * createAndSchedule(). - */ - private start; - /** - * Queues the operation to run immediately (if it hasn't already been run or - * canceled). - */ - skipDelay(): void; - /** - * Cancels the operation if it hasn't already been executed or canceled. The - * promise will be rejected. - * - * As long as the operation has not yet been run, calling cancel() provides a - * guarantee that the operation will not be run. - */ - cancel(reason?: string): void; - then: ( - onfulfilled?: - | ((value: T) => TResult1 | PromiseLike) - | null - | undefined, - onrejected?: - | ((reason: any) => TResult2 | PromiseLike) - | null - | undefined - ) => Promise; - private handleDelayElapsed; - private clearTimeout; -} - -/** - * Removes all persistent cache indexes. - * - * Please note this function will also deletes indexes generated by - * `setIndexConfiguration()`, which is deprecated. - */ -export declare function deleteAllPersistentCacheIndexes( - indexManager: PersistentCacheIndexManager -): void; - -/** - * Deletes the document referred to by the specified `DocumentReference`. - * - * @param reference - A reference to the document to delete. - * @returns A Promise resolved once the document has been successfully - * deleted from the backend (note that it won't resolve while you're offline). - */ -export declare function deleteDoc< - AppModelType, - DbModelType extends DocumentData ->(reference: DocumentReference): Promise; - -/** - * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or - * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. - */ -export declare function deleteField(): FieldValue; - -/** - * The direction of sorting in an order by. - */ -declare const enum Direction { - ASCENDING = 'asc', - DESCENDING = 'desc' -} - -/** - * Disables network usage for this instance. It can be re-enabled via {@link - * enableNetwork}. While the network is disabled, any snapshot listeners, - * `getDoc()` or `getDocs()` calls will return results from cache, and any write - * operations will be queued until the network is restored. - * - * @returns A `Promise` that is resolved once the network has been disabled. - */ -export declare function disableNetwork(firestore: Firestore): Promise; - -/** - * Stops creating persistent cache indexes automatically for local query - * execution. The indexes which have been created by calling - * `enablePersistentCacheIndexAutoCreation()` still take effect. - */ -export declare function disablePersistentCacheIndexAutoCreation( - indexManager: PersistentCacheIndexManager -): void; - -/** - * Gets a `DocumentReference` instance that refers to the document at the - * specified absolute path. - * - * @param firestore - A reference to the root `Firestore` instance. - * @param path - A slash-separated path to a document. - * @param pathSegments - Additional path segments that will be applied relative - * to the first argument. - * @throws If the final path has an odd number of segments and does not point to - * a document. - * @returns The `DocumentReference` instance. - */ -export declare function doc( - firestore: Firestore_2, - path: string, - ...pathSegments: string[] -): DocumentReference; - -/** - * Gets a `DocumentReference` instance that refers to a document within - * `reference` at the specified relative path. If no path is specified, an - * automatically-generated unique ID will be used for the returned - * `DocumentReference`. - * - * @param reference - A reference to a collection. - * @param path - A slash-separated path to a document. Has to be omitted to use - * auto-generated IDs. - * @param pathSegments - Additional path segments that will be applied relative - * to the first argument. - * @throws If the final path has an odd number of segments and does not point to - * a document. - * @returns The `DocumentReference` instance. - */ -export declare function doc( - reference: CollectionReference, - path?: string, - ...pathSegments: string[] -): DocumentReference; - -/** - * Gets a `DocumentReference` instance that refers to a document within - * `reference` at the specified relative path. - * - * @param reference - A reference to a Firestore document. - * @param path - A slash-separated path to a document. - * @param pathSegments - Additional path segments that will be applied relative - * to the first argument. - * @throws If the final path has an odd number of segments and does not point to - * a document. - * @returns The `DocumentReference` instance. - */ -export declare function doc( - reference: DocumentReference, - path: string, - ...pathSegments: string[] -): DocumentReference; - -/** - * Represents a document in Firestore with a key, version, data and whether the - * data has local mutations applied to it. - */ -declare interface Document_2 { - /** The key for this document */ - readonly key: _DocumentKey; - /** - * The version of this document if it exists or a version at which this - * document was guaranteed to not exist. - */ - readonly version: SnapshotVersion; - /** - * The timestamp at which this document was read from the remote server. Uses - * `SnapshotVersion.min()` for documents created by the user. - */ - readonly readTime: SnapshotVersion; - /** - * The timestamp at which the document was created. This value increases - * monotonically when a document is deleted then recreated. It can also be - * compared to `createTime` of other documents and the `readTime` of a query. - */ - readonly createTime: SnapshotVersion; - /** The underlying data of this document or an empty value if no data exists. */ - readonly data: ObjectValue; - /** Returns whether local mutations were applied via the mutation queue. */ - readonly hasLocalMutations: boolean; - /** Returns whether mutations were applied based on a write acknowledgment. */ - readonly hasCommittedMutations: boolean; - /** - * Whether this document had a local mutation applied that has not yet been - * acknowledged by Watch. - */ - readonly hasPendingWrites: boolean; - /** - * Returns whether this document is valid (i.e. it is an entry in the - * RemoteDocumentCache, was created by a mutation or read from the backend). - */ - isValidDocument(): boolean; - /** - * Returns whether the document exists and its data is known at the current - * version. - */ - isFoundDocument(): boolean; - /** - * Returns whether the document is known to not exist at the current version. - */ - isNoDocument(): boolean; - /** - * Returns whether the document exists and its data is unknown at the current - * version. - */ - isUnknownDocument(): boolean; - isEqual(other: Document_2 | null | undefined): boolean; - /** Creates a mutable copy of this document. */ - mutableCopy(): MutableDocument; - toString(): string; -} - -/** - * A `DocumentChange` represents a change to the documents matching a query. - * It contains the document affected and the type of change that occurred. - */ -export declare 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; -} - -/** - * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. - */ -export declare type DocumentChangeType = 'added' | 'removed' | 'modified'; - -declare type DocumentComparator = ( - doc1: Document_2, - doc2: Document_2 -) => number; - -/** - * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to - * values. - */ -export declare interface DocumentData { - /** A mapping between a field and its value. */ - [field: string]: any; -} - -/** - * Returns a special sentinel `FieldPath` to refer to the ID of a document. - * It can be used in queries to sort or filter by the document ID. - */ -export declare function documentId(): FieldPath; - -/* Excluded from this release type: _DocumentKey */ - -declare type DocumentKeyMap = ObjectMap<_DocumentKey, T>; - -declare type DocumentKeySet = SortedSet<_DocumentKey>; - -declare type DocumentMap = SortedMap<_DocumentKey, Document_2>; - -/** - * Provides methods to read and write document overlays. - * - * An overlay is a saved mutation, that gives a local view of a document when - * applied to the remote version of the document. - * - * Each overlay stores the largest batch ID that is included in the overlay, - * which allows us to remove the overlay once all batches leading up to it have - * been acknowledged. - */ -declare interface DocumentOverlayCache { - /** - * Gets the saved overlay mutation for the given document key. - * Returns null if there is no overlay for that key. - */ - getOverlay( - transaction: PersistenceTransaction, - key: _DocumentKey - ): PersistencePromise; - /** - * Gets the saved overlay mutation for the given document keys. Skips keys for - * which there are no overlays. - */ - getOverlays( - transaction: PersistenceTransaction, - keys: _DocumentKey[] - ): PersistencePromise; - /** - * Saves the given document mutation map to persistence as overlays. - * All overlays will have their largest batch id set to `largestBatchId`. - */ - saveOverlays( - transaction: PersistenceTransaction, - largestBatchId: number, - overlays: MutationMap - ): PersistencePromise; - /** Removes overlays for the given document keys and batch ID. */ - removeOverlaysForBatchId( - transaction: PersistenceTransaction, - documentKeys: DocumentKeySet, - batchId: number - ): PersistencePromise; - /** - * Returns all saved overlays for the given collection. - * - * @param transaction - The persistence transaction to use for this operation. - * @param collection - The collection path to get the overlays for. - * @param sinceBatchId - The minimum batch ID to filter by (exclusive). - * Only overlays that contain a change past `sinceBatchId` are returned. - * @returns Mapping of each document key in the collection to its overlay. - */ - getOverlaysForCollection( - transaction: PersistenceTransaction, - collection: _ResourcePath, - sinceBatchId: number - ): PersistencePromise; - /** - * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the - * provided collection group, processed by ascending batch ID. The method - * always returns all overlays for a batch even if the last batch contains - * more documents than the remaining limit. - * - * @param transaction - The persistence transaction used for this operation. - * @param collectionGroup - The collection group to get the overlays for. - * @param sinceBatchId - The minimum batch ID to filter by (exclusive). - * Only overlays that contain a change past `sinceBatchId` are returned. - * @param count - The number of overlays to return. Can be exceeded if the last - * batch contains more entries. - * @return Mapping of each document key in the collection group to its overlay. - */ - getOverlaysForCollectionGroup( - transaction: PersistenceTransaction, - collectionGroup: string, - sinceBatchId: number, - count: number - ): PersistencePromise; -} - -/** - * A `DocumentReference` refers to a document location in a Firestore database - * and can be used to write, read, or listen to the location. The document at - * the referenced location may or may not exist. - */ -export declare class DocumentReference< - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> { - /** - * If provided, the `FirestoreDataConverter` associated with this instance. - */ - readonly converter: FirestoreDataConverter_2< - AppModelType, - DbModelType - > | null; - readonly _key: _DocumentKey; - /** The type of this Firestore reference. */ - readonly type = 'document'; - /** - * The {@link Firestore} instance the document is in. - * This is useful for performing transactions, for example. - */ - readonly firestore: Firestore_2; - /** @hideconstructor */ - constructor( - firestore: Firestore_2, - /** - * If provided, the `FirestoreDataConverter` associated with this instance. - */ - converter: FirestoreDataConverter_2 | null, - _key: _DocumentKey - ); - get _path(): _ResourcePath; - /** - * The document's identifier within its collection. - */ - get id(): string; - /** - * A string representing the path of the referenced document (relative - * to the root of the database). - */ - get path(): string; - /** - * The collection this `DocumentReference` belongs to. - */ - get parent(): CollectionReference; - /** - * Applies a custom data converter to this `DocumentReference`, allowing you - * to use your own custom model objects with Firestore. When you call {@link - * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` - * instance, the provided converter will convert between Firestore data of - * type `NewDbModelType` and your custom type `NewAppModelType`. - * - * @param converter - Converts objects to and from Firestore. - * @returns A `DocumentReference` that uses the provided converter. - */ - withConverter< - NewAppModelType, - NewDbModelType extends DocumentData = DocumentData - >( - converter: FirestoreDataConverter_2 - ): DocumentReference; - /** - * Removes the current converter. - * - * @param converter - `null` removes the current converter. - * @returns A `DocumentReference` that does not - * use a converter. - */ - withConverter(converter: null): DocumentReference; -} - -/** - * DocumentSet is an immutable (copy-on-write) collection that holds documents - * in order specified by the provided comparator. We always add a document key - * comparator on top of what is provided to guarantee document equality based on - * the key. - */ -declare class DocumentSet { - /** - * Returns an empty copy of the existing DocumentSet, using the same - * comparator. - */ - static emptySet(oldSet: DocumentSet): DocumentSet; - private comparator; - private keyedMap; - private sortedSet; - /** The default ordering is by key if the comparator is omitted */ - constructor(comp?: DocumentComparator); - has(key: _DocumentKey): boolean; - get(key: _DocumentKey): Document_2 | null; - first(): Document_2 | null; - last(): Document_2 | null; - isEmpty(): boolean; - /** - * Returns the index of the provided key in the document set, or -1 if the - * document key is not present in the set; - */ - indexOf(key: _DocumentKey): number; - get size(): number; - /** Iterates documents in order defined by "comparator" */ - forEach(cb: (doc: Document_2) => void): void; - /** Inserts or updates a document with the same key */ - add(doc: Document_2): DocumentSet; - /** Deletes a document with a given key */ - delete(key: _DocumentKey): DocumentSet; - isEqual(other: DocumentSet | null | undefined): boolean; - toString(): string; - private copy; -} - -/** - * A `DocumentSnapshot` contains data read from a document in your Firestore - * database. The data can be extracted with `.data()` or `.get()` to - * get a specific field. - * - * For a `DocumentSnapshot` that points to a non-existing document, any data - * access will return 'undefined'. You can use the `exists()` method to - * explicitly verify a document's existence. - */ -export declare class DocumentSnapshot< - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> extends DocumentSnapshot_2 { - readonly _firestore: Firestore; - private readonly _firestoreImpl; - /** - * Metadata about the `DocumentSnapshot`, including information about its - * source and local modifications. - */ - readonly metadata: SnapshotMetadata; - /** @hideconstructor protected */ - constructor( - _firestore: Firestore, - userDataWriter: AbstractUserDataWriter, - key: _DocumentKey, - document: Document_2 | null, - metadata: SnapshotMetadata, - converter: UntypedFirestoreDataConverter | null - ); - /** - * Returns whether or not the data exists. True if the document exists. - */ - exists(): this is QueryDocumentSnapshot; - /** - * Retrieves all fields in the document as an `Object`. Returns `undefined` if - * the document doesn't exist. - * - * By default, `serverTimestamp()` values that have not yet been - * set to their final value will be returned as `null`. You can override - * this by passing an options object. - * - * @param options - An options object to configure how data is retrieved from - * the snapshot (for example the desired behavior for server timestamps that - * have not yet been set to their final value). - * @returns An `Object` containing all fields in the document or `undefined` if - * the document doesn't exist. - */ - data(options?: SnapshotOptions): AppModelType | undefined; - /** - * Retrieves the field specified by `fieldPath`. Returns `undefined` if the - * document or field doesn't exist. - * - * By default, a `serverTimestamp()` that has not yet been set to - * its final value will be returned as `null`. You can override this by - * passing an options object. - * - * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific - * field. - * @param options - An options object to configure how the field is retrieved - * from the snapshot (for example the desired behavior for server timestamps - * that have not yet been set to their final value). - * @returns The data at the specified field location or undefined if no such - * field exists in the document. - */ - get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; -} - -/** - * A `DocumentSnapshot` contains data read from a document in your Firestore - * database. The data can be extracted with `.data()` or `.get()` to - * get a specific field. - * - * For a `DocumentSnapshot` that points to a non-existing document, any data - * access will return 'undefined'. You can use the `exists()` method to - * explicitly verify a document's existence. - */ -declare class DocumentSnapshot_2< - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> { - _firestore: Firestore_2; - _userDataWriter: AbstractUserDataWriter; - _key: _DocumentKey; - _document: Document_2 | null; - _converter: UntypedFirestoreDataConverter | null; - /** @hideconstructor protected */ - constructor( - _firestore: Firestore_2, - _userDataWriter: AbstractUserDataWriter, - _key: _DocumentKey, - _document: Document_2 | null, - _converter: UntypedFirestoreDataConverter | null - ); - /** Property of the `DocumentSnapshot` that provides the document's ID. */ - get id(): string; - /** - * The `DocumentReference` for the document included in the `DocumentSnapshot`. - */ - get ref(): DocumentReference; - /** - * Signals whether or not the document at the snapshot's location exists. - * - * @returns true if the document exists. - */ - exists(): this is QueryDocumentSnapshot_2; - /** - * Retrieves all fields in the document as an `Object`. Returns `undefined` if - * the document doesn't exist. - * - * @returns An `Object` containing all fields in the document or `undefined` - * if the document doesn't exist. - */ - data(): AppModelType | undefined; - /** - * Retrieves the field specified by `fieldPath`. Returns `undefined` if the - * document or field doesn't exist. - * - * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific - * field. - * @returns The data at the specified field location or undefined if no such - * field exists in the document. - */ - get(fieldPath: string | FieldPath): any; -} - -declare type DocumentVersionMap = SortedMap<_DocumentKey, SnapshotVersion>; - -declare interface DocumentViewChange { - type: ChangeType; - doc: Document_2; -} - -/* Excluded from this release type: _EmptyAppCheckTokenProvider */ - -/* Excluded from this release type: _EmptyAuthCredentialsProvider */ -export { EmulatorMockTokenOptions }; - -/** - * Attempts to enable persistent storage, if possible. - * - * On failure, `enableIndexedDbPersistence()` will reject the promise or - * throw an exception. There are several reasons why this can fail, which can be - * identified by the `code` on the error. - * - * * failed-precondition: The app is already open in another browser tab. - * * unimplemented: The browser is incompatible with the offline persistence - * implementation. - * - * Note that even after a failure, the {@link Firestore} instance will remain - * usable, however offline persistence will be disabled. - * - * Note: `enableIndexedDbPersistence()` must be called before any other functions - * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or - * {@link clearIndexedDbPersistence}. - * - * Persistence cannot be used in a Node.js environment. - * - * @param firestore - The {@link Firestore} instance to enable persistence for. - * @param persistenceSettings - Optional settings object to configure - * persistence. - * @returns A `Promise` that represents successfully enabling persistent storage. - * @deprecated This function will be removed in a future major release. Instead, set - * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to - * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` - * is already specified will throw an exception. - */ -export declare function enableIndexedDbPersistence( - firestore: Firestore, - persistenceSettings?: PersistenceSettings -): Promise; - -/** - * Attempts to enable multi-tab persistent storage, if possible. If enabled - * across all tabs, all operations share access to local persistence, including - * shared execution of queries and latency-compensated local document updates - * across all connected instances. - * - * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or - * throw an exception. There are several reasons why this can fail, which can be - * identified by the `code` on the error. - * - * * failed-precondition: The app is already open in another browser tab and - * multi-tab is not enabled. - * * unimplemented: The browser is incompatible with the offline persistence - * implementation. - * - * Note that even after a failure, the {@link Firestore} instance will remain - * usable, however offline persistence will be disabled. - * - * @param firestore - The {@link Firestore} instance to enable persistence for. - * @returns A `Promise` that represents successfully enabling persistent - * storage. - * @deprecated This function will be removed in a future major release. Instead, set - * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to - * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` - * is already specified will throw an exception. - */ -export declare function enableMultiTabIndexedDbPersistence( - firestore: Firestore -): Promise; - -/** - * Re-enables use of the network for this {@link Firestore} instance after a prior - * call to {@link disableNetwork}. - * - * @returns A `Promise` that is resolved once the network has been enabled. - */ -export declare function enableNetwork(firestore: Firestore): Promise; - -/** - * Enables the SDK to create persistent cache indexes automatically for local - * query execution when the SDK believes cache indexes can help improve - * performance. - * - * This feature is disabled by default. - */ -export declare function enablePersistentCacheIndexAutoCreation( - indexManager: PersistentCacheIndexManager -): void; - -/** - * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at - * the provided document (inclusive). The end position is relative to the order - * of the query. The document must contain all of the fields provided in the - * orderBy of the query. - * - * @param snapshot - The snapshot of the document to end at. - * @returns A {@link QueryEndAtConstraint} to pass to `query()` - */ -export declare function endAt( - snapshot: DocumentSnapshot_2 -): QueryEndAtConstraint; - -/** - * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at - * the provided fields relative to the order of the query. The order of the field - * values must match the order of the order by clauses of the query. - * - * @param fieldValues - The field values to end this query at, in order - * of the query's order by. - * @returns A {@link QueryEndAtConstraint} to pass to `query()` - */ -export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; - -/** - * Creates a {@link QueryEndAtConstraint} that modifies the result set to end - * before the provided document (exclusive). The end position is relative to the - * order of the query. The document must contain all of the fields provided in - * the orderBy of the query. - * - * @param snapshot - The snapshot of the document to end before. - * @returns A {@link QueryEndAtConstraint} to pass to `query()` - */ -export declare function endBefore< - AppModelType, - DbModelType extends DocumentData ->( - snapshot: DocumentSnapshot_2 -): QueryEndAtConstraint; - -/** - * Creates a {@link QueryEndAtConstraint} that modifies the result set to end - * before the provided fields relative to the order of the query. The order of - * the field values must match the order of the order by clauses of the query. - * - * @param fieldValues - The field values to end this query before, in order - * of the query's order by. - * @returns A {@link QueryEndAtConstraint} to pass to `query()` - */ -export declare function endBefore( - ...fieldValues: unknown[] -): QueryEndAtConstraint; - -/* Excluded from this release type: ensureFirestoreConfigured */ - -declare interface Entry { - key: K; - value: V; -} - -/** - * EventManager is responsible for mapping queries to query event emitters. - * It handles "fan-out". -- Identical queries will re-use the same watch on the - * backend. - * - * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be - * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This - * allows users to tree-shake the Watch logic. - */ -declare interface EventManager { - onListen?: ( - query: Query_2, - enableRemoteListen: boolean - ) => Promise; - onUnlisten?: (query: Query_2, disableRemoteListen: boolean) => Promise; - onFirstRemoteStoreListen?: (query: Query_2) => Promise; - onLastRemoteStoreUnlisten?: (query: Query_2) => Promise; - terminate(): void; -} - -/* Excluded from this release type: executeWrite */ - -/** - * @license - * Copyright 2023 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Options that configure the SDK’s underlying network transport (WebChannel) - * when long-polling is used. - * - * Note: This interface is "experimental" and is subject to change. - * - * See `FirestoreSettings.experimentalAutoDetectLongPolling`, - * `FirestoreSettings.experimentalForceLongPolling`, and - * `FirestoreSettings.experimentalLongPollingOptions`. - */ -export declare interface ExperimentalLongPollingOptions { - /** - * The desired maximum timeout interval, in seconds, to complete a - * long-polling GET response. Valid values are between 5 and 30, inclusive. - * Floating point values are allowed and will be rounded to the nearest - * millisecond. - * - * By default, when long-polling is used the "hanging GET" request sent by - * the client times out after 30 seconds. To request a different timeout - * from the server, set this setting with the desired timeout. - * - * Changing the default timeout may be useful, for example, if the buffering - * proxy that necessitated enabling long-polling in the first place has a - * shorter timeout for hanging GET requests, in which case setting the - * long-polling timeout to a shorter value, such as 25 seconds, may fix - * prematurely-closed hanging GET requests. - * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. - */ - timeoutSeconds?: number; -} - -declare class FieldFilter extends Filter { - readonly field: _FieldPath; - readonly op: Operator; - readonly value: Value; - protected constructor(field: _FieldPath, op: Operator, value: Value); - /** - * Creates a filter based on the provided arguments. - */ - static create(field: _FieldPath, op: Operator, value: Value): FieldFilter; - private static createKeyFieldInFilter; - matches(doc: Document_2): boolean; - protected matchesComparison(comparison: number): boolean; - isInequality(): boolean; - getFlattenedFilters(): readonly FieldFilter[]; - getFilters(): Filter[]; -} - -declare type FieldFilterOp = - | 'OPERATOR_UNSPECIFIED' - | 'LESS_THAN' - | 'LESS_THAN_OR_EQUAL' - | 'GREATER_THAN' - | 'GREATER_THAN_OR_EQUAL' - | 'EQUAL' - | 'NOT_EQUAL' - | 'ARRAY_CONTAINS' - | 'IN' - | 'ARRAY_CONTAINS_ANY' - | 'NOT_IN'; - -/** - * An index definition for field indexes in Firestore. - * - * Every index is associated with a collection. The definition contains a list - * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or - * `CONTAINS` for ArrayContains/ArrayContainsAny queries). - * - * Unlike the backend, the SDK does not differentiate between collection or - * collection group-scoped indices. Every index can be used for both single - * collection and collection group queries. - */ -declare class FieldIndex { - /** - * The index ID. Returns -1 if the index ID is not available (e.g. the index - * has not yet been persisted). - */ - readonly indexId: number; - /** The collection ID this index applies to. */ - readonly collectionGroup: string; - /** The field segments for this index. */ - readonly fields: IndexSegment[]; - /** Shows how up-to-date the index is for the current user. */ - readonly indexState: IndexState; - /** An ID for an index that has not yet been added to persistence. */ - static UNKNOWN_ID: number; - constructor( - /** - * The index ID. Returns -1 if the index ID is not available (e.g. the index - * has not yet been persisted). - */ - indexId: number, - /** The collection ID this index applies to. */ - collectionGroup: string, - /** The field segments for this index. */ - fields: IndexSegment[], - /** Shows how up-to-date the index is for the current user. */ - indexState: IndexState - ); -} - -/** - * Provides a set of fields that can be used to partially patch a document. - * FieldMask is used in conjunction with ObjectValue. - * Examples: - * foo - Overwrites foo entirely with the provided value. If foo is not - * present in the companion ObjectValue, the field is deleted. - * foo.bar - Overwrites only the field bar of the object foo. - * If foo is not an object, foo is replaced with an object - * containing foo - */ -declare class FieldMask { - readonly fields: _FieldPath[]; - constructor(fields: _FieldPath[]); - static empty(): FieldMask; - /** - * Returns a new FieldMask object that is the result of adding all the given - * fields paths to this field mask. - */ - unionWith(extraFields: _FieldPath[]): FieldMask; - /** - * Verifies that `fieldPath` is included by at least one field in this field - * mask. - * - * This is an O(n) operation, where `n` is the size of the field mask. - */ - covers(fieldPath: _FieldPath): boolean; - isEqual(other: FieldMask): boolean; -} - -/** - * A `FieldPath` refers to a field in a document. The path may consist of a - * single field name (referring to a top-level field in the document), or a - * list of field names (referring to a nested field in the document). - * - * Create a `FieldPath` by providing field names. If more than one field - * name is provided, the path will point to a nested field in a document. - */ -export declare class FieldPath { - /** Internal representation of a Firestore field path. */ - readonly _internalPath: _FieldPath; - /** - * Creates a `FieldPath` from the provided field names. If more than one field - * name is provided, the path will point to a nested field in a document. - * - * @param fieldNames - A list of field names. - */ - constructor(...fieldNames: string[]); - /** - * Returns true if this `FieldPath` is equal to the provided one. - * - * @param other - The `FieldPath` to compare against. - * @returns true if this `FieldPath` is equal to the provided one. - */ - isEqual(other: FieldPath): boolean; -} - -/* Excluded from this release type: _FieldPath */ - -/** A field path and the TransformOperation to perform upon it. */ -declare class FieldTransform { - readonly field: _FieldPath; - readonly transform: TransformOperation; - constructor(field: _FieldPath, transform: TransformOperation); -} - -declare type FieldTransformSetToServerValue = - | 'SERVER_VALUE_UNSPECIFIED' - | 'REQUEST_TIME'; - -/** - * Sentinel values that can be used when writing document fields with `set()` - * or `update()`. - */ -export declare abstract class FieldValue { - _methodName: string; - /** - * @param _methodName - The public API endpoint that returns this class. - * @hideconstructor - */ - constructor(_methodName: string); - /** Compares `FieldValue`s for equality. */ - abstract isEqual(other: FieldValue): boolean; - abstract _toFieldTransform(context: ParseContext): FieldTransform | null; -} - -declare abstract class Filter { - abstract matches(doc: Document_2): boolean; - abstract getFlattenedFilters(): readonly FieldFilter[]; - abstract getFilters(): Filter[]; -} - -/* Excluded from this release type: _FirebaseService */ - -/** - * The Cloud Firestore service interface. - * - * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. - */ -export declare class Firestore extends Firestore_2 { - /** - * Whether it's a {@link Firestore} or Firestore Lite instance. - */ - type: 'firestore-lite' | 'firestore'; - _queue: AsyncQueue; - readonly _persistenceKey: string; - _firestoreClient: FirestoreClient | undefined; - _componentsProvider?: { - _offline: OfflineComponentProviderFactory; - _online: OnlineComponentProviderFactory; - }; - /** @hideconstructor */ - constructor( - authCredentialsProvider: CredentialsProvider, - appCheckCredentialsProvider: CredentialsProvider, - databaseId: _DatabaseId, - app?: FirebaseApp - ); - protected _terminate(): Promise; -} - -/** - * The Cloud Firestore service interface. - * - * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. - */ -declare class Firestore_2 implements FirestoreService { - _authCredentials: CredentialsProvider; - _appCheckCredentials: CredentialsProvider; - readonly _databaseId: _DatabaseId; - readonly _app?: FirebaseApp | undefined; - /** - * Whether it's a Firestore or Firestore Lite instance. - */ - type: 'firestore-lite' | 'firestore'; - readonly _persistenceKey: string; - private _settings; - private _settingsFrozen; - private _terminateTask; - /** @hideconstructor */ - constructor( - _authCredentials: CredentialsProvider, - _appCheckCredentials: CredentialsProvider, - _databaseId: _DatabaseId, - _app?: FirebaseApp | undefined - ); - /** - * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service - * instance. - */ - get app(): FirebaseApp; - get _initialized(): boolean; - get _terminated(): boolean; - _setSettings(settings: PrivateSettings): void; - _getSettings(): FirestoreSettingsImpl; - _freezeSettings(): FirestoreSettingsImpl; - _delete(): Promise; - _restart(): Promise; - /** Returns a JSON-serializable representation of this `Firestore` instance. */ - toJSON(): object; - /** - * Terminates all components used by this client. Subclasses can override - * this method to clean up their own dependencies, but must also call this - * method. - * - * Only ever called once. - */ - protected _terminate(): Promise; -} - -/** - * FirestoreClient is a top-level class that constructs and owns all of the // - * pieces of the client SDK architecture. It is responsible for creating the // - * async queue that is shared by all of the other components in the system. // - */ -declare class FirestoreClient { - private authCredentials; - private appCheckCredentials; - /** - * Asynchronous queue responsible for all of our internal processing. When - * we get incoming work from the user (via public API) or the network - * (incoming GRPC messages), we should always schedule onto this queue. - * This ensures all of our work is properly serialized (e.g. we don't - * start processing a new operation while the previous one is waiting for - * an async I/O to complete). - */ - asyncQueue: AsyncQueue; - private databaseInfo; - private user; - private readonly clientId; - private authCredentialListener; - private appCheckCredentialListener; - _uninitializedComponentsProvider?: { - _offline: OfflineComponentProvider; - _online: OnlineComponentProvider; - }; - _offlineComponents?: OfflineComponentProvider; - _onlineComponents?: OnlineComponentProvider; - constructor( - authCredentials: CredentialsProvider, - appCheckCredentials: CredentialsProvider, - /** - * Asynchronous queue responsible for all of our internal processing. When - * we get incoming work from the user (via public API) or the network - * (incoming GRPC messages), we should always schedule onto this queue. - * This ensures all of our work is properly serialized (e.g. we don't - * start processing a new operation while the previous one is waiting for - * an async I/O to complete). - */ - asyncQueue: AsyncQueue, - databaseInfo: DatabaseInfo, - componentProvider?: { - _offline: OfflineComponentProvider; - _online: OnlineComponentProvider; - } - ); - get configuration(): ComponentConfiguration; - setCredentialChangeListener(listener: (user: User) => Promise): void; - setAppCheckTokenChangeListener( - listener: (appCheckToken: string, user: User) => Promise - ): void; - terminate(): Promise; -} - -/** - * Converter used by `withConverter()` to transform user objects of type - * `AppModelType` into Firestore data of type `DbModelType`. - * - * Using the converter allows you to specify generic type arguments when - * storing and retrieving objects from Firestore. - * - * In this context, an "AppModel" is a class that is used in an application to - * package together related information and functionality. Such a class could, - * for example, have properties with complex, nested data types, properties used - * for memoization, properties of types not supported by Firestore (such as - * `symbol` and `bigint`), and helper functions that perform compound - * operations. Such classes are not suitable and/or possible to store into a - * Firestore database. Instead, instances of such classes need to be converted - * to "plain old JavaScript objects" (POJOs) with exclusively primitive - * properties, potentially nested inside other POJOs or arrays of POJOs. In this - * context, this type is referred to as the "DbModel" and would be an object - * suitable for persisting into Firestore. For convenience, applications can - * implement `FirestoreDataConverter` and register the converter with Firestore - * objects, such as `DocumentReference` or `Query`, to automatically convert - * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` - * to `AppModel` when retrieving from Firestore. - * - * @example - * - * Simple Example - * - * ```typescript - * const numberConverter = { - * toFirestore(value: WithFieldValue) { - * return { value }; - * }, - * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { - * return snapshot.data(options).value as number; - * } - * }; - * - * async function simpleDemo(db: Firestore): Promise { - * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); - * - * // converters are used with `setDoc`, `addDoc`, and `getDoc` - * await setDoc(documentRef, 42); - * const snapshot1 = await getDoc(documentRef); - * assertEqual(snapshot1.data(), 42); - * - * // converters are not used when writing data with `updateDoc` - * await updateDoc(documentRef, { value: 999 }); - * const snapshot2 = await getDoc(documentRef); - * assertEqual(snapshot2.data(), 999); - * } - * ``` - * - * Advanced Example - * - * ```typescript - * // The Post class is a model that is used by our application. - * // This class may have properties and methods that are specific - * // to our application execution, which do not need to be persisted - * // to Firestore. - * class Post { - * constructor( - * readonly title: string, - * readonly author: string, - * readonly lastUpdatedMillis: number - * ) {} - * toString(): string { - * return `${this.title} by ${this.author}`; - * } - * } - * - * // The PostDbModel represents how we want our posts to be stored - * // in Firestore. This DbModel has different properties (`ttl`, - * // `aut`, and `lut`) from the Post class we use in our application. - * interface PostDbModel { - * ttl: string; - * aut: { firstName: string; lastName: string }; - * lut: Timestamp; - * } - * - * // The `PostConverter` implements `FirestoreDataConverter` and specifies - * // how the Firestore SDK can convert `Post` objects to `PostDbModel` - * // objects and vice versa. - * class PostConverter implements FirestoreDataConverter { - * toFirestore(post: WithFieldValue): WithFieldValue { - * return { - * ttl: post.title, - * aut: this._autFromAuthor(post.author), - * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) - * }; - * } - * - * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { - * const data = snapshot.data(options) as PostDbModel; - * const author = `${data.aut.firstName} ${data.aut.lastName}`; - * return new Post(data.ttl, author, data.lut.toMillis()); - * } - * - * _autFromAuthor( - * author: string | FieldValue - * ): { firstName: string; lastName: string } | FieldValue { - * if (typeof author !== 'string') { - * // `author` is a FieldValue, so just return it. - * return author; - * } - * const [firstName, lastName] = author.split(' '); - * return {firstName, lastName}; - * } - * - * _lutFromLastUpdatedMillis( - * lastUpdatedMillis: number | FieldValue - * ): Timestamp | FieldValue { - * if (typeof lastUpdatedMillis !== 'number') { - * // `lastUpdatedMillis` must be a FieldValue, so just return it. - * return lastUpdatedMillis; - * } - * return Timestamp.fromMillis(lastUpdatedMillis); - * } - * } - * - * async function advancedDemo(db: Firestore): Promise { - * // Create a `DocumentReference` with a `FirestoreDataConverter`. - * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); - * - * // The `data` argument specified to `setDoc()` is type checked by the - * // TypeScript compiler to be compatible with `Post`. Since the `data` - * // argument is typed as `WithFieldValue` rather than just `Post`, - * // this allows properties of the `data` argument to also be special - * // Firestore values that perform server-side mutations, such as - * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. - * await setDoc(documentRef, { - * title: 'My Life', - * author: 'Foo Bar', - * lastUpdatedMillis: serverTimestamp() - * }); - * - * // The TypeScript compiler will fail to compile if the `data` argument to - * // `setDoc()` is _not_ compatible with `WithFieldValue`. This - * // type checking prevents the caller from specifying objects with incorrect - * // properties or property values. - * // @ts-expect-error "Argument of type { ttl: string; } is not assignable - * // to parameter of type WithFieldValue" - * await setDoc(documentRef, { ttl: 'The Title' }); - * - * // When retrieving a document with `getDoc()` the `DocumentSnapshot` - * // object's `data()` method returns a `Post`, rather than a generic object, - * // which would have been returned if the `DocumentReference` did _not_ have a - * // `FirestoreDataConverter` attached to it. - * const snapshot1: DocumentSnapshot = await getDoc(documentRef); - * const post1: Post = snapshot1.data()!; - * if (post1) { - * assertEqual(post1.title, 'My Life'); - * assertEqual(post1.author, 'Foo Bar'); - * } - * - * // The `data` argument specified to `updateDoc()` is type checked by the - * // TypeScript compiler to be compatible with `PostDbModel`. Note that - * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, - * // the `data` argument to `updateDoc()` must be compatible with - * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed - * // as `WithFieldValue` rather than just `PostDbModel`, this - * // allows properties of the `data` argument to also be those special - * // Firestore values, like `arrayRemove()`, `deleteField()`, and - * // `serverTimestamp()`. - * await updateDoc(documentRef, { - * 'aut.firstName': 'NewFirstName', - * lut: serverTimestamp() - * }); - * - * // The TypeScript compiler will fail to compile if the `data` argument to - * // `updateDoc()` is _not_ compatible with `WithFieldValue`. - * // This type checking prevents the caller from specifying objects with - * // incorrect properties or property values. - * // @ts-expect-error "Argument of type { title: string; } is not assignable - * // to parameter of type WithFieldValue" - * await updateDoc(documentRef, { title: 'New Title' }); - * const snapshot2: DocumentSnapshot = await getDoc(documentRef); - * const post2: Post = snapshot2.data()!; - * if (post2) { - * assertEqual(post2.title, 'My Life'); - * assertEqual(post2.author, 'NewFirstName Bar'); - * } - * } - * ``` - */ -export declare interface FirestoreDataConverter< - AppModelType, - DbModelType extends DocumentData = DocumentData -> extends FirestoreDataConverter_2 { - /** - * Called by the Firestore SDK to convert a custom model object of type - * `AppModelType` into a plain JavaScript object (suitable for writing - * directly to the Firestore database) of type `DbModelType`. To use `set()` - * with `merge` and `mergeFields`, `toFirestore()` must be defined with - * `PartialWithFieldValue`. - * - * The `WithFieldValue` type extends `T` to also allow FieldValues such as - * {@link (deleteField:1)} to be used as property values. - */ - toFirestore( - modelObject: WithFieldValue - ): WithFieldValue; - /** - * Called by the Firestore SDK to convert a custom model object of type - * `AppModelType` into a plain JavaScript object (suitable for writing - * directly to the Firestore database) of type `DbModelType`. Used with - * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and - * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. - * - * The `PartialWithFieldValue` type extends `Partial` to allow - * FieldValues such as {@link (arrayUnion:1)} to be used as property values. - * It also supports nested `Partial` by allowing nested fields to be - * omitted. - */ - toFirestore( - modelObject: PartialWithFieldValue, - options: SetOptions - ): PartialWithFieldValue; - /** - * Called by the Firestore SDK to convert Firestore data into an object of - * type `AppModelType`. You can access your data by calling: - * `snapshot.data(options)`. - * - * Generally, the data returned from `snapshot.data()` can be cast to - * `DbModelType`; however, this is not guaranteed because Firestore does not - * enforce a schema on the database. For example, writes from a previous - * version of the application or writes from another client that did not use a - * type converter could have written data with different properties and/or - * property types. The implementation will need to choose whether to - * gracefully recover from non-conforming data or throw an error. - * - * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. - * - * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. - * @param options - The `SnapshotOptions` from the initial call to `data()`. - */ - fromFirestore( - snapshot: QueryDocumentSnapshot, - options?: SnapshotOptions - ): AppModelType; -} - -/** - * Converter used by `withConverter()` to transform user objects of type - * `AppModelType` into Firestore data of type `DbModelType`. - * - * Using the converter allows you to specify generic type arguments when - * storing and retrieving objects from Firestore. - * - * In this context, an "AppModel" is a class that is used in an application to - * package together related information and functionality. Such a class could, - * for example, have properties with complex, nested data types, properties used - * for memoization, properties of types not supported by Firestore (such as - * `symbol` and `bigint`), and helper functions that perform compound - * operations. Such classes are not suitable and/or possible to store into a - * Firestore database. Instead, instances of such classes need to be converted - * to "plain old JavaScript objects" (POJOs) with exclusively primitive - * properties, potentially nested inside other POJOs or arrays of POJOs. In this - * context, this type is referred to as the "DbModel" and would be an object - * suitable for persisting into Firestore. For convenience, applications can - * implement `FirestoreDataConverter` and register the converter with Firestore - * objects, such as `DocumentReference` or `Query`, to automatically convert - * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` - * to `AppModel` when retrieving from Firestore. - * - * @example - * - * Simple Example - * - * ```typescript - * const numberConverter = { - * toFirestore(value: WithFieldValue) { - * return { value }; - * }, - * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { - * return snapshot.data(options).value as number; - * } - * }; - * - * async function simpleDemo(db: Firestore): Promise { - * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); - * - * // converters are used with `setDoc`, `addDoc`, and `getDoc` - * await setDoc(documentRef, 42); - * const snapshot1 = await getDoc(documentRef); - * assertEqual(snapshot1.data(), 42); - * - * // converters are not used when writing data with `updateDoc` - * await updateDoc(documentRef, { value: 999 }); - * const snapshot2 = await getDoc(documentRef); - * assertEqual(snapshot2.data(), 999); - * } - * ``` - * - * Advanced Example - * - * ```typescript - * // The Post class is a model that is used by our application. - * // This class may have properties and methods that are specific - * // to our application execution, which do not need to be persisted - * // to Firestore. - * class Post { - * constructor( - * readonly title: string, - * readonly author: string, - * readonly lastUpdatedMillis: number - * ) {} - * toString(): string { - * return `${this.title} by ${this.author}`; - * } - * } - * - * // The PostDbModel represents how we want our posts to be stored - * // in Firestore. This DbModel has different properties (`ttl`, - * // `aut`, and `lut`) from the Post class we use in our application. - * interface PostDbModel { - * ttl: string; - * aut: { firstName: string; lastName: string }; - * lut: Timestamp; - * } - * - * // The `PostConverter` implements `FirestoreDataConverter` and specifies - * // how the Firestore SDK can convert `Post` objects to `PostDbModel` - * // objects and vice versa. - * class PostConverter implements FirestoreDataConverter { - * toFirestore(post: WithFieldValue): WithFieldValue { - * return { - * ttl: post.title, - * aut: this._autFromAuthor(post.author), - * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) - * }; - * } - * - * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { - * const data = snapshot.data(options) as PostDbModel; - * const author = `${data.aut.firstName} ${data.aut.lastName}`; - * return new Post(data.ttl, author, data.lut.toMillis()); - * } - * - * _autFromAuthor( - * author: string | FieldValue - * ): { firstName: string; lastName: string } | FieldValue { - * if (typeof author !== 'string') { - * // `author` is a FieldValue, so just return it. - * return author; - * } - * const [firstName, lastName] = author.split(' '); - * return {firstName, lastName}; - * } - * - * _lutFromLastUpdatedMillis( - * lastUpdatedMillis: number | FieldValue - * ): Timestamp | FieldValue { - * if (typeof lastUpdatedMillis !== 'number') { - * // `lastUpdatedMillis` must be a FieldValue, so just return it. - * return lastUpdatedMillis; - * } - * return Timestamp.fromMillis(lastUpdatedMillis); - * } - * } - * - * async function advancedDemo(db: Firestore): Promise { - * // Create a `DocumentReference` with a `FirestoreDataConverter`. - * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); - * - * // The `data` argument specified to `setDoc()` is type checked by the - * // TypeScript compiler to be compatible with `Post`. Since the `data` - * // argument is typed as `WithFieldValue` rather than just `Post`, - * // this allows properties of the `data` argument to also be special - * // Firestore values that perform server-side mutations, such as - * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. - * await setDoc(documentRef, { - * title: 'My Life', - * author: 'Foo Bar', - * lastUpdatedMillis: serverTimestamp() - * }); - * - * // The TypeScript compiler will fail to compile if the `data` argument to - * // `setDoc()` is _not_ compatible with `WithFieldValue`. This - * // type checking prevents the caller from specifying objects with incorrect - * // properties or property values. - * // @ts-expect-error "Argument of type { ttl: string; } is not assignable - * // to parameter of type WithFieldValue" - * await setDoc(documentRef, { ttl: 'The Title' }); - * - * // When retrieving a document with `getDoc()` the `DocumentSnapshot` - * // object's `data()` method returns a `Post`, rather than a generic object, - * // which would have been returned if the `DocumentReference` did _not_ have a - * // `FirestoreDataConverter` attached to it. - * const snapshot1: DocumentSnapshot = await getDoc(documentRef); - * const post1: Post = snapshot1.data()!; - * if (post1) { - * assertEqual(post1.title, 'My Life'); - * assertEqual(post1.author, 'Foo Bar'); - * } - * - * // The `data` argument specified to `updateDoc()` is type checked by the - * // TypeScript compiler to be compatible with `PostDbModel`. Note that - * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, - * // the `data` argument to `updateDoc()` must be compatible with - * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed - * // as `WithFieldValue` rather than just `PostDbModel`, this - * // allows properties of the `data` argument to also be those special - * // Firestore values, like `arrayRemove()`, `deleteField()`, and - * // `serverTimestamp()`. - * await updateDoc(documentRef, { - * 'aut.firstName': 'NewFirstName', - * lut: serverTimestamp() - * }); - * - * // The TypeScript compiler will fail to compile if the `data` argument to - * // `updateDoc()` is _not_ compatible with `WithFieldValue`. - * // This type checking prevents the caller from specifying objects with - * // incorrect properties or property values. - * // @ts-expect-error "Argument of type { title: string; } is not assignable - * // to parameter of type WithFieldValue" - * await updateDoc(documentRef, { title: 'New Title' }); - * const snapshot2: DocumentSnapshot = await getDoc(documentRef); - * const post2: Post = snapshot2.data()!; - * if (post2) { - * assertEqual(post2.title, 'My Life'); - * assertEqual(post2.author, 'NewFirstName Bar'); - * } - * } - * ``` - */ -declare interface FirestoreDataConverter_2< - 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`. Used with - * {@link @firebase/firestore/lite#(setDoc:1)}, - * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and - * {@link @firebase/firestore/lite#(Transaction.set:1)}. - * - * The `WithFieldValue` type extends `T` to also allow FieldValues such as - * {@link (deleteField:1)} to be used as property values. - */ - toFirestore( - modelObject: WithFieldValue - ): WithFieldValue; - /** - * Called by the Firestore SDK to convert a custom model object of type - * `AppModelType` into a plain JavaScript object (suitable for writing - * directly to the Firestore database) of type `DbModelType`. Used with - * {@link @firebase/firestore/lite#(setDoc:1)}, - * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and - * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` - * or `mergeFields`. - * - * The `PartialWithFieldValue` type extends `Partial` to allow - * FieldValues such as {@link (arrayUnion:1)} to be used as property values. - * It also supports nested `Partial` by allowing nested fields to be - * omitted. - */ - toFirestore( - modelObject: PartialWithFieldValue, - options: SetOptions - ): PartialWithFieldValue; - /** - * Called by the Firestore SDK to convert Firestore data into an object of - * type `AppModelType`. You can access your data by calling: - * `snapshot.data()`. - * - * - * Generally, the data returned from `snapshot.data()` can be cast to - * `DbModelType`; however, this is not guaranteed because Firestore does not - * enforce a schema on the database. For example, writes from a previous - * version of the application or writes from another client that did not use a - * type converter could have written data with different properties and/or - * property types. The implementation will need to choose whether to - * gracefully recover from non-conforming data or throw an error. - * - * @param snapshot - A `QueryDocumentSnapshot` containing your data and - * metadata. - */ - fromFirestore( - snapshot: QueryDocumentSnapshot_2 - ): AppModelType; -} - -/** An error returned by a Firestore operation. */ -export declare class FirestoreError extends FirebaseError { - /** - * The backend error code associated with this error. - */ - readonly code: FirestoreErrorCode; - /** - * A custom error description. - */ - readonly message: string; - /** The stack of the error. */ - readonly stack?: string; - /** @hideconstructor */ - constructor( - /** - * The backend error code associated with this error. - */ - code: FirestoreErrorCode, - /** - * A custom error description. - */ - message: string - ); -} - -/** - * The set of Firestore status codes. The codes are the same at the ones - * exposed by gRPC here: - * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md - * - * Possible values: - * - 'cancelled': The operation was cancelled (typically by the caller). - * - 'unknown': Unknown error or an error from a different error domain. - * - 'invalid-argument': Client specified an invalid argument. Note that this - * differs from 'failed-precondition'. 'invalid-argument' indicates - * arguments that are problematic regardless of the state of the system - * (e.g. an invalid field name). - * - 'deadline-exceeded': Deadline expired before operation could complete. - * For operations that change the state of the system, this error may be - * returned even if the operation has completed successfully. For example, - * a successful response from a server could have been delayed long enough - * for the deadline to expire. - * - 'not-found': Some requested document was not found. - * - 'already-exists': Some document that we attempted to create already - * exists. - * - 'permission-denied': The caller does not have permission to execute the - * specified operation. - * - 'resource-exhausted': Some resource has been exhausted, perhaps a - * per-user quota, or perhaps the entire file system is out of space. - * - 'failed-precondition': Operation was rejected because the system is not - * in a state required for the operation's execution. - * - 'aborted': The operation was aborted, typically due to a concurrency - * issue like transaction aborts, etc. - * - 'out-of-range': Operation was attempted past the valid range. - * - 'unimplemented': Operation is not implemented or not supported/enabled. - * - 'internal': Internal errors. Means some invariants expected by - * underlying system has been broken. If you see one of these errors, - * something is very broken. - * - 'unavailable': The service is currently unavailable. This is most likely - * a transient condition and may be corrected by retrying with a backoff. - * - 'data-loss': Unrecoverable data loss or corruption. - * - 'unauthenticated': The request does not have valid authentication - * credentials for the operation. - */ -export declare type FirestoreErrorCode = - | 'cancelled' - | 'unknown' - | 'invalid-argument' - | 'deadline-exceeded' - | 'not-found' - | 'already-exists' - | 'permission-denied' - | 'resource-exhausted' - | 'failed-precondition' - | 'aborted' - | 'out-of-range' - | 'unimplemented' - | 'internal' - | 'unavailable' - | 'data-loss' - | 'unauthenticated'; - -/** - * Union type from all supported SDK cache layer. - */ -export declare type FirestoreLocalCache = - | MemoryLocalCache - | PersistentLocalCache; - -/** - * An interface implemented by FirebaseFirestore that provides compatibility - * with the usage in this file. - * - * This interface mainly exists to remove a cyclic dependency. - */ -declare interface FirestoreService extends _FirebaseService { - _authCredentials: CredentialsProvider; - _appCheckCredentials: CredentialsProvider; - _persistenceKey: string; - _databaseId: _DatabaseId; - _terminated: boolean; - _freezeSettings(): FirestoreSettingsImpl; -} - -/** - * Specifies custom configurations for your Cloud Firestore instance. - * You must set these before invoking any other methods. - */ -export declare interface FirestoreSettings extends FirestoreSettings_2 { - /** - * NOTE: This field will be deprecated in a future major release. Use `cache` field - * instead to specify cache size, and other cache configurations. - * - * An approximate cache size threshold for the on-disk data. If the cache - * grows beyond this size, Firestore will start removing data that hasn't been - * recently used. The size is not a guarantee that the cache will stay below - * that size, only that if the cache exceeds the given size, cleanup will be - * attempted. - * - * The default value is 40 MB. The threshold must be set to at least 1 MB, and - * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. - */ - cacheSizeBytes?: number; - /** - * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` - * and `PersistentLocalCache`, each with different configuration options. - * - * When unspecified, `MemoryLocalCache` will be used by default. - * - * NOTE: setting this field and `cacheSizeBytes` at the same time will throw - * exception during SDK initialization. Instead, using the configuration in - * the `FirestoreLocalCache` object to specify the cache size. - */ - localCache?: FirestoreLocalCache; - /** - * Forces the SDK’s underlying network transport (WebChannel) to use - * long-polling. Each response from the backend will be closed immediately - * after the backend sends data (by default responses are kept open in - * case the backend has more data to send). This avoids incompatibility - * issues with certain proxies, antivirus software, etc. that incorrectly - * buffer traffic indefinitely. Use of this option will cause some - * performance degradation though. - * - * This setting cannot be used with `experimentalAutoDetectLongPolling` and - * may be removed in a future release. If you find yourself using it to - * work around a specific network reliability issue, please tell us about - * it in https://github.com/firebase/firebase-js-sdk/issues/1674. - * - * This setting cannot be used in a Node.js environment. - */ - experimentalForceLongPolling?: boolean; - /** - * Configures the SDK's underlying transport (WebChannel) to automatically - * detect if long-polling should be used. This is very similar to - * `experimentalForceLongPolling`, but only uses long-polling if required. - * - * After having had a default value of `false` since its inception in 2019, - * the default value of this setting was changed in May 2023 to `true` in - * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long - * polling is now enabled by default. To disable it, set this setting to - * `false`, and please open a GitHub issue to share the problems that - * motivated you disabling long-polling auto-detection. - * - * This setting cannot be used in a Node.js environment. - */ - experimentalAutoDetectLongPolling?: boolean; - /** - * Options that configure the SDK’s underlying network transport (WebChannel) - * when long-polling is used. - * - * These options are only used if `experimentalForceLongPolling` is true or if - * `experimentalAutoDetectLongPolling` is true and the auto-detection - * determined that long-polling was needed. Otherwise, these options have no - * effect. - */ - experimentalLongPollingOptions?: ExperimentalLongPollingOptions; -} - -/** - * Specifies custom configurations for your Cloud Firestore instance. - * You must set these before invoking any other methods. - */ -declare interface FirestoreSettings_2 { - /** The hostname to connect to. */ - host?: string; - /** Whether to use SSL when connecting. */ - ssl?: boolean; - /** - * Whether to skip nested properties that are set to `undefined` during - * object serialization. If set to `true`, these properties are skipped - * and not written to Firestore. If set to `false` or omitted, the SDK - * throws an exception when it encounters properties of type `undefined`. - */ - ignoreUndefinedProperties?: boolean; -} - -/** - * A concrete type describing all the values that can be applied via a - * user-supplied `FirestoreSettings` object. This is a separate type so that - * defaults can be supplied and the value can be checked for equality. - */ -declare class FirestoreSettingsImpl { - /** The hostname to connect to. */ - readonly host: string; - /** Whether to use SSL when connecting. */ - readonly ssl: boolean; - readonly cacheSizeBytes: number; - readonly experimentalForceLongPolling: boolean; - readonly experimentalAutoDetectLongPolling: boolean; - readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; - readonly ignoreUndefinedProperties: boolean; - readonly useFetchStreams: boolean; - readonly localCache?: FirestoreLocalCache; - credentials?: any; - constructor(settings: PrivateSettings); - isEqual(other: FirestoreSettingsImpl): boolean; -} - -declare namespace firestoreV1ApiClientInterfaces { - interface ArrayValue { - values?: Value[]; - } - interface BatchGetDocumentsRequest { - database?: string; - documents?: string[]; - mask?: DocumentMask; - transaction?: string; - newTransaction?: TransactionOptions; - readTime?: string; - } - interface BatchGetDocumentsResponse { - found?: Document; - missing?: string; - transaction?: string; - readTime?: string; - } - interface BeginTransactionRequest { - options?: TransactionOptions; - } - interface BeginTransactionResponse { - transaction?: string; - } - interface CollectionSelector { - collectionId?: string; - allDescendants?: boolean; - } - interface CommitRequest { - database?: string; - writes?: Write[]; - transaction?: string; - } - interface CommitResponse { - writeResults?: WriteResult[]; - commitTime?: string; - } - interface CompositeFilter { - op?: CompositeFilterOp; - filters?: Filter[]; - } - interface Cursor { - values?: Value[]; - before?: boolean; - } - interface Document { - name?: string; - fields?: ApiClientObjectMap; - createTime?: Timestamp_2; - updateTime?: Timestamp_2; - } - interface DocumentChange { - document?: Document; - targetIds?: number[]; - removedTargetIds?: number[]; - } - interface DocumentDelete { - document?: string; - removedTargetIds?: number[]; - readTime?: Timestamp_2; - } - interface DocumentMask { - fieldPaths?: string[]; - } - interface DocumentRemove { - document?: string; - removedTargetIds?: number[]; - readTime?: string; - } - interface DocumentTransform { - document?: string; - fieldTransforms?: FieldTransform[]; - } - interface DocumentsTarget { - documents?: string[]; - } - interface Empty {} - interface ExistenceFilter { - targetId?: number; - count?: number; - unchangedNames?: BloomFilter; - } - interface BloomFilter { - bits?: BitSequence; - hashCount?: number; - } - interface BitSequence { - bitmap?: string | Uint8Array; - padding?: number; - } - interface FieldFilter { - field?: FieldReference; - op?: FieldFilterOp; - value?: Value; - } - interface FieldReference { - fieldPath?: string; - } - interface FieldTransform { - fieldPath?: string; - setToServerValue?: FieldTransformSetToServerValue; - appendMissingElements?: ArrayValue; - removeAllFromArray?: ArrayValue; - increment?: Value; - } - interface Filter { - compositeFilter?: CompositeFilter; - fieldFilter?: FieldFilter; - unaryFilter?: UnaryFilter; - } - interface Index { - name?: string; - collectionId?: string; - fields?: IndexField[]; - state?: IndexState_2; - } - interface IndexField { - fieldPath?: string; - mode?: IndexFieldMode; - } - interface LatLng { - latitude?: number; - longitude?: number; - } - interface ListCollectionIdsRequest { - pageSize?: number; - pageToken?: string; - } - interface ListCollectionIdsResponse { - collectionIds?: string[]; - nextPageToken?: string; - } - interface ListDocumentsResponse { - documents?: Document[]; - nextPageToken?: string; - } - interface ListIndexesResponse { - indexes?: Index[]; - nextPageToken?: string; - } - interface ListenRequest { - addTarget?: Target; - removeTarget?: number; - labels?: ApiClientObjectMap; - } - interface ListenResponse { - targetChange?: TargetChange; - documentChange?: DocumentChange; - documentDelete?: DocumentDelete; - documentRemove?: DocumentRemove; - filter?: ExistenceFilter; - } - interface MapValue { - fields?: ApiClientObjectMap; - } - interface Operation { - name?: string; - metadata?: ApiClientObjectMap; - done?: boolean; - error?: Status; - response?: ApiClientObjectMap; - } - interface Order { - field?: FieldReference; - direction?: OrderDirection; - } - interface Precondition { - exists?: boolean; - updateTime?: Timestamp_2; - } - interface Projection { - fields?: FieldReference[]; - } - interface QueryTarget { - parent?: string; - structuredQuery?: StructuredQuery; - } - interface ReadOnly { - readTime?: string; - } - interface ReadWrite { - retryTransaction?: string; - } - interface RollbackRequest { - transaction?: string; - } - interface RunQueryRequest { - parent?: string; - structuredQuery?: StructuredQuery; - transaction?: string; - newTransaction?: TransactionOptions; - readTime?: string; - } - interface RunQueryResponse { - transaction?: string; - document?: Document; - readTime?: string; - skippedResults?: number; - } - interface RunAggregationQueryRequest { - parent?: string; - structuredAggregationQuery?: StructuredAggregationQuery; - transaction?: string; - newTransaction?: TransactionOptions; - readTime?: string; - } - interface RunAggregationQueryResponse { - result?: AggregationResult; - transaction?: string; - readTime?: string; - } - interface AggregationResult { - aggregateFields?: ApiClientObjectMap; - } - interface StructuredAggregationQuery { - structuredQuery?: StructuredQuery; - aggregations?: Aggregation[]; - } - interface Aggregation { - count?: Count; - sum?: Sum; - avg?: Avg; - alias?: string; - } - interface Count { - upTo?: number; - } - interface Sum { - field?: FieldReference; - } - interface Avg { - field?: FieldReference; - } - interface Status { - code?: number; - message?: string; - details?: Array>; - } - interface StructuredQuery { - select?: Projection; - from?: CollectionSelector[]; - where?: Filter; - orderBy?: Order[]; - startAt?: Cursor; - endAt?: Cursor; - offset?: number; - limit?: - | number - | { - value: number; - }; - } - interface Target { - query?: QueryTarget; - documents?: DocumentsTarget; - resumeToken?: string | Uint8Array; - readTime?: Timestamp_2; - targetId?: number; - once?: boolean; - expectedCount?: - | number - | { - value: number; - }; - } - interface TargetChange { - targetChangeType?: TargetChangeTargetChangeType; - targetIds?: number[]; - cause?: Status; - resumeToken?: string | Uint8Array; - readTime?: Timestamp_2; - } - interface TransactionOptions { - readOnly?: ReadOnly; - readWrite?: ReadWrite; - } - interface UnaryFilter { - op?: UnaryFilterOp; - field?: FieldReference; - } - interface Value { - nullValue?: ValueNullValue; - booleanValue?: boolean; - integerValue?: string | number; - doubleValue?: string | number; - timestampValue?: Timestamp_2; - stringValue?: string; - bytesValue?: string | Uint8Array; - referenceValue?: string; - geoPointValue?: LatLng; - arrayValue?: ArrayValue; - mapValue?: MapValue; - } - interface Write { - update?: Document; - delete?: string; - verify?: string; - transform?: DocumentTransform; - updateMask?: DocumentMask; - updateTransforms?: FieldTransform[]; - currentDocument?: Precondition; - } - interface WriteRequest { - streamId?: string; - writes?: Write[]; - streamToken?: string | Uint8Array; - labels?: ApiClientObjectMap; - } - interface WriteResponse { - streamId?: string; - streamToken?: string | Uint8Array; - writeResults?: WriteResult[]; - commitTime?: Timestamp_2; - } - interface WriteResult { - updateTime?: Timestamp_2; - transformResults?: Value[]; - } -} - -/* Excluded from this release type: FirstPartyCredentialsSettings */ - -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -declare type FulfilledHandler = - | ((result: T) => R | PersistencePromise) - | null; - -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An immutable object representing a geographic location in Firestore. The - * location is represented as latitude/longitude pair. - * - * Latitude values are in the range of [-90, 90]. - * Longitude values are in the range of [-180, 180]. - */ -export declare class GeoPoint { - private _lat; - private _long; - /** - * Creates a new immutable `GeoPoint` object with the provided latitude and - * longitude values. - * @param latitude - The latitude as number between -90 and 90. - * @param longitude - The longitude as number between -180 and 180. - */ - constructor(latitude: number, longitude: number); - /** - * The latitude of this `GeoPoint` instance. - */ - get latitude(): number; - /** - * The longitude of this `GeoPoint` instance. - */ - get longitude(): number; - /** - * Returns true if this `GeoPoint` is equal to the provided one. - * - * @param other - The `GeoPoint` to compare against. - * @returns true if this `GeoPoint` is equal to the provided one. - */ - isEqual(other: GeoPoint): boolean; - /** Returns a JSON-serializable representation of this GeoPoint. */ - toJSON(): { - latitude: number; - longitude: number; - }; - /** - * Actually private to JS consumers of our API, so this function is prefixed - * with an underscore. - */ - _compareTo(other: GeoPoint): number; -} - -/** - * Calculates the specified aggregations over the documents in the result - * set of the given query without actually downloading the documents. - * - * Using this function to perform aggregations is efficient because only the - * final aggregation values, not the documents' data, are downloaded. This - * function can perform aggregations of the documents in cases where the result - * set is prohibitively large to download entirely (thousands of documents). - * - * The result received from the server is presented, unaltered, without - * considering any local state. That is, documents in the local cache are not - * taken into consideration, neither are local modifications not yet - * synchronized with the server. Previously-downloaded results, if any, are not - * used. Every invocation of this function necessarily involves a round trip to - * the server. - * - * @param query The query whose result set is aggregated over. - * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates - * to perform over the result set. The AggregateSpec specifies aliases for each - * aggregate, which can be used to retrieve the aggregate result. - * @example - * ```typescript - * const aggregateSnapshot = await getAggregateFromServer(query, { - * countOfDocs: count(), - * totalHours: sum('hours'), - * averageScore: average('score') - * }); - * - * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; - * const totalHours: number = aggregateSnapshot.data().totalHours; - * const averageScore: number | null = aggregateSnapshot.data().averageScore; - * ``` - */ -export declare function getAggregateFromServer< - AggregateSpecType extends AggregateSpec, - AppModelType, - DbModelType extends DocumentData ->( - query: Query, - aggregateSpec: AggregateSpecType -): Promise< - AggregateQuerySnapshot ->; - -/** - * Calculates the number of documents in the result set of the given query - * without actually downloading the documents. - * - * Using this function to count the documents is efficient because only the - * final count, not the documents' data, is downloaded. This function can - * count the documents in cases where the result set is prohibitively large to - * download entirely (thousands of documents). - * - * The result received from the server is presented, unaltered, without - * considering any local state. That is, documents in the local cache are not - * taken into consideration, neither are local modifications not yet - * synchronized with the server. Previously-downloaded results, if any, are not - * used. Every invocation of this function necessarily involves a round trip to - * the server. - * - * @param query The query whose result set size is calculated. - * @returns A Promise that will be resolved with the count; the count can be - * retrieved from `snapshot.data().count`, where `snapshot` is the - * `AggregateQuerySnapshot` to which the returned Promise resolves. - */ -export declare function getCountFromServer< - AppModelType, - DbModelType extends DocumentData ->( - query: Query -): Promise< - AggregateQuerySnapshot< - { - count: AggregateField; - }, - AppModelType, - DbModelType - > ->; - -/** - * Reads the document referred to by this `DocumentReference`. - * - * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting - * for data from the server, but it may return cached data or fail if you are - * offline and the server cannot be reached. To specify this behavior, invoke - * {@link getDocFromCache} or {@link getDocFromServer}. - * - * @param reference - The reference of the document to fetch. - * @returns A Promise resolved with a `DocumentSnapshot` containing the - * current document contents. - */ -export declare function getDoc( - reference: DocumentReference -): Promise>; - -/** - * Reads the document referred to by this `DocumentReference` from cache. - * Returns an error if the document is not currently cached. - * - * @returns A `Promise` resolved with a `DocumentSnapshot` containing the - * current document contents. - */ -export declare function getDocFromCache< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference -): Promise>; - -/** - * Reads the document referred to by this `DocumentReference` from the server. - * Returns an error if the network is not available. - * - * @returns A `Promise` resolved with a `DocumentSnapshot` containing the - * current document contents. - */ -export declare function getDocFromServer< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference -): Promise>; - -/** - * Executes the query and returns the results as a `QuerySnapshot`. - * - * Note: `getDocs()` attempts to provide up-to-date data when possible by - * waiting for data from the server, but it may return cached data or fail if - * you are offline and the server cannot be reached. To specify this behavior, - * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. - * - * @returns A `Promise` that will be resolved with the results of the query. - */ -export declare function getDocs( - query: Query -): Promise>; - -/** - * Executes the query and returns the results as a `QuerySnapshot` from cache. - * Returns an empty result set if no documents matching the query are currently - * cached. - * - * @returns A `Promise` that will be resolved with the results of the query. - */ -export declare function getDocsFromCache< - AppModelType, - DbModelType extends DocumentData ->( - query: Query -): Promise>; - -/** - * Executes the query and returns the results as a `QuerySnapshot` from the - * server. Returns an error if the network is not available. - * - * @returns A `Promise` that will be resolved with the results of the query. - */ -export declare function getDocsFromServer< - AppModelType, - DbModelType extends DocumentData ->( - query: Query -): Promise>; - -/** - * Returns the existing default {@link Firestore} instance that is associated with the - * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new - * instance with default settings. - * - * @returns The default {@link Firestore} instance of the default app. - */ -export declare function getFirestore(): Firestore; - -/** - * Returns the existing default {@link Firestore} instance that is associated with the - * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new - * instance with default settings. - * - * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} - * instance is associated with. - * @returns The default {@link Firestore} instance of the provided app. - */ -export declare function getFirestore(app: FirebaseApp): Firestore; - -/** - * Returns the existing named {@link Firestore} instance that is associated with the - * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new - * instance with default settings. - * - * @param databaseId - The name of the database. - * @returns The named {@link Firestore} instance of the default app. - * @beta - */ -export declare function getFirestore(databaseId: string): Firestore; - -/** - * Returns the existing named {@link Firestore} instance that is associated with the - * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new - * instance with default settings. - * - * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} - * instance is associated with. - * @param databaseId - The name of the database. - * @returns The named {@link Firestore} instance of the provided app. - * @beta - */ -export declare function getFirestore( - app: FirebaseApp, - databaseId: string -): Firestore; - -/** - * Returns the PersistentCache Index Manager used by the given `Firestore` - * object. - * - * @return The `PersistentCacheIndexManager` instance, or `null` if local - * persistent storage is not in use. - */ -export declare function getPersistentCacheIndexManager( - firestore: Firestore -): PersistentCacheIndexManager | null; - -/** - * General purpose cache for global values. - * - * Global state that cuts across components should be saved here. Following are contained herein: - * - * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache - * synchronization and invalidation. - */ -declare interface GlobalsCache { - /** - * Gets session token. - */ - getSessionToken( - transaction: PersistenceTransaction - ): PersistencePromise<_ByteString>; - /** - * Sets session token. - * - * @param sessionToken - The new session token. - */ - setSessionToken( - transaction: PersistenceTransaction, - sessionToken: _ByteString - ): PersistencePromise; -} - -/** - * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link - * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by - * the given value. - * - * If either the operand or the current field value uses floating point - * precision, all arithmetic follows IEEE 754 semantics. If both values are - * integers, values outside of JavaScript's safe number range - * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to - * precision loss. Furthermore, once processed by the Firestore backend, all - * integer operations are capped between -2^63 and 2^63-1. - * - * If the current field value is not of type `number`, or if the field does not - * yet exist, the transformation sets the field to the given value. - * - * @param n - The value to increment by. - * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or - * `updateDoc()` - */ -export declare function increment(n: number): FieldValue; - -/** - * The SDK definition of a Firestore index. - * - * @deprecated Instead of creating cache indexes manually, consider using - * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to - * create cache indexes for queries running locally. - * - * @beta - */ -export declare interface Index { - /** The ID of the collection to index. */ - readonly collectionGroup: string; - /** A list of fields to index. */ - readonly fields?: IndexField[]; - [key: string]: unknown; -} - -/** - * A list of Firestore indexes to speed up local query execution. - * - * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} - * for a description of the format of the index definition. - * - * @deprecated Instead of creating cache indexes manually, consider using - * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to - * create cache indexes for queries running locally. - * - * @beta - */ -export declare interface IndexConfiguration { - /** A list of all Firestore indexes. */ - readonly indexes?: Index[]; - [key: string]: unknown; -} - -/** - * A single field element in an index configuration. - * - * @deprecated Instead of creating cache indexes manually, consider using - * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to - * create cache indexes for queries running locally. - * - * @beta - */ -export declare interface IndexField { - /** The field path to index. */ - readonly fieldPath: string; - /** - * What type of array index to create. Set to `CONTAINS` for `array-contains` - * and `array-contains-any` indexes. - * - * Only one of `arrayConfig` or `order` should be set; - */ - readonly arrayConfig?: 'CONTAINS'; - /** - * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for - * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. - * - * Only one of `arrayConfig` or `order` should be set. - */ - readonly order?: 'ASCENDING' | 'DESCENDING'; - [key: string]: unknown; -} - -declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; - -/** The type of the index, e.g. for which type of query it can be used. */ -declare const enum IndexKind { - /** - * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. - */ - ASCENDING = 0, - /** - * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. - */ - DESCENDING = 1, - /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ - CONTAINS = 2 -} - -/** - * Represents a set of indexes that are used to execute queries efficiently. - * - * Currently the only index is a [collection id] => [parent path] index, used - * to execute Collection Group queries. - */ -declare interface IndexManager { - /** - * Creates an index entry mapping the collectionId (last segment of the path) - * to the parent path (either the containing document location or the empty - * path for root-level collections). Index entries can be retrieved via - * getCollectionParents(). - * - * NOTE: Currently we don't remove index entries. If this ends up being an - * issue we can devise some sort of GC strategy. - */ - addToCollectionParentIndex( - transaction: PersistenceTransaction, - collectionPath: _ResourcePath - ): PersistencePromise; - /** - * Retrieves all parent locations containing the given collectionId, as a - * list of paths (each path being either a document location or the empty - * path for a root-level collection). - */ - getCollectionParents( - transaction: PersistenceTransaction, - collectionId: string - ): PersistencePromise<_ResourcePath[]>; - /** - * Adds a field path index. - * - * Values for this index are persisted via the index backfill, which runs - * asynchronously in the background. Once the first values are written, - * an index can be used to serve partial results for any matching queries. - * Any unindexed portion of the database will continue to be served via - * collection scons. - */ - addFieldIndex( - transaction: PersistenceTransaction, - index: FieldIndex - ): PersistencePromise; - /** Removes the given field index and deletes all index values. */ - deleteFieldIndex( - transaction: PersistenceTransaction, - index: FieldIndex - ): PersistencePromise; - /** Removes all field indexes and deletes all index values. */ - deleteAllFieldIndexes( - transaction: PersistenceTransaction - ): PersistencePromise; - /** Creates a full matched field index which serves the given target. */ - createTargetIndexes( - transaction: PersistenceTransaction, - target: Target - ): PersistencePromise; - /** - * Returns a list of field indexes that correspond to the specified collection - * group. - * - * @param collectionGroup The collection group to get matching field indexes - * for. - * @return A collection of field indexes for the specified collection group. - */ - getFieldIndexes( - transaction: PersistenceTransaction, - collectionGroup: string - ): PersistencePromise; - /** Returns all configured field indexes. */ - getFieldIndexes( - transaction: PersistenceTransaction - ): PersistencePromise; - /** - * Returns the type of index (if any) that can be used to serve the given - * target. - */ - getIndexType( - transaction: PersistenceTransaction, - target: Target - ): PersistencePromise; - /** - * Returns the documents that match the given target based on the provided - * index or `null` if the target does not have a matching index. - */ - getDocumentsMatchingTarget( - transaction: PersistenceTransaction, - target: Target - ): PersistencePromise<_DocumentKey[] | null>; - /** - * Returns the next collection group to update. Returns `null` if no group - * exists. - */ - getNextCollectionGroupToUpdate( - transaction: PersistenceTransaction - ): PersistencePromise; - /** - * Sets the collection group's latest read time. - * - * This method updates the index offset for all field indices for the - * collection group and increments their sequence number. Subsequent calls to - * `getNextCollectionGroupToUpdate()` will return a different collection group - * (unless only one collection group is configured). - */ - updateCollectionGroup( - transaction: PersistenceTransaction, - collectionGroup: string, - offset: IndexOffset - ): PersistencePromise; - /** Updates the index entries for the provided documents. */ - updateIndexEntries( - transaction: PersistenceTransaction, - documents: DocumentMap - ): PersistencePromise; - /** - * Iterates over all field indexes that are used to serve the given target, - * and returns the minimum offset of them all. - */ - getMinOffset( - transaction: PersistenceTransaction, - target: Target - ): PersistencePromise; - /** Returns the minimum offset for the given collection group. */ - getMinOffsetFromCollectionGroup( - transaction: PersistenceTransaction, - collectionGroup: string - ): PersistencePromise; -} - -/** - * Stores the latest read time, document and batch ID that were processed for an - * index. - */ -declare class IndexOffset { - /** - * The latest read time version that has been indexed by Firestore for this - * field index. - */ - readonly readTime: SnapshotVersion; - /** - * The key of the last document that was indexed for this query. Use - * `DocumentKey.empty()` if no document has been indexed. - */ - readonly documentKey: _DocumentKey; - readonly largestBatchId: number; - constructor( - /** - * The latest read time version that has been indexed by Firestore for this - * field index. - */ - readTime: SnapshotVersion, - /** - * The key of the last document that was indexed for this query. Use - * `DocumentKey.empty()` if no document has been indexed. - */ - documentKey: _DocumentKey, - largestBatchId: number - ); - /** Returns an offset that sorts before all regular offsets. */ - static min(): IndexOffset; - /** Returns an offset that sorts after all regular offsets. */ - static max(): IndexOffset; -} - -/** An index component consisting of field path and index type. */ -declare class IndexSegment { - /** The field path of the component. */ - readonly fieldPath: _FieldPath; - /** The fields sorting order. */ - readonly kind: IndexKind; - constructor( - /** The field path of the component. */ - fieldPath: _FieldPath, - /** The fields sorting order. */ - kind: IndexKind - ); -} - -/** - * Stores the "high water mark" that indicates how updated the Index is for the - * current user. - */ -declare class IndexState { - /** - * Indicates when the index was last updated (relative to other indexes). - */ - readonly sequenceNumber: number; - /** The the latest indexed read time, document and batch id. */ - readonly offset: IndexOffset; - constructor( - /** - * Indicates when the index was last updated (relative to other indexes). - */ - sequenceNumber: number, - /** The the latest indexed read time, document and batch id. */ - offset: IndexOffset - ); - /** The state of an index that has not yet been backfilled. */ - static empty(): IndexState; -} - -declare type IndexState_2 = - | 'STATE_UNSPECIFIED' - | 'CREATING' - | 'READY' - | 'ERROR'; - -/** Represents the index state as it relates to a particular target. */ -declare const enum IndexType { - /** Indicates that no index could be found for serving the target. */ - NONE = 0, - /** - * Indicates that only a "partial index" could be found for serving the - * target. A partial index is one which does not have a segment for every - * filter/orderBy in the target. - */ - PARTIAL = 1, - /** - * Indicates that a "full index" could be found for serving the target. A full - * index is one which has a segment for every filter/orderBy in the target. - */ - FULL = 2 -} - -/** - * Initializes a new instance of {@link Firestore} with the provided settings. - * Can only be called before any other function, including - * {@link (getFirestore:1)}. If the custom settings are empty, this function is - * equivalent to calling {@link (getFirestore:1)}. - * - * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will - * be associated. - * @param settings - A settings object to configure the {@link Firestore} instance. - * @param databaseId - The name of the database. - * @returns A newly initialized {@link Firestore} instance. - */ -export declare function initializeFirestore( - app: FirebaseApp, - settings: FirestoreSettings, - databaseId?: string -): Firestore; - -/* Excluded from this release type: _internalAggregationQueryToProtoRunAggregationQueryRequest */ - -/* Excluded from this release type: _internalQueryToProtoQueryTarget */ - -/* Excluded from this release type: _isBase64Available */ - -/** - * This class generates JsonObject values for the Datastore API suitable for - * sending to either GRPC stub methods or via the JSON/HTTP REST API. - * - * The serializer supports both Protobuf.js and Proto3 JSON formats. By - * setting `useProto3Json` to true, the serializer will use the Proto3 JSON - * format. - * - * For a description of the Proto3 JSON format check - * https://developers.google.com/protocol-buffers/docs/proto3#json - * - * TODO(klimt): We can remove the databaseId argument if we keep the full - * resource name in documents. - */ -declare class JsonProtoSerializer implements Serializer { - readonly databaseId: _DatabaseId; - readonly useProto3Json: boolean; - constructor(databaseId: _DatabaseId, useProto3Json: boolean); -} - -declare type Kind = 'memory' | 'persistent'; - -/** - * Creates a {@link QueryLimitConstraint} that only returns the first matching - * documents. - * - * @param limit - The maximum number of items to return. - * @returns The created {@link QueryLimitConstraint}. - */ -export declare function limit(limit: number): QueryLimitConstraint; - -/** - * Creates a {@link QueryLimitConstraint} that only returns the last matching - * documents. - * - * You must specify at least one `orderBy` clause for `limitToLast` queries, - * otherwise an exception will be thrown during execution. - * - * @param limit - The maximum number of items to return. - * @returns The created {@link QueryLimitConstraint}. - */ -export declare function limitToLast(limit: number): QueryLimitConstraint; - -declare const enum LimitType { - First = 'F', - Last = 'L' -} - -/** LimitType enum. */ -declare type LimitType_2 = 'FIRST' | 'LAST'; - -declare type ListenSequenceNumber = number; - -/** - * Describe the source a query listens to. - * - * Set to `default` to listen to both cache and server changes. Set to `cache` - * to listen to changes in cache only. - */ -export declare type ListenSource = 'default' | 'cache'; - -declare class LLRBEmptyNode { - get key(): never; - get value(): never; - get color(): never; - get left(): never; - get right(): never; - size: number; - copy( - key: K | null, - value: V | null, - color: boolean | null, - left: LLRBNode | LLRBEmptyNode | null, - right: LLRBNode | LLRBEmptyNode | null - ): LLRBEmptyNode; - insert(key: K, value: V, comparator: Comparator): LLRBNode; - remove(key: K, comparator: Comparator): LLRBEmptyNode; - isEmpty(): boolean; - inorderTraversal(action: (k: K, v: V) => boolean): boolean; - reverseTraversal(action: (k: K, v: V) => boolean): boolean; - minKey(): K | null; - maxKey(): K | null; - isRed(): boolean; - checkMaxDepth(): boolean; - protected check(): 0; -} - -declare class LLRBNode { - key: K; - value: V; - readonly color: boolean; - readonly left: LLRBNode | LLRBEmptyNode; - readonly right: LLRBNode | LLRBEmptyNode; - readonly size: number; - static EMPTY: LLRBEmptyNode; - static RED: boolean; - static BLACK: boolean; - constructor( - key: K, - value: V, - color?: boolean, - left?: LLRBNode | LLRBEmptyNode, - right?: LLRBNode | LLRBEmptyNode - ); - copy( - key: K | null, - value: V | null, - color: boolean | null, - left: LLRBNode | LLRBEmptyNode | null, - right: LLRBNode | LLRBEmptyNode | null - ): LLRBNode; - isEmpty(): boolean; - inorderTraversal(action: (k: K, v: V) => T): T; - reverseTraversal(action: (k: K, v: V) => T): T; - private min; - minKey(): K | null; - maxKey(): K | null; - insert(key: K, value: V, comparator: Comparator): LLRBNode; - private removeMin; - remove( - key: K, - comparator: Comparator - ): LLRBNode | LLRBEmptyNode; - isRed(): boolean; - private fixUp; - private moveRedLeft; - private moveRedRight; - private rotateLeft; - private rotateRight; - private colorFlip; - checkMaxDepth(): boolean; - protected check(): number; -} - -/** - * Loads a Firestore bundle into the local cache. - * - * @param firestore - The {@link Firestore} instance to load bundles for. - * @param bundleData - An object representing the bundle to be loaded. Valid - * objects are `ArrayBuffer`, `ReadableStream` or `string`. - * - * @returns A `LoadBundleTask` object, which notifies callers with progress - * updates, and completion or error events. It can be used as a - * `Promise`. - */ -export declare function loadBundle( - firestore: Firestore, - bundleData: ReadableStream | ArrayBuffer | string -): LoadBundleTask; - -/** - * Represents the task of loading a Firestore bundle. It provides progress of bundle - * loading, as well as task completion and error events. - * - * The API is compatible with `Promise`. - */ -export declare class LoadBundleTask - implements PromiseLike -{ - private _progressObserver; - private _taskCompletionResolver; - private _lastProgress; - /** - * Registers functions to listen to bundle loading progress events. - * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur - * each time a Firestore document is loaded from the bundle. - * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the - * error, and there should be no more updates after this. - * @param complete - Called when the loading task is complete. - */ - onProgress( - next?: (progress: LoadBundleTaskProgress) => unknown, - error?: (err: Error) => unknown, - complete?: () => void - ): void; - /** - * Implements the `Promise.catch` interface. - * - * @param onRejected - Called when an error occurs during bundle loading. - */ - catch( - onRejected: (a: Error) => R | PromiseLike - ): Promise; - /** - * Implements the `Promise.then` interface. - * - * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. - * The update will always have its `taskState` set to `"Success"`. - * @param onRejected - Called when an error occurs during bundle loading. - */ - then( - onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike, - onRejected?: (a: Error) => R | PromiseLike - ): Promise; - /** - * Notifies all observers that bundle loading has completed, with a provided - * `LoadBundleTaskProgress` object. - * - * @private - */ - _completeWith(progress: LoadBundleTaskProgress): void; - /** - * Notifies all observers that bundle loading has failed, with a provided - * `Error` as the reason. - * - * @private - */ - _failWith(error: FirestoreError): void; - /** - * Notifies a progress update of loading a bundle. - * @param progress - The new progress. - * - * @private - */ - _updateProgress(progress: LoadBundleTaskProgress): void; -} - -/** - * Represents a progress update or a final state from loading bundles. - */ -export declare interface LoadBundleTaskProgress { - /** How many documents have been loaded. */ - documentsLoaded: number; - /** How many documents are in the bundle being loaded. */ - totalDocuments: number; - /** How many bytes have been loaded. */ - bytesLoaded: number; - /** How many bytes are in the bundle being loaded. */ - totalBytes: number; - /** Current task state. */ - taskState: TaskState; -} - -/** - * A readonly view of the local state of all documents we're tracking (i.e. we - * have a cached version in remoteDocumentCache or local mutations for the - * document). The view is computed by applying the mutations in the - * MutationQueue to the RemoteDocumentCache. - */ -declare class LocalDocumentsView { - readonly remoteDocumentCache: RemoteDocumentCache; - readonly mutationQueue: MutationQueue; - readonly documentOverlayCache: DocumentOverlayCache; - readonly indexManager: IndexManager; - constructor( - remoteDocumentCache: RemoteDocumentCache, - mutationQueue: MutationQueue, - documentOverlayCache: DocumentOverlayCache, - indexManager: IndexManager - ); - /** - * Get the local view of the document identified by `key`. - * - * @returns Local view of the document or null if we don't have any cached - * state for it. - */ - getDocument( - transaction: PersistenceTransaction, - key: _DocumentKey - ): PersistencePromise; - /** - * Gets the local view of the documents identified by `keys`. - * - * If we don't have cached state for a document in `keys`, a NoDocument will - * be stored for that key in the resulting set. - */ - getDocuments( - transaction: PersistenceTransaction, - keys: DocumentKeySet - ): PersistencePromise; - /** - * Similar to `getDocuments`, but creates the local view from the given - * `baseDocs` without retrieving documents from the local store. - * - * @param transaction - The transaction this operation is scoped to. - * @param docs - The documents to apply local mutations to get the local views. - * @param existenceStateChanged - The set of document keys whose existence state - * is changed. This is useful to determine if some documents overlay needs - * to be recalculated. - */ - getLocalViewOfDocuments( - transaction: PersistenceTransaction, - docs: MutableDocumentMap, - existenceStateChanged?: DocumentKeySet - ): PersistencePromise; - /** - * Gets the overlayed documents for the given document map, which will include - * the local view of those documents and a `FieldMask` indicating which fields - * are mutated locally, `null` if overlay is a Set or Delete mutation. - */ - getOverlayedDocuments( - transaction: PersistenceTransaction, - docs: MutableDocumentMap - ): PersistencePromise; - /** - * Fetches the overlays for {@code docs} and adds them to provided overlay map - * if the map does not already contain an entry for the given document key. - */ - private populateOverlays; - /** - * Computes the local view for the given documents. - * - * @param docs - The documents to compute views for. It also has the base - * version of the documents. - * @param overlays - The overlays that need to be applied to the given base - * version of the documents. - * @param existenceStateChanged - A set of documents whose existence states - * might have changed. This is used to determine if we need to re-calculate - * overlays from mutation queues. - * @return A map represents the local documents view. - */ - computeViews( - transaction: PersistenceTransaction, - docs: MutableDocumentMap, - overlays: OverlayMap, - existenceStateChanged: DocumentKeySet - ): PersistencePromise; - private recalculateAndSaveOverlays; - /** - * Recalculates overlays by reading the documents from remote document cache - * first, and saves them after they are calculated. - */ - recalculateAndSaveOverlaysForDocumentKeys( - transaction: PersistenceTransaction, - documentKeys: DocumentKeySet - ): PersistencePromise>; - /** - * Performs a query against the local view of all documents. - * - * @param transaction - The persistence transaction. - * @param query - The query to match documents against. - * @param offset - Read time and key to start scanning by (exclusive). - * @param context - A optional tracker to keep a record of important details - * during database local query execution. - */ - getDocumentsMatchingQuery( - transaction: PersistenceTransaction, - query: Query_2, - offset: IndexOffset, - context?: QueryContext - ): PersistencePromise; - /** - * Given a collection group, returns the next documents that follow the provided offset, along - * with an updated batch ID. - * - *

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

    - *
  • `debug` for the most verbose logging level, primarily for - * debugging.
  • - *
  • `error` to log errors only.
  • - *
  • `silent` to turn off logging.
  • - *
- */ -export declare function setLogLevel(logLevel: LogLevel): void; - -/** - * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link - * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be - * configured to perform granular merges instead of overwriting the target - * documents in their entirety by providing a `SetOptions` with `merge: true`. - * - * @param merge - Changes the behavior of a `setDoc()` call to only replace the - * values specified in its data argument. Fields omitted from the `setDoc()` - * call remain untouched. If your input sets any field to an empty map, all - * nested fields are overwritten. - * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace - * the specified field paths. Any field path that is not specified is ignored - * and remains untouched. If your input sets any field to an empty map, all - * nested fields are overwritten. - */ -export declare type SetOptions = - | { - readonly merge?: boolean; - } - | { - readonly mergeFields?: Array; - }; - -/** - * A `SharedClientState` keeps track of the global state of the mutations - * and query targets for all active clients with the same persistence key (i.e. - * project ID and FirebaseApp name). It relays local changes to other clients - * and updates its local state as new state is observed. - * - * `SharedClientState` is primarily used for synchronization in Multi-Tab - * environments. Each tab is responsible for registering its active query - * targets and mutations. `SharedClientState` will then notify the listener - * assigned to `.syncEngine` for updates to mutations and queries that - * originated in other clients. - * - * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be - * assigned before calling `start()`. - */ -declare interface SharedClientState { - onlineStateHandler: ((onlineState: OnlineState) => void) | null; - sequenceNumberHandler: - | ((sequenceNumber: ListenSequenceNumber) => void) - | null; - /** Registers the Mutation Batch ID of a newly pending mutation. */ - addPendingMutation(batchId: BatchId): void; - /** - * Records that a pending mutation has been acknowledged or rejected. - * Called by the primary client to notify secondary clients of mutation - * results as they come back from the backend. - */ - updateMutationState( - batchId: BatchId, - state: 'acknowledged' | 'rejected', - error?: FirestoreError - ): void; - /** - * Associates a new Query Target ID with the local Firestore client. Returns - * the new query state for the query (which can be 'current' if the query is - * already associated with another tab). - * - * If the target id is already associated with local client, the method simply - * returns its `QueryTargetState`. - */ - addLocalQueryTarget( - targetId: TargetId, - addToActiveTargetIds?: boolean - ): QueryTargetState; - /** Removes the Query Target ID association from the local client. */ - removeLocalQueryTarget(targetId: TargetId): void; - /** Checks whether the target is associated with the local client. */ - isLocalQueryTarget(targetId: TargetId): boolean; - /** - * Processes an update to a query target. - * - * Called by the primary client to notify secondary clients of document - * changes or state transitions that affect the provided query target. - */ - updateQueryState( - targetId: TargetId, - state: QueryTargetState, - error?: FirestoreError - ): void; - /** - * Removes the target's metadata entry. - * - * Called by the primary client when all clients stopped listening to a query - * target. - */ - clearQueryState(targetId: TargetId): void; - /** - * Gets the active Query Targets IDs for all active clients. - * - * The implementation for this may require O(n) runtime, where 'n' is the size - * of the result set. - */ - getAllActiveQueryTargets(): SortedSet; - /** - * Checks whether the provided target ID is currently being listened to by - * any of the active clients. - * - * The implementation may require O(n*log m) runtime, where 'n' is the number - * of clients and 'm' the number of targets. - */ - isActiveQueryTarget(targetId: TargetId): boolean; - /** - * Starts the SharedClientState, reads existing client data and registers - * listeners for updates to new and existing clients. - */ - start(): Promise; - /** Shuts down the `SharedClientState` and its listeners. */ - shutdown(): void; - /** - * Changes the active user and removes all existing user-specific data. The - * user change does not call back into SyncEngine (for example, no mutations - * will be marked as removed). - */ - handleUserChange( - user: User, - removedBatchIds: BatchId[], - addedBatchIds: BatchId[] - ): void; - /** Changes the shared online state of all clients. */ - setOnlineState(onlineState: OnlineState): void; - writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; - /** - * Notifies other clients when remote documents have changed due to loading - * a bundle. - * - * @param collectionGroups The collection groups affected by this bundle. - */ - notifyBundleLoaded(collectionGroups: Set): void; -} - -/** - * Returns true if the provided snapshots are equal. - * - * @param left - A snapshot to compare. - * @param right - A snapshot to compare. - * @returns true if the snapshots are equal. - */ -export declare function snapshotEqual< - AppModelType, - DbModelType extends DocumentData ->( - left: - | DocumentSnapshot - | QuerySnapshot, - right: - | DocumentSnapshot - | QuerySnapshot -): boolean; - -/** - * An options object that can be passed to {@link (onSnapshot:1)} and {@link - * QuerySnapshot.docChanges} to control which types of changes to include in the - * result set. - */ -export declare interface SnapshotListenOptions { - /** - * Include a change even if only the metadata of the query or of a document - * changed. Default is false. - */ - readonly includeMetadataChanges?: boolean; - /** - * Set the source the query listens to. Default to "default", which - * listens to both cache and server. - */ - readonly source?: ListenSource; -} - -/** - * Metadata about a snapshot, describing the state of the snapshot. - */ -export declare class SnapshotMetadata { - /** - * True if the snapshot contains the result of local writes (for example - * `set()` or `update()` calls) that have not yet been committed to the - * backend. If your listener has opted into metadata updates (via - * `SnapshotListenOptions`) you will receive another snapshot with - * `hasPendingWrites` equal to false once the writes have been committed to - * the backend. - */ - readonly hasPendingWrites: boolean; - /** - * True if the snapshot was created from cached data rather than guaranteed - * up-to-date server data. If your listener has opted into metadata updates - * (via `SnapshotListenOptions`) you will receive another snapshot with - * `fromCache` set to false once the client has received up-to-date data from - * the backend. - */ - readonly fromCache: boolean; - /** @hideconstructor */ - constructor(hasPendingWrites: boolean, fromCache: boolean); - /** - * Returns true if this `SnapshotMetadata` is equal to the provided one. - * - * @param other - The `SnapshotMetadata` to compare against. - * @returns true if this `SnapshotMetadata` is equal to the provided one. - */ - isEqual(other: SnapshotMetadata): boolean; -} - -/** - * Options that configure how data is retrieved from a `DocumentSnapshot` (for - * example the desired behavior for server timestamps that have not yet been set - * to their final value). - */ -export declare interface SnapshotOptions { - /** - * If set, controls the return value for server timestamps that have not yet - * been set to their final value. - * - * By specifying 'estimate', pending server timestamps return an estimate - * based on the local clock. This estimate will differ from the final value - * and cause these values to change once the server result becomes available. - * - * By specifying 'previous', pending timestamps will be ignored and return - * their previous value instead. - * - * If omitted or set to 'none', `null` will be returned by default until the - * server value becomes available. - */ - readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; -} - -/** - * A version of a document in Firestore. This corresponds to the version - * timestamp, such as update_time or read_time. - */ -declare class SnapshotVersion { - private timestamp; - static fromTimestamp(value: Timestamp): SnapshotVersion; - static min(): SnapshotVersion; - static max(): SnapshotVersion; - private constructor(); - compareTo(other: SnapshotVersion): number; - isEqual(other: SnapshotVersion): boolean; - /** Returns a number representation of the version for use in spec tests. */ - toMicroseconds(): number; - toString(): string; - toTimestamp(): Timestamp; -} - -declare class SortedMap { - comparator: Comparator; - root: LLRBNode | LLRBEmptyNode; - constructor( - comparator: Comparator, - root?: LLRBNode | LLRBEmptyNode - ); - insert(key: K, value: V): SortedMap; - remove(key: K): SortedMap; - get(key: K): V | null; - indexOf(key: K): number; - isEmpty(): boolean; - get size(): number; - minKey(): K | null; - maxKey(): K | null; - inorderTraversal(action: (k: K, v: V) => T): T; - forEach(fn: (k: K, v: V) => void): void; - toString(): string; - reverseTraversal(action: (k: K, v: V) => T): T; - getIterator(): SortedMapIterator; - getIteratorFrom(key: K): SortedMapIterator; - getReverseIterator(): SortedMapIterator; - getReverseIteratorFrom(key: K): SortedMapIterator; -} - -declare class SortedMapIterator { - private isReverse; - private nodeStack; - constructor( - node: LLRBNode | LLRBEmptyNode, - startKey: K | null, - comparator: Comparator, - isReverse: boolean - ); - getNext(): Entry; - hasNext(): boolean; - peek(): Entry | null; -} - -/** - * SortedSet is an immutable (copy-on-write) collection that holds elements - * in order specified by the provided comparator. - * - * NOTE: if provided comparator returns 0 for two elements, we consider them to - * be equal! - */ -declare class SortedSet { - private comparator; - private data; - constructor(comparator: (left: T, right: T) => number); - has(elem: T): boolean; - first(): T | null; - last(): T | null; - get size(): number; - indexOf(elem: T): number; - /** Iterates elements in order defined by "comparator" */ - forEach(cb: (elem: T) => void): void; - /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ - forEachInRange(range: [T, T], cb: (elem: T) => void): void; - /** - * Iterates over `elem`s such that: start <= elem until false is returned. - */ - forEachWhile(cb: (elem: T) => boolean, start?: T): void; - /** Finds the least element greater than or equal to `elem`. */ - firstAfterOrEqual(elem: T): T | null; - getIterator(): SortedSetIterator; - getIteratorFrom(key: T): SortedSetIterator; - /** Inserts or updates an element */ - add(elem: T): SortedSet; - /** Deletes an element */ - delete(elem: T): SortedSet; - isEmpty(): boolean; - unionWith(other: SortedSet): SortedSet; - isEqual(other: SortedSet): boolean; - toArray(): T[]; - toString(): string; - private copy; -} - -declare class SortedSetIterator { - private iter; - constructor(iter: SortedMapIterator); - getNext(): T; - hasNext(): boolean; -} - -/** - * Creates a {@link QueryStartAtConstraint} that modifies the result set to - * start after the provided document (exclusive). The starting position is - * relative to the order of the query. The document must contain all of the - * fields provided in the orderBy of the query. - * - * @param snapshot - The snapshot of the document to start after. - * @returns A {@link QueryStartAtConstraint} to pass to `query()` - */ -export declare function startAfter< - AppModelType, - DbModelType extends DocumentData ->( - snapshot: DocumentSnapshot_2 -): QueryStartAtConstraint; - -/** - * Creates a {@link QueryStartAtConstraint} that modifies the result set to - * start after the provided fields relative to the order of the query. The order - * of the field values must match the order of the order by clauses of the query. - * - * @param fieldValues - The field values to start this query after, in order - * of the query's order by. - * @returns A {@link QueryStartAtConstraint} to pass to `query()` - */ -export declare function startAfter( - ...fieldValues: unknown[] -): QueryStartAtConstraint; - -/** - * Creates a {@link QueryStartAtConstraint} that modifies the result set to - * start at the provided document (inclusive). The starting position is relative - * to the order of the query. The document must contain all of the fields - * provided in the `orderBy` of this query. - * - * @param snapshot - The snapshot of the document to start at. - * @returns A {@link QueryStartAtConstraint} to pass to `query()`. - */ -export declare function startAt( - snapshot: DocumentSnapshot_2 -): QueryStartAtConstraint; - -/** - * Creates a {@link QueryStartAtConstraint} that modifies the result set to - * start at the provided fields relative to the order of the query. The order of - * the field values must match the order of the order by clauses of the query. - * - * @param fieldValues - The field values to start this query at, in order - * of the query's order by. - * @returns A {@link QueryStartAtConstraint} to pass to `query()`. - */ -export declare function startAt( - ...fieldValues: unknown[] -): QueryStartAtConstraint; - -declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; - -/** - * Create an AggregateField object that can be used to compute the sum of - * a specified field over a range of documents in the result set of a query. - * @param field Specifies the field to sum across the result set. - */ -export declare function sum(field: string | FieldPath): AggregateField; - -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * SyncEngine is the central controller in the client SDK architecture. It is - * the glue code between the EventManager, LocalStore, and RemoteStore. Some of - * SyncEngine's responsibilities include: - * 1. Coordinating client requests and remote events between the EventManager - * and the local and remote data stores. - * 2. Managing a View object for each query, providing the unified view between - * the local and remote data stores. - * 3. Notifying the RemoteStore when the LocalStore has new mutations in its - * queue that need sending to the backend. - * - * The SyncEngine’s methods should only ever be called by methods running in the - * global async queue. - * - * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() - * function. Instead, it directly depends on EventManager's tree-shakeable API - * (via `ensureWatchStream()`). - */ -declare interface SyncEngine { - isPrimaryClient: boolean; -} - -/** - * A Target represents the WatchTarget representation of a Query, which is used - * by the LocalStore and the RemoteStore to keep track of and to execute - * backend queries. While a Query can represent multiple Targets, each Targets - * maps to a single WatchTarget in RemoteStore and a single TargetData entry - * in persistence. - */ -declare interface Target { - readonly path: _ResourcePath; - readonly collectionGroup: string | null; - readonly orderBy: OrderBy[]; - readonly filters: Filter[]; - readonly limit: number | null; - readonly startAt: Bound | null; - readonly endAt: Bound | null; -} - -/** - * Represents cached targets received from the remote backend. - * - * The cache is keyed by `Target` and entries in the cache are `TargetData` - * instances. - */ -declare interface TargetCache { - /** - * A global snapshot version representing the last consistent snapshot we - * received from the backend. This is monotonically increasing and any - * snapshots received from the backend prior to this version (e.g. for targets - * resumed with a resume_token) should be suppressed (buffered) until the - * backend has caught up to this snapshot version again. This prevents our - * cache from ever going backwards in time. - * - * This is updated whenever our we get a TargetChange with a read_time and - * empty target_ids. - */ - getLastRemoteSnapshotVersion( - transaction: PersistenceTransaction - ): PersistencePromise; - /** - * @returns The highest sequence number observed, including any that might be - * persisted on-disk. - */ - getHighestSequenceNumber( - transaction: PersistenceTransaction - ): PersistencePromise; - /** - * Call provided function with each `TargetData` that we have cached. - */ - forEachTarget( - txn: PersistenceTransaction, - f: (q: TargetData) => void - ): PersistencePromise; - /** - * Set the highest listen sequence number and optionally updates the - * snapshot version of the last consistent snapshot received from the backend - * (see getLastRemoteSnapshotVersion() for more details). - * - * @param highestListenSequenceNumber - The new maximum listen sequence number. - * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. - */ - setTargetsMetadata( - transaction: PersistenceTransaction, - highestListenSequenceNumber: number, - lastRemoteSnapshotVersion?: SnapshotVersion - ): PersistencePromise; - /** - * Adds an entry in the cache. - * - * The cache key is extracted from `targetData.target`. The key must not already - * exist in the cache. - * - * @param targetData - A TargetData instance to put in the cache. - */ - addTargetData( - transaction: PersistenceTransaction, - targetData: TargetData - ): PersistencePromise; - /** - * Updates an entry in the cache. - * - * The cache key is extracted from `targetData.target`. The entry must already - * exist in the cache, and it will be replaced. - * @param targetData - The TargetData to be replaced into the cache. - */ - updateTargetData( - transaction: PersistenceTransaction, - targetData: TargetData - ): PersistencePromise; - /** - * Removes the cached entry for the given target data. It is an error to remove - * a target data that does not exist. - * - * Multi-Tab Note: This operation should only be called by the primary client. - */ - removeTargetData( - transaction: PersistenceTransaction, - targetData: TargetData - ): PersistencePromise; - /** - * The number of targets currently in the cache. - */ - getTargetCount( - transaction: PersistenceTransaction - ): PersistencePromise; - /** - * Looks up a TargetData entry by target. - * - * @param target - The query target corresponding to the entry to look up. - * @returns The cached TargetData entry, or null if the cache has no entry for - * the target. - */ - getTargetData( - transaction: PersistenceTransaction, - target: Target - ): PersistencePromise; - /** - * Adds the given document keys to cached query results of the given target - * ID. - * - * Multi-Tab Note: This operation should only be called by the primary client. - */ - addMatchingKeys( - transaction: PersistenceTransaction, - keys: DocumentKeySet, - targetId: TargetId - ): PersistencePromise; - /** - * Removes the given document keys from the cached query results of the - * given target ID. - * - * Multi-Tab Note: This operation should only be called by the primary client. - */ - removeMatchingKeys( - transaction: PersistenceTransaction, - keys: DocumentKeySet, - targetId: TargetId - ): PersistencePromise; - /** - * Removes all the keys in the query results of the given target ID. - * - * Multi-Tab Note: This operation should only be called by the primary client. - */ - removeMatchingKeysForTargetId( - transaction: PersistenceTransaction, - targetId: TargetId - ): PersistencePromise; - /** - * Returns the document keys that match the provided target ID. - */ - getMatchingKeysForTargetId( - transaction: PersistenceTransaction, - targetId: TargetId - ): PersistencePromise; - /** - * Returns a new target ID that is higher than any query in the cache. If - * there are no queries in the cache, returns the first valid target ID. - * Allocated target IDs are persisted and `allocateTargetId()` will never - * return the same ID twice. - */ - allocateTargetId( - transaction: PersistenceTransaction - ): PersistencePromise; - containsKey( - transaction: PersistenceTransaction, - key: _DocumentKey - ): PersistencePromise; -} - -/** - * A TargetChange specifies the set of changes for a specific target as part of - * a RemoteEvent. These changes track which documents are added, modified or - * removed, as well as the target's resume token and whether the target is - * marked CURRENT. - * The actual changes *to* documents are not part of the TargetChange since - * documents may be part of multiple targets. - */ -declare class TargetChange { - /** - * An opaque, server-assigned token that allows watching a query to be resumed - * after disconnecting without retransmitting all the data that matches the - * query. The resume token essentially identifies a point in time from which - * the server should resume sending results. - */ - readonly resumeToken: _ByteString; - /** - * The "current" (synced) status of this target. Note that "current" - * has special meaning in the RPC protocol that implies that a target is - * both up-to-date and consistent with the rest of the watch stream. - */ - readonly current: boolean; - /** - * The set of documents that were newly assigned to this target as part of - * this remote event. - */ - readonly addedDocuments: DocumentKeySet; - /** - * The set of documents that were already assigned to this target but received - * an update during this remote event. - */ - readonly modifiedDocuments: DocumentKeySet; - /** - * The set of documents that were removed from this target as part of this - * remote event. - */ - readonly removedDocuments: DocumentKeySet; - constructor( - /** - * An opaque, server-assigned token that allows watching a query to be resumed - * after disconnecting without retransmitting all the data that matches the - * query. The resume token essentially identifies a point in time from which - * the server should resume sending results. - */ - resumeToken: _ByteString, - /** - * The "current" (synced) status of this target. Note that "current" - * has special meaning in the RPC protocol that implies that a target is - * both up-to-date and consistent with the rest of the watch stream. - */ - current: boolean, - /** - * The set of documents that were newly assigned to this target as part of - * this remote event. - */ - addedDocuments: DocumentKeySet, - /** - * The set of documents that were already assigned to this target but received - * an update during this remote event. - */ - modifiedDocuments: DocumentKeySet, - /** - * The set of documents that were removed from this target as part of this - * remote event. - */ - removedDocuments: DocumentKeySet - ); - /** - * This method is used to create a synthesized TargetChanges that can be used to - * apply a CURRENT status change to a View (for queries executed in a different - * tab) or for new queries (to raise snapshots with correct CURRENT status). - */ - static createSynthesizedTargetChangeForCurrentChange( - targetId: TargetId, - current: boolean, - resumeToken: _ByteString - ): TargetChange; -} - -declare type TargetChangeTargetChangeType = - | 'NO_CHANGE' - | 'ADD' - | 'REMOVE' - | 'CURRENT' - | 'RESET'; - -/** - * An immutable set of metadata that the local store tracks for each target. - */ -declare class TargetData { - /** The target being listened to. */ - readonly target: Target; - /** - * The target ID to which the target corresponds; Assigned by the - * LocalStore for user listens and by the SyncEngine for limbo watches. - */ - readonly targetId: TargetId; - /** The purpose of the target. */ - readonly purpose: TargetPurpose; - /** - * The sequence number of the last transaction during which this target data - * was modified. - */ - readonly sequenceNumber: ListenSequenceNumber; - /** The latest snapshot version seen for this target. */ - readonly snapshotVersion: SnapshotVersion; - /** - * The maximum snapshot version at which the associated view - * contained no limbo documents. - */ - readonly lastLimboFreeSnapshotVersion: SnapshotVersion; - /** - * An opaque, server-assigned token that allows watching a target to be - * resumed after disconnecting without retransmitting all the data that - * matches the target. The resume token essentially identifies a point in - * time from which the server should resume sending results. - */ - readonly resumeToken: _ByteString; - /** - * The number of documents that last matched the query at the resume token or - * read time. Documents are counted only when making a listen request with - * resume token or read time, otherwise, keep it null. - */ - readonly expectedCount: number | null; - constructor( - /** The target being listened to. */ - target: Target, - /** - * The target ID to which the target corresponds; Assigned by the - * LocalStore for user listens and by the SyncEngine for limbo watches. - */ - targetId: TargetId, - /** The purpose of the target. */ - purpose: TargetPurpose, - /** - * The sequence number of the last transaction during which this target data - * was modified. - */ - sequenceNumber: ListenSequenceNumber, - /** The latest snapshot version seen for this target. */ - snapshotVersion?: SnapshotVersion, - /** - * The maximum snapshot version at which the associated view - * contained no limbo documents. - */ - lastLimboFreeSnapshotVersion?: SnapshotVersion, - /** - * An opaque, server-assigned token that allows watching a target to be - * resumed after disconnecting without retransmitting all the data that - * matches the target. The resume token essentially identifies a point in - * time from which the server should resume sending results. - */ - resumeToken?: _ByteString, - /** - * The number of documents that last matched the query at the resume token or - * read time. Documents are counted only when making a listen request with - * resume token or read time, otherwise, keep it null. - */ - expectedCount?: number | null - ); - /** Creates a new target data instance with an updated sequence number. */ - withSequenceNumber(sequenceNumber: number): TargetData; - /** - * Creates a new target data instance with an updated resume token and - * snapshot version. - */ - withResumeToken( - resumeToken: _ByteString, - snapshotVersion: SnapshotVersion - ): TargetData; - /** - * Creates a new target data instance with an updated expected count. - */ - withExpectedCount(expectedCount: number): TargetData; - /** - * Creates a new target data instance with an updated last limbo free - * snapshot version number. - */ - withLastLimboFreeSnapshotVersion( - lastLimboFreeSnapshotVersion: SnapshotVersion - ): TargetData; -} - -/** - * A locally-assigned ID used to refer to a target being watched via the - * Watch service. - */ -declare type TargetId = number; - -/** An enumeration of the different purposes we have for targets. */ -declare const enum TargetPurpose { - /** A regular, normal query target. */ - Listen = 'TargetPurposeListen', - /** - * The query target was used to refill a query after an existence filter - * mismatch. - */ - ExistenceFilterMismatch = 'TargetPurposeExistenceFilterMismatch', - /** - * The query target was used if the query is the result of a false positive in - * the bloom filter. - */ - ExistenceFilterMismatchBloom = 'TargetPurposeExistenceFilterMismatchBloom', - /** The query target was used to resolve a limbo document. */ - LimboResolution = 'TargetPurposeLimboResolution' -} - -/** - * Represents the state of bundle loading tasks. - * - * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will - * be no more updates after they are reported. - */ -export declare type TaskState = 'Error' | 'Running' | 'Success'; - -/** - * Terminates the provided {@link Firestore} instance. - * - * After calling `terminate()` only the `clearIndexedDbPersistence()` function - * may be used. Any other function will throw a `FirestoreError`. - * - * To restart after termination, create a new instance of FirebaseFirestore with - * {@link (getFirestore:1)}. - * - * Termination does not cancel any pending writes, and any promises that are - * awaiting a response from the server will not be resolved. If you have - * persistence enabled, the next time you start this instance, it will resume - * sending these writes to the server. - * - * Note: Under normal circumstances, calling `terminate()` is not required. This - * function is useful only when you want to force this instance to release all - * of its resources or in combination with `clearIndexedDbPersistence()` to - * ensure that all local state is destroyed between test runs. - * - * @returns A `Promise` that is resolved when the instance has been successfully - * terminated. - */ -export declare function terminate(firestore: Firestore): Promise; - -/* Excluded from this release type: _TestingHooks */ - -/* Excluded from this release type: _TestingHooksExistenceFilterMismatchCallback */ - -/* Excluded from this release type: _TestingHooksExistenceFilterMismatchInfo */ - -/** - * Wellknown "timer" IDs used when scheduling delayed operations on the - * AsyncQueue. These IDs can then be used from tests to check for the presence - * of operations or to run them early. - * - * The string values are used when encoding these timer IDs in JSON spec tests. - */ -declare const enum TimerId { - /** All can be used with runDelayedOperationsEarly() to run all timers. */ - All = 'all', - /** - * The following 5 timers are used in persistent_stream.ts for the listen and - * write streams. The "Idle" timer is used to close the stream due to - * inactivity. The "ConnectionBackoff" timer is used to restart a stream once - * the appropriate backoff delay has elapsed. The health check is used to mark - * a stream healthy if it has not received an error during its initial setup. - */ - ListenStreamIdle = 'listen_stream_idle', - ListenStreamConnectionBackoff = 'listen_stream_connection_backoff', - WriteStreamIdle = 'write_stream_idle', - WriteStreamConnectionBackoff = 'write_stream_connection_backoff', - HealthCheckTimeout = 'health_check_timeout', - /** - * A timer used in online_state_tracker.ts to transition from - * OnlineState.Unknown to Offline after a set timeout, rather than waiting - * indefinitely for success or failure. - */ - OnlineStateTimeout = 'online_state_timeout', - /** - * A timer used to update the client metadata in IndexedDb, which is used - * to determine the primary leaseholder. - */ - ClientMetadataRefresh = 'client_metadata_refresh', - /** A timer used to periodically attempt LRU Garbage collection */ - LruGarbageCollection = 'lru_garbage_collection', - /** - * A timer used to retry transactions. Since there can be multiple concurrent - * transactions, multiple of these may be in the queue at a given time. - */ - TransactionRetry = 'transaction_retry', - /** - * A timer used to retry operations scheduled via retryable AsyncQueue - * operations. - */ - AsyncQueueRetry = 'async_queue_retry', - /** - * A timer used to periodically attempt index backfill. - */ - IndexBackfill = 'index_backfill' -} - -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A `Timestamp` represents a point in time independent of any time zone or - * calendar, represented as seconds and fractions of seconds at nanosecond - * resolution in UTC Epoch time. - * - * It is encoded using the Proleptic Gregorian Calendar which extends the - * Gregorian calendar backwards to year one. It is encoded assuming all minutes - * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second - * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59.999999999Z. - * - * For examples and further specifications, refer to the - * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. - */ -export declare class Timestamp { - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - */ - readonly seconds: number; - /** - * The fractions of a second at nanosecond resolution.* - */ - readonly nanoseconds: number; - /** - * Creates a new timestamp with the current date, with millisecond precision. - * - * @returns a new timestamp representing the current date. - */ - static now(): Timestamp; - /** - * Creates a new timestamp from the given date. - * - * @param date - The date to initialize the `Timestamp` from. - * @returns A new `Timestamp` representing the same point in time as the given - * date. - */ - static fromDate(date: Date): Timestamp; - /** - * Creates a new timestamp from the given number of milliseconds. - * - * @param milliseconds - Number of milliseconds since Unix epoch - * 1970-01-01T00:00:00Z. - * @returns A new `Timestamp` representing the same point in time as the given - * number of milliseconds. - */ - static fromMillis(milliseconds: number): Timestamp; - /** - * Creates a new timestamp. - * - * @param seconds - The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive. - * @param nanoseconds - The non-negative fractions of a second at nanosecond - * resolution. Negative second values with fractions must still have - * non-negative nanoseconds values that count forward in time. Must be - * from 0 to 999,999,999 inclusive. - */ - constructor( - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - */ - seconds: number, - /** - * The fractions of a second at nanosecond resolution.* - */ - nanoseconds: number - ); - /** - * Converts a `Timestamp` to a JavaScript `Date` object. This conversion - * causes a loss of precision since `Date` objects only support millisecond - * precision. - * - * @returns JavaScript `Date` object representing the same point in time as - * this `Timestamp`, with millisecond precision. - */ - toDate(): Date; - /** - * Converts a `Timestamp` to a numeric timestamp (in milliseconds since - * epoch). This operation causes a loss of precision. - * - * @returns The point in time corresponding to this timestamp, represented as - * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. - */ - toMillis(): number; - _compareTo(other: Timestamp): number; - /** - * Returns true if this `Timestamp` is equal to the provided one. - * - * @param other - The `Timestamp` to compare against. - * @returns true if this `Timestamp` is equal to the provided one. - */ - isEqual(other: Timestamp): boolean; - /** Returns a textual representation of this `Timestamp`. */ - toString(): string; - /** Returns a JSON-serializable representation of this `Timestamp`. */ - toJSON(): { - seconds: number; - nanoseconds: number; - }; - /** - * Converts this object to a primitive string, which allows `Timestamp` objects - * to be compared using the `>`, `<=`, `>=` and `>` operators. - */ - valueOf(): string; -} - -declare type Timestamp_2 = - | string - | { - seconds?: string | number; - nanos?: number; - }; - -declare interface Token { - /** Type of token. */ - type: TokenType; - /** - * The user with which the token is associated (used for persisting user - * state on disk, etc.). - * This will be null for Tokens of the type 'AppCheck'. - */ - user?: User; - /** Header values to set for this token */ - headers: Map; -} - -declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; - -/** - * A reference to a transaction. - * - * The `Transaction` object passed to a transaction's `updateFunction` provides - * the methods to read and write data within the transaction context. See - * {@link runTransaction}. - */ -export declare class Transaction extends Transaction_2 { - protected readonly _firestore: Firestore; - /** @hideconstructor */ - constructor(_firestore: Firestore, _transaction: Transaction_3); - /** - * Reads the document referenced by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be read. - * @returns A `DocumentSnapshot` with the read data. - */ - get( - documentRef: DocumentReference - ): Promise>; -} - -/** - * A reference to a transaction. - * - * The `Transaction` object passed to a transaction's `updateFunction` provides - * the methods to read and write data within the transaction context. See - * {@link runTransaction}. - */ -declare class Transaction_2 { - protected readonly _firestore: Firestore_2; - private readonly _transaction; - private readonly _dataReader; - /** @hideconstructor */ - constructor(_firestore: Firestore_2, _transaction: Transaction_3); - /** - * Reads the document referenced by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be read. - * @returns A `DocumentSnapshot` with the read data. - */ - get( - documentRef: DocumentReference - ): Promise>; - /** - * Writes to the document referred to by the provided {@link - * DocumentReference}. If the document does not exist yet, it will be created. - * - * @param documentRef - A reference to the document to be set. - * @param data - An object of the fields and values for the document. - * @throws Error - If the provided input is not a valid Firestore document. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - set( - documentRef: DocumentReference, - data: WithFieldValue - ): this; - /** - * Writes to the document referred to by the provided {@link - * DocumentReference}. If the document does not exist yet, it will be created. - * If you provide `merge` or `mergeFields`, the provided data can be merged - * into an existing document. - * - * @param documentRef - A reference to the document to be set. - * @param data - An object of the fields and values for the document. - * @param options - An object to configure the set behavior. - * @throws Error - If the provided input is not a valid Firestore document. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - set( - documentRef: DocumentReference, - data: PartialWithFieldValue, - options: SetOptions - ): this; - /** - * Updates fields in the document referred to by the provided {@link - * DocumentReference}. The update will fail if applied to a document that does - * not exist. - * - * @param documentRef - A reference to the document to be updated. - * @param data - An object containing the fields and values with which to - * update the document. Fields can contain dots to reference nested fields - * within the document. - * @throws Error - If the provided input is not valid Firestore data. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - update( - documentRef: DocumentReference, - data: UpdateData - ): this; - /** - * Updates fields in the document referred to by the provided {@link - * DocumentReference}. The update will fail if applied to a document that does - * not exist. - * - * Nested fields can be updated by providing dot-separated field path - * strings or by providing `FieldPath` objects. - * - * @param documentRef - A reference to the document to be updated. - * @param field - The first field to update. - * @param value - The first value. - * @param moreFieldsAndValues - Additional key/value pairs. - * @throws Error - If the provided input is not valid Firestore data. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - update( - documentRef: DocumentReference, - field: string | FieldPath, - value: unknown, - ...moreFieldsAndValues: unknown[] - ): this; - /** - * Deletes the document referred to by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be deleted. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - delete( - documentRef: DocumentReference - ): this; -} - -/** - * Internal transaction object responsible for accumulating the mutations to - * perform and the base versions for any documents read. - */ -declare class Transaction_3 { - private datastore; - private readVersions; - private mutations; - private committed; - /** - * A deferred usage error that occurred previously in this transaction that - * will cause the transaction to fail once it actually commits. - */ - private lastTransactionError; - /** - * Set of documents that have been written in the transaction. - * - * When there's more than one write to the same key in a transaction, any - * writes after the first are handled differently. - */ - private writtenDocs; - constructor(datastore: Datastore); - lookup(keys: _DocumentKey[]): Promise; - set(key: _DocumentKey, data: ParsedSetData): void; - update(key: _DocumentKey, data: ParsedUpdateData): void; - delete(key: _DocumentKey): void; - commit(): Promise; - private recordVersion; - /** - * Returns the version of this document when it was read in this transaction, - * as a precondition, or no precondition if it was not read. - */ - private precondition; - /** - * Returns the precondition for a document if the operation is an update. - */ - private preconditionForUpdate; - private write; - private ensureCommitNotCalled; -} - -/** - * @license - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Options to customize transaction behavior. - */ -export declare interface TransactionOptions { - /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ - readonly maxAttempts?: number; -} - -/** Used to represent a field transform on a mutation. */ -declare class TransformOperation { - private _; -} - -declare type UnaryFilterOp = - | 'OPERATOR_UNSPECIFIED' - | 'IS_NAN' - | 'IS_NULL' - | 'IS_NOT_NAN' - | 'IS_NOT_NULL'; - -/** - * Given a union type `U = T1 | T2 | ...`, returns an intersected type - * `(T1 & T2 & ...)`. - * - * Uses distributive conditional types and inference from conditional types. - * This works because multiple candidates for the same type variable in - * contra-variant positions causes an intersection type to be inferred. - * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types - * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type - */ -export declare type UnionToIntersection = ( - U extends unknown ? (k: U) => void : never -) extends (k: infer I) => void - ? I - : never; - -/** - * A function returned by `onSnapshot()` that removes the listener when invoked. - */ -export declare interface Unsubscribe { - /** Removes the listener when invoked. */ - (): void; -} - -/** - * An untyped Firestore Data Converter interface that is shared between the - * lite, firestore-exp and classic SDK. - */ -declare interface UntypedFirestoreDataConverter< - AppModelType, - DbModelType extends DocumentData_2 = DocumentData_2 -> { - toFirestore( - modelObject: WithFieldValue - ): WithFieldValue; - toFirestore( - modelObject: PartialWithFieldValue, - options: SetOptions_2 - ): PartialWithFieldValue; - fromFirestore(snapshot: unknown, options?: unknown): AppModelType; -} - -/** - * Update data (for use with {@link (updateDoc:1)}) that consists of field paths - * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots - * reference nested fields within the document. FieldValues can be passed in - * as property values. - */ -export declare type UpdateData = T extends Primitive - ? T - : T extends {} - ? { - [K in keyof T]?: UpdateData | FieldValue; - } & NestedUpdateFields - : Partial; - -/** - * Updates fields in the document referred to by the specified - * `DocumentReference`. The update will fail if applied to a document that does - * not exist. - * - * @param reference - A reference to the document to update. - * @param data - An object containing the fields and values with which to - * update the document. Fields can contain dots to reference nested fields - * within the document. - * @returns A `Promise` resolved once the data has been successfully written - * to the backend (note that it won't resolve while you're offline). - */ -export declare function updateDoc< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference, - data: UpdateData -): Promise; - -/** - * Updates fields in the document referred to by the specified - * `DocumentReference` The update will fail if applied to a document that does - * not exist. - * - * Nested fields can be updated by providing dot-separated field path - * strings or by providing `FieldPath` objects. - * - * @param reference - A reference to the document to update. - * @param field - The first field to update. - * @param value - The first value. - * @param moreFieldsAndValues - Additional key value pairs. - * @returns A `Promise` resolved once the data has been successfully written - * to the backend (note that it won't resolve while you're offline). - */ -export declare function updateDoc< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference, - field: string | FieldPath, - value: unknown, - ...moreFieldsAndValues: unknown[] -): Promise; - -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Simple wrapper around a nullable UID. Mostly exists to make code more - * readable. - */ -declare class User { - readonly uid: string | null; - /** A user with a null UID. */ - static readonly UNAUTHENTICATED: User; - static readonly GOOGLE_CREDENTIALS: User; - static readonly FIRST_PARTY: User; - static readonly MOCK_USER: User; - constructor(uid: string | null); - isAuthenticated(): boolean; - /** - * Returns a key representing this user, suitable for inclusion in a - * dictionary. - */ - toKey(): string; - isEqual(otherUser: User): boolean; -} - -/* Excluded from this release type: _validateIsNotUsedTogether */ - -declare type Value = firestoreV1ApiClientInterfaces.Value; - -declare type ValueNullValue = 'NULL_VALUE'; - -/** - * Creates a new `VectorValue` constructed with a copy of the given array of numbers. - * - * @param values - Create a `VectorValue` instance with a copy of this array of numbers. - * - * @returns A new `VectorValue` constructed with a copy of the given array of numbers. - */ -export declare function vector(values?: number[]): VectorValue; - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Represents a vector type in Firestore documents. - * Create an instance with {@link FieldValue.vector}. - * - * @class VectorValue - */ -export declare class VectorValue { - private readonly _values; - /* Excluded from this release type: __constructor */ - /** - * Returns a copy of the raw number array form of the vector. - */ - toArray(): number[]; - /** - * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise. - */ - isEqual(other: VectorValue): boolean; -} - -declare class ViewSnapshot { - readonly query: Query_2; - readonly docs: DocumentSet; - readonly oldDocs: DocumentSet; - readonly docChanges: DocumentViewChange[]; - readonly mutatedKeys: DocumentKeySet; - readonly fromCache: boolean; - readonly syncStateChanged: boolean; - readonly excludesMetadataChanges: boolean; - readonly hasCachedResults: boolean; - constructor( - query: Query_2, - docs: DocumentSet, - oldDocs: DocumentSet, - docChanges: DocumentViewChange[], - mutatedKeys: DocumentKeySet, - fromCache: boolean, - syncStateChanged: boolean, - excludesMetadataChanges: boolean, - hasCachedResults: boolean - ); - /** Returns a view snapshot as if all documents in the snapshot were added. */ - static fromInitialDocuments( - query: Query_2, - documents: DocumentSet, - mutatedKeys: DocumentKeySet, - fromCache: boolean, - hasCachedResults: boolean - ): ViewSnapshot; - get hasPendingWrites(): boolean; - isEqual(other: ViewSnapshot): boolean; -} - -/** - * Waits until all currently pending writes for the active user have been - * acknowledged by the backend. - * - * The returned promise resolves immediately if there are no outstanding writes. - * Otherwise, the promise waits for all previously issued writes (including - * those written in a previous app session), but it does not wait for writes - * that were added after the function is called. If you want to wait for - * additional writes, call `waitForPendingWrites()` again. - * - * Any outstanding `waitForPendingWrites()` promises are rejected during user - * changes. - * - * @returns A `Promise` which resolves when all currently pending writes have been - * acknowledged by the backend. - */ -export declare function waitForPendingWrites( - firestore: Firestore -): Promise; - -/** - * Creates a {@link QueryFieldFilterConstraint} that enforces that documents - * must contain the specified field and that the value should satisfy the - * relation constraint provided. - * - * @param fieldPath - The path to compare - * @param opStr - The operation string (e.g "<", "<=", "==", "<", - * "<=", "!="). - * @param value - The value for comparison - * @returns The created {@link QueryFieldFilterConstraint}. - */ -export declare function where( - fieldPath: string | FieldPath, - opStr: WhereFilterOp, - value: unknown -): QueryFieldFilterConstraint; - -/** - * Filter conditions in a {@link where} clause are specified using the - * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', - * 'array-contains-any', and 'not-in'. - */ -export declare type WhereFilterOp = - | '<' - | '<=' - | '==' - | '!=' - | '>=' - | '>' - | 'array-contains' - | 'in' - | 'array-contains-any' - | 'not-in'; - -/** - * Allows FieldValues to be passed in as a property value while maintaining - * type safety. - */ -export declare type WithFieldValue = - | T - | (T extends Primitive - ? T - : T extends {} - ? { - [K in keyof T]: WithFieldValue | FieldValue; - } - : never); - -/** - * A write batch, used to perform multiple writes as a single atomic unit. - * - * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It - * provides methods for adding writes to the write batch. None of the writes - * will be committed (or visible locally) until {@link WriteBatch.commit} is - * called. - */ -export declare class WriteBatch { - private readonly _firestore; - private readonly _commitHandler; - private readonly _dataReader; - private _mutations; - private _committed; - /** @hideconstructor */ - constructor( - _firestore: Firestore_2, - _commitHandler: (m: Mutation[]) => Promise - ); - /** - * Writes to the document referred to by the provided {@link - * DocumentReference}. If the document does not exist yet, it will be created. - * - * @param documentRef - A reference to the document to be set. - * @param data - An object of the fields and values for the document. - * @returns This `WriteBatch` instance. Used for chaining method calls. - */ - set( - documentRef: DocumentReference, - data: WithFieldValue - ): WriteBatch; - /** - * Writes to the document referred to by the provided {@link - * DocumentReference}. If the document does not exist yet, it will be created. - * If you provide `merge` or `mergeFields`, the provided data can be merged - * into an existing document. - * - * @param documentRef - A reference to the document to be set. - * @param data - An object of the fields and values for the document. - * @param options - An object to configure the set behavior. - * @throws Error - If the provided input is not a valid Firestore document. - * @returns This `WriteBatch` instance. Used for chaining method calls. - */ - set( - documentRef: DocumentReference, - data: PartialWithFieldValue, - options: SetOptions - ): WriteBatch; - /** - * Updates fields in the document referred to by the provided {@link - * DocumentReference}. The update will fail if applied to a document that does - * not exist. - * - * @param documentRef - A reference to the document to be updated. - * @param data - An object containing the fields and values with which to - * update the document. Fields can contain dots to reference nested fields - * within the document. - * @throws Error - If the provided input is not valid Firestore data. - * @returns This `WriteBatch` instance. Used for chaining method calls. - */ - update( - documentRef: DocumentReference, - data: UpdateData - ): WriteBatch; - /** - * Updates fields in the document referred to by this {@link - * DocumentReference}. The update will fail if applied to a document that does - * not exist. - * - * Nested fields can be update by providing dot-separated field path strings - * or by providing `FieldPath` objects. - * - * @param documentRef - A reference to the document to be updated. - * @param field - The first field to update. - * @param value - The first value. - * @param moreFieldsAndValues - Additional key value pairs. - * @throws Error - If the provided input is not valid Firestore data. - * @returns This `WriteBatch` instance. Used for chaining method calls. - */ - update( - documentRef: DocumentReference, - field: string | FieldPath, - value: unknown, - ...moreFieldsAndValues: unknown[] - ): WriteBatch; - /** - * Deletes the document referred to by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be deleted. - * @returns This `WriteBatch` instance. Used for chaining method calls. - */ - delete( - documentRef: DocumentReference - ): WriteBatch; - /** - * Commits all of the writes in this write batch as a single atomic unit. - * - * The result of these writes will only be reflected in document reads that - * occur after the returned promise resolves. If the client is offline, the - * write fails. If you would like to see local modifications or buffer writes - * until the client is online, use the full Firestore SDK. - * - * @returns A `Promise` resolved once all of the writes in the batch have been - * successfully written to the backend as an atomic unit (note that it won't - * resolve while you're offline). - */ - commit(): Promise; - private _verifyNotCommitted; -} - -/** - * Creates a write batch, used for performing multiple writes as a single - * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} - * is 500. - * - * Unlike transactions, write batches are persisted offline and therefore are - * preferable when you don't need to condition your writes on read data. - * - * @returns A {@link WriteBatch} that can be used to atomically execute multiple - * writes. - */ -export declare function writeBatch(firestore: Firestore): WriteBatch; - -export {}; diff --git a/repo-scripts/prune-dts/new-tests/firestore.output.d.ts b/repo-scripts/prune-dts/new-tests/firestore.output.d.ts deleted file mode 100644 index 33048292e38..00000000000 --- a/repo-scripts/prune-dts/new-tests/firestore.output.d.ts +++ /dev/null @@ -1,3475 +0,0 @@ -/** - * Cloud Firestore - * - * @packageDocumentation - */ -import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; -import { EmulatorMockTokenOptions } from '@firebase/util'; -import { FirebaseApp } from '@firebase/app'; -import { FirebaseError } from '@firebase/util'; -import { LogLevelString as LogLevel } from '@firebase/logger'; -import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; -/** - * Add a new document to specified `CollectionReference` with the given data, - * assigning it a document ID automatically. - * - * @param reference - A reference to the collection to add this document to. - * @param data - An Object containing the data for the new document. - * @returns A `Promise` resolved with a `DocumentReference` pointing to the - * newly created document after it has been written to the backend (Note that it - * won't resolve while you're offline). - */ -export declare function addDoc( - reference: CollectionReference, - data: WithFieldValue -): Promise>; -/** - * Returns a new map where every key is prefixed with the outer key appended - * to a dot. - */ -export declare type AddPrefixToKeys< - Prefix extends string, - T extends Record -> = { - [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; -}; -/** - * Represents an aggregation that can be performed by Firestore. - */ -export declare class AggregateField { - /** A type string to uniquely identify instances of this class. */ - readonly type = 'AggregateField'; - /** Indicates the aggregation operation of this AggregateField. */ - readonly aggregateType: AggregateType; -} -/** - * Compares two 'AggregateField` instances for equality. - * - * @param left Compare this AggregateField to the `right`. - * @param right Compare this AggregateField to the `left`. - */ -export declare function aggregateFieldEqual( - left: AggregateField, - right: AggregateField -): boolean; -/** - * The union of all `AggregateField` types that are supported by Firestore. - */ -export declare type AggregateFieldType = - | ReturnType - | ReturnType - | ReturnType; -/** - * The results of executing an aggregation query. - */ -export declare class AggregateQuerySnapshot< - AggregateSpecType extends AggregateSpec, - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> { - /** A type string to uniquely identify instances of this class. */ - readonly type = 'AggregateQuerySnapshot'; - /** - * The underlying query over which the aggregations recorded in this - * `AggregateQuerySnapshot` were performed. - */ - readonly query: Query; - private constructor(); - /** - * Returns the results of the aggregations performed over the underlying - * query. - * - * The keys of the returned object will be the same as those of the - * `AggregateSpec` object specified to the aggregation method, and the values - * will be the corresponding aggregation result. - * - * @returns The results of the aggregations performed over the underlying - * query. - */ - data(): AggregateSpecData; -} -/** - * Compares two `AggregateQuerySnapshot` instances for equality. - * - * Two `AggregateQuerySnapshot` instances are considered "equal" if they have - * underlying queries that compare equal, and the same data. - * - * @param left - The first `AggregateQuerySnapshot` to compare. - * @param right - The second `AggregateQuerySnapshot` to compare. - * - * @returns `true` if the objects are "equal", as defined above, or `false` - * otherwise. - */ -export declare function aggregateQuerySnapshotEqual< - AggregateSpecType extends AggregateSpec, - AppModelType, - DbModelType extends DocumentData ->( - left: AggregateQuerySnapshot, - right: AggregateQuerySnapshot -): boolean; -/** - * Specifies a set of aggregations and their aliases. - */ -export declare interface AggregateSpec { - [field: string]: AggregateFieldType; -} -/** - * A type whose keys are taken from an `AggregateSpec`, and whose values are the - * result of the aggregation performed by the corresponding `AggregateField` - * from the input `AggregateSpec`. - */ -export declare type AggregateSpecData = { - [P in keyof T]: T[P] extends AggregateField ? U : never; -}; -/** - * Union type representing the aggregate type to be performed. - */ -export declare type AggregateType = 'count' | 'avg' | 'sum'; -/** - * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of - * the given filter constraints. A conjunction filter includes a document if it - * satisfies all of the given filters. - * - * @param queryConstraints - Optional. The list of - * {@link QueryFilterConstraint}s to perform a conjunction for. These must be - * created with calls to {@link where}, {@link or}, or {@link and}. - * @returns The newly created {@link QueryCompositeFilterConstraint}. - */ -export declare function and( - ...queryConstraints: QueryFilterConstraint[] -): QueryCompositeFilterConstraint; -/** - * Returns a special value that can be used with {@link (setDoc:1)} or {@link - * updateDoc:1} that tells the server to remove the given elements from any - * array value that already exists on the server. All instances of each element - * specified will be removed from the array. If the field being modified is not - * already an array it will be overwritten with an empty array. - * - * @param elements - The elements to remove from the array. - * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or - * `updateDoc()` - */ -export declare function arrayRemove(...elements: unknown[]): FieldValue; -/** - * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link - * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array - * value that already exists on the server. Each specified element that doesn't - * already exist in the array will be added to the end. If the field being - * modified is not already an array it will be overwritten with an array - * containing exactly the specified elements. - * - * @param elements - The elements to union into the array. - * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or - * `updateDoc()`. - */ -export declare function arrayUnion(...elements: unknown[]): FieldValue; -/* Excluded from this release type: AuthTokenFactory */ -/* Excluded from this release type: _AutoId */ -/** - * Create an AggregateField object that can be used to compute the average of - * a specified field over a range of documents in the result set of a query. - * @param field Specifies the field to average across the result set. - */ -export declare function average( - field: string | FieldPath -): AggregateField; -/** - * An immutable object representing an array of bytes. - */ -export declare class Bytes { - private constructor(); - /** - * Creates a new `Bytes` object from the given Base64 string, converting it to - * bytes. - * - * @param base64 - The Base64 string used to create the `Bytes` object. - */ - static fromBase64String(base64: string): Bytes; - /** - * Creates a new `Bytes` object from the given Uint8Array. - * - * @param array - The Uint8Array used to create the `Bytes` object. - */ - static fromUint8Array(array: Uint8Array): Bytes; - /** - * Returns the underlying bytes as a Base64-encoded string. - * - * @returns The Base64-encoded string created from the `Bytes` object. - */ - toBase64(): string; - /** - * Returns the underlying bytes in a new `Uint8Array`. - * - * @returns The Uint8Array created from the `Bytes` object. - */ - toUint8Array(): Uint8Array; - /** - * Returns a string representation of the `Bytes` object. - * - * @returns A string representation of the `Bytes` object. - */ - toString(): string; - /** - * Returns true if this `Bytes` object is equal to the provided one. - * - * @param other - The `Bytes` object to compare against. - * @returns true if this `Bytes` object is equal to the provided one. - */ - isEqual(other: Bytes): boolean; -} -/* Excluded from this release type: _ByteString */ -/** - * Constant used to indicate the LRU garbage collection should be disabled. - * Set this value as the `cacheSizeBytes` on the settings passed to the - * {@link Firestore} instance. - */ -export declare const CACHE_SIZE_UNLIMITED = -1; -/** - * Helper for calculating the nested fields for a given type T1. This is needed - * to distribute union types such as `undefined | {...}` (happens for optional - * props) or `{a: A} | {b: B}`. - * - * In this use case, `V` is used to distribute the union types of `T[K]` on - * `Record`, since `T[K]` is evaluated as an expression and not distributed. - * - * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types - */ -export declare type ChildUpdateFields = V extends Record< - string, - unknown -> - ? AddPrefixToKeys> - : never; -/** - * Clears the persistent storage. This includes pending writes and cached - * documents. - * - * Must be called while the {@link Firestore} instance is not started (after the app is - * terminated or when the app is first initialized). On startup, this function - * must be called before other functions (other than {@link - * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} - * instance is still running, the promise will be rejected with the error code - * of `failed-precondition`. - * - * Note: `clearIndexedDbPersistence()` is primarily intended to help write - * reliable tests that use Cloud Firestore. It uses an efficient mechanism for - * dropping existing data but does not attempt to securely overwrite or - * otherwise make cached data unrecoverable. For applications that are sensitive - * to the disclosure of cached data in between user sessions, we strongly - * recommend not enabling persistence at all. - * - * @param firestore - The {@link Firestore} instance to clear persistence for. - * @returns A `Promise` that is resolved when the persistent storage is - * cleared. Otherwise, the promise is rejected with an error. - */ -export declare function clearIndexedDbPersistence( - firestore: Firestore -): Promise; -/** - * Gets a `CollectionReference` instance that refers to the collection at - * the specified absolute path. - * - * @param firestore - A reference to the root `Firestore` instance. - * @param path - A slash-separated path to a collection. - * @param pathSegments - Additional path segments to apply relative to the first - * argument. - * @throws If the final path has an even number of segments and does not point - * to a collection. - * @returns The `CollectionReference` instance. - */ -export declare function collection( - firestore: Firestore, - path: string, - ...pathSegments: string[] -): CollectionReference; -/** - * Gets a `CollectionReference` instance that refers to a subcollection of - * `reference` at the specified relative path. - * - * @param reference - A reference to a collection. - * @param path - A slash-separated path to a collection. - * @param pathSegments - Additional path segments to apply relative to the first - * argument. - * @throws If the final path has an even number of segments and does not point - * to a collection. - * @returns The `CollectionReference` instance. - */ -export declare function collection< - AppModelType, - DbModelType extends DocumentData ->( - reference: CollectionReference, - path: string, - ...pathSegments: string[] -): CollectionReference; -/** - * Gets a `CollectionReference` instance that refers to a subcollection of - * `reference` at the specified relative path. - * - * @param reference - A reference to a Firestore document. - * @param path - A slash-separated path to a collection. - * @param pathSegments - Additional path segments that will be applied relative - * to the first argument. - * @throws If the final path has an even number of segments and does not point - * to a collection. - * @returns The `CollectionReference` instance. - */ -export declare function collection< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference, - path: string, - ...pathSegments: string[] -): CollectionReference; -/** - * Creates and returns a new `Query` instance that includes all documents in the - * database that are contained in a collection or subcollection with the - * given `collectionId`. - * - * @param firestore - A reference to the root `Firestore` instance. - * @param collectionId - Identifies the collections to query over. Every - * collection or subcollection with this ID as the last segment of its path - * will be included. Cannot contain a slash. - * @returns The created `Query`. - */ -export declare function collectionGroup( - firestore: Firestore, - collectionId: string -): Query; -/** - * A `CollectionReference` object can be used for adding documents, getting - * document references, and querying for documents (using {@link (query:1)}). - */ -export declare class CollectionReference< - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> extends Query { - /** The type of this Firestore reference. */ - readonly type = 'collection'; - private constructor(); - /** The collection's identifier. */ - get id(): string; - /** - * A string representing the path of the referenced collection (relative - * to the root of the database). - */ - get path(): string; - /** - * A reference to the containing `DocumentReference` if this is a - * subcollection. If this isn't a subcollection, the reference is null. - */ - get parent(): DocumentReference | null; - /** - * Applies a custom data converter to this `CollectionReference`, allowing you - * to use your own custom model objects with Firestore. When you call {@link - * addDoc} with the returned `CollectionReference` instance, the provided - * converter will convert between Firestore data of type `NewDbModelType` and - * your custom type `NewAppModelType`. - * - * @param converter - Converts objects to and from Firestore. - * @returns A `CollectionReference` that uses the provided converter. - */ - withConverter< - NewAppModelType, - NewDbModelType extends DocumentData = DocumentData - >( - converter: FirestoreDataConverter - ): CollectionReference; - /** - * Removes the current converter. - * - * @param converter - `null` removes the current converter. - * @returns A `CollectionReference` that does not - * use a converter. - */ - withConverter( - converter: null - ): CollectionReference; -} -/** - * Modify this instance to communicate with the Cloud Firestore emulator. - * - * Note: This must be called before this instance has been used to do any - * operations. - * - * @param firestore - The `Firestore` instance to configure to connect to the - * emulator. - * @param host - the emulator host (ex: localhost). - * @param port - the emulator port (ex: 9000). - * @param options.mockUserToken - the mock auth token to use for unit testing - * Security Rules. - */ -export declare function connectFirestoreEmulator( - firestore: Firestore, - host: string, - port: number, - options?: { - mockUserToken?: EmulatorMockTokenOptions | string; - } -): void; -/** - * Create an AggregateField object that can be used to compute the count of - * documents in the result set of a query. - */ -export declare function count(): AggregateField; -/** - * Removes all persistent cache indexes. - * - * Please note this function will also deletes indexes generated by - * `setIndexConfiguration()`, which is deprecated. - */ -export declare function deleteAllPersistentCacheIndexes( - indexManager: PersistentCacheIndexManager -): void; -/** - * Deletes the document referred to by the specified `DocumentReference`. - * - * @param reference - A reference to the document to delete. - * @returns A Promise resolved once the document has been successfully - * deleted from the backend (note that it won't resolve while you're offline). - */ -export declare function deleteDoc< - AppModelType, - DbModelType extends DocumentData ->(reference: DocumentReference): Promise; -/** - * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or - * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. - */ -export declare function deleteField(): FieldValue; -/** - * Disables network usage for this instance. It can be re-enabled via {@link - * enableNetwork}. While the network is disabled, any snapshot listeners, - * `getDoc()` or `getDocs()` calls will return results from cache, and any write - * operations will be queued until the network is restored. - * - * @returns A `Promise` that is resolved once the network has been disabled. - */ -export declare function disableNetwork(firestore: Firestore): Promise; -/** - * Stops creating persistent cache indexes automatically for local query - * execution. The indexes which have been created by calling - * `enablePersistentCacheIndexAutoCreation()` still take effect. - */ -export declare function disablePersistentCacheIndexAutoCreation( - indexManager: PersistentCacheIndexManager -): void; -/** - * Gets a `DocumentReference` instance that refers to the document at the - * specified absolute path. - * - * @param firestore - A reference to the root `Firestore` instance. - * @param path - A slash-separated path to a document. - * @param pathSegments - Additional path segments that will be applied relative - * to the first argument. - * @throws If the final path has an odd number of segments and does not point to - * a document. - * @returns The `DocumentReference` instance. - */ -export declare function doc( - firestore: Firestore, - path: string, - ...pathSegments: string[] -): DocumentReference; -/** - * Gets a `DocumentReference` instance that refers to a document within - * `reference` at the specified relative path. If no path is specified, an - * automatically-generated unique ID will be used for the returned - * `DocumentReference`. - * - * @param reference - A reference to a collection. - * @param path - A slash-separated path to a document. Has to be omitted to use - * auto-generated IDs. - * @param pathSegments - Additional path segments that will be applied relative - * to the first argument. - * @throws If the final path has an odd number of segments and does not point to - * a document. - * @returns The `DocumentReference` instance. - */ -export declare function doc( - reference: CollectionReference, - path?: string, - ...pathSegments: string[] -): DocumentReference; -/** - * Gets a `DocumentReference` instance that refers to a document within - * `reference` at the specified relative path. - * - * @param reference - A reference to a Firestore document. - * @param path - A slash-separated path to a document. - * @param pathSegments - Additional path segments that will be applied relative - * to the first argument. - * @throws If the final path has an odd number of segments and does not point to - * a document. - * @returns The `DocumentReference` instance. - */ -export declare function doc( - reference: DocumentReference, - path: string, - ...pathSegments: string[] -): DocumentReference; -/** - * A `DocumentChange` represents a change to the documents matching a query. - * It contains the document affected and the type of change that occurred. - */ -export declare 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; -} -/** - * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. - */ -export declare type DocumentChangeType = 'added' | 'removed' | 'modified'; -/** - * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to - * values. - */ -export declare interface DocumentData { - /** A mapping between a field and its value. */ - [field: string]: any; -} -/** - * Returns a special sentinel `FieldPath` to refer to the ID of a document. - * It can be used in queries to sort or filter by the document ID. - */ -export declare function documentId(): FieldPath; -/** - * A `DocumentReference` refers to a document location in a Firestore database - * and can be used to write, read, or listen to the location. The document at - * the referenced location may or may not exist. - */ -export declare class DocumentReference< - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> { - /** - * If provided, the `FirestoreDataConverter` associated with this instance. - */ - readonly converter: FirestoreDataConverter | null; - /** The type of this Firestore reference. */ - readonly type = 'document'; - /** - * The {@link Firestore} instance the document is in. - * This is useful for performing transactions, for example. - */ - readonly firestore: Firestore; - private constructor(); - /** - * The document's identifier within its collection. - */ - get id(): string; - /** - * A string representing the path of the referenced document (relative - * to the root of the database). - */ - get path(): string; - /** - * The collection this `DocumentReference` belongs to. - */ - get parent(): CollectionReference; - /** - * Applies a custom data converter to this `DocumentReference`, allowing you - * to use your own custom model objects with Firestore. When you call {@link - * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` - * instance, the provided converter will convert between Firestore data of - * type `NewDbModelType` and your custom type `NewAppModelType`. - * - * @param converter - Converts objects to and from Firestore. - * @returns A `DocumentReference` that uses the provided converter. - */ - withConverter< - NewAppModelType, - NewDbModelType extends DocumentData = DocumentData - >( - converter: FirestoreDataConverter - ): DocumentReference; - /** - * Removes the current converter. - * - * @param converter - `null` removes the current converter. - * @returns A `DocumentReference` that does not - * use a converter. - */ - withConverter(converter: null): DocumentReference; -} -/** - * A `DocumentSnapshot` contains data read from a document in your Firestore - * database. The data can be extracted with `.data()` or `.get()` to - * get a specific field. - * - * For a `DocumentSnapshot` that points to a non-existing document, any data - * access will return 'undefined'. You can use the `exists()` method to - * explicitly verify a document's existence. - */ -export declare class DocumentSnapshot< - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> { - /** - * Metadata about the `DocumentSnapshot`, including information about its - * source and local modifications. - */ - readonly metadata: SnapshotMetadata; - protected constructor(); - /** - * Returns whether or not the data exists. True if the document exists. - */ - exists(): this is QueryDocumentSnapshot; - /** - * Retrieves all fields in the document as an `Object`. Returns `undefined` if - * the document doesn't exist. - * - * By default, `serverTimestamp()` values that have not yet been - * set to their final value will be returned as `null`. You can override - * this by passing an options object. - * - * @param options - An options object to configure how data is retrieved from - * the snapshot (for example the desired behavior for server timestamps that - * have not yet been set to their final value). - * @returns An `Object` containing all fields in the document or `undefined` if - * the document doesn't exist. - */ - data(options?: SnapshotOptions): AppModelType | undefined; - /** - * Retrieves the field specified by `fieldPath`. Returns `undefined` if the - * document or field doesn't exist. - * - * By default, a `serverTimestamp()` that has not yet been set to - * its final value will be returned as `null`. You can override this by - * passing an options object. - * - * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific - * field. - * @param options - An options object to configure how the field is retrieved - * from the snapshot (for example the desired behavior for server timestamps - * that have not yet been set to their final value). - * @returns The data at the specified field location or undefined if no such - * field exists in the document. - */ - get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; - /** - * Property of the `DocumentSnapshot` that provides the document's ID. - */ - get id(): string; - /** - * The `DocumentReference` for the document included in the `DocumentSnapshot`. - */ - get ref(): DocumentReference; -} -/* Excluded from this release type: _EmptyAppCheckTokenProvider */ -/* Excluded from this release type: _EmptyAuthCredentialsProvider */ -export { EmulatorMockTokenOptions }; -/** - * Attempts to enable persistent storage, if possible. - * - * On failure, `enableIndexedDbPersistence()` will reject the promise or - * throw an exception. There are several reasons why this can fail, which can be - * identified by the `code` on the error. - * - * * failed-precondition: The app is already open in another browser tab. - * * unimplemented: The browser is incompatible with the offline persistence - * implementation. - * - * Note that even after a failure, the {@link Firestore} instance will remain - * usable, however offline persistence will be disabled. - * - * Note: `enableIndexedDbPersistence()` must be called before any other functions - * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or - * {@link clearIndexedDbPersistence}. - * - * Persistence cannot be used in a Node.js environment. - * - * @param firestore - The {@link Firestore} instance to enable persistence for. - * @param persistenceSettings - Optional settings object to configure - * persistence. - * @returns A `Promise` that represents successfully enabling persistent storage. - * @deprecated This function will be removed in a future major release. Instead, set - * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to - * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` - * is already specified will throw an exception. - */ -export declare function enableIndexedDbPersistence( - firestore: Firestore, - persistenceSettings?: PersistenceSettings -): Promise; -/** - * Attempts to enable multi-tab persistent storage, if possible. If enabled - * across all tabs, all operations share access to local persistence, including - * shared execution of queries and latency-compensated local document updates - * across all connected instances. - * - * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or - * throw an exception. There are several reasons why this can fail, which can be - * identified by the `code` on the error. - * - * * failed-precondition: The app is already open in another browser tab and - * multi-tab is not enabled. - * * unimplemented: The browser is incompatible with the offline persistence - * implementation. - * - * Note that even after a failure, the {@link Firestore} instance will remain - * usable, however offline persistence will be disabled. - * - * @param firestore - The {@link Firestore} instance to enable persistence for. - * @returns A `Promise` that represents successfully enabling persistent - * storage. - * @deprecated This function will be removed in a future major release. Instead, set - * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to - * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` - * is already specified will throw an exception. - */ -export declare function enableMultiTabIndexedDbPersistence( - firestore: Firestore -): Promise; -/** - * Re-enables use of the network for this {@link Firestore} instance after a prior - * call to {@link disableNetwork}. - * - * @returns A `Promise` that is resolved once the network has been enabled. - */ -export declare function enableNetwork(firestore: Firestore): Promise; -/** - * Enables the SDK to create persistent cache indexes automatically for local - * query execution when the SDK believes cache indexes can help improve - * performance. - * - * This feature is disabled by default. - */ -export declare function enablePersistentCacheIndexAutoCreation( - indexManager: PersistentCacheIndexManager -): void; -/** - * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at - * the provided document (inclusive). The end position is relative to the order - * of the query. The document must contain all of the fields provided in the - * orderBy of the query. - * - * @param snapshot - The snapshot of the document to end at. - * @returns A {@link QueryEndAtConstraint} to pass to `query()` - */ -export declare function endAt( - snapshot: DocumentSnapshot -): QueryEndAtConstraint; -/** - * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at - * the provided fields relative to the order of the query. The order of the field - * values must match the order of the order by clauses of the query. - * - * @param fieldValues - The field values to end this query at, in order - * of the query's order by. - * @returns A {@link QueryEndAtConstraint} to pass to `query()` - */ -export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; -/** - * Creates a {@link QueryEndAtConstraint} that modifies the result set to end - * before the provided document (exclusive). The end position is relative to the - * order of the query. The document must contain all of the fields provided in - * the orderBy of the query. - * - * @param snapshot - The snapshot of the document to end before. - * @returns A {@link QueryEndAtConstraint} to pass to `query()` - */ -export declare function endBefore< - AppModelType, - DbModelType extends DocumentData ->(snapshot: DocumentSnapshot): QueryEndAtConstraint; -/** - * Creates a {@link QueryEndAtConstraint} that modifies the result set to end - * before the provided fields relative to the order of the query. The order of - * the field values must match the order of the order by clauses of the query. - * - * @param fieldValues - The field values to end this query before, in order - * of the query's order by. - * @returns A {@link QueryEndAtConstraint} to pass to `query()` - */ -export declare function endBefore( - ...fieldValues: unknown[] -): QueryEndAtConstraint; -/* Excluded from this release type: executeWrite */ -/** - * @license - * Copyright 2023 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Options that configure the SDK’s underlying network transport (WebChannel) - * when long-polling is used. - * - * Note: This interface is "experimental" and is subject to change. - * - * See `FirestoreSettings.experimentalAutoDetectLongPolling`, - * `FirestoreSettings.experimentalForceLongPolling`, and - * `FirestoreSettings.experimentalLongPollingOptions`. - */ -export declare interface ExperimentalLongPollingOptions { - /** - * The desired maximum timeout interval, in seconds, to complete a - * long-polling GET response. Valid values are between 5 and 30, inclusive. - * Floating point values are allowed and will be rounded to the nearest - * millisecond. - * - * By default, when long-polling is used the "hanging GET" request sent by - * the client times out after 30 seconds. To request a different timeout - * from the server, set this setting with the desired timeout. - * - * Changing the default timeout may be useful, for example, if the buffering - * proxy that necessitated enabling long-polling in the first place has a - * shorter timeout for hanging GET requests, in which case setting the - * long-polling timeout to a shorter value, such as 25 seconds, may fix - * prematurely-closed hanging GET requests. - * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. - */ - timeoutSeconds?: number; -} -/** - * A `FieldPath` refers to a field in a document. The path may consist of a - * single field name (referring to a top-level field in the document), or a - * list of field names (referring to a nested field in the document). - * - * Create a `FieldPath` by providing field names. If more than one field - * name is provided, the path will point to a nested field in a document. - */ -export declare class FieldPath { - /** - * Creates a `FieldPath` from the provided field names. If more than one field - * name is provided, the path will point to a nested field in a document. - * - * @param fieldNames - A list of field names. - */ - constructor(...fieldNames: string[]); - /** - * Returns true if this `FieldPath` is equal to the provided one. - * - * @param other - The `FieldPath` to compare against. - * @returns true if this `FieldPath` is equal to the provided one. - */ - isEqual(other: FieldPath): boolean; -} -/** - * Sentinel values that can be used when writing document fields with `set()` - * or `update()`. - */ -export declare abstract class FieldValue { - private constructor(); - /** Compares `FieldValue`s for equality. */ - abstract isEqual(other: FieldValue): boolean; -} -/* Excluded from this release type: _FirebaseService */ -/** - * The Cloud Firestore service interface. - * - * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. - */ -export declare class Firestore { - /** - * Whether it's a {@link Firestore} or Firestore Lite instance. - */ - type: 'firestore-lite' | 'firestore'; - private constructor(); - /** - * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service - * instance. - */ - get app(): FirebaseApp; - /** - * Returns a JSON-serializable representation of this `Firestore` instance. - */ - toJSON(): object; -} -/** - * Converter used by `withConverter()` to transform user objects of type - * `AppModelType` into Firestore data of type `DbModelType`. - * - * Using the converter allows you to specify generic type arguments when - * storing and retrieving objects from Firestore. - * - * In this context, an "AppModel" is a class that is used in an application to - * package together related information and functionality. Such a class could, - * for example, have properties with complex, nested data types, properties used - * for memoization, properties of types not supported by Firestore (such as - * `symbol` and `bigint`), and helper functions that perform compound - * operations. Such classes are not suitable and/or possible to store into a - * Firestore database. Instead, instances of such classes need to be converted - * to "plain old JavaScript objects" (POJOs) with exclusively primitive - * properties, potentially nested inside other POJOs or arrays of POJOs. In this - * context, this type is referred to as the "DbModel" and would be an object - * suitable for persisting into Firestore. For convenience, applications can - * implement `FirestoreDataConverter` and register the converter with Firestore - * objects, such as `DocumentReference` or `Query`, to automatically convert - * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` - * to `AppModel` when retrieving from Firestore. - * - * @example - * - * Simple Example - * - * ```typescript - * const numberConverter = { - * toFirestore(value: WithFieldValue) { - * return { value }; - * }, - * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { - * return snapshot.data(options).value as number; - * } - * }; - * - * async function simpleDemo(db: Firestore): Promise { - * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); - * - * // converters are used with `setDoc`, `addDoc`, and `getDoc` - * await setDoc(documentRef, 42); - * const snapshot1 = await getDoc(documentRef); - * assertEqual(snapshot1.data(), 42); - * - * // converters are not used when writing data with `updateDoc` - * await updateDoc(documentRef, { value: 999 }); - * const snapshot2 = await getDoc(documentRef); - * assertEqual(snapshot2.data(), 999); - * } - * ``` - * - * Advanced Example - * - * ```typescript - * // The Post class is a model that is used by our application. - * // This class may have properties and methods that are specific - * // to our application execution, which do not need to be persisted - * // to Firestore. - * class Post { - * constructor( - * readonly title: string, - * readonly author: string, - * readonly lastUpdatedMillis: number - * ) {} - * toString(): string { - * return `${this.title} by ${this.author}`; - * } - * } - * - * // The PostDbModel represents how we want our posts to be stored - * // in Firestore. This DbModel has different properties (`ttl`, - * // `aut`, and `lut`) from the Post class we use in our application. - * interface PostDbModel { - * ttl: string; - * aut: { firstName: string; lastName: string }; - * lut: Timestamp; - * } - * - * // The `PostConverter` implements `FirestoreDataConverter` and specifies - * // how the Firestore SDK can convert `Post` objects to `PostDbModel` - * // objects and vice versa. - * class PostConverter implements FirestoreDataConverter { - * toFirestore(post: WithFieldValue): WithFieldValue { - * return { - * ttl: post.title, - * aut: this._autFromAuthor(post.author), - * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) - * }; - * } - * - * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { - * const data = snapshot.data(options) as PostDbModel; - * const author = `${data.aut.firstName} ${data.aut.lastName}`; - * return new Post(data.ttl, author, data.lut.toMillis()); - * } - * - * _autFromAuthor( - * author: string | FieldValue - * ): { firstName: string; lastName: string } | FieldValue { - * if (typeof author !== 'string') { - * // `author` is a FieldValue, so just return it. - * return author; - * } - * const [firstName, lastName] = author.split(' '); - * return {firstName, lastName}; - * } - * - * _lutFromLastUpdatedMillis( - * lastUpdatedMillis: number | FieldValue - * ): Timestamp | FieldValue { - * if (typeof lastUpdatedMillis !== 'number') { - * // `lastUpdatedMillis` must be a FieldValue, so just return it. - * return lastUpdatedMillis; - * } - * return Timestamp.fromMillis(lastUpdatedMillis); - * } - * } - * - * async function advancedDemo(db: Firestore): Promise { - * // Create a `DocumentReference` with a `FirestoreDataConverter`. - * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); - * - * // The `data` argument specified to `setDoc()` is type checked by the - * // TypeScript compiler to be compatible with `Post`. Since the `data` - * // argument is typed as `WithFieldValue` rather than just `Post`, - * // this allows properties of the `data` argument to also be special - * // Firestore values that perform server-side mutations, such as - * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. - * await setDoc(documentRef, { - * title: 'My Life', - * author: 'Foo Bar', - * lastUpdatedMillis: serverTimestamp() - * }); - * - * // The TypeScript compiler will fail to compile if the `data` argument to - * // `setDoc()` is _not_ compatible with `WithFieldValue`. This - * // type checking prevents the caller from specifying objects with incorrect - * // properties or property values. - * // @ts-expect-error "Argument of type { ttl: string; } is not assignable - * // to parameter of type WithFieldValue" - * await setDoc(documentRef, { ttl: 'The Title' }); - * - * // When retrieving a document with `getDoc()` the `DocumentSnapshot` - * // object's `data()` method returns a `Post`, rather than a generic object, - * // which would have been returned if the `DocumentReference` did _not_ have a - * // `FirestoreDataConverter` attached to it. - * const snapshot1: DocumentSnapshot = await getDoc(documentRef); - * const post1: Post = snapshot1.data()!; - * if (post1) { - * assertEqual(post1.title, 'My Life'); - * assertEqual(post1.author, 'Foo Bar'); - * } - * - * // The `data` argument specified to `updateDoc()` is type checked by the - * // TypeScript compiler to be compatible with `PostDbModel`. Note that - * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, - * // the `data` argument to `updateDoc()` must be compatible with - * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed - * // as `WithFieldValue` rather than just `PostDbModel`, this - * // allows properties of the `data` argument to also be those special - * // Firestore values, like `arrayRemove()`, `deleteField()`, and - * // `serverTimestamp()`. - * await updateDoc(documentRef, { - * 'aut.firstName': 'NewFirstName', - * lut: serverTimestamp() - * }); - * - * // The TypeScript compiler will fail to compile if the `data` argument to - * // `updateDoc()` is _not_ compatible with `WithFieldValue`. - * // This type checking prevents the caller from specifying objects with - * // incorrect properties or property values. - * // @ts-expect-error "Argument of type { title: string; } is not assignable - * // to parameter of type WithFieldValue" - * await updateDoc(documentRef, { title: 'New Title' }); - * const snapshot2: DocumentSnapshot = await getDoc(documentRef); - * const post2: Post = snapshot2.data()!; - * if (post2) { - * assertEqual(post2.title, 'My Life'); - * assertEqual(post2.author, 'NewFirstName Bar'); - * } - * } - * ``` - */ -export declare interface FirestoreDataConverter< - 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 - * `PartialWithFieldValue`. - * - * The `WithFieldValue` type extends `T` to also allow FieldValues such as - * {@link (deleteField:1)} to be used as property values. - */ - toFirestore( - modelObject: WithFieldValue - ): WithFieldValue; - /** - * Called by the Firestore SDK to convert a custom model object of type - * `AppModelType` into a plain JavaScript object (suitable for writing - * directly to the Firestore database) of type `DbModelType`. Used with - * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and - * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. - * - * The `PartialWithFieldValue` type extends `Partial` to allow - * FieldValues such as {@link (arrayUnion:1)} to be used as property values. - * It also supports nested `Partial` by allowing nested fields to be - * omitted. - */ - toFirestore( - modelObject: PartialWithFieldValue, - options: SetOptions - ): PartialWithFieldValue; - /** - * Called by the Firestore SDK to convert Firestore data into an object of - * type `AppModelType`. You can access your data by calling: - * `snapshot.data(options)`. - * - * Generally, the data returned from `snapshot.data()` can be cast to - * `DbModelType`; however, this is not guaranteed because Firestore does not - * enforce a schema on the database. For example, writes from a previous - * version of the application or writes from another client that did not use a - * type converter could have written data with different properties and/or - * property types. The implementation will need to choose whether to - * gracefully recover from non-conforming data or throw an error. - * - * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. - * - * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. - * @param options - The `SnapshotOptions` from the initial call to `data()`. - */ - fromFirestore( - snapshot: QueryDocumentSnapshot, - options?: SnapshotOptions - ): AppModelType; -} -/** An error returned by a Firestore operation. */ -export declare class FirestoreError extends FirebaseError { - /** - * The backend error code associated with this error. - */ - readonly code: FirestoreErrorCode; - /** - * A custom error description. - */ - readonly message: string; - /** The stack of the error. */ - readonly stack?: string; - private constructor(); -} -/** - * The set of Firestore status codes. The codes are the same at the ones - * exposed by gRPC here: - * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md - * - * Possible values: - * - 'cancelled': The operation was cancelled (typically by the caller). - * - 'unknown': Unknown error or an error from a different error domain. - * - 'invalid-argument': Client specified an invalid argument. Note that this - * differs from 'failed-precondition'. 'invalid-argument' indicates - * arguments that are problematic regardless of the state of the system - * (e.g. an invalid field name). - * - 'deadline-exceeded': Deadline expired before operation could complete. - * For operations that change the state of the system, this error may be - * returned even if the operation has completed successfully. For example, - * a successful response from a server could have been delayed long enough - * for the deadline to expire. - * - 'not-found': Some requested document was not found. - * - 'already-exists': Some document that we attempted to create already - * exists. - * - 'permission-denied': The caller does not have permission to execute the - * specified operation. - * - 'resource-exhausted': Some resource has been exhausted, perhaps a - * per-user quota, or perhaps the entire file system is out of space. - * - 'failed-precondition': Operation was rejected because the system is not - * in a state required for the operation's execution. - * - 'aborted': The operation was aborted, typically due to a concurrency - * issue like transaction aborts, etc. - * - 'out-of-range': Operation was attempted past the valid range. - * - 'unimplemented': Operation is not implemented or not supported/enabled. - * - 'internal': Internal errors. Means some invariants expected by - * underlying system has been broken. If you see one of these errors, - * something is very broken. - * - 'unavailable': The service is currently unavailable. This is most likely - * a transient condition and may be corrected by retrying with a backoff. - * - 'data-loss': Unrecoverable data loss or corruption. - * - 'unauthenticated': The request does not have valid authentication - * credentials for the operation. - */ -export declare type FirestoreErrorCode = - | 'cancelled' - | 'unknown' - | 'invalid-argument' - | 'deadline-exceeded' - | 'not-found' - | 'already-exists' - | 'permission-denied' - | 'resource-exhausted' - | 'failed-precondition' - | 'aborted' - | 'out-of-range' - | 'unimplemented' - | 'internal' - | 'unavailable' - | 'data-loss' - | 'unauthenticated'; -/** - * Union type from all supported SDK cache layer. - */ -export declare type FirestoreLocalCache = - | MemoryLocalCache - | PersistentLocalCache; -/** - * Specifies custom configurations for your Cloud Firestore instance. - * You must set these before invoking any other methods. - */ -export declare interface FirestoreSettings { - /** - * NOTE: This field will be deprecated in a future major release. Use `cache` field - * instead to specify cache size, and other cache configurations. - * - * An approximate cache size threshold for the on-disk data. If the cache - * grows beyond this size, Firestore will start removing data that hasn't been - * recently used. The size is not a guarantee that the cache will stay below - * that size, only that if the cache exceeds the given size, cleanup will be - * attempted. - * - * The default value is 40 MB. The threshold must be set to at least 1 MB, and - * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. - */ - cacheSizeBytes?: number; - /** - * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` - * and `PersistentLocalCache`, each with different configuration options. - * - * When unspecified, `MemoryLocalCache` will be used by default. - * - * NOTE: setting this field and `cacheSizeBytes` at the same time will throw - * exception during SDK initialization. Instead, using the configuration in - * the `FirestoreLocalCache` object to specify the cache size. - */ - localCache?: FirestoreLocalCache; - /** - * Forces the SDK’s underlying network transport (WebChannel) to use - * long-polling. Each response from the backend will be closed immediately - * after the backend sends data (by default responses are kept open in - * case the backend has more data to send). This avoids incompatibility - * issues with certain proxies, antivirus software, etc. that incorrectly - * buffer traffic indefinitely. Use of this option will cause some - * performance degradation though. - * - * This setting cannot be used with `experimentalAutoDetectLongPolling` and - * may be removed in a future release. If you find yourself using it to - * work around a specific network reliability issue, please tell us about - * it in https://github.com/firebase/firebase-js-sdk/issues/1674. - * - * This setting cannot be used in a Node.js environment. - */ - experimentalForceLongPolling?: boolean; - /** - * Configures the SDK's underlying transport (WebChannel) to automatically - * detect if long-polling should be used. This is very similar to - * `experimentalForceLongPolling`, but only uses long-polling if required. - * - * After having had a default value of `false` since its inception in 2019, - * the default value of this setting was changed in May 2023 to `true` in - * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long - * polling is now enabled by default. To disable it, set this setting to - * `false`, and please open a GitHub issue to share the problems that - * motivated you disabling long-polling auto-detection. - * - * This setting cannot be used in a Node.js environment. - */ - experimentalAutoDetectLongPolling?: boolean; - /** - * Options that configure the SDK’s underlying network transport (WebChannel) - * when long-polling is used. - * - * These options are only used if `experimentalForceLongPolling` is true or if - * `experimentalAutoDetectLongPolling` is true and the auto-detection - * determined that long-polling was needed. Otherwise, these options have no - * effect. - */ - experimentalLongPollingOptions?: ExperimentalLongPollingOptions; - /** - * The hostname to connect to. - */ - host?: string; - /** - * Whether to use SSL when connecting. - */ - ssl?: boolean; - /** - * Whether to skip nested properties that are set to `undefined` during - * object serialization. If set to `true`, these properties are skipped - * and not written to Firestore. If set to `false` or omitted, the SDK - * throws an exception when it encounters properties of type `undefined`. - */ - ignoreUndefinedProperties?: boolean; -} -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An immutable object representing a geographic location in Firestore. The - * location is represented as latitude/longitude pair. - * - * Latitude values are in the range of [-90, 90]. - * Longitude values are in the range of [-180, 180]. - */ -export declare class GeoPoint { - /** - * Creates a new immutable `GeoPoint` object with the provided latitude and - * longitude values. - * @param latitude - The latitude as number between -90 and 90. - * @param longitude - The longitude as number between -180 and 180. - */ - constructor(latitude: number, longitude: number); - /** - * The latitude of this `GeoPoint` instance. - */ - get latitude(): number; - /** - * The longitude of this `GeoPoint` instance. - */ - get longitude(): number; - /** - * Returns true if this `GeoPoint` is equal to the provided one. - * - * @param other - The `GeoPoint` to compare against. - * @returns true if this `GeoPoint` is equal to the provided one. - */ - isEqual(other: GeoPoint): boolean; - /** Returns a JSON-serializable representation of this GeoPoint. */ - toJSON(): { - latitude: number; - longitude: number; - }; -} -/** - * Calculates the specified aggregations over the documents in the result - * set of the given query without actually downloading the documents. - * - * Using this function to perform aggregations is efficient because only the - * final aggregation values, not the documents' data, are downloaded. This - * function can perform aggregations of the documents in cases where the result - * set is prohibitively large to download entirely (thousands of documents). - * - * The result received from the server is presented, unaltered, without - * considering any local state. That is, documents in the local cache are not - * taken into consideration, neither are local modifications not yet - * synchronized with the server. Previously-downloaded results, if any, are not - * used. Every invocation of this function necessarily involves a round trip to - * the server. - * - * @param query The query whose result set is aggregated over. - * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates - * to perform over the result set. The AggregateSpec specifies aliases for each - * aggregate, which can be used to retrieve the aggregate result. - * @example - * ```typescript - * const aggregateSnapshot = await getAggregateFromServer(query, { - * countOfDocs: count(), - * totalHours: sum('hours'), - * averageScore: average('score') - * }); - * - * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; - * const totalHours: number = aggregateSnapshot.data().totalHours; - * const averageScore: number | null = aggregateSnapshot.data().averageScore; - * ``` - */ -export declare function getAggregateFromServer< - AggregateSpecType extends AggregateSpec, - AppModelType, - DbModelType extends DocumentData ->( - query: Query, - aggregateSpec: AggregateSpecType -): Promise< - AggregateQuerySnapshot ->; -/** - * Calculates the number of documents in the result set of the given query - * without actually downloading the documents. - * - * Using this function to count the documents is efficient because only the - * final count, not the documents' data, is downloaded. This function can - * count the documents in cases where the result set is prohibitively large to - * download entirely (thousands of documents). - * - * The result received from the server is presented, unaltered, without - * considering any local state. That is, documents in the local cache are not - * taken into consideration, neither are local modifications not yet - * synchronized with the server. Previously-downloaded results, if any, are not - * used. Every invocation of this function necessarily involves a round trip to - * the server. - * - * @param query The query whose result set size is calculated. - * @returns A Promise that will be resolved with the count; the count can be - * retrieved from `snapshot.data().count`, where `snapshot` is the - * `AggregateQuerySnapshot` to which the returned Promise resolves. - */ -export declare function getCountFromServer< - AppModelType, - DbModelType extends DocumentData ->( - query: Query -): Promise< - AggregateQuerySnapshot< - { - count: AggregateField; - }, - AppModelType, - DbModelType - > ->; -/** - * Reads the document referred to by this `DocumentReference`. - * - * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting - * for data from the server, but it may return cached data or fail if you are - * offline and the server cannot be reached. To specify this behavior, invoke - * {@link getDocFromCache} or {@link getDocFromServer}. - * - * @param reference - The reference of the document to fetch. - * @returns A Promise resolved with a `DocumentSnapshot` containing the - * current document contents. - */ -export declare function getDoc( - reference: DocumentReference -): Promise>; -/** - * Reads the document referred to by this `DocumentReference` from cache. - * Returns an error if the document is not currently cached. - * - * @returns A `Promise` resolved with a `DocumentSnapshot` containing the - * current document contents. - */ -export declare function getDocFromCache< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference -): Promise>; -/** - * Reads the document referred to by this `DocumentReference` from the server. - * Returns an error if the network is not available. - * - * @returns A `Promise` resolved with a `DocumentSnapshot` containing the - * current document contents. - */ -export declare function getDocFromServer< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference -): Promise>; -/** - * Executes the query and returns the results as a `QuerySnapshot`. - * - * Note: `getDocs()` attempts to provide up-to-date data when possible by - * waiting for data from the server, but it may return cached data or fail if - * you are offline and the server cannot be reached. To specify this behavior, - * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. - * - * @returns A `Promise` that will be resolved with the results of the query. - */ -export declare function getDocs( - query: Query -): Promise>; -/** - * Executes the query and returns the results as a `QuerySnapshot` from cache. - * Returns an empty result set if no documents matching the query are currently - * cached. - * - * @returns A `Promise` that will be resolved with the results of the query. - */ -export declare function getDocsFromCache< - AppModelType, - DbModelType extends DocumentData ->( - query: Query -): Promise>; -/** - * Executes the query and returns the results as a `QuerySnapshot` from the - * server. Returns an error if the network is not available. - * - * @returns A `Promise` that will be resolved with the results of the query. - */ -export declare function getDocsFromServer< - AppModelType, - DbModelType extends DocumentData ->( - query: Query -): Promise>; -/** - * Returns the existing default {@link Firestore} instance that is associated with the - * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new - * instance with default settings. - * - * @returns The default {@link Firestore} instance of the default app. - */ -export declare function getFirestore(): Firestore; -/** - * Returns the existing default {@link Firestore} instance that is associated with the - * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new - * instance with default settings. - * - * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} - * instance is associated with. - * @returns The default {@link Firestore} instance of the provided app. - */ -export declare function getFirestore(app: FirebaseApp): Firestore; -/** - * Returns the existing named {@link Firestore} instance that is associated with the - * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new - * instance with default settings. - * - * @param databaseId - The name of the database. - * @returns The named {@link Firestore} instance of the default app. - * @beta - */ -export declare function getFirestore(databaseId: string): Firestore; -/** - * Returns the existing named {@link Firestore} instance that is associated with the - * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new - * instance with default settings. - * - * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} - * instance is associated with. - * @param databaseId - The name of the database. - * @returns The named {@link Firestore} instance of the provided app. - * @beta - */ -export declare function getFirestore( - app: FirebaseApp, - databaseId: string -): Firestore; -/** - * Returns the PersistentCache Index Manager used by the given `Firestore` - * object. - * - * @return The `PersistentCacheIndexManager` instance, or `null` if local - * persistent storage is not in use. - */ -export declare function getPersistentCacheIndexManager( - firestore: Firestore -): PersistentCacheIndexManager | null; -/** - * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link - * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by - * the given value. - * - * If either the operand or the current field value uses floating point - * precision, all arithmetic follows IEEE 754 semantics. If both values are - * integers, values outside of JavaScript's safe number range - * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to - * precision loss. Furthermore, once processed by the Firestore backend, all - * integer operations are capped between -2^63 and 2^63-1. - * - * If the current field value is not of type `number`, or if the field does not - * yet exist, the transformation sets the field to the given value. - * - * @param n - The value to increment by. - * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or - * `updateDoc()` - */ -export declare function increment(n: number): FieldValue; -/** - * The SDK definition of a Firestore index. - * - * @deprecated Instead of creating cache indexes manually, consider using - * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to - * create cache indexes for queries running locally. - * - * @beta - */ -export declare interface Index { - /** The ID of the collection to index. */ - readonly collectionGroup: string; - /** A list of fields to index. */ - readonly fields?: IndexField[]; - [key: string]: unknown; -} -/** - * A list of Firestore indexes to speed up local query execution. - * - * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} - * for a description of the format of the index definition. - * - * @deprecated Instead of creating cache indexes manually, consider using - * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to - * create cache indexes for queries running locally. - * - * @beta - */ -export declare interface IndexConfiguration { - /** A list of all Firestore indexes. */ - readonly indexes?: Index[]; - [key: string]: unknown; -} -/** - * A single field element in an index configuration. - * - * @deprecated Instead of creating cache indexes manually, consider using - * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to - * create cache indexes for queries running locally. - * - * @beta - */ -export declare interface IndexField { - /** The field path to index. */ - readonly fieldPath: string; - /** - * What type of array index to create. Set to `CONTAINS` for `array-contains` - * and `array-contains-any` indexes. - * - * Only one of `arrayConfig` or `order` should be set; - */ - readonly arrayConfig?: 'CONTAINS'; - /** - * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for - * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. - * - * Only one of `arrayConfig` or `order` should be set. - */ - readonly order?: 'ASCENDING' | 'DESCENDING'; - [key: string]: unknown; -} -/** - * Initializes a new instance of {@link Firestore} with the provided settings. - * Can only be called before any other function, including - * {@link (getFirestore:1)}. If the custom settings are empty, this function is - * equivalent to calling {@link (getFirestore:1)}. - * - * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will - * be associated. - * @param settings - A settings object to configure the {@link Firestore} instance. - * @param databaseId - The name of the database. - * @returns A newly initialized {@link Firestore} instance. - */ -export declare function initializeFirestore( - app: FirebaseApp, - settings: FirestoreSettings, - databaseId?: string -): Firestore; -/** - * Creates a {@link QueryLimitConstraint} that only returns the first matching - * documents. - * - * @param limit - The maximum number of items to return. - * @returns The created {@link QueryLimitConstraint}. - */ -export declare function limit(limit: number): QueryLimitConstraint; -/** - * Creates a {@link QueryLimitConstraint} that only returns the last matching - * documents. - * - * You must specify at least one `orderBy` clause for `limitToLast` queries, - * otherwise an exception will be thrown during execution. - * - * @param limit - The maximum number of items to return. - * @returns The created {@link QueryLimitConstraint}. - */ -export declare function limitToLast(limit: number): QueryLimitConstraint; -/** - * Describe the source a query listens to. - * - * Set to `default` to listen to both cache and server changes. Set to `cache` - * to listen to changes in cache only. - */ -export declare type ListenSource = 'default' | 'cache'; -/** - * Loads a Firestore bundle into the local cache. - * - * @param firestore - The {@link Firestore} instance to load bundles for. - * @param bundleData - An object representing the bundle to be loaded. Valid - * objects are `ArrayBuffer`, `ReadableStream` or `string`. - * - * @returns A `LoadBundleTask` object, which notifies callers with progress - * updates, and completion or error events. It can be used as a - * `Promise`. - */ -export declare function loadBundle( - firestore: Firestore, - bundleData: ReadableStream | ArrayBuffer | string -): LoadBundleTask; -/** - * Represents the task of loading a Firestore bundle. It provides progress of bundle - * loading, as well as task completion and error events. - * - * The API is compatible with `Promise`. - */ -export declare class LoadBundleTask - implements PromiseLike -{ - /** - * Registers functions to listen to bundle loading progress events. - * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur - * each time a Firestore document is loaded from the bundle. - * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the - * error, and there should be no more updates after this. - * @param complete - Called when the loading task is complete. - */ - onProgress( - next?: (progress: LoadBundleTaskProgress) => unknown, - error?: (err: Error) => unknown, - complete?: () => void - ): void; - /** - * Implements the `Promise.catch` interface. - * - * @param onRejected - Called when an error occurs during bundle loading. - */ - catch( - onRejected: (a: Error) => R | PromiseLike - ): Promise; - /** - * Implements the `Promise.then` interface. - * - * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. - * The update will always have its `taskState` set to `"Success"`. - * @param onRejected - Called when an error occurs during bundle loading. - */ - then( - onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike, - onRejected?: (a: Error) => R | PromiseLike - ): Promise; -} -/** - * Represents a progress update or a final state from loading bundles. - */ -export declare interface LoadBundleTaskProgress { - /** How many documents have been loaded. */ - documentsLoaded: number; - /** How many documents are in the bundle being loaded. */ - totalDocuments: number; - /** How many bytes have been loaded. */ - bytesLoaded: number; - /** How many bytes are in the bundle being loaded. */ - totalBytes: number; - /** Current task state. */ - taskState: TaskState; -} -export { LogLevel }; -/** - * An settings object to configure an `MemoryLocalCache` instance. - */ -export declare type MemoryCacheSettings = { - /** - * The garbage collector to use, for the memory cache layer. - * A `MemoryEagerGarbageCollector` is used when this is undefined. - */ - garbageCollector?: MemoryGarbageCollector; -}; -/** - * A garbage collector deletes documents whenever they are not part of any - * active queries, and have no local mutations attached to them. - * - * This collector tries to ensure lowest memory footprints from the SDK, - * at the risk of documents not being cached for offline queries or for - * direct queries to the cache. - * - * Use factory function {@link memoryEagerGarbageCollector()} to create an - * instance of this collector. - */ -export declare type MemoryEagerGarbageCollector = { - kind: 'memoryEager'; -}; -/** - * Creates an instance of `MemoryEagerGarbageCollector`. This is also the - * default garbage collector unless it is explicitly specified otherwise. - */ -export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector; -/** - * Union type from all support garbage collectors for memory local cache. - */ -export declare type MemoryGarbageCollector = - | MemoryEagerGarbageCollector - | MemoryLruGarbageCollector; -/** - * Provides an in-memory cache to the SDK. This is the default cache unless explicitly - * configured otherwise. - * - * To use, create an instance using the factory function {@link memoryLocalCache()}, then - * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using - * the settings object. - */ -export declare type MemoryLocalCache = { - kind: 'memory'; -}; -/** - * Creates an instance of `MemoryLocalCache`. The instance can be set to - * `FirestoreSettings.cache` to tell the SDK which cache layer to use. - */ -export declare function memoryLocalCache( - settings?: MemoryCacheSettings -): MemoryLocalCache; -/** - * A garbage collector deletes Least-Recently-Used documents in multiple - * batches. - * - * This collector is configured with a target size, and will only perform - * collection when the cached documents exceed the target size. It avoids - * querying backend repeated for the same query or document, at the risk - * of having a larger memory footprint. - * - * Use factory function {@link memoryLruGarbageCollector()} to create a - * instance of this collector. - */ -export declare type MemoryLruGarbageCollector = { - kind: 'memoryLru'; -}; -/** - * Creates an instance of `MemoryLruGarbageCollector`. - * - * A target size can be specified as part of the setting parameter. The - * collector will start deleting documents once the cache size exceeds - * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). - */ -export declare function memoryLruGarbageCollector(settings?: { - cacheSizeBytes?: number; -}): MemoryLruGarbageCollector; -/** - * Reads a Firestore {@link Query} from local cache, identified by the given - * name. - * - * The named queries are packaged into bundles on the server side (along - * with resulting documents), and loaded to local cache using `loadBundle`. Once - * in local cache, use this method to extract a {@link Query} by name. - * - * @param firestore - The {@link Firestore} instance to read the query from. - * @param name - The name of the query. - * @returns A `Promise` that is resolved with the Query or `null`. - */ -export declare function namedQuery( - firestore: Firestore, - name: string -): Promise; -/** - * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, - * 'bar.qux': T2}). Intersect them together to make a single map containing - * all possible keys that are all marked as optional - */ -export declare type NestedUpdateFields> = - UnionToIntersection< - { - [K in keyof T & string]: ChildUpdateFields; - }[keyof T & string] - >; -/** - * Attaches a listener for `DocumentSnapshot` events. You may either pass - * individual `onNext` and `onError` callbacks or pass a single observer - * object with `next` and `error` callbacks. - * - * NOTE: Although an `onCompletion` callback can be provided, it will - * never be called because the snapshot stream is never-ending. - * - * @param reference - A reference to the document to listen to. - * @param observer - A single object containing `next` and `error` callbacks. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshot< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference, - observer: { - next?: (snapshot: DocumentSnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - } -): Unsubscribe; -/** - * Attaches a listener for `DocumentSnapshot` events. You may either pass - * individual `onNext` and `onError` callbacks or pass a single observer - * object with `next` and `error` callbacks. - * - * NOTE: Although an `onCompletion` callback can be provided, it will - * never be called because the snapshot stream is never-ending. - * - * @param reference - A reference to the document to listen to. - * @param options - Options controlling the listen behavior. - * @param observer - A single object containing `next` and `error` callbacks. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshot< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference, - options: SnapshotListenOptions, - observer: { - next?: (snapshot: DocumentSnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - } -): Unsubscribe; -/** - * Attaches a listener for `DocumentSnapshot` events. You may either pass - * individual `onNext` and `onError` callbacks or pass a single observer - * object with `next` and `error` callbacks. - * - * NOTE: Although an `onCompletion` callback can be provided, it will - * never be called because the snapshot stream is never-ending. - * - * @param reference - A reference to the document to listen to. - * @param onNext - A callback to be called every time a new `DocumentSnapshot` - * is available. - * @param onError - A callback to be called if the listen fails or is - * cancelled. No further callbacks will occur. - * @param onCompletion - Can be provided, but will not be called since streams are - * never ending. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshot< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference, - onNext: (snapshot: DocumentSnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void -): Unsubscribe; -/** - * Attaches a listener for `DocumentSnapshot` events. You may either pass - * individual `onNext` and `onError` callbacks or pass a single observer - * object with `next` and `error` callbacks. - * - * NOTE: Although an `onCompletion` callback can be provided, it will - * never be called because the snapshot stream is never-ending. - * - * @param reference - A reference to the document to listen to. - * @param options - Options controlling the listen behavior. - * @param onNext - A callback to be called every time a new `DocumentSnapshot` - * is available. - * @param onError - A callback to be called if the listen fails or is - * cancelled. No further callbacks will occur. - * @param onCompletion - Can be provided, but will not be called since streams are - * never ending. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshot< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference, - options: SnapshotListenOptions, - onNext: (snapshot: DocumentSnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events. You may either pass - * individual `onNext` and `onError` callbacks or pass a single observer - * object with `next` and `error` callbacks. The listener can be cancelled by - * calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will - * never be called because the snapshot stream is never-ending. - * - * @param query - The query to listen to. - * @param observer - A single object containing `next` and `error` callbacks. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshot< - AppModelType, - DbModelType extends DocumentData ->( - query: Query, - observer: { - next?: (snapshot: QuerySnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - } -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events. You may either pass - * individual `onNext` and `onError` callbacks or pass a single observer - * object with `next` and `error` callbacks. The listener can be cancelled by - * calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will - * never be called because the snapshot stream is never-ending. - * - * @param query - The query to listen to. - * @param options - Options controlling the listen behavior. - * @param observer - A single object containing `next` and `error` callbacks. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshot< - AppModelType, - DbModelType extends DocumentData ->( - query: Query, - options: SnapshotListenOptions, - observer: { - next?: (snapshot: QuerySnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - } -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events. You may either pass - * individual `onNext` and `onError` callbacks or pass a single observer - * object with `next` and `error` callbacks. The listener can be cancelled by - * calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will - * never be called because the snapshot stream is never-ending. - * - * @param query - The query to listen to. - * @param onNext - A callback to be called every time a new `QuerySnapshot` - * is available. - * @param onCompletion - Can be provided, but will not be called since streams are - * never ending. - * @param onError - A callback to be called if the listen fails or is - * cancelled. No further callbacks will occur. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshot< - AppModelType, - DbModelType extends DocumentData ->( - query: Query, - onNext: (snapshot: QuerySnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events. You may either pass - * individual `onNext` and `onError` callbacks or pass a single observer - * object with `next` and `error` callbacks. The listener can be cancelled by - * calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will - * never be called because the snapshot stream is never-ending. - * - * @param query - The query to listen to. - * @param options - Options controlling the listen behavior. - * @param onNext - A callback to be called every time a new `QuerySnapshot` - * is available. - * @param onCompletion - Can be provided, but will not be called since streams are - * never ending. - * @param onError - A callback to be called if the listen fails or is - * cancelled. No further callbacks will occur. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshot< - AppModelType, - DbModelType extends DocumentData ->( - query: Query, - options: SnapshotListenOptions, - onNext: (snapshot: QuerySnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void -): Unsubscribe; -/** - * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync - * event indicates that all listeners affected by a given change have fired, - * even if a single server-generated change affects multiple listeners. - * - * NOTE: The snapshots-in-sync event only indicates that listeners are in sync - * with each other, but does not relate to whether those snapshots are in sync - * with the server. Use SnapshotMetadata in the individual listeners to - * determine if a snapshot is from the cache or the server. - * - * @param firestore - The instance of Firestore for synchronizing snapshots. - * @param observer - A single object containing `next` and `error` callbacks. - * @returns An unsubscribe function that can be called to cancel the snapshot - * listener. - */ -export declare function onSnapshotsInSync( - firestore: Firestore, - observer: { - next?: (value: void) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - } -): Unsubscribe; -/** - * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync - * event indicates that all listeners affected by a given change have fired, - * even if a single server-generated change affects multiple listeners. - * - * NOTE: The snapshots-in-sync event only indicates that listeners are in sync - * with each other, but does not relate to whether those snapshots are in sync - * with the server. Use `SnapshotMetadata` in the individual listeners to - * determine if a snapshot is from the cache or the server. - * - * @param firestore - The `Firestore` instance for synchronizing snapshots. - * @param onSync - A callback to be called every time all snapshot listeners are - * in sync with each other. - * @returns An unsubscribe function that can be called to cancel the snapshot - * listener. - */ -export declare function onSnapshotsInSync( - firestore: Firestore, - onSync: () => void -): Unsubscribe; -/** - * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of - * the given filter constraints. A disjunction filter includes a document if it - * satisfies any of the given filters. - * - * @param queryConstraints - Optional. The list of - * {@link QueryFilterConstraint}s to perform a disjunction for. These must be - * created with calls to {@link where}, {@link or}, or {@link and}. - * @returns The newly created {@link QueryCompositeFilterConstraint}. - */ -export declare function or( - ...queryConstraints: QueryFilterConstraint[] -): QueryCompositeFilterConstraint; -/** - * Creates a {@link QueryOrderByConstraint} that sorts the query result by the - * specified field, optionally in descending order instead of ascending. - * - * Note: Documents that do not contain the specified field will not be present - * in the query result. - * - * @param fieldPath - The field to sort by. - * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If - * not specified, order will be ascending. - * @returns The created {@link QueryOrderByConstraint}. - */ -export declare function orderBy( - fieldPath: string | FieldPath, - directionStr?: OrderByDirection -): QueryOrderByConstraint; -/** - * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' - * (descending or ascending). - */ -export declare type OrderByDirection = 'desc' | 'asc'; -/** - * Similar to TypeScript's `Partial`, but allows nested fields to be - * omitted and FieldValues to be passed in as property values. - */ -export declare type PartialWithFieldValue = - | Partial - | (T extends Primitive - ? T - : T extends {} - ? { - [K in keyof T]?: PartialWithFieldValue | FieldValue; - } - : never); -/** - * Settings that can be passed to `enableIndexedDbPersistence()` to configure - * Firestore persistence. - * - * Persistence cannot be used in a Node.js environment. - */ -export declare interface PersistenceSettings { - /** - * Whether to force enable persistence for the client. This cannot be used - * with multi-tab synchronization and is primarily intended for use with Web - * Workers. Setting this to `true` will enable persistence, but cause other - * tabs using persistence to fail. - */ - forceOwnership?: boolean; -} -/** - * A `PersistentCacheIndexManager` for configuring persistent cache indexes used - * for local query execution. - * - * To use, call `getPersistentCacheIndexManager()` to get an instance. - */ -export declare class PersistentCacheIndexManager { - /** A type string to uniquely identify instances of this class. */ - readonly type: 'PersistentCacheIndexManager'; - private constructor(); -} -/** - * An settings object to configure an `PersistentLocalCache` instance. - * - * Persistent cache cannot be used in a Node.js environment. - */ -export declare type PersistentCacheSettings = { - /** - * An approximate cache size threshold for the on-disk data. If the cache - * grows beyond this size, Firestore will start removing data that hasn't been - * recently used. The SDK does not guarantee that the cache will stay below - * that size, only that if the cache exceeds the given size, cleanup will be - * attempted. - * - * The default value is 40 MB. The threshold must be set to at least 1 MB, and - * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. - */ - cacheSizeBytes?: number; - /** - * Specifies how multiple tabs/windows will be managed by the SDK. - */ - tabManager?: PersistentTabManager; -}; -/** - * Provides a persistent cache backed by IndexedDb to the SDK. - * - * To use, create an instance using the factory function {@link persistentLocalCache()}, then - * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using - * the settings object. - */ -export declare type PersistentLocalCache = { - kind: 'persistent'; -}; -/** - * Creates an instance of `PersistentLocalCache`. The instance can be set to - * `FirestoreSettings.cache` to tell the SDK which cache layer to use. - * - * Persistent cache cannot be used in a Node.js environment. - */ -export declare function persistentLocalCache( - settings?: PersistentCacheSettings -): PersistentLocalCache; -/** - * A tab manager supporting multiple tabs. SDK will synchronize queries and - * mutations done across all tabs using the SDK. - */ -export declare type PersistentMultipleTabManager = { - kind: 'PersistentMultipleTab'; -}; -/** - * Creates an instance of `PersistentMultipleTabManager`. - */ -export declare function persistentMultipleTabManager(): PersistentMultipleTabManager; -/** - * A tab manager supporting only one tab, no synchronization will be - * performed across tabs. - */ -export declare type PersistentSingleTabManager = { - kind: 'persistentSingleTab'; -}; -/** - * Creates an instance of `PersistentSingleTabManager`. - * - * @param settings Configures the created tab manager. - */ -export declare function persistentSingleTabManager( - settings: PersistentSingleTabManagerSettings | undefined -): PersistentSingleTabManager; -/** - * Type to configure an `PersistentSingleTabManager` instance. - */ -export declare type PersistentSingleTabManagerSettings = { - /** - * Whether to force-enable persistent (IndexedDB) cache for the client. This - * cannot be used with multi-tab synchronization and is primarily intended for - * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause - * other tabs using IndexedDB cache to fail. - */ - forceOwnership?: boolean; -}; -/** - * A union of all available tab managers. - */ -export declare type PersistentTabManager = - | PersistentSingleTabManager - | PersistentMultipleTabManager; -/** - * These types primarily exist to support the `UpdateData`, - * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed - * directly by the end developer. - */ -/** Primitive types. */ -export declare type Primitive = string | number | boolean | undefined | null; -/** - * A `Query` refers to a query which you can read or listen to. You can also - * construct refined `Query` objects by adding filters and ordering. - */ -export declare class Query< - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> { - /** - * If provided, the `FirestoreDataConverter` associated with this instance. - */ - readonly converter: FirestoreDataConverter | null; - /** The type of this Firestore reference. */ - readonly type: 'query' | 'collection'; - /** - * The `Firestore` instance for the Firestore database (useful for performing - * transactions, etc.). - */ - readonly firestore: Firestore; - protected constructor(); - /** - * Removes the current converter. - * - * @param converter - `null` removes the current converter. - * @returns A `Query` that does not use a - * converter. - */ - withConverter(converter: null): Query; - /** - * Applies a custom data converter to this query, allowing you to use your own - * custom model objects with Firestore. When you call {@link getDocs} with - * the returned query, the provided converter will convert between Firestore - * data of type `NewDbModelType` and your custom type `NewAppModelType`. - * - * @param converter - Converts objects to and from Firestore. - * @returns A `Query` that uses the provided converter. - */ - withConverter< - NewAppModelType, - NewDbModelType extends DocumentData = DocumentData - >( - converter: FirestoreDataConverter - ): Query; -} -/** - * Creates a new immutable instance of {@link Query} that is extended to also - * include additional query constraints. - * - * @param query - The {@link Query} instance to use as a base for the new - * constraints. - * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to - * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or - * {@link or}. - * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to - * apply (e.g. {@link orderBy}, {@link limit}). - * @throws if any of the provided query constraints cannot be combined with the - * existing or new constraints. - */ -export declare function query( - query: Query, - compositeFilter: QueryCompositeFilterConstraint, - ...queryConstraints: QueryNonFilterConstraint[] -): Query; -/** - * Creates a new immutable instance of {@link Query} that is extended to also - * include additional query constraints. - * - * @param query - The {@link Query} instance to use as a base for the new - * constraints. - * @param queryConstraints - The list of {@link QueryConstraint}s to apply. - * @throws if any of the provided query constraints cannot be combined with the - * existing or new constraints. - */ -export declare function query( - query: Query, - ...queryConstraints: QueryConstraint[] -): Query; -/** - * A `QueryCompositeFilterConstraint` is used to narrow the set of documents - * returned by a Firestore query by performing the logical OR or AND of multiple - * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. - * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or - * {@link and} and can then be passed to {@link (query:1)} to create a new query - * instance that also contains the `QueryCompositeFilterConstraint`. - */ -export declare class QueryCompositeFilterConstraint { - /** The type of this query constraint */ - readonly type: 'or' | 'and'; -} -/** - * A `QueryConstraint` is used to narrow the set of documents returned by a - * Firestore query. `QueryConstraint`s are created by invoking {@link where}, - * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link - * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and - * can then be passed to {@link (query:1)} to create a new query instance that - * also contains this `QueryConstraint`. - */ -export declare abstract class QueryConstraint { - /** The type of this query constraint */ - abstract readonly type: QueryConstraintType; -} -/** Describes the different query constraints available in this SDK. */ -export declare type QueryConstraintType = - | 'where' - | 'orderBy' - | 'limit' - | 'limitToLast' - | 'startAt' - | 'startAfter' - | 'endAt' - | 'endBefore'; -/** - * A `QueryDocumentSnapshot` contains data read from a document in your - * Firestore database as part of a query. The document is guaranteed to exist - * and its data can be extracted with `.data()` or `.get()` to get a - * specific field. - * - * A `QueryDocumentSnapshot` offers the same API surface as a - * `DocumentSnapshot`. Since query results contain only existing documents, the - * `exists` property will always be true and `data()` will never return - * 'undefined'. - */ -export declare class QueryDocumentSnapshot< - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> extends DocumentSnapshot { - /** - * Retrieves all fields in the document as an `Object`. - * - * By default, `serverTimestamp()` values that have not yet been - * set to their final value will be returned as `null`. You can override - * this by passing an options object. - * - * @override - * @param options - An options object to configure how data is retrieved from - * the snapshot (for example the desired behavior for server timestamps that - * have not yet been set to their final value). - * @returns An `Object` containing all fields in the document. - */ - data(options?: SnapshotOptions): AppModelType; -} -/** - * A `QueryEndAtConstraint` is used to exclude documents from the end of a - * result set returned by a Firestore query. - * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or - * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new - * query instance that also contains this `QueryEndAtConstraint`. - */ -export declare class QueryEndAtConstraint extends QueryConstraint { - /** The type of this query constraint */ - readonly type: 'endBefore' | 'endAt'; -} -/** - * Returns true if the provided queries point to the same collection and apply - * the same constraints. - * - * @param left - A `Query` to compare. - * @param right - A `Query` to compare. - * @returns true if the references point to the same location in the same - * Firestore database. - */ -export declare function queryEqual< - AppModelType, - DbModelType extends DocumentData ->( - left: Query, - right: Query -): boolean; -/** - * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by - * a Firestore query by filtering on one or more document fields. - * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then - * be passed to {@link (query:1)} to create a new query instance that also contains - * this `QueryFieldFilterConstraint`. - */ -export declare class QueryFieldFilterConstraint extends QueryConstraint { - /** The type of this query constraint */ - readonly type = 'where'; -} -/** - * `QueryFilterConstraint` is a helper union type that represents - * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. - */ -export declare type QueryFilterConstraint = - | QueryFieldFilterConstraint - | QueryCompositeFilterConstraint; -/** - * A `QueryLimitConstraint` is used to limit the number of documents returned by - * a Firestore query. - * `QueryLimitConstraint`s are created by invoking {@link limit} or - * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new - * query instance that also contains this `QueryLimitConstraint`. - */ -export declare class QueryLimitConstraint extends QueryConstraint { - /** The type of this query constraint */ - readonly type: 'limit' | 'limitToLast'; -} -/** - * `QueryNonFilterConstraint` is a helper union type that represents - * QueryConstraints which are used to narrow or order the set of documents, - * but that do not explicitly filter on a document field. - * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, - * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, - * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} - * to create a new query instance that also contains the `QueryConstraint`. - */ -export declare type QueryNonFilterConstraint = - | QueryOrderByConstraint - | QueryLimitConstraint - | QueryStartAtConstraint - | QueryEndAtConstraint; -/** - * A `QueryOrderByConstraint` is used to sort the set of documents returned by a - * Firestore query. `QueryOrderByConstraint`s are created by invoking - * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query - * instance that also contains this `QueryOrderByConstraint`. - * - * Note: Documents that do not contain the orderBy field will not be present in - * the query result. - */ -export declare class QueryOrderByConstraint extends QueryConstraint { - /** The type of this query constraint */ - readonly type = 'orderBy'; -} -/** - * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects - * representing the results of a query. The documents can be accessed as an - * array via the `docs` property or enumerated using the `forEach` method. The - * number of documents can be determined via the `empty` and `size` - * properties. - */ -export declare class QuerySnapshot< - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData -> { - /** - * Metadata about this snapshot, concerning its source and if it has local - * modifications. - */ - readonly metadata: SnapshotMetadata; - /** - * The query on which you called `get` or `onSnapshot` in order to get this - * `QuerySnapshot`. - */ - readonly query: Query; - private constructor(); - /** An array of all the documents in the `QuerySnapshot`. */ - get docs(): Array>; - /** The number of documents in the `QuerySnapshot`. */ - get size(): number; - /** True if there are no documents in the `QuerySnapshot`. */ - get empty(): boolean; - /** - * Enumerates all of the documents in the `QuerySnapshot`. - * - * @param callback - A callback to be called with a `QueryDocumentSnapshot` for - * each document in the snapshot. - * @param thisArg - The `this` binding for the callback. - */ - forEach( - callback: ( - result: QueryDocumentSnapshot - ) => void, - thisArg?: unknown - ): void; - /** - * Returns an array of the documents changes since the last snapshot. If this - * is the first snapshot, all documents will be in the list as 'added' - * changes. - * - * @param options - `SnapshotListenOptions` that control whether metadata-only - * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger - * snapshot events. - */ - docChanges( - options?: SnapshotListenOptions - ): Array>; -} -/** - * A `QueryStartAtConstraint` is used to exclude documents from the start of a - * result set returned by a Firestore query. - * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or - * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a - * new query instance that also contains this `QueryStartAtConstraint`. - */ -export declare class QueryStartAtConstraint extends QueryConstraint { - /** The type of this query constraint */ - readonly type: 'startAt' | 'startAfter'; -} -/** - * Returns true if the provided references are equal. - * - * @param left - A reference to compare. - * @param right - A reference to compare. - * @returns true if the references point to the same location in the same - * Firestore database. - */ -export declare function refEqual< - AppModelType, - DbModelType extends DocumentData ->( - left: - | DocumentReference - | CollectionReference, - right: - | DocumentReference - | CollectionReference -): boolean; -/* Excluded from this release type: _ResourcePath */ -/** - * Executes the given `updateFunction` and then attempts to commit the changes - * applied within the transaction. If any document read within the transaction - * has changed, Cloud Firestore retries the `updateFunction`. If it fails to - * commit after 5 attempts, the transaction fails. - * - * The maximum number of writes allowed in a single transaction is 500. - * - * @param firestore - A reference to the Firestore database to run this - * transaction against. - * @param updateFunction - The function to execute within the transaction - * context. - * @param options - An options object to configure maximum number of attempts to - * commit. - * @returns If the transaction completed successfully or was explicitly aborted - * (the `updateFunction` returned a failed promise), the promise returned by the - * `updateFunction `is returned here. Otherwise, if the transaction failed, a - * rejected promise with the corresponding failure error is returned. - */ -export declare function runTransaction( - firestore: Firestore, - updateFunction: (transaction: Transaction) => Promise, - options?: TransactionOptions -): Promise; -/** - * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to - * include a server-generated timestamp in the written data. - */ -export declare function serverTimestamp(): FieldValue; -/** - * Writes to the document referred to by this `DocumentReference`. If the - * document does not yet exist, it will be created. - * - * @param reference - A reference to the document to write. - * @param data - A map of the fields and values for the document. - * @returns A `Promise` resolved once the data has been successfully written - * to the backend (note that it won't resolve while you're offline). - */ -export declare function setDoc( - reference: DocumentReference, - data: WithFieldValue -): Promise; -/** - * Writes to the document referred to by the specified `DocumentReference`. If - * the document does not yet exist, it will be created. If you provide `merge` - * or `mergeFields`, the provided data can be merged into an existing document. - * - * @param reference - A reference to the document to write. - * @param data - A map of the fields and values for the document. - * @param options - An object to configure the set behavior. - * @returns A Promise resolved once the data has been successfully written - * to the backend (note that it won't resolve while you're offline). - */ -export declare function setDoc( - reference: DocumentReference, - data: PartialWithFieldValue, - options: SetOptions -): Promise; -/** - * Configures indexing for local query execution. Any previous index - * configuration is overridden. The `Promise` resolves once the index - * configuration has been persisted. - * - * The index entries themselves are created asynchronously. You can continue to - * use queries that require indexing even if the indices are not yet available. - * Query execution will automatically start using the index once the index - * entries have been written. - * - * Indexes are only supported with IndexedDb persistence. If IndexedDb is not - * enabled, any index configuration is ignored. - * - * @param firestore - The {@link Firestore} instance to configure indexes for. - * @param configuration -The index definition. - * @throws FirestoreError if the JSON format is invalid. - * @returns A `Promise` that resolves once all indices are successfully - * configured. - * - * @deprecated Instead of creating cache indexes manually, consider using - * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to - * create cache indexes for queries running locally. - * - * @beta - */ -export declare function setIndexConfiguration( - firestore: Firestore, - configuration: IndexConfiguration -): Promise; -/** - * Configures indexing for local query execution. Any previous index - * configuration is overridden. The `Promise` resolves once the index - * configuration has been persisted. - * - * The index entries themselves are created asynchronously. You can continue to - * use queries that require indexing even if the indices are not yet available. - * Query execution will automatically start using the index once the index - * entries have been written. - * - * Indexes are only supported with IndexedDb persistence. Invoke either - * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()` - * before setting an index configuration. If IndexedDb is not enabled, any - * index configuration is ignored. - * - * The method accepts the JSON format exported by the Firebase CLI (`firebase - * firestore:indexes`). If the JSON format is invalid, this method throws an - * error. - * - * @param firestore - The {@link Firestore} instance to configure indexes for. - * @param json -The JSON format exported by the Firebase CLI. - * @throws FirestoreError if the JSON format is invalid. - * @returns A `Promise` that resolves once all indices are successfully - * configured. - * - * @deprecated Instead of creating cache indexes manually, consider using - * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to - * create cache indexes for queries running locally. - * - * @beta - */ -export declare function setIndexConfiguration( - firestore: Firestore, - json: string -): Promise; -/** - * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). - * - * @param logLevel - The verbosity you set for activity and error logging. Can - * be any of the following values: - * - *
    - *
  • `debug` for the most verbose logging level, primarily for - * debugging.
  • - *
  • `error` to log errors only.
  • - *
  • `silent` to turn off logging.
  • - *
- */ -export declare function setLogLevel(logLevel: LogLevel): void; -/** - * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link - * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be - * configured to perform granular merges instead of overwriting the target - * documents in their entirety by providing a `SetOptions` with `merge: true`. - * - * @param merge - Changes the behavior of a `setDoc()` call to only replace the - * values specified in its data argument. Fields omitted from the `setDoc()` - * call remain untouched. If your input sets any field to an empty map, all - * nested fields are overwritten. - * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace - * the specified field paths. Any field path that is not specified is ignored - * and remains untouched. If your input sets any field to an empty map, all - * nested fields are overwritten. - */ -export declare type SetOptions = - | { - readonly merge?: boolean; - } - | { - readonly mergeFields?: Array; - }; -/** - * Returns true if the provided snapshots are equal. - * - * @param left - A snapshot to compare. - * @param right - A snapshot to compare. - * @returns true if the snapshots are equal. - */ -export declare function snapshotEqual< - AppModelType, - DbModelType extends DocumentData ->( - left: - | DocumentSnapshot - | QuerySnapshot, - right: - | DocumentSnapshot - | QuerySnapshot -): boolean; -/** - * An options object that can be passed to {@link (onSnapshot:1)} and {@link - * QuerySnapshot.docChanges} to control which types of changes to include in the - * result set. - */ -export declare interface SnapshotListenOptions { - /** - * Include a change even if only the metadata of the query or of a document - * changed. Default is false. - */ - readonly includeMetadataChanges?: boolean; - /** - * Set the source the query listens to. Default to "default", which - * listens to both cache and server. - */ - readonly source?: ListenSource; -} -/** - * Metadata about a snapshot, describing the state of the snapshot. - */ -export declare class SnapshotMetadata { - /** - * True if the snapshot contains the result of local writes (for example - * `set()` or `update()` calls) that have not yet been committed to the - * backend. If your listener has opted into metadata updates (via - * `SnapshotListenOptions`) you will receive another snapshot with - * `hasPendingWrites` equal to false once the writes have been committed to - * the backend. - */ - readonly hasPendingWrites: boolean; - /** - * True if the snapshot was created from cached data rather than guaranteed - * up-to-date server data. If your listener has opted into metadata updates - * (via `SnapshotListenOptions`) you will receive another snapshot with - * `fromCache` set to false once the client has received up-to-date data from - * the backend. - */ - readonly fromCache: boolean; - private constructor(); - /** - * Returns true if this `SnapshotMetadata` is equal to the provided one. - * - * @param other - The `SnapshotMetadata` to compare against. - * @returns true if this `SnapshotMetadata` is equal to the provided one. - */ - isEqual(other: SnapshotMetadata): boolean; -} -/** - * Options that configure how data is retrieved from a `DocumentSnapshot` (for - * example the desired behavior for server timestamps that have not yet been set - * to their final value). - */ -export declare interface SnapshotOptions { - /** - * If set, controls the return value for server timestamps that have not yet - * been set to their final value. - * - * By specifying 'estimate', pending server timestamps return an estimate - * based on the local clock. This estimate will differ from the final value - * and cause these values to change once the server result becomes available. - * - * By specifying 'previous', pending timestamps will be ignored and return - * their previous value instead. - * - * If omitted or set to 'none', `null` will be returned by default until the - * server value becomes available. - */ - readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; -} -/** - * Creates a {@link QueryStartAtConstraint} that modifies the result set to - * start after the provided document (exclusive). The starting position is - * relative to the order of the query. The document must contain all of the - * fields provided in the orderBy of the query. - * - * @param snapshot - The snapshot of the document to start after. - * @returns A {@link QueryStartAtConstraint} to pass to `query()` - */ -export declare function startAfter< - AppModelType, - DbModelType extends DocumentData ->( - snapshot: DocumentSnapshot -): QueryStartAtConstraint; -/** - * Creates a {@link QueryStartAtConstraint} that modifies the result set to - * start after the provided fields relative to the order of the query. The order - * of the field values must match the order of the order by clauses of the query. - * - * @param fieldValues - The field values to start this query after, in order - * of the query's order by. - * @returns A {@link QueryStartAtConstraint} to pass to `query()` - */ -export declare function startAfter( - ...fieldValues: unknown[] -): QueryStartAtConstraint; -/** - * Creates a {@link QueryStartAtConstraint} that modifies the result set to - * start at the provided document (inclusive). The starting position is relative - * to the order of the query. The document must contain all of the fields - * provided in the `orderBy` of this query. - * - * @param snapshot - The snapshot of the document to start at. - * @returns A {@link QueryStartAtConstraint} to pass to `query()`. - */ -export declare function startAt( - snapshot: DocumentSnapshot -): QueryStartAtConstraint; -/** - * Creates a {@link QueryStartAtConstraint} that modifies the result set to - * start at the provided fields relative to the order of the query. The order of - * the field values must match the order of the order by clauses of the query. - * - * @param fieldValues - The field values to start this query at, in order - * of the query's order by. - * @returns A {@link QueryStartAtConstraint} to pass to `query()`. - */ -export declare function startAt( - ...fieldValues: unknown[] -): QueryStartAtConstraint; -/** - * Create an AggregateField object that can be used to compute the sum of - * a specified field over a range of documents in the result set of a query. - * @param field Specifies the field to sum across the result set. - */ -export declare function sum(field: string | FieldPath): AggregateField; -/** - * Represents the state of bundle loading tasks. - * - * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will - * be no more updates after they are reported. - */ -export declare type TaskState = 'Error' | 'Running' | 'Success'; -/** - * Terminates the provided {@link Firestore} instance. - * - * After calling `terminate()` only the `clearIndexedDbPersistence()` function - * may be used. Any other function will throw a `FirestoreError`. - * - * To restart after termination, create a new instance of FirebaseFirestore with - * {@link (getFirestore:1)}. - * - * Termination does not cancel any pending writes, and any promises that are - * awaiting a response from the server will not be resolved. If you have - * persistence enabled, the next time you start this instance, it will resume - * sending these writes to the server. - * - * Note: Under normal circumstances, calling `terminate()` is not required. This - * function is useful only when you want to force this instance to release all - * of its resources or in combination with `clearIndexedDbPersistence()` to - * ensure that all local state is destroyed between test runs. - * - * @returns A `Promise` that is resolved when the instance has been successfully - * terminated. - */ -export declare function terminate(firestore: Firestore): Promise; -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A `Timestamp` represents a point in time independent of any time zone or - * calendar, represented as seconds and fractions of seconds at nanosecond - * resolution in UTC Epoch time. - * - * It is encoded using the Proleptic Gregorian Calendar which extends the - * Gregorian calendar backwards to year one. It is encoded assuming all minutes - * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second - * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59.999999999Z. - * - * For examples and further specifications, refer to the - * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. - */ -export declare class Timestamp { - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - */ - readonly seconds: number; - /** - * The fractions of a second at nanosecond resolution.* - */ - readonly nanoseconds: number; - /** - * Creates a new timestamp with the current date, with millisecond precision. - * - * @returns a new timestamp representing the current date. - */ - static now(): Timestamp; - /** - * Creates a new timestamp from the given date. - * - * @param date - The date to initialize the `Timestamp` from. - * @returns A new `Timestamp` representing the same point in time as the given - * date. - */ - static fromDate(date: Date): Timestamp; - /** - * Creates a new timestamp from the given number of milliseconds. - * - * @param milliseconds - Number of milliseconds since Unix epoch - * 1970-01-01T00:00:00Z. - * @returns A new `Timestamp` representing the same point in time as the given - * number of milliseconds. - */ - static fromMillis(milliseconds: number): Timestamp; - /** - * Creates a new timestamp. - * - * @param seconds - The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive. - * @param nanoseconds - The non-negative fractions of a second at nanosecond - * resolution. Negative second values with fractions must still have - * non-negative nanoseconds values that count forward in time. Must be - * from 0 to 999,999,999 inclusive. - */ - constructor( - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - */ - seconds: number, - /** - * The fractions of a second at nanosecond resolution.* - */ - nanoseconds: number - ); - /** - * Converts a `Timestamp` to a JavaScript `Date` object. This conversion - * causes a loss of precision since `Date` objects only support millisecond - * precision. - * - * @returns JavaScript `Date` object representing the same point in time as - * this `Timestamp`, with millisecond precision. - */ - toDate(): Date; - /** - * Converts a `Timestamp` to a numeric timestamp (in milliseconds since - * epoch). This operation causes a loss of precision. - * - * @returns The point in time corresponding to this timestamp, represented as - * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. - */ - toMillis(): number; - /** - * Returns true if this `Timestamp` is equal to the provided one. - * - * @param other - The `Timestamp` to compare against. - * @returns true if this `Timestamp` is equal to the provided one. - */ - isEqual(other: Timestamp): boolean; - /** Returns a textual representation of this `Timestamp`. */ - toString(): string; - /** Returns a JSON-serializable representation of this `Timestamp`. */ - toJSON(): { - seconds: number; - nanoseconds: number; - }; - /** - * Converts this object to a primitive string, which allows `Timestamp` objects - * to be compared using the `>`, `<=`, `>=` and `>` operators. - */ - valueOf(): string; -} -/** - * A reference to a transaction. - * - * The `Transaction` object passed to a transaction's `updateFunction` provides - * the methods to read and write data within the transaction context. See - * {@link runTransaction}. - */ -export declare class Transaction { - private constructor(); - /** - * Reads the document referenced by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be read. - * @returns A `DocumentSnapshot` with the read data. - */ - get( - documentRef: DocumentReference - ): Promise>; - /** - * Writes to the document referred to by the provided {@link - * DocumentReference}. If the document does not exist yet, it will be created. - * - * @param documentRef - A reference to the document to be set. - * @param data - An object of the fields and values for the document. - * @throws Error - If the provided input is not a valid Firestore document. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - set( - documentRef: DocumentReference, - data: WithFieldValue - ): this; - /** - * Writes to the document referred to by the provided {@link - * DocumentReference}. If the document does not exist yet, it will be created. - * If you provide `merge` or `mergeFields`, the provided data can be merged - * into an existing document. - * - * @param documentRef - A reference to the document to be set. - * @param data - An object of the fields and values for the document. - * @param options - An object to configure the set behavior. - * @throws Error - If the provided input is not a valid Firestore document. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - set( - documentRef: DocumentReference, - data: PartialWithFieldValue, - options: SetOptions - ): this; - /** - * Updates fields in the document referred to by the provided {@link - * DocumentReference}. The update will fail if applied to a document that does - * not exist. - * - * @param documentRef - A reference to the document to be updated. - * @param data - An object containing the fields and values with which to - * update the document. Fields can contain dots to reference nested fields - * within the document. - * @throws Error - If the provided input is not valid Firestore data. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - update( - documentRef: DocumentReference, - data: UpdateData - ): this; - /** - * Updates fields in the document referred to by the provided {@link - * DocumentReference}. The update will fail if applied to a document that does - * not exist. - * - * Nested fields can be updated by providing dot-separated field path - * strings or by providing `FieldPath` objects. - * - * @param documentRef - A reference to the document to be updated. - * @param field - The first field to update. - * @param value - The first value. - * @param moreFieldsAndValues - Additional key/value pairs. - * @throws Error - If the provided input is not valid Firestore data. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - update( - documentRef: DocumentReference, - field: string | FieldPath, - value: unknown, - ...moreFieldsAndValues: unknown[] - ): this; - /** - * Deletes the document referred to by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be deleted. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - delete( - documentRef: DocumentReference - ): this; -} -/** - * @license - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Options to customize transaction behavior. - */ -export declare interface TransactionOptions { - /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ - readonly maxAttempts?: number; -} -/** - * Given a union type `U = T1 | T2 | ...`, returns an intersected type - * `(T1 & T2 & ...)`. - * - * Uses distributive conditional types and inference from conditional types. - * This works because multiple candidates for the same type variable in - * contra-variant positions causes an intersection type to be inferred. - * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types - * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type - */ -export declare type UnionToIntersection = ( - U extends unknown ? (k: U) => void : never -) extends (k: infer I) => void - ? I - : never; -/** - * A function returned by `onSnapshot()` that removes the listener when invoked. - */ -export declare interface Unsubscribe { - /** Removes the listener when invoked. */ - (): void; -} -/** - * Update data (for use with {@link (updateDoc:1)}) that consists of field paths - * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots - * reference nested fields within the document. FieldValues can be passed in - * as property values. - */ -export declare type UpdateData = T extends Primitive - ? T - : T extends {} - ? { - [K in keyof T]?: UpdateData | FieldValue; - } & NestedUpdateFields - : Partial; -/** - * Updates fields in the document referred to by the specified - * `DocumentReference`. The update will fail if applied to a document that does - * not exist. - * - * @param reference - A reference to the document to update. - * @param data - An object containing the fields and values with which to - * update the document. Fields can contain dots to reference nested fields - * within the document. - * @returns A `Promise` resolved once the data has been successfully written - * to the backend (note that it won't resolve while you're offline). - */ -export declare function updateDoc< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference, - data: UpdateData -): Promise; -/** - * Updates fields in the document referred to by the specified - * `DocumentReference` The update will fail if applied to a document that does - * not exist. - * - * Nested fields can be updated by providing dot-separated field path - * strings or by providing `FieldPath` objects. - * - * @param reference - A reference to the document to update. - * @param field - The first field to update. - * @param value - The first value. - * @param moreFieldsAndValues - Additional key value pairs. - * @returns A `Promise` resolved once the data has been successfully written - * to the backend (note that it won't resolve while you're offline). - */ -export declare function updateDoc< - AppModelType, - DbModelType extends DocumentData ->( - reference: DocumentReference, - field: string | FieldPath, - value: unknown, - ...moreFieldsAndValues: unknown[] -): Promise; -/** - * Creates a new `VectorValue` constructed with a copy of the given array of numbers. - * - * @param values - Create a `VectorValue` instance with a copy of this array of numbers. - * - * @returns A new `VectorValue` constructed with a copy of the given array of numbers. - */ -export declare function vector(values?: number[]): VectorValue; -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Represents a vector type in Firestore documents. - * Create an instance with {@link FieldValue.vector}. - * - * @class VectorValue - */ -export declare class VectorValue { - /* Excluded from this release type: __constructor */ - /** - * Returns a copy of the raw number array form of the vector. - */ - toArray(): number[]; - /** - * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise. - */ - isEqual(other: VectorValue): boolean; -} -/** - * Waits until all currently pending writes for the active user have been - * acknowledged by the backend. - * - * The returned promise resolves immediately if there are no outstanding writes. - * Otherwise, the promise waits for all previously issued writes (including - * those written in a previous app session), but it does not wait for writes - * that were added after the function is called. If you want to wait for - * additional writes, call `waitForPendingWrites()` again. - * - * Any outstanding `waitForPendingWrites()` promises are rejected during user - * changes. - * - * @returns A `Promise` which resolves when all currently pending writes have been - * acknowledged by the backend. - */ -export declare function waitForPendingWrites( - firestore: Firestore -): Promise; -/** - * Creates a {@link QueryFieldFilterConstraint} that enforces that documents - * must contain the specified field and that the value should satisfy the - * relation constraint provided. - * - * @param fieldPath - The path to compare - * @param opStr - The operation string (e.g "<", "<=", "==", "<", - * "<=", "!="). - * @param value - The value for comparison - * @returns The created {@link QueryFieldFilterConstraint}. - */ -export declare function where( - fieldPath: string | FieldPath, - opStr: WhereFilterOp, - value: unknown -): QueryFieldFilterConstraint; -/** - * Filter conditions in a {@link where} clause are specified using the - * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', - * 'array-contains-any', and 'not-in'. - */ -export declare type WhereFilterOp = - | '<' - | '<=' - | '==' - | '!=' - | '>=' - | '>' - | 'array-contains' - | 'in' - | 'array-contains-any' - | 'not-in'; -/** - * Allows FieldValues to be passed in as a property value while maintaining - * type safety. - */ -export declare type WithFieldValue = - | T - | (T extends Primitive - ? T - : T extends {} - ? { - [K in keyof T]: WithFieldValue | FieldValue; - } - : never); -/** - * A write batch, used to perform multiple writes as a single atomic unit. - * - * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It - * provides methods for adding writes to the write batch. None of the writes - * will be committed (or visible locally) until {@link WriteBatch.commit} is - * called. - */ -export declare class WriteBatch { - private constructor(); - /** - * Writes to the document referred to by the provided {@link - * DocumentReference}. If the document does not exist yet, it will be created. - * - * @param documentRef - A reference to the document to be set. - * @param data - An object of the fields and values for the document. - * @returns This `WriteBatch` instance. Used for chaining method calls. - */ - set( - documentRef: DocumentReference, - data: WithFieldValue - ): WriteBatch; - /** - * Writes to the document referred to by the provided {@link - * DocumentReference}. If the document does not exist yet, it will be created. - * If you provide `merge` or `mergeFields`, the provided data can be merged - * into an existing document. - * - * @param documentRef - A reference to the document to be set. - * @param data - An object of the fields and values for the document. - * @param options - An object to configure the set behavior. - * @throws Error - If the provided input is not a valid Firestore document. - * @returns This `WriteBatch` instance. Used for chaining method calls. - */ - set( - documentRef: DocumentReference, - data: PartialWithFieldValue, - options: SetOptions - ): WriteBatch; - /** - * Updates fields in the document referred to by the provided {@link - * DocumentReference}. The update will fail if applied to a document that does - * not exist. - * - * @param documentRef - A reference to the document to be updated. - * @param data - An object containing the fields and values with which to - * update the document. Fields can contain dots to reference nested fields - * within the document. - * @throws Error - If the provided input is not valid Firestore data. - * @returns This `WriteBatch` instance. Used for chaining method calls. - */ - update( - documentRef: DocumentReference, - data: UpdateData - ): WriteBatch; - /** - * Updates fields in the document referred to by this {@link - * DocumentReference}. The update will fail if applied to a document that does - * not exist. - * - * Nested fields can be update by providing dot-separated field path strings - * or by providing `FieldPath` objects. - * - * @param documentRef - A reference to the document to be updated. - * @param field - The first field to update. - * @param value - The first value. - * @param moreFieldsAndValues - Additional key value pairs. - * @throws Error - If the provided input is not valid Firestore data. - * @returns This `WriteBatch` instance. Used for chaining method calls. - */ - update( - documentRef: DocumentReference, - field: string | FieldPath, - value: unknown, - ...moreFieldsAndValues: unknown[] - ): WriteBatch; - /** - * Deletes the document referred to by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be deleted. - * @returns This `WriteBatch` instance. Used for chaining method calls. - */ - delete( - documentRef: DocumentReference - ): WriteBatch; - /** - * Commits all of the writes in this write batch as a single atomic unit. - * - * The result of these writes will only be reflected in document reads that - * occur after the returned promise resolves. If the client is offline, the - * write fails. If you would like to see local modifications or buffer writes - * until the client is online, use the full Firestore SDK. - * - * @returns A `Promise` resolved once all of the writes in the batch have been - * successfully written to the backend as an atomic unit (note that it won't - * resolve while you're offline). - */ - commit(): Promise; -} -/** - * Creates a write batch, used for performing multiple writes as a single - * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} - * is 500. - * - * Unlike transactions, write batches are persisted offline and therefore are - * preferable when you don't need to condition your writes on read data. - * - * @returns A {@link WriteBatch} that can be used to atomically execute multiple - * writes. - */ -export declare function writeBatch(firestore: Firestore): WriteBatch; -export {}; diff --git a/repo-scripts/prune-dts/prune-dts.test.ts b/repo-scripts/prune-dts/prune-dts.test.ts index 0e08de0078f..ba770e43cd9 100644 --- a/repo-scripts/prune-dts/prune-dts.test.ts +++ b/repo-scripts/prune-dts/prune-dts.test.ts @@ -23,7 +23,7 @@ import { expect } from 'chai'; import { describe, it } from 'mocha'; import { pruneDts } from './prune-dts'; -const testCasesDir = path.resolve(__dirname, 'new-tests'); +const testCasesDir = path.resolve(__dirname, 'tests'); const tmpDir = os.tmpdir(); const testDataFilter = /(.*).input.d.ts/; diff --git a/repo-scripts/prune-dts/subtests/app.input.d.ts b/repo-scripts/prune-dts/subtests/app.input.d.ts deleted file mode 100644 index a0181b92462..00000000000 --- a/repo-scripts/prune-dts/subtests/app.input.d.ts +++ /dev/null @@ -1,576 +0,0 @@ -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Firebase App - * - * @remarks This package coordinates the communication between the different Firebase components - * @packageDocumentation - */ - -import { Component } from '@firebase/component'; -import { ComponentContainer } from '@firebase/component'; -import { FirebaseError } from '@firebase/util'; -import { LogCallback } from '@firebase/logger'; -import { LogLevelString } from '@firebase/logger'; -import { LogOptions } from '@firebase/logger'; -import { Name } from '@firebase/component'; -import { Provider } from '@firebase/component'; - -/** - * @param component - the component being added to this app's container - * - * @internal - */ -export declare function _addComponent( - app: FirebaseApp, - component: Component -): void; - -/** - * - * @internal - */ -export declare function _addOrOverwriteComponent( - app: FirebaseApp, - component: Component -): void; - -/** - * @internal - */ -export declare const _apps: Map; - -/** - * Test only - * - * @internal - */ -export declare function _clearComponents(): void; - -/** - * Registered components. - * - * @internal - */ -export declare const _components: Map>; - -/** - * The default app name - * - * @internal - */ -export declare const _DEFAULT_ENTRY_NAME = '[DEFAULT]'; - -/** - * Renders this app unusable and frees the resources of all associated - * services. - * - * @example - * ```javascript - * deleteApp(app) - * .then(function() { - * console.log("App deleted successfully"); - * }) - * .catch(function(error) { - * console.log("Error deleting app:", error); - * }); - * ``` - * - * @public - */ -export declare function deleteApp(app: FirebaseApp): Promise; - -/** - * A {@link @firebase/app#FirebaseApp} holds the initialization information for a collection of - * services. - * - * Do not call this constructor directly. Instead, use - * {@link (initializeApp:1) | initializeApp()} to create an app. - * - * @public - */ -export declare interface FirebaseApp { - /** - * The (read-only) name for this app. - * - * The default app's name is `"[DEFAULT]"`. - * - * @example - * ```javascript - * // The default app's name is "[DEFAULT]" - * const app = initializeApp(defaultAppConfig); - * console.log(app.name); // "[DEFAULT]" - * ``` - * - * @example - * ```javascript - * // A named app's name is what you provide to initializeApp() - * const otherApp = initializeApp(otherAppConfig, "other"); - * console.log(otherApp.name); // "other" - * ``` - */ - readonly name: string; - /** - * The (read-only) configuration options for this app. These are the original - * parameters given in {@link (initializeApp:1) | initializeApp()}. - * - * @example - * ```javascript - * const app = initializeApp(config); - * console.log(app.options.databaseURL === config.databaseURL); // true - * ``` - */ - readonly options: FirebaseOptions; - /** - * The settable config flag for GDPR opt-in/opt-out - */ - automaticDataCollectionEnabled: boolean; -} - -/** - * @internal - */ -export declare interface _FirebaseAppInternal extends FirebaseApp { - container: ComponentContainer; - isDeleted: boolean; - checkDestroyed(): void; -} - -/** - * @public - * - * Configuration options given to {@link (initializeApp:1) | initializeApp()} - */ -export declare interface FirebaseAppSettings { - /** - * custom name for the Firebase App. - * The default value is `"[DEFAULT]"`. - */ - name?: string; - /** - * The settable config flag for GDPR opt-in/opt-out - */ - automaticDataCollectionEnabled?: boolean; -} -export { FirebaseError }; - -/** - * @public - * - * Firebase configuration object. Contains a set of parameters required by - * services in order to successfully communicate with Firebase server APIs - * and to associate client data with your Firebase project and - * Firebase application. Typically this object is populated by the Firebase - * console at project setup. See also: - * {@link https://firebase.google.com/docs/web/setup#config-object | Learn about the Firebase config object}. - */ -export declare interface FirebaseOptions { - /** - * An encrypted string used when calling certain APIs that don't need to - * access private user data - * (example value: `AIzaSyDOCAbC123dEf456GhI789jKl012-MnO`). - */ - apiKey?: string; - /** - * Auth domain for the project ID. - */ - authDomain?: string; - /** - * Default Realtime Database URL. - */ - databaseURL?: string; - /** - * The unique identifier for the project across all of Firebase and - * Google Cloud. - */ - projectId?: string; - /** - * The default Cloud Storage bucket name. - */ - storageBucket?: string; - /** - * Unique numerical value used to identify each sender that can send - * Firebase Cloud Messaging messages to client apps. - */ - messagingSenderId?: string; - /** - * Unique identifier for the app. - */ - appId?: string; - /** - * An ID automatically created when you enable Analytics in your - * Firebase project and register a web app. In versions 7.20.0 - * and higher, this parameter is optional. - */ - measurementId?: string; -} - -/** - * A {@link @firebase/app#FirebaseServerApp} holds the initialization information - * for a collection of services running in server environments. - * - * Do not call this constructor directly. Instead, use - * {@link (initializeServerApp:1) | initializeServerApp()} to create - * an app. - * - * @public - */ -export declare interface FirebaseServerApp extends FirebaseApp { - /** - * There is no `getApp()` operation for `FirebaseServerApp`, so the name is not relevant for - * applications. However, it may be used internally, and is declared here so that - * `FirebaseServerApp` conforms to the `FirebaseApp` interface. - */ - name: string; - /** - * The (read-only) configuration settings for this server app. These are the original - * parameters given in {@link (initializeServerApp:1) | initializeServerApp()}. - * - * @example - * ```javascript - * const app = initializeServerApp(settings); - * console.log(app.settings.authIdToken === options.authIdToken); // true - * ``` - */ - readonly settings: FirebaseServerAppSettings; -} - -/** - * @public - * - * Configuration options given to {@link (initializeServerApp:1) | initializeServerApp()} - */ -export declare interface FirebaseServerAppSettings - extends Omit { - /** - * An optional Auth ID token used to resume a signed in user session from a client - * runtime environment. - * - * Invoking `getAuth` with a `FirebaseServerApp` configured with a validated `authIdToken` - * causes an automatic attempt to sign in the user that the `authIdToken` represents. The token - * needs to have been recently minted for this operation to succeed. - * - * If the token fails local verification, or if the Auth service has failed to validate it when - * the Auth SDK is initialized, then a warning is logged to the console and the Auth SDK will not - * sign in a user on initialization. - * - * If a user is successfully signed in, then the Auth instance's `onAuthStateChanged` callback - * is invoked with the `User` object as per standard Auth flows. However, `User` objects - * created via an `authIdToken` do not have a refresh token. Attempted `refreshToken` - * operations fail. - */ - authIdToken?: string; - /** - * An optional object. If provided, the Firebase SDK uses a `FinalizationRegistry` - * object to monitor the garbage collection status of the provided object. The - * Firebase SDK releases its reference on the `FirebaseServerApp` instance when the - * provided `releaseOnDeref` object is garbage collected. - * - * You can use this field to reduce memory management overhead for your application. - * If provided, an app running in a SSR pass does not need to perform - * `FirebaseServerApp` cleanup, so long as the reference object is deleted (by falling out of - * SSR scope, for instance.) - * - * If an object is not provided then the application must clean up the `FirebaseServerApp` - * instance by invoking `deleteApp`. - * - * If the application provides an object in this parameter, but the application is - * executed in a JavaScript engine that predates the support of `FinalizationRegistry` - * (introduced in node v14.6.0, for instance), then an error is thrown at `FirebaseServerApp` - * initialization. - */ - releaseOnDeref?: object; -} - -/** - * @internal - */ -export declare interface _FirebaseService { - app: FirebaseApp; - /** - * Delete the service and free it's resources - called from - * {@link @firebase/app#deleteApp | deleteApp()} - */ - _delete(): Promise; -} - -/** - * Retrieves a {@link @firebase/app#FirebaseApp} instance. - * - * When called with no arguments, the default app is returned. When an app name - * is provided, the app corresponding to that name is returned. - * - * An exception is thrown if the app being retrieved has not yet been - * initialized. - * - * @example - * ```javascript - * // Return the default app - * const app = getApp(); - * ``` - * - * @example - * ```javascript - * // Return a named app - * const otherApp = getApp("otherApp"); - * ``` - * - * @param name - Optional name of the app to return. If no name is - * provided, the default is `"[DEFAULT]"`. - * - * @returns The app corresponding to the provided app name. - * If no app name is provided, the default app is returned. - * - * @public - */ -export declare function getApp(name?: string): FirebaseApp; - -/** - * A (read-only) array of all initialized apps. - * @public - */ -export declare function getApps(): FirebaseApp[]; - -/** - * - * @param app - FirebaseApp instance - * @param name - service name - * - * @returns the provider for the service with the matching name - * - * @internal - */ -export declare function _getProvider( - app: FirebaseApp, - name: T -): Provider; - -/** - * Creates and initializes a {@link @firebase/app#FirebaseApp} instance. - * - * See - * {@link - * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app - * | Add Firebase to your app} and - * {@link - * https://firebase.google.com/docs/web/setup#multiple-projects - * | Initialize multiple projects} for detailed documentation. - * - * @example - * ```javascript - * - * // Initialize default app - * // Retrieve your own options values by adding a web app on - * // https://console.firebase.google.com - * initializeApp({ - * apiKey: "AIza....", // Auth / General Use - * authDomain: "YOUR_APP.firebaseapp.com", // Auth with popup/redirect - * databaseURL: "https://YOUR_APP.firebaseio.com", // Realtime Database - * storageBucket: "YOUR_APP.appspot.com", // Storage - * messagingSenderId: "123456789" // Cloud Messaging - * }); - * ``` - * - * @example - * ```javascript - * - * // Initialize another app - * const otherApp = initializeApp({ - * databaseURL: "https://.firebaseio.com", - * storageBucket: ".appspot.com" - * }, "otherApp"); - * ``` - * - * @param options - Options to configure the app's services. - * @param name - Optional name of the app to initialize. If no name - * is provided, the default is `"[DEFAULT]"`. - * - * @returns The initialized app. - * - * @public - */ -export declare function initializeApp( - options: FirebaseOptions, - name?: string -): FirebaseApp; - -/** - * Creates and initializes a FirebaseApp instance. - * - * @param options - Options to configure the app's services. - * @param config - FirebaseApp Configuration - * - * @public - */ -export declare function initializeApp( - options: FirebaseOptions, - config?: FirebaseAppSettings -): FirebaseApp; - -/** - * Creates and initializes a FirebaseApp instance. - * - * @public - */ -export declare function initializeApp(): FirebaseApp; - -/** - * Creates and initializes a {@link @firebase/app#FirebaseServerApp} instance. - * - * The `FirebaseServerApp` is similar to `FirebaseApp`, but is intended for execution in - * server side rendering environments only. Initialization will fail if invoked from a - * browser environment. - * - * See - * {@link - * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app - * | Add Firebase to your app} and - * {@link - * https://firebase.google.com/docs/web/setup#multiple-projects - * | Initialize multiple projects} for detailed documentation. - * - * @example - * ```javascript - * - * // Initialize an instance of `FirebaseServerApp`. - * // Retrieve your own options values by adding a web app on - * // https://console.firebase.google.com - * initializeServerApp({ - * apiKey: "AIza....", // Auth / General Use - * authDomain: "YOUR_APP.firebaseapp.com", // Auth with popup/redirect - * databaseURL: "https://YOUR_APP.firebaseio.com", // Realtime Database - * storageBucket: "YOUR_APP.appspot.com", // Storage - * messagingSenderId: "123456789" // Cloud Messaging - * }, - * { - * authIdToken: "Your Auth ID Token" - * }); - * ``` - * - * @param options - `Firebase.AppOptions` to configure the app's services, or a - * a `FirebaseApp` instance which contains the `AppOptions` within. - * @param config - `FirebaseServerApp` configuration. - * - * @returns The initialized `FirebaseServerApp`. - * - * @public - */ -export declare function initializeServerApp( - options: FirebaseOptions | FirebaseApp, - config: FirebaseServerAppSettings -): FirebaseServerApp; - -/** - * - * @param obj - an object of type FirebaseApp or FirebaseOptions. - * - * @returns true if the provide object is of type FirebaseApp. - * - * @internal - */ -export declare function _isFirebaseApp( - obj: FirebaseApp | FirebaseOptions -): obj is FirebaseApp; - -/** - * - * @param obj - an object of type FirebaseApp. - * - * @returns true if the provided object is of type FirebaseServerAppImpl. - * - * @internal - */ -export declare function _isFirebaseServerApp( - obj: FirebaseApp | FirebaseServerApp -): obj is FirebaseServerApp; - -/** - * Sets log handler for all Firebase SDKs. - * @param logCallback - An optional custom log handler that executes user code whenever - * the Firebase SDK makes a logging call. - * - * @public - */ -export declare function onLog( - logCallback: LogCallback | null, - options?: LogOptions -): void; - -/** - * - * @param component - the component to register - * @returns whether or not the component is registered successfully - * - * @internal - */ -export declare function _registerComponent( - component: Component -): boolean; - -/** - * Registers a library's name and version for platform logging purposes. - * @param library - Name of 1p or 3p library (e.g. firestore, angularfire) - * @param version - Current version of that library. - * @param variant - Bundle variant, e.g., node, rn, etc. - * - * @public - */ -export declare function registerVersion( - libraryKeyOrName: string, - version: string, - variant?: string -): void; - -/** - * - * @param app - FirebaseApp instance - * @param name - service name - * @param instanceIdentifier - service instance identifier in case the service supports multiple instances - * - * @internal - */ -export declare function _removeServiceInstance( - app: FirebaseApp, - name: T, - instanceIdentifier?: string -): void; - -/** - * The current SDK version. - * - * @public - */ -export declare const SDK_VERSION: string; - -/** - * @internal - */ -export declare const _serverApps: Map; - -/** - * Sets log level for all Firebase SDKs. - * - * All of the log types above the current log level are captured (i.e. if - * you set the log level to `info`, errors are logged, but `debug` and - * `verbose` logs are not). - * - * @public - */ -export declare function setLogLevel(logLevel: LogLevelString): void; - -export {}; diff --git a/repo-scripts/prune-dts/subtests/app.output.d.ts b/repo-scripts/prune-dts/subtests/app.output.d.ts deleted file mode 100644 index a988662d4bf..00000000000 --- a/repo-scripts/prune-dts/subtests/app.output.d.ts +++ /dev/null @@ -1,470 +0,0 @@ -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Firebase App - * - * @remarks This package coordinates the communication between the different Firebase components - * @packageDocumentation - */ - -import { Component } from '@firebase/component'; -import { ComponentContainer } from '@firebase/component'; -import { FirebaseError } from '@firebase/util'; -import { LogCallback } from '@firebase/logger'; -import { LogLevelString } from '@firebase/logger'; -import { LogOptions } from '@firebase/logger'; -import { Name } from '@firebase/component'; -import { Provider } from '@firebase/component'; - -/* Excluded from this release type: _addComponent */ - -/* Excluded from this release type: _addOrOverwriteComponent */ - -/* Excluded from this release type: _apps */ - -/* Excluded from this release type: _clearComponents */ - -/* Excluded from this release type: _components */ - -/* Excluded from this release type: _DEFAULT_ENTRY_NAME */ - -/** - * Renders this app unusable and frees the resources of all associated - * services. - * - * @example - * ```javascript - * deleteApp(app) - * .then(function() { - * console.log("App deleted successfully"); - * }) - * .catch(function(error) { - * console.log("Error deleting app:", error); - * }); - * ``` - * - * @public - */ -export declare function deleteApp(app: FirebaseApp): Promise; - -/** - * A {@link @firebase/app#FirebaseApp} holds the initialization information for a collection of - * services. - * - * Do not call this constructor directly. Instead, use - * {@link (initializeApp:1) | initializeApp()} to create an app. - * - * @public - */ -export declare interface FirebaseApp { - /** - * The (read-only) name for this app. - * - * The default app's name is `"[DEFAULT]"`. - * - * @example - * ```javascript - * // The default app's name is "[DEFAULT]" - * const app = initializeApp(defaultAppConfig); - * console.log(app.name); // "[DEFAULT]" - * ``` - * - * @example - * ```javascript - * // A named app's name is what you provide to initializeApp() - * const otherApp = initializeApp(otherAppConfig, "other"); - * console.log(otherApp.name); // "other" - * ``` - */ - readonly name: string; - /** - * The (read-only) configuration options for this app. These are the original - * parameters given in {@link (initializeApp:1) | initializeApp()}. - * - * @example - * ```javascript - * const app = initializeApp(config); - * console.log(app.options.databaseURL === config.databaseURL); // true - * ``` - */ - readonly options: FirebaseOptions; - /** - * The settable config flag for GDPR opt-in/opt-out - */ - automaticDataCollectionEnabled: boolean; -} - -/* Excluded from this release type: _FirebaseAppInternal */ - -/** - * @public - * - * Configuration options given to {@link (initializeApp:1) | initializeApp()} - */ -export declare interface FirebaseAppSettings { - /** - * custom name for the Firebase App. - * The default value is `"[DEFAULT]"`. - */ - name?: string; - /** - * The settable config flag for GDPR opt-in/opt-out - */ - automaticDataCollectionEnabled?: boolean; -} -export { FirebaseError }; - -/** - * @public - * - * Firebase configuration object. Contains a set of parameters required by - * services in order to successfully communicate with Firebase server APIs - * and to associate client data with your Firebase project and - * Firebase application. Typically this object is populated by the Firebase - * console at project setup. See also: - * {@link https://firebase.google.com/docs/web/setup#config-object | Learn about the Firebase config object}. - */ -export declare interface FirebaseOptions { - /** - * An encrypted string used when calling certain APIs that don't need to - * access private user data - * (example value: `AIzaSyDOCAbC123dEf456GhI789jKl012-MnO`). - */ - apiKey?: string; - /** - * Auth domain for the project ID. - */ - authDomain?: string; - /** - * Default Realtime Database URL. - */ - databaseURL?: string; - /** - * The unique identifier for the project across all of Firebase and - * Google Cloud. - */ - projectId?: string; - /** - * The default Cloud Storage bucket name. - */ - storageBucket?: string; - /** - * Unique numerical value used to identify each sender that can send - * Firebase Cloud Messaging messages to client apps. - */ - messagingSenderId?: string; - /** - * Unique identifier for the app. - */ - appId?: string; - /** - * An ID automatically created when you enable Analytics in your - * Firebase project and register a web app. In versions 7.20.0 - * and higher, this parameter is optional. - */ - measurementId?: string; -} - -/** - * A {@link @firebase/app#FirebaseServerApp} holds the initialization information - * for a collection of services running in server environments. - * - * Do not call this constructor directly. Instead, use - * {@link (initializeServerApp:1) | initializeServerApp()} to create - * an app. - * - * @public - */ -export declare interface FirebaseServerApp extends FirebaseApp { - /** - * There is no `getApp()` operation for `FirebaseServerApp`, so the name is not relevant for - * applications. However, it may be used internally, and is declared here so that - * `FirebaseServerApp` conforms to the `FirebaseApp` interface. - */ - name: string; - /** - * The (read-only) configuration settings for this server app. These are the original - * parameters given in {@link (initializeServerApp:1) | initializeServerApp()}. - * - * @example - * ```javascript - * const app = initializeServerApp(settings); - * console.log(app.settings.authIdToken === options.authIdToken); // true - * ``` - */ - readonly settings: FirebaseServerAppSettings; -} - -/** - * @public - * - * Configuration options given to {@link (initializeServerApp:1) | initializeServerApp()} - */ -export declare interface FirebaseServerAppSettings - extends Omit { - /** - * An optional Auth ID token used to resume a signed in user session from a client - * runtime environment. - * - * Invoking `getAuth` with a `FirebaseServerApp` configured with a validated `authIdToken` - * causes an automatic attempt to sign in the user that the `authIdToken` represents. The token - * needs to have been recently minted for this operation to succeed. - * - * If the token fails local verification, or if the Auth service has failed to validate it when - * the Auth SDK is initialized, then a warning is logged to the console and the Auth SDK will not - * sign in a user on initialization. - * - * If a user is successfully signed in, then the Auth instance's `onAuthStateChanged` callback - * is invoked with the `User` object as per standard Auth flows. However, `User` objects - * created via an `authIdToken` do not have a refresh token. Attempted `refreshToken` - * operations fail. - */ - authIdToken?: string; - /** - * An optional object. If provided, the Firebase SDK uses a `FinalizationRegistry` - * object to monitor the garbage collection status of the provided object. The - * Firebase SDK releases its reference on the `FirebaseServerApp` instance when the - * provided `releaseOnDeref` object is garbage collected. - * - * You can use this field to reduce memory management overhead for your application. - * If provided, an app running in a SSR pass does not need to perform - * `FirebaseServerApp` cleanup, so long as the reference object is deleted (by falling out of - * SSR scope, for instance.) - * - * If an object is not provided then the application must clean up the `FirebaseServerApp` - * instance by invoking `deleteApp`. - * - * If the application provides an object in this parameter, but the application is - * executed in a JavaScript engine that predates the support of `FinalizationRegistry` - * (introduced in node v14.6.0, for instance), then an error is thrown at `FirebaseServerApp` - * initialization. - */ - releaseOnDeref?: object; -} - -/* Excluded from this release type: _FirebaseService */ - -/** - * Retrieves a {@link @firebase/app#FirebaseApp} instance. - * - * When called with no arguments, the default app is returned. When an app name - * is provided, the app corresponding to that name is returned. - * - * An exception is thrown if the app being retrieved has not yet been - * initialized. - * - * @example - * ```javascript - * // Return the default app - * const app = getApp(); - * ``` - * - * @example - * ```javascript - * // Return a named app - * const otherApp = getApp("otherApp"); - * ``` - * - * @param name - Optional name of the app to return. If no name is - * provided, the default is `"[DEFAULT]"`. - * - * @returns The app corresponding to the provided app name. - * If no app name is provided, the default app is returned. - * - * @public - */ -export declare function getApp(name?: string): FirebaseApp; - -/** - * A (read-only) array of all initialized apps. - * @public - */ -export declare function getApps(): FirebaseApp[]; - -/* Excluded from this release type: _getProvider */ - -/** - * Creates and initializes a {@link @firebase/app#FirebaseApp} instance. - * - * See - * {@link - * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app - * | Add Firebase to your app} and - * {@link - * https://firebase.google.com/docs/web/setup#multiple-projects - * | Initialize multiple projects} for detailed documentation. - * - * @example - * ```javascript - * - * // Initialize default app - * // Retrieve your own options values by adding a web app on - * // https://console.firebase.google.com - * initializeApp({ - * apiKey: "AIza....", // Auth / General Use - * authDomain: "YOUR_APP.firebaseapp.com", // Auth with popup/redirect - * databaseURL: "https://YOUR_APP.firebaseio.com", // Realtime Database - * storageBucket: "YOUR_APP.appspot.com", // Storage - * messagingSenderId: "123456789" // Cloud Messaging - * }); - * ``` - * - * @example - * ```javascript - * - * // Initialize another app - * const otherApp = initializeApp({ - * databaseURL: "https://.firebaseio.com", - * storageBucket: ".appspot.com" - * }, "otherApp"); - * ``` - * - * @param options - Options to configure the app's services. - * @param name - Optional name of the app to initialize. If no name - * is provided, the default is `"[DEFAULT]"`. - * - * @returns The initialized app. - * - * @public - */ -export declare function initializeApp( - options: FirebaseOptions, - name?: string -): FirebaseApp; - -/** - * Creates and initializes a FirebaseApp instance. - * - * @param options - Options to configure the app's services. - * @param config - FirebaseApp Configuration - * - * @public - */ -export declare function initializeApp( - options: FirebaseOptions, - config?: FirebaseAppSettings -): FirebaseApp; - -/** - * Creates and initializes a FirebaseApp instance. - * - * @public - */ -export declare function initializeApp(): FirebaseApp; - -/** - * Creates and initializes a {@link @firebase/app#FirebaseServerApp} instance. - * - * The `FirebaseServerApp` is similar to `FirebaseApp`, but is intended for execution in - * server side rendering environments only. Initialization will fail if invoked from a - * browser environment. - * - * See - * {@link - * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app - * | Add Firebase to your app} and - * {@link - * https://firebase.google.com/docs/web/setup#multiple-projects - * | Initialize multiple projects} for detailed documentation. - * - * @example - * ```javascript - * - * // Initialize an instance of `FirebaseServerApp`. - * // Retrieve your own options values by adding a web app on - * // https://console.firebase.google.com - * initializeServerApp({ - * apiKey: "AIza....", // Auth / General Use - * authDomain: "YOUR_APP.firebaseapp.com", // Auth with popup/redirect - * databaseURL: "https://YOUR_APP.firebaseio.com", // Realtime Database - * storageBucket: "YOUR_APP.appspot.com", // Storage - * messagingSenderId: "123456789" // Cloud Messaging - * }, - * { - * authIdToken: "Your Auth ID Token" - * }); - * ``` - * - * @param options - `Firebase.AppOptions` to configure the app's services, or a - * a `FirebaseApp` instance which contains the `AppOptions` within. - * @param config - `FirebaseServerApp` configuration. - * - * @returns The initialized `FirebaseServerApp`. - * - * @public - */ -export declare function initializeServerApp( - options: FirebaseOptions | FirebaseApp, - config: FirebaseServerAppSettings -): FirebaseServerApp; - -/* Excluded from this release type: _isFirebaseApp */ - -/* Excluded from this release type: _isFirebaseServerApp */ - -/** - * Sets log handler for all Firebase SDKs. - * @param logCallback - An optional custom log handler that executes user code whenever - * the Firebase SDK makes a logging call. - * - * @public - */ -export declare function onLog( - logCallback: LogCallback | null, - options?: LogOptions -): void; - -/* Excluded from this release type: _registerComponent */ - -/** - * Registers a library's name and version for platform logging purposes. - * @param library - Name of 1p or 3p library (e.g. firestore, angularfire) - * @param version - Current version of that library. - * @param variant - Bundle variant, e.g., node, rn, etc. - * - * @public - */ -export declare function registerVersion( - libraryKeyOrName: string, - version: string, - variant?: string -): void; - -/* Excluded from this release type: _removeServiceInstance */ - -/** - * The current SDK version. - * - * @public - */ -export declare const SDK_VERSION: string; - -/* Excluded from this release type: _serverApps */ - -/** - * Sets log level for all Firebase SDKs. - * - * All of the log types above the current log level are captured (i.e. if - * you set the log level to `info`, errors are logged, but `debug` and - * `verbose` logs are not). - * - * @public - */ -export declare function setLogLevel(logLevel: LogLevelString): void; - -export {}; diff --git a/repo-scripts/prune-dts/new-tests/data-connect.input.d.ts b/repo-scripts/prune-dts/tests/data-connect.input.d.ts similarity index 100% rename from repo-scripts/prune-dts/new-tests/data-connect.input.d.ts rename to repo-scripts/prune-dts/tests/data-connect.input.d.ts diff --git a/repo-scripts/prune-dts/new-tests/data-connect.output.d.ts b/repo-scripts/prune-dts/tests/data-connect.output.d.ts similarity index 100% rename from repo-scripts/prune-dts/new-tests/data-connect.output.d.ts rename to repo-scripts/prune-dts/tests/data-connect.output.d.ts diff --git a/repo-scripts/prune-dts/new-tests/database.input.d.ts b/repo-scripts/prune-dts/tests/database.input.d.ts similarity index 100% rename from repo-scripts/prune-dts/new-tests/database.input.d.ts rename to repo-scripts/prune-dts/tests/database.input.d.ts diff --git a/repo-scripts/prune-dts/new-tests/database.output.d.ts b/repo-scripts/prune-dts/tests/database.output.d.ts similarity index 100% rename from repo-scripts/prune-dts/new-tests/database.output.d.ts rename to repo-scripts/prune-dts/tests/database.output.d.ts diff --git a/repo-scripts/prune-dts/tests/firestore.input.d.ts b/repo-scripts/prune-dts/tests/firestore.input.d.ts index aa71ccffaf0..a69b8be42de 100644 --- a/repo-scripts/prune-dts/tests/firestore.input.d.ts +++ b/repo-scripts/prune-dts/tests/firestore.input.d.ts @@ -1,48 +1,17 @@ /** - * @license - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Cloud Firestore * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * @packageDocumentation */ + import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; import { FirebaseApp } from '@firebase/app'; -import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; -import { _FirebaseService } from '@firebase/app'; +import { FirebaseError } from '@firebase/util'; import { LogLevelString as LogLevel } from '@firebase/logger'; -import { Provider } from '@firebase/component'; import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; -/** - * Converts Firestore's internal types to the JavaScript types that we expose - * to the user. - */ -declare abstract class AbstractUserDataWriter { - convertValue( - value: Value, - serverTimestampBehavior?: ServerTimestampBehavior - ): unknown; - private convertObject; - private convertGeoPoint; - private convertArray; - private convertServerTimestamp; - private convertTimestamp; - protected convertDocumentKey( - name: string, - expectedDatabaseId: DatabaseId - ): DocumentKey; - protected abstract convertReference(name: string): unknown; - protected abstract convertBytes(bytes: ByteString): unknown; -} +/* Excluded from this release type: AbstractUserDataWriter */ /** * Describes a map whose keys are active target ids. We do not care about the type of the @@ -56,22 +25,171 @@ declare type ActiveTargets = SortedMap; * * @param reference - A reference to the collection to add this document to. * @param data - An Object containing the data for the new document. - * @returns A Promise resolved with a `DocumentReference` pointing to the + * @returns A `Promise` resolved with a `DocumentReference` pointing to the * newly created document after it has been written to the backend (Note that it * won't resolve while you're offline). */ -export declare function addDoc( - reference: CollectionReference, - data: T -): Promise>; +export declare function addDoc( + reference: CollectionReference, + data: WithFieldValue +): Promise>; + +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys< + Prefix extends string, + T extends Record +> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; + +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + readonly _internalFieldPath?: _FieldPath | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = 'AggregateField'; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /* Excluded from this release type: __constructor */ +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual( + left: AggregateField, + right: AggregateField +): boolean; + +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = + | ReturnType + | ReturnType + | ReturnType; + +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot< + AggregateSpecType extends AggregateSpec, + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = 'AggregateQuerySnapshot'; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor( + query: Query, + _userDataWriter: AbstractUserDataWriter, + _data: ApiClientObjectMap + ); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual< + AggregateSpecType extends AggregateSpec, + AppModelType, + DbModelType extends DocumentData +>( + left: AggregateQuerySnapshot, + right: AggregateQuerySnapshot +): boolean; + +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} + +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; + +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and( + ...queryConstraints: QueryFilterConstraint[] +): QueryCompositeFilterConstraint; declare interface ApiClientObjectMap { [k: string]: T; } +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply( + query: Query + ): Query; +} + /** * Returns a special value that can be used with {@link (setDoc:1)} or {@link - * updateDoc} that tells the server to remove the given elements from any + * updateDoc:1} that tells the server to remove the given elements from any * array value that already exists on the server. All instances of each element * specified will be removed from the array. If the field being modified is not * already an array it will be overwritten with an empty array. @@ -83,8 +201,8 @@ declare interface ApiClientObjectMap { export declare function arrayRemove(...elements: unknown[]): FieldValue; /** - * Returns a special value that can be used with {@link setDoc} or {@link - * updateDoc} that tells the server to union the given elements with any array + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array * value that already exists on the server. Each specified element that doesn't * already exist in the array will be added to the end. If the field being * modified is not already an array it will be overwritten with an array @@ -114,8 +232,12 @@ declare interface AsyncQueue { * Initialize the shutdown of this queue. Once this method is called, the * only possible way to request running an operation is through * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. */ - enterRestrictedMode(): void; + enterRestrictedMode(purgeExistingTasks?: boolean): void; /** * Adds a new operation to the queue. Returns a promise that will be resolved * when the promise returned by the new operation is (with its value). @@ -149,6 +271,19 @@ declare interface AsyncQueue { verifyOperationInProgress(): void; } +/* Excluded from this release type: AuthTokenFactory */ + +/* Excluded from this release type: _AutoId */ + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average( + field: string | FieldPath +): AggregateField; + /** * Path represents an ordered sequence of string segments. */ @@ -232,8 +367,8 @@ declare type BatchId = number; */ declare class Bound { readonly position: Value[]; - readonly before: boolean; - constructor(position: Value[], before: boolean); + readonly inclusive: boolean; + constructor(position: Value[], inclusive: boolean); } /** @@ -319,9 +454,9 @@ declare interface BundleMetadata_2 { * An immutable object representing an array of bytes. */ export declare class Bytes { - _byteString: ByteString; + _byteString: _ByteString; /** @hideconstructor */ - constructor(byteString: ByteString); + constructor(byteString: _ByteString); /** * Creates a new `Bytes` object from the given Base64 string, converting it to * bytes. @@ -362,50 +497,17 @@ export declare class Bytes { isEqual(other: Bytes): boolean; } -/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Immutable class that represents a "proto" byte string. - * - * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when - * sent on the wire. This class abstracts away this differentiation by holding - * the proto byte string in a common class that must be converted into a string - * before being sent as a proto. - */ -declare class ByteString { - private readonly binaryString; - static readonly EMPTY_BYTE_STRING: ByteString; - private constructor(); - static fromBase64String(base64: string): ByteString; - static fromUint8Array(array: Uint8Array): ByteString; - toBase64(): string; - toUint8Array(): Uint8Array; - approximateByteSize(): number; - compareTo(other: ByteString): number; - isEqual(other: ByteString): boolean; -} +/* Excluded from this release type: _ByteString */ /** * Constant used to indicate the LRU garbage collection should be disabled. * Set this value as the `cacheSizeBytes` on the settings passed to the - * `Firestore` instance. + * {@link Firestore} instance. */ export declare const CACHE_SIZE_UNLIMITED = -1; +/* Excluded from this release type: _cast */ + declare const enum ChangeType { Added = 0, Removed = 1, @@ -413,14 +515,31 @@ declare const enum ChangeType { Metadata = 3 } +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record< + string, + unknown +> + ? AddPrefixToKeys> + : never; + /** * Clears the persistent storage. This includes pending writes and cached * documents. * - * Must be called while the `Firestore` instance is not started (after the app is + * Must be called while the {@link Firestore} instance is not started (after the app is * terminated or when the app is first initialized). On startup, this function * must be called before other functions (other than {@link - * initializeFirestore} or {@link getFirestore})). If the `Firestore` + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} * instance is still running, the promise will be rejected with the error code * of `failed-precondition`. * @@ -431,12 +550,12 @@ declare const enum ChangeType { * to the disclosure of cached data in between user sessions, we strongly * recommend not enabling persistence at all. * - * @param firestore - The `Firestore` instance to clear persistence for. - * @returns A promise that is resolved when the persistent storage is + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is * cleared. Otherwise, the promise is rejected with an error. */ export declare function clearIndexedDbPersistence( - firestore: FirebaseFirestore + firestore: Firestore ): Promise; /** @@ -448,7 +567,7 @@ declare type ClientId = string; * Gets a `CollectionReference` instance that refers to the collection at * the specified absolute path. * - * @param firestore - A reference to the root Firestore instance. + * @param firestore - A reference to the root `Firestore` instance. * @param path - A slash-separated path to a collection. * @param pathSegments - Additional path segments to apply relative to the first * argument. @@ -457,10 +576,10 @@ declare type ClientId = string; * @returns The `CollectionReference` instance. */ export declare function collection( - firestore: FirebaseFirestore_2, + firestore: Firestore_2, path: string, ...pathSegments: string[] -): CollectionReference; +): CollectionReference; /** * Gets a `CollectionReference` instance that refers to a subcollection of @@ -474,11 +593,14 @@ export declare function collection( * to a collection. * @returns The `CollectionReference` instance. */ -export declare function collection( - reference: CollectionReference, +export declare function collection< + AppModelType, + DbModelType extends DocumentData +>( + reference: CollectionReference, path: string, ...pathSegments: string[] -): CollectionReference; +): CollectionReference; /** * Gets a `CollectionReference` instance that refers to a subcollection of @@ -492,41 +614,47 @@ export declare function collection( * to a collection. * @returns The `CollectionReference` instance. */ -export declare function collection( - reference: DocumentReference, +export declare function collection< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, path: string, ...pathSegments: string[] -): CollectionReference; +): CollectionReference; /** * Creates and returns a new `Query` instance that includes all documents in the * database that are contained in a collection or subcollection with the * given `collectionId`. * - * @param firestore - A reference to the root Firestore instance. + * @param firestore - A reference to the root `Firestore` instance. * @param collectionId - Identifies the collections to query over. Every * collection or subcollection with this ID as the last segment of its path * will be included. Cannot contain a slash. * @returns The created `Query`. */ export declare function collectionGroup( - firestore: FirebaseFirestore_2, + firestore: Firestore_2, collectionId: string -): Query; +): Query; /** * A `CollectionReference` object can be used for adding documents, getting - * document references, and querying for documents (using {@link query}). + * document references, and querying for documents (using {@link (query:1)}). */ -export declare class CollectionReference extends Query { - readonly firestore: FirebaseFirestore_2; - readonly _path: ResourcePath; +export declare class CollectionReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> extends Query { + readonly _path: _ResourcePath; + /** The type of this Firestore reference. */ readonly type = 'collection'; /** @hideconstructor */ constructor( - firestore: FirebaseFirestore_2, - converter: FirestoreDataConverter_2 | null, - _path: ResourcePath + firestore: Firestore_2, + converter: FirestoreDataConverter_2 | null, + _path: _ResourcePath ); /** The collection's identifier. */ get id(): string; @@ -539,19 +667,33 @@ export declare class CollectionReference extends Query { * A reference to the containing `DocumentReference` if this is a * subcollection. If this isn't a subcollection, the reference is null. */ - get parent(): DocumentReference | null; + get parent(): DocumentReference | null; /** - * Applies a custom data converter to this CollectionReference, allowing you + * Applies a custom data converter to this `CollectionReference`, allowing you * to use your own custom model objects with Firestore. When you call {@link * addDoc} with the returned `CollectionReference` instance, the provided - * converter will convert between Firestore data and your custom type `U`. + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. * * @param converter - Converts objects to and from Firestore. - * @returns A `CollectionReference` that uses the provided converter. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData + >( + converter: FirestoreDataConverter_2 + ): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. */ - withConverter( - converter: FirestoreDataConverter_2 - ): CollectionReference; + withConverter( + converter: null + ): CollectionReference; } /** @@ -575,26 +717,71 @@ declare type Comparator = (key1: K, key2: K) => number; declare interface ComponentConfiguration { asyncQueue: AsyncQueue; databaseInfo: DatabaseInfo; - credentials: CredentialsProvider; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; clientId: ClientId; initialUser: User; maxConcurrentLimboResolutions: number; } -declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND'; +declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; + +declare const enum CompositeOperator { + OR = 'or', + AND = 'and' +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator( + firestore: Firestore_2, + host: string, + port: number, + options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + } +): void; + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; /** * A Listener for credential change events. The listener should fetch a new * token and may need to invalidate other state if the current user has also * changed. */ -declare type CredentialChangeListener = (user: User) => void; +declare type CredentialChangeListener = (credential: T) => Promise; /** * Provides methods for getting the uid and token for the current user and * listening for changes. */ -declare interface CredentialsProvider { +declare interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start( + asyncQueue: AsyncQueue, + changeListener: CredentialChangeListener + ): void; /** Requests a token for the current user. */ getToken(): Promise; /** @@ -602,14 +789,7 @@ declare interface CredentialsProvider { * force-refresh the token. */ invalidateToken(): void; - /** - * Specifies a listener to be notified of credential changes - * (sign-in / sign-out, token changes). It is immediately called once with the - * initial user. - */ - setChangeListener(changeListener: CredentialChangeListener): void; - /** Removes the previously-set change listener. */ - removeChangeListener(): void; + shutdown(): void; } /** Settings for private credentials */ @@ -617,14 +797,7 @@ declare type CredentialsSettings = | FirstPartyCredentialsSettings | ProviderCredentialsSettings; -/** Represents the database ID a Firestore client is associated with. */ -declare class DatabaseId { - readonly projectId: string; - readonly database: string; - constructor(projectId: string, database?: string); - get isDefaultDatabase(): boolean; - isEqual(other: {}): boolean; -} +/* Excluded from this release type: _DatabaseId */ /** * @license @@ -643,17 +816,21 @@ declare class DatabaseId { * limitations under the License. */ declare class DatabaseInfo { - readonly databaseId: DatabaseId; + readonly databaseId: _DatabaseId; + readonly appId: string; readonly persistenceKey: string; readonly host: string; readonly ssl: boolean; readonly forceLongPolling: boolean; readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; /** * Constructs a DatabaseInfo using the provided host, databaseId and * persistenceKey. * * @param databaseId - The database to use. + * @param appId - The Firebase App Id. * @param persistenceKey - A unique identifier for this Firestore's local * storage (used in conjunction with the databaseId). * @param host - The Firestore backend host to connect to. @@ -662,14 +839,20 @@ declare class DatabaseInfo { * when using WebChannel as the network transport. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest */ constructor( - databaseId: DatabaseId, + databaseId: _DatabaseId, + appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, - autoDetectLongPolling: boolean + autoDetectLongPolling: boolean, + longPollingOptions: ExperimentalLongPollingOptions, + useFetchStreams: boolean ); } @@ -680,8 +863,11 @@ declare class DatabaseInfo { */ declare abstract class Datastore { abstract terminate(): void; + abstract serializer: JsonProtoSerializer; } +/* Excluded from this release type: _debugAssert */ + /** * Represents an operation scheduled to be run in the future on an AsyncQueue. * @@ -702,6 +888,7 @@ declare class DelayedOperation implements PromiseLike { private timerHandle; private readonly deferred; private constructor(); + get promise(): Promise; /** * Creates and returns a DelayedOperation that has been scheduled to be * executed on the provided asyncQueue after the provided delayMs. @@ -755,6 +942,16 @@ declare class DelayedOperation implements PromiseLike { private clearTimeout; } +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +export declare function deleteAllPersistentCacheIndexes( + indexManager: PersistentCacheIndexManager +): void; + /** * Deletes the document referred to by the specified `DocumentReference`. * @@ -762,13 +959,14 @@ declare class DelayedOperation implements PromiseLike { * @returns A Promise resolved once the document has been successfully * deleted from the backend (note that it won't resolve while you're offline). */ -export declare function deleteDoc( - reference: DocumentReference -): Promise; +export declare function deleteDoc< + AppModelType, + DbModelType extends DocumentData +>(reference: DocumentReference): Promise; /** - * Returns a sentinel for use with {@link updateDoc} or - * {@link setDoc} with `{merge: true}` to mark a field for deletion. + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. */ export declare function deleteField(): FieldValue; @@ -786,17 +984,24 @@ declare const enum Direction { * `getDoc()` or `getDocs()` calls will return results from cache, and any write * operations will be queued until the network is restored. * - * @returns A promise that is resolved once the network has been disabled. + * @returns A `Promise` that is resolved once the network has been disabled. */ -export declare function disableNetwork( - firestore: FirebaseFirestore -): Promise; +export declare function disableNetwork(firestore: Firestore): Promise; + +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +export declare function disablePersistentCacheIndexAutoCreation( + indexManager: PersistentCacheIndexManager +): void; /** * Gets a `DocumentReference` instance that refers to the document at the * specified absolute path. * - * @param firestore - A reference to the root Firestore instance. + * @param firestore - A reference to the root `Firestore` instance. * @param path - A slash-separated path to a document. * @param pathSegments - Additional path segments that will be applied relative * to the first argument. @@ -805,10 +1010,10 @@ export declare function disableNetwork( * @returns The `DocumentReference` instance. */ export declare function doc( - firestore: FirebaseFirestore_2, + firestore: Firestore_2, path: string, ...pathSegments: string[] -): DocumentReference; +): DocumentReference; /** * Gets a `DocumentReference` instance that refers to a document within @@ -825,11 +1030,11 @@ export declare function doc( * a document. * @returns The `DocumentReference` instance. */ -export declare function doc( - reference: CollectionReference, +export declare function doc( + reference: CollectionReference, path?: string, ...pathSegments: string[] -): DocumentReference; +): DocumentReference; /** * Gets a `DocumentReference` instance that refers to a document within @@ -843,45 +1048,83 @@ export declare function doc( * a document. * @returns The `DocumentReference` instance. */ -export declare function doc( - reference: DocumentReference, +export declare function doc( + reference: DocumentReference, path: string, ...pathSegments: string[] -): DocumentReference; +): DocumentReference; /** * Represents a document in Firestore with a key, version, data and whether the * data has local mutations applied to it. */ -declare class Document_2 extends MaybeDocument { - private readonly objectValue; +declare interface Document_2 { + /** The key for this document */ + readonly key: _DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ readonly hasCommittedMutations: boolean; - constructor( - key: DocumentKey, - version: SnapshotVersion, - objectValue: ObjectValue, - options: DocumentOptions - ); - field(path: FieldPath_2): Value | null; - data(): ObjectValue; - toProto(): { - mapValue: MapValue; - }; - isEqual(other: MaybeDocument | null | undefined): boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; toString(): string; - get hasPendingWrites(): boolean; } /** * A `DocumentChange` represents a change to the documents matching a query. * It contains the document affected and the type of change that occurred. */ -export declare interface DocumentChange { +export declare 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; + 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 @@ -908,10 +1151,11 @@ declare type DocumentComparator = ( ) => number; /** - * Document data (for use with {@link setDoc}) consists of fields mapped to + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to * values. */ export declare interface DocumentData { + /** A mapping between a field and its value. */ [field: string]: any; } @@ -921,33 +1165,90 @@ export declare interface DocumentData { */ export declare function documentId(): FieldPath; -declare class DocumentKey { - readonly path: ResourcePath; - constructor(path: ResourcePath); - static fromPath(path: string): DocumentKey; - static fromName(name: string): DocumentKey; - /** Returns true if the document is in the specified collectionId. */ - hasCollectionId(collectionId: string): boolean; - isEqual(other: DocumentKey | null): boolean; - toString(): string; - static comparator(k1: DocumentKey, k2: DocumentKey): number; - static isDocumentKey(path: ResourcePath): boolean; - /** - * Creates and returns a new document key with the given segments. - * - * @param segments - The segments of the path to the document - * @returns A new instance of DocumentKey - */ - static fromSegments(segments: string[]): DocumentKey; -} +/* Excluded from this release type: _DocumentKey */ + +declare type DocumentKeyMap = ObjectMap<_DocumentKey, T>; -declare type DocumentKeySet = SortedSet; +declare type DocumentKeySet = SortedSet<_DocumentKey>; -declare type DocumentMap = SortedMap; +declare type DocumentMap = SortedMap<_DocumentKey, Document_2>; -declare interface DocumentOptions { - hasLocalMutations?: boolean; - hasCommittedMutations?: boolean; +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +declare interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay( + transaction: PersistenceTransaction, + key: _DocumentKey + ): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays( + transaction: PersistenceTransaction, + keys: _DocumentKey[] + ): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays( + transaction: PersistenceTransaction, + largestBatchId: number, + overlays: MutationMap + ): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId( + transaction: PersistenceTransaction, + documentKeys: DocumentKeySet, + batchId: number + ): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection( + transaction: PersistenceTransaction, + collection: _ResourcePath, + sinceBatchId: number + ): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup( + transaction: PersistenceTransaction, + collectionGroup: string, + sinceBatchId: number, + count: number + ): PersistencePromise; } /** @@ -955,23 +1256,35 @@ declare interface DocumentOptions { * and can be used to write, read, or listen to the location. The document at * the referenced location may or may not exist. */ -export declare class DocumentReference { - readonly _converter: FirestoreDataConverter_2 | null; - readonly _key: DocumentKey; +export declare class DocumentReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter_2< + AppModelType, + DbModelType + > | null; + readonly _key: _DocumentKey; /** The type of this Firestore reference. */ readonly type = 'document'; /** - * The {@link FirebaseFirestore} the document is in. + * The {@link Firestore} instance the document is in. * This is useful for performing transactions, for example. */ - readonly firestore: FirebaseFirestore_2; + readonly firestore: Firestore_2; /** @hideconstructor */ constructor( - firestore: FirebaseFirestore_2, - _converter: FirestoreDataConverter_2 | null, - _key: DocumentKey + firestore: Firestore_2, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter_2 | null, + _key: _DocumentKey ); - get _path(): ResourcePath; + get _path(): _ResourcePath; /** * The document's identifier within its collection. */ @@ -984,20 +1297,31 @@ export declare class DocumentReference { /** * The collection this `DocumentReference` belongs to. */ - get parent(): CollectionReference; + get parent(): CollectionReference; /** * Applies a custom data converter to this `DocumentReference`, allowing you * to use your own custom model objects with Firestore. When you call {@link - * setDoc}, {@link getDoc}, etc. with the returned `DocumentReference` - * instance, the provided converter will convert between Firestore data and - * your custom type `U`. + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. * * @param converter - Converts objects to and from Firestore. - * @returns A `DocumentReference` that uses the provided converter. + * @returns A `DocumentReference` that uses the provided converter. */ - withConverter( - converter: FirestoreDataConverter_2 - ): DocumentReference; + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData + >( + converter: FirestoreDataConverter_2 + ): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; } /** @@ -1017,8 +1341,8 @@ declare class DocumentSet { private sortedSet; /** The default ordering is by key if the comparator is omitted */ constructor(comp?: DocumentComparator); - has(key: DocumentKey): boolean; - get(key: DocumentKey): Document_2 | null; + has(key: _DocumentKey): boolean; + get(key: _DocumentKey): Document_2 | null; first(): Document_2 | null; last(): Document_2 | null; isEmpty(): boolean; @@ -1026,14 +1350,14 @@ declare class DocumentSet { * Returns the index of the provided key in the document set, or -1 if the * document key is not present in the set; */ - indexOf(key: DocumentKey): number; + indexOf(key: _DocumentKey): number; get size(): number; /** Iterates documents in order defined by "comparator" */ forEach(cb: (doc: Document_2) => void): void; /** Inserts or updates a document with the same key */ add(doc: Document_2): DocumentSet; /** Deletes a document with a given key */ - delete(key: DocumentKey): DocumentSet; + delete(key: _DocumentKey): DocumentSet; isEqual(other: DocumentSet | null | undefined): boolean; toString(): string; private copy; @@ -1049,9 +1373,10 @@ declare class DocumentSet { * explicitly verify a document's existence. */ export declare class DocumentSnapshot< - T = DocumentData -> extends DocumentSnapshot_2 { - readonly _firestore: FirebaseFirestore; + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> extends DocumentSnapshot_2 { + readonly _firestore: Firestore; private readonly _firestoreImpl; /** * Metadata about the `DocumentSnapshot`, including information about its @@ -1060,23 +1385,22 @@ export declare class DocumentSnapshot< readonly metadata: SnapshotMetadata; /** @hideconstructor protected */ constructor( - _firestore: FirebaseFirestore, + _firestore: Firestore, userDataWriter: AbstractUserDataWriter, - key: DocumentKey, + key: _DocumentKey, document: Document_2 | null, metadata: SnapshotMetadata, - converter: UntypedFirestoreDataConverter | null + converter: UntypedFirestoreDataConverter | null ); /** - * Property of the `DocumentSnapshot` that signals whether or not the data - * exists. True if the document exists. + * Returns whether or not the data exists. True if the document exists. */ - exists(): this is QueryDocumentSnapshot; + exists(): this is QueryDocumentSnapshot; /** * Retrieves all fields in the document as an `Object`. Returns `undefined` if * the document doesn't exist. * - * By default, `FieldValue.serverTimestamp()` values that have not yet been + * By default, `serverTimestamp()` values that have not yet been * set to their final value will be returned as `null`. You can override * this by passing an options object. * @@ -1086,12 +1410,12 @@ export declare class DocumentSnapshot< * @returns An `Object` containing all fields in the document or `undefined` if * the document doesn't exist. */ - data(options?: SnapshotOptions): T | undefined; + data(options?: SnapshotOptions): AppModelType | undefined; /** * Retrieves the field specified by `fieldPath`. Returns `undefined` if the * document or field doesn't exist. * - * By default, a `FieldValue.serverTimestamp()` that has not yet been set to + * By default, a `serverTimestamp()` that has not yet been set to * its final value will be returned as `null`. You can override this by * passing an options object. * @@ -1115,32 +1439,35 @@ export declare class DocumentSnapshot< * access will return 'undefined'. You can use the `exists()` method to * explicitly verify a document's existence. */ -declare class DocumentSnapshot_2 { - _firestore: FirebaseFirestore_2; +declare class DocumentSnapshot_2< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + _firestore: Firestore_2; _userDataWriter: AbstractUserDataWriter; - _key: DocumentKey; + _key: _DocumentKey; _document: Document_2 | null; - _converter: UntypedFirestoreDataConverter | null; + _converter: UntypedFirestoreDataConverter | null; /** @hideconstructor protected */ constructor( - _firestore: FirebaseFirestore_2, + _firestore: Firestore_2, _userDataWriter: AbstractUserDataWriter, - _key: DocumentKey, + _key: _DocumentKey, _document: Document_2 | null, - _converter: UntypedFirestoreDataConverter | null + _converter: UntypedFirestoreDataConverter | null ); /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id(): string; /** * The `DocumentReference` for the document included in the `DocumentSnapshot`. */ - get ref(): DocumentReference; + get ref(): DocumentReference; /** * Signals whether or not the document at the snapshot's location exists. * * @returns true if the document exists. */ - exists(): this is QueryDocumentSnapshot_2; + exists(): this is QueryDocumentSnapshot_2; /** * Retrieves all fields in the document as an `Object`. Returns `undefined` if * the document doesn't exist. @@ -1148,7 +1475,7 @@ declare class DocumentSnapshot_2 { * @returns An `Object` containing all fields in the document or `undefined` * if the document doesn't exist. */ - data(): T | undefined; + data(): AppModelType | undefined; /** * Retrieves the field specified by `fieldPath`. Returns `undefined` if the * document or field doesn't exist. @@ -1161,38 +1488,49 @@ declare class DocumentSnapshot_2 { get(fieldPath: string | FieldPath): any; } -declare type DocumentVersionMap = SortedMap; +declare type DocumentVersionMap = SortedMap<_DocumentKey, SnapshotVersion>; declare interface DocumentViewChange { type: ChangeType; doc: Document_2; } +/* Excluded from this release type: _EmptyAppCheckTokenProvider */ + +/* Excluded from this release type: _EmptyAuthCredentialsProvider */ +export { EmulatorMockTokenOptions }; + /** * Attempts to enable persistent storage, if possible. * - * Must be called before any other functions (other than - * {@link initializeFirestore}, {@link getFirestore} or - * {@link clearIndexedDbPersistence}. + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. * - * If this fails, `enableIndexedDbPersistence()` will reject the promise it - * returns. Note that even after this failure, the `Firestore` instance will - * remain usable, however offline persistence will be disabled. + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. * - * There are several reasons why this can fail, which can be identified by - * the `code` on the error. + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. * - * * failed-precondition: The app is already open in another browser tab. - * * unimplemented: The browser is incompatible with the offline - * persistence implementation. + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. * - * @param firestore - The `Firestore` instance to enable persistence for. + * @param firestore - The {@link Firestore} instance to enable persistence for. * @param persistenceSettings - Optional settings object to configure * persistence. - * @returns A promise that represents successfully enabling persistent storage. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. */ export declare function enableIndexedDbPersistence( - firestore: FirebaseFirestore, + firestore: Firestore, persistenceSettings?: PersistenceSettings ): Promise; @@ -1202,83 +1540,103 @@ export declare function enableIndexedDbPersistence( * shared execution of queries and latency-compensated local document updates * across all connected instances. * - * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise - * it returns. Note that even after this failure, the `Firestore` instance will - * remain usable, however offline persistence will be disabled. - * - * There are several reasons why this can fail, which can be identified by - * the `code` on the error. + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. * * * failed-precondition: The app is already open in another browser tab and * multi-tab is not enabled. - * * unimplemented: The browser is incompatible with the offline - * persistence implementation. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. * - * @param firestore - The `Firestore` instance to enable persistence for. - * @returns A promise that represents successfully enabling persistent + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. */ export declare function enableMultiTabIndexedDbPersistence( - firestore: FirebaseFirestore + firestore: Firestore ): Promise; /** - * Re-enables use of the network for this Firestore instance after a prior + * Re-enables use of the network for this {@link Firestore} instance after a prior * call to {@link disableNetwork}. * - * @returns A promise that is resolved once the network has been enabled. + * @returns A `Promise` that is resolved once the network has been enabled. */ -export declare function enableNetwork( - firestore: FirebaseFirestore -): Promise; +export declare function enableNetwork(firestore: Firestore): Promise; + +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +export declare function enablePersistentCacheIndexAutoCreation( + indexManager: PersistentCacheIndexManager +): void; /** - * Creates a `QueryConstraint` that modifies the result set to end at the - * provided document (inclusive). The end position is relative to the order of - * the query. The document must contain all of the fields provided in the + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the * orderBy of the query. * * @param snapshot - The snapshot of the document to end at. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ -export declare function endAt( - snapshot: DocumentSnapshot_2 -): QueryConstraint; +export declare function endAt( + snapshot: DocumentSnapshot_2 +): QueryEndAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to end at the - * provided fields relative to the order of the query. The order of the field + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field * values must match the order of the order by clauses of the query. * * @param fieldValues - The field values to end this query at, in order * of the query's order by. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ -export declare function endAt(...fieldValues: unknown[]): QueryConstraint; +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to end before the - * provided document (exclusive). The end position is relative to the order of - * the query. The document must contain all of the fields provided in the - * orderBy of the query. + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. * * @param snapshot - The snapshot of the document to end before. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ -export declare function endBefore( - snapshot: DocumentSnapshot_2 -): QueryConstraint; +export declare function endBefore< + AppModelType, + DbModelType extends DocumentData +>( + snapshot: DocumentSnapshot_2 +): QueryEndAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to end before the - * provided fields relative to the order of the query. The order of the field - * values must match the order of the order by clauses of the query. + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. * * @param fieldValues - The field values to end this query before, in order * of the query's order by. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ -export declare function endBefore(...fieldValues: unknown[]): QueryConstraint; +export declare function endBefore( + ...fieldValues: unknown[] +): QueryEndAtConstraint; + +/* Excluded from this release type: ensureFirestoreConfigured */ declare interface Entry { key: K; @@ -1295,27 +1653,139 @@ declare interface Entry { * allows users to tree-shake the Watch logic. */ declare interface EventManager { - onListen?: (query: Query_2) => Promise; - onUnlisten?: (query: Query_2) => Promise; + onListen?: ( + query: Query_2, + enableRemoteListen: boolean + ) => Promise; + onUnlisten?: (query: Query_2, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query_2) => Promise; + onLastRemoteStoreUnlisten?: (query: Query_2) => Promise; + terminate(): void; } -declare type FieldFilterOp = - | 'OPERATOR_UNSPECIFIED' - | 'LESS_THAN' - | 'LESS_THAN_OR_EQUAL' - | 'GREATER_THAN' - | 'GREATER_THAN_OR_EQUAL' - | 'EQUAL' - | 'NOT_EQUAL' - | 'ARRAY_CONTAINS' - | 'IN' - | 'ARRAY_CONTAINS_ANY' - | 'NOT_IN'; +/* Excluded from this release type: executeWrite */ /** - * Provides a set of fields that can be used to partially patch a document. - * FieldMask is used in conjunction with ObjectValue. - * Examples: + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +export declare interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} + +declare class FieldFilter extends Filter { + readonly field: _FieldPath; + readonly op: Operator; + readonly value: Value; + protected constructor(field: _FieldPath, op: Operator, value: Value); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: _FieldPath, op: Operator, value: Value): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document_2): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} + +declare type FieldFilterOp = + | 'OPERATOR_UNSPECIFIED' + | 'LESS_THAN' + | 'LESS_THAN_OR_EQUAL' + | 'GREATER_THAN' + | 'GREATER_THAN_OR_EQUAL' + | 'EQUAL' + | 'NOT_EQUAL' + | 'ARRAY_CONTAINS' + | 'IN' + | 'ARRAY_CONTAINS_ANY' + | 'NOT_IN'; + +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState + ); +} + +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: * foo - Overwrites foo entirely with the provided value. If foo is not * present in the companion ObjectValue, the field is deleted. * foo.bar - Overwrites only the field bar of the object foo. @@ -1323,15 +1793,21 @@ declare type FieldFilterOp = * containing foo */ declare class FieldMask { - readonly fields: FieldPath_2[]; - constructor(fields: FieldPath_2[]); + readonly fields: _FieldPath[]; + constructor(fields: _FieldPath[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: _FieldPath[]): FieldMask; /** * Verifies that `fieldPath` is included by at least one field in this field * mask. * * This is an O(n) operation, where `n` is the size of the field mask. */ - covers(fieldPath: FieldPath_2): boolean; + covers(fieldPath: _FieldPath): boolean; isEqual(other: FieldMask): boolean; } @@ -1345,9 +1821,9 @@ declare class FieldMask { */ export declare class FieldPath { /** Internal representation of a Firestore field path. */ - readonly _internalPath: FieldPath_2; + readonly _internalPath: _FieldPath; /** - * Creates a FieldPath from the provided field names. If more than one field + * 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. @@ -1362,47 +1838,13 @@ export declare class FieldPath { isEqual(other: FieldPath): boolean; } -/** A dot-separated path for navigating sub-objects within a document. */ -declare class FieldPath_2 extends BasePath { - protected construct( - segments: string[], - offset?: number, - length?: number - ): FieldPath_2; - /** - * Returns true if the string could be used as a segment in a field path - * without escaping. - */ - private static isValidIdentifier; - canonicalString(): string; - toString(): string; - /** - * Returns true if this field references the key of a document. - */ - isKeyField(): boolean; - /** - * The field designating the key of a document. - */ - static keyField(): FieldPath_2; - /** - * Parses a field string from the given server-formatted string. - * - * - Splitting the empty string is not allowed (for now at least). - * - Empty segments within the string (e.g. if there are two consecutive - * separators) are not allowed. - * - * TODO(b/37244157): we should make this more strict. Right now, it allows - * non-identifier path components, even if they aren't escaped. - */ - static fromServerFormat(path: string): FieldPath_2; - static emptyPath(): FieldPath_2; -} +/* Excluded from this release type: _FieldPath */ /** A field path and the TransformOperation to perform upon it. */ declare class FieldTransform { - readonly field: FieldPath_2; + readonly field: _FieldPath; readonly transform: TransformOperation; - constructor(field: FieldPath_2, transform: TransformOperation); + constructor(field: _FieldPath, transform: TransformOperation); } declare type FieldTransformSetToServerValue = @@ -1417,62 +1859,87 @@ export declare abstract class FieldValue { _methodName: string; /** * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor */ constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ abstract isEqual(other: FieldValue): boolean; abstract _toFieldTransform(context: ParseContext): FieldTransform | null; } declare abstract class Filter { abstract matches(doc: Document_2): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; } +/* Excluded from this release type: _FirebaseService */ + /** * The Cloud Firestore service interface. * - * Do not call this constructor directly. Instead, use {@link getFirestore}. + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. */ -export declare class FirebaseFirestore extends FirebaseFirestore_2 { - readonly _queue: AsyncQueue; +export declare class Firestore extends Firestore_2 { + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + _queue: AsyncQueue; readonly _persistenceKey: string; _firestoreClient: FirestoreClient | undefined; + _componentsProvider?: { + _offline: OfflineComponentProviderFactory; + _online: OnlineComponentProviderFactory; + }; /** @hideconstructor */ constructor( - databaseIdOrApp: DatabaseId | FirebaseApp, - authProvider: Provider + authCredentialsProvider: CredentialsProvider, + appCheckCredentialsProvider: CredentialsProvider, + databaseId: _DatabaseId, + app?: FirebaseApp ); - _terminate(): Promise; + protected _terminate(): Promise; } /** * The Cloud Firestore service interface. * - * Do not call this constructor directly. Instead, use {@link getFirestore}. + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. */ -declare class FirebaseFirestore_2 implements FirestoreService { - readonly _databaseId: DatabaseId; +declare class Firestore_2 implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: _DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; readonly _persistenceKey: string; - _credentials: CredentialsProvider; private _settings; private _settingsFrozen; - private _terminateTask?; - private _app?; + private _terminateTask; /** @hideconstructor */ constructor( - databaseIdOrApp: DatabaseId | FirebaseApp, - authProvider: Provider + _authCredentials: CredentialsProvider, + _appCheckCredentials: CredentialsProvider, + _databaseId: _DatabaseId, + _app?: FirebaseApp | undefined ); /** - * The {@link FirebaseApp} associated with this `Firestore` service + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service * instance. */ get app(): FirebaseApp; get _initialized(): boolean; get _terminated(): boolean; _setSettings(settings: PrivateSettings): void; - _getSettings(): FirestoreSettings; - _freezeSettings(): FirestoreSettings; + _getSettings(): FirestoreSettingsImpl; + _freezeSettings(): FirestoreSettingsImpl; _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON(): object; /** * Terminates all components used by this client. Subclasses can override @@ -1485,12 +1952,13 @@ declare class FirebaseFirestore_2 implements FirestoreService { } /** - * FirestoreClient is a top-level class that constructs and owns all of the - * pieces of the client SDK architecture. It is responsible for creating the - * async queue that is shared by all of the other components in the system. + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // */ declare class FirestoreClient { - private credentials; + private authCredentials; + private appCheckCredentials; /** * Asynchronous queue responsible for all of our internal processing. When * we get incoming work from the user (via public API) or the network @@ -1503,12 +1971,17 @@ declare class FirestoreClient { private databaseInfo; private user; private readonly clientId; - private credentialListener; - private readonly receivedInitialUser; - offlineComponents?: OfflineComponentProvider; - onlineComponents?: OnlineComponentProvider; + private authCredentialListener; + private appCheckCredentialListener; + _uninitializedComponentsProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }; + _offlineComponents?: OfflineComponentProvider; + _onlineComponents?: OnlineComponentProvider; constructor( - credentials: CredentialsProvider, + authCredentials: CredentialsProvider, + appCheckCredentials: CredentialsProvider, /** * Asynchronous queue responsible for all of our internal processing. When * we get incoming work from the user (via public API) or the network @@ -1518,179 +1991,528 @@ declare class FirestoreClient { * an async I/O to complete). */ asyncQueue: AsyncQueue, - databaseInfo: DatabaseInfo + databaseInfo: DatabaseInfo, + componentProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + } ); - getConfiguration(): Promise; - setCredentialChangeListener(listener: (user: User) => void): void; - /** - * Checks that the client has not been terminated. Ensures that other methods on - * this class cannot be called after the client is terminated. - */ - verifyNotTerminated(): void; + get configuration(): ComponentConfiguration; + setCredentialChangeListener(listener: (user: User) => Promise): void; + setAppCheckTokenChangeListener( + listener: (appCheckToken: string, user: User) => Promise + ): void; terminate(): Promise; } /** - * Converter used by `withConverter()` to transform user objects of type `T` - * into Firestore data. + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. * * Using the converter allows you to specify generic type arguments when * storing and retrieving objects from Firestore. * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. * class Post { - * constructor(readonly title: string, readonly author: string) {} + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } * - * 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; * } * - * const postConverter = { - * toFirestore(post: Post): firebase.firestore.DocumentData { - * return {title: post.title, author: post.author}; - * }, - * fromFirestore( - * snapshot: firebase.firestore.QueryDocumentSnapshot, - * options: firebase.firestore.SnapshotOptions - * ): Post { - * const data = snapshot.data(options)!; - * return new Post(data.title, data.author); - * } - * }; + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } * - * const postSnap = await firebase.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 + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } * } * ``` */ -export declare interface FirestoreDataConverter - extends FirestoreDataConverter_2 { - /** - * Called by the Firestore SDK to convert a custom model object of type `T` - * into a plain JavaScript object (suitable for writing directly to the - * Firestore database). To use `set()` with `merge` and `mergeFields`, - * `toFirestore()` must be defined with `Partial`. - */ - toFirestore(modelObject: T): DocumentData; +export declare interface FirestoreDataConverter< + AppModelType, + DbModelType extends DocumentData = DocumentData +> extends FirestoreDataConverter_2 { /** - * Called by the Firestore SDK to convert a custom model object of type `T` - * into a plain JavaScript object (suitable for writing directly to the - * Firestore database). Used with {@link setData}, {@link WriteBatch#set} - * and {@link Transaction#set} with `merge:true` or `mergeFields`. + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. To use `set()` + * with `merge` and `mergeFields`, `toFirestore()` must be defined with + * `PartialWithFieldValue`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore( + modelObject: WithFieldValue + ): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and + * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. */ - toFirestore(modelObject: Partial, options: SetOptions): DocumentData; + toFirestore( + modelObject: PartialWithFieldValue, + options: SetOptions + ): PartialWithFieldValue; /** * Called by the Firestore SDK to convert Firestore data into an object of - * type T. You can access your data by calling: `snapshot.data(options)`. + * type `AppModelType`. You can access your data by calling: + * `snapshot.data(options)`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. * * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. * @param options - The `SnapshotOptions` from the initial call to `data()`. */ fromFirestore( - snapshot: QueryDocumentSnapshot, + snapshot: QueryDocumentSnapshot, options?: SnapshotOptions - ): T; + ): AppModelType; } /** - * Converter used by `withConverter()` to transform user objects of type `T` - * into Firestore data. + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. * * Using the converter allows you to specify generic type arguments when * storing and retrieving objects from Firestore. * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. * class Post { - * constructor(readonly title: string, readonly author: string) {} + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } * - * 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; * } * - * const postConverter = { - * toFirestore(post: Post): firebase.firestore.DocumentData { - * return {title: post.title, author: post.author}; - * }, - * fromFirestore(snapshot: firebase.firestore.QueryDocumentSnapshot): Post { - * const data = snapshot.data(options)!; - * return new Post(data.title, data.author); - * } - * }; + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } * - * const postSnap = await firebase.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 + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } * } * ``` */ -declare interface FirestoreDataConverter_2 { - /** - * Called by the Firestore SDK to convert a custom model object of type `T` - * into a plain JavaScript object (suitable for writing directly to the - * Firestore database). Used with {@link setData}, {@link WriteBatch#set} - * and {@link Transaction#set}. - */ - toFirestore(modelObject: T): DocumentData; - /** - * Called by the Firestore SDK to convert a custom model object of type `T` - * into a plain JavaScript object (suitable for writing directly to the - * Firestore database). Used with {@link setData}, {@link WriteBatch#set} - * and {@link Transaction#set} with `merge:true` or `mergeFields`. +declare interface FirestoreDataConverter_2< + 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`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore( + modelObject: WithFieldValue + ): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. */ - toFirestore(modelObject: Partial, options: SetOptions): DocumentData; + toFirestore( + modelObject: PartialWithFieldValue, + options: SetOptions + ): PartialWithFieldValue; /** * Called by the Firestore SDK to convert Firestore data into an object of - * type T. You can access your data by calling: `snapshot.data()`. + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. * * @param snapshot - A `QueryDocumentSnapshot` containing your data and * metadata. */ - fromFirestore(snapshot: QueryDocumentSnapshot_2): T; + fromFirestore( + snapshot: QueryDocumentSnapshot_2 + ): AppModelType; } /** An error returned by a Firestore operation. */ -export declare class FirestoreError extends Error { +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ readonly message: string; - readonly name: string; + /** The stack of the error. */ readonly stack?: string; /** @hideconstructor */ - constructor(code: FirestoreErrorCode, message: string); + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode, + /** + * A custom error description. + */ + message: string + ); } -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ /** * The set of Firestore status codes. The codes are the same at the ones * exposed by gRPC here: @@ -1748,6 +2570,13 @@ export declare type FirestoreErrorCode = | 'data-loss' | 'unauthenticated'; +/** + * Union type from all supported SDK cache layer. + */ +export declare type FirestoreLocalCache = + | MemoryLocalCache + | PersistentLocalCache; + /** * An interface implemented by FirebaseFirestore that provides compatibility * with the usage in this file. @@ -1755,19 +2584,112 @@ export declare type FirestoreErrorCode = * This interface mainly exists to remove a cyclic dependency. */ declare interface FirestoreService extends _FirebaseService { - _credentials: CredentialsProvider; + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; _persistenceKey: string; - _databaseId: DatabaseId; + _databaseId: _DatabaseId; _terminated: boolean; - _freezeSettings(): FirestoreSettings; + _freezeSettings(): FirestoreSettingsImpl; +} + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface FirestoreSettings extends FirestoreSettings_2 { + /** + * NOTE: This field will be deprecated in a future major release. Use `cache` field + * instead to specify cache size, and other cache configurations. + * + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The size is not a guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` + * and `PersistentLocalCache`, each with different configuration options. + * + * When unspecified, `MemoryLocalCache` will be used by default. + * + * NOTE: setting this field and `cacheSizeBytes` at the same time will throw + * exception during SDK initialization. Instead, using the configuration in + * the `FirestoreLocalCache` object to specify the cache size. + */ + localCache?: FirestoreLocalCache; + /** + * Forces the SDK’s underlying network transport (WebChannel) to use + * long-polling. Each response from the backend will be closed immediately + * after the backend sends data (by default responses are kept open in + * case the backend has more data to send). This avoids incompatibility + * issues with certain proxies, antivirus software, etc. that incorrectly + * buffer traffic indefinitely. Use of this option will cause some + * performance degradation though. + * + * This setting cannot be used with `experimentalAutoDetectLongPolling` and + * may be removed in a future release. If you find yourself using it to + * work around a specific network reliability issue, please tell us about + * it in https://github.com/firebase/firebase-js-sdk/issues/1674. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalForceLongPolling?: boolean; + /** + * Configures the SDK's underlying transport (WebChannel) to automatically + * detect if long-polling should be used. This is very similar to + * `experimentalForceLongPolling`, but only uses long-polling if required. + * + * After having had a default value of `false` since its inception in 2019, + * the default value of this setting was changed in May 2023 to `true` in + * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long + * polling is now enabled by default. To disable it, set this setting to + * `false`, and please open a GitHub issue to share the problems that + * motivated you disabling long-polling auto-detection. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalAutoDetectLongPolling?: boolean; + /** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * These options are only used if `experimentalForceLongPolling` is true or if + * `experimentalAutoDetectLongPolling` is true and the auto-detection + * determined that long-polling was needed. Otherwise, these options have no + * effect. + */ + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; +} + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +declare interface FirestoreSettings_2 { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; } /** * A concrete type describing all the values that can be applied via a - * user-supplied firestore.Settings object. This is a separate type so that + * user-supplied `FirestoreSettings` object. This is a separate type so that * defaults can be supplied and the value can be checked for equality. */ -declare class FirestoreSettings { +declare class FirestoreSettingsImpl { /** The hostname to connect to. */ readonly host: string; /** Whether to use SSL when connecting. */ @@ -1775,10 +2697,13 @@ declare class FirestoreSettings { readonly cacheSizeBytes: number; readonly experimentalForceLongPolling: boolean; readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; credentials?: any; constructor(settings: PrivateSettings); - isEqual(other: FirestoreSettings): boolean; + isEqual(other: FirestoreSettingsImpl): boolean; } declare namespace firestoreV1ApiClientInterfaces { @@ -1861,6 +2786,15 @@ declare namespace firestoreV1ApiClientInterfaces { interface ExistenceFilter { targetId?: number; count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; } interface FieldFilter { field?: FieldReference; @@ -1886,7 +2820,7 @@ declare namespace firestoreV1ApiClientInterfaces { name?: string; collectionId?: string; fields?: IndexField[]; - state?: IndexState; + state?: IndexState_2; } interface IndexField { fieldPath?: string; @@ -1971,6 +2905,40 @@ declare namespace firestoreV1ApiClientInterfaces { readTime?: string; skippedResults?: number; } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } interface Status { code?: number; message?: string; @@ -1997,6 +2965,11 @@ declare namespace firestoreV1ApiClientInterfaces { readTime?: Timestamp_2; targetId?: number; once?: boolean; + expectedCount?: + | number + | { + value: number; + }; } interface TargetChange { targetChangeType?: TargetChangeTargetChangeType; @@ -2053,11 +3026,7 @@ declare namespace firestoreV1ApiClientInterfaces { } } -declare interface FirstPartyCredentialsSettings { - ['type']: 'gapi'; - ['client']: unknown; - ['sessionIndex']: string; -} +/* Excluded from this release type: FirstPartyCredentialsSettings */ /** * @license @@ -2079,16 +3048,6 @@ declare type FulfilledHandler = | ((result: T) => R | PersistencePromise) | null; -/** - * Interface implemented by the LRU scheduler to start(), stop() and restart - * garbage collection. - */ -declare interface GarbageCollectionScheduler { - readonly started: boolean; - start(localStore: LocalStore): void; - stop(): void; -} - /** * @license * Copyright 2017 Google LLC @@ -2137,6 +3096,7 @@ export declare class GeoPoint { * @returns true if this `GeoPoint` is equal to the provided one. */ isEqual(other: GeoPoint): boolean; + /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON(): { latitude: number; longitude: number; @@ -2148,6 +3108,86 @@ export declare class GeoPoint { _compareTo(other: GeoPoint): number; } +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregateFromServer< + AggregateSpecType extends AggregateSpec, + AppModelType, + DbModelType extends DocumentData +>( + query: Query, + aggregateSpec: AggregateSpecType +): Promise< + AggregateQuerySnapshot +>; + +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCountFromServer< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise< + AggregateQuerySnapshot< + { + count: AggregateField; + }, + AppModelType, + DbModelType + > +>; + /** * Reads the document referred to by this `DocumentReference`. * @@ -2160,31 +3200,37 @@ export declare class GeoPoint { * @returns A Promise resolved with a `DocumentSnapshot` containing the * current document contents. */ -export declare function getDoc( - reference: DocumentReference -): Promise>; +export declare function getDoc( + reference: DocumentReference +): Promise>; /** * Reads the document referred to by this `DocumentReference` from cache. * Returns an error if the document is not currently cached. * - * @returns A Promise resolved with a `DocumentSnapshot` containing the + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the * current document contents. */ -export declare function getDocFromCache( - reference: DocumentReference -): Promise>; +export declare function getDocFromCache< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference +): Promise>; /** * Reads the document referred to by this `DocumentReference` from the server. * Returns an error if the network is not available. * - * @returns A Promise resolved with a `DocumentSnapshot` containing the + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the * current document contents. */ -export declare function getDocFromServer( - reference: DocumentReference -): Promise>; +export declare function getDocFromServer< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference +): Promise>; /** * Executes the query and returns the results as a `QuerySnapshot`. @@ -2194,44 +3240,126 @@ export declare function getDocFromServer( * you are offline and the server cannot be reached. To specify this behavior, * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. * - * @returns A Promise that will be resolved with the results of the query. + * @returns A `Promise` that will be resolved with the results of the query. */ -export declare function getDocs(query: Query): Promise>; +export declare function getDocs( + query: Query +): Promise>; /** * Executes the query and returns the results as a `QuerySnapshot` from cache. - * Returns an error if the document is not currently cached. + * Returns an empty result set if no documents matching the query are currently + * cached. * - * @returns A Promise that will be resolved with the results of the query. + * @returns A `Promise` that will be resolved with the results of the query. */ -export declare function getDocsFromCache( - query: Query -): Promise>; +export declare function getDocsFromCache< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise>; /** * Executes the query and returns the results as a `QuerySnapshot` from the * server. Returns an error if the network is not available. * - * @returns A Promise that will be resolved with the results of the query. + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromServer< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise>; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The default {@link Firestore} instance of the default app. + */ +export declare function getFirestore(): Firestore; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The default {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; + +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the default app. + * @beta */ -export declare function getDocsFromServer( - query: Query -): Promise>; +export declare function getFirestore(databaseId: string): Firestore; /** - * Returns the existing instance of Firestore that is associated with the - * provided {@link FirebaseApp}. If no instance exists, initializes a new + * Returns the existing named {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new * instance with default settings. * - * @param app - The {@link FirebaseApp} instance that the returned Firestore + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} * instance is associated with. - * @returns The `Firestore` instance of the provided app. + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore( + app: FirebaseApp, + databaseId: string +): Firestore; + +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +export declare function getPersistentCacheIndexManager( + firestore: Firestore +): PersistentCacheIndexManager | null; + +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. */ -export declare function getFirestore(app: FirebaseApp): FirebaseFirestore; +declare interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken( + transaction: PersistenceTransaction + ): PersistencePromise<_ByteString>; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken( + transaction: PersistenceTransaction, + sessionToken: _ByteString + ): PersistencePromise; +} /** - * Returns a special value that can be used with {@link setDoc} or {@link - * updateDoc} that tells the server to increment the field's current value by + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by * the given value. * * If either the operand or the current field value uses floating point @@ -2250,8 +3378,86 @@ export declare function getFirestore(app: FirebaseApp): FirebaseFirestore; */ export declare function increment(n: number): FieldValue; +/** + * The SDK definition of a Firestore index. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface Index { + /** The ID of the collection to index. */ + readonly collectionGroup: string; + /** A list of fields to index. */ + readonly fields?: IndexField[]; + [key: string]: unknown; +} + +/** + * A list of Firestore indexes to speed up local query execution. + * + * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} + * for a description of the format of the index definition. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexConfiguration { + /** A list of all Firestore indexes. */ + readonly indexes?: Index[]; + [key: string]: unknown; +} + +/** + * A single field element in an index configuration. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexField { + /** The field path to index. */ + readonly fieldPath: string; + /** + * What type of array index to create. Set to `CONTAINS` for `array-contains` + * and `array-contains-any` indexes. + * + * Only one of `arrayConfig` or `order` should be set; + */ + readonly arrayConfig?: 'CONTAINS'; + /** + * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for + * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. + * + * Only one of `arrayConfig` or `order` should be set. + */ + readonly order?: 'ASCENDING' | 'DESCENDING'; + [key: string]: unknown; +} + declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; +/** The type of the index, e.g. for which type of query it can be used. */ +declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} + /** * Represents a set of indexes that are used to execute queries efficiently. * @@ -2270,7 +3476,7 @@ declare interface IndexManager { */ addToCollectionParentIndex( transaction: PersistenceTransaction, - collectionPath: ResourcePath + collectionPath: _ResourcePath ): PersistencePromise; /** * Retrieves all parent locations containing the given collectionId, as a @@ -2280,45 +3486,267 @@ declare interface IndexManager { getCollectionParents( transaction: PersistenceTransaction, collectionId: string - ): PersistencePromise; + ): PersistencePromise<_ResourcePath[]>; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex( + transaction: PersistenceTransaction, + index: FieldIndex + ): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex( + transaction: PersistenceTransaction, + index: FieldIndex + ): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes( + transaction: PersistenceTransaction + ): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes( + transaction: PersistenceTransaction, + target: Target + ): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes( + transaction: PersistenceTransaction, + collectionGroup: string + ): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes( + transaction: PersistenceTransaction + ): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType( + transaction: PersistenceTransaction, + target: Target + ): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget( + transaction: PersistenceTransaction, + target: Target + ): PersistencePromise<_DocumentKey[] | null>; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate( + transaction: PersistenceTransaction + ): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup( + transaction: PersistenceTransaction, + collectionGroup: string, + offset: IndexOffset + ): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries( + transaction: PersistenceTransaction, + documents: DocumentMap + ): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset( + transaction: PersistenceTransaction, + target: Target + ): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup( + transaction: PersistenceTransaction, + collectionGroup: string + ): PersistencePromise; +} + +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: _DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: _DocumentKey, + largestBatchId: number + ); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} + +/** An index component consisting of field path and index type. */ +declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: _FieldPath; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: _FieldPath, + /** The fields sorting order. */ + kind: IndexKind + ); +} + +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset + ); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} + +declare type IndexState_2 = + | 'STATE_UNSPECIFIED' + | 'CREATING' + | 'READY' + | 'ERROR'; + +/** Represents the index state as it relates to a particular target. */ +declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 } -declare type IndexState = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR'; - /** - * Initializes a new instance of Cloud Firestore with the provided settings. + * Initializes a new instance of {@link Firestore} with the provided settings. * Can only be called before any other function, including - * {@link getFirestore}. If the custom settings are empty, this function is - * equivalent to calling {@link getFirestore}. + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. * - * @param app - The {@link FirebaseApp} with which the `Firestore` instance will + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will * be associated. - * @param settings - A settings object to configure the `Firestore` instance. - * @returns A newly initialized `Firestore` instance. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. */ export declare function initializeFirestore( app: FirebaseApp, - settings: Settings -): FirebaseFirestore; + settings: FirestoreSettings, + databaseId?: string +): Firestore; + +/* Excluded from this release type: _internalAggregationQueryToProtoRunAggregationQueryRequest */ + +/* Excluded from this release type: _internalQueryToProtoQueryTarget */ + +/* Excluded from this release type: _isBase64Available */ + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +declare class JsonProtoSerializer implements Serializer { + readonly databaseId: _DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: _DatabaseId, useProto3Json: boolean); +} + +declare type Kind = 'memory' | 'persistent'; /** - * Creates a `QueryConstraint` that only returns the first matching documents. + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. * * @param limit - The maximum number of items to return. - * @returns The created `Query`. + * @returns The created {@link QueryLimitConstraint}. */ -export declare function limit(limit: number): QueryConstraint; +export declare function limit(limit: number): QueryLimitConstraint; /** - * Creates a `QueryConstraint` that only returns the last matching documents. + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. * * You must specify at least one `orderBy` clause for `limitToLast` queries, * otherwise an exception will be thrown during execution. * * @param limit - The maximum number of items to return. - * @returns The created `Query`. + * @returns The created {@link QueryLimitConstraint}. */ -export declare function limitToLast(limit: number): QueryConstraint; +export declare function limitToLast(limit: number): QueryLimitConstraint; declare const enum LimitType { First = 'F', @@ -2330,6 +3758,14 @@ declare type LimitType_2 = 'FIRST' | 'LAST'; declare type ListenSequenceNumber = number; +/** + * Describe the source a query listens to. + * + * Set to `default` to listen to both cache and server changes. Set to `cache` + * to listen to changes in cache only. + */ +export declare type ListenSource = 'default' | 'cache'; + declare class LLRBEmptyNode { get key(): never; get value(): never; @@ -2406,16 +3842,16 @@ declare class LLRBNode { /** * Loads a Firestore bundle into the local cache. * - * @param firestore - The `Firestore` instance to load bundles for for. - * @param bundleData - An object representing the bundle to be loaded. Valid objects are - * `ArrayBuffer`, `ReadableStream` or `string`. + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. * - * @return - * A `LoadBundleTask` object, which notifies callers with progress updates, and completion - * or error events. It can be used as a `Promise`. + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. */ export declare function loadBundle( - firestore: FirebaseFirestore, + firestore: Firestore, bundleData: ReadableStream | ArrayBuffer | string ): LoadBundleTask; @@ -2502,11 +3938,160 @@ export declare interface LoadBundleTaskProgress { taskState: TaskState; } +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor( + remoteDocumentCache: RemoteDocumentCache, + mutationQueue: MutationQueue, + documentOverlayCache: DocumentOverlayCache, + indexManager: IndexManager + ); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument( + transaction: PersistenceTransaction, + key: _DocumentKey + ): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments( + transaction: PersistenceTransaction, + keys: DocumentKeySet + ): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments( + transaction: PersistenceTransaction, + docs: MutableDocumentMap, + existenceStateChanged?: DocumentKeySet + ): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments( + transaction: PersistenceTransaction, + docs: MutableDocumentMap + ): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews( + transaction: PersistenceTransaction, + docs: MutableDocumentMap, + overlays: OverlayMap, + existenceStateChanged: DocumentKeySet + ): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys( + transaction: PersistenceTransaction, + documentKeys: DocumentKeySet + ): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery( + transaction: PersistenceTransaction, + query: Query_2, + offset: IndexOffset, + context?: QueryContext + ): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments( + transaction: PersistenceTransaction, + collectionGroup: string, + offset: IndexOffset, + count: number + ): PersistencePromise; + private getDocumentsMatchingDocumentQuery; + private getDocumentsMatchingCollectionGroupQuery; + private getDocumentsMatchingCollectionQuery; +} + declare interface LocalStore { collectGarbage(garbageCollector: LruGarbageCollector): Promise; + /** Manages the list of active field and collection indices. */ + indexManager: IndexManager; + /** + * The "local" view of all documents (layering mutationQueue on top of + * remoteDocumentCache). + */ + localDocuments: LocalDocumentsView; +} + +/** The result of a write to the local store. */ +declare interface LocalWriteResult { + batchId: BatchId; + changes: DocumentMap; } export { LogLevel }; +/* Excluded from this release type: _logWarn */ + declare interface LruGarbageCollector { readonly params: LruParams; collect( @@ -2575,23 +4160,179 @@ declare interface LruResults { declare type MapValue = firestoreV1ApiClientInterfaces.MapValue; /** - * The result of a lookup for a given path may be an existing document or a - * marker that this document does not exist at a given version. + * An settings object to configure an `MemoryLocalCache` instance. */ -declare abstract class MaybeDocument { - readonly key: DocumentKey; - readonly version: SnapshotVersion; - constructor(key: DocumentKey, version: SnapshotVersion); +export declare type MemoryCacheSettings = { /** - * Whether this document had a local mutation applied that has not yet been - * acknowledged by Watch. + * The garbage collector to use, for the memory cache layer. + * A `MemoryEagerGarbageCollector` is used when this is undefined. */ - abstract get hasPendingWrites(): boolean; - abstract isEqual(other: MaybeDocument | null | undefined): boolean; - abstract toString(): string; + garbageCollector?: MemoryGarbageCollector; +}; + +/** + * A garbage collector deletes documents whenever they are not part of any + * active queries, and have no local mutations attached to them. + * + * This collector tries to ensure lowest memory footprints from the SDK, + * at the risk of documents not being cached for offline queries or for + * direct queries to the cache. + * + * Use factory function {@link memoryEagerGarbageCollector()} to create an + * instance of this collector. + */ +export declare type MemoryEagerGarbageCollector = { + kind: 'memoryEager'; + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector; + +/** + * Union type from all support garbage collectors for memory local cache. + */ +export declare type MemoryGarbageCollector = + | MemoryEagerGarbageCollector + | MemoryLruGarbageCollector; + +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare type MemoryLocalCache = { + kind: 'memory'; + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +export declare function memoryLocalCache( + settings?: MemoryCacheSettings +): MemoryLocalCache; + +/** + * A garbage collector deletes Least-Recently-Used documents in multiple + * batches. + * + * This collector is configured with a target size, and will only perform + * collection when the cached documents exceed the target size. It avoids + * querying backend repeated for the same query or document, at the risk + * of having a larger memory footprint. + * + * Use factory function {@link memoryLruGarbageCollector()} to create a + * instance of this collector. + */ +export declare type MemoryLruGarbageCollector = { + kind: 'memoryLru'; + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +export declare function memoryLruGarbageCollector(settings?: { + cacheSizeBytes?: number; +}): MemoryLruGarbageCollector; + +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +declare class MutableDocument implements Document_2 { + readonly key: _DocumentKey; + private documentType; + version: SnapshotVersion; + readTime: SnapshotVersion; + createTime: SnapshotVersion; + data: ObjectValue; + private documentState; + private constructor(); + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey: _DocumentKey): MutableDocument; + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument( + documentKey: _DocumentKey, + version: SnapshotVersion, + createTime: SnapshotVersion, + value: ObjectValue + ): MutableDocument; + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument( + documentKey: _DocumentKey, + version: SnapshotVersion + ): MutableDocument; + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument( + documentKey: _DocumentKey, + version: SnapshotVersion + ): MutableDocument; + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument( + version: SnapshotVersion, + value: ObjectValue + ): MutableDocument; + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version: SnapshotVersion): MutableDocument; + setHasCommittedMutations(): MutableDocument; + setHasLocalMutations(): MutableDocument; + setReadTime(readTime: SnapshotVersion): MutableDocument; + get hasLocalMutations(): boolean; + get hasCommittedMutations(): boolean; + get hasPendingWrites(): boolean; + isValidDocument(): boolean; + isFoundDocument(): boolean; + isNoDocument(): boolean; + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + mutableCopy(): MutableDocument; + toString(): string; } -declare type MaybeDocumentMap = SortedMap; +/** Miscellaneous collection types / constants. */ +declare type MutableDocumentMap = SortedMap<_DocumentKey, MutableDocument>; /** * A mutation describes a self-contained change to a document. Mutations can @@ -2609,13 +4350,13 @@ declare type MaybeDocumentMap = SortedMap; * * SetMutation Document(v3) Document(v3) * SetMutation NoDocument(v3) Document(v0) - * SetMutation null Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) * PatchMutation Document(v3) Document(v3) * PatchMutation NoDocument(v3) NoDocument(v3) - * PatchMutation null null + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) * DeleteMutation Document(v3) NoDocument(v0) * DeleteMutation NoDocument(v3) NoDocument(v0) - * DeleteMutation null NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) * * For acknowledged mutations, we use the updateTime of the WriteResponse as * the resulting version for Set and Patch mutations. As deletes have no @@ -2623,8 +4364,8 @@ declare type MaybeDocumentMap = SortedMap; * Delete mutations. * * If a mutation is acknowledged by the backend but fails the precondition check - * locally, we return an `UnknownDocument` and rely on Watch to send us the - * updated version. + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. * * Field transforms are used only with Patch and Set Mutations. We use the * `updateTransforms` message to store transforms, rather than the `transforms`s @@ -2632,15 +4373,22 @@ declare type MaybeDocumentMap = SortedMap; * * ## Subclassing Notes * - * Subclasses of Mutation need to implement applyToRemoteDocument() and + * Every type of mutation needs to implement its own applyToRemoteDocument() and * applyToLocalView() to implement the actual behavior of applying the mutation - * to some source document. + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). */ declare abstract class Mutation { abstract readonly type: MutationType; - abstract readonly key: DocumentKey; + abstract readonly key: _DocumentKey; abstract readonly precondition: Precondition; abstract readonly fieldTransforms: FieldTransform[]; + /** + * Returns a `FieldMask` representing the fields that will be changed by + * applying this mutation. Returns `null` if the mutation will overwrite the + * entire document. + */ + abstract getFieldMask(): FieldMask | null; } /** @@ -2670,34 +4418,37 @@ declare class MutationBatch { ); /** * Applies all the mutations in this MutationBatch to the specified document - * to create a new remote document + * to compute the state of the remote document * - * @param docKey - The key of the document to apply mutations to. - * @param maybeDoc - The document to apply mutations to. + * @param document - The document to apply mutations to. * @param batchResult - The result of applying the MutationBatch to the * backend. */ applyToRemoteDocument( - docKey: DocumentKey, - maybeDoc: MaybeDocument | null, + document: MutableDocument, batchResult: MutationBatchResult - ): MaybeDocument | null; + ): void; /** * Computes the local view of a document given all the mutations in this * batch. * - * @param docKey - The key of the document to apply mutations to. - * @param maybeDoc - The document to apply mutations to. + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. */ applyToLocalView( - docKey: DocumentKey, - maybeDoc: MaybeDocument | null - ): MaybeDocument | null; + document: MutableDocument, + mutatedFields: FieldMask | null + ): FieldMask | null; /** * Computes the local view for all provided documents given the mutations in - * this batch. + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. */ - applyToLocalDocumentSet(maybeDocs: MaybeDocumentMap): MaybeDocumentMap; + applyToLocalDocumentSet( + documentMap: OverlayedDocumentMap, + documentsWithoutRemoteVersion: DocumentKeySet + ): MutationMap; keys(): DocumentKeySet; isEqual(other: MutationBatch): boolean; } @@ -2725,6 +4476,8 @@ declare class MutationBatchResult { ): MutationBatchResult; } +declare type MutationMap = DocumentKeyMap; + /** A queue of mutations to apply to the remote store. */ declare interface MutationQueue { /** Returns true if this queue contains no mutation batches. */ @@ -2794,7 +4547,7 @@ declare interface MutationQueue { */ getAllMutationBatchesAffectingDocumentKey( transaction: PersistenceTransaction, - documentKey: DocumentKey + documentKey: _DocumentKey ): PersistencePromise; /** * Finds all mutation batches that could possibly affect the given set of @@ -2810,7 +4563,7 @@ declare interface MutationQueue { */ getAllMutationBatchesAffectingDocumentKeys( transaction: PersistenceTransaction, - documentKeys: SortedMap + documentKeys: SortedMap<_DocumentKey, unknown> ): PersistencePromise; /** * Finds all mutation batches that could affect the results for the given @@ -2871,9 +4624,9 @@ declare class MutationResult { * containing field transforms has been committed. Contains one FieldValue * for each FieldTransform that was in the mutation. * - * Will be null if the mutation did not contain any field transforms. + * Will be empty if the mutation did not contain any field transforms. */ - readonly transformResults: Array | null; + readonly transformResults: Array; constructor( /** * The version at which the mutation was committed: @@ -2891,9 +4644,9 @@ declare class MutationResult { * containing field transforms has been committed. Contains one FieldValue * for each FieldTransform that was in the mutation. * - * Will be null if the mutation did not contain any field transforms. + * Will be empty if the mutation did not contain any field transforms. */ - transformResults: Array | null + transformResults: Array ); } @@ -2917,14 +4670,19 @@ declare interface NamedQuery { } /** - * Reads a Firestore `Query` from local cache, identified by the given name. + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. * * The named queries are packaged into bundles on the server side (along - * with resulting documents), and loaded to local cache using `loadBundle`. Once in local - * cache, use this method to extract a `Query` by name. + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. */ export declare function namedQuery( - firestore: FirebaseFirestore, + firestore: Firestore, name: string ): Promise; @@ -2938,10 +4696,17 @@ declare interface NamedQuery_2 { readTime?: Timestamp_2 | null; } -declare type NullableMaybeDocumentMap = SortedMap< - DocumentKey, - MaybeDocument | null ->; +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = + UnionToIntersection< + { + [K in keyof T & string]: ChildUpdateFields; + }[keyof T & string] + >; /** * @license @@ -2975,6 +4740,8 @@ declare class ObjectMap { * constant time lookups in practice. */ private inner; + /** The number of entries stored in the map */ + private innerSize; constructor( mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean @@ -2990,6 +4757,7 @@ declare class ObjectMap { delete(key: KeyType): boolean; forEach(fn: (key: KeyType, val: ValueType) => void): void; isEmpty(): boolean; + size(): number; } /** @@ -2997,19 +4765,50 @@ declare class ObjectMap { * ability to add and remove fields (via the ObjectValueBuilder). */ declare class ObjectValue { - readonly proto: { + readonly value: { mapValue: MapValue; }; - constructor(proto: { mapValue: MapValue }); + constructor(value: { mapValue: MapValue }); static empty(): ObjectValue; /** * Returns the value at the given path or null. * * @param path - the path to search - * @returns The value at the path or if there it doesn't exist. + * @returns The value at the path or null if the path is not set. + */ + field(path: _FieldPath): Value | null; + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: _FieldPath, value: Value): void; + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map<_FieldPath, Value | null>): void; + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. */ - field(path: FieldPath_2): Value | null; + delete(path: _FieldPath): void; isEqual(other: ObjectValue): boolean; + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap; + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges; + clone(): ObjectValue; } /** @@ -3017,20 +4816,27 @@ declare class ObjectValue { * cache. Implementations override `initialize()` to provide all components. */ declare interface OfflineComponentProvider { + readonly kind: Kind; persistence: Persistence; sharedClientState: SharedClientState; localStore: LocalStore; - gcScheduler: GarbageCollectionScheduler | null; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; synchronizeTabs: boolean; initialize(cfg: ComponentConfiguration): Promise; terminate(): Promise; } +declare interface OfflineComponentProviderFactory { + build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider; +} + /** * Initializes and wires the components that are needed to interface with the * network. */ declare class OnlineComponentProvider { + static readonly provider: OnlineComponentProviderFactory; protected localStore: LocalStore; protected sharedClientState: SharedClientState; datastore: Datastore; @@ -3051,6 +4857,10 @@ declare class OnlineComponentProvider { terminate(): Promise; } +declare interface OnlineComponentProviderFactory { + build(): OnlineComponentProvider; +} + /** * Describes the online state of the Firestore client. Note that this does not * indicate whether or not the remote store is trying to connect or not. This is @@ -3096,10 +4906,13 @@ declare const enum OnlineState { * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - reference: DocumentReference, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, observer: { - next?: (snapshot: DocumentSnapshot) => void; + next?: (snapshot: DocumentSnapshot) => void; error?: (error: FirestoreError) => void; complete?: () => void; } @@ -3119,11 +4932,14 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - reference: DocumentReference, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, options: SnapshotListenOptions, observer: { - next?: (snapshot: DocumentSnapshot) => void; + next?: (snapshot: DocumentSnapshot) => void; error?: (error: FirestoreError) => void; complete?: () => void; } @@ -3147,9 +4963,12 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - reference: DocumentReference, - onNext: (snapshot: DocumentSnapshot) => void, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe; @@ -3173,10 +4992,13 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - reference: DocumentReference, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, options: SnapshotListenOptions, - onNext: (snapshot: DocumentSnapshot) => void, + onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe; @@ -3195,10 +5017,13 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - query: Query, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, observer: { - next?: (snapshot: QuerySnapshot) => void; + next?: (snapshot: QuerySnapshot) => void; error?: (error: FirestoreError) => void; complete?: () => void; } @@ -3219,11 +5044,14 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - query: Query, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, options: SnapshotListenOptions, observer: { - next?: (snapshot: QuerySnapshot) => void; + next?: (snapshot: QuerySnapshot) => void; error?: (error: FirestoreError) => void; complete?: () => void; } @@ -3248,9 +5076,12 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - query: Query, - onNext: (snapshot: QuerySnapshot) => void, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, + onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe; @@ -3275,10 +5106,13 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - query: Query, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, options: SnapshotListenOptions, - onNext: (snapshot: QuerySnapshot) => void, + onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe; @@ -3299,7 +5133,7 @@ export declare function onSnapshot( * listener. */ export declare function onSnapshotsInSync( - firestore: FirebaseFirestore, + firestore: Firestore, observer: { next?: (value: void) => void; error?: (error: FirestoreError) => void; @@ -3314,42 +5148,72 @@ export declare function onSnapshotsInSync( * * NOTE: The snapshots-in-sync event only indicates that listeners are in sync * with each other, but does not relate to whether those snapshots are in sync - * with the server. Use SnapshotMetadata in the individual listeners to + * with the server. Use `SnapshotMetadata` in the individual listeners to * determine if a snapshot is from the cache or the server. * - * @param firestore - The instance of Firestore for synchronizing snapshots. + * @param firestore - The `Firestore` instance for synchronizing snapshots. * @param onSync - A callback to be called every time all snapshot listeners are * in sync with each other. * @returns An unsubscribe function that can be called to cancel the snapshot * listener. */ export declare function onSnapshotsInSync( - firestore: FirebaseFirestore, + firestore: Firestore, onSync: () => void ): Unsubscribe; +declare const enum Operator { + LESS_THAN = '<', + LESS_THAN_OR_EQUAL = '<=', + EQUAL = '==', + NOT_EQUAL = '!=', + GREATER_THAN = '>', + GREATER_THAN_OR_EQUAL = '>=', + ARRAY_CONTAINS = 'array-contains', + IN = 'in', + NOT_IN = 'not-in', + ARRAY_CONTAINS_ANY = 'array-contains-any' +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or( + ...queryConstraints: QueryFilterConstraint[] +): QueryCompositeFilterConstraint; + /** * An ordering on a field, in some Direction. Direction defaults to ASCENDING. */ declare class OrderBy { - readonly field: FieldPath_2; + readonly field: _FieldPath; readonly dir: Direction; - constructor(field: FieldPath_2, dir?: Direction); + constructor(field: _FieldPath, dir?: Direction); } /** - * Creates a `QueryConstraint` that sorts the query result by the + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the * specified field, optionally in descending order instead of ascending. * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * * @param fieldPath - The field to sort by. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If * not specified, order will be ascending. - * @returns The created `Query`. + * @returns The created {@link QueryOrderByConstraint}. */ export declare function orderBy( fieldPath: string | FieldPath, directionStr?: OrderByDirection -): QueryConstraint; +): QueryOrderByConstraint; /** * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' @@ -3362,8 +5226,52 @@ declare type OrderDirection = | 'ASCENDING' | 'DESCENDING'; +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +declare class Overlay { + readonly largestBatchId: number; + readonly mutation: Mutation; + constructor(largestBatchId: number, mutation: Mutation); + getKey(): _DocumentKey; + isEqual(other: Overlay | null): boolean; + toString(): string; +} + +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +declare class OverlayedDocument { + readonly overlayedDocument: Document_2; + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + readonly mutatedFields: FieldMask | null; + constructor( + overlayedDocument: Document_2, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields: FieldMask | null + ); +} + +declare type OverlayedDocumentMap = DocumentKeyMap; + +declare type OverlayMap = DocumentKeyMap; + declare interface ParseContext { - readonly databaseId: DatabaseId; + readonly databaseId: _DatabaseId; readonly ignoreUndefinedProperties: boolean; } @@ -3377,7 +5285,7 @@ declare class ParsedSetData { fieldMask: FieldMask | null, fieldTransforms: FieldTransform[] ); - toMutation(key: DocumentKey, precondition: Precondition): Mutation; + toMutation(key: _DocumentKey, precondition: Precondition): Mutation; } /** The result of parsing "update" data (i.e. for an updateData call). */ @@ -3390,9 +5298,23 @@ declare class ParsedUpdateData { fieldMask: FieldMask, fieldTransforms: FieldTransform[] ); - toMutation(key: DocumentKey, precondition: Precondition): Mutation; + toMutation(key: _DocumentKey, precondition: Precondition): Mutation; } +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = + | Partial + | (T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; + } + : never); + /** * Persistence is the lowest-level shared interface to persistent storage in * Firestore. @@ -3457,6 +5379,10 @@ declare interface Persistence { * PORTING NOTE: This is only used for Web multi-tab. */ setNetworkEnabled(networkEnabled: boolean): void; + /** + * Returns GlobalCache representing a general purpose cache for global values. + */ + getGlobalsCache(): GlobalsCache; /** * Returns a MutationQueue representing the persisted mutations for the * given user. @@ -3467,7 +5393,7 @@ declare interface Persistence { * extent possible (e.g. in the case of uid switching from * sally=>jack=>sally, sally's mutation queue will be preserved). */ - getMutationQueue(user: User): MutationQueue; + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; /** * Returns a TargetCache representing the persisted cache of targets. * @@ -3500,7 +5426,12 @@ declare interface Persistence { * this is called. In particular, the memory-backed implementation does this * to emulate the persisted implementation to the extent possible. */ - getIndexManager(): IndexManager; + getIndexManager(user: User): IndexManager; + /** + * Returns a DocumentOverlayCache representing the documents that are mutated + * locally. + */ + getDocumentOverlayCache(user: User): DocumentOverlayCache; /** * Performs an operation inside a persistence transaction. Any reads or writes * against persistence must be performed within a transaction. Writes will be @@ -3520,7 +5451,7 @@ declare interface Persistence { * be acquired and the returned promise will be rejected with a * FAILED_PRECONDITION error. * @param transactionOperation - The operation to run inside a transaction. - * @returns A promise that is resolved once the transaction completes. + * @returns A `Promise` that is resolved once the transaction completes. */ runTransaction( action: string, @@ -3597,32 +5528,177 @@ declare class PersistencePromise { }, f: (r: R) => PersistencePromise ): PersistencePromise; + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray( + array: T[], + f: (t: T) => PersistencePromise + ): PersistencePromise; + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile( + condition: () => boolean, + action: () => PersistencePromise + ): PersistencePromise; } +/** + * Settings that can be passed to `enableIndexedDbPersistence()` to configure + * Firestore persistence. + * + * Persistence cannot be used in a Node.js environment. + */ export declare interface PersistenceSettings { + /** + * Whether to force enable persistence for the client. This cannot be used + * with multi-tab synchronization and is primarily intended for use with Web + * Workers. Setting this to `true` will enable persistence, but cause other + * tabs using persistence to fail. + */ forceOwnership?: boolean; } /** - * A base class representing a persistence transaction, encapsulating both the - * transaction's sequence numbers as well as a list of onCommitted listeners. - * - * When you call Persistence.runTransaction(), it will create a transaction and - * pass it to your callback. You then pass it to any method that operates - * on persistence. + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +declare abstract class PersistenceTransaction { + private readonly onCommittedListeners; + abstract readonly currentSequenceNumber: ListenSequenceNumber; + addOnCommittedListener(listener: () => void): void; + raiseOnCommittedEvent(): void; +} + +/** The different modes supported by `Persistence.runTransaction()`. */ +declare type PersistenceTransactionMode = + | 'readonly' + | 'readwrite' + | 'readwrite-primary'; + +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +export declare class PersistentCacheIndexManager { + readonly _firestore: Firestore; + /** A type string to uniquely identify instances of this class. */ + readonly type: 'PersistentCacheIndexManager'; + /** @hideconstructor */ + constructor(_firestore: Firestore); +} + +/** + * An settings object to configure an `PersistentLocalCache` instance. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare type PersistentCacheSettings = { + /** + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The SDK does not guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies how multiple tabs/windows will be managed by the SDK. + */ + tabManager?: PersistentTabManager; +}; + +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare type PersistentLocalCache = { + kind: 'persistent'; + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare function persistentLocalCache( + settings?: PersistentCacheSettings +): PersistentLocalCache; + +/** + * A tab manager supporting multiple tabs. SDK will synchronize queries and + * mutations done across all tabs using the SDK. + */ +export declare type PersistentMultipleTabManager = { + kind: 'PersistentMultipleTab'; + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +export declare function persistentMultipleTabManager(): PersistentMultipleTabManager; + +/** + * A tab manager supporting only one tab, no synchronization will be + * performed across tabs. + */ +export declare type PersistentSingleTabManager = { + kind: 'persistentSingleTab'; + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +export declare function persistentSingleTabManager( + settings: PersistentSingleTabManagerSettings | undefined +): PersistentSingleTabManager; + +/** + * Type to configure an `PersistentSingleTabManager` instance. + */ +export declare type PersistentSingleTabManagerSettings = { + /** + * Whether to force-enable persistent (IndexedDB) cache for the client. This + * cannot be used with multi-tab synchronization and is primarily intended for + * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause + * other tabs using IndexedDB cache to fail. + */ + forceOwnership?: boolean; +}; + +/** + * A union of all available tab managers. */ -declare abstract class PersistenceTransaction { - private readonly onCommittedListeners; - abstract readonly currentSequenceNumber: ListenSequenceNumber; - addOnCommittedListener(listener: () => void): void; - raiseOnCommittedEvent(): void; -} - -/** The different modes supported by `Persistence.runTransaction()`. */ -declare type PersistenceTransactionMode = - | 'readonly' - | 'readwrite' - | 'readwrite-primary'; +export declare type PersistentTabManager = + | PersistentSingleTabManager + | PersistentMultipleTabManager; /** * Encodes a precondition for a mutation. This follows the model that the @@ -3644,70 +5720,121 @@ declare class Precondition { isEqual(other: Precondition): boolean; } -/** Undocumented, private additional settings not exposed in our public API. */ -declare interface PrivateSettings extends Settings_2 { - credentials?: CredentialsSettings; -} +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; + +/* Excluded from this release type: PrivateSettings */ declare interface ProviderCredentialsSettings { ['type']: 'provider'; - ['client']: CredentialsProvider; + ['client']: CredentialsProvider; } /** - * A `Query` refers to a Query which you can read or listen to. You can also + * A `Query` refers to a query which you can read or listen to. You can also * construct refined `Query` objects by adding filters and ordering. */ -export declare class Query { - readonly _converter: FirestoreDataConverter_2 | null; +export declare class Query< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter_2< + AppModelType, + DbModelType + > | null; readonly _query: Query_2; /** The type of this Firestore reference. */ readonly type: 'query' | 'collection'; /** - * The `FirebaseFirestore` for the Firestore database (useful for performing + * The `Firestore` instance for the Firestore database (useful for performing * transactions, etc.). */ - readonly firestore: FirebaseFirestore_2; + readonly firestore: Firestore_2; /** @hideconstructor protected */ constructor( - firestore: FirebaseFirestore_2, - _converter: FirestoreDataConverter_2 | null, + firestore: Firestore_2, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter_2 | null, _query: Query_2 ); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; /** * Applies a custom data converter to this query, allowing you to use your own * custom model objects with Firestore. When you call {@link getDocs} with * the returned query, the provided converter will convert between Firestore - * data and your custom type `U`. + * data of type `NewDbModelType` and your custom type `NewAppModelType`. * * @param converter - Converts objects to and from Firestore. - * @returns A `Query` that uses the provided converter. + * @returns A `Query` that uses the provided converter. */ - withConverter(converter: FirestoreDataConverter_2): Query; + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData + >( + converter: FirestoreDataConverter_2 + ): Query; } /** - * Creates a new immutable instance of `query` that is extended to also include - * additional query constraints. + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query( + query: Query, + compositeFilter: QueryCompositeFilterConstraint, + ...queryConstraints: QueryNonFilterConstraint[] +): Query; + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. * - * @param query - The query instance to use as a base for the new constraints. - * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. * @throws if any of the provided query constraints cannot be combined with the * existing or new constraints. */ -export declare function query( - query: Query, +export declare function query( + query: Query, ...queryConstraints: QueryConstraint[] -): Query; +): Query; /** * The Query interface defines all external properties of a query. * - * QueryImpl implements this interface to provide memoization for `queryOrderBy` + * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy` * and `queryToTarget`. */ declare interface Query_2 { - readonly path: ResourcePath; + readonly path: _ResourcePath; readonly collectionGroup: string | null; readonly explicitOrderBy: OrderBy[]; readonly filters: Filter[]; @@ -3717,22 +5844,51 @@ declare interface Query_2 { readonly endAt: Bound | null; } +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint extends AppliableConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; + private readonly _queryConstraints; + /* Excluded from this release type: __constructor */ + static _create( + type: 'or' | 'and', + _queryConstraints: QueryFilterConstraint[] + ): QueryCompositeFilterConstraint; + _parse( + query: Query + ): Filter; + _apply( + query: Query + ): Query; + _getQueryConstraints(): readonly AppliableConstraint[]; + _getOperator(): CompositeOperator; +} + /** * A `QueryConstraint` is used to narrow the set of documents returned by a * Firestore query. `QueryConstraint`s are created by invoking {@link where}, - * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link - * endBefore}, {@link endAt}, {@link limit} or {@link limitToLast} and - * can then be passed to {@link query} to create a new query instance that + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that * also contains this `QueryConstraint`. */ -export declare abstract class QueryConstraint { - /** The type of this query constraints */ +export declare abstract class QueryConstraint extends AppliableConstraint { + /** The type of this query constraint */ abstract readonly type: QueryConstraintType; /** - * Takes the provided `Query` and returns a copy of the `Query` with this - * `QueryConstraint` applied. + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. */ - abstract _apply(query: Query): Query; + abstract _apply( + query: Query + ): Query; } /** Describes the different query constraints available in this SDK. */ @@ -3746,6 +5902,35 @@ export declare type QueryConstraintType = | 'endAt' | 'endBefore'; +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +declare class QueryContext { + /** + * Counts the number of documents passed through during local query execution. + */ + private _documentReadCount; + get documentReadCount(): number; + incrementDocumentReadCount(amount: number): void; +} + /** * A `QueryDocumentSnapshot` contains data read from a document in your * Firestore database as part of a query. The document is guaranteed to exist @@ -3758,12 +5943,13 @@ export declare type QueryConstraintType = * 'undefined'. */ export declare class QueryDocumentSnapshot< - T = DocumentData -> extends DocumentSnapshot { + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> extends DocumentSnapshot { /** * Retrieves all fields in the document as an `Object`. * - * By default, `FieldValue.serverTimestamp()` values that have not yet been + * By default, `serverTimestamp()` values that have not yet been * set to their final value will be returned as `null`. You can override * this by passing an options object. * @@ -3773,7 +5959,7 @@ export declare class QueryDocumentSnapshot< * have not yet been set to their final value). * @returns An `Object` containing all fields in the document. */ - data(options?: SnapshotOptions): T; + data(options?: SnapshotOptions): AppModelType; } /** @@ -3788,15 +5974,39 @@ export declare class QueryDocumentSnapshot< * 'undefined'. */ declare class QueryDocumentSnapshot_2< - T = DocumentData -> extends DocumentSnapshot_2 { + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> extends DocumentSnapshot_2 { /** * Retrieves all fields in the document as an `Object`. * * @override * @returns An `Object` containing all fields in the document. */ - data(): T; + data(): AppModelType; +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; + private readonly _docOrFields; + private readonly _inclusive; + /* Excluded from this release type: __constructor */ + static _create( + type: 'endBefore' | 'endAt', + _docOrFields: Array>, + _inclusive: boolean + ): QueryEndAtConstraint; + _apply( + query: Query + ): Query; } /** @@ -3808,7 +6018,110 @@ declare class QueryDocumentSnapshot_2< * @returns true if the references point to the same location in the same * Firestore database. */ -export declare function queryEqual(left: Query, right: Query): boolean; +export declare function queryEqual< + AppModelType, + DbModelType extends DocumentData +>( + left: Query, + right: Query +): boolean; + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + private readonly _field; + private _op; + private _value; + /** The type of this query constraint */ + readonly type = 'where'; + /* Excluded from this release type: __constructor */ + static _create( + _field: _FieldPath, + _op: Operator, + _value: unknown + ): QueryFieldFilterConstraint; + _apply( + query: Query + ): Query; + _parse( + query: Query + ): FieldFilter; +} + +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = + | QueryFieldFilterConstraint + | QueryCompositeFilterConstraint; + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; + private readonly _limit; + private readonly _limitType; + /* Excluded from this release type: __constructor */ + static _create( + type: 'limit' | 'limitToLast', + _limit: number, + _limitType: LimitType + ): QueryLimitConstraint; + _apply( + query: Query + ): Query; +} + +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = + | QueryOrderByConstraint + | QueryLimitConstraint + | QueryStartAtConstraint + | QueryEndAtConstraint; + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + private readonly _field; + private _direction; + /** The type of this query constraint */ + readonly type = 'orderBy'; + /* Excluded from this release type: __constructor */ + static _create( + _field: _FieldPath, + _direction: Direction + ): QueryOrderByConstraint; + _apply( + query: Query + ): Query; +} /** * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects @@ -3817,8 +6130,11 @@ export declare function queryEqual(left: Query, right: Query): boolean; * number of documents can be determined via the `empty` and `size` * properties. */ -export declare class QuerySnapshot { - readonly _firestore: FirebaseFirestore; +export declare class QuerySnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + readonly _firestore: Firestore; readonly _userDataWriter: AbstractUserDataWriter; readonly _snapshot: ViewSnapshot; /** @@ -3830,18 +6146,18 @@ export declare class QuerySnapshot { * The query on which you called `get` or `onSnapshot` in order to get this * `QuerySnapshot`. */ - readonly query: Query; + readonly query: Query; private _cachedChanges?; private _cachedChangesIncludeMetadataChanges?; /** @hideconstructor */ constructor( - _firestore: FirebaseFirestore, + _firestore: Firestore, _userDataWriter: AbstractUserDataWriter, - query: Query, + query: Query, _snapshot: ViewSnapshot ); /** An array of all the documents in the `QuerySnapshot`. */ - get docs(): Array>; + get docs(): Array>; /** The number of documents in the `QuerySnapshot`. */ get size(): number; /** True if there are no documents in the `QuerySnapshot`. */ @@ -3854,7 +6170,9 @@ export declare class QuerySnapshot { * @param thisArg - The `this` binding for the callback. */ forEach( - callback: (result: QueryDocumentSnapshot) => void, + callback: ( + result: QueryDocumentSnapshot + ) => void, thisArg?: unknown ): void; /** @@ -3866,7 +6184,32 @@ export declare class QuerySnapshot { * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger * snapshot events. */ - docChanges(options?: SnapshotListenOptions): Array>; + docChanges( + options?: SnapshotListenOptions + ): Array>; +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; + private readonly _docOrFields; + private readonly _inclusive; + /* Excluded from this release type: __constructor */ + static _create( + type: 'startAt' | 'startAfter', + _docOrFields: Array>, + _inclusive: boolean + ): QueryStartAtConstraint; + _apply( + query: Query + ): Query; } /** The different states of a watch target. */ @@ -3880,9 +6223,16 @@ declare type QueryTargetState = 'not-current' | 'current' | 'rejected'; * @returns true if the references point to the same location in the same * Firestore database. */ -export declare function refEqual( - left: DocumentReference | CollectionReference, - right: DocumentReference | CollectionReference +export declare function refEqual< + AppModelType, + DbModelType extends DocumentData +>( + left: + | DocumentReference + | CollectionReference, + right: + | DocumentReference + | CollectionReference ): boolean; /** @@ -3903,13 +6253,13 @@ declare interface ReferenceDelegate { addReference( txn: PersistenceTransaction, targetId: TargetId, - doc: DocumentKey + doc: _DocumentKey ): PersistencePromise; /** Notify the delegate that the given document was removed from a target. */ removeReference( txn: PersistenceTransaction, targetId: TargetId, - doc: DocumentKey + doc: _DocumentKey ): PersistencePromise; /** * Notify the delegate that a target was removed. The delegate may, but is not obligated to, @@ -3925,12 +6275,12 @@ declare interface ReferenceDelegate { */ markPotentiallyOrphaned( txn: PersistenceTransaction, - doc: DocumentKey + doc: _DocumentKey ): PersistencePromise; /** Notify the delegate that a limbo document was updated. */ updateLimboDocument( txn: PersistenceTransaction, - doc: DocumentKey + doc: _DocumentKey ): PersistencePromise; } @@ -3943,52 +6293,66 @@ declare type Rejector = (error: Error) => void; /** * Represents cached documents received from the remote backend. * - * The cache is keyed by DocumentKey and entries in the cache are MaybeDocument - * instances, meaning we can cache both Document instances (an actual document - * with data) as well as NoDocument instances (indicating that the document is - * known to not exist). + * The cache is keyed by DocumentKey and entries in the cache are + * MutableDocuments, meaning we can cache both actual documents as well as + * documents that are known to not exist. */ declare interface RemoteDocumentCache { + /** Sets the index manager to use for managing the collectionGroup index. */ + setIndexManager(indexManager: IndexManager): void; /** * Looks up an entry in the cache. * * @param documentKey - The key of the entry to look up.* - * @returns The cached Document or NoDocument entry, or null if we have - * nothing cached. + * @returns The cached document entry. Returns an invalid document if the + * document is not cached. */ getEntry( transaction: PersistenceTransaction, - documentKey: DocumentKey - ): PersistencePromise; + documentKey: _DocumentKey + ): PersistencePromise; /** * Looks up a set of entries in the cache. * * @param documentKeys - The keys of the entries to look up. - * @returns The cached Document or NoDocument entries indexed by key. If an - * entry is not cached, the corresponding key will be mapped to a null value. + * @returns The cached document entries indexed by key. If an entry is not + * cached, the corresponding key will be mapped to an invalid document. */ getEntries( transaction: PersistenceTransaction, documentKeys: DocumentKeySet - ): PersistencePromise; + ): PersistencePromise; /** - * Executes a query against the cached Document entries. - * - * Implementations may return extra documents if convenient. The results - * should be re-filtered by the consumer before presenting them to the user. - * - * Cached NoDocument entries have no bearing on query results. + * Returns the documents matching the given query * * @param query - The query to match documents against. - * @param sinceReadTime - If not set to SnapshotVersion.min(), return only - * documents that have been read since this snapshot version (exclusive). + * @param offset - The offset to start the scan at (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. * @returns The set of matching documents. */ getDocumentsMatchingQuery( transaction: PersistenceTransaction, query: Query_2, - sinceReadTime: SnapshotVersion - ): PersistencePromise; + offset: IndexOffset, + mutatedDocs: OverlayMap, + context?: QueryContext + ): PersistencePromise; + /** + * Looks up the next `limit` documents for a collection group based on the + * provided offset. The ordering is based on the document's read time and key. + * + * @param collectionGroup - The collection group to scan. + * @param offset - The offset to start the scan at (exclusive). + * @param limit - The maximum number of results to return. + * @returns The set of matching documents. + */ + getAllFromCollectionGroup( + transaction: PersistenceTransaction, + collectionGroup: string, + offset: IndexOffset, + limit: number + ): PersistencePromise; /** * Provides access to add or update the contents of the cache. The buffer * handles proper size accounting for the change. @@ -4009,14 +6373,6 @@ declare interface RemoteDocumentCache { getSize(transaction: PersistenceTransaction): PersistencePromise; } -/** - * Represents a document change to be applied to remote document cache. - */ -declare interface RemoteDocumentChange { - readonly maybeDocument: MaybeDocument | null; - readonly readTime: SnapshotVersion | null; -} - /** * An in-memory buffer of entries to be written to a RemoteDocumentCache. * It can be used to batch up a set of changes to be written to the cache, but @@ -4032,34 +6388,33 @@ declare interface RemoteDocumentChange { * porting this class as part of that implementation work. */ declare abstract class RemoteDocumentChangeBuffer { - protected changes: ObjectMap; + protected changes: ObjectMap<_DocumentKey, MutableDocument>; private changesApplied; protected abstract getFromCache( transaction: PersistenceTransaction, - documentKey: DocumentKey - ): PersistencePromise; + documentKey: _DocumentKey + ): PersistencePromise; protected abstract getAllFromCache( transaction: PersistenceTransaction, documentKeys: DocumentKeySet - ): PersistencePromise; + ): PersistencePromise; protected abstract applyChanges( transaction: PersistenceTransaction ): PersistencePromise; - protected getReadTime(key: DocumentKey): SnapshotVersion; /** * Buffers a `RemoteDocumentCache.addEntry()` call. * * You can only modify documents that have already been retrieved via * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). */ - addEntry(maybeDocument: MaybeDocument, readTime: SnapshotVersion): void; + addEntry(document: MutableDocument): void; /** * Buffers a `RemoteDocumentCache.removeEntry()` call. * * You can only remove documents that have already been retrieved via * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). */ - removeEntry(key: DocumentKey, readTime?: SnapshotVersion | null): void; + removeEntry(key: _DocumentKey, readTime: SnapshotVersion): void; /** * Looks up an entry in the cache. The buffered changes will first be checked, * and if no buffered change applies, this will forward to @@ -4068,13 +6423,13 @@ declare abstract class RemoteDocumentChangeBuffer { * @param transaction - The transaction in which to perform any persistence * operations. * @param documentKey - The key of the entry to look up. - * @returns The cached Document or NoDocument entry, or null if we have - * nothing cached. + * @returns The cached document or an invalid document if we have nothing + * cached. */ getEntry( transaction: PersistenceTransaction, - documentKey: DocumentKey - ): PersistencePromise; + documentKey: _DocumentKey + ): PersistencePromise; /** * Looks up several entries in the cache, forwarding to * `RemoteDocumentCache.getEntry()`. @@ -4082,14 +6437,13 @@ declare abstract class RemoteDocumentChangeBuffer { * @param transaction - The transaction in which to perform any persistence * operations. * @param documentKeys - The keys of the entries to look up. - * @returns A map of cached `Document`s or `NoDocument`s, indexed by key. If - * an entry cannot be found, the corresponding key will be mapped to a - * null value. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. */ getEntries( transaction: PersistenceTransaction, documentKeys: DocumentKeySet - ): PersistencePromise; + ): PersistencePromise; /** * Applies buffered changes to the underlying RemoteDocumentCache, using * the provided transaction. @@ -4114,15 +6468,16 @@ declare class RemoteEvent { */ readonly targetChanges: Map; /** - * A set of targets that is known to be inconsistent. Listens for these - * targets should be re-established without resume tokens. + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. */ - readonly targetMismatches: SortedSet; + readonly targetMismatches: SortedMap; /** * A set of which documents have changed or been deleted, along with the * doc's new values (if not deleted). */ - readonly documentUpdates: MaybeDocumentMap; + readonly documentUpdates: MutableDocumentMap; /** * A set of which document updates are due only to limbo resolution targets. */ @@ -4137,15 +6492,16 @@ declare class RemoteEvent { */ targetChanges: Map, /** - * A set of targets that is known to be inconsistent. Listens for these - * targets should be re-established without resume tokens. + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. */ - targetMismatches: SortedSet, + targetMismatches: SortedMap, /** * A set of which documents have changed or been deleted, along with the * doc's new values (if not deleted). */ - documentUpdates: MaybeDocumentMap, + documentUpdates: MutableDocumentMap, /** * A set of which document updates are due only to limbo resolution targets. */ @@ -4159,7 +6515,8 @@ declare class RemoteEvent { */ static createSynthesizedRemoteEventForCurrentChange( targetId: TargetId, - current: boolean + current: boolean, + resumeToken: _ByteString ): RemoteEvent; } @@ -4239,26 +6596,7 @@ declare interface RemoteSyncer { declare type Resolver = (value?: T) => void; -/** - * A slash-separated path for navigating resources (documents and collections) - * within Firestore. - */ -declare class ResourcePath extends BasePath { - protected construct( - segments: string[], - offset?: number, - length?: number - ): ResourcePath; - canonicalString(): string; - toString(): string; - /** - * Creates a resource path from the given slash-delimited string. If multiple - * arguments are provided, all components are combined. Leading and trailing - * slashes from all components are ignored. - */ - static fromString(...pathComponents: string[]): ResourcePath; - static emptyPath(): ResourcePath; -} +/* Excluded from this release type: _ResourcePath */ /** * Executes the given `updateFunction` and then attempts to commit the changes @@ -4272,18 +6610,35 @@ declare class ResourcePath extends BasePath { * transaction against. * @param updateFunction - The function to execute within the transaction * context. + * @param options - An options object to configure maximum number of attempts to + * commit. * @returns If the transaction completed successfully or was explicitly aborted * (the `updateFunction` returned a failed promise), the promise returned by the * `updateFunction `is returned here. Otherwise, if the transaction failed, a * rejected promise with the corresponding failure error is returned. */ export declare function runTransaction( - firestore: FirebaseFirestore, - updateFunction: (transaction: Transaction) => Promise + firestore: Firestore, + updateFunction: (transaction: Transaction) => Promise, + options?: TransactionOptions ): Promise; /** - * Returns a sentinel used with {@link setDoc} or {@link updateDoc} to + * Interface to schedule periodic tasks within SDK. + */ +declare interface Scheduler { + readonly started: boolean; + start(): void; + stop(): void; +} + +/** Base interface for the Serializer implementation. */ +declare interface Serializer { + readonly useProto3Json: boolean; +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to * include a server-generated timestamp in the written data. */ export declare function serverTimestamp(): FieldValue; @@ -4296,12 +6651,12 @@ declare type ServerTimestampBehavior = 'estimate' | 'previous' | 'none'; * * @param reference - A reference to the document to write. * @param data - A map of the fields and values for the document. - * @returns A Promise resolved once the data has been successfully written + * @returns A `Promise` resolved once the data has been successfully written * to the backend (note that it won't resolve while you're offline). */ -export declare function setDoc( - reference: DocumentReference, - data: T +export declare function setDoc( + reference: DocumentReference, + data: WithFieldValue ): Promise; /** @@ -4315,12 +6670,78 @@ export declare function setDoc( * @returns A Promise resolved once the data has been successfully written * to the backend (note that it won't resolve while you're offline). */ -export declare function setDoc( - reference: DocumentReference, - data: Partial, +export declare function setDoc( + reference: DocumentReference, + data: PartialWithFieldValue, options: SetOptions ): Promise; +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. If IndexedDb is not + * enabled, any index configuration is ignored. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param configuration -The index definition. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration( + firestore: Firestore, + configuration: IndexConfiguration +): Promise; + +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. Invoke either + * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()` + * before setting an index configuration. If IndexedDb is not enabled, any + * index configuration is ignored. + * + * The method accepts the JSON format exported by the Firebase CLI (`firebase + * firestore:indexes`). If the JSON format is invalid, this method throws an + * error. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param json -The JSON format exported by the Firebase CLI. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration( + firestore: Firestore, + json: string +): Promise; + /** * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). * @@ -4337,17 +6758,19 @@ export declare function setDoc( export declare function setLogLevel(logLevel: LogLevel): void; /** - * An options object that configures the behavior of {@link setDoc}, {@link - * WriteBatch#set} and {@link Transaction#set} calls. These calls can be + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be * configured to perform granular merges instead of overwriting the target * documents in their entirety by providing a `SetOptions` with `merge: true`. * * @param merge - Changes the behavior of a `setDoc()` call to only replace the * values specified in its data argument. Fields omitted from the `setDoc()` - * call remain untouched. + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace * the specified field paths. Any field path that is not specified is ignored - * and remains untouched. + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. */ export declare type SetOptions = | { @@ -4357,19 +6780,6 @@ export declare type SetOptions = readonly mergeFields?: Array; }; -export declare interface Settings extends Settings_2 { - cacheSizeBytes?: number; -} - -declare interface Settings_2 { - host?: string; - ssl?: boolean; - ignoreUndefinedProperties?: boolean; - cacheSizeBytes?: number; - experimentalForceLongPolling?: boolean; - experimentalAutoDetectLongPolling?: boolean; -} - /** * A `SharedClientState` keeps track of the global state of the mutations * and query targets for all active clients with the same persistence key (i.e. @@ -4410,7 +6820,10 @@ declare interface SharedClientState { * If the target id is already associated with local client, the method simply * returns its `QueryTargetState`. */ - addLocalQueryTarget(targetId: TargetId): QueryTargetState; + addLocalQueryTarget( + targetId: TargetId, + addToActiveTargetIds?: boolean + ): QueryTargetState; /** Removes the Query Target ID association from the local client. */ removeLocalQueryTarget(targetId: TargetId): void; /** Checks whether the target is associated with the local client. */ @@ -4471,8 +6884,10 @@ declare interface SharedClientState { /** * Notifies other clients when remote documents have changed due to loading * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. */ - notifyBundleLoaded(): void; + notifyBundleLoaded(collectionGroups: Set): void; } /** @@ -4482,14 +6897,21 @@ declare interface SharedClientState { * @param right - A snapshot to compare. * @returns true if the snapshots are equal. */ -export declare function snapshotEqual( - left: DocumentSnapshot | QuerySnapshot, - right: DocumentSnapshot | QuerySnapshot +export declare function snapshotEqual< + AppModelType, + DbModelType extends DocumentData +>( + left: + | DocumentSnapshot + | QuerySnapshot, + right: + | DocumentSnapshot + | QuerySnapshot ): boolean; /** - * An options object that can be passed to {@link onSnapshot} and {@link - * QuerySnapshot#docChanges} to control which types of changes to include in the + * An options object that can be passed to {@link (onSnapshot:1)} and {@link + * QuerySnapshot.docChanges} to control which types of changes to include in the * result set. */ export declare interface SnapshotListenOptions { @@ -4498,6 +6920,11 @@ export declare interface SnapshotListenOptions { * changed. Default is false. */ readonly includeMetadataChanges?: boolean; + /** + * Set the source the query listens to. Default to "default", which + * listens to both cache and server. + */ + readonly source?: ListenSource; } /** @@ -4563,6 +6990,7 @@ declare class SnapshotVersion { private timestamp; static fromTimestamp(value: Timestamp): SnapshotVersion; static min(): SnapshotVersion; + static max(): SnapshotVersion; private constructor(); compareTo(other: SnapshotVersion): number; isEqual(other: SnapshotVersion): boolean; @@ -4659,55 +7087,69 @@ declare class SortedSetIterator { } /** - * Creates a `QueryConstraint` that modifies the result set to start after the - * provided document (exclusive). The starting position is relative to the order - * of the query. The document must contain all of the fields provided in the - * orderBy of the query. + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. * * @param snapshot - The snapshot of the document to start after. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryStartAtConstraint} to pass to `query()` */ -export declare function startAfter( - snapshot: DocumentSnapshot_2 -): QueryConstraint; +export declare function startAfter< + AppModelType, + DbModelType extends DocumentData +>( + snapshot: DocumentSnapshot_2 +): QueryStartAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to start after the - * provided fields relative to the order of the query. The order of the field - * values must match the order of the order by clauses of the query. + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. * * @param fieldValues - The field values to start this query after, in order * of the query's order by. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryStartAtConstraint} to pass to `query()` */ -export declare function startAfter(...fieldValues: unknown[]): QueryConstraint; +export declare function startAfter( + ...fieldValues: unknown[] +): QueryStartAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to start at the - * provided document (inclusive). The starting position is relative to the order - * of the query. The document must contain all of the fields provided in the - * `orderBy` of this query. + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. * * @param snapshot - The snapshot of the document to start at. - * @returns A `QueryConstraint` to pass to `query()`. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. */ -export declare function startAt( - snapshot: DocumentSnapshot_2 -): QueryConstraint; +export declare function startAt( + snapshot: DocumentSnapshot_2 +): QueryStartAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to start at the - * provided fields relative to the order of the query. The order of the field - * values must match the order of the order by clauses of the query. + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. * * @param fieldValues - The field values to start this query at, in order * of the query's order by. - * @returns A `QueryConstraint` to pass to `query()`. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. */ -export declare function startAt(...fieldValues: unknown[]): QueryConstraint; +export declare function startAt( + ...fieldValues: unknown[] +): QueryStartAtConstraint; declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; + /** * @license * Copyright 2017 Google LLC @@ -4754,7 +7196,7 @@ declare interface SyncEngine { * in persistence. */ declare interface Target { - readonly path: ResourcePath; + readonly path: _ResourcePath; readonly collectionGroup: string | null; readonly orderBy: OrderBy[]; readonly filters: Filter[]; @@ -4910,7 +7352,7 @@ declare interface TargetCache { ): PersistencePromise; containsKey( transaction: PersistenceTransaction, - key: DocumentKey + key: _DocumentKey ): PersistencePromise; } @@ -4929,7 +7371,7 @@ declare class TargetChange { * query. The resume token essentially identifies a point in time from which * the server should resume sending results. */ - readonly resumeToken: ByteString; + readonly resumeToken: _ByteString; /** * The "current" (synced) status of this target. Note that "current" * has special meaning in the RPC protocol that implies that a target is @@ -4958,7 +7400,7 @@ declare class TargetChange { * query. The resume token essentially identifies a point in time from which * the server should resume sending results. */ - resumeToken: ByteString, + resumeToken: _ByteString, /** * The "current" (synced) status of this target. Note that "current" * has special meaning in the RPC protocol that implies that a target is @@ -4988,7 +7430,8 @@ declare class TargetChange { */ static createSynthesizedTargetChangeForCurrentChange( targetId: TargetId, - current: boolean + current: boolean, + resumeToken: _ByteString ): TargetChange; } @@ -5030,7 +7473,13 @@ declare class TargetData { * matches the target. The resume token essentially identifies a point in * time from which the server should resume sending results. */ - readonly resumeToken: ByteString; + readonly resumeToken: _ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; constructor( /** The target being listened to. */ target: Target, @@ -5059,7 +7508,13 @@ declare class TargetData { * matches the target. The resume token essentially identifies a point in * time from which the server should resume sending results. */ - resumeToken?: ByteString + resumeToken?: _ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null ); /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(sequenceNumber: number): TargetData; @@ -5068,9 +7523,13 @@ declare class TargetData { * snapshot version. */ withResumeToken( - resumeToken: ByteString, + resumeToken: _ByteString, snapshotVersion: SnapshotVersion ): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; /** * Creates a new target data instance with an updated last limbo free * snapshot version number. @@ -5089,13 +7548,19 @@ declare type TargetId = number; /** An enumeration of the different purposes we have for targets. */ declare const enum TargetPurpose { /** A regular, normal query target. */ - Listen = 0, + Listen = 'TargetPurposeListen', /** - * The query target was used to refill a query after an existence filter mismatch. + * The query target was used to refill a query after an existence filter + * mismatch. */ - ExistenceFilterMismatch = 1, + ExistenceFilterMismatch = 'TargetPurposeExistenceFilterMismatch', + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = 'TargetPurposeExistenceFilterMismatchBloom', /** The query target was used to resolve a limbo document. */ - LimboResolution = 2 + LimboResolution = 'TargetPurposeLimboResolution' } /** @@ -5107,13 +7572,13 @@ declare const enum TargetPurpose { export declare type TaskState = 'Error' | 'Running' | 'Success'; /** - * Terminates the provided Firestore instance. + * Terminates the provided {@link Firestore} instance. * * After calling `terminate()` only the `clearIndexedDbPersistence()` function * may be used. Any other function will throw a `FirestoreError`. * * To restart after termination, create a new instance of FirebaseFirestore with - * {@link getFirestore}. + * {@link (getFirestore:1)}. * * Termination does not cancel any pending writes, and any promises that are * awaiting a response from the server will not be resolved. If you have @@ -5125,10 +7590,16 @@ export declare type TaskState = 'Error' | 'Running' | 'Success'; * of its resources or in combination with `clearIndexedDbPersistence()` to * ensure that all local state is destroyed between test runs. * - * @returns A promise that is resolved when the instance has been successfully + * @returns A `Promise` that is resolved when the instance has been successfully * terminated. */ -export declare function terminate(firestore: FirebaseFirestore): Promise; +export declare function terminate(firestore: Firestore): Promise; + +/* Excluded from this release type: _TestingHooks */ + +/* Excluded from this release type: _TestingHooksExistenceFilterMismatchCallback */ + +/* Excluded from this release type: _TestingHooksExistenceFilterMismatchInfo */ /** * Wellknown "timer" IDs used when scheduling delayed operations on the @@ -5141,15 +7612,17 @@ declare const enum TimerId { /** All can be used with runDelayedOperationsEarly() to run all timers. */ All = 'all', /** - * The following 4 timers are used in persistent_stream.ts for the listen and + * The following 5 timers are used in persistent_stream.ts for the listen and * write streams. The "Idle" timer is used to close the stream due to * inactivity. The "ConnectionBackoff" timer is used to restart a stream once - * the appropriate backoff delay has elapsed. + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. */ ListenStreamIdle = 'listen_stream_idle', ListenStreamConnectionBackoff = 'listen_stream_connection_backoff', WriteStreamIdle = 'write_stream_idle', WriteStreamConnectionBackoff = 'write_stream_connection_backoff', + HealthCheckTimeout = 'health_check_timeout', /** * A timer used in online_state_tracker.ts to transition from * OnlineState.Unknown to Offline after a set timeout, rather than waiting @@ -5172,7 +7645,11 @@ declare const enum TimerId { * A timer used to retry operations scheduled via retryable AsyncQueue * operations. */ - AsyncQueueRetry = 'async_queue_retry' + AsyncQueueRetry = 'async_queue_retry', + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = 'index_backfill' } /** @@ -5206,7 +7683,13 @@ declare const enum TimerId { * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. */ export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ readonly nanoseconds: number; /** * Creates a new timestamp with the current date, with millisecond precision. @@ -5242,10 +7725,20 @@ export declare class Timestamp { * non-negative nanoseconds values that count forward in time. Must be * from 0 to 999,999,999 inclusive. */ - constructor(seconds: number, nanoseconds: number); + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number + ); /** - * Converts a `Timestamp` to a JavaScript `Date` object. This conversion causes - * a loss of precision since `Date` objects only support millisecond precision. + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. * * @returns JavaScript `Date` object representing the same point in time as * this `Timestamp`, with millisecond precision. @@ -5267,14 +7760,16 @@ export declare class Timestamp { * @returns true if this `Timestamp` is equal to the provided one. */ isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ toString(): string; + /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON(): { seconds: number; nanoseconds: number; }; /** - * Converts this object to a primitive string, which allows Timestamp objects to be compared - * using the `>`, `<=`, `>=` and `>` operators. + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. */ valueOf(): string; } @@ -5292,15 +7787,14 @@ declare interface Token { /** * The user with which the token is associated (used for persisting user * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. */ - user: User; - /** Extra header values to be passed along with a request */ - authHeaders: { - [header: string]: string; - }; + user?: User; + /** Header values to set for this token */ + headers: Map; } -declare type TokenType = 'OAuth' | 'FirstParty'; +declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; /** * A reference to a transaction. @@ -5310,16 +7804,18 @@ declare type TokenType = 'OAuth' | 'FirstParty'; * {@link runTransaction}. */ export declare class Transaction extends Transaction_2 { - protected readonly _firestore: FirebaseFirestore; + protected readonly _firestore: Firestore; /** @hideconstructor */ - constructor(_firestore: FirebaseFirestore, _transaction: Transaction_3); + constructor(_firestore: Firestore, _transaction: Transaction_3); /** * Reads the document referenced by the provided {@link DocumentReference}. * * @param documentRef - A reference to the document to be read. * @returns A `DocumentSnapshot` with the read data. */ - get(documentRef: DocumentReference): Promise>; + get( + documentRef: DocumentReference + ): Promise>; } /** @@ -5330,27 +7826,33 @@ export declare class Transaction extends Transaction_2 { * {@link runTransaction}. */ declare class Transaction_2 { - protected readonly _firestore: FirebaseFirestore_2; + protected readonly _firestore: Firestore_2; private readonly _transaction; private readonly _dataReader; /** @hideconstructor */ - constructor(_firestore: FirebaseFirestore_2, _transaction: Transaction_3); + constructor(_firestore: Firestore_2, _transaction: Transaction_3); /** * Reads the document referenced by the provided {@link DocumentReference}. * * @param documentRef - A reference to the document to be read. * @returns A `DocumentSnapshot` with the read data. */ - get(documentRef: DocumentReference): Promise>; + get( + documentRef: DocumentReference + ): Promise>; /** * Writes to the document referred to by the provided {@link * DocumentReference}. If the document does not exist yet, it will be created. * * @param documentRef - A reference to the document to be set. * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. * @returns This `Transaction` instance. Used for chaining method calls. */ - set(documentRef: DocumentReference, data: T): this; + set( + documentRef: DocumentReference, + data: WithFieldValue + ): this; /** * Writes to the document referred to by the provided {@link * DocumentReference}. If the document does not exist yet, it will be created. @@ -5360,11 +7862,12 @@ declare class Transaction_2 { * @param documentRef - A reference to the document to be set. * @param data - An object of the fields and values for the document. * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. * @returns This `Transaction` instance. Used for chaining method calls. */ - set( - documentRef: DocumentReference, - data: Partial, + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, options: SetOptions ): this; /** @@ -5376,9 +7879,13 @@ declare class Transaction_2 { * @param data - An object containing the fields and values with which to * update the document. Fields can contain dots to reference nested fields * within the document. + * @throws Error - If the provided input is not valid Firestore data. * @returns This `Transaction` instance. Used for chaining method calls. */ - update(documentRef: DocumentReference, data: UpdateData): this; + update( + documentRef: DocumentReference, + data: UpdateData + ): this; /** * Updates fields in the document referred to by the provided {@link * DocumentReference}. The update will fail if applied to a document that does @@ -5391,10 +7898,11 @@ declare class Transaction_2 { * @param field - The first field to update. * @param value - The first value. * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. * @returns This `Transaction` instance. Used for chaining method calls. */ - update( - documentRef: DocumentReference, + update( + documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[] @@ -5405,7 +7913,9 @@ declare class Transaction_2 { * @param documentRef - A reference to the document to be deleted. * @returns This `Transaction` instance. Used for chaining method calls. */ - delete(documentRef: DocumentReference): this; + delete( + documentRef: DocumentReference + ): this; } /** @@ -5421,7 +7931,7 @@ declare class Transaction_3 { * A deferred usage error that occurred previously in this transaction that * will cause the transaction to fail once it actually commits. */ - private lastWriteError; + private lastTransactionError; /** * Set of documents that have been written in the transaction. * @@ -5430,10 +7940,10 @@ declare class Transaction_3 { */ private writtenDocs; constructor(datastore: Datastore); - lookup(keys: DocumentKey[]): Promise; - set(key: DocumentKey, data: ParsedSetData): void; - update(key: DocumentKey, data: ParsedUpdateData): void; - delete(key: DocumentKey): void; + lookup(keys: _DocumentKey[]): Promise; + set(key: _DocumentKey, data: ParsedSetData): void; + update(key: _DocumentKey, data: ParsedUpdateData): void; + delete(key: _DocumentKey): void; commit(): Promise; private recordVersion; /** @@ -5449,6 +7959,30 @@ declare class Transaction_3 { private ensureCommitNotCalled; } +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} + /** Used to represent a field transform on a mutation. */ declare class TransformOperation { private _; @@ -5461,7 +7995,27 @@ declare type UnaryFilterOp = | 'IS_NOT_NAN' | 'IS_NOT_NULL'; +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = ( + U extends unknown ? (k: U) => void : never +) extends (k: infer I) => void + ? I + : never; + +/** + * A function returned by `onSnapshot()` that removes the listener when invoked. + */ export declare interface Unsubscribe { + /** Removes the listener when invoked. */ (): void; } @@ -5469,20 +8023,33 @@ export declare interface Unsubscribe { * An untyped Firestore Data Converter interface that is shared between the * lite, firestore-exp and classic SDK. */ -declare interface UntypedFirestoreDataConverter { - toFirestore(modelObject: T): DocumentData_2; - toFirestore(modelObject: Partial, options: SetOptions_2): DocumentData_2; - fromFirestore(snapshot: unknown, options?: unknown): T; +declare interface UntypedFirestoreDataConverter< + AppModelType, + DbModelType extends DocumentData_2 = DocumentData_2 +> { + toFirestore( + modelObject: WithFieldValue + ): WithFieldValue; + toFirestore( + modelObject: PartialWithFieldValue, + options: SetOptions_2 + ): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; } /** - * Update data (for use with {@link updateDoc}) consists of field paths (e.g. - * 'foo' or 'foo.baz') mapped to values. Fields that contain dots reference - * nested fields within the document. + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. */ -export declare interface UpdateData { - [fieldPath: string]: any; -} +export declare type UpdateData = T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]?: UpdateData | FieldValue; + } & NestedUpdateFields + : Partial; /** * Updates fields in the document referred to by the specified @@ -5493,12 +8060,15 @@ export declare interface UpdateData { * @param data - An object containing the fields and values with which to * update the document. Fields can contain dots to reference nested fields * within the document. - * @returns A Promise resolved once the data has been successfully written + * @returns A `Promise` resolved once the data has been successfully written * to the backend (note that it won't resolve while you're offline). */ -export declare function updateDoc( - reference: DocumentReference, - data: UpdateData +export declare function updateDoc< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + data: UpdateData ): Promise; /** @@ -5513,33 +8083,19 @@ export declare function updateDoc( * @param field - The first field to update. * @param value - The first value. * @param moreFieldsAndValues - Additional key value pairs. - * @returns A Promise resolved once the data has been successfully written + * @returns A `Promise` resolved once the data has been successfully written * to the backend (note that it won't resolve while you're offline). */ -export declare function updateDoc( - reference: DocumentReference, +export declare function updateDoc< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[] ): Promise; -/** - * Modify this instance to communicate with the Cloud Firestore emulator. - * - * Note: This must be called before this instance has been used to do any - * operations. - * - * @param firestore - The Firestore instance to configure to connect to the - * emulator. - * @param host - the emulator host (ex: localhost). - * @param port - the emulator port (ex: 9000). - */ -export declare function useFirestoreEmulator( - firestore: FirebaseFirestore_2, - host: string, - port: number -): void; - /** * @license * Copyright 2017 Google LLC @@ -5566,6 +8122,7 @@ declare class User { static readonly UNAUTHENTICATED: User; static readonly GOOGLE_CREDENTIALS: User; static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; constructor(uid: string | null); isAuthenticated(): boolean; /** @@ -5576,10 +8133,56 @@ declare class User { isEqual(otherUser: User): boolean; } +/* Excluded from this release type: _validateIsNotUsedTogether */ + declare type Value = firestoreV1ApiClientInterfaces.Value; declare type ValueNullValue = 'NULL_VALUE'; +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link FieldValue.vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + private readonly _values; + /* Excluded from this release type: __constructor */ + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; +} + declare class ViewSnapshot { readonly query: Query_2; readonly docs: DocumentSet; @@ -5589,6 +8192,7 @@ declare class ViewSnapshot { readonly fromCache: boolean; readonly syncStateChanged: boolean; readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; constructor( query: Query_2, docs: DocumentSet, @@ -5597,14 +8201,16 @@ declare class ViewSnapshot { mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, - excludesMetadataChanges: boolean + excludesMetadataChanges: boolean, + hasCachedResults: boolean ); /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments( query: Query_2, documents: DocumentSet, mutatedKeys: DocumentKeySet, - fromCache: boolean + fromCache: boolean, + hasCachedResults: boolean ): ViewSnapshot; get hasPendingWrites(): boolean; isEqual(other: ViewSnapshot): boolean; @@ -5614,38 +8220,38 @@ declare class ViewSnapshot { * Waits until all currently pending writes for the active user have been * acknowledged by the backend. * - * The returned Promise resolves immediately if there are no outstanding writes. - * Otherwise, the Promise waits for all previously issued writes (including + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including * those written in a previous app session), but it does not wait for writes * that were added after the function is called. If you want to wait for * additional writes, call `waitForPendingWrites()` again. * - * Any outstanding `waitForPendingWrites()` Promises are rejected during user + * Any outstanding `waitForPendingWrites()` promises are rejected during user * changes. * - * @returns A Promise which resolves when all currently pending writes have been + * @returns A `Promise` which resolves when all currently pending writes have been * acknowledged by the backend. */ export declare function waitForPendingWrites( - firestore: FirebaseFirestore + firestore: Firestore ): Promise; /** - * Creates a `QueryConstraint` that enforces that documents must contain the - * specified field and that the value should satisfy the relation constraint - * provided. + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. * * @param fieldPath - The path to compare * @param opStr - The operation string (e.g "<", "<=", "==", "<", * "<=", "!="). * @param value - The value for comparison - * @returns The created `Query`. + * @returns The created {@link QueryFieldFilterConstraint}. */ export declare function where( fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown -): QueryConstraint; +): QueryFieldFilterConstraint; /** * Filter conditions in a {@link where} clause are specified using the @@ -5664,12 +8270,26 @@ export declare type WhereFilterOp = | 'array-contains-any' | 'not-in'; +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = + | T + | (T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]: WithFieldValue | FieldValue; + } + : never); + /** * A write batch, used to perform multiple writes as a single atomic unit. * * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It * provides methods for adding writes to the write batch. None of the writes - * will be committed (or visible locally) until {@link WriteBatch#commit} is + * will be committed (or visible locally) until {@link WriteBatch.commit} is * called. */ export declare class WriteBatch { @@ -5680,7 +8300,7 @@ export declare class WriteBatch { private _committed; /** @hideconstructor */ constructor( - _firestore: FirebaseFirestore_2, + _firestore: Firestore_2, _commitHandler: (m: Mutation[]) => Promise ); /** @@ -5691,7 +8311,10 @@ export declare class WriteBatch { * @param data - An object of the fields and values for the document. * @returns This `WriteBatch` instance. Used for chaining method calls. */ - set(documentRef: DocumentReference, data: T): WriteBatch; + set( + documentRef: DocumentReference, + data: WithFieldValue + ): WriteBatch; /** * Writes to the document referred to by the provided {@link * DocumentReference}. If the document does not exist yet, it will be created. @@ -5701,11 +8324,12 @@ export declare class WriteBatch { * @param documentRef - A reference to the document to be set. * @param data - An object of the fields and values for the document. * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. * @returns This `WriteBatch` instance. Used for chaining method calls. */ - set( - documentRef: DocumentReference, - data: Partial, + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, options: SetOptions ): WriteBatch; /** @@ -5717,9 +8341,13 @@ export declare class WriteBatch { * @param data - An object containing the fields and values with which to * update the document. Fields can contain dots to reference nested fields * within the document. + * @throws Error - If the provided input is not valid Firestore data. * @returns This `WriteBatch` instance. Used for chaining method calls. */ - update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + update( + documentRef: DocumentReference, + data: UpdateData + ): WriteBatch; /** * Updates fields in the document referred to by this {@link * DocumentReference}. The update will fail if applied to a document that does @@ -5732,10 +8360,11 @@ export declare class WriteBatch { * @param field - The first field to update. * @param value - The first value. * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. * @returns This `WriteBatch` instance. Used for chaining method calls. */ - update( - documentRef: DocumentReference, + update( + documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[] @@ -5746,16 +8375,18 @@ export declare class WriteBatch { * @param documentRef - A reference to the document to be deleted. * @returns This `WriteBatch` instance. Used for chaining method calls. */ - delete(documentRef: DocumentReference): WriteBatch; + delete( + documentRef: DocumentReference + ): WriteBatch; /** * Commits all of the writes in this write batch as a single atomic unit. * * The result of these writes will only be reflected in document reads that - * occur after the returned Promise resolves. If the client is offline, the + * occur after the returned promise resolves. If the client is offline, the * write fails. If you would like to see local modifications or buffer writes * until the client is online, use the full Firestore SDK. * - * @returns A Promise resolved once all of the writes in the batch have been + * @returns A `Promise` resolved once all of the writes in the batch have been * successfully written to the backend as an atomic unit (note that it won't * resolve while you're offline). */ @@ -5765,15 +8396,15 @@ export declare class WriteBatch { /** * Creates a write batch, used for performing multiple writes as a single - * atomic operation. The maximum number of writes allowed in a single WriteBatch + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} * is 500. * * Unlike transactions, write batches are persisted offline and therefore are * preferable when you don't need to condition your writes on read data. * - * @returns A `WriteBatch` that can be used to atomically execute multiple + * @returns A {@link WriteBatch} that can be used to atomically execute multiple * writes. */ -export declare function writeBatch(firestore: FirebaseFirestore): WriteBatch; +export declare function writeBatch(firestore: Firestore): WriteBatch; export {}; diff --git a/repo-scripts/prune-dts/tests/firestore.output.d.ts b/repo-scripts/prune-dts/tests/firestore.output.d.ts index 58411538953..33048292e38 100644 --- a/repo-scripts/prune-dts/tests/firestore.output.d.ts +++ b/repo-scripts/prune-dts/tests/firestore.output.d.ts @@ -1,25 +1,13 @@ /** - * @license - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Cloud Firestore * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * @packageDocumentation */ import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; import { FirebaseApp } from '@firebase/app'; -import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; -import { _FirebaseService } from '@firebase/app'; +import { FirebaseError } from '@firebase/util'; import { LogLevelString as LogLevel } from '@firebase/logger'; -import { Provider } from '@firebase/component'; import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; /** * Add a new document to specified `CollectionReference` with the given data, @@ -27,17 +15,133 @@ import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; * * @param reference - A reference to the collection to add this document to. * @param data - An Object containing the data for the new document. - * @returns A Promise resolved with a `DocumentReference` pointing to the + * @returns A `Promise` resolved with a `DocumentReference` pointing to the * newly created document after it has been written to the backend (Note that it * won't resolve while you're offline). */ -export declare function addDoc( - reference: CollectionReference, - data: T -): Promise>; +export declare function addDoc( + reference: CollectionReference, + data: WithFieldValue +): Promise>; +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys< + Prefix extends string, + T extends Record +> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + /** A type string to uniquely identify instances of this class. */ + readonly type = 'AggregateField'; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; +} +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual( + left: AggregateField, + right: AggregateField +): boolean; +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = + | ReturnType + | ReturnType + | ReturnType; +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot< + AggregateSpecType extends AggregateSpec, + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + /** A type string to uniquely identify instances of this class. */ + readonly type = 'AggregateQuerySnapshot'; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + private constructor(); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual< + AggregateSpecType extends AggregateSpec, + AppModelType, + DbModelType extends DocumentData +>( + left: AggregateQuerySnapshot, + right: AggregateQuerySnapshot +): boolean; +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and( + ...queryConstraints: QueryFilterConstraint[] +): QueryCompositeFilterConstraint; /** * Returns a special value that can be used with {@link (setDoc:1)} or {@link - * updateDoc} that tells the server to remove the given elements from any + * updateDoc:1} that tells the server to remove the given elements from any * array value that already exists on the server. All instances of each element * specified will be removed from the array. If the field being modified is not * already an array it will be overwritten with an empty array. @@ -48,8 +152,8 @@ export declare function addDoc( */ export declare function arrayRemove(...elements: unknown[]): FieldValue; /** - * Returns a special value that can be used with {@link setDoc} or {@link - * updateDoc} that tells the server to union the given elements with any array + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array * value that already exists on the server. Each specified element that doesn't * already exist in the array will be added to the end. If the field being * modified is not already an array it will be overwritten with an array @@ -60,6 +164,16 @@ export declare function arrayRemove(...elements: unknown[]): FieldValue; * `updateDoc()`. */ export declare function arrayUnion(...elements: unknown[]): FieldValue; +/* Excluded from this release type: AuthTokenFactory */ +/* Excluded from this release type: _AutoId */ +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average( + field: string | FieldPath +): AggregateField; /** * An immutable object representing an array of bytes. */ @@ -104,20 +218,37 @@ export declare class Bytes { */ isEqual(other: Bytes): boolean; } +/* Excluded from this release type: _ByteString */ /** * Constant used to indicate the LRU garbage collection should be disabled. * Set this value as the `cacheSizeBytes` on the settings passed to the - * `Firestore` instance. + * {@link Firestore} instance. */ export declare const CACHE_SIZE_UNLIMITED = -1; +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record< + string, + unknown +> + ? AddPrefixToKeys> + : never; /** * Clears the persistent storage. This includes pending writes and cached * documents. * - * Must be called while the `Firestore` instance is not started (after the app is + * Must be called while the {@link Firestore} instance is not started (after the app is * terminated or when the app is first initialized). On startup, this function * must be called before other functions (other than {@link - * initializeFirestore} or {@link getFirestore})). If the `Firestore` + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} * instance is still running, the promise will be rejected with the error code * of `failed-precondition`. * @@ -128,18 +259,18 @@ export declare const CACHE_SIZE_UNLIMITED = -1; * to the disclosure of cached data in between user sessions, we strongly * recommend not enabling persistence at all. * - * @param firestore - The `Firestore` instance to clear persistence for. - * @returns A promise that is resolved when the persistent storage is + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is * cleared. Otherwise, the promise is rejected with an error. */ export declare function clearIndexedDbPersistence( - firestore: FirebaseFirestore + firestore: Firestore ): Promise; /** * Gets a `CollectionReference` instance that refers to the collection at * the specified absolute path. * - * @param firestore - A reference to the root Firestore instance. + * @param firestore - A reference to the root `Firestore` instance. * @param path - A slash-separated path to a collection. * @param pathSegments - Additional path segments to apply relative to the first * argument. @@ -148,10 +279,10 @@ export declare function clearIndexedDbPersistence( * @returns The `CollectionReference` instance. */ export declare function collection( - firestore: FirebaseFirestore, + firestore: Firestore, path: string, ...pathSegments: string[] -): CollectionReference; +): CollectionReference; /** * Gets a `CollectionReference` instance that refers to a subcollection of * `reference` at the specified relative path. @@ -164,11 +295,14 @@ export declare function collection( * to a collection. * @returns The `CollectionReference` instance. */ -export declare function collection( - reference: CollectionReference, +export declare function collection< + AppModelType, + DbModelType extends DocumentData +>( + reference: CollectionReference, path: string, ...pathSegments: string[] -): CollectionReference; +): CollectionReference; /** * Gets a `CollectionReference` instance that refers to a subcollection of * `reference` at the specified relative path. @@ -181,32 +315,38 @@ export declare function collection( * to a collection. * @returns The `CollectionReference` instance. */ -export declare function collection( - reference: DocumentReference, +export declare function collection< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, path: string, ...pathSegments: string[] -): CollectionReference; +): CollectionReference; /** * Creates and returns a new `Query` instance that includes all documents in the * database that are contained in a collection or subcollection with the * given `collectionId`. * - * @param firestore - A reference to the root Firestore instance. + * @param firestore - A reference to the root `Firestore` instance. * @param collectionId - Identifies the collections to query over. Every * collection or subcollection with this ID as the last segment of its path * will be included. Cannot contain a slash. * @returns The created `Query`. */ export declare function collectionGroup( - firestore: FirebaseFirestore, + firestore: Firestore, collectionId: string -): Query; +): Query; /** * A `CollectionReference` object can be used for adding documents, getting - * document references, and querying for documents (using {@link query}). + * document references, and querying for documents (using {@link (query:1)}). */ -export declare class CollectionReference extends Query { - readonly firestore: FirebaseFirestore; +export declare class CollectionReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> extends Query { + /** The type of this Firestore reference. */ readonly type = 'collection'; private constructor(); /** The collection's identifier. */ @@ -220,20 +360,69 @@ export declare class CollectionReference extends Query { * A reference to the containing `DocumentReference` if this is a * subcollection. If this isn't a subcollection, the reference is null. */ - get parent(): DocumentReference | null; + get parent(): DocumentReference | null; /** - * Applies a custom data converter to this CollectionReference, allowing you + * Applies a custom data converter to this `CollectionReference`, allowing you * to use your own custom model objects with Firestore. When you call {@link * addDoc} with the returned `CollectionReference` instance, the provided - * converter will convert between Firestore data and your custom type `U`. + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. * * @param converter - Converts objects to and from Firestore. - * @returns A `CollectionReference` that uses the provided converter. + * @returns A `CollectionReference` that uses the provided converter. */ - withConverter( - converter: FirestoreDataConverter - ): CollectionReference; + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData + >( + converter: FirestoreDataConverter + ): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter( + converter: null + ): CollectionReference; } +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator( + firestore: Firestore, + host: string, + port: number, + options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + } +): void; +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +export declare function deleteAllPersistentCacheIndexes( + indexManager: PersistentCacheIndexManager +): void; /** * Deletes the document referred to by the specified `DocumentReference`. * @@ -241,12 +430,13 @@ export declare class CollectionReference extends Query { * @returns A Promise resolved once the document has been successfully * deleted from the backend (note that it won't resolve while you're offline). */ -export declare function deleteDoc( - reference: DocumentReference -): Promise; +export declare function deleteDoc< + AppModelType, + DbModelType extends DocumentData +>(reference: DocumentReference): Promise; /** - * Returns a sentinel for use with {@link updateDoc} or - * {@link setDoc} with `{merge: true}` to mark a field for deletion. + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. */ export declare function deleteField(): FieldValue; /** @@ -255,16 +445,22 @@ export declare function deleteField(): FieldValue; * `getDoc()` or `getDocs()` calls will return results from cache, and any write * operations will be queued until the network is restored. * - * @returns A promise that is resolved once the network has been disabled. + * @returns A `Promise` that is resolved once the network has been disabled. */ -export declare function disableNetwork( - firestore: FirebaseFirestore -): Promise; +export declare function disableNetwork(firestore: Firestore): Promise; +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +export declare function disablePersistentCacheIndexAutoCreation( + indexManager: PersistentCacheIndexManager +): void; /** * Gets a `DocumentReference` instance that refers to the document at the * specified absolute path. * - * @param firestore - A reference to the root Firestore instance. + * @param firestore - A reference to the root `Firestore` instance. * @param path - A slash-separated path to a document. * @param pathSegments - Additional path segments that will be applied relative * to the first argument. @@ -273,10 +469,10 @@ export declare function disableNetwork( * @returns The `DocumentReference` instance. */ export declare function doc( - firestore: FirebaseFirestore, + firestore: Firestore, path: string, ...pathSegments: string[] -): DocumentReference; +): DocumentReference; /** * Gets a `DocumentReference` instance that refers to a document within * `reference` at the specified relative path. If no path is specified, an @@ -292,11 +488,11 @@ export declare function doc( * a document. * @returns The `DocumentReference` instance. */ -export declare function doc( - reference: CollectionReference, +export declare function doc( + reference: CollectionReference, path?: string, ...pathSegments: string[] -): DocumentReference; +): DocumentReference; /** * Gets a `DocumentReference` instance that refers to a document within * `reference` at the specified relative path. @@ -309,20 +505,23 @@ export declare function doc( * a document. * @returns The `DocumentReference` instance. */ -export declare function doc( - reference: DocumentReference, +export declare function doc( + reference: DocumentReference, path: string, ...pathSegments: string[] -): DocumentReference; +): DocumentReference; /** * A `DocumentChange` represents a change to the documents matching a query. * It contains the document affected and the type of change that occurred. */ -export declare interface DocumentChange { +export declare 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; + 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 @@ -342,10 +541,11 @@ export declare interface DocumentChange { */ export declare type DocumentChangeType = 'added' | 'removed' | 'modified'; /** - * Document data (for use with {@link setDoc}) consists of fields mapped to + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to * values. */ export declare interface DocumentData { + /** A mapping between a field and its value. */ [field: string]: any; } /** @@ -358,14 +558,21 @@ export declare function documentId(): FieldPath; * and can be used to write, read, or listen to the location. The document at * the referenced location may or may not exist. */ -export declare class DocumentReference { +export declare class DocumentReference< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; /** The type of this Firestore reference. */ readonly type = 'document'; /** - * The {@link FirebaseFirestore} the document is in. + * The {@link Firestore} instance the document is in. * This is useful for performing transactions, for example. */ - readonly firestore: FirebaseFirestore; + readonly firestore: Firestore; private constructor(); /** * The document's identifier within its collection. @@ -379,18 +586,31 @@ export declare class DocumentReference { /** * The collection this `DocumentReference` belongs to. */ - get parent(): CollectionReference; + get parent(): CollectionReference; /** * Applies a custom data converter to this `DocumentReference`, allowing you * to use your own custom model objects with Firestore. When you call {@link - * setDoc}, {@link getDoc}, etc. with the returned `DocumentReference` - * instance, the provided converter will convert between Firestore data and - * your custom type `U`. + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. * * @param converter - Converts objects to and from Firestore. - * @returns A `DocumentReference` that uses the provided converter. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData + >( + converter: FirestoreDataConverter + ): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. */ - withConverter(converter: FirestoreDataConverter): DocumentReference; + withConverter(converter: null): DocumentReference; } /** * A `DocumentSnapshot` contains data read from a document in your Firestore @@ -401,7 +621,10 @@ export declare class DocumentReference { * access will return 'undefined'. You can use the `exists()` method to * explicitly verify a document's existence. */ -export declare class DocumentSnapshot { +export declare class DocumentSnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { /** * Metadata about the `DocumentSnapshot`, including information about its * source and local modifications. @@ -409,15 +632,14 @@ export declare class DocumentSnapshot { readonly metadata: SnapshotMetadata; protected constructor(); /** - * Property of the `DocumentSnapshot` that signals whether or not the data - * exists. True if the document exists. + * Returns whether or not the data exists. True if the document exists. */ - exists(): this is QueryDocumentSnapshot; + exists(): this is QueryDocumentSnapshot; /** * Retrieves all fields in the document as an `Object`. Returns `undefined` if * the document doesn't exist. * - * By default, `FieldValue.serverTimestamp()` values that have not yet been + * By default, `serverTimestamp()` values that have not yet been * set to their final value will be returned as `null`. You can override * this by passing an options object. * @@ -427,12 +649,12 @@ export declare class DocumentSnapshot { * @returns An `Object` containing all fields in the document or `undefined` if * the document doesn't exist. */ - data(options?: SnapshotOptions): T | undefined; + data(options?: SnapshotOptions): AppModelType | undefined; /** * Retrieves the field specified by `fieldPath`. Returns `undefined` if the * document or field doesn't exist. * - * By default, a `FieldValue.serverTimestamp()` that has not yet been set to + * By default, a `serverTimestamp()` that has not yet been set to * its final value will be returned as `null`. You can override this by * passing an options object. * @@ -452,33 +674,42 @@ export declare class DocumentSnapshot { /** * The `DocumentReference` for the document included in the `DocumentSnapshot`. */ - get ref(): DocumentReference; + get ref(): DocumentReference; } +/* Excluded from this release type: _EmptyAppCheckTokenProvider */ +/* Excluded from this release type: _EmptyAuthCredentialsProvider */ +export { EmulatorMockTokenOptions }; /** * Attempts to enable persistent storage, if possible. * - * Must be called before any other functions (other than - * {@link initializeFirestore}, {@link getFirestore} or - * {@link clearIndexedDbPersistence}. + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. * - * If this fails, `enableIndexedDbPersistence()` will reject the promise it - * returns. Note that even after this failure, the `Firestore` instance will - * remain usable, however offline persistence will be disabled. + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. * - * There are several reasons why this can fail, which can be identified by - * the `code` on the error. + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. * - * * failed-precondition: The app is already open in another browser tab. - * * unimplemented: The browser is incompatible with the offline - * persistence implementation. + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. * - * @param firestore - The `Firestore` instance to enable persistence for. + * @param firestore - The {@link Firestore} instance to enable persistence for. * @param persistenceSettings - Optional settings object to configure * persistence. - * @returns A promise that represents successfully enabling persistent storage. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. */ export declare function enableIndexedDbPersistence( - firestore: FirebaseFirestore, + firestore: Firestore, persistenceSettings?: PersistenceSettings ): Promise; /** @@ -487,78 +718,140 @@ export declare function enableIndexedDbPersistence( * shared execution of queries and latency-compensated local document updates * across all connected instances. * - * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise - * it returns. Note that even after this failure, the `Firestore` instance will - * remain usable, however offline persistence will be disabled. - * - * There are several reasons why this can fail, which can be identified by - * the `code` on the error. + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. * * * failed-precondition: The app is already open in another browser tab and * multi-tab is not enabled. - * * unimplemented: The browser is incompatible with the offline - * persistence implementation. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. * - * @param firestore - The `Firestore` instance to enable persistence for. - * @returns A promise that represents successfully enabling persistent + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. */ export declare function enableMultiTabIndexedDbPersistence( - firestore: FirebaseFirestore + firestore: Firestore ): Promise; /** - * Re-enables use of the network for this Firestore instance after a prior + * Re-enables use of the network for this {@link Firestore} instance after a prior * call to {@link disableNetwork}. * - * @returns A promise that is resolved once the network has been enabled. + * @returns A `Promise` that is resolved once the network has been enabled. */ -export declare function enableNetwork( - firestore: FirebaseFirestore -): Promise; +export declare function enableNetwork(firestore: Firestore): Promise; +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +export declare function enablePersistentCacheIndexAutoCreation( + indexManager: PersistentCacheIndexManager +): void; /** - * Creates a `QueryConstraint` that modifies the result set to end at the - * provided document (inclusive). The end position is relative to the order of - * the query. The document must contain all of the fields provided in the + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the * orderBy of the query. * * @param snapshot - The snapshot of the document to end at. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ -export declare function endAt( - snapshot: DocumentSnapshot -): QueryConstraint; +export declare function endAt( + snapshot: DocumentSnapshot +): QueryEndAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to end at the - * provided fields relative to the order of the query. The order of the field + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field * values must match the order of the order by clauses of the query. * * @param fieldValues - The field values to end this query at, in order * of the query's order by. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ -export declare function endAt(...fieldValues: unknown[]): QueryConstraint; +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to end before the - * provided document (exclusive). The end position is relative to the order of - * the query. The document must contain all of the fields provided in the - * orderBy of the query. + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. * * @param snapshot - The snapshot of the document to end before. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ -export declare function endBefore( - snapshot: DocumentSnapshot -): QueryConstraint; +export declare function endBefore< + AppModelType, + DbModelType extends DocumentData +>(snapshot: DocumentSnapshot): QueryEndAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to end before the - * provided fields relative to the order of the query. The order of the field - * values must match the order of the order by clauses of the query. + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. * * @param fieldValues - The field values to end this query before, in order * of the query's order by. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryEndAtConstraint} to pass to `query()` */ -export declare function endBefore(...fieldValues: unknown[]): QueryConstraint; +export declare function endBefore( + ...fieldValues: unknown[] +): QueryEndAtConstraint; +/* Excluded from this release type: executeWrite */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +export declare interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} /** * 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 @@ -569,7 +862,7 @@ export declare function endBefore(...fieldValues: unknown[]): QueryConstraint; */ export declare class FieldPath { /** - * Creates a FieldPath from the provided field names. If more than one field + * 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. @@ -588,119 +881,286 @@ export declare class FieldPath { * or `update()`. */ export declare abstract class FieldValue { - /** - * @param _methodName - The public API endpoint that returns this class. - */ - constructor(_methodName: string); + private constructor(); + /** Compares `FieldValue`s for equality. */ abstract isEqual(other: FieldValue): boolean; } +/* Excluded from this release type: _FirebaseService */ /** * The Cloud Firestore service interface. * - * Do not call this constructor directly. Instead, use {@link getFirestore}. + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. */ -export declare class FirebaseFirestore { +export declare class Firestore { + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; private constructor(); /** - * The {@link FirebaseApp} associated with this `Firestore` service + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service * instance. */ get app(): FirebaseApp; + /** + * Returns a JSON-serializable representation of this `Firestore` instance. + */ toJSON(): object; } /** - * Converter used by `withConverter()` to transform user objects of type `T` - * into Firestore data. + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. * * Using the converter allows you to specify generic type arguments when * storing and retrieving objects from Firestore. * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * * @example + * + * Simple Example + * * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. * class Post { - * constructor(readonly title: string, readonly author: string) {} + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } * - * 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; * } * - * const postConverter = { - * toFirestore(post: Post): firebase.firestore.DocumentData { - * return {title: post.title, author: post.author}; - * }, - * fromFirestore( - * snapshot: firebase.firestore.QueryDocumentSnapshot, - * options: firebase.firestore.SnapshotOptions - * ): Post { - * const data = snapshot.data(options)!; - * return new Post(data.title, data.author); - * } - * }; + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } * - * const postSnap = await firebase.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 + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } * } * ``` */ -export declare interface FirestoreDataConverter { +export declare interface FirestoreDataConverter< + AppModelType, + DbModelType extends DocumentData = DocumentData +> { /** - * Called by the Firestore SDK to convert a custom model object of type `T` - * into a plain JavaScript object (suitable for writing directly to the - * Firestore database). To use `set()` with `merge` and `mergeFields`, - * `toFirestore()` must be defined with `Partial`. - */ - toFirestore(modelObject: T): DocumentData; - /** - * Called by the Firestore SDK to convert a custom model object of type `T` - * into a plain JavaScript object (suitable for writing directly to the - * Firestore database). Used with {@link setData}, {@link WriteBatch#set} - * and {@link Transaction#set} with `merge:true` or `mergeFields`. + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. To use `set()` + * with `merge` and `mergeFields`, `toFirestore()` must be defined with + * `PartialWithFieldValue`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore( + modelObject: WithFieldValue + ): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and + * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. */ - toFirestore(modelObject: Partial, options: SetOptions): DocumentData; + toFirestore( + modelObject: PartialWithFieldValue, + options: SetOptions + ): PartialWithFieldValue; /** * Called by the Firestore SDK to convert Firestore data into an object of - * type T. You can access your data by calling: `snapshot.data(options)`. + * type `AppModelType`. You can access your data by calling: + * `snapshot.data(options)`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. * * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. * @param options - The `SnapshotOptions` from the initial call to `data()`. */ fromFirestore( - snapshot: QueryDocumentSnapshot, + snapshot: QueryDocumentSnapshot, options?: SnapshotOptions - ): T; + ): AppModelType; } /** An error returned by a Firestore operation. */ -export declare class FirestoreError extends Error { +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ readonly message: string; - readonly name: string; + /** The stack of the error. */ readonly stack?: string; private constructor(); } -/** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ /** * The set of Firestore status codes. The codes are the same at the ones * exposed by gRPC here: @@ -757,6 +1217,100 @@ export declare type FirestoreErrorCode = | 'unavailable' | 'data-loss' | 'unauthenticated'; +/** + * Union type from all supported SDK cache layer. + */ +export declare type FirestoreLocalCache = + | MemoryLocalCache + | PersistentLocalCache; +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface FirestoreSettings { + /** + * NOTE: This field will be deprecated in a future major release. Use `cache` field + * instead to specify cache size, and other cache configurations. + * + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The size is not a guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` + * and `PersistentLocalCache`, each with different configuration options. + * + * When unspecified, `MemoryLocalCache` will be used by default. + * + * NOTE: setting this field and `cacheSizeBytes` at the same time will throw + * exception during SDK initialization. Instead, using the configuration in + * the `FirestoreLocalCache` object to specify the cache size. + */ + localCache?: FirestoreLocalCache; + /** + * Forces the SDK’s underlying network transport (WebChannel) to use + * long-polling. Each response from the backend will be closed immediately + * after the backend sends data (by default responses are kept open in + * case the backend has more data to send). This avoids incompatibility + * issues with certain proxies, antivirus software, etc. that incorrectly + * buffer traffic indefinitely. Use of this option will cause some + * performance degradation though. + * + * This setting cannot be used with `experimentalAutoDetectLongPolling` and + * may be removed in a future release. If you find yourself using it to + * work around a specific network reliability issue, please tell us about + * it in https://github.com/firebase/firebase-js-sdk/issues/1674. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalForceLongPolling?: boolean; + /** + * Configures the SDK's underlying transport (WebChannel) to automatically + * detect if long-polling should be used. This is very similar to + * `experimentalForceLongPolling`, but only uses long-polling if required. + * + * After having had a default value of `false` since its inception in 2019, + * the default value of this setting was changed in May 2023 to `true` in + * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long + * polling is now enabled by default. To disable it, set this setting to + * `false`, and please open a GitHub issue to share the problems that + * motivated you disabling long-polling auto-detection. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalAutoDetectLongPolling?: boolean; + /** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * These options are only used if `experimentalForceLongPolling` is true or if + * `experimentalAutoDetectLongPolling` is true and the auto-detection + * determined that long-polling was needed. Otherwise, these options have no + * effect. + */ + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; + /** + * The hostname to connect to. + */ + host?: string; + /** + * Whether to use SSL when connecting. + */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} /** * @license * Copyright 2017 Google LLC @@ -803,11 +1357,90 @@ export declare class GeoPoint { * @returns true if this `GeoPoint` is equal to the provided one. */ isEqual(other: GeoPoint): boolean; + /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON(): { latitude: number; longitude: number; }; } +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregateFromServer< + AggregateSpecType extends AggregateSpec, + AppModelType, + DbModelType extends DocumentData +>( + query: Query, + aggregateSpec: AggregateSpecType +): Promise< + AggregateQuerySnapshot +>; +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCountFromServer< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise< + AggregateQuerySnapshot< + { + count: AggregateField; + }, + AppModelType, + DbModelType + > +>; /** * Reads the document referred to by this `DocumentReference`. * @@ -820,29 +1453,35 @@ export declare class GeoPoint { * @returns A Promise resolved with a `DocumentSnapshot` containing the * current document contents. */ -export declare function getDoc( - reference: DocumentReference -): Promise>; +export declare function getDoc( + reference: DocumentReference +): Promise>; /** * Reads the document referred to by this `DocumentReference` from cache. * Returns an error if the document is not currently cached. * - * @returns A Promise resolved with a `DocumentSnapshot` containing the + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the * current document contents. */ -export declare function getDocFromCache( - reference: DocumentReference -): Promise>; +export declare function getDocFromCache< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference +): Promise>; /** * Reads the document referred to by this `DocumentReference` from the server. * Returns an error if the network is not available. * - * @returns A Promise resolved with a `DocumentSnapshot` containing the + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the * current document contents. */ -export declare function getDocFromServer( - reference: DocumentReference -): Promise>; +export declare function getDocFromServer< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference +): Promise>; /** * Executes the query and returns the results as a `QuerySnapshot`. * @@ -851,40 +1490,92 @@ export declare function getDocFromServer( * you are offline and the server cannot be reached. To specify this behavior, * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. * - * @returns A Promise that will be resolved with the results of the query. + * @returns A `Promise` that will be resolved with the results of the query. */ -export declare function getDocs(query: Query): Promise>; +export declare function getDocs( + query: Query +): Promise>; /** * Executes the query and returns the results as a `QuerySnapshot` from cache. - * Returns an error if the document is not currently cached. + * Returns an empty result set if no documents matching the query are currently + * cached. * - * @returns A Promise that will be resolved with the results of the query. + * @returns A `Promise` that will be resolved with the results of the query. */ -export declare function getDocsFromCache( - query: Query -): Promise>; +export declare function getDocsFromCache< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise>; /** * Executes the query and returns the results as a `QuerySnapshot` from the * server. Returns an error if the network is not available. * - * @returns A Promise that will be resolved with the results of the query. + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromServer< + AppModelType, + DbModelType extends DocumentData +>( + query: Query +): Promise>; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The default {@link Firestore} instance of the default app. */ -export declare function getDocsFromServer( - query: Query -): Promise>; +export declare function getFirestore(): Firestore; /** - * Returns the existing instance of Firestore that is associated with the - * provided {@link FirebaseApp}. If no instance exists, initializes a new + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new * instance with default settings. * - * @param app - The {@link FirebaseApp} instance that the returned Firestore + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} * instance is associated with. - * @returns The `Firestore` instance of the provided app. + * @returns The default {@link Firestore} instance of the provided app. */ -export declare function getFirestore(app: FirebaseApp): FirebaseFirestore; +export declare function getFirestore(app: FirebaseApp): Firestore; /** - * Returns a special value that can be used with {@link setDoc} or {@link - * updateDoc} that tells the server to increment the field's current value by + * Returns the existing named {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the default app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore( + app: FirebaseApp, + databaseId: string +): Firestore; +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +export declare function getPersistentCacheIndexManager( + firestore: Firestore +): PersistentCacheIndexManager | null; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by * the given value. * * If either the operand or the current field value uses floating point @@ -903,50 +1594,122 @@ export declare function getFirestore(app: FirebaseApp): FirebaseFirestore; */ export declare function increment(n: number): FieldValue; /** - * Initializes a new instance of Cloud Firestore with the provided settings. + * The SDK definition of a Firestore index. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface Index { + /** The ID of the collection to index. */ + readonly collectionGroup: string; + /** A list of fields to index. */ + readonly fields?: IndexField[]; + [key: string]: unknown; +} +/** + * A list of Firestore indexes to speed up local query execution. + * + * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} + * for a description of the format of the index definition. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexConfiguration { + /** A list of all Firestore indexes. */ + readonly indexes?: Index[]; + [key: string]: unknown; +} +/** + * A single field element in an index configuration. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexField { + /** The field path to index. */ + readonly fieldPath: string; + /** + * What type of array index to create. Set to `CONTAINS` for `array-contains` + * and `array-contains-any` indexes. + * + * Only one of `arrayConfig` or `order` should be set; + */ + readonly arrayConfig?: 'CONTAINS'; + /** + * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for + * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. + * + * Only one of `arrayConfig` or `order` should be set. + */ + readonly order?: 'ASCENDING' | 'DESCENDING'; + [key: string]: unknown; +} +/** + * Initializes a new instance of {@link Firestore} with the provided settings. * Can only be called before any other function, including - * {@link getFirestore}. If the custom settings are empty, this function is - * equivalent to calling {@link getFirestore}. + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. * - * @param app - The {@link FirebaseApp} with which the `Firestore` instance will + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will * be associated. - * @param settings - A settings object to configure the `Firestore` instance. - * @returns A newly initialized `Firestore` instance. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. */ export declare function initializeFirestore( app: FirebaseApp, - settings: Settings -): FirebaseFirestore; + settings: FirestoreSettings, + databaseId?: string +): Firestore; /** - * Creates a `QueryConstraint` that only returns the first matching documents. + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. * * @param limit - The maximum number of items to return. - * @returns The created `Query`. + * @returns The created {@link QueryLimitConstraint}. */ -export declare function limit(limit: number): QueryConstraint; +export declare function limit(limit: number): QueryLimitConstraint; /** - * Creates a `QueryConstraint` that only returns the last matching documents. + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. * * You must specify at least one `orderBy` clause for `limitToLast` queries, * otherwise an exception will be thrown during execution. * * @param limit - The maximum number of items to return. - * @returns The created `Query`. + * @returns The created {@link QueryLimitConstraint}. */ -export declare function limitToLast(limit: number): QueryConstraint; +export declare function limitToLast(limit: number): QueryLimitConstraint; +/** + * Describe the source a query listens to. + * + * Set to `default` to listen to both cache and server changes. Set to `cache` + * to listen to changes in cache only. + */ +export declare type ListenSource = 'default' | 'cache'; /** * Loads a Firestore bundle into the local cache. * - * @param firestore - The `Firestore` instance to load bundles for for. - * @param bundleData - An object representing the bundle to be loaded. Valid objects are - * `ArrayBuffer`, `ReadableStream` or `string`. + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. * - * @return - * A `LoadBundleTask` object, which notifies callers with progress updates, and completion - * or error events. It can be used as a `Promise`. + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. */ export declare function loadBundle( - firestore: FirebaseFirestore, + firestore: Firestore, bundleData: ReadableStream | ArrayBuffer | string ): LoadBundleTask; /** @@ -1008,16 +1771,110 @@ export declare interface LoadBundleTaskProgress { } export { LogLevel }; /** - * Reads a Firestore `Query` from local cache, identified by the given name. + * An settings object to configure an `MemoryLocalCache` instance. + */ +export declare type MemoryCacheSettings = { + /** + * The garbage collector to use, for the memory cache layer. + * A `MemoryEagerGarbageCollector` is used when this is undefined. + */ + garbageCollector?: MemoryGarbageCollector; +}; +/** + * A garbage collector deletes documents whenever they are not part of any + * active queries, and have no local mutations attached to them. + * + * This collector tries to ensure lowest memory footprints from the SDK, + * at the risk of documents not being cached for offline queries or for + * direct queries to the cache. + * + * Use factory function {@link memoryEagerGarbageCollector()} to create an + * instance of this collector. + */ +export declare type MemoryEagerGarbageCollector = { + kind: 'memoryEager'; +}; +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector; +/** + * Union type from all support garbage collectors for memory local cache. + */ +export declare type MemoryGarbageCollector = + | MemoryEagerGarbageCollector + | MemoryLruGarbageCollector; +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare type MemoryLocalCache = { + kind: 'memory'; +}; +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +export declare function memoryLocalCache( + settings?: MemoryCacheSettings +): MemoryLocalCache; +/** + * A garbage collector deletes Least-Recently-Used documents in multiple + * batches. + * + * This collector is configured with a target size, and will only perform + * collection when the cached documents exceed the target size. It avoids + * querying backend repeated for the same query or document, at the risk + * of having a larger memory footprint. + * + * Use factory function {@link memoryLruGarbageCollector()} to create a + * instance of this collector. + */ +export declare type MemoryLruGarbageCollector = { + kind: 'memoryLru'; +}; +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +export declare function memoryLruGarbageCollector(settings?: { + cacheSizeBytes?: number; +}): MemoryLruGarbageCollector; +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. * * The named queries are packaged into bundles on the server side (along - * with resulting documents), and loaded to local cache using `loadBundle`. Once in local - * cache, use this method to extract a `Query` by name. + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. */ export declare function namedQuery( - firestore: FirebaseFirestore, + firestore: Firestore, name: string ): Promise; +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = + UnionToIntersection< + { + [K in keyof T & string]: ChildUpdateFields; + }[keyof T & string] + >; /** * Attaches a listener for `DocumentSnapshot` events. You may either pass * individual `onNext` and `onError` callbacks or pass a single observer @@ -1031,10 +1888,13 @@ export declare function namedQuery( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - reference: DocumentReference, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, observer: { - next?: (snapshot: DocumentSnapshot) => void; + next?: (snapshot: DocumentSnapshot) => void; error?: (error: FirestoreError) => void; complete?: () => void; } @@ -1053,11 +1913,14 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - reference: DocumentReference, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, options: SnapshotListenOptions, observer: { - next?: (snapshot: DocumentSnapshot) => void; + next?: (snapshot: DocumentSnapshot) => void; error?: (error: FirestoreError) => void; complete?: () => void; } @@ -1080,9 +1943,12 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - reference: DocumentReference, - onNext: (snapshot: DocumentSnapshot) => void, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe; @@ -1105,10 +1971,13 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - reference: DocumentReference, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, options: SnapshotListenOptions, - onNext: (snapshot: DocumentSnapshot) => void, + onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe; @@ -1126,10 +1995,13 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - query: Query, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, observer: { - next?: (snapshot: QuerySnapshot) => void; + next?: (snapshot: QuerySnapshot) => void; error?: (error: FirestoreError) => void; complete?: () => void; } @@ -1149,11 +2021,14 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - query: Query, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, options: SnapshotListenOptions, observer: { - next?: (snapshot: QuerySnapshot) => void; + next?: (snapshot: QuerySnapshot) => void; error?: (error: FirestoreError) => void; complete?: () => void; } @@ -1177,9 +2052,12 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - query: Query, - onNext: (snapshot: QuerySnapshot) => void, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, + onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe; @@ -1203,10 +2081,13 @@ export declare function onSnapshot( * @returns An unsubscribe function that can be called to cancel * the snapshot listener. */ -export declare function onSnapshot( - query: Query, +export declare function onSnapshot< + AppModelType, + DbModelType extends DocumentData +>( + query: Query, options: SnapshotListenOptions, - onNext: (snapshot: QuerySnapshot) => void, + onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe; @@ -1226,7 +2107,7 @@ export declare function onSnapshot( * listener. */ export declare function onSnapshotsInSync( - firestore: FirebaseFirestore, + firestore: Firestore, observer: { next?: (value: void) => void; error?: (error: FirestoreError) => void; @@ -1240,87 +2121,283 @@ export declare function onSnapshotsInSync( * * NOTE: The snapshots-in-sync event only indicates that listeners are in sync * with each other, but does not relate to whether those snapshots are in sync - * with the server. Use SnapshotMetadata in the individual listeners to + * with the server. Use `SnapshotMetadata` in the individual listeners to * determine if a snapshot is from the cache or the server. * - * @param firestore - The instance of Firestore for synchronizing snapshots. + * @param firestore - The `Firestore` instance for synchronizing snapshots. * @param onSync - A callback to be called every time all snapshot listeners are * in sync with each other. * @returns An unsubscribe function that can be called to cancel the snapshot * listener. */ export declare function onSnapshotsInSync( - firestore: FirebaseFirestore, + firestore: Firestore, onSync: () => void ): Unsubscribe; /** - * Creates a `QueryConstraint` that sorts the query result by the + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or( + ...queryConstraints: QueryFilterConstraint[] +): QueryCompositeFilterConstraint; +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the * specified field, optionally in descending order instead of ascending. * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * * @param fieldPath - The field to sort by. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If * not specified, order will be ascending. - * @returns The created `Query`. + * @returns The created {@link QueryOrderByConstraint}. */ export declare function orderBy( fieldPath: string | FieldPath, directionStr?: OrderByDirection -): QueryConstraint; +): QueryOrderByConstraint; /** * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' * (descending or ascending). */ export declare type OrderByDirection = 'desc' | 'asc'; +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = + | Partial + | (T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; + } + : never); +/** + * Settings that can be passed to `enableIndexedDbPersistence()` to configure + * Firestore persistence. + * + * Persistence cannot be used in a Node.js environment. + */ export declare interface PersistenceSettings { + /** + * Whether to force enable persistence for the client. This cannot be used + * with multi-tab synchronization and is primarily intended for use with Web + * Workers. Setting this to `true` will enable persistence, but cause other + * tabs using persistence to fail. + */ forceOwnership?: boolean; } /** - * A `Query` refers to a Query which you can read or listen to. You can also + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +export declare class PersistentCacheIndexManager { + /** A type string to uniquely identify instances of this class. */ + readonly type: 'PersistentCacheIndexManager'; + private constructor(); +} +/** + * An settings object to configure an `PersistentLocalCache` instance. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare type PersistentCacheSettings = { + /** + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The SDK does not guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies how multiple tabs/windows will be managed by the SDK. + */ + tabManager?: PersistentTabManager; +}; +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare type PersistentLocalCache = { + kind: 'persistent'; +}; +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare function persistentLocalCache( + settings?: PersistentCacheSettings +): PersistentLocalCache; +/** + * A tab manager supporting multiple tabs. SDK will synchronize queries and + * mutations done across all tabs using the SDK. + */ +export declare type PersistentMultipleTabManager = { + kind: 'PersistentMultipleTab'; +}; +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +export declare function persistentMultipleTabManager(): PersistentMultipleTabManager; +/** + * A tab manager supporting only one tab, no synchronization will be + * performed across tabs. + */ +export declare type PersistentSingleTabManager = { + kind: 'persistentSingleTab'; +}; +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +export declare function persistentSingleTabManager( + settings: PersistentSingleTabManagerSettings | undefined +): PersistentSingleTabManager; +/** + * Type to configure an `PersistentSingleTabManager` instance. + */ +export declare type PersistentSingleTabManagerSettings = { + /** + * Whether to force-enable persistent (IndexedDB) cache for the client. This + * cannot be used with multi-tab synchronization and is primarily intended for + * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause + * other tabs using IndexedDB cache to fail. + */ + forceOwnership?: boolean; +}; +/** + * A union of all available tab managers. + */ +export declare type PersistentTabManager = + | PersistentSingleTabManager + | PersistentMultipleTabManager; +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; +/** + * A `Query` refers to a query which you can read or listen to. You can also * construct refined `Query` objects by adding filters and ordering. */ -export declare class Query { +export declare class Query< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; /** The type of this Firestore reference. */ readonly type: 'query' | 'collection'; /** - * The `FirebaseFirestore` for the Firestore database (useful for performing + * The `Firestore` instance for the Firestore database (useful for performing * transactions, etc.). */ - readonly firestore: FirebaseFirestore; + readonly firestore: Firestore; protected constructor(); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; /** * Applies a custom data converter to this query, allowing you to use your own * custom model objects with Firestore. When you call {@link getDocs} with * the returned query, the provided converter will convert between Firestore - * data and your custom type `U`. + * data of type `NewDbModelType` and your custom type `NewAppModelType`. * * @param converter - Converts objects to and from Firestore. - * @returns A `Query` that uses the provided converter. - */ - withConverter(converter: FirestoreDataConverter): Query; + * @returns A `Query` that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends DocumentData = DocumentData + >( + converter: FirestoreDataConverter + ): Query; } /** - * Creates a new immutable instance of `query` that is extended to also include - * additional query constraints. + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query( + query: Query, + compositeFilter: QueryCompositeFilterConstraint, + ...queryConstraints: QueryNonFilterConstraint[] +): Query; +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. * - * @param query - The query instance to use as a base for the new constraints. - * @param queryConstraints - The list of `QueryConstraint`s to apply. + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. * @throws if any of the provided query constraints cannot be combined with the * existing or new constraints. */ -export declare function query( - query: Query, +export declare function query( + query: Query, ...queryConstraints: QueryConstraint[] -): Query; +): Query; +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; +} /** * A `QueryConstraint` is used to narrow the set of documents returned by a * Firestore query. `QueryConstraint`s are created by invoking {@link where}, - * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link - * endBefore}, {@link endAt}, {@link limit} or {@link limitToLast} and - * can then be passed to {@link query} to create a new query instance that + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that * also contains this `QueryConstraint`. */ export declare abstract class QueryConstraint { - /** The type of this query constraints */ + /** The type of this query constraint */ abstract readonly type: QueryConstraintType; } /** Describes the different query constraints available in this SDK. */ @@ -1345,12 +2422,13 @@ export declare type QueryConstraintType = * 'undefined'. */ export declare class QueryDocumentSnapshot< - T = DocumentData -> extends DocumentSnapshot { + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> extends DocumentSnapshot { /** * Retrieves all fields in the document as an `Object`. * - * By default, `FieldValue.serverTimestamp()` values that have not yet been + * By default, `serverTimestamp()` values that have not yet been * set to their final value will be returned as `null`. You can override * this by passing an options object. * @@ -1360,7 +2438,18 @@ export declare class QueryDocumentSnapshot< * have not yet been set to their final value). * @returns An `Object` containing all fields in the document. */ - data(options?: SnapshotOptions): T; + data(options?: SnapshotOptions): AppModelType; +} +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; } /** * Returns true if the provided queries point to the same collection and apply @@ -1371,7 +2460,69 @@ export declare class QueryDocumentSnapshot< * @returns true if the references point to the same location in the same * Firestore database. */ -export declare function queryEqual(left: Query, right: Query): boolean; +export declare function queryEqual< + AppModelType, + DbModelType extends DocumentData +>( + left: Query, + right: Query +): boolean; +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type = 'where'; +} +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = + | QueryFieldFilterConstraint + | QueryCompositeFilterConstraint; +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; +} +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = + | QueryOrderByConstraint + | QueryLimitConstraint + | QueryStartAtConstraint + | QueryEndAtConstraint; +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type = 'orderBy'; +} /** * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects * representing the results of a query. The documents can be accessed as an @@ -1379,7 +2530,10 @@ export declare function queryEqual(left: Query, right: Query): boolean; * number of documents can be determined via the `empty` and `size` * properties. */ -export declare class QuerySnapshot { +export declare class QuerySnapshot< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +> { /** * Metadata about this snapshot, concerning its source and if it has local * modifications. @@ -1389,10 +2543,10 @@ export declare class QuerySnapshot { * The query on which you called `get` or `onSnapshot` in order to get this * `QuerySnapshot`. */ - readonly query: Query; + readonly query: Query; private constructor(); /** An array of all the documents in the `QuerySnapshot`. */ - get docs(): Array>; + get docs(): Array>; /** The number of documents in the `QuerySnapshot`. */ get size(): number; /** True if there are no documents in the `QuerySnapshot`. */ @@ -1405,7 +2559,9 @@ export declare class QuerySnapshot { * @param thisArg - The `this` binding for the callback. */ forEach( - callback: (result: QueryDocumentSnapshot) => void, + callback: ( + result: QueryDocumentSnapshot + ) => void, thisArg?: unknown ): void; /** @@ -1417,7 +2573,20 @@ export declare class QuerySnapshot { * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger * snapshot events. */ - docChanges(options?: SnapshotListenOptions): Array>; + docChanges( + options?: SnapshotListenOptions + ): Array>; +} +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; } /** * Returns true if the provided references are equal. @@ -1427,10 +2596,18 @@ export declare class QuerySnapshot { * @returns true if the references point to the same location in the same * Firestore database. */ -export declare function refEqual( - left: DocumentReference | CollectionReference, - right: DocumentReference | CollectionReference +export declare function refEqual< + AppModelType, + DbModelType extends DocumentData +>( + left: + | DocumentReference + | CollectionReference, + right: + | DocumentReference + | CollectionReference ): boolean; +/* Excluded from this release type: _ResourcePath */ /** * Executes the given `updateFunction` and then attempts to commit the changes * applied within the transaction. If any document read within the transaction @@ -1443,17 +2620,20 @@ export declare function refEqual( * transaction against. * @param updateFunction - The function to execute within the transaction * context. + * @param options - An options object to configure maximum number of attempts to + * commit. * @returns If the transaction completed successfully or was explicitly aborted * (the `updateFunction` returned a failed promise), the promise returned by the * `updateFunction `is returned here. Otherwise, if the transaction failed, a * rejected promise with the corresponding failure error is returned. */ export declare function runTransaction( - firestore: FirebaseFirestore, - updateFunction: (transaction: Transaction) => Promise + firestore: Firestore, + updateFunction: (transaction: Transaction) => Promise, + options?: TransactionOptions ): Promise; /** - * Returns a sentinel used with {@link setDoc} or {@link updateDoc} to + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to * include a server-generated timestamp in the written data. */ export declare function serverTimestamp(): FieldValue; @@ -1463,12 +2643,12 @@ export declare function serverTimestamp(): FieldValue; * * @param reference - A reference to the document to write. * @param data - A map of the fields and values for the document. - * @returns A Promise resolved once the data has been successfully written + * @returns A `Promise` resolved once the data has been successfully written * to the backend (note that it won't resolve while you're offline). */ -export declare function setDoc( - reference: DocumentReference, - data: T +export declare function setDoc( + reference: DocumentReference, + data: WithFieldValue ): Promise; /** * Writes to the document referred to by the specified `DocumentReference`. If @@ -1481,11 +2661,75 @@ export declare function setDoc( * @returns A Promise resolved once the data has been successfully written * to the backend (note that it won't resolve while you're offline). */ -export declare function setDoc( - reference: DocumentReference, - data: Partial, +export declare function setDoc( + reference: DocumentReference, + data: PartialWithFieldValue, options: SetOptions ): Promise; +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. If IndexedDb is not + * enabled, any index configuration is ignored. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param configuration -The index definition. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration( + firestore: Firestore, + configuration: IndexConfiguration +): Promise; +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. Invoke either + * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()` + * before setting an index configuration. If IndexedDb is not enabled, any + * index configuration is ignored. + * + * The method accepts the JSON format exported by the Firebase CLI (`firebase + * firestore:indexes`). If the JSON format is invalid, this method throws an + * error. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param json -The JSON format exported by the Firebase CLI. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration( + firestore: Firestore, + json: string +): Promise; /** * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). * @@ -1501,17 +2745,19 @@ export declare function setDoc( */ export declare function setLogLevel(logLevel: LogLevel): void; /** - * An options object that configures the behavior of {@link setDoc}, {@link - * WriteBatch#set} and {@link Transaction#set} calls. These calls can be + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be * configured to perform granular merges instead of overwriting the target * documents in their entirety by providing a `SetOptions` with `merge: true`. * * @param merge - Changes the behavior of a `setDoc()` call to only replace the * values specified in its data argument. Fields omitted from the `setDoc()` - * call remain untouched. + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace * the specified field paths. Any field path that is not specified is ignored - * and remains untouched. + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. */ export declare type SetOptions = | { @@ -1520,14 +2766,6 @@ export declare type SetOptions = | { readonly mergeFields?: Array; }; -export declare interface Settings { - cacheSizeBytes?: number; - host?: string; - ssl?: boolean; - ignoreUndefinedProperties?: boolean; - experimentalForceLongPolling?: boolean; - experimentalAutoDetectLongPolling?: boolean; -} /** * Returns true if the provided snapshots are equal. * @@ -1535,13 +2773,20 @@ export declare interface Settings { * @param right - A snapshot to compare. * @returns true if the snapshots are equal. */ -export declare function snapshotEqual( - left: DocumentSnapshot | QuerySnapshot, - right: DocumentSnapshot | QuerySnapshot +export declare function snapshotEqual< + AppModelType, + DbModelType extends DocumentData +>( + left: + | DocumentSnapshot + | QuerySnapshot, + right: + | DocumentSnapshot + | QuerySnapshot ): boolean; /** - * An options object that can be passed to {@link onSnapshot} and {@link - * QuerySnapshot#docChanges} to control which types of changes to include in the + * An options object that can be passed to {@link (onSnapshot:1)} and {@link + * QuerySnapshot.docChanges} to control which types of changes to include in the * result set. */ export declare interface SnapshotListenOptions { @@ -1550,6 +2795,11 @@ export declare interface SnapshotListenOptions { * changed. Default is false. */ readonly includeMetadataChanges?: boolean; + /** + * Set the source the query listens to. Default to "default", which + * listens to both cache and server. + */ + readonly source?: ListenSource; } /** * Metadata about a snapshot, describing the state of the snapshot. @@ -1604,49 +2854,62 @@ export declare interface SnapshotOptions { readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; } /** - * Creates a `QueryConstraint` that modifies the result set to start after the - * provided document (exclusive). The starting position is relative to the order - * of the query. The document must contain all of the fields provided in the - * orderBy of the query. + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. * * @param snapshot - The snapshot of the document to start after. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryStartAtConstraint} to pass to `query()` */ -export declare function startAfter( - snapshot: DocumentSnapshot -): QueryConstraint; +export declare function startAfter< + AppModelType, + DbModelType extends DocumentData +>( + snapshot: DocumentSnapshot +): QueryStartAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to start after the - * provided fields relative to the order of the query. The order of the field - * values must match the order of the order by clauses of the query. + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. * * @param fieldValues - The field values to start this query after, in order * of the query's order by. - * @returns A `QueryConstraint` to pass to `query()` + * @returns A {@link QueryStartAtConstraint} to pass to `query()` */ -export declare function startAfter(...fieldValues: unknown[]): QueryConstraint; +export declare function startAfter( + ...fieldValues: unknown[] +): QueryStartAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to start at the - * provided document (inclusive). The starting position is relative to the order - * of the query. The document must contain all of the fields provided in the - * `orderBy` of this query. + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. * * @param snapshot - The snapshot of the document to start at. - * @returns A `QueryConstraint` to pass to `query()`. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. */ -export declare function startAt( - snapshot: DocumentSnapshot -): QueryConstraint; +export declare function startAt( + snapshot: DocumentSnapshot +): QueryStartAtConstraint; /** - * Creates a `QueryConstraint` that modifies the result set to start at the - * provided fields relative to the order of the query. The order of the field - * values must match the order of the order by clauses of the query. + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. * * @param fieldValues - The field values to start this query at, in order * of the query's order by. - * @returns A `QueryConstraint` to pass to `query()`. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt( + ...fieldValues: unknown[] +): QueryStartAtConstraint; +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. */ -export declare function startAt(...fieldValues: unknown[]): QueryConstraint; +export declare function sum(field: string | FieldPath): AggregateField; /** * Represents the state of bundle loading tasks. * @@ -1655,13 +2918,13 @@ export declare function startAt(...fieldValues: unknown[]): QueryConstraint; */ export declare type TaskState = 'Error' | 'Running' | 'Success'; /** - * Terminates the provided Firestore instance. + * Terminates the provided {@link Firestore} instance. * * After calling `terminate()` only the `clearIndexedDbPersistence()` function * may be used. Any other function will throw a `FirestoreError`. * * To restart after termination, create a new instance of FirebaseFirestore with - * {@link getFirestore}. + * {@link (getFirestore:1)}. * * Termination does not cancel any pending writes, and any promises that are * awaiting a response from the server will not be resolved. If you have @@ -1673,10 +2936,10 @@ export declare type TaskState = 'Error' | 'Running' | 'Success'; * of its resources or in combination with `clearIndexedDbPersistence()` to * ensure that all local state is destroyed between test runs. * - * @returns A promise that is resolved when the instance has been successfully + * @returns A `Promise` that is resolved when the instance has been successfully * terminated. */ -export declare function terminate(firestore: FirebaseFirestore): Promise; +export declare function terminate(firestore: Firestore): Promise; /** * @license * Copyright 2017 Google LLC @@ -1708,7 +2971,13 @@ export declare function terminate(firestore: FirebaseFirestore): Promise; * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. */ export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ readonly nanoseconds: number; /** * Creates a new timestamp with the current date, with millisecond precision. @@ -1744,10 +3013,20 @@ export declare class Timestamp { * non-negative nanoseconds values that count forward in time. Must be * from 0 to 999,999,999 inclusive. */ - constructor(seconds: number, nanoseconds: number); + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number + ); /** - * Converts a `Timestamp` to a JavaScript `Date` object. This conversion causes - * a loss of precision since `Date` objects only support millisecond precision. + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. * * @returns JavaScript `Date` object representing the same point in time as * this `Timestamp`, with millisecond precision. @@ -1768,14 +3047,16 @@ export declare class Timestamp { * @returns true if this `Timestamp` is equal to the provided one. */ isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ toString(): string; + /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON(): { seconds: number; nanoseconds: number; }; /** - * Converts this object to a primitive string, which allows Timestamp objects to be compared - * using the `>`, `<=`, `>=` and `>` operators. + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. */ valueOf(): string; } @@ -1794,16 +3075,22 @@ export declare class Transaction { * @param documentRef - A reference to the document to be read. * @returns A `DocumentSnapshot` with the read data. */ - get(documentRef: DocumentReference): Promise>; + get( + documentRef: DocumentReference + ): Promise>; /** * Writes to the document referred to by the provided {@link * DocumentReference}. If the document does not exist yet, it will be created. * * @param documentRef - A reference to the document to be set. * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. * @returns This `Transaction` instance. Used for chaining method calls. */ - set(documentRef: DocumentReference, data: T): this; + set( + documentRef: DocumentReference, + data: WithFieldValue + ): this; /** * Writes to the document referred to by the provided {@link * DocumentReference}. If the document does not exist yet, it will be created. @@ -1813,25 +3100,30 @@ export declare class Transaction { * @param documentRef - A reference to the document to be set. * @param data - An object of the fields and values for the document. * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. * @returns This `Transaction` instance. Used for chaining method calls. */ - set( - documentRef: DocumentReference, - data: Partial, + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, options: SetOptions ): this; /** - * Updates fields in the document referred to by the provided {@link - * DocumentReference}. The update will fail if applied to a document that does - * not exist. - * - * @param documentRef - A reference to the document to be updated. - * @param data - An object containing the fields and values with which to -update the document. Fields can contain dots to reference nested fields -within the document. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - update(documentRef: DocumentReference, data: UpdateData): this; + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update( + documentRef: DocumentReference, + data: UpdateData + ): this; /** * Updates fields in the document referred to by the provided {@link * DocumentReference}. The update will fail if applied to a document that does @@ -1844,10 +3136,11 @@ within the document. * @param field - The first field to update. * @param value - The first value. * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. * @returns This `Transaction` instance. Used for chaining method calls. */ - update( - documentRef: DocumentReference, + update( + documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[] @@ -1858,19 +3151,68 @@ within the document. * @param documentRef - A reference to the document to be deleted. * @returns This `Transaction` instance. Used for chaining method calls. */ - delete(documentRef: DocumentReference): this; + delete( + documentRef: DocumentReference + ): this; +} +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; } +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = ( + U extends unknown ? (k: U) => void : never +) extends (k: infer I) => void + ? I + : never; +/** + * A function returned by `onSnapshot()` that removes the listener when invoked. + */ export declare interface Unsubscribe { + /** Removes the listener when invoked. */ (): void; } /** - * Update data (for use with {@link updateDoc}) consists of field paths (e.g. - * 'foo' or 'foo.baz') mapped to values. Fields that contain dots reference - * nested fields within the document. + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. */ -export declare interface UpdateData { - [fieldPath: string]: any; -} +export declare type UpdateData = T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]?: UpdateData | FieldValue; + } & NestedUpdateFields + : Partial; /** * Updates fields in the document referred to by the specified * `DocumentReference`. The update will fail if applied to a document that does @@ -1880,12 +3222,15 @@ export declare interface UpdateData { * @param data - An object containing the fields and values with which to * update the document. Fields can contain dots to reference nested fields * within the document. - * @returns A Promise resolved once the data has been successfully written + * @returns A `Promise` resolved once the data has been successfully written * to the backend (note that it won't resolve while you're offline). */ -export declare function updateDoc( - reference: DocumentReference, - data: UpdateData +export declare function updateDoc< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, + data: UpdateData ): Promise; /** * Updates fields in the document referred to by the specified @@ -1899,66 +3244,94 @@ export declare function updateDoc( * @param field - The first field to update. * @param value - The first value. * @param moreFieldsAndValues - Additional key value pairs. - * @returns A Promise resolved once the data has been successfully written + * @returns A `Promise` resolved once the data has been successfully written * to the backend (note that it won't resolve while you're offline). */ -export declare function updateDoc( - reference: DocumentReference, +export declare function updateDoc< + AppModelType, + DbModelType extends DocumentData +>( + reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[] ): Promise; /** - * Modify this instance to communicate with the Cloud Firestore emulator. + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. * - * Note: This must be called before this instance has been used to do any - * operations. + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. * - * @param firestore - The Firestore instance to configure to connect to the - * emulator. - * @param host - the emulator host (ex: localhost). - * @param port - the emulator port (ex: 9000). + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. */ -export declare function useFirestoreEmulator( - firestore: FirebaseFirestore, - host: string, - port: number -): void; +export declare function vector(values?: number[]): VectorValue; +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link FieldValue.vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + /* Excluded from this release type: __constructor */ + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; +} /** * Waits until all currently pending writes for the active user have been * acknowledged by the backend. * - * The returned Promise resolves immediately if there are no outstanding writes. - * Otherwise, the Promise waits for all previously issued writes (including + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including * those written in a previous app session), but it does not wait for writes * that were added after the function is called. If you want to wait for * additional writes, call `waitForPendingWrites()` again. * - * Any outstanding `waitForPendingWrites()` Promises are rejected during user + * Any outstanding `waitForPendingWrites()` promises are rejected during user * changes. * - * @returns A Promise which resolves when all currently pending writes have been + * @returns A `Promise` which resolves when all currently pending writes have been * acknowledged by the backend. */ export declare function waitForPendingWrites( - firestore: FirebaseFirestore + firestore: Firestore ): Promise; /** - * Creates a `QueryConstraint` that enforces that documents must contain the - * specified field and that the value should satisfy the relation constraint - * provided. + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. * * @param fieldPath - The path to compare * @param opStr - The operation string (e.g "<", "<=", "==", "<", * "<=", "!="). * @param value - The value for comparison - * @returns The created `Query`. + * @returns The created {@link QueryFieldFilterConstraint}. */ export declare function where( fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown -): QueryConstraint; +): QueryFieldFilterConstraint; /** * Filter conditions in a {@link where} clause are specified using the * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', @@ -1975,12 +3348,25 @@ export declare type WhereFilterOp = | 'in' | 'array-contains-any' | 'not-in'; +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = + | T + | (T extends Primitive + ? T + : T extends {} + ? { + [K in keyof T]: WithFieldValue | FieldValue; + } + : never); /** * A write batch, used to perform multiple writes as a single atomic unit. * * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It * provides methods for adding writes to the write batch. None of the writes - * will be committed (or visible locally) until {@link WriteBatch#commit} is + * will be committed (or visible locally) until {@link WriteBatch.commit} is * called. */ export declare class WriteBatch { @@ -1993,7 +3379,10 @@ export declare class WriteBatch { * @param data - An object of the fields and values for the document. * @returns This `WriteBatch` instance. Used for chaining method calls. */ - set(documentRef: DocumentReference, data: T): WriteBatch; + set( + documentRef: DocumentReference, + data: WithFieldValue + ): WriteBatch; /** * Writes to the document referred to by the provided {@link * DocumentReference}. If the document does not exist yet, it will be created. @@ -2003,11 +3392,12 @@ export declare class WriteBatch { * @param documentRef - A reference to the document to be set. * @param data - An object of the fields and values for the document. * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. * @returns This `WriteBatch` instance. Used for chaining method calls. */ - set( - documentRef: DocumentReference, - data: Partial, + set( + documentRef: DocumentReference, + data: PartialWithFieldValue, options: SetOptions ): WriteBatch; /** @@ -2019,9 +3409,13 @@ export declare class WriteBatch { * @param data - An object containing the fields and values with which to * update the document. Fields can contain dots to reference nested fields * within the document. + * @throws Error - If the provided input is not valid Firestore data. * @returns This `WriteBatch` instance. Used for chaining method calls. */ - update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + update( + documentRef: DocumentReference, + data: UpdateData + ): WriteBatch; /** * Updates fields in the document referred to by this {@link * DocumentReference}. The update will fail if applied to a document that does @@ -2034,10 +3428,11 @@ export declare class WriteBatch { * @param field - The first field to update. * @param value - The first value. * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. * @returns This `WriteBatch` instance. Used for chaining method calls. */ - update( - documentRef: DocumentReference, + update( + documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[] @@ -2048,16 +3443,18 @@ export declare class WriteBatch { * @param documentRef - A reference to the document to be deleted. * @returns This `WriteBatch` instance. Used for chaining method calls. */ - delete(documentRef: DocumentReference): WriteBatch; + delete( + documentRef: DocumentReference + ): WriteBatch; /** * Commits all of the writes in this write batch as a single atomic unit. * * The result of these writes will only be reflected in document reads that - * occur after the returned Promise resolves. If the client is offline, the + * occur after the returned promise resolves. If the client is offline, the * write fails. If you would like to see local modifications or buffer writes * until the client is online, use the full Firestore SDK. * - * @returns A Promise resolved once all of the writes in the batch have been + * @returns A `Promise` resolved once all of the writes in the batch have been * successfully written to the backend as an atomic unit (note that it won't * resolve while you're offline). */ @@ -2065,14 +3462,14 @@ export declare class WriteBatch { } /** * Creates a write batch, used for performing multiple writes as a single - * atomic operation. The maximum number of writes allowed in a single WriteBatch + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} * is 500. * * Unlike transactions, write batches are persisted offline and therefore are * preferable when you don't need to condition your writes on read data. * - * @returns A `WriteBatch` that can be used to atomically execute multiple + * @returns A {@link WriteBatch} that can be used to atomically execute multiple * writes. */ -export declare function writeBatch(firestore: FirebaseFirestore): WriteBatch; +export declare function writeBatch(firestore: Firestore): WriteBatch; export {}; diff --git a/repo-scripts/prune-dts/new-tests/messaging.input.d.ts b/repo-scripts/prune-dts/tests/messaging.input.d.ts similarity index 100% rename from repo-scripts/prune-dts/new-tests/messaging.input.d.ts rename to repo-scripts/prune-dts/tests/messaging.input.d.ts diff --git a/repo-scripts/prune-dts/new-tests/messaging.output.d.ts b/repo-scripts/prune-dts/tests/messaging.output.d.ts similarity index 100% rename from repo-scripts/prune-dts/new-tests/messaging.output.d.ts rename to repo-scripts/prune-dts/tests/messaging.output.d.ts diff --git a/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts b/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts index 90c1d70b0ea..7208f2cf528 100644 --- a/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts +++ b/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.input.d.ts @@ -22,4 +22,4 @@ export class B extends A { b: T; } export class C extends A {} -export {}; \ No newline at end of file +export {}; diff --git a/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts b/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts index b14555d6c52..3dca92f7d56 100644 --- a/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts +++ b/repo-scripts/prune-dts/tests/resolves-generics-through-inheritance.output.d.ts @@ -1,24 +1,24 @@ -/** - * @license - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - export class B { - b: T; - a: string; -} -export class C { - a: T; -} -export {}; \ No newline at end of file +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 class B { + b: T; + a: string; +} +export class C { + a: T; +} +export {}; diff --git a/repo-scripts/prune-dts/new-tests/storage-public.input.d.ts b/repo-scripts/prune-dts/tests/storage-public.input.d.ts similarity index 100% rename from repo-scripts/prune-dts/new-tests/storage-public.input.d.ts rename to repo-scripts/prune-dts/tests/storage-public.input.d.ts diff --git a/repo-scripts/prune-dts/new-tests/storage-public.output.d.ts b/repo-scripts/prune-dts/tests/storage-public.output.d.ts similarity index 100% rename from repo-scripts/prune-dts/new-tests/storage-public.output.d.ts rename to repo-scripts/prune-dts/tests/storage-public.output.d.ts From 6d3fe1451c44b877f0eb92f05308b96f7fd31cae Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Thu, 17 Oct 2024 11:09:52 -0400 Subject: [PATCH 11/24] Fix unknown comparison with number --- packages/database-compat/test/transaction.test.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/database-compat/test/transaction.test.ts b/packages/database-compat/test/transaction.test.ts index 55d7b5042c0..950e9b74e5f 100644 --- a/packages/database-compat/test/transaction.test.ts +++ b/packages/database-compat/test/transaction.test.ts @@ -847,9 +847,11 @@ describe('Transaction Tests', () => { ref1.transaction( current => { retries++; - // We should be getting server events while the transaction is outstanding. - for (let i = 0; i < (current || 0); i++) { - expect(events[i]).to.equal(i); + if (typeof current === 'number') { + // We should be getting server events while the transaction is outstanding. + for (let i = 0; i < (current || 0); i++) { + expect(events[i]).to.equal(i); + } } if (current === SETS - 1) { @@ -919,7 +921,7 @@ describe('Transaction Tests', () => { current => { if (current == null) { return 0; - } else if (current < COUNT) { + } else if (typeof current === 'number' && current < COUNT) { return (current as number) + 1; } else { shouldCommit = false; From 1fb70f2ee75eeaa66d92b861279d1633d44afe15 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Thu, 17 Oct 2024 11:32:01 -0400 Subject: [PATCH 12/24] Fix remote-config timeoutStub types --- packages/remote-config/test/remote_config.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/remote-config/test/remote_config.test.ts b/packages/remote-config/test/remote_config.test.ts index d275adcad89..f53f4a72c86 100644 --- a/packages/remote-config/test/remote_config.test.ts +++ b/packages/remote-config/test/remote_config.test.ts @@ -442,7 +442,7 @@ describe('RemoteConfig', () => { describe('fetch', () => { let timeoutStub: sinon.SinonStub< - [(...args: any[]) => void, number, ...any[]] + [callback: (args: void) => void, ms?: number | undefined] >; beforeEach(() => { client.fetch = sinon From 6bda4e2b54be63117fefa63ce458c45d453afc42 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Fri, 18 Oct 2024 12:21:56 -0400 Subject: [PATCH 13/24] Make Auth Recaptcha request extend object --- .../platform_browser/recaptcha/recaptcha_enterprise_verifier.ts | 2 +- packages/auth/src/platform_browser/strategies/phone.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts b/packages/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts index 0543c030682..53796664de6 100644 --- a/packages/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts +++ b/packages/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts @@ -238,7 +238,7 @@ type ActionMethod = ( request: TRequest ) => Promise; -export async function handleRecaptchaFlow( +export async function handleRecaptchaFlow( authInstance: AuthInternal, request: TRequest, actionName: RecaptchaActionName, diff --git a/packages/auth/src/platform_browser/strategies/phone.ts b/packages/auth/src/platform_browser/strategies/phone.ts index dc6bf1ff788..ebbad499add 100644 --- a/packages/auth/src/platform_browser/strategies/phone.ts +++ b/packages/auth/src/platform_browser/strategies/phone.ts @@ -462,7 +462,7 @@ export async function updatePhoneNumber( } // Helper function that fetches and injects a reCAPTCHA v2 token into the request. -export async function injectRecaptchaV2Token( +export async function injectRecaptchaV2Token( auth: AuthInternal, request: T, recaptchaV2Verifier: ApplicationVerifierInternal From 9628d69d9c6391c6474e9d26d60e31667784c407 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Fri, 18 Oct 2024 13:07:17 -0400 Subject: [PATCH 14/24] Declare Firestore Data Converter test type `MyModelType` as PartialWithFieldValue --- packages/firestore/test/unit/lite-api/types.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/firestore/test/unit/lite-api/types.test.ts b/packages/firestore/test/unit/lite-api/types.test.ts index 5326a288be7..29662856d89 100644 --- a/packages/firestore/test/unit/lite-api/types.test.ts +++ b/packages/firestore/test/unit/lite-api/types.test.ts @@ -632,7 +632,7 @@ describe('FirestoreTypeConverter', () => { await setDoc(newDocRef, { stringProperty: 'foo', numberProperty: 42 }); await updateDoc(newDocRef, { a: 'newFoo', b: 43 }); const snapshot = await getDoc(newDocRef); - const data: MyModelType = snapshot.data()!; + const data: PartialWithFieldValue = snapshot.data()!; expect(data.stringProperty).to.equal('newFoo'); expect(data.numberProperty).to.equal(43); } From 9d2fd6894b0abb73f6eaae08a730e4283b1652d8 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Fri, 18 Oct 2024 14:55:22 -0400 Subject: [PATCH 15/24] Revert firestore lite typings test fix --- packages/firestore/test/unit/lite-api/types.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/firestore/test/unit/lite-api/types.test.ts b/packages/firestore/test/unit/lite-api/types.test.ts index 29662856d89..e2346d0ec27 100644 --- a/packages/firestore/test/unit/lite-api/types.test.ts +++ b/packages/firestore/test/unit/lite-api/types.test.ts @@ -33,6 +33,7 @@ import { FirestoreDataConverter, QueryDocumentSnapshot } from '../../../src/lite-api/snapshot'; +import { DocumentSnapshot } from '../../../src'; // A union type for testing type MyUnionType = string | number; @@ -632,7 +633,7 @@ describe('FirestoreTypeConverter', () => { await setDoc(newDocRef, { stringProperty: 'foo', numberProperty: 42 }); await updateDoc(newDocRef, { a: 'newFoo', b: 43 }); const snapshot = await getDoc(newDocRef); - const data: PartialWithFieldValue = snapshot.data()!; + const data: MyModelType = snapshot.data()!; expect(data.stringProperty).to.equal('newFoo'); expect(data.numberProperty).to.equal(43); } From b82f2b6ab0b1c8e4726bf3d4460150d81deccd4e Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Mon, 21 Oct 2024 14:08:12 -0400 Subject: [PATCH 16/24] Disable import/no-extraneous-dependencies for auth recaptcha tests --- .../auth/test/integration/flows/recaptcha_enterprise.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/auth/test/integration/flows/recaptcha_enterprise.test.ts b/packages/auth/test/integration/flows/recaptcha_enterprise.test.ts index 394f9a9e9a5..00cec9dfd7e 100644 --- a/packages/auth/test/integration/flows/recaptcha_enterprise.test.ts +++ b/packages/auth/test/integration/flows/recaptcha_enterprise.test.ts @@ -18,6 +18,7 @@ import { expect, use } from 'chai'; import chaiAsPromised from 'chai-as-promised'; import sinonChai from 'sinon-chai'; +// eslint-disable-next-line import/no-extraneous-dependencies import { linkWithPhoneNumber, PhoneAuthProvider, From b19aebd40fa81d1a9bd3319938d0ad5183efbd96 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Mon, 21 Oct 2024 14:08:46 -0400 Subject: [PATCH 17/24] Explicitly type Firestore data converter in type tests --- packages/firestore/test/unit/lite-api/types.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/firestore/test/unit/lite-api/types.test.ts b/packages/firestore/test/unit/lite-api/types.test.ts index e2346d0ec27..65b2ffa43ba 100644 --- a/packages/firestore/test/unit/lite-api/types.test.ts +++ b/packages/firestore/test/unit/lite-api/types.test.ts @@ -33,7 +33,6 @@ import { FirestoreDataConverter, QueryDocumentSnapshot } from '../../../src/lite-api/snapshot'; -import { DocumentSnapshot } from '../../../src'; // A union type for testing type MyUnionType = string | number; @@ -601,7 +600,7 @@ describe('FirestoreTypeConverter', () => { stringProperty: string; numberProperty: number; } - const converter = { + const converter: FirestoreDataConverter = { toFirestore( modelObject: PartialWithFieldValue, options?: SetOptions From 7aa755a2c105781e43aeac157f091e482a862e2b Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Mon, 21 Oct 2024 15:35:50 -0400 Subject: [PATCH 18/24] Downgrade `@types/node` to 18.19.57 --- package.json | 2 +- repo-scripts/changelog-generator/package.json | 2 +- yarn.lock | 15 +++++---------- 3 files changed, 7 insertions(+), 12 deletions(-) diff --git a/package.json b/package.json index d7493067196..147ef5e7b24 100644 --- a/package.json +++ b/package.json @@ -80,7 +80,7 @@ "@types/long": "4.0.2", "@types/mocha": "9.1.1", "@types/mz": "2.7.8", - "@types/node": "22.7.5", + "@types/node": "18.19.57", "@types/request": "2.48.12", "@types/sinon": "9.0.11", "@types/sinon-chai": "3.2.12", diff --git a/repo-scripts/changelog-generator/package.json b/repo-scripts/changelog-generator/package.json index 99247b61085..14986d98c33 100644 --- a/repo-scripts/changelog-generator/package.json +++ b/repo-scripts/changelog-generator/package.json @@ -19,7 +19,7 @@ "dependencies": { "@changesets/types": "3.3.0", "@changesets/get-github-info": "0.5.2", - "@types/node": "22.7.5" + "@types/node": "18.19.57" }, "license": "Apache-2.0", "devDependencies": { diff --git a/yarn.lock b/yarn.lock index 73f6c60a2fa..03539a92d43 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3490,12 +3490,12 @@ resolved "https://registry.npmjs.org/@types/node/-/node-10.17.13.tgz" integrity sha512-pMCcqU2zT4TjqYFrWtYHKal7Sl30Ims6ulZ4UFXxI4xbtQqK/qqKwkDoBFCfooRqqmRu9vY3xaJRwxSh673aYg== -"@types/node@22.7.5": - version "22.7.5" - resolved "https://registry.npmjs.org/@types/node/-/node-22.7.5.tgz#cfde981727a7ab3611a481510b473ae54442b92b" - integrity sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ== +"@types/node@18.19.57": + version "18.19.57" + resolved "https://registry.npmjs.org/@types/node/-/node-18.19.57.tgz#a075ff6bb71a947d410a9d7ad2b6cb010a0c5230" + integrity sha512-I2ioBd/IPrYDMv9UNR5NlPElOZ68QB7yY5V2EsLtSrTO0LM0PnCEFF9biLWHf5k+sIy4ohueCV9t4gk1AEdlVA== dependencies: - undici-types "~6.19.2" + undici-types "~5.26.4" "@types/node@>=12.12.47": version "16.9.6" @@ -17390,11 +17390,6 @@ undici-types@~5.26.4: resolved "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617" integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA== -undici-types@~6.19.2: - version "6.19.8" - resolved "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz#35111c9d1437ab83a7cdc0abae2f26d88eda0a02" - integrity sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw== - unicode-canonical-property-names-ecmascript@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.0.tgz" From aa51e6666f981c68de840153de572f939bcd1df9 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Mon, 21 Oct 2024 15:36:22 -0400 Subject: [PATCH 19/24] Revert "Convert `EmulatorConfig`'s `HostAndPort` to be an optional property" This reverts commit c58e63b1b124e8a520202da7b66720495688d8e6. --- .../rules-unit-testing/src/impl/discovery.ts | 33 ++++++++++++------- packages/rules-unit-testing/src/initialize.ts | 2 +- .../src/public_types/index.ts | 11 ++----- .../test/impl/discovery.test.ts | 28 +++++++++++++--- 4 files changed, 49 insertions(+), 25 deletions(-) diff --git a/packages/rules-unit-testing/src/impl/discovery.ts b/packages/rules-unit-testing/src/impl/discovery.ts index a3bcb85bd92..4d57660aa60 100644 --- a/packages/rules-unit-testing/src/impl/discovery.ts +++ b/packages/rules-unit-testing/src/impl/discovery.ts @@ -84,20 +84,29 @@ export interface DiscoveredEmulators { */ export function getEmulatorHostAndPort( emulator: keyof DiscoveredEmulators, - endpoint?: HostAndPort, + conf?: EmulatorConfig, discovered?: DiscoveredEmulators -): HostAndPort | undefined { - if (endpoint) { - if (discovered && !discovered[emulator]) { - console.warn( - `Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` + - 'reports it as not running. This may lead to errors such as connection refused.' - ); +) { + if (conf && 'host' in conf && 'port' in conf) { + const { host, port } = conf; + if (host || port) { + if (!host || !port) { + throw new Error( + `Invalid configuration ${emulator}.host=${host} and ${emulator}.port=${port}. ` + + 'If either parameter is supplied, both must be defined.' + ); + } + if (discovered && !discovered[emulator]) { + console.warn( + `Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` + + 'reports it as not running. This may lead to errors such as connection refused.' + ); + } + return { + host: fixHostname(conf.host, discovered?.hub?.host), + port: conf.port + }; } - return { - host: fixHostname(endpoint.host, discovered?.hub?.host), - port: endpoint.port - }; } const envVar = EMULATOR_HOST_ENV_VARS[emulator]; const fallback = discovered?.[emulator] || emulatorFromEnvVar(envVar); diff --git a/packages/rules-unit-testing/src/initialize.ts b/packages/rules-unit-testing/src/initialize.ts index 80eb13373c9..d0442e24524 100644 --- a/packages/rules-unit-testing/src/initialize.ts +++ b/packages/rules-unit-testing/src/initialize.ts @@ -73,7 +73,7 @@ export async function initializeTestEnvironment( for (const emulator of SUPPORTED_EMULATORS) { const hostAndPort = getEmulatorHostAndPort( emulator, - config[emulator]?.endpoint, + config[emulator], discovered ); if (hostAndPort) { diff --git a/packages/rules-unit-testing/src/public_types/index.ts b/packages/rules-unit-testing/src/public_types/index.ts index fd3ac67d2ff..060e8b8f15b 100644 --- a/packages/rules-unit-testing/src/public_types/index.ts +++ b/packages/rules-unit-testing/src/public_types/index.ts @@ -128,7 +128,7 @@ export interface TestEnvironmentConfig { * An object containing the hostname and port number of an emulator. * @public */ -export type HostAndPort = { +export interface HostAndPort { /** * The host of the emulator. Can be omitted if discovered automatically through the hub or * specified via environment variables. See `TestEnvironmentConfig` for details. @@ -140,7 +140,7 @@ export type HostAndPort = { * specified via environment variables. See `TestEnvironmentConfig` for details. */ port: number; -}; +} /** * Configuration for a given emulator. @@ -149,12 +149,7 @@ export type HostAndPort = { export type EmulatorConfig = { /** The security rules source code under test for this emulator. Strongly recommended. */ rules?: string; - /** - * Endpoint of the emulator. Can be omitted if discovered automatically through the hub. - * See `TestEnvironmentConfig` for details. - */ - endpoint?: HostAndPort; -}; +} & (HostAndPort | {}); // Both or none of host and port should be specified. /** * An object used to control the rules unit test environment. Can be used to create RulesTestContext diff --git a/packages/rules-unit-testing/test/impl/discovery.test.ts b/packages/rules-unit-testing/test/impl/discovery.test.ts index 95d008c1466..39b5628ddc2 100644 --- a/packages/rules-unit-testing/test/impl/discovery.test.ts +++ b/packages/rules-unit-testing/test/impl/discovery.test.ts @@ -22,7 +22,7 @@ import { EMULATOR_HOST_ENV_VARS, getEmulatorHostAndPort } from '../../src/impl/discovery'; -import { EmulatorConfig, HostAndPort } from '../../src/public_types'; +import { HostAndPort } from '../../src/public_types'; import { restoreEnvVars, stashEnvVars } from '../test_utils'; describe('discoverEmulators()', () => { @@ -106,8 +106,10 @@ describe('getEmulatorHostAndPort()', () => { expect(result).to.be.undefined; }); - it('returns undefined if endpoint is undefined', async () => { - const result = getEmulatorHostAndPort('hub'); + it('returns undefined if config option does not contain host/port', async () => { + const result = getEmulatorHostAndPort('hub', { + rules: '/* security rules only, no host/port */' + }); expect(result).to.be.undefined; }); @@ -121,6 +123,22 @@ describe('getEmulatorHostAndPort()', () => { expect(result?.host).to.equal('::1'); }); + it('throws if only host is present', async () => { + expect(() => + getEmulatorHostAndPort('hub', { + host: '[::1]' + } as HostAndPort) + ).to.throw(/hub.port=undefined/); + }); + + it('throws if only port is present', async () => { + expect(() => + getEmulatorHostAndPort('database', { + port: 1234 + } as HostAndPort) + ).to.throw(/Invalid configuration database.host=undefined/); + }); + it('connect to 127.0.0.1 if host is wildcard 0.0.0.0', async () => { const result = getEmulatorHostAndPort('hub', { host: '0.0.0.0', @@ -286,7 +304,9 @@ describe('getEmulatorHostAndPort()', () => { it('takes host and port from env var if config has no host/port', async () => { process.env[EMULATOR_HOST_ENV_VARS.hub] = '127.0.0.1:3445'; - const result = getEmulatorHostAndPort('hub'); + const result = getEmulatorHostAndPort('hub', { + rules: '/* security rules only, no host/port */' + }); expect(result?.host).to.equal('127.0.0.1'); expect(result?.port).to.equal(3445); From db3b0d51de021878048c92564c52d4e39e3369ca Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Mon, 21 Oct 2024 15:38:48 -0400 Subject: [PATCH 20/24] Don't throw an error in case where only one of host or port are defines --- .../rules-unit-testing/src/impl/discovery.ts | 27 +++++++------------ .../test/impl/discovery.test.ts | 16 ----------- 2 files changed, 9 insertions(+), 34 deletions(-) diff --git a/packages/rules-unit-testing/src/impl/discovery.ts b/packages/rules-unit-testing/src/impl/discovery.ts index 4d57660aa60..7bcbccd3f85 100644 --- a/packages/rules-unit-testing/src/impl/discovery.ts +++ b/packages/rules-unit-testing/src/impl/discovery.ts @@ -88,25 +88,16 @@ export function getEmulatorHostAndPort( discovered?: DiscoveredEmulators ) { if (conf && 'host' in conf && 'port' in conf) { - const { host, port } = conf; - if (host || port) { - if (!host || !port) { - throw new Error( - `Invalid configuration ${emulator}.host=${host} and ${emulator}.port=${port}. ` + - 'If either parameter is supplied, both must be defined.' - ); - } - if (discovered && !discovered[emulator]) { - console.warn( - `Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` + - 'reports it as not running. This may lead to errors such as connection refused.' - ); - } - return { - host: fixHostname(conf.host, discovered?.hub?.host), - port: conf.port - }; + if (discovered && !discovered[emulator]) { + console.warn( + `Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` + + 'reports it as not running. This may lead to errors such as connection refused.' + ); } + return { + host: fixHostname(conf.host, discovered?.hub?.host), + port: conf.port + }; } const envVar = EMULATOR_HOST_ENV_VARS[emulator]; const fallback = discovered?.[emulator] || emulatorFromEnvVar(envVar); diff --git a/packages/rules-unit-testing/test/impl/discovery.test.ts b/packages/rules-unit-testing/test/impl/discovery.test.ts index 39b5628ddc2..952f54e8354 100644 --- a/packages/rules-unit-testing/test/impl/discovery.test.ts +++ b/packages/rules-unit-testing/test/impl/discovery.test.ts @@ -123,22 +123,6 @@ describe('getEmulatorHostAndPort()', () => { expect(result?.host).to.equal('::1'); }); - it('throws if only host is present', async () => { - expect(() => - getEmulatorHostAndPort('hub', { - host: '[::1]' - } as HostAndPort) - ).to.throw(/hub.port=undefined/); - }); - - it('throws if only port is present', async () => { - expect(() => - getEmulatorHostAndPort('database', { - port: 1234 - } as HostAndPort) - ).to.throw(/Invalid configuration database.host=undefined/); - }); - it('connect to 127.0.0.1 if host is wildcard 0.0.0.0', async () => { const result = getEmulatorHostAndPort('hub', { host: '0.0.0.0', From e7b9b125691838319bbeb9f88591a614261ef1f4 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Tue, 22 Oct 2024 13:42:26 -0400 Subject: [PATCH 21/24] Throw error if only one of host or port are defined --- .../rules-unit-testing/src/impl/discovery.ts | 13 ++++++++++--- .../test/impl/discovery.test.ts | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/packages/rules-unit-testing/src/impl/discovery.ts b/packages/rules-unit-testing/src/impl/discovery.ts index 7bcbccd3f85..25fd2b00323 100644 --- a/packages/rules-unit-testing/src/impl/discovery.ts +++ b/packages/rules-unit-testing/src/impl/discovery.ts @@ -87,7 +87,14 @@ export function getEmulatorHostAndPort( conf?: EmulatorConfig, discovered?: DiscoveredEmulators ) { - if (conf && 'host' in conf && 'port' in conf) { + if (conf && ('host' in conf || 'port' in conf)) { + const { host, port } = conf as any; + if (!host || !port) { + throw new Error( + `Invalid configuration ${emulator}.host=${host} and ${emulator}.port=${port}. ` + + 'If either parameter is supplied, both must be defined.' + ); + } if (discovered && !discovered[emulator]) { console.warn( `Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` + @@ -95,8 +102,8 @@ export function getEmulatorHostAndPort( ); } return { - host: fixHostname(conf.host, discovered?.hub?.host), - port: conf.port + host: fixHostname(host, discovered?.hub?.host), + port: port }; } const envVar = EMULATOR_HOST_ENV_VARS[emulator]; diff --git a/packages/rules-unit-testing/test/impl/discovery.test.ts b/packages/rules-unit-testing/test/impl/discovery.test.ts index 952f54e8354..afbdbda2266 100644 --- a/packages/rules-unit-testing/test/impl/discovery.test.ts +++ b/packages/rules-unit-testing/test/impl/discovery.test.ts @@ -140,6 +140,22 @@ describe('getEmulatorHostAndPort()', () => { expect(result?.host).to.equal('::1'); }); + it('throws if only host is present', async () => { + expect(() => + getEmulatorHostAndPort('hub', { + host: '[::1]' + } as HostAndPort) + ).to.throw(/hub.port=undefined/); + }); + + it('throws if only port is present', async () => { + expect(() => + getEmulatorHostAndPort('database', { + port: 1234 + } as HostAndPort) + ).to.throw(/Invalid configuration database.host=undefined/); + }); + it('uses discovered host/port if both config and env var are unset', async () => { const result = getEmulatorHostAndPort('hub', undefined, { hub: { host: '::1', port: 3333 } From c27254f30c94c52b45243093e2979538203c8a00 Mon Sep 17 00:00:00 2001 From: dlarocque Date: Tue, 22 Oct 2024 17:55:10 +0000 Subject: [PATCH 22/24] Update API reports --- common/api-review/rules-unit-testing.api.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/common/api-review/rules-unit-testing.api.md b/common/api-review/rules-unit-testing.api.md index f2d4a34d464..e0a646d01bd 100644 --- a/common/api-review/rules-unit-testing.api.md +++ b/common/api-review/rules-unit-testing.api.md @@ -16,14 +16,13 @@ export function assertSucceeds(pr: Promise): Promise; // @public export type EmulatorConfig = { rules?: string; - endpoint?: HostAndPort; -}; +} & (HostAndPort | {}); // @public -export type HostAndPort = { +export interface HostAndPort { host: string; port: number; -}; +} // @public export function initializeTestEnvironment(config: TestEnvironmentConfig): Promise; From e27616b1bded9eee1d7fff5ba9a62a1a838ebd3e Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Tue, 22 Oct 2024 22:02:17 -0400 Subject: [PATCH 23/24] Add outer host and port check, and move tests back --- .../rules-unit-testing/src/impl/discovery.ts | 32 ++++++++++--------- .../test/impl/discovery.test.ts | 32 +++++++++---------- 2 files changed, 33 insertions(+), 31 deletions(-) diff --git a/packages/rules-unit-testing/src/impl/discovery.ts b/packages/rules-unit-testing/src/impl/discovery.ts index 25fd2b00323..d32aab280e3 100644 --- a/packages/rules-unit-testing/src/impl/discovery.ts +++ b/packages/rules-unit-testing/src/impl/discovery.ts @@ -89,22 +89,24 @@ export function getEmulatorHostAndPort( ) { if (conf && ('host' in conf || 'port' in conf)) { const { host, port } = conf as any; - if (!host || !port) { - throw new Error( - `Invalid configuration ${emulator}.host=${host} and ${emulator}.port=${port}. ` + - 'If either parameter is supplied, both must be defined.' - ); + if (host || port) { + if (!host || !port) { + throw new Error( + `Invalid configuration ${emulator}.host=${host} and ${emulator}.port=${port}. ` + + 'If either parameter is supplied, both must be defined.' + ); + } + if (discovered && !discovered[emulator]) { + console.warn( + `Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` + + 'reports it as not running. This may lead to errors such as connection refused.' + ); + } + return { + host: fixHostname(host, discovered?.hub?.host), + port: port + }; } - if (discovered && !discovered[emulator]) { - console.warn( - `Warning: config for the ${emulator} emulator is specified, but the Emulator hub ` + - 'reports it as not running. This may lead to errors such as connection refused.' - ); - } - return { - host: fixHostname(host, discovered?.hub?.host), - port: port - }; } const envVar = EMULATOR_HOST_ENV_VARS[emulator]; const fallback = discovered?.[emulator] || emulatorFromEnvVar(envVar); diff --git a/packages/rules-unit-testing/test/impl/discovery.test.ts b/packages/rules-unit-testing/test/impl/discovery.test.ts index afbdbda2266..39b5628ddc2 100644 --- a/packages/rules-unit-testing/test/impl/discovery.test.ts +++ b/packages/rules-unit-testing/test/impl/discovery.test.ts @@ -123,6 +123,22 @@ describe('getEmulatorHostAndPort()', () => { expect(result?.host).to.equal('::1'); }); + it('throws if only host is present', async () => { + expect(() => + getEmulatorHostAndPort('hub', { + host: '[::1]' + } as HostAndPort) + ).to.throw(/hub.port=undefined/); + }); + + it('throws if only port is present', async () => { + expect(() => + getEmulatorHostAndPort('database', { + port: 1234 + } as HostAndPort) + ).to.throw(/Invalid configuration database.host=undefined/); + }); + it('connect to 127.0.0.1 if host is wildcard 0.0.0.0', async () => { const result = getEmulatorHostAndPort('hub', { host: '0.0.0.0', @@ -140,22 +156,6 @@ describe('getEmulatorHostAndPort()', () => { expect(result?.host).to.equal('::1'); }); - it('throws if only host is present', async () => { - expect(() => - getEmulatorHostAndPort('hub', { - host: '[::1]' - } as HostAndPort) - ).to.throw(/hub.port=undefined/); - }); - - it('throws if only port is present', async () => { - expect(() => - getEmulatorHostAndPort('database', { - port: 1234 - } as HostAndPort) - ).to.throw(/Invalid configuration database.host=undefined/); - }); - it('uses discovered host/port if both config and env var are unset', async () => { const result = getEmulatorHostAndPort('hub', undefined, { hub: { host: '::1', port: 3333 } From d693bfde52eefd7f3229c9534555e1b2e5cd77ea Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Wed, 23 Oct 2024 12:49:31 -0400 Subject: [PATCH 24/24] Update devsite docs --- docs-devsite/analytics.md | 8 ++++---- docs-devsite/app-check.md | 2 +- docs-devsite/auth.md | 8 ++++---- docs-devsite/functions.md | 6 +++--- docs-devsite/installations.md | 4 ++-- docs-devsite/remote-config.md | 6 +++--- docs-devsite/storage.md | 6 +++--- docs-devsite/vertexai.md | 6 +++--- 8 files changed, 23 insertions(+), 23 deletions(-) diff --git a/docs-devsite/analytics.md b/docs-devsite/analytics.md index fe4fa13a68d..e8568b1e792 100644 --- a/docs-devsite/analytics.md +++ b/docs-devsite/analytics.md @@ -990,7 +990,7 @@ Whether a particular consent type has been granted or denied. Signature: ```typescript -export declare type ConsentStatusString = 'granted' | 'denied'; +export type ConsentStatusString = 'granted' | 'denied'; ``` ## Currency @@ -1000,7 +1000,7 @@ Standard Google Analytics currency type. Signature: ```typescript -export declare type Currency = string | number; +export type Currency = string | number; ``` ## CustomEventName @@ -1010,7 +1010,7 @@ Any custom event name string not in the standard list of recommended event names Signature: ```typescript -export declare type CustomEventName = T extends EventNameString ? never : T; +export type CustomEventName = T extends EventNameString ? never : T; ``` ## EventNameString @@ -1020,5 +1020,5 @@ Type for standard Google Analytics event names. `logEvent` also accepts any cust Signature: ```typescript -export declare type EventNameString = 'add_payment_info' | 'add_shipping_info' | 'add_to_cart' | 'add_to_wishlist' | 'begin_checkout' | 'checkout_progress' | 'exception' | 'generate_lead' | 'login' | 'page_view' | 'purchase' | 'refund' | 'remove_from_cart' | 'screen_view' | 'search' | 'select_content' | 'select_item' | 'select_promotion' | 'set_checkout_option' | 'share' | 'sign_up' | 'timing_complete' | 'view_cart' | 'view_item' | 'view_item_list' | 'view_promotion' | 'view_search_results'; +export type EventNameString = 'add_payment_info' | 'add_shipping_info' | 'add_to_cart' | 'add_to_wishlist' | 'begin_checkout' | 'checkout_progress' | 'exception' | 'generate_lead' | 'login' | 'page_view' | 'purchase' | 'refund' | 'remove_from_cart' | 'screen_view' | 'search' | 'select_content' | 'select_item' | 'select_promotion' | 'set_checkout_option' | 'share' | 'sign_up' | 'timing_complete' | 'view_cart' | 'view_item' | 'view_item_list' | 'view_promotion' | 'view_search_results'; ``` diff --git a/docs-devsite/app-check.md b/docs-devsite/app-check.md index ea60678e688..f0d401a530f 100644 --- a/docs-devsite/app-check.md +++ b/docs-devsite/app-check.md @@ -197,5 +197,5 @@ A listener that is called whenever the App Check token changes. Signature: ```typescript -export declare type AppCheckTokenListener = (token: AppCheckTokenResult) => void; +export type AppCheckTokenListener = (token: AppCheckTokenResult) => void; ``` diff --git a/docs-devsite/auth.md b/docs-devsite/auth.md index c417da9110c..83c91db1de2 100644 --- a/docs-devsite/auth.md +++ b/docs-devsite/auth.md @@ -2114,7 +2114,7 @@ Map of OAuth Custom Parameters. Signature: ```typescript -export declare type CustomParameters = Record; +export type CustomParameters = Record; ``` ## NextOrObserver @@ -2124,7 +2124,7 @@ Type definition for an event callback. Signature: ```typescript -export declare type NextOrObserver = NextFn | Observer; +export type NextOrObserver = NextFn | Observer; ``` ## PhoneInfoOptions @@ -2136,7 +2136,7 @@ The information that's required depends on whether you are doing single-factor s Signature: ```typescript -export declare type PhoneInfoOptions = PhoneSingleFactorInfoOptions | PhoneMultiFactorEnrollInfoOptions | PhoneMultiFactorSignInInfoOptions; +export type PhoneInfoOptions = PhoneSingleFactorInfoOptions | PhoneMultiFactorEnrollInfoOptions | PhoneMultiFactorSignInInfoOptions; ``` ## UserProfile @@ -2146,5 +2146,5 @@ User profile used in [AdditionalUserInfo](./auth.additionaluserinfo.md#additiona Signature: ```typescript -export declare type UserProfile = Record; +export type UserProfile = Record; ``` diff --git a/docs-devsite/functions.md b/docs-devsite/functions.md index 07256a1ab13..4887fcd4911 100644 --- a/docs-devsite/functions.md +++ b/docs-devsite/functions.md @@ -147,7 +147,7 @@ Possible values: - 'cancelled': The operation was cancelled (typically by the ca Signature: ```typescript -export declare type FunctionsErrorCode = `functions/${FunctionsErrorCodeCore}`; +export type FunctionsErrorCode = `functions/${FunctionsErrorCodeCore}`; ``` ## FunctionsErrorCodeCore @@ -157,7 +157,7 @@ Functions error code string appended after "functions/" product prefix. See [Fun Signature: ```typescript -export declare type FunctionsErrorCodeCore = 'ok' | 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; +export type FunctionsErrorCodeCore = 'ok' | 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; ``` ## HttpsCallable @@ -167,5 +167,5 @@ A reference to a "callable" HTTP trigger in Google Cloud Functions. Signature: ```typescript -export declare type HttpsCallable = (data?: RequestData | null) => Promise>; +export type HttpsCallable = (data?: RequestData | null) => Promise>; ``` diff --git a/docs-devsite/installations.md b/docs-devsite/installations.md index 3e20ae4935f..89565124f01 100644 --- a/docs-devsite/installations.md +++ b/docs-devsite/installations.md @@ -152,7 +152,7 @@ An user defined callback function that gets called when Installations ID changes Signature: ```typescript -export declare type IdChangeCallbackFn = (installationId: string) => void; +export type IdChangeCallbackFn = (installationId: string) => void; ``` ## IdChangeUnsubscribeFn @@ -162,5 +162,5 @@ Unsubscribe a callback function previously added via [IdChangeCallbackFn](./inst Signature: ```typescript -export declare type IdChangeUnsubscribeFn = () => void; +export type IdChangeUnsubscribeFn = () => void; ``` diff --git a/docs-devsite/remote-config.md b/docs-devsite/remote-config.md index 41663da6751..371ab7ff157 100644 --- a/docs-devsite/remote-config.md +++ b/docs-devsite/remote-config.md @@ -325,7 +325,7 @@ Summarizes the outcome of the last attempt to fetch config from the Firebase Rem Signature: ```typescript -export declare type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle'; +export type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle'; ``` ## LogLevel @@ -335,7 +335,7 @@ Defines levels of Remote Config logging. Signature: ```typescript -export declare type LogLevel = 'debug' | 'error' | 'silent'; +export type LogLevel = 'debug' | 'error' | 'silent'; ``` ## ValueSource @@ -347,5 +347,5 @@ Indicates the source of a value. Signature: ```typescript -export declare type ValueSource = 'static' | 'default' | 'remote'; +export type ValueSource = 'static' | 'default' | 'remote'; ``` diff --git a/docs-devsite/storage.md b/docs-devsite/storage.md index 76d6f6887d3..da72929ebc9 100644 --- a/docs-devsite/storage.md +++ b/docs-devsite/storage.md @@ -493,7 +493,7 @@ An enumeration of the possible string formats for upload. Signature: ```typescript -export declare type StringFormat = (typeof StringFormat)[keyof typeof StringFormat]; +export type StringFormat = (typeof StringFormat)[keyof typeof StringFormat]; ``` ## TaskEvent @@ -503,7 +503,7 @@ An event that is triggered on a task. Signature: ```typescript -export declare type TaskEvent = 'state_changed'; +export type TaskEvent = 'state_changed'; ``` ## TaskState @@ -513,7 +513,7 @@ Represents the current state of a running upload. Signature: ```typescript -export declare type TaskState = 'running' | 'paused' | 'success' | 'canceled' | 'error'; +export type TaskState = 'running' | 'paused' | 'success' | 'canceled' | 'error'; ``` ## StorageErrorCode diff --git a/docs-devsite/vertexai.md b/docs-devsite/vertexai.md index d7eed6f2f86..d9e26eabc5d 100644 --- a/docs-devsite/vertexai.md +++ b/docs-devsite/vertexai.md @@ -184,7 +184,7 @@ Content part - includes text, image/video, or function call/response part types. Signature: ```typescript -export declare type Part = TextPart | InlineDataPart | FunctionCallPart | FunctionResponsePart | FileDataPart; +export type Part = TextPart | InlineDataPart | FunctionCallPart | FunctionResponsePart | FileDataPart; ``` ## Role @@ -194,7 +194,7 @@ Role is the producer of the content. Signature: ```typescript -export declare type Role = (typeof POSSIBLE_ROLES)[number]; +export type Role = (typeof POSSIBLE_ROLES)[number]; ``` ## Tool @@ -214,7 +214,7 @@ A type that includes all specific Schema types. Signature: ```typescript -export declare type TypedSchema = IntegerSchema | NumberSchema | StringSchema | BooleanSchema | ObjectSchema | ArraySchema; +export type TypedSchema = IntegerSchema | NumberSchema | StringSchema | BooleanSchema | ObjectSchema | ArraySchema; ``` ## BlockReason