diff --git a/.github/scripts/compare-types/README.md b/.github/scripts/compare-types/README.md index c4c031de27..fbe85e0106 100644 --- a/.github/scripts/compare-types/README.md +++ b/.github/scripts/compare-types/README.md @@ -10,14 +10,16 @@ For each registered package it compares the **modular** public API exported by t | **Extra in RN Firebase** | Export exists in the RN package but not in the firebase-js-sdk | | **Different shape** | Same name, but the type signature or interface members differ | -Every difference must have an entry in the package's `config.ts` explaining why it exists. The script exits with code 1, failing CI, if either: +Every difference must have an entry in the package's `configs/.ts` explaining why it exists. The script exits with code 1, failing CI, if either: -- A difference is **undocumented** — add it to `config.ts` with a reason, or fix the RN Firebase types to match. -- A config entry is **stale** — the API now matches the firebase-js-sdk, so the entry should be removed from `config.ts`. +- A difference is **undocumented** — add it to `configs/.ts` with a reason, or fix the RN Firebase types to match. +- A config entry is **stale** — the API now matches the firebase-js-sdk, so the entry should be removed from `configs/.ts`. ## Prerequisites -The RN Firebase package(s) must be built before running the script, because the script reads from the compiled `dist/typescript/lib/` files: +The root repository dependencies must be installed because the script reads the Firebase JS SDK types from the installed root `node_modules/firebase` package. + +The RN Firebase package(s) must also be built before running the script, because the script reads from the compiled `dist/typescript/lib/` files: ```sh yarn @@ -54,16 +56,16 @@ yarn compare rn: (RemoteConfig) => ConfigValues ... - ✓ All 17 difference(s) are documented in config.ts + ✓ All 17 difference(s) are documented in configs/.ts ``` ``` 📦 storage Stale config entries (1): - ✗ uploadString [STALE] — now matches the firebase-js-sdk; remove from config.ts + ✗ uploadString [STALE] — now matches the firebase-js-sdk; remove from configs/.ts - ✗ 1 stale config entry/entries — remove them from config.ts + ✗ 1 stale config entry/entries — remove them from configs/.ts ``` `~` (yellow) = documented difference — CI passes. @@ -76,8 +78,8 @@ yarn compare ``` src/ index.ts Entry point. Iterates packages, calls parse → compare → report. - parse.ts Uses ts-morph to read .d.ts files and extract typed export shapes - without needing to resolve external imports (reads type text as-written). + parse.ts Uses ts-morph to read .d.ts files, resolve SDK re-export chains, + and extract typed export shapes. compare.ts Diffs two export maps and classifies each difference. Cross-references against the package config to split documented from undocumented differences, and detects stale config entries @@ -88,8 +90,10 @@ src/ packages/ / - firebase-sdk.d.ts Snapshot of the firebase-js-sdk public types for this package. - config.ts Documented known differences for this package. + (obsolete snapshots should not be added here) + +configs/ + .ts Documented known differences for this package. ``` ### Type shapes @@ -107,17 +111,17 @@ Shapes are compared as normalised strings. Semantically equivalent types that ar ## Adding a new package -### 1. Get the firebase-js-sdk public types +### 1. Confirm the firebase-js-sdk public types -Copy the public type declarations for the package from the firebase-js-sdk release into a new file: +The script reads Firebase JS SDK public declarations from the root `node_modules/firebase` package. Confirm the package exposes the modular public type entry in `node_modules/firebase/package.json`: ``` -packages//firebase-sdk.d.ts +"./": { + "types": ".//dist//index.d.ts" +} ``` -The file should contain only the **modular** (tree-shakeable) public exports — interfaces, type aliases, and `declare function` declarations. Strip internal/private types. - -> In the future this step will be automated: a CI job will clone the firebase-js-sdk, run `yarn && yarn build`, and extract the generated `.d.ts` files automatically. +Those wrapper files often re-export public declarations from `@firebase/`, and the parser resolves that chain through root `node_modules`. ### 2. Identify the RN Firebase modular files @@ -134,10 +138,10 @@ Also note any **support files** — files that are re-exported from the modular ### 3. Create the config file -Create `packages//config.ts` with a `PackageConfig` object: +Create `configs/.ts` with a `PackageConfig` object: ```typescript -import type { PackageConfig } from '../../src/types'; +import type { PackageConfig } from '../src/types'; const config: PackageConfig = { // Rename mapping: sdkName → rnName (when an export has been renamed) @@ -180,14 +184,12 @@ Leave any section as an empty array (or omit it) if there are no differences in Add an entry to [`src/registry.ts`](src/registry.ts): ```typescript -import newPackageConfig from '../packages//config'; +import newPackageConfig from '../configs/'; // inside the packages array: { name: '', - firebaseSdkTypesPaths: [ - path.join(SCRIPT_DIR, 'packages', '', 'firebase-sdk.d.ts'), - ], + firebaseSdkTypesPaths: [firebaseTypes('')], rnFirebaseModularFiles: [ path.join(rnDist(''), 'types', 'modular.d.ts'), path.join(rnDist(''), 'modular.d.ts'), @@ -202,7 +204,7 @@ import newPackageConfig from '../packages//config'; ### 5. Verify -Build the package and run the script. Any undocumented differences will be printed in red — add them to `config.ts` with a reason, or fix the RN Firebase types to match the SDK. +Build the package and run the script. Any undocumented differences will be printed in red — add them to `configs/.ts` with a reason, or fix the RN Firebase types to match the SDK. ```sh # from repo root @@ -212,16 +214,16 @@ yarn compare:types --- -## Updating a package's firebase-sdk snapshot +## Updating the Firebase SDK reference When a new firebase-js-sdk version ships with type changes: -1. Copy the updated public types from `node_modules/@firebase//dist/index.d.ts` (or the equivalent built output) into `packages//firebase-sdk.d.ts`. +1. Update the root `firebase` dependency and run `yarn` from the repository root. 2. Run `yarn compare:types`. 3. Any newly introduced differences will be flagged as undocumented. Either: - Update the RN Firebase types to match, or - - Add a new entry to `config.ts` explaining why the difference is intentional. -4. Any config entries that the SDK change has now made redundant will be flagged as **stale**. Remove them from `config.ts`. + - Add a new entry to `configs/.ts` explaining why the difference is intentional. +4. Any config entries that the SDK change has now made redundant will be flagged as **stale**. Remove them from `configs/.ts`. ## Resolving a known difference in RN Firebase @@ -229,4 +231,4 @@ When the RN Firebase types are updated to match the firebase-js-sdk for a previo 1. Update the RN Firebase types and rebuild the package. 2. Run `yarn compare:types`. -3. The resolved entry will be flagged as **stale** (`✗ [STALE]`). Remove it from `config.ts`. +3. The resolved entry will be flagged as **stale** (`✗ [STALE]`). Remove it from `configs/.ts`. diff --git a/.github/scripts/compare-types/packages/ai/config.ts b/.github/scripts/compare-types/configs/ai.ts similarity index 88% rename from .github/scripts/compare-types/packages/ai/config.ts rename to .github/scripts/compare-types/configs/ai.ts index 9fff3aa64c..32fc0b1ae4 100644 --- a/.github/scripts/compare-types/packages/ai/config.ts +++ b/.github/scripts/compare-types/configs/ai.ts @@ -2,7 +2,7 @@ * Known differences between the firebase-js-sdk AI public API and the * @react-native-firebase/ai public API. * - * Reference: .github/scripts/compare-types/packages/ai/firebase-sdk.d.ts (JS SDK snapshot). + * Reference: root node_modules/firebase AI public types. * RN Firebase built types: packages/ai/dist/typescript/lib/(any subdir)/*.d.ts * * Each entry must have a `name` (the export name) and a `reason` explaining @@ -16,7 +16,7 @@ * differentShape - exports present in both but with differing signatures/members */ -import type { PackageConfig } from '../../src/types'; +import type { PackageConfig } from '../src/types'; const config: PackageConfig = { nameMapping: {}, @@ -121,6 +121,36 @@ const config: PackageConfig = { reason: 'RN Firebase does not currently expose per-call request overrides such as `AbortSignal`; requests are configured via model-level `RequestOptions` only.', }, + { + name: 'ChatSessionBase', + reason: + 'Base class used by the firebase-js-sdk template chat implementation. RN Firebase exposes its concrete chat session surface instead.', + }, + { + name: 'StartTemplateChatParams', + reason: + 'Template chat startup parameters are part of the firebase-js-sdk template chat API, which RN Firebase does not currently expose.', + }, + { + name: 'TemplateChatSession', + reason: + 'Template chat sessions are not currently part of the RN Firebase public AI API.', + }, + { + name: 'TemplateFunctionDeclaration', + reason: + 'Template function declaration helpers are part of firebase-js-sdk template tooling that RN Firebase does not currently expose.', + }, + { + name: 'TemplateFunctionDeclarationsTool', + reason: + 'Template function declaration tools are part of firebase-js-sdk template tooling that RN Firebase does not currently expose.', + }, + { + name: 'TemplateTool', + reason: + 'Template tool unions are part of firebase-js-sdk template tooling that RN Firebase does not currently expose.', + }, { name: 'ThinkingLevel', reason: @@ -195,6 +225,11 @@ const config: PackageConfig = { reason: 'RN Firebase function responses omit the optional `parts` field from the JS SDK declaration and only expose the structured response payload.', }, + { + name: 'GenerationConfig', + reason: + 'RN Firebase does not currently expose the JS SDK `responseJsonSchema` generation config field.', + }, { name: 'GenerativeModel', reason: diff --git a/.github/scripts/compare-types/packages/app-check/config.ts b/.github/scripts/compare-types/configs/app-check.ts similarity index 98% rename from .github/scripts/compare-types/packages/app-check/config.ts rename to .github/scripts/compare-types/configs/app-check.ts index 118c64308c..37296e77f6 100644 --- a/.github/scripts/compare-types/packages/app-check/config.ts +++ b/.github/scripts/compare-types/configs/app-check.ts @@ -7,7 +7,7 @@ * fail so that new drift is caught and deliberately acknowledged. */ -import type { PackageConfig } from '../../src/types'; +import type { PackageConfig } from '../src/types'; const config: PackageConfig = { nameMapping: {}, diff --git a/.github/scripts/compare-types/packages/database/config.ts b/.github/scripts/compare-types/configs/database.ts similarity index 69% rename from .github/scripts/compare-types/packages/database/config.ts rename to .github/scripts/compare-types/configs/database.ts index 3b1ee9adfa..bd01ed8fd5 100644 --- a/.github/scripts/compare-types/packages/database/config.ts +++ b/.github/scripts/compare-types/configs/database.ts @@ -1,4 +1,4 @@ -import type { PackageConfig } from '../../src/types'; +import type { PackageConfig } from '../src/types'; const config: PackageConfig = { nameMapping: {}, @@ -41,12 +41,19 @@ const config: PackageConfig = { ], differentShape: [ { - name: 'EmulatorMockTokenOptions', + name: 'Database', reason: - 'RN Firebase reuses the local `FirebaseIdToken` alias in ' + - '`Partial`, while the snapshot inlines the token ' + - 'shape so compare-types does not treat the helper alias as an extra export. ' + - 'The two types are structurally equivalent.', + 'RN Firebase narrows the public `type` member to the concrete `database` literal, while the firebase-js-sdk declaration leaves it less specific.', + }, + { + name: 'DataSnapshot', + reason: + 'RN Firebase exposes native snapshot metadata helpers such as `key`, `priority`, and `size` on the public snapshot type.', + }, + { + name: 'OnDisconnect', + reason: + 'The public method signatures are equivalent, but the generated declaration text differs in union ordering for the priority parameter.', }, ], }; diff --git a/.github/scripts/compare-types/configs/firestore-pipelines.ts b/.github/scripts/compare-types/configs/firestore-pipelines.ts new file mode 100644 index 0000000000..1e924adf17 --- /dev/null +++ b/.github/scripts/compare-types/configs/firestore-pipelines.ts @@ -0,0 +1,185 @@ +/** + * Known differences between the firebase-js-sdk Firestore Pipelines API + * and the @react-native-firebase/firestore pipelines API + * (imported from "@react-native-firebase/firestore/pipelines"). + * + * Reference: root node_modules/firebase Firestore Pipelines public types. + * RN Firebase built types: packages/firestore/dist/typescript/lib/pipelines/*.d.ts + * + * Each entry must have a `name` (the export name) and a `reason` explaining + * why the difference exists. Any difference NOT listed here will cause CI to + * fail so that new drift is caught and deliberately acknowledged. + * + * Sections: + * nameMapping — exports that exist in both but under different names + * missingInRN — JS SDK pipeline exports absent from RN Firebase + * extraInRN — RN Firebase pipeline exports not in the JS SDK + * differentShape — same export name but differing signatures/members + */ + +import type { PackageConfig } from '../src/types'; + + +const config: PackageConfig = { + nameMapping: {}, + missingInRN: [ + { + name: 'arrayFilter', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayFirst', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayFirstN', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayIndexOf', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayIndexOfAll', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayLast', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayLastIndexOf', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayLastN', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayMaximum', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayMaximumN', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayMinimum', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayMinimumN', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arraySlice', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayTransform', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'arrayTransformWithIndex', + reason: 'Newer firebase-js-sdk array expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'coalesce', + reason: 'Newer firebase-js-sdk expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'currentDocument', + reason: 'Newer firebase-js-sdk document expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'documentMatches', + reason: 'Newer firebase-js-sdk document expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'geoDistance', + reason: 'Newer firebase-js-sdk geospatial expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'ifNull', + reason: 'Newer firebase-js-sdk null-handling expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'nor', + reason: 'Newer firebase-js-sdk boolean expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'score', + reason: 'Newer firebase-js-sdk search score expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'subcollection', + reason: 'Newer firebase-js-sdk subcollection stage helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'switchOn', + reason: 'Newer firebase-js-sdk conditional expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'timestampDiff', + reason: 'Newer firebase-js-sdk timestamp expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'timestampExtract', + reason: 'Newer firebase-js-sdk timestamp expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'variable', + reason: 'Newer firebase-js-sdk variable expression helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'DefineStageOptions', + reason: 'Newer firebase-js-sdk stage options type not yet exposed by RN Firebase pipelines.', + }, + { + name: 'parent', + reason: 'Newer firebase-js-sdk parent stage helper not yet exposed by RN Firebase pipelines.', + }, + { + name: 'SearchStageOptions', + reason: 'Newer firebase-js-sdk search stage options type not yet exposed by RN Firebase pipelines.', + }, + { + name: 'SubcollectionStageOptions', + reason: 'Newer firebase-js-sdk subcollection stage options type not yet exposed by RN Firebase pipelines.', + }, + { + name: 'TimePart', + reason: 'Newer firebase-js-sdk timestamp extraction type not yet exposed by RN Firebase pipelines.', + }, + { + name: 'TimeUnit', + reason: 'Newer firebase-js-sdk timestamp unit type not yet exposed by RN Firebase pipelines.', + }, + ], + extraInRN: [ + { + name: 'Type', + reason: 'RN Firebase exposes a local type discriminator alias for pipeline expression helpers.', + }, + ], + differentShape: [ + { + name: 'isType', + reason: 'RN Firebase accepts its local `Type` alias where the firebase-js-sdk declaration accepts a string.', + }, + { + name: 'ExpressionType', + reason: 'RN Firebase has not yet exposed the newer firebase-js-sdk `Variable` and `PipelineValue` expression kinds.', + }, + { + name: 'StageOptions', + reason: 'Declaration formatting differs for the raw options object, but the public shape is equivalent.', + }, + { + name: 'TimeGranularity', + reason: 'RN Firebase uses the existing `isoWeek` and `isoYear` casing while the firebase-js-sdk declaration includes lowercase variants.', + }, + ], +}; + +export default config; diff --git a/.github/scripts/compare-types/packages/firestore/config.ts b/.github/scripts/compare-types/configs/firestore.ts similarity index 97% rename from .github/scripts/compare-types/packages/firestore/config.ts rename to .github/scripts/compare-types/configs/firestore.ts index 8f7852e313..c36fe2e38d 100644 --- a/.github/scripts/compare-types/packages/firestore/config.ts +++ b/.github/scripts/compare-types/configs/firestore.ts @@ -13,7 +13,7 @@ * differentShape — exports present in both but with differing signatures/members */ -import type { PackageConfig } from '../../src/types'; +import type { PackageConfig } from '../src/types'; const config: PackageConfig = { // --------------------------------------------------------------------------- @@ -219,6 +219,16 @@ const config: PackageConfig = { '`@react-native-firebase/app`. Used as the app parameter type in RN ' + 'Firebase functions. Not part of the firebase-js-sdk public Firestore API.', }, + { + name: 'FirebaseSignInProvider', + reason: + 'RN Firebase re-exports this helper type from shared app declarations for emulator mock-token support.', + }, + { + name: 'FirebaseIdToken', + reason: + 'RN Firebase re-exports this helper type from shared app declarations for emulator mock-token support.', + }, { name: 'LiteTransaction', reason: diff --git a/.github/scripts/compare-types/packages/remote-config/config.ts b/.github/scripts/compare-types/configs/remote-config.ts similarity index 98% rename from .github/scripts/compare-types/packages/remote-config/config.ts rename to .github/scripts/compare-types/configs/remote-config.ts index 2ec9fb80fd..83a89ae3ef 100644 --- a/.github/scripts/compare-types/packages/remote-config/config.ts +++ b/.github/scripts/compare-types/configs/remote-config.ts @@ -13,7 +13,7 @@ * differentShape — exports present in both but with differing signatures/members */ -import type { PackageConfig } from '../../src/types'; +import type { PackageConfig } from '../src/types'; const config: PackageConfig = { missingInRN: [ diff --git a/.github/scripts/compare-types/packages/storage/config.ts b/.github/scripts/compare-types/configs/storage.ts similarity index 99% rename from .github/scripts/compare-types/packages/storage/config.ts rename to .github/scripts/compare-types/configs/storage.ts index f880e0ca63..e764da9256 100644 --- a/.github/scripts/compare-types/packages/storage/config.ts +++ b/.github/scripts/compare-types/configs/storage.ts @@ -13,7 +13,7 @@ * differentShape — exports present in both but with differing signatures/members */ -import type { PackageConfig } from '../../src/types'; +import type { PackageConfig } from '../src/types'; const config: PackageConfig = { // --------------------------------------------------------------------------- diff --git a/.github/scripts/compare-types/packages/ai/ai-sdk.d.ts b/.github/scripts/compare-types/packages/ai/ai-sdk.d.ts deleted file mode 100644 index e03ce62182..0000000000 --- a/.github/scripts/compare-types/packages/ai/ai-sdk.d.ts +++ /dev/null @@ -1,3485 +0,0 @@ -/** - * Paste the firebase-js-sdk AI public type snapshot into this file. - * - * Source guidance: - * - Copy only the modular public exports for the AI package. - * - Strip internal/private declarations. - * - Keep this file in sync with the firebase-js-sdk release you want to compare against. - * - * Once populated, run `yarn compare:types` from the repo root to detect - * undocumented AI API drift. - */ - -/** - * The Firebase AI Web SDK. - * - * @packageDocumentation - */ - -import { AppCheckTokenResult } from '@firebase/app-check-interop-types'; -import { FirebaseApp } from '@firebase/app'; -import { FirebaseAuthTokenData } from '@firebase/auth-interop-types'; -import { FirebaseError } from '@firebase/util'; - -/** - * An instance of the Firebase AI SDK. - * - * Do not create this instance directly. Instead, use {@link getAI | getAI()}. - * - * @public - */ -export declare interface AI { - /** - * The {@link @firebase/app#FirebaseApp} this {@link AI} instance is associated with. - */ - app: FirebaseApp; - /** - * A {@link Backend} instance that specifies the configuration for the target backend, - * either the Gemini Developer API (using {@link GoogleAIBackend}) or the - * Vertex AI Gemini API (using {@link VertexAIBackend}). - */ - backend: Backend; - /** - * Options applied to this {@link AI} instance. - */ - options?: AIOptions; - /** - * @deprecated use `AI.backend.location` instead. - * - * The location configured for this AI service instance, relevant for Vertex AI backends. - */ - location: string; -} - -/** - * Error class for the Firebase AI SDK. - * - * @public - */ -export declare class AIError extends FirebaseError { - readonly code: AIErrorCode; - readonly customErrorData?: CustomErrorData | undefined; - /** - * Constructs a new instance of the `AIError` class. - * - * @param code - The error code from {@link (AIErrorCode:type)}. - * @param message - A human-readable message describing the error. - * @param customErrorData - Optional error data. - */ - constructor(code: AIErrorCode, message: string, customErrorData?: CustomErrorData | undefined); -} - -/** - * Standardized error codes that {@link AIError} can have. - * - * @public - */ -export declare const AIErrorCode: { - /** A generic error occurred. */ - readonly ERROR: "error"; - /** An error occurred in a request. */ - readonly REQUEST_ERROR: "request-error"; - /** An error occurred in a response. */ - readonly RESPONSE_ERROR: "response-error"; - /** An error occurred while performing a fetch. */ - readonly FETCH_ERROR: "fetch-error"; - /** An error occurred because an operation was attempted on a closed session. */ - readonly SESSION_CLOSED: "session-closed"; - /** An error associated with a Content object. */ - readonly INVALID_CONTENT: "invalid-content"; - /** An error due to the Firebase API not being enabled in the Console. */ - readonly API_NOT_ENABLED: "api-not-enabled"; - /** An error due to invalid Schema input. */ - readonly INVALID_SCHEMA: "invalid-schema"; - /** An error occurred due to a missing Firebase API key. */ - readonly NO_API_KEY: "no-api-key"; - /** An error occurred due to a missing Firebase app ID. */ - readonly NO_APP_ID: "no-app-id"; - /** An error occurred due to a model name not being specified during initialization. */ - readonly NO_MODEL: "no-model"; - /** An error occurred due to a missing project ID. */ - readonly NO_PROJECT_ID: "no-project-id"; - /** An error occurred while parsing. */ - readonly PARSE_FAILED: "parse-failed"; - /** An error occurred due an attempt to use an unsupported feature. */ - readonly UNSUPPORTED: "unsupported"; -}; - -/** - * Standardized error codes that {@link AIError} can have. - * - * @public - */ -export declare type AIErrorCode = (typeof AIErrorCode)[keyof typeof AIErrorCode]; - -/** - * Base class for Firebase AI model APIs. - * - * Instances of this class are associated with a specific Firebase AI {@link Backend} - * and provide methods for interacting with the configured generative model. - * - * @public - */ -export declare abstract class AIModel { - /** - * The fully qualified model resource name to use for generating images - * (for example, `publishers/google/models/imagen-3.0-generate-002`). - */ - readonly model: string; - /* Excluded from this release type: _apiSettings */ - /* Excluded from this release type: __constructor */ - /* Excluded from this release type: normalizeModelName */ - /* Excluded from this release type: normalizeGoogleAIModelName */ - /* Excluded from this release type: normalizeVertexAIModelName */ -} - -/** - * Options for initializing the AI service using {@link getAI | getAI()}. - * This allows specifying which backend to use (Vertex AI Gemini API or Gemini Developer API) - * and configuring its specific options (like location for Vertex AI). - * - * @public - */ -export declare interface AIOptions { - /** - * The backend configuration to use for the AI service instance. - * Defaults to the Gemini Developer API backend ({@link GoogleAIBackend}). - */ - backend?: Backend; - /** - * Whether to use App Check limited use tokens. Defaults to false. - */ - useLimitedUseAppCheckTokens?: boolean; -} - -/** - * Schema class representing a value that can conform to any of the provided sub-schemas. This is - * useful when a field can accept multiple distinct types or structures. - * @public - */ -export declare class AnyOfSchema extends Schema { - anyOf: TypedSchema[]; - constructor(schemaParams: SchemaParams & { - anyOf: TypedSchema[]; - }); - /* Excluded from this release type: toJSON */ -} - -declare interface ApiSettings { - apiKey: string; - project: string; - appId: string; - automaticDataCollectionEnabled?: boolean; - /** - * @deprecated Use `backend.location` instead. - */ - location: string; - backend: Backend; - getAuthToken?: () => Promise; - getAppCheckToken?: () => Promise; - inferenceMode?: InferenceMode; -} - -/** - * Schema class for "array" types. - * The `items` param should refer to the type of item that can be a member - * of the array. - * @public - */ -export declare class ArraySchema extends Schema { - items: TypedSchema; - constructor(schemaParams: SchemaParams, items: TypedSchema); - /* Excluded from this release type: toJSON */ -} - -/** - * A controller for managing an active audio conversation. - * - * @beta - */ -export declare interface AudioConversationController { - /** - * Stops the audio conversation, closes the microphone connection, and - * cleans up resources. Returns a promise that resolves when cleanup is complete. - */ - stop: () => Promise; -} - -/** - * The audio transcription configuration. - */ -export declare interface AudioTranscriptionConfig { -} - -/** - * Abstract base class representing the configuration for an AI service backend. - * This class should not be instantiated directly. Use its subclasses; {@link GoogleAIBackend} for - * the Gemini Developer API (via {@link https://ai.google/ | Google AI}), and - * {@link VertexAIBackend} for the Vertex AI Gemini API. - * - * @public - */ -export declare abstract class Backend { - /** - * Specifies the backend type. - */ - readonly backendType: BackendType; - /** - * Protected constructor for use by subclasses. - * @param type - The backend type. - */ - protected constructor(type: BackendType); - /* Excluded from this release type: _getModelPath */ - /* Excluded from this release type: _getTemplatePath */ -} - -/** - * An enum-like object containing constants that represent the supported backends - * for the Firebase AI SDK. - * This determines which backend service (Vertex AI Gemini API or Gemini Developer API) - * the SDK will communicate with. - * - * These values are assigned to the `backendType` property within the specific backend - * configuration objects ({@link GoogleAIBackend} or {@link VertexAIBackend}) to identify - * which service to target. - * - * @public - */ -export declare const BackendType: { - /** - * Identifies the backend service for the Vertex AI Gemini API provided through Google Cloud. - * Use this constant when creating a {@link VertexAIBackend} configuration. - */ - readonly VERTEX_AI: "VERTEX_AI"; - /** - * Identifies the backend service for the Gemini Developer API ({@link https://ai.google/ | Google AI}). - * Use this constant when creating a {@link GoogleAIBackend} configuration. - */ - readonly GOOGLE_AI: "GOOGLE_AI"; -}; - -/** - * Type alias representing valid backend types. - * It can be either `'VERTEX_AI'` or `'GOOGLE_AI'`. - * - * @public - */ -export declare type BackendType = (typeof BackendType)[keyof typeof BackendType]; - -/** - * Base parameters for a number of methods. - * @public - */ -export declare interface BaseParams { - safetySettings?: SafetySetting[]; - generationConfig?: GenerationConfig; -} - -/** - * Reason that a prompt was blocked. - * @public - */ -export declare const BlockReason: { - /** - * Content was blocked by safety settings. - */ - readonly SAFETY: "SAFETY"; - /** - * Content was blocked, but the reason is uncategorized. - */ - readonly OTHER: "OTHER"; - /** - * Content was blocked because it contained terms from the terminology blocklist. - */ - readonly BLOCKLIST: "BLOCKLIST"; - /** - * Content was blocked due to prohibited content. - */ - readonly PROHIBITED_CONTENT: "PROHIBITED_CONTENT"; -}; - -/** - * Reason that a prompt was blocked. - * @public - */ -export declare type BlockReason = (typeof BlockReason)[keyof typeof BlockReason]; - -/** - * Schema class for "boolean" types. - * @public - */ -export declare class BooleanSchema extends Schema { - constructor(schemaParams?: SchemaParams); -} - -/** - * ChatSession class that enables sending chat messages and stores - * history of sent and received messages so far. - * - * @public - */ -export declare class ChatSession { - model: string; - private chromeAdapter?; - params?: StartChatParams | undefined; - requestOptions?: RequestOptions | undefined; - private _apiSettings; - private _history; - /** - * Ensures sequential execution of chat messages to maintain history order. - * Each call waits for the previous one to settle before proceeding. - */ - private _sendPromise; - constructor(apiSettings: ApiSettings, model: string, chromeAdapter?: ChromeAdapter | undefined, params?: StartChatParams | undefined, requestOptions?: RequestOptions | undefined); - /** - * Gets the chat history so far. Blocked prompts are not added to history. - * Neither blocked candidates nor the prompts that generated them are added - * to history. - */ - getHistory(): Promise; - /* Excluded from this release type: _formatRequest */ - /** - * Sends a chat message and receives a non-streaming - * {@link GenerateContentResult} - */ - sendMessage(request: string | Array, singleRequestOptions?: SingleRequestOptions): Promise; - /** - * Sends a chat message and receives the response as a - * {@link GenerateContentStreamResult} containing an iterable stream - * and a response promise. - */ - sendMessageStream(request: string | Array, singleRequestOptions?: SingleRequestOptions): Promise; - /* Excluded from this release type: _getCallableFunctionCalls */ - /* Excluded from this release type: _callFunctionsAsNeeded */ -} - -/** - * Defines an inference "backend" that uses Chrome's on-device model, - * and encapsulates logic for detecting when on-device inference is - * possible. - * - * These methods should not be called directly by the user. - * - * @beta - */ -export declare interface ChromeAdapter { - /* Excluded from this release type: mode */ - /** - * Checks if the on-device model is capable of handling a given - * request. - * @param request - A potential request to be passed to the model. - */ - isAvailable(request: GenerateContentRequest): Promise; - /** - * Generates content using on-device inference. - * - * @remarks - * This is comparable to {@link GenerativeModel.generateContent} for generating - * content using in-cloud inference. - * @param request - a standard Firebase AI {@link GenerateContentRequest} - */ - generateContent(request: GenerateContentRequest): Promise; - /** - * Generates a content stream using on-device inference. - * - * @remarks - * This is comparable to {@link GenerativeModel.generateContentStream} for generating - * a content stream using in-cloud inference. - * @param request - a standard Firebase AI {@link GenerateContentRequest} - */ - generateContentStream(request: GenerateContentRequest): Promise; - /* Excluded from this release type: countTokens */ -} - -/** - * A single citation. - * @public - */ -export declare interface Citation { - startIndex?: number; - endIndex?: number; - uri?: string; - license?: string; - /** - * The title of the cited source, if available. - * - * This property is only supported in the Vertex AI Gemini API ({@link VertexAIBackend}). - */ - title?: string; - /** - * The publication date of the cited source, if available. - * - * This property is only supported in the Vertex AI Gemini API ({@link VertexAIBackend}). - */ - publicationDate?: Date_2; -} - -/** - * Citation metadata that may be found on a {@link GenerateContentCandidate}. - * @public - */ -export declare interface CitationMetadata { - citations: Citation[]; -} - -/** - * The results of code execution run by the model. - * - * @public - */ -export declare interface CodeExecutionResult { - /** - * The result of the code execution. - */ - outcome?: Outcome; - /** - * The output from the code execution, or an error message - * if it failed. - */ - output?: string; -} - -/** - * Represents the code execution result from the model. - * - * @public - */ -export declare interface CodeExecutionResultPart { - text?: never; - inlineData?: never; - functionCall?: never; - functionResponse?: never; - fileData: never; - thought?: never; - /* Excluded from this release type: thoughtSignature */ - executableCode?: never; - codeExecutionResult?: CodeExecutionResult; -} - -/** - * A tool that enables the model to use code execution. - * - * @beta - */ -export declare interface CodeExecutionTool { - /** - * Specifies the Google Search configuration. - * Currently, this is an empty object, but it's reserved for future configuration options. - */ - codeExecution: {}; -} - -/** - * Content type for both prompts and response candidates. - * @public - */ -export declare interface Content { - role: Role; - parts: Part[]; -} - -/** - * Params for calling {@link GenerativeModel.countTokens} - * @public - */ -export declare interface CountTokensRequest { - contents: Content[]; - /** - * Instructions that direct the model to behave a certain way. - */ - systemInstruction?: string | Part | Content; - /** - * {@link Tool} configuration. - */ - tools?: Tool[]; - /** - * Configuration options that control how the model generates a response. - */ - generationConfig?: GenerationConfig; -} - -/** - * Response from calling {@link GenerativeModel.countTokens}. - * @public - */ -export declare interface CountTokensResponse { - /** - * The total number of tokens counted across all instances from the request. - */ - totalTokens: number; - /** - * @deprecated Use `totalTokens` instead. This property is undefined when using models greater than `gemini-1.5-*`. - * - * The total number of billable characters counted across all instances - * from the request. - */ - totalBillableCharacters?: number; - /** - * The breakdown, by modality, of how many tokens are consumed by the prompt. - */ - promptTokensDetails?: ModalityTokenCount[]; -} - -/** - * Details object that contains data originating from a bad HTTP response. - * - * @public - */ -export declare interface CustomErrorData { - /** HTTP status code of the error response. */ - status?: number; - /** HTTP status text of the error response. */ - statusText?: string; - /** Response from a {@link GenerateContentRequest} */ - response?: GenerateContentResponse; - /** Optional additional details about the error. */ - errorDetails?: ErrorDetails[]; -} - -/** - * Protobuf google.type.Date - * @public - */ -declare interface Date_2 { - year: number; - month: number; - day: number; -} -export { Date_2 as Date } - -/** - * Response object wrapped with helper methods. - * - * @public - */ -export declare interface EnhancedGenerateContentResponse extends GenerateContentResponse { - /** - * Returns the text string from the response, if available. - * Throws if the prompt or candidate was blocked. - */ - text: () => string; - /** - * Aggregates and returns every {@link InlineDataPart} from the first candidate of - * {@link GenerateContentResponse}. - * - * @throws If the prompt or candidate was blocked. - */ - inlineDataParts: () => InlineDataPart[] | undefined; - /** - * Aggregates and returns every {@link FunctionCall} from the first candidate of - * {@link GenerateContentResponse}. - * - * @throws If the prompt or candidate was blocked. - */ - functionCalls: () => FunctionCall[] | undefined; - /** - * Aggregates and returns every {@link TextPart} with their `thought` property set - * to `true` from the first candidate of {@link GenerateContentResponse}. - * - * @throws If the prompt or candidate was blocked. - * - * @remarks - * Thought summaries provide a brief overview of the model's internal thinking process, - * offering insight into how it arrived at the final answer. This can be useful for - * debugging, understanding the model's reasoning, and verifying its accuracy. - * - * Thoughts will only be included if {@link ThinkingConfig.includeThoughts} is - * set to `true`. - */ - thoughtSummary: () => string | undefined; - /** - * Indicates whether inference happened on-device or in-cloud. - * - * @beta - */ - inferenceSource?: InferenceSource; -} - -/** - * Details object that may be included in an error response. - * - * @public - */ -export declare interface ErrorDetails { - '@type'?: string; - /** The reason for the error. */ - reason?: string; - /** The domain where the error occurred. */ - domain?: string; - /** Additional metadata about the error. */ - metadata?: Record; - /** Any other relevant information about the error. */ - [key: string]: unknown; -} - -/** - * An interface for executable code returned by the model. - * - * @public - */ -export declare interface ExecutableCode { - /** - * The programming language of the code. - */ - language?: Language; - /** - * The source code to be executed. - */ - code?: string; -} - -/** - * Represents the code that is executed by the model. - * - * @public - */ -export declare interface ExecutableCodePart { - text?: never; - inlineData?: never; - functionCall?: never; - functionResponse?: never; - fileData: never; - thought?: never; - /* Excluded from this release type: thoughtSignature */ - executableCode?: ExecutableCode; - codeExecutionResult?: never; -} - -/** - * Data pointing to a file uploaded on Google Cloud Storage. - * @public - */ -export declare interface FileData { - mimeType: string; - fileUri: string; -} - -/** - * Content part interface if the part represents {@link FileData} - * @public - */ -export declare interface FileDataPart { - text?: never; - inlineData?: never; - functionCall?: never; - functionResponse?: never; - fileData: FileData; - thought?: boolean; - /* Excluded from this release type: thoughtSignature */ - executableCode?: never; - codeExecutionResult?: never; -} - -/** - * Reason that a candidate finished. - * @public - */ -export declare const FinishReason: { - /** - * Natural stop point of the model or provided stop sequence. - */ - readonly STOP: "STOP"; - /** - * The maximum number of tokens as specified in the request was reached. - */ - readonly MAX_TOKENS: "MAX_TOKENS"; - /** - * The candidate content was flagged for safety reasons. - */ - readonly SAFETY: "SAFETY"; - /** - * The candidate content was flagged for recitation reasons. - */ - readonly RECITATION: "RECITATION"; - /** - * Unknown reason. - */ - readonly OTHER: "OTHER"; - /** - * The candidate content contained forbidden terms. - */ - readonly BLOCKLIST: "BLOCKLIST"; - /** - * The candidate content potentially contained prohibited content. - */ - readonly PROHIBITED_CONTENT: "PROHIBITED_CONTENT"; - /** - * The candidate content potentially contained Sensitive Personally Identifiable Information (SPII). - */ - readonly SPII: "SPII"; - /** - * The function call generated by the model was invalid. - */ - readonly MALFORMED_FUNCTION_CALL: "MALFORMED_FUNCTION_CALL"; -}; - -/** - * Reason that a candidate finished. - * @public - */ -export declare type FinishReason = (typeof FinishReason)[keyof typeof FinishReason]; - -/** - * A predicted {@link FunctionCall} returned from the model - * that contains a string representing the {@link FunctionDeclaration.name} - * and a structured JSON object containing the parameters and their values. - * @public - */ -export declare interface FunctionCall { - /** - * The id of the function call. This must be sent back in the associated {@link FunctionResponse}. - * - * - * @remarks This property is only supported in the Gemini Developer API ({@link GoogleAIBackend}). - * When using the Gemini Developer API ({@link GoogleAIBackend}), this property will be - * `undefined`. - */ - id?: string; - name: string; - args: object; -} - -/** - * @public - */ -export declare interface FunctionCallingConfig { - mode?: FunctionCallingMode; - allowedFunctionNames?: string[]; -} - -/** - * @public - */ -export declare const FunctionCallingMode: { - /** - * Default model behavior; model decides to predict either a function call - * or a natural language response. - */ - readonly AUTO: "AUTO"; - /** - * Model is constrained to always predicting a function call only. - * If `allowed_function_names` is set, the predicted function call will be - * limited to any one of `allowed_function_names`, else the predicted - * function call will be any one of the provided `function_declarations`. - */ - readonly ANY: "ANY"; - /** - * Model will not predict any function call. Model behavior is same as when - * not passing any function declarations. - */ - readonly NONE: "NONE"; -}; - -/** - * @public - */ -export declare type FunctionCallingMode = (typeof FunctionCallingMode)[keyof typeof FunctionCallingMode]; - -/** - * Content part interface if the part represents a {@link FunctionCall}. - * @public - */ -export declare interface FunctionCallPart { - text?: never; - inlineData?: never; - functionCall: FunctionCall; - functionResponse?: never; - thought?: boolean; - /* Excluded from this release type: thoughtSignature */ - executableCode?: never; - codeExecutionResult?: never; -} - -/** - * Structured representation of a function declaration as defined by the - * {@link https://spec.openapis.org/oas/v3.0.3 | OpenAPI 3.0 specification}. - * Included - * in this declaration are the function name and parameters. This - * `FunctionDeclaration` is a representation of a block of code that can be used - * as a Tool by the model and executed by the client. - * @public - */ -export declare interface FunctionDeclaration { - /** - * The name of the function to call. Must start with a letter or an - * underscore. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with - * a max length of 64. - */ - name: string; - /** - * Description and purpose of the function. Model uses it to decide - * how and whether to call the function. - */ - description: string; - /** - * Optional. Describes the parameters to this function in JSON Schema Object - * format. Reflects the Open API 3.03 Parameter Object. Parameter names are - * case-sensitive. For a function with no parameters, this can be left unset. - */ - parameters?: ObjectSchema | ObjectSchemaRequest; - /** - * Reference to an actual function to call. Specifying this will cause the - * function to be called automatically when requested by the model. - */ - functionReference?: Function; -} - -/** - * A `FunctionDeclarationsTool` is a piece of code that enables the system to - * interact with external systems to perform an action, or set of actions, - * outside of knowledge and scope of the model. - * @public - */ -export declare interface FunctionDeclarationsTool { - /** - * Optional. One or more function declarations - * to be passed to the model along with the current user query. Model may - * decide to call a subset of these functions by populating - * {@link FunctionCall} in the response. User should - * provide a {@link FunctionResponse} for each - * function call in the next turn. Based on the function responses, the model will - * generate the final response back to the user. Maximum 64 function - * declarations can be provided. - */ - functionDeclarations?: FunctionDeclaration[]; -} - -/** - * The result output from a {@link FunctionCall} that contains a string - * representing the {@link FunctionDeclaration.name} - * and a structured JSON object containing any output - * from the function is used as context to the model. - * This should contain the result of a {@link FunctionCall} - * made based on model prediction. - * @public - */ -export declare interface FunctionResponse { - /** - * The id of the {@link FunctionCall}. - * - * @remarks This property is only supported in the Gemini Developer API ({@link GoogleAIBackend}). - * When using the Gemini Developer API ({@link GoogleAIBackend}), this property will be - * `undefined`. - */ - id?: string; - name: string; - response: object; - parts?: Part[]; -} - -/** - * Content part interface if the part represents {@link FunctionResponse}. - * @public - */ -export declare interface FunctionResponsePart { - text?: never; - inlineData?: never; - functionCall?: never; - functionResponse: FunctionResponse; - thought?: boolean; - /* Excluded from this release type: thoughtSignature */ - executableCode?: never; - codeExecutionResult?: never; -} - -/** - * A candidate returned as part of a {@link GenerateContentResponse}. - * @public - */ -export declare interface GenerateContentCandidate { - index: number; - content: Content; - finishReason?: FinishReason; - finishMessage?: string; - safetyRatings?: SafetyRating[]; - citationMetadata?: CitationMetadata; - groundingMetadata?: GroundingMetadata; - urlContextMetadata?: URLContextMetadata; -} - -/** - * Request sent through {@link GenerativeModel.generateContent} - * @public - */ -export declare interface GenerateContentRequest extends BaseParams { - contents: Content[]; - tools?: Tool[]; - toolConfig?: ToolConfig; - systemInstruction?: string | Part | Content; -} - -/** - * Individual response from {@link GenerativeModel.generateContent} and - * {@link GenerativeModel.generateContentStream}. - * `generateContentStream()` will return one in each chunk until - * the stream is done. - * @public - */ -export declare interface GenerateContentResponse { - candidates?: GenerateContentCandidate[]; - promptFeedback?: PromptFeedback; - usageMetadata?: UsageMetadata; -} - -/** - * Result object returned from {@link GenerativeModel.generateContent} call. - * - * @public - */ -export declare interface GenerateContentResult { - response: EnhancedGenerateContentResponse; -} - -/** - * Result object returned from {@link GenerativeModel.generateContentStream} call. - * Iterate over `stream` to get chunks as they come in and/or - * use the `response` promise to get the aggregated response when - * the stream is done. - * - * @public - */ -export declare interface GenerateContentStreamResult { - stream: AsyncGenerator; - response: Promise; -} - -/** - * Config options for content-related requests - * @public - */ -export declare interface GenerationConfig { - candidateCount?: number; - stopSequences?: string[]; - maxOutputTokens?: number; - temperature?: number; - topP?: number; - topK?: number; - presencePenalty?: number; - frequencyPenalty?: number; - /** - * Output response MIME type of the generated candidate text. - * Supported MIME types are `text/plain` (default, text output), - * `application/json` (JSON response in the candidates), and - * `text/x.enum`. - */ - responseMimeType?: string; - /** - * Output response schema of the generated candidate text. This - * value can be a class generated with a {@link Schema} static method - * like `Schema.string()` or `Schema.object()` or it can be a plain - * JS object matching the {@link SchemaRequest} interface. - *
Note: This only applies when the specified `responseMimeType` supports a schema; currently - * this is limited to `application/json` and `text/x.enum`. - */ - responseSchema?: TypedSchema | SchemaRequest; - /** - * Generation modalities to be returned in generation responses. - * - * @remarks - * - Multimodal response generation is only supported by some Gemini models and versions; see {@link https://firebase.google.com/docs/vertex-ai/models | model versions}. - * - Only image generation (`ResponseModality.IMAGE`) is supported. - * - * @beta - */ - responseModalities?: ResponseModality[]; - /** - * Configuration for "thinking" behavior of compatible Gemini models. - */ - thinkingConfig?: ThinkingConfig; -} - -/** - * Interface for sending an image. - * @public - */ -export declare interface GenerativeContentBlob { - mimeType: string; - /** - * Image as a base64 string. - */ - data: string; -} - -/** - * Class for generative model APIs. - * @public - */ -export declare class GenerativeModel extends AIModel { - private chromeAdapter?; - generationConfig: GenerationConfig; - safetySettings: SafetySetting[]; - requestOptions?: RequestOptions; - tools?: Tool[]; - toolConfig?: ToolConfig; - systemInstruction?: Content; - constructor(ai: AI, modelParams: ModelParams, requestOptions?: RequestOptions, chromeAdapter?: ChromeAdapter | undefined); - /** - * Makes a single non-streaming call to the model - * and returns an object containing a single {@link GenerateContentResponse}. - */ - generateContent(request: GenerateContentRequest | string | Array, singleRequestOptions?: SingleRequestOptions): Promise; - /** - * Makes a single streaming call to the model - * and returns an object containing an iterable stream that iterates - * over all chunks in the streaming response as well as - * a promise that returns the final aggregated response. - */ - generateContentStream(request: GenerateContentRequest | string | Array, singleRequestOptions?: SingleRequestOptions): Promise; - /** - * Gets a new {@link ChatSession} instance which can be used for - * multi-turn chats. - */ - startChat(startChatParams?: StartChatParams): ChatSession; - /** - * Counts the tokens in the provided request. - */ - countTokens(request: CountTokensRequest | string | Array, singleRequestOptions?: SingleRequestOptions): Promise; -} - -/** - * Returns the default {@link AI} instance that is associated with the provided - * {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new instance with the - * default settings. - * - * @example - * ```javascript - * const ai = getAI(app); - * ``` - * - * @example - * ```javascript - * // Get an AI instance configured to use the Gemini Developer API (via Google AI). - * const ai = getAI(app, { backend: new GoogleAIBackend() }); - * ``` - * - * @example - * ```javascript - * // Get an AI instance configured to use the Vertex AI Gemini API. - * const ai = getAI(app, { backend: new VertexAIBackend() }); - * ``` - * - * @param app - The {@link @firebase/app#FirebaseApp} to use. - * @param options - {@link AIOptions} that configure the AI instance. - * @returns The default {@link AI} instance for the given {@link @firebase/app#FirebaseApp}. - * - * @public - */ -export declare function getAI(app?: FirebaseApp, options?: AIOptions): AI; - -/** - * Returns a {@link GenerativeModel} class with methods for inference - * and other functionality. - * - * @public - */ -export declare function getGenerativeModel(ai: AI, modelParams: ModelParams | HybridParams, requestOptions?: RequestOptions): GenerativeModel; - -/** - * Returns an {@link ImagenModel} class with methods for using Imagen. - * - * Only Imagen 3 models (named `imagen-3.0-*`) are supported. - * - * @param ai - An {@link AI} instance. - * @param modelParams - Parameters to use when making Imagen requests. - * @param requestOptions - Additional options to use when making requests. - * - * @throws If the `apiKey` or `projectId` fields are missing in your - * Firebase config. - * - * @public - */ -export declare function getImagenModel(ai: AI, modelParams: ImagenModelParams, requestOptions?: RequestOptions): ImagenModel; - -/** - * Returns a {@link LiveGenerativeModel} class for real-time, bidirectional communication. - * - * The Live API is only supported in modern browser windows and Node >= 22. - * - * @param ai - An {@link AI} instance. - * @param modelParams - Parameters to use when setting up a {@link LiveSession}. - * @throws If the `apiKey` or `projectId` fields are missing in your - * Firebase config. - * - * @beta - */ -export declare function getLiveGenerativeModel(ai: AI, modelParams: LiveModelParams): LiveGenerativeModel; - -/** - * Returns a {@link TemplateGenerativeModel} class for executing server-side - * templates. - * - * @param ai - An {@link AI} instance. - * @param requestOptions - Additional options to use when making requests. - * - * @beta - */ -export declare function getTemplateGenerativeModel(ai: AI, requestOptions?: RequestOptions): TemplateGenerativeModel; - -/** - * Returns a {@link TemplateImagenModel} class for executing server-side - * Imagen templates. - * - * @param ai - An {@link AI} instance. - * @param requestOptions - Additional options to use when making requests. - * - * @beta - */ -export declare function getTemplateImagenModel(ai: AI, requestOptions?: RequestOptions): TemplateImagenModel; - -/** - * Configuration class for the Gemini Developer API. - * - * Use this with {@link AIOptions} when initializing the AI service via - * {@link getAI | getAI()} to specify the Gemini Developer API as the backend. - * - * @public - */ -export declare class GoogleAIBackend extends Backend { - /** - * Creates a configuration object for the Gemini Developer API backend. - */ - constructor(); - /* Excluded from this release type: _getModelPath */ - /* Excluded from this release type: _getTemplatePath */ -} - -/* Excluded from this release type: GoogleAICitationMetadata */ - -/* Excluded from this release type: GoogleAICountTokensRequest */ - -/* Excluded from this release type: GoogleAIGenerateContentCandidate */ - -/* Excluded from this release type: GoogleAIGenerateContentResponse */ - -/** - * Specifies the Google Search configuration. - * - * @remarks Currently, this is an empty object, but it's reserved for future configuration options. - * - * @public - */ -export declare interface GoogleSearch { -} - -/** - * A tool that allows a Gemini model to connect to Google Search to access and incorporate - * up-to-date information from the web into its responses. - * - * Important: If using Grounding with Google Search, you are required to comply with the - * "Grounding with Google Search" usage requirements for your chosen API provider: {@link https://ai.google.dev/gemini-api/terms#grounding-with-google-search | Gemini Developer API} - * or Vertex AI Gemini API (see {@link https://cloud.google.com/terms/service-terms | Service Terms} - * section within the Service Specific Terms). - * - * @public - */ -export declare interface GoogleSearchTool { - /** - * Specifies the Google Search configuration. - * Currently, this is an empty object, but it's reserved for future configuration options. - * - * When using this feature, you are required to comply with the "Grounding with Google Search" - * usage requirements for your chosen API provider: {@link https://ai.google.dev/gemini-api/terms#grounding-with-google-search | Gemini Developer API} - * or Vertex AI Gemini API (see {@link https://cloud.google.com/terms/service-terms | Service Terms} - * section within the Service Specific Terms). - */ - googleSearch: GoogleSearch; -} - -/** - * Represents a chunk of retrieved data that supports a claim in the model's response. This is part - * of the grounding information provided when grounding is enabled. - * - * @public - */ -export declare interface GroundingChunk { - /** - * Contains details if the grounding chunk is from a web source. - */ - web?: WebGroundingChunk; -} - -/** - * Metadata returned when grounding is enabled. - * - * Currently, only Grounding with Google Search is supported (see {@link GoogleSearchTool}). - * - * Important: If using Grounding with Google Search, you are required to comply with the - * "Grounding with Google Search" usage requirements for your chosen API provider: {@link https://ai.google.dev/gemini-api/terms#grounding-with-google-search | Gemini Developer API} - * or Vertex AI Gemini API (see {@link https://cloud.google.com/terms/service-terms | Service Terms} - * section within the Service Specific Terms). - * - * @public - */ -export declare interface GroundingMetadata { - /** - * Google Search entry point for web searches. This contains an HTML/CSS snippet that must be - * embedded in an app to display a Google Search entry point for follow-up web searches related to - * a model's "Grounded Response". - */ - searchEntryPoint?: SearchEntrypoint; - /** - * A list of {@link GroundingChunk} objects. Each chunk represents a piece of retrieved content - * (for example, from a web page). that the model used to ground its response. - */ - groundingChunks?: GroundingChunk[]; - /** - * A list of {@link GroundingSupport} objects. Each object details how specific segments of the - * model's response are supported by the `groundingChunks`. - */ - groundingSupports?: GroundingSupport[]; - /** - * A list of web search queries that the model performed to gather the grounding information. - * These can be used to allow users to explore the search results themselves. - */ - webSearchQueries?: string[]; - /** - * @deprecated Use {@link GroundingSupport} instead. - */ - retrievalQueries?: string[]; -} - -/** - * Provides information about how a specific segment of the model's response is supported by the - * retrieved grounding chunks. - * - * @public - */ -export declare interface GroundingSupport { - /** - * Specifies the segment of the model's response content that this grounding support pertains to. - */ - segment?: Segment; - /** - * A list of indices that refer to specific {@link GroundingChunk} objects within the - * {@link GroundingMetadata.groundingChunks} array. These referenced chunks - * are the sources that support the claim made in the associated `segment` of the response. - * For example, an array `[1, 3, 4]` means that `groundingChunks[1]`, `groundingChunks[3]`, - * and `groundingChunks[4]` are the retrieved content supporting this part of the response. - */ - groundingChunkIndices?: number[]; -} - -/** - * This property is not supported in the Gemini Developer API ({@link GoogleAIBackend}). - * - * @public - */ -export declare const HarmBlockMethod: { - /** - * The harm block method uses both probability and severity scores. - */ - readonly SEVERITY: "SEVERITY"; - /** - * The harm block method uses the probability score. - */ - readonly PROBABILITY: "PROBABILITY"; -}; - -/** - * This property is not supported in the Gemini Developer API ({@link GoogleAIBackend}). - * - * @public - */ -export declare type HarmBlockMethod = (typeof HarmBlockMethod)[keyof typeof HarmBlockMethod]; - -/** - * Threshold above which a prompt or candidate will be blocked. - * @public - */ -export declare const HarmBlockThreshold: { - /** - * Content with `NEGLIGIBLE` will be allowed. - */ - readonly BLOCK_LOW_AND_ABOVE: "BLOCK_LOW_AND_ABOVE"; - /** - * Content with `NEGLIGIBLE` and `LOW` will be allowed. - */ - readonly BLOCK_MEDIUM_AND_ABOVE: "BLOCK_MEDIUM_AND_ABOVE"; - /** - * Content with `NEGLIGIBLE`, `LOW`, and `MEDIUM` will be allowed. - */ - readonly BLOCK_ONLY_HIGH: "BLOCK_ONLY_HIGH"; - /** - * All content will be allowed. - */ - readonly BLOCK_NONE: "BLOCK_NONE"; - /** - * All content will be allowed. This is the same as `BLOCK_NONE`, but the metadata corresponding - * to the {@link (HarmCategory:type)} will not be present in the response. - */ - readonly OFF: "OFF"; -}; - -/** - * Threshold above which a prompt or candidate will be blocked. - * @public - */ -export declare type HarmBlockThreshold = (typeof HarmBlockThreshold)[keyof typeof HarmBlockThreshold]; - -/** - * Harm categories that would cause prompts or candidates to be blocked. - * @public - */ -export declare const HarmCategory: { - readonly HARM_CATEGORY_HATE_SPEECH: "HARM_CATEGORY_HATE_SPEECH"; - readonly HARM_CATEGORY_SEXUALLY_EXPLICIT: "HARM_CATEGORY_SEXUALLY_EXPLICIT"; - readonly HARM_CATEGORY_HARASSMENT: "HARM_CATEGORY_HARASSMENT"; - readonly HARM_CATEGORY_DANGEROUS_CONTENT: "HARM_CATEGORY_DANGEROUS_CONTENT"; -}; - -/** - * Harm categories that would cause prompts or candidates to be blocked. - * @public - */ -export declare type HarmCategory = (typeof HarmCategory)[keyof typeof HarmCategory]; - -/** - * Probability that a prompt or candidate matches a harm category. - * @public - */ -export declare const HarmProbability: { - /** - * Content has a negligible chance of being unsafe. - */ - readonly NEGLIGIBLE: "NEGLIGIBLE"; - /** - * Content has a low chance of being unsafe. - */ - readonly LOW: "LOW"; - /** - * Content has a medium chance of being unsafe. - */ - readonly MEDIUM: "MEDIUM"; - /** - * Content has a high chance of being unsafe. - */ - readonly HIGH: "HIGH"; -}; - -/** - * Probability that a prompt or candidate matches a harm category. - * @public - */ -export declare type HarmProbability = (typeof HarmProbability)[keyof typeof HarmProbability]; - -/** - * Harm severity levels. - * @public - */ -export declare const HarmSeverity: { - /** - * Negligible level of harm severity. - */ - readonly HARM_SEVERITY_NEGLIGIBLE: "HARM_SEVERITY_NEGLIGIBLE"; - /** - * Low level of harm severity. - */ - readonly HARM_SEVERITY_LOW: "HARM_SEVERITY_LOW"; - /** - * Medium level of harm severity. - */ - readonly HARM_SEVERITY_MEDIUM: "HARM_SEVERITY_MEDIUM"; - /** - * High level of harm severity. - */ - readonly HARM_SEVERITY_HIGH: "HARM_SEVERITY_HIGH"; - /** - * Harm severity is not supported. - * - * @remarks - * The GoogleAI backend does not support `HarmSeverity`, so this value is used as a fallback. - */ - readonly HARM_SEVERITY_UNSUPPORTED: "HARM_SEVERITY_UNSUPPORTED"; -}; - -/** - * Harm severity levels. - * @public - */ -export declare type HarmSeverity = (typeof HarmSeverity)[keyof typeof HarmSeverity]; - -/** - * Configures hybrid inference. - * @beta - */ -export declare interface HybridParams { - /** - * Specifies on-device or in-cloud inference. Defaults to prefer on-device. - */ - mode: InferenceMode; - /** - * Optional. Specifies advanced params for on-device inference. - */ - onDeviceParams?: OnDeviceParams; - /** - * Optional. Specifies advanced params for in-cloud inference. - */ - inCloudParams?: ModelParams; -} - -/** - * Aspect ratios for Imagen images. - * - * To specify an aspect ratio for generated images, set the `aspectRatio` property in your - * {@link ImagenGenerationConfig}. - * - * See the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation } - * for more details and examples of the supported aspect ratios. - * - * @public - */ -export declare const ImagenAspectRatio: { - /** - * Square (1:1) aspect ratio. - */ - readonly SQUARE: "1:1"; - /** - * Landscape (3:4) aspect ratio. - */ - readonly LANDSCAPE_3x4: "3:4"; - /** - * Portrait (4:3) aspect ratio. - */ - readonly PORTRAIT_4x3: "4:3"; - /** - * Landscape (16:9) aspect ratio. - */ - readonly LANDSCAPE_16x9: "16:9"; - /** - * Portrait (9:16) aspect ratio. - */ - readonly PORTRAIT_9x16: "9:16"; -}; - -/** - * Aspect ratios for Imagen images. - * - * To specify an aspect ratio for generated images, set the `aspectRatio` property in your - * {@link ImagenGenerationConfig}. - * - * See the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation } - * for more details and examples of the supported aspect ratios. - * - * @public - */ -export declare type ImagenAspectRatio = (typeof ImagenAspectRatio)[keyof typeof ImagenAspectRatio]; - -/** - * An image generated by Imagen, stored in a Cloud Storage for Firebase bucket. - * - * This feature is not available yet. - * @public - */ -export declare interface ImagenGCSImage { - /** - * The MIME type of the image; either `"image/png"` or `"image/jpeg"`. - * - * To request a different format, set the `imageFormat` property in your {@link ImagenGenerationConfig}. - */ - mimeType: string; - /** - * The URI of the file stored in a Cloud Storage for Firebase bucket. - * - * @example `"gs://bucket-name/path/sample_0.jpg"`. - */ - gcsURI: string; -} - -/** - * Configuration options for generating images with Imagen. - * - * See the {@link http://firebase.google.com/docs/vertex-ai/generate-images-imagen | documentation} for - * more details. - * - * @public - */ -export declare interface ImagenGenerationConfig { - /** - * A description of what should be omitted from the generated images. - * - * Support for negative prompts depends on the Imagen model. - * - * See the {@link http://firebase.google.com/docs/vertex-ai/model-parameters#imagen | documentation} for more details. - * - * This is no longer supported in the Gemini Developer API ({@link GoogleAIBackend}) in versions - * greater than `imagen-3.0-generate-002`. - */ - negativePrompt?: string; - /** - * The number of images to generate. The default value is 1. - * - * The number of sample images that may be generated in each request depends on the model - * (typically up to 4); see the sampleCount - * documentation for more details. - */ - numberOfImages?: number; - /** - * The aspect ratio of the generated images. The default value is square 1:1. - * Supported aspect ratios depend on the Imagen model, see {@link (ImagenAspectRatio:type)} - * for more details. - */ - aspectRatio?: ImagenAspectRatio; - /** - * The image format of the generated images. The default is PNG. - * - * See {@link ImagenImageFormat} for more details. - */ - imageFormat?: ImagenImageFormat; - /** - * Whether to add an invisible watermark to generated images. - * - * If set to `true`, an invisible SynthID watermark is embedded in generated images to indicate - * that they are AI generated. If set to `false`, watermarking will be disabled. - * - * For Imagen 3 models, the default value is `true`; see the addWatermark - * documentation for more details. - * - * When using the Gemini Developer API ({@link GoogleAIBackend}), this will default to true, - * and cannot be turned off. - */ - addWatermark?: boolean; -} - -/** - * The response from a request to generate images with Imagen. - * - * @public - */ -export declare interface ImagenGenerationResponse { - /** - * The images generated by Imagen. - * - * The number of images generated may be fewer than the number requested if one or more were - * filtered out; see `filteredReason`. - */ - images: T[]; - /** - * The reason that images were filtered out. This property will only be defined if one - * or more images were filtered. - * - * Images may be filtered out due to the {@link (ImagenSafetyFilterLevel:type)}, - * {@link (ImagenPersonFilterLevel:type)}, or filtering included in the model. - * The filter levels may be adjusted in your {@link ImagenSafetySettings}. - * - * See the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen | Responsible AI and usage guidelines for Imagen} - * for more details. - */ - filteredReason?: string; -} - -/** - * @license - * Copyright 2025 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Defines the image format for images generated by Imagen. - * - * Use this class to specify the desired format (JPEG or PNG) and compression quality - * for images generated by Imagen. This is typically included as part of - * {@link ImagenModelParams}. - * - * @example - * ```javascript - * const imagenModelParams = { - * // ... other ImagenModelParams - * imageFormat: ImagenImageFormat.jpeg(75) // JPEG with a compression level of 75. - * } - * ``` - * - * @public - */ -export declare class ImagenImageFormat { - /** - * The MIME type. - */ - mimeType: string; - /** - * The level of compression (a number between 0 and 100). - */ - compressionQuality?: number; - private constructor(); - /** - * Creates an {@link ImagenImageFormat} for a JPEG image. - * - * @param compressionQuality - The level of compression (a number between 0 and 100). - * @returns An {@link ImagenImageFormat} object for a JPEG image. - * - * @public - */ - static jpeg(compressionQuality?: number): ImagenImageFormat; - /** - * Creates an {@link ImagenImageFormat} for a PNG image. - * - * @returns An {@link ImagenImageFormat} object for a PNG image. - * - * @public - */ - static png(): ImagenImageFormat; -} - -/** - * @license - * Copyright 2025 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An image generated by Imagen, represented as inline data. - * - * @public - */ -export declare interface ImagenInlineImage { - /** - * The MIME type of the image; either `"image/png"` or `"image/jpeg"`. - * - * To request a different format, set the `imageFormat` property in your {@link ImagenGenerationConfig}. - */ - mimeType: string; - /** - * The base64-encoded image data. - */ - bytesBase64Encoded: string; -} - -/** - * Class for Imagen model APIs. - * - * This class provides methods for generating images using the Imagen model. - * - * @example - * ```javascript - * const imagen = new ImagenModel( - * ai, - * { - * model: 'imagen-3.0-generate-002' - * } - * ); - * - * const response = await imagen.generateImages('A photo of a cat'); - * if (response.images.length > 0) { - * console.log(response.images[0].bytesBase64Encoded); - * } - * ``` - * - * @public - */ -export declare class ImagenModel extends AIModel { - requestOptions?: RequestOptions | undefined; - /** - * The Imagen generation configuration. - */ - generationConfig?: ImagenGenerationConfig; - /** - * Safety settings for filtering inappropriate content. - */ - safetySettings?: ImagenSafetySettings; - /** - * Constructs a new instance of the {@link ImagenModel} class. - * - * @param ai - an {@link AI} instance. - * @param modelParams - Parameters to use when making requests to Imagen. - * @param requestOptions - Additional options to use when making requests. - * - * @throws If the `apiKey` or `projectId` fields are missing in your - * Firebase config. - */ - constructor(ai: AI, modelParams: ImagenModelParams, requestOptions?: RequestOptions | undefined); - /** - * Generates images using the Imagen model and returns them as - * base64-encoded strings. - * - * @param prompt - A text prompt describing the image(s) to generate. - * @returns A promise that resolves to an {@link ImagenGenerationResponse} - * object containing the generated images. - * - * @throws If the request to generate images fails. This happens if the - * prompt is blocked. - * - * @remarks - * If the prompt was not blocked, but one or more of the generated images were filtered, the - * returned object will have a `filteredReason` property. - * If all images are filtered, the `images` array will be empty. - * - * @public - */ - generateImages(prompt: string, singleRequestOptions?: SingleRequestOptions): Promise>; - /* Excluded from this release type: generateImagesGCS */ -} - -/** - * Parameters for configuring an {@link ImagenModel}. - * - * @public - */ -export declare interface ImagenModelParams { - /** - * The Imagen model to use for generating images. - * For example: `imagen-3.0-generate-002`. - * - * Only Imagen 3 models (named `imagen-3.0-*`) are supported. - * - * See {@link https://firebase.google.com/docs/vertex-ai/models | model versions} - * for a full list of supported Imagen 3 models. - */ - model: string; - /** - * Configuration options for generating images with Imagen. - */ - generationConfig?: ImagenGenerationConfig; - /** - * Safety settings for filtering potentially inappropriate content. - */ - safetySettings?: ImagenSafetySettings; -} - -/** - * A filter level controlling whether generation of images containing people or faces is allowed. - * - * See the personGeneration - * documentation for more details. - * - * @public - */ -export declare const ImagenPersonFilterLevel: { - /** - * Disallow generation of images containing people or faces; images of people are filtered out. - */ - readonly BLOCK_ALL: "dont_allow"; - /** - * Allow generation of images containing adults only; images of children are filtered out. - * - * Generation of images containing people or faces may require your use case to be - * reviewed and approved by Cloud support; see the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#person-face-gen | Responsible AI and usage guidelines} - * for more details. - */ - readonly ALLOW_ADULT: "allow_adult"; - /** - * Allow generation of images containing adults only; images of children are filtered out. - * - * Generation of images containing people or faces may require your use case to be - * reviewed and approved by Cloud support; see the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#person-face-gen | Responsible AI and usage guidelines} - * for more details. - */ - readonly ALLOW_ALL: "allow_all"; -}; - -/** - * A filter level controlling whether generation of images containing people or faces is allowed. - * - * See the personGeneration - * documentation for more details. - * - * @public - */ -export declare type ImagenPersonFilterLevel = (typeof ImagenPersonFilterLevel)[keyof typeof ImagenPersonFilterLevel]; - -/** - * A filter level controlling how aggressively to filter sensitive content. - * - * Text prompts provided as inputs and images (generated or uploaded) through Imagen on Vertex AI - * are assessed against a list of safety filters, which include 'harmful categories' (for example, - * `violence`, `sexual`, `derogatory`, and `toxic`). This filter level controls how aggressively to - * filter out potentially harmful content from responses. See the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation } - * and the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#safety-filters | Responsible AI and usage guidelines} - * for more details. - * - * @public - */ -export declare const ImagenSafetyFilterLevel: { - /** - * The most aggressive filtering level; most strict blocking. - */ - readonly BLOCK_LOW_AND_ABOVE: "block_low_and_above"; - /** - * Blocks some sensitive prompts and responses. - */ - readonly BLOCK_MEDIUM_AND_ABOVE: "block_medium_and_above"; - /** - * Blocks few sensitive prompts and responses. - */ - readonly BLOCK_ONLY_HIGH: "block_only_high"; - /** - * The least aggressive filtering level; blocks very few sensitive prompts and responses. - * - * Access to this feature is restricted and may require your case to be reviewed and approved by - * Cloud support. - */ - readonly BLOCK_NONE: "block_none"; -}; - -/** - * A filter level controlling how aggressively to filter sensitive content. - * - * Text prompts provided as inputs and images (generated or uploaded) through Imagen on Vertex AI - * are assessed against a list of safety filters, which include 'harmful categories' (for example, - * `violence`, `sexual`, `derogatory`, and `toxic`). This filter level controls how aggressively to - * filter out potentially harmful content from responses. See the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation } - * and the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#safety-filters | Responsible AI and usage guidelines} - * for more details. - * - * @public - */ -export declare type ImagenSafetyFilterLevel = (typeof ImagenSafetyFilterLevel)[keyof typeof ImagenSafetyFilterLevel]; - -/** - * Settings for controlling the aggressiveness of filtering out sensitive content. - * - * See the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation } - * for more details. - * - * @public - */ -export declare interface ImagenSafetySettings { - /** - * A filter level controlling how aggressive to filter out sensitive content from generated - * images. - */ - safetyFilterLevel?: ImagenSafetyFilterLevel; - /** - * A filter level controlling whether generation of images containing people or faces is allowed. - */ - personFilterLevel?: ImagenPersonFilterLevel; -} - -/** - * Determines whether inference happens on-device or in-cloud. - * - * @remarks - * PREFER_ON_DEVICE: Attempt to make inference calls using an - * on-device model. If on-device inference is not available, the SDK - * will fall back to using a cloud-hosted model. - *
- * ONLY_ON_DEVICE: Only attempt to make inference calls using an - * on-device model. The SDK will not fall back to a cloud-hosted model. - * If on-device inference is not available, inference methods will throw. - *
- * ONLY_IN_CLOUD: Only attempt to make inference calls using a - * cloud-hosted model. The SDK will not fall back to an on-device model. - *
- * PREFER_IN_CLOUD: Attempt to make inference calls to a - * cloud-hosted model. If not available, the SDK will fall back to an - * on-device model. - * - * @beta - */ -export declare const InferenceMode: { - readonly PREFER_ON_DEVICE: "prefer_on_device"; - readonly ONLY_ON_DEVICE: "only_on_device"; - readonly ONLY_IN_CLOUD: "only_in_cloud"; - readonly PREFER_IN_CLOUD: "prefer_in_cloud"; -}; - -/** - * Determines whether inference happens on-device or in-cloud. - * - * @beta - */ -export declare type InferenceMode = (typeof InferenceMode)[keyof typeof InferenceMode]; - -/** - * Indicates whether inference happened on-device or in-cloud. - * - * @beta - */ -export declare const InferenceSource: { - readonly ON_DEVICE: "on_device"; - readonly IN_CLOUD: "in_cloud"; -}; - -/** - * Indicates whether inference happened on-device or in-cloud. - * - * @beta - */ -export declare type InferenceSource = (typeof InferenceSource)[keyof typeof InferenceSource]; - -/** - * Content part interface if the part represents an image. - * @public - */ -export declare interface InlineDataPart { - text?: never; - inlineData: GenerativeContentBlob; - functionCall?: never; - functionResponse?: never; - /** - * Applicable if `inlineData` is a video. - */ - videoMetadata?: VideoMetadata; - thought?: boolean; - /* Excluded from this release type: thoughtSignature */ - executableCode?: never; - codeExecutionResult?: never; -} - -/** - * Schema class for "integer" types. - * @public - */ -export declare class IntegerSchema extends Schema { - constructor(schemaParams?: SchemaParams); -} - -/** - * The programming language of the code. - * - * @public - */ -export declare const Language: { - UNSPECIFIED: string; - PYTHON: string; -}; - -/** - * The programming language of the code. - * - * @public - */ -export declare type Language = (typeof Language)[keyof typeof Language]; - -/** - * Configures the creation of an on-device language model session. - * @beta - */ -export declare interface LanguageModelCreateCoreOptions { - topK?: number; - temperature?: number; - expectedInputs?: LanguageModelExpected[]; -} - -/** - * Configures the creation of an on-device language model session. - * @beta - */ -export declare interface LanguageModelCreateOptions extends LanguageModelCreateCoreOptions { - signal?: AbortSignal; - initialPrompts?: LanguageModelMessage[]; -} - -/** - * Options for the expected inputs for an on-device language model. - * @beta - */ export declare interface LanguageModelExpected { - type: LanguageModelMessageType; - languages?: string[]; -} - -/** - * An on-device language model message. - * @beta - */ -export declare interface LanguageModelMessage { - role: LanguageModelMessageRole; - content: LanguageModelMessageContent[]; -} - -/** - * An on-device language model content object. - * @beta - */ -export declare interface LanguageModelMessageContent { - type: LanguageModelMessageType; - value: LanguageModelMessageContentValue; -} - -/** - * Content formats that can be provided as on-device message content. - * @beta - */ -export declare type LanguageModelMessageContentValue = ImageBitmapSource | AudioBuffer | BufferSource | string; - -/** - * Allowable roles for on-device language model usage. - * @beta - */ -export declare type LanguageModelMessageRole = 'system' | 'user' | 'assistant'; - -/** - * Allowable types for on-device language model messages. - * @beta - */ -export declare type LanguageModelMessageType = 'text' | 'image' | 'audio'; - -/** - * Options for an on-device language model prompt. - * @beta - */ -export declare interface LanguageModelPromptOptions { - responseConstraint?: object; -} - -/** - * Configuration parameters used by {@link LiveGenerativeModel} to control live content generation. - * - * @beta - */ -export declare interface LiveGenerationConfig { - /** - * Configuration for speech synthesis. - */ - speechConfig?: SpeechConfig; - /** - * Specifies the maximum number of tokens that can be generated in the response. The number of - * tokens per word varies depending on the language outputted. Is unbounded by default. - */ - maxOutputTokens?: number; - /** - * Controls the degree of randomness in token selection. A `temperature` value of 0 means that the highest - * probability tokens are always selected. In this case, responses for a given prompt are mostly - * deterministic, but a small amount of variation is still possible. - */ - temperature?: number; - /** - * Changes how the model selects tokens for output. Tokens are - * selected from the most to least probable until the sum of their probabilities equals the `topP` - * value. For example, if tokens A, B, and C have probabilities of 0.3, 0.2, and 0.1 respectively - * and the `topP` value is 0.5, then the model will select either A or B as the next token by using - * the `temperature` and exclude C as a candidate. Defaults to 0.95 if unset. - */ - topP?: number; - /** - * Changes how the model selects token for output. A `topK` value of 1 means the select token is - * the most probable among all tokens in the model's vocabulary, while a `topK` value 3 means that - * the next token is selected from among the 3 most probably using probabilities sampled. Tokens - * are then further filtered with the highest selected `temperature` sampling. Defaults to 40 - * if unspecified. - */ - topK?: number; - /** - * Positive penalties. - */ - presencePenalty?: number; - /** - * Frequency penalties. - */ - frequencyPenalty?: number; - /** - * The modalities of the response. - */ - responseModalities?: ResponseModality[]; - /** - * Enables transcription of audio input. - * - * When enabled, the model will respond with transcriptions of your audio input in the `inputTranscriptions` property - * in {@link LiveServerContent} messages. Note that the transcriptions are broken up across - * messages, so you may only receive small amounts of text per message. For example, if you ask the model - * "How are you today?", the model may transcribe that input across three messages, broken up as "How a", "re yo", "u today?". - */ - inputAudioTranscription?: AudioTranscriptionConfig; - /** - * Enables transcription of audio input. - * - * When enabled, the model will respond with transcriptions of its audio output in the `outputTranscription` property - * in {@link LiveServerContent} messages. Note that the transcriptions are broken up across - * messages, so you may only receive small amounts of text per message. For example, if the model says - * "How are you today?", the model may transcribe that output across three messages, broken up as "How a", "re yo", "u today?". - */ - outputAudioTranscription?: AudioTranscriptionConfig; -} - -/** - * Class for Live generative model APIs. The Live API enables low-latency, two-way multimodal - * interactions with Gemini. - * - * This class should only be instantiated with {@link getLiveGenerativeModel}. - * - * @beta - */ -export declare class LiveGenerativeModel extends AIModel { - /* Excluded from this release type: _webSocketHandler */ - generationConfig: LiveGenerationConfig; - tools?: Tool[]; - toolConfig?: ToolConfig; - systemInstruction?: Content; - /* Excluded from this release type: __constructor */ - /** - * Starts a {@link LiveSession}. - * - * @returns A {@link LiveSession}. - * @throws If the connection failed to be established with the server. - * - * @beta - */ - connect(): Promise; -} - -/** - * Params passed to {@link getLiveGenerativeModel}. - * @beta - */ -export declare interface LiveModelParams { - model: string; - generationConfig?: LiveGenerationConfig; - tools?: Tool[]; - toolConfig?: ToolConfig; - systemInstruction?: string | Part | Content; -} - -/** - * The types of responses that can be returned by {@link LiveSession.receive}. - * - * @beta - */ -export declare const LiveResponseType: { - SERVER_CONTENT: string; - TOOL_CALL: string; - TOOL_CALL_CANCELLATION: string; - GOING_AWAY_NOTICE: string; -}; - -/** - * The types of responses that can be returned by {@link LiveSession.receive}. - * This is a property on all messages that can be used for type narrowing. This property is not - * returned by the server, it is assigned to a server message object once it's parsed. - * - * @beta - */ -export declare type LiveResponseType = (typeof LiveResponseType)[keyof typeof LiveResponseType]; - -/** - * An incremental content update from the model. - * - * @beta - */ -export declare interface LiveServerContent { - type: 'serverContent'; - /** - * The content that the model has generated as part of the current conversation with the user. - */ - modelTurn?: Content; - /** - * Indicates whether the turn is complete. This is `undefined` if the turn is not complete. - */ - turnComplete?: boolean; - /** - * Indicates whether the model was interrupted by the client. An interruption occurs when - * the client sends a message before the model finishes it's turn. This is `undefined` if the - * model was not interrupted. - */ - interrupted?: boolean; - /** - * Transcription of the audio that was input to the model. - */ - inputTranscription?: Transcription; - /** - * Transcription of the audio output from the model. - */ - outputTranscription?: Transcription; -} - -/** - * Notification that the server will not be able to service the client soon. - * - * @beta - */ -export declare interface LiveServerGoingAwayNotice { - type: 'goingAwayNotice'; - /** - * The remaining time (in seconds) before the connection will be terminated. - */ - timeLeft: number; -} - -/** - * A request from the model for the client to execute one or more functions. - * - * @beta - */ -export declare interface LiveServerToolCall { - type: 'toolCall'; - /** - * An array of function calls to run. - */ - functionCalls: FunctionCall[]; -} - -/** - * Notification to cancel a previous function call triggered by {@link LiveServerToolCall}. - * - * @beta - */ -export declare interface LiveServerToolCallCancellation { - type: 'toolCallCancellation'; - /** - * IDs of function calls that were cancelled. These refer to the `id` property of a {@link FunctionCall}. - */ - functionIds: string[]; -} - -/** - * Represents an active, real-time, bidirectional conversation with the model. - * - * This class should only be instantiated by calling {@link LiveGenerativeModel.connect}. - * - * @beta - */ -export declare class LiveSession { - private webSocketHandler; - private serverMessages; - /** - * Indicates whether this Live session is closed. - * - * @beta - */ - isClosed: boolean; - /** - * Indicates whether this Live session is being controlled by an `AudioConversationController`. - * - * @beta - */ - inConversation: boolean; - /* Excluded from this release type: __constructor */ - /** - * Sends content to the server. - * - * @param request - The message to send to the model. - * @param turnComplete - Indicates if the turn is complete. Defaults to false. - * @throws If this session has been closed. - * - * @beta - */ - send(request: string | Array, turnComplete?: boolean): Promise; - /** - * Sends text to the server in realtime. - * - * @example - * ```javascript - * liveSession.sendTextRealtime("Hello, how are you?"); - * ``` - * - * @param text - The text data to send. - * @throws If this session has been closed. - * - * @beta - */ - sendTextRealtime(text: string): Promise; - /** - * Sends audio data to the server in realtime. - * - * @remarks The server requires that the audio data is base64-encoded 16-bit PCM at 16kHz - * little-endian. - * - * @example - * ```javascript - * // const pcmData = ... base64-encoded 16-bit PCM at 16kHz little-endian. - * const blob = { mimeType: "audio/pcm", data: pcmData }; - * liveSession.sendAudioRealtime(blob); - * ``` - * - * @param blob - The base64-encoded PCM data to send to the server in realtime. - * @throws If this session has been closed. - * - * @beta - */ - sendAudioRealtime(blob: GenerativeContentBlob): Promise; - /** - * Sends video data to the server in realtime. - * - * @remarks The server requires that the video is sent as individual video frames at 1 FPS. It - * is recommended to set `mimeType` to `image/jpeg`. - * - * @example - * ```javascript - * // const videoFrame = ... base64-encoded JPEG data - * const blob = { mimeType: "image/jpeg", data: videoFrame }; - * liveSession.sendVideoRealtime(blob); - * ``` - * @param blob - The base64-encoded video data to send to the server in realtime. - * @throws If this session has been closed. - * - * @beta - */ - sendVideoRealtime(blob: GenerativeContentBlob): Promise; - /** - * Sends function responses to the server. - * - * @param functionResponses - The function responses to send. - * @throws If this session has been closed. - * - * @beta - */ - sendFunctionResponses(functionResponses: FunctionResponse[]): Promise; - /** - * Yields messages received from the server. - * This can only be used by one consumer at a time. - * - * @returns An `AsyncGenerator` that yields server messages as they arrive. - * @throws If the session is already closed, or if we receive a response that we don't support. - * - * @beta - */ - receive(): AsyncGenerator; - /** - * Closes this session. - * All methods on this session will throw an error once this resolves. - * - * @beta - */ - close(): Promise; - /** - * Sends realtime input to the server. - * - * @deprecated Use `sendTextRealtime()`, `sendAudioRealtime()`, and `sendVideoRealtime()` instead. - * - * @param mediaChunks - The media chunks to send. - * @throws If this session has been closed. - * - * @beta - */ - sendMediaChunks(mediaChunks: GenerativeContentBlob[]): Promise; - /** - * @deprecated Use `sendTextRealtime()`, `sendAudioRealtime()`, and `sendVideoRealtime()` instead. - * - * Sends a stream of {@link GenerativeContentBlob}. - * - * @param mediaChunkStream - The stream of {@link GenerativeContentBlob} to send. - * @throws If this session has been closed. - * - * @beta - */ - sendMediaStream(mediaChunkStream: ReadableStream): Promise; -} - -/** - * Content part modality. - * @public - */ -export declare const Modality: { - /** - * Unspecified modality. - */ - readonly MODALITY_UNSPECIFIED: "MODALITY_UNSPECIFIED"; - /** - * Plain text. - */ - readonly TEXT: "TEXT"; - /** - * Image. - */ - readonly IMAGE: "IMAGE"; - /** - * Video. - */ - readonly VIDEO: "VIDEO"; - /** - * Audio. - */ - readonly AUDIO: "AUDIO"; - /** - * Document (for example, PDF). - */ - readonly DOCUMENT: "DOCUMENT"; -}; - -/** - * Content part modality. - * @public - */ -export declare type Modality = (typeof Modality)[keyof typeof Modality]; - -/** - * Represents token counting info for a single modality. - * - * @public - */ -export declare interface ModalityTokenCount { - /** The modality associated with this token count. */ - modality: Modality; - /** The number of tokens counted. */ - tokenCount: number; -} - -/** - * Params passed to {@link getGenerativeModel}. - * @public - */ -export declare interface ModelParams extends BaseParams { - model: string; - tools?: Tool[]; - toolConfig?: ToolConfig; - systemInstruction?: string | Part | Content; -} - -/** - * Schema class for "number" types. - * @public - */ -export declare class NumberSchema extends Schema { - constructor(schemaParams?: SchemaParams); -} - -/** - * Schema class for "object" types. - * The `properties` param must be a map of `Schema` objects. - * @public - */ -export declare class ObjectSchema extends Schema { - properties: { - [k: string]: TypedSchema; - }; - optionalProperties: string[]; - constructor(schemaParams: SchemaParams, properties: { - [k: string]: TypedSchema; - }, optionalProperties?: string[]); - /* Excluded from this release type: toJSON */ -} - -/** - * Interface for JSON parameters in a schema of {@link (SchemaType:type)} - * "object" when not using the `Schema.object()` helper. - * @public - */ -export declare interface ObjectSchemaRequest extends SchemaRequest { - type: 'object'; - /** - * This is not a property accepted in the final request to the backend, but is - * a client-side convenience property that is only usable by constructing - * a schema through the `Schema.object()` helper method. Populating this - * property will cause response errors if the object is not wrapped with - * `Schema.object()`. - */ - optionalProperties?: never; -} - -/** - * Encapsulates configuration for on-device inference. - * - * @beta - */ -export declare interface OnDeviceParams { - createOptions?: LanguageModelCreateOptions; - promptOptions?: LanguageModelPromptOptions; -} - -/** - * Represents the result of the code execution. - * - * @public - */ -export declare const Outcome: { - UNSPECIFIED: string; - OK: string; - FAILED: string; - DEADLINE_EXCEEDED: string; -}; - -/** - * Represents the result of the code execution. - * - * @public - */ -export declare type Outcome = (typeof Outcome)[keyof typeof Outcome]; - -/** - * Content part - includes text, image/video, or function call/response - * part types. - * @public - */ -export declare type Part = TextPart | InlineDataPart | FunctionCallPart | FunctionResponsePart | FileDataPart | ExecutableCodePart | CodeExecutionResultPart; - -/** - * Possible roles. - * @public - */ -export declare const POSSIBLE_ROLES: readonly ["user", "model", "function", "system"]; - -/** - * Configuration for a pre-built voice. - * - * @beta - */ -export declare interface PrebuiltVoiceConfig { - /** - * The voice name to use for speech synthesis. - * - * For a full list of names and demos of what each voice sounds like, see {@link https://cloud.google.com/text-to-speech/docs/chirp3-hd | Chirp 3: HD Voices}. - */ - voiceName?: string; -} - -/** - * If the prompt was blocked, this will be populated with `blockReason` and - * the relevant `safetyRatings`. - * @public - */ -export declare interface PromptFeedback { - blockReason?: BlockReason; - safetyRatings: SafetyRating[]; - /** - * A human-readable description of the `blockReason`. - * - * This property is only supported in the Vertex AI Gemini API ({@link VertexAIBackend}). - */ - blockReasonMessage?: string; -} - -/** - * Params passed to {@link getGenerativeModel}. - * @public - */ -export declare interface RequestOptions { - /** - * Request timeout in milliseconds. Defaults to 180 seconds (180000ms). - */ - timeout?: number; - /** - * Base url for endpoint. Defaults to - * https://firebasevertexai.googleapis.com, which is the - * {@link https://console.cloud.google.com/apis/library/firebasevertexai.googleapis.com?project=_ | Firebase AI Logic API} - * (used regardless of your chosen Gemini API provider). - */ - baseUrl?: string; - /** - * Limits amount of sequential function calls the SDK can make during automatic - * function calling, in order to prevent infinite loops. If not specified, - * this value defaults to 10. - * - * When it reaches this limit, it will return the last response received - * from the model, whether it is a text response or further function calls. - */ - maxSequentalFunctionCalls?: number; -} - -/** - * Generation modalities to be returned in generation responses. - * - * @beta - */ -export declare const ResponseModality: { - /** - * Text. - * @beta - */ - readonly TEXT: "TEXT"; - /** - * Image. - * @beta - */ - readonly IMAGE: "IMAGE"; - /** - * Audio. - * @beta - */ - readonly AUDIO: "AUDIO"; -}; - -/** - * Generation modalities to be returned in generation responses. - * - * @beta - */ -export declare type ResponseModality = (typeof ResponseModality)[keyof typeof ResponseModality]; - -/** - * @public - */ -export declare interface RetrievedContextAttribution { - uri: string; - title: string; -} - -/** - * @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. - */ -/** - * Role is the producer of the content. - * @public - */ -export declare type Role = (typeof POSSIBLE_ROLES)[number]; - -/** - * A safety rating associated with a {@link GenerateContentCandidate} - * @public - */ -export declare interface SafetyRating { - category: HarmCategory; - probability: HarmProbability; - /** - * The harm severity level. - * - * This property is only supported when using the Vertex AI Gemini API ({@link VertexAIBackend}). - * When using the Gemini Developer API ({@link GoogleAIBackend}), this property is not supported and will default to `HarmSeverity.UNSUPPORTED`. - */ - severity: HarmSeverity; - /** - * The probability score of the harm category. - * - * This property is only supported when using the Vertex AI Gemini API ({@link VertexAIBackend}). - * When using the Gemini Developer API ({@link GoogleAIBackend}), this property is not supported and will default to 0. - */ - probabilityScore: number; - /** - * The severity score of the harm category. - * - * This property is only supported when using the Vertex AI Gemini API ({@link VertexAIBackend}). - * When using the Gemini Developer API ({@link GoogleAIBackend}), this property is not supported and will default to 0. - */ - severityScore: number; - blocked: boolean; -} - -/** - * Safety setting that can be sent as part of request parameters. - * @public - */ -export declare interface SafetySetting { - category: HarmCategory; - threshold: HarmBlockThreshold; - /** - * The harm block method. - * - * This property is only supported in the Vertex AI Gemini API ({@link VertexAIBackend}). - * When using the Gemini Developer API ({@link GoogleAIBackend}), an {@link AIError} will be - * thrown if this property is defined. - */ - method?: HarmBlockMethod; -} - -/** - * Parent class encompassing all Schema types, with static methods that - * allow building specific Schema types. This class can be converted with - * `JSON.stringify()` into a JSON string accepted by Vertex AI REST endpoints. - * (This string conversion is automatically done when calling SDK methods.) - * @public - */ -export declare abstract class Schema implements SchemaInterface { - /** - * Optional. The type of the property. - * This can only be undefined when using `anyOf` schemas, which do not have an - * explicit type in the {@link https://swagger.io/docs/specification/v3_0/data-models/data-types/#any-type | OpenAPI specification}. - */ - type?: SchemaType; - /** Optional. The format of the property. - * Supported formats:
- *
    - *
  • for NUMBER type: "float", "double"
  • - *
  • for INTEGER type: "int32", "int64"
  • - *
  • for STRING type: "email", "byte", etc
  • - *
- */ - format?: string; - /** Optional. The description of the property. */ - description?: string; - /** Optional. The items of the property. */ - items?: SchemaInterface; - /** The minimum number of items (elements) in a schema of {@link (SchemaType:type)} `array`. */ - minItems?: number; - /** The maximum number of items (elements) in a schema of {@link (SchemaType:type)} `array`. */ - maxItems?: number; - /** Optional. Whether the property is nullable. Defaults to false. */ - nullable: boolean; - /** Optional. The example of the property. */ - example?: unknown; - /** - * Allows user to add other schema properties that have not yet - * been officially added to the SDK. - */ - [key: string]: unknown; - constructor(schemaParams: SchemaInterface); - /* Excluded from this release type: toJSON */ - static array(arrayParams: SchemaParams & { - items: Schema; - }): ArraySchema; - static object(objectParams: SchemaParams & { - properties: { - [k: string]: Schema; - }; - optionalProperties?: string[]; - }): ObjectSchema; - static string(stringParams?: SchemaParams): StringSchema; - static enumString(stringParams: SchemaParams & { - enum: string[]; - }): StringSchema; - static integer(integerParams?: SchemaParams): IntegerSchema; - static number(numberParams?: SchemaParams): NumberSchema; - static boolean(booleanParams?: SchemaParams): BooleanSchema; - static anyOf(anyOfParams: SchemaParams & { - anyOf: TypedSchema[]; - }): AnyOfSchema; -} - -/** - * Interface for {@link Schema} class. - * @public - */ -export declare interface SchemaInterface extends SchemaShared { - /** - * The type of the property. this can only be undefined when using `anyof` schemas, - * which do not have an explicit type in the {@link https://swagger.io/docs/specification/v3_0/data-models/data-types/#any-type | OpenAPI Specification}. - */ - type?: SchemaType; -} - -/** - * Params passed to {@link Schema} static methods to create specific - * {@link Schema} classes. - * @public - */ -export declare interface SchemaParams extends SchemaShared { -} - -/** - * Final format for {@link Schema} params passed to backend requests. - * @public - */ -export declare interface SchemaRequest extends SchemaShared { - /** - * The type of the property. this can only be undefined when using `anyOf` schemas, - * which do not have an explicit type in the {@link https://swagger.io/docs/specification/v3_0/data-models/data-types/#any-type | OpenAPI specification }. - */ - type?: SchemaType; - /** Optional. Array of required property. */ - required?: string[]; -} - -/** - * Basic {@link Schema} properties shared across several Schema-related - * types. - * @public - */ -export declare interface SchemaShared { - /** - * An array of {@link Schema}. The generated data must be valid against any of the schemas - * listed in this array. This allows specifying multiple possible structures or types for a - * single field. - */ - anyOf?: T[]; - /** Optional. The format of the property. - * When using the Gemini Developer API ({@link GoogleAIBackend}), this must be either `'enum'` or - * `'date-time'`, otherwise requests will fail. - */ - format?: string; - /** Optional. The description of the property. */ - description?: string; - /** - * The title of the property. This helps document the schema's purpose but does not typically - * constrain the generated value. It can subtly guide the model by clarifying the intent of a - * field. - */ - title?: string; - /** Optional. The items of the property. */ - items?: T; - /** The minimum number of items (elements) in a schema of {@link (SchemaType:type)} `array`. */ - minItems?: number; - /** The maximum number of items (elements) in a schema of {@link (SchemaType:type)} `array`. */ - maxItems?: number; - /** Optional. Map of `Schema` objects. */ - properties?: { - [k: string]: T; - }; - /** A hint suggesting the order in which the keys should appear in the generated JSON string. */ - propertyOrdering?: string[]; - /** Optional. The enum of the property. */ - enum?: string[]; - /** Optional. The example of the property. */ - example?: unknown; - /** Optional. Whether the property is nullable. */ - nullable?: boolean; - /** The minimum value of a numeric type. */ - minimum?: number; - /** The maximum value of a numeric type. */ - maximum?: number; - [key: string]: unknown; -} - -/** - * Contains the list of OpenAPI data types - * as defined by the - * {@link https://swagger.io/docs/specification/data-models/data-types/ | OpenAPI specification} - * @public - */ -export declare const SchemaType: { - /** String type. */ - readonly STRING: "string"; - /** Number type. */ - readonly NUMBER: "number"; - /** Integer type. */ - readonly INTEGER: "integer"; - /** Boolean type. */ - readonly BOOLEAN: "boolean"; - /** Array type. */ - readonly ARRAY: "array"; - /** Object type. */ - readonly OBJECT: "object"; -}; - -/** - * Contains the list of OpenAPI data types - * as defined by the - * {@link https://swagger.io/docs/specification/data-models/data-types/ | OpenAPI specification} - * @public - */ -export declare type SchemaType = (typeof SchemaType)[keyof typeof SchemaType]; - -/** - * Google search entry point. - * - * @public - */ -export declare interface SearchEntrypoint { - /** - * HTML/CSS snippet that must be embedded in a web page. The snippet is designed to avoid - * undesired interaction with the rest of the page's CSS. - * - * To ensure proper rendering and prevent CSS conflicts, it is recommended - * to encapsulate this `renderedContent` within a shadow DOM when embedding it - * into a webpage. See {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_shadow_DOM | MDN: Using shadow DOM}. - * - * @example - * ```javascript - * const container = document.createElement('div'); - * document.body.appendChild(container); - * container.attachShadow({ mode: 'open' }).innerHTML = renderedContent; - * ``` - */ - renderedContent?: string; -} - -/** - * Represents a specific segment within a {@link Content} object, often used to - * pinpoint the exact location of text or data that grounding information refers to. - * - * @public - */ -export declare interface Segment { - /** - * The zero-based index of the {@link Part} object within the `parts` array - * of its parent {@link Content} object. This identifies which part of the - * content the segment belongs to. - */ - partIndex: number; - /** - * The zero-based start index of the segment within the specified `Part`, - * measured in UTF-8 bytes. This offset is inclusive, starting from 0 at the - * beginning of the part's content (e.g., `Part.text`). - */ - startIndex: number; - /** - * The zero-based end index of the segment within the specified `Part`, - * measured in UTF-8 bytes. This offset is exclusive, meaning the character - * at this index is not included in the segment. - */ - endIndex: number; - /** - * The text corresponding to the segment from the response. - */ - text: string; -} - -/** - * Options that can be provided per-request. - * Extends the base {@link RequestOptions} (like `timeout` and `baseUrl`) - * with request-specific controls like cancellation via `AbortSignal`. - * - * Options specified here will override any default {@link RequestOptions} - * configured on a model (for example, {@link GenerativeModel}). - * - * @public - */ -export declare interface SingleRequestOptions extends RequestOptions { - /** - * An `AbortSignal` instance that allows cancelling ongoing requests (like `generateContent` or - * `generateImages`). - * - * If provided, calling `abort()` on the corresponding `AbortController` - * will attempt to cancel the underlying HTTP request. An `AbortError` will be thrown - * if cancellation is successful. - * - * Note that this will not cancel the request in the backend, so any applicable billing charges - * will still be applied despite cancellation. - * - * @example - * ```javascript - * const controller = new AbortController(); - * const model = getGenerativeModel({ - * // ... - * }); - * model.generateContent( - * "Write a story about a magic backpack.", - * { signal: controller.signal } - * ); - * - * // To cancel request: - * controller.abort(); - * ``` - * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal - */ - signal?: AbortSignal; -} - -/** - * Configures speech synthesis. - * - * @beta - */ -export declare interface SpeechConfig { - /** - * Configures the voice to be used in speech synthesis. - */ - voiceConfig?: VoiceConfig; -} - -/** - * Starts a real-time, bidirectional audio conversation with the model. This helper function manages - * the complexities of microphone access, audio recording, playback, and interruptions. - * - * @remarks Important: This function must be called in response to a user gesture - * (for example, a button click) to comply with {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Best_practices#autoplay_policy | browser autoplay policies}. - * - * @example - * ```javascript - * const liveSession = await model.connect(); - * let conversationController; - * - * // This function must be called from within a click handler. - * async function startConversation() { - * try { - * conversationController = await startAudioConversation(liveSession); - * } catch (e) { - * // Handle AI-specific errors - * if (e instanceof AIError) { - * console.error("AI Error:", e.message); - * } - * // Handle microphone permission and hardware errors - * else if (e instanceof DOMException) { - * console.error("Microphone Error:", e.message); - * } - * // Handle other unexpected errors - * else { - * console.error("An unexpected error occurred:", e); - * } - * } - * } - * - * // Later, to stop the conversation: - * // if (conversationController) { - * // await conversationController.stop(); - * // } - * ``` - * - * @param liveSession - An active {@link LiveSession} instance. - * @param options - Configuration options for the audio conversation. - * @returns A `Promise` that resolves with an {@link AudioConversationController}. - * @throws `AIError` if the environment does not support required Web APIs (`UNSUPPORTED`), if a conversation is already active (`REQUEST_ERROR`), the session is closed (`SESSION_CLOSED`), or if an unexpected initialization error occurs (`ERROR`). - * @throws `DOMException` Thrown by `navigator.mediaDevices.getUserMedia()` if issues occur with microphone access, such as permissions being denied (`NotAllowedError`) or no compatible hardware being found (`NotFoundError`). See the {@link https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#exceptions | MDN documentation} for a full list of exceptions. - * - * @beta - */ -export declare function startAudioConversation(liveSession: LiveSession, options?: StartAudioConversationOptions): Promise; - -/** - * Options for {@link startAudioConversation}. - * - * @beta - */ -export declare interface StartAudioConversationOptions { - /** - * An async handler that is called when the model requests a function to be executed. - * The handler should perform the function call and return the result as a `Part`, - * which will then be sent back to the model. - */ - functionCallingHandler?: (functionCalls: FunctionCall[]) => Promise; -} - -/** - * Params for {@link GenerativeModel.startChat}. - * @public - */ -export declare interface StartChatParams extends BaseParams { - history?: Content[]; - tools?: Tool[]; - toolConfig?: ToolConfig; - systemInstruction?: string | Part | Content; -} - -/** - * Schema class for "string" types. Can be used with or without - * enum values. - * @public - */ -export declare class StringSchema extends Schema { - enum?: string[]; - constructor(schemaParams?: SchemaParams, enumValues?: string[]); - /* Excluded from this release type: toJSON */ -} - -/** - * {@link GenerativeModel} APIs that execute on a server-side template. - * - * This class should only be instantiated with {@link getTemplateGenerativeModel}. - * - * @beta - */ -export declare class TemplateGenerativeModel { - /* Excluded from this release type: _apiSettings */ - /** - * Additional options to use when making requests. - */ - requestOptions?: RequestOptions; - /** - * @hideconstructor - */ - constructor(ai: AI, requestOptions?: RequestOptions); - /** - * Makes a single non-streaming call to the model and returns an object - * containing a single {@link GenerateContentResponse}. - * - * @param templateId - The ID of the server-side template to execute. - * @param templateVariables - A key-value map of variables to populate the - * template with. - * - * @beta - */ - generateContent(templateId: string, templateVariables: object, singleRequestOptions?: SingleRequestOptions): Promise; - /** - * Makes a single streaming call to the model and returns an object - * containing an iterable stream that iterates over all chunks in the - * streaming response as well as a promise that returns the final aggregated - * response. - * - * @param templateId - The ID of the server-side template to execute. - * @param templateVariables - A key-value map of variables to populate the - * template with. - * - * @beta - */ - generateContentStream(templateId: string, templateVariables: object, singleRequestOptions?: SingleRequestOptions): Promise; -} - -/** - * Class for Imagen model APIs that execute on a server-side template. - * - * This class should only be instantiated with {@link getTemplateImagenModel}. - * - * @beta - */ -export declare class TemplateImagenModel { - /* Excluded from this release type: _apiSettings */ - /** - * Additional options to use when making requests. - */ - requestOptions?: RequestOptions; - /** - * @hideconstructor - */ - constructor(ai: AI, requestOptions?: RequestOptions); - /** - * Makes a single call to the model and returns an object containing a single - * {@link ImagenGenerationResponse}. - * - * @param templateId - The ID of the server-side template to execute. - * @param templateVariables - A key-value map of variables to populate the - * template with. - * - * @beta - */ - generateImages(templateId: string, templateVariables: object, singleRequestOptions?: SingleRequestOptions): Promise>; -} - -/** - * Content part interface if the part represents a text string. - * @public - */ -export declare interface TextPart { - text: string; - inlineData?: never; - functionCall?: never; - functionResponse?: never; - thought?: boolean; - /* Excluded from this release type: thoughtSignature */ - executableCode?: never; - codeExecutionResult?: never; -} - -/** - * Configuration for "thinking" behavior of compatible Gemini models. - * - * Certain models utilize a thinking process before generating a response. This allows them to - * reason through complex problems and plan a more coherent and accurate answer. - * - * @public - */ -export declare interface ThinkingConfig { - /** - * The thinking budget, in tokens. - * - * @remarks - * This parameter sets an upper limit on the number of tokens the model can use for its internal - * "thinking" process. A higher budget may result in higher quality responses for complex tasks - * but can also increase latency and cost. - * - * The range of supported thinking budget values depends on the model. - * - *
    - *
  • To use the default thinking budget for a model, leave - * this value undefined.
  • - * - *
  • To disable thinking, when supported by the model, set this value - * to `0`.
  • - * - *
  • To use dynamic thinking, which allows the model to decide on the thinking - * budget based on the task, set this value to `-1`.
  • - *
- * - * An error will be thrown if you set a thinking budget for a model that does not support this - * feature or if the specified budget is not within the model's supported range. - * - * The model will also error if `thinkingLevel` and `thinkingBudget` are - * both set. - */ - thinkingBudget?: number; - /** - * If not specified, Gemini will use the model's default dynamic thinking level. - * - * @remarks - * Note: The model will error if `thinkingLevel` and `thinkingBudget` are - * both set. - * - * Important: Gemini 2.5 series models do not support thinking levels; use - * `thinkingBudget` to set a thinking budget instead. - */ - thinkingLevel?: ThinkingLevel; - /** - * Whether to include "thought summaries" in the model's response. - * - * @remarks - * Thought summaries provide a brief overview of the model's internal thinking process, - * offering insight into how it arrived at the final answer. This can be useful for - * debugging, understanding the model's reasoning, and verifying its accuracy. - */ - includeThoughts?: boolean; -} - -/** - * A preset that controls the model's "thinking" process. Use - * `ThinkingLevel.LOW` for faster responses on less complex tasks, and - * `ThinkingLevel.HIGH` for better reasoning on more complex tasks. - * - * @public - */ -export declare const ThinkingLevel: { - MINIMAL: string; - LOW: string; - MEDIUM: string; - HIGH: string; -}; - -/** - * A preset that controls the model's "thinking" process. Use - * `ThinkingLevel.LOW` for faster responses on less complex tasks, and - * `ThinkingLevel.HIGH` for better reasoning on more complex tasks. - * - * @public - */ -export declare type ThinkingLevel = (typeof ThinkingLevel)[keyof typeof ThinkingLevel]; - -/** - * Defines a tool that model can call to access external knowledge. - * @public - */ -export declare type Tool = FunctionDeclarationsTool | GoogleSearchTool | CodeExecutionTool | URLContextTool; - -/** - * Tool config. This config is shared for all tools provided in the request. - * @public - */ -export declare interface ToolConfig { - functionCallingConfig?: FunctionCallingConfig; -} - -/** - * Transcription of audio. This can be returned from a {@link LiveGenerativeModel} if transcription - * is enabled with the `inputAudioTranscription` or `outputAudioTranscription` properties on - * the {@link LiveGenerationConfig}. - * - * @beta - */ -export declare interface Transcription { - /** - * The text transcription of the audio. - */ - text?: string; -} - -/** - * A type that includes all specific Schema types. - * @public - */ -export declare type TypedSchema = IntegerSchema | NumberSchema | StringSchema | BooleanSchema | ObjectSchema | ArraySchema | AnyOfSchema; - -/** - * Specifies the URL Context configuration. - * - * @beta - */ -export declare interface URLContext { -} - -/** - * Metadata related to {@link URLContextTool}. - * - * @public - */ -export declare interface URLContextMetadata { - /** - * List of URL metadata used to provide context to the Gemini model. - */ - urlMetadata: URLMetadata[]; -} - -/** - * A tool that allows you to provide additional context to the models in the form of public web - * URLs. By including URLs in your request, the Gemini model will access the content from those - * pages to inform and enhance its response. - * - * @beta - */ -export declare interface URLContextTool { - /** - * Specifies the URL Context configuration. - */ - urlContext: URLContext; -} - -/** - * Metadata for a single URL retrieved by the {@link URLContextTool} tool. - * - * @public - */ -export declare interface URLMetadata { - /** - * The retrieved URL. - */ - retrievedUrl?: string; - /** - * The status of the URL retrieval. - */ - urlRetrievalStatus?: URLRetrievalStatus; -} - -/** - * The status of a URL retrieval. - * - * @remarks - * URL_RETRIEVAL_STATUS_UNSPECIFIED: Unspecified retrieval status. - *
- * URL_RETRIEVAL_STATUS_SUCCESS: The URL retrieval was successful. - *
- * URL_RETRIEVAL_STATUS_ERROR: The URL retrieval failed. - *
- * URL_RETRIEVAL_STATUS_PAYWALL: The URL retrieval failed because the content is behind a paywall. - *
- * URL_RETRIEVAL_STATUS_UNSAFE: The URL retrieval failed because the content is unsafe. - *
- * - * @public - */ -export declare const URLRetrievalStatus: { - /** - * Unspecified retrieval status. - */ - URL_RETRIEVAL_STATUS_UNSPECIFIED: string; - /** - * The URL retrieval was successful. - */ - URL_RETRIEVAL_STATUS_SUCCESS: string; - /** - * The URL retrieval failed. - */ - URL_RETRIEVAL_STATUS_ERROR: string; - /** - * The URL retrieval failed because the content is behind a paywall. - */ - URL_RETRIEVAL_STATUS_PAYWALL: string; - /** - * The URL retrieval failed because the content is unsafe. - */ - URL_RETRIEVAL_STATUS_UNSAFE: string; -}; - -/** - * The status of a URL retrieval. - * - * @remarks - * URL_RETRIEVAL_STATUS_UNSPECIFIED: Unspecified retrieval status. - *
- * URL_RETRIEVAL_STATUS_SUCCESS: The URL retrieval was successful. - *
- * URL_RETRIEVAL_STATUS_ERROR: The URL retrieval failed. - *
- * URL_RETRIEVAL_STATUS_PAYWALL: The URL retrieval failed because the content is behind a paywall. - *
- * URL_RETRIEVAL_STATUS_UNSAFE: The URL retrieval failed because the content is unsafe. - *
- * - * @public - */ -export declare type URLRetrievalStatus = (typeof URLRetrievalStatus)[keyof typeof URLRetrievalStatus]; - -/** - * Usage metadata about a {@link GenerateContentResponse}. - * - * @public - */ -export declare interface UsageMetadata { - promptTokenCount: number; - candidatesTokenCount: number; - /** - * The number of tokens used by the model's internal "thinking" process. - */ - thoughtsTokenCount?: number; - totalTokenCount: number; - /** - * The number of tokens used by tools. - */ - toolUsePromptTokenCount?: number; - promptTokensDetails?: ModalityTokenCount[]; - candidatesTokensDetails?: ModalityTokenCount[]; - /** - * A list of tokens used by tools, broken down by modality. - */ - toolUsePromptTokensDetails?: ModalityTokenCount[]; - /** - * The number of tokens in the prompt that were served from the cache. - * If implicit caching is not active or no content was cached, - * this will be 0. - */ - cachedContentTokenCount?: number; - /** - * Detailed breakdown of the cached tokens by modality (for example, text or - * image). This list provides granular insight into which parts of - * the content were cached. - */ - cacheTokensDetails?: ModalityTokenCount[]; -} - -/** - * Configuration class for the Vertex AI Gemini API. - * - * Use this with {@link AIOptions} when initializing the AI service via - * {@link getAI | getAI()} to specify the Vertex AI Gemini API as the backend. - * - * @public - */ -export declare class VertexAIBackend extends Backend { - /** - * The region identifier. - * See {@link https://firebase.google.com/docs/vertex-ai/locations#available-locations | Vertex AI locations} - * for a list of supported locations. - */ - readonly location: string; - /** - * Creates a configuration object for the Vertex AI backend. - * - * @param location - The region identifier, defaulting to `us-central1`; - * see {@link https://firebase.google.com/docs/vertex-ai/locations#available-locations | Vertex AI locations} - * for a list of supported locations. - */ - constructor(location?: string); - /* Excluded from this release type: _getModelPath */ - /* Excluded from this release type: _getTemplatePath */ -} - -/** - * Describes the input video content. - * @public - */ -export declare interface VideoMetadata { - /** - * The start offset of the video in - * protobuf {@link https://cloud.google.com/ruby/docs/reference/google-cloud-workflows-v1/latest/Google-Protobuf-Duration#json-mapping | Duration} format. - */ - startOffset: string; - /** - * The end offset of the video in - * protobuf {@link https://cloud.google.com/ruby/docs/reference/google-cloud-workflows-v1/latest/Google-Protobuf-Duration#json-mapping | Duration} format. - */ - endOffset: string; -} - -/** - * Configuration for the voice to used in speech synthesis. - * - * @beta - */ -export declare interface VoiceConfig { - /** - * Configures the voice using a pre-built voice configuration. - */ - prebuiltVoiceConfig?: PrebuiltVoiceConfig; -} - -/** - * @public - */ -export declare interface WebAttribution { - uri: string; - title: string; -} - -/** - * A grounding chunk from the web. - * - * Important: If using Grounding with Google Search, you are required to comply with the - * {@link https://cloud.google.com/terms/service-terms | Service Specific Terms} for "Grounding with Google Search". - * - * @public - */ -export declare interface WebGroundingChunk { - /** - * The URI of the retrieved web page. - */ - uri?: string; - /** - * The title of the retrieved web page. - */ - title?: string; - /** - * The domain of the original URI from which the content was retrieved. - * - * This property is only supported in the Vertex AI Gemini API ({@link VertexAIBackend}). - * When using the Gemini Developer API ({@link GoogleAIBackend}), this property will be - * `undefined`. - */ - domain?: string; -} - -/* Excluded from this release type: WebSocketHandler */ - -export { } - diff --git a/.github/scripts/compare-types/packages/app-check/app-check-sdk.d.ts b/.github/scripts/compare-types/packages/app-check/app-check-sdk.d.ts deleted file mode 100644 index f3239432a4..0000000000 --- a/.github/scripts/compare-types/packages/app-check/app-check-sdk.d.ts +++ /dev/null @@ -1,248 +0,0 @@ -/** - * The Firebase App Check Web SDK. - * - * @remarks - * Firebase App Check does not work in a Node.js environment using `ReCaptchaV3Provider` or - * `ReCaptchaEnterpriseProvider`, but can be used in Node.js if you use - * `CustomProvider` and write your own attestation method. - * - * @packageDocumentation - */ - -import { FirebaseApp } from '@firebase/app'; -import { PartialObserver } from '@firebase/util'; -import { Unsubscribe } from '@firebase/util'; - -/** - * The Firebase App Check service interface. - * - * @public - */ -export declare interface AppCheck { - /** - * The {@link @firebase/app#FirebaseApp} this `AppCheck` instance is associated with. - */ - app: FirebaseApp; -} - -/* Excluded from this release type: _AppCheckComponentName */ - -/* Excluded from this release type: _AppCheckInternalComponentName */ - -/** - * Options for App Check initialization. - * @public - */ -export declare interface AppCheckOptions { - /** - * A reCAPTCHA V3 provider, reCAPTCHA Enterprise provider, or custom provider. - */ - provider: CustomProvider | ReCaptchaV3Provider | ReCaptchaEnterpriseProvider; - /** - * If set to true, enables automatic background refresh of App Check token. - */ - isTokenAutoRefreshEnabled?: boolean; -} - -declare interface AppCheckProvider { - /* Excluded from this release type: getToken */ - /* Excluded from this release type: initialize */ -} - -/** - * The token returned from an App Check provider. - * @public - */ -export declare interface AppCheckToken { - readonly token: string; - /** - * The local timestamp after which the token will expire. - */ - readonly expireTimeMillis: number; -} - -declare interface AppCheckTokenInternal extends AppCheckToken { - issuedAtTimeMillis: number; -} - -/** - * A listener that is called whenever the App Check token changes. - * @public - */ -export declare type AppCheckTokenListener = (token: AppCheckTokenResult) => void; - -/** - * Result returned by `getToken()`. - * @public - */ -export declare interface AppCheckTokenResult { - /** - * The token string in JWT format. - */ - readonly token: string; -} - -/** - * Custom provider class. - * @public - */ -export declare class CustomProvider implements AppCheckProvider { - private _customProviderOptions; - private _app?; - constructor(_customProviderOptions: CustomProviderOptions); - /* Excluded from this release type: getToken */ - /* Excluded from this release type: initialize */ - /* Excluded from this release type: isEqual */ -} - -/** - * Options when creating a {@link CustomProvider}. - * @public - */ -export declare interface CustomProviderOptions { - /** - * Function to get an App Check token through a custom provider - * service. - */ - getToken: () => Promise; -} - -/** - * Requests a Firebase App Check token. This method should be used - * only if you need to authorize requests to a non-Firebase backend. - * - * Returns limited-use tokens that are intended for use with your - * non-Firebase backend endpoints that are protected with - * - * Replay Protection. This method - * does not affect the token generation behavior of the - * #getAppCheckToken() method. - * - * @param appCheckInstance - The App Check service instance. - * @returns The limited use token. - * @public - */ -export declare function getLimitedUseToken(appCheckInstance: AppCheck): Promise; - -/** - * Get the current App Check token. If `forceRefresh` is false, this function first - * checks for a valid token in memory, then local persistence (IndexedDB). - * If not found, or if `forceRefresh` is true, it makes a request to the - * App Check endpoint for a fresh token. That request attaches - * to the most recent in-flight request if one is present. - * - * @param appCheckInstance - The App Check service instance. - * @param forceRefresh - If true, will always try to fetch a fresh token. - * If false, will use a cached token if found in storage. - * @public - */ -export declare function getToken(appCheckInstance: AppCheck, forceRefresh?: boolean): Promise; - -/** - * Activate App Check for the given app. Can be called only once per app. - * @param app - the {@link @firebase/app#FirebaseApp} to activate App Check for - * @param options - App Check initialization options - * @public - */ -export declare function initializeAppCheck(app: FirebaseApp | undefined, options: AppCheckOptions): AppCheck; - -/** - * Registers a listener to changes in the token state. There can be more - * than one listener registered at the same time for one or more - * App Check instances. The listeners call back on the UI thread whenever - * the current token associated with this App Check instance changes. - * - * @param appCheckInstance - The App Check service instance. - * @param observer - An object with `next`, `error`, and `complete` - * properties. `next` is called with an - * {@link AppCheckTokenResult} - * whenever the token changes. `error` is optional and is called if an - * error is thrown by the listener (the `next` function). `complete` - * is unused, as the token stream is unending. - * - * @returns A function that unsubscribes this listener. - * @public - */ -export declare function onTokenChanged(appCheckInstance: AppCheck, observer: PartialObserver): Unsubscribe; - -/** - * Registers a listener to changes in the token state. There can be more - * than one listener registered at the same time for one or more - * App Check instances. The listeners call back on the UI thread whenever - * the current token associated with this App Check instance changes. - * - * @param appCheckInstance - The App Check service instance. - * @param onNext - When the token changes, this function is called with an - * {@link AppCheckTokenResult}. - * @param onError - Optional. Called if there is an error thrown by the - * listener (the `onNext` function). - * @param onCompletion - Currently unused, as the token stream is unending. - * @returns A function that unsubscribes this listener. - * @public - */ -export declare function onTokenChanged(appCheckInstance: AppCheck, onNext: (tokenResult: AppCheckTokenResult) => void, onError?: (error: Error) => void, onCompletion?: () => void): Unsubscribe; -export { PartialObserver } - -/** - * App Check provider that can obtain a reCAPTCHA Enterprise token and exchange it - * for an App Check token. - * - * @public - */ -export declare class ReCaptchaEnterpriseProvider implements AppCheckProvider { - private _siteKey; - private _app?; - private _heartbeatServiceProvider?; - /** - * Throttle requests on certain error codes to prevent too many retries - * in a short time. - */ - private _throttleData; - /** - * Create a ReCaptchaEnterpriseProvider instance. - * @param siteKey - reCAPTCHA Enterprise score-based site key. - */ - constructor(_siteKey: string); - /* Excluded from this release type: getToken */ - /* Excluded from this release type: initialize */ - /* Excluded from this release type: isEqual */ -} - -/** - * App Check provider that can obtain a reCAPTCHA V3 token and exchange it - * for an App Check token. - * - * @public - */ -export declare class ReCaptchaV3Provider implements AppCheckProvider { - private _siteKey; - private _app?; - private _heartbeatServiceProvider?; - /** - * Throttle requests on certain error codes to prevent too many retries - * in a short time. - */ - private _throttleData; - /** - * Create a ReCaptchaV3Provider instance. - * @param siteKey - ReCAPTCHA V3 siteKey. - */ - constructor(_siteKey: string); - /* Excluded from this release type: getToken */ - /* Excluded from this release type: initialize */ - /* Excluded from this release type: isEqual */ -} - -/** - * Set whether App Check will automatically refresh tokens as needed. - * - * @param appCheckInstance - The App Check service instance. - * @param isTokenAutoRefreshEnabled - If true, the SDK automatically - * refreshes App Check tokens as needed. This overrides any value set - * during `initializeAppCheck()`. - * @public - */ -export declare function setTokenAutoRefreshEnabled(appCheckInstance: AppCheck, isTokenAutoRefreshEnabled: boolean): void; -export { Unsubscribe } - -export { } diff --git a/.github/scripts/compare-types/packages/database/firebase-sdk.d.ts b/.github/scripts/compare-types/packages/database/firebase-sdk.d.ts deleted file mode 100644 index 58d55eb907..0000000000 --- a/.github/scripts/compare-types/packages/database/firebase-sdk.d.ts +++ /dev/null @@ -1,321 +0,0 @@ -/** - * Public types snapshot from the Firebase JS SDK (@firebase/database). - * - * Source: firebase-js-sdk API report for "@firebase/database" - * Modality: modular (tree-shakeable) API only - */ - -import { FirebaseApp } from '@firebase/app'; - -export declare type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) & - Partial<{ - iss: string; - aud: string; - sub: string; - iat: number; - exp: number; - user_id: string; - auth_time: number; - provider_id?: 'anonymous'; - email?: string; - email_verified?: boolean; - phone_number?: string; - name?: string; - picture?: string; - firebase: { - sign_in_provider: - | 'custom' - | 'email' - | 'password' - | 'phone' - | 'anonymous' - | 'google.com' - | 'facebook.com' - | 'github.com' - | 'twitter.com' - | 'microsoft.com' - | 'apple.com'; - identities?: { - custom?: string[]; - email?: string[]; - password?: string[]; - phone?: string[]; - anonymous?: string[]; - 'google.com'?: string[]; - 'facebook.com'?: string[]; - 'github.com'?: string[]; - 'twitter.com'?: string[]; - 'microsoft.com'?: string[]; - 'apple.com'?: string[]; - }; - }; - uid?: never; - [claim: string]: unknown; - }>; - -export declare function child(parent: DatabaseReference, path: string): DatabaseReference; - -export declare function connectDatabaseEmulator( - db: Database, - host: string, - port: number, - options?: { - mockUserToken?: EmulatorMockTokenOptions | string; - }, -): void; - -export declare class Database { - readonly app: FirebaseApp; - readonly type: 'database'; -} - -export declare interface DatabaseReference extends Query { - readonly key: string | null; - readonly parent: DatabaseReference | null; - readonly root: DatabaseReference; -} - -export declare class DataSnapshot { - readonly key: string | null; - readonly priority: string | number | null; - readonly ref: DatabaseReference; - readonly size: number; - child(path: string): DataSnapshot; - exists(): boolean; - exportVal(): any; - forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean; - hasChild(path: string): boolean; - hasChildren(): boolean; - toJSON(): object | null; - val(): any; -} - -export declare function enableLogging(enabled: boolean, persistent?: boolean): any; -export declare function enableLogging(logger: (message: string) => unknown): any; - -export declare function endAt( - value: number | string | boolean | null, - key?: string, -): QueryConstraint; - -export declare function endBefore( - value: number | string | boolean | null, - key?: string, -): QueryConstraint; - -export declare function equalTo( - value: number | string | boolean | null, - key?: string, -): QueryConstraint; - -export declare type EventType = - | 'value' - | 'child_added' - | 'child_changed' - | 'child_moved' - | 'child_removed'; - -export declare function forceLongPolling(): void; -export declare function forceWebSockets(): void; - -export declare function get(query: Query): Promise; -export declare function getDatabase(app?: FirebaseApp, url?: string): Database; -export declare function goOffline(db: Database): void; -export declare function goOnline(db: Database): void; -export declare function increment(delta: number): object; - -export declare interface IteratedDataSnapshot extends DataSnapshot { - key: string; -} - -export declare function limitToFirst(limit: number): QueryConstraint; -export declare function limitToLast(limit: number): QueryConstraint; - -export declare interface ListenOptions { - readonly onlyOnce?: boolean; -} - -export declare function off( - query: Query, - eventType?: EventType, - callback?: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown, -): void; - -export declare function onChildAdded( - query: Query, - callback: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown, - cancelCallback?: (error: Error) => unknown, -): Unsubscribe; -export declare function onChildAdded( - query: Query, - callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, - options: ListenOptions, -): Unsubscribe; -export declare function onChildAdded( - query: Query, - callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, - cancelCallback: (error: Error) => unknown, - options: ListenOptions, -): Unsubscribe; - -export declare function onChildChanged( - query: Query, - callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, - cancelCallback?: (error: Error) => unknown, -): Unsubscribe; -export declare function onChildChanged( - query: Query, - callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, - options: ListenOptions, -): Unsubscribe; -export declare function onChildChanged( - query: Query, - callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, - cancelCallback: (error: Error) => unknown, - options: ListenOptions, -): Unsubscribe; - -export declare function onChildMoved( - query: Query, - callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, - cancelCallback?: (error: Error) => unknown, -): Unsubscribe; -export declare function onChildMoved( - query: Query, - callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, - options: ListenOptions, -): Unsubscribe; -export declare function onChildMoved( - query: Query, - callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, - cancelCallback: (error: Error) => unknown, - options: ListenOptions, -): Unsubscribe; - -export declare function onChildRemoved( - query: Query, - callback: (snapshot: DataSnapshot) => unknown, - cancelCallback?: (error: Error) => unknown, -): Unsubscribe; -export declare function onChildRemoved( - query: Query, - callback: (snapshot: DataSnapshot) => unknown, - options: ListenOptions, -): Unsubscribe; -export declare function onChildRemoved( - query: Query, - callback: (snapshot: DataSnapshot) => unknown, - cancelCallback: (error: Error) => unknown, - options: ListenOptions, -): Unsubscribe; - -export declare class OnDisconnect { - cancel(): Promise; - remove(): Promise; - set(value: unknown): Promise; - setWithPriority(value: unknown, priority: string | number | null): Promise; - update(values: object): Promise; -} - -export declare function onDisconnect(ref: DatabaseReference): OnDisconnect; - -export declare function onValue( - query: Query, - callback: (snapshot: DataSnapshot) => unknown, - cancelCallback?: (error: Error) => unknown, -): Unsubscribe; -export declare function onValue( - query: Query, - callback: (snapshot: DataSnapshot) => unknown, - options: ListenOptions, -): Unsubscribe; -export declare function onValue( - query: Query, - callback: (snapshot: DataSnapshot) => unknown, - cancelCallback: (error: Error) => unknown, - options: ListenOptions, -): Unsubscribe; - -export declare function orderByChild(path: string): QueryConstraint; -export declare function orderByKey(): QueryConstraint; -export declare function orderByPriority(): QueryConstraint; -export declare function orderByValue(): QueryConstraint; - -export declare function push(parent: DatabaseReference, value?: unknown): ThenableReference; - -export declare interface Query { - isEqual(other: Query | null): boolean; - readonly ref: DatabaseReference; - toJSON(): string; - toString(): string; -} - -export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; - -export declare abstract class QueryConstraint { - abstract readonly type: QueryConstraintType; -} - -export declare type QueryConstraintType = - | 'endAt' - | 'endBefore' - | 'startAt' - | 'startAfter' - | 'limitToFirst' - | 'limitToLast' - | 'orderByChild' - | 'orderByKey' - | 'orderByPriority' - | 'orderByValue' - | 'equalTo'; - -export declare function ref(db: Database, path?: string): DatabaseReference; -export declare function refFromURL(db: Database, url: string): DatabaseReference; -export declare function remove(ref: DatabaseReference): Promise; - -export declare function runTransaction( - ref: DatabaseReference, - transactionUpdate: (currentData: any) => unknown, - options?: TransactionOptions, -): Promise; - -export declare function serverTimestamp(): object; -export declare function set(ref: DatabaseReference, value: unknown): Promise; -export declare function setPriority( - ref: DatabaseReference, - priority: string | number | null, -): Promise; -export declare function setWithPriority( - ref: DatabaseReference, - value: unknown, - priority: string | number | null, -): Promise; - -export declare function startAfter( - value: number | string | boolean | null, - key?: string, -): QueryConstraint; -export declare function startAt( - value?: number | string | boolean | null, - key?: string, -): QueryConstraint; - -export declare interface ThenableReference - extends DatabaseReference, Pick, 'then' | 'catch'> { - key: string; - parent: DatabaseReference; -} - -export declare interface TransactionOptions { - readonly applyLocally?: boolean; -} - -export declare class TransactionResult { - readonly committed: boolean; - readonly snapshot: DataSnapshot; - toJSON(): object; -} - -export declare type Unsubscribe = () => void; - -export declare function update(ref: DatabaseReference, values: object): Promise; diff --git a/.github/scripts/compare-types/packages/firestore-pipelines/config.ts b/.github/scripts/compare-types/packages/firestore-pipelines/config.ts deleted file mode 100644 index 7121a0a491..0000000000 --- a/.github/scripts/compare-types/packages/firestore-pipelines/config.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Known differences between the firebase-js-sdk Firestore Pipelines API - * and the @react-native-firebase/firestore pipelines API - * (imported from "@react-native-firebase/firestore/pipelines"). - * - * Reference: .github/scripts/compare-types/packages/firestore-pipelines/pipelines.d.ts (JS SDK). - * RN Firebase built types: packages/firestore/dist/typescript/lib/pipelines/*.d.ts - * - * Each entry must have a `name` (the export name) and a `reason` explaining - * why the difference exists. Any difference NOT listed here will cause CI to - * fail so that new drift is caught and deliberately acknowledged. - * - * Sections: - * nameMapping — exports that exist in both but under different names - * missingInRN — JS SDK pipeline exports absent from RN Firebase - * extraInRN — RN Firebase pipeline exports not in the JS SDK - * differentShape — same export name but differing signatures/members - */ - -import type { PackageConfig } from '../../src/types'; - - -const config: PackageConfig = { - nameMapping: {}, - missingInRN: [], - extraInRN: [], - differentShape: [], -}; - -export default config; diff --git a/.github/scripts/compare-types/packages/firestore-pipelines/pipelines.d.ts b/.github/scripts/compare-types/packages/firestore-pipelines/pipelines.d.ts deleted file mode 100644 index c133468fc5..0000000000 --- a/.github/scripts/compare-types/packages/firestore-pipelines/pipelines.d.ts +++ /dev/null @@ -1,7752 +0,0 @@ -import type { Bytes, DocumentData, DocumentReference, FieldPath, FieldValue, Firestore, FirestoreDataConverter, GeoPoint, PartialWithFieldValue, Primitive, Query, QueryDocumentSnapshot, SetOptions, SnapshotMetadata, SnapshotOptions, Timestamp, VectorValue, WithFieldValue } from './index'; -/** - * 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 { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; -/** - * @beta - * Creates an expression that computes the absolute value of a numeric value. - * - * @param expr - The expression to compute the absolute value of. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the absolute value of the numeric value. - */ -export declare function abs(expr: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that computes the absolute value of a numeric value. - * - * @param fieldName - The field to compute the absolute value of. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the absolute value of the numeric value. - */ -export declare function abs(fieldName: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that adds two expressions together. - * - * @example - * ```typescript - * // Add the value of the 'quantity' field and the 'reserve' field. - * add(field("quantity"), field("reserve")); - * ``` - * - * @param first - The first expression to add. - * @param second - The second expression or literal to add. - * @param others - Optional other expressions or literals to add. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the addition operation. - */ -export declare function add(first: Expression, second: Expression | unknown): FunctionExpression; -/** - * @beta - * - * Creates an expression that adds a field's value to an expression. - * - * @example - * ```typescript - * // Add the value of the 'quantity' field and the 'reserve' field. - * add("quantity", field("reserve")); - * ``` - * - * @param fieldName - The name of the field containing the value to add. - * @param second - The second expression or literal to add. - * @param others - Optional other expressions or literals to add. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the addition operation. - */ -export declare function add(fieldName: string, second: Expression | unknown): FunctionExpression; -/** - * @beta - * Options defining how an AddFieldsStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(addFields:1)}. - */ -export declare type AddFieldsStageOptions = StageOptions & { - /** - * @beta - * The fields to add to each document, specified as a {@link @firebase/firestore/pipelines#Selectable}. - * At least one field is required. - */ - fields: Selectable[]; -}; -/** - * @beta - * - * A class that represents an aggregate function. - */ -export declare class AggregateFunction { - private name; - private params; - exprType: ExpressionType; - /* Excluded from this release type: _methodName */ - constructor(name: string, params: Expression[]); - /* Excluded from this release type: _create */ - /** - * @beta - * Assigns an alias to this AggregateFunction. The alias specifies the name that - * the aggregated value will have in the output document. - * - * @example - * ```typescript - * // Calculate the average price of all items and assign it the alias "averagePrice". - * firestore.pipeline().collection("items") - * .aggregate(field("price").average().as("averagePrice")); - * ``` - * - * @param name - The alias to assign to this AggregateFunction. - * @returns A new {@link @firebase/firestore/pipelines#AliasedAggregate} that wraps this - * AggregateFunction and associates it with the provided alias. - */ - as(name: string): AliasedAggregate; -} -/** - * @beta - * Options defining how an AggregateStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(aggregate:1)}. - */ -export declare type AggregateStageOptions = StageOptions & { - /** - * @beta - * The {@link @firebase/firestore/pipelines#AliasedAggregate} values specifying aggregate operations to - * perform on the input documents. - */ - accumulators: AliasedAggregate[]; - /** - * @beta - * The {@link @firebase/firestore/pipelines#Selectable} expressions or field names to consider when determining - * distinct value combinations (groups), which will be aggregated over. - */ - groups?: Array; -}; -/** - * @beta - * - * An AggregateFunction with alias. - */ -export declare class AliasedAggregate { - readonly aggregate: AggregateFunction; - readonly alias: string; - constructor(aggregate: AggregateFunction, alias: string, _methodName: string | undefined); -} -/** - * @beta - */ -export declare class AliasedExpression implements Selectable { - readonly expr: Expression; - readonly alias: string; - exprType: ExpressionType; - selectable: true; - constructor(expr: Expression, alias: string, _methodName: string | undefined); -} -/** - * @beta - * - * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. - * - * @example - * ```typescript - * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND - * // the 'status' field is "active" - * const condition = and(greaterThan("age", 18), equal("city", "London"), equal("status", "active")); - * ``` - * - * @param first - The first filter condition. - * @param second - The second filter condition. - * @param more - Additional filter conditions to 'AND' together. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'AND' operation. - */ -export declare function and(first: BooleanExpression, second: BooleanExpression, ...more: BooleanExpression[]): BooleanExpression; -/** - * @beta - * - * Creates an expression that creates a Firestore array value from an input array. - * - * @example - * ```typescript - * // Create an array value from the input array and reference the 'baz' field value from the input document. - * array(['bar', Field.of('baz')]).as('foo'); - * ``` - * - * @param elements - The input array to evaluate in the expression. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the array function. - */ -export declare function array(elements: unknown[]): FunctionExpression; -/** - * @beta - * Creates an aggregation that collects all values of an expression across multiple stage - * inputs into an array. - * - * @remarks - * If the expression resolves to an absent value, it is converted to `null`. - * The order of elements in the output array is not stable and shouldn't be relied upon. - * - * @example - * ```typescript - * // Collect all tags from books into an array - * arrayAgg(field("tags")).as("allTags"); - * ``` - * - * @param expression - The expression to collect values from. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg' aggregation. - */ -export declare function arrayAgg(expression: Expression): AggregateFunction; -/** - * @beta - * Creates an aggregation that collects all values of a field across multiple stage inputs - * into an array. - * - * @remarks - * If the expression resolves to an absent value, it is converted to `null`. - * The order of elements in the output array is not stable and shouldn't be relied upon. - * - * @example - * ```typescript - * // Collect all tags from books into an array - * arrayAgg("tags").as("allTags"); - * ``` - * - * @param fieldName - The name of the field to collect values from. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg' aggregation. - */ -export declare function arrayAgg(fieldName: string): AggregateFunction; -/** - * @beta - * Creates an aggregation that collects all distinct values of an expression across multiple stage - * inputs into an array. - * - * @remarks - * If the expression resolves to an absent value, it is converted to `null`. - * The order of elements in the output array is not stable and shouldn't be relied upon. - * - * @example - * ```typescript - * // Collect all distinct tags from books into an array - * arrayAggDistinct(field("tags")).as("allDistinctTags"); - * ``` - * - * @param expression - The expression to collect values from. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg_distinct' aggregation. - */ -export declare function arrayAggDistinct(expression: Expression): AggregateFunction; -/** - * @beta - * Creates an aggregation that collects all distinct values of a field across multiple stage inputs - * into an array. - * - * @remarks - * If the expression resolves to an absent value, it is converted to `null`. - * The order of elements in the output array is not stable and shouldn't be relied upon. - * - * @example - * ```typescript - * // Collect all distinct tags from books into an array - * arrayAggDistinct("tags").as("allDistinctTags"); - * ``` - * - * @param fieldName - The name of the field to collect values from. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'array_agg_distinct' aggregation. - */ -export declare function arrayAggDistinct(fieldName: string): AggregateFunction; -/** - * @beta - * - * Creates an expression that concatenates an array expression with other arrays. - * - * @example - * ```typescript - * // Combine the 'items' array with two new item arrays - * arrayConcat(field("items"), [field("newItems"), field("otherItems")]); - * ``` - * - * @param firstArray - The first array expression to concatenate to. - * @param secondArray - The second array expression or array literal to concatenate to. - * @param otherArrays - Optional additional array expressions or array literals to concatenate. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated array. - */ -export declare function arrayConcat(firstArray: Expression, secondArray: Expression | unknown[], ...otherArrays: Array): FunctionExpression; -/** - * @beta - * - * Creates an expression that concatenates a field's array value with other arrays. - * - * @example - * ```typescript - * // Combine the 'items' array with two new item arrays - * arrayConcat("items", [field("newItems"), field("otherItems")]); - * ``` - * - * @param firstArrayField - The first array to concatenate to. - * @param secondArray - The second array expression or array literal to concatenate to. - * @param otherArrays - Optional additional array expressions or array literals to concatenate. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated array. - */ -export declare function arrayConcat(firstArrayField: string, secondArray: Expression | unknown[], ...otherArrays: Array): FunctionExpression; -/** - * @beta - * - * Creates an expression that checks if an array expression contains a specific element. - * - * @example - * ```typescript - * // Check if the 'colors' array contains the value of field 'selectedColor' - * arrayContains(field("colors"), field("selectedColor")); - * ``` - * - * @param array - The array expression to check. - * @param element - The element to search for in the array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison. - */ -export declare function arrayContains(array: Expression, element: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an array expression contains a specific element. - * - * @example - * ```typescript - * // Check if the 'colors' array contains "red" - * arrayContains(field("colors"), "red"); - * ``` - * - * @param array - The array expression to check. - * @param element - The element to search for in the array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison. - */ -export declare function arrayContains(array: Expression, element: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's array value contains a specific element. - * - * @example - * ```typescript - * // Check if the 'colors' array contains the value of field 'selectedColor' - * arrayContains("colors", field("selectedColor")); - * ``` - * - * @param fieldName - The field name to check. - * @param element - The element to search for in the array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison. - */ -export declare function arrayContains(fieldName: string, element: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's array value contains a specific value. - * - * @example - * ```typescript - * // Check if the 'colors' array contains "red" - * arrayContains("colors", "red"); - * ``` - * - * @param fieldName - The field name to check. - * @param element - The element to search for in the array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains' comparison. - */ -export declare function arrayContains(fieldName: string, element: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an array expression contains all the specified elements. - * - * @example - * ```typescript - * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" - * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); - * ``` - * - * @param array - The array expression to check. - * @param values - The elements to check for in the array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison. - */ -export declare function arrayContainsAll(array: Expression, values: Array): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's array value contains all the specified values or - * expressions. - * - * @example - * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" - * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); - * ``` - * - * @param fieldName - The field name to check. - * @param values - The elements to check for in the array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison. - */ -export declare function arrayContainsAll(fieldName: string, values: Array): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an array expression contains all the specified elements. - * - * @example - * ```typescript - * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" - * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); - * ``` - * - * @param array - The array expression to check. - * @param arrayExpression - The elements to check for in the array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison. - */ -export declare function arrayContainsAll(array: Expression, arrayExpression: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's array value contains all the specified values or - * expressions. - * - * @example - * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" - * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); - * ``` - * - * @param fieldName - The field name to check. - * @param arrayExpression - The elements to check for in the array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_all' comparison. - */ -export declare function arrayContainsAll(fieldName: string, arrayExpression: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an array expression contains any of the specified - * elements. - * - * @example - * ```typescript - * // Check if the 'categories' array contains either values from field "cate1" or "Science" - * arrayContainsAny(field("categories"), [field("cate1"), "Science"]); - * ``` - * - * @param array - The array expression to check. - * @param values - The elements to check for in the array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison. - */ -export declare function arrayContainsAny(array: Expression, values: Array): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's array value contains any of the specified - * elements. - * - * @example - * ```typescript - * // Check if the 'groups' array contains either the value from the 'userGroup' field - * // or the value "guest" - * arrayContainsAny("categories", [field("cate1"), "Science"]); - * ``` - * - * @param fieldName - The field name to check. - * @param values - The elements to check for in the array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison. - */ -export declare function arrayContainsAny(fieldName: string, values: Array): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an array expression contains any of the specified - * elements. - * - * @example - * ```typescript - * // Check if the 'categories' array contains either values from field "cate1" or "Science" - * arrayContainsAny(field("categories"), array([field("cate1"), "Science"])); - * ``` - * - * @param array - The array expression to check. - * @param values - An expression that evaluates to an array, whose elements to check for in the array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison. - */ -export declare function arrayContainsAny(array: Expression, values: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's array value contains any of the specified - * elements. - * - * @example - * ```typescript - * // Check if the 'groups' array contains either the value from the 'userGroup' field - * // or the value "guest" - * arrayContainsAny("categories", array([field("cate1"), "Science"])); - * ``` - * - * @param fieldName - The field name to check. - * @param values - An expression that evaluates to an array, whose elements to check for in the array field. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'array_contains_any' comparison. - */ -export declare function arrayContainsAny(fieldName: string, values: Expression): BooleanExpression; -/** - * @beta - * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. - * - * @example - * ```typescript - * // Return the value in the tags field array at index 1. - * arrayGet('tags', 1); - * ``` - * - * @param arrayField - The name of the array field. - * @param offset - The index of the element to return. - * @returns A new `Expression` representing the 'arrayGet' operation. - */ -export declare function arrayGet(arrayField: string, offset: number): FunctionExpression; -/** - * @beta - * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. - * - * @example - * ```typescript - * // Return the value in the tags field array at index specified by field - * // 'favoriteTag'. - * arrayGet('tags', field('favoriteTag')); - * ``` - * - * @param arrayField - The name of the array field. - * @param offsetExpr - An `Expression` evaluating to the index of the element to return. - * @returns A new `Expression` representing the 'arrayGet' operation. - */ -export declare function arrayGet(arrayField: string, offsetExpr: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. - * - * @example - * ```typescript - * // Return the value in the tags field array at index 1. - * arrayGet(field('tags'), 1); - * ``` - * - * @param arrayExpression - An `Expression` evaluating to an array. - * @param offset - The index of the element to return. - * @returns A new `Expression` representing the 'arrayGet' operation. - */ -export declare function arrayGet(arrayExpression: Expression, offset: number): FunctionExpression; -/** - * @beta - * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. - * - * @example - * ```typescript - * // Return the value in the tags field array at index specified by field - * // 'favoriteTag'. - * arrayGet(field('tags'), field('favoriteTag')); - * ``` - * - * @param arrayExpression - An `Expression` evaluating to an array. - * @param offsetExpr - An `Expression` evaluating to the index of the element to return. - * @returns A new `Expression` representing the 'arrayGet' operation. - */ -export declare function arrayGet(arrayExpression: Expression, offsetExpr: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that calculates the length of an array in a specified field. - * - * @example - * ```typescript - * // Get the number of items in field 'cart' - * arrayLength('cart'); - * ``` - * - * @param fieldName - The name of the field containing an array to calculate the length of. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array. - */ -export declare function arrayLength(fieldName: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that calculates the length of an array expression. - * - * @example - * ```typescript - * // Get the number of items in the 'cart' array - * arrayLength(field("cart")); - * ``` - * - * @param array - The array expression to calculate the length of. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array. - */ -export declare function arrayLength(array: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that computes the sum of the elements in an array. - * - * @example - * ```typescript - * // Compute the sum of the elements in the 'scores' field. - * arraySum("scores"); - * ``` - * - * @param fieldName - The name of the field to compute the sum of. - * @returns A new `Expression` representing the sum of the elements in the array. - */ -export declare function arraySum(fieldName: string): FunctionExpression; -/** - * @beta - * Creates an expression that computes the sum of the elements in an array. - * - * @example - * ```typescript - * // Compute the sum of the elements in the 'scores' field. - * arraySum(field("scores")); - * ``` - * - * @param expression - An expression evaluating to a numeric array, which the sum will be computed for. - * @returns A new `Expression` representing the sum of the elements in the array. - */ -export declare function arraySum(expression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in ascending order based on an expression. - * - * @example - * ```typescript - * // Sort documents by the 'name' field in lowercase in ascending order - * firestore.pipeline().collection("users") - * .sort(ascending(field("name").toLower())); - * ``` - * - * @param expr - The expression to create an ascending ordering for. - * @returns A new `Ordering` for ascending sorting. - */ -export declare function ascending(expr: Expression): Ordering; -/** - * @beta - * - * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in ascending order based on a field. - * - * @example - * ```typescript - * // Sort documents by the 'name' field in ascending order - * firestore.pipeline().collection("users") - * .sort(ascending("name")); - * ``` - * - * @param fieldName - The field to create an ascending ordering for. - * @returns A new `Ordering` for ascending sorting. - */ -export declare function ascending(fieldName: string): Ordering; -/* Excluded from this release type: AuthTokenFactory */ -/** - * @beta - * - * Creates an aggregation that calculates the average (mean) of values from an expression across - * multiple stage inputs. - * - * @example - * ```typescript - * // Calculate the average age of users - * average(field("age")).as("averageAge"); - * ``` - * - * @param expression - The expression representing the values to average. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'average' aggregation. - */ -export declare function average(expression: Expression): AggregateFunction; -/** - * @beta - * - * Creates an aggregation that calculates the average (mean) of a field's values across multiple - * stage inputs. - * - * @example - * ```typescript - * // Calculate the average age of users - * average("age").as("averageAge"); - * ``` - * - * @param fieldName - The name of the field containing numeric values to average. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'average' aggregation. - */ -export declare function average(fieldName: string): AggregateFunction; -/** - * @beta - * - * An interface that represents a filter condition. - */ -export declare abstract class BooleanExpression extends Expression { - /** - * @beta - * Creates an aggregation that finds the count of input documents satisfying - * this boolean expression. - * - * @example - * ```typescript - * // Find the count of documents with a score greater than 90 - * field("score").greaterThan(90).countIf().as("highestScore"); - * ``` - * - * @returns A new `AggregateFunction` representing the 'countIf' aggregation. - */ - countIf(): AggregateFunction; - /** - * @beta - * Creates an expression that negates this boolean expression. - * - * @example - * ```typescript - * // Find documents where the 'tags' field does not contain 'completed' - * field("tags").arrayContains("completed").not(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the negated filter condition. - */ - not(): BooleanExpression; - /** - * @beta - * Creates a conditional expression that evaluates to the 'then' expression - * if `this` expression evaluates to `true`, - * or evaluates to the 'else' expression if `this` expressions evaluates `false`. - * - * @example - * ```typescript - * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". - * field("age").greaterThanOrEqual(18).conditional(constant("Adult"), constant("Minor")); - * ``` - * - * @param thenExpr - The expression to evaluate if the condition is true. - * @param elseExpr - The expression to evaluate if the condition is false. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the conditional expression. - */ - conditional(thenExpr: Expression, elseExpr: Expression): FunctionExpression; - /** - * @beta - * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of this expression. - * - * @example - * ```typescript - * // Create an expression that protects against a divide by zero error - * // but always returns a boolean expression. - * constant(50).divide('length').gt(1).ifError(constant(false)); - * ``` - * - * @param catchValue - The value that will be returned if this expression - * produces an error. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation. - */ - ifError(catchValue: BooleanExpression): BooleanExpression; - /** - * @beta - * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of this expression. - * - * @example - * ```typescript - * // Create an expression that protects against a divide by zero error - * // but always returns a boolean expression. - * constant(50).divide('length').gt(1).ifError(false); - * ``` - * - * @param catchValue - The value that will be returned if this expression - * produces an error. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation. - */ - ifError(catchValue: boolean): BooleanExpression; - /** - * @beta - * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of this expression. - * - * @example - * ```typescript - * // Create an expression that protects against a divide by zero error. - * constant(50).divide('length').gt(1).ifError(constant(0)); - * ``` - * - * @param catchValue - The value that will be returned if this expression - * produces an error. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation. - */ - ifError(catchValue: Expression): FunctionExpression; - /** - * @beta - * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of this expression. - * - * @example - * ```typescript - * // Create an expression that protects against a divide by zero error. - * constant(50).divide('length').gt(1).ifError(0); - * ``` - * - * @param catchValue - The value that will be returned if this expression - * produces an error. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation. - */ - ifError(catchValue: unknown): FunctionExpression; -} -/** - * @beta - * - * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob. - * - * @example - * ```typescript - * // Calculate the length of the 'myString' field in bytes. - * byteLength(field("myString")); - * ``` - * - * @param expr - The expression representing the string. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string in bytes. - */ -export declare function byteLength(expr: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob. - * - * @example - * ```typescript - * // Calculate the length of the 'myString' field in bytes. - * byteLength("myString"); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string in bytes. - */ -export declare function byteLength(fieldName: string): FunctionExpression; -/* Excluded from this release type: ByteString */ -/** - * @beta - * Creates an expression that computes the ceiling of a numeric value. - * - * @example - * ```typescript - * // Compute the ceiling of the 'price' field. - * ceil("price"); - * ``` - * - * @param fieldName - The name of the field to compute the ceiling of. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ceiling of the numeric value. - */ -export declare function ceil(fieldName: string): FunctionExpression; -/** - * @beta - * Creates an expression that computes the ceiling of a numeric value. - * - * @example - * ```typescript - * // Compute the ceiling of the 'price' field. - * ceil(field("price")); - * ``` - * - * @param expression - An expression evaluating to a numeric value, which the ceiling will be computed for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ceiling of the numeric value. - */ -export declare function ceil(expression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that calculates the character length of a string field in UTF8. - * - * @example - * ```typescript - * // Get the character length of the 'name' field in UTF-8. - * strLength("name"); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string. - */ -export declare function charLength(fieldName: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that calculates the character length of a string expression in UTF-8. - * - * @example - * ```typescript - * // Get the character length of the 'name' field in UTF-8. - * strLength(field("name")); - * ``` - * - * @param stringExpression - The expression representing the string to calculate the length of. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string. - */ -export declare function charLength(stringExpression: Expression): FunctionExpression; -/** - * @beta - * Defines the configuration options for a CollectionGroupStage within a pipeline. - * This type extends {@link @firebase/firestore/pipelines#StageOptions} and provides specific settings for how a collection group - * is identified and processed during pipeline execution. - * - * See {@link @firebase/firestore/pipelines#PipelineSource.(collectionGroup:1)} to create a collection group stage. - */ -export declare type CollectionGroupStageOptions = StageOptions & { - /** - * @beta - * ID of the collection group to use as the Pipeline source. - */ - collectionId: string; - /** - * @beta - * Specifies the name of an index to be used for a query, overriding the query optimizer's default choice. - * This can be useful for performance tuning in specific scenarios where the default index selection - * does not yield optimal performance. - * - * @remarks This property is optional. When provided, it should be the exact name of the index to force. - */ - forceIndex?: string; -}; -/** - * @beta - * Creates an expression that returns the collection ID from a path. - * - * @example - * ```typescript - * // Get the collection ID from a path. - * collectionId("__name__"); - * ``` - * - * @param fieldName - The name of the field to get the collection ID from. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the collectionId operation. - */ -export declare function collectionId(fieldName: string): FunctionExpression; -/** - * @beta - * Creates an expression that returns the collection ID from a path. - * - * @example - * ```typescript - * // Get the collection ID from a path. - * collectionId(field("__name__")); - * ``` - * - * @param expression - An expression evaluating to a path, which the collection ID will be extracted from. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the collectionId operation. - */ -export declare function collectionId(expression: Expression): FunctionExpression; -/** - * @beta - * Options defining how a CollectionStage is evaluated. See {@link @firebase/firestore/pipelines#PipelineSource.(collection:1)}. - */ -export declare type CollectionStageOptions = StageOptions & { - /** - * @beta - * Name or reference to the collection that will be used as the Pipeline source. - */ - collection: string | Query; - /** - * @beta - * Specifies the name of an index to be used for a query, overriding the query optimizer's default choice. - * This can be useful for performance tuning in specific scenarios where the default index selection - * does not yield optimal performance. - * - * @remarks This property is optional. When provided, it should be the exact name of the index to force. - */ - forceIndex?: string; -}; -/** - * @beta - * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed. - * - * @example - * ```typescript - * // Concatenate the 'firstName' and 'lastName' fields with a space in between. - * concat(field("firstName"), " ", field("lastName")) - * ``` - * - * @param first - The first expressions to concatenate. - * @param second - The second literal or expression to concatenate. - * @param others - Additional literals or expressions to concatenate. - * @returns A new `Expression` representing the concatenation. - */ -export declare function concat(first: Expression, second: Expression | unknown, ...others: Array): FunctionExpression; -/** - * @beta - * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed. - * - * @example - * ```typescript - * // Concatenate a field with a literal string. - * concat(field("firstName"), "Doe") - * ``` - * - * @param fieldName - The name of a field to concatenate. - * @param second - The second literal or expression to concatenate. - * @param others - Additional literal or expressions to concatenate. - * @returns A new `Expression` representing the concatenation. - */ -export declare function concat(fieldName: string, second: Expression | unknown, ...others: Array): FunctionExpression; -/** - * @beta - * - * Creates a conditional expression that evaluates to a 'then' expression if a condition is true - * and an 'else' expression if the condition is false. - * - * @example - * ```typescript - * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". - * conditional( - * greaterThan("age", 18), constant("Adult"), constant("Minor")); - * ``` - * - * @param condition - The condition to evaluate. - * @param thenExpr - The expression to evaluate if the condition is true. - * @param elseExpr - The expression to evaluate if the condition is false. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the conditional expression. - */ -export declare function conditional(condition: BooleanExpression, thenExpr: Expression, elseExpr: Expression): FunctionExpression; -/** - * @beta - * Creates a `Constant` instance for a number value. - * - * @param value - The number value. - * @returns A new `Constant` instance. - */ -export declare function constant(value: number): Expression; -/** - * @beta - * Creates a `Constant` instance for a string value. - * - * @param value - The string value. - * @returns A new `Constant` instance. - */ -export declare function constant(value: string): Expression; -/** - * @beta - * Creates a `BooleanExpression` instance for a boolean value. - * - * @param value - The boolean value. - * @returns A new `Constant` instance. - */ -export declare function constant(value: boolean): BooleanExpression; -/** - * @beta - * Creates a `Constant` instance for a null value. - * - * @param value - The null value. - * @returns A new `Constant` instance. - */ -export declare function constant(value: null): Expression; -/** - * @beta - * Creates a `Constant` instance for a GeoPoint value. - * - * @param value - The GeoPoint value. - * @returns A new `Constant` instance. - */ -export declare function constant(value: GeoPoint): Expression; -/** - * @beta - * Creates a `Constant` instance for a Timestamp value. - * - * @param value - The Timestamp value. - * @returns A new `Constant` instance. - */ -export declare function constant(value: Timestamp): Expression; -/** - * @beta - * Creates a `Constant` instance for a Date value. - * - * @param value - The Date value. - * @returns A new `Constant` instance. - */ -export declare function constant(value: Date): Expression; -/** - * @beta - * Creates a `Constant` instance for a Bytes value. - * - * @param value - The Bytes value. - * @returns A new `Constant` instance. - */ -export declare function constant(value: Bytes): Expression; -/** - * @beta - * Creates a `Constant` instance for a DocumentReference value. - * - * @param value - The DocumentReference value. - * @returns A new `Constant` instance. - */ -export declare function constant(value: DocumentReference): Expression; -/* Excluded declaration from this release type: constant */ -/** - * @beta - * Creates a `Constant` instance for a VectorValue value. - * - * @param value - The VectorValue value. - * @returns A new `Constant` instance. - */ -export declare function constant(value: VectorValue): Expression; -/** - * @beta - * - * Calculates the Cosine distance between a field's vector value and a literal vector value. - * - * @example - * ```typescript - * // Calculate the Cosine distance between the 'location' field and a target location - * cosineDistance("location", [37.7749, -122.4194]); - * ``` - * - * @param fieldName - The name of the field containing the first vector. - * @param vector - The other vector (as an array of doubles) or {@link VectorValue} to compare against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Cosine distance between the two vectors. - */ -export declare function cosineDistance(fieldName: string, vector: number[] | VectorValue): FunctionExpression; -/** - * @beta - * - * Calculates the Cosine distance between a field's vector value and a vector expression. - * - * @example - * ```typescript - * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * cosineDistance("userVector", field("itemVector")); - * ``` - * - * @param fieldName - The name of the field containing the first vector. - * @param vectorExpression - The other vector (represented as an `Expression`) to compare against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the cosine distance between the two vectors. - */ -export declare function cosineDistance(fieldName: string, vectorExpression: Expression): FunctionExpression; -/** - * @beta - * - * Calculates the Cosine distance between a vector expression and a vector literal. - * - * @example - * ```typescript - * // Calculate the cosine distance between the 'location' field and a target location - * cosineDistance(field("location"), [37.7749, -122.4194]); - * ``` - * - * @param vectorExpression - The first vector (represented as an `Expression`) to compare against. - * @param vector - The other vector (as an array of doubles or VectorValue) to compare against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the cosine distance between the two vectors. - */ -export declare function cosineDistance(vectorExpression: Expression, vector: number[] | VectorValue): FunctionExpression; -/** - * @beta - * - * Calculates the Cosine distance between two vector expressions. - * - * @example - * ```typescript - * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * cosineDistance(field("userVector"), field("itemVector")); - * ``` - * - * @param vectorExpression - The first vector (represented as an `Expression`) to compare against. - * @param otherVectorExpression - The other vector (represented as an `Expression`) to compare against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the cosine distance between the two vectors. - */ -export declare function cosineDistance(vectorExpression: Expression, otherVectorExpression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an aggregation that counts the number of stage inputs with valid evaluations of the - * provided expression. - * - * @example - * ```typescript - * // Count the number of items where the price is greater than 10 - * count(field("price").greaterThan(10)).as("expensiveItemCount"); - * ``` - * - * @param expression - The expression to count. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'count' aggregation. - */ -export declare function count(expression: Expression): AggregateFunction; -/** - * @beta - * Creates an aggregation that counts the number of stage inputs where the input field exists. - * - * @example - * ```typescript - * // Count the total number of products - * count("productId").as("totalProducts"); - * ``` - * - * @param fieldName - The name of the field to count. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'count' aggregation. - */ -export declare function count(fieldName: string): AggregateFunction; -/** - * @beta - * - * Creates an aggregation that counts the total number of stage inputs. - * - * @example - * ```typescript - * // Count the total number of input documents - * countAll().as("totalDocument"); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'countAll' aggregation. - */ -export declare function countAll(): AggregateFunction; -/** - * @beta - * Creates an aggregation that counts the number of distinct values of a field. - * - * @param expr - The expression or field to count distinct values of. - * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation. - */ -export declare function countDistinct(expr: Expression | string): AggregateFunction; -/** - * @beta - * Creates an aggregation that counts the number of stage inputs where the provided - * boolean expression evaluates to true. - * - * @example - * ```typescript - * // Count the number of documents where 'is_active' field equals true - * countIf(field("is_active").equal(true)).as("numActiveDocuments"); - * ``` - * - * @param booleanExpr - The boolean expression to evaluate on each input. - * @returns A new `AggregateFunction` representing the 'countIf' aggregation. - */ -export declare function countIf(booleanExpr: BooleanExpression): AggregateFunction; -/** - * @beta - * - * Creates an expression that evaluates to the current server timestamp. - * - * @example - * ```typescript - * // Get the current server timestamp - * currentTimestamp() - * ``` - * - * @returns A new Expression representing the current server timestamp. - */ -export declare function currentTimestamp(): FunctionExpression; -/** - * @beta - * Options defining how a DatabaseStage is evaluated. See {@link @firebase/firestore/pipelines#PipelineSource.(database:1)}. - */ -export declare type DatabaseStageOptions = StageOptions & {}; -/** - * @beta - * - * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in descending order based on an expression. - * - * @example - * ```typescript - * // Sort documents by the 'name' field in lowercase in descending order - * firestore.pipeline().collection("users") - * .sort(descending(field("name").toLower())); - * ``` - * - * @param expr - The expression to create a descending ordering for. - * @returns A new `Ordering` for descending sorting. - */ -export declare function descending(expr: Expression): Ordering; -/** - * @beta - * - * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in descending order based on a field. - * - * @example - * ```typescript - * // Sort documents by the 'name' field in descending order - * firestore.pipeline().collection("users") - * .sort(descending("name")); - * ``` - * - * @param fieldName - The field to create a descending ordering for. - * @returns A new `Ordering` for descending sorting. - */ -export declare function descending(fieldName: string): Ordering; -/** - * @beta - * Options defining how a DistinctStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(distinct:1)}. - */ -export declare type DistinctStageOptions = StageOptions & { - /** - * @beta - * The {@link @firebase/firestore/pipelines#Selectable} expressions or field names to consider when determining - * distinct value combinations (groups). - */ - groups: Array; -}; -/** - * @beta - * - * Creates an expression that divides two expressions. - * - * @example - * ```typescript - * // Divide the 'total' field by the 'count' field - * divide(field("total"), field("count")); - * ``` - * - * @param left - The expression to be divided. - * @param right - The expression to divide by. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation. - */ -export declare function divide(left: Expression, right: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that divides an expression by a constant value. - * - * @example - * ```typescript - * // Divide the 'value' field by 10 - * divide(field("value"), 10); - * ``` - * - * @param expression - The expression to be divided. - * @param value - The constant value to divide by. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation. - */ -export declare function divide(expression: Expression, value: unknown): FunctionExpression; -/** - * @beta - * - * Creates an expression that divides a field's value by an expression. - * - * @example - * ```typescript - * // Divide the 'total' field by the 'count' field - * divide("total", field("count")); - * ``` - * - * @param fieldName - The field name to be divided. - * @param expressions - The expression to divide by. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation. - */ -export declare function divide(fieldName: string, expressions: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that divides a field's value by a constant value. - * - * @example - * ```typescript - * // Divide the 'value' field by 10 - * divide("value", 10); - * ``` - * - * @param fieldName - The field name to be divided. - * @param value - The constant value to divide by. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the division operation. - */ -export declare function divide(fieldName: string, value: unknown): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns the document ID from a path. - * - * @example - * ```typescript - * // Get the document ID from a path. - * documentId(myDocumentReference); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the documentId operation. - */ -export declare function documentId(documentPath: string | DocumentReference): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns the document ID from a path. - * - * @example - * ```typescript - * // Get the document ID from a path. - * documentId(field("__path__")); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the documentId operation. - */ -export declare function documentId(documentPathExpr: Expression): FunctionExpression; -/** - * @beta - * Options defining how a DocumentsStage is evaluated. See {@link @firebase/firestore/pipelines#PipelineSource.(documents:1)}. - */ -export declare type DocumentsStageOptions = StageOptions & { - /** - * @beta - * An array of paths and DocumentReferences specifying the individual documents that will be the source of this pipeline. - * The converters for these DocumentReferences will be ignored and not have an effect on this pipeline. - * There must be at least one document specified in the array. - */ - docs: Array; -}; -/** - * @beta - * - * Calculates the dot product between a field's vector value and a double array. - * - * @example - * ```typescript - * // Calculate the dot product distance between a feature vector and a target vector - * dotProduct("features", [0.5, 0.8, 0.2]); - * ``` - * - * @param fieldName - The name of the field containing the first vector. - * @param vector - The other vector (as an array of doubles or VectorValue) to calculate with. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors. - */ -export declare function dotProduct(fieldName: string, vector: number[] | VectorValue): FunctionExpression; -/** - * @beta - * - * Calculates the dot product between a field's vector value and a vector expression. - * - * @example - * ```typescript - * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' - * dotProduct("docVector1", field("docVector2")); - * ``` - * - * @param fieldName - The name of the field containing the first vector. - * @param vectorExpression - The other vector (represented as an `Expression`) to calculate with. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors. - */ -export declare function dotProduct(fieldName: string, vectorExpression: Expression): FunctionExpression; -/** - * @beta - * - * Calculates the dot product between a vector expression and a double array. - * - * @example - * ```typescript - * // Calculate the dot product between a feature vector and a target vector - * dotProduct(field("features"), [0.5, 0.8, 0.2]); - * ``` - * - * @param vectorExpression - The first vector (represented as an `Expression`) to calculate with. - * @param vector - The other vector (as an array of doubles or VectorValue) to calculate with. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors. - */ -export declare function dotProduct(vectorExpression: Expression, vector: number[] | VectorValue): FunctionExpression; -/** - * @beta - * - * Calculates the dot product between two vector expressions. - * - * @example - * ```typescript - * // Calculate the dot product between two document vectors: 'docVector1' and 'docVector2' - * dotProduct(field("docVector1"), field("docVector2")); - * ``` - * - * @param vectorExpression - The first vector (represented as an `Expression`) to calculate with. - * @param otherVectorExpression - The other vector (represented as an `Expression`) to calculate with. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the dot product between the two vectors. - */ -export declare function dotProduct(vectorExpression: Expression, otherVectorExpression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value ends with a given postfix. - * - * @example - * ```typescript - * // Check if the 'filename' field ends with ".txt" - * endsWith("filename", ".txt"); - * ``` - * - * @param fieldName - The field name to check. - * @param suffix - The postfix to check for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison. - */ -export declare function endsWith(fieldName: string, suffix: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value ends with a given postfix. - * - * @example - * ```typescript - * // Check if the 'url' field ends with the value of the 'extension' field - * endsWith("url", field("extension")); - * ``` - * - * @param fieldName - The field name to check. - * @param suffix - The expression representing the postfix. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison. - */ -export declare function endsWith(fieldName: string, suffix: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string expression ends with a given postfix. - * - * @example - * ```typescript - * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." - * endsWith(field("fullName"), "Jr."); - * ``` - * - * @param stringExpression - The expression to check. - * @param suffix - The postfix to check for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison. - */ -export declare function endsWith(stringExpression: Expression, suffix: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string expression ends with a given postfix. - * - * @example - * ```typescript - * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." - * endsWith(field("fullName"), constant("Jr.")); - * ``` - * - * @param stringExpression - The expression to check. - * @param suffix - The postfix to check for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ends with' comparison. - */ -export declare function endsWith(stringExpression: Expression, suffix: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if two expressions are equal. - * - * @example - * ```typescript - * // Check if the 'age' field is equal to an expression - * equal(field("age"), field("minAge").add(10)); - * ``` - * - * @param left - The first expression to compare. - * @param right - The second expression to compare. - * @returns A new `Expression` representing the equality comparison. - */ -export declare function equal(left: Expression, right: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an expression is equal to a constant value. - * - * @example - * ```typescript - * // Check if the 'age' field is equal to 21 - * equal(field("age"), 21); - * ``` - * - * @param expression - The expression to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the equality comparison. - */ -export declare function equal(expression: Expression, value: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is equal to an expression. - * - * @example - * ```typescript - * // Check if the 'age' field is equal to the 'limit' field - * equal("age", field("limit")); - * ``` - * - * @param fieldName - The field name to compare. - * @param expression - The expression to compare to. - * @returns A new `Expression` representing the equality comparison. - */ -export declare function equal(fieldName: string, expression: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is equal to a constant value. - * - * @example - * ```typescript - * // Check if the 'city' field is equal to string constant "London" - * equal("city", "London"); - * ``` - * - * @param fieldName - The field name to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the equality comparison. - */ -export declare function equal(fieldName: string, value: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or - * expressions. - * - * @example - * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * equalAny(field("category"), [constant("Electronics"), field("primaryType")]); - * ``` - * - * @param expression - The expression whose results to compare. - * @param values - The values to check against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison. - */ -export declare function equalAny(expression: Expression, values: Array): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an expression is equal to any of the provided values. - * - * @example - * ```typescript - * // Check if the 'category' field is set to a value in the disabledCategories field - * equalAny(field("category"), field('disabledCategories')); - * ``` - * - * @param expression - The expression whose results to compare. - * @param arrayExpression - An expression that evaluates to an array, whose elements to check for equality to the input. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison. - */ -export declare function equalAny(expression: Expression, arrayExpression: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is equal to any of the provided values or - * expressions. - * - * @example - * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * equalAny("category", [constant("Electronics"), field("primaryType")]); - * ``` - * - * @param fieldName - The field to compare. - * @param values - The values to check against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison. - */ -export declare function equalAny(fieldName: string, values: Array): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is equal to any of the provided values or - * expressions. - * - * @example - * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * equalAny("category", ["Electronics", field("primaryType")]); - * ``` - * - * @param fieldName - The field to compare. - * @param arrayExpression - An expression that evaluates to an array, whose elements to check for equality to the input field. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'IN' comparison. - */ -export declare function equalAny(fieldName: string, arrayExpression: Expression): BooleanExpression; -/** - * @beta - * - * Calculates the Euclidean distance between a field's vector value and a double array. - * - * @example - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * euclideanDistance("location", [37.7749, -122.4194]); - * ``` - * - * @param fieldName - The name of the field containing the first vector. - * @param vector - The other vector (as an array of doubles or VectorValue) to compare against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors. - */ -export declare function euclideanDistance(fieldName: string, vector: number[] | VectorValue): FunctionExpression; -/** - * @beta - * - * Calculates the Euclidean distance between a field's vector value and a vector expression. - * - * @example - * ```typescript - * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' - * euclideanDistance("pointA", field("pointB")); - * ``` - * - * @param fieldName - The name of the field containing the first vector. - * @param vectorExpression - The other vector (represented as an `Expression`) to compare against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors. - */ -export declare function euclideanDistance(fieldName: string, vectorExpression: Expression): FunctionExpression; -/** - * @beta - * - * Calculates the Euclidean distance between a vector expression and a double array. - * - * @example - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * - * euclideanDistance(field("location"), [37.7749, -122.4194]); - * ``` - * - * @param vectorExpression - The first vector (represented as an `Expression`) to compare against. - * @param vector - The other vector (as an array of doubles or VectorValue) to compare against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors. - */ -export declare function euclideanDistance(vectorExpression: Expression, vector: number[] | VectorValue): FunctionExpression; -/** - * @beta - * - * Calculates the Euclidean distance between two vector expressions. - * - * @example - * ```typescript - * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' - * euclideanDistance(field("pointA"), field("pointB")); - * ``` - * - * @param vectorExpression - The first vector (represented as an `Expression`) to compare against. - * @param otherVectorExpression - The other vector (represented as an `Expression`) to compare against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the Euclidean distance between the two vectors. - */ -export declare function euclideanDistance(vectorExpression: Expression, otherVectorExpression: Expression): FunctionExpression; -/** - * @beta - * Executes a pipeline and returns a Promise to represent the asynchronous operation. - * - * The returned Promise can be used to track the progress of the pipeline execution - * and retrieve the results (or handle any errors) asynchronously. - * - * The pipeline results are returned as a {@link @firebase/firestore/pipelines#PipelineSnapshot} that contains - * a list of {@link @firebase/firestore/pipelines#PipelineResult} objects. Each {@link @firebase/firestore/pipelines#PipelineResult} typically - * represents a single key/value map that has passed through all the - * stages of the pipeline, however this might differ depending on the stages involved in the - * pipeline. For example: - * - *
    - *
  • If there are no stages or only transformation stages, each {@link @firebase/firestore/pipelines#PipelineResult} - * represents a single document.
  • - *
  • If there is an aggregation, only a single {@link @firebase/firestore/pipelines#PipelineResult} is returned, - * representing the aggregated results over the entire dataset .
  • - *
  • If there is an aggregation stage with grouping, each {@link @firebase/firestore/pipelines#PipelineResult} represents a - * distinct group and its associated aggregated values.
  • - *
- * - * @example - * ```typescript - * const snapshot: PipelineSnapshot = await execute(firestore.pipeline().collection("books") - * .where(gt(field("rating"), 4.5)) - * .select("title", "author", "rating")); - * - * const results: PipelineResults = snapshot.results; - * ``` - * - * @param pipeline - The pipeline to execute. - * @returns A Promise representing the asynchronous pipeline execution. - */ -export declare function execute(pipeline: Pipeline): Promise; -/** - * @beta - * Executes a pipeline and returns a Promise to represent the asynchronous operation. - * - * The returned Promise can be used to track the progress of the pipeline execution - * and retrieve the results (or handle any errors) asynchronously. - * - * The pipeline results are returned as a {@link @firebase/firestore/pipelines#PipelineSnapshot} that contains - * a list of {@link @firebase/firestore/pipelines#PipelineResult} objects. Each {@link @firebase/firestore/pipelines#PipelineResult} typically - * represents a single key/value map that has passed through all the - * stages of the pipeline, however this might differ depending on the stages involved in the - * pipeline. For example: - * - *
    - *
  • If there are no stages or only transformation stages, each {@link @firebase/firestore/pipelines#PipelineResult} - * represents a single document.
  • - *
  • If there is an aggregation, only a single {@link @firebase/firestore/pipelines#PipelineResult} is returned, - * representing the aggregated results over the entire dataset .
  • - *
  • If there is an aggregation stage with grouping, each {@link @firebase/firestore/pipelines#PipelineResult} represents a - * distinct group and its associated aggregated values.
  • - *
- * - * @example - * ```typescript - * const snapshot: PipelineSnapshot = await execute(firestore.pipeline().collection("books") - * .where(gt(field("rating"), 4.5)) - * .select("title", "author", "rating")); - * - * const results: PipelineResults = snapshot.results; - * ``` - * - * @param options - Specifies the pipeline to execute and other options for execute. - * @returns A Promise representing the asynchronous pipeline execution. - */ -export declare function execute(options: PipelineExecuteOptions): Promise; -/** - * @beta - * - * Creates an expression that checks if a field exists. - * - * @example - * ```typescript - * // Check if the document has a field named "phoneNumber" - * exists(field("phoneNumber")); - * ``` - * - * @param value - An expression evaluates to the name of the field to check. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'exists' check. - */ -export declare function exists(value: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field exists. - * - * @example - * ```typescript - * // Check if the document has a field named "phoneNumber" - * exists("phoneNumber"); - * ``` - * - * @param fieldName - The field name to check. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'exists' check. - */ -export declare function exists(fieldName: string): BooleanExpression; -/** - * @beta - * Creates an expression that computes e to the power of the expression's result. - * - * @example - * ```typescript - * // Compute e to the power of 2. - * exp(constant(2)); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the exp of the numeric value. - */ -export declare function exp(expression: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that computes e to the power of the expression's result. - * - * @example - * ```typescript - * // Compute e to the power of the 'value' field. - * exp('value'); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the exp of the numeric value. - */ -export declare function exp(fieldName: string): FunctionExpression; -/** - * @beta - * - * Represents an expression that can be evaluated to a value within the execution of a {@link - * @firebase/firestore/pipelines#Pipeline}. - * - * Expressions are the building blocks for creating complex queries and transformations in - * Firestore pipelines. They can represent: - * - * - **Field references:** Access values from document fields. - * - **Literals:** Represent constant values (strings, numbers, booleans). - * - **Function calls:** Apply functions to one or more expressions. - * - * The `Expression` class provides a fluent API for building expressions. You can chain together - * method calls to create complex expressions. - */ -export declare abstract class Expression { - abstract readonly expressionType: ExpressionType; - /* Excluded from this release type: _readUserData */ - /** - * Creates an expression that adds this expression to another expression. - * - * @example - * ```typescript - * // Add the value of the 'quantity' field and the 'reserve' field. - * field("quantity").add(field("reserve")); - * ``` - * - * @param second - The expression or literal to add to this expression. - * @param others - Optional additional expressions or literals to add to this expression. - * @returns A new `Expression` representing the addition operation. - */ - add(second: Expression | unknown): FunctionExpression; - /** - * @beta - * Wraps the expression in a [BooleanExpression]. - * - * @returns A [BooleanExpression] representing the same expression. - */ - asBoolean(): BooleanExpression; - /** - * @beta - * Creates an expression that subtracts another expression from this expression. - * - * @example - * ```typescript - * // Subtract the 'discount' field from the 'price' field - * field("price").subtract(field("discount")); - * ``` - * - * @param subtrahend - The expression to subtract from this expression. - * @returns A new `Expression` representing the subtraction operation. - */ - subtract(subtrahend: Expression): FunctionExpression; - /** - * @beta - * Creates an expression that subtracts a constant value from this expression. - * - * @example - * ```typescript - * // Subtract 20 from the value of the 'total' field - * field("total").subtract(20); - * ``` - * - * @param subtrahend - The constant value to subtract. - * @returns A new `Expression` representing the subtraction operation. - */ - subtract(subtrahend: number): FunctionExpression; - /** - * @beta - * Creates an expression that multiplies this expression by another expression. - * - * @example - * ```typescript - * // Multiply the 'quantity' field by the 'price' field - * field("quantity").multiply(field("price")); - * ``` - * - * @param second - The second expression or literal to multiply by. - * @param others - Optional additional expressions or literals to multiply by. - * @returns A new `Expression` representing the multiplication operation. - */ - multiply(second: Expression | number): FunctionExpression; - /** - * @beta - * Creates an expression that divides this expression by another expression. - * - * @example - * ```typescript - * // Divide the 'total' field by the 'count' field - * field("total").divide(field("count")); - * ``` - * - * @param divisor - The expression to divide by. - * @returns A new `Expression` representing the division operation. - */ - divide(divisor: Expression): FunctionExpression; - /** - * @beta - * Creates an expression that divides this expression by a constant value. - * - * @example - * ```typescript - * // Divide the 'value' field by 10 - * field("value").divide(10); - * ``` - * - * @param divisor - The constant value to divide by. - * @returns A new `Expression` representing the division operation. - */ - divide(divisor: number): FunctionExpression; - /** - * @beta - * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression. - * - * @example - * ```typescript - * // Calculate the remainder of dividing the 'value' field by the 'divisor' field - * field("value").mod(field("divisor")); - * ``` - * - * @param expression - The expression to divide by. - * @returns A new `Expression` representing the modulo operation. - */ - mod(expression: Expression): FunctionExpression; - /** - * @beta - * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. - * - * @example - * ```typescript - * // Calculate the remainder of dividing the 'value' field by 10 - * field("value").mod(10); - * ``` - * - * @param value - The constant value to divide by. - * @returns A new `Expression` representing the modulo operation. - */ - mod(value: number): FunctionExpression; - /** - * @beta - * Creates an expression that checks if this expression is equal to another expression. - * - * @example - * ```typescript - * // Check if the 'age' field is equal to 21 - * field("age").equal(21); - * ``` - * - * @param expression - The expression to compare for equality. - * @returns A new `Expression` representing the equality comparison. - */ - equal(expression: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is equal to a constant value. - * - * @example - * ```typescript - * // Check if the 'city' field is equal to "London" - * field("city").equal("London"); - * ``` - * - * @param value - The constant value to compare for equality. - * @returns A new `Expression` representing the equality comparison. - */ - equal(value: unknown): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is not equal to another expression. - * - * @example - * ```typescript - * // Check if the 'status' field is not equal to "completed" - * field("status").notEqual("completed"); - * ``` - * - * @param expression - The expression to compare for inequality. - * @returns A new `Expression` representing the inequality comparison. - */ - notEqual(expression: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is not equal to a constant value. - * - * @example - * ```typescript - * // Check if the 'country' field is not equal to "USA" - * field("country").notEqual("USA"); - * ``` - * - * @param value - The constant value to compare for inequality. - * @returns A new `Expression` representing the inequality comparison. - */ - notEqual(value: unknown): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is less than another expression. - * - * @example - * ```typescript - * // Check if the 'age' field is less than 'limit' - * field("age").lessThan(field('limit')); - * ``` - * - * @param experession - The expression to compare for less than. - * @returns A new `Expression` representing the less than comparison. - */ - lessThan(experession: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is less than a constant value. - * - * @example - * ```typescript - * // Check if the 'price' field is less than 50 - * field("price").lessThan(50); - * ``` - * - * @param value - The constant value to compare for less than. - * @returns A new `Expression` representing the less than comparison. - */ - lessThan(value: unknown): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is less than or equal to another - * expression. - * - * @example - * ```typescript - * // Check if the 'quantity' field is less than or equal to 20 - * field("quantity").lessThan(constant(20)); - * ``` - * - * @param expression - The expression to compare for less than or equal to. - * @returns A new `Expression` representing the less than or equal to comparison. - */ - lessThanOrEqual(expression: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is less than or equal to a constant value. - * - * @example - * ```typescript - * // Check if the 'score' field is less than or equal to 70 - * field("score").lessThan(70); - * ``` - * - * @param value - The constant value to compare for less than or equal to. - * @returns A new `Expression` representing the less than or equal to comparison. - */ - lessThanOrEqual(value: unknown): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is greater than another expression. - * - * @example - * ```typescript - * // Check if the 'age' field is greater than the 'limit' field - * field("age").greaterThan(field("limit")); - * ``` - * - * @param expression - The expression to compare for greater than. - * @returns A new `Expression` representing the greater than comparison. - */ - greaterThan(expression: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is greater than a constant value. - * - * @example - * ```typescript - * // Check if the 'price' field is greater than 100 - * field("price").greaterThan(100); - * ``` - * - * @param value - The constant value to compare for greater than. - * @returns A new `Expression` representing the greater than comparison. - */ - greaterThan(value: unknown): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is greater than or equal to another - * expression. - * - * @example - * ```typescript - * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1 - * field("quantity").greaterThanOrEqual(field('requirement').add(1)); - * ``` - * - * @param expression - The expression to compare for greater than or equal to. - * @returns A new `Expression` representing the greater than or equal to comparison. - */ - greaterThanOrEqual(expression: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is greater than or equal to a constant - * value. - * - * @example - * ```typescript - * // Check if the 'score' field is greater than or equal to 80 - * field("score").greaterThanOrEqual(80); - * ``` - * - * @param value - The constant value to compare for greater than or equal to. - * @returns A new `Expression` representing the greater than or equal to comparison. - */ - greaterThanOrEqual(value: unknown): BooleanExpression; - /** - * @beta - * Creates an expression that concatenates an array expression with one or more other arrays. - * - * @example - * ```typescript - * // Combine the 'items' array with another array field. - * field("items").arrayConcat(field("otherItems")); - * ``` - * @param secondArray - Second array expression or array literal to concatenate. - * @param otherArrays - Optional additional array expressions or array literals to concatenate. - * @returns A new `Expression` representing the concatenated array. - */ - arrayConcat(secondArray: Expression | unknown[], ...otherArrays: Array): FunctionExpression; - /** - * @beta - * Creates an expression that checks if an array contains a specific element. - * - * @example - * ```typescript - * // Check if the 'sizes' array contains the value from the 'selectedSize' field - * field("sizes").arrayContains(field("selectedSize")); - * ``` - * - * @param expression - The element to search for in the array. - * @returns A new `Expression` representing the 'array_contains' comparison. - */ - arrayContains(expression: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if an array contains a specific value. - * - * @example - * ```typescript - * // Check if the 'colors' array contains "red" - * field("colors").arrayContains("red"); - * ``` - * - * @param value - The element to search for in the array. - * @returns A new `Expression` representing the 'array_contains' comparison. - */ - arrayContains(value: unknown): BooleanExpression; - /** - * @beta - * Creates an expression that checks if an array contains all the specified elements. - * - * @example - * ```typescript - * // Check if the 'tags' array contains both the value in field "tag1" and the literal value "tag2" - * field("tags").arrayContainsAll([field("tag1"), "tag2"]); - * ``` - * - * @param values - The elements to check for in the array. - * @returns A new `Expression` representing the 'array_contains_all' comparison. - */ - arrayContainsAll(values: Array): BooleanExpression; - /** - * @beta - * Creates an expression that checks if an array contains all the specified elements. - * - * @example - * ```typescript - * // Check if the 'tags' array contains both of the values from field "tag1" and the literal value "tag2" - * field("tags").arrayContainsAll(array([field("tag1"), "tag2"])); - * ``` - * - * @param arrayExpression - The elements to check for in the array. - * @returns A new `Expression` representing the 'array_contains_all' comparison. - */ - arrayContainsAll(arrayExpression: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if an array contains any of the specified elements. - * - * @example - * ```typescript - * // Check if the 'categories' array contains either values from field "cate1" or "cate2" - * field("categories").arrayContainsAny([field("cate1"), field("cate2")]); - * ``` - * - * @param values - The elements to check for in the array. - * @returns A new `Expression` representing the 'array_contains_any' comparison. - */ - arrayContainsAny(values: Array): BooleanExpression; - /** - * @beta - * Creates an expression that checks if an array contains any of the specified elements. - * - * @example - * ```typescript - * // Check if the 'groups' array contains either the value from the 'userGroup' field - * // or the value "guest" - * field("groups").arrayContainsAny(array([field("userGroup"), "guest"])); - * ``` - * - * @param arrayExpression - The elements to check for in the array. - * @returns A new `Expression` representing the 'array_contains_any' comparison. - */ - arrayContainsAny(arrayExpression: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that reverses an array. - * - * @example - * ```typescript - * // Reverse the value of the 'myArray' field. - * field("myArray").arrayReverse(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed array. - */ - arrayReverse(): FunctionExpression; - /** - * @beta - * Creates an expression that calculates the length of an array. - * - * @example - * ```typescript - * // Get the number of items in the 'cart' array - * field("cart").arrayLength(); - * ``` - * - * @returns A new `Expression` representing the length of the array. - */ - arrayLength(): FunctionExpression; - /** - * @beta - * Creates an expression that checks if this expression is equal to any of the provided values or - * expressions. - * - * @example - * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * field("category").equalAny("Electronics", field("primaryType")); - * ``` - * - * @param values - The values or expressions to check against. - * @returns A new `Expression` representing the 'IN' comparison. - */ - equalAny(values: Array): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is equal to any of the provided values or - * expressions. - * - * @example - * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * field("category").equalAny(array(["Electronics", field("primaryType")])); - * ``` - * - * @param arrayExpression - An expression that evaluates to an array of values to check against. - * @returns A new `Expression` representing the 'IN' comparison. - */ - equalAny(arrayExpression: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is not equal to any of the provided values or - * expressions. - * - * @example - * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * field("status").notEqualAny(["pending", field("rejectedStatus")]); - * ``` - * - * @param values - The values or expressions to check against. - * @returns A new `Expression` representing the 'notEqualAny' comparison. - */ - notEqualAny(values: Array): BooleanExpression; - /** - * @beta - * Creates an expression that checks if this expression is not equal to any of the values in the evaluated expression. - * - * @example - * ```typescript - * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' - * field("status").notEqualAny(field('rejectedStatuses')); - * ``` - * - * @param arrayExpression - The values or expressions to check against. - * @returns A new `Expression` representing the 'notEqualAny' comparison. - */ - notEqualAny(arrayExpression: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if a field exists in the document. - * - * @example - * ```typescript - * // Check if the document has a field named "phoneNumber" - * field("phoneNumber").exists(); - * ``` - * - * @returns A new `Expression` representing the 'exists' check. - */ - exists(): BooleanExpression; - /** - * @beta - * Creates an expression that calculates the character length of a string in UTF-8. - * - * @example - * ```typescript - * // Get the character length of the 'name' field in its UTF-8 form. - * field("name").charLength(); - * ``` - * - * @returns A new `Expression` representing the length of the string. - */ - charLength(): FunctionExpression; - /** - * @beta - * Creates an expression that performs a case-sensitive string comparison. - * - * @example - * ```typescript - * // Check if the 'title' field contains the word "guide" (case-sensitive) - * field("title").like("%guide%"); - * ``` - * - * @param pattern - The pattern to search for. You can use "%" as a wildcard character. - * @returns A new `Expression` representing the 'like' comparison. - */ - like(pattern: string): BooleanExpression; - /** - * @beta - * Creates an expression that performs a case-sensitive string comparison. - * - * @example - * ```typescript - * // Check if the 'title' field contains the word "guide" (case-sensitive) - * field("title").like("%guide%"); - * ``` - * - * @param pattern - The pattern to search for. You can use "%" as a wildcard character. - * @returns A new `Expression` representing the 'like' comparison. - */ - like(pattern: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if a string contains a specified regular expression as a - * substring. - * - * @example - * ```typescript - * // Check if the 'description' field contains "example" (case-insensitive) - * field("description").regexContains("(?i)example"); - * ``` - * - * @param pattern - The regular expression to use for the search. - * @returns A new `Expression` representing the 'contains' comparison. - */ - regexContains(pattern: string): BooleanExpression; - /** - * @beta - * Creates an expression that checks if a string contains a specified regular expression as a - * substring. - * - * @example - * ```typescript - * // Check if the 'description' field contains the regular expression stored in field 'regex' - * field("description").regexContains(field("regex")); - * ``` - * - * @param pattern - The regular expression to use for the search. - * @returns A new `Expression` representing the 'contains' comparison. - */ - regexContains(pattern: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that returns the first substring of a string expression that matches - * a specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract the domain from an email address - * field("email").regexFind("@.+") - * ``` - * - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function. - */ - regexFind(pattern: string): FunctionExpression; - /** - * @beta - * Creates an expression that returns the first substring of a string expression that matches - * a specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract the domain from an email address - * field("email").regexFind(field("domain")) - * ``` - * - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function. - */ - regexFind(pattern: Expression): FunctionExpression; - /** - * @beta - * - * Creates an expression that evaluates to a list of all substrings in this string expression that - * match a specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract all hashtags from a post content field - * field("content").regexFindAll("#[A-Za-z0-9_]+") - * ``` - * - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} that evaluates to an array of matched substrings. - */ - regexFindAll(pattern: string): FunctionExpression; - /** - * @beta - * - * Creates an expression that evaluates to a list of all substrings in this string expression that - * match a specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract all names from a post content field - * field("content").regexFindAll(field("names")) - * ``` - * - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} that evaluates to an array of matched substrings. - */ - regexFindAll(pattern: Expression): FunctionExpression; - /** - * @beta - * Creates an expression that checks if a string matches a specified regular expression. - * - * @example - * ```typescript - * // Check if the 'email' field matches a valid email pattern - * field("email").regexMatch("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); - * ``` - * - * @param pattern - The regular expression to use for the match. - * @returns A new `Expression` representing the regular expression match. - */ - regexMatch(pattern: string): BooleanExpression; - /** - * @beta - * Creates an expression that checks if a string matches a specified regular expression. - * - * @example - * ```typescript - * // Check if the 'email' field matches a regular expression stored in field 'regex' - * field("email").regexMatch(field("regex")); - * ``` - * - * @param pattern - The regular expression to use for the match. - * @returns A new `Expression` representing the regular expression match. - */ - regexMatch(pattern: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if a string contains a specified substring. - * - * @example - * ```typescript - * // Check if the 'description' field contains "example". - * field("description").stringContains("example"); - * ``` - * - * @param substring - The substring to search for. - * @returns A new `Expression` representing the 'contains' comparison. - */ - stringContains(substring: string): BooleanExpression; - /** - * @beta - * Creates an expression that checks if a string contains the string represented by another expression. - * - * @example - * ```typescript - * // Check if the 'description' field contains the value of the 'keyword' field. - * field("description").stringContains(field("keyword")); - * ``` - * - * @param expr - The expression representing the substring to search for. - * @returns A new `Expression` representing the 'contains' comparison. - */ - stringContains(expr: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if a string starts with a given prefix. - * - * @example - * ```typescript - * // Check if the 'name' field starts with "Mr." - * field("name").startsWith("Mr."); - * ``` - * - * @param prefix - The prefix to check for. - * @returns A new `Expression` representing the 'starts with' comparison. - */ - startsWith(prefix: string): BooleanExpression; - /** - * @beta - * Creates an expression that checks if a string starts with a given prefix (represented as an - * expression). - * - * @example - * ```typescript - * // Check if the 'fullName' field starts with the value of the 'firstName' field - * field("fullName").startsWith(field("firstName")); - * ``` - * - * @param prefix - The prefix expression to check for. - * @returns A new `Expression` representing the 'starts with' comparison. - */ - startsWith(prefix: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that checks if a string ends with a given postfix. - * - * @example - * ```typescript - * // Check if the 'filename' field ends with ".txt" - * field("filename").endsWith(".txt"); - * ``` - * - * @param suffix - The postfix to check for. - * @returns A new `Expression` representing the 'ends with' comparison. - */ - endsWith(suffix: string): BooleanExpression; - /** - * @beta - * Creates an expression that checks if a string ends with a given postfix (represented as an - * expression). - * - * @example - * ```typescript - * // Check if the 'url' field ends with the value of the 'extension' field - * field("url").endsWith(field("extension")); - * ``` - * - * @param suffix - The postfix expression to check for. - * @returns A new `Expression` representing the 'ends with' comparison. - */ - endsWith(suffix: Expression): BooleanExpression; - /** - * @beta - * Creates an expression that converts a string to lowercase. - * - * @example - * ```typescript - * // Convert the 'name' field to lowercase - * field("name").toLower(); - * ``` - * - * @returns A new `Expression` representing the lowercase string. - */ - toLower(): FunctionExpression; - /** - * @beta - * Creates an expression that converts a string to uppercase. - * - * @example - * ```typescript - * // Convert the 'title' field to uppercase - * field("title").toUpper(); - * ``` - * - * @returns A new `Expression` representing the uppercase string. - */ - toUpper(): FunctionExpression; - /** - * @beta - * Creates an expression that removes leading and trailing characters from a string or byte array. - * - * @example - * ```typescript - * // Trim whitespace from the 'userInput' field - * field("userInput").trim(); - * - * // Trim quotes from the 'userInput' field - * field("userInput").trim('"'); - * ``` - * @param valueToTrim - Optional This parameter is treated as a set of characters or bytes that will be - * trimmed from the input. If not specified, then whitespace will be trimmed. - * @returns A new `Expression` representing the trimmed string or byte array. - */ - trim(valueToTrim?: string | Expression | Bytes): FunctionExpression; - /** - * @beta - * Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array. - * - * @example - * ```typescript - * // Trim whitespace from the beginning of the 'userInput' field - * field("userInput").ltrim(); - * - * // Trim quotes from the beginning of the 'userInput' field - * field("userInput").ltrim('"'); - * ``` - * - * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim. - * If not specified, whitespace will be trimmed. - * @returns A new `Expression` representing the trimmed string. - */ - ltrim(valueToTrim?: string | Expression | Bytes): FunctionExpression; - /** - * @beta - * Trims whitespace or a specified set of characters/bytes from the end of a string or byte array. - * - * @example - * ```typescript - * // Trim whitespace from the end of the 'userInput' field - * field("userInput").rtrim(); - * - * // Trim quotes from the end of the 'userInput' field - * field("userInput").rtrim('"'); - * ``` - * - * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim. - * If not specified, whitespace will be trimmed. - * @returns A new `Expression` representing the trimmed string or byte array. - */ - rtrim(valueToTrim?: string | Expression | Bytes): FunctionExpression; - /** - * @beta - * Creates an expression that returns the data type of this expression's result, as a string. - * - * @remarks - * This is evaluated on the backend. This means: - * 1. Generic typed elements (like `array`) evaluate strictly to the primitive `'array'`. - * 2. Any custom `FirestoreDataConverter` mappings are ignored. - * 3. For numeric values, the backend does not yield the JavaScript `"number"` type; it evaluates - * precisely as `"int64"` or `"float64"`. - * 4. For date or timestamp objects, the backend evaluates to `"timestamp"`. - * - * @example - * ```typescript - * // Get the data type of the value in field 'title' - * field('title').type() - * ``` - * - * @returns A new `Expression` representing the data type. - */ - type(): FunctionExpression; - /** - * @beta - * Creates an expression that checks if the result of this expression is of the given type. - * - * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data. - * - * @example - * ```typescript - * // Check if the 'price' field is specifically an integer (not just 'number') - * field('price').isType('int64'); - * ``` - * - * @param type - The type to check for. - * @returns A new `BooleanExpression` that evaluates to true if the expression's result is of the given type, false otherwise. - */ - isType(type: Type): BooleanExpression; - /** - * @beta - * Creates an expression that concatenates string expressions together. - * - * @example - * ```typescript - * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * field("firstName").stringConcat(constant(" "), field("lastName")); - * ``` - * - * @param secondString - The additional expression or string literal to concatenate. - * @param otherStrings - Optional additional expressions or string literals to concatenate. - * @returns A new `Expression` representing the concatenated string. - */ - stringConcat(secondString: Expression | string, ...otherStrings: Array): FunctionExpression; - /** - * @beta - * Creates an expression that finds the index of the first occurrence of a substring or byte sequence. - * - * @example - * ```typescript - * // Find the index of "foo" in the 'text' field - * field("text").stringIndexOf("foo"); - * ``` - * - * @param search - The substring or byte sequence to search for. - * @returns A new `Expression` representing the index of the first occurrence. - */ - stringIndexOf(search: string | Expression | Bytes): FunctionExpression; - /** - * @beta - * Creates an expression that repeats a string or byte array a specified number of times. - * - * @example - * ```typescript - * // Repeat the 'label' field 3 times - * field("label").stringRepeat(3); - * ``` - * - * @param repetitions - The number of times to repeat the string or byte array. - * @returns A new `Expression` representing the repeated string or byte array. - */ - stringRepeat(repetitions: number | Expression): FunctionExpression; - /** - * @beta - * Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement. - * - * @example - * ```typescript - * // Replace all occurrences of "foo" with "bar" in the 'text' field - * field("text").stringReplaceAll("foo", "bar"); - * ``` - * - * @param find - The substring or byte sequence to search for. - * @param replacement - The replacement string or byte sequence. - * @returns A new `Expression` representing the string or byte array with replacements. - */ - stringReplaceAll(find: string | Expression | Bytes, replacement: string | Expression | Bytes): FunctionExpression; - /** - * @beta - * Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement. - * - * @example - * ```typescript - * // Replace the first occurrence of "foo" with "bar" in the 'text' field - * field("text").stringReplaceOne("foo", "bar"); - * ``` - * - * @param find - The substring or byte sequence to search for. - * @param replacement - The replacement string or byte sequence. - * @returns A new `Expression` representing the string or byte array with the replacement. - */ - stringReplaceOne(find: string | Expression | Bytes, replacement: string | Expression | Bytes): FunctionExpression; - /** - * @beta - * Creates an expression that concatenates expression results together. - * - * @example - * ```typescript - * // Combine the 'firstName', ' ', and 'lastName' fields into a single value. - * field("firstName").concat(constant(" "), field("lastName")); - * ``` - * - * @param second - The additional expression or literal to concatenate. - * @param others - Optional additional expressions or literals to concatenate. - * @returns A new `Expression` representing the concatenated value. - */ - concat(second: Expression | unknown, ...others: Array): FunctionExpression; - /** - * @beta - * Creates an expression that reverses this string expression. - * - * @example - * ```typescript - * // Reverse the value of the 'myString' field. - * field("myString").reverse(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string. - */ - reverse(): FunctionExpression; - /** - * @beta - * Creates an expression that calculates the length of this string expression in bytes. - * - * @example - * ```typescript - * // Calculate the length of the 'myString' field in bytes. - * field("myString").byteLength(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string in bytes. - */ - byteLength(): FunctionExpression; - /** - * @beta - * Creates an expression that computes the ceiling of a numeric value. - * - * @example - * ```typescript - * // Compute the ceiling of the 'price' field. - * field("price").ceil(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ceiling of the numeric value. - */ - ceil(): FunctionExpression; - /** - * @beta - * Creates an expression that computes the floor of a numeric value. - * - * @example - * ```typescript - * // Compute the floor of the 'price' field. - * field("price").floor(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the floor of the numeric value. - */ - floor(): FunctionExpression; - /** - * @beta - * Creates an expression that computes the absolute value of a numeric value. - * - * @example - * ```typescript - * // Compute the absolute value of the 'price' field. - * field("price").abs(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the absolute value of the numeric value. - */ - abs(): FunctionExpression; - /** - * @beta - * Creates an expression that computes e to the power of this expression. - * - * @example - * ```typescript - * // Compute e to the power of the 'value' field. - * field("value").exp(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the exp of the numeric value. - */ - exp(): FunctionExpression; - /** - * @beta - * Accesses a value from a map (object) field using the provided key. - * - * @example - * ```typescript - * // Get the 'city' value from the 'address' map field - * field("address").mapGet("city"); - * ``` - * - * @param subfield - The key to access in the map. - * @returns A new `Expression` representing the value associated with the given key in the map. - */ - mapGet(subfield: string): FunctionExpression; - /** - * @beta - * Creates an expression that returns a new map with the specified entries added or updated. - * - * @remarks - * Note that `mapSet` only performs shallow updates to the map. Setting a value to `null` - * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`. - * - * @example - * ```typescript - * // Set the 'city' to "San Francisco" in the 'address' map - * field("address").mapSet("city", "San Francisco"); - * ``` - * - * @param key - The key to set. Must be a string or a constant string expression. - * @param value - The value to set. - * @param moreKeyValues - Additional key-value pairs to set. - * @returns A new `Expression` representing the map with the entries set. - */ - mapSet(key: string | Expression, value: unknown, ...moreKeyValues: unknown[]): FunctionExpression; - /** - * @beta - * Creates an expression that returns the keys of a map. - * - * @remarks - * While the backend generally preserves insertion order, relying on the - * order of the output array is not guaranteed and should be avoided. - * - * @example - * ```typescript - * // Get the keys of the 'address' map - * field("address").mapKeys(); - * ``` - * - * @returns A new `Expression` representing the keys of the map. - */ - mapKeys(): FunctionExpression; - /** - * @beta - * Creates an expression that returns the values of a map. - * - * @remarks - * While the backend generally preserves insertion order, relying on the - * order of the output array is not guaranteed and should be avoided. - * - * @example - * ```typescript - * // Get the values of the 'address' map - * field("address").mapValues(); - * ``` - * - * @returns A new `Expression` representing the values of the map. - */ - mapValues(): FunctionExpression; - /** - * @beta - * Creates an expression that returns the entries of a map as an array of maps, - * where each map contains a `"k"` property for the key and a `"v"` property for the value. - * For example: `[{ k: "key1", v: "value1" }, ...]`. - * - * @example - * ```typescript - * // Get the entries of the 'address' map - * field("address").mapEntries(); - * ``` - * - * @returns A new `Expression` representing the entries of the map. - */ - mapEntries(): FunctionExpression; - /** - * @beta - * Creates an aggregation that counts the number of stage inputs with valid evaluations of the - * expression or field. - * - * @example - * ```typescript - * // Count the total number of products - * field("productId").count().as("totalProducts"); - * ``` - * - * @returns A new `AggregateFunction` representing the 'count' aggregation. - */ - count(): AggregateFunction; - /** - * @beta - * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs. - * - * @example - * ```typescript - * // Calculate the total revenue from a set of orders - * field("orderAmount").sum().as("totalRevenue"); - * ``` - * - * @returns A new `AggregateFunction` representing the 'sum' aggregation. - */ - sum(): AggregateFunction; - /** - * @beta - * Creates an aggregation that calculates the average (mean) of a numeric field across multiple - * stage inputs. - * - * @example - * ```typescript - * // Calculate the average age of users - * field("age").average().as("averageAge"); - * ``` - * - * @returns A new `AggregateFunction` representing the 'average' aggregation. - */ - average(): AggregateFunction; - /** - * @beta - * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. - * - * @example - * ```typescript - * // Find the lowest price of all products - * field("price").minimum().as("lowestPrice"); - * ``` - * - * @returns A new `AggregateFunction` representing the 'minimum' aggregation. - */ - minimum(): AggregateFunction; - /** - * @beta - * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. - * - * @example - * ```typescript - * // Find the highest score in a leaderboard - * field("score").maximum().as("highestScore"); - * ``` - * - * @returns A new `AggregateFunction` representing the 'maximum' aggregation. - */ - maximum(): AggregateFunction; - /** - * @beta - * Creates an aggregation that finds the first value of an expression across multiple stage inputs. - * - * @example - * ```typescript - * // Find the first value of the 'rating' field - * field("rating").first().as("firstRating"); - * ``` - * - * @returns A new `AggregateFunction` representing the 'first' aggregation. - */ - first(): AggregateFunction; - /** - * @beta - * Creates an aggregation that finds the last value of an expression across multiple stage inputs. - * - * @example - * ```typescript - * // Find the last value of the 'rating' field - * field("rating").last().as("lastRating"); - * ``` - * - * @returns A new `AggregateFunction` representing the 'last' aggregation. - */ - last(): AggregateFunction; - /** - * @beta - * Creates an aggregation that collects all values of an expression across multiple stage inputs - * into an array. - * - * @remarks - * If the expression resolves to an absent value, it is converted to `null`. - * The order of elements in the output array is not stable and shouldn't be relied upon. - * - * @example - * ```typescript - * // Collect all tags from books into an array - * field("tags").arrayAgg().as("allTags"); - * ``` - * - * @returns A new `AggregateFunction` representing the 'array_agg' aggregation. - */ - arrayAgg(): AggregateFunction; - /** - * @beta - * Creates an aggregation that collects all distinct values of an expression across multiple stage - * inputs into an array. - * - * @remarks - * If the expression resolves to an absent value, it is converted to `null`. - * The order of elements in the output array is not stable and shouldn't be relied upon. - * - * @example - * ```typescript - * // Collect all distinct tags from books into an array - * field("tags").arrayAggDistinct().as("allDistinctTags"); - * ``` - * - * @returns A new `AggregateFunction` representing the 'array_agg_distinct' aggregation. - */ - arrayAggDistinct(): AggregateFunction; - /** - * @beta - * Creates an aggregation that counts the number of distinct values of the expression or field. - * - * @example - * ```typescript - * // Count the distinct number of products - * field("productId").countDistinct().as("distinctProducts"); - * ``` - * - * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation. - */ - countDistinct(): AggregateFunction; - /** - * @beta - * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering. - * - * @example - * ```typescript - * // Returns the larger value between the 'timestamp' field and the current timestamp. - * field("timestamp").logicalMaximum(Function.currentTimestamp()); - * ``` - * - * @param second - The second expression or literal to compare with. - * @param others - Optional additional expressions or literals to compare with. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical maximum operation. - */ - logicalMaximum(second: Expression | unknown, ...others: Array): FunctionExpression; - /** - * @beta - * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. - * - * @example - * ```typescript - * // Returns the smaller value between the 'timestamp' field and the current timestamp. - * field("timestamp").logicalMinimum(Function.currentTimestamp()); - * ``` - * - * @param second - The second expression or literal to compare with. - * @param others - Optional additional expressions or literals to compare with. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical minimum operation. - */ - logicalMinimum(second: Expression | unknown, ...others: Array): FunctionExpression; - /** - * @beta - * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. - * - * @example - * ```typescript - * // Get the vector length (dimension) of the field 'embedding'. - * field("embedding").vectorLength(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the vector. - */ - vectorLength(): FunctionExpression; - /** - * @beta - * Calculates the cosine distance between two vectors. - * - * @example - * ```typescript - * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * field("userVector").cosineDistance(field("itemVector")); - * ``` - * - * @param vectorExpression - The other vector (represented as an Expression) to compare against. - * @returns A new `Expression` representing the cosine distance between the two vectors. - */ - cosineDistance(vectorExpression: Expression): FunctionExpression; - /** - * @beta - * Calculates the Cosine distance between two vectors. - * - * @example - * ```typescript - * // Calculate the Cosine distance between the 'location' field and a target location - * field("location").cosineDistance(new VectorValue([37.7749, -122.4194])); - * ``` - * - * @param vector - The other vector (as a VectorValue) to compare against. - * @returns A new `Expression` representing the Cosine* distance between the two vectors. - */ - cosineDistance(vector: VectorValue | number[]): FunctionExpression; - /** - * @beta - * Calculates the dot product between two vectors. - * - * @example - * ```typescript - * // Calculate the dot product between a feature vector and a target vector - * field("features").dotProduct([0.5, 0.8, 0.2]); - * ``` - * - * @param vectorExpression - The other vector (as an array of numbers) to calculate with. - * @returns A new `Expression` representing the dot product between the two vectors. - */ - dotProduct(vectorExpression: Expression): FunctionExpression; - /** - * @beta - * Calculates the dot product between two vectors. - * - * @example - * ```typescript - * // Calculate the dot product between a feature vector and a target vector - * field("features").dotProduct(new VectorValue([0.5, 0.8, 0.2])); - * ``` - * - * @param vector - The other vector (as an array of numbers) to calculate with. - * @returns A new `Expression` representing the dot product between the two vectors. - */ - dotProduct(vector: VectorValue | number[]): FunctionExpression; - /** - * @beta - * Calculates the Euclidean distance between two vectors. - * - * @example - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * field("location").euclideanDistance([37.7749, -122.4194]); - * ``` - * - * @param vectorExpression - The other vector (as an array of numbers) to calculate with. - * @returns A new `Expression` representing the Euclidean distance between the two vectors. - */ - euclideanDistance(vectorExpression: Expression): FunctionExpression; - /** - * @beta - * Calculates the Euclidean distance between two vectors. - * - * @example - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * field("location").euclideanDistance(new VectorValue([37.7749, -122.4194])); - * ``` - * - * @param vector - The other vector (as a VectorValue) to compare against. - * @returns A new `Expression` representing the Euclidean distance between the two vectors. - */ - euclideanDistance(vector: VectorValue | number[]): FunctionExpression; - /** - * @beta - * Creates an expression that interprets this expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * @example - * ```typescript - * // Interpret the 'microseconds' field as microseconds since epoch. - * field("microseconds").unixMicrosToTimestamp(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp. - */ - unixMicrosToTimestamp(): FunctionExpression; - /** - * @beta - * Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * @example - * ```typescript - * // Convert the 'timestamp' field to microseconds since epoch. - * field("timestamp").timestampToUnixMicros(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of microseconds since epoch. - */ - timestampToUnixMicros(): FunctionExpression; - /** - * @beta - * Creates an expression that interprets this expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * @example - * ```typescript - * // Interpret the 'milliseconds' field as milliseconds since epoch. - * field("milliseconds").unixMillisToTimestamp(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp. - */ - unixMillisToTimestamp(): FunctionExpression; - /** - * @beta - * Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * @example - * ```typescript - * // Convert the 'timestamp' field to milliseconds since epoch. - * field("timestamp").timestampToUnixMillis(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of milliseconds since epoch. - */ - timestampToUnixMillis(): FunctionExpression; - /** - * @beta - * Creates an expression that interprets this expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * @example - * ```typescript - * // Interpret the 'seconds' field as seconds since epoch. - * field("seconds").unixSecondsToTimestamp(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp. - */ - unixSecondsToTimestamp(): FunctionExpression; - /** - * @beta - * Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * @example - * ```typescript - * // Convert the 'timestamp' field to seconds since epoch. - * field("timestamp").timestampToUnixSeconds(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of seconds since epoch. - */ - timestampToUnixSeconds(): FunctionExpression; - /** - * @beta - * Creates an expression that adds a specified amount of time to this timestamp expression. - * - * @example - * ```typescript - * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. - * field("timestamp").timestampAdd(field("unit"), field("amount")); - * ``` - * - * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. - * @param amount - The expression evaluates to amount of the unit. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp. - */ - timestampAdd(unit: Expression, amount: Expression): FunctionExpression; - /** - * @beta - * Creates an expression that adds a specified amount of time to this timestamp expression. - * - * @example - * ```typescript - * // Add 1 day to the 'timestamp' field. - * field("timestamp").timestampAdd("day", 1); - * ``` - * - * @param unit - The unit of time to add (e.g., "day", "hour"). - * @param amount - The amount of time to add. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp. - */ - timestampAdd(unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; - /** - * @beta - * Creates an expression that subtracts a specified amount of time from this timestamp expression. - * - * @example - * ```typescript - * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * field("timestamp").timestampSubtract(field("unit"), field("amount")); - * ``` - * - * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. - * @param amount - The expression evaluates to amount of the unit. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp. - */ - timestampSubtract(unit: Expression, amount: Expression): FunctionExpression; - /** - * @beta - * Creates an expression that subtracts a specified amount of time from this timestamp expression. - * - * @example - * ```typescript - * // Subtract 1 day from the 'timestamp' field. - * field("timestamp").timestampSubtract("day", 1); - * ``` - * - * @param unit - The unit of time to subtract (e.g., "day", "hour"). - * @param amount - The amount of time to subtract. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp. - */ - timestampSubtract(unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; - /** - * @beta - * - * Creates an expression that returns the document ID from a path. - * - * @example - * ```typescript - * // Get the document ID from a path. - * field("__path__").documentId(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the documentId operation. - */ - documentId(): FunctionExpression; - /** - * @beta - * - * Creates an expression that returns a substring of the results of this expression. - * - * @param position - Index of the first character of the substring. - * @param length - Length of the substring. If not provided, the substring will - * end at the end of the input. - */ - substring(position: number, length?: number): FunctionExpression; - /** - * @beta - * - * Creates an expression that returns a substring of the results of this expression. - * - * @param position - An expression returning the index of the first character of the substring. - * @param length - An expression returning the length of the substring. If not provided the - * substring will end at the end of the input. - */ - substring(position: Expression, length?: Expression): FunctionExpression; - /** - * @beta - * Creates an expression that indexes into an array from the beginning or end - * and returns the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. - * - * @example - * ```typescript - * // Return the value in the 'tags' field array at index `1`. - * field('tags').arrayGet(1); - * ``` - * - * @param offset - The index of the element to return. - * @returns A new `Expression` representing the 'arrayGet' operation. - */ - arrayGet(offset: number): FunctionExpression; - /** - * @beta - * Creates an expression that indexes into an array from the beginning or end - * and returns the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. - * - * @example - * ```typescript - * // Return the value in the tags field array at index specified by field - * // 'favoriteTag'. - * field('tags').arrayGet(field('favoriteTag')); - * ``` - * - * @param offsetExpr - An `Expression` evaluating to the index of the element to return. - * @returns A new `Expression` representing the 'arrayGet' operation. - */ - arrayGet(offsetExpr: Expression): FunctionExpression; - /** - * @beta - * - * Creates an expression that checks if a given expression produces an error. - * - * @example - * ```typescript - * // Check if the result of a calculation is an error - * field("title").arrayContains(1).isError(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the 'isError' check. - */ - isError(): BooleanExpression; - /** - * @beta - * - * Creates an expression that returns the result of the `catchExpr` argument - * if there is an error, else return the result of this expression. - * - * @example - * ```typescript - * // Returns the first item in the title field arrays, or returns - * // the entire title field if the array is empty or the field is another type. - * field("title").arrayGet(0).ifError(field("title")); - * ``` - * - * @param catchExpr - The catch expression that will be evaluated and - * returned if this expression produces an error. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation. - */ - ifError(catchExpr: Expression): FunctionExpression; - /** - * @beta - * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of this expression. - * - * @example - * ```typescript - * // Returns the first item in the title field arrays, or returns - * // "Default Title" - * field("title").arrayGet(0).ifError("Default Title"); - * ``` - * - * @param catchValue - The value that will be returned if this expression - * produces an error. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation. - */ - ifError(catchValue: unknown): FunctionExpression; - /** - * @beta - * - * Creates an expression that returns `true` if the result of this expression - * is absent. Otherwise, returns `false` even if the value is `null`. - * - * @example - * ```typescript - * // Check if the field `value` is absent. - * field("value").isAbsent(); - * @example - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the 'isAbsent' check. - */ - isAbsent(): BooleanExpression; - /** - * @beta - * - * Creates an expression that removes a key from the map produced by evaluating this expression. - * - * @example - * ``` - * // Removes the key 'baz' from the input map. - * map({foo: 'bar', baz: true}).mapRemove('baz'); - * ``` - * - * @param key - The name of the key to remove from the input map. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'mapRemove' operation. - */ - mapRemove(key: string): FunctionExpression; - /** - * @beta - * - * Creates an expression that removes a key from the map produced by evaluating this expression. - * - * @example - * ``` - * // Removes the key 'baz' from the input map. - * map({foo: 'bar', baz: true}).mapRemove(constant('baz')); - * @example - * ``` - * - * @param keyExpr - An expression that produces the name of the key to remove from the input map. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'mapRemove' operation. - */ - mapRemove(keyExpr: Expression): FunctionExpression; - /** - * @beta - * - * Creates an expression that merges multiple map values. - * - * @example - * ``` - * // Merges the map in the settings field with, a map literal, and a map in - * // that is conditionally returned by another expression - * field('settings').mapMerge({ enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) - * ``` - * - * @param secondMap - A required second map to merge. Represented as a literal or - * an expression that returns a map. - * @param otherMaps - Optional additional maps to merge. Each map is represented - * as a literal or an expression that returns a map. - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'mapMerge' operation. - */ - mapMerge(secondMap: Record | Expression, ...otherMaps: Array | Expression>): FunctionExpression; - /** - * @beta - * Creates an expression that returns the value of this expression raised to the power of another expression. - * - * @example - * ```typescript - * // Raise the value of the 'base' field to the power of the 'exponent' field. - * field("base").pow(field("exponent")); - * ``` - * - * @param exponent - The expression to raise this expression to the power of. - * @returns A new `Expression` representing the power operation. - */ - pow(exponent: Expression): FunctionExpression; - /** - * @beta - * Creates an expression that returns the value of this expression raised to the power of a constant value. - * - * @example - * ```typescript - * // Raise the value of the 'base' field to the power of 2. - * field("base").pow(2); - * ``` - * - * @param exponent - The constant value to raise this expression to the power of. - * @returns A new `Expression` representing the power operation. - */ - pow(exponent: number): FunctionExpression; - /** - * @beta - * Creates an expression that truncates the numeric value to an integer. - * - * @example - * ```typescript - * // Truncate the 'rating' field - * field("rating").trunc(); - * ``` - * - * @returns A new `Expression` representing the truncated value. - */ - trunc(): FunctionExpression; - /** - * @beta - * Creates an expression that truncates a numeric value to the specified number of decimal places. - * - * @example - * ```typescript - * // Truncate the value of the 'rating' field to two decimal places. - * field("rating").trunc(2); - * ``` - * - * @param decimalPlaces - A constant specifying the truncation precision in decimal places. - * @returns A new `Expression` representing the truncated value. - */ - trunc(decimalPlaces: number): FunctionExpression; - /** - * @beta - * Creates an expression that truncates a numeric value to the specified number of decimal places. - * - * @example - * ```typescript - * // Truncate the value of the 'rating' field to two decimal places. - * field("rating").trunc(constant(2)); - * ``` - * - * @param decimalPlaces - An expression specifying the truncation precision in decimal places. - * @returns A new `Expression` representing the truncated value. - */ - trunc(decimalPlaces: Expression): FunctionExpression; - /** - * @beta - * Creates an expression that rounds a numeric value to the nearest whole number. - * - * @example - * ```typescript - * // Round the value of the 'price' field. - * field("price").round(); - * ``` - * - * @returns A new `Expression` representing the rounded value. - */ - round(): FunctionExpression; - /** - * @beta - * Creates an expression that rounds a numeric value to the specified number of decimal places. - * - * @example - * ```typescript - * // Round the value of the 'price' field to two decimal places. - * field("price").round(2); - * ``` - * - * @param decimalPlaces - A constant specifying the rounding precision in decimal places. - * - * @returns A new `Expression` representing the rounded value. - */ - round(decimalPlaces: number): FunctionExpression; - /** - * @beta - * Creates an expression that rounds a numeric value to the specified number of decimal places. - * - * @example - * ```typescript - * // Round the value of the 'price' field to two decimal places. - * field("price").round(constant(2)); - * ``` - * - * @param decimalPlaces - An expression specifying the rounding precision in decimal places. - * - * @returns A new `Expression` representing the rounded value. - */ - round(decimalPlaces: Expression): FunctionExpression; - /** - * @beta - * Creates an expression that returns the collection ID from a path. - * - * @example - * ```typescript - * // Get the collection ID from a path. - * field("__path__").collectionId(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the collectionId operation. - */ - collectionId(): FunctionExpression; - /** - * @beta - * Creates an expression that calculates the length of a string, array, map, vector, or bytes. - * - * @example - * ```typescript - * // Get the length of the 'name' field. - * field("name").length(); - * - * // Get the number of items in the 'cart' array. - * field("cart").length(); - * ``` - * - * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes. - */ - length(): FunctionExpression; - /** - * @beta - * Creates an expression that computes the natural logarithm of a numeric value. - * - * @example - * ```typescript - * // Compute the natural logarithm of the 'value' field. - * field("value").ln(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the natural logarithm of the numeric value. - */ - ln(): FunctionExpression; - /** - * @beta - * Creates an expression that computes the square root of a numeric value. - * - * @example - * ```typescript - * // Compute the square root of the 'value' field. - * field("value").sqrt(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the square root of the numeric value. - */ - sqrt(): FunctionExpression; - /** - * @beta - * Creates an expression that reverses a string. - * - * @example - * ```typescript - * // Reverse the value of the 'myString' field. - * field("myString").stringReverse(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string. - */ - stringReverse(): FunctionExpression; - /** - * @beta - * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else - * return the result of the this expression evaluation. - * - * @example - * ```typescript - * // Returns the value of the optional field 'optional_field', or returns 'default_value' - * // if the field is absent. - * field("optional_field").ifAbsent("default_value") - * ``` - * - * @param elseValue - The value that will be returned if this Expression evaluates to an absent value. - * @returns A new [Expression] representing the ifAbsent operation. - */ - ifAbsent(elseValue: unknown): Expression; - /** - * @beta - * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else - * return the result of this expression evaluation. - * - * ```typescript - * // Returns the value of the optional field 'optional_field', or if that is - * // absent, then returns the value of the field ` - * field("optional_field").ifAbsent(field('default_field')) - * ``` - * - * @param elseExpression - The Expression that will be evaluated if this Expression evaluates to an absent value. - * @returns A new [Expression] representing the ifAbsent operation. - */ - ifAbsent(elseExpression: unknown): Expression; - /** - * @beta - * Creates an expression that joins the elements of an array into a string. - * - * @example - * ```typescript - * // Join the elements of the 'tags' field with the delimiter from the 'separator' field. - * field("tags").join(field("separator")) - * ``` - * - * @param delimiterExpression - The expression that evaluates to the delimiter string. - * @returns A new Expression representing the join operation. - */ - join(delimiterExpression: Expression): Expression; - /** - * @beta - * Creates an expression that joins the elements of an array field into a string. - * - * @example - * ```typescript - * // Join the elements of the 'tags' field with a comma and space. - * field("tags").join(", ") - * ``` - * - * @param delimiter - The string to use as a delimiter. - * @returns A new Expression representing the join operation. - */ - join(delimiter: string): Expression; - /** - * @beta - * Creates an expression that computes the base-10 logarithm of a numeric value. - * - * @example - * ```typescript - * // Compute the base-10 logarithm of the 'value' field. - * field("value").log10(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the base-10 logarithm of the numeric value. - */ - log10(): FunctionExpression; - /** - * @beta - * Creates an expression that computes the sum of the elements in an array. - * - * @example - * ```typescript - * // Compute the sum of the elements in the 'scores' field. - * field("scores").arraySum(); - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the sum of the elements in the array. - */ - arraySum(): FunctionExpression; - /** - * @beta - * Creates an expression that splits the result of this expression into an - * array of substrings based on the provided delimiter. - * - * @example - * ```typescript - * // Split the 'scoresCsv' field on delimiter ',' - * field('scoresCsv').split(',') - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function. - */ - split(delimiter: string): FunctionExpression; - /** - * @beta - * Creates an expression that splits the result of this expression into an - * array of substrings based on the provided delimiter. - * - * @example - * ```typescript - * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format - * field('scores').split(conditional(field('format').equal('csv'), constant(','), constant(':')) - * ``` - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function. - */ - split(delimiter: Expression): FunctionExpression; - /** - * Creates an expression that truncates a timestamp to a specified granularity. - * - * @example - * ```typescript - * // Truncate the 'createdAt' timestamp to the beginning of the day. - * field('createdAt').timestampTruncate('day') - * ``` - * - * @param granularity - The granularity to truncate to. - * @param timezone - The timezone to use for truncation. Valid values are from - * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". - * @returns A new `Expression` representing the truncated timestamp. - */ - timestampTruncate(granularity: TimeGranularity, timezone?: string | Expression): FunctionExpression; - /** - * Creates an expression that truncates a timestamp to a specified granularity. - * - * @example - * ```typescript - * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. - * field('createdAt').timestampTruncate(field('granularity')) - * ``` - * - * @param granularity - The granularity to truncate to. - * @param timezone - The timezone to use for truncation. Valid values are from - * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". - * @returns A new `Expression` representing the truncated timestamp. - */ - timestampTruncate(granularity: Expression, timezone?: string | Expression): FunctionExpression; - /** - * @beta - * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in ascending order based on this expression. - * - * @example - * ```typescript - * // Sort documents by the 'name' field in ascending order - * pipeline().collection("users") - * .sort(field("name").ascending()); - * ``` - * - * @returns A new `Ordering` for ascending sorting. - */ - ascending(): Ordering; - /** - * @beta - * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in descending order based on this expression. - * - * @example - * ```typescript - * // Sort documents by the 'createdAt' field in descending order - * firestore.pipeline().collection("users") - * .sort(field("createdAt").descending()); - * ``` - * - * @returns A new `Ordering` for descending sorting. - */ - descending(): Ordering; - /** - * @beta - * Assigns an alias to this expression. - * - * Aliases are useful for renaming fields in the output of a stage or for giving meaningful - * names to calculated values. - * - * @example - * ```typescript - * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. - * firestore.pipeline().collection("items") - * .addFields(field("price").multiply(field("quantity")).as("totalPrice")); - * ``` - * - * @param name - The alias to assign to this expression. - * @returns A new {@link @firebase/firestore/pipelines#AliasedExpression} that wraps this - * expression and associates it with the provided alias. - */ - as(name: string): AliasedExpression; -} -/** - * @beta - * - * An enumeration of the different types of expressions. - */ -export declare type ExpressionType = 'Field' | 'Constant' | 'Function' | 'AggregateFunction' | 'ListOfExpressions' | 'AliasedExpression'; -/** - * @beta - * - * Represents a reference to a field in a Firestore document, or outputs of a {@link @firebase/firestore/pipelines#Pipeline} stage. - * - *

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

You can create a `Field` instance using the static {@link @firebase/firestore/pipelines#field} method: - * - * @example - * ```typescript - * // Create a Field instance for the 'name' field - * const nameField = field("name"); - * - * // Create a Field instance for a nested field 'address.city' - * const cityField = field("address.city"); - * ``` - */ -export declare class Field extends Expression implements Selectable { - private fieldPath; - readonly expressionType: ExpressionType; - selectable: true; - /* Excluded from this release type: __constructor */ - get fieldName(): string; - get alias(): string; - get expr(): Expression; -} -/** - * @beta - * Creates a {@link @firebase/firestore/pipelines#Field} instance representing the field at the given path. - * - * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field - * (e.g., "address.city"). - * - * @example - * ```typescript - * // Create a Field instance for the 'title' field - * const titleField = field("title"); - * - * // Create a Field instance for a nested field 'author.firstName' - * const authorFirstNameField = field("author.firstName"); - * ``` - * - * @param name - The path to the field. - * @returns A new {@link @firebase/firestore/pipelines#Field} instance representing the specified field. - */ -export declare function field(name: string): Field; -/** - * @beta - * Creates a {@link @firebase/firestore/pipelines#Field} instance representing the field at the given path. - * - * @param path - A FieldPath specifying the field. - * @returns A new {@link @firebase/firestore/pipelines#Field} instance representing the specified field. - */ -export declare function field(path: FieldPath): Field; -/** - * @beta - * Options defining how a FindNearestStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(findNearest:1)}. - */ -export declare type FindNearestStageOptions = StageOptions & { - /** - * @beta - * Specifies the field to be used. This can be a string representing the field path - * (e.g., 'fieldName', 'nested.fieldName') or an object of type {@link @firebase/firestore/pipelines#Field} - * representing a more complex field expression. - */ - field: Field | string; - /** - * @beta - * Specifies the query vector value, to which the vector distance will be computed. - */ - vectorValue: VectorValue | number[]; - /** - * @beta - * Specifies the method used to compute the distance between vectors. - * - * Possible values are: - * - `'euclidean'`: Euclidean distance. - * - `'cosine'`: Cosine similarity. - * - `'dot_product'`: Dot product. - */ - distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; - /** - * @beta - * The maximum number of documents to return from the FindNearest stage. - */ - limit?: number; - /** - * @beta - * If set, specifies the field on the output documents that will contain - * the computed vector distance for the document. If not set, the computed - * vector distance will not be returned. - */ - distanceField?: string; -}; -/** - * @beta - * Creates an aggregation that finds the first value of an expression across multiple stage - * inputs. - * - * @example - * ```typescript - * // Find the first value of the 'rating' field - * first(field("rating")).as("firstRating"); - * ``` - * - * @param expression - The expression to find the first value of. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'first' aggregation. - */ -export declare function first(expression: Expression): AggregateFunction; -/** - * @beta - * Creates an aggregation that finds the first value of a field across multiple stage inputs. - * - * @example - * ```typescript - * // Find the first value of the 'rating' field - * first("rating").as("firstRating"); - * ``` - * - * @param fieldName - The name of the field to find the first value of. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'first' aggregation. - */ -export declare function first(fieldName: string): AggregateFunction; -/* Excluded from this release type: FirstPartyCredentialsSettings */ -/** - * @beta - * Creates an expression that computes the floor of a numeric value. - * - * @param expr - The expression to compute the floor of. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the floor of the numeric value. - */ -export declare function floor(expr: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that computes the floor of a numeric value. - * - * @param fieldName - The name of the field to compute the floor of. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the floor of the numeric value. - */ -export declare function floor(fieldName: string): FunctionExpression; -/** - * @beta - * - * This class defines the base class for Firestore {@link @firebase/firestore/pipelines#Pipeline} functions, which can be evaluated within pipeline - * execution. - * - * Typically, you would not use this class or its children directly. Use either the functions like {@link @firebase/firestore/pipelines#and}, {@link @firebase/firestore/pipelines#(equal:1)}, - * or the methods on {@link @firebase/firestore/pipelines#Expression} ({@link @firebase/firestore/pipelines#Expression.(equal:1)}, {@link @firebase/firestore/pipelines#Expression.(lessThan:1)}, etc.) to construct new Function instances. - */ -export declare class FunctionExpression extends Expression { - private name; - private params; - readonly expressionType: ExpressionType; - constructor(name: string, params: Expression[]); - constructor(name: string, params: Expression[], _methodName: string | undefined); -} -/** - * @beta - * - * Creates an expression that checks if the first expression is greater than the second - * expression. - * - * @example - * ```typescript - * // Check if the 'age' field is greater than 18 - * greaterThan(field("age"), Constant(9).add(9)); - * ``` - * - * @param left - The first expression to compare. - * @param right - The second expression to compare. - * @returns A new `Expression` representing the greater than comparison. - */ -export declare function greaterThan(left: Expression, right: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an expression is greater than a constant value. - * - * @example - * ```typescript - * // Check if the 'age' field is greater than 18 - * greaterThan(field("age"), 18); - * ``` - * - * @param expression - The expression to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the greater than comparison. - */ -export declare function greaterThan(expression: Expression, value: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is greater than an expression. - * - * @example - * ```typescript - * // Check if the value of field 'age' is greater than the value of field 'limit' - * greaterThan("age", field("limit")); - * ``` - * - * @param fieldName - The field name to compare. - * @param expression - The expression to compare to. - * @returns A new `Expression` representing the greater than comparison. - */ -export declare function greaterThan(fieldName: string, expression: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is greater than a constant value. - * - * @example - * ```typescript - * // Check if the 'price' field is greater than 100 - * greaterThan("price", 100); - * ``` - * - * @param fieldName - The field name to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the greater than comparison. - */ -export declare function greaterThan(fieldName: string, value: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if the first expression is greater than or equal to the - * second expression. - * - * @example - * ```typescript - * // Check if the 'quantity' field is greater than or equal to the field "threshold" - * greaterThanOrEqual(field("quantity"), field("threshold")); - * ``` - * - * @param left - The first expression to compare. - * @param right - The second expression to compare. - * @returns A new `Expression` representing the greater than or equal to comparison. - */ -export declare function greaterThanOrEqual(left: Expression, right: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an expression is greater than or equal to a constant - * value. - * - * @example - * ```typescript - * // Check if the 'quantity' field is greater than or equal to 10 - * greaterThanOrEqual(field("quantity"), 10); - * ``` - * - * @param expression - The expression to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the greater than or equal to comparison. - */ -export declare function greaterThanOrEqual(expression: Expression, value: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is greater than or equal to an expression. - * - * @example - * ```typescript - * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' - * greaterThanOrEqual("age", field("limit")); - * ``` - * - * @param fieldName - The field name to compare. - * @param value - The expression to compare to. - * @returns A new `Expression` representing the greater than or equal to comparison. - */ -export declare function greaterThanOrEqual(fieldName: string, value: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is greater than or equal to a constant - * value. - * - * @example - * ```typescript - * // Check if the 'score' field is greater than or equal to 80 - * greaterThanOrEqual("score", 80); - * ``` - * - * @param fieldName - The field name to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the greater than or equal to comparison. - */ -export declare function greaterThanOrEqual(fieldName: string, value: unknown): BooleanExpression; -/** - * @beta - * Creates an expression that returns the `elseExpr` argument if `ifExpr` is absent, else return - * the result of the `ifExpr` argument evaluation. - * - * @example - * ```typescript - * // Returns the value of the optional field 'optional_field', or returns 'default_value' - * // if the field is absent. - * ifAbsent(field("optional_field"), constant("default_value")) - * ``` - * - * @param ifExpr - The expression to check for absence. - * @param elseExpr - The expression that will be evaluated and returned if [ifExpr] is absent. - * @returns A new Expression representing the ifAbsent operation. - */ -export declare function ifAbsent(ifExpr: Expression, elseExpr: Expression): Expression; -/** - * @beta - * Creates an expression that returns the `elseValue` argument if `ifExpr` is absent, else - * return the result of the `ifExpr` argument evaluation. - * - * @example - * ```typescript - * // Returns the value of the optional field 'optional_field', or returns 'default_value' - * // if the field is absent. - * ifAbsent(field("optional_field"), "default_value") - * ``` - * - * @param ifExpr - The expression to check for absence. - * @param elseValue - The value that will be returned if `ifExpr` evaluates to an absent value. - * @returns A new [Expression] representing the ifAbsent operation. - */ -export declare function ifAbsent(ifExpr: Expression, elseValue: unknown): Expression; -/** - * @beta - * Creates an expression that returns the `elseExpr` argument if `ifFieldName` is absent, else - * return the value of the field. - * - * @example - * ```typescript - * // Returns the value of the optional field 'optional_field', or returns the value of - * // 'default_field' if 'optional_field' is absent. - * ifAbsent("optional_field", field("default_field")) - * ``` - * - * @param ifFieldName - The field to check for absence. - * @param elseExpr - The expression that will be evaluated and returned if `ifFieldName` is - * absent. - * @returns A new Expression representing the ifAbsent operation. - */ -export declare function ifAbsent(ifFieldName: string, elseExpr: Expression): Expression; -/** - * @beta - * Creates an expression that returns the `elseValue` argument if `ifFieldName` is absent, else - * return the value of the field. - * - * @example - * ```typescript - * // Returns the value of the optional field 'optional_field', or returns 'default_value' - * // if the field is absent. - * ifAbsent("optional_field", "default_value") - * ``` - * - * @param ifFieldName - The field to check for absence. - * @param elseValue - The value that will be returned if [ifFieldName] is absent. - * @returns A new Expression representing the ifAbsent operation. - */ -export declare function ifAbsent(ifFieldName: string | Expression, elseValue: Expression | unknown): Expression; -/** - * @beta - * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of the `try` argument evaluation. - * - * This overload is useful when a BooleanExpression is required. - * - * @example - * ```typescript - * // Create an expression that protects against a divide by zero error - * // but always returns a boolean expression. - * ifError(constant(50).divide('length').gt(1), constant(false)); - * ``` - * - * @param tryExpr - The try expression. - * @param catchExpr - The catch expression that will be evaluated and - * returned if the tryExpr produces an error. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation. - */ -export declare function ifError(tryExpr: BooleanExpression, catchExpr: BooleanExpression): BooleanExpression; -/** - * @beta - * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of the `try` argument evaluation. - * - * @example - * ```typescript - * // Returns the first item in the title field arrays, or returns - * // the entire title field if the array is empty or the field is another type. - * ifError(field("title").arrayGet(0), field("title")); - * ``` - * - * @param tryExpr - The try expression. - * @param catchExpr - The catch expression that will be evaluated and - * returned if the tryExpr produces an error. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation. - */ -export declare function ifError(tryExpr: Expression, catchExpr: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of the `try` argument evaluation. - * - * @example - * ```typescript - * // Returns the first item in the title field arrays, or returns - * // "Default Title" - * ifError(field("title").arrayGet(0), "Default Title"); - * ``` - * - * @param tryExpr - The try expression. - * @param catchValue - The value that will be returned if the tryExpr produces an - * error. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'ifError' operation. - */ -export declare function ifError(tryExpr: Expression, catchValue: unknown): FunctionExpression; -/* Excluded from this release type: _internalPipelineToExecutePipelineRequestProto */ -/** - * @beta - * - * Creates an expression that returns `true` if a value is absent. Otherwise, - * returns `false` even if the value is `null`. - * - * @example - * ```typescript - * // Check if the field `value` is absent. - * isAbsent(field("value")); - * ``` - * - * @param value - The expression to check. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'isAbsent' check. - */ -export declare function isAbsent(value: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that returns `true` if a field is absent. Otherwise, - * returns `false` even if the field value is `null`. - * - * @example - * ```typescript - * // Check if the field `value` is absent. - * isAbsent("value"); - * ``` - * - * @param field - The field to check. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'isAbsent' check. - */ -export declare function isAbsent(field: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a given expression produces an error. - * - * @example - * ```typescript - * // Check if the result of a calculation is an error - * isError(field("title").arrayContains(1)); - * ``` - * - * @param value - The expression to check. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'isError' check. - */ -export declare function isError(value: Expression): BooleanExpression; -/** - * @beta - * Creates an expression that checks if the value in the specified field is of the given type. - * - * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data. - * - * @example - * ```typescript - * // Check if the 'price' field is a floating point number (evaluating to true inside pipeline conditionals) - * isType('price', 'float64'); - * ``` - * - * @param fieldName - The name of the field to check. - * @param type - The type to check for. - * @returns A new `BooleanExpression` that evaluates to true if the field's value is of the given type, false otherwise. - */ -export declare function isType(fieldName: string, type: Type): BooleanExpression; -/** - * @beta - * Creates an expression that checks if the result of an expression is of the given type. - * - * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data. - * - * @example - * ```typescript - * // Check if the result of a calculation is a number - * isType(add('count', 1), 'number') - * ``` - * - * @param expression - The expression to check. - * @param type - The type to check for. - * @returns A new `BooleanExpression` that evaluates to true if the expression's result is of the given type, false otherwise. - */ -export declare function isType(expression: Expression, type: Type): BooleanExpression; -/** - * @beta - * Creates an expression that joins the elements of an array into a string. - * - * @example - * ```typescript - * // Join the elements of the 'tags' field with a comma and space. - * join("tags", ", ") - * ``` - * - * @param arrayFieldName - The name of the field containing the array. - * @param delimiter - The string to use as a delimiter. - * @returns A new Expression representing the join operation. - */ -export declare function join(arrayFieldName: string, delimiter: string): Expression; -/** - * @beta - * Creates an expression that joins the elements of an array into a string. - * - * @example - * ```typescript - * // Join an array of string using the delimiter from the 'separator' field. - * join(array(['foo', 'bar']), field("separator")) - * ``` - * - * @param arrayExpression - An expression that evaluates to an array. - * @param delimiterExpression - The expression that evaluates to the delimiter string. - * @returns A new Expression representing the join operation. - */ -export declare function join(arrayExpression: Expression, delimiterExpression: Expression): Expression; -/** - * @beta - * Creates an expression that joins the elements of an array into a string. - * - * @example - * ```typescript - * // Join the elements of the 'tags' field with a comma and space. - * join(field("tags"), ", ") - * ``` - * - * @param arrayExpression - An expression that evaluates to an array. - * @param delimiter - The string to use as a delimiter. - * @returns A new Expression representing the join operation. - */ -export declare function join(arrayExpression: Expression, delimiter: string): Expression; -/** - * @beta - * Creates an expression that joins the elements of an array into a string. - * - * @example - * ```typescript - * // Join the elements of the 'tags' field with the delimiter from the 'separator' field. - * join('tags', field("separator")) - * ``` - * - * @param arrayFieldName - The name of the field containing the array. - * @param delimiterExpression - The expression that evaluates to the delimiter string. - * @returns A new Expression representing the join operation. - */ -export declare function join(arrayFieldName: string, delimiterExpression: Expression): Expression; -/** - * @beta - * Creates an aggregation that finds the last value of an expression across multiple stage - * inputs. - * - * @example - * ```typescript - * // Find the last value of the 'rating' field - * last(field("rating")).as("lastRating"); - * ``` - * - * @param expression - The expression to find the last value of. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'last' aggregation. - */ -export declare function last(expression: Expression): AggregateFunction; -/** - * @beta - * Creates an aggregation that finds the last value of a field across multiple stage inputs. - * - * @example - * ```typescript - * // Find the last value of the 'rating' field - * last("rating").as("lastRating"); - * ``` - * - * @param fieldName - The name of the field to find the last value of. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'last' aggregation. - */ -export declare function last(fieldName: string): AggregateFunction; -/** - * @beta - * Creates an expression that calculates the length of a string, array, map, vector, or bytes. - * - * @example - * ```typescript - * // Get the length of the 'name' field. - * length("name"); - * - * // Get the number of items in the 'cart' array. - * length("cart"); - * ``` - * - * @param fieldName - The name of the field to calculate the length of. - * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes. - */ -declare function length_2(fieldName: string): FunctionExpression; -/** - * @beta - * Creates an expression that calculates the length of a string, array, map, vector, or bytes. - * - * @example - * ```typescript - * // Get the length of the 'name' field. - * length(field("name")); - * - * // Get the number of items in the 'cart' array. - * length(field("cart")); - * ``` - * - * @param expression - An expression evaluating to a string, array, map, vector, or bytes, which the length will be calculated for. - * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes. - */ -declare function length_2(expression: Expression): FunctionExpression; -export { length_2 as length }; -/** - * @beta - * - * Creates an expression that checks if the first expression is less than the second expression. - * - * @example - * ```typescript - * // Check if the 'age' field is less than 30 - * lessThan(field("age"), field("limit")); - * ``` - * - * @param left - The first expression to compare. - * @param right - The second expression to compare. - * @returns A new `Expression` representing the less than comparison. - */ -export declare function lessThan(left: Expression, right: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an expression is less than a constant value. - * - * @example - * ```typescript - * // Check if the 'age' field is less than 30 - * lessThan(field("age"), 30); - * ``` - * - * @param expression - The expression to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the less than comparison. - */ -export declare function lessThan(expression: Expression, value: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is less than an expression. - * - * @example - * ```typescript - * // Check if the 'age' field is less than the 'limit' field - * lessThan("age", field("limit")); - * ``` - * - * @param fieldName - The field name to compare. - * @param expression - The expression to compare to. - * @returns A new `Expression` representing the less than comparison. - */ -export declare function lessThan(fieldName: string, expression: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is less than a constant value. - * - * @example - * ```typescript - * // Check if the 'price' field is less than 50 - * lessThan("price", 50); - * ``` - * - * @param fieldName - The field name to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the less than comparison. - */ -export declare function lessThan(fieldName: string, value: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if the first expression is less than or equal to the second - * expression. - * - * @example - * ```typescript - * // Check if the 'quantity' field is less than or equal to 20 - * lessThan(field("quantity"), field("limit")); - * ``` - * - * @param left - The first expression to compare. - * @param right - The second expression to compare. - * @returns A new `Expression` representing the less than or equal to comparison. - */ -export declare function lessThanOrEqual(left: Expression, right: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an expression is less than or equal to a constant value. - * - * @example - * ```typescript - * // Check if the 'quantity' field is less than or equal to 20 - * lessThan(field("quantity"), 20); - * ``` - * - * @param expression - The expression to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the less than or equal to comparison. - */ -export declare function lessThanOrEqual(expression: Expression, value: unknown): BooleanExpression; -/** - * @beta - * Creates an expression that checks if a field's value is less than or equal to an expression. - * - * @example - * ```typescript - * // Check if the 'quantity' field is less than or equal to the 'limit' field - * lessThan("quantity", field("limit")); - * ``` - * - * @param fieldName - The field name to compare. - * @param expression - The expression to compare to. - * @returns A new `Expression` representing the less than or equal to comparison. - */ -export declare function lessThanOrEqual(fieldName: string, expression: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is less than or equal to a constant value. - * - * @example - * ```typescript - * // Check if the 'score' field is less than or equal to 70 - * lessThan("score", 70); - * ``` - * - * @param fieldName - The field name to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the less than or equal to comparison. - */ -export declare function lessThanOrEqual(fieldName: string, value: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that performs a case-sensitive wildcard string comparison against a - * field. - * - * @example - * ```typescript - * // Check if the 'title' field contains the string "guide" - * like("title", "%guide%"); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @param pattern - The pattern to search for. You can use "%" as a wildcard character. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison. - */ -export declare function like(fieldName: string, pattern: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that performs a case-sensitive wildcard string comparison against a - * field. - * - * @example - * ```typescript - * // Check if the 'title' field contains the string "guide" - * like("title", field("pattern")); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @param pattern - The pattern to search for. You can use "%" as a wildcard character. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison. - */ -export declare function like(fieldName: string, pattern: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that performs a case-sensitive wildcard string comparison. - * - * @example - * ```typescript - * // Check if the 'title' field contains the string "guide" - * like(field("title"), "%guide%"); - * ``` - * - * @param stringExpression - The expression representing the string to perform the comparison on. - * @param pattern - The pattern to search for. You can use "%" as a wildcard character. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison. - */ -export declare function like(stringExpression: Expression, pattern: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that performs a case-sensitive wildcard string comparison. - * - * @example - * ```typescript - * // Check if the 'title' field contains the string "guide" - * like(field("title"), field("pattern")); - * ``` - * - * @param stringExpression - The expression representing the string to perform the comparison on. - * @param pattern - The pattern to search for. You can use "%" as a wildcard character. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'like' comparison. - */ -export declare function like(stringExpression: Expression, pattern: Expression): BooleanExpression; -/** - * @beta - * Options defining how a LimitStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(limit:1)}. - */ -export declare type LimitStageOptions = StageOptions & { - /** - * @beta - * The maximum number of documents to return. - */ - limit: number; -}; -/** - * @beta - * Creates an expression that computes the natural logarithm of a numeric value. - * - * @example - * ```typescript - * // Compute the natural logarithm of the 'value' field. - * ln("value"); - * ``` - * - * @param fieldName - The name of the field to compute the natural logarithm of. - * @returns A new `Expression` representing the natural logarithm of the numeric value. - */ -export declare function ln(fieldName: string): FunctionExpression; -/** - * @beta - * Creates an expression that computes the natural logarithm of a numeric value. - * - * @example - * ```typescript - * // Compute the natural logarithm of the 'value' field. - * ln(field("value")); - * ``` - * - * @param expression - An expression evaluating to a numeric value, which the natural logarithm will be computed for. - * @returns A new `Expression` representing the natural logarithm of the numeric value. - */ -export declare function ln(expression: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that computes the logarithm of an expression to a given base. - * - * @example - * ```typescript - * // Compute the logarithm of the 'value' field with base 10. - * log(field("value"), 10); - * ``` - * - * @param expression - An expression evaluating to a numeric value, which the logarithm will be computed for. - * @param base - The base of the logarithm. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value. - */ -export declare function log(expression: Expression, base: number): FunctionExpression; -/** - * @beta - * Creates an expression that computes the logarithm of an expression to a given base. - * - * @example - * ```typescript - * // Compute the logarithm of the 'value' field with the base in the 'base' field. - * log(field("value"), field("base")); - * ``` - * - * @param expression - An expression evaluating to a numeric value, which the logarithm will be computed for. - * @param base - The base of the logarithm. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value. - */ -export declare function log(expression: Expression, base: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that computes the logarithm of a field to a given base. - * - * @example - * ```typescript - * // Compute the logarithm of the 'value' field with base 10. - * log("value", 10); - * ``` - * - * @param fieldName - The name of the field to compute the logarithm of. - * @param base - The base of the logarithm. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value. - */ -export declare function log(fieldName: string, base: number): FunctionExpression; -/** - * @beta - * Creates an expression that computes the logarithm of a field to a given base. - * - * @example - * ```typescript - * // Compute the logarithm of the 'value' field with the base in the 'base' field. - * log("value", field("base")); - * ``` - * - * @param fieldName - The name of the field to compute the logarithm of. - * @param base - The base of the logarithm. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logarithm of the numeric value. - */ -export declare function log(fieldName: string, base: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that computes the base-10 logarithm of a numeric value. - * - * @example - * ```typescript - * // Compute the base-10 logarithm of the 'value' field. - * log10("value"); - * ``` - * - * @param fieldName - The name of the field to compute the base-10 logarithm of. - * @returns A new `Expression` representing the base-10 logarithm of the numeric value. - */ -export declare function log10(fieldName: string): FunctionExpression; -/** - * @beta - * Creates an expression that computes the base-10 logarithm of a numeric value. - * - * @example - * ```typescript - * // Compute the base-10 logarithm of the 'value' field. - * log10(field("value")); - * ``` - * - * @param expression - An expression evaluating to a numeric value, which the base-10 logarithm will be computed for. - * @returns A new `Expression` representing the base-10 logarithm of the numeric value. - */ -export declare function log10(expression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns the largest value between multiple input - * expressions or literal values. Based on Firestore's value type ordering. - * - * @example - * ```typescript - * // Returns the largest value between the 'field1' field, the 'field2' field, - * // and 1000 - * logicalMaximum(field("field1"), field("field2"), 1000); - * ``` - * - * @param first - The first operand expression. - * @param second - The second expression or literal. - * @param others - Optional additional expressions or literals. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical maximum operation. - */ -export declare function logicalMaximum(first: Expression, second: Expression | unknown, ...others: Array): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns the largest value between multiple input - * expressions or literal values. Based on Firestore's value type ordering. - * - * @example - * ```typescript - * // Returns the largest value between the 'field1' field, the 'field2' field, - * // and 1000. - * logicalMaximum("field1", field("field2"), 1000); - * ``` - * - * @param fieldName - The first operand field name. - * @param second - The second expression or literal. - * @param others - Optional additional expressions or literals. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical maximum operation. - */ -export declare function logicalMaximum(fieldName: string, second: Expression | unknown, ...others: Array): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns the smallest value between multiple input - * expressions and literal values. Based on Firestore's value type ordering. - * - * @example - * ```typescript - * // Returns the smallest value between the 'field1' field, the 'field2' field, - * // and 1000. - * logicalMinimum(field("field1"), field("field2"), 1000); - * ``` - * - * @param first - The first operand expression. - * @param second - The second expression or literal. - * @param others - Optional additional expressions or literals. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical minimum operation. - */ -export declare function logicalMinimum(first: Expression, second: Expression | unknown, ...others: Array): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns the smallest value between a field's value - * and other input expressions or literal values. - * Based on Firestore's value type ordering. - * - * @example - * ```typescript - * // Returns the smallest value between the 'field1' field, the 'field2' field, - * // and 1000. - * logicalMinimum("field1", field("field2"), 1000); - * ``` - * - * @param fieldName - The first operand field name. - * @param second - The second expression or literal. - * @param others - Optional additional expressions or literals. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical minimum operation. - */ -export declare function logicalMinimum(fieldName: string, second: Expression | unknown, ...others: Array): FunctionExpression; -/** - * @beta - * Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array. - * - * @example - * ```typescript - * // Trim whitespace from the beginning of the 'userInput' field - * ltrim(field("userInput")); - * - * // Trim quotes from the beginning of the 'userInput' field - * ltrim(field("userInput"), '"'); - * ``` - * - * @param fieldName - The name of the field containing the string or byte array. - * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim. - * If not specified, whitespace will be trimmed. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array. - */ -export declare function ltrim(fieldName: string, valueToTrim?: string | Expression | Bytes): FunctionExpression; -/** - * @beta - * Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array. - * - * @example - * ```typescript - * // Trim whitespace from the beginning of the 'userInput' field - * ltrim(field("userInput")); - * - * // Trim quotes from the beginning of the 'userInput' field - * ltrim(field("userInput"), '"'); - * ``` - * - * @param expression - The expression representing the string or byte array. - * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim. - * If not specified, whitespace will be trimmed. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array. - */ -export declare function ltrim(expression: Expression, valueToTrim?: string | Expression | Bytes): FunctionExpression; -/** - * @beta - * - * Creates an expression that creates a Firestore map value from an input object. - * - * @example - * ```typescript - * // Create a map from the input object and reference the 'baz' field value from the input document. - * map({foo: 'bar', baz: Field.of('baz')}).as('data'); - * ``` - * - * @param elements - The input map to evaluate in the expression. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the map function. - */ -export declare function map(elements: Record): FunctionExpression; -/** - * @beta - * Creates an expression that returns the entries of a map as an array of maps, - * where each map contains a `"k"` property for the key and a `"v"` property for the value. - * For example: `[{ k: "key1", v: "value1" }, ...]`. - * - * @remarks - * While the backend generally preserves insertion order, relying on the - * order of the output array is not guaranteed and should be avoided. - * - * @example - * ```typescript - * // Get the entries of the 'address' map field - * mapEntries("address"); - * ``` - * - * @param mapField - The map field to get the entries of. - * @returns A new `Expression` representing the entries of the map. - */ -export declare function mapEntries(mapField: string): FunctionExpression; -/** - * @beta - * Creates an expression that returns the entries of a map as an array of maps, - * where each map contains a `"k"` property for the key and a `"v"` property for the value. - * For example: `[{ k: "key1", v: "value1" }, ...]`. - * - * @remarks - * While the backend generally preserves insertion order, relying on the - * order of the output array is not guaranteed and should be avoided. - * - * @example - * ```typescript - * // Get the entries of the map expression - * mapEntries(map({"city": "San Francisco"})); - * ``` - * - * @param mapExpression - The expression representing the map to get the entries of. - * @returns A new `Expression` representing the entries of the map. - */ -export declare function mapEntries(mapExpression: Expression): FunctionExpression; -/** - * @beta - * - * Accesses a value from a map (object) field using the provided key. - * - * @example - * ```typescript - * // Get the 'city' value from the 'address' map field - * mapGet("address", "city"); - * ``` - * - * @param fieldName - The field name of the map field. - * @param subField - The key to access in the map. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the value associated with the given key in the map. - */ -export declare function mapGet(fieldName: string, subField: string): FunctionExpression; -/** - * @beta - * - * Accesses a value from a map (object) expression using the provided key. - * - * @example - * ```typescript - * // Get the 'city' value from the 'address' map field - * mapGet(field("address"), "city"); - * ``` - * - * @param mapExpression - The expression representing the map. - * @param subField - The key to access in the map. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the value associated with the given key in the map. - */ -export declare function mapGet(mapExpression: Expression, subField: string): FunctionExpression; -/** - * @beta - * Creates an expression that returns the keys of a map. - * - * @remarks - * While the backend generally preserves insertion order, relying on the - * order of the output array is not guaranteed and should be avoided. - * - * @example - * ```typescript - * // Get the keys of the 'address' map field - * mapKeys("address"); - * ``` - * - * @param mapField - The map field to get the keys of. - * @returns A new `Expression` representing the keys of the map. - */ -export declare function mapKeys(mapField: string): FunctionExpression; -/** - * @beta - * Creates an expression that returns the keys of a map. - * - * @remarks - * While the backend generally preserves insertion order, relying on the - * order of the output array is not guaranteed and should be avoided. - * - * @example - * ```typescript - * // Get the keys of the map expression - * mapKeys(map({"city": "San Francisco"})); - * ``` - * - * @param mapExpression - The expression representing the map to get the keys of. - * @returns A new `Expression` representing the keys of the map. - */ -export declare function mapKeys(mapExpression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that merges multiple map values. - * - * @example - * ``` - * // Merges the map in the settings field with, a map literal, and a map in - * // that is conditionally returned by another expression - * mapMerge('settings', { enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) - * ``` - * - * @param mapField - Name of a field containing a map value that will be merged. - * @param secondMap - A required second map to merge. Represented as a literal or - * an expression that returns a map. - * @param otherMaps - Optional additional maps to merge. Each map is represented - * as a literal or an expression that returns a map. - */ -export declare function mapMerge(mapField: string, secondMap: Record | Expression, ...otherMaps: Array | Expression>): FunctionExpression; -/** - * @beta - * - * Creates an expression that merges multiple map values. - * - * @example - * ``` - * // Merges the map in the settings field with, a map literal, and a map in - * // that is conditionally returned by another expression - * mapMerge(field('settings'), { enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) - * ``` - * - * @param firstMap - An expression or literal map value that will be merged. - * @param secondMap - A required second map to merge. Represented as a literal or - * an expression that returns a map. - * @param otherMaps - Optional additional maps to merge. Each map is represented - * as a literal or an expression that returns a map. - */ -export declare function mapMerge(firstMap: Record | Expression, secondMap: Record | Expression, ...otherMaps: Array | Expression>): FunctionExpression; -/** - * @beta - * - * Creates an expression that removes a key from the map at the specified field name. - * - * @example - * ``` - * // Removes the key 'city' field from the map in the address field of the input document. - * mapRemove('address', 'city'); - * ``` - * - * @param mapField - The name of a field containing a map value. - * @param key - The name of the key to remove from the input map. - */ -export declare function mapRemove(mapField: string, key: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that removes a key from the map produced by evaluating an expression. - * - * @example - * ``` - * // Removes the key 'baz' from the input map. - * mapRemove(map({foo: 'bar', baz: true}), 'baz'); - * @example - * ``` - * - * @param mapExpr - An expression return a map value. - * @param key - The name of the key to remove from the input map. - */ -export declare function mapRemove(mapExpr: Expression, key: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that removes a key from the map at the specified field name. - * - * @example - * ``` - * // Removes the key 'city' field from the map in the address field of the input document. - * mapRemove('address', constant('city')); - * ``` - * - * @param mapField - The name of a field containing a map value. - * @param keyExpr - An expression that produces the name of the key to remove from the input map. - */ -export declare function mapRemove(mapField: string, keyExpr: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that removes a key from the map produced by evaluating an expression. - * - * @example - * ``` - * // Removes the key 'baz' from the input map. - * mapRemove(map({foo: 'bar', baz: true}), constant('baz')); - * @example - * ``` - * - * @param mapExpr - An expression return a map value. - * @param keyExpr - An expression that produces the name of the key to remove from the input map. - */ -export declare function mapRemove(mapExpr: Expression, keyExpr: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that returns a new map with the specified entries added or updated. - * - * @remarks - * This only performs shallow updates to the map. Setting a value to `null` - * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`. - * - * @example - * ```typescript - * // Set the 'city' to 'San Francisco' in the 'address' map field - * mapSet("address", "city", "San Francisco"); - * ``` - * - * @param mapField - The map field to set entries in. - * @param key - The key to set. Must be a string or a constant string expression. - * @param value - The value to set. - * @param moreKeyValues - Additional key-value pairs to set. - * @returns A new `Expression` representing the map with the entries set. - */ -export declare function mapSet(mapField: string, key: string | Expression, value: unknown, ...moreKeyValues: unknown[]): FunctionExpression; -/** - * @beta - * Creates an expression that returns a new map with the specified entries added or updated. - * - * @remarks - * This only performs shallow updates to the map. Setting a value to `null` - * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`. - * - * @example - * ```typescript - * // Set the 'city' to "San Francisco" - * mapSet(map({"state": "California"}), "city", "San Francisco"); - * ``` - * - * @param mapExpression - The expression representing the map. - * @param key - The key to set. Must be a string or a constant string expression. - * @param value - The value to set. - * @param moreKeyValues - Additional key-value pairs to set. - * @returns A new `Expression` representing the map with the entries set. - */ -export declare function mapSet(mapExpression: Expression, key: string | Expression, value: unknown, ...moreKeyValues: unknown[]): FunctionExpression; -/** - * @beta - * Creates an expression that returns the values of a map. - * - * @remarks - * While the backend generally preserves insertion order, relying on the - * order of the output array is not guaranteed and should be avoided. - * - * @example - * ```typescript - * // Get the values of the 'address' map field - * mapValues("address"); - * ``` - * - * @param mapField - The map field to get the values of. - * @returns A new `Expression` representing the values of the map. - */ -export declare function mapValues(mapField: string): FunctionExpression; -/** - * @beta - * Creates an expression that returns the values of a map. - * - * @remarks - * While the backend generally preserves insertion order, relying on the - * order of the output array is not guaranteed and should be avoided. - * - * @example - * ```typescript - * // Get the values of the map expression - * mapValues(map({"city": "San Francisco"})); - * ``` - * - * @param mapExpression - The expression representing the map to get the values of. - * @returns A new `Expression` representing the values of the map. - */ -export declare function mapValues(mapExpression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an aggregation that finds the maximum value of an expression across multiple stage - * inputs. - * - * @example - * ```typescript - * // Find the highest score in a leaderboard - * maximum(field("score")).as("highestScore"); - * ``` - * - * @param expression - The expression to find the maximum value of. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'maximum' aggregation. - */ -export declare function maximum(expression: Expression): AggregateFunction; -/** - * @beta - * - * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. - * - * @example - * ```typescript - * // Find the highest score in a leaderboard - * maximum("score").as("highestScore"); - * ``` - * - * @param fieldName - The name of the field to find the maximum value of. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'maximum' aggregation. - */ -export declare function maximum(fieldName: string): AggregateFunction; -/** - * @beta - * - * Creates an aggregation that finds the minimum value of an expression across multiple stage - * inputs. - * - * @example - * ```typescript - * // Find the lowest price of all products - * minimum(field("price")).as("lowestPrice"); - * ``` - * - * @param expression - The expression to find the minimum value of. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'minimum' aggregation. - */ -export declare function minimum(expression: Expression): AggregateFunction; -/** - * @beta - * - * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. - * - * @example - * ```typescript - * // Find the lowest price of all products - * minimum("price").as("lowestPrice"); - * ``` - * - * @param fieldName - The name of the field to find the minimum value of. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'minimum' aggregation. - */ -export declare function minimum(fieldName: string): AggregateFunction; -/** - * @beta - * - * Creates an expression that calculates the modulo (remainder) of dividing two expressions. - * - * @example - * ```typescript - * // Calculate the remainder of dividing 'field1' by 'field2'. - * mod(field("field1"), field("field2")); - * ``` - * - * @param left - The dividend expression. - * @param right - The divisor expression. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation. - */ -export declare function mod(left: Expression, right: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant. - * - * @example - * ```typescript - * // Calculate the remainder of dividing 'field1' by 5. - * mod(field("field1"), 5); - * ``` - * - * @param expression - The dividend expression. - * @param value - The divisor constant. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation. - */ -export declare function mod(expression: Expression, value: unknown): FunctionExpression; -/** - * @beta - * - * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression. - * - * @example - * ```typescript - * // Calculate the remainder of dividing 'field1' by 'field2'. - * mod("field1", field("field2")); - * ``` - * - * @param fieldName - The dividend field name. - * @param expression - The divisor expression. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation. - */ -export declare function mod(fieldName: string, expression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant. - * - * @example - * ```typescript - * // Calculate the remainder of dividing 'field1' by 5. - * mod("field1", 5); - * ``` - * - * @param fieldName - The dividend field name. - * @param value - The divisor constant. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the modulo operation. - */ -export declare function mod(fieldName: string, value: unknown): FunctionExpression; -/** - * @beta - * - * Creates an expression that multiplies two expressions together. - * - * @example - * ```typescript - * // Multiply the 'quantity' field by the 'price' field - * multiply(field("quantity"), field("price")); - * ``` - * - * @param first - The first expression to multiply. - * @param second - The second expression or literal to multiply. - * @param others - Optional additional expressions or literals to multiply. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the multiplication operation. - */ -export declare function multiply(first: Expression, second: Expression | unknown): FunctionExpression; -/** - * @beta - * - * Creates an expression that multiplies a field's value by an expression. - * - * @example - * ```typescript - * // Multiply the 'quantity' field by the 'price' field - * multiply("quantity", field("price")); - * ``` - * - * @param fieldName - The name of the field containing the value to add. - * @param second - The second expression or literal to add. - * @param others - Optional other expressions or literals to add. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the multiplication operation. - */ -export declare function multiply(fieldName: string, second: Expression | unknown): FunctionExpression; -/** - * @beta - * - * Creates an expression that negates a filter condition. - * - * @example - * ```typescript - * // Find documents where the 'completed' field is NOT true - * not(equal("completed", true)); - * ``` - * - * @param booleanExpr - The filter condition to negate. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the negated filter condition. - */ -export declare function not(booleanExpr: BooleanExpression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if two expressions are not equal. - * - * @example - * ```typescript - * // Check if the 'status' field is not equal to field 'finalState' - * notEqual(field("status"), field("finalState")); - * ``` - * - * @param left - The first expression to compare. - * @param right - The second expression to compare. - * @returns A new `Expression` representing the inequality comparison. - */ -export declare function notEqual(left: Expression, right: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an expression is not equal to a constant value. - * - * @example - * ```typescript - * // Check if the 'status' field is not equal to "completed" - * notEqual(field("status"), "completed"); - * ``` - * - * @param expression - The expression to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the inequality comparison. - */ -export declare function notEqual(expression: Expression, value: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is not equal to an expression. - * - * @example - * ```typescript - * // Check if the 'status' field is not equal to the value of 'expectedStatus' - * notEqual("status", field("expectedStatus")); - * ``` - * - * @param fieldName - The field name to compare. - * @param expression - The expression to compare to. - * @returns A new `Expression` representing the inequality comparison. - */ -export declare function notEqual(fieldName: string, expression: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is not equal to a constant value. - * - * @example - * ```typescript - * // Check if the 'country' field is not equal to "USA" - * notEqual("country", "USA"); - * ``` - * - * @param fieldName - The field name to compare. - * @param value - The constant value to compare to. - * @returns A new `Expression` representing the inequality comparison. - */ -export declare function notEqual(fieldName: string, value: unknown): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an expression is not equal to any of the provided values - * or expressions. - * - * @example - * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqualAny(field("status"), ["pending", field("rejectedStatus")]); - * ``` - * - * @param element - The expression to compare. - * @param values - The values to check against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison. - */ -export declare function notEqualAny(element: Expression, values: Array): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is not equal to any of the provided values - * or expressions. - * - * @example - * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqualAny("status", [constant("pending"), field("rejectedStatus")]); - * ``` - * - * @param fieldName - The field name to compare. - * @param values - The values to check against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison. - */ -export declare function notEqualAny(fieldName: string, values: Array): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if an expression is not equal to any of the provided values - * or expressions. - * - * @example - * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of the field 'rejectedStatus' - * notEqualAny(field("status"), ["pending", field("rejectedStatus")]); - * ``` - * - * @param element - The expression to compare. - * @param arrayExpression - The values to check against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison. - */ -export declare function notEqualAny(element: Expression, arrayExpression: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression. - * - * @example - * ```typescript - * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' - * notEqualAny("status", field("rejectedStatuses")); - * ``` - * - * @param fieldName - The field name to compare. - * @param arrayExpression - The values to check against. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'NOT IN' comparison. - */ -export declare function notEqualAny(fieldName: string, arrayExpression: Expression): BooleanExpression; -/** - * @beta - * Options defining how an OffsetStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(offset:1)}. - */ -export declare type OffsetStageOptions = StageOptions & { - /** - * @beta - * The number of documents to skip. - */ - offset: number; -}; -/** - * @beta - * Utility type to create an type that only allows one - * property of the Type param T to be set. - * - * @example - * ``` - * type XorY = OneOf<{ x: unknown, y: unknown }> - * let a = { x: "foo" } // OK - * let b = { y: "foo" } // OK - * let c = { a: "foo", y: "foo" } // Not OK - * ``` - */ -export declare type OneOf = { - [K in keyof T]: Pick & { - [P in Exclude]?: undefined; - }; -}[keyof T]; -/** - * @beta - * - * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. - * - * @example - * ```typescript - * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR - * // the 'status' field is "active" - * const condition = or(greaterThan("age", 18), equal("city", "London"), equal("status", "active")); - * ``` - * - * @param first - The first filter condition. - * @param second - The second filter condition. - * @param more - Additional filter conditions to 'OR' together. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'OR' operation. - */ -export declare function or(first: BooleanExpression, second: BooleanExpression, ...more: BooleanExpression[]): BooleanExpression; -/** - * @beta - * - * Represents an ordering criterion for sorting documents in a Firestore pipeline. - * - * You create `Ordering` instances using the `ascending` and `descending` helper functions. - */ -export declare class Ordering { - readonly expr: Expression; - readonly direction: 'ascending' | 'descending'; - constructor(expr: Expression, direction: 'ascending' | 'descending', _methodName: string | undefined); -} -/** - * @beta - */ -export declare class Pipeline { - addFields(field: Selectable, ...additionalFields: Selectable[]): Pipeline; - addFields(options: AddFieldsStageOptions): Pipeline; - removeFields(fieldValue: Field | string, ...additionalFields: Array): Pipeline; - removeFields(options: RemoveFieldsStageOptions): Pipeline; - select(selection: Selectable | string, ...additionalSelections: Array): Pipeline; - select(options: SelectStageOptions): Pipeline; - where(condition: BooleanExpression): Pipeline; - where(options: WhereStageOptions): Pipeline; - offset(offset: number): Pipeline; - offset(options: OffsetStageOptions): Pipeline; - limit(limit: number): Pipeline; - limit(options: LimitStageOptions): Pipeline; - distinct(group: string | Selectable, ...additionalGroups: Array): Pipeline; - distinct(options: DistinctStageOptions): Pipeline; - aggregate(accumulator: AliasedAggregate, ...additionalAccumulators: AliasedAggregate[]): Pipeline; - aggregate(options: AggregateStageOptions): Pipeline; - findNearest(options: FindNearestStageOptions): Pipeline; - sort(ordering: Ordering, ...additionalOrderings: Ordering[]): Pipeline; - sort(options: SortStageOptions): Pipeline; - replaceWith(fieldName: string): Pipeline; - replaceWith(expr: Expression): Pipeline; - replaceWith(options: ReplaceWithStageOptions): Pipeline; - sample(documents: number): Pipeline; - sample(options: SampleStageOptions): Pipeline; - union(other: Pipeline): Pipeline; - union(options: UnionStageOptions): Pipeline; - unnest(selectable: Selectable, indexField?: string): Pipeline; - unnest(options: UnnestStageOptions): Pipeline; - rawStage(name: string, params: unknown[], options?: { [key: string]: Expression | unknown; }): Pipeline; -} -/** - * @beta - * Options defining Pipeline execution. - */ -export declare interface PipelineExecuteOptions { - /** - * @beta - * Pipeline to be evaluated. - */ - pipeline: Pipeline; - /** - * @beta - * Specify the index mode. - */ - indexMode?: 'recommended'; - /** - * @beta - * An escape hatch to set options not known at SDK build time. These values - * will be passed directly to the Firestore backend and not used by the SDK. - * - * The option name will be used as provided. And must match the name - * format used by the backend (hint: use a snake_case_name). - * - * Custom option values can be any type supported - * by Firestore (for example: string, boolean, number, map, …). Value types - * not known to the SDK will be rejected. - * - * Values specified in rawOptions will take precedence over any options - * with the same name set by the SDK. - * - * @example - * Override the `example_option`: - * ``` - * execute({ - * pipeline: myPipeline, - * rawOptions: { - * // Override `example_option`. This will not - * // merge with the existing `example_option` object. - * "example_option": { - * foo: "bar" - * } - * } - * } - * ``` - * - * `rawOptions` supports dot notation, if you want to override - * a nested option. - * ``` - * execute({ - * pipeline: myPipeline, - * rawOptions: { - * // Override `example_option.foo` and do not override - * // any other properties of `example_option`. - * "example_option.foo": "bar" - * } - * } - * ``` - */ - rawOptions?: { - [name: string]: unknown; - }; -} -/** - * @beta - * - * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the - * {@link @firebase/firestore/pipelines#PipelineResult.data} or {@link @firebase/firestore/pipelines#PipelineResult.(get:1)} methods. - * - *

If the PipelineResult represents a non-document result, `ref` will return a undefined - * value. - */ -export declare class PipelineResult { - /* Excluded from this release type: _ref */ - /* Excluded from this release type: _fields */ - /* Excluded from this release type: __constructor */ - /** - * @beta - * The reference of the document, if it is a document; otherwise `undefined`. - */ - get ref(): DocumentReference | undefined; - /** - * @beta - * The ID of the document for which this PipelineResult contains data, if it is a document; otherwise `undefined`. - * - * @readonly - * - */ - get id(): string | undefined; - /** - * @beta - * The time the document was created. Undefined if this result is not a document. - * - * @readonly - */ - get createTime(): Timestamp | undefined; - /** - * @beta - * The time the document was last updated (at the time the snapshot was - * generated). Undefined if this result is not a document. - * - * @readonly - */ - get updateTime(): Timestamp | undefined; - /** - * @beta - * Retrieves all fields in the result as an object. - * - * @returns An object containing all fields in the document or - * 'undefined' if the document doesn't exist. - * - * @example - * ``` - * let p = firestore.pipeline().collection('col'); - * - * p.execute().then(results => { - * let data = results[0].data(); - * console.log(`Retrieved data: ${JSON.stringify(data)}`); - * }); - * ``` - */ - data(): AppModelType; - /* Excluded from this release type: _fieldsProto */ - /** - * @beta - * Retrieves the field specified by `field`. - * - * @param field - The field path - * (e.g. 'foo' or 'foo.bar') to a specific field. - * @returns The data at the specified field location or `undefined` if no - * such field exists. - * - * @example - * ``` - * let p = firestore.pipeline().collection('col'); - * - * p.execute().then(results => { - * let field = results[0].get('a.b'); - * console.log(`Retrieved field value: ${field}`); - * }); - * ``` - */ - get(fieldPath: string | FieldPath | Field): any; -} -/** - * @beta - * Test equality of two PipelineResults. - * @param left - First PipelineResult to compare. - * @param right - Second PipelineResult to compare. - */ -export declare function pipelineResultEqual(left: PipelineResult, right: PipelineResult): boolean; -/** - * @beta - * Represents the results of a Firestore pipeline execution. - * - * A `PipelineSnapshot` contains zero or more {@link @firebase/firestore/pipelines#PipelineResult} objects - * representing the documents returned by a pipeline query. It provides methods - * to iterate over the documents and access metadata about the query results. - * - * @example - * ```typescript - * const snapshot: PipelineSnapshot = await firestore - * .pipeline() - * .collection('myCollection') - * .where(field('value').greaterThan(10)) - * .execute(); - * - * snapshot.results.forEach(doc => { - * console.log(doc.id, '=>', doc.data()); - * }); - * ``` - */ -export declare class PipelineSnapshot { - constructor(pipeline: Pipeline, results: PipelineResult[], executionTime?: Timestamp); - /** - * @beta An array of all the results in the `PipelineSnapshot`. - */ - get results(): PipelineResult[]; - /** - * @beta - * The time at which the pipeline producing this result is executed. - * - * @readonly - * - */ - get executionTime(): Timestamp; -} -/** - * @beta - * Provides the entry point for defining the data source of a Firestore {@link @firebase/firestore/pipelines#Pipeline}. - * - * Use the methods of this class (e.g., {@link @firebase/firestore/pipelines#PipelineSource.(collection:1)}, {@link @firebase/firestore/pipelines#PipelineSource.(collectionGroup:1)}, - * {@link @firebase/firestore/pipelines#PipelineSource.(database:1)}, or {@link @firebase/firestore/pipelines#PipelineSource.(documents:1)}) to specify the initial data - * for your pipeline, such as a collection, a collection group, the entire database, or a set of specific documents. - */ -export declare class PipelineSource { - private databaseId; - private userDataReader; - /* Excluded from this release type: _createPipeline */ - /* Excluded from this release type: __constructor */ - /** - * @beta - * Returns all documents from the entire collection. The collection can be nested. - * @param collection - Name or reference to the collection that will be used as the Pipeline source. - */ - collection(collection: string | Query): PipelineType; - /** - * @beta - * Returns all documents from the entire collection. The collection can be nested. - * @param options - Options defining how this CollectionStage is evaluated. - */ - collection(options: CollectionStageOptions): PipelineType; - /** - * @beta - * Returns all documents from a collection ID regardless of the parent. - * @param collectionId - ID of the collection group to use as the Pipeline source. - */ - collectionGroup(collectionId: string): PipelineType; - /** - * @beta - * Returns all documents from a collection ID regardless of the parent. - * @param options - Options defining how this CollectionGroupStage is evaluated. - */ - collectionGroup(options: CollectionGroupStageOptions): PipelineType; - /** - * @beta - * Returns all documents from the entire database. - */ - database(): PipelineType; - /** - * @beta - * Returns all documents from the entire database. - * @param options - Options defining how a DatabaseStage is evaluated. - */ - database(options: DatabaseStageOptions): PipelineType; - /** - * @beta - * Set the pipeline's source to the documents specified by the given paths and DocumentReferences. - * - * @param docs - An array of paths and DocumentReferences specifying the individual documents that will be the source of this pipeline. - * The converters for these DocumentReferences will be ignored and not have an effect on this pipeline. - * - * @throws `FirestoreError` Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. - */ - documents(docs: Array): PipelineType; - /** - * @beta - * Set the pipeline's source to the documents specified by the given paths and DocumentReferences. - * - * @param options - Options defining how this DocumentsStage is evaluated. - * - * @throws `FirestoreError` Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. - */ - documents(options: DocumentsStageOptions): PipelineType; - /** - * @beta - * Convert the given Query into an equivalent Pipeline. - * - * @param query - A Query to be converted into a Pipeline. - * - * @throws `FirestoreError` Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. - */ - createFrom(query: Query): Pipeline; -} -/** - * @beta - * Creates an expression that returns the value of the base expression raised to the power of the exponent expression. - * - * @example - * ```typescript - * // Raise the value of the 'base' field to the power of the 'exponent' field. - * pow(field("base"), field("exponent")); - * ``` - * - * @param base - The expression to raise to the power of the exponent. - * @param exponent - The expression to raise the base to the power of. - * @returns A new `Expression` representing the power operation. - */ -export declare function pow(base: Expression, exponent: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that returns the value of the base expression raised to the power of the exponent. - * - * @example - * ```typescript - * // Raise the value of the 'base' field to the power of 2. - * pow(field("base"), 2); - * ``` - * - * @param base - The expression to raise to the power of the exponent. - * @param exponent - The constant value to raise the base to the power of. - * @returns A new `Expression` representing the power operation. - */ -export declare function pow(base: Expression, exponent: number): FunctionExpression; -/** - * @beta - * Creates an expression that returns the value of the base field raised to the power of the exponent expression. - * - * @example - * ```typescript - * // Raise the value of the 'base' field to the power of the 'exponent' field. - * pow("base", field("exponent")); - * ``` - * - * @param base - The name of the field to raise to the power of the exponent. - * @param exponent - The expression to raise the base to the power of. - * @returns A new `Expression` representing the power operation. - */ -export declare function pow(base: string, exponent: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that returns the value of the base field raised to the power of the exponent. - * - * @example - * ```typescript - * // Raise the value of the 'base' field to the power of 2. - * pow("base", 2); - * ``` - * - * @param base - The name of the field to raise to the power of the exponent. - * @param exponent - The constant value to raise the base to the power of. - * @returns A new `Expression` representing the power operation. - */ -export declare function pow(base: string, exponent: number): FunctionExpression; -/** - * @beta - * - * Creates an expression that generates a random number between 0.0 and 1.0 but not including 1.0. - * - * @example - * ```typescript - * // Generate a random number between 0.0 and 1.0. - * rand(); - * ``` - * - * @returns A new `Expression` representing the rand operation. - */ -export declare function rand(): FunctionExpression; -/** - * @beta - * - * Creates an expression that checks if a string field contains a specified regular expression as - * a substring. - * - * @example - * ```typescript - * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains("description", "(?i)example"); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @param pattern - The regular expression to use for the search. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison. - */ -export declare function regexContains(fieldName: string, pattern: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string field contains a specified regular expression as - * a substring. - * - * @example - * ```typescript - * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains("description", field("pattern")); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @param pattern - The regular expression to use for the search. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison. - */ -export declare function regexContains(fieldName: string, pattern: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string expression contains a specified regular - * expression as a substring. - * - * @example - * ```typescript - * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains(field("description"), "(?i)example"); - * ``` - * - * @param stringExpression - The expression representing the string to perform the comparison on. - * @param pattern - The regular expression to use for the search. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison. - */ -export declare function regexContains(stringExpression: Expression, pattern: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string expression contains a specified regular - * expression as a substring. - * - * @example - * ```typescript - * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains(field("description"), field("pattern")); - * ``` - * - * @param stringExpression - The expression representing the string to perform the comparison on. - * @param pattern - The regular expression to use for the search. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison. - */ -export declare function regexContains(stringExpression: Expression, pattern: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that returns the first substring of a string field that matches a - * specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract the domain name from an email field - * regexFind("email", "@[A-Za-z0-9.-]+"); - * ``` - * - * @param fieldName - The name of the field containing the string to search. - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function. - */ -export declare function regexFind(fieldName: string, pattern: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns the first substring of a string field that matches a - * specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract a substring from 'email' based on a pattern stored in another field - * regexFind("email", field("pattern")); - * ``` - * - * @param fieldName - The name of the field containing the string to search. - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function. - */ -export declare function regexFind(fieldName: string, pattern: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns the first substring of a string expression that matches - * a specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract the domain from a lower-cased email address - * regexFind(field("email"), "@[A-Za-z0-9.-]+"); - * ``` - * - * @param stringExpression - The expression representing the string to search. - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function. - */ -export declare function regexFind(stringExpression: Expression, pattern: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns the first substring of a string expression that matches - * a specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract a substring based on a dynamic pattern field - * regexFind(field("email"), field("pattern")); - * ``` - * - * @param stringExpression - The expression representing the string to search. - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression find function. - */ -export declare function regexFind(stringExpression: Expression, pattern: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that evaluates to a list of all substrings in a string field that - * match a specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract all hashtags from a post content field - * regexFindAll("content", "#[A-Za-z0-9_]+"); - * ``` - * - * @param fieldName - The name of the field containing the string to search. - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings. - */ -export declare function regexFindAll(fieldName: string, pattern: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that evaluates to a list of all substrings in a string field that - * match a specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract all matches from 'content' based on a pattern stored in another field - * regexFindAll("content", field("pattern")); - * ``` - * - * @param fieldName - The name of the field containing the string to search. - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings. - */ -export declare function regexFindAll(fieldName: string, pattern: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that evaluates to a list of all substrings in a string expression - * that match a specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract all mentions from a lower-cased comment - * regexFindAll(field("comment"), "@[A-Za-z0-9_]+"); - * ``` - * - * @param stringExpression - The expression representing the string to search. - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings. - */ -export declare function regexFindAll(stringExpression: Expression, pattern: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that evaluates to a list of all substrings in a string expression - * that match a specified regular expression. - * - * This expression uses the {@link https://github.com/google/re2/wiki/Syntax | RE2} regular expression syntax. - * - * @example - * ```typescript - * // Extract all matches based on a dynamic pattern expression - * regexFindAll(field("comment"), field("pattern")); - * ``` - * - * @param stringExpression - The expression representing the string to search. - * @param pattern - The regular expression to search for. - * @returns A new {@link @firebase/firestore/pipelines#FunctionExpression} that evaluates to an array of matched substrings. - */ -export declare function regexFindAll(stringExpression: Expression, pattern: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that checks if a string field matches a specified regular expression. - * - * @example - * ```typescript - * // Check if the 'email' field matches a valid email pattern - * regexMatch("email", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @param pattern - The regular expression to use for the match. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match. - */ -export declare function regexMatch(fieldName: string, pattern: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string field matches a specified regular expression. - * - * @example - * ```typescript - * // Check if the 'email' field matches a valid email pattern - * regexMatch("email", field("pattern")); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @param pattern - The regular expression to use for the match. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match. - */ -export declare function regexMatch(fieldName: string, pattern: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string expression matches a specified regular - * expression. - * - * @example - * ```typescript - * // Check if the 'email' field matches a valid email pattern - * regexMatch(field("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); - * ``` - * - * @param stringExpression - The expression representing the string to match against. - * @param pattern - The regular expression to use for the match. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match. - */ -export declare function regexMatch(stringExpression: Expression, pattern: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string expression matches a specified regular - * expression. - * - * @example - * ```typescript - * // Check if the 'email' field matches a valid email pattern - * regexMatch(field("email"), field("pattern")); - * ``` - * - * @param stringExpression - The expression representing the string to match against. - * @param pattern - The regular expression to use for the match. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the regular expression match. - */ -export declare function regexMatch(stringExpression: Expression, pattern: Expression): BooleanExpression; -/** - * @beta - * Options defining how a RemoveFieldsStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(removeFields:1)}. - */ -export declare type RemoveFieldsStageOptions = StageOptions & { - /** - * @beta - * The fields to remove from each document. - */ - fields: Array; -}; -/** - * @beta - * Options defining how a ReplaceWithStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(replaceWith:1)}. - */ -export declare type ReplaceWithStageOptions = StageOptions & { - /** - * @beta - * The name of a field that contains a map or an {@link @firebase/firestore/pipelines#Expression} that - * evaluates to a map. - */ - map: Expression | string; -}; -/* Excluded from this release type: ResourcePath */ -/** - * @beta - * - * Creates an expression that reverses a string. - * - * @example - * ```typescript - * // Reverse the value of the 'myString' field. - * reverse(field("myString")); - * ``` - * - * @param stringExpression - An expression evaluating to a string value, which will be reversed. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string. - */ -export declare function reverse(stringExpression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that reverses a string value in the specified field. - * - * @example - * ```typescript - * // Reverse the value of the 'myString' field. - * reverse("myString"); - * ``` - * - * @param field - The name of the field representing the string to reverse. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string. - */ -export declare function reverse(field: string): FunctionExpression; -/** - * @beta - * Creates an expression that rounds a numeric value to the nearest whole number. - * - * @example - * ```typescript - * // Round the value of the 'price' field. - * round("price"); - * ``` - * - * @param fieldName - The name of the field to round. - * @returns A new `Expression` representing the rounded value. - */ -export declare function round(fieldName: string): FunctionExpression; -/** - * @beta - * Creates an expression that rounds a numeric value to the nearest whole number. - * - * @example - * ```typescript - * // Round the value of the 'price' field. - * round(field("price")); - * ``` - * - * @param expression - An expression evaluating to a numeric value, which will be rounded. - * @returns A new `Expression` representing the rounded value. - */ -export declare function round(expression: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that rounds a numeric value to the specified number of decimal places. - * - * @example - * ```typescript - * // Round the value of the 'price' field to two decimal places. - * round("price", 2); - * ``` - * - * @param fieldName - The name of the field to round. - * @param decimalPlaces - A constant or expression specifying the rounding precision in decimal places. - * @returns A new `Expression` representing the rounded value. - */ -export declare function round(fieldName: string, decimalPlaces: number | Expression): FunctionExpression; -/** - * @beta - * Creates an expression that rounds a numeric value to the specified number of decimal places. - * - * @example - * ```typescript - * // Round the value of the 'price' field to two decimal places. - * round(field("price"), constant(2)); - * ``` - * - * @param expression - An expression evaluating to a numeric value, which will be rounded. - * @param decimalPlaces - A constant or expression specifying the rounding precision in decimal places. - * @returns A new `Expression` representing the rounded value. - */ -export declare function round(expression: Expression, decimalPlaces: number | Expression): FunctionExpression; -/** - * @beta - * Trims whitespace or a specified set of characters/bytes from the end of a string or byte array. - * - * @example - * ```typescript - * // Trim whitespace from the end of the 'userInput' field - * rtrim(field("userInput")); - * - * // Trim quotes from the end of the 'userInput' field - * rtrim(field("userInput"), '"'); - * ``` - * - * @param fieldName - The name of the field containing the string or byte array. - * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim. - * If not specified, whitespace will be trimmed. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array. - */ -export declare function rtrim(fieldName: string, valueToTrim?: string | Expression | Bytes): FunctionExpression; -/** - * @beta - * Trims whitespace or a specified set of characters/bytes from the end of a string or byte array. - * - * @example - * ```typescript - * // Trim whitespace from the end of the 'userInput' field - * rtrim(field("userInput")); - * - * // Trim quotes from the end of the 'userInput' field - * rtrim(field("userInput"), '"'); - * ``` - * - * @param expression - The expression representing the string or byte array. - * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim. - * If not specified, whitespace will be trimmed. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array. - */ -export declare function rtrim(expression: Expression, valueToTrim?: string | Expression | Bytes): FunctionExpression; -/** - * @beta - * Defines the options for evaluating a sample stage within a pipeline. - * This type combines common {@link @firebase/firestore/pipelines#StageOptions} with a specific configuration - * where only one of the defined sampling methods can be applied. - * - * See {@link @firebase/firestore/pipelines#Pipeline.(sample:1)} to create a sample stage.. - */ -export declare type SampleStageOptions = StageOptions & OneOf<{ - /** - * @beta - * If set, specifies the sample rate as a percentage of the - * input documents. - * - * Cannot be set when `documents: number` is set. - */ - percentage: number; - /** - * @beta - * If set, specifies the sample rate as a total number of - * documents to sample from the input documents. - * - * Cannot be set when `percentage: number` is set. - */ - documents: number; -}>; -/** - * @beta - * - * An interface that represents a selectable expression. - */ -export declare interface Selectable { - selectable: true; -} -/** - * @beta - * Options defining how a SelectStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(select:1)}. - */ -export declare type SelectStageOptions = StageOptions & { - /** - * @beta - * The fields to include in the output documents, specified as {@link @firebase/firestore/pipelines#Selectable} expression - * or as a string value indicating the field name. - */ - selections: Array; -}; -/** - * @beta - * @beta - * Options defining how a SortStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(sort:1)}. - */ -export declare type SortStageOptions = StageOptions & { - /** - * @beta - * Orderings specify how the input documents are sorted. - * One or more ordering are required. - */ - orderings: Ordering[]; -}; -/** - * @beta - * Creates an expression that splits the value of a field on the provided delimiter. - * - * @example - * ```typescript - * // Split the 'scoresCsv' field on delimiter ',' - * split('scoresCsv', ',') - * ``` - * - * @param fieldName - Split the value in this field. - * @param delimiter - Split on this delimiter. - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function. - */ -export declare function split(fieldName: string, delimiter: string): FunctionExpression; -/** - * @beta - * Creates an expression that splits the value of a field on the provided delimiter. - * - * @example - * ```typescript - * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format - * split('scores', conditional(field('format').equal('csv'), constant(','), constant(':')) - * ``` - * - * @param fieldName - Split the value in this field. - * @param delimiter - Split on this delimiter returned by evaluating this expression. - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function. - */ -export declare function split(fieldName: string, delimiter: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that splits a string into an array of substrings based on the provided delimiter. - * - * @example - * ```typescript - * // Split the 'scoresCsv' field on delimiter ',' - * split(field('scoresCsv'), ',') - * ``` - * - * @param expression - Split the result of this expression. - * @param delimiter - Split on this delimiter. - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function. - */ -export declare function split(expression: Expression, delimiter: string): FunctionExpression; -/** - * @beta - * Creates an expression that splits a string into an array of substrings based on the provided delimiter. - * - * @example - * ```typescript - * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format - * split(field('scores'), conditional(field('format').equal('csv'), constant(','), constant(':')) - * ``` - * - * @param expression - Split the result of this expression. - * @param delimiter - Split on this delimiter returned by evaluating this expression. - * - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the split function. - */ -export declare function split(expression: Expression, delimiter: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that computes the square root of a numeric value. - * - * @example - * ```typescript - * // Compute the square root of the 'value' field. - * sqrt(field("value")); - * ``` - * - * @param expression - An expression evaluating to a numeric value, which the square root will be computed for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the square root of the numeric value. - */ -export declare function sqrt(expression: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that computes the square root of a numeric value. - * - * @example - * ```typescript - * // Compute the square root of the 'value' field. - * sqrt("value"); - * ``` - * - * @param fieldName - The name of the field to compute the square root of. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the square root of the numeric value. - */ -export declare function sqrt(fieldName: string): FunctionExpression; -/** - * @beta - * Options defining how a Stage is evaluated. - */ -export declare interface StageOptions { - /** - * @beta - * An escape hatch to set options not known at SDK build time. These values - * will be passed directly to the Firestore backend and not used by the SDK. - * - * The option name will be used as provided. And must match the name - * format used by the backend (hint: use a snake_case_name). - * - * Raw option values can be any type supported - * by Firestore (for example: string, boolean, number, map, …). Value types - * not known to the SDK will be rejected. - * - * Values specified in rawOptions will take precedence over any options - * with the same name set by the SDK. - * - * `rawOptions` supports dot notation, if you want to override - * a nested option. - */ - rawOptions?: { - [name: string]: unknown; - }; -} -/** - * @beta - * - * Creates an expression that checks if a field's value starts with a given prefix. - * - * @example - * ```typescript - * // Check if the 'name' field starts with "Mr." - * startsWith("name", "Mr."); - * ``` - * - * @param fieldName - The field name to check. - * @param prefix - The prefix to check for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison. - */ -export declare function startsWith(fieldName: string, prefix: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a field's value starts with a given prefix. - * - * @example - * ```typescript - * // Check if the 'fullName' field starts with the value of the 'firstName' field - * startsWith("fullName", field("firstName")); - * ``` - * - * @param fieldName - The field name to check. - * @param prefix - The expression representing the prefix. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison. - */ -export declare function startsWith(fieldName: string, prefix: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string expression starts with a given prefix. - * - * @example - * ```typescript - * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." - * startsWith(field("fullName"), "Mr."); - * ``` - * - * @param stringExpression - The expression to check. - * @param prefix - The prefix to check for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison. - */ -export declare function startsWith(stringExpression: Expression, prefix: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string expression starts with a given prefix. - * - * @example - * ```typescript - * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." - * startsWith(field("fullName"), field("prefix")); - * ``` - * - * @param stringExpression - The expression to check. - * @param prefix - The prefix to check for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'starts with' comparison. - */ -export declare function startsWith(stringExpression: Expression, prefix: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that concatenates string functions, fields or constants together. - * - * @example - * ```typescript - * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * stringConcat("firstName", " ", field("lastName")); - * ``` - * - * @param fieldName - The field name containing the initial string value. - * @param secondString - An expression or string literal to concatenate. - * @param otherStrings - Optional additional expressions or literals (typically strings) to concatenate. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated string. - */ -export declare function stringConcat(fieldName: string, secondString: Expression | string, ...otherStrings: Array): FunctionExpression; -/** - * @beta - * Creates an expression that concatenates string expressions together. - * - * @example - * ```typescript - * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * stringConcat(field("firstName"), " ", field("lastName")); - * ``` - * - * @param firstString - The initial string expression to concatenate to. - * @param secondString - An expression or string literal to concatenate. - * @param otherStrings - Optional additional expressions or literals (typically strings) to concatenate. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the concatenated string. - */ -export declare function stringConcat(firstString: Expression, secondString: Expression | string, ...otherStrings: Array): FunctionExpression; -/** - * @beta - * - * Creates an expression that checks if a string field contains a specified substring. - * - * @example - * ```typescript - * // Check if the 'description' field contains "example". - * stringContains("description", "example"); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @param substring - The substring to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison. - */ -export declare function stringContains(fieldName: string, substring: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string field contains a substring specified by an expression. - * - * @example - * ```typescript - * // Check if the 'description' field contains the value of the 'keyword' field. - * stringContains("description", field("keyword")); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @param substring - The expression representing the substring to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison. - */ -export declare function stringContains(fieldName: string, substring: Expression): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string expression contains a specified substring. - * - * @example - * ```typescript - * // Check if the 'description' field contains "example". - * stringContains(field("description"), "example"); - * ``` - * - * @param stringExpression - The expression representing the string to perform the comparison on. - * @param substring - The substring to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison. - */ -export declare function stringContains(stringExpression: Expression, substring: string): BooleanExpression; -/** - * @beta - * - * Creates an expression that checks if a string expression contains a substring specified by another expression. - * - * @example - * ```typescript - * // Check if the 'description' field contains the value of the 'keyword' field. - * stringContains(field("description"), field("keyword")); - * ``` - * - * @param stringExpression - The expression representing the string to perform the comparison on. - * @param substring - The expression representing the substring to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'contains' comparison. - */ -export declare function stringContains(stringExpression: Expression, substring: Expression): BooleanExpression; -/** - * @beta - * Creates an expression that finds the index of the first occurrence of a substring or byte sequence. - * - * @example - * ```typescript - * // Find the index of "foo" in the 'text' field - * stringIndexOf("text", "foo"); - * ``` - * - * @param fieldName - The name of the field containing the string or byte array. - * @param search - The substring or byte sequence to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index of the first occurrence. - */ -export declare function stringIndexOf(fieldName: string, search: string | Expression | Bytes): FunctionExpression; -/** - * @beta - * Creates an expression that finds the index of the first occurrence of a substring or byte sequence. - * - * @example - * ```typescript - * // Find the index of "foo" in the 'text' field - * stringIndexOf(field("text"), "foo"); - * ``` - * - * @param expression - The expression representing the string or byte array. - * @param search - The substring or byte sequence to search for. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the index of the first occurrence. - */ -export declare function stringIndexOf(expression: Expression, search: string | Expression | Bytes): FunctionExpression; -/** - * @beta - * Creates an expression that repeats a string or byte array a specified number of times. - * - * @example - * ```typescript - * // Repeat the 'label' field 3 times - * stringRepeat("label", 3); - * ``` - * - * @param fieldName - The name of the field containing the string or byte array. - * @param repetitions - The number of times to repeat the string or byte array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the repeated string or byte array. - */ -export declare function stringRepeat(fieldName: string, repetitions: number | Expression): FunctionExpression; -/** - * @beta - * Creates an expression that repeats a string or byte array a specified number of times. - * - * @example - * ```typescript - * // Repeat the 'label' field 3 times - * stringRepeat(field("label"), 3); - * ``` - * - * @param expression - The expression representing the string or byte array. - * @param repetitions - The number of times to repeat the string or byte array. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the repeated string or byte array. - */ -export declare function stringRepeat(expression: Expression, repetitions: number | Expression): FunctionExpression; -/** - * @beta - * Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement. - * - * @example - * ```typescript - * // Replace all occurrences of "foo" with "bar" in the 'text' field - * stringReplaceAll("text", "foo", "bar"); - * ``` - * - * @param fieldName - The name of the field containing the string or byte array. - * @param find - The substring or byte sequence to search for. - * @param replacement - The replacement string or byte sequence. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with replacements. - */ -export declare function stringReplaceAll(fieldName: string, find: string | Expression | Bytes, replacement: string | Expression | Bytes): FunctionExpression; -/** - * @beta - * Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement. - * - * @example - * ```typescript - * // Replace all occurrences of "foo" with "bar" in the 'text' field - * stringReplaceAll(field("text"), "foo", "bar"); - * ``` - * - * @param expression - The expression representing the string or byte array. - * @param find - The substring or byte sequence to search for. - * @param replacement - The replacement string or byte sequence. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with replacements. - */ -export declare function stringReplaceAll(expression: Expression, find: string | Expression | Bytes, replacement: string | Expression | Bytes): FunctionExpression; -/** - * @beta - * Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement. - * - * @example - * ```typescript - * // Replace the first occurrence of "foo" with "bar" in the 'text' field - * stringReplaceOne("text", "foo", "bar"); - * ``` - * - * @param fieldName - The name of the field containing the string or byte array. - * @param find - The substring or byte sequence to search for. - * @param replacement - The replacement string or byte sequence. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with the replacement. - */ -export declare function stringReplaceOne(fieldName: string, find: string | Expression | Bytes, replacement: string | Expression | Bytes): FunctionExpression; -/** - * @beta - * Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement. - * - * @example - * ```typescript - * // Replace the first occurrence of "foo" with "bar" in the 'text' field - * stringReplaceOne(field("text"), "foo", "bar"); - * ``` - * - * @param expression - The expression representing the string or byte array. - * @param find - The substring or byte sequence to search for. - * @param replacement - The replacement string or byte sequence. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the string or byte array with the replacement. - */ -export declare function stringReplaceOne(expression: Expression, find: string | Expression | Bytes, replacement: string | Expression | Bytes): FunctionExpression; -/** - * @beta - * Creates an expression that reverses a string. - * - * @example - * ```typescript - * // Reverse the value of the 'myString' field. - * strReverse(field("myString")); - * ``` - * - * @param stringExpression - An expression evaluating to a string value, which will be reversed. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string. - */ -export declare function stringReverse(stringExpression: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that reverses a string value in the specified field. - * - * @example - * ```typescript - * // Reverse the value of the 'myString' field. - * strReverse("myString"); - * ``` - * - * @param field - The name of the field representing the string to reverse. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string. - */ -export declare function stringReverse(field: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns a substring of a string or byte array. - * - * @param field - The name of a field containing a string or byte array to compute the substring from. - * @param position - Index of the first character of the substring. - * @param length - Length of the substring. - */ -export declare function substring(field: string, position: number, length?: number): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns a substring of a string or byte array. - * - * @param input - An expression returning a string or byte array to compute the substring from. - * @param position - Index of the first character of the substring. - * @param length - Length of the substring. - */ -export declare function substring(input: Expression, position: number, length?: number): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns a substring of a string or byte array. - * - * @param field - The name of a field containing a string or byte array to compute the substring from. - * @param position - An expression that returns the index of the first character of the substring. - * @param length - An expression that returns the length of the substring. - */ -export declare function substring(field: string, position: Expression, length?: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that returns a substring of a string or byte array. - * - * @param input - An expression returning a string or byte array to compute the substring from. - * @param position - An expression that returns the index of the first character of the substring. - * @param length - An expression that returns the length of the substring. - */ -export declare function substring(input: Expression, position: Expression, length?: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that subtracts two expressions. - * - * @example - * ```typescript - * // Subtract the 'discount' field from the 'price' field - * subtract(field("price"), field("discount")); - * ``` - * - * @param left - The expression to subtract from. - * @param right - The expression to subtract. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation. - */ -export declare function subtract(left: Expression, right: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that subtracts a constant value from an expression. - * - * @example - * ```typescript - * // Subtract the constant value 2 from the 'value' field - * subtract(field("value"), 2); - * ``` - * - * @param expression - The expression to subtract from. - * @param value - The constant value to subtract. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation. - */ -export declare function subtract(expression: Expression, value: unknown): FunctionExpression; -/** - * @beta - * - * Creates an expression that subtracts an expression from a field's value. - * - * @example - * ```typescript - * // Subtract the 'discount' field from the 'price' field - * subtract("price", field("discount")); - * ``` - * - * @param fieldName - The field name to subtract from. - * @param expression - The expression to subtract. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation. - */ -export declare function subtract(fieldName: string, expression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that subtracts a constant value from a field's value. - * - * @example - * ```typescript - * // Subtract 20 from the value of the 'total' field - * subtract("total", 20); - * ``` - * - * @param fieldName - The field name to subtract from. - * @param value - The constant value to subtract. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the subtraction operation. - */ -export declare function subtract(fieldName: string, value: unknown): FunctionExpression; -/** - * @beta - * - * Creates an aggregation that calculates the sum of values from an expression across multiple - * stage inputs. - * - * @example - * ```typescript - * // Calculate the total revenue from a set of orders - * sum(field("orderAmount")).as("totalRevenue"); - * ``` - * - * @param expression - The expression to sum up. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'sum' aggregation. - */ -export declare function sum(expression: Expression): AggregateFunction; -/** - * @beta - * - * Creates an aggregation that calculates the sum of a field's values across multiple stage - * inputs. - * - * @example - * ```typescript - * // Calculate the total revenue from a set of orders - * sum("orderAmount").as("totalRevenue"); - * ``` - * - * @param fieldName - The name of the field containing numeric values to sum up. - * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'sum' aggregation. - */ -export declare function sum(fieldName: string): AggregateFunction; -/** - * @beta - * Specify time granularity for expressions. - */ -export declare type TimeGranularity = 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'week(monday)' | 'week(tuesday)' | 'week(wednesday)' | 'week(thursday)' | 'week(friday)' | 'week(saturday)' | 'week(sunday)' | 'isoWeek' | 'month' | 'quarter' | 'year' | 'isoYear'; -/** - * @beta - * - * Creates an expression that adds a specified amount of time to a timestamp. - * - * @example - * ```typescript - * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. - * timestampAdd(field("timestamp"), field("unit"), field("amount")); - * ``` - * - * @param timestamp - The expression representing the timestamp. - * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. - * @param amount - The expression evaluates to amount of the unit. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp. - */ -export declare function timestampAdd(timestamp: Expression, unit: Expression, amount: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that adds a specified amount of time to a timestamp. - * - * @example - * ```typescript - * // Add 1 day to the 'timestamp' field. - * timestampAdd(field("timestamp"), "day", 1); - * ``` - * - * @param timestamp - The expression representing the timestamp. - * @param unit - The unit of time to add (e.g., "day", "hour"). - * @param amount - The amount of time to add. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp. - */ -export declare function timestampAdd(timestamp: Expression, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; -/** - * @beta - * - * Creates an expression that adds a specified amount of time to a timestamp represented by a field. - * - * @example - * ```typescript - * // Add 1 day to the 'timestamp' field. - * timestampAdd("timestamp", "day", 1); - * ``` - * - * @param fieldName - The name of the field representing the timestamp. - * @param unit - The unit of time to add (e.g., "day", "hour"). - * @param amount - The amount of time to add. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp. - */ -export declare function timestampAdd(fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; -/** - * @beta - * - * Creates an expression that subtracts a specified amount of time from a timestamp. - * - * @example - * ```typescript - * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * timestampSubtract(field("timestamp"), field("unit"), field("amount")); - * ``` - * - * @param timestamp - The expression representing the timestamp. - * @param unit - The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. - * @param amount - The expression evaluates to amount of the unit. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp. - */ -export declare function timestampSubtract(timestamp: Expression, unit: Expression, amount: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that subtracts a specified amount of time from a timestamp. - * - * @example - * ```typescript - * // Subtract 1 day from the 'timestamp' field. - * timestampSubtract(field("timestamp"), "day", 1); - * ``` - * - * @param timestamp - The expression representing the timestamp. - * @param unit - The unit of time to subtract (e.g., "day", "hour"). - * @param amount - The amount of time to subtract. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp. - */ -export declare function timestampSubtract(timestamp: Expression, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; -/** - * @beta - * - * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field. - * - * @example - * ```typescript - * // Subtract 1 day from the 'timestamp' field. - * timestampSubtract("timestamp", "day", 1); - * ``` - * - * @param fieldName - The name of the field representing the timestamp. - * @param unit - The unit of time to subtract (e.g., "day", "hour"). - * @param amount - The amount of time to subtract. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the resulting timestamp. - */ -export declare function timestampSubtract(fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; -/** - * @beta - * - * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * @example - * ```typescript - * // Convert the 'timestamp' field to microseconds since epoch. - * timestampToUnixMicros(field("timestamp")); - * ``` - * - * @param expr - The expression representing the timestamp. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of microseconds since epoch. - */ -export declare function timestampToUnixMicros(expr: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * @example - * ```typescript - * // Convert the 'timestamp' field to microseconds since epoch. - * timestampToUnixMicros("timestamp"); - * ``` - * - * @param fieldName - The name of the field representing the timestamp. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of microseconds since epoch. - */ -export declare function timestampToUnixMicros(fieldName: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * @example - * ```typescript - * // Convert the 'timestamp' field to milliseconds since epoch. - * timestampToUnixMillis(field("timestamp")); - * ``` - * - * @param expr - The expression representing the timestamp. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of milliseconds since epoch. - */ -export declare function timestampToUnixMillis(expr: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * @example - * ```typescript - * // Convert the 'timestamp' field to milliseconds since epoch. - * timestampToUnixMillis("timestamp"); - * ``` - * - * @param fieldName - The name of the field representing the timestamp. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of milliseconds since epoch. - */ -export declare function timestampToUnixMillis(fieldName: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * @example - * ```typescript - * // Convert the 'timestamp' field to seconds since epoch. - * timestampToUnixSeconds(field("timestamp")); - * ``` - * - * @param expr - The expression representing the timestamp. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of seconds since epoch. - */ -export declare function timestampToUnixSeconds(expr: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * @example - * ```typescript - * // Convert the 'timestamp' field to seconds since epoch. - * timestampToUnixSeconds("timestamp"); - * ``` - * - * @param fieldName - The name of the field representing the timestamp. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of seconds since epoch. - */ -export declare function timestampToUnixSeconds(fieldName: string): FunctionExpression; -/** - * @beta - * Creates an expression that truncates a timestamp to a specified granularity. - * - * @example - * ```typescript - * // Truncate the 'createdAt' timestamp to the beginning of the day. - * field('createdAt').timestampTruncate('day') - * ``` - * - * @param fieldName - Truncate the timestamp value contained in this field. - * @param granularity - The granularity to truncate to. - * @param timezone - The timezone to use for truncation. Valid values are from - * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". - * @returns A new `Expression` representing the truncated timestamp. - */ -export declare function timestampTruncate(fieldName: string, granularity: TimeGranularity, timezone?: string | Expression): FunctionExpression; -/** - * @beta - * Creates an expression that truncates a timestamp to a specified granularity. - * - * @example - * ```typescript - * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. - * field('createdAt').timestampTruncate(field('granularity')) - * ``` - * - * @param fieldName - Truncate the timestamp value contained in this field. - * @param granularity - The granularity to truncate to. - * @param timezone - The timezone to use for truncation. Valid values are from - * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". - * @returns A new `Expression` representing the truncated timestamp. - */ -export declare function timestampTruncate(fieldName: string, granularity: Expression, timezone?: string | Expression): FunctionExpression; -/** - * @beta - * Creates an expression that truncates a timestamp to a specified granularity. - * - * @example - * ```typescript - * // Truncate the 'createdAt' timestamp to the beginning of the day. - * field('createdAt').timestampTruncate('day') - * ``` - * - * @param timestampExpression - Truncate the timestamp value that is returned by this expression. - * @param granularity - The granularity to truncate to. - * @param timezone - The timezone to use for truncation. Valid values are from - * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". - * @returns A new `Expression` representing the truncated timestamp. - */ -export declare function timestampTruncate(timestampExpression: Expression, granularity: TimeGranularity, timezone?: string | Expression): FunctionExpression; -/** - * @beta - * Creates an expression that truncates a timestamp to a specified granularity. - * - * @example - * ```typescript - * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. - * field('createdAt').timestampTruncate(field('granularity')) - * ``` - * - * @param timestampExpression - Truncate the timestamp value that is returned by this expression. - * @param granularity - The granularity to truncate to. - * @param timezone - The timezone to use for truncation. Valid values are from - * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". - * @returns A new `Expression` representing the truncated timestamp. - */ -export declare function timestampTruncate(timestampExpression: Expression, granularity: Expression, timezone?: string | Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that converts a string field to lowercase. - * - * @example - * ```typescript - * // Convert the 'name' field to lowercase - * toLower("name"); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the lowercase string. - */ -export declare function toLower(fieldName: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that converts a string expression to lowercase. - * - * @example - * ```typescript - * // Convert the 'name' field to lowercase - * toLower(field("name")); - * ``` - * - * @param stringExpression - The expression representing the string to convert to lowercase. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the lowercase string. - */ -export declare function toLower(stringExpression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that converts a string field to uppercase. - * - * @example - * ```typescript - * // Convert the 'title' field to uppercase - * toUpper("title"); - * ``` - * - * @param fieldName - The name of the field containing the string. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the uppercase string. - */ -export declare function toUpper(fieldName: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that converts a string expression to uppercase. - * - * @example - * ```typescript - * // Convert the 'title' field to uppercase - * toUppercase(field("title")); - * ``` - * - * @param stringExpression - The expression representing the string to convert to uppercase. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the uppercase string. - */ -export declare function toUpper(stringExpression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that removes leading and trailing whitespace from a string or byte array. - * - * @example - * ```typescript - * // Trim whitespace from the 'userInput' field - * trim("userInput"); - * - * // Trim quotes from the 'userInput' field - * trim("userInput", '"'); - * ``` - * - * @param fieldName - The name of the field containing the string or byte array. - * @param valueToTrim - Optional This parameter is treated as a set of characters or bytes that will be - * trimmed from the input. If not specified, then whitespace will be trimmed. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string. - */ -export declare function trim(fieldName: string, valueToTrim?: string | Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that removes leading and trailing characters from a string or byte array expression. - * - * @example - * ```typescript - * // Trim whitespace from the 'userInput' field - * trim(field("userInput")); - * - * // Trim quotes from the 'userInput' field - * trim(field("userInput"), '"'); - * ``` - * - * @param stringExpression - The expression representing the string or byte array to trim. - * @param valueToTrim - Optional This parameter is treated as a set of characters or bytes that will be - * trimmed from the input. If not specified, then whitespace will be trimmed. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the trimmed string or byte array. - */ -export declare function trim(stringExpression: Expression, valueToTrim?: string | Expression): FunctionExpression; -/** - * @beta - * Creates an expression that truncates the numeric value of a field to an integer. - * - * @example - * ```typescript - * // Truncate the value of the 'rating' field - * trunc("rating"); - * ``` - * - * @param fieldName - The name of the field containing the number to truncate. - * @returns A new `Expression` representing the truncated value. - */ -export declare function trunc(fieldName: string): FunctionExpression; -/** - * @beta - * Creates an expression that truncates the numeric value of an expression to an integer. - * - * @example - * ```typescript - * // Truncate the value of the 'rating' field. - * trunc(field("rating")); - * ``` - * - * @param expression - An expression evaluating to a numeric value, which will be truncated. - * @returns A new `Expression` representing the truncated value. - */ -export declare function trunc(expression: Expression): FunctionExpression; -/** - * @beta - * Creates an expression that truncates a numeric expression to the specified number of decimal places. - * - * @example - * ```typescript - * // Truncate the value of the 'rating' field to two decimal places. - * trunc("rating", 2); - * ``` - * - * @param fieldName - The name of the field to truncate. - * @param decimalPlaces - A constant or expression specifying the truncation precision in decimal places. - * @returns A new `Expression` representing the truncated value. - */ -export declare function trunc(fieldName: string, decimalPlaces: number | Expression): FunctionExpression; -/** - * @beta - * Creates an expression that truncates a numeric value to the specified number of decimal places. - * - * @example - * ```typescript - * // Truncate the value of the 'rating' field to two decimal places. - * trunc(field("rating"), constant(2)); - * ``` - * - * @param expression - An expression evaluating to a numeric value, which will be truncated. - * @param decimalPlaces - A constant or expression specifying the truncation precision in decimal places. - * @returns A new `Expression` representing the truncated value. - */ -export declare function trunc(expression: Expression, decimalPlaces: number | Expression): FunctionExpression; -/* Excluded from this release type: TSType */ -/** - * @beta - * - * An enumeration of the different types generated by the Firestore backend. - * - *

    - *
  • Numerics evaluate directly to backend representation (`int64` or `float64`), not JS `number`.
  • - *
  • JavaScript `Date` and firestore `Timestamp` objects strictly evaluate to `'timestamp'`.
  • - *
  • Advanced configurations parsing backend types (such as `decimal128`, `max_key` or `min_key` from BSON) are also incorporated in this union string type. Note that `decimal128` is a backend-only numeric type that the JavaScript SDK cannot create natively, but can be evaluated in pipelines.
  • - *
- */ -export declare type Type = 'null' | 'array' | 'boolean' | 'bytes' | 'timestamp' | 'geo_point' | 'number' | 'int32' | 'int64' | 'float64' | 'decimal128' | 'map' | 'reference' | 'string' | 'vector' | 'max_key' | 'min_key' | 'object_id' | 'regex' | 'request_timestamp'; -/** - * @beta - * Creates an expression that returns the data type of the data in the specified field. - * - * @remarks - * String inputs passed iteratively to this global function act as `field()` path lookups. - * If you wish to pass a string literal value, it must be wrapped: `type(constant("my_string"))`. - * - * @example - * ```typescript - * // Get the data type of the value in field 'title' - * type('title') - * ``` - * - * @returns A new `Expression` representing the data type. - */ -export declare function type(fieldName: string): FunctionExpression; -/** - * @beta - * Creates an expression that returns the data type of an expression's result. - * - * @example - * ```typescript - * // Get the data type of a conditional expression - * type(conditional(exists('foo'), constant(1), constant(true))) - * ``` - * - * @returns A new `Expression` representing the data type. - */ -export declare function type(expression: Expression): FunctionExpression; -/** - * @beta - * Options defining how a UnionStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(union:1)}. - */ -export declare type UnionStageOptions = StageOptions & { - /** - * @beta - * Specifies the other Pipeline to union with. - */ - other: Pipeline; -}; -/** - * @beta - * - * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * @example - * ```typescript - * // Interpret the 'microseconds' field as microseconds since epoch. - * unixMicrosToTimestamp(field("microseconds")); - * ``` - * - * @param expr - The expression representing the number of microseconds since epoch. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp. - */ -export declare function unixMicrosToTimestamp(expr: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * @example - * ```typescript - * // Interpret the 'microseconds' field as microseconds since epoch. - * unixMicrosToTimestamp("microseconds"); - * ``` - * - * @param fieldName - The name of the field representing the number of microseconds since epoch. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp. - */ -export declare function unixMicrosToTimestamp(fieldName: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * @example - * ```typescript - * // Interpret the 'milliseconds' field as milliseconds since epoch. - * unixMillisToTimestamp(field("milliseconds")); - * ``` - * - * @param expr - The expression representing the number of milliseconds since epoch. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp. - */ -export declare function unixMillisToTimestamp(expr: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * @example - * ```typescript - * // Interpret the 'milliseconds' field as milliseconds since epoch. - * unixMillisToTimestamp("milliseconds"); - * ``` - * - * @param fieldName - The name of the field representing the number of milliseconds since epoch. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp. - */ -export declare function unixMillisToTimestamp(fieldName: string): FunctionExpression; -/** - * @beta - * - * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * @example - * ```typescript - * // Interpret the 'seconds' field as seconds since epoch. - * unixSecondsToTimestamp(field("seconds")); - * ``` - * - * @param expr - The expression representing the number of seconds since epoch. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp. - */ -export declare function unixSecondsToTimestamp(expr: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * @example - * ```typescript - * // Interpret the 'seconds' field as seconds since epoch. - * unixSecondsToTimestamp("seconds"); - * ``` - * - * @param fieldName - The name of the field representing the number of seconds since epoch. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp. - */ -export declare function unixSecondsToTimestamp(fieldName: string): FunctionExpression; -/** - * @beta - * Represents the specific options available for configuring an `UnnestStage` within a pipeline. - */ -export declare type UnnestStageOptions = StageOptions & { - /** - * @beta - * A `Selectable` object that defines an array expression to be un-nested - * and the alias for the un-nested field. - */ - selectable: Selectable; - /** - * @beta - * If set, specifies the field on the output documents that will contain the - * offset (starting at zero) that the element is from the original array. - */ - indexField?: string; -}; -/** - * @beta - * - * Creates an expression that calculates the length of a Firestore Vector. - * - * @example - * ```typescript - * // Get the vector length (dimension) of the field 'embedding'. - * vectorLength(field("embedding")); - * ``` - * - * @param vectorExpression - The expression representing the Firestore Vector. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array. - */ -export declare function vectorLength(vectorExpression: Expression): FunctionExpression; -/** - * @beta - * - * Creates an expression that calculates the length of a Firestore Vector represented by a field. - * - * @example - * ```typescript - * // Get the vector length (dimension) of the field 'embedding'. - * vectorLength("embedding"); - * ``` - * - * @param fieldName - The name of the field representing the Firestore Vector. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the array. - */ -export declare function vectorLength(fieldName: string): FunctionExpression; -/** - * @beta - * Options defining how a WhereStage is evaluated. See {@link @firebase/firestore/pipelines#Pipeline.(where:1)}. - */ -export declare type WhereStageOptions = StageOptions & { - /** - * @beta - * The {@link @firebase/firestore/pipelines#BooleanExpression} to apply as a filter for each input document to this stage. - */ - condition: BooleanExpression; -}; -/** - * @beta - * - * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExpressions. - * - * @example - * ```typescript - * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", - * // or 'status' is "active". - * const condition = xor( - * greaterThan("age", 18), - * equal("city", "London"), - * equal("status", "active")); - * ``` - * - * @param first - The first condition. - * @param second - The second condition. - * @param additionalConditions - Additional conditions to 'XOR' together. - * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'XOR' operation. - */ -export declare function xor(first: BooleanExpression, second: BooleanExpression, ...additionalConditions: BooleanExpression[]): BooleanExpression; -export {}; diff --git a/.github/scripts/compare-types/packages/firestore/firestore-js-sdk.d.ts b/.github/scripts/compare-types/packages/firestore/firestore-js-sdk.d.ts deleted file mode 100644 index 1979c975b3..0000000000 --- a/.github/scripts/compare-types/packages/firestore/firestore-js-sdk.d.ts +++ /dev/null @@ -1,3700 +0,0 @@ -/** - * Cloud Firestore - * - * @packageDocumentation - */ -import { FirebaseApp } from '@firebase/app'; -import { LogLevelString as LogLevel } from '@firebase/logger'; -import { FirebaseError } from '@firebase/util'; - -/** - * Provider identifier for Firebase Auth (from @firebase/util). - * Inlined here so the compare-types script can resolve EmulatorMockTokenOptions. - */ -export declare type FirebaseSignInProvider = - | 'custom' - | 'email' - | 'password' - | 'phone' - | 'anonymous' - | 'google.com' - | 'facebook.com' - | 'github.com' - | 'twitter.com' - | 'microsoft.com' - | 'apple.com'; - -/** - * Shape of a decoded Firebase ID token (from @firebase/util). - * Inlined here so the compare-types script can resolve EmulatorMockTokenOptions. - */ -export declare interface FirebaseIdToken { - iss: string; - aud: string; - sub: string; - iat: number; - exp: number; - user_id: string; - auth_time: number; - provider_id?: 'anonymous'; - email?: string; - email_verified?: boolean; - phone_number?: string; - name?: string; - picture?: string; - firebase: { - sign_in_provider: FirebaseSignInProvider; - identities?: { [provider in FirebaseSignInProvider]?: string[] }; - }; - [claim: string]: unknown; - uid?: never; -} - -/** - * Options for mock auth token when using emulators (from @firebase/util). - * Inlined here so the compare-types script has access to the full type. - */ -export declare type EmulatorMockTokenOptions = ( - | { user_id: string } - | { sub: string } -) & - Partial; - -/** - * 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> = { - [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; - /** - * Returns a JSON-serializable representation of this `Bytes` instance. - * - * @returns a JSON representation of this object. - */ - toJSON(): object; - /** - * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. - * - * @param json - a JSON object represention of a `Bytes` instance - * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a - * {@link FirestoreError} if an error occurs. - */ - static fromJSON(json: object): Bytes; -} -/* Excluded from this release type: _ByteString */ -/** - * 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 ? 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( - reference: CollectionReference, - path: string, - ...pathSegments: string[] -): CollectionReference; -/** - * Gets a `CollectionReference` instance that refers to a subcollection of - * `reference` at the specified relative path. - * - * @param reference - A reference to a Firestore document. - * @param path - A slash-separated path to a collection. - * @param pathSegments - Additional path segments that will be applied relative - * to the first argument. - * @throws If the final path has an even number of segments and does not point - * to a collection. - * @returns The `CollectionReference` instance. - */ -export declare function collection( - reference: DocumentReference, - path: string, - ...pathSegments: string[] -): CollectionReference; -/** - * Creates and returns a new `Query` instance that includes all documents in the - * database that are contained in a collection or subcollection with the - * given `collectionId`. - * - * @param firestore - A reference to the root `Firestore` instance. - * @param collectionId - Identifies the collections to query over. Every - * collection or subcollection with this ID as the last segment of its path - * will be included. Cannot contain a slash. - * @returns The created `Query`. - */ -export declare function collectionGroup( - firestore: Firestore, - collectionId: string, -): Query; -/** - * A `CollectionReference` object can be used for adding documents, getting - * document references, and querying for documents (using {@link (query:1)}). - */ -export declare class CollectionReference< - 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( - 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( - 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( - converter: FirestoreDataConverter, - ): DocumentReference; - /** - * Removes the current converter. - * - * @param converter - `null` removes the current converter. - * @returns A `DocumentReference` that does not - * use a converter. - */ - withConverter(converter: null): DocumentReference; - /** - * Returns a JSON-serializable representation of this `DocumentReference` instance. - * - * @returns a JSON representation of this object. - */ - toJSON(): object; - /** - * Builds a `DocumentReference` instance from a JSON object created by - * {@link DocumentReference.toJSON}. - * - * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. - * @param json - a JSON object represention of a `DocumentReference` instance - * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a - * {@link FirestoreError} if an error occurs. - */ - static fromJSON(firestore: Firestore, json: object): DocumentReference; - /** - * Builds a `DocumentReference` instance from a JSON object created by - * {@link DocumentReference.toJSON}. - * - * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. - * @param json - a JSON object represention of a `DocumentReference` instance - * @param converter - Converts objects to and from Firestore. - * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a - * {@link FirestoreError} if an error occurs. - */ - static fromJSON< - NewAppModelType = DocumentData, - NewDbModelType extends DocumentData = DocumentData, - >( - firestore: Firestore, - json: object, - converter: FirestoreDataConverter, - ): DocumentReference; -} -/** - * A `DocumentSnapshot` contains data read from a document in your Firestore - * database. The data can be extracted with `.data()` or `.get()` to - * get a specific field. - * - * For a `DocumentSnapshot` that points to a non-existing document, any data - * access will return 'undefined'. You can use the `exists()` method to - * explicitly verify a document's existence. - */ -export declare class DocumentSnapshot< - 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; - /** - * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. - * - * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this - * `DocumentSnapshot` has pending writes. - */ - toJSON(): object; - /** - * 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; -} -/** - * Builds a `DocumentSnapshot` instance from a JSON object created by - * {@link DocumentSnapshot.toJSON}. - * - * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. - * @param json - a JSON object represention of a `DocumentSnapshot` instance. - * @returns an instance of {@link DocumentSnapshot} if the JSON object could be - * parsed. Throws a {@link FirestoreError} if an error occurs. - */ -export declare function documentSnapshotFromJSON(db: Firestore, json: object): DocumentSnapshot; -/** - * Builds a `DocumentSnapshot` instance from a JSON object created by - * {@link DocumentSnapshot.toJSON}. - * - * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. - * @param json - a JSON object represention of a `DocumentSnapshot` instance. - * @param converter - Converts objects to and from Firestore. - * @returns an instance of {@link DocumentSnapshot} if the JSON object could be - * parsed. Throws a {@link FirestoreError} if an error occurs. - */ -export declare function documentSnapshotFromJSON< - AppModelType, - DbModelType extends DocumentData = DocumentData, ->( - db: Firestore, - json: object, - converter: FirestoreDataConverter, -): DocumentSnapshot; -/* Excluded from this release type: _EmptyAppCheckTokenProvider */ -/* Excluded from this release type: _EmptyAuthCredentialsProvider */ -/** - * 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( - 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; -} -/** - * An immutable object representing a geographic location in Firestore. The - * location is represented as latitude/longitude pair. - * - * Latitude values are in the range of [-90, 90]. - * Longitude values are in the range of [-180, 180]. - */ -export declare class GeoPoint { - /** - * Creates a new immutable `GeoPoint` object with the provided latitude and - * longitude values. - * @param latitude - The latitude as number between -90 and 90. - * @param longitude - The longitude as number between -180 and 180. - */ - constructor(latitude: number, longitude: number); - /** - * The latitude of this `GeoPoint` instance. - */ - get latitude(): number; - /** - * The longitude of this `GeoPoint` instance. - */ - get longitude(): number; - /** - * Returns true if this `GeoPoint` is equal to the provided one. - * - * @param other - The `GeoPoint` to compare against. - * @returns true if this `GeoPoint` is equal to the provided one. - */ - isEqual(other: GeoPoint): boolean; - /** - * Returns a JSON-serializable representation of this `GeoPoint` instance. - * - * @returns a JSON representation of this object. - */ - toJSON(): { - latitude: number; - longitude: number; - type: string; - }; - /** - * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. - * - * @param json - a JSON object represention of a `GeoPoint` instance - * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a - * {@link FirestoreError} if an error occurs. - */ - static fromJSON(json: object): GeoPoint; -} -/** - * Calculates the specified aggregations over the documents in the result - * set of the given query without actually downloading the documents. - * - * Using this function to perform aggregations is efficient because only the - * final aggregation values, not the documents' data, are downloaded. This - * function can perform aggregations of the documents in cases where the result - * set is prohibitively large to download entirely (thousands of documents). - * - * 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>; -/** - * Calculates the number of documents in the result set of the given query - * without actually downloading the documents. - * - * Using this function to count the documents is efficient because only the - * final count, not the documents' data, is downloaded. This function can - * count the documents in cases where the result set is prohibitively large to - * download entirely (thousands of documents). - * - * The result received from the server is presented, unaltered, without - * considering any local state. That is, documents in the local cache are not - * taken into consideration, neither are local modifications not yet - * synchronized with the server. Previously-downloaded results, if any, are not - * used. Every invocation of this function necessarily involves a round trip to - * the server. - * - * @param query - The query whose result set size is calculated. - * @returns A Promise that will be resolved with the count; the count can be - * retrieved from `snapshot.data().count`, where `snapshot` is the - * `AggregateQuerySnapshot` to which the returned Promise resolves. - */ -export declare function getCountFromServer( - query: Query, -): Promise< - 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( - reference: DocumentReference, -): Promise>; -/** - * Reads the document referred to by this `DocumentReference` from the server. - * Returns an error if the network is not available. - * - * @returns A `Promise` resolved with a `DocumentSnapshot` containing the - * current document contents. - */ -export declare function getDocFromServer( - reference: DocumentReference, -): Promise>; -/** - * Executes the query and returns the results as a `QuerySnapshot`. - * - * Note: `getDocs()` attempts to provide up-to-date data when possible by - * waiting for data from the server, but it may return cached data or fail if - * you are offline and the server cannot be reached. To specify this behavior, - * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. - * - * @returns A `Promise` that will be resolved with the results of the query. - */ -export declare function getDocs( - query: Query, -): Promise>; -/** - * Executes the query and returns the results as a `QuerySnapshot` from cache. - * Returns an empty result set if no documents matching the query are currently - * cached. - * - * @returns A `Promise` that will be resolved with the results of the query. - */ -export declare function getDocsFromCache( - query: Query, -): Promise>; -/** - * Executes the query and returns the results as a `QuerySnapshot` from the - * server. Returns an error if the network is not available. - * - * @returns A `Promise` that will be resolved with the results of the query. - */ -export declare function getDocsFromServer( - query: Query, -): Promise>; -/** - * 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. - * - * @returns 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 interface 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 interface 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 interface 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 interface 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( - reference: DocumentReference, - observer: { - next?: (snapshot: DocumentSnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - }, -): Unsubscribe; -/** - * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and - * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param reference - A reference to the document to listen to. - * @param options - Options controlling the listen behavior. - * @param observer - A single object containing `next` and `error` callbacks. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshot( - reference: DocumentReference, - options: SnapshotListenOptions, - observer: { - next?: (snapshot: DocumentSnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - }, -): Unsubscribe; -/** - * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and - * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param reference - A reference to the document to listen to. - * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. - * @param onError - A callback to be called if the listen fails or is cancelled. No further - * callbacks will occur. - * @param onCompletion - Can be provided, but will not be called since streams are never ending. - * @returns An unsubscribe function that can be called to cancel the snapshot listener. - */ -export declare function onSnapshot( - reference: DocumentReference, - onNext: (snapshot: DocumentSnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void, -): Unsubscribe; -/** - * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and - * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param reference - A reference to the document to listen to. - * @param options - Options controlling the listen behavior. - * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. - * @param onError - A callback to be called if the listen fails or is cancelled. No further - * callbacks will occur. - * @param onCompletion - Can be provided, but will not be called since streams are never ending. - * @returns An unsubscribe function that can be called to cancel the snapshot listener. - */ -export declare function onSnapshot( - reference: DocumentReference, - options: SnapshotListenOptions, - onNext: (snapshot: DocumentSnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void, -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and - * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The - * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param query - The query to listen to. - * @param observer - A single object containing `next` and `error` callbacks. - * @returns An unsubscribe function that can be called to cancel the snapshot listener. - */ -export declare function onSnapshot( - query: Query, - observer: { - next?: (snapshot: QuerySnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - }, -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and - * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The - * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param query - The query to listen to. - * @param options - Options controlling the listen behavior. - * @param observer - A single object containing `next` and `error` callbacks. - * @returns An unsubscribe function that can be called to cancel the snapshot listener. - */ -export declare function onSnapshot( - query: Query, - options: SnapshotListenOptions, - observer: { - next?: (snapshot: QuerySnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - }, -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and - * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The - * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param query - The query to listen to. - * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. - * @param onCompletion - Can be provided, but will not be called since streams are never ending. - * @param onError - A callback to be called if the listen fails or is cancelled. No further - * callbacks will occur. - * @returns An unsubscribe function that can be called to cancel the snapshot listener. - */ -export declare function onSnapshot( - query: Query, - onNext: (snapshot: QuerySnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void, -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and - * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The - * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param query - The query to listen to. - * @param options - Options controlling the listen behavior. - * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. - * @param onCompletion - Can be provided, but will not be called since streams are never ending. - * @param onError - A callback to be called if the listen fails or is cancelled. No further - * callbacks will occur. - * @returns An unsubscribe function that can be called to cancel the snapshot listener. - */ -export declare function onSnapshot( - query: Query, - options: SnapshotListenOptions, - onNext: (snapshot: QuerySnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void, -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events based on data generated by invoking - * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or - * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by - * calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param firestore - The {@link Firestore} instance to enable the listener for. - * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. - * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. - * @param onError - A callback to be called if the listen fails or is cancelled. No further - * callbacks will occur. - * @param onCompletion - Can be provided, but will not be called since streams are never ending. - * @param converter - An optional object that converts objects from Firestore before the onNext - * listener is invoked. - * @returns An unsubscribe function that can be called to cancel the snapshot listener. - */ -export declare function onSnapshotResume( - firestore: Firestore, - snapshotJson: object, - onNext: (snapshot: QuerySnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void, - converter?: FirestoreDataConverter, -): Unsubscribe; -/** - * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking - * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or - * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by - * calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param firestore - The {@link Firestore} instance to enable the listener for. - * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. - * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. - * @param onError - A callback to be called if the listen fails or is cancelled. No further - * callbacks will occur. - * @param onCompletion - Can be provided, but will not be called since streams are - * never ending. - * @param converter - An optional object that converts objects from Firestore before the onNext - * listener is invoked. - * @returns An unsubscribe function that can be called to cancel the snapshot listener. - */ -export declare function onSnapshotResume( - firestore: Firestore, - snapshotJson: object, - onNext: (snapshot: DocumentSnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void, - converter?: FirestoreDataConverter, -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events based on data generated by invoking - * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or - * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by - * calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param firestore - The {@link Firestore} instance to enable the listener for. - * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. - * @param options - Options controlling the listen behavior. - * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. - * @param onError - A callback to be called if the listen fails or is cancelled. No further - * callbacks will occur. - * @param onCompletion - Can be provided, but will not be called since streams are never ending. - * @param converter - An optional object that converts objects from Firestore before the onNext - * listener is invoked. - * @returns An unsubscribe function that can be called to cancel the snapshot listener. - */ -export declare function onSnapshotResume( - firestore: Firestore, - snapshotJson: object, - options: SnapshotListenOptions, - onNext: (snapshot: QuerySnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void, - converter?: FirestoreDataConverter, -): Unsubscribe; -/** - * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking - * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks - * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled - * by calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param firestore - The {@link Firestore} instance to enable the listener for. - * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. - * @param options - Options controlling the listen behavior. - * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. - * @param onError - A callback to be called if the listen fails or is cancelled. No further - * callbacks will occur. - * @param onCompletion - Can be provided, but will not be called since streams are never ending. - * @param converter - An optional object that converts objects from Firestore before the onNext - * listener is invoked. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshotResume( - firestore: Firestore, - snapshotJson: object, - options: SnapshotListenOptions, - onNext: (snapshot: DocumentSnapshot) => void, - onError?: (error: FirestoreError) => void, - onCompletion?: () => void, - converter?: FirestoreDataConverter, -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking - * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or - * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by - * calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param firestore - The {@link Firestore} instance to enable the listener for. - * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. - * @param observer - A single object containing `next` and `error` callbacks. - * @param converter - An optional object that converts objects from Firestore before the onNext - * listener is invoked. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshotResume( - firestore: Firestore, - snapshotJson: object, - observer: { - next: (snapshot: QuerySnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - }, - converter?: FirestoreDataConverter, -): Unsubscribe; -/** - * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking - * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks - * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled - * by calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param firestore - The {@link Firestore} instance to enable the listener for. - * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. - * @param observer - A single object containing `next` and `error` callbacks. - * @param converter - An optional object that converts objects from Firestore before the onNext - * listener is invoked. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshotResume( - firestore: Firestore, - snapshotJson: object, - observer: { - next: (snapshot: DocumentSnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - }, - converter?: FirestoreDataConverter, -): Unsubscribe; -/** - * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking - * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or - * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by - * calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param firestore - The {@link Firestore} instance to enable the listener for. - * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. - * @param options - Options controlling the listen behavior. - * @param observer - A single object containing `next` and `error` callbacks. - * @param converter - An optional object that converts objects from Firestore before the onNext - * listener is invoked. - * @returns An unsubscribe function that can be called to cancel - * the snapshot listener. - */ -export declare function onSnapshotResume( - firestore: Firestore, - snapshotJson: object, - options: SnapshotListenOptions, - observer: { - next: (snapshot: QuerySnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - }, - converter?: FirestoreDataConverter, -): Unsubscribe; -/** - * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by - * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` - * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be - * cancelled by calling the function that is returned when `onSnapshot` is called. - * - * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the - * snapshot stream is never-ending. - * - * @param firestore - The {@link Firestore} instance to enable the listener for. - * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. - * @param options - Options controlling the listen behavior. - * @param observer - A single object containing `next` and `error` callbacks. - * @param converter - An optional object that converts objects from Firestore before the onNext - * listener is invoked. - * @returns An unsubscribe function that can be called to cancel the snapshot listener. - */ -export declare function onSnapshotResume( - firestore: Firestore, - snapshotJson: object, - options: SnapshotListenOptions, - observer: { - next: (snapshot: DocumentSnapshot) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - }, - converter?: FirestoreDataConverter, -): Unsubscribe; -/** - * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync - * event indicates that all listeners affected by a given change have fired, - * even if a single server-generated change affects multiple listeners. - * - * NOTE: The snapshots-in-sync event only indicates that listeners are in sync - * with each other, but does not relate to whether those snapshots are in sync - * with the server. Use SnapshotMetadata in the individual listeners to - * determine if a snapshot is from the cache or the server. - * - * @param firestore - The instance of Firestore for synchronizing snapshots. - * @param observer - A single object containing `next` and `error` callbacks. - * @returns An unsubscribe function that can be called to cancel the snapshot - * listener. - */ -export declare function onSnapshotsInSync( - firestore: Firestore, - observer: { - next?: (value: void) => void; - error?: (error: FirestoreError) => void; - complete?: () => void; - }, -): Unsubscribe; -/** - * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync - * event indicates that all listeners affected by a given change have fired, - * even if a single server-generated change affects multiple listeners. - * - * NOTE: The snapshots-in-sync event only indicates that listeners are in sync - * with each other, but does not relate to whether those snapshots are in sync - * with the server. Use `SnapshotMetadata` in the individual listeners to - * determine if a snapshot is from the cache or the server. - * - * @param firestore - The `Firestore` instance for synchronizing snapshots. - * @param onSync - A callback to be called every time all snapshot listeners are - * in sync with each other. - * @returns An unsubscribe function that can be called to cancel the snapshot - * listener. - */ -export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe; -/** - * 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 interface 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 interface 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 interface 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 interface 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 interface 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( - 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( - 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>; - /** - * Returns a JSON-serializable representation of this `QuerySnapshot` instance. - * - * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this - * `QuerySnapshot` has pending writes. - */ - toJSON(): object; -} -/** - * Builds a `QuerySnapshot` instance from a JSON object created by - * {@link QuerySnapshot.toJSON}. - * - * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. - * @param json - a JSON object represention of a `QuerySnapshot` instance. - * @returns an instance of {@link QuerySnapshot} if the JSON object could be - * parsed. Throws a {@link FirestoreError} if an error occurs. - */ -export declare function querySnapshotFromJSON(db: Firestore, json: object): QuerySnapshot; -/** - * Builds a `QuerySnapshot` instance from a JSON object created by - * {@link QuerySnapshot.toJSON}. - * - * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. - * @param json - a JSON object represention of a `QuerySnapshot` instance. - * @param converter - Converts objects to and from Firestore. - * @returns an instance of {@link QuerySnapshot} if the JSON object could be - * parsed. Throws a {@link FirestoreError} if an error occurs. - */ -export declare function querySnapshotFromJSON< - AppModelType, - DbModelType extends DocumentData = DocumentData, ->( - db: Firestore, - json: object, - converter: FirestoreDataConverter, -): QuerySnapshot; -/** - * A `QueryStartAtConstraint` is used to exclude documents from the start of a - * result set returned by a Firestore query. - * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or - * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a - * new query instance that also contains this `QueryStartAtConstraint`. - */ -export declare class QueryStartAtConstraint extends QueryConstraint { - /** The type of this query constraint */ - readonly type: 'startAt' | 'startAfter'; -} -/** - * Returns true if the provided references are equal. - * - * @param left - A reference to compare. - * @param right - A reference to compare. - * @returns true if the references point to the same location in the same - * Firestore database. - */ -export declare function refEqual( - left: - | DocumentReference - | CollectionReference, - right: - | DocumentReference - | CollectionReference, -): boolean; -/* Excluded from this release type: _ResourcePath */ -/** - * Executes the given `updateFunction` and then attempts to commit the changes - * applied within the transaction. If any document read within the transaction - * has changed, Cloud Firestore retries the `updateFunction`. If it fails to - * commit after 5 attempts, the transaction fails. - * - * The maximum number of writes allowed in a single transaction is 500. - * - * @param firestore - A reference to the Firestore database to run this - * transaction against. - * @param updateFunction - The function to execute within the transaction - * context. - * @param options - An options object to configure maximum number of attempts to - * commit. - * @returns If the transaction completed successfully or was explicitly aborted - * (the `updateFunction` returned a failed promise), the promise returned by the - * `updateFunction `is returned here. Otherwise, if the transaction failed, a - * rejected promise with the corresponding failure error is returned. - */ -export declare function runTransaction( - firestore: Firestore, - updateFunction: (transaction: Transaction) => Promise, - options?: TransactionOptions, -): Promise; -/** - * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to - * include a server-generated timestamp in the written data. - */ -export declare function serverTimestamp(): FieldValue; -/** - * Writes to the document referred to by 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( - 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( - 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; -/** - * A `Timestamp` represents a point in time independent of any time zone or - * calendar, represented as seconds and fractions of seconds at nanosecond - * resolution in UTC Epoch time. - * - * It is encoded using the Proleptic Gregorian Calendar which extends the - * Gregorian calendar backwards to year one. It is encoded assuming all minutes - * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second - * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59.999999999Z. - * - * For examples and further specifications, refer to the - * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. - */ -export declare class Timestamp { - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - */ - readonly seconds: number; - /** - * The fractions of a second at nanosecond resolution.* - */ - readonly nanoseconds: number; - /** - * Creates a new timestamp with the current date, with millisecond precision. - * - * @returns a new timestamp representing the current date. - */ - static now(): Timestamp; - /** - * Creates a new timestamp from the given date. - * - * @param date - The date to initialize the `Timestamp` from. - * @returns A new `Timestamp` representing the same point in time as the given - * date. - */ - static fromDate(date: Date): Timestamp; - /** - * Creates a new timestamp from the given number of milliseconds. - * - * @param milliseconds - Number of milliseconds since Unix epoch - * 1970-01-01T00:00:00Z. - * @returns A new `Timestamp` representing the same point in time as the given - * number of milliseconds. - */ - static fromMillis(milliseconds: number): Timestamp; - /** - * Creates a new timestamp. - * - * @param seconds - The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive. - * @param nanoseconds - The non-negative fractions of a second at nanosecond - * resolution. Negative second values with fractions must still have - * non-negative nanoseconds values that count forward in time. Must be - * from 0 to 999,999,999 inclusive. - */ - constructor( - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - */ - seconds: number, - /** - * The fractions of a second at nanosecond resolution.* - */ - nanoseconds: number, - ); - /** - * Converts a `Timestamp` to a JavaScript `Date` object. This conversion - * causes a loss of precision since `Date` objects only support millisecond - * precision. - * - * @returns JavaScript `Date` object representing the same point in time as - * this `Timestamp`, with millisecond precision. - */ - toDate(): Date; - /** - * Converts a `Timestamp` to a numeric timestamp (in milliseconds since - * epoch). This operation causes a loss of precision. - * - * @returns The point in time corresponding to this timestamp, represented as - * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. - */ - toMillis(): number; - /** - * Returns true if this `Timestamp` is equal to the provided one. - * - * @param other - The `Timestamp` to compare against. - * @returns true if this `Timestamp` is equal to the provided one. - */ - isEqual(other: Timestamp): boolean; - /** Returns a textual representation of this `Timestamp`. */ - toString(): string; - /** - * Returns a JSON-serializable representation of this `Timestamp`. - */ - toJSON(): { - seconds: number; - nanoseconds: number; - type: string; - }; - /** - * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. - */ - static fromJSON(json: object): Timestamp; - /** - * Converts this object to a primitive string, which allows `Timestamp` objects - * to be compared using the `>`, `<=`, `>=` and `>` operators. - */ - valueOf(): string; -} -/** - * A reference to a transaction. - * - * The `Transaction` object passed to a transaction's `updateFunction` provides - * the methods to read and write data within the transaction context. See - * {@link runTransaction}. - */ -export declare class Transaction { - private constructor(); - /** - * Reads the document referenced by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be read. - * @returns A `DocumentSnapshot` with the read data. - */ - get( - documentRef: DocumentReference, - ): Promise>; - /** - * Writes to the document referred to by the provided {@link - * DocumentReference}. If the document does not exist yet, it will be created. - * - * @param documentRef - A reference to the document to be set. - * @param data - An object of the fields and values for the document. - * @throws Error - If the provided input is not a valid Firestore document. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - set( - documentRef: DocumentReference, - data: WithFieldValue, - ): this; - /** - * Writes to the document referred to by the provided {@link - * DocumentReference}. If the document does not exist yet, it will be created. - * If you provide `merge` or `mergeFields`, the provided data can be merged - * into an existing document. - * - * @param documentRef - A reference to the document to be set. - * @param data - An object of the fields and values for the document. - * @param options - An object to configure the set behavior. - * @throws Error - If the provided input is not a valid Firestore document. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - set( - documentRef: DocumentReference, - data: PartialWithFieldValue, - options: SetOptions, - ): this; - /** - * Updates fields in the document referred to by the provided {@link - * DocumentReference}. The update will fail if applied to a document that does - * not exist. - * - * @param documentRef - A reference to the document to be updated. - * @param data - An object containing the fields and values with which to - * update the document. Fields can contain dots to reference nested fields - * within the document. - * @throws Error - If the provided input is not valid Firestore data. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - update( - documentRef: DocumentReference, - data: UpdateData, - ): this; - /** - * Updates fields in the document referred to by the provided {@link - * DocumentReference}. The update will fail if applied to a document that does - * not exist. - * - * Nested fields can be updated by providing dot-separated field path - * strings or by providing `FieldPath` objects. - * - * @param documentRef - A reference to the document to be updated. - * @param field - The first field to update. - * @param value - The first value. - * @param moreFieldsAndValues - Additional key/value pairs. - * @throws Error - If the provided input is not valid Firestore data. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - update( - documentRef: DocumentReference, - field: string | FieldPath, - value: unknown, - ...moreFieldsAndValues: unknown[] - ): this; - /** - * Deletes the document referred to by the provided {@link DocumentReference}. - * - * @param documentRef - A reference to the document to be deleted. - * @returns This `Transaction` instance. Used for chaining method calls. - */ - delete( - documentRef: DocumentReference, - ): this; -} -/** - * @license - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Options to customize transaction behavior. - */ -export declare interface TransactionOptions { - /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ - readonly maxAttempts?: number; -} -/** - * Given a union type `U = T1 | T2 | ...`, returns an intersected type - * `(T1 & T2 & ...)`. - * - * Uses distributive conditional types and inference from conditional types. - * This works because multiple candidates for the same type variable in - * contra-variant positions causes an intersection type to be inferred. - * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types - * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type - */ -export declare type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends ( - k: infer I, -) => void - ? I - : never; -/** - * 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( - reference: DocumentReference, - data: UpdateData, -): Promise; -/** - * Updates fields in the document referred to by the specified - * `DocumentReference` The update will fail if applied to a document that does - * not exist. - * - * Nested fields can be updated by providing dot-separated field path - * strings or by providing `FieldPath` objects. - * - * @param reference - A reference to the document to update. - * @param field - The first field to update. - * @param value - The first value. - * @param moreFieldsAndValues - Additional key value pairs. - * @returns A `Promise` resolved once the data has been successfully written - * to the backend (note that it won't resolve while you're offline). - */ -export declare function updateDoc( - reference: DocumentReference, - field: string | FieldPath, - value: unknown, - ...moreFieldsAndValues: unknown[] -): Promise; -/** - * Creates a new `VectorValue` constructed with a copy of the given array of numbers. - * - * @param values - Create a `VectorValue` instance with a copy of this array of numbers. - * - * @returns A new `VectorValue` constructed with a copy of the given array of numbers. - */ -export declare function vector(values?: number[]): VectorValue; -/** - * Represents a vector type in Firestore documents. - * Create an instance with {@link vector}. - */ -export declare class VectorValue { - /* Excluded from this release type: __constructor */ - /** - * Returns a copy of the raw number array form of the vector. - */ - toArray(): number[]; - /** - * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. - */ - isEqual(other: VectorValue): boolean; - /** - * Returns a JSON-serializable representation of this `VectorValue` instance. - * - * @returns a JSON representation of this object. - */ - toJSON(): object; - /** - * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. - * - * @param json - a JSON object represention of a `VectorValue` instance. - * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a - * {@link FirestoreError} if an error occurs. - */ - static fromJSON(json: object): VectorValue; -} -/** - * 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/.github/scripts/compare-types/packages/remote-config/firebase-sdk.d.ts b/.github/scripts/compare-types/packages/remote-config/firebase-sdk.d.ts deleted file mode 100644 index 5776b0450d..0000000000 --- a/.github/scripts/compare-types/packages/remote-config/firebase-sdk.d.ts +++ /dev/null @@ -1,266 +0,0 @@ -/** - * Public types snapshot from the Firebase JS SDK (@firebase/remote-config). - * - * Source: firebase-js-sdk package @firebase/remote-config - * Modality: modular (tree-shakeable) API only - * - * This file is the reference snapshot used to detect API drift between the - * firebase-js-sdk and the @react-native-firebase/remote-config modular API. - * - * When a new version of the firebase-js-sdk ships with type changes, update - * this file with the new public types from @firebase/remote-config/dist/index.d.ts. - */ - -import { FirebaseApp } from '@firebase/app'; -import { FirebaseError } from '@firebase/app'; - -/** - * Makes the last fetched config available to the getters. - * @public - */ -export declare function activate(remoteConfig: RemoteConfig): Promise; - -/** - * Contains information about which keys have been updated. - * @public - */ -export declare interface ConfigUpdate { - /** - * Parameter keys whose values have been updated from the currently activated values. - * Includes keys that are added, deleted, or whose value, value source, or metadata has changed. - */ - getUpdatedKeys(): Set; -} - -/** - * Observer interface for receiving real-time Remote Config update notifications. - * @public - */ -export declare interface ConfigUpdateObserver { - next: (configUpdate: ConfigUpdate) => void; - error: (error: FirebaseError) => void; - complete: () => void; -} - -/** - * Defines the type for representing custom signals and their values. - * @public - */ -export declare interface CustomSignals { - [key: string]: string | number | null; -} - -/** - * Ensures the last activated config are available to the getters. - * @public - */ -export declare function ensureInitialized( - remoteConfig: RemoteConfig, -): Promise; - -/** - * Performs fetch and activate operations, as a convenience. - * @public - */ -export declare function fetchAndActivate( - remoteConfig: RemoteConfig, -): Promise; - -/** - * Fetches and caches configuration from the Remote Config service. - * @public - */ -export declare function fetchConfig(remoteConfig: RemoteConfig): Promise; - -/** - * Defines a successful response (200 or 304). - * @public - */ -export declare interface FetchResponse { - status: number; - eTag?: string; - config?: FirebaseRemoteConfigObject; - templateVersion?: number; - experiments?: FirebaseExperimentDescription[]; -} - -/** - * Summarizes the outcome of the last attempt to fetch config. - * @public - */ -export declare type FetchStatus = - | 'no-fetch-yet' - | 'success' - | 'failure' - | 'throttle'; - -/** - * Indicates the type of fetch request. - * @public - */ -export declare type FetchType = 'BASE' | 'REALTIME'; - -/** - * Defines experiment and variant attached to a config parameter. - * @public - */ -export declare interface FirebaseExperimentDescription { - experimentId: string; - variantId: string; - experimentStartTime: string; - triggerTimeoutMillis: string; - timeToLiveMillis: string; - affectedParameterKeys?: string[]; -} - -/** - * Defines a self-descriptive reference for config key-value pairs. - * @public - */ -export declare interface FirebaseRemoteConfigObject { - [key: string]: string; -} - -/** - * Gets all config. - * @public - */ -export declare function getAll( - remoteConfig: RemoteConfig, -): Record; - -/** - * Gets the value for the given key as a boolean. - * @public - */ -export declare function getBoolean( - remoteConfig: RemoteConfig, - key: string, -): boolean; - -/** - * Gets the value for the given key as a number. - * @public - */ -export declare function getNumber( - remoteConfig: RemoteConfig, - key: string, -): number; - -/** - * Returns a RemoteConfig instance for the given app. - * @public - */ -export declare function getRemoteConfig( - app?: FirebaseApp, - options?: RemoteConfigOptions, -): RemoteConfig; - -/** - * Gets the value for the given key as a string. - * @public - */ -export declare function getString( - remoteConfig: RemoteConfig, - key: string, -): string; - -/** - * Gets the Value for the given key. - * @public - */ -export declare function getValue(remoteConfig: RemoteConfig, key: string): Value; - -/** - * Returns true if a RemoteConfig instance can be initialized in this environment. - * @public - */ -export declare function isSupported(): Promise; - -/** - * Defines levels of Remote Config logging. - * @public - */ -export declare type LogLevel = 'debug' | 'error' | 'silent'; - -/** - * Starts listening for real-time config updates from the Remote Config backend. - * @public - */ -export declare function onConfigUpdate( - remoteConfig: RemoteConfig, - observer: ConfigUpdateObserver, -): Unsubscribe; - -/** - * The Firebase Remote Config service interface. - * @public - */ -export declare interface RemoteConfig { - app: FirebaseApp; - settings: RemoteConfigSettings; - defaultConfig: { - [key: string]: string | number | boolean; - }; - fetchTimeMillis: number; - lastFetchStatus: FetchStatus; -} - -/** - * Options for Remote Config initialization. - * @public - */ -export declare interface RemoteConfigOptions { - templateId?: string; - initialFetchResponse?: FetchResponse; -} - -/** - * Defines configuration options for the Remote Config SDK. - * @public - */ -export declare interface RemoteConfigSettings { - minimumFetchIntervalMillis: number; - fetchTimeoutMillis: number; -} - -/** - * Sets the custom signals for the app instance. - * @public - */ -export declare function setCustomSignals( - remoteConfig: RemoteConfig, - customSignals: CustomSignals, -): Promise; - -/** - * Defines the log level to use. - * @public - */ -export declare function setLogLevel( - remoteConfig: RemoteConfig, - logLevel: LogLevel, -): void; - -/** - * A function that unsubscribes from a real-time event stream. - * @public - */ -export declare type Unsubscribe = () => void; - -/** - * Wraps a value with metadata and type-safe getters. - * @public - */ -export declare interface Value { - asBoolean(): boolean; - asNumber(): number; - asString(): string; - getSource(): ValueSource; -} - -/** - * Indicates the source of a value. - * @public - */ -export declare type ValueSource = 'static' | 'default' | 'remote'; diff --git a/.github/scripts/compare-types/packages/storage/storage-js-sdk.d.ts b/.github/scripts/compare-types/packages/storage/storage-js-sdk.d.ts deleted file mode 100644 index 83d657bc0d..0000000000 --- a/.github/scripts/compare-types/packages/storage/storage-js-sdk.d.ts +++ /dev/null @@ -1,725 +0,0 @@ -/** - * Cloud Storage for Firebase - * - * @packageDocumentation - */ -import { CompleteFn , EmulatorMockTokenOptions , FirebaseError , NextFn , Subscribe , Unsubscribe } from '@firebase/util'; -import { FirebaseApp } from '@firebase/app'; -/** - * 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/.github/scripts/compare-types/src/index.ts b/.github/scripts/compare-types/src/index.ts index 063733e1bd..e9e05292d5 100644 --- a/.github/scripts/compare-types/src/index.ts +++ b/.github/scripts/compare-types/src/index.ts @@ -36,7 +36,7 @@ async function main(): Promise { for (const pkg of packages) { checkFilesExist( pkg.firebaseSdkTypesPaths, - `firebase-js-sdk snapshot(s) for "${pkg.name}"`, + `installed firebase-js-sdk type(s) for "${pkg.name}"`, ); checkFilesExist( pkg.rnFirebaseModularFiles, diff --git a/.github/scripts/compare-types/src/parse.ts b/.github/scripts/compare-types/src/parse.ts index cafb35e7d0..274f141134 100644 --- a/.github/scripts/compare-types/src/parse.ts +++ b/.github/scripts/compare-types/src/parse.ts @@ -1,8 +1,9 @@ /** * Uses ts-morph to parse .d.ts files and extract export shapes. * We use getTypeNode()?.getText() throughout to read the type text as-written - * in the source file, so unresolved external imports (e.g. @firebase/app) are - * not a problem — they simply appear as their short name strings. + * in the source file. External imports still need normal TypeScript module + * resolution so wrapper declarations like `firebase/storage` can re-export the + * public declarations from `@firebase/storage`. */ import fs from 'fs'; @@ -10,6 +11,9 @@ import { Project, Node, SyntaxKind, + ModuleKind, + ModuleResolutionKind, + ScriptTarget, type ClassDeclaration, type ExportedDeclarations, type SourceFile, @@ -296,6 +300,9 @@ function createProject(): Project { return new Project({ skipAddingFilesFromTsConfig: true, compilerOptions: { + target: ScriptTarget.ES2022, + module: ModuleKind.NodeNext, + moduleResolution: ModuleResolutionKind.NodeNext, // Don't error on declaration files from libraries we can't resolve. skipLibCheck: true, // Allow JS files (won't be added, but prevents config errors). @@ -323,7 +330,7 @@ function collectExportsFromSourceFile( // --------------------------------------------------------------------------- /** - * Parses a single self-contained .d.ts file (e.g. the firebase-js-sdk snapshot) + * Parses a single .d.ts file from the installed Firebase JS SDK * and returns a map of export name → ExportEntry. */ export function parseSingleFile(filePath: string): Map { diff --git a/.github/scripts/compare-types/src/registry.ts b/.github/scripts/compare-types/src/registry.ts index 5c6520a4e2..851ed89851 100644 --- a/.github/scripts/compare-types/src/registry.ts +++ b/.github/scripts/compare-types/src/registry.ts @@ -2,24 +2,22 @@ * Package registry — defines which packages are compared and where to find * their type files. * - * To add a new package: - * 1. Create .github/scripts/compare-types/packages//firebase-sdk.d.ts - * with the public types copied from the firebase-js-sdk release. - * 2. Create .github/scripts/compare-types/packages//config.ts - * documenting any known differences. - * 3. Add an entry to the `packages` array below. + * Firebase JS SDK declarations are resolved from the repository root + * `node_modules/firebase` package, so the comparison always uses the installed + * SDK version instead of checked-in declaration snapshots. */ +import fs from 'fs'; import path from 'path'; import type { PackageConfig } from './types'; -import storageConfig from '../packages/storage/config'; -import aiConfig from '../packages/ai/config'; -import databaseConfig from '../packages/database/config'; -import appCheckConfig from '../packages/app-check/config'; -import firestoreConfig from '../packages/firestore/config'; -import firestorePipelinesConfig from '../packages/firestore-pipelines/config'; -import remoteConfigConfig from '../packages/remote-config/config'; +import storageConfig from '../configs/storage'; +import aiConfig from '../configs/ai'; +import databaseConfig from '../configs/database'; +import appCheckConfig from '../configs/app-check'; +import firestoreConfig from '../configs/firestore'; +import firestorePipelinesConfig from '../configs/firestore-pipelines'; +import remoteConfigConfig from '../configs/remote-config'; const SCRIPT_DIR = path.resolve(__dirname, '..'); const REPO_ROOT = path.resolve(SCRIPT_DIR, '..', '..', '..'); @@ -28,8 +26,7 @@ export interface PackageEntry { /** Short name used in reports (e.g. "remote-config"). */ name: string; /** - * Paths to the firebase-js-sdk public type snapshot(s) (.d.ts). - * Kept in .github/scripts/compare-types/packages//. + * Paths to the installed firebase-js-sdk public type files. * Exports from all files are merged (first file wins for duplicate names). */ firebaseSdkTypesPaths: string[]; @@ -51,15 +48,62 @@ function rnDist(packageName: string): string { return path.join(REPO_ROOT, 'packages', packageName, 'dist', 'typescript', 'lib'); } +const FIREBASE_PACKAGE_DIR = path.join(REPO_ROOT, 'node_modules', 'firebase'); +const FIREBASE_PACKAGE_JSON = path.join(FIREBASE_PACKAGE_DIR, 'package.json'); + +interface FirebasePackageJson { + exports?: Record; +} + +function readFirebasePackageJson(): FirebasePackageJson { + if (!fs.existsSync(FIREBASE_PACKAGE_JSON)) { + throw new Error( + `Firebase package not found at ${FIREBASE_PACKAGE_JSON}. Run \`yarn\` from the repository root before running compare-types.`, + ); + } + + return JSON.parse(fs.readFileSync(FIREBASE_PACKAGE_JSON, 'utf8')) as FirebasePackageJson; +} + +const firebasePackageJson = readFirebasePackageJson(); + +function firebaseTypes(packageName: string, optional = false): string | null { + const exportName = `./${packageName}`; + const exportEntry = firebasePackageJson.exports?.[exportName]; + const typesPath = (exportEntry && typeof exportEntry === 'object') ? (exportEntry as any).types : undefined; + + if (!typesPath) { + if (optional) { + console.warn( + `Skipping firebase/${packageName}: no public Firebase type export found in ${FIREBASE_PACKAGE_JSON}.`, + ); + return null; + } + + throw new Error( + `No public Firebase type export found for "firebase/${packageName}" in ${FIREBASE_PACKAGE_JSON}.`, + ); + } + + return path.resolve(FIREBASE_PACKAGE_DIR, typesPath); +} + +function requiredFirebaseTypes(packageName: string): string { + return firebaseTypes(packageName) as string; +} + +function optionalFirebasePackage( + packageName: string, + createEntry: (typesPath: string) => PackageEntry, +): PackageEntry[] { + const typesPath = firebaseTypes(packageName, true); + return typesPath ? [createEntry(typesPath)] : []; +} + export const packages: PackageEntry[] = [ { name: 'storage', - firebaseSdkTypesPaths: [path.join( - SCRIPT_DIR, - 'packages', - 'storage', - 'storage-js-sdk.d.ts', - )], + firebaseSdkTypesPaths: [requiredFirebaseTypes('storage')], rnFirebaseModularFiles: [ path.join(rnDist('storage'), 'types', 'storage.d.ts'), path.join(rnDist('storage'), 'modular.d.ts'), @@ -73,9 +117,7 @@ export const packages: PackageEntry[] = [ }, { name: 'remote-config', - firebaseSdkTypesPaths: [ - path.join(SCRIPT_DIR, 'packages', 'remote-config', 'firebase-sdk.d.ts'), - ], + firebaseSdkTypesPaths: [requiredFirebaseTypes('remote-config')], rnFirebaseModularFiles: [ path.join(rnDist('remote-config'), 'types', 'remote-config.d.ts'), path.join(rnDist('remote-config'), 'modular.d.ts'), @@ -88,7 +130,7 @@ export const packages: PackageEntry[] = [ }, { name: 'ai', - firebaseSdkTypesPaths: [path.join(SCRIPT_DIR, 'packages', 'ai', 'ai-sdk.d.ts')], + firebaseSdkTypesPaths: [requiredFirebaseTypes('ai')], rnFirebaseModularFiles: [path.join(rnDist('ai'), 'index.d.ts')], rnFirebaseSupportFiles: [ path.join(rnDist('ai'), 'backend.d.ts'), @@ -122,7 +164,7 @@ export const packages: PackageEntry[] = [ }, { name: 'database', - firebaseSdkTypesPaths: [path.join(SCRIPT_DIR, 'packages', 'database', 'firebase-sdk.d.ts')], + firebaseSdkTypesPaths: [requiredFirebaseTypes('database')], rnFirebaseModularFiles: [ path.join(rnDist('database'), 'types', 'database.d.ts'), path.join(rnDist('database'), 'modular.d.ts'), @@ -143,9 +185,7 @@ export const packages: PackageEntry[] = [ }, { name: 'app-check', - firebaseSdkTypesPaths: [ - path.join(SCRIPT_DIR, 'packages', 'app-check', 'app-check-sdk.d.ts'), - ], + firebaseSdkTypesPaths: [requiredFirebaseTypes('app-check')], rnFirebaseModularFiles: [ path.join(rnDist('app-check'), 'types', 'appcheck.d.ts'), path.join(rnDist('app-check'), 'modular.d.ts'), @@ -158,9 +198,7 @@ export const packages: PackageEntry[] = [ }, { name: 'firestore', - firebaseSdkTypesPaths: [ - path.join(SCRIPT_DIR, 'packages', 'firestore', 'firestore-js-sdk.d.ts'), - ], + firebaseSdkTypesPaths: [requiredFirebaseTypes('firestore')], rnFirebaseModularFiles: [ path.join(rnDist('firestore'), 'types', 'firestore.d.ts'), path.join(rnDist('firestore'), 'modular.d.ts'), @@ -193,11 +231,9 @@ export const packages: PackageEntry[] = [ ], config: firestoreConfig, }, - { + ...optionalFirebasePackage('firestore/pipelines', firebaseTypesPath => ({ name: 'firestore-pipelines', - firebaseSdkTypesPaths: [ - path.join(SCRIPT_DIR, 'packages', 'firestore-pipelines', 'pipelines.d.ts'), - ], + firebaseSdkTypesPaths: [firebaseTypesPath], rnFirebaseModularFiles: [path.join(rnDist('firestore'), 'pipelines', 'index.d.ts')], rnFirebaseSupportFiles: [ path.join(rnDist('firestore'), 'pipelines', 'expressions.d.ts'), @@ -210,7 +246,7 @@ export const packages: PackageEntry[] = [ path.join(rnDist('firestore'), 'pipelines', 'types.d.ts'), ], config: firestorePipelinesConfig, - }, + })), ]; diff --git a/.github/scripts/compare-types/src/report.ts b/.github/scripts/compare-types/src/report.ts index 3347f673a3..f454bcad31 100644 --- a/.github/scripts/compare-types/src/report.ts +++ b/.github/scripts/compare-types/src/report.ts @@ -1,3 +1,5 @@ +/* eslint-disable no-console */ + /** * Terminal output formatting for comparison results. * @@ -61,7 +63,7 @@ function countStale(result: ComparisonResult): number { } /** - * Prints stale `config.ts` entries and returns how many were printed. + * Prints stale config entries and returns how many were printed. * These must run even when there are zero live diffs, otherwise a resolved * API (e.g. an export removed from `missingInRN` in reality) would never * force updating the comparison registry. @@ -78,7 +80,7 @@ function printStaleRegistrySection(result: ComparisonResult): number { console.log( `${c(RED, ' ✗')} ${c(BOLD, name)}${c(RED, ' [STALE missingInRN]')}${c( DIM, - ` — ${name} exists in React Native Firebase but is still listed under missingInRN in config.ts; remove it or reclassify (e.g. differentShape) if types still differ.`, + ` — ${name} exists in React Native Firebase but is still listed under missingInRN in configs/${result.packageName}.ts; remove it or reclassify (e.g. differentShape) if types still differ.`, )}`, ); } @@ -87,7 +89,7 @@ function printStaleRegistrySection(result: ComparisonResult): number { console.log( `${c(RED, ' ✗')} ${c(BOLD, name)}${c(RED, ' [STALE extraInRN]')}${c( DIM, - ` — ${name} is no longer an extra export in React Native Firebase but is still listed under extraInRN; remove from config.ts.`, + ` — ${name} is no longer an extra export in React Native Firebase but is still listed under extraInRN; remove from configs/${result.packageName}.ts.`, )}`, ); } @@ -96,7 +98,7 @@ function printStaleRegistrySection(result: ComparisonResult): number { console.log( `${c(RED, ' ✗')} ${c(BOLD, name)}${c(RED, ' [STALE differentShape]')}${c( DIM, - ` — ${name} now matches the firebase-js-sdk shape; remove from differentShape in config.ts.`, + ` — ${name} now matches the firebase-js-sdk shape; remove from differentShape in configs/${result.packageName}.ts.`, )}`, ); } @@ -104,6 +106,77 @@ function printStaleRegistrySection(result: ComparisonResult): number { return totalStale; } +// --------------------------------------------------------------------------- +// Final summary +// --------------------------------------------------------------------------- + +function countUndocumented(result: ComparisonResult): number { + return ( + result.undocumentedMissing.length + + result.undocumentedExtra.length + + result.undocumentedDifferentShape.length + ); +} + +function countDiffs(result: ComparisonResult): number { + return ( + result.missing.length + + result.extra.length + + result.differentShape.length + ); +} + +function pad(value: string | number, width: number): string { + return String(value).padEnd(width, ' '); +} + +function printPackageSummary(results: ComparisonResult[]): void { + const packageWidth = Math.max( + 'Package'.length, + ...results.map(result => result.packageName.length), + ); + + console.log(`\n${c(BOLD, '📊 Package Summary')}`); + console.log( + c( + DIM, + [ + pad('Package', packageWidth), + pad('Missing', 8), + pad('Extra', 6), + pad('Different', 10), + pad('Total', 7), + pad('Undoc', 7), + pad('Stale', 7), + 'Status', + ].join(' '), + ), + ); + + for (const result of results) { + const totalDiffs = countDiffs(result); + const totalUndoc = countUndocumented(result); + const totalStale = countStale(result); + const hasFailures = totalUndoc > 0 || totalStale > 0; + const status = hasFailures + ? c(RED, '✗ needs config update') + : c(GREEN, '✓ documented'); + + console.log( + [ + pad(result.packageName, packageWidth), + pad(result.missing.length, 8), + pad(result.extra.length, 6), + pad(result.differentShape.length, 10), + pad(totalDiffs, 7), + pad(totalUndoc, 7), + pad(totalStale, 7), + status, + ].join(' '), + ); + } +} + // --------------------------------------------------------------------------- // Public API // --------------------------------------------------------------------------- @@ -124,11 +197,7 @@ export function printReport(results: ComparisonResult[]): boolean { for (const result of results) { console.log(`\n${c(BOLD, `📦 ${result.packageName}`)}`); - const totalDiffs = - result.missing.length + - result.extra.length + - result.differentShape.length; - + const totalDiffs = countDiffs(result); const totalStale = countStale(result); if (totalDiffs === 0 && totalStale === 0) { @@ -140,7 +209,7 @@ export function printReport(results: ComparisonResult[]): boolean { console.log( c( GREEN, - ' ✓ Exported types match the firebase-js-sdk snapshot (no live diffs)', + ' ✓ Exported types match the installed firebase-js-sdk types (no live diffs)', ), ); } @@ -188,33 +257,31 @@ export function printReport(results: ComparisonResult[]): boolean { const printedStale = printStaleRegistrySection(result); // --- Summary --- - const totalUndoc = - result.undocumentedMissing.length + - result.undocumentedExtra.length + - result.undocumentedDifferentShape.length; + const totalUndoc = countUndocumented(result); if (totalUndoc > 0 || printedStale > 0) { hasFailures = true; if (totalUndoc > 0) { console.log( - `\n ${c(RED, `✗ ${totalUndoc} undocumented difference(s) — add them to config.ts with a reason`)}`, + `\n ${c(RED, `✗ ${totalUndoc} undocumented difference(s) — add them to configs/${result.packageName}.ts with a reason`)}`, ); } if (printedStale > 0) { console.log( `\n ${c( RED, - `✗ ${printedStale} stale registry entry/entries — update packages//config.ts for the type comparison tool`, + `✗ ${printedStale} stale registry entry/entries — update configs/${result.packageName}.ts for the type comparison tool`, )}`, ); } } else { console.log( - `\n ${c(GREEN, `✓ All ${totalDiffs} difference(s) are documented in config.ts`)}`, + `\n ${c(GREEN, `✓ All ${totalDiffs} difference(s) are documented in configs/${result.packageName}.ts`)}`, ); } } + printPackageSummary(results); console.log(''); return hasFailures; } diff --git a/.github/scripts/compare-types/src/types.ts b/.github/scripts/compare-types/src/types.ts index f8be85d801..f70edfca8f 100644 --- a/.github/scripts/compare-types/src/types.ts +++ b/.github/scripts/compare-types/src/types.ts @@ -141,7 +141,8 @@ export interface ComparisonResult { undocumentedDifferentShape: string[]; /** * Config entries that are no longer needed because the API now matches the - * firebase-js-sdk. These should be removed from config.ts (CI failures). + * firebase-js-sdk. These should be removed from configs/.ts + * (CI failures). */ staleConfigMissing: string[]; staleConfigExtra: string[]; diff --git a/.github/scripts/compare-types/tsconfig.json b/.github/scripts/compare-types/tsconfig.json index e4fab5729c..c98ae1096e 100644 --- a/.github/scripts/compare-types/tsconfig.json +++ b/.github/scripts/compare-types/tsconfig.json @@ -9,5 +9,5 @@ "outDir": "dist", "rootDir": "." }, - "include": ["src/**/*.ts", "packages/**/*.ts"] + "include": ["src/**/*.ts", "configs/**/*.ts"] }