# API Reference (Full)

---
source: /docs/api.md

# API Reference

Technical reference documentation for Bkper APIs and SDKs. Use a REST API directly or choose a client library for your platform.

  - [REST API](https://bkper.com/docs/api/rest.md): Full OpenAPI reference for the Bkper REST API — endpoints, parameters, and response schemas.
  - [AI API](https://bkper.com/docs/api/ai.md): OpenAPI reference for Bkper AI — discover models and create complete or streaming responses.
  - [bkper-js](https://bkper.com/docs/api/bkper-js.md): JavaScript/TypeScript client library for Bkper — classes, interfaces, and type definitions.
  - [bkper-gs](https://bkper.com/docs/api/bkper-gs.md): Google Apps Script library for Bkper — use Bkper directly in Google Sheets and Apps Script projects.
  - [bkper-web-auth](https://bkper.com/docs/api/bkper-web-auth.md): Web authentication SDK for Bkper — OAuth flows, token management, and session handling.
  - [bkper-api-types](https://bkper.com/docs/api/bkper-api-types.md): TypeScript type definitions for the Bkper API — shared interfaces and enumerations.
  - [Design Tokens](https://bkper.com/docs/api/bkper-web-design.md): CSS design tokens — typography, spacing, colors, and theming for Bkper web applications.

---
source: /docs/api/bkper-api-types.md

# bkper-api-types

This package contains Typescript definitions for the [Bkper REST API](https://bkper.com/docs/#rest-api).

The types are generated based on the Bkper [Open API spec](https://bkper.com/docs/api/rest/openapi.json) using the [dtsgenerator](https://github.com/horiuchi/dtsgenerator) tool.

More information at the [Bkper Developer Documentation](https://bkper.com/docs/#rest-api)

[![npm (scoped)](https://img.shields.io/npm/v/@bkper/bkper-api-types?color=%235889e4)](https://www.npmjs.com/package/@bkper/bkper-api-types) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--api--types-blue?logo=github)](https://github.com/bkper/bkper-api-types)

### 1) Add the package:

```bash
npm i -S @bkper/bkper-api-types
```
### 2) Configure tsconfig.json:

```
{
    "compilerOptions": {
        "typeRoots" : ["node_modules/@bkper", "node_modules/@types" ]
    }
}
```

[Learn more](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types) about **@types**, **typeRoots** and **types**

---
source: /docs/api/bkper-gs.md

# bkper-gs

[![GitHub](https://img.shields.io/badge/bkper%2Fbkper--gs-blue?logo=github)](https://github.com/bkper/bkper-gs)

# Summary

This package contains Typescript definitions for [BkperApp](https://bkper.com/docs/bkper-gs/)

### 1) Add the package:

```
npm i -S @bkper/bkper-gs-types
```
or
```
yarn add --dev @bkper/bkper-gs-types
```

### 2) Configure tsconfig.json:

```
{
    "compilerOptions": {
        "typeRoots" : ["node_modules/@bkper", "node_modules/@types" ]
    }
}
```

[Learn more](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types) about **@types**, **typeRoots** and **types**

# Details

Generated using [clasp-types](https://github.com/maelcaldas/clasp-types)

---
source: /docs/api/bkper-js.md

# bkper-js

bkper-js library is a simple and secure way to access the [Bkper REST API](https://bkper.com/docs/api/rest) on Node.js and modern browsers.

It provides a set of classes and functions to interact with the Bkper API, including authentication, authorization, and data manipulation.

[![npm](https://img.shields.io/npm/v/bkper-js?color=%235889e4)](https://www.npmjs.com/package/bkper-js) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--js-blue?logo=github)](https://github.com/bkper/bkper-js)

### Add the package:

```bash
npm i -S bkper-js
```

### CDN / Browser

The simplest way to use bkper-js in a browser — no build tools, no npm, just a `<script>` tag and a valid access token. Works on **any domain**.

```html
<script src="https://cdn.jsdelivr.net/npm/bkper-js@2/dist/bkper.min.js"></script>
<script>
    const { Bkper } = bkperjs;

    async function listBooks(token) {
        Bkper.setConfig({
            oauthTokenProvider: async () => token,
        });
        const bkper = new Bkper();
        return await bkper.getBooks();
    }

    // Example: prompt for a token and list books
    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('go').addEventListener('click', async () => {
            const token = document.getElementById('token').value;
            const books = await listBooks(token);
            document.getElementById('output').textContent = books.map(b => b.getName()).join('\n');
        });
    });
</script>

<input id="token" placeholder="Paste your access token" />
<button id="go">List Books</button>
<pre id="output"></pre>
```

Get an access token with the [Bkper CLI](https://www.npmjs.com/package/bkper):

```bash
bkper auth login   # one-time setup
bkper auth token   # prints a token (valid for 1 hour)
```

Pin to a specific version by replacing `@2` with e.g. `@2.31.0`.

### Node.js / CLI Scripts

For local scripts and CLI tools, use the [bkper](https://www.npmjs.com/package/bkper) CLI package for authentication:

```typescript
import { Bkper } from 'bkper-js';
import { getOAuthToken } from 'bkper';

// Configure with CLI authentication
Bkper.setConfig({
    oauthTokenProvider: async () => getOAuthToken(),
});

// Create Bkper instance
const bkper = new Bkper();

// Get a book and work with it
const book = await bkper.getBook('your-book-id');
console.log(`Book: ${book.getName()}`);

// List all books
const books = await bkper.getBooks();
console.log(`You have ${books.length} books`);
```

First, login via CLI: `bkper auth login`

### npm + Bundler

If you are using a bundler (Vite, webpack, esbuild, etc.), install from npm and provide an access token the same way as the CDN example:

```typescript
import { Bkper } from 'bkper-js';

Bkper.setConfig({
    oauthTokenProvider: async () => 'your-access-token',
});

const bkper = new Bkper();
const books = await bkper.getBooks();
```

### Web Applications on \*.bkper.app

> **Note:** `@bkper/web-auth` **only works on `*.bkper.app` subdomains**. Its session cookies are scoped to the `.bkper.app` domain and will not work on any other domain. For apps on other domains, use the [CDN / Browser](#cdn--browser) approach with an access token instead.

For apps hosted on `*.bkper.app` subdomains, use the [@bkper/web-auth](https://www.npmjs.com/package/@bkper/web-auth) SDK for built-in OAuth login flow:

```typescript
import { Bkper } from 'bkper-js';
import { BkperAuth } from '@bkper/web-auth';

// Initialize authentication
const auth = new BkperAuth({
    onLoginSuccess: () => initializeApp(),
    onLoginRequired: () => showLoginButton(),
});

// Restore session on app load
await auth.init();

// Configure Bkper with web auth
Bkper.setConfig({
    oauthTokenProvider: async () => auth.getAccessToken(),
});

// Create Bkper instance and use it
const bkper = new Bkper();
const books = await bkper.getBooks();
```

See the [@bkper/web-auth documentation](https://bkper.com/docs/api/bkper-web-auth) for more details.

For Bkper Platform app server routes under `/api/*`, send `Authorization: Bearer ${auth.getAccessToken()}` from the client. The server route can use `new Bkper()` without a token provider because platform outbound auth injects the validated user's token on Bkper API calls.

### API Key (Optional)

API keys are optional and only needed for dedicated quota limits. If not provided, requests use a shared managed quota via the Bkper API proxy.

```typescript
Bkper.setConfig({
    oauthTokenProvider: async () => getOAuthToken(),
    apiKeyProvider: async () => process.env.BKPER_API_KEY, // Optional - for dedicated quota
});
```

---
source: /docs/api/bkper-web-auth.md

# @bkper/web-auth

[![npm](https://img.shields.io/npm/v/@bkper/web-auth?color=%235889e4)](https://www.npmjs.com/package/@bkper/web-auth) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--web--sdks-blue?logo=github)](https://github.com/bkper/bkper-web-sdks)

# @bkper/web-auth

OAuth authentication SDK for apps on the [Bkper Platform](https://bkper.com/docs/build/apps/overview) (`*.bkper.app` subdomains).

## Installation

```bash
bun add @bkper/web-auth
```
## Quick Start

```typescript
import { BkperAuth } from '@bkper/web-auth';

// Initialize client with callbacks
const auth = new BkperAuth({
    onLoginSuccess: () => {
        console.log('User authenticated!');
        loadUserData();
    },
    onLoginRequired: () => {
        console.log('Please sign in');
        showLoginButton();
    },
});

// Initialize authentication flow on app load
await auth.init();

// Make an authenticated request with automatic token refresh and one retry
const response = await auth.authenticatedFetch('/data');
```

## Authenticated Requests

`authenticatedFetch()` implements the standard Fetch API contract. It adds the current bearer token to a request. If the response is `401`, it refreshes the token and retries exactly once. Other response statuses are returned unchanged.

```typescript
const response = await auth.authenticatedFetch('/data', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ value: 42 }),
});
```

The method can also be supplied to any HTTP client that accepts a Fetch-compatible function:

```typescript
const fetchWithAuth = auth.authenticatedFetch.bind(auth);
```

Call `init()` before the first authenticated request. If no token is available, or the session cannot be refreshed, `onLoginRequired` is called and the request rejects with an authentication-required error. If the retried request also returns `401`, that response is returned without another retry. Concurrent refresh calls share one refresh request.

To prevent accidental token disclosure, authenticated requests are restricted to:

- HTTPS origins on `bkper.app` or its subdomains
- The current `localhost` or `127.0.0.1` origin during local development

Request paths are not restricted.

### Using with bkper-js

`@bkper/web-auth` does not depend on `bkper-js`, but they can be connected through the client configuration. Provide the current token for each request and refresh it when the Bkper API reports an expired login:

```typescript
import { Bkper } from 'bkper-js';

const bkper = new Bkper({
    oauthTokenProvider: async () => auth.getAccessToken(),
    requestRetryHandler: async (status, _error, attempt) => {
        if (status === 403 && attempt === 1) {
            await auth.refresh();
        }
    },
});
```

`bkper-js` owns its request and retry lifecycle. `@bkper/web-auth` remains responsible only for the current access token and session refresh.

## What's Included

-   OAuth authentication SDK for apps on `*.bkper.app` subdomains
-   Callback-based API for authentication events
-   OAuth flow with in-memory token management
-   Single-flight token refresh mechanism
-   Authenticated Fetch API with one-time refresh and retry
-   TypeScript support with full type definitions

## How It Works

**Session Persistence:**

-   Access tokens are stored in-memory (cleared on page refresh)
-   Sessions persist via HTTP-only cookies scoped to the `.bkper.app` domain
-   Call `init()` on app load to restore an access token from the session
-   Protected resources still require `Authorization: Bearer <token>`; session cookies only restore client auth state

> **Note:** This SDK only works for apps hosted on `*.bkper.app` subdomains. Applications on other domains must provide a valid access token through their own authentication mechanism.

**Security:**

-   HTTP-only cookies protect refresh tokens from XSS
-   In-memory access tokens minimize exposure

## TypeScript Support

This package is written in TypeScript and provides full type definitions out of the box. All public APIs are fully typed, including callbacks and configuration options.

```typescript
import { BkperAuth, BkperAuthConfig } from '@bkper/web-auth';

const config: BkperAuthConfig = {
    onLoginSuccess: () => console.log('Authenticated'),
    onError: error => console.error('Auth error:', error),
};

const auth = new BkperAuth(config);
```

## Browser Compatibility

This package requires a modern browser with support for:

-   [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#browser_compatibility) for HTTP requests
-   [Location API](https://developer.mozilla.org/en-US/docs/Web/API/Location) for login/logout redirects

The app must be deployed to a `*.bkper.app` subdomain for session-cookie token restoration to work.

---
source: /docs/api/bkper-web-design.md

# Design Tokens

[![npm](https://img.shields.io/npm/v/@bkper/web-design?color=%235889e4)](https://www.npmjs.com/package/@bkper/web-design) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--web--sdks-blue?logo=github)](https://github.com/bkper/bkper-web-sdks)

# @bkper/web-design

Bkper's design system - CSS variables, tokens, and themes.

## Installation

```bash
npm install @bkper/web-design
```

## Usage

Import in your build system:

```css
@import '@bkper/web-design';
```

Or link directly in HTML:

```html
<link rel="stylesheet" href="node_modules/@bkper/web-design/src/bkper.css">
```

Alternatively, skip installation and link directly to a hosted version (CDN):

```html
<link rel="stylesheet" href="https://bkper.app/design/v2/style.css">
```

Note: The CDN serves the most recent npm release.

## What's Included

- CSS custom properties (variables)
- Account type colors: blue (Assets), yellow (Liabilities), green (Incoming), red (Outgoing)
- Light/dark theme support
- Typography scale
- Spacing scale
- Border and color tokens

## Web Awesome Integration

This package works standalone with sensible default values. If [Web Awesome](https://www.webawesome.com/) is loaded, Bkper tokens will automatically inherit from Web Awesome's design system for seamless integration.

---
source: /docs/api/ai.md

# AI API

> Full OpenAPI reference for Bkper AI — model discovery, complete responses, streaming events, and schemas.

Public inference API implementing the stateless Bkper [Open Responses 2026-04-24](https://www.openresponses.org/specification/2026-04-24) profile.

## Base URL

```text
https://ai.bkper.app
```

## OpenAPI specification

The canonical machine-readable contract is available at [https://ai.bkper.app/openapi.json](https://ai.bkper.app/openapi.json).

## Authentication

Send a Bkper OAuth access token with every inference request:

```text
Authorization: Bearer <Bkper access token>
```

See the [Bkper AI provider guide](https://bkper.com/docs/ai/bkper-ai-provider) for token setup and client configuration.

## Request workflow

1. Call `GET /v1/models` to discover the current public model IDs, capabilities, limits, and usage rates.
2. Select a returned model ID.
3. Call `POST /v1/responses` with that model and explicit input.

Use `stream: false` for a complete JSON response. Use `stream: true` for semantic server-sent events ending with `data: [DONE]`.

## Stateless operation and privacy

Bkper AI does not persist response state. Omitted `store` defaults to `false`; the only accepted explicit value is `store: false`. Continue a conversation by sending explicit prior items in `input`.

Bkper usage logs record attribution, status, token, cache, and cost metadata. They exclude prompt and response content. Provider-specific retention and caching boundaries are documented in the Bkper AI provider guide.

## Usage

Requests consume the authenticated user's Bkper AI allowance. The model catalog provides current effective rates and limits. New requests stop when the recorded allowance is exhausted; Bkper does not create automatic paid AI overages. See [Models and Usage](https://bkper.com/docs/ai/models) for policy details.

## Attribution

Clients may send the optional `bkper-ai-source` header with a stable lowercase application identifier so usage can be attributed to that client.

## Specification

- OpenAPI: `3.1.0`
- API version: `v1`
- External documentation:
```json
{
  "description": "Bkper AI provider documentation",
  "url": "https://bkper.com/docs/ai/bkper-ai-provider"
}
```

### Servers

```json
[
  {
    "url": "https://ai.bkper.app"
  }
]
```

### Specification extensions

```json
{
  "x-open-responses-version": "2026-04-24",
  "x-open-responses-specification": "https://www.openresponses.org/specification/2026-04-24"
}
```

## Tags

```json
[
  {
    "name": "Models"
  },
  {
    "name": "Responses"
  }
]
```

## Authentication

```json
{
  "bkperBearer": {
    "type": "http",
    "scheme": "bearer",
    "bearerFormat": "Bkper OAuth access token",
    "description": "Send a Bkper OAuth access token. See [token setup](https://bkper.com/docs/ai/bkper-ai-provider#get-a-token-for-local-testing)."
  }
}
```

## Operations

### `GET /v1/models` — List available models

Returns the current model IDs and effective capabilities available through Bkper AI.

Operation contract:

```json
{
  "tags": [
    "Models"
  ],
  "operationId": "listModels",
  "summary": "List available models",
  "description": "Returns the current model IDs and effective capabilities available through Bkper AI.",
  "security": [],
  "responses": {
    "200": {
      "description": "Available Bkper AI models",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/ModelList"
          }
        }
      }
    }
  }
}
```

### `POST /v1/responses` — Generate a response

Generates a response using the Bkper Open Responses 2026-04-24 profile. Bkper AI is stateless: send explicit prior input and output items to continue a conversation. Model IDs, reasoning levels, structured-output support, limits, and inline file types are published by GET /v1/models. Some request controls are model-dependent and return a 400 error when unavailable. Set stream to true to receive semantic server-sent events ending with data: [DONE].

Operation contract:

```json
{
  "summary": "Generate a response",
  "description": "Generates a response using the Bkper Open Responses 2026-04-24 profile. Bkper AI is stateless: send explicit prior input and output items to continue a conversation. Model IDs, reasoning levels, structured-output support, limits, and inline file types are published by GET /v1/models. Some request controls are model-dependent and return a 400 error when unavailable. Set stream to true to receive semantic server-sent events ending with data: [DONE].",
  "operationId": "createResponse",
  "parameters": [
    {
      "name": "bkper-ai-source",
      "in": "header",
      "required": false,
      "description": "Stable lowercase client or application identifier used for usage attribution. Invalid values are recorded as unknown.",
      "schema": {
        "type": "string",
        "pattern": "^[a-z0-9][a-z0-9._-]{0,127}$"
      }
    }
  ],
  "requestBody": {
    "content": {
      "application/json": {
        "schema": {
          "$ref": "#/components/schemas/CreateResponseBody"
        },
        "examples": {
          "complete": {
            "summary": "Complete response",
            "value": {
              "model": "gpt-5.6-luna",
              "input": "Reply with exactly: connected",
              "store": false
            }
          },
          "streaming": {
            "summary": "Streaming response",
            "value": {
              "model": "gpt-5.6-luna",
              "input": "Explain Bkper in one sentence.",
              "stream": true,
              "store": false
            }
          },
          "structured": {
            "summary": "Structured JSON response",
            "value": {
              "model": "gpt-5.6-luna",
              "input": "Return the invoice number.",
              "text": {
                "format": {
                  "type": "json_schema",
                  "name": "invoice",
                  "schema": {
                    "type": "object",
                    "properties": {
                      "invoice_number": {
                        "type": "string"
                      }
                    },
                    "required": [
                      "invoice_number"
                    ],
                    "additionalProperties": false
                  },
                  "strict": true
                }
              },
              "store": false
            }
          }
        }
      }
    },
    "required": true
  },
  "responses": {
    "200": {
      "description": "Success",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/ResponseResource"
          }
        },
        "text/event-stream": {
          "schema": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/ResponseCreatedStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseQueuedStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseInProgressStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseCompletedStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseFailedStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseIncompleteStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseOutputItemAddedStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseOutputItemDoneStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseReasoningSummaryPartAddedStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseReasoningSummaryPartDoneStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseContentPartAddedStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseContentPartDoneStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseOutputTextDeltaStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseOutputTextDoneStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseRefusalDeltaStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseRefusalDoneStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseReasoningDeltaStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseReasoningDoneStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseReasoningSummaryDeltaStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseReasoningSummaryDoneStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseOutputTextAnnotationAddedStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseFunctionCallArgumentsDeltaStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ResponseFunctionCallArgumentsDoneStreamingEvent"
              },
              {
                "$ref": "#/components/schemas/ErrorStreamingEvent"
              }
            ],
            "discriminator": {
              "propertyName": "type"
            }
          }
        }
      }
    },
    "400": {
      "description": "Invalid request or unsupported capability",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/BkperErrorResponse"
          }
        }
      }
    },
    "401": {
      "description": "Missing or invalid Bkper bearer token",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/BkperErrorResponse"
          }
        }
      }
    },
    "402": {
      "description": "Subscription payment is overdue",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/BkperErrorResponse"
          }
        }
      }
    },
    "403": {
      "description": "Bkper AI entitlement is unavailable",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/BkperErrorResponse"
          }
        }
      }
    },
    "429": {
      "description": "Monthly allowance exhausted or provider throttled",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/BkperErrorResponse"
          }
        }
      }
    },
    "499": {
      "description": "Client aborted the request",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/BkperErrorResponse"
          }
        }
      }
    },
    "502": {
      "description": "Provider or transport failure",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/BkperErrorResponse"
          }
        }
      }
    },
    "default": {
      "description": "Other provider or transport rejection",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/BkperErrorResponse"
          }
        }
      }
    }
  },
  "tags": [
    "Responses"
  ],
  "security": [
    {
      "bkperBearer": []
    }
  ]
}
```

## Schemas

### ReasoningSummaryContentParam

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "summary_text"
      ],
      "description": "The content type. Always `summary_text`.",
      "default": "summary_text"
    },
    "text": {
      "type": "string",
      "maxLength": 10485760,
      "description": "The reasoning summary text."
    }
  },
  "type": "object",
  "required": [
    "type",
    "text"
  ],
  "additionalProperties": false
}
```

### ReasoningItemParam

```json
{
  "properties": {
    "id": {
      "anyOf": [
        {
          "type": "string",
          "description": "The unique ID of this reasoning item.",
          "example": "rs_123"
        },
        {
          "type": "null"
        }
      ]
    },
    "type": {
      "type": "string",
      "enum": [
        "reasoning"
      ],
      "description": "The item type. Always `reasoning`.",
      "default": "reasoning"
    },
    "summary": {
      "items": {
        "$ref": "#/components/schemas/ReasoningSummaryContentParam"
      },
      "type": "array",
      "description": "Reasoning summary content associated with this item."
    },
    "content": {
      "anyOf": [
        {
          "type": "null"
        }
      ]
    },
    "encrypted_content": {
      "anyOf": [
        {
          "type": "string",
          "description": "An encrypted representation of the reasoning content."
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "summary"
  ],
  "additionalProperties": false
}
```

### InputTextContentParam

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "input_text"
      ],
      "description": "The type of the input item. Always `input_text`.",
      "default": "input_text"
    },
    "text": {
      "type": "string",
      "maxLength": 10485760,
      "description": "The text input to the model."
    }
  },
  "type": "object",
  "required": [
    "type",
    "text"
  ],
  "title": "Input text",
  "description": "A text input to the model.",
  "x-unionDisplay": "section",
  "x-unionTitle": "Content Type",
  "additionalProperties": false
}
```

### InputImageContentParamAutoParam

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "input_image"
      ],
      "description": "The type of the input item. Always `input_image`.",
      "default": "input_image"
    },
    "image_url": {
      "type": "string",
      "maxLength": 20971520,
      "description": "An HTTP(S) URL or supported base64 image data URL. Remote URL availability depends on the selected model."
    },
    "detail": {
      "allOf": [
        {
          "$ref": "#/components/schemas/ImageDetail"
        },
        {
          "description": "The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`."
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "image_url"
  ],
  "title": "Input image",
  "description": "An image input to the model. Learn about [image inputs](https://www.openresponses.org/reference/2026-04-24#object-InputImageContentParamAutoParam)",
  "additionalProperties": false
}
```

### InputFileContentParam

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "input_file"
      ],
      "description": "The type of the input item. Always `input_file`.",
      "default": "input_file"
    },
    "filename": {
      "type": "string",
      "description": "The name of the file to be sent to the model.",
      "minLength": 1
    },
    "file_data": {
      "type": "string",
      "maxLength": 33554432,
      "description": "The base64-encoded data of the file to be sent to the model.",
      "minLength": 1
    }
  },
  "type": "object",
  "required": [
    "type",
    "filename",
    "file_data"
  ],
  "title": "Input file",
  "description": "A file input to the model.",
  "additionalProperties": false
}
```

### UserMessageItemParam

```json
{
  "properties": {
    "id": {
      "anyOf": [
        {
          "type": "string",
          "description": "The unique ID of this message item.",
          "example": "msg_123"
        },
        {
          "type": "null"
        }
      ]
    },
    "type": {
      "type": "string",
      "enum": [
        "message"
      ],
      "description": "The item type. Always `message`."
    },
    "role": {
      "type": "string",
      "enum": [
        "user"
      ],
      "description": "The message role. Always `user`.",
      "default": "user"
    },
    "content": {
      "oneOf": [
        {
          "items": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/InputTextContentParam"
              },
              {
                "$ref": "#/components/schemas/InputImageContentParamAutoParam"
              },
              {
                "$ref": "#/components/schemas/InputFileContentParam"
              }
            ],
            "description": "A piece of message content, such as text, an image, or a file.",
            "discriminator": {
              "propertyName": "type"
            }
          },
          "type": "array",
          "minItems": 1
        },
        {
          "type": "string",
          "maxLength": 10485760,
          "description": "The message content, as a single string."
        }
      ],
      "description": "The message content, as an array of content parts."
    },
    "status": {
      "anyOf": [
        {
          "type": "string",
          "description": "The status of the message item."
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "role",
    "content"
  ],
  "additionalProperties": false
}
```

### SystemMessageItemParam

```json
{
  "properties": {
    "id": {
      "anyOf": [
        {
          "type": "string",
          "description": "The unique ID of this message item.",
          "example": "msg_123"
        },
        {
          "type": "null"
        }
      ]
    },
    "type": {
      "type": "string",
      "enum": [
        "message"
      ],
      "description": "The item type. Always `message`."
    },
    "role": {
      "type": "string",
      "enum": [
        "system"
      ],
      "description": "The message role. Always `system`.",
      "default": "system"
    },
    "content": {
      "oneOf": [
        {
          "items": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/InputTextContentParam"
              }
            ],
            "discriminator": {
              "propertyName": "type"
            }
          },
          "type": "array",
          "minItems": 1
        },
        {
          "type": "string",
          "maxLength": 10485760,
          "description": "The message content, as a single string."
        }
      ],
      "description": "The message content, as an array of content parts."
    },
    "status": {
      "anyOf": [
        {
          "type": "string",
          "description": "The status of the message item."
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "role",
    "content"
  ],
  "additionalProperties": false
}
```

### DeveloperMessageItemParam

```json
{
  "properties": {
    "id": {
      "anyOf": [
        {
          "type": "string",
          "description": "The unique ID of this message item.",
          "example": "msg_123"
        },
        {
          "type": "null"
        }
      ]
    },
    "type": {
      "type": "string",
      "enum": [
        "message"
      ],
      "description": "The item type. Always `message`."
    },
    "role": {
      "type": "string",
      "enum": [
        "developer"
      ],
      "description": "The message role. Always `developer`.",
      "default": "developer"
    },
    "content": {
      "oneOf": [
        {
          "items": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/InputTextContentParam"
              }
            ],
            "discriminator": {
              "propertyName": "type"
            }
          },
          "type": "array",
          "minItems": 1
        },
        {
          "type": "string",
          "maxLength": 10485760,
          "description": "The message content, as a single string."
        }
      ],
      "description": "The message content, as an array of content parts."
    },
    "status": {
      "anyOf": [
        {
          "type": "string",
          "description": "The status of the message item."
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "role",
    "content"
  ],
  "additionalProperties": false
}
```

### UrlCitationParam

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "url_citation"
      ],
      "description": "The citation type. Always `url_citation`.",
      "default": "url_citation"
    },
    "start_index": {
      "type": "integer",
      "minimum": 0,
      "description": "The index of the first character of the citation in the message."
    },
    "end_index": {
      "type": "integer",
      "minimum": 0,
      "description": "The index of the last character of the citation in the message."
    },
    "url": {
      "type": "string",
      "description": "The URL of the cited resource."
    },
    "title": {
      "type": "string",
      "description": "The title of the cited resource."
    }
  },
  "type": "object",
  "required": [
    "type",
    "start_index",
    "end_index",
    "url",
    "title"
  ]
}
```

### OutputTextContentParam

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "output_text"
      ],
      "description": "The content type. Always `output_text`.",
      "default": "output_text"
    },
    "text": {
      "type": "string",
      "maxLength": 10485760,
      "description": "The text content."
    },
    "annotations": {
      "oneOf": [
        {
          "items": {
            "$ref": "#/components/schemas/UrlCitationParam"
          },
          "type": "array"
        }
      ],
      "description": "Citations associated with the text content."
    },
    "logprobs": {
      "items": {
        "$ref": "#/components/schemas/LogProb"
      },
      "type": "array"
    }
  },
  "type": "object",
  "required": [
    "type",
    "text"
  ],
  "additionalProperties": false
}
```

### RefusalContentParam

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "refusal"
      ],
      "description": "The content type. Always `refusal`.",
      "default": "refusal"
    },
    "refusal": {
      "type": "string",
      "maxLength": 10485760,
      "description": "The refusal text."
    }
  },
  "type": "object",
  "required": [
    "type",
    "refusal"
  ],
  "additionalProperties": false
}
```

### AssistantMessageItemParam

```json
{
  "properties": {
    "id": {
      "anyOf": [
        {
          "type": "string",
          "description": "The unique ID of this message item.",
          "example": "msg_123"
        },
        {
          "type": "null"
        }
      ]
    },
    "type": {
      "type": "string",
      "enum": [
        "message"
      ],
      "description": "The item type. Always `message`."
    },
    "role": {
      "type": "string",
      "enum": [
        "assistant"
      ],
      "description": "The role of the message author. Always `assistant`.",
      "default": "assistant"
    },
    "content": {
      "oneOf": [
        {
          "items": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/OutputTextContentParam"
              },
              {
                "$ref": "#/components/schemas/RefusalContentParam"
              }
            ],
            "description": "A piece of assistant message content, such as text or a refusal.",
            "discriminator": {
              "propertyName": "type"
            }
          },
          "type": "array",
          "minItems": 1
        },
        {
          "type": "string",
          "maxLength": 10485760,
          "description": "The message content, as a single string."
        }
      ],
      "description": "The message content, as an array of content parts."
    },
    "phase": {
      "type": "string",
      "enum": [
        "commentary",
        "final_answer"
      ],
      "description": "Labels an `assistant` message as intermediate commentary (`commentary`) or the final answer (`final_answer`). when sending follow-up requests, preserve and resend phase on all assistant messages. Omitting it can degrade performance. Not used for user messages.",
      "x-openresponses-added-in": "2026-04-24"
    },
    "status": {
      "anyOf": [
        {
          "type": "string",
          "description": "The status of the message item."
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "role",
    "content"
  ],
  "additionalProperties": false
}
```

### FunctionCallItemParam

```json
{
  "properties": {
    "id": {
      "anyOf": [
        {
          "type": "string",
          "description": "The unique ID of this function tool call.",
          "example": "fc_123"
        },
        {
          "type": "null"
        }
      ]
    },
    "call_id": {
      "type": "string",
      "maxLength": 64,
      "minLength": 1,
      "description": "The unique ID of the function tool call generated by the model."
    },
    "type": {
      "type": "string",
      "enum": [
        "function_call"
      ],
      "description": "The item type. Always `function_call`.",
      "default": "function_call"
    },
    "name": {
      "type": "string",
      "maxLength": 64,
      "minLength": 1,
      "pattern": "^[a-zA-Z0-9_-]+$",
      "description": "The name of the function to call."
    },
    "arguments": {
      "type": "string",
      "description": "The function arguments as a JSON string."
    },
    "status": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/FunctionCallStatus"
            },
            {
              "description": "The status of the function tool call."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "call_id",
    "type",
    "name",
    "arguments"
  ],
  "additionalProperties": false
}
```

### FunctionCallOutputItemParam

```json
{
  "properties": {
    "id": {
      "anyOf": [
        {
          "type": "string",
          "description": "The unique ID of the function tool call output. Populated when this item is returned via API.",
          "example": "fc_123"
        },
        {
          "type": "null"
        }
      ]
    },
    "call_id": {
      "type": "string",
      "maxLength": 64,
      "minLength": 1,
      "description": "The unique ID of the function tool call generated by the model."
    },
    "type": {
      "type": "string",
      "enum": [
        "function_call_output"
      ],
      "description": "The type of the function tool call output. Always `function_call_output`.",
      "default": "function_call_output"
    },
    "output": {
      "oneOf": [
        {
          "type": "string",
          "maxLength": 10485760,
          "description": "A JSON string of the output of the function tool call."
        },
        {
          "items": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/InputTextContentParam"
              },
              {
                "$ref": "#/components/schemas/InputImageContentParamAutoParam"
              },
              {
                "$ref": "#/components/schemas/InputFileContentParam"
              }
            ],
            "description": "A piece of message content, such as text, an image, or a file.",
            "discriminator": {
              "propertyName": "type"
            }
          },
          "type": "array",
          "description": "An array of content outputs (text, image, file) for the function tool call."
        }
      ],
      "description": "Text, image, or file output of the function tool call."
    },
    "status": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/FunctionCallStatus"
            },
            {
              "description": "The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "call_id",
    "type",
    "output"
  ],
  "title": "Function tool call output",
  "description": "The output of a function tool call. Inline file content is accepted only when the selected model supports that file type in function outputs.",
  "additionalProperties": false
}
```

### ItemParam

```json
{
  "oneOf": [
    {
      "$ref": "#/components/schemas/ReasoningItemParam"
    },
    {
      "$ref": "#/components/schemas/UserMessageItemParam"
    },
    {
      "$ref": "#/components/schemas/SystemMessageItemParam"
    },
    {
      "$ref": "#/components/schemas/DeveloperMessageItemParam"
    },
    {
      "$ref": "#/components/schemas/AssistantMessageItemParam"
    },
    {
      "$ref": "#/components/schemas/FunctionCallItemParam"
    },
    {
      "$ref": "#/components/schemas/FunctionCallOutputItemParam"
    }
  ],
  "x-unionDisplay": "section",
  "x-unionTitle": "Input Item Types"
}
```

### IncludeEnum

```json
{
  "type": "string",
  "enum": [
    "reasoning.encrypted_content"
  ],
  "description": "Additional response data to include. Only encrypted reasoning continuity data is supported.",
  "x-enumDescriptions": {
    "reasoning.encrypted_content": "Includes provider-sealed reasoning state for explicit stateless continuation."
  }
}
```

### EmptyModelParam

```json
{
  "properties": {},
  "type": "object",
  "required": []
}
```

### FunctionToolParam

```json
{
  "properties": {
    "name": {
      "type": "string",
      "maxLength": 64,
      "minLength": 1,
      "pattern": "^[a-zA-Z0-9_-]+$"
    },
    "description": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ]
    },
    "parameters": {
      "anyOf": [
        {
          "$ref": "#/components/schemas/EmptyModelParam"
        },
        {
          "type": "null"
        }
      ]
    },
    "strict": {
      "type": "boolean",
      "description": "Whether to enforce strict function parameters. Some models require strict function tools and reject false."
    },
    "type": {
      "type": "string",
      "enum": [
        "function"
      ],
      "default": "function"
    }
  },
  "type": "object",
  "required": [
    "name",
    "type"
  ],
  "additionalProperties": false,
  "description": "Defines a function tool. See [Open Responses function tools](https://www.openresponses.org/reference/2026-04-24#object-FunctionToolParam)."
}
```

### ResponsesToolParam

```json
{
  "oneOf": [
    {
      "$ref": "#/components/schemas/FunctionToolParam"
    }
  ],
  "discriminator": {
    "propertyName": "type"
  },
  "x-unionDisplay": "section",
  "x-unionTitle": "Tool Types"
}
```

### SpecificFunctionParam

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "function"
      ],
      "description": "The tool to call. Always `function`.",
      "default": "function"
    },
    "name": {
      "type": "string",
      "description": "The name of the function tool to call.",
      "minLength": 1,
      "maxLength": 64,
      "pattern": "^[a-zA-Z0-9_-]+$"
    }
  },
  "type": "object",
  "required": [
    "type",
    "name"
  ],
  "additionalProperties": false
}
```

### SpecificToolChoiceParam

```json
{
  "oneOf": [
    {
      "$ref": "#/components/schemas/SpecificFunctionParam"
    }
  ]
}
```

### ToolChoiceValueEnum

```json
{
  "type": "string",
  "enum": [
    "none",
    "auto",
    "required"
  ],
  "x-enumDescriptions": {
    "auto": "Let the model choose the tools from among the provided set.",
    "none": "Restrict the model from calling any tools.",
    "required": "Require the model to call a tool."
  }
}
```

### ToolChoiceParam

```json
{
  "oneOf": [
    {
      "$ref": "#/components/schemas/SpecificToolChoiceParam"
    },
    {
      "$ref": "#/components/schemas/ToolChoiceValueEnum"
    }
  ],
  "description": "Controls which tool the model should use, if any."
}
```

### TextParam

```json
{
  "properties": {
    "format": {
      "description": "The format configuration for text output.",
      "oneOf": [
        {
          "$ref": "#/components/schemas/TextFormatParam"
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [],
  "additionalProperties": false
}
```

### ReasoningEffortEnum

```json
{
  "type": "string",
  "enum": [
    "none",
    "minimal",
    "low",
    "medium",
    "high",
    "xhigh",
    "max"
  ],
  "x-enumDescriptions": {
    "high": "Use a higher reasoning effort to improve answer quality.",
    "max": "Use the highest reasoning effort available.",
    "medium": "Use a balanced reasoning effort.",
    "minimal": "Use minimal reasoning effort for the fastest responses.",
    "low": "Use a lower reasoning effort for faster responses.",
    "none": "Restrict the model from performing any reasoning before emitting a final answer.",
    "xhigh": "Use a very high reasoning effort."
  }
}
```

### ReasoningSummaryEnum

```json
{
  "type": "string",
  "enum": [
    "concise",
    "detailed",
    "auto"
  ],
  "x-enumDescriptions": {
    "auto": "Allow the model to decide when to summarize.",
    "concise": "Emit concise summaries of reasoning content.",
    "detailed": "Emit details summaries of reasoning content."
  }
}
```

### ReasoningParam

```json
{
  "properties": {
    "effort": {
      "anyOf": [
        {
          "oneOf": [
            {
              "$ref": "#/components/schemas/ReasoningEffortEnum"
            }
          ],
          "description": "Controls the level of reasoning effort the model should apply. Higher effort may increase latency and cost."
        },
        {
          "type": "null"
        }
      ]
    },
    "summary": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/ReasoningSummaryEnum"
            },
            {
              "description": "Controls whether the response includes a reasoning summary."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [],
  "description": "Configuration options for [reasoning models](https://www.openresponses.org/reference/2026-04-24#enum-ReasoningEffortEnum).",
  "additionalProperties": false
}
```

### CreateResponseBody

```json
{
  "properties": {
    "model": {
      "type": "string",
      "description": "A model ID returned by GET /v1/models.",
      "examples": [
        "gpt-5.6-luna",
        "gpt-5.6-terra",
        "grok-4.5",
        "gemini-3.6-flash",
        "deepseek-v4-flash"
      ]
    },
    "input": {
      "oneOf": [
        {
          "type": "string",
          "maxLength": 10485760
        },
        {
          "items": {
            "$ref": "#/components/schemas/ItemParam"
          },
          "type": "array"
        }
      ],
      "description": "Context to provide to the model for the scope of this request. May either be a string or an array of input items. If a string is provided, it is interpreted as a user message."
    },
    "include": {
      "items": {
        "$ref": "#/components/schemas/IncludeEnum"
      },
      "type": "array"
    },
    "tools": {
      "items": {
        "$ref": "#/components/schemas/ResponsesToolParam"
      },
      "type": "array",
      "description": "A list of tools that the model may call while generating the response."
    },
    "tool_choice": {
      "x-unionTitle": "ToolChoiceParam",
      "allOf": [
        {
          "$ref": "#/components/schemas/ToolChoiceParam"
        },
        {
          "description": "Controls which tool the model should use, if any."
        }
      ]
    },
    "text": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/TextParam"
            },
            {
              "description": "Configuration options for text output."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    },
    "temperature": {
      "anyOf": [
        {
          "type": "number",
          "description": "Sampling temperature to use, between 0 and 2. Higher values make the output more random.",
          "minimum": 0,
          "maximum": 2
        },
        {
          "type": "null"
        }
      ]
    },
    "top_p": {
      "anyOf": [
        {
          "type": "number",
          "description": "Nucleus sampling parameter, between 0 and 1. The model considers only the tokens with the top cumulative probability.",
          "minimum": 0,
          "maximum": 1
        },
        {
          "type": "null"
        }
      ]
    },
    "presence_penalty": {
      "anyOf": [
        {
          "type": "number",
          "description": "Penalizes new tokens based on whether they appear in the text so far.",
          "minimum": -2,
          "maximum": 2
        },
        {
          "type": "null"
        }
      ],
      "description": "Availability depends on the selected model. Unsupported values return an invalid request error."
    },
    "frequency_penalty": {
      "anyOf": [
        {
          "type": "number",
          "description": "Penalizes new tokens based on their frequency in the text so far.",
          "minimum": -2,
          "maximum": 2
        },
        {
          "type": "null"
        }
      ],
      "description": "Availability depends on the selected model. Unsupported values return an invalid request error."
    },
    "parallel_tool_calls": {
      "anyOf": [
        {
          "type": "boolean",
          "description": "Whether the model may call multiple tools in parallel."
        },
        {
          "type": "null"
        }
      ],
      "description": "Availability depends on the selected model. Unsupported values return an invalid request error."
    },
    "stream": {
      "type": "boolean",
      "description": "Whether to stream response events as server-sent events."
    },
    "max_output_tokens": {
      "anyOf": [
        {
          "type": "integer",
          "minimum": 16,
          "description": "The maximum number of tokens the model may generate for this response."
        },
        {
          "type": "null"
        }
      ]
    },
    "reasoning": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/ReasoningParam"
            },
            {
              "description": "Configuration options for reasoning behavior."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    },
    "prompt_cache_key": {
      "anyOf": [
        {
          "type": "string",
          "maxLength": 64,
          "description": "A key to use when reading from or writing to the prompt cache."
        },
        {
          "type": "null"
        }
      ]
    },
    "instructions": {
      "anyOf": [
        {
          "type": "string",
          "description": "Additional instructions to guide the model for this request."
        },
        {
          "type": "null"
        }
      ]
    },
    "store": {
      "type": "boolean",
      "const": false,
      "default": false,
      "description": "Bkper AI is stateless. The only supported value is false."
    }
  },
  "type": "object",
  "required": [
    "model",
    "input"
  ],
  "additionalProperties": false
}
```

### IncompleteDetails

```json
{
  "properties": {
    "reason": {
      "type": "string",
      "description": "The reason the response could not be completed."
    }
  },
  "type": "object",
  "required": [
    "reason"
  ],
  "title": "Incomplete details",
  "description": "Details about why the response was incomplete."
}
```

### UrlCitationBody

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "url_citation"
      ],
      "description": "The type of the URL citation. Always `url_citation`.",
      "default": "url_citation"
    },
    "url": {
      "type": "string",
      "description": "The URL of the web resource."
    },
    "start_index": {
      "type": "integer",
      "description": "The index of the first character of the URL citation in the message."
    },
    "end_index": {
      "type": "integer",
      "description": "The index of the last character of the URL citation in the message."
    },
    "title": {
      "type": "string",
      "description": "The title of the web resource."
    }
  },
  "type": "object",
  "required": [
    "type",
    "url",
    "start_index",
    "end_index",
    "title"
  ],
  "title": "URL citation",
  "description": "A citation for a web resource used to generate a model response."
}
```

### Annotation

```json
{
  "oneOf": [
    {
      "$ref": "#/components/schemas/UrlCitationBody"
    }
  ],
  "description": "An annotation that applies to a span of output text.",
  "discriminator": {
    "propertyName": "type"
  }
}
```

### TopLogProb

```json
{
  "properties": {
    "token": {
      "type": "string"
    },
    "logprob": {
      "type": "number"
    },
    "bytes": {
      "items": {
        "type": "integer"
      },
      "type": "array"
    }
  },
  "type": "object",
  "required": [
    "token",
    "logprob",
    "bytes"
  ],
  "title": "Top log probability",
  "description": "The top log probability of a token."
}
```

### LogProb

```json
{
  "properties": {
    "token": {
      "type": "string"
    },
    "logprob": {
      "type": "number"
    },
    "bytes": {
      "items": {
        "type": "integer"
      },
      "type": "array"
    },
    "top_logprobs": {
      "items": {
        "$ref": "#/components/schemas/TopLogProb"
      },
      "type": "array"
    }
  },
  "type": "object",
  "required": [
    "token",
    "logprob",
    "bytes",
    "top_logprobs"
  ],
  "title": "Log probability",
  "description": "The log probability of a token."
}
```

### OutputTextContent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "output_text"
      ],
      "description": "The type of the output text. Always `output_text`.",
      "default": "output_text"
    },
    "text": {
      "type": "string",
      "description": "The text output from the model."
    },
    "annotations": {
      "items": {
        "$ref": "#/components/schemas/Annotation"
      },
      "type": "array",
      "description": "The annotations of the text output."
    },
    "logprobs": {
      "items": {
        "$ref": "#/components/schemas/LogProb"
      },
      "type": "array"
    }
  },
  "type": "object",
  "required": [
    "type",
    "text",
    "annotations"
  ],
  "title": "Output text",
  "description": "A text output from the model."
}
```

### SummaryTextContent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "summary_text"
      ],
      "description": "The type of the object. Always `summary_text`.",
      "default": "summary_text"
    },
    "text": {
      "type": "string",
      "description": "A summary of the reasoning output from the model so far."
    }
  },
  "type": "object",
  "required": [
    "type",
    "text"
  ],
  "title": "Summary text",
  "description": "A summary text from the model."
}
```

### ReasoningTextContent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "reasoning_text"
      ],
      "description": "The type of the reasoning text. Always `reasoning_text`.",
      "default": "reasoning_text"
    },
    "text": {
      "type": "string",
      "description": "The reasoning text from the model."
    }
  },
  "type": "object",
  "required": [
    "type",
    "text"
  ],
  "title": "Reasoning text",
  "description": "Reasoning text from the model."
}
```

### RefusalContent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "refusal"
      ],
      "description": "The type of the refusal. Always `refusal`.",
      "default": "refusal"
    },
    "refusal": {
      "type": "string",
      "description": "The refusal explanation from the model."
    }
  },
  "type": "object",
  "required": [
    "type",
    "refusal"
  ],
  "title": "Refusal",
  "description": "A refusal from the model."
}
```

### ImageDetail

```json
{
  "type": "string",
  "enum": [
    "low",
    "high",
    "auto"
  ],
  "x-enumDescriptions": {
    "auto": "Choose the detail level automatically.",
    "high": "Allows the model to \"see\" a higher-resolution version of the image, usually increasing input token costs.",
    "low": "Restricts the model to a lower-resolution version of the image."
  }
}
```

### MessageStatus

```json
{
  "type": "string",
  "enum": [
    "in_progress",
    "completed",
    "incomplete"
  ],
  "x-enumDescriptions": {
    "completed": "Model has finished sampling this item.",
    "in_progress": "Model is currently sampling this item.",
    "incomplete": "Model was interrupted from sampling this item partway through. This can occur, for example, if the model encounters a stop token or exhausts its output_token budget."
  }
}
```

### Message

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "message"
      ],
      "description": "The type of the message. Always set to `message`.",
      "default": "message"
    },
    "id": {
      "type": "string",
      "description": "The unique ID of the message."
    },
    "status": {
      "allOf": [
        {
          "$ref": "#/components/schemas/MessageStatus"
        },
        {
          "description": "The status of item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API."
        }
      ]
    },
    "role": {
      "type": "string",
      "const": "assistant",
      "description": "The response message role. Always assistant."
    },
    "content": {
      "items": {
        "oneOf": [
          {
            "$ref": "#/components/schemas/OutputTextContent"
          },
          {
            "$ref": "#/components/schemas/RefusalContent"
          }
        ],
        "description": "A content part that makes up an input or output item.",
        "discriminator": {
          "propertyName": "type"
        }
      },
      "type": "array",
      "description": "The content of the message"
    },
    "phase": {
      "type": "string",
      "enum": [
        "commentary",
        "final_answer"
      ],
      "description": "Labels an `assistant` message as intermediate commentary (`commentary`) or the final answer (`final_answer`). when sending follow-up requests, preserve and resend phase on all assistant messages. Omitting it can degrade performance. Not used for user messages.",
      "x-openresponses-added-in": "2026-04-24"
    }
  },
  "type": "object",
  "required": [
    "type",
    "id",
    "status",
    "role",
    "content"
  ],
  "title": "Message",
  "description": "A message to or from the model."
}
```

### FunctionCallStatus

```json
{
  "type": "string",
  "enum": [
    "in_progress",
    "completed",
    "incomplete"
  ],
  "x-enumDescriptions": {
    "completed": "Model has finished sampling this item.",
    "in_progress": "Model is currently sampling this item.",
    "incomplete": "Model was interrupted from sampling this item partway through. This can occur, for example, if the model encounters a stop token or exhausts its output_token budget."
  }
}
```

### FunctionCall

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "function_call"
      ],
      "description": "The type of the item. Always `function_call`.",
      "default": "function_call"
    },
    "id": {
      "type": "string",
      "description": "The unique ID of the function call item."
    },
    "call_id": {
      "type": "string",
      "description": "The unique ID of the function tool call that was generated."
    },
    "name": {
      "type": "string",
      "description": "The name of the function that was called."
    },
    "arguments": {
      "type": "string",
      "description": "The arguments JSON string that was generated."
    },
    "status": {
      "allOf": [
        {
          "$ref": "#/components/schemas/FunctionCallStatus"
        },
        {
          "description": "The status of the function call item that was recorded."
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "id",
    "call_id",
    "name",
    "arguments",
    "status"
  ],
  "title": "Function call",
  "description": "A function tool call that was generated by the model."
}
```

### ReasoningBody

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "reasoning"
      ],
      "description": "The type of the item. Always `reasoning`.",
      "default": "reasoning"
    },
    "id": {
      "type": "string",
      "description": "The unique ID of the reasoning item."
    },
    "content": {
      "anyOf": [
        {
          "type": "array",
          "items": {
            "$ref": "#/components/schemas/ReasoningTextContent"
          }
        },
        {
          "type": "null"
        }
      ],
      "description": "Reasoning content, when returned by the selected model."
    },
    "summary": {
      "type": "array",
      "items": {
        "$ref": "#/components/schemas/SummaryTextContent"
      },
      "description": "Readable reasoning summary content."
    },
    "encrypted_content": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "description": "Provider-sealed reasoning state for explicit continuation."
    }
  },
  "type": "object",
  "required": [
    "type",
    "id",
    "summary"
  ],
  "title": "Reasoning item",
  "description": "A reasoning item that was generated by the model."
}
```

### ItemField

```json
{
  "oneOf": [
    {
      "$ref": "#/components/schemas/Message"
    },
    {
      "$ref": "#/components/schemas/FunctionCall"
    },
    {
      "$ref": "#/components/schemas/ReasoningBody"
    }
  ],
  "description": "An item representing a message, tool call, tool output, reasoning, or other response element.",
  "discriminator": {
    "propertyName": "type"
  }
}
```

### Error

```json
{
  "properties": {
    "code": {
      "type": "string",
      "description": "A machine-readable error code that was returned."
    },
    "message": {
      "type": "string",
      "description": "A human-readable description of the error that was returned."
    }
  },
  "type": "object",
  "required": [
    "code",
    "message"
  ],
  "title": "Error",
  "description": "An error that occurred while generating the response."
}
```

### FunctionTool

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "function"
      ],
      "description": "The type of the function tool. Always `function`.",
      "default": "function"
    },
    "name": {
      "type": "string",
      "description": "The name of the function to call."
    },
    "description": {
      "anyOf": [
        {
          "type": "string",
          "description": "A description of the function. Used by the model to determine whether or not to call the function."
        },
        {
          "type": "null"
        }
      ]
    },
    "parameters": {
      "anyOf": [
        {
          "additionalProperties": {},
          "type": "object",
          "description": "A JSON schema object describing the parameters of the function."
        },
        {
          "type": "null"
        }
      ]
    },
    "strict": {
      "type": "boolean",
      "description": "The effective strictness applied to this function tool."
    }
  },
  "type": "object",
  "required": [
    "type",
    "name",
    "description",
    "parameters",
    "strict"
  ],
  "title": "Function",
  "description": "Defines a function in your own code the model can choose to call. Learn more about [function calling](https://www.openresponses.org/reference/2026-04-24#object-FunctionToolParam).",
  "additionalProperties": false
}
```

### Tool

```json
{
  "oneOf": [
    {
      "$ref": "#/components/schemas/FunctionTool"
    }
  ],
  "description": "A tool that can be used to generate a response.",
  "discriminator": {
    "propertyName": "type"
  }
}
```

### FunctionToolChoice

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "function"
      ],
      "default": "function"
    },
    "name": {
      "type": "string"
    }
  },
  "type": "object",
  "required": [
    "type"
  ]
}
```

### TextResponseFormat

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "text"
      ],
      "default": "text"
    }
  },
  "type": "object",
  "required": [
    "type"
  ],
  "additionalProperties": false
}
```

### TextField

```json
{
  "properties": {
    "format": {
      "$ref": "#/components/schemas/TextFormatParam"
    }
  },
  "type": "object",
  "required": [
    "format"
  ],
  "additionalProperties": false
}
```

### Reasoning

```json
{
  "properties": {
    "effort": {
      "anyOf": [
        {
          "oneOf": [
            {
              "$ref": "#/components/schemas/ReasoningEffortEnum"
            }
          ],
          "description": "The reasoning effort that was requested for the model, if specified."
        },
        {
          "type": "null"
        }
      ]
    },
    "summary": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/ReasoningSummaryEnum"
            },
            {
              "description": "A model-generated summary of its reasoning that was produced, if available."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "effort",
    "summary"
  ],
  "title": "Reasoning",
  "description": "Reasoning configuration and metadata that were used for the response."
}
```

### InputTokensDetails

```json
{
  "properties": {
    "cached_tokens": {
      "type": "integer",
      "description": "The number of input tokens that were served from cache."
    },
    "cache_write_tokens": {
      "type": "integer",
      "minimum": 0,
      "description": "The number of input tokens written to a provider prompt cache."
    }
  },
  "type": "object",
  "required": [
    "cached_tokens",
    "cache_write_tokens"
  ],
  "title": "Input tokens details",
  "description": "A breakdown of input token usage that was recorded."
}
```

### OutputTokensDetails

```json
{
  "properties": {
    "reasoning_tokens": {
      "type": "integer",
      "description": "The number of output tokens that were attributed to reasoning."
    }
  },
  "type": "object",
  "required": [
    "reasoning_tokens"
  ],
  "title": "Output tokens details",
  "description": "A breakdown of output token usage that was recorded."
}
```

### Usage

```json
{
  "properties": {
    "input_tokens": {
      "type": "integer",
      "description": "The number of input tokens that were used to generate the response."
    },
    "output_tokens": {
      "type": "integer",
      "description": "The number of output tokens that were generated by the model."
    },
    "total_tokens": {
      "type": "integer",
      "description": "The total number of tokens that were used."
    },
    "input_tokens_details": {
      "allOf": [
        {
          "$ref": "#/components/schemas/InputTokensDetails"
        },
        {
          "description": "A breakdown of input token usage that was recorded."
        }
      ]
    },
    "output_tokens_details": {
      "allOf": [
        {
          "$ref": "#/components/schemas/OutputTokensDetails"
        },
        {
          "description": "A breakdown of output token usage that was recorded."
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "input_tokens",
    "output_tokens",
    "total_tokens",
    "input_tokens_details",
    "output_tokens_details"
  ],
  "title": "Usage",
  "description": "Token usage statistics that were recorded for the response."
}
```

### ResponseResource

```json
{
  "properties": {
    "id": {
      "type": "string",
      "description": "The unique ID of the response that was created."
    },
    "object": {
      "type": "string",
      "enum": [
        "response"
      ],
      "description": "The object type, which was always `response`.",
      "default": "response"
    },
    "created_at": {
      "type": "integer",
      "description": "The Unix timestamp (in seconds) for when the response was created."
    },
    "completed_at": {
      "anyOf": [
        {
          "type": "integer",
          "description": "The Unix timestamp (in seconds) for when the response was completed, if it was completed."
        },
        {
          "type": "null"
        }
      ]
    },
    "status": {
      "type": "string",
      "description": "The status that was set for the response."
    },
    "incomplete_details": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/IncompleteDetails"
            },
            {
              "description": "Details about why the response was incomplete, if applicable."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    },
    "model": {
      "type": "string",
      "description": "The model that generated this response."
    },
    "previous_response_id": {
      "type": "null",
      "const": null,
      "description": "Always null because Bkper AI does not persist response state."
    },
    "instructions": {
      "anyOf": [
        {
          "oneOf": [
            {
              "type": "string"
            }
          ],
          "description": "Additional instructions that were used to guide the model for this response."
        },
        {
          "type": "null"
        }
      ]
    },
    "output": {
      "items": {
        "$ref": "#/components/schemas/ItemField"
      },
      "type": "array",
      "description": "The output items that were generated by the model."
    },
    "error": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/Error"
            },
            {
              "description": "The error that occurred, if the response failed."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    },
    "tools": {
      "items": {
        "$ref": "#/components/schemas/Tool"
      },
      "type": "array",
      "description": "The tools that were available to the model during response generation."
    },
    "tool_choice": {
      "oneOf": [
        {
          "$ref": "#/components/schemas/FunctionToolChoice"
        },
        {
          "$ref": "#/components/schemas/ToolChoiceValueEnum"
        }
      ]
    },
    "truncation": {
      "type": "string",
      "const": "disabled",
      "description": "Always disabled. Requests that exceed the context window fail explicitly."
    },
    "parallel_tool_calls": {
      "type": "boolean",
      "description": "Whether the model was allowed to call multiple tools in parallel."
    },
    "text": {
      "allOf": [
        {
          "$ref": "#/components/schemas/TextField"
        },
        {
          "description": "Configuration options for text output that were used."
        }
      ]
    },
    "top_p": {
      "type": "number",
      "description": "The nucleus sampling parameter that was used for this response."
    },
    "presence_penalty": {
      "type": "number",
      "description": "The presence penalty that was used to penalize new tokens based on whether they appear in the text so far."
    },
    "frequency_penalty": {
      "type": "number",
      "description": "The frequency penalty that was used to penalize new tokens based on their frequency in the text so far."
    },
    "top_logprobs": {
      "type": "integer",
      "const": 0
    },
    "temperature": {
      "type": "number",
      "description": "The sampling temperature that was used for this response."
    },
    "reasoning": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/Reasoning"
            },
            {
              "description": "Reasoning configuration and outputs that were produced for this response."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    },
    "usage": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/Usage"
            },
            {
              "description": "Token usage statistics that were recorded for the response, if available."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    },
    "max_output_tokens": {
      "anyOf": [
        {
          "type": "integer",
          "description": "The maximum number of tokens the model was allowed to generate for this response."
        },
        {
          "type": "null"
        }
      ]
    },
    "max_tool_calls": {
      "type": "null",
      "const": null
    },
    "store": {
      "type": "boolean",
      "const": false,
      "description": "Always false because Bkper AI is stateless."
    },
    "background": {
      "type": "boolean",
      "const": false,
      "description": "Always false because background responses are not supported."
    },
    "service_tier": {
      "type": "string",
      "const": "default"
    },
    "metadata": {
      "type": "object",
      "maxProperties": 0,
      "additionalProperties": false
    },
    "safety_identifier": {
      "type": "null",
      "const": null
    },
    "prompt_cache_key": {
      "anyOf": [
        {
          "type": "string",
          "description": "A key that was used to read from or write to the prompt cache."
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "id",
    "object",
    "created_at",
    "completed_at",
    "status",
    "incomplete_details",
    "model",
    "previous_response_id",
    "instructions",
    "output",
    "error",
    "tools",
    "tool_choice",
    "truncation",
    "parallel_tool_calls",
    "text",
    "top_p",
    "presence_penalty",
    "frequency_penalty",
    "top_logprobs",
    "temperature",
    "reasoning",
    "usage",
    "max_output_tokens",
    "max_tool_calls",
    "store",
    "background",
    "service_tier",
    "metadata",
    "safety_identifier",
    "prompt_cache_key"
  ],
  "title": "The response object",
  "description": "The complete response object that was returned by the Responses API.",
  "example": {
    "id": "resp_67ccd3a9da748190baa7f1570fe91ac604becb25c45c1d41",
    "object": "response",
    "created_at": 1741476777,
    "status": "completed",
    "completed_at": 1741476778,
    "model": "gpt-4o-2024-08-06",
    "output": [
      {
        "type": "message",
        "id": "msg_67ccd3acc8d48190a77525dc6de64b4104becb25c45c1d41",
        "status": "completed",
        "role": "assistant",
        "content": [
          {
            "type": "output_text",
            "text": "The image depicts a scenic landscape with a wooden boardwalk or pathway leading through lush, green grass under a blue sky with some clouds. The setting suggests a peaceful natural area, possibly a park or nature reserve. There are trees and shrubs in the background.",
            "annotations": []
          }
        ]
      }
    ],
    "parallel_tool_calls": true,
    "reasoning": {},
    "store": true,
    "background": false,
    "temperature": 1,
    "presence_penalty": 0,
    "frequency_penalty": 0,
    "text": {
      "format": {
        "type": "text"
      }
    },
    "tool_choice": "auto",
    "tools": [],
    "top_p": 1,
    "truncation": "disabled",
    "usage": {
      "input_tokens": 328,
      "input_tokens_details": {
        "cached_tokens": 0
      },
      "output_tokens": 52,
      "output_tokens_details": {
        "reasoning_tokens": 0
      },
      "total_tokens": 380
    },
    "metadata": {},
    "service_tier": "default",
    "top_logprobs": 0
  }
}
```

### ResponseCreatedStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.created"
      ],
      "description": "The type of the event, always `response.created`.",
      "default": "response.created"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "response": {
      "allOf": [
        {
          "$ref": "#/components/schemas/ResponseResource"
        },
        {
          "description": "The response snapshot that was emitted with the event."
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "response"
  ],
  "title": "Response created event",
  "description": "A streaming event that indicated the response was created."
}
```

### ResponseQueuedStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.queued"
      ],
      "description": "The type of the event, always `response.queued`.",
      "default": "response.queued"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "response": {
      "allOf": [
        {
          "$ref": "#/components/schemas/ResponseResource"
        },
        {
          "description": "The response snapshot that was emitted with the event."
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "response"
  ],
  "title": "Response queued event",
  "description": "A streaming event that indicated the response was queued."
}
```

### ResponseInProgressStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.in_progress"
      ],
      "description": "The type of the event, always `response.in_progress`.",
      "default": "response.in_progress"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "response": {
      "allOf": [
        {
          "$ref": "#/components/schemas/ResponseResource"
        },
        {
          "description": "The response snapshot that was emitted with the event."
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "response"
  ],
  "title": "Response in progress event",
  "description": "A streaming event that indicated the response was in progress."
}
```

### ResponseCompletedStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.completed"
      ],
      "description": "The type of the event, always `response.completed`.",
      "default": "response.completed"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "response": {
      "allOf": [
        {
          "$ref": "#/components/schemas/ResponseResource"
        },
        {
          "description": "The response snapshot that was emitted with the event."
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "response"
  ],
  "title": "Response completed event",
  "description": "A streaming event that indicated the response was completed."
}
```

### ResponseFailedStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.failed"
      ],
      "description": "The type of the event, always `response.failed`.",
      "default": "response.failed"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "response": {
      "allOf": [
        {
          "$ref": "#/components/schemas/ResponseResource"
        },
        {
          "description": "The response snapshot that was emitted with the event."
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "response"
  ],
  "title": "Response failed event",
  "description": "A streaming event that indicated the response had failed."
}
```

### ResponseIncompleteStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.incomplete"
      ],
      "description": "The type of the event, always `response.incomplete`.",
      "default": "response.incomplete"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "response": {
      "allOf": [
        {
          "$ref": "#/components/schemas/ResponseResource"
        },
        {
          "description": "The response snapshot that was emitted with the event."
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "response"
  ],
  "title": "Response incomplete event",
  "description": "A streaming event that indicated the response was incomplete."
}
```

### ResponseOutputItemAddedStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.output_item.added"
      ],
      "description": "The type of the event, always `response.output_item.added`.",
      "default": "response.output_item.added"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was added."
    },
    "item": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/ItemField"
            },
            {
              "description": "An item representing a message, tool call, tool output, reasoning, or other response element."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "output_index",
    "item"
  ],
  "title": "Response output item added event",
  "description": "A streaming event that indicated an output item was added to the response."
}
```

### ResponseOutputItemDoneStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.output_item.done"
      ],
      "description": "The type of the event, always `response.output_item.done`.",
      "default": "response.output_item.done"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was completed."
    },
    "item": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/ItemField"
            },
            {
              "description": "An item representing a message, tool call, tool output, reasoning, or other response element."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "output_index",
    "item"
  ],
  "title": "Response output item done event",
  "description": "A streaming event that indicated an output item was completed."
}
```

### ResponseReasoningSummaryPartAddedStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.reasoning_summary_part.added"
      ],
      "description": "The type of the event, always `response.reasoning_summary_part.added`.",
      "default": "response.reasoning_summary_part.added"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "summary_index": {
      "type": "integer",
      "description": "The index of the summary part that was added."
    },
    "part": {
      "$ref": "#/components/schemas/SummaryTextContent"
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "summary_index",
    "part"
  ],
  "title": "Response reasoning summary part added event",
  "description": "A streaming event that indicated a reasoning summary part was added."
}
```

### ResponseReasoningSummaryPartDoneStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.reasoning_summary_part.done"
      ],
      "description": "The type of the event, always `response.reasoning_summary_part.done`.",
      "default": "response.reasoning_summary_part.done"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "summary_index": {
      "type": "integer",
      "description": "The index of the summary part that was completed."
    },
    "part": {
      "$ref": "#/components/schemas/SummaryTextContent"
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "summary_index",
    "part"
  ],
  "title": "Response reasoning summary part done event",
  "description": "A streaming event that indicated a reasoning summary part was completed."
}
```

### ResponseContentPartAddedStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.content_part.added"
      ],
      "description": "The type of the event, always `response.content_part.added`.",
      "default": "response.content_part.added"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "content_index": {
      "type": "integer",
      "description": "The index of the content part that was added."
    },
    "part": {
      "oneOf": [
        {
          "$ref": "#/components/schemas/OutputTextContent"
        },
        {
          "$ref": "#/components/schemas/RefusalContent"
        }
      ],
      "description": "A content part that makes up an input or output item.",
      "discriminator": {
        "propertyName": "type"
      }
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "content_index",
    "part"
  ],
  "title": "Response content part added event",
  "description": "A streaming event that indicated a content part was added."
}
```

### ResponseContentPartDoneStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.content_part.done"
      ],
      "description": "The type of the event, always `response.content_part.done`.",
      "default": "response.content_part.done"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "content_index": {
      "type": "integer",
      "description": "The index of the content part that was completed."
    },
    "part": {
      "oneOf": [
        {
          "$ref": "#/components/schemas/OutputTextContent"
        },
        {
          "$ref": "#/components/schemas/RefusalContent"
        }
      ],
      "description": "A content part that makes up an input or output item.",
      "discriminator": {
        "propertyName": "type"
      }
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "content_index",
    "part"
  ],
  "title": "Response content part done event",
  "description": "A streaming event that indicated a content part was completed."
}
```

### ResponseOutputTextDeltaStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.output_text.delta"
      ],
      "description": "The type of the event, always `response.output_text.delta`.",
      "default": "response.output_text.delta"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "content_index": {
      "type": "integer",
      "description": "The index of the content part that was updated."
    },
    "delta": {
      "type": "string",
      "description": "The text delta that was appended."
    },
    "logprobs": {
      "items": {
        "$ref": "#/components/schemas/LogProb"
      },
      "type": "array",
      "description": "The token log probabilities that were emitted with the delta, if any."
    },
    "obfuscation": {
      "type": "string",
      "description": "An obfuscation string that was added to pad the event payload."
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "content_index",
    "delta"
  ],
  "title": "Response output text delta event",
  "description": "A streaming event that indicated output text was incrementally added."
}
```

### ResponseOutputTextDoneStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.output_text.done"
      ],
      "description": "The type of the event, always `response.output_text.done`.",
      "default": "response.output_text.done"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "content_index": {
      "type": "integer",
      "description": "The index of the content part that was completed."
    },
    "text": {
      "type": "string",
      "description": "The final text that was emitted."
    },
    "logprobs": {
      "items": {
        "$ref": "#/components/schemas/LogProb"
      },
      "type": "array",
      "description": "The token log probabilities that were emitted with the final text, if any."
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "content_index",
    "text"
  ],
  "title": "Response output text done event",
  "description": "A streaming event that indicated output text was completed."
}
```

### ResponseRefusalDeltaStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.refusal.delta"
      ],
      "description": "The type of the event, always `response.refusal.delta`.",
      "default": "response.refusal.delta"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "content_index": {
      "type": "integer",
      "description": "The index of the refusal content that was updated."
    },
    "delta": {
      "type": "string",
      "description": "The refusal text delta that was appended."
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "content_index",
    "delta"
  ],
  "title": "Response refusal delta event",
  "description": "A streaming event that indicated refusal text was incrementally added."
}
```

### ResponseRefusalDoneStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.refusal.done"
      ],
      "description": "The type of the event, always `response.refusal.done`.",
      "default": "response.refusal.done"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "content_index": {
      "type": "integer",
      "description": "The index of the refusal content that was completed."
    },
    "refusal": {
      "type": "string",
      "description": "The final refusal text that was emitted."
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "content_index",
    "refusal"
  ],
  "title": "Response refusal done event",
  "description": "A streaming event that indicated refusal text was completed."
}
```

### ResponseReasoningDeltaStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.reasoning.delta"
      ],
      "description": "The type of the event, always `response.reasoning.delta`.",
      "default": "response.reasoning.delta"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "content_index": {
      "type": "integer",
      "description": "The index of the reasoning content that was updated."
    },
    "delta": {
      "type": "string",
      "description": "The reasoning text delta that was appended."
    },
    "obfuscation": {
      "type": "string",
      "description": "An obfuscation string that was added to pad the event payload."
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "content_index",
    "delta"
  ],
  "title": "Response reasoning delta event",
  "description": "A streaming event that indicated reasoning text was incrementally added."
}
```

### ResponseReasoningDoneStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.reasoning.done"
      ],
      "description": "The type of the event, always `response.reasoning.done`.",
      "default": "response.reasoning.done"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "content_index": {
      "type": "integer",
      "description": "The index of the reasoning content that was completed."
    },
    "text": {
      "type": "string",
      "description": "The final reasoning text that was emitted."
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "content_index",
    "text"
  ],
  "title": "Response reasoning done event",
  "description": "A streaming event that indicated reasoning text was completed."
}
```

### ResponseReasoningSummaryDeltaStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.reasoning_summary_text.delta"
      ],
      "description": "The type of the event, always `response.reasoning_summary.delta`.",
      "default": "response.reasoning_summary_text.delta"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "summary_index": {
      "type": "integer",
      "description": "The index of the summary content that was updated."
    },
    "delta": {
      "type": "string",
      "description": "The summary text delta that was appended."
    },
    "obfuscation": {
      "type": "string",
      "description": "An obfuscation string that was added to pad the event payload."
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "summary_index",
    "delta"
  ],
  "title": "Response reasoning summary delta event",
  "description": "A streaming event that indicated a reasoning summary was incrementally added."
}
```

### ResponseReasoningSummaryDoneStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.reasoning_summary_text.done"
      ],
      "description": "The type of the event, always `response.reasoning_summary.done`.",
      "default": "response.reasoning_summary_text.done"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "summary_index": {
      "type": "integer",
      "description": "The index of the summary content that was completed."
    },
    "text": {
      "type": "string",
      "description": "The final summary text that was emitted."
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "summary_index",
    "text"
  ],
  "title": "Response reasoning summary done event",
  "description": "A streaming event that indicated a reasoning summary was completed."
}
```

### ResponseOutputTextAnnotationAddedStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.output_text.annotation.added"
      ],
      "description": "The type of the event, always `response.output_text.annotation.added`.",
      "default": "response.output_text.annotation.added"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "content_index": {
      "type": "integer",
      "description": "The index of the output text content that was updated."
    },
    "annotation_index": {
      "type": "integer",
      "description": "The index of the annotation that was added."
    },
    "annotation": {
      "anyOf": [
        {
          "allOf": [
            {
              "$ref": "#/components/schemas/Annotation"
            },
            {
              "description": "An annotation that applies to a span of output text."
            }
          ]
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "content_index",
    "annotation_index",
    "annotation"
  ],
  "title": "Response output text annotation added event",
  "description": "A streaming event that indicated an output text annotation was added."
}
```

### ResponseFunctionCallArgumentsDeltaStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.function_call_arguments.delta"
      ],
      "description": "The type of the event, always `response.function_call_arguments.delta`.",
      "default": "response.function_call_arguments.delta"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the tool call item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "delta": {
      "type": "string",
      "description": "The arguments delta that was appended."
    },
    "obfuscation": {
      "type": "string",
      "description": "An obfuscation string that was added to pad the event payload."
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "delta"
  ],
  "title": "Response function call arguments delta event",
  "description": "A streaming event that indicated function call arguments were incrementally added."
}
```

### ResponseFunctionCallArgumentsDoneStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "response.function_call_arguments.done"
      ],
      "description": "The type of the event, always `response.function_call_arguments.done`.",
      "default": "response.function_call_arguments.done"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "item_id": {
      "type": "string",
      "description": "The ID of the tool call item that was updated."
    },
    "output_index": {
      "type": "integer",
      "description": "The index of the output item that was updated."
    },
    "arguments": {
      "type": "string",
      "description": "The final arguments string that was emitted."
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "item_id",
    "output_index",
    "arguments"
  ],
  "title": "Response function call arguments done event",
  "description": "A streaming event that indicated function call arguments were completed."
}
```

### ErrorPayload

```json
{
  "properties": {
    "type": {
      "type": "string",
      "description": "The error type that was emitted."
    },
    "code": {
      "anyOf": [
        {
          "type": "string",
          "description": "The error code that was emitted, if any."
        },
        {
          "type": "null"
        }
      ]
    },
    "message": {
      "type": "string",
      "description": "The human-readable error message that was emitted."
    },
    "param": {
      "anyOf": [
        {
          "type": "string",
          "description": "The parameter name that was associated with the error, if any."
        },
        {
          "type": "null"
        }
      ]
    },
    "headers": {
      "additionalProperties": {
        "type": "string",
        "description": "The header value that was emitted."
      },
      "type": "object",
      "description": "The response headers that were emitted with the error, if any."
    }
  },
  "type": "object",
  "required": [
    "type",
    "code",
    "message",
    "param"
  ],
  "title": "Error payload",
  "description": "An error payload that was emitted for a streaming error event."
}
```

### ErrorStreamingEvent

```json
{
  "properties": {
    "type": {
      "type": "string",
      "enum": [
        "error"
      ],
      "description": "The type of the event, always `error`.",
      "default": "error"
    },
    "sequence_number": {
      "type": "integer",
      "description": "The sequence number of the event that was emitted."
    },
    "error": {
      "allOf": [
        {
          "$ref": "#/components/schemas/ErrorPayload"
        },
        {
          "description": "The error payload that was emitted."
        }
      ]
    }
  },
  "type": "object",
  "required": [
    "type",
    "sequence_number",
    "error"
  ],
  "title": "Error event",
  "description": "A streaming event that indicated an error was emitted."
}
```

### JsonSchemaResponseFormatParam

```json
{
  "type": "object",
  "properties": {
    "type": {
      "type": "string",
      "description": "The type of response format being defined. Always `json_schema`.",
      "enum": [
        "json_schema"
      ]
    },
    "description": {
      "anyOf": [
        {
          "type": "string",
          "description": "A description of what the response format is for, used by the model to\ndetermine how to respond in the format.\n"
        },
        {
          "type": "null"
        }
      ]
    },
    "name": {
      "type": "string",
      "description": "The name of the response format. Must be a-z, A-Z, 0-9, or contain\nunderscores and dashes, with a maximum length of 64.\n",
      "minLength": 1,
      "maxLength": 64,
      "pattern": "^[a-zA-Z0-9_-]+$"
    },
    "schema": {
      "type": "object",
      "title": "JSON schema",
      "description": "The JSON Schema for the response. Bkper validates type, properties, required, additionalProperties, items, composition, enum, references, string constraints, numeric bounds, and array bounds before dispatch. With strict true, every object property must be required and additionalProperties must be false.",
      "additionalProperties": true
    },
    "strict": {
      "type": "boolean",
      "description": "Whether to enforce exact schema adherence. The selected model must publish structured_output.strict as true."
    }
  },
  "required": [
    "type",
    "name",
    "schema",
    "strict"
  ],
  "additionalProperties": false
}
```

### TextFormatParam

```json
{
  "oneOf": [
    {
      "$ref": "#/components/schemas/TextResponseFormat"
    },
    {
      "$ref": "#/components/schemas/JsonSchemaResponseFormatParam"
    }
  ]
}
```

### ModelList

```json
{
  "type": "object",
  "properties": {
    "object": {
      "type": "string",
      "enum": [
        "list"
      ],
      "description": "Object type. Always list."
    },
    "default_model": {
      "type": "string",
      "description": "Current default model ID."
    },
    "data": {
      "type": "array",
      "items": {
        "$ref": "#/components/schemas/Model"
      },
      "description": "Current discoverable model profiles."
    }
  },
  "required": [
    "object",
    "default_model",
    "data"
  ]
}
```

### Model

```json
{
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "description": "Stable model ID to send in POST /v1/responses."
    },
    "object": {
      "type": "string",
      "enum": [
        "model"
      ],
      "description": "Object type. Always model."
    },
    "created": {
      "type": "integer",
      "minimum": 0,
      "description": "Unix timestamp for this public model profile."
    },
    "owned_by": {
      "type": "string",
      "description": "Organization that develops or owns the model."
    },
    "display_name": {
      "type": "string",
      "description": "Human-readable model name."
    },
    "input_modalities": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": [
          "text",
          "image"
        ]
      },
      "description": "Input modalities accepted by this model through Bkper AI."
    },
    "pricing": {
      "$ref": "#/components/schemas/ModelPricing"
    },
    "default_thinking_level": {
      "type": "string",
      "enum": [
        "none",
        "minimal",
        "low",
        "medium",
        "high",
        "xhigh",
        "max"
      ],
      "description": "Default reasoning effort when the client does not choose one."
    },
    "context_window": {
      "type": "integer",
      "exclusiveMinimum": 0,
      "description": "Maximum supported request context in tokens."
    },
    "max_output_tokens": {
      "type": "integer",
      "exclusiveMinimum": 0,
      "description": "Maximum output-token limit accepted for this model."
    },
    "thinking_levels": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": [
          "none",
          "minimal",
          "low",
          "medium",
          "high",
          "xhigh",
          "max"
        ]
      },
      "description": "Reasoning-effort values accepted for this model."
    },
    "structured_output": {
      "type": "object",
      "properties": {
        "json_schema": {
          "type": "boolean",
          "description": "Whether JSON Schema structured output is supported."
        },
        "strict": {
          "type": "boolean",
          "description": "Whether strict JSON Schema enforcement is supported."
        }
      },
      "required": [
        "json_schema",
        "strict"
      ],
      "description": "Structured-output capabilities. Omitted when unsupported."
    },
    "inline_file_extensions": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "description": "Supported inline file extensions. Omitted when unsupported."
    }
  },
  "required": [
    "id",
    "object",
    "created",
    "owned_by",
    "display_name",
    "input_modalities",
    "pricing",
    "default_thinking_level",
    "context_window",
    "max_output_tokens",
    "thinking_levels"
  ]
}
```

### ModelPricing

```json
{
  "type": "object",
  "properties": {
    "inputNanoUsdPerToken": {
      "type": "integer",
      "minimum": 0,
      "description": "Effective uncached-input rate in nano-USD per token."
    },
    "cachedInputNanoUsdPerToken": {
      "type": "integer",
      "minimum": 0,
      "description": "Effective cache-read input rate in nano-USD per token."
    },
    "cacheWriteNanoUsdPerToken": {
      "type": "integer",
      "minimum": 0,
      "description": "Effective cache-write input rate in nano-USD per token."
    },
    "outputNanoUsdPerToken": {
      "type": "integer",
      "minimum": 0,
      "description": "Effective output rate in nano-USD per token."
    }
  },
  "required": [
    "inputNanoUsdPerToken",
    "cachedInputNanoUsdPerToken",
    "cacheWriteNanoUsdPerToken",
    "outputNanoUsdPerToken"
  ],
  "description": "Effective Bkper AI usage rates. One nano-USD is 0.000000001 USD."
}
```

### BkperErrorResponse

```json
{
  "type": "object",
  "additionalProperties": false,
  "required": [
    "error"
  ],
  "properties": {
    "error": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "message",
        "type",
        "param",
        "code"
      ],
      "properties": {
        "message": {
          "type": "string"
        },
        "type": {
          "type": "string"
        },
        "param": {
          "type": [
            "string",
            "null"
          ]
        },
        "code": {
          "type": "string",
          "description": "Stable Bkper error code. New codes may be added over time."
        }
      }
    }
  }
}
```

---
source: /docs/api/bkper-api-types.md

# bkper-api-types

> TypeScript type definitions for the Bkper API — shared interfaces and enumerations.

This package contains Typescript definitions for the [Bkper REST API](https://bkper.com/docs/#rest-api).

The types are generated based on the Bkper [Open API spec](https://bkper.com/docs/api/rest/openapi.json) using the [dtsgenerator](https://github.com/horiuchi/dtsgenerator) tool.

More information at the [Bkper Developer Documentation](https://bkper.com/docs/#rest-api)

[![npm (scoped)](https://img.shields.io/npm/v/@bkper/bkper-api-types?color=%235889e4)](https://www.npmjs.com/package/@bkper/bkper-api-types) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--api--types-blue?logo=github)](https://github.com/bkper/bkper-api-types)

### 2) Configure tsconfig.json:

```
{
    "compilerOptions": {
        "typeRoots" : ["node_modules/@bkper", "node_modules/@types" ]
    }
}
```

[Learn more](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types) about **@types**, **typeRoots** and **types**

## Interfaces

### Account

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `archived?`: `boolean` — Archived accounts are kept for history
- `balance?`: `string` — The running balance of the account at the transaction date.
- `balanceVerified?`: `boolean` — Whether the account balance has been verified/audited
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `credit?`: `boolean` — Credit nature or Debit otherwise
- `groups?`: `bkper.Group[]` — The groups of the account
- `hasTransactionPosted?`: `boolean` — Whether the account has any transactions posted
- `id?`: `string` — The unique id that identifies the Account in the Book
- `name?`: `string` — The name of the Account
- `normalizedName?`: `string` — The name of the Account, lowercase, without spaces or special characters
- `permanent?`: `boolean` — Permanent are such as bank accounts, customers or the like
- `properties?`: `{ [name: string]: string }` — The key/value custom properties of the Account
- `type?`: `"ASSET" | "LIABILITY" | "INCOMING" | "OUTGOING"` — The type of the account
- `updatedAt?`: `string` — The last update timestamp, in milliseconds

### AccountBalances

**Properties:**

- `archived?`: `boolean`
- `balances?`: `bkper.Balance[]`
- `credit?`: `boolean`
- `cumulativeBalance?`: `string`
- `cumulativeCredit?`: `string`
- `cumulativeDebit?`: `string`
- `empty?`: `boolean`
- `name?`: `string`
- `normalizedName?`: `string`
- `periodBalance?`: `string`
- `periodCredit?`: `string`
- `periodDebit?`: `string`
- `permanent?`: `boolean`
- `properties?`: `{ [name: string]: string }`

### AccountList

**Properties:**

- `items?`: `bkper.Account[]` — List items

### Agent

**Properties:**

- `id?`: `string` — The agent id
- `logo?`: `string` — The agent logo. Public url or Base64 encoded
- `logoDark?`: `string` — The agent logo on dark mode. Public url or Base64 encoded
- `name?`: `string` — The agent name

### App

**Properties:**

- `apiVersion?`: `"v0" | "v1" | "v2" | "v3" | "v4" | "v5"` — The API version of the event payload
- `clientId?`: `string` — The Google OAuth Client ID
- `clientSecret?`: `string` — The Google OAuth Client Secret
- `connectable?`: `boolean` — Whether this app is connectable by a user
- `deprecated?`: `boolean` — Whether the app is deprecated
- `description?`: `string` — The App description
- `developers?`: `string` — The developers (usernames and domain patterns), comma or space separated
- `events?`: `("FILE_CREATED" | "FILE_UPDATED" | "FILE_DELETED" | "TRANSACTION_CREATED" | "TRANSACTION_UPDATED" | "TRANSACTION_DELETED" | "TRANSACTION_POSTED" | "TRANSACTION_CHECKED" | "TRANSACTION_UNCHECKED" | "TRANSACTION_RESTORED" | "ACCOUNT_CREATED" | "ACCOUNT_UPDATED" | "ACCOUNT_DELETED" | "QUERY_CREATED" | "QUERY_UPDATED" | "QUERY_DELETED" | "GROUP_CREATED" | "GROUP_UPDATED" | "GROUP_DELETED" | "COMMENT_CREATED" | "COMMENT_DELETED" | "COLLABORATOR_ADDED" | "COLLABORATOR_UPDATED" | "COLLABORATOR_REMOVED" | "INTEGRATION_CREATED" | "INTEGRATION_UPDATED" | "INTEGRATION_DELETED" | "BOOK_CREATED" | "BOOK_AUDITED" | "BOOK_UPDATED" | "BOOK_DELETED")[]` — Event types the App listen to
- `filePatterns?`: `string[]` — File patterns the App handles - wildcard accepted. E.g. *.pdf, *-bank.csv
- `id?`: `string` — The unique agent id of the App - this can't be changed after created
- `installable?`: `boolean` — Whether this app is installable in a book
- `logoUrl?`: `string` — The App logo url
- `logoUrlDark?`: `string` — The App logo url in dark mode
- `menuOpenMode?`: `"SIDEBAR" | "EXPANDED" | "NEW_TAB"` — How the app menu opens. Default to SIDEBAR
- `menuPopupHeight?`: `string` — Deprecated
- `menuPopupWidth?`: `string` — Deprecated
- `menuText?`: `string` — The contex menu text - default to the App name
- `menuUrl?`: `string` — The context menu url
- `menuUrlDev?`: `string` — The context menu url in dev mode
- `name?`: `string` — The App name
- `ownerEmail?`: `string` — The owner user email
- `ownerId?`: `string` — The owner user id
- `ownerLogoUrl?`: `string` — The owner company logo url
- `ownerName?`: `string` — The owner company name
- `ownerWebsite?`: `string` — The owner company website url
- `propertiesSchema?`: `bkper.AppPropertiesSchema`
- `published?`: `boolean` — Whether this app is already published
- `readme?`: `string` — The readme.md file as string
- `readmeMd?`: `string` — The readme.md file as raw markdown string
- `repoPrivate?`: `boolean` — Whether the code repository is private
- `repoUrl?`: `string` — The code repository url
- `scopes?`: `string[]` — The Google OAuth Scopes used by the app
- `users?`: `string` — The users (usernames and domain patterns) to enable the App while not yet published
- `webhookUrl?`: `string` — The Webhook endpoint URL to listen for book events
- `webhookUrlDev?`: `string` — The Webhook endpoint URL to listen for book events in dev mode
- `website?`: `string` — The App website url

### AppList

**Properties:**

- `items?`: `bkper.App[]`

### AppPropertiesSchema

**Properties:**

- `account?`: `bkper.AppPropertySchema`
- `book?`: `bkper.AppPropertySchema`
- `group?`: `bkper.AppPropertySchema`
- `transaction?`: `bkper.AppPropertySchema`

### AppPropertySchema

**Properties:**

- `keys?`: `string[]` — The property keys schema
- `values?`: `string[]` — The property values schema

### Backlog

**Properties:**

- `count?`: `number`

### Balance

**Properties:**

- `cumulativeBalance?`: `string`
- `cumulativeCredit?`: `string`
- `cumulativeDebit?`: `string`
- `day?`: `number`
- `fuzzyDate?`: `number`
- `month?`: `number`
- `periodBalance?`: `string`
- `periodCredit?`: `string`
- `periodDebit?`: `string`
- `year?`: `number`

### Balances

**Properties:**

- `accountBalances?`: `bkper.AccountBalances[]`
- `balancesUrl?`: `string`
- `groupBalances?`: `bkper.GroupBalances[]`
- `nextRange?`: `string`
- `periodicity?`: `"DAILY" | "MONTHLY" | "YEARLY"`
- `previousRange?`: `string`
- `range?`: `string`
- `rangeBeginLabel?`: `string`
- `rangeEndLabel?`: `string`

### Billing

**Properties:**

- `adminEmail?`: `string` — The billing admin email for the user's billing account
- `daysLeftInTrial?`: `number` — How many days the user has left in the trial period
- `email?`: `string` — The user's email address
- `enabled?`: `boolean` — True if billing is enabled for the user
- `hostedDomain?`: `string` — The user hosted domain
- `plan?`: `string` — The user's current plan
- `planOverdue?`: `boolean` — True if subscription payment is overdue
- `startedTrial?`: `boolean` — True if the user has started the trial period
- `totalTransactionsThisMonth?`: `number` — User-level total transactions this month
- `totalTransactionsThisYear?`: `number` — User-level total transactions this year

### Book

**Properties:**

- `accounts?`: `bkper.Account[]` — The book Accounts
- `agentId?`: `string` — The id of agent that created the resource
- `autoPost?`: `boolean` — Tells if the Book has auto post enabled
- `closingDate?`: `string` — The book closing date, in ISO format yyyy-MM-dd. Transactions on or before this date are closed for the period
- `collection?`: `bkper.Collection`
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `datePattern?`: `string` — The date pattern of the Book. Example: dd/MM/yyyy
- `decimalSeparator?`: `"DOT" | "COMMA"` — The decimal separator of the Book
- `fractionDigits?`: `number` — The number of fraction digits (decimal places) of the Book. E.g. 2 for ####.##, 4 for ####.####
- `groups?`: `bkper.Group[]` — The book account Groups
- `id?`: `string` — The unique id that identifies the Book in the system. Found at bookId url param
- `lastUpdateMs?`: `string` — The last update date of the Book, in milliseconds
- `lockDate?`: `string` — The book lock date, in ISO format yyyy-MM-dd. Transactions on or before this date are locked
- `logoUrl?`: `string` — The logo URL of the book owner's custom domain
- `name?`: `string` — The name of the Book
- `ownerName?`: `string` — The Book owner username
- `pageSize?`: `number` — The transactions pagination page size
- `period?`: `"MONTH" | "QUARTER" | "YEAR"` — The period slice for balances visualization
- `periodStartMonth?`: `"JANUARY" | "FEBRUARY" | "MARCH" | "APRIL" | "MAY" | "JUNE" | "JULY" | "AUGUST" | "SEPTEMBER" | "OCTOBER" | "NOVEMBER" | "DECEMBER"` — The start month when YEAR period set
- `permission?`: `"OWNER" | "EDITOR" | "POSTER" | "RECORDER" | "VIEWER" | "NONE"` — The Permission the current user has in the Book
- `properties?`: `{ [name: string]: string }` — The key/value custom properties of the Book
- `timeZone?`: `string` — The time zone of the Book, in IANA format. E.g. America/New_York, Europe/London
- `timeZoneOffset?`: `number` — The time zone offset of the Book, in minutes
- `totalTransactions?`: `number` — The total transactions posted
- `totalTransactionsCurrentMonth?`: `number` — The total transactions posted on current month
- `totalTransactionsCurrentYear?`: `number` — The total transactions posted on current year
- `updatedAt?`: `string` — The last update timestamp, in milliseconds
- `visibility?`: `"PUBLIC" | "PRIVATE"` — The Visibility of the Book

### BookList

**Properties:**

- `items?`: `bkper.Book[]` — List items

### BotResponse

**Properties:**

- `agentId?`: `string`
- `createdAt?`: `string`
- `message?`: `string`
- `type?`: `"INFO" | "WARNING" | "ERROR"`

### Collaborator

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `avatarUrl?`: `string` — The Collaborator public avatar url
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `email?`: `string` — The email of the Collaborator
- `id?`: `string` — The unique id that identifies the Collaborator in the Book
- `permission?`: `"OWNER" | "EDITOR" | "POSTER" | "RECORDER" | "VIEWER" | "NONE"` — The permission the Collaborator has in the Book
- `updatedAt?`: `string` — The last update timestamp, in milliseconds

### CollaboratorPayloadCollection

**Properties:**

- `items?`: `bkper.Collaborator[]`

### Collection

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `books?`: `bkper.Book[]` — The Books contained in the Collection
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `id?`: `string` — The unique id of the Collection
- `name?`: `string` — The name of the Collection
- `ownerUsername?`: `string` — The username of the Collection owner
- `permission?`: `"OWNER" | "EDITOR" | "POSTER" | "RECORDER" | "VIEWER" | "NONE"` — The permission the current user has in the Collection. E.g. OWNER, EDITOR, NONE
- `updatedAt?`: `string` — The last update timestamp, in milliseconds

### CollectionList

**Properties:**

- `items?`: `bkper.Collection[]` — List items

### Connection

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `dateAddedMs?`: `string`
- `email?`: `string`
- `id?`: `string`
- `logo?`: `string`
- `name?`: `string`
- `properties?`: `{ [name: string]: string }`
- `type?`: `"APP" | "BANK"`
- `updatedAt?`: `string` — The last update timestamp, in milliseconds
- `userId?`: `string`
- `uuid?`: `string`

### ConnectionList

**Properties:**

- `items?`: `bkper.Connection[]` — List items

### Count

**Properties:**

- `day?`: `number`
- `fuzzyDate?`: `number`
- `month?`: `number`
- `total?`: `number`
- `year?`: `number`

### Counts

**Properties:**

- `posted?`: `bkper.Count[]`
- `trashed?`: `bkper.Count[]`

### Event

**Properties:**

- `agent?`: `bkper.Agent`
- `book?`: `bkper.Book`
- `bookId?`: `string` — The id of the Book associated to the Event
- `botResponses?`: `bkper.BotResponse[]` — The list of bot responses associated to the Event
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `createdOn?`: `string` — The creation date time on RFC3339 format
- `data?`: `bkper.EventData`
- `id?`: `string` — The unique id that identifies the Event
- `resource?`: `string` — The resource associated to the Event
- `type?`: `"FILE_CREATED" | "FILE_UPDATED" | "FILE_DELETED" | "TRANSACTION_CREATED" | "TRANSACTION_UPDATED" | "TRANSACTION_DELETED" | "TRANSACTION_POSTED" | "TRANSACTION_CHECKED" | "TRANSACTION_UNCHECKED" | "TRANSACTION_RESTORED" | "ACCOUNT_CREATED" | "ACCOUNT_UPDATED" | "ACCOUNT_DELETED" | "QUERY_CREATED" | "QUERY_UPDATED" | "QUERY_DELETED" | "GROUP_CREATED" | "GROUP_UPDATED" | "GROUP_DELETED" | "COMMENT_CREATED" | "COMMENT_DELETED" | "COLLABORATOR_ADDED" | "COLLABORATOR_UPDATED" | "COLLABORATOR_REMOVED" | "INTEGRATION_CREATED" | "INTEGRATION_UPDATED" | "INTEGRATION_DELETED" | "BOOK_CREATED" | "BOOK_AUDITED" | "BOOK_UPDATED" | "BOOK_DELETED"` — The type of the Event
- `user?`: `bkper.User`

### EventData

**Properties:**

- `object?`: `{ [key: string]: any }`
- `previousAttributes?`: `{ [name: string]: string }` — The object previous attributes when updated

### EventList

**Properties:**

- `cursor?`: `string` — The cursor, for pagination
- `items?`: `bkper.Event[]` — List items

### File

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `content?`: `string` — The file content Base64 encoded
- `contentType?`: `string` — The file content type
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `id?`: `string` — The unique id that identifies the file in the book
- `name?`: `string` — The file name
- `properties?`: `{ [name: string]: string }` — The key/value custom properties of the File
- `size?`: `number` — The file size in bytes
- `updatedAt?`: `string` — The last update timestamp, in milliseconds
- `url?`: `string` — The file serving url

### FileList

**Properties:**

- `cursor?`: `string` — The cursor, for pagination
- `items?`: `bkper.File[]` — List items

### Group

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `credit?`: `boolean` — Whether the group has credit nature
- `hasAccounts?`: `boolean` — Whether the group has any accounts
- `hasGroups?`: `boolean` — Whether the group has any children groups
- `hidden?`: `boolean` — Whether the group is hidden on the transactions main menu
- `id?`: `string` — The unique id that identifies the Group in the Book
- `locked?`: `boolean` — Whether the group is locked by the Book owner
- `mixed?`: `boolean` — Whether the group has mixed types of accounts
- `name?`: `string` — The name of the Group
- `normalizedName?`: `string` — The name of the Group, lowercase, without spaces or special characters
- `parent?`: `bkper.Group`
- `permanent?`: `boolean` — Whether the group is permanent
- `properties?`: `{ [name: string]: string }` — The key/value custom properties of the Group
- `type?`: `"ASSET" | "LIABILITY" | "INCOMING" | "OUTGOING"` — The type of the accounts in the group. E.g. ASSET, LIABILITY, INCOMING, OUTGOING
- `updatedAt?`: `string` — The last update timestamp, in milliseconds

### GroupBalances

**Properties:**

- `accountBalances?`: `bkper.AccountBalances[]`
- `balances?`: `bkper.Balance[]`
- `credit?`: `boolean`
- `cumulativeBalance?`: `string`
- `cumulativeCredit?`: `string`
- `cumulativeDebit?`: `string`
- `groupBalances?`: `bkper.GroupBalances[]`
- `name?`: `string`
- `normalizedName?`: `string`
- `periodBalance?`: `string`
- `periodCredit?`: `string`
- `periodDebit?`: `string`
- `permanent?`: `boolean`
- `properties?`: `{ [name: string]: string }`

### GroupList

**Properties:**

- `items?`: `bkper.Group[]` — List items

### Integration

**Properties:**

- `addedBy?`: `string`
- `agentId?`: `string` — The id of agent that created the resource
- `bookId?`: `string`
- `connectionId?`: `string`
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `dateAddedMs?`: `string`
- `id?`: `string`
- `lastUpdateMs?`: `string`
- `logo?`: `string`
- `logoDark?`: `string`
- `name?`: `string`
- `normalizedName?`: `string`
- `properties?`: `{ [name: string]: string }`
- `updatedAt?`: `string` — The last update timestamp, in milliseconds
- `userId?`: `string`

### IntegrationList

**Properties:**

- `items?`: `bkper.Integration[]` — List items

### Query

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `id?`: `string` — The unique id that identifies the saved Query in the Book
- `query?`: `string` — The Query string to be executed
- `title?`: `string` — The title of the saved Query
- `updatedAt?`: `string` — The last update timestamp, in milliseconds

### QueryList

**Properties:**

- `items?`: `bkper.Query[]` — List items

### Template

**Properties:**

- `bookId?`: `string`
- `bookLink?`: `string`
- `category?`: `string`
- `description?`: `string`
- `imageUrl?`: `string`
- `name?`: `string`
- `sheetsLink?`: `string`
- `timesUsed?`: `number`

### TemplateList

**Properties:**

- `items?`: `bkper.Template[]` — List items

### Transaction

**Properties:**

- `agentId?`: `string` — The id of agent that created the resource
- `agentLogo?`: `string` — The logo of the agent that created the transaction
- `agentLogoDark?`: `string` — The logo in dark mode, of the agent that created the transaction
- `agentName?`: `string` — The name of the agent that created the transaction
- `amount?`: `string` — The amount on format ####.##
- `checked?`: `boolean` — Whether the transaction is checked
- `createdAt?`: `string` — The creation timestamp, in milliseconds
- `createdBy?`: `string` — The actor username that created the transaction
- `creditAccount?`: `bkper.Account`
- `date?`: `string` — The date on ISO format yyyy-MM-dd
- `dateFormatted?`: `string` — The date on format of the Book
- `dateValue?`: `number` — The date number representation on format YYYYMMDD
- `debitAccount?`: `bkper.Account`
- `description?`: `string` — The transaction description
- `draft?`: `boolean` — Whether the transaction is a draft
- `files?`: `bkper.File[]` — The files attached to the transaction
- `id?`: `string` — The unique id that identifies the transaction in the book
- `posted?`: `boolean` — Whether the transaction is already posted on accounts, otherwise is a draft
- `properties?`: `{ [name: string]: string }` — The key/value custom properties of the Transaction
- `remoteIds?`: `string[]` — The transaction remote ids, to avoid duplication
- `tags?`: `string[]` — The transaction #hashtags
- `trashed?`: `boolean` — Whether the transaction is trashed
- `updatedAt?`: `string` — The last update timestamp, in milliseconds
- `urls?`: `string[]` — The transaction urls

### TransactionList

**Properties:**

- `account?`: `string` — The account id when filtering by a single account. E.g. account='Bank'
- `cursor?`: `string` — The cursor, for pagination
- `items?`: `bkper.Transaction[]` — List items

### TransactionOperation

**Properties:**

- `accounts?`: `bkper.Account[]` — The affected accounts
- `transaction?`: `bkper.Transaction`

### Url

**Properties:**

- `url?`: `string`

### User

**Properties:**

- `avatarUrl?`: `string` — The user public avatar url
- `bankConnections?`: `boolean` — True if user already had any bank connection
- `billingAdminEmail?`: `string` — The billing admin email for this user's billing account
- `billingEnabled?`: `boolean` — True if billing is enabled for the user
- `daysLeftInTrial?`: `number` — How many days left in trial
- `domain?`: `bkper.Domain`
- `email?`: `string` — The user email
- `free?`: `boolean` — True if user is in the free plan
- `fullName?`: `string` — The user full name
- `givenName?`: `string` — The user given name
- `hash?`: `string` — The user hash
- `hostedDomain?`: `string` — The user hosted domain
- `id?`: `string` — The user unique id
- `name?`: `string` — The user display name
- `plan?`: `string` — The user plan
- `planCycle?`: `"MONTHLY" | "YEARLY"` — The user plan billing cycle
- `planOverdue?`: `boolean` — True if subscription payment is overdue
- `startedTrial?`: `boolean` — True if user started trial
- `totalTransactionsThisMonth?`: `number` — User-level total transactions this month
- `totalTransactionsThisYear?`: `number` — User-level total transactions this year
- `username?`: `string` — The Bkper username of the user

---
source: /docs/api/bkper-gs.md

# bkper-gs

> Google Apps Script library for Bkper — use Bkper directly in Google Sheets and Apps Script projects.

[![GitHub](https://img.shields.io/badge/bkper%2Fbkper--gs-blue?logo=github)](https://github.com/bkper/bkper-gs)

# Summary

This package contains Typescript definitions for [BkperApp](https://bkper.com/docs/bkper-gs/)

### 1) Add the package:

```
npm i -S @bkper/bkper-gs-types
```
or
```
yarn add --dev @bkper/bkper-gs-types
```

### 2) Configure tsconfig.json:

```
{
    "compilerOptions": {
        "typeRoots" : ["node_modules/@bkper", "node_modules/@types" ]
    }
}
```

[Learn more](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types) about **@types**, **typeRoots** and **types**

# Details

Generated using [clasp-types](https://github.com/maelcaldas/clasp-types)

## Interfaces

### Account

**Properties:**

- `payload`: `bkper.Account` — The underlying payload data for this resource

**Methods:**

- `addGroup(group: string | Bkper.Group)` → `Bkper.Account` — Add a group to the Account.
- `create()` → `Bkper.Account` — Perform create new account.
- `deleteProperty(key: string)` → `this` — Deletes a custom property.
- `getBalance()` → `Bkper.Amount` — Gets the balance on the current month, based on the credit nature of this Account.
- `getBalanceRaw()` → `Bkper.Amount` — Gets the raw balance on the current month, no matter the credit nature of this Account.
- `getDescription()` → `string` — ~~Deprecated: Use properties instead~~ Gets the account description
- `getGroups()` / `setGroups(groups: Bkper.Group[] | string[])` → `Bkper.Group[] (set: Bkper.Group[] | string[])` — Get the `Groups` of this account.
- `getId()` → `string` — Gets the account internal id.
- `getName()` / `setName(name: string)` → `string` — Gets the account name.
- `getNormalizedName()` → `string`
- `getProperties()` / `setProperties(properties: { [key: string]: string })` → `{ [key: string]: string }` — Gets the custom properties stored in this resource.
- `getProperty(keys: string[])` / `setProperty(key: string, value: string)` → `string` — Gets the property value for given keys. First property found will be retrieved.
- `getPropertyKeys()` → `string[]` — Gets the custom properties keys stored in this resource.
- `getType()` / `setType(type: Bkper.AccountType)` → `Bkper.AccountType`
- `getVisibleProperties()` / `setVisibleProperties(properties: { [key: string]: string })` → `{ [key: string]: string }` — Gets the visible custom properties stored in this resource.
Hidden properties (those ending with "_") are excluded from the result.
- `hasTransactionPosted()` → `boolean` — Tell if the Account has any transaction already posted.
- `isActive()` → `boolean` — ~~Deprecated: Use isArchived instead~~ Tell if this account is Active or otherwise Archived.
- `isArchived()` → `boolean` — Tell if this account is archived.
- `isCredit()` → `boolean` — Tell if the account has a Credit nature or Debit otherwise
- `isInGroup(group: string | Bkper.Group)` → `boolean` — Tell if this account is in the `Group`
- `isPermanent()` → `boolean` — Tell if the account is permanent.
- `json()` → `bkper.Account` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Bkper.Account` — Perform delete account.
- `removeGroup(group: string | Bkper.Group)` → `Bkper.Account` — Remove a group from the Account.
- `setArchived(archived: boolean)` → `Bkper.Account` — Set account archived/unarchived.
- `setVisibleProperty(key: string, value: string | null)` → `this` — Sets a custom property in this resource, filtering out hidden properties.
Hidden properties are those whose keys end with an underscore "_".
- `update()` → `Bkper.Account` — Perform update account, applying pending changes.

**hasTransactionPosted**

Accounts with transaction posted, even with zero balance, can only be archived.

**isCredit**

Credit accounts are just for representation purposes. It increase or decrease the absolute balance. It doesn't affect the overall balance or the behavior of the system.

The absolute balance of credit accounts increase when it participate as a credit/origin in a transaction. Its usually for Accounts that increase the balance of the assets, like revenue accounts.

```
        Crediting a credit
  Thus ---------------------> account increases its absolute balance
        Debiting a debit


        Debiting a credit
  Thus ---------------------> account decreases its absolute balance
        Crediting a debit
```

As a rule of thumb, and for simple understanding, almost all accounts are Debit nature (NOT credit), except the ones that "offers" amount for the books, like revenue accounts.

**isPermanent**

Permanent Accounts are the ones which final balance is relevant and keep its balances over time.

They are also called [Real Accounts](http://en.wikipedia.org/wiki/Account_(accountancy)#Based_on_periodicity_of_flow)

Usually represents assets or tangibles, capable of being perceived by the senses or the mind, like bank accounts, money, debts and so on.

### AccountsDataTableBuilder

**Methods:**

- `archived(include: boolean)` → `Bkper.AccountsDataTableBuilder` — Defines whether the archived accounts should included.
- `build()` → `any[][]`
- `groups(include: boolean)` → `Bkper.AccountsDataTableBuilder` — Defines whether include account groups.
- `ids(include: boolean)` → `Bkper.AccountsDataTableBuilder` — Defines whether include account ids.
- `properties(include: boolean)` → `Bkper.AccountsDataTableBuilder` — Defines whether include custom account properties.

### Amount

**Methods:**

- `abs()` → `Bkper.Amount` — Returns an absolute Amount.
- `cmp(n: string | number | Bkper.Amount)` → `-1 | 0 | 1` — Compare
- `div(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Divide by
- `eq(n: string | number | Bkper.Amount)` → `boolean` — Equals to
- `gt(n: string | number | Bkper.Amount)` → `boolean` — Greater than
- `gte(n: string | number | Bkper.Amount)` → `boolean` — Greater than or equal
- `lt(n: string | number | Bkper.Amount)` → `boolean` — Less than
- `lte(n: string | number | Bkper.Amount)` → `boolean` — Less than or equal to
- `minus(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Minus
- `mod(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Modulo - the integer remainder of dividing this Amount by n.
- `plus(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Sum
- `round(dp?: number)` → `Bkper.Amount` — Round to a maximum of dp decimal places.
- `times(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Multiply
- `toFixed(dp?: number)` → `string` — Returns a string representing the value of this Amount in normal notation to a fixed number of decimal places dp.
- `toNumber()` → `number` — Returns a primitive number representing the value of this Amount.
- `toString()` → `string` — Returns a string representing the value of this Amount.

**mod**

Similar to % operator

### App

**Properties:**

- `payload`: `bkper.App` — The underlying payload data for this resource

**Methods:**

- `getDescription()` → `string`
- `getId()` → `string`
- `getName()` → `string`
- `json()` → `bkper.App` — Gets an immutable copy of the JSON payload for this resource.

### Backlog

**Properties:**

- `payload`: `bkper.Backlog` — The underlying payload data for this resource

**Methods:**

- `getCount()` → `number`
- `json()` → `bkper.Backlog` — Gets an immutable copy of the JSON payload for this resource.

### Balance

**Properties:**

- `payload`: `bkper.Balance` — The underlying payload data for this resource

**Methods:**

- `getCumulativeBalance()` → `Bkper.Amount` — The cumulative balance to the date, based on the credit nature of the container
- `getCumulativeBalanceRaw()` → `Bkper.Amount` — The raw cumulative balance to the date.
- `getCumulativeCredit()` → `Bkper.Amount` — The cumulative credit to the date.
- `getCumulativeDebit()` → `Bkper.Amount` — The cumulative debit to the date.
- `getDate()` → `Date` — Date object constructed based on `Book` time zone offset. Usefull for
- `getDay()` → `number` — The day of the balance. Days starts on 1 to 31.
- `getFuzzyDate()` → `number` — The Fuzzy Date of the balance, based on `Periodicity` of the `BalancesReport` query, composed by Year, Month and Day.
- `getMonth()` → `number` — The month of the balance. Months starts on 1 (January) to 12 (December)
- `getPeriodBalance()` → `Bkper.Amount` — The balance on the date period, based on credit nature of the container.
- `getPeriodBalanceRaw()` → `Bkper.Amount` — The raw balance on the date period.
- `getPeriodCredit()` → `Bkper.Amount` — The credit on the date period.
- `getPeriodDebit()` → `Bkper.Amount` — The debit on the date period.
- `getYear()` → `number` — The year of the balance
- `json()` → `bkper.Balance` — Gets an immutable copy of the JSON payload for this resource.

**getDate**

If Month or Day is zero, the date will be constructed with first Month (January) or Day (1).

**getDay**

Day can be 0 (zero) in case of Monthly or Early `Periodicity` of the `BalancesReport`

**getFuzzyDate**

The format is **YYYYMMDD**. Very usefull for ordering and indexing

Month and Day can be 0 (zero), depending on the granularity of the `Periodicity`.

*Example:*

**20180125** - 25, January, 2018 - DAILY Periodicity

**20180100** - January, 2018 - MONTHLY Periodicity

**20180000** - 2018 - YEARLY Periodicity

**getMonth**

Month can be 0 (zero) in case of Early `Periodicity` of the `BalancesReport`

### BalancesContainer

**Methods:**

- `addBalancesContainer(container: Bkper.BalancesContainer)` → `Bkper.BalancesContainer` — Adds an `Account` container to a `Group` container.
- `createDataTable()` → `Bkper.BalancesDataTableBuilder` — Creates a BalancesDataTableBuilder to generate a two-dimensional array with all `BalancesContainers`
- `getAccount()` → `Bkper.Account` — The `Account` associated with this container
- `getAccountBalancesContainers()` → `Bkper.BalancesContainer[]` — Gets all `Account` `BalancesContainers`.
- `getBalances()` → `Bkper.Balance[]` — All `Balances` of the container
- `getBalancesContainer(name: string)` → `Bkper.BalancesContainer` — Gets a specific `BalancesContainer`.
- `getBalancesContainers()` → `Bkper.BalancesContainer[]` — Gets all child `BalancesContainers`.
- `getBalancesReport()` → `Bkper.BalancesReport` — The parent BalancesReport of the container
- `getCumulativeBalance()` → `Bkper.Amount` — The cumulative balance to the date.
- `getCumulativeBalanceRaw()` → `Bkper.Amount` — The cumulative raw balance to the date.
- `getCumulativeBalanceRawText()` → `string` — The cumulative raw balance formatted according to `Book` decimal format and fraction digits.
- `getCumulativeBalanceText()` → `string` — The cumulative balance formatted according to `Book` decimal format and fraction digits.
- `getCumulativeCredit()` → `Bkper.Amount` — The cumulative credit to the date.
- `getCumulativeCreditText()` → `string` — The cumulative credit formatted according to `Book` decimal format and fraction digits.
- `getCumulativeDebit()` → `Bkper.Amount` — The cumulative debit to the date.
- `getCumulativeDebitText()` → `string` — The cumulative credit formatted according to `Book` decimal format and fraction digits.
- `getDepth()` → `number` — The depth in the parent chain up to the root.
- `getGroup()` → `Bkper.Group` — The `Group` associated with this container
- `getName()` → `string` — The `Account` or `Group` name
- `getNormalizedName()` → `string` — The `Account` or `Group` name without spaces or special characters.
- `getParent()` → `Bkper.BalancesContainer` — The parent BalanceContainer
- `getPeriodBalance()` → `Bkper.Amount` — The balance on the date period.
- `getPeriodBalanceRaw()` → `Bkper.Amount` — The raw balance on the date period.
- `getPeriodBalanceRawText()` → `string` — The raw balance on the date period formatted according to `Book` decimal format and fraction digits
- `getPeriodBalanceText()` → `string` — The balance on the date period formatted according to `Book` decimal format and fraction digits
- `getPeriodCredit()` → `Bkper.Amount` — The credit on the date period.
- `getPeriodCreditText()` → `string` — The credit on the date period formatted according to `Book` decimal format and fraction digits
- `getPeriodDebit()` → `Bkper.Amount` — The debit on the date period.
- `getPeriodDebitText()` → `string` — The debit on the date period formatted according to `Book` decimal format and fraction digits
- `getProperties()` → `{ [key: string]: string }` — Gets the custom properties stored in this Account or Group.
- `getProperty(keys: string[])` → `string` — Gets the property value for given keys. First property found will be retrieved
- `getPropertyKeys()` → `string[]` — Gets the custom properties keys stored in the associated `Account` or `Group`.
- `hasGroupBalances()` → `boolean` — Tell if the balance container is from a parent group
- `isCredit()` → `boolean` — Gets the credit nature of the BalancesContainer, based on `Account` or `Group`.
- `isFromAccount()` → `boolean` — Tell if this balance container if from an `Account`
- `isFromGroup()` → `boolean` — Tell if this balance container if from a `Group`
- `isPermanent()` → `boolean` — Tell if this balance container is permament, based on the `Account` or `Group`.
- `removeBalancesContainer(container: Bkper.BalancesContainer)` → `Bkper.BalancesContainer` — Removes an `Account` container from a `Group` container.

**addBalancesContainer**

**NOTE**: Only for Group balance containers.

**getBalancesContainers**

**NOTE**: Only for Group balance containers. Accounts returns null.

**isCredit**

For `Account`, the credit nature will be the same as the one from the Account

For `Group`, the credit nature will be the same, if all accounts containing on it has the same credit nature. False if mixed.

**isPermanent**

Permanent are the ones which final balance is relevant and keep its balances over time.

They are also called [Real Accounts](http://en.wikipedia.org/wiki/Account_(accountancy)#Based_on_periodicity_of_flow)

Usually represents assets or liabilities, capable of being perceived by the senses or the mind, like bank accounts, money, debts and so on.

**removeBalancesContainer**

**NOTE**: Only for Group balance containers.

### BalancesDataTableBuilder

**Methods:**

- `build()` → `any[][]` — Builds an two-dimensional array with the balances.
- `expanded(expanded: number | boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether Groups should expand its child accounts.
- `formatDates(format: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether the dates should be ISO YYYY-MM-DD formatted.
- `formatValues(format: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether the value should be formatted based on decimal separator of the `Book`.
- `hideDates(hide: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether the dates should be hidden for **PERIOD** or **CUMULATIVE** `BalanceType`.
- `hideNames(hide: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether the `Accounts` and `Groups` names should be hidden.
- `period(period: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether should force use of period balances for **TOTAL** `BalanceType`.
- `properties(include: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether include custom `Accounts` and `Groups` properties.
- `raw(raw: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether should show raw balances, no matter the credit nature of the Account or Group.
- `transposed(transposed: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether should rows and columns should be transposed.
- `trial(trial: boolean)` → `Bkper.BalancesDataTableBuilder` — Defines whether should split **TOTAL** `BalanceType` into debit and credit.
- `type(type: Bkper.BalanceType)` → `Bkper.BalancesDataTableBuilder` — Fluent method to set the `BalanceType` for the builder.

**expanded**

true to expand itself
-1 to expand all subgroups
-2 to expand all accounts
0 to expand nothing
1 to expand itself and its first level of children
2 to expand itself and its first two levels of children
etc.

**transposed**

For **TOTAL** `BalanceType`, the **transposed** table looks like:

```
  _____________________________
 |  Expenses | Income  |  ...  |
 | -4568.23  | 5678.93 |  ...  |
 |___________|_________|_______|

```
Two rows, and each `Account` or `Group` per column.


For **PERIOD** or **CUMULATIVE** `BalanceType`, the **transposed** table will be a time table, and the format looks like:

```
  _______________________________________________________________
 |            | Expenses   | Income     |     ...    |    ...    |
 | 15/01/2014 | -2345.23   |  3452.93   |     ...    |    ...    |
 | 15/02/2014 | -2345.93   |  3456.46   |     ...    |    ...    |
 | 15/03/2014 | -2456.45   |  3567.87   |     ...    |    ...    |
 |     ...    |     ...    |     ...    |     ...    |    ...    |
 |____________|____________|____________|____________|___________|

```

First column will be each `Account` or `Group`, and one column for each Date.

### BalancesReport

**Properties:**

- `payload`: `bkper.Balances` — The underlying payload data for this resource

**Methods:**

- `createDataTable()` → `Bkper.BalancesDataTableBuilder` — Creates a BalancesDataTableBuilder to generate a two-dimensional array with all `BalancesContainers`.
- `getAccountBalancesContainers()` → `Bkper.BalancesContainer[]` — Gets all `Account` `BalancesContainers`.
- `getBalancesContainer(name: string)` → `Bkper.BalancesContainer` — Gets a specific `BalancesContainer`.
- `getBalancesContainers()` → `Bkper.BalancesContainer[]` — Gets all `BalancesContainers` of the report.
- `getBook()` → `Bkper.Book` — The `Book` that generated the report.
- `getPeriodicity()` → `Bkper.Periodicity` — The `Periodicity` of the query used to generate the report.
- `hasOnlyOneGroup()` → `boolean` — Check if the report has only one Group specified on query.
- `json()` → `bkper.Balances` — Gets an immutable copy of the JSON payload for this resource.

### BkperApp

**Properties:**

- `AccountType`: `Bkper.AccountType`
- `BalanceType`: `Bkper.BalanceType`
- `BotResponseType`: `Bkper.BotResponseType`
- `DecimalSeparator`: `Bkper.DecimalSeparator`
- `Month`: `Bkper.Month`
- `Periodicity`: `Bkper.Periodicity`
- `Permission`: `Bkper.Permission`
- `TransactionStatus`: `Bkper.TransactionStatus`

**Methods:**

- `getBook(id: string)` → `Bkper.Book` — Gets the `Book` with the specified bookId from url param.
- `getBooks()` → `Bkper.Book[]` — Gets all `Books` the user has access.
- `newAmount(n: string | number | Bkper.Amount)` → `Bkper.Amount` — Create a new `Amount` wrapping a given number, or arbitrary-precision math calculations.
- `normalizeName(name: string)` → `string` — Normalize a name
- `setAgentId(agentId: string | null)` → `void` — Sets the agent ID to identify the calling agent for attribution purposes.
- `setApiKey(key: string | null)` → `void` — Sets the API key for dedicated quota limits.
- `setOAuthTokenProvider(tokenProvider: Bkper.OAuthTokenProvider)` → `void` — Sets the `OAuthTokenProvider`.

**getBook**

This is the main Entry Point to start interacting with the [bkper-gs](https://github.com/bkper/bkper-gs) library.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");
book.record("#fuel for my Land Rover 126.50 28/01/2013");
```

**setAgentId**

This ID is sent via the `bkper-agent-id` header with each API request,
allowing the server to attribute actions to the correct agent.

**setApiKey**

API keys are optional - if not set, the Bkper API proxy provides a managed key with shared quota.
Use your own API key for dedicated quota limits and project-level usage tracking.

API keys are for project identification only, not for authentication or agent attribution.
Agent attribution is handled separately via `setAgentId()`.

**setOAuthTokenProvider**

If none set, the default built-in [ScriptApp](https://developers.google.com/apps-script/reference/script/script-app#getoauthtoken) will be used.

### Book

**Properties:**

- `payload`: `bkper.Book` — The underlying payload data for this resource

**Methods:**

- `addCollaborator(email: string, permission: Bkper.Permission)` → `void` — Adds a collaborator to the Book.
- `audit()` → `void` — Trigger Balances Audit async process.
- `batchCheckTransactions(transactions: Bkper.Transaction[])` → `void` — Batch check `Transactions` on the Book.
- `batchCreateAccounts(accounts: Bkper.Account[])` → `Bkper.Account[]` — Create `Accounts` on the Book, in batch.
- `batchCreateGroups(groups: Bkper.Group[])` → `Bkper.Group[]` — Create `Groups` on the Book, in batch.
- `batchCreateTransactions(transactions: Bkper.Transaction[])` → `Bkper.Transaction[]` — Batch create `Transactions` on the Book.
- `batchTrashTransactions(transactions: Bkper.Transaction[], trashChecked?: boolean)` → `void` — Batch trash `Transactions` on the Book.
- `batchUncheckTransactions(transactions: Bkper.Transaction[])` → `void` — Batch uncheck `Transactions` on the Book.
- `batchUpdateTransactions(transactions: Bkper.Transaction[], updateChecked?: boolean)` → `void` — Batch update `Transactions` on the Book.
- `continueTransactionIterator(query: string, continuationToken: string)` → `Bkper.TransactionIterator` — Resumes a transaction iteration using a continuation token from a previous iterator.
- `countTransactions(query?: string)` → `number` — Retrieve the number of transactions based on a query.
- `createAccount(name: string, group?: string, description?: string)` → `Bkper.Account` — ~~Deprecated~~ Create an `Account` in this book.
- `createAccounts(accounts: string[][])` → `Bkper.Account[]` — ~~Deprecated~~ Create `Accounts` on the Book, in batch.
- `createAccountsDataTable(group?: string)` → `Bkper.AccountsDataTableBuilder` — Create a `AccountsDataTableBuilder`, to build two dimensional Array representations of `Accounts` dataset.
- `createBalancesDataTable(query: string)` → `Bkper.BalancesDataTableBuilder` — Create a `BalancesDataTableBuilder` based on a query, to create two dimensional Array representation of balances of `Account` or `Group`
- `createGroups(groups: string[])` → `Bkper.Group[]` — ~~Deprecated~~ Create `Groups` on the Book, in batch.
- `createGroupsDataTable()` → `Bkper.GroupsDataTableBuilder` — Create a `GroupsDataTableBuilder`, to build two dimensional Array representations of `Groups` dataset.
- `createTransactionsDataTable(query?: string)` → `Bkper.TransactionsDataTableBuilder` — Create a `TransactionsDataTableBuilder` based on a query, to build two dimensional Array representations of `Transactions` dataset.
- `formatAmount(amount: Bkper.Amount)` → `string` — Formats an amount according to `DecimalSeparator` and fraction digits of the Book.
- `formatDate(date: Date, timeZone?: string)` → `string` — Formats a date according to date pattern of the Book.
- `formatValue(value: Bkper.Amount)` → `string` — ~~Deprecated~~ Formats a value according to `DecimalSeparator` and fraction digits of the Book.
- `getAccount(idOrName: string)` → `Bkper.Account` — Gets an `Account` object
- `getAccounts(group?: string)` → `Bkper.Account[]`
- `getApps()` → `Bkper.App[]` — Retrieve installed `Apps` for this Book
- `getBacklog()` → `Bkper.Backlog` — Retrieve the pending events `Backlog` for this Book
- `getBalancesReport(query: string)` → `Bkper.BalancesReport` — Create a `BalancesReport` based on query
- `getClosingDate()` / `setClosingDate(closingDate: string | null)` → `string (set: string | null)`
- `getCollection()` → `Bkper.Collection`
- `getDatePattern()` / `setDatePattern(datePattern: string)` → `string`
- `getDecimalSeparator()` / `setDecimalSeparator(decimalSeparator: Bkper.DecimalSeparator)` → `Bkper.DecimalSeparator`
- `getEvents(afterDate?: string, beforeDate?: string, onError?: boolean, resource?: Bkper.Account | Bkper.Group | Bkper.Transaction)` → `Bkper.EventIterator` — Get Book events based on search parameters.
- `getFile(id: string)` → `Bkper.File` — Retrieve a `File` by id
- `getFiles()` → `Bkper.FileIterator` — Gets all files uploaded to this Book.
- `getFractionDigits()` / `setFractionDigits(fractionDigits: number)` → `number`
- `getGroup(idOrName: string)` → `Bkper.Group` — Gets a `Group` object
- `getGroups()` → `Bkper.Group[]`
- `getId()` → `string` — Same as bookId param
- `getLastUpdateMs()` → `number`
- `getLockDate()` / `setLockDate(lockDate: string | null)` → `string (set: string | null)`
- `getName()` / `setName(name: string)` → `string`
- `getOwnerName()` → `string`
- `getPeriodStartMonth()` / `setPeriodStartMonth(month: Bkper.Month)` → `Bkper.Month`
- `getPermission()` → `Bkper.Permission`
- `getSavedQueries()` → `{ id?: string; query?: string; title?: string }[]`
- `getTimeZone()` / `setTimeZone(timeZone: string)` → `string`
- `getTimeZoneOffset()` → `number`
- `getTotalTransactions()` → `number`
- `getTotalTransactionsCurrentMonth()` → `number`
- `getTotalTransactionsCurrentYear()` → `number`
- `getTransaction(id: string)` → `Bkper.Transaction` — Retrieve a `Transaction` by id
- `getTransactions(query?: string)` → `Bkper.TransactionIterator` — Get Book transactions based on a query.
- `json()` → `bkper.Book` — Gets an immutable copy of the JSON payload for this resource.
- `mergeTransactions(transaction1: Bkper.Transaction, transaction2: Bkper.Transaction)` → `Bkper.Transaction` — Merge two `Transactions` into one.
- `newAccount()` → `Bkper.Account` — Instantiate a new `Account`
- `newFile()` → `Bkper.File` — Instantiate a new `File`
- `newGroup()` → `Bkper.Group` — Instantiate a new `Group`
- `newTransaction()` → `Bkper.Transaction` — Instantiate a new `Transaction`
- `parseAmount(value: string)` → `Bkper.Amount` — Parse an amount string according to `DecimalSeparator` and fraction digits of the Book.
- `parseDate(date: string)` → `Date` — Parse a date string according to date pattern and timezone of the Book.
- `parseValue(value: string)` → `Bkper.Amount` — ~~Deprecated~~ Parse a value string according to `DecimalSeparator` and fraction digits of the Book.
- `record(transactions: string | any[] | any[][], timeZone?: string)` → `void` — ~~Deprecated~~ Record `Transactions` on the Book.
- `removeCollaborator(email: string)` → `void` — Removes a collaborator from the Book.
- `round(amount: Bkper.Amount)` → `Bkper.Amount` — Rounds an amount according to the number of fraction digits of the Book
- `update()` → `Bkper.Book` — Perform update Book, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

**createAccount**

The type of account will be determined by the type of others Accounts in same group.

If not specified, the type ASSET (permanent=true/credit=false) will be set.

If all other accounts in same group is in another group, the account will also be added to the other group.

**Deprecated**

**createAccounts**

The first column of the matrix will be used as the `Account` name.

The other columns will be used to find a matching `AccountType`.

Names matching existent accounts will be skipped.

**Deprecated**

**createAccountsDataTable**

Accounts data table builder.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var accountsDataTable = book.createAccountsDataTable().build();

// Or filter by group
var filteredDataTable = book.createAccountsDataTable("Revenue").build();
```

**createBalancesDataTable**

The balances data table builder

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var balancesDataTable = book.createBalancesDataTable("account:'Credit card' after:7/2018 before:8/2018").build();
```

**createGroupsDataTable**

Groups data table builder.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var groupsDataTable = book.createGroupsDataTable().build();
```

**createTransactionsDataTable**

Transactions data table builder.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var transactionsDataTable = book.createTransactionsDataTable("account:'Bank Account' before:1/2019").build();
```

**getBalancesReport**

The balances report

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var balancesReport = book.getBalancesReport("group:'Equity' after:7/2018 before:8/2018");

var accountBalance = balancesReport.getBalancesContainer("Bank Account").getCumulativeBalance();
```

**getTransactions**

The Transactions result as an iterator.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");

var transactions = book.getTransactions("account:CreditCard after:28/01/2013 before:29/01/2013");

while (transactions.hasNext()) {
 var transaction = transactions.next();
 Logger.log(transaction.getDescription());
}
```

**mergeTransactions**

The merged transaction is created synchronously. Cleanup of the two
originals is scheduled asynchronously by the backend.

**newAccount**

The new Account, for chainning.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");

book.newAccount()
 .setName('Some New Account')
 .setType('INCOMING')
 .addGroup('Revenue').addGroup('Salary')
 .setProperties({prop_a: 'A', prop_b: 'B'})
 .create();
```

**newFile**

The new File, for chainning.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");

book.newFile()
 .setBlob(UrlFetchApp.fetch('https://bkper.com/images/index/integrations4.png').getBlob())
 .create();
```

**newGroup**

The new Group, for chainning.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");

book.newGroup()
 .setName('Some New Group')
 .setProperty('key', 'value')
 .create();
```

**newTransaction**

The new Transaction, for chainning.

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgIDggqALDA");

book.newTransaction()
 .setDate('2013-01-25')
 .setDescription("Filling tank of my truck")
 .from('Credit Card')
 .to('Gas')
 .setAmount(126.50)
 .create();

```

**parseDate**

Also parse ISO yyyy-mm-dd format.

**record**

The text is usually amount and description, but it can also can contain an informed Date in full format (dd/mm/yyyy - mm/dd/yyyy).

Example:

```js
book.record("#gas 63.23");
```

**Deprecated**

### BotResponse

**Properties:**

- `payload`: `bkper.BotResponse` — The underlying payload data for this resource

**Methods:**

- `getAgentId()` → `string`
- `getMessage()` → `string`
- `getType()` → `Bkper.BotResponseType`
- `json()` → `bkper.BotResponse` — Gets an immutable copy of the JSON payload for this resource.

### Collection

**Properties:**

- `payload`: `bkper.Collection` — The underlying payload data for this resource

**Methods:**

- `getBooks()` → `Bkper.Book[]`
- `getId()` → `string`
- `getName()` / `setName(name: string)` → `string`
- `json()` → `bkper.Collection` — Gets an immutable copy of the JSON payload for this resource.
- `update()` → `Bkper.Collection` — Performs update Collection, applying pending changes.

### Event

**Properties:**

- `payload`: `bkper.Event` — The underlying payload data for this resource

**Methods:**

- `getBotResponses()` → `Bkper.BotResponse[]`
- `getId()` → `string`
- `json()` → `bkper.Event` — Gets an immutable copy of the JSON payload for this resource.

### EventIterator

**Methods:**

- `getBook()` → `Bkper.Book` — Gets the Book that originated the iterator
- `getContinuationToken()` / `setContinuationToken(continuationToken: string)` → `string` — Gets a token that can be used to resume this iteration at a later time.
- `hasNext()` → `boolean` — Determines whether calling next() will return a transaction.
- `next()` → `Bkper.Event` — Gets the next event in the collection of events.

**continuationToken**

This method is useful if processing an iterator in one execution would exceed the maximum execution time.

Continuation tokens are generally valid short period of time.

### File

**Properties:**

- `payload`: `bkper.File` — The underlying payload data for this resource

**Methods:**

- `create()` → `Bkper.File` — Perform create new File.
- `getBlob()` / `setBlob(blob: GoogleAppsScript.Base.Blob)` → `GoogleAppsScript.Base.Blob` — Gets the Blob from this file
- `getContent()` / `setContent(content: string)` → `string` — Gets the file content Base64 encoded
- `getContentType()` / `setContentType(contentType: string)` → `string` — Gets the File content type
- `getId()` → `string` — Gets the File id
- `getName()` / `setName(name: string)` → `string` — Gets the File name
- `getSize()` → `number` — Gets the file size in bytes
- `getUrl()` → `string` — Gets the file serving url for accessing via browser
- `json()` → `bkper.File` — Gets an immutable copy of the JSON payload for this resource.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### FileIterator

**Methods:**

- `getBook()` → `Bkper.Book` — Gets the Book that originate the iterator
- `getContinuationToken()` / `setContinuationToken(continuationToken: string)` → `string` — Gets a token that can be used to resume this iteration at a later time.
- `hasNext()` → `boolean` — Determines whether calling next() will return a file.
- `next()` → `Bkper.File` — Gets the next file in the collection of files.

### Group

**Properties:**

- `payload`: `bkper.Group` — The underlying payload data for this resource

**Methods:**

- `create()` → `Bkper.Group` — Perform create new group.
- `getAccounts()` → `Bkper.Account[]`
- `getChildren()` → `Bkper.Group[]`
- `getDepth()` → `number`
- `getId()` → `string`
- `getName()` / `setName(name: string)` → `string`
- `getNormalizedName()` → `string`
- `getParent()` / `setParent(group: Bkper.Group | null)` → `Bkper.Group (set: Bkper.Group | null)`
- `getParentGroupsChain()` → `Bkper.Group[]`
- `getRoot()` → `Bkper.Group`
- `getType()` → `Bkper.AccountType`
- `hasAccounts()` → `boolean`
- `hasChildren()` → `boolean` — Tell if this group has any children
- `isCredit()` → `boolean` — Tell if this is a credit (Incoming and Liabities) group
- `isHidden()` → `boolean` — Tell if the Group is hidden on main transactions menu
- `isLocked()` → `boolean`
- `isMixed()` → `boolean` — Tell if this is a mixed (Assets/Liabilities or Incoming/Outgoing) group
- `isPermanent()` → `boolean` — Tell if this is a permanent (Assets and Liabilities) group
- `json()` → `bkper.Group` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Bkper.Group` — Perform delete group.
- `setHidden(hidden: boolean)` → `Bkper.Group` — Hide/Show group on main menu.
- `setLocked(locked: boolean)` → `Bkper.Group` — Sets the locked state of the Group.
- `update()` → `Bkper.Group` — Perform update group, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### GroupsDataTableBuilder

**Methods:**

- `build()` → `any[][]`
- `ids(include: boolean)` → `Bkper.GroupsDataTableBuilder` — Defines whether include group ids.
- `properties(include: boolean)` → `Bkper.GroupsDataTableBuilder` — Defines whether include custom group properties.

### OAuthTokenProvider

**Methods:**

- `getOAuthToken()` → `string` — A valid OAuth2 access token with **email** scope authorized.

### Transaction

**Properties:**

- `payload`: `bkper.Transaction` — The underlying payload data for this resource

**Methods:**

- `addFile(file: any)` → `Bkper.Transaction` — Add a File attachment to the Transaction.
- `addRemoteId(remoteId: string)` → `Bkper.Transaction` — Add a remote id to the Transaction.
- `addUrl(url: string)` → `Bkper.Transaction` — Add a url to the Transaction. Url starts with https://
- `check()` → `Bkper.Transaction` — Perform check transaction.
- `create()` → `Bkper.Transaction` — Perform create new draft transaction.
- `from(account: string | Bkper.Account)` → `Bkper.Transaction` — Set the credit/origin Account of the Transaction. Same as setCreditAccount().
- `getAccountBalance(raw?: boolean)` → `Bkper.Amount` — Gets the balance that the `Account` has at that day, when listing transactions of that Account.
- `getAgentId()` → `string`
- `getAmount()` / `setAmount(amount: string | number | Bkper.Amount)` → `Bkper.Amount (set: string | number | Bkper.Amount)`
- `getCreatedAt()` → `Date`
- `getCreatedAtFormatted()` → `string`
- `getCreditAccount()` / `setCreditAccount(account: string | Bkper.Account)` → `Bkper.Account (set: string | Bkper.Account)`
- `getCreditAccountName()` → `string`
- `getCreditAmount(account: string | Bkper.Account)` → `Bkper.Amount` — Get the absolute amount of this transaction if the given account is at the credit side, else null.
- `getDate()` / `setDate(date: string | Date)` → `string (set: string | Date)`
- `getDateFormatted()` → `string`
- `getDateObject()` → `Date`
- `getDateValue()` → `number`
- `getDebitAccount()` / `setDebitAccount(account: string | Bkper.Account)` → `Bkper.Account (set: string | Bkper.Account)`
- `getDebitAccountName()` → `string`
- `getDebitAmount(account: string | Bkper.Account)` → `Bkper.Amount` — Gets the absolute amount of this transaction if the given account is at the debit side, else null.
- `getDescription()` / `setDescription(description: string)` → `string`
- `getFiles()` → `Bkper.File[]`
- `getId()` → `string`
- `getInformedDate()` → `Date` — ~~Deprecated: Use getDateObject instead.~~
- `getInformedDateText()` → `string` — ~~Deprecated: use getDateFormatted instead~~
- `getInformedDateValue()` → `number` — ~~Deprecated: use getDateValue instead.~~
- `getOtherAccount(account: string | Bkper.Account)` → `Bkper.Account` — Gets the `Account` at the other side of the transaction given the one in one side.
- `getOtherAccountName(account: string | Bkper.Account)` → `string` — The account name at the other side of the transaction given the one in one side.
- `getPostDate()` → `Date` — ~~Deprecated: use getCreatedAt instead.~~
- `getPostDateText()` → `string` — ~~Deprecated: use getCreatedAtFormatted instead.~~
- `getRemoteIds()` → `string[]` — Remote ids are used to avoid duplication.
- `getStatus()` → `Bkper.TransactionStatus` — Gets the status of the transaction.
- `getTags()` → `string[]`
- `getUrls()` / `setUrls(urls: string[])` → `string[]`
- `hasTag(tag: string)` → `boolean` — Check if the transaction has the specified tag.
- `isChecked()` → `boolean`
- `isCredit(account: Bkper.Account)` → `boolean` — Tell if the given account is credit on the transaction
- `isDebit(account: Bkper.Account)` → `boolean` — Tell if the given account is debit on the transaction
- `isLocked()` → `boolean`
- `isPosted()` → `boolean`
- `isTrashed()` → `boolean`
- `json()` → `bkper.Transaction` — Gets an immutable copy of the JSON payload for this resource.
- `post()` → `Bkper.Transaction` — Perform post transaction, changing credit and debit `Account` balances.
- `remove()` → `Bkper.Transaction` — ~~Deprecated~~ Remove the transaction, sending to trash.
- `restore()` → `Bkper.Transaction` — ~~Deprecated~~ Restore the transaction from trash.
- `setChecked(checked: boolean)` → `Bkper.Transaction` — Set the check state of the Transaction.
- `to(account: string | Bkper.Account)` → `Bkper.Transaction` — Set the debit/destination Account of the Transaction. Same as setDebitAccount().
- `trash()` → `Bkper.Transaction` — Perform trash transaction.
- `uncheck()` → `Bkper.Transaction` — Perform uncheck transaction.
- `untrash()` → `Bkper.Transaction` — Perform untrash transaction.
- `update()` → `Bkper.Transaction` — Upddate transaction, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

**addFile**

Files not previously created in the Book will be automatically created when the Transaction is persisted.

**getAccountBalance**

Evolved balances is returned when searching for transactions of a permanent `Account`.

Only comes with the last posted transaction of the day.

**getStatus**

The status is determined by precedence: TRASHED > DRAFT > CHECKED/UNCHECKED

### TransactionIterator

**Methods:**

- `getAccount()` → `Bkper.Account`
- `getBook()` → `Bkper.Book` — Gets the Book that originate the iterator
- `getContinuationToken()` / `setContinuationToken(continuationToken: string)` → `string` — Gets a token that can be used to resume this iteration at a later time.
- `hasNext()` → `boolean` — Determines whether calling next() will return a transaction.
- `next()` → `Bkper.Transaction` — Gets the next transaction in the collection of transactions.

**continuationToken**

This method is useful if processing an iterator in one execution would exceed the maximum execution time.

Continuation tokens are generally valid short period of time.

### TransactionsDataTableBuilder

**Methods:**

- `build()` → `any[][]`
- `formatDates(format: boolean)` → `Bkper.TransactionsDataTableBuilder` — Defines whether the dates should be formatted, based on date patter of the `Book`
- `formatValues(format: boolean)` → `Bkper.TransactionsDataTableBuilder` — Defines whether amounts should be formatted based on `DecimalSeparator` of the `Book`
- `getAccount()` → `Bkper.Account`
- `includeIds(include: boolean)` → `Bkper.TransactionsDataTableBuilder` — Defines whether include transaction ids.
- `includeProperties(include: boolean)` → `Bkper.TransactionsDataTableBuilder` — Defines whether include custom transaction properties.
- `includeUrls(include: boolean)` → `Bkper.TransactionsDataTableBuilder` — Defines whether include attachments and url links.

## Enums

### AccountType

Enum that represents account types.

- `ASSET` — Asset account type
- `INCOMING` — Incoming account type
- `LIABILITY` — Liability account type
- `OUTGOING` — Outgoing account type

### BalanceType

Enum that represents balance types.

- `CUMULATIVE` — Cumulative balance
- `PERIOD` — Period balance
- `TOTAL` — Total balance

### BotResponseType

Enum that represents a Bot Response type

- `ERROR` — Error bot response
- `INFO` — Info bot response
- `WARNING` — Warning bot response

### DecimalSeparator

Decimal separator of numbers on book

- `COMMA` — ,
- `DOT` — .

### Month

Enum that represents a Month.

- `APRIL`
- `AUGUST`
- `DECEMBER`
- `FEBRUARY`
- `JANUARY`
- `JULY`
- `JUNE`
- `MARCH`
- `MAY`
- `NOVEMBER`
- `OCTOBER`
- `SEPTEMBER`

### Periodicity

The Periodicity of the query. It may depend on the level of granularity you write the range params.

- `DAILY` — Example: after:25/01/1983, before:04/03/2013, after:$d-30, before:$d, after:$d-15/$m
- `MONTHLY` — Example: after:jan/2013, before:mar/2013, after:$m-1, before:$m
- `YEARLY` — Example: on:2013, after:2013, $y

### Permission

Enum representing permissions of user in the Book

- `EDITOR` — Manage accounts, transactions, book configuration and sharing
- `NONE` — No permission
- `OWNER` — Manage everything, including book visibility and deletion. Only one owner per book.
- `POSTER` — View transactions, accounts, record and delete drafts
- `RECORDER` — Record and delete drafts only. Useful to collect data only
- `VIEWER` — View transactions, accounts and balances.

### TransactionStatus

Enum that represents a Transaction status.

- `CHECKED` — Transaction is posted and checked
- `DRAFT` — Transaction is not yet posted (draft)
- `TRASHED` — Transaction is in trash
- `UNCHECKED` — Transaction is posted but not checked

---
source: /docs/api/bkper-js.md

# bkper-js

> JavaScript/TypeScript client library for Bkper — classes, interfaces, and type definitions.

bkper-js library is a simple and secure way to access the [Bkper REST API](https://bkper.com/docs/api/rest) on Node.js and modern browsers.

It provides a set of classes and functions to interact with the Bkper API, including authentication, authorization, and data manipulation.

[![npm](https://img.shields.io/npm/v/bkper-js?color=%235889e4)](https://www.npmjs.com/package/bkper-js) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--js-blue?logo=github)](https://github.com/bkper/bkper-js)

### CDN / Browser

The simplest way to use bkper-js in a browser — no build tools, no npm, just a `<script>` tag and a valid access token. Works on **any domain**.

```html
<script src="https://cdn.jsdelivr.net/npm/bkper-js@2/dist/bkper.min.js"></script>
<script>
    const { Bkper } = bkperjs;

    async function listBooks(token) {
        Bkper.setConfig({
            oauthTokenProvider: async () => token,
        });
        const bkper = new Bkper();
        return await bkper.getBooks();
    }

    // Example: prompt for a token and list books
    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('go').addEventListener('click', async () => {
            const token = document.getElementById('token').value;
            const books = await listBooks(token);
            document.getElementById('output').textContent = books.map(b => b.getName()).join('\n');
        });
    });
</script>

<input id="token" placeholder="Paste your access token" />
<button id="go">List Books</button>
<pre id="output"></pre>
```

Get an access token with the [Bkper CLI](https://www.npmjs.com/package/bkper):

```bash
bkper auth login   # one-time setup
bkper auth token   # prints a token (valid for 1 hour)
```

Pin to a specific version by replacing `@2` with e.g. `@2.31.0`.

### Node.js / CLI Scripts

For local scripts and CLI tools, use the [bkper](https://www.npmjs.com/package/bkper) CLI package for authentication:

```typescript
import { Bkper } from 'bkper-js';
import { getOAuthToken } from 'bkper';

// Configure with CLI authentication
Bkper.setConfig({
    oauthTokenProvider: async () => getOAuthToken(),
});

// Create Bkper instance
const bkper = new Bkper();

// Get a book and work with it
const book = await bkper.getBook('your-book-id');
console.log(`Book: ${book.getName()}`);

// List all books
const books = await bkper.getBooks();
console.log(`You have ${books.length} books`);
```

First, login via CLI: `bkper auth login`

### npm + Bundler

If you are using a bundler (Vite, webpack, esbuild, etc.), install from npm and provide an access token the same way as the CDN example:

```typescript
import { Bkper } from 'bkper-js';

Bkper.setConfig({
    oauthTokenProvider: async () => 'your-access-token',
});

const bkper = new Bkper();
const books = await bkper.getBooks();
```

### Web Applications on \*.bkper.app

> **Note:** `@bkper/web-auth` **only works on `*.bkper.app` subdomains**. Its session cookies are scoped to the `.bkper.app` domain and will not work on any other domain. For apps on other domains, use the [CDN / Browser](#cdn--browser) approach with an access token instead.

For apps hosted on `*.bkper.app` subdomains, use the [@bkper/web-auth](https://www.npmjs.com/package/@bkper/web-auth) SDK for built-in OAuth login flow:

```typescript
import { Bkper } from 'bkper-js';
import { BkperAuth } from '@bkper/web-auth';

// Initialize authentication
const auth = new BkperAuth({
    onLoginSuccess: () => initializeApp(),
    onLoginRequired: () => showLoginButton(),
});

// Restore session on app load
await auth.init();

// Configure Bkper with web auth
Bkper.setConfig({
    oauthTokenProvider: async () => auth.getAccessToken(),
});

// Create Bkper instance and use it
const bkper = new Bkper();
const books = await bkper.getBooks();
```

See the [@bkper/web-auth documentation](https://bkper.com/docs/api/bkper-web-auth) for more details.

For Bkper Platform app server routes under `/api/*`, send `Authorization: Bearer ${auth.getAccessToken()}` from the client. The server route can use `new Bkper()` without a token provider because platform outbound auth injects the validated user's token on Bkper API calls.

### API Key (Optional)

API keys are optional and only needed for dedicated quota limits. If not provided, requests use a shared managed quota via the Bkper API proxy.

```typescript
Bkper.setConfig({
    oauthTokenProvider: async () => getOAuthToken(),
    apiKeyProvider: async () => process.env.BKPER_API_KEY, // Optional - for dedicated quota
});
```

## Classes

### Account *(extends ResourceProperty<bkper.Account>)*

This class defines an [Account](https://en.wikipedia.org/wiki/Account_(bookkeeping)) of a `Book`.

It maintains a balance of all amount [credited and debited](http://en.wikipedia.org/wiki/Debits_and_credits) in it by `Transactions`.

An Account can be grouped by `Groups`.

`Account` has no `getBalance()` method. To retrieve account balances, use
`Book.getBalancesReport` and read the resulting `BalancesContainer`.

**Constructor:** `new Account(book: Book, payload?: bkper.Account)`

**Properties:**

- `payload`: `bkper.Account` — The underlying payload data for this resource

**Methods:**

- `addGroup(group: bkper.Group | Group)` → `Account` — Adds a group to the Account.
- `create()` → `Promise<Account>` — Performs create new Account.
- `deleteProperty(key: string)` → `this` — Deletes a custom property.
- `getGroups()` / `setGroups(groups: Group[] | bkper.Group[])` → `Promise<Group[]> (set: Group[] | bkper.Group[])` — Gets the `Groups` of this Account.
- `getId()` → `string | undefined` — Gets the Account internal id.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the Account name.
- `getNormalizedName()` → `string` — Gets the normalized name of this Account without spaces or special characters.
- `getProperties()` / `setProperties(properties: { [key: string]: string })` → `{ [key: string]: string }` — Gets the custom properties stored in this resource.
- `getProperty(keys: string[])` / `setProperty(key: string, value: string | null | undefined)` → `string | undefined (set: string)` — Gets the property value for given keys. First property found will be retrieved.
- `getPropertyKeys()` → `string[]` — Gets the custom properties keys stored in this resource.
- `getType()` / `setType(type: AccountType)` → `AccountType` — Gets the type of this Account.
- `getVisibleProperties()` / `setVisibleProperties(properties: { [key: string]: string })` → `{ [key: string]: string }` — Gets the visible custom properties stored in this resource.
Hidden properties (those ending with "_") are excluded from the result.
- `hasTransactionPosted()` → `boolean | undefined` — Tells if the Account has any transaction already posted.
- `isArchived()` → `boolean | undefined` — Tells if this Account is archived.
- `isBalanceVerified()` → `boolean | undefined` — Tells if the balance of this Account has been verified/audited.
- `isCredit()` → `boolean | undefined` — Tells if the Account has a Credit nature or Debit otherwise.
- `isInGroup(group: string | Group)` → `Promise<boolean>` — Tells if this Account is in the `Group`.
- `isPermanent()` → `boolean | undefined` — Tells if the Account is permanent.
- `json()` → `bkper.Account` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Account>` — Performs delete Account.
- `removeGroup(group: string | Group)` → `Promise<Account>` — Removes a group from the Account.
- `setArchived(archived: boolean)` → `Account` — Sets Account archived/unarchived.
- `setVisibleProperty(key: string, value: string | null | undefined)` → `this` — Sets a custom property in this resource, filtering out hidden properties.
Hidden properties are those whose keys end with an underscore "_".
- `update()` → `Promise<Account>` — Performs update Account, applying pending changes.

**groups**

When groups are already embedded in the account payload (e.g. from
`Bkper.getBook` with includeGroups), resolves them from the
book's cache instead of making API calls.

**hasTransactionPosted**

Accounts with transaction posted, even with zero balance, can only be archived.

**isCredit**

Credit Accounts are just for representation purposes. It increase or decrease the absolute balance. It doesn't affect the overall balance or the behavior of the system.

The absolute balance of credit Accounts increase when it participate as a credit/origin in a transaction. Its usually for Accounts that increase the balance of the assets, like revenue Accounts.

```
        Crediting a credit
  Thus ---------------------> Account increases its absolute balance
        Debiting a debit


        Debiting a credit
  Thus ---------------------> Account decreases its absolute balance
        Crediting a debit
```

As a rule of thumb, and for simple understanding, almost all Accounts are Debit nature (NOT credit), except the ones that "offers" amount for the books, like revenue Accounts.

**isPermanent**

Permanent Accounts are the ones which final balance is relevant and keep its balances over time.

They are also called [Real Accounts](http://en.wikipedia.org/wiki/Account_(Accountancy)#Based_on_periodicity_of_flow)

Usually represents assets or tangibles, capable of being perceived by the senses or the mind, like bank Accounts, money, debts and so on.

### AccountsDataTableBuilder

A AccountsDataTableBuilder is used to setup and build two-dimensional arrays containing accounts.

**Constructor:** `new AccountsDataTableBuilder(accounts: Account[])`

**Methods:**

- `archived(include: boolean)` → `AccountsDataTableBuilder` — Defines whether the archived accounts should be included.
- `build()` → `Promise<any[][]>` — Builds a two-dimensional array containing all accounts.
- `groups(include: boolean)` → `AccountsDataTableBuilder` — Defines whether include account groups.
- `hiddenProperties(include: boolean)` → `AccountsDataTableBuilder` — Defines whether to include hidden properties (keys ending with underscore "_").
- `ids(include: boolean)` → `AccountsDataTableBuilder` — Defines whether include account ids.
- `properties(include: boolean)` → `AccountsDataTableBuilder` — Defines whether include custom account properties.

### Agent

Defines an Agent on Bkper.

An Agent represents an entity (such as an App or Bot) that interacts with Bkper, executing actions on behalf of users.

**Constructor:** `new Agent(payload?: bkper.Agent)`

**Properties:**

- `payload`: `bkper.Agent`

**Methods:**

- `getId()` → `string | undefined` — Gets the Agent universal identifier.
- `getLogoUrl()` → `string | undefined` — Gets the Agent logo URL.
- `getLogoUrlDark()` → `string | undefined` — Gets the Agent logo URL in dark mode.
- `getName()` → `string | undefined` — Gets the Agent name.
- `json()` → `bkper.Agent` — Gets the wrapped plain JSON object.

### Amount

This class defines an Amount for arbitrary-precision decimal arithmetic.

It inherits methods from [big.js](http://mikemcl.github.io/big.js/) library

**Constructor:** `new Amount(n: string | number | Amount)`

The Amount constructor.

**Methods:**

- `abs()` → `Amount` — Returns an absolute Amount.
- `cmp(n: string | number | Amount)` → `-1 | 0 | 1` — Compares this Amount with another value.
- `div(n: string | number | Amount)` → `Amount` — Divides this Amount by another value.
- `eq(n: string | number | Amount)` → `boolean` — Checks if this Amount equals another value.
- `gt(n: string | number | Amount)` → `boolean` — Checks if this Amount is greater than another value.
- `gte(n: string | number | Amount)` → `boolean` — Checks if this Amount is greater than or equal to another value.
- `lt(n: string | number | Amount)` → `boolean` — Checks if this Amount is less than another value.
- `lte(n: string | number | Amount)` → `boolean` — Checks if this Amount is less than or equal to another value.
- `minus(n: string | number | Amount)` → `Amount` — Subtracts another value from this Amount.
- `mod(n: string | number | Amount)` → `Amount` — Calculates the modulo (remainder) of dividing this Amount by another value.
- `plus(n: string | number | Amount)` → `Amount` — Adds another value to this Amount.
- `round(dp?: number)` → `Amount` — Rounds this Amount to a maximum of dp decimal places.
- `times(n: string | number | Amount)` → `Amount` — Multiplies this Amount by another value.
- `toFixed(dp?: number)` → `string` — Returns a string representing the value of this Amount in normal notation to a fixed number of decimal places.
- `toNumber()` → `number` — Returns a primitive number representing the value of this Amount.
- `toString()` → `string` — Returns a string representing the value of this Amount.

**mod**

Similar to % operator

### App *(extends Resource<bkper.App>)*

Defines an App on Bkper.

Apps can be installed on Books by users.

**Constructor:** `new App(payload?: bkper.App, config?: Config)`

**Properties:**

- `payload`: `bkper.App` — The underlying payload data for this resource

**Methods:**

- `create()` → `Promise<App>` — Performs the app creation, applying pending changes.
- `getDescription()` → `string | undefined` — Gets the description of this App.
- `getDevelopers()` / `setDevelopers(developers?: string)` → `string | undefined (set: string)` — Gets the developers (usernames and domain patterns).
- `getEvents()` → `EventType[] | undefined` — Gets the events bound to this App.
- `getFilePatterns()` → `string[] | undefined` — Gets the file patterns the App handles.
- `getId()` → `string | undefined` — Gets the App universal identifier.
- `getLogoUrl()` → `string | undefined` — Gets the logo url of this App.
- `getLogoUrlDark()` → `string | undefined` — Gets the logo url of this App in dark mode.
- `getMenuOpenMode()` / `setMenuOpenMode(menuOpenMode?: MenuOpenMode)` → `MenuOpenMode` — Gets how the app menu opens.
- `getMenuPopupHeight()` → `string | undefined` — ~~Deprecated: Use getMenuOpenMode() to decide how the app should open.~~ Gets the menu popup height of this App.
- `getMenuPopupWidth()` → `string | undefined` — ~~Deprecated: Use getMenuOpenMode() to decide how the app should open.~~ Gets the menu popup width of this App.
- `getMenuText()` → `string | undefined` — Gets the menu text of this App.
- `getMenuUrl()` → `string | undefined` — Gets the menu url of this App.
- `getMenuUrlDev()` → `string | undefined` — Gets the menu development url of this App.
- `getName()` → `string | undefined` — Gets the name of this App.
- `getOwnerLogoUrl()` → `string | undefined` — Gets the logo url of the owner of this App.
- `getOwnerName()` → `string | undefined` — Gets the name of the owner of this App.
- `getOwnerWebsiteUrl()` → `string | undefined` — Gets the website url of the owner of this App.
- `getReadme()` / `setReadme(readme?: string)` → `string | undefined (set: string)` — Gets the readme.md file as text.
- `getRepositoryUrl()` → `string | undefined` — Gets the repository url of this App.
- `getUsers()` / `setUsers(users?: string)` → `string | undefined (set: string)` — Gets the whitelisted users (usernames and domain patterns).
- `getWebsiteUrl()` → `string | undefined` — Gets the website url of this App.
- `hasEvents()` → `boolean` — Checks if this App has events bound to it.
- `isInstallable()` → `boolean` — Tells if this App is installable.
- `isPublished()` → `boolean` — Checks if this App is published.
- `isRepositoryPrivate()` → `boolean | undefined` — Tells if the repository is private.
- `json()` → `bkper.App` — Gets an immutable copy of the JSON payload for this resource.
- `setClientSecret(clientSecret?: string)` → `App` — Sets the client secret.
- `setWebhookUrlDev(webhookUrlDev: string)` → `App` — Sets the webhook url for development.
- `update()` → `Promise<App>` — Performs a full update of the App, applying pending changes.

**create**

The App id MUST be unique. If another app is already existing, an error will be thrown.

### Backlog *(extends Resource<bkper.Backlog>)*

This class defines the Backlog of a `Book`.

A Backlog is a list of pending tasks in a Book

**Constructor:** `new Backlog(payload?: bkper.Backlog, config?: Config)`

**Properties:**

- `payload`: `bkper.Backlog` — The underlying payload data for this resource

**Methods:**

- `getCount()` → `number | undefined` — Returns the number of pending tasks in this Backlog.
- `json()` → `bkper.Backlog` — Gets an immutable copy of the JSON payload for this resource.

### Balance

Class that represents an `Account` or `Group` balance on a window of time (Day / Month / Year).

**Constructor:** `new Balance(container: BalancesContainer, balancePlain: bkper.Balance)`

**Properties:**

- `payload`: `bkper.Balance`

**Methods:**

- `getCumulativeBalance()` → `Amount` — The cumulative balance to the date, based on the credit nature of the container
- `getCumulativeBalanceRaw()` → `Amount` — The raw cumulative balance to the date.
- `getCumulativeCredit()` → `Amount` — The cumulative credit to the date.
- `getCumulativeDebit()` → `Amount` — The cumulative debit to the date.
- `getDate()` → `Date` — Date object constructed based on `Book` time zone offset. Usefull for
- `getDay()` → `number` — The day of the balance. Days starts on 1 to 31.
- `getFuzzyDate()` → `number` — The Fuzzy Date of the balance, based on `Periodicity` of the `BalancesReport` query, composed by Year, Month and Day.
- `getMonth()` → `number` — The month of the balance. Months starts on 1 (January) to 12 (December)
- `getPeriodBalance()` → `Amount` — The balance on the date period, based on credit nature of the container.
- `getPeriodBalanceRaw()` → `Amount` — The raw balance on the date period.
- `getPeriodCredit()` → `Amount` — The credit on the date period.
- `getPeriodDebit()` → `Amount` — The debit on the date period.
- `getYear()` → `number` — The year of the balance

**getDate**

If Month or Day is zero, the date will be constructed with first Month (January) or Day (1) of the next period.

**getDay**

Day can be 0 (zero) in case of Monthly or Early `Periodicity` of the `BalancesReport`

**getFuzzyDate**

The format is **YYYYMMDD**. Very usefull for ordering and indexing

Month and Day can be 0 (zero), depending on the granularity of the `Periodicity`.

*Example:*

**20180125** - 25, January, 2018 - DAILY Periodicity

**20180100** - January, 2018 - MONTHLY Periodicity

**20180000** - 2018 - YEARLY Periodicity

**getMonth**

Month can be 0 (zero) in case of Early `Periodicity` of the `BalancesReport`

### BalancesDataTableBuilder *(implements BalancesDataTableBuilder)*

A BalancesDataTableBuilder is used to setup and build two-dimensional arrays containing balance information.

**Constructor:** `new BalancesDataTableBuilder(book: Book, balancesContainers: BalancesContainer[], periodicity: Periodicity)`

**Methods:**

- `build()` → `any[][]` — Builds an two-dimensional array with the balances.
- `expanded(expanded: number | boolean)` → `BalancesDataTableBuilder` — Defines whether Groups should expand its child accounts.
- `formatDates(format: boolean)` → `BalancesDataTableBuilder` — Defines whether the dates should be ISO formatted YYYY-MM-DD. E.g. 2025-01-01
- `formatValues(format: boolean)` → `BalancesDataTableBuilder` — Defines whether the value should be formatted based on decimal separator of the `Book`.
- `hiddenProperties(include: boolean)` → `BalancesDataTableBuilder` — Defines whether to include hidden properties (keys ending with underscore "_").
- `hideDates(hide: boolean)` → `BalancesDataTableBuilder` — Defines whether the dates should be hidden for **PERIOD** or **CUMULATIVE** `BalanceType`.
- `hideNames(hide: boolean)` → `BalancesDataTableBuilder` — Defines whether the `Accounts` and `Groups` names should be hidden.
- `period(period: boolean)` → `BalancesDataTableBuilder` — Defines whether should force use of period balances for **TOTAL** `BalanceType`.
- `properties(include: boolean)` → `BalancesDataTableBuilder` — Defines whether include custom `Accounts` and `Groups` properties.
- `raw(raw: boolean)` → `BalancesDataTableBuilder` — Defines whether should show raw balances, no matter the credit nature of the Account or Group.
- `transposed(transposed: boolean)` → `BalancesDataTableBuilder` — Defines whether should rows and columns should be transposed.
- `trial(trial: boolean)` → `BalancesDataTableBuilder` — Defines whether should split **TOTAL** `BalanceType` into debit and credit.
- `type(type: BalanceType)` → `BalancesDataTableBuilder` — Fluent method to set the `BalanceType` for the builder.

**expanded**

true to expand itself
-1 to expand all subgroups
-2 to expand all accounts
0 to expand nothing
1 to expand itself and its first level of children
2 to expand itself and its first two levels of children
etc.

**transposed**

For **TOTAL** `BalanceType`, the **transposed** table looks like:

```
  _____________________________
 |  Expenses | Income  |  ...  |
 | -4568.23  | 5678.93 |  ...  |
 |___________|_________|_______|

```
Two rows, and each `Account` or `Group` per column.


For **PERIOD** or **CUMULATIVE** `BalanceType`, the **transposed** table will be a time table, and the format looks like:

```
  _______________________________________________________________
 |            | Expenses   | Income     |     ...    |    ...    |
 | 15/01/2014 | -2345.23   |  3452.93   |     ...    |    ...    |
 | 15/02/2014 | -2345.93   |  3456.46   |     ...    |    ...    |
 | 15/03/2014 | -2456.45   |  3567.87   |     ...    |    ...    |
 |     ...    |     ...    |     ...    |     ...    |    ...    |
 |____________|____________|____________|____________|___________|

```

First column will be each Date, and one column for each `Account` or `Group`.

### BalancesReport

Class representing a Balance Report, generated when calling [Book.getBalanceReport](#book_getbalancesreport)

**Constructor:** `new BalancesReport(book: Book, payload: bkper.Balances)`

**Properties:**

- `payload`: `bkper.Balances`

**Methods:**

- `createDataTable()` → `BalancesDataTableBuilder` — Creates a BalancesDataTableBuilder to generate a two-dimensional array with all `BalancesContainers`.
- `getBalancesContainer(name: string)` → `BalancesContainer` — Gets a specific `BalancesContainer`.
- `getBalancesContainers()` → `BalancesContainer[]` — Gets all `BalancesContainers` of the report.
- `getBook()` → `Book` — Gets the `Book` that generated the report.
- `getPeriodicity()` → `Periodicity` — Gets the `Periodicity` of the query used to generate the report.

### Billing *(extends Resource<bkper.Billing>)*

This class defines the Billing information for a `User`.

The Billing information includes the plan, the admin email, and the billing portal URL.

**Constructor:** `new Billing(json?: bkper.Billing, config?: Config)`

**Properties:**

- `payload`: `bkper.Billing` — The underlying payload data for this resource

**Methods:**

- `getAdminEmail()` → `string | undefined` — Gets the admin email for this User's billing account.
- `getCheckoutUrl(plan: string, successUrl?: string, cancelUrl?: string, cycle?: string)` → `Promise<string | undefined>` — Gets the URL to redirect the User to the billing checkout.
- `getCounts()` → `Promise<bkper.Counts>` — Gets the transaction counts associated to the User's billing account.
- `getDaysLeftInTrial()` → `number | undefined` — Gets the number of days left in User's trial period.
- `getEmail()` → `string | undefined` — Gets the email for the User.
- `getHostedDomain()` → `string | undefined` — Gets the hosted domain for the User.
- `getPlan()` → `string | undefined` — Gets the current plan of the User.
- `getPortalUrl(returnUrl: string)` → `Promise<string | undefined>` — Gets the URL to redirect the User to the billing portal.
- `getTotalTransactionsThisMonth()` → `number | undefined` — Gets the number of total transactions this month for the User's billing account.
- `getTotalTransactionsThisYear()` → `number | undefined` — Gets the number of total transactions this year for the User's billing account.
- `hasStartedTrial()` → `boolean | undefined` — Tells if the User has started the trial period.
- `isEnabled()` → `boolean | undefined` — Tells if billing is enabled for the User.
- `isPlanOverdue()` → `boolean | undefined` — Tells if the User's current plan payment is overdue.
- `json()` → `bkper.Billing` — Gets an immutable copy of the JSON payload for this resource.

### Bkper

This is the main entry point of the [bkper-js](https://www.npmjs.com/package/bkper-js) library.

**Constructor:** `new Bkper(config?: Config)`

Creates a new Bkper instance with the provided configuration.

**Methods:**

- `getApp(id: string)` → `Promise<App>` — Gets the `App` with the specified id.
- `getApps()` → `Promise<App[]>` — Gets all `Apps` available for the user.
- `getBook(id: string, includeAccounts?: boolean, includeGroups?: boolean)` → `Promise<Book>` — Gets the `Book` with the specified bookId from url param.
- `getBooks(query?: string)` → `Promise<Book[]>` — Gets all `Books` the user has access to.
- `getCollections()` → `Promise<Collection[]>` — Gets all `Collections` the user has access to.
- `getConfig()` → `Config` — Gets the current instance configuration.
- `getTemplates()` → `Promise<Template[]>` — Gets all `Templates` available for the user.
- `getUser()` → `Promise<User>` — Gets the current logged `User`.
- `requestBookAccess(bookId: string, permission: Permission, message?: string)` → `Promise<void>` — Requests access to a Book the current user cannot access.
- `static setConfig(config: Config)` → `void` — Sets the global API configuration for all Bkper operations.

**setConfig**

WARNING: This configuration will be shared and should NOT be used on shared environments.

### BkperError *(extends Error)*

Standard error class for Bkper API errors.
Extends Error to enable instanceof checks and standard error handling.

**Constructor:** `new BkperError(code: number, message: string, reason?: string)`

**Properties:**

- `readonly code`: `number` — HTTP status code (e.g., 404, 400, 500)
- `message`: `string`
- `name`: `string`
- `readonly reason?`: `string` — Machine-readable reason (e.g., "notFound", "badRequest")
- `stack?`: `string`
- `static prepareStackTrace?`: `(err: Error, stackTraces: __global.NodeJS.CallSite[]) => any` — Optional override for formatting stack traces
- `static stackTraceLimit`: `number`

**Methods:**

- `static captureStackTrace(targetObject: object, constructorOpt?: Function)` → `void` — Create .stack property on a target object

### Book *(extends ResourceProperty<bkper.Book>)*

A Book represents a [General Ledger](https://en.wikipedia.org/wiki/General_ledger) for a company or business, but can also represent a [Ledger](https://en.wikipedia.org/wiki/Ledger) for a project or department

It contains all `Accounts` where `Transactions` are recorded/posted;

**Constructor:** `new Book(payload?: bkper.Book, config?: Config)`

**Properties:**

- `payload`: `bkper.Book` — The underlying payload data for this resource

**Methods:**

- `audit()` → `void` — Trigger Balances Audit async process.
- `batchCheckTransactions(transactions: Transaction[])` → `Promise<void>` — Batch check `Transactions` on the Book.
- `batchCreateAccounts(accounts: Account[])` → `Promise<Account[]>` — Create `Accounts` on the Book, in batch.
- `batchCreateGroups(groups: Group[])` → `Promise<Group[]>` — Create `Groups` on the Book, in batch.
- `batchCreateTransactions(transactions: Transaction[])` → `Promise<Transaction[]>` — Batch create `Transactions` on the Book.
- `batchDeleteAccounts(accounts: Account[])` → `Promise<Account[]>` — Delete `Accounts` on the Book, in batch.
- `batchPostTransactions(transactions: Transaction[])` → `Promise<void>` — Batch post `Transactions` on the Book.
- `batchReplayEvents(events: Event[], errorOnly?: boolean)` → `Promise<void>` — Replay `Events` on the Book, in batch.
- `batchTrashTransactions(transactions: Transaction[], trashChecked?: boolean)` → `Promise<void>` — Batch trash `Transactions` on the Book.
- `batchUncheckTransactions(transactions: Transaction[])` → `Promise<void>` — Batch uncheck `Transactions` on the Book.
- `batchUntrashTransactions(transactions: Transaction[])` → `Promise<void>` — Batch untrash `Transactions` on the Book.
- `batchUpdateAccounts(accounts: Account[])` → `Promise<Account[]>` — Update `Accounts` on the Book, in batch.
- `batchUpdateTransactions(transactions: Transaction[], updateChecked?: boolean)` → `Promise<Transaction[]>` — Batch update `Transactions` on the Book.
- `copy(name: string, copyTransactions?: boolean, fromDate?: number)` → `Promise<Book>` — Creates a copy of this Book
- `countTransactions(query?: string)` → `Promise<number | undefined>` — Retrieve the number of transactions based on a query.
- `create()` → `Promise<Book>` — Performs create new Book.
- `createAccountsDataTable(accounts?: Account[])` → `Promise<AccountsDataTableBuilder>` — Create a `AccountsDataTableBuilder`, to build two dimensional Array representations of `Account` dataset.
- `createGroupsDataTable(groups?: Group[])` → `Promise<GroupsDataTableBuilder>` — Create a `GroupsDataTableBuilder`, to build two dimensional Array representations of `Group` dataset.
- `createIntegration(integration: bkper.Integration | Integration)` → `Promise<Integration>` — Creates a new `Integration` in the Book.
- `createTransactionsDataTable(transactions: Transaction[], account?: Account)` → `TransactionsDataTableBuilder` — Create a `TransactionsDataTableBuilder`, to build two dimensional Array representations of `Transaction` dataset.
- `formatDate(date: Date, timeZone?: string)` → `string` — Formats a date according to date pattern of the Book.
- `formatValue(value: number | Amount | null | undefined)` → `string` — Formats a value according to `DecimalSeparator` and fraction digits of the Book.
- `getAccount(idOrName?: string)` → `Promise<Account | undefined>` — Gets an `Account` object by id or name.
- `getAccounts()` → `Promise<Account[]>` — Gets all `Accounts` of this Book with full account-group relationships.
- `getApps()` → `Promise<App[]>` — Retrieve installed `Apps` for this Book.
- `getAutoPost()` / `setAutoPost(autoPost: boolean)` → `boolean | undefined (set: boolean)` — Gets the auto post status of the Book.
- `getBacklog()` → `Promise<Backlog>` — Gets the Backlog of this Book.
- `getBalancesReport(query: string)` → `Promise<BalancesReport>` — Create a `BalancesReport` based on query.
- `getClosingDate()` / `setClosingDate(closingDate: string | null)` → `string | undefined (set: string | null)` — Gets the closing date of the Book in ISO format yyyy-MM-dd.
- `getCollaborators()` → `Promise<Collaborator[]>` — Gets all collaborators of this Book.
- `getCollection()` → `Collection | undefined` — Gets the collection of this Book, if any.
- `getDatePattern()` / `setDatePattern(datePattern: string)` → `string` — Gets the date pattern of the Book.
- `getDecimalPlaces()` → `number | undefined` — Gets the number of decimal places supported by this Book.
- `getDecimalSeparator()` / `setDecimalSeparator(decimalSeparator: DecimalSeparator)` → `DecimalSeparator` — Gets the decimal separator of the Book.
- `getFile(id: string)` → `Promise<File | undefined>` — Retrieve a file by id.
- `getFractionDigits()` / `setFractionDigits(fractionDigits: number)` → `number | undefined (set: number)` — Gets the number of fraction digits supported by this Book.
- `getGroup(idOrName?: string)` → `Promise<Group | undefined>` — Gets a `Group` object by id or name.
- `getGroups()` → `Promise<Group[]>` — Gets all `Groups` of this Book with complete parent/child hierarchy.
- `getId()` → `string` — Gets the unique identifier of this Book.
- `getIntegrations()` → `Promise<Integration[]>` — Gets the existing `Integrations` in the Book.
- `getLastUpdateMs()` → `number | undefined` — Gets the last update date of the book, in milliseconds.
- `getLockDate()` / `setLockDate(lockDate: string | null)` → `string | undefined (set: string | null)` — Gets the lock date of the Book in ISO format yyyy-MM-dd.
- `getLogoUrl()` → `string | undefined` — Gets the logo URL of the Book owner's custom domain, if any.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the name of this Book.
- `getOwnerName()` → `string | undefined` — Gets the name of the owner of the Book.
- `getPageSize()` / `setPageSize(pageSize: number)` → `number | undefined (set: number)` — Gets the transactions pagination page size.
- `getPeriod()` / `setPeriod(period: Period)` → `Period` — Gets the period slice for balances visualization.
- `getPeriodStartMonth()` / `setPeriodStartMonth(month: Month)` → `Month` — Gets the start month when YEAR period is set.
- `getPermission()` → `Permission` — Gets the permission for the current user in this Book.
- `getSavedQueries()` → `Promise<Query[]>` — Gets the saved queries from this book.
- `getTimeZone()` / `setTimeZone(timeZone: string)` → `string | undefined (set: string)` — Gets the time zone of the Book.
- `getTimeZoneOffset()` → `number | undefined` — Gets the time zone offset of the book, in minutes.
- `getTotalTransactions()` → `number` — Gets the total number of posted transactions.
- `getTotalTransactionsCurrentMonth()` → `number` — Gets the total number of posted transactions on current month.
- `getTotalTransactionsCurrentYear()` → `number` — Gets the total number of posted transactions on current year.
- `getTransaction(id: string)` → `Promise<Transaction | undefined>` — Retrieve a transaction by id.
- `getVisibility()` / `setVisibility(visibility: Visibility)` → `Visibility` — Gets the visibility of the book.
- `json()` → `bkper.Book` — Gets an immutable copy of the JSON payload for this resource.
- `listEvents(options: ListEventsOptions)` → `Promise<EventList>` — Lists events in the Book based on the provided options.
- `listFiles(limit?: number, cursor?: string)` → `Promise<FileList>` — Lists files in the Book, for pagination.
- `listTransactions(query?: string, limit?: number, cursor?: string)` → `Promise<TransactionList>` — Lists transactions in the Book based on the provided query, limit, and cursor, for pagination.
- `mergeTransactions(transaction1: string | bkper.Transaction | Transaction, transaction2: string | bkper.Transaction | Transaction)` → `Promise<Transaction>` — Merge two `Transactions` into a single new canonical transaction.
- `parseDate(date: string)` → `Date` — Parse a date string according to date pattern and timezone of the Book. Also parse ISO yyyy-mm-dd format.
- `parseValue(value: string)` → `Amount | undefined` — Parse a value string according to `DecimalSeparator` and fraction digits of the Book.
- `remove()` → `Promise<Book>` — Warning!
- `resolveAccessRequest(accessRequestId: string)` → `Promise<Collaborator>` — Resolves an access request for this Book.
- `round(value: number | Amount)` → `Amount` — Rounds a value according to the number of fraction digits of the Book.
- `update()` → `Promise<Book>` — Perform update Book, applying pending changes.
- `updateIntegration(integration: bkper.Integration)` → `Promise<Integration>` — Updates an existing `Integration` in the Book.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

**getAccount**

Results are cached to avoid repeated server calls. Account-group relationships
are included if the full chart was loaded via getAccounts() or when the Book
was loaded with includeAccounts=true.

```typescript
// Get individual account (basic data, cached)
const account = await book.getAccount('Bank Account');

// For account-group relationships, use one of these approaches:
// Option 1: Load book with full data upfront
const bookWithAccounts = await Bkper.getBook(bookId, true);
const accountWithGroups = await bookWithAccounts.getAccount('Bank Account');

// Option 2: Load full chart when needed
await book.getAccounts();
const accountWithGroups2 = await book.getAccount('Bank Account');
```

**getAccounts**

Results are cached for performance. Groups are automatically loaded first
to ensure proper linking. Consider using Bkper.getBook(id, true) for
upfront loading when you know you'll need all accounts.

```typescript
// Load all accounts with complete relationships
const accounts = await book.getAccounts();

// Alternative: Load book with accounts upfront (more efficient)
const bookWithAccounts = await Bkper.getBook(bookId, true);
const accounts2 = await bookWithAccounts.getAccounts(); // Already cached
```

**getBalancesReport**

The balances report

Example:

```js
var book = BkperApp.getBook("agtzfmJrcGVyLWhyZHITCxIGTGVkZ2VyGICAgPXjx7oKDA");

var balancesReport = book.getBalancesReport("group:'Equity' after:7/2018 before:8/2018");

var accountBalance = balancesReport.getBalancesContainer("Bank Account").getCumulativeBalance();
```

**getGroup**

Results are cached to avoid repeated server calls. Parent/child relationships
are included if all groups were loaded via getGroups() or when the Book was
loaded with includeGroups=true.

```typescript
// Get individual group (basic data, cached)
const group = await book.getGroup('Assets');

// For parent/child relationships, use one of these approaches:
// Option 1: Load book with full hierarchy upfront
const bookWithGroups = await Bkper.getBook(bookId, false, true);
const groupWithTree = await bookWithGroups.getGroup('Assets');

// Option 2: Load full hierarchy when needed
await book.getGroups();
const groupWithTree2 = await book.getGroup('Assets');
console.log(groupWithTree2.getParent(), groupWithTree2.getChildren());
```

**getGroups**

Results are cached for performance. Group tree relationships are built
during loading. Consider using Bkper.getBook(id, false, true) for
upfront loading when you know you'll need all groups.

```typescript
// Load all groups with complete hierarchy
const groups = await book.getGroups();

// Alternative: Load book with groups upfront (more efficient)
const bookWithGroups = await Bkper.getBook(bookId, false, true);
const groups2 = await bookWithGroups.getGroups(); // Already cached
```

**mergeTransactions**

The merged transaction is created synchronously. Cleanup of the two
originals is scheduled asynchronously by the backend.

**remove**

Deletes this Book and all its data (transactions, accounts, groups). Book owner only.

**resolveAccessRequest**

Resolving the request does not grant access. Call Collaborator.create
on the returned Collaborator to grant access to the Book.

### BooksDataTableBuilder

A BooksDataTableBuilder is used to setup and build two-dimensional arrays containing books.

**Constructor:** `new BooksDataTableBuilder(books: Book[])`

**Methods:**

- `build()` → `any[][]` — Builds a two-dimensional array containing all Books.
- `hiddenProperties(include: boolean)` → `BooksDataTableBuilder` — Defines whether to include hidden properties (keys ending with underscore "_").
- `ids(include: boolean)` → `BooksDataTableBuilder` — Defines whether to include book ids.
- `properties(include: boolean)` → `BooksDataTableBuilder` — Defines whether to include custom book properties.

### BotResponse

This class defines a Bot Response associated to an `Event`.

**Constructor:** `new BotResponse(event: Event, payload?: bkper.BotResponse)`

**Properties:**

- `payload`: `bkper.BotResponse`

**Methods:**

- `getAgentId()` → `string | undefined` — Gets the agent id of this Bot Response.
- `getCreatedAt()` → `Date | undefined` — Gets the date this Bot Response was created.
- `getEvent()` → `Event` — Gets the Event this Bot Response is associated to.
- `getMessage()` → `string | undefined` — Gets the message of this Bot Response.
- `getType()` → `BotResponseType | undefined` — Gets the type of this Bot Response.
- `remove()` → `Promise<BotResponse>` — Delete this Bot Response.
- `replay()` → `Promise<BotResponse>` — Replay this Bot Response.

### Collaborator *(extends Resource<bkper.Collaborator>)*

This class defines a Collaborator of a `Book`.

A Collaborator represents a user that has been granted access to a Book with specific permissions.

**Constructor:** `new Collaborator(book: Book, payload?: bkper.Collaborator)`

**Properties:**

- `payload`: `bkper.Collaborator` — The underlying payload data for this resource

**Methods:**

- `create(message?: string)` → `Promise<Collaborator>` — Performs create new Collaborator.
- `getAvatarUrl()` → `string | undefined` — Gets the public avatar url of the Collaborator.
- `getEmail()` / `setEmail(email: string)` → `string | undefined (set: string)` — Gets the Collaborator email address.
- `getId()` → `string | undefined` — Gets the Collaborator internal id.
- `getPermission()` / `setPermission(permission: Permission)` → `Permission | undefined (set: Permission)` — Gets the permission level of the Collaborator.
- `json()` → `bkper.Collaborator` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Collaborator>` — Performs remove Collaborator.
- `update()` → `Promise<Collaborator>` — Performs update Collaborator.

### Collection *(extends Resource<bkper.Collection>)*

This class defines a Collection of `Books`.

**Constructor:** `new Collection(payload?: bkper.Collection, config?: Config)`

**Properties:**

- `payload`: `bkper.Collection` — The underlying payload data for this resource

**Methods:**

- `addBooks(books: Book[])` → `Promise<Book[]>` — Adds Books to this Collection.
- `create()` → `Promise<Collection>` — Performs create new Collection.
- `getBooks()` → `Book[]` — Gets all Books of this collection.
- `getId()` → `string | undefined` — Gets the unique identifier of this Collection.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the name of this Collection.
- `getOwnerUsername()` → `string | undefined` — Gets the username of the owner of this Collection
- `getPermission()` → `Permission | undefined` — Gets the user permission for this Collection
- `getUpdatedAt()` → `string | undefined` — Gets the last update date of this Collection
- `json()` → `bkper.Collection` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Book[]>` — Performs delete Collection.
- `removeBooks(books: Book[])` → `Promise<Book[]>` — Removes Books from this Collection.
- `update()` → `Promise<Collection>` — Performs update Collection, applying pending changes.

### Connection *(extends ResourceProperty<bkper.Connection>)*

This class defines a Connection from an `User` to an external service.

**Constructor:** `new Connection(payload?: bkper.Connection, config?: Config)`

**Properties:**

- `payload`: `bkper.Connection` — The underlying payload data for this resource

**Methods:**

- `clearTokenProperties()` → `void` — Cleans any token property stored in the Connection.
- `create()` → `Promise<Connection>` — Performs create new Connection.
- `getAgentId()` / `setAgentId(agentId: string)` → `string | undefined (set: string)` — Gets the agentId of the Connection.
- `getDateAddedMs()` → `string | undefined` — Gets the date when the Connection was added.
- `getEmail()` → `string | undefined` — Gets the email of the owner of the Connection.
- `getId()` → `string | undefined` — Gets the id of the Connection.
- `getIntegrations()` → `Promise<Integration[]>` — Gets the existing `Integrations` on the Connection.
- `getLogo()` → `string | undefined` — Gets the logo of the Connection.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the name of the Connection.
- `getType()` / `setType(type: "APP" | "BANK")` → `"APP" | "BANK" | undefined (set: "APP" | "BANK")` — Gets the type of the Connection.
- `getUUID()` / `setUUID(uuid: string)` → `string | undefined (set: string)` — Gets the universal unique identifier of this Connection.
- `json()` → `bkper.Connection` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Connection>` — Performs remove Connection.
- `update()` → `Promise<Connection>` — Performs update Connection.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### Event

This class defines an Event from a `Book`.

An event is an object that represents an action (such as posting or deleting a `Transaction`) made by an actor (such as a user or a [Bot](https://bkper.com/apps) acting on behalf of a user).

**Constructor:** `new Event(book: Book, payload?: bkper.Event)`

**Properties:**

- `payload`: `bkper.Event`

**Methods:**

- `getAgent()` → `Agent | undefined` — Gets the Agent who performed the Event.
- `getBook()` → `Book` — Gets the book in which the Event was created.
- `getBotResponses()` → `BotResponse[]` — Gets the Bot Responses associated to this Event.
- `getCreatedAt()` → `Date | undefined` — Gets the date the Event was created.
- `getId()` → `string | undefined` — Gets the id of the Event.
- `getType()` → `EventType | undefined` — Gets the type of the Event.
- `getUser()` → `User | undefined` — Gets the user who performed the Event.
- `hasErrorResponse()` → `boolean` — Checks if this Event has at least one Bot Response of type ERROR.
- `json()` → `bkper.Event` — Gets an immutable copy of the JSON payload for this Event.

### EventList

A list associated with an event query.

**Constructor:** `new EventList(book: Book, payload: bkper.EventList)`

**Methods:**

- `getCursor()` → `string | undefined` — Gets the cursor associated with the query for pagination.
- `getFirst()` → `Event | undefined` — Gets the first Event in the list.
- `getItems()` → `Event[]` — Get the events in the list.
- `size()` → `number` — Get the total number of events in the list.

### File *(extends ResourceProperty<bkper.File>)*

This class defines a File uploaded to a `Book`.

A File can be attached to a `Transaction` or used to import data.

**Constructor:** `new File(book: Book, payload?: bkper.File)`

**Properties:**

- `payload`: `bkper.File` — The underlying payload data for this resource

**Methods:**

- `create()` → `Promise<File>` — Perform create new File.
- `getBook()` → `Book` — Gets the Book this File belongs to.
- `getContent()` / `setContent(content: string)` → `Promise<string | undefined> (set: string)` — Gets the file content Base64 encoded.
- `getContentType()` / `setContentType(contentType: string)` → `string | undefined (set: string)` — Gets the File content type.
- `getCreatedAt()` → `Date | undefined` — Gets the date the File was created.
- `getId()` → `string | undefined` — Gets the File id.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the File name.
- `getSize()` → `number | undefined` — Gets the file size in bytes.
- `getUrl()` → `string | undefined` — Gets the file serving url for accessing via browser.
- `json()` → `bkper.File` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<File>` — Perform delete File.
- `update()` → `Promise<File>` — Perform update File, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### FileList

A list associated with a file query.

**Constructor:** `new FileList(book: Book, payload: bkper.FileList)`

**Methods:**

- `getCursor()` → `string | undefined` — Gets the cursor associated with the query for pagination.
- `getFirst()` → `File | undefined` — Gets the first File in the list.
- `getItems()` → `File[]` — Gets the files in the list.
- `size()` → `number` — Gets the total number of files in the list.

### Group *(extends ResourceProperty<bkper.Group>)*

This class defines a Group of `Accounts`.

Accounts can be grouped by different meaning, like Expenses, Revenue, Assets, Liabilities and so on

Its useful to keep organized and for high level analysis.

**Constructor:** `new Group(book: Book, payload?: bkper.Group)`

**Properties:**

- `payload`: `bkper.Group` — The underlying payload data for this resource

**Methods:**

- `create()` → `Promise<Group>` — Performs create new group.
- `getAccounts()` → `Promise<Account[]>` — Gets all Accounts of this group.
- `getChildren()` → `Group[]` — Gets the children of the Group.
- `getDepth()` → `number` — Gets the depth of the Group in the hierarchy.
- `getDescendants()` → `Set<Group>` — Gets all descendant Groups of the current Group.
- `getDescendantTreeIds()` → `Set<string>` — Gets the IDs of all descendant Groups in a tree structure.
- `getId()` → `string | undefined` — Gets the id of this Group.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the name of this Group.
- `getNormalizedName()` → `string` — Gets the normalized name of this group without spaces and special characters.
- `getParent()` / `setParent(group: Group | null | undefined)` → `Group | undefined (set: Group | null | undefined)` — Gets the parent Group.
- `getRoot()` → `Group` — Gets the root Group of the current Group.
- `getRootName()` → `string` — Gets the name of the root Group.
- `getType()` → `AccountType` — Gets the type of the accounts of this group.
- `hasAccounts()` → `boolean | undefined` — Tells if this group has any account in it.
- `hasChildren()` → `boolean` — Checks if the Group has any children.
- `hasParent()` → `boolean` — Checks if the Group has a parent.
- `isBalanceVerified()` → `Promise<boolean | undefined>` — Tells if the balance of this Group has been verified/audited.
- `isCredit()` → `boolean | undefined` — Tells if this is a credit (Incoming and Liabilities) group.
- `isHidden()` → `boolean | undefined` — Tells if the Group is hidden on main transactions menu.
- `isLeaf()` → `boolean` — Checks if the Group is a leaf node (i.e., has no children).
- `isLocked()` → `boolean` — Tells if the Group is locked by the Book owner.
- `isMixed()` → `boolean | undefined` — Tells if this is a mixed (Assets/Liabilities or Incoming/Outgoing) group.
- `isPermanent()` → `boolean | undefined` — Tells if the Group is permanent.
- `isRoot()` → `boolean` — Checks if the Group is a root node (i.e., has no parent).
- `json()` → `bkper.Group` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Group>` — Performs delete group.
- `setHidden(hidden: boolean)` → `Group` — Hide/Show group on main menu.
- `setLocked(locked: boolean)` → `Group` — Sets the locked state of the Group.
- `update()` → `Promise<Group>` — Performs update group, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### GroupsDataTableBuilder

A GroupsDataTableBuilder is used to setup and build two-dimensional arrays containing groups.

**Constructor:** `new GroupsDataTableBuilder(groups: Group[])`

**Methods:**

- `build()` → `any[][]` — Builds a two-dimensional array containing all Groups.
- `hiddenProperties(include: boolean)` → `GroupsDataTableBuilder` — Defines whether to include hidden properties (keys ending with underscore "_").
- `ids(include: boolean)` → `GroupsDataTableBuilder` — Defines whether include group ids.
- `properties(include: boolean)` → `GroupsDataTableBuilder` — Defines whether include custom group properties.
- `tree(enable: boolean)` → `GroupsDataTableBuilder` — Defines whether to render groups as an indented tree instead of flat rows with a Parent column.

### Integration *(extends ResourceProperty<bkper.Integration>)*

This class defines a Integration from an `User` to an external service.

**Constructor:** `new Integration(payload?: bkper.Integration, config?: Config)`

**Properties:**

- `payload`: `bkper.Integration` — The underlying payload data for this resource

**Methods:**

- `getAddedBy()` → `string | undefined` — Gets the name of the user who added the Integration.
- `getAgentId()` → `string | undefined` — Gets the agent id of the Integration.
- `getBookId()` → `string | undefined` — Gets the `Book` id of the Integration.
- `getDateAddedMs()` → `string | undefined` — Gets the date when the Integration was added.
- `getId()` → `string | undefined` — Gets the id of the Integration.
- `getLastUpdateMs()` → `string | undefined` — Gets the date when the Integration was last updated.
- `getLogo()` → `string | undefined` — ~~Deprecated: Use getLogoUrl instead.~~ Gets the logo of the Integration.
- `getLogoUrl()` → `string | undefined` — Gets the logo url of this Integration.
- `getLogoUrlDark()` → `string | undefined` — Gets the logo url of this Integration in dark mode.
- `getName()` / `setName(name: string)` → `string | undefined (set: string)` — Gets the name of the Integration.
- `json()` → `bkper.Integration` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Integration>` — Performs remove Integration.
- `update()` → `Promise<Integration>` — Performs update Integration.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

### Query *(extends Resource<bkper.Query>)*

Defines a saved Query in a `Book`.

Queries can be saved on Books by users.

**Constructor:** `new Query(book: Book, payload?: bkper.Query)`

**Properties:**

- `payload`: `bkper.Query` — The underlying payload data for this resource

**Methods:**

- `create()` → `Promise<Query>` — Perform create new Query.
- `getId()` → `string | undefined` — Gets the Query universal identifier.
- `getQuery()` / `setQuery(query: string)` → `string | undefined (set: string)` — Gets the query string to be executed.
- `getTitle()` / `setTitle(title: string)` → `string | undefined (set: string)` — Gets the title of this saved Query.
- `json()` → `bkper.Query` — Gets an immutable copy of the JSON payload for this resource.
- `remove()` → `Promise<Query>` — Perform delete Query.
- `update()` → `Promise<Query>` — Perform update Query, applying pending changes.

### Template *(extends Resource<bkper.Template>)*

This class defines a Template.

A Template is a pre-configured setup for `Books` and associated Google Sheets that provides users with a starting point for specific accounting or financial management needs.

**Constructor:** `new Template(json?: bkper.Template, config?: Config)`

**Properties:**

- `payload`: `bkper.Template` — The underlying payload data for this resource

**Methods:**

- `getBookId()` → `string | undefined` — Gets the bookId of the `Book` associated with the Template.
- `getBookLink()` → `string | undefined` — Gets the link of the `Book` associated with the Template.
- `getCategory()` → `string | undefined` — Gets the category of the Template.
- `getDescription()` → `string | undefined` — Gets the description of the Template.
- `getImageUrl()` → `string | undefined` — Gets the url of the image of the Template.
- `getName()` → `string | undefined` — Gets the name of the Template.
- `getSheetsLink()` → `string | undefined` — Gets the link of the Google Sheets spreadsheet associated with the Template.
- `getTimesUsed()` → `number` — Gets the times the Template has been used.
- `json()` → `bkper.Template` — Gets an immutable copy of the JSON payload for this resource.

### Transaction *(extends ResourceProperty<bkper.Transaction>)*

This class defines a Transaction between [credit and debit](http://en.wikipedia.org/wiki/Debits_and_credits) `Accounts`.

A Transaction is the main entity on the [Double Entry](http://en.wikipedia.org/wiki/Double-entry_bookkeeping_system) [Bookkeeping](http://en.wikipedia.org/wiki/Bookkeeping) system.

**Constructor:** `new Transaction(book: Book, payload?: bkper.Transaction)`

**Properties:**

- `payload`: `bkper.Transaction` — The underlying payload data for this resource

**Methods:**

- `addFile(file: File)` → `Transaction` — Adds a file attachment to the Transaction.
- `addRemoteId(remoteId: string)` → `Transaction` — Add a remote id to the Transaction.
- `addUrl(url: string)` → `Transaction` — Add a url to the Transaction. Url starts with https://
- `check()` → `Promise<Transaction>` — Perform check transaction.
- `create()` → `Promise<Transaction>` — Perform create new draft transaction.
- `from(account: bkper.Account | Account | null | undefined)` → `Transaction` — Sets the credit/origin `Account` of this Transaction. Same as setCreditAccount()
- `getAccountBalance(raw?: boolean)` → `Promise<Amount | undefined>` — Gets the balance that the `Account` has at that day, when listing transactions of that Account.
- `getAgentId()` → `string | undefined` — Gets the unique identifier of the agent that created this transaction.
- `getAgentLogoUrl()` → `string | undefined` — Gets the logo URL of the agent that created this transaction.
- `getAgentLogoUrlDark()` → `string | undefined` — Gets the dark mode logo URL of the agent that created this transaction.
- `getAgentName()` → `string | undefined` — Gets the name of the agent that created this transaction.
- `getAmount()` / `setAmount(amount: string | number | Amount)` → `Amount | undefined (set: string | number | Amount)` — Gets the amount of this Transaction.
- `getAmountFormatted()` → `string | undefined` — Gets the formatted amount of this Transaction according to the Book format.
- `getBook()` → `Book` — Gets the book associated with this transaction.
- `getCreatedAt()` → `Date` — Gets the date when the transaction was created.
- `getCreatedAtFormatted()` → `string` — Gets the formatted creation date of the transaction.
- `getCreatedBy()` → `string | undefined` — Gets the username of the user who created the transaction.
- `getCreditAccount()` / `setCreditAccount(account: bkper.Account | Account | null | undefined)` → `Promise<Account | undefined> (set: bkper.Account | Account | null | undefined)` — Gets the credit account associated with this Transaction. Same as origin account
- `getCreditAccountName()` → `Promise<string | undefined>` — Gets the name of this Transaction's credit account.
- `getCreditAmount(account: string | Account)` → `Promise<Amount | undefined>` — Get the absolute amount of this Transaction if the given account is at the credit side.
- `getDate()` / `setDate(date: string | Date)` → `string | undefined (set: string | Date)` — Gets the transaction date in ISO format.
- `getDateFormatted()` → `string | undefined` — Gets the transaction date formatted according to the book's date pattern.
- `getDateObject()` → `Date` — Gets the transaction date as a Date object in the book's timezone.
- `getDateValue()` → `number | undefined` — Gets the transaction date as a numeric value.
- `getDebitAccount()` / `setDebitAccount(account: bkper.Account | Account | null | undefined)` → `Promise<Account | undefined> (set: bkper.Account | Account | null | undefined)` — Gets the debit account associated with this Transaction. Same as destination account
- `getDebitAccountName()` → `Promise<string | undefined>` — Gets the name of this Transaction's debit account.
- `getDebitAmount(account: string | Account)` → `Promise<Amount | undefined>` — Gets the absolute amount of this Transaction if the given account is at the debit side.
- `getDescription()` / `setDescription(description: string)` → `string` — Gets the description of this Transaction.
- `getFiles()` → `File[]` — Gets all files attached to the transaction.
- `getId()` → `string | undefined` — Gets the unique identifier of the transaction.
- `getOtherAccount(account: string | Account)` → `Promise<Account | undefined>` — Gets the `Account` at the other side of the transaction given the one in one side.
- `getOtherAccountName(account: string | Account)` → `Promise<string | undefined>` — The Account name at the other side of this Transaction given the one in one side.
- `getRemoteIds()` → `string[]` — Gets the remote IDs associated with this transaction. Remote ids are used to avoid duplication.
- `getStatus()` → `TransactionStatus` — Gets the status of the transaction.
- `getTags()` → `string[]` — Gets all hashtags used in the transaction.
- `getUpdatedAt()` → `Date` — Gets the date when the transaction was last updated.
- `getUpdatedAtFormatted()` → `string` — Gets the formatted last update date of the transaction.
- `getUrls()` / `setUrls(urls: string[])` → `string[]` — Gets all URLs associated with the transaction.
- `hasTag(tag: string)` → `boolean` — Check if the transaction has the specified tag.
- `isChecked()` → `boolean | undefined` — Checks if the transaction is marked as checked.
- `isCredit(account?: Account)` → `Promise<boolean>` — Tell if the given account is credit on this Transaction
- `isDebit(account?: Account)` → `Promise<boolean>` — Tell if the given account is debit on the Transaction
- `isLocked()` → `boolean` — Checks if the transaction is locked by the book's lock or closing date.
- `isPosted()` → `boolean | undefined` — Checks if the transaction has been posted to the accounts.
- `isTrashed()` → `boolean | undefined` — Checks if the transaction is in the trash.
- `json()` → `bkper.Transaction` — Gets an immutable copy of the JSON payload for this resource.
- `post()` → `Promise<Transaction>` — Perform post transaction, changing credit and debit `Account` balances.
- `removeFile(file: File)` → `Transaction` — Removes a file attachment from the Transaction.
- `setChecked(checked: boolean)` → `Transaction` — Set the check state of the Transaction.
- `to(account: bkper.Account | Account | null | undefined)` → `Transaction` — Sets the debit/destination `Account` of this Transaction. Same as setDebitAccount()
- `trash()` → `Promise<Transaction>` — Trash the transaction.
- `uncheck()` → `Promise<Transaction>` — Perform uncheck transaction.
- `untrash()` → `Promise<Transaction>` — Untrash the transaction.
- `update()` → `Promise<Transaction>` — Update transaction, applying pending changes.

*Standard property methods (deleteProperty, getProperties, getProperty, getPropertyKeys, getVisibleProperties, setProperties, setProperty, setVisibleProperties, setVisibleProperty) — see Account.*

**addFile**

Files not previously created in the Book will be automatically created when the transaction is persisted.

**getAccountBalance**

Evolved balances is returned when searching for transactions of a permanent `Account`.

Only comes with the last posted transaction of the day.

### TransactionList

A list associated with a transaction query.

**Constructor:** `new TransactionList(book: Book, payload: bkper.TransactionList)`

**Methods:**

- `getAccount()` → `Promise<Account | undefined>` — Retrieves the account associated with the query, when filtering by account.
- `getCursor()` → `string | undefined` — Gets the cursor associated with the query for pagination.
- `getFirst()` → `Transaction | undefined` — Gets the first Transaction in the list.
- `getItems()` → `Transaction[]` — Gets the transactions in the list.
- `size()` → `number` — Gets the total number of transactions in the list.

### TransactionsDataTableBuilder

A TransactionsDataTableBuilder is used to setup and build two-dimensional arrays containing transactions.

**Constructor:** `new TransactionsDataTableBuilder(book: Book, transactions: Transaction[], account?: Account)`

**Methods:**

- `build()` → `Promise<any[][]>` — Builds a two-dimensional array containing all transactions.
- `formatDates(format: boolean)` → `TransactionsDataTableBuilder` — Defines whether the dates should be formatted, based on date pattern of the `Book`.
- `formatValues(format: boolean)` → `TransactionsDataTableBuilder` — Defines whether amounts should be formatted based on `DecimalSeparator` of the `Book`.
- `getAccount()` → `Account | undefined` — Gets the account used to filter transactions, when applicable.
- `hiddenProperties(include: boolean)` → `TransactionsDataTableBuilder` — Defines whether to include hidden properties (keys ending with underscore "_").
- `ids(include: boolean)` → `TransactionsDataTableBuilder` — Defines whether to include transaction ids and remote ids.
- `includeIds(include: boolean)` → `TransactionsDataTableBuilder` — ~~Deprecated: Use `ids` instead.~~
- `includeProperties(include: boolean)` → `TransactionsDataTableBuilder` — ~~Deprecated: Use `properties` instead.~~
- `includeUrls(include: boolean)` → `TransactionsDataTableBuilder` — ~~Deprecated: Use `urls` instead.~~
- `properties(include: boolean)` → `TransactionsDataTableBuilder` — Defines whether to include custom transaction properties.
- `recordedAt(include: boolean)` → `TransactionsDataTableBuilder` — Defines whether to include the "Recorded at" column.
- `urls(include: boolean)` → `TransactionsDataTableBuilder` — Defines whether to include attachments and url links.

### User *(extends Resource<bkper.User>)*

This class defines a User on the Bkper platform.

Users can own and collaborate on `Books`, manage `Collections`, and connect to external services through `Connections`.

Each User has a unique identity, subscription plan details, and access permissions across the platform.

**Constructor:** `new User(payload?: bkper.User, config?: Config)`

**Properties:**

- `payload`: `bkper.User` — The underlying payload data for this resource

**Methods:**

- `getAvatarUrl()` → `string | undefined` — Gets the avatar url of the User.
- `getBilling()` → `Promise<Billing>` — Gets the billing information for this User.
- `getConnection(id: string)` → `Promise<Connection>` — Gets a `Connection` of the User.
- `getConnections()` → `Promise<Connection[]>` — Gets the `Connections` of the User.
- `getEmail()` → `string | undefined` — Gets the email of the User.
- `getFullName()` → `string | undefined` — Gets the full name of the User.
- `getGivenName()` → `string | undefined` — Gets the given name of the User.
- `getHostedDomain()` → `string | undefined` — Gets the hosted domain of the User.
- `getId()` → `string | undefined` — Gets the id of the User.
- `getName()` → `string | undefined` — Gets the name of the User.
- `getPlanCycle()` → `"MONTHLY" | "YEARLY" | undefined` — Gets the billing cycle of the User's current plan.
- `getUsername()` → `string | undefined` — Gets the username of the User.
- `hasUsedConnections()` → `boolean | undefined` — Tells if the User has already used `Connections`.
- `json()` → `bkper.User` — Gets an immutable copy of the JSON payload for this resource.

## Interfaces

### BalancesContainer

The container of balances of an `Account` or `Group`

The container is composed of a list of `Balances` for a window of time, as well as its period and cumulative totals.

**Properties:**

- `getAccount`: `() => Promise<Account | null>` — Gets the `Account` associated with this container.
- `getBalances`: `() => Balance[]` — Gets all `Balances` of the container
- `getBalancesContainer`: `(name: string) => BalancesContainer` — Gets a specific `BalancesContainer`.
- `getBalancesContainers`: `() => BalancesContainer[]` — Gets all child `BalancesContainers`.
- `getBalancesReport`: `() => BalancesReport` — Gets the parent `BalancesReport` of the container.
- `getCumulativeBalance`: `() => Amount` — Gets the cumulative balance to the date.
- `getCumulativeBalanceRaw`: `() => Amount` — Gets the cumulative raw balance to the date.
- `getCumulativeBalanceRawText`: `() => string` — Gets the cumulative raw balance formatted according to `Book` decimal format and fraction digits.
- `getCumulativeBalanceText`: `() => string` — Gets the cumulative balance formatted according to `Book` decimal format and fraction digits.
- `getDepth`: `() => number` — Gets the depth in the parent chain up to the root.
- `getGroup`: `() => Promise<Group | null>` — Gets the `Group` associated with this container.
- `getName`: `() => string` — Gets the `Account` or `Group` name.
- `getNormalizedName`: `() => string` — Gets the `Account` or `Group` name without spaces or special characters.
- `getParent`: `() => BalancesContainer | null` — Gets the parent BalanceContainer.
- `getPeriodBalance`: `() => Amount` — Gets the balance on the date period.
- `getPeriodBalanceRaw`: `() => Amount` — Gets the raw balance on the date period.
- `getPeriodBalanceRawText`: `() => string` — Gets the raw balance on the date period formatted according to `Book` decimal format and fraction digits.
- `getPeriodBalanceText`: `() => string` — Gets the balance on the date period formatted according to `Book` decimal format and fraction digits.
- `hasGroupBalances`: `() => boolean` — Gets whether the balance container is from a parent group.
- `isCredit`: `() => boolean | undefined` — Gets the credit nature of the BalancesContainer, based on `Account` or `Group`.
- `isFromAccount`: `() => boolean` — Gets whether this balance container is from an `Account`.
- `isFromGroup`: `() => boolean` — Gets whether this balance container is from a `Group`.
- `isPermanent`: `() => boolean` — Tell if this balance container is permanent, based on the `Account` or `Group`.
- `payload`: `bkper.AccountBalances | bkper.GroupBalances`

**Methods:**

- `createDataTable()` → `BalancesDataTableBuilder` — Creates a BalancesDataTableBuilder to generate a two-dimensional array with all `BalancesContainers`
- `getCumulativeCredit()` → `Amount` — The cumulative credit to the date.
- `getCumulativeCreditText()` → `string` — The cumulative credit formatted according to `Book` decimal format and fraction digits.
- `getCumulativeDebit()` → `Amount` — The cumulative debit to the date.
- `getCumulativeDebitText()` → `string` — The cumulative credit formatted according to `Book` decimal format and fraction digits.
- `getPeriodCredit()` → `Amount` — The credit on the date period.
- `getPeriodCreditText()` → `string` — The credit on the date period formatted according to `Book` decimal format and fraction digits
- `getPeriodDebit()` → `Amount` — The debit on the date period.
- `getPeriodDebitText()` → `string` — The debit on the date period formatted according to `Book` decimal format and fraction digits
- `getProperties()` → `{ [key: string]: string }` — Gets the custom properties stored in this Account or Group.
- `getProperty(keys: string[])` → `string | undefined` — Gets the property value for given keys. First property found will be retrieved
- `getPropertyKeys()` → `string[]` — Gets the custom properties keys stored in the associated `Account` or `Group`.

**getBalancesContainers**

**NOTE**: Only for Group balance containers. Accounts returns null.

**isCredit**

For `Account`, the credit nature will be the same as the one from the Account.

For `Group`, the credit nature will be the same, if all accounts containing on it has the same credit nature. False if mixed.

**isPermanent**

Permanent are the ones which final balance is relevant and keep its balances over time.

They are also called [Real Accounts](http://en.wikipedia.org/wiki/Account_(accountancy)#Based_on_periodicity_of_flow).

Usually represents assets or liabilities, capable of being perceived by the senses or the mind, like bank accounts, money, debts and so on.

### Config

This class defines the `Bkper` API Config.

**Properties:**

- `agentIdProvider?`: `() => Promise<string | undefined>` — Provides the agent ID to identify the calling agent for attribution purposes.
- `apiKeyProvider?`: `() => Promise<string>` — Optional API key for dedicated quota limits.
- `oauthTokenProvider?`: `() => Promise<string | undefined>` — Issue a valid OAuth2 access token with **https://www.googleapis.com/auth/userinfo.email** scope authorized.
- `requestErrorHandler?`: `(error: any) => any` — Custom request error handler
- `requestHeadersProvider?`: `() => Promise<{ [key: string]: string }>` — Provides additional headers to append to the API request
- `requestRetryHandler?`: `(status?: number, error?: any, attempt?: number) => Promise<void>` — Custom request retry handler.

**agentIdProvider**

This ID is sent via the `bkper-agent-id` header with each API request,
allowing the server to attribute actions to the correct agent.

**apiKeyProvider**

If not provided, requests use a shared managed quota via the Bkper API proxy.
Use your own API key for dedicated quota limits and project-level usage tracking.

API keys are for project identification only, not for authentication or agent attribution.
Agent attribution is handled separately via the `agentIdProvider`.

**oauthTokenProvider**

If omitted or if it returns undefined, requests are sent without an Authorization header.
This supports environments where authentication is injected outside bkper-js, such as
Bkper Platform outbound for server-side app routes.

**requestRetryHandler**

This function is called when a request fails and needs to be retried.
It provides the HTTP status code, error message, and the number of retry attempts made so far.

### ListEventsOptions

Options for listing events in a Book.

**Properties:**

- `afterDate?`: `string` — The start date (inclusive) for the events search range, in [RFC3339](https://en.wikipedia.org/wiki/ISO_8601#RFC_3339) format.
- `beforeDate?`: `string` — The end date (exclusive) for the events search range, in [RFC3339](https://en.wikipedia.org/wiki/ISO_8601#RFC_3339) format.
- `cursor?`: `string` — The cursor for pagination.
- `limit`: `number` — The maximum number of events to return.
- `onError?`: `boolean` — Whether to filter events by error responses.
- `resourceId?`: `string` — The ID of the event's resource (Transaction, Account, or Group).
- `type?`: `EventType` — The event type to filter by.

**limit**

Defaults to `50`, maximum is `200`.

**onError**

`true` returns events with at least one error response.
`false` returns events with no error responses.
`null` or `undefined` includes events regardless of error responses.

Ignored when `resourceId` is set. When set, `type` is ignored.

**resourceId**

When set, `onError` and `type` are ignored.

**type**

Ignored when `resourceId` or `onError` is set.

## Enums

### AccountType

Enum that represents account types.

- `ASSET` — Asset account type
- `INCOMING` — Incoming account type
- `LIABILITY` — Liability account type
- `OUTGOING` — Outgoing account type

### BalanceType

Enum that represents balance types.

- `CUMULATIVE` — Cumulative balance
- `PERIOD` — Period balance
- `TOTAL` — Total balance

### BotResponseType

Enum that represents the type of a Bot Response

- `ERROR` — Error bot response
- `INFO` — Info bot response
- `WARNING` — Warning bot response

### DecimalSeparator

Decimal separator of numbers on book

- `COMMA` — ,
- `DOT` — .

### EventType

Enum that represents event types.

- `ACCOUNT_CREATED`
- `ACCOUNT_DELETED`
- `ACCOUNT_UPDATED`
- `BOOK_AUDITED`
- `BOOK_CREATED`
- `BOOK_DELETED`
- `BOOK_UPDATED`
- `COLLABORATOR_ADDED`
- `COLLABORATOR_REMOVED`
- `COLLABORATOR_UPDATED`
- `COMMENT_CREATED`
- `COMMENT_DELETED`
- `FILE_CREATED`
- `FILE_DELETED`
- `FILE_UPDATED`
- `GROUP_CREATED`
- `GROUP_DELETED`
- `GROUP_UPDATED`
- `INTEGRATION_CREATED`
- `INTEGRATION_DELETED`
- `INTEGRATION_UPDATED`
- `QUERY_CREATED`
- `QUERY_DELETED`
- `QUERY_UPDATED`
- `TRANSACTION_CHECKED`
- `TRANSACTION_CREATED`
- `TRANSACTION_DELETED`
- `TRANSACTION_POSTED`
- `TRANSACTION_RESTORED`
- `TRANSACTION_UNCHECKED`
- `TRANSACTION_UPDATED`

### MenuOpenMode

Enum that represents how an App menu opens.

- `EXPANDED` — Open expanded inside the app panel.
- `NEW_TAB` — Open in a new browser tab.
- `SIDEBAR` — Open inside the sidebar panel.

### Month

Enum that represents a Month.

- `APRIL`
- `AUGUST`
- `DECEMBER`
- `FEBRUARY`
- `JANUARY`
- `JULY`
- `JUNE`
- `MARCH`
- `MAY`
- `NOVEMBER`
- `OCTOBER`
- `SEPTEMBER`

### Period

Enum that represents a period slice.

- `MONTH` — Monthly period
- `QUARTER` — Quarterly period
- `YEAR` — Yearly period

### Periodicity

The Periodicity of the query. It may depend on the level of granularity you write the range params.

- `DAILY` — Example: after:25/01/1983, before:04/03/2013, after:$d-30, before:$d, after:$d-15/$m
- `MONTHLY` — Example: after:jan/2013, before:mar/2013, after:$m-1, before:$m
- `YEARLY` — Example: on:2013, after:2013, $y

### Permission

Enum representing permissions of user in the Book

- `EDITOR` — Manage accounts, transactions, book configuration and sharing
- `NONE` — No permission
- `OWNER` — Manage everything, including book visibility and deletion. Only one owner per book.
- `POSTER` — View transactions, accounts, record and delete drafts
- `RECORDER` — Record and delete drafts only. Useful to collect data only
- `VIEWER` — View transactions, accounts and balances.

### TransactionStatus

Enum that represents the status of a Transaction.

- `CHECKED` — Transaction is posted and checked
- `DRAFT` — Transaction is a draft, not yet posted
- `TRASHED` — Transaction is in the trash
- `UNCHECKED` — Transaction is posted but not checked

### Visibility

Enum representing the visibility of a Book

- `PRIVATE` — The book can be accessed by the owner and collaborators
- `PUBLIC` — The book can be accessed by anyone with the link

---
source: /docs/api/bkper-web-auth.md

# @bkper/web-auth

> Web authentication SDK for Bkper — OAuth flows, token management, and session handling.

[![npm](https://img.shields.io/npm/v/@bkper/web-auth?color=%235889e4)](https://www.npmjs.com/package/@bkper/web-auth) [![GitHub](https://img.shields.io/badge/bkper%2Fbkper--web--sdks-blue?logo=github)](https://github.com/bkper/bkper-web-sdks)

# @bkper/web-auth

OAuth authentication SDK for apps on the [Bkper Platform](https://bkper.com/docs/build/apps/overview) (`*.bkper.app` subdomains).

## Quick Start

```typescript
import { BkperAuth } from '@bkper/web-auth';

// Initialize client with callbacks
const auth = new BkperAuth({
    onLoginSuccess: () => {
        console.log('User authenticated!');
        loadUserData();
    },
    onLoginRequired: () => {
        console.log('Please sign in');
        showLoginButton();
    },
});

// Initialize authentication flow on app load
await auth.init();

// Make an authenticated request with automatic token refresh and one retry
const response = await auth.authenticatedFetch('/data');
```

## Authenticated Requests

`authenticatedFetch()` implements the standard Fetch API contract. It adds the current bearer token to a request. If the response is `401`, it refreshes the token and retries exactly once. Other response statuses are returned unchanged.

```typescript
const response = await auth.authenticatedFetch('/data', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ value: 42 }),
});
```

The method can also be supplied to any HTTP client that accepts a Fetch-compatible function:

```typescript
const fetchWithAuth = auth.authenticatedFetch.bind(auth);
```

Call `init()` before the first authenticated request. If no token is available, or the session cannot be refreshed, `onLoginRequired` is called and the request rejects with an authentication-required error. If the retried request also returns `401`, that response is returned without another retry. Concurrent refresh calls share one refresh request.

To prevent accidental token disclosure, authenticated requests are restricted to:

- HTTPS origins on `bkper.app` or its subdomains
- The current `localhost` or `127.0.0.1` origin during local development

Request paths are not restricted.

### Using with bkper-js

`@bkper/web-auth` does not depend on `bkper-js`, but they can be connected through the client configuration. Provide the current token for each request and refresh it when the Bkper API reports an expired login:

```typescript
import { Bkper } from 'bkper-js';

const bkper = new Bkper({
    oauthTokenProvider: async () => auth.getAccessToken(),
    requestRetryHandler: async (status, _error, attempt) => {
        if (status === 403 && attempt === 1) {
            await auth.refresh();
        }
    },
});
```

`bkper-js` owns its request and retry lifecycle. `@bkper/web-auth` remains responsible only for the current access token and session refresh.

## What's Included

-   OAuth authentication SDK for apps on `*.bkper.app` subdomains
-   Callback-based API for authentication events
-   OAuth flow with in-memory token management
-   Single-flight token refresh mechanism
-   Authenticated Fetch API with one-time refresh and retry
-   TypeScript support with full type definitions

## How It Works

**Session Persistence:**

-   Access tokens are stored in-memory (cleared on page refresh)
-   Sessions persist via HTTP-only cookies scoped to the `.bkper.app` domain
-   Call `init()` on app load to restore an access token from the session
-   Protected resources still require `Authorization: Bearer <token>`; session cookies only restore client auth state

> **Note:** This SDK only works for apps hosted on `*.bkper.app` subdomains. Applications on other domains must provide a valid access token through their own authentication mechanism.

**Security:**

-   HTTP-only cookies protect refresh tokens from XSS
-   In-memory access tokens minimize exposure

## TypeScript Support

This package is written in TypeScript and provides full type definitions out of the box. All public APIs are fully typed, including callbacks and configuration options.

```typescript
import { BkperAuth, BkperAuthConfig } from '@bkper/web-auth';

const config: BkperAuthConfig = {
    onLoginSuccess: () => console.log('Authenticated'),
    onError: error => console.error('Auth error:', error),
};

const auth = new BkperAuth(config);
```

## Browser Compatibility

This package requires a modern browser with support for:

-   [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#browser_compatibility) for HTTP requests
-   [Location API](https://developer.mozilla.org/en-US/docs/Web/API/Location) for login/logout redirects

The app must be deployed to a `*.bkper.app` subdomain for session-cookie token restoration to work.

## Classes

### BkperAuth

OAuth authentication client for the Bkper API.

Provides framework-agnostic authentication with callback-based event handling.
Access tokens are stored in-memory; sessions persist via HTTP-only cookies.

```typescript
// Initialize authentication client
const auth = new BkperAuth({
  onLoginSuccess: () => loadUserData(),
  onLoginRequired: () => showLoginButton()
});

// Restore session on app load
await auth.init();
```

**Constructor:** `new BkperAuth(config?: BkperAuthConfig)`

Creates a new BkperAuth instance.

```typescript
// Simple usage with defaults
const auth = new BkperAuth();

// With callbacks
const auth = new BkperAuth({
  onLoginSuccess: () => console.log('Logged in!'),
  onLoginRequired: () => showLoginDialog(),
  onError: (error) => console.error(error)
});
```

**Methods:**

- `authenticatedFetch(input: RequestInfo | URL, init?: RequestInit)` → `Promise<Response>` — Performs an authenticated request and retries it once after refreshing an
expired or invalid access token.
- `getAccessToken()` → `string | undefined` — Gets the current access token.
- `init()` → `Promise<void>` — Initializes the authentication state by attempting to refresh the access token.
- `login()` → `void` — Redirects the user to the login page.
- `logout()` → `void` — Logs out the user and redirects to the logout page.
- `refresh()` → `Promise<void>` — Refreshes the access token using the current session.

**authenticatedFetch**

Concurrent refresh calls share the same refresh request. A second 401
response is returned without another retry.

Call `init()` before the first request. Bearer tokens are sent only to
HTTPS Bkper origins or the current local development origin. Request
paths are not restricted.

**getAccessToken**

```typescript
const tokenProvider = async () => auth.getAccessToken();
```

The access token if authenticated, undefined otherwise

Use

`authenticatedFetch()`

for Fetch API requests. This getter is
available for HTTP clients that accept an access-token provider.

**init**

Call this method when your app loads to restore the user's session.
Triggers `onLoginSuccess` if a valid session exists, or `onLoginRequired` if login is needed.

**login**

The user will be redirected to the authentication service to complete the login flow.
After successful login, they will be redirected back to the current page.

```typescript
// Trigger login when user clicks a button
loginButton.addEventListener('click', () => {
  auth.login();
});
```

**logout**

Triggers the `onLogout` callback before redirecting.
The user's session will be terminated.

```typescript
// Logout when user clicks logout button
logoutButton.addEventListener('click', () => {
  auth.logout();
});
```

**refresh**

Concurrent calls share one refresh request. Triggers `onTokenRefresh`
if successful and throws if the refresh request fails.

`authenticatedFetch()` calls this method automatically after a 401.
Consumers can also call it explicitly when they need a new token.

```typescript
await auth.refresh();
const token = auth.getAccessToken();
```

## Interfaces

### BkperAuthConfig

Configuration options for the BkperAuth class.

**Properties:**

- `baseUrl?`: `string` — Override the authentication service base URL.
- `getAdditionalAuthParams?`: `() => Record<string, string>` — Provide additional parameters to send to the authentication service.
- `onError?`: `(error: unknown) => void` — Called when an error occurs during authentication.
- `onLoginRequired?`: `() => void` — Called when login is required (user needs to sign in).
- `onLoginSuccess?`: `() => void` — Called when login succeeds (user is authenticated).
- `onLogout?`: `() => void` — Called when the user logs out.
- `onTokenRefresh?`: `(token: string) => void` — Called when the access token is refreshed.

**baseUrl**

Most users don't need this. The default production URL works out of the box.

Use cases:
- Testing: Point to a mock authentication service for integration tests
- Development: Use a local mock server

```typescript
// Testing with mock server
const auth = new BkperAuth({
  baseUrl: 'http://localhost:3000/mock-auth'
});
```

**getAdditionalAuthParams**

Useful for custom authentication flows or passing additional context
to your authentication implementation.

```typescript
// Custom authentication context
const auth = new BkperAuth({
  getAdditionalAuthParams: () => {
    const token = new URLSearchParams(location.search).get('custom-token');
    return token ? { customToken: token } : {};
  }
});
```

---
source: /docs/api/rest.md

# REST API

> Full OpenAPI reference for the Bkper REST API — endpoints, parameters, and response schemas.

RESTful API for managing financial books, accounts, transactions, and balances in [Bkper](https://bkper.com).

## Base URL

```
https://api.bkper.app
```

All endpoints are under `/v5/`. For example:
- `GET https://api.bkper.app/v5/user` — Get the authenticated user
- `GET https://api.bkper.app/v5/books` — List books
- `GET https://api.bkper.app/v5/books/{bookId}` — Get a specific book

## Authentication

All requests require a [Google OAuth2](https://developers.google.com/identity/protocols/oauth2) access token with the `email` scope, sent as a Bearer token:

```
Authorization: Bearer <access_token>
```

### Getting a token

The easiest way to authenticate is through the [Bkper CLI](https://www.npmjs.com/package/bkper), which manages the OAuth flow for you:

```bash
npm i -g bkper
bkper auth login  # Opens browser for Google sign-in
bkper book list   # You're connected
```

For programmatic access, use a client library that handles token management:

- **Node.js** — [bkper-js](https://www.npmjs.com/package/bkper-js) with the CLI's `getOAuthToken()` for local scripts, or with [@bkper/web-auth](https://www.npmjs.com/package/@bkper/web-auth) for browser apps
- **Google Apps Script** — [bkper-gs](https://www.npmjs.com/package/@bkper/bkper-gs) library, which uses Apps Script's built-in OAuth

You can also set up your own [OAuth2 client credentials](https://developers.google.com/identity/protocols/oauth2) in a Google Cloud project if you need full control over the authentication flow.

## API Key (optional)

For dedicated quota and project-level usage tracking, you can pass an API key via the `key` query parameter. API keys are for quota management only — they do not replace OAuth2 authentication.

## OpenAPI Specification

The machine-readable spec is available at [`https://bkper.com/docs/api/rest/openapi.json`](https://bkper.com/docs/api/rest/openapi.json). Use it with Swagger UI, Postman, or any OpenAPI-compatible tool.

Content-Type: `application/json`

## Endpoints

All `/v5/books/{bookId}/...` endpoints require `bookId` (path, string, required) — the book's unique identifier.

### Apps

#### `GET /v5/apps` — listApps

**Response 200:** AppList

#### `POST /v5/apps` — createApp

**Request body:** App

**Response 200:** App

#### `PUT /v5/apps` — updateApp

**Request body:** App

**Response 200:** App

#### `GET /v5/apps/{agentId}` — getApp

**Parameters:**

- `agentId` (path, string, required)

**Response 200:** App

### Books

#### `GET /v5/books` — listBooks

**Parameters:**

- `query` (query, string) — Optional search term to filter books

**Response 200:** BookList

#### `POST /v5/books` — createNewBook

**Parameters:**

- `name` (query, string)

**Request body:** Book

**Response 200:** Book

#### `PUT /v5/books` — updateBook

**Request body:** Book

**Response 200:** Book

#### `GET /v5/books/{bookId}` — getBook

Load a book

**Parameters:**

- `loadAccounts` (query, boolean) — Optionally load accounts and groups
- `loadGroups` (query, boolean) — Optionally load groups

**Response 200:** Book

#### `PUT /v5/books/{bookId}` *(deprecated)* — updateBookDeprecated

**Request body:** Book

**Response 200:** Book

#### `DELETE /v5/books/{bookId}` — deleteBook

**Response 200:** Book

#### `GET /v5/books/{bookId}/apps` — listBookApps

**Response 200:** AppList

#### `PATCH /v5/books/{bookId}/audit` — auditBook

Audit a book async

**Response 204:** A successful response

#### `POST /v5/books/{bookId}/copy` — copyBook

Copy a book with optional transaction copying

**Parameters:**

- `name` (query, string) — Name for the copied book
- `copyTransactions` (query, boolean) — Whether to copy transactions
- `fromDate` (query, integer (int32)) — Start date for copying transactions (YYYYMMDD format)

**Response 200:** Book

### Accounts

#### `GET /v5/books/{bookId}/accounts` — listAccounts

**Response 200:** AccountList

#### `POST /v5/books/{bookId}/accounts` — createAccount

**Request body:** Account

**Response 200:** Account

#### `PUT /v5/books/{bookId}/accounts` — updateAccount

**Request body:** Account

**Response 200:** Account

#### `POST /v5/books/{bookId}/accounts/batch` — createAccountsBatch

Batch create accounts

**Request body:** AccountList

**Response 200:** AccountList

#### `PUT /v5/books/{bookId}/accounts/batch` — updateAccountsBatch

Batch update accounts

**Request body:** AccountList

**Response 200:** AccountList

#### `POST /v5/books/{bookId}/accounts/delete/batch` — deleteAccountsBatch

Batch delete accounts

**Request body:** AccountList

**Response 200:** AccountList

#### `GET /v5/books/{bookId}/accounts/{id}` — getAccount

**Parameters:**

- `id` (path, string, required) — The account id or name

**Response 200:** Account

#### `DELETE /v5/books/{bookId}/accounts/{id}` — deleteAccount

**Parameters:**

- `id` (path, integer (int64), required) — The account id

**Response 200:** Account

#### `GET /v5/books/{bookId}/accounts/{id}/groups` — listAccountGroups

List the groups of an account

**Parameters:**

- `id` (path, string, required) — The account id or name

**Response 200:** GroupList

### Balances

#### `GET /v5/books/{bookId}/balances` — getBalances

**Parameters:**

- `query` (query, string, required) — The query to filter balances

**Response 200:** Balances

### Collaborators

#### `GET /v5/books/{bookId}/collaborators` — listCollaborators

List collaborators of the book

**Response 200:** CollaboratorPayloadCollection

#### `POST /v5/books/{bookId}/collaborators` — addCollaborator

Add or update a collaborator to the book

**Parameters:**

- `message` (query, string) — Optional message to send with the invitation email

**Request body:** Collaborator

**Response 200:** Collaborator

#### `POST /v5/books/{bookId}/collaborators/request` — requestBookAccess

Request access to a Book

**Parameters:**

- `permission` (query, string — `OWNER` | `EDITOR` | `POSTER` | `RECORDER` | `VIEWER` | `NONE`, required) — The permission requested in the Book
- `message` (query, string) — An optional message to the Book owner

**Response 204:** A successful response

#### `GET /v5/books/{bookId}/collaborators/request/{id}` — getBookAccessRequest

Resolve a Book access request

**Parameters:**

- `id` (path, string, required) — The Book access request id

**Response 200:** Collaborator

#### `DELETE /v5/books/{bookId}/collaborators/{id}` — removeCollaborator

Remove a collaborator from the book

**Parameters:**

- `id` (path, string, required) — The collaborator id or email

**Response 200:** Collaborator

### Collections

#### `GET /v5/collections` — listCollections

**Response 200:** CollectionList

#### `POST /v5/collections` — createCollection

**Request body:** Collection

**Response 200:** Collection

#### `PUT /v5/collections` — updateCollection

**Request body:** Collection

**Response 200:** Collection

#### `DELETE /v5/collections/{id}` — deleteCollection

**Parameters:**

- `id` (path, string, required)

**Response 200:** BookList

#### `PATCH /v5/collections/{id}/books/add` — addBooksToCollection

**Parameters:**

- `id` (path, string, required)

**Request body:** BookList

**Response 200:** BookList

#### `PATCH /v5/collections/{id}/books/remove` — removeBooksFromCollection

**Parameters:**

- `id` (path, string, required)

**Request body:** BookList

**Response 200:** BookList

### Events

#### `GET /v5/books/{bookId}/events` — listEvents

**Parameters:**

- `after` (query, string (date-time)) — After date and time, on RFC3339 format
- `before` (query, string (date-time)) — Before date and time, on RFC3339 format
- `error` (query, boolean) — Filter by error
- `resoureId` (query, string) — The resourceId associated
- `type` (query, string — `FILE_CREATED` | `FILE_UPDATED` | `FILE_DELETED` | `TRANSACTION_CREATED` | `TRANSACTION_UPDATED` | `TRANSACTION_DELETED` | `TRANSACTION_POSTED` | `TRANSACTION_CHECKED` | `TRANSACTION_UNCHECKED` | `TRANSACTION_RESTORED` | `ACCOUNT_CREATED` | `ACCOUNT_UPDATED` | `ACCOUNT_DELETED` | `QUERY_CREATED` | `QUERY_UPDATED` | `QUERY_DELETED` | `GROUP_CREATED` | `GROUP_UPDATED` | `GROUP_DELETED` | `COMMENT_CREATED` | `COMMENT_DELETED` | `COLLABORATOR_ADDED` | `COLLABORATOR_UPDATED` | `COLLABORATOR_REMOVED` | `INTEGRATION_CREATED` | `INTEGRATION_UPDATED` | `INTEGRATION_DELETED` | `BOOK_CREATED` | `BOOK_AUDITED` | `BOOK_UPDATED` | `BOOK_DELETED`) — Filter by event type
- `limit` (query, integer (int32)) — The dataset limit. Useful for pagination

**Response 200:** EventList

#### `GET /v5/books/{bookId}/events/backlog` — getBookEventsBacklog

Get book events backlog

**Response 200:** Backlog

#### `PATCH /v5/books/{bookId}/events/replay/batch` — replayEvents

Batch replay events responses

**Parameters:**

- `errorsOnly` (query, boolean) — Replay errors only

**Request body:** EventList

**Response 204:** A successful response

#### `PUT /v5/books/{bookId}/events/{id}/responses/{agentId}` — replayEventResponse

Replay an event response

**Parameters:**

- `id` (path, string, required) — The event id
- `agentId` (path, string, required) — The agent id

**Response 200:** Event

#### `DELETE /v5/books/{bookId}/events/{id}/responses/{agentId}` — deleteEventResponse

Delete an event response

**Parameters:**

- `id` (path, string, required) — The event id
- `agentId` (path, string, required) — The agent id

**Response 200:** Event

### Files

#### `GET /v5/books/{bookId}/files` — listFiles

**Parameters:**

- `limit` (query, integer (int32)) — The dataset limit. Useful for pagination

**Response 200:** FileList

#### `POST /v5/books/{bookId}/files` — createFile

**Request body:** File

**Response 200:** File

#### `PUT /v5/books/{bookId}/files` — updateFile

**Request body:** File

**Response 200:** File

#### `GET /v5/books/{bookId}/files/{id}` — getFile

**Parameters:**

- `id` (path, string, required) — The file id

**Response 200:** File

#### `DELETE /v5/books/{bookId}/files/{id}` — deleteFile

**Parameters:**

- `id` (path, string, required) — The file id

**Response 200:** File

### Groups

#### `GET /v5/books/{bookId}/groups` — listGroups

**Response 200:** GroupList

#### `POST /v5/books/{bookId}/groups` — createGroup

Group a group

**Request body:** Group

**Response 200:** Group

#### `PUT /v5/books/{bookId}/groups` — updateGroup

**Request body:** Group

**Response 200:** Group

#### `POST /v5/books/{bookId}/groups/batch` — createGroupsBatch

Batch create groups

**Request body:** GroupList

**Response 200:** GroupList

#### `GET /v5/books/{bookId}/groups/{id}` — getGroup

**Parameters:**

- `id` (path, string, required) — The group id or name

**Response 200:** Group

#### `DELETE /v5/books/{bookId}/groups/{id}` — deleteGroup

**Parameters:**

- `id` (path, integer (int64), required) — The group id

**Response 200:** Group

#### `GET /v5/books/{bookId}/groups/{id}/accounts` — listGroupAccounts

List the accounts of a group

**Parameters:**

- `id` (path, string, required) — The group id or name

**Response 200:** AccountList

### Integrations

#### `GET /v5/books/{bookId}/integrations` — listIntegrations

List the integrations of the book

**Response 200:** IntegrationList

#### `POST /v5/books/{bookId}/integrations` — createIntegration

**Request body:** Integration

**Response 200:** Integration

#### `PUT /v5/books/{bookId}/integrations` — updateIntegration

**Request body:** Integration

**Response 200:** Integration

#### `DELETE /v5/books/{bookId}/integrations/{id}` — deleteIntegration

**Parameters:**

- `id` (path, integer (int64), required)

**Response 200:** Integration

### Queries

#### `GET /v5/books/{bookId}/queries` — listQueries

**Response 200:** QueryList

#### `POST /v5/books/{bookId}/queries` — saveQuery

Create a saved query

**Request body:** Query

**Response 200:** Query

#### `PUT /v5/books/{bookId}/queries` — updateQuery

Update a saved query

**Request body:** Query

**Response 200:** Query

#### `DELETE /v5/books/{bookId}/queries/{id}` — deleteQuery

Delete a saved query

**Parameters:**

- `id` (path, integer (int64), required) — The query id

**Response 200:** Query

### Templates

#### `GET /v5/templates` — listTemplates

**Response 200:** TemplateList

### Transactions

#### `GET /v5/books/{bookId}/transactions` — listTransactions

**Parameters:**

- `query` (query, string) — The query to filter transactions
- `limit` (query, integer (int32)) — The dataset limit. Useful for pagination

**Response 200:** TransactionList

#### `POST /v5/books/{bookId}/transactions` — createTransaction

**Parameters:**

- `timeZone` (query, string) — Optional time zone for parsing dates when recording from different book time zone

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PUT /v5/books/{bookId}/transactions` — updateTransaction

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `POST /v5/books/{bookId}/transactions/batch` — createTransactionsBatch

Batch create transactions

**Parameters:**

- `timeZone` (query, string) — Optional time zone for parsing dates when recording from different book time zone

**Request body:** TransactionList

**Response 200:** TransactionList

#### `PUT /v5/books/{bookId}/transactions/batch` — updateTransactionsBatch

Batch update transactions

**Parameters:**

- `updateChecked` (query, boolean) — True to also update checked transactions

**Request body:** TransactionList

**Response 200:** TransactionList

#### `PATCH /v5/books/{bookId}/transactions/check` — checkTransaction

Check a transaction

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/check/batch` — checkTransactionsBatch

Batch check transactions

**Request body:** TransactionList

**Response 204:** A successful response

#### `GET /v5/books/{bookId}/transactions/count` — countTransactions

Count transactions

**Parameters:**

- `query` (query, string) — The query to filter transactions

**Response 200:** Count

#### `GET /v5/books/{bookId}/transactions/count/posted` — countTransactionsPosted

Count transactions posted

**Parameters:**

- `after` (query, string (date), required) — After date, on yyyy-mm-dd format.
- `before` (query, string (date), required) — Before date, on yyyy-mm-dd format.
- `periodicity` (query, string — `DAILY` | `MONTHLY` | `YEARLY`, required) — Periodicity DAILY or MONTHLY

**Response 200:** Counts

#### `PATCH /v5/books/{bookId}/transactions/merge` — mergeTransactions

Merge two transactions into a single new canonical transaction

**Request body:** TransactionList

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/post` — postTransaction

Post a transaction into accounts

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/post/batch` — postTransactionsBatch

Batch post transactions

**Request body:** TransactionList

**Response 204:** A successful response

#### `PATCH /v5/books/{bookId}/transactions/remove` *(deprecated)* — removeTransaction

Remove a transaction, sending to trash

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/restore` *(deprecated)* — restoreTransaction

Restore a transaction from trash

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/trash` — trashTransaction

Trash a transaction

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/trash/batch` — trashTransactionsBatch

Batch trash transactions

**Parameters:**

- `trashChecked` (query, boolean) — True to also trash checked transactions

**Request body:** TransactionList

**Response 204:** A successful response

#### `PATCH /v5/books/{bookId}/transactions/uncheck` — uncheckTransaction

Uncheck a transaction

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/uncheck/batch` — uncheckTransactionsBatch

Batch uncheck a transactions

**Request body:** TransactionList

**Response 204:** A successful response

#### `PATCH /v5/books/{bookId}/transactions/untrash` — untrashTransaction

Untrash a transaction

**Request body:** Transaction

**Response 200:** TransactionOperation

#### `PATCH /v5/books/{bookId}/transactions/untrash/batch` — untrashTransactionsBatch

Batch untrash transactions

**Request body:** TransactionList

**Response 204:** A successful response

#### `GET /v5/books/{bookId}/transactions/{id}` — getTransaction

**Parameters:**

- `id` (path, string, required) — The transaction id

**Response 200:** Transaction

### User

#### `GET /v5/user` — getUser

Retrieve the current user

**Response 200:** User

#### `GET /v5/user/billing` — getBilling

Retrieve the user billing information

**Response 200:** Billing

#### `GET /v5/user/billing/checkout` — getBillingCheckout

Retrieve the user billing checkout url for a plan

**Parameters:**

- `plan` (query, string, required)
- `cycle` (query, string)
- `successUrl` (query, string, required)
- `cancelUrl` (query, string, required)

**Response 200:** Url

#### `GET /v5/user/billing/counts` — listBillingCounts

List user billing transaction counts for last 12 months

**Response 200:** Counts

#### `GET /v5/user/billing/portal` — getBillingPortal

Retrieve the user billing portal url

**Parameters:**

- `returnUrl` (query, string, required)

**Response 200:** Url

#### `GET /v5/user/connections` — listConnections

**Response 200:** ConnectionList

#### `POST /v5/user/connections` — createConnection

**Request body:** Connection

**Response 200:** Connection

#### `PUT /v5/user/connections` — updateConnection

**Request body:** Connection

**Response 200:** Connection

#### `GET /v5/user/connections/{id}` — getConnection

Retrieve a connection by id

**Parameters:**

- `id` (path, string, required)

**Response 200:** Connection

#### `DELETE /v5/user/connections/{id}` — deleteConnection

**Parameters:**

- `id` (path, string, required)

**Response 200:** Connection

#### `GET /v5/user/connections/{id}/integrations` — listConnectionIntegrations

List integrations by connection

**Parameters:**

- `id` (path, string, required)

**Response 200:** IntegrationList

## Data Models

### Account

- `agentId`: string — The id of agent that created the resource
- `archived`: boolean — Archived accounts are kept for history
- `balance`: string — The running balance of the account at the transaction date. Only present when the account is part of a transaction response filtered by account. NOT the current account balance. To get current balances, use the Balances endpoint: GET /books/{bookId}/balances
- `balanceVerified`: boolean — Whether the account balance has been verified/audited
- `createdAt`: string — The creation timestamp, in milliseconds
- `credit`: boolean — Credit nature or Debit otherwise
- `groups`: Group[] — The groups of the account
- `hasTransactionPosted`: boolean — Whether the account has any transactions posted
- `id`: string — The unique id that identifies the Account in the Book
- `name`: string — The name of the Account
- `normalizedName`: string — The name of the Account, lowercase, without spaces or special characters
- `permanent`: boolean — Permanent are such as bank accounts, customers or the like
- `properties`: Record<string, string> — The key/value custom properties of the Account
- `type`: string — `ASSET` | `LIABILITY` | `INCOMING` | `OUTGOING` — The type of the account
- `updatedAt`: string — The last update timestamp, in milliseconds

### AccountBalances

- `archived`: boolean
- `balances`: Balance[]
- `credit`: boolean
- `cumulativeBalance`: string
- `cumulativeCredit`: string
- `cumulativeDebit`: string
- `empty`: boolean
- `name`: string
- `normalizedName`: string
- `periodBalance`: string
- `periodCredit`: string
- `periodDebit`: string
- `permanent`: boolean
- `properties`: Record<string, string>

### AccountList

- `items`: Account[] — List items

### Agent

- `id`: string — The agent id
- `logo`: string — The agent logo. Public url or Base64 encoded
- `logoDark`: string — The agent logo on dark mode. Public url or Base64 encoded
- `name`: string — The agent name

### App

- `apiVersion`: string — `v0` | `v1` | `v2` | `v3` | `v4` | `v5` — The API version of the event payload
- `clientId`: string — The Google OAuth Client ID
- `clientSecret`: string — The Google OAuth Client Secret
- `connectable`: boolean — Whether this app is connectable by a user
- `deprecated`: boolean — Whether the app is deprecated
- `description`: string — The App description
- `developers`: string — The developers (usernames and domain patterns), comma or space separated
- `events`: string[] — `FILE_CREATED` | `FILE_UPDATED` | `FILE_DELETED` | `TRANSACTION_CREATED` | `TRANSACTION_UPDATED` | `TRANSACTION_DELETED` | `TRANSACTION_POSTED` | `TRANSACTION_CHECKED` | `TRANSACTION_UNCHECKED` | `TRANSACTION_RESTORED` | `ACCOUNT_CREATED` | `ACCOUNT_UPDATED` | `ACCOUNT_DELETED` | `QUERY_CREATED` | `QUERY_UPDATED` | `QUERY_DELETED` | `GROUP_CREATED` | `GROUP_UPDATED` | `GROUP_DELETED` | `COMMENT_CREATED` | `COMMENT_DELETED` | `COLLABORATOR_ADDED` | `COLLABORATOR_UPDATED` | `COLLABORATOR_REMOVED` | `INTEGRATION_CREATED` | `INTEGRATION_UPDATED` | `INTEGRATION_DELETED` | `BOOK_CREATED` | `BOOK_AUDITED` | `BOOK_UPDATED` | `BOOK_DELETED` — Event types the App listen to
- `filePatterns`: string[] — File patterns the App handles - wildcard accepted. E.g. *.pdf, *-bank.csv
- `id`: string — The unique agent id of the App - this can't be changed after created
- `installable`: boolean — Whether this app is installable in a book
- `logoUrl`: string — The App logo url
- `logoUrlDark`: string — The App logo url in dark mode
- `menuOpenMode`: string — `SIDEBAR` | `EXPANDED` | `NEW_TAB` — How the app menu opens. Default to SIDEBAR
- `menuPopupHeight`: string — Deprecated
- `menuPopupWidth`: string — Deprecated
- `menuText`: string — The contex menu text - default to the App name
- `menuUrl`: string — The context menu url
- `menuUrlDev`: string — The context menu url in dev mode
- `name`: string — The App name
- `ownerEmail`: string — The owner user email
- `ownerId`: string — The owner user id
- `ownerLogoUrl`: string — The owner company logo url
- `ownerName`: string — The owner company name
- `ownerWebsite`: string — The owner company website url
- `propertiesSchema`: AppPropertiesSchema
- `published`: boolean — Whether this app is already published
- `readme`: string — The readme.md file as string
- `readmeMd`: string — The readme.md file as raw markdown string
- `repoPrivate`: boolean — Whether the code repository is private
- `repoUrl`: string — The code repository url
- `scopes`: string[] — The Google OAuth Scopes used by the app
- `users`: string — The users (usernames and domain patterns) to enable the App while not yet published
- `webhookUrl`: string — The Webhook endpoint URL to listen for book events
- `webhookUrlDev`: string — The Webhook endpoint URL to listen for book events in dev mode
- `website`: string — The App website url

### AppList

- `items`: App[]

### AppPropertiesSchema

- `account`: AppPropertySchema
- `book`: AppPropertySchema
- `group`: AppPropertySchema
- `transaction`: AppPropertySchema

### AppPropertySchema

- `keys`: string[] — The property keys schema
- `values`: string[] — The property values schema

### Backlog

- `count`: integer (int32)

### Balance

- `cumulativeBalance`: string
- `cumulativeCredit`: string
- `cumulativeDebit`: string
- `day`: integer (int32)
- `fuzzyDate`: integer (int32)
- `month`: integer (int32)
- `periodBalance`: string
- `periodCredit`: string
- `periodDebit`: string
- `year`: integer (int32)

### Balances

- `accountBalances`: AccountBalances[]
- `balancesUrl`: string
- `groupBalances`: GroupBalances[]
- `nextRange`: string
- `periodicity`: string — `DAILY` | `MONTHLY` | `YEARLY`
- `previousRange`: string
- `range`: string
- `rangeBeginLabel`: string
- `rangeEndLabel`: string

### Billing

- `adminEmail`: string — The billing admin email for the user's billing account
- `daysLeftInTrial`: integer (int32) — How many days the user has left in the trial period
- `email`: string — The user's email address
- `enabled`: boolean — True if billing is enabled for the user
- `hostedDomain`: string — The user hosted domain
- `plan`: string — The user's current plan
- `planOverdue`: boolean — True if subscription payment is overdue
- `startedTrial`: boolean — True if the user has started the trial period
- `totalTransactionsThisMonth`: integer (int64) — User-level total transactions this month
- `totalTransactionsThisYear`: integer (int64) — User-level total transactions this year

### Book

- `accounts`: Account[] — The book Accounts
- `agentId`: string — The id of agent that created the resource
- `autoPost`: boolean — Tells if the Book has auto post enabled
- `closingDate`: string — The book closing date, in ISO format yyyy-MM-dd. Transactions on or before this date are closed for the period
- `collection`: Collection
- `createdAt`: string — The creation timestamp, in milliseconds
- `datePattern`: string — The date pattern of the Book. Example: dd/MM/yyyy
- `decimalSeparator`: string — `DOT` | `COMMA` — The decimal separator of the Book
- `fractionDigits`: integer (int32) — The number of fraction digits (decimal places) of the Book. E.g. 2 for ####.##, 4 for ####.####
- `groups`: Group[] — The book account Groups
- `id`: string — The unique id that identifies the Book in the system. Found at bookId url param
- `lastUpdateMs`: string — The last update date of the Book, in milliseconds
- `lockDate`: string — The book lock date, in ISO format yyyy-MM-dd. Transactions on or before this date are locked
- `logoUrl`: string — The logo URL of the book owner's custom domain
- `name`: string — The name of the Book
- `ownerName`: string — The Book owner username
- `pageSize`: integer (int32) — The transactions pagination page size
- `period`: string — `MONTH` | `QUARTER` | `YEAR` — The period slice for balances visualization
- `periodStartMonth`: string — `JANUARY` | `FEBRUARY` | `MARCH` | `APRIL` | `MAY` | `JUNE` | `JULY` | `AUGUST` | `SEPTEMBER` | `OCTOBER` | `NOVEMBER` | `DECEMBER` — The start month when YEAR period set
- `permission`: string — `OWNER` | `EDITOR` | `POSTER` | `RECORDER` | `VIEWER` | `NONE` — The Permission the current user has in the Book
- `properties`: Record<string, string> — The key/value custom properties of the Book
- `timeZone`: string — The time zone of the Book, in IANA format. E.g. America/New_York, Europe/London
- `timeZoneOffset`: integer (int32) — The time zone offset of the Book, in minutes
- `totalTransactions`: integer (int64) — The total transactions posted
- `totalTransactionsCurrentMonth`: integer (int64) — The total transactions posted on current month
- `totalTransactionsCurrentYear`: integer (int64) — The total transactions posted on current year
- `updatedAt`: string — The last update timestamp, in milliseconds
- `visibility`: string — `PUBLIC` | `PRIVATE` — The Visibility of the Book

### BookList

- `items`: Book[] — List items

### BotResponse

- `agentId`: string
- `createdAt`: string
- `message`: string
- `type`: string — `INFO` | `WARNING` | `ERROR`

### Collaborator

- `agentId`: string — The id of agent that created the resource
- `avatarUrl`: string — The Collaborator public avatar url
- `createdAt`: string — The creation timestamp, in milliseconds
- `email`: string — The email of the Collaborator
- `id`: string — The unique id that identifies the Collaborator in the Book
- `permission`: string — `OWNER` | `EDITOR` | `POSTER` | `RECORDER` | `VIEWER` | `NONE` — The permission the Collaborator has in the Book
- `updatedAt`: string — The last update timestamp, in milliseconds

### CollaboratorPayloadCollection

An ordered list of Collaborator

- `items`: Collaborator[]

### Collection

- `agentId`: string — The id of agent that created the resource
- `books`: Book[] — The Books contained in the Collection
- `createdAt`: string — The creation timestamp, in milliseconds
- `id`: string — The unique id of the Collection
- `name`: string — The name of the Collection
- `ownerUsername`: string — The username of the Collection owner
- `permission`: string — `OWNER` | `EDITOR` | `POSTER` | `RECORDER` | `VIEWER` | `NONE` — The permission the current user has in the Collection. E.g. OWNER, EDITOR, NONE
- `updatedAt`: string — The last update timestamp, in milliseconds

### CollectionList

- `items`: Collection[] — List items

### Connection

- `agentId`: string — The id of agent that created the resource
- `createdAt`: string — The creation timestamp, in milliseconds
- `dateAddedMs`: string
- `email`: string
- `id`: string
- `logo`: string
- `name`: string
- `properties`: Record<string, string>
- `type`: string — `APP` | `BANK`
- `updatedAt`: string — The last update timestamp, in milliseconds
- `userId`: string
- `uuid`: string

### ConnectionList

- `items`: Connection[] — List items

### Count

- `day`: integer (int32)
- `fuzzyDate`: integer (int32)
- `month`: integer (int32)
- `total`: integer (int64)
- `year`: integer (int32)

### Counts

- `posted`: Count[]
- `trashed`: Count[]

### Domain

- `id`: string — The unique id of the domain
- `name`: string — The domain name

### Event

- `agent`: Agent
- `book`: Book
- `bookId`: string — The id of the Book associated to the Event
- `botResponses`: BotResponse[] — The list of bot responses associated to the Event
- `createdAt`: string — The creation timestamp, in milliseconds
- `createdOn`: string (date-time) — The creation date time on RFC3339 format
- `data`: EventData
- `id`: string — The unique id that identifies the Event
- `resource`: string — The resource associated to the Event
- `type`: string — `FILE_CREATED` | `FILE_UPDATED` | `FILE_DELETED` | `TRANSACTION_CREATED` | `TRANSACTION_UPDATED` | `TRANSACTION_DELETED` | `TRANSACTION_POSTED` | `TRANSACTION_CHECKED` | `TRANSACTION_UNCHECKED` | `TRANSACTION_RESTORED` | `ACCOUNT_CREATED` | `ACCOUNT_UPDATED` | `ACCOUNT_DELETED` | `QUERY_CREATED` | `QUERY_UPDATED` | `QUERY_DELETED` | `GROUP_CREATED` | `GROUP_UPDATED` | `GROUP_DELETED` | `COMMENT_CREATED` | `COMMENT_DELETED` | `COLLABORATOR_ADDED` | `COLLABORATOR_UPDATED` | `COLLABORATOR_REMOVED` | `INTEGRATION_CREATED` | `INTEGRATION_UPDATED` | `INTEGRATION_DELETED` | `BOOK_CREATED` | `BOOK_AUDITED` | `BOOK_UPDATED` | `BOOK_DELETED` — The type of the Event
- `user`: User

### EventData

- `object`: object
- `previousAttributes`: Record<string, string> — The object previous attributes when updated

### EventList

- `cursor`: string — The cursor, for pagination
- `items`: Event[] — List items

### File

- `agentId`: string — The id of agent that created the resource
- `content`: string — The file content Base64 encoded
- `contentType`: string — The file content type
- `createdAt`: string — The creation timestamp, in milliseconds
- `id`: string — The unique id that identifies the file in the book
- `name`: string — The file name
- `properties`: Record<string, string> — The key/value custom properties of the File
- `size`: integer (int64) — The file size in bytes
- `updatedAt`: string — The last update timestamp, in milliseconds
- `url`: string — The file serving url

### FileList

- `cursor`: string — The cursor, for pagination
- `items`: File[] — List items

### Group

- `agentId`: string — The id of agent that created the resource
- `createdAt`: string — The creation timestamp, in milliseconds
- `credit`: boolean — Whether the group has credit nature
- `hasAccounts`: boolean — Whether the group has any accounts
- `hasGroups`: boolean — Whether the group has any children groups
- `hidden`: boolean — Whether the group is hidden on the transactions main menu
- `id`: string — The unique id that identifies the Group in the Book
- `locked`: boolean — Whether the group is locked by the Book owner
- `mixed`: boolean — Whether the group has mixed types of accounts
- `name`: string — The name of the Group
- `normalizedName`: string — The name of the Group, lowercase, without spaces or special characters
- `parent`: Group
- `permanent`: boolean — Whether the group is permanent
- `properties`: Record<string, string> — The key/value custom properties of the Group
- `type`: string — `ASSET` | `LIABILITY` | `INCOMING` | `OUTGOING` — The type of the accounts in the group. E.g. ASSET, LIABILITY, INCOMING, OUTGOING
- `updatedAt`: string — The last update timestamp, in milliseconds

### GroupBalances

- `accountBalances`: AccountBalances[]
- `balances`: Balance[]
- `credit`: boolean
- `cumulativeBalance`: string
- `cumulativeCredit`: string
- `cumulativeDebit`: string
- `groupBalances`: GroupBalances[]
- `name`: string
- `normalizedName`: string
- `periodBalance`: string
- `periodCredit`: string
- `periodDebit`: string
- `permanent`: boolean
- `properties`: Record<string, string>

### GroupList

- `items`: Group[] — List items

### Integration

- `addedBy`: string
- `agentId`: string — The id of agent that created the resource
- `bookId`: string
- `connectionId`: string
- `createdAt`: string — The creation timestamp, in milliseconds
- `dateAddedMs`: string
- `id`: string
- `lastUpdateMs`: string
- `logo`: string
- `logoDark`: string
- `name`: string
- `normalizedName`: string
- `properties`: Record<string, string>
- `updatedAt`: string — The last update timestamp, in milliseconds
- `userId`: string

### IntegrationList

- `items`: Integration[] — List items

### Query

- `agentId`: string — The id of agent that created the resource
- `createdAt`: string — The creation timestamp, in milliseconds
- `id`: string — The unique id that identifies the saved Query in the Book
- `query`: string — The Query string to be executed
- `title`: string — The title of the saved Query
- `updatedAt`: string — The last update timestamp, in milliseconds

### QueryList

- `items`: Query[] — List items

### Template

- `bookId`: string
- `bookLink`: string
- `category`: string
- `description`: string
- `imageUrl`: string
- `name`: string
- `sheetsLink`: string
- `timesUsed`: integer (int32)

### TemplateList

- `items`: Template[] — List items

### Transaction

- `agentId`: string — The id of agent that created the resource
- `agentLogo`: string — The logo of the agent that created the transaction
- `agentLogoDark`: string — The logo in dark mode, of the agent that created the transaction
- `agentName`: string — The name of the agent that created the transaction
- `amount`: string — The amount on format ####.##
- `checked`: boolean — Whether the transaction is checked
- `createdAt`: string — The creation timestamp, in milliseconds
- `createdBy`: string — The actor username that created the transaction
- `creditAccount`: Account
- `date`: string — The date on ISO format yyyy-MM-dd
- `dateFormatted`: string — The date on format of the Book
- `dateValue`: integer (int32) — The date number representation on format YYYYMMDD
- `debitAccount`: Account
- `description`: string — The transaction description
- `draft`: boolean — Whether the transaction is a draft
- `files`: File[] — The files attached to the transaction
- `id`: string — The unique id that identifies the transaction in the book
- `posted`: boolean — Whether the transaction is already posted on accounts, otherwise is a draft
- `properties`: Record<string, string> — The key/value custom properties of the Transaction
- `remoteIds`: string[] — The transaction remote ids, to avoid duplication
- `tags`: string[] — The transaction #hashtags
- `trashed`: boolean — Whether the transaction is trashed
- `updatedAt`: string — The last update timestamp, in milliseconds
- `urls`: string[] — The transaction urls

### TransactionList

- `account`: string — The account id when filtering by a single account. E.g. account='Bank'
- `cursor`: string — The cursor, for pagination
- `items`: Transaction[] — List items

### TransactionOperation

- `accounts`: Account[] — The affected accounts
- `transaction`: Transaction

### Url

- `url`: string

### User

- `avatarUrl`: string — The user public avatar url
- `bankConnections`: boolean — True if user already had any bank connection
- `billingAdminEmail`: string — The billing admin email for this user's billing account
- `billingEnabled`: boolean — True if billing is enabled for the user
- `daysLeftInTrial`: integer (int32) — How many days left in trial
- `domain`: Domain
- `email`: string — The user email
- `free`: boolean — True if user is in the free plan
- `fullName`: string — The user full name
- `givenName`: string — The user given name
- `hash`: string — The user hash
- `hostedDomain`: string — The user hosted domain
- `id`: string — The user unique id
- `name`: string — The user display name
- `plan`: string — The user plan
- `planCycle`: string — `MONTHLY` | `YEARLY` — The user plan billing cycle
- `planOverdue`: boolean — True if subscription payment is overdue
- `startedTrial`: boolean — True if user started trial
- `totalTransactionsThisMonth`: integer (int64) — User-level total transactions this month
- `totalTransactionsThisYear`: integer (int64) — User-level total transactions this year
- `username`: string — The Bkper username of the user
