# Overview > Calendarpit is a local Google Calendar API v3 and OAuth server for development and tests. Run it with Docker or Homebrew, with fixtures, webhooks, and an admin UI. Source: https://calendarpit.dev/ ## Why Calendarpit Building apps and AI agents that use Google Calendar means setting up OAuth and preparing test data. With a live calendar, repeating a test from the same state can be hard. Calendarpit lets you test locally with fixtures and no Google credentials. - Needs a Google account, Cloud project, and OAuth setup. - Depends on internet access and shared API quotas. - Shared calendar data changes between test runs. - Sign in as a local test user with no real credentials. - Runs on 127.0.0.1 in one process with no network access. - Seed data from fixtures and reset state between tests. ## How it works ### Start Calendarpit One process serves the API, local OAuth, and the admin UI on `http://127.0.0.1:4173`. ```sh docker run --rm -p 127.0.0.1:4173:4173 ghcr.io/iktakahiro/calendarpit:latest ``` ```sh brew install iktakahiro/tap/calendarpit calendarpit serve ``` ### Point your app to Calendarpit Keep your Google SDK and override its OAuth and API endpoints. For example, with `@googleapis/calendar` and `google-auth-library`: ```ts const origin = 'http://127.0.0.1:4173'; const auth = new OAuth2Client({ clientId: 'sample-app', clientSecret: 'local-sample-secret', redirectUri: 'http://127.0.0.1:4175/callback', endpoints: { oauth2AuthBaseUrl: `${origin}/oauth/authorize`, oauth2TokenUrl: `${origin}/oauth/token`, }, }); const api = calendar({ version: 'v3', auth, rootUrl: origin }); ``` For every available endpoint, see [Connect your app](https://calendarpit.dev/connect.md). To set up the SDK in Python, Go, or another language, see [SDK examples](https://calendarpit.dev/sdks.md). ### Test with fixtures Reset to the startup fixture before each test, and inspect requests in the admin UI. ```sh curl -X POST http://127.0.0.1:4173/__calendarpit/reset \ -H "Content-Type: application/json" \ -d '{}' ``` ## Inside the admin UI The admin UI is served on the same origin as the API (`http://127.0.0.1:4173/`). Open it in the browser while your app runs to check events written through the Calendar API, inspect requests and webhook deliveries, and edit test data between runs. ## What Calendarpit includes } /> } /> } /> } /> } /> } /> ## Start building calendar apps with Calendarpit Calendarpit is built for local development and automated tests only. It implements a defined subset of the Google Calendar API v3 on loopback.
Quick start GitHub
# Quick start > Start Calendarpit without cloning a repository and connect your application. Source: https://calendarpit.dev/quick-start/ ## Start Calendarpit Start with Docker: ```sh docker run --rm \ -p 127.0.0.1:4173:4173 \ -v calendarpit-data:/data \ ghcr.io/iktakahiro/calendarpit:latest ``` Or install and start with Homebrew: ```sh brew install iktakahiro/tap/calendarpit calendarpit serve ``` Both commands start the API, the local OAuth server, and the admin UI on the same origin. You do not need any of the following: - A Google account or Google Cloud project - An external database - A `.env` file - Provider credentials For Compose and standalone downloads, see [Installation](https://calendarpit.dev/installation.md). ## Open the admin UI Open `http://127.0.0.1:4173`. Changes made through the API appear there automatically. [Admin UI](https://calendarpit.dev/admin-ui.md) explains each screen. The built-in fixture includes: - Test users `alex` and `sam` - Three calendars - A planning event on `2026-10-19` ### Where data is stored - **CLI**: `.calendarpit/calendarpit.sqlite` under your current directory. - **Docker**: the mounted volume. For disposable tests, use in-memory storage: - **CLI**: pass `--database :memory:`. - **Docker**: pass `-e CALENDARPIT_DATABASE=:memory:`. See [Storage and restarts](https://calendarpit.dev/storage.md). ## Connect your app 1. Follow [Connect your app](https://calendarpit.dev/connect.md) to point your SDK and OAuth flow at Calendarpit. 2. Use [Fixtures](https://calendarpit.dev/fixtures.md) to register local client credentials and exact callback URIs. The built-in `sample-app` / `local-sample-secret` credentials are public test values. Their callback is `http://127.0.0.1:4175/callback`. ### Optional source sample The source sample walks through approval, event creation, FreeBusy, watch delivery, and revocation. It is separate from the distributed server. For setup, see the [development guide](https://github.com/iktakahiro/calendarpit/blob/main/docs/development.md). ## Give the docs to a coding agent Every documentation page is also published as Markdown for AI coding agents: - [llms.txt](https://calendarpit.dev/llms.txt): an index of every page, linking to its Markdown version. - [llms-full.txt](https://calendarpit.dev/llms-full.txt): every page in one file. - Add `.md` to a page path to get that page alone, for example `https://calendarpit.dev/quick-start.md`. ## Next steps - [Run and configure](https://calendarpit.dev/running.md): ports, fixtures, and environment variables. - [Test control API](https://calendarpit.dev/test-control.md): reset state and drain deliveries between tests. - [Scope and limitations](https://calendarpit.dev/scope.md): implemented compatibility and explicit exclusions. # Installation > Install Calendarpit with Docker Compose, Homebrew, or a standalone executable. Source: https://calendarpit.dev/installation/ Calendarpit is available through Docker, Homebrew, and standalone downloads. See [GitHub Releases](https://github.com/iktakahiro/calendarpit/releases/latest) for the current version. - **Docker Compose**: Use it for a container environment. - **Homebrew**: Use it for a local CLI. Both include the API, OAuth server, admin UI, and SQLite. Neither requires Bun, Node.js, Google credentials, or a separate database. Calendarpit is not distributed through npm. ## Docker ```sh docker run --rm \ -p 127.0.0.1:4173:4173 \ -v calendarpit-data:/data \ ghcr.io/iktakahiro/calendarpit:latest ``` The image: - Targets Linux amd64 and arm64, including Docker on Apple Silicon. - Runs as a non-root user. - Persists SQLite in `/data/calendarpit.sqlite`. - Is tagged `latest` and with each release version. Pin a version tag when CI needs a fixed version. Keep the named volume to retain data across container recreation. For disposable tests, use `-e CALENDARPIT_DATABASE=:memory:`. The host port is published only on loopback. Inside the container, Calendarpit explicitly binds `0.0.0.0`. ## Docker Compose Add this service and volume to your `compose.yaml`: ```yaml services: calendarpit: image: ghcr.io/iktakahiro/calendarpit:latest ports: - '127.0.0.1:4173:4173' volumes: - calendarpit-data:/data volumes: calendarpit-data: ``` ```sh docker compose up -d calendarpit docker compose logs calendarpit docker compose down ``` `down` preserves the volume. `down -v` deletes its saved data. The image includes a health check. To wait for Calendarpit in another service, use `depends_on: { calendarpit: { condition: service_healthy } }`. If you override the container port, set `CALENDARPIT_PORT` as well as the port mapping. The health check then uses the same port. ### Addresses depend on who makes the request | Request origin | Calendarpit address | | ---------------------------------- | ------------------------- | | Browser or app running on the host | `http://127.0.0.1:4173` | | App in the same Compose network | `http://calendarpit:4173` | - Keep the browser's OAuth authorization URL on the host-accessible address. - A containerized backend uses the Compose address for token exchange and Calendar API requests. - The OAuth `redirect_uri` must exactly match the fixture's registered URI. It must also be accessible to the browser. ### Webhook receivers Webhook addresses are resolved by Calendarpit: - **Receiver service in Compose**: For a service named `app`, allow `CALENDARPIT_WATCH_HOSTS=app` and register `http://app:/`. - **Process on the host**: Docker Desktop provides `host.docker.internal`. On Linux Docker Engine, add `extra_hosts: ["host.docker.internal:host-gateway"]`. Allow that hostname with `CALENDARPIT_WATCH_HOSTS`. The receiving process must listen on an address reachable from the container. See [Watch notifications](https://calendarpit.dev/watch.md). ## Homebrew ```sh brew install iktakahiro/tap/calendarpit calendarpit serve ``` The tap installs a standalone executable for macOS or Linux. Bun and Node.js are not required. Run it in your project's directory so the default SQLite path belongs to that project. To update: ```sh brew update brew upgrade iktakahiro/tap/calendarpit ``` ## Standalone download From [GitHub Releases](https://github.com/iktakahiro/calendarpit/releases), download the archive that matches your OS and CPU, together with `SHA256SUMS`. Verify the archive checksum before you extract it. For example, on Apple Silicon: ```sh shasum -a 256 calendarpit-0.9.5-darwin-arm64.tar.gz tar -xzf calendarpit-0.9.5-darwin-arm64.tar.gz ./bin/calendarpit serve ``` Compare the printed hash with the matching line in `SHA256SUMS`. Windows archives contain `bin/calendarpit.exe`. No Bun, Node.js, or asset directory is required. ## Updates and storage When you choose to upgrade: - **Docker**: Update the exact image tag. - **Homebrew**: Use `brew upgrade`. Before upgrading, stop Calendarpit and back up its SQLite directory or Docker volume. > [!WARNING] > Never run two instances against the same database file. See [Storage and restarts](https://calendarpit.dev/storage.md) and [Run and configure](https://calendarpit.dev/running.md). # Run and configure > Ways to start Calendarpit, command-line options, environment variables, and Docker setup. Source: https://calendarpit.dev/running/ Calendarpit serves the API, OAuth, and admin UI from one origin. The commands below use the packaged distribution. You need no source checkout or build. See [Installation](https://calendarpit.dev/installation.md) for prerequisites and supported platforms. ## Ways to run Calendarpit ### Docker and Compose ```sh docker run --rm \ -p 127.0.0.1:4173:4173 \ -v calendarpit-data:/data \ ghcr.io/iktakahiro/calendarpit:latest ``` The container has these defaults: - It runs as a non-root user. - It sets `CALENDARPIT_HOST=0.0.0.0` and `CALENDARPIT_PORT=4173`. - It stores the SQLite database at `/data/calendarpit.sqlite`. The published host port stays on loopback. Add environment variables with `-e` before the image name. Add CLI flags after it: ```sh docker run --rm -p 127.0.0.1:4173:4173 \ ghcr.io/iktakahiro/calendarpit:latest serve --database :memory: ``` Related pages: - [Installation](https://calendarpit.dev/installation.md): a Compose service, health checks, and host/container addresses. - [Fixtures](https://calendarpit.dev/fixtures.md): mount a startup configuration. - [Development guide](https://github.com/iktakahiro/calendarpit/blob/main/docs/development.md): source development instructions. ### Installed CLI Install with Homebrew or place a standalone executable on your `PATH`. Then run it from your project directory. See [Installation](https://calendarpit.dev/installation.md) for setup. ```sh calendarpit serve --port 4173 calendarpit serve --port 0 --database :memory: ``` These are alternative startup commands: - Run one server per database file. - Port `0` lets the OS choose an available port. - Read the actual URLs in the startup output: ```text Calendarpit data: :memory: Calendarpit v Data :memory: Admin http://127.0.0.1:38425/ API http://127.0.0.1:38425/calendar/v3 Health http://127.0.0.1:38425/__calendarpit/health ``` The packaged executable includes the server, the admin UI assets (including `favicon.svg`), and the Bun runtime. You need no separate Node.js or Bun installation. Stop the server with Ctrl+C. ## Command-line options and environment variables The CLI syntax is `calendarpit [serve] [options]`. The `serve` subcommand is optional. The CLI prints an error to `stderr` and exits with code `1` on any of these: - an unknown command - an unknown flag - an invalid option value Command-line flags take precedence over environment variables. | CLI option | Environment variable | Default | Description | | --------------------- | ------------------------ | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `--host ` | `CALENDARPIT_HOST` | `127.0.0.1` | Bind address. Non-loopback addresses (`0.0.0.0`, `::`) must be set explicitly. | | `-p`, `--port ` | `CALENDARPIT_PORT` | `4173` | Listen port (`0`–`65535`). Use `0` to let the OS choose a free port. | | `--database ` | `CALENDARPIT_DATABASE` | `.calendarpit/calendarpit.sqlite` | SQLite database file path, or `:memory:` for a disposable in-memory session. See [Storage and restarts](https://calendarpit.dev/storage.md). | | `--config ` | `CALENDARPIT_CONFIG` | Built-in fixture | Path to a JSON startup fixture. See [Fixtures](https://calendarpit.dev/fixtures.md). | | `--rate-limit ` | `CALENDARPIT_RATE_LIMIT` | `off` | Calendar API rate-limit simulation: `off`, `production`, or `error-test`. See [Calendar API rate limits](#calendar-api-rate-limits). | | `-h`, `--help` | — | — | Print help and exit. | | `-v`, `--version` | — | — | Print the version and exit. | Option details: - **`--port 0`**: The assigned port appears in the startup output. - **Port `4175`**: Avoid it if you also run the reference sample app. - **`--config`**: The file must exist and contain valid JSON. It seeds a new database or a `:memory:` session. > [!WARNING] > > `--config` is silently ignored when Calendarpit opens an existing SQLite file. > ### Additional environment variables | Environment variable | Default | Description | | ------------------------- | ------------- | --------------------------------------------------------------------------------------------------- | | `CALENDARPIT_WATCH_HOSTS` | Loopback only | Comma-separated extra hostnames allowed as `events.watch` and `calendarList.watch` webhook targets. | About `CALENDARPIT_WATCH_HOSTS`: - Example: `host.docker.internal` when running in Docker. - It is an environment variable only. There is no CLI flag. - See [Watch notifications](https://calendarpit.dev/watch.md). ### Calendar API rate limits Calendarpit can answer Calendar API requests with the same quota errors Google returns, so an app can exercise that path locally. The default is `off`: requests are not limited. Set the mode with `--rate-limit` or `CALENDARPIT_RATE_LIMIT`, or in **Settings → Developer**. Accepted values are `off`, `production`, and `error-test`. Any other value is rejected at startup. The mode is saved in the workspace and kept across SQLite restarts. On startup, an explicit flag or environment variable replaces the saved mode and is written back. When neither is set, Calendarpit keeps the saved mode. A snapshot without a mode, or with a saved value that is not one of these modes, loads as `off`. Reset and fixture load keep the mode and clear the in-memory counters. Counters also clear when the mode changes, and they are not restored after a process restart. Every `/calendar/v3` request with a valid access token counts, including `events`, `calendarList`, `freeBusy`, and `watch`. A request without a valid access token (missing, unknown, expired, or revoked) is not counted and gets the usual `401`. OAuth, `/userinfo`, and `/__calendarpit` do not count. `quotaUser` or `x-goog-quota-user` (1–40 characters) selects the per-user bucket and overrides the access token's user. Otherwise the token's user is used. `primary` resolves to the token user's primary calendar. A request that exceeds a limit is rejected and is not counted. `production` roughly matches the Calendar API quotas Google publishes for Cloud projects created on or after 1 May 2026 ([Usage limits](https://developers.google.com/workspace/calendar/api/guides/quota)). It is approximate, not identical to Google's behavior: | Limit | `production` | Error | | ------------------------------ | --------------- | --------------------------- | | Per minute per user | 600 requests | `403 userRateLimitExceeded` | | Per minute per project | 10,000 requests | `429 rateLimitExceeded` | | Writes per minute per calendar | 60 requests | `403 rateLimitExceeded` | Quotas use a sliding minute. The published 1,000,000 requests per day is a billing threshold, not a rejection, so `production` does not fail at that number. Google also says writes to one calendar in quick succession can be limited, without a published figure. `production` uses 60 writes per minute per calendar for that limit. This number is Calendarpit's estimate. `error-test` uses very low limits, so the same `403` and `429` errors happen quickly. Use it to check retry and backoff handling: | Limit | `error-test` | Error | | ------------------------------ | ------------ | --------------------------- | | Per minute per user | 4 requests | `403 userRateLimitExceeded` | | Per minute per project | 12 requests | `429 rateLimitExceeded` | | Writes per minute per calendar | 2 requests | `403 rateLimitExceeded` | | Per day per user | 20 requests | `403 quotaExceeded` | Google uses `quotaExceeded` for per-user Calendar usage limits. The daily limit always counts the access token's user, even when `quotaUser` is sent. The daily limit is checked first, then per-calendar writes, then the per-user per-minute limit, then the per-project per-minute limit. Error bodies use Google's `usageLimits` domain ([Handle API errors](https://developers.google.com/workspace/calendar/api/guides/errors)): ```json { "error": { "code": 403, "message": "User Rate Limit Exceeded", "errors": [ { "domain": "usageLimits", "reason": "userRateLimitExceeded", "message": "User Rate Limit Exceeded" } ] } } ``` `rateLimitExceeded` uses the message `Rate Limit Exceeded`. `quotaExceeded` uses `Calendar usage limits exceeded.` Calendarpit adds `Retry-After` to these responses as a hint. Google's documentation does not specify this header, so clients should still use exponential backoff. ### Loopback binding and working directory **Loopback by default.** Calendarpit binds to `127.0.0.1` unless you pass `--host` or `CALENDARPIT_HOST`. > [!WARNING] > > The admin UI and [test control API](https://calendarpit.dev/test-control.md) have no authentication. Binding to `0.0.0.0` exposes them to other machines on your network. > **Relative paths.** Path resolution depends on how you run Calendarpit: - **Homebrew and standalone executables**: Paths in `--database` and `--config` (or their environment variables) resolve from the directory where you start Calendarpit. Run it from your project directory or use absolute paths. - **Docker**: Paths are inside the container. Mount host files before referencing them. See [Troubleshooting](https://calendarpit.dev/troubleshooting.md) for common startup errors. ## Admin UI The admin UI is served at the root of the same origin as the API. The default URL is `http://127.0.0.1:4173/`. It shows the workspace, request history, and webhook deliveries, and lets you edit test data. See [Admin UI](https://calendarpit.dev/admin-ui.md). # Admin UI > Use the Calendarpit admin UI in the browser to inspect events written through the Calendar API, trace requests and webhook deliveries, revoke OAuth connections, and edit test data. Source: https://calendarpit.dev/admin-ui/ The admin UI is a browser interface for the local Calendarpit workspace. Keep it open while your app runs to inspect events your app creates or updates through the Calendar API, examine every request and webhook delivery, and edit test data between runs. It is served at the root of the same origin as the API (`http://127.0.0.1:4173/` by default) and requires no sign-in. ## Layout The left rail controls the context for every screen: - **Live**: The admin UI subscribes to `GET /__calendarpit/changes` and reloads the state and request history as soon as the server saves a change. Changes your app makes through the Calendar API appear immediately, without a page reload. It also polls every 30 seconds as a fallback. The indicator switches to **Disconnected** if the server stops responding, and the UI reconnects on its own. - **Test user** and **Calendars**: Select which test user and calendar the screens display. The selection is stored in the URL (`?user=&calendar=`), so you can bookmark or share it. - **Sections**: **Schedule** is at the top. **Activity** groups what your app did: **API history**, **Watch**, and **Connections**. **Workspace** groups the test data your app runs against: **Users**, **Calendars**, and **Settings**. The badge counts show recorded history entries, active watch channels, and active OAuth connections. - **Storage**: The footer shows the storage mode (`SQLite` or `In-memory`) and the server address. See [Storage and restarts](https://calendarpit.dev/storage.md). Each screen header has a **Refresh** button that reloads the workspace state immediately. | Route | Screen | Use it to | | -------------- | --------------- | ------------------------------------------------------------------------------------------------------------------ | | `/` | **Schedule** | View, create, edit, and delete events in the selected calendar. | | `/history` | **API history** | Inspect and clear recent Calendar API and OAuth requests and responses. | | `/watch` | **Watch** | Inspect active watch channels and webhook deliveries (read-only). | | `/connections` | **Connections** | Inspect and revoke OAuth authorizations (grants). | | `/users` | **Users** | Create, edit, and delete test users. | | `/calendars` | **Calendars** | Create and configure the selected user's calendars. | | `/settings` | **Settings** | Theme, language, Calendar API rate limits, storage mode, fixtures, workspace reset, state JSON, and OAuth clients. | > [!WARNING] > > The admin UI has no authentication. Calendarpit binds to `127.0.0.1` by default. Binding to another address exposes the admin UI to other machines. See [Loopback binding](https://calendarpit.dev/running.md#loopback-binding-and-working-directory). > ## Command palette and keyboard shortcuts Press ⌘ K on macOS or Ctrl K elsewhere, or select **Commands** in the section header, to open the command palette. Type to filter, use the arrow keys to move, and press Enter to run a command. ? also opens the palette, which shows each command's shortcut. - Go to any section, create an event, or change the theme. - The palette is in English whatever the interface language. Section names also match their Japanese labels, such as `ユーザー`. - Type a test user's name or email, or a calendar's name, to switch to it. **Switch user…** and **Switch calendar…** list them all. - **Go to date…** accepts `2026-10-21`, `today`, `tomorrow`, `yesterday`, or an offset from the shown date such as `+3`, `-1`, or `+1w`. On a palette page such as **Go to date…**, press Backspace in the empty field to return to every command. | Shortcut | Action | | -------------------------------------------------------- | --------------------------------------------------- | | ⌘ K / Ctrl K | Open or close the command palette | | ? | Open the command palette | | ⌘ , / Ctrl , | Open **Settings** | | C | Create an event in the selected calendar | | T | Show today | | P / N | Show the previous or next day, or week in week view | | D / W | Switch to the day or week view | | G | Go to a date | T, P, N, D, W, and G work on **Schedule**. The others work on every screen. Single-key shortcuts do nothing while you type in a field or while the event editor or a dialog has focus, so typing an event title never triggers them. ## Check the events your app writes **Schedule** shows the events in the selected calendar, including events your app creates or updates in Calendarpit through the Calendar API. To create or configure the calendars themselves, use [Calendars](#manage-test-users-and-calendars). The default date is `2026-10-19`, the date of the built-in fixture's planning event. - **Day** shows a 24-hour timeline and the event list for that day. **Week** shows a 7-day time grid from Sunday to Saturday. - Use the arrows, the date picker, and **Today** to move between dates. The URL keeps both the date and the view (`?date=2026-10-19&view=week`). - Times are displayed in the selected calendar's time zone. End times are exclusive. Busy events are solid; free (transparent) events are hatched or outlined and do not block availability in `freeBusy` queries. - A recurring series appears once, at its first occurrence, and is not expanded in the schedule view. Stored exception instances appear on their own dates. ### Create and edit events Select an existing event to open it in the editor, or select **New event**. In week view, select an empty time slot to start a new event at that time. The editor edits the summary, all-day toggle, start and end times, availability (busy or free), location, description, and extended properties (JSON). > [!WARNING] > > Saving an event in the editor overwrites it with only the fields shown in the form: > > - Attendees, colors, and other fields set through the Calendar API are removed. > - A recurring event loses its `recurrence` rule and becomes a single event. > - Custom reminders reset to the default (`reminders: { useDefault: true }`). > > Use the Calendar API to edit events that rely on those fields. See [Scope and limitations](https://calendarpit.dev/scope.md). > ## Manage test users and calendars Test users are local identities with no password. When your app starts the OAuth flow, you pick a test user on the [local consent page](https://calendarpit.dev/oauth.md) to sign in as that user. **Users** lists every test user with their email address and calendar count. Select a user to edit their display name and email address. - Deleting a user also deletes all of their calendars and events. - Deleting a user also revokes their OAuth connections, invalidating their tokens and stopping their watch channels. **Calendars** manages the calendars owned by the selected user (not the events inside them). Create, rename, and delete calendars, set each calendar's IANA time zone (`Asia/Tokyo` by default), and choose which calendar is primary. - The primary calendar is the calendar that the special `primary` calendar ID resolves to in the Calendar API. - Changing a calendar's time zone invalidates incremental sync tokens that were issued without an explicit `timeZone` parameter. See [Incremental sync](https://calendarpit.dev/sync.md). ## Trace your app's requests **API history** records the latest 200 Calendar API and OAuth requests your app sent to Calendarpit, newest first. Use it to inspect the exact request your SDK or HTTP client sent and the response Calendarpit returned. - Each row shows the HTTP status, method, path, area (such as `calendar` or `oauth`), and timestamp. - Select a row to inspect the request and response headers and bodies. Select **Copy** to copy a payload as JSON. - Credentials, such as the `Authorization` header, access and refresh tokens, client secrets, and authorization codes, are masked as `[REDACTED]`. - Filter by method, path, or status, or select **Errors** to show only responses with status `400` or higher. - **Clear history** deletes all recorded entries. See [Troubleshooting](https://calendarpit.dev/troubleshooting.md) for common error responses and how to fix them. ## Inspect watch notifications **Watch** is a read-only view of push notifications across all calendars. - **Watch channels** lists active channels with their target calendar (or `CalendarList`), your app's callback URL, and the channel expiration time. - **Delivery log** lists the latest 200 webhook deliveries with the channel ID and message number, the resource state (`sync` or `exists`), the attempt count, the timestamp, and the delivery status (`queued`, `delivered`, `failed`, or `cancelled`) along with the last HTTP status your endpoint returned. In automated tests, call `POST /__calendarpit/deliveries/drain` to wait for in-flight deliveries to finish instead of polling this screen. See [Watch notifications](https://calendarpit.dev/watch.md). ## Test reconnection In **Connections**, each connection is an OAuth authorization (grant), created when a test user approves your app on the consent page. The screen shows which test user authorized which OAuth client, the granted scopes, and when. Access and refresh tokens are issued against this grant. Select **Revoke** on an active connection to test how your app handles token revocation. Revoking a connection deletes its access tokens, refresh tokens, and authorization codes, and stops any watch channels created under that grant: - Subsequent Calendar API requests with the old access token fail with `401 authError`. - Token refresh requests at `POST /oauth/token` with the old refresh token fail with `400 invalid_grant`. Because both tokens stop working, your app must send the user through the [OAuth flow](https://calendarpit.dev/oauth.md) again to obtain a new grant. ## Prepare test data **Settings** has four tabs. ### Appearance - **Theme**: choose **Light**, **Dark**, or **System**. **System** follows your device's color scheme and uses **Dark** when the device does not report one. - **Language**: choose **English**, **日本語** (Japanese), or **System**. **System** follows your browser's preferred languages and falls back to English. Both settings start as **System**, and nothing is stored until you choose. Your choice is stored in a cookie in your browser for a year, so the next page load renders in the chosen theme and language. The language applies to interface text only: navigation, headings, buttons, form labels, messages, and dates. Protocol data stays as Calendarpit sends and receives it: paths, HTTP methods and statuses, JSON, scopes, resource states, and IDs. The [local consent page](https://calendarpit.dev/oauth.md) is always in English. ### Developer **Calendar API rate limits** sets how `/calendar/v3` requests are limited: - **Off** (`off`) does not limit requests. This is the default. - **Production** (`production`) uses limits that roughly match Google's published quotas (approximate, not identical). The per-calendar write limit is Calendarpit's estimate, because Google does not publish one. - **Error testing** (`error-test`) uses very low limits so `403` and `429` quota errors happen quickly. Use it to check retry and backoff handling. The mode is saved with the workspace and persists across SQLite restarts. Reset and fixture load keep the mode and clear the current counters. Quota values, error bodies, and the `--rate-limit` / `CALENDARPIT_RATE_LIMIT` startup options are in [Run and configure](https://calendarpit.dev/running.md#calendar-api-rate-limits). ### Test data - **Storage** shows the active storage mode and the SQLite file path (or `:memory:`). - **Fixtures & reset** loads a [fixture](https://calendarpit.dev/fixtures.md). Paste JSON or select **Open JSON file…**, then select **Load fixture**. Loading a fixture replaces all users, calendars, events, and OAuth clients, and clears all OAuth connections, request history, and watch channels, without changing the startup reset baseline. - **Reset workspace** restores the startup fixture and clears all OAuth connections, request history, and watch channels. - **Current state** displays the current workspace data as JSON, with credentials omitted. Both **Load fixture** and **Reset workspace** ask for confirmation before running. Automated tests can perform the same operations through the [Test control API](https://calendarpit.dev/test-control.md). ### OAuth clients Add, edit, or delete OAuth clients without reloading the fixture—for example, to add a redirect URI or change a client secret. Adding or editing a client keeps users, calendars, events, and existing OAuth connections intact; deleting a client revokes its connections. See [Connect your app](https://calendarpit.dev/connect.md). ## Fonts and network access > [!NOTE] > > The admin UI loads the Roboto Mono font from Google Fonts (`fonts.googleapis.com` and `fonts.gstatic.com`). It falls back to system fonts when offline. Calendar API and OAuth operations never contact Google and need no internet access. > # Connect your app > Point your app's OAuth and Google Calendar SDK clients at Calendarpit while keeping production Google settings switchable. Source: https://calendarpit.dev/connect/ ## Add a provider switch Your app must choose Calendarpit explicitly. Starting Calendarpit does not intercept network traffic to Google. To use Calendarpit in local development or automated tests, add a provider switch. Put it in the code that creates your OAuth client and Google Calendar SDK client. Environment variable names such as `CALENDARPIT_URL` are conventions in your app. Google SDKs do not read `CALENDARPIT_URL` automatically. Your initialization code must read your configuration and pass the local URLs to the SDK. Keep your provider credentials separate: - Use Calendarpit access tokens and refresh tokens only with the local provider. - Keep real Google client secrets and tokens in your Google configuration. > [!WARNING] > > Never put real Google credentials in a fixture. > ## Override every provider endpoint Override all five endpoints together. Changing only the Calendar API URL is not enough. If OAuth stays on its default endpoints, your app still sends these requests to Google: - Browser redirects - Token exchanges - Token refreshes | Purpose | Local endpoint | | ------------------------- | --------------------------------------- | | Authorization screen | `http://127.0.0.1:4173/oauth/authorize` | | Code exchange and refresh | `http://127.0.0.1:4173/oauth/token` | | User profile | `http://127.0.0.1:4173/userinfo` | | Calendar API root | `http://127.0.0.1:4173/` | | Token revocation | `http://127.0.0.1:4173/oauth/revoke` | ### Calendar API URL format by SDK Each SDK expects a different form of the Calendar API URL: - **JavaScript** (`@googleapis/calendar`): Appends `/calendar/v3/...` to `rootUrl`. Do not include `/calendar/v3` twice. - **Python, Go, and .NET**: Expect the full service URL, including `/calendar/v3/`. - **Kotlin** (Java client library): Sets the root URL and service path separately. - **PHP** (`google/apiclient`): Takes the origin as the `$rootUrl` constructor argument and appends `calendar/v3/`. See [SDK examples](https://calendarpit.dev/sdks.md). ### Watch callback address A watch callback address points in the opposite direction: from Calendarpit to your app. An example is `http://127.0.0.1:4175/notifications`. By default, Calendarpit allows only loopback callback hosts (`127.0.0.1`, `localhost`, `[::1]`). To allow extra hosts, list them in `CALENDARPIT_WATCH_HOSTS`. See [Watch notifications](https://calendarpit.dev/watch.md). ## Register a test OAuth client Register your app in the `clients` array of your fixture. Calendarpit checks these values: - **Authorization endpoint**: `client_id` and `redirect_uri`. - **`/oauth/token`**: `client_id` and `client_secret`, plus `redirect_uri` for code exchange. ```json { "clients": [ { "id": "my-app", "secret": "local-test-secret", "redirectUris": ["http://127.0.0.1:3000/auth/google/callback"] } ] } ``` Two fields need care: - **`redirectUris`** must contain your app's exact callback URL. Calendarpit matches `redirect_uri` by exact string equality. It does not apply port wildcards or trailing-slash normalization. - **`secret`** is required. Your app must send it as `client_secret` (or HTTP Basic) on every `/oauth/token` request, including PKCE flows. ### How the fixture is applied A fixture replaces the whole workspace. Include `users` and `calendars` alongside `clients`. If you use the sample app, keep the `sample-app` entry. When the fixture takes effect depends on how you pass it: - **Startup fixture**: Applies only to a new database or a `:memory:` session. - **Running or persisted workspace**: Load the fixture with `POST /__calendarpit/fixtures`, or start with a new database. > [!NOTE] > > A reset restores the startup fixture, not a fixture loaded through the API. To keep your client across resets, do one of the following: > > - Pass the fixture at startup (`--config` or `CALENDARPIT_CONFIG`) with a new database or `:memory:` session. > - Reload the fixture after each reset. > See [Fixtures](https://calendarpit.dev/fixtures.md). ### Edit a client without reloading the fixture To change a callback URL or rotate a secret in a running workspace, open **Settings → OAuth clients** in the admin UI. You can add, edit, and delete clients there. Users, calendars, events, and connections stay as they are. Scripts can do the same with the [Test control API](https://calendarpit.dev/test-control.md): ```bash curl -X PATCH http://127.0.0.1:4173/__calendarpit/clients/my-app \ -H 'Content-Type: application/json' \ -d '{"redirectUris": ["http://127.0.0.1:3000/auth/google/callback"]}' ``` These edits are saved like other admin changes. A reset still restores the startup fixture. ### Built-in client The built-in default fixture registers one OAuth client for local testing: - Client ID: `sample-app` - Client secret: `local-sample-secret` (a public local test value) - Redirect URI: `http://127.0.0.1:4175/callback` For the full authorization code, refresh, `/userinfo`, and revocation flow, see [Local OAuth](https://calendarpit.dev/oauth.md). ## JavaScript OAuth and Calendar client With `@googleapis/calendar` and `google-auth-library`, configure two settings: - `endpoints` on `OAuth2Client` - `rootUrl` on the Calendar client ```ts import { calendar } from '@googleapis/calendar'; import { OAuth2Client } from 'google-auth-library'; const origin = 'http://127.0.0.1:4173'; const auth = new OAuth2Client({ clientId: 'sample-app', clientSecret: 'local-sample-secret', redirectUri: 'http://127.0.0.1:4175/callback', endpoints: { oauth2AuthBaseUrl: `${origin}/oauth/authorize`, oauth2TokenUrl: `${origin}/oauth/token`, oauth2RevokeUrl: `${origin}/oauth/revoke`, }, }); const api = calendar({ version: 'v3', auth, rootUrl: origin }); // After the callback: auth.setCredentials((await auth.getToken(code)).tokens) const profile = await auth.request({ url: `${origin}/userinfo` }); const calendars = await api.calendarList.list(); const { data } = await api.freebusy.query({ requestBody: { timeMin: '2026-10-19T00:00:00+09:00', timeMax: '2026-10-20T00:00:00+09:00', items: [{ id: 'primary' }], }, }); console.log(data.calendars?.primary?.busy); ``` ### Scopes Authorize the grant with scopes that cover all three calls in this example. For example: `auth.generateAuthUrl({ access_type: 'offline', scope: ['https://www.googleapis.com/auth/calendar', 'email', 'profile'] })`. - **`calendarList.list`** requires `calendar`, `calendar.readonly`, `calendar.calendarlist`, or `calendar.calendarlist.readonly`. Narrower scopes such as `calendar.events` or `calendar.freebusy` do not cover it. - **`/userinfo`** requires `openid`, `email`, `profile`, or a `userinfo.*` scope. It returns `email` only with an email scope, and `name` only with a profile scope. - **Refresh tokens** are issued only with `access_type=offline`. See [Local OAuth](https://calendarpit.dev/oauth.md) for the full scope list. ### Token refresh and unsupported helpers After you call `auth.setCredentials`, token refresh requests from `OAuth2Client` also use the local `oauth2TokenUrl`. Other `OAuth2Client` helpers, such as `getTokenInfo` and `verifyIdToken`, still call Google. This changes only if you also override `tokenInfoUrl` and the certificate URLs, as the sample app does. > [!WARNING] > > Calendarpit does not support these endpoints or issue ID tokens. Do not call those helpers against the local provider. > For Python, Go, and other languages, see [SDK examples](https://calendarpit.dev/sdks.md). ## Reference sample app The repository includes an optional sample app using `@googleapis/calendar` and `google-auth-library`. It is not bundled with Calendarpit. You do not need it to connect your own app. To try it, prepare a source checkout using the [development guide](https://github.com/iktakahiro/calendarpit/blob/main/docs/development.md). Then run these commands in separate terminals: ```sh # Terminal 1: start the packaged server calendarpit serve # Terminal 2: from the prepared source checkout bun run sample:dev ``` Calendarpit runs at `http://127.0.0.1:4173`, and the sample app runs at `http://127.0.0.1:4175`. ### Patterns to reuse The sample app is a single-connection local demo. It shows two patterns for your own integration: - **State cookie verification**: It stores the OAuth `state` parameter in a 5-minute HttpOnly cookie (`sample_state`). It verifies the value on `/callback` before exchanging the authorization code. - **Loopback-only outbound guard**: It blocks outbound SDK requests to hosts other than `127.0.0.1`, `localhost`, or `[::1]`. It also rejects HTTP redirects. Together, these prevent accidental requests to real Google servers. ### Environment variables The sample app uses these environment variables: | Environment variable | Default | | ---------------------- | ------------------------------------ | | `CALENDARPIT_URL` | `http://127.0.0.1:4173` | | `SAMPLE_PORT` | `4175` | | `SAMPLE_CLIENT_ID` | `sample-app` | | `SAMPLE_CLIENT_SECRET` | `local-sample-secret` | | `AUTHORIZATION_URL` | `${CALENDARPIT_URL}/oauth/authorize` | | `TOKEN_URL` | `${CALENDARPIT_URL}/oauth/token` | | `USERINFO_URL` | `${CALENDARPIT_URL}/userinfo` | | `CALENDAR_API_URL` | `${CALENDARPIT_URL}` | The sample app also sets these values: - Revocation URL: `${CALENDARPIT_URL}/oauth/revoke` - Redirect URI: `http://127.0.0.1:/callback` The built-in `sample-app` client registers only port `4175`. If you change `SAMPLE_PORT`, update the client's `redirectUris` in **Settings → OAuth clients** or in a fixture. ## Checklist for your app When you maintain a Calendarpit integration in your app, verify: - **All endpoint overrides**: Authorization, token exchange, token refresh, user profile, Calendar API calls, and token revocation all use the local endpoints. - **Callback reachability**: - The browser can reach your app's OAuth `redirect_uri`. - Calendarpit can reach your app's watch webhook address. If the webhook host is not loopback, set `CALENDARPIT_WATCH_HOSTS`. - **Full application flow**: Test your UI and background workers across login, event reads and writes, watch notifications, token refresh, revocation, and workspace reset. - **App-specific fixtures**: Keep your app's fixtures and E2E test scenarios in its own repository. # Local OAuth > Use Calendarpit's local OAuth 2.0 authorization code flow, token endpoints, and supported scopes. Source: https://calendarpit.dev/oauth/ Calendarpit includes a local OAuth 2.0 authorization server. Use it to test your app without a Google Cloud project or real Google accounts. During authorization, you pick a test user from a dropdown on the local consent page. You do not enter a password. Before you start the flow, point your app's OAuth client and Google Calendar SDK at `http://127.0.0.1:4173`. See [Connect your app](https://calendarpit.dev/connect.md) for endpoint configuration. ## Endpoints | Method | Path | Purpose | | ------ | --------------------------------------------- | ---------------------------------------------------------------------------------------- | | `GET` | `/oauth/authorize` | Validate the authorization request and render the local HTML consent page | | `POST` | `/oauth/authorize` | Submit the consent decision (`approve` or `deny`) and redirect (`302`) to `redirect_uri` | | `POST` | `/oauth/token` | Exchange an authorization code or refresh token for an access token | | `POST` | `/oauth/revoke` | Revoke an access token or refresh token and its connection | | `GET` | `/userinfo` | Return profile claims for the authorized test user | | `POST` | `/__calendarpit/connections/{grantId}/revoke` | Revoke a connection from the management API (`204`) | - `POST /oauth/authorize` accepts same-origin requests only. Cross-site requests return `403 forbidden`. - `POST /__calendarpit/connections/{grantId}/revoke` follows the management API request rules. See [Test control API](https://calendarpit.dev/test-control.md). Only the paths above are routed. These requests return `501`: - Google endpoints under `/oauth2/...`, such as `/oauth2/v4/token` or `/oauth2/v3/userinfo` - Unsupported HTTP methods on `/oauth/*` The `501` response body is `{"error":"unsupportedFeature","error_description":"Unsupported API endpoint or method."}`. ## Authorization code flow 1. **Register an OAuth client in your fixture.** Add an entry with `id`, `secret`, and `redirectUris` to the startup fixture's `clients` array. Each redirect URI must be an absolute `http:` or `https:` URL with no fragment or userinfo. - The startup fixture seeds only a new database or a `:memory:` session. - For an existing database file, load the fixture with `POST /__calendarpit/fixtures`, or start with a new database. Loading a fixture replaces workspace data until the next reset. See [Fixtures](https://calendarpit.dev/fixtures.md) and [Storage and restarts](https://calendarpit.dev/storage.md). - The default fixture includes the client `sample-app` with secret `local-sample-secret` and redirect URI `http://127.0.0.1:4175/callback`. Calendarpit uses the default fixture when neither `--config` nor `CALENDARPIT_CONFIG` is set. 2. **Send the browser to `GET /oauth/authorize`.** Build a URL at `http://127.0.0.1:4173/oauth/authorize` with URL-encoded query parameters: - `client_id` (required): Registered client ID. Unknown IDs return `400 invalid_client`. - `redirect_uri` (required): Callback URL. It must match one of the client's `redirectUris` by exact string comparison. There are no loopback port wildcards and no trailing-slash normalization. Mismatches return `400 invalid_request`. - `response_type` (required): Must be `code`. - `scope` (required): Space-separated list of supported scopes. See [Scopes](#scopes). - `state` (optional): Random value tied to the user's browser session. When provided, it is echoed back on the redirect. - `access_type` (optional): `online` or `offline`. Set `access_type=offline` to receive a refresh token. - `code_challenge` and `code_challenge_method` (optional): PKCE parameters. When used, `code_challenge_method` must be `S256`. `code_challenge` must be a 43-character base64url digest. - `prompt` (optional): Accepts `consent`, `select_account`, `consent select_account`, or `select_account consent`. The consent page is always displayed. - `include_granted_scopes` (optional): Must be `false` if present. 3. **Approve or deny on the consent page.** The page lists all workspace test users (`Name · email`) and the requested scope strings. Choose a test user and click **Approve** or **Deny**: - **Approve** creates a new connection (grant) and redirects (`302`) to `?state=&code=`. - **Deny** redirects (`302`) to `?state=&error=access_denied`. 4. **Verify `state` in your callback handler.** Compare the `state` query parameter with the session value you stored before redirecting. If `error=access_denied` is present, stop and do not call `/oauth/token`. 5. **Exchange the authorization code at `POST /oauth/token`.** Send an `application/x-www-form-urlencoded` body. Include `grant_type=authorization_code`, `code`, `redirect_uri` (identical to step 2), client credentials, and `code_verifier` if you used PKCE. For credentials, see [Client authentication](#client-authentication). The endpoint returns JSON: ```json { "access_token": "...", "token_type": "Bearer", "expires_in": 3600, "scope": "https://www.googleapis.com/auth/calendar email profile", "refresh_token": "..." } ``` `refresh_token` is present only when the authorization request included `access_type=offline`. 6. **Call the API with the access token.** Pass `Authorization: Bearer ` on requests to `/calendar/v3/...` and `GET /userinfo`. See [SDK examples](https://calendarpit.dev/sdks.md). ## HTTP examples These examples use shell variables for your client values and tokens: - `PIT_CLIENT_ID`, `PIT_CLIENT_SECRET`, and `PIT_REDIRECT_URI`: your client's values. - `PIT_CODE`: the code that your callback received. - `PIT_REFRESH_TOKEN`: the `refresh_token` returned by the token exchange. - `CALENDARPIT_ACCESS_TOKEN`: the `access_token` returned by the token exchange. If you used PKCE, also pass `--data-urlencode "code_verifier=$PIT_VERIFIER"` when you exchange the code. The Profile request requires `openid`, `email`, `profile`, or one of the `userinfo.*` scopes. ```sh curl --fail-with-body http://127.0.0.1:4173/oauth/token \ --data-urlencode 'grant_type=authorization_code' \ --data-urlencode "client_id=$PIT_CLIENT_ID" \ --data-urlencode "client_secret=$PIT_CLIENT_SECRET" \ --data-urlencode "redirect_uri=$PIT_REDIRECT_URI" \ --data-urlencode "code=$PIT_CODE" ``` ```sh curl --fail-with-body http://127.0.0.1:4173/oauth/token \ --data-urlencode 'grant_type=refresh_token' \ --data-urlencode "client_id=$PIT_CLIENT_ID" \ --data-urlencode "client_secret=$PIT_CLIENT_SECRET" \ --data-urlencode "refresh_token=$PIT_REFRESH_TOKEN" ``` ```sh curl --fail-with-body http://127.0.0.1:4173/userinfo \ -H "Authorization: Bearer $CALENDARPIT_ACCESS_TOKEN" ``` ```sh curl --fail-with-body http://127.0.0.1:4173/oauth/revoke \ --data-urlencode "token=$CALENDARPIT_ACCESS_TOKEN" ``` ## Client authentication, lifetimes, and revocation ### Client authentication Every `POST /oauth/token` call requires client authentication. This applies to both `authorization_code` and `refresh_token`, even when you use PKCE. Public clients without a secret are not supported. You can supply credentials in two ways: - **Form fields (`client_secret_post`)**: Include `client_id` and `client_secret` in the URL-encoded body. - **HTTP Basic (`client_secret_basic`)**: Send `Authorization: Basic `. If you send both, the `Authorization` header takes precedence. > [!WARNING] > `POST /oauth/token` always parses the body as > `application/x-www-form-urlencoded`, regardless of the `Content-Type` header. > It does not read JSON bodies. Sending JSON fails with `400 invalid_client`, or > with `400 unsupported_grant_type` when credentials come from HTTP Basic. ### Lifetimes and persistence | Item | Lifetime | Single use | Persisted in SQLite across restart | | --------------------- | ------------------------------------------------------------- | ---------- | ---------------------------------- | | Pending consent nonce | 5 minutes | Yes | No | | Authorization code | 60 seconds | Yes | No | | Access token | 1 hour (`expires_in: 3600`) | No | Yes (with original expiry) | | Refresh token | No expiry until revoked, user deleted, reset, or fixture load | No | Yes | | Connection (grant) | Until revoked, user deleted, reset, or fixture load | No | Yes | - At most 1,000 consents can be pending. Above that, the response is `429 rateLimitExceeded`. - An authorization code is bound to its `client_id` and `redirect_uri`. - In `:memory:` mode, all OAuth state is lost when the process exits. See [Storage and restarts](https://calendarpit.dev/storage.md). ### Refresh `grant_type=refresh_token` issues a new `access_token` (`expires_in: 3600`). - It does not return or rotate the `refresh_token`. Your existing refresh token stays valid. - If you include `scope` in the refresh request, it must equal the original space-joined scope string exactly. Otherwise the call fails with `400 invalid_scope`. ### Revocation To revoke a token, call `POST /oauth/revoke`: - Pass an access token or refresh token in the `token` form field, or in the `?token=` query parameter. - Client authentication is not required. - Revoking either token revokes the entire grant. It deletes all of the grant's access tokens, refresh tokens, and authorization codes, and stops its watch channels. - An unknown token returns `200` with an empty body. - A missing or blank `token` returns `400 invalidParameter`. Other actions also invalidate tokens: - **Revoke a connection** in the admin UI (`POST /__calendarpit/connections/{grantId}/revoke`): Invalidates the connection's tokens and stops its watch channels. - **Delete a test user** (`DELETE /__calendarpit/users/{id}`): Invalidates the user's tokens and stops their watch channels. - **Reset or load a fixture** (`POST /__calendarpit/reset` or `POST /__calendarpit/fixtures`): Deletes all connections, tokens, authorization codes, and pending consents, and stops all watch channels. See [Test control API](https://calendarpit.dev/test-control.md). ## Scopes Every `GET /oauth/authorize` request must include at least one supported scope. Requesting any other scope returns `400 invalid_scope`. ### Calendar API scopes | Scope | Allowed operations | | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `https://www.googleapis.com/auth/calendar` | All supported Calendar API reads and writes (`calendarList.*`, `calendars.get`, `events.*`, `channels.stop`, `freebusy.query`) | | `https://www.googleapis.com/auth/calendar.readonly` | `calendarList.list`, `calendarList.get`, `calendarList.watch`, `calendars.get`, `events.list`, `events.get`, `events.instances`, `events.watch`, `channels.stop`, `freebusy.query` | | `https://www.googleapis.com/auth/calendar.events` | `events.list`, `events.get`, `events.instances`, `events.insert`, `events.update`, `events.patch`, `events.delete`, `events.watch`, `channels.stop`, `freebusy.query` | | `https://www.googleapis.com/auth/calendar.events.readonly` | `events.list`, `events.get`, `events.instances`, `events.watch`, `channels.stop`, `freebusy.query` | | `https://www.googleapis.com/auth/calendar.calendarlist` | `calendarList.list`, `calendarList.get`, `calendarList.insert`, `calendarList.patch`, `calendarList.update`, `calendarList.delete`, `calendarList.watch`, `channels.stop` | | `https://www.googleapis.com/auth/calendar.calendarlist.readonly` | `calendarList.list`, `calendarList.get`, `calendarList.watch`, `channels.stop` | | `https://www.googleapis.com/auth/calendar.calendars.readonly` | `calendars.get` | | `https://www.googleapis.com/auth/calendar.freebusy` | `freebusy.query` | | `https://www.googleapis.com/auth/calendar.events.freebusy` | `freebusy.query` | ### Profile scopes These scopes allow `GET /userinfo`. The response always contains `{ sub, id }`, both set to the test user ID. | Scope | `GET /userinfo` response | | ------------------------------------------------------------- | ---------------------------------------------------------------- | | `openid` | `{ sub, id }` | | `email`, `https://www.googleapis.com/auth/userinfo.email` | Adds `email`, `verified_email: true`, and `email_verified: true` | | `profile`, `https://www.googleapis.com/auth/userinfo.profile` | Adds `name` | > [!NOTE] > `openid` only grants access to `GET /userinfo` with `{ sub, id }`. Calendarpit does not: > > - return an `id_token` from `/oauth/token` > - serve `/.well-known/openid-configuration` or JWKS > - include `picture`, `given_name`, `family_name`, or `locale` in `/userinfo` > ### Token and scope errors | Condition | Response | | -------------------------------------------------------- | ------------------------------------------------------------ | | Missing, expired, or revoked access token | `401` (`authError`) with a `WWW-Authenticate: Bearer` header | | Valid token missing a required scope for the endpoint | `403` (`insufficientPermissions`) | | `channels.stop` with a token from a different connection | `404` (`notFound`) | `channels.stop` requires the token to belong to the same connection (grant) that opened the channel. Unlike `/oauth/*` endpoints, `GET /userinfo` and Calendar API endpoints return errors in the Google API error envelope. See [Troubleshooting](https://calendarpit.dev/troubleshooting.md). ## Unsupported OAuth features `GET /oauth/authorize` returns validation errors directly to the browser. It does not redirect to `redirect_uri`. The response is `400` JSON: `{"error": "", "error_description": ""}`. - **Unknown `client_id`**: `400 invalid_client` ("Unknown client."). - **Unregistered `redirect_uri`**: `400 invalid_request` ("Unregistered redirect URI."). This covers any value that does not match one of the client's `redirectUris` by exact string equality. - **Unknown authorize parameters**: `400 unsupported_feature`. Examples are `nonce`, `login_hint`, `hd`, `request`, `request_uri`, and `enable_granular_consent`. - **Non-interactive consent**: `400 unsupported_feature`. This covers `prompt=none` and any `prompt` value other than the four listed in step 2. - **Incremental authorization** (`include_granted_scopes=true`): `400 unsupported_feature`. - **Other response types** (anything other than `response_type=code`): `400 unsupported_response_type`. - **PKCE `plain` method**: `400 invalid_request`. - **Unlisted scopes**: `400 invalid_scope`. Examples are `calendar.events.owned`, `calendar.app.created`, `calendar.settings.readonly`, `calendar.acls`, and the write scope `calendar.calendars`. Other OAuth limits: - **Other token grant types**: `POST /oauth/token` returns `400 unsupported_grant_type` after client authentication succeeds. - **API keys (`key=` query parameter)**: Accepted as a system parameter on API requests, but never replace bearer token authentication. See [Scope and limitations](https://calendarpit.dev/scope.md) for a summary of all unsupported Google features. # SDK examples > Point official Google Calendar clients in TypeScript, Python, Go, Kotlin, PHP, and C# at Calendarpit. Source: https://calendarpit.dev/sdks/ Point your app's official Google Calendar SDK client at Calendarpit. You do not need a Calendarpit-specific SDK. The examples below list calendars and query FreeBusy. ## Before you call the SDK Prepare an access token and the SDK packages first: 1. Start Calendarpit, for example with `calendarpit serve`. See [Run and configure](https://calendarpit.dev/running.md). 2. Complete the [local OAuth flow](https://calendarpit.dev/oauth.md) with the `https://www.googleapis.com/auth/calendar` scope. If you need a refresh token, add `access_type=offline`. 3. Set `CALENDARPIT_ACCESS_TOKEN` in your shell to the resulting access token. The token is valid for one hour. 4. Install the packages listed in each tab in your project. Calendarpit does not install language runtimes or SDK packages for you. The examples read `CALENDARPIT_ACCESS_TOKEN` directly. It is not a Google SDK setting. > [!NOTE] > > These snippets pass an existing access token. They show how to route Calendar API requests to Calendarpit. > > - They do not handle authorization callbacks or automatic token refresh. > - To refresh tokens, call `POST /oauth/token`. Then update the client's token or recreate the client. > > See [Connect your app](https://calendarpit.dev/connect.md) for the sample app and full OAuth client configuration. > ## Configure the service URL Each library expects a different endpoint format. - Preserve trailing slashes where shown. - If Calendarpit runs on another host or port, replace `127.0.0.1:4173` in every value. | Language | SDK setting | Value | | ----------------------- | --------------------------------------- | ----------------------------------------- | | TypeScript / JavaScript | `rootUrl` | `http://127.0.0.1:4173/` | | Python | `client_options.api_endpoint` | `http://127.0.0.1:4173/calendar/v3/` | | Go | `option.WithEndpoint` | `http://127.0.0.1:4173/calendar/v3/` | | Kotlin | `setRootUrl` + `setServicePath` | `http://127.0.0.1:4173/` + `calendar/v3/` | | PHP | `Calendar` constructor `$rootUrl` | `http://127.0.0.1:4173/` | | C# / .NET | `BaseClientService.Initializer.BaseUri` | `http://127.0.0.1:4173/calendar/v3/` | Every FreeBusy example sends `POST /calendar/v3/freeBusy` to Calendarpit. Event CRUD and calendar-list calls on the same client also use that local URL. For `calendarList`, these methods are supported: `list`, `get`, `insert`, `patch`, `update`, `delete`, and `watch`. The single-owner limits in [Calendar API compatibility](https://calendarpit.dev/compatibility.md) apply. > [!WARNING] > > Only the operations listed in [Calendar API compatibility](https://calendarpit.dev/compatibility.md) are supported, even if the SDK exposes more methods. > ## List calendars and query FreeBusy - **Packages**: `@googleapis/calendar` and `google-auth-library`. - **Runtime**: Bun, or Node.js 22 or later as an ES module (`.mjs`). - **Monolithic package**: `googleapis` also accepts `google.calendar({ version: 'v3', auth, rootUrl })`. ```ts import { calendar } from '@googleapis/calendar'; import { OAuth2Client } from 'google-auth-library'; const token = process.env.CALENDARPIT_ACCESS_TOKEN; if (!token) throw new Error('Set CALENDARPIT_ACCESS_TOKEN first.'); const auth = new OAuth2Client(); auth.setCredentials({ access_token: token }); const api = calendar({ version: 'v3', auth, rootUrl: 'http://127.0.0.1:4173/', }); const calendars = await api.calendarList.list(); console.log(calendars.data.items); const { data } = await api.freebusy.query({ requestBody: { timeMin: '2026-10-19T00:00:00+09:00', timeMax: '2026-10-20T00:00:00+09:00', timeZone: 'Asia/Tokyo', items: [{ id: 'primary' }], }, }); console.log(data.calendars?.primary?.busy ?? []); ``` This access-token-only client cannot refresh tokens. For full OAuth setup, use the local `endpoints` configuration shown in [Connect your app](https://calendarpit.dev/connect.md). Reference: [Google Calendar Node.js client implementation](https://github.com/googleapis/google-api-nodejs-client/blob/main/src/apis/calendar/v3.ts). - **Packages**: `google-api-python-client` (2.x) and `google-auth`. - **Discovery**: `static_discovery=True` uses the discovery document bundled with the installed library. Building the client therefore does not fetch discovery metadata from Google. - **Endpoint**: `api_endpoint` includes the `/calendar/v3/` path. ```python import os from google.oauth2.credentials import Credentials from googleapiclient.discovery import build credentials = Credentials(token=os.environ["CALENDARPIT_ACCESS_TOKEN"]) with build( "calendar", "v3", credentials=credentials, static_discovery=True, cache_discovery=False, client_options={ "api_endpoint": "http://127.0.0.1:4173/calendar/v3/", }, ) as api: print(api.calendarList().list().execute().get("items", [])) result = api.freebusy().query(body={ "timeMin": "2026-10-19T00:00:00+09:00", "timeMax": "2026-10-20T00:00:00+09:00", "timeZone": "Asia/Tokyo", "items": [{"id": "primary"}], }).execute() print(result["calendars"]["primary"]["busy"]) ``` If you pass a refresh token to `Credentials`: - Also supply the registered client ID, client secret, and `token_uri="http://127.0.0.1:4173/oauth/token"`. - Omit `scopes`, or pass the exact granted scopes in the same order. Configure the authorization, userinfo, and revocation URLs separately in your app's [OAuth flow](https://calendarpit.dev/oauth.md). References: [bundled discovery documents](https://googleapis.github.io/google-api-python-client/docs/start.html#building-and-calling-a-service), [endpoint selection](https://github.com/googleapis/google-api-python-client/blob/main/googleapiclient/discovery.py). - **Modules**: `google.golang.org/api` and `golang.org/x/oauth2`. - **Credentials**: Supply an explicit token source. This keeps the client from looking up Google Application Default Credentials. ```go package main import ( "context" "fmt" "log" "os" "golang.org/x/oauth2" "google.golang.org/api/calendar/v3" "google.golang.org/api/option" ) func main() { token := os.Getenv("CALENDARPIT_ACCESS_TOKEN") if token == "" { log.Fatal("Set CALENDARPIT_ACCESS_TOKEN first.") } api, err := calendar.NewService(context.Background(), option.WithEndpoint("http://127.0.0.1:4173/calendar/v3/"), option.WithTokenSource(oauth2.StaticTokenSource(&oauth2.Token{ AccessToken: token, TokenType: "Bearer", })), ) if err != nil { log.Fatal(err) } calendars, err := api.CalendarList.List().Do() if err != nil { log.Fatal(err) } for _, c := range calendars.Items { fmt.Println(c.Id) } result, err := api.Freebusy.Query(&calendar.FreeBusyRequest{ TimeMin: "2026-10-19T00:00:00+09:00", TimeMax: "2026-10-20T00:00:00+09:00", TimeZone: "Asia/Tokyo", Items: []*calendar.FreeBusyRequestItem{{Id: "primary"}}, }).Do() if err != nil { log.Fatal(err) } for _, b := range result.Calendars["primary"].Busy { fmt.Println(b.Start, "-", b.End) } } ``` `StaticTokenSource` never refreshes tokens. For SDK-managed OAuth: 1. Set `oauth2.Config.Endpoint.AuthURL` and `TokenURL` to Calendarpit's [OAuth endpoints](https://calendarpit.dev/oauth.md). 2. Pass `config.TokenSource(ctx, token)`. References: [Calendar client](https://pkg.go.dev/google.golang.org/api/calendar/v3), [WithEndpoint](https://pkg.go.dev/google.golang.org/api/option#WithEndpoint), [OAuth configuration](https://pkg.go.dev/golang.org/x/oauth2#Config). - **Artifacts**: `com.google.apis:google-api-services-calendar`, `com.google.http-client:google-http-client`, and `com.google.http-client:google-http-client-gson`. - **Runtime**: Kotlin/JVM with JDK 11 or later. The example calls the Google API Client Library for Java from Kotlin. ```kotlin import com.google.api.client.http.javanet.NetHttpTransport import com.google.api.client.json.gson.GsonFactory import com.google.api.client.util.DateTime import com.google.api.services.calendar.Calendar import com.google.api.services.calendar.model.FreeBusyRequest import com.google.api.services.calendar.model.FreeBusyRequestItem fun main() { val token = System.getenv("CALENDARPIT_ACCESS_TOKEN") require(!token.isNullOrBlank()) { "Set CALENDARPIT_ACCESS_TOKEN first." } val api = Calendar.Builder( NetHttpTransport(), GsonFactory.getDefaultInstance(), ) { request -> request.headers.setAuthorization("Bearer $token") } .setRootUrl("http://127.0.0.1:4173/") .setServicePath("calendar/v3/") .setApplicationName("Calendarpit local example") .build() println(api.calendarList().list().execute().items) val body = FreeBusyRequest() .setTimeMin(DateTime("2026-10-19T00:00:00+09:00")) .setTimeMax(DateTime("2026-10-20T00:00:00+09:00")) .setTimeZone("Asia/Tokyo") .setItems(listOf(FreeBusyRequestItem().setId("primary"))) val result = api.freebusy().query(body).execute() println(result.calendars["primary"]?.busy) } ``` The request initializer lambda sets the bearer token header directly. Obtain and refresh tokens using the [local OAuth endpoints](https://calendarpit.dev/oauth.md). Setting `setRootUrl` does not redirect separate Google authorization helpers. References: [Calendar builder](https://googleapis.dev/java/google-api-services-calendar/latest/com/google/api/services/calendar/Calendar.Builder.html), [FreeBusy request](https://googleapis.dev/java/google-api-services-calendar/latest/com/google/api/services/calendar/model/FreeBusyRequest.html). - **Composer package**: `google/apiclient` (2.x). - **Runtime**: PHP 8.1 or later, run from the project directory that contains `vendor/`. - **Root URL**: The second `Calendar` constructor argument is the origin. The service appends `calendar/v3/`. ```php setApplicationName('Calendarpit local example'); $client->setAccessToken($token); $api = new Calendar($client, 'http://127.0.0.1:4173/'); foreach ($api->calendarList->listCalendarList()->getItems() as $calendar) { echo $calendar->getId(), PHP_EOL; } $item = new FreeBusyRequestItem(); $item->setId('primary'); $request = new FreeBusyRequest(); $request->setTimeMin('2026-10-19T00:00:00+09:00'); $request->setTimeMax('2026-10-20T00:00:00+09:00'); $request->setTimeZone('Asia/Tokyo'); $request->setItems([$item]); $result = $api->freebusy->query($request); foreach ($result->getCalendars()['primary']->getBusy() as $interval) { echo $interval->getStart(), ' - ', $interval->getEnd(), PHP_EOL; } ``` `setAccessToken` with only an access token does not refresh it. Refresh via the [local token endpoint](https://calendarpit.dev/oauth.md), then call `setAccessToken` again. The `$rootUrl` argument configures Calendar API requests only. OAuth helpers on `Google\Client`, such as `fetchAccessTokenWithAuthCode`, still target Google. References: [PHP client library](https://github.com/googleapis/google-api-php-client), [Calendar service](https://github.com/googleapis/google-api-php-client-services/blob/main/src/Calendar.php). - **NuGet packages**: `Google.Apis.Calendar.v3` and `Google.Apis.Auth`. - **Project type**: A console application with top-level statements. ```csharp using System; using System.Collections.Generic; using Google.Apis.Auth.OAuth2; using Google.Apis.Calendar.v3; using Google.Apis.Calendar.v3.Data; using Google.Apis.Services; var token = Environment.GetEnvironmentVariable("CALENDARPIT_ACCESS_TOKEN"); if (string.IsNullOrWhiteSpace(token)) throw new InvalidOperationException("Set CALENDARPIT_ACCESS_TOKEN first."); using var api = new CalendarService(new BaseClientService.Initializer { BaseUri = "http://127.0.0.1:4173/calendar/v3/", HttpClientInitializer = GoogleCredential.FromAccessToken(token), ApplicationName = "Calendarpit local example", }); var calendars = await api.CalendarList.List().ExecuteAsync(); foreach (var calendar in calendars.Items) Console.WriteLine(calendar.Id); var result = await api.Freebusy.Query(new FreeBusyRequest { TimeMinRaw = "2026-10-19T00:00:00+09:00", TimeMaxRaw = "2026-10-20T00:00:00+09:00", TimeZone = "Asia/Tokyo", Items = new List { new FreeBusyRequestItem { Id = "primary" }, }, }).ExecuteAsync(); foreach (var interval in result.Calendars["primary"].Busy) Console.WriteLine($"{interval.StartRaw} - {interval.EndRaw}"); ``` `FromAccessToken` does not refresh tokens. Refresh via the [local token endpoint](https://calendarpit.dev/oauth.md), then recreate the credentials. `BaseUri` configures Calendar API requests only. It does not redirect OAuth helpers. References: [service base URI](https://docs.cloud.google.com/dotnet/docs/reference/Google.Apis/latest/Google.Apis.Services.BaseClientService.Initializer), [access-token credentials](https://docs.cloud.google.com/dotnet/docs/reference/Google.Apis/latest/Google.Apis.Auth.OAuth2.GoogleCredential), [FreeBusy request](https://googleapis.dev/dotnet/Google.Apis.Calendar.v3/latest/api/Google.Apis.Calendar.v3.Data.FreeBusyRequest.html). You can call the same HTTP endpoints directly from any language. ```sh curl --fail-with-body http://127.0.0.1:4173/calendar/v3/users/me/calendarList \ -H "Authorization: Bearer $CALENDARPIT_ACCESS_TOKEN" curl --fail-with-body http://127.0.0.1:4173/calendar/v3/freeBusy \ -H "Authorization: Bearer $CALENDARPIT_ACCESS_TOKEN" \ -H 'Content-Type: application/json' \ --data '{ "timeMin": "2026-10-19T00:00:00+09:00", "timeMax": "2026-10-20T00:00:00+09:00", "timeZone": "Asia/Tokyo", "items": [{"id": "primary"}] }' ``` ### Expected result `primary` resolves to the primary calendar of the authenticated test user. For Alex in the default fixture, this query returns one busy interval: `10:00` to `11:00` on October 19, 2026, in `Asia/Tokyo`. Editing events in the admin UI changes the next FreeBusy response. Transparent and cancelled events do not count as busy time. ## Verification status Only the Bun/TypeScript sample app in [Connect your app](https://calendarpit.dev/connect.md) has an automated end-to-end test. > [!WARNING] > > The examples on this page, including the TypeScript example, follow the official client APIs. They have not been compiled or run in this repository's CI. > For common configuration and request errors, see [Troubleshooting](https://calendarpit.dev/troubleshooting.md). # Fixtures > Define test users, calendars, events, and OAuth clients in a JSON fixture file. Source: https://calendarpit.dev/fixtures/ A fixture is a JSON file that defines initial test data for Calendarpit: test users, calendars, events, and OAuth clients. Use a fixture to start your local server or test suite with a known dataset. Set explicit `id` values in a fixture to give your tests fixed user, calendar, event, and OAuth client IDs. Your test assertions can then check exact IDs instead of querying for generated values. ## Load a fixture at startup Pass a fixture file path with the `--config` CLI flag or the `CALENDARPIT_CONFIG` environment variable. If you omit both, Calendarpit loads a built-in default fixture. It matches `fixtures/default.json` in the repository and contains: - Users `alex` and `sam` - Calendars `alex-work`, `alex-personal`, and `sam-work` - One `planning` event - The `sample-app` OAuth client ### Start from the CLI Save the JSON example below as `calendarpit.fixture.json` and edit it for your test. Check prerequisites and publication status in [Installation](https://calendarpit.dev/installation.md). Then start Calendarpit from the directory that contains the file: ```sh calendarpit serve \ --database :memory: --config ./calendarpit.fixture.json ``` Relative `--config` and `CALENDARPIT_CONFIG` paths resolve from the directory where you start Calendarpit. ### Start in Docker or Compose In Docker, mount the existing file read-only and use its container path. This command uses POSIX shell syntax: ```sh docker run --rm -p 127.0.0.1:4173:4173 \ --mount "type=bind,source=$PWD/calendarpit.fixture.json,target=/fixtures/startup.json,readonly" \ -e CALENDARPIT_CONFIG=/fixtures/startup.json \ -e CALENDARPIT_DATABASE=:memory: \ ghcr.io/iktakahiro/calendarpit:latest ``` For Compose, make two changes to the service: - Add `./calendarpit.fixture.json:/fixtures/startup.json:ro` to its `volumes`. - Set `CALENDARPIT_CONFIG: /fixtures/startup.json` in its `environment`. The host file must be readable by the container's non-root user. See [Run and configure](https://calendarpit.dev/running.md) for startup options. #### Share the host directory with the container runtime Docker Desktop, Colima, and other VM-based runtimes can bind-mount only the host directories they share with their VM. If the fixture is outside those directories, the container sees an empty directory instead of the file, and startup fails with `Fixture path is a directory, not a file`. - **Colima**: Only your home directory is shared by default. To share another directory, add it to `mounts` in `~/.colima/default/colima.yaml`, then restart Colima with `colima stop` and `colima start`. A nonempty `mounts` list replaces the default, so list your home directory too if you still need it. ```yaml mounts: - location: ~ writable: true - location: /Volumes/Work/my-app writable: false ``` - **Docker Desktop**: Add the directory under **Settings → Resources → File sharing**. If you cannot change the shared directories, copy the fixture into the container before it starts instead of mounting it: ```sh docker create --name calendarpit -p 127.0.0.1:4173:4173 \ -e CALENDARPIT_CONFIG=/app/startup.json \ -e CALENDARPIT_DATABASE=:memory: \ ghcr.io/iktakahiro/calendarpit:latest docker cp ./calendarpit.fixture.json calendarpit:/app/startup.json docker start calendarpit ``` The copied file must be readable by other users (for example, mode `644`). To load a fixture into a server that is already running, use `POST /__calendarpit/fixtures` instead. See [Load or reset at runtime](#load-or-reset-at-runtime). ### When the startup fixture applies A startup fixture seeds only a **new, empty** database: - **`--database :memory:` mode**: The database is new on every process start, so the fixture always applies. - **SQLite file with saved data**: Calendarpit does not apply the fixture and prints no warning. It loads the saved data and the original reset baseline. The saved data includes per-user calendar-list settings and deleted-calendar tombstones. > [!WARNING] > Even when Calendarpit skips the fixture, the path you pass must still point to > a readable JSON file, or startup fails. Its contents are not validated in this > case. See [Storage and restarts](https://calendarpit.dev/storage.md) for details. ### Load or reset at runtime Use the test control API to change data between tests: - `POST /__calendarpit/fixtures` loads a different fixture at runtime. - `POST /__calendarpit/reset` resets to the startup baseline. It restores the startup fixture, including default calendar-list entries with their startup etags. Both endpoints clear: - OAuth grants and tokens - Per-user calendar-list settings - Deleted-calendar tombstones - Watch channels - Deliveries - Request history - Sync tokens - Notifications `GET /__calendarpit/state` omits client secrets, calendar-list settings, and tombstones. You cannot reload its output as a fixture. See [Test control API](https://calendarpit.dev/test-control.md). ## Root structure and example The root value of a fixture file must be a JSON object. It accepts four optional array keys: `users`, `calendars`, `events`, and `clients`. An empty object (`{}`) is a valid empty fixture. - Each key, if present, must be an array. Otherwise validation fails with `" must be an array."`. - Any other key fails validation with `"Unsupported field: "` (reason `unsupportedFeature`). This applies to the root object and to every user, calendar, event, and client entry. ```json { "users": [{ "id": "alex", "name": "Alex", "email": "alex@example.test" }], "calendars": [ { "id": "work", "userId": "alex", "summary": "Work", "timeZone": "Asia/Tokyo", "primary": true } ], "events": [ { "id": "meeting", "calendarId": "work", "summary": "Planning", "start": { "dateTime": "2026-10-19T10:00:00+09:00" }, "end": { "dateTime": "2026-10-19T11:00:00+09:00" } } ], "clients": [ { "id": "sample-app", "secret": "local-sample-secret", "redirectUris": ["http://127.0.0.1:4175/callback"] } ] } ``` ## ID rules and validation IDs are optional for users, calendars, events, and clients. However, users that own calendars and calendars that contain events need an explicit `id`, so other entries can reference them. - **Allowed characters**: ASCII letters, digits, `@`, `.`, `_`, and `-`, up to 128 characters (`^[a-zA-Z0-9@._-]{1,128}$`). - **Reserved ID**: `primary` is reserved and cannot be used as an ID. - **Uniqueness**: IDs must be unique within each of `users`, `calendars`, and `clients` (`"Duplicate fixture ID."`). Event IDs must be unique within each calendar (`"Duplicate event ID."`). The same event ID can appear in different calendars. ### ID errors | `id` value | Error | | ----------------------------------------------- | --------------------------------- | | Empty, whitespace-only, or not a string | `"id must be a nonempty string."` | | Nonempty string that does not match the pattern | `"Invalid ID."` | | 129 to 10,000 characters | `"Invalid ID."` | | Longer than 10,000 characters | `"id must be a nonempty string."` | | `primary` | `"Invalid ID."` | ### Generated IDs and the reset baseline When you omit an `id`, Calendarpit generates a UUID. At seed time, Calendarpit captures generated IDs and initial event metadata (`created`, `updated`, `etag`) in the startup reset baseline. As a result, repeated calls to `POST /__calendarpit/reset` reproduce the same data. - SQLite preserves that baseline across process restarts. - In `:memory:` mode, every new process generates fresh UUIDs and timestamps. ### Validation failures Validation is atomic. Every owner and calendar reference must exist in the fixture. If any fixture rule fails, Calendarpit stops at the first error: - **At startup with a new database**: The process prints `Calendarpit: ` and exits with code `1`. - **On `POST /__calendarpit/fixtures`**: Calendarpit returns `400` (`invalidParameter` or `unsupportedFeature`) and leaves existing data unchanged. ## Section reference ### `users` Defines test users. A test user can approve access on the consent page and own calendars. | Field | Required | Default | Rules | | ------- | -------- | -------------- | ----------------------------------------------------------------------------------------------- | | `id` | Optional | Generated UUID | 1–128 chars matching `[a-zA-Z0-9@._-]`; not `primary`. Unique across `users`. | | `name` | Required | — | Nonempty string up to 10,000 characters. | | `email` | Required | — | Nonempty string up to 10,000 characters matching `^[^\s@]+@[^\s@]+$` (else `"Invalid email."`). | ### `calendars` Defines calendars owned by fixture users. - Every user that owns calendars must have **exactly one** calendar with `"primary": true`. Otherwise validation fails with `"Each user with calendars must have exactly one primary calendar."`. - This includes a user with a single calendar. That calendar fails validation without `"primary": true`. - Users without calendars are allowed. For those users, the `primary` calendar alias returns `404`. | Field | Required | Default | Rules | | ---------- | -------- | -------------- | --------------------------------------------------------------------------------- | | `id` | Optional | Generated UUID | 1–128 chars matching `[a-zA-Z0-9@._-]`; not `primary`. Unique across `calendars`. | | `userId` | Required | — | Must match a user `id` in `users` (else `"Unknown calendar owner."`). | | `summary` | Required | — | Nonempty string up to 10,000 characters. | | `timeZone` | Optional | `"UTC"` | Valid IANA time zone name (else `"Invalid IANA time zone."`). | | `primary` | Optional | `false` | Boolean (else `"primary must be boolean."`). | Seeded calendars start on their owner's calendar list with default settings (`selected: true`, `colorId: "1"`). You can later modify calendars or users through the management API (see [Test control API](https://calendarpit.dev/test-control.md)). Calendarpit then behaves as follows: - **Delete a primary calendar**: The first remaining owned calendar on the calendar list becomes the new primary calendar. If none are on the list, the first remaining owned calendar becomes primary. The new primary calendar is put back on the list if needed, keeping its other list settings. - **Set `"primary": true` on another calendar**: The flag transfers atomically. That calendar is put back on the calendar list, keeping its other list settings. - **Delete a calendar**: Its list settings are dropped, and Calendarpit records a deleted-calendar tombstone. With `showDeleted=true`, the tombstone appears as `deleted: true` with default list settings. A deleted primary calendar's tombstone keeps `primary: true`. Recreating a calendar with a previously deleted ID clears that tombstone and any saved list settings. - **Delete a user**: Calendarpit revokes the user's OAuth grants, which stops their watch channels. It removes their calendars, events, and list settings without adding tombstones. ### `events` Defines initial events. Fixture events use the Calendar API event fields and validation rules, plus `calendarId`. See [Calendar API compatibility](https://calendarpit.dev/compatibility.md) and [Events, recurrence and time](https://calendarpit.dev/recurrence.md). - Read-only fields (`organizer`, `creator`, `iCalUID`, `recurringEventId`, `originalStartTime`) may be set. - `conferenceData` does not require `conferenceDataVersion`. - The request-only field `attendeesOmitted` is rejected (`"Unsupported field: attendeesOmitted"`). - Seeding does not trigger API insert side effects. Attendees do not receive invitation copies in their own calendars. A `conferenceData.createRequest` does not generate a meeting link. | Field | Required | Default | Rules | | --------------------------------------- | -------- | ------------------------ | ----------------------------------------------------------------------------------- | | `calendarId` | Required | — | Must match a calendar `id` in `calendars` (else `"Unknown event calendar."`). | | `id` | Optional | Generated UUID | 1–128 chars matching `[a-zA-Z0-9@._-]`; not `primary`. Unique within the calendar. | | `start`, `end` | Required | — | Event start and end (`dateTime` or all-day `date`), same rules as the Calendar API. | | `organizer`, `creator` | Optional | Calendar owner | Read-only in normal API requests, but may be set in fixtures. | | `iCalUID` | Optional | `@calendarpit.local` | Read-only in normal API requests, but may be set in fixtures. | | `recurringEventId`, `originalStartTime` | Optional | None | Read-only in normal API requests, but may be set in fixtures. Set both or neither. | | `sequence` | Optional | `0` | Non-negative integer (else `"Invalid sequence."`). | | `created`, `updated`, `etag` | Ignored | Generated at seed time | Provided values are ignored; new values are generated when seeding the fixture. | Setting read-only fields is useful, for example, to seed an external organizer or stored recurring exceptions. Setting only one of `recurringEventId` or `originalStartTime` fails with `"Instances require recurringEventId and originalStartTime."`. ### `clients` Defines OAuth clients for [Local OAuth](https://calendarpit.dev/oauth.md). There is no `scopes` field per client. Any client may request any supported scope. | Field | Required | Default | Rules | | -------------- | -------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | Optional | Generated UUID | 1–128 chars matching `[a-zA-Z0-9@._-]`; not `primary`. Unique across `clients`. | | `secret` | Required | — | Nonempty string up to 10,000 characters. | | `redirectUris` | Required | — | Nonempty array of absolute `http` or `https` URLs (up to 10,000 characters each), without fragments or credentials. Matched exactly at `/oauth/authorize`. | # Test control API > Reset state, load fixtures, inspect request history, and drain webhook deliveries over HTTP during automated tests. Source: https://calendarpit.dev/test-control/ Calendarpit has a local management API under `/__calendarpit`. Use it to seed data, inspect server state, and reset between test runs. ## Request rules - **Base path**: All management endpoints start with `/__calendarpit`. For example: `http://127.0.0.1:4173/__calendarpit/reset`. - **No authentication**: Management endpoints do not use a bearer token. Calendarpit is a local development server and binds to loopback by default. - **`Content-Type: application/json` on writes**: Every request other than `GET` or `HEAD` must send a `Content-Type` header that starts with `application/json` (case-sensitive). - This includes `DELETE` routes and `POST` controls with no body, such as `/reset` and `/deliveries/drain`. - Requests without the header fail with HTTP `415` (`unsupportedMediaType`). - For `POST` controls with no request body, send an empty body or `{}`. - **Same-origin check**: A request fails with HTTP `403` (`forbidden`) in either case: - Its `Origin` header does not match the server origin. - It has `Sec-Fetch-Site: cross-site`. Non-browser clients such as `curl` and test runners usually omit `Origin`, so they are allowed. - **Health check exemption**: `/__calendarpit/health` skips these checks. `GET` and `HEAD` readiness probes need no extra headers. - **Excluded from history**: Requests to `/__calendarpit/*` are not recorded in the protocol request history. - **Error format**: Management errors use the Google JSON error envelope with `domain: "calendarpit"`. > [!WARNING] > > If you bind to a non-loopback address (for example, inside a container), anyone who can reach the port can call these endpoints. > ## Management endpoints All paths below are relative to `/__calendarpit`. | Method | Path | Behavior | | ---------------------------------- | ---------------------------------- | -------------------------------------------------------------------------- | | `GET` / `HEAD` | `/health` | Return server information and capability flags. | | `GET` | `/state` | Return a snapshot of the server state. | | `GET` | `/changes` | Stream a `change` event whenever the saved state changes (SSE). | | `POST` | `/fixtures` | Validate and replace fixture data (`200` snapshot). | | `POST` | `/reset` | Restore the startup fixture baseline (`200` snapshot). | | `GET` / `DELETE` | `/history` | Return (`200`) or clear (`204`) the latest 200 protocol requests. | | `POST` | `/users` | Create a user (`201`). | | `PATCH` / `DELETE` | `/users/{id}` | Edit or delete (`204`) a user. | | `POST` | `/calendars` | Create a calendar (`201`). | | `PATCH` / `DELETE` | `/calendars/{id}` | Edit or delete (`204`) a calendar. | | `GET` / `POST` | `/calendars/{id}/events` | List events or create an event (`200`). | | `GET` / `PUT` / `PATCH` / `DELETE` | `/calendars/{id}/events/{eventId}` | Read, replace, patch, or delete (`204`) an event. | | `POST` | `/clients` | Register an OAuth client (`201`). | | `PATCH` / `DELETE` | `/clients/{id}` | Edit or delete (`204`) an OAuth client. | | `POST` | `/connections/{id}/revoke` | Revoke the connection's tokens and stop its watch channels (`204`). | | `POST` | `/deliveries/drain` | Wait for pending webhook deliveries, then return the delivery log (`200`). | | `PUT` | `/rate-limit` | Set the Calendar API rate-limit mode and return the snapshot (`200`). | ### Endpoint details - **`/health`**: Returns the server `name` (`"Calendarpit"`), `version`, `stage`, and `storage` (`"memory"` or `"sqlite"`). It also returns the capability flags `calendar`, `oauth`, `watch`, and `fixtures`. `HEAD` returns an empty `200`. - **`/state`**: Removes expired channels first. It then returns a snapshot of `storage`, `users`, `calendars`, `events`, `clients` (without secrets), `connections`, `channels` (`token` redacted), `deliveries`, `notifications`, `revision`, and `rateLimitMode` (`off`, `production`, or `error-test`). - **`/changes`**: A [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) stream for `EventSource`. It sends a `change` event after any request or watch delivery changes the saved state, including Calendar API, OAuth, and management writes. Reads that change nothing send no event. Events carry no state, so read `/state` or `/history` again. Comment lines keep the connection open, and the stream ends when the server stops. - **`/fixtures`**: Validates and replaces users, calendars, events, and clients. It clears runtime state and invalidates connections. - **`/reset`**: Restores the startup fixture baseline and clears all runtime state. - **`/history`**: `GET` returns the requests ordered from oldest to newest. - **`/users`**: Accepts `name`, `email`, and an optional `id`. Returns `409 duplicate` if the ID already exists. - **`/users/{id}`**: `PATCH` edits `name` and `email`. `id` is immutable. Deleting a user also deletes the data they own. - **`/calendars`**: Accepts `userId`, `summary`, and optional `timeZone`, `primary`, and `id`. - **`/calendars/{id}`**: `id` and `userId` are immutable. - **`/clients`**: Accepts `id`, `secret`, and `redirectUris` with the same rules as a fixture client. Returns `409 duplicate` if the ID already exists. Responses omit the secret. - **`/clients/{id}`**: `PATCH` edits `secret` and `redirectUris`; an omitted `secret` keeps the current one. `id` is immutable. Users, calendars, events, and connections are kept, and issued tokens stay valid. Pending consent requests and unexchanged authorization codes for a removed redirect URI are discarded. Deleting a client revokes its connections. - **`/calendars/{id}/events`**: Listing supports `events.list` parameters, including `syncToken`. Listed items include `calendarId`. - **`/calendars/{id}/events/{eventId}`**: `DELETE` keeps a tombstone. - **`/deliveries/drain`**: Also waits for the retries of pending deliveries. The response is the delivery log array. - **`/rate-limit`**: `PUT` body is `{ "mode": "off" }`, `{ "mode": "production" }`, or `{ "mode": "error-test" }`. Unknown fields return `400 unsupportedFeature`. An unknown mode returns `400`. The mode is saved with the workspace, and changing it clears the in-memory counters. See [Calendar API rate limits](https://calendarpit.dev/running.md#calendar-api-rate-limits). ### Cascades and admin writes - **User deletion**: Deleting a user revokes their OAuth connections and stops their watch channels. It also deletes their calendars and events without creating calendar tombstones. - **Primary flag**: A user's first calendar becomes `primary: true` automatically. - Setting `primary: true` on another calendar of the same user moves the flag to that calendar in one step. - Unsetting `primary` directly returns `400`. - **Calendar deletion**: Deleting a calendar does the following: - Deletes the calendar's events and stops its event watch channels. - Records a `calendarList` tombstone with default list settings. Per-user customizations such as `summaryOverride` or `colorId` are dropped. - Makes another of the owner's calendars primary if the deleted calendar was primary. Calendarpit prefers a calendar that is still on the owner's calendar list. - **Calendar list notifications**: Each admin calendar create (`POST /calendars`), edit (`PATCH /calendars/{id}`), and delete queues an `exists` notification on the owner's `calendarList.watch` channels. - An edit sends a notification even when nothing changes. - Expect these extra deliveries if your test counts them. - **Admin event writes**: Event writes under `/__calendarpit/calendars/{id}/events` differ from Calendar API writes: - They skip invitee restrictions. - They do not require `conferenceDataVersion=1`. - They can set read-only fields: `organizer`, `creator`, `iCalUID`, `recurringEventId`, and `originalStartTime`. - Updates keep the stored `organizer`, `creator`, and `iCalUID`. If an event already has `recurringEventId` and `originalStartTime`, updates keep those too. ## Reset vs fixture load `POST /__calendarpit/reset` and `POST /__calendarpit/fixtures` both replace stored data, save it immediately, and clear all runtime state. The difference is the data they load. | Behavior | `POST /__calendarpit/reset` | `POST /__calendarpit/fixtures` | | --------------------------------- | ---------------------------------- | ---------------------------------------------------------------------- | | Users, calendars, events, clients | Restored from the startup baseline | Replaced by the posted [fixture JSON](https://calendarpit.dev/fixtures.md) | | Startup reset baseline | Unchanged | Unchanged (the next `/reset` still restores the original startup seed) | | Runtime state | Cleared | Cleared | Validation on `POST /__calendarpit/fixtures` is atomic. If any record is invalid, Calendarpit returns `400` and changes nothing. ### What both endpoints clear Both endpoints stop all active [watch channels](https://calendarpit.dev/watch.md) and abort their in-flight requests. They also clear: - OAuth connections, access and refresh tokens, authorization codes, and pending consents - Request history - [Sync tokens](https://calendarpit.dev/sync.md), plus event and calendar list page tokens - Calendar tombstones - Per-user calendar list settings: customizations made with `calendarList.insert`/`patch`/`update`, and removals made with `calendarList.delete` - Invitation notifications and all delivery log records After either call: - Old access tokens fail with `401` (`authError`). - Old sync tokens fail with `410` (`fullSyncRequired`). Reset does not delete the SQLite database file. It does not change the fixture file on disk either. ## Request history and state export ### Request history `GET /__calendarpit/history` returns the latest 200 requests served on `/calendar/v3/*`, `/oauth*`, and `/userinfo`. They are ordered from oldest to newest. Failed requests, such as `401` or `501` responses, are included. Calendarpit masks credentials in the history: - These keys are replaced with `"[REDACTED]"`: `authorization`, `cookie`, `set-cookie`, `client_secret`, `secret`, `access_token`, `refresh_token`, `id_token`, `code`, `code_verifier`, `code_challenge`, `consent`, `token`, `x-goog-channel-token`, and `state`. This applies to headers, bodies, query strings, and `Location` or `Referer` URLs. - However, in bodies, `code` is not masked when its value is a number, so numeric error codes such as `"code": 403` in API error responses stay visible. - Credentials inside URLs are removed. - Strings longer than 12,000 characters are cut off and end with ` [truncated]`. ### State export Use `GET /__calendarpit/state` for inspection only. You cannot load its output back with `POST /__calendarpit/fixtures`: - It omits client secrets. `clients` entries contain only `id` and `redirectUris`. - Channel tokens appear as `"[REDACTED]"`. - It includes runtime fields (`storage`, `connections`, `channels`, `deliveries`, `notifications`, `revision`, `rateLimitMode`). `POST /__calendarpit/fixtures` rejects them with `400` (`unsupportedFeature`). - It does not include calendar list settings. Read those with `calendarList.list`/`get`. Keep your original fixture files for seeding and reloading. ## Writing repeatable tests - **Reset before each scenario**: Call `POST /__calendarpit/reset` before each test to restore the startup baseline. To load a specific fixture instead, call `POST /__calendarpit/fixtures`. Reset and fixture load clear rate-limit counters and keep `rateLimitMode`. Call `PUT /__calendarpit/rate-limit` with `{ "mode": "off" }` when a shared server must start unlimited. - **Use fixed IDs**: Set explicit `id` values for users, calendars, events, and clients in your fixture file. Calendarpit generates missing IDs once at seed time. In `:memory:` mode, each new server process generates new IDs. - **Isolate parallel workers**: Run one Calendarpit process per test worker with `--port 0` and `--database :memory:`. You can also give each worker its own SQLite file. - **Read the port from stdout**: With `--port 0`, read the URL from the startup line `Admin http://127.0.0.1:/`. For example, match it with `/Admin\s+(http:\/\/[^\s]+)/`. Then poll `GET /__calendarpit/health` until it responds before you run tests. - **Drain webhook deliveries instead of sleeping**: `POST /__calendarpit/deliveries/drain` waits for the deliveries pending when you call it, including their retries. - **Expect aborted webhooks after reset**: `/reset` aborts in-progress webhook requests. A receiver may still receive a request before it is aborted. - **Refetch after restarts**: When you test [SQLite restarts](https://calendarpit.dev/storage.md), deliveries queued before shutdown are marked `cancelled` and are not sent again. Refetch the calendar state after the restart. ```ts const baseUrl = 'http://127.0.0.1:4173'; const jsonHeaders = { 'Content-Type': 'application/json' }; export async function resetCalendarpit() { const res = await fetch(`${baseUrl}/__calendarpit/reset`, { method: 'POST', headers: jsonHeaders, body: '{}', }); if (!res.ok) throw new Error(`Reset failed: ${res.status}`); return res.json(); } export async function drainDeliveries() { const res = await fetch(`${baseUrl}/__calendarpit/deliveries/drain`, { method: 'POST', headers: jsonHeaders, body: '{}', }); if (!res.ok) throw new Error(`Drain failed: ${res.status}`); return res.json(); } ``` # Storage and restarts > Where Calendarpit stores data, how to choose between SQLite and in-memory mode, and what persists across restarts and resets. Source: https://calendarpit.dev/storage/ Calendarpit stores workspace state in a local SQLite file by default. For throwaway test sessions, it can keep state in memory instead. ## Choosing a storage mode By default, Homebrew and standalone executable installs save to `.calendarpit/calendarpit.sqlite` in the directory where you start Calendarpit. Run it from your project directory to keep that project's data together. To choose a file or `:memory:`, use `--database ` or `CALENDARPIT_DATABASE`. CLI flags override environment variables. Check prerequisites and publication status in [Installation](https://calendarpit.dev/installation.md). ```sh # Temporary E2E session; no database files are written calendarpit serve --database :memory: --port 0 # Choose a persistent workspace calendarpit serve --database ./.calendarpit/manual.sqlite ``` ### Modes - **SQLite file (default)**: Saves changes after each request that modifies state. It also saves after each webhook delivery finishes. Relative paths resolve against the working directory. - **In-memory (`:memory:`)**: Writes no database or lock files. All state is discarded when the process exits. - **Docker**: The image sets `CALENDARPIT_DATABASE=/data/calendarpit.sqlite`. - To retain data when the container is removed and re-created, mount a named volume with `-v calendarpit-data:/data`. - For a temporary session, pass `-e CALENDARPIT_DATABASE=:memory:`. - The [Compose example](https://calendarpit.dev/installation.md) also uses a named volume. `docker compose down` preserves data, while `docker compose down -v` deletes it. ### Check the active mode You can see the active storage mode and path in three places: - **Startup log**: The CLI prints `Data ` (or `Data :memory:`). When the server entry loads, it also prints `Calendarpit data: `. - **Admin UI**: The sidebar footer shows `SQLite` or `In-memory`. **Settings → Test data** describes the mode and shows the path (or `:memory:`). - **Management API**: `GET /__calendarpit/health` returns `storage: "sqlite" | "memory"`. `GET /__calendarpit/state` returns `storage: { mode, path? }`. ## What survives a SQLite restart Reopening an existing SQLite file restores saved data. Short-lived flow state is dropped. On `SIGINT` or `SIGTERM`, Calendarpit: 1. Aborts in-flight webhook deliveries. 2. Saves state. 3. Releases the database lock. Each kind of state behaves as follows after a restart: | State | SQLite restart behavior | | -------------------------------------------------- | ---------------------------------------------------- | | Users, calendars, events, OAuth clients | Restored, including event IDs, timestamps, and etags | | Calendar-list settings | Restored; cleared by a reset or fixture load | | Reset baseline (startup fixture) | Original seed retained | | Connections (grants), access and refresh tokens | Restored | | Watch channels | Restored only under the conditions below | | Request history, delivery log, notifications | Latest 200 entries of each restored | | Queued or in-flight webhook deliveries | Marked `cancelled`; never replayed automatically | | Sync tokens, calendar tombstones | Restored; cleared by a reset or fixture load | | Pending consents, authorization codes, page tokens | Discarded; restart the flow or list query | Details for some rows: - **Calendar-list settings** include per-user overrides, colors, hidden/selected, reminders, and removed entries. - **Reset baseline**: `--config` and `CALENDARPIT_CONFIG` file contents are ignored. - **Tokens and connections**: - Access tokens keep their original expiry. - Refresh tokens do not expire. - Revoked connections stay revoked. - **Watch channels** are restored if all of these hold. Restored channels keep their message numbers. - The channel is unexpired. - The connection is active. - The callback host is still allowed. - **Page tokens** are the `calendarList` and `events` cursors. After a restart, refetch calendar state in your app. This reconciles [watch notifications](https://calendarpit.dev/watch.md) interrupted by shutdown. ## Seed baseline, fixtures, and reset A startup [fixture](https://calendarpit.dev/fixtures.md) seeds **only a new database**. The startup fixture comes from `--config`, `CALENDARPIT_CONFIG`, or the built-in default. - **Existing SQLite file**: Reopens saved data and the original baseline. - If `--config` or `CALENDARPIT_CONFIG` is set, the fixture's contents are ignored and do not overwrite the database. - The file must still exist and contain valid JSON. - **In-memory mode**: Every start is a new database. The startup fixture is applied, and any omitted IDs are regenerated, on every start. - **Reset (`POST /__calendarpit/reset`)**: Restores the original startup baseline, even after restarts. - It clears connections, tokens, codes, consents, watch channels, calendar-list settings, [sync tokens](https://calendarpit.dev/sync.md), page tokens, calendar tombstones, request history, notifications, and deliveries. - It saves immediately. - It does not delete the SQLite file or modify the fixture file. - **Load fixture (`POST /__calendarpit/fixtures`)**: Replaces current data and clears runtime state **without changing the reset baseline**. Subsequent resets still restore the original seed. See [Test control API](https://calendarpit.dev/test-control.md). ## Locking, files, and parallel runs ### One process per file Only one Calendarpit process can use a SQLite file at a time. - While running, Calendarpit holds an exclusive lock on `.lock`. - A second process on the same file fails at startup with `Database is already in use: . Use a separate path or :memory:.` The CLI prefixes this with `Calendarpit: `. - The OS releases the lock on exit, including after a crash. Give each parallel test worker `--database :memory:` or a separate SQLite file. ### Sidecar files and permissions SQLite runs in WAL mode. While running, Calendarpit creates these sidecar files next to the database: - `-wal` - `-shm` - `.lock` - `.lock-journal` The database, `-wal`, `-shm`, and `.lock` files use mode `0600`. Any database directory Calendarpit creates uses mode `0700`. Keep sidecar files with the database while running. Stop the server before copying a database file. ### Keep the database out of Git > [!WARNING] > > The database contains local test credentials and client secrets. Keep it out of Git. > In this repository, Git ignores: - `.calendarpit/` - The `*.sqlite`, `*.sqlite-wal`, `*.sqlite-shm`, and `*.sqlite.lock` patterns - `.lock-journal`, but only inside `.calendarpit/` # Calendar API compatibility > Reference for the Google Calendar API v3 methods, parameters, and event fields supported by Calendarpit, and what returns an explicit error. Source: https://calendarpit.dev/compatibility/ ## Calendar API Calendarpit serves the endpoints below. Access follows these rules: - Every supported `/calendar/v3` endpoint requires a Calendarpit bearer token. See [Local OAuth](https://calendarpit.dev/oauth.md) for scopes. - Access is limited to calendars owned by the authorized test user. - `primary` resolves to that user's primary calendar. - Unknown or unowned calendar IDs return `404` (`notFound`). - Exception: `freebusy.query` returns `200` and reports a per-calendar `notFound` error inside the response. All paths in this table are relative to `/calendar/v3`. | Method | Path | Behavior | | ----------------------- | ---------------------------------------------------- | ----------------------------------------------- | | GET | `/users/me/calendarList` | List owned calendars | | POST | `/users/me/calendarList` | Restore an owned calendar to the list | | GET, PUT, PATCH, DELETE | `/users/me/calendarList/{calendarId}` | Read, replace, patch, or remove a list entry | | POST | `/users/me/calendarList/watch` | Subscribe to calendar-list changes | | GET | `/calendars/{calendarId}` | Calendar metadata (`id`, `summary`, `timeZone`) | | GET, POST | `/calendars/{calendarId}/events` | List or create events | | GET, PUT, PATCH, DELETE | `/calendars/{calendarId}/events/{eventId}` | Read, replace, patch, or delete an event | | GET | `/calendars/{calendarId}/events/{eventId}/instances` | Recurring instances and exceptions | | POST | `/freeBusy` | Merged, clipped busy ranges, up to 50 calendars | | POST | `/calendars/{calendarId}/events/watch` | Subscribe to event changes | | POST | `/channels/stop` | Stop an event or calendar-list watch channel | The `calendarList.list` query parameters are listed under Lists and paging below. ### Method coverage Unsupported methods return an explicit error: | Request | Response | | --------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | Unrouted endpoint | `501` (`unsupportedFeature`) | | `calendars.update`, `calendars.patch`, `calendars.delete` | Token, scope, and ownership checks first (`401`, `403`, or `404`), then `501` | | `events.import` | `404` (`notFound`) | | `events.quickAdd` with `text` | `400` (`unsupportedFeature`) | | `events.quickAdd` without `text` | `404` | | Unsupported HTTP method on the events collection or an existing event | `405` (`methodNotAllowed`) | `events.import` and `events.quickAdd` share the `/events/{eventId}` path. That is why they return these codes. | Resource | Method | Supported | Notes | | ------------ | ------------------- | :-------: | ------------------------------------------------------------- | | Acl | `delete` | ❌ | ACLs and shared-calendar access are not simulated | | Acl | `get` | ❌ | | | Acl | `insert` | ❌ | | | Acl | `list` | ❌ | | | Acl | `patch` | ❌ | | | Acl | `update` | ❌ | | | Acl | `watch` | ❌ | Event and calendar-list watches do not cover ACLs | | CalendarList | `list` | ✅ | Owned calendars; `minAccessRole`, `showDeleted`, `showHidden` | | CalendarList | `delete` | ✅ | Removes a non-primary calendar from the list only | | CalendarList | `get` | ✅ | Same entry `list` returns for that calendar | | CalendarList | `insert` | ✅ | Restores an owned calendar removed from the list | | CalendarList | `patch` | ✅ | Preserves omitted writable fields | | CalendarList | `update` | ✅ | `PUT` replaces writable fields | | CalendarList | `watch` | ✅ | Caller's list changes; loopback callbacks by default | | Calendars | `get` | ✅ | Metadata of a calendar the test user owns | | Calendars | `clear` | ❌ | Delete the events, or reset to the startup fixture | | Calendars | `delete` | ❌ | Use the admin UI or the management API | | Calendars | `insert` | ❌ | | | Calendars | `patch` | ❌ | | | Calendars | `transferOwnership` | ❌ | One owner per calendar, with no sharing model | | Calendars | `update` | ❌ | | | Channels | `stop` | ✅ | Stops an event or calendar-list watch channel | | Colors | `get` | ❌ | Event colors 1–11 and calendar colors 1–24 need no endpoint | | Events | `list` | ✅ | Time bounds, paging, `singleEvents`, sync tokens, filters | | Events | `get` | ✅ | Includes `cancelled` tombstones and recurring instance IDs | | Events | `insert` | ✅ | Returns `200` with the stored event | | Events | `update` | ✅ | `PUT` replaces writable fields | | Events | `patch` | ✅ | Preserves omitted fields | | Events | `delete` | ✅ | Keeps a `cancelled` record for synchronization | | Events | `instances` | ✅ | Recurring instances, exceptions, and `originalStart` | | Events | `watch` | ✅ | Loopback callbacks by default; retries and a delivery log | | Events | `import` | ❌ | Create the event with `insert` | | Events | `move` | ❌ | Delete and insert across calendars instead | | Events | `quickAdd` | ❌ | No natural-language parsing | | Freebusy | `query` | ✅ | Merged, clipped busy ranges, up to 50 calendars | | Settings | `get` | ❌ | No per-user Google settings | | Settings | `list` | ❌ | | | Settings | `watch` | ❌ | | ## Events ### Supported fields - `id`: matches `[a-zA-Z0-9@._-]{1,128}`. `primary` is not allowed. Duplicate IDs return `409` (`duplicate`). - `summary`, `description`, and `location` - `start` and `end` - `transparency`: `opaque` or `transparent` - `status`: `confirmed`, `tentative`, or `cancelled` - `visibility`: `default`, `public`, `private`, or `confidential` - `colorId`: `"1"`–`"11"` - `attendees` and `attendeesOmitted` - `guestsCanModify`, `guestsCanInviteOthers`, and `guestsCanSeeOtherGuests` - `reminders` and `recurrence` - `conferenceData`: requires `conferenceDataVersion=1` - `hangoutLink` - `extendedProperties.private` and `extendedProperties.shared`: string maps Write endpoints also accept: - `sendUpdates`: `all`, `externalOnly`, or `none` - `conferenceDataVersion`: `0` or `1` ### Server-managed fields - Responses include `organizer`, `creator`, `iCalUID`, `sequence`, `created`, `updated`, and a quoted `etag`. - Write requests also accept `kind`, `etag`, `created`, `updated`, `calendarId`, and `sequence`. This lets you send a fetched event back unchanged. - In write requests, `calendarId` is the resolved calendar ID, not `primary`. - `organizer`, `creator`, `iCalUID`, `recurringEventId`, and `originalStartTime` are read-only. Updates accept unchanged values. - On `events.insert`, omit these read-only fields. Calendarpit sets them. - `sequence` increments on each update. - `If-Match` is checked on `GET`, `PUT`, `PATCH`, and `DELETE` of stored events. A mismatch returns `412` (`conditionNotMet`). ### PUT and PATCH - **`PUT`** replaces writable fields. It resets omitted optional fields to defaults. - **`PATCH`** preserves omitted fields. - A supplied `start` or `end` object replaces the stored object. Its fields are not merged. - `extendedProperties` maps merge by key. `null` removes a key or a whole map. - All-day inputs accept `dateTime: null` and `timeZone: null`. ### Deletion and tombstones `events.delete` returns `204` and keeps a `cancelled` tombstone. If the event is already cancelled, it returns `410` (`deleted`). | Method | Tombstones | | ---------------- | --------------------------------------------------------- | | `events.get` | Returned | | `freebusy.query` | Excluded | | Lists | Excluded unless `showDeleted=true` or `updatedMin` is set | With `singleEvents=false`, cancelled exceptions of a series stay visible in lists. For recurrence, invitations, reminders, synthetic Meet links, and time rules, see [Events, recurrence and time](https://calendarpit.dev/recurrence.md). ## Calendar list ### Entry shape - Calendar-list entries use `kind: "calendar#calendarListEntry"`. - `list` and `get` return the same entry shape. Each owned calendar starts on its owner's list with these values: - `accessRole: "owner"` - `selected: true` - `colorId: "1"` (`backgroundColor: "#ac725e"`, `foregroundColor: "#1d1d1d"`) - `defaultReminders: []` - `primary` - `conferenceProperties.allowedConferenceSolutionTypes: ["hangoutsMeet"]` Some fields appear only in certain cases: - `hidden` is omitted unless `true`. - `summaryOverride` and `notificationSettings` are omitted when empty. - `deleted: true` appears only on removed or tombstoned entries. - `description` and `location` are omitted. Requests that include them are rejected with `400` (`unsupportedFeature`). Writes and concurrency: - Read-only fields are `kind`, `etag`, `id`, `summary`, `timeZone`, `accessRole`, `primary`, `deleted`, and `conferenceProperties`. - Writes accept read-only fields only when unchanged. A mismatch returns `400` (`invalidParameter`). - `id` accepts `primary` when the path uses `primary`. - `etag` updates when entry settings change. It also updates when the calendar's `summary`, `timeZone`, or `primary` flag changes. - `If-Match` is checked on `PATCH`, `PUT`, and `DELETE`. A mismatch returns `412` (`conditionNotMet`). ### Writing settings (patch, update, insert) Writable per-user settings are `summaryOverride`, `colorId`, `backgroundColor`, `foregroundColor`, `hidden`, `selected`, `defaultReminders`, and `notificationSettings`. - They persist across SQLite restarts. - They clear on reset or fixture load. - `summaryOverride` requires a non-blank string of up to 10,000 characters. `""` returns `400`. How each write treats omitted fields: - **`PATCH`** preserves omitted writable fields. `null` clears `summaryOverride`, `defaultReminders`, and `notificationSettings`. - **`PUT` and `insert`** (`200`) replace writable fields: - Omitted overrides, reminders, and notifications are cleared. - `hidden` and `selected` reset to `false`. Never-written entries stay `selected: true`. - `colorId` resets to `"1"` unless colors are supplied. - **Unchanged writes** return `200`. They do not change the `etag`, invalidate calendar-list page tokens, or notify watch channels. ### Colors - `colorId` accepts palette IDs `"1"`–`"24"`. The foreground is `"#1d1d1d"`. - Unknown IDs, and inherited names like `"constructor"`, return `400`. **With `colorRgbFormat=true`**: - Every `insert`, `patch`, or `update` must include both `backgroundColor` and `foregroundColor` (`#rrggbb`). Otherwise it returns `400`. - Any supplied `colorId` is ignored and set to the nearest palette color. **Without `colorRgbFormat=true`**: - RGB fields may only repeat the displayed colors. - On `PATCH`, repeating the current `colorId` and RGB keeps custom colors. - `PUT` and `insert` must send `colorRgbFormat=true` to keep custom RGB colors. - A different `colorId` clears custom RGB. ### Reminders and notifications - `defaultReminders` accepts up to 5 `{method: "email" | "popup", minutes: 0–40320}` items. - `notificationSettings.notifications` accepts up to 5 `{method: "email", type}` items. - `type` is one of `eventCreation`, `eventChange`, `eventCancellation`, `eventResponse`, or `agenda`. - `type` values must be unique. Duplicate types return `400`. - Neither setting sends email. - `PATCH {"notificationSettings": {}}` keeps existing notifications. - `[]`, `null`, or `PUT` without `notifications` clears them. > [!NOTE] > > Two behaviors follow Google's reference docs and were not checked against live Google: > > - Ignoring `colorId` with `colorRgbFormat=true` > - Preserving notifications on `PATCH {"notificationSettings": {}}` > ### Delete and insert **`calendarList.delete`** (`204`) removes a non-primary calendar from the caller's list only. - The primary calendar returns `403` (`cannotDeletePrimaryCalendar`). - An already removed calendar returns `404`. - The calendar and its events remain accessible to `calendars.get`, `events.*`, `freebusy.query`, and `events.watch`. - `calendarList.get`, `patch`, and `update` return `404` for it. **`calendarList.insert`** restores a removed owned calendar (`200`). - It requires `id`. A missing `id` returns `400`. - It never creates a calendar. - Already-listed calendars, including hidden ones and `primary`, return `409` (`duplicate`). To unhide a calendar, use `patch`. **Management API effects**: - Deleting a primary calendar promotes the first remaining listed calendar. - If all calendars were removed from the list, it instead restores the first owned calendar to the list with its saved settings. - Setting `primary: true` also restores a removed calendar to the list. ### Watch `calendarList.watch` shares the loopback allowlist, delivery log, and `channels.stop` endpoint with `events.watch`. See [Watch notifications](https://calendarpit.dev/watch.md). - It sends `sync` on open. - It then sends `exists` when a list write changes stored settings. - It also sends `exists` when the management API creates, updates, or deletes the user's calendars. - Event writes do not trigger it. - Other query parameters (including `syncToken`) return `400` (`unsupportedFeature`). - `params` (such as `params.ttl`) also returns `400` (`unsupportedFeature`). ## Lists and paging ### `calendarList.list` `calendarList.list` accepts these parameters: - `maxResults` and `pageToken` - `minAccessRole`: `freeBusyReader`, `reader`, `writer`, or `owner`. All owned calendars have the `owner` role, so every valid value matches them. - `showHidden`: defaults to `false`. Then `list` omits `hidden: true` entries, but `get` still returns them. - `showDeleted`: see below. The response includes a collection `etag`, but no `nextSyncToken`. `showDeleted=true` includes `deleted: true` entries for: - **Calendars removed with `calendarList.delete`**: they keep their stored settings, even if `hidden: true`. - **Tombstones of calendars deleted through the management API**: they use default list settings. They keep `primary: true` if the deleted calendar was primary. ### `events.list` `events.list` accepts these parameters: - `timeMin`, `timeMax`, and `updatedMin`: RFC 3339 timestamps with an offset. - `maxResults`: 1–2500, default 250. - `orderBy`: `startTime` or `updated`. `orderBy=startTime` requires `singleEvents=true`. - `pageToken`, `singleEvents`, `timeZone`, `showDeleted`, `syncToken`, and `iCalUID`. - `privateExtendedProperty=name=value` and `sharedExtendedProperty=name=value`: repeatable filters. All must match. Matching and ordering: - Time matching uses `start < timeMax` and `end > timeMin`. - Unordered lists sort by event ID. > [!WARNING] > > If a calendar has an unbounded recurring series: > > - `events.list` requires `timeMax` whenever `singleEvents=true` or `timeMin` is set. > - `events.instances` on that series always requires `timeMax`. > > A missing `timeMax` returns `400` (`unsupportedFeature`). > ### Page tokens - Event list pages freeze a snapshot on the first page. Writes between pages do not skip items. - Event page tokens are bound to the query and the user. - Event page tokens expire after 1 hour. They clear on restart, reset, or fixture load. - Calendar-list page tokens invalidate on any data or calendar-list write. They are not persisted. - Expired or stale tokens return `410` (`invalidPageToken`). For `syncToken` and `nextSyncToken`, see [Incremental sync](https://calendarpit.dev/sync.md). ## Explicit exclusions These features are unsupported: - ACLs, shared calendars, and delegation - Calendar groups - Color palettes (`colors.get`) - User settings - Calendar-list sync tokens - ACL and settings watch - Free-text search (`q`) - `eventTypes` - Attachments - Real email delivery - Real Google Meet creation - Full OIDC ### Request validation - Unknown body fields return `400` (`unsupportedFeature`). - Unknown query parameters, including `fields`, return `400` (`unsupportedFeature`) on every `/calendar/v3` endpoint. - Exception: `channels.stop` ignores its query string. - Transport parameters (`alt=json`, `prettyPrint`, `quotaUser`, `key`) are accepted. - API keys never replace OAuth bearer tokens. - Calendarpit never proxies to or syncs with Google. To manage calendars and reset data, see [Test control API](https://calendarpit.dev/test-control.md). To point a client at Calendarpit, see [Connect your app](https://calendarpit.dev/connect.md). # Events, recurrence and time > How Calendarpit expands recurring events, simulates invitations and meetings locally, and handles time zones, DST, and free/busy intervals. Source: https://calendarpit.dev/recurrence/ Calendarpit handles these locally: - expanding recurring series - syncing invitations between local test users - calculating time ranges and free/busy intervals For supported endpoints and fields, see [Calendar API compatibility](https://calendarpit.dev/compatibility.md). ## Recurrence You can read a recurring event as a series or as expanded occurrences. In `events.list`, `singleEvents` controls the shape: - **`singleEvents=false`** (default): returns series masters and stored exceptions. - **`singleEvents=true`**: expands occurrences. ### The instances endpoint `GET /calendar/v3/calendars/{calendarId}/events/{eventId}/instances` always returns expanded occurrences for one series. - With `singleEvents=false`, cancelled exceptions appear without `showDeleted`. - It accepts the `events.list` parameters, plus `originalStart`. Examples include `timeMin`, `timeMax`, `showDeleted`, `maxResults`, `pageToken`, and `timeZone`. - It rejects `syncToken`. - It omits `nextSyncToken`. ### Instance IDs and exceptions Each instance carries `recurringEventId`, `originalStartTime`, and a deterministic ID: - **Timed events**: `_`, in UTC. - **All-day events**: `_`. On `/events/{instanceId}`, each method works on a single occurrence: | Method | Behavior | | -------------- | ------------------------------------------------------- | | `GET` | Returns the occurrence, even if no exception is stored. | | `PUT`, `PATCH` | Stores the occurrence as an exception. | | `DELETE` | Stores a cancelled exception. | Changes to the master affect its occurrences: - Updating a master updates its instances. It also cancels stored exceptions that the new rule no longer produces. - Deleting a master cancels its exceptions. Expansion also applies to other features: - With `singleEvents=true`, [incremental sync](https://calendarpit.dev/sync.md) reports removed occurrences as `cancelled`. - `freebusy.query` uses the same expansion. ### Rules and validation `recurrence` accepts 1–20 `RRULE`, `EXRULE`, `RDATE`, or `EXDATE` lines. An empty array stores a non-recurring event. These return `400 unsupportedFeature`: - other lines, such as `DTSTART` - a missing `FREQ` - a sub-daily `FREQ` (`HOURLY`, `MINUTELY`, `SECONDLY`) - uppercase rule parts not listed below, such as `BYHOUR` - duplicate rule parts These return `400 invalidParameter`: - malformed parts - invalid values, combinations, or line counts Supported rule parts: | Rule part | Supported values | | ------------ | ---------------------------------------------------------------------- | | `FREQ` | `DAILY`, `WEEKLY`, `MONTHLY`, `YEARLY` | | `INTERVAL` | 1–10000 | | `COUNT` | 1–10000. Use `COUNT` or `UNTIL`, not both. | | `UNTIL` | Timed `UNTIL` must be UTC (`...Z`). All-day `UNTIL` is a date. | | `BYDAY` | `MO`–`SU`. On `MONTHLY` and `YEARLY`, an optional `±1`–`5` is allowed. | | `BYMONTHDAY` | `±1`–`31` | | `BYMONTH` | `1`–`12` | | `BYSETPOS` | `±1`–`366` | | `WKST` | Supported | Time zone requirements: - **Timed series**: require `start.timeZone`. - **`RDATE` and `EXDATE`**: Timed series allow `;TZID=`. All-day series require `;VALUE=DATE`. ### Expansion limits Expansion has two limits. Exceeding either returns `400 unsupportedFeature`. - **Instance count**: At most 10,000 instances per expansion. The count applies per request window, or to the whole series when there is no `timeMax`. - **Time span**: At most 100 years (366×100 days) from `DTSTART`. This applies to finite series expanded without `timeMax`, and to `timeMin` and `timeMax`. Unbounded series (no `COUNT` or `UNTIL`) require `timeMax` in these cases: - when expanding (`singleEvents=true`) - when `timeMin` is passed to `events.list` > [!WARNING] > > One series over a limit fails the whole list or `freeBusy` request. Deleted series still count. Send `timeMax` or reset state. > ### Daylight saving time (DST) Rules keep wall-clock time in `start.timeZone`. **Nonexistent local times** (the spring-forward gap) fail with `400 unsupportedFeature` when an expansion reaches the gap occurrence. This affects: - `instances` - `events.list` with `singleEvents=true` or with `timeMin`/`timeMax` - instance IDs for occurrences within about two days of the gap - `freeBusy` The insert itself succeeds. The error fails the whole request. **Ambiguous times** (the fall-back fold) use the earlier, pre-transition offset, such as `-04:00` in New York. ## Invitations, reminders, and local meetings Calendarpit never sends email or calls Google Meet. ### Invitations `attendees` accepts up to 200 unique emails. Each attendee supports `displayName`, `optional`, `resource`, `additionalGuests`, `comment`, and `responseStatus`. `responseStatus` is one of `needsAction`, `accepted`, `tentative`, or `declined`. Inviting a local test user with a primary calendar writes a copy to that calendar. The copy has the same `id` and `iCalUID`. - Organizer updates and cancellations propagate to copies and trigger [watch notifications](https://calendarpit.dev/watch.md). - Removing an attendee cancels their copy. - `reminders` and `extendedProperties.private` stay per-copy. - `extendedProperties.shared` comes from the organizer. ### RSVP and invitee edits Invitees must use `PATCH`. `PUT` returns `403 forbiddenForNonOrganizer`. Invitees may only edit: - their own `responseStatus` and `comment`, or set `attendeesOmitted: true` with only their own entry - `reminders` - `colorId` - `transparency` - `extendedProperties` Effects of invitee edits: - RSVP changes update the organizer and other copies. - An RSVP to one instance of a series creates an exception in the organizer's calendar. - Declining sets the invitee's copy to `transparent`. Other `attendees` patches reset it to `opaque`. - The next organizer update overwrites `colorId` and `transparency` changes on a copy. ### Guest flags | Flag | Default | | ------------------------- | ------- | | `guestsCanModify` | `false` | | `guestsCanInviteOthers` | `true` | | `guestsCanSeeOtherGuests` | `true` | - These flags round-trip as booleans. - Only the organizer can change them. - They are stored only. They do not change what invitees may edit. ### `sendUpdates` | Value | What Calendarpit records | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `all` | One entry per write. `recipients` holds all attendees except the organizer, including removed attendees. For an invitee's `REPLY`, the recipient is the organizer. | | `externalOnly` | Only recipients who are not local users. | | `none` (default) | Nothing. | - Entries (`REQUEST`, `CANCEL`, or `REPLY`) appear in `GET /__calendarpit/state` under `notifications`. It keeps the last 200. See [Test control API](https://calendarpit.dev/test-control.md). - Local copies sync regardless of `sendUpdates`. ### Reminders - **Shape**: `{ useDefault: boolean, overrides?: [{ method: "email" | "popup", minutes: 0..40320 }] }`. - **Limit**: At most 5 overrides when `useDefault: false`. - **Behavior**: Reminders are stored only. They never fire. ### Conference data - Non-null `conferenceData` requires `?conferenceDataVersion=1`. - A `hangoutsMeet` `createRequest.requestId` generates a deterministic ID, a `hangoutLink`, and a `video` entry point at `https://meet.calendarpit.invalid/`. - `conferenceData: null` clears it. ## Time semantics and free/busy Event intervals are half-open `[start, end)`. `end` must be after `start`. List filters match `start < timeMax` and `end > timeMin`. As a result, adjacent events do not overlap. ### All-day events - `start.date` and exclusive `end.date` use `YYYY-MM-DD`. - They use midnight in the calendar's time zone. - This also holds on 23-hour and 25-hour DST days. ### Timed events - `dateTime` requires a UTC offset or `Z`, or an IANA `timeZone`. - Unoffset local times in a DST gap or overlap return `400`. - Responses format `dateTime` with a numeric offset in the requested `timeZone`, or in the calendar's zone. - The response's `timeZone` is also the requested or calendar zone. It is not the event's stored zone. ### Free/busy `POST /calendar/v3/freeBusy` queries up to 50 calendars. It returns busy ranges formatted in `timeZone` (default `UTC`). When it computes busy ranges, it: - expands recurring series - excludes `transparent` events (free, including declined invitations) - excludes `cancelled` (deleted) events - merges overlapping or adjacent intervals - clips them to `[timeMin, timeMax)` Unknown or unowned calendars return a per-calendar `notFound` error with `busy: []`. # Incremental sync > Run a full event sync and fetch incremental changes and deletions with nextSyncToken. Source: https://calendarpit.dev/sync/ Calendarpit implements Google Calendar's full and incremental synchronization flow for `events.list`. The flow has two steps: 1. Run an initial full list to get a `nextSyncToken`. 2. Pass that token as `syncToken` on later requests. You get only the events created, updated, or deleted since that checkpoint. See Google's [sync guide](https://developers.google.com/workspace/calendar/api/guides/sync) and [`events.list` reference](https://developers.google.com/workspace/calendar/api/v3/reference/events/list) for protocol details. ## Full synchronization Every full `events.list` call (not `events.instances`) issues a sync token, whether or not you pass `showDeleted=true`. ### Pagination - Follow every `nextPageToken` until the final page. - Send the same query parameters with each `pageToken`. Changing a parameter returns HTTP `410` (`invalidPageToken`). - Calendarpit returns `nextSyncToken` only on the last page, never alongside `nextPageToken`. Save `nextSyncToken` after you process all pages. - Page rows and the sync snapshot are frozen together on the first page. Event writes during pagination appear in the next incremental sync. ### Unbounded recurring series > [!WARNING] > > With `singleEvents=true`, always set `timeMax` on the full sync. > An unbounded recurring series is an `RRULE` without `COUNT` or `UNTIL`. When the calendar contains one, these requests fail: - **`singleEvents=true`**: A token issued without `timeMax` returns HTTP `400` (`unsupportedFeature`). Run a new full sync with `timeMax`. - **`singleEvents=false`**: A full `events.list` with `timeMin` and no `timeMax` is also rejected (see [Events, recurrence and time](https://calendarpit.dev/recurrence.md)). Incremental syncs with `singleEvents=false` are not affected. A deleted unbounded series still counts. Its tombstone stays in the calendar until a reset or fixture load. ```ts // api is the Google SDK client configured with Calendarpit's rootUrl. const query = { calendarId: 'primary', singleEvents: true, showDeleted: true, timeMin: '2026-10-01T00:00:00Z', timeMax: '2026-11-01T00:00:00Z', }; let pageToken: string | undefined; let syncToken: string | undefined; do { const { data } = await api.events.list({ ...query, pageToken }); for (const event of data.items ?? []) { if (event.status === 'cancelled') await removeLocalEvent(event.id!); else await upsertLocalEvent(event); } pageToken = data.nextPageToken ?? undefined; if (!pageToken) syncToken = data.nextSyncToken ?? undefined; } while (pageToken); ``` ## Incremental synchronization After a [watch notification](https://calendarpit.dev/watch.md) or on a poll timer, call `events.list` with `syncToken`. You can paginate incremental results with `maxResults` and `pageToken`. ```ts const previousToken = syncToken; do { const { data } = await api.events.list({ calendarId: 'primary', singleEvents: true, showDeleted: true, syncToken: previousToken, pageToken, }); for (const event of data.items ?? []) { if (event.status === 'cancelled') await removeLocalEvent(event.id!); else await upsertLocalEvent(event); } pageToken = data.nextPageToken ?? undefined; if (!pageToken) syncToken = data.nextSyncToken ?? undefined; } while (pageToken); ``` ### Query rules Requests that break these rules fail with HTTP `400` (`invalidParameter`): - **Forbidden parameters**: Do not combine `syncToken` with `timeMin`, `timeMax`, `orderBy`, `updatedMin`, `privateExtendedProperty`, `sharedExtendedProperty`, or `iCalUID`. `events.instances` does not support `syncToken`. - **Deleted events**: Do not pass `showDeleted=false`. Incremental sync always includes deletions. Pass `showDeleted=true` or omit `showDeleted`. - **Matching expansion options**: `singleEvents` and the effective `timeZone` must match the initial sync. The effective `timeZone` is the `timeZone` parameter, or the calendar's time zone when you omit it. - **Time zone changes**: Changing a calendar's time zone in the admin UI or management API invalidates tokens issued without an explicit `timeZone` parameter (HTTP `400`). ### Delta contents and behavior - **Retries**: Sync tokens are not consumed on use. If a request fails, you can retry with the same `syncToken`. - **New token on every sync**: Each incremental sync returns a new `nextSyncToken` on its last page. - **Empty deltas**: When nothing changed, `items` is `[]`. A new `nextSyncToken` is still returned. - **Tombstones**: Deleted events are kept as tombstones and returned with `status: "cancelled"`. - **Unfiltered deltas**: Deltas are not filtered by the initial request's `updatedMin`, extended-property, or `iCalUID` filters. They contain every changed event in the calendar. - **Recurring series window**: What a delta contains depends on `singleEvents`: - With `singleEvents=false`, deltas contain changed series masters, stored exceptions, and single events. - With `singleEvents=true`, recurring series are re-expanded within the `timeMin` and `timeMax` window from the initial full sync. Editing a series master returns all of its occurrences in that window. Occurrences removed by trimming or cancelling a series are returned with `status: "cancelled"`. - Changed non-recurring events are returned even outside the initial `timeMin` and `timeMax` window. Run a new full sync when you move the recurring expansion window. ## Lifecycle and limits Sync tokens are opaque UUIDs bound to the user, calendar, expansion options, and initial time window. | Token | Lifetime and capacity | Persistence | Error when invalid | | ----------- | ----------------------------------------------------------------------- | ---------------------------------------------------- | ------------------------------- | | `syncToken` | 7 days TTL; max 100 per workspace (oldest evicted first) | Stored in SQLite; lost on restart in `:memory:` mode | HTTP `410` (`fullSyncRequired`) | | `pageToken` | 1 hour TTL; max 1,000 frozen pages per workspace (oldest evicted first) | In-memory only (lost on restart) | HTTP `410` (`invalidPageToken`) | - **HTTP `410` (`fullSyncRequired`)**: Returned when a `syncToken` is any of the following: - Unknown or expired - Evicted past the 100-token limit - Cleared by a reset or fixture load - Issued for another user or calendar Discard your local synced data for that calendar and run a full sync. - **Token limit**: Each full or incremental `events.list` request without a `pageToken` issues a new token. All users and calendars share the 100-token limit, including management API event lists. - **Resets and fixtures**: `POST /__calendarpit/reset` and `POST /__calendarpit/fixtures` clear all sync tokens and page tokens (see [Test control API](https://calendarpit.dev/test-control.md)). They also revoke all OAuth grants, so clients must reauthorize first. - **Page cursors**: Event `pageToken` cursors are bound to the query parameters and user. They do not survive restarts, resets, or fixture loads. After HTTP `410` (`invalidPageToken`), restart pagination from your `syncToken` or restart the full sync. # Watch notifications > Register events.watch and calendarList.watch webhook channels, receive local HTTP callbacks, and drain deliveries in tests. Source: https://calendarpit.dev/watch/ Calendarpit implements `events.watch` and `calendarList.watch` push notifications. You can test webhook handling locally without a public URL or HTTPS tunnel. When watched calendar events or a user's calendar list change, Calendarpit sends an HTTP `POST` request to your callback address. ## Register and stop a channel To watch a calendar's events, send `POST /calendar/v3/calendars/{calendarId}/events/watch`. The request must meet these conditions: - **Scope**: The OAuth access token must include an event-read scope: `calendar`, `calendar.readonly`, `calendar.events`, or `calendar.events.readonly`. Other scopes fail with `403`. - **Calendar**: The calendar must belong to the authorized user. `primary` is allowed. Other calendars fail with `404 notFound`. To watch the user's calendar list instead, see [Calendar list](#calendar-list). ```sh curl -X POST http://127.0.0.1:4173/calendar/v3/calendars/primary/events/watch \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "id": "channel-1", "type": "web_hook", "address": "http://127.0.0.1:3000/webhooks/calendar", "token": "secret-123" }' ``` ### Request body Allowed request body fields: - `id` (required): 1 to 64 ASCII letters, digits, underscores, or hyphens (`^[A-Za-z0-9_-]{1,64}$`). It must be unique across all active event and calendar-list channels in the workspace. A duplicate fails with `409 duplicate`. - `type` (required): Must be `"web_hook"`. - `address` (required): Callback URL (`http:` or `https:`). - `token` (optional): Non-blank string of up to 256 characters without CR or LF. It is echoed in `X-Goog-Channel-Token`. - `expiration` (optional): Future Unix timestamp in milliseconds, as a number or numeric string. - Defaults to 24 hours from creation. - Values beyond 7 days are capped at 7 days without an error. Read the effective value from the response. Errors: - Invalid values fail with `400 invalidParameter`. - Any other field (such as `params`, `params.ttl`, or `payload`) fails with `400 unsupportedFeature`. So does any unknown query parameter. ### Response For `events.watch`, a `200` response returns: - `kind: "api#channel"` - `id` - `resourceId`: `calendar-` - `resourceUri`: `/calendar/v3/calendars//events`, with `` URL-encoded - `expiration`: a millisecond string - `token`: only if set `` is the watched calendar's actual ID, even if you registered with `primary`. Pass the returned `resourceId` to `channels.stop`. Channels cannot be renewed in place. Register a new channel instead, with a new `id` or with the same `id` after you stop the old channel. ### Stop a channel To stop a channel, send `POST /calendar/v3/channels/stop` with a JSON body that contains only `id` and `resourceId`. - **Body**: Other body fields fail with `400 unsupportedFeature`. - **Token**: Use a token from the same OAuth connection (grant) that created the channel. It needs an event-read or calendar-list-read scope. - **Success**: Returns `204` and aborts any queued or in-flight deliveries. - **Not found**: An unknown `id`, a mismatched `resourceId`, or a token from another connection returns `404 notFound`. Expiration alone does not cause `404`. A matching channel that has expired but has not yet been pruned still returns `204`. After pruning, its `id` is no longer found. ## What your callback receives Calendarpit queues an initial `sync` notification (message number `1`) before it returns the watch response. The callback can therefore arrive before your caller receives the `200` response. For `events.watch`, Calendarpit then sends an `exists` notification after each committed event write on every affected calendar: - **Writes**: insert, update, patch, or delete. - **Sources**: the Calendar API, the management API, or the admin UI. - **Included**: attendee copies and organizer RSVP updates. - **Excluded**: user and calendar metadata edits do not trigger event channel notifications. Each delivery is an HTTP `POST` to `address` with an **empty body**. Calendarpit never sends resource payloads, `X-Goog-Changed`, or OAuth access tokens to callbacks. When your receiver gets an event notification, call `events.list` with your saved `syncToken` to fetch changes (see [Incremental sync](https://calendarpit.dev/sync.md)). | Header | Value | | --------------------------- | ---------------------------------------------------------------------------- | | `X-Goog-Channel-ID` | Channel `id` from registration | | `X-Goog-Resource-ID` | Resource identifier (`calendar-` or `calendarList-`) | | `X-Goog-Resource-URI` | Endpoint URL for the watched calendar's events or the user's calendar list | | `X-Goog-Resource-State` | `sync` on channel creation, `exists` after a watched change | | `X-Goog-Message-Number` | Integer starting at `1`, incremented by 1 per notification (reused on retry) | | `X-Goog-Channel-Expiration` | Expiration time in RFC 1123 UTC format | | `X-Goog-Channel-Token` | Channel `token`, included only when set at registration | ## Calendar list To watch a user's calendar list, send `POST /calendar/v3/users/me/calendarList/watch`. It requires a calendar-list-read scope: `calendar`, `calendar.readonly`, `calendar.calendarlist`, or `calendar.calendarlist.readonly`. Other scopes fail with `403`. It follows the same rules as `events.watch` for: - Request body fields - The shared channel ID space - Lifetime limits - The callback host allowlist - Headers - Retry policy - The delivery log - `channels.stop` Any `params` field (including `params.ttl`) fails with `400 unsupportedFeature`. So does any non-system query parameter. Set `expiration` instead. A `200` response returns `resourceId: "calendarList-"` and `resourceUri: "/calendar/v3/users/me/calendarList"`. To stop the channel, send `POST /calendar/v3/channels/stop` with a token from the same OAuth connection that created it. ### Calendar list notifications The channel queues an initial `sync` notification (`1`). It then sends `exists` when: - A calendar-list write (`insert`, `patch`, `update`, or `delete`) changes the user's stored list settings. - One of the user's own calendars is created, updated, or deleted through the management API or admin UI. Any management `PATCH` counts as an update, even one that changes nothing. These changes do not notify `calendarList.watch` channels: - No-op calendar-list writes - Event writes - Changes to another user's calendars - User metadata edits Calendar-list writes do not notify `events.watch` channels. Calendar lists do not support `syncToken`. When a callback arrives, refetch with `calendarList.list`. ## Allowed callback hosts Unlike Google Calendar, Calendarpit permits plain `http:` callbacks. By default, only `127.0.0.1`, `[::1]`, and `localhost` are allowed. `localhost` delivers to `127.0.0.1`. To allow other containers or test hosts, set `CALENDARPIT_WATCH_HOSTS` to a comma-separated list of hostnames. For example: `CALENDARPIT_WATCH_HOSTS=app,host.docker.internal`. - Each entry must match the callback URL's hostname exactly. - Write entries in lowercase, with no port or wildcards. - Use brackets and compressed form for IPv6, for example `[fd00::1]`. Callback URLs fail with `400` if they have any of the following: - A non-HTTP(S) scheme - Credentials - A non-empty `#fragment` - A disallowed host Calendarpit checks the allowlist at registration, before each delivery attempt, and when it restores channels on startup. ## Delivery policy and lifecycle | Setting | Value | | ------------------------- | ----------------------------------------------------------------------------- | | Attempts per notification | Up to 3 (initial attempt plus 2 retries) | | Per-attempt timeout | 2000 ms | | Delay between attempts | 100 ms | | Success status codes | `200`, `201`, `202`, `204` (redirects are not followed and count as failures) | | Ordering | Serialized per channel | | Delivery log | Latest 200 records (`queued`, `delivered`, `failed`, `cancelled`) | ### When a channel stops A channel stops when any of the following happens. Its queued or in-flight deliveries are then marked `cancelled`. - You call `channels.stop`. - The channel expires. - Its OAuth connection is revoked. - Its user is deleted. Related cases: - **Calendar deletion**: Deleting a calendar stops `events.watch` channels on that calendar. The owner's `calendarList.watch` channels remain active and receive `exists`. - **Reset and fixture load**: `POST /__calendarpit/reset` or `POST /__calendarpit/fixtures` stops all channels and clears the delivery log (see [Test control API](https://calendarpit.dev/test-control.md)). - **Expired channels**: Calendarpit prunes expired channels lazily: when a channel is opened, when event or calendar-list notifications run, or when state is read. Pruning frees their `id` for reuse. Deliveries to an expired channel are cancelled. ### Restarts Calendarpit does not keep a durable delivery queue across restarts. - **SQLite mode**: Unexpired event and calendar-list channels and their message counters resume on restart. This requires that their OAuth connection is still valid and their callback host passes the allowlist. - **Interrupted deliveries**: Deliveries interrupted by shutdown are marked `cancelled` and are not replayed. - **Downtime**: Changes made while the server is down produce no notifications. - **`:memory:` mode**: All channels are lost on restart (see [Storage and restarts](https://calendarpit.dev/storage.md)). ## Inspect and drain deliveries in tests The admin UI shows the latest 200 delivery records with their attempt counts, status, and last HTTP status code. In automated tests, call `POST /__calendarpit/deliveries/drain` with `Content-Type: application/json`. It waits for all pending deliveries and their retries to finish: ```sh curl -X POST http://127.0.0.1:4173/__calendarpit/deliveries/drain \ -H "Content-Type: application/json" \ -d '{}' ``` The endpoint returns `200` with the full delivery log array. Deliveries queued after the drain call starts are not awaited. # Scope and limitations > What Calendarpit covers, what it leaves out, and the current project status. Source: https://calendarpit.dev/scope/ Calendarpit is a local Google Calendar-compatible API and OAuth server. It lets you develop and test your app without a real Google account, a Google Cloud project, or network access to Google. It implements the subset of the following that local development, CI, and end-to-end tests need: - Google Calendar API v3 - OAuth 2.0 - Incremental sync - Webhook notifications ## What is covered Everything in this section is implemented. ### Runtime and state - One Bun process serves the API, the OAuth flow, and the admin UI. - The default address is `http://127.0.0.1:4173`. - Storage is SQLite or `:memory:`. See [Run and configure](https://calendarpit.dev/running.md) and [Storage and restarts](https://calendarpit.dev/storage.md). ### Test users and calendars - Passwordless test users own calendars. - Each calendar has an IANA time zone. - Each user has a primary calendar, reachable as `primary`. - You read calendars with `calendars.get`. - You manage each user's list with `calendarList` (`list`, `get`, `insert`, `patch`, `update`, `delete`). Per-user list settings include: - `summaryOverride` - `colorId`, or custom RGB with `colorRgbFormat` - `hidden` and `selected` - `defaultReminders` - `notificationSettings` - Removing or restoring non-primary owned calendars ### Events and availability - Event CRUD: `list`, `get`, `insert`, `update`, `patch`, `delete`, and `instances` - Recurrence with exceptions, using a subset of `RRULE`, `EXRULE`, `RDATE`, and `EXDATE` - DST-aware `[start, end)` intervals - ETags and extended properties - Local invitations and RSVP - Stored reminders - Synthetic `hangoutsMeet` links - `freebusy.query` A series without `COUNT` or `UNTIL` is unbounded. If a calendar contains one, listing or expanding that calendar requires `timeMax` whenever you use `timeMin` or `singleEvents=true`. See [Calendar API compatibility](https://calendarpit.dev/compatibility.md) and [Events, recurrence and time](https://calendarpit.dev/recurrence.md). ### OAuth - Local consent page with a test-user selector - Approval and denial, with `state` preservation - Exact `redirect_uri` checks - OAuth client editing in the admin UI and the management API, without reloading a fixture - Code exchange with `S256` PKCE - Scope checks - Refresh tokens, `/userinfo`, and revocation See [Local OAuth](https://calendarpit.dev/oauth.md). ### Incremental sync - `nextSyncToken` and `syncToken` on `events.list` - Frozen paginated snapshots - `status: "cancelled"` tombstones - `410 fullSyncRequired` responses See [Incremental sync](https://calendarpit.dev/sync.md). ### Watch - `events.watch`, `calendarList.watch`, and `channels.stop` - `sync` and `exists` webhooks - A callback host allowlist - Up to 3 delivery attempts - Channel expiry - `POST /__calendarpit/deliveries/drain` See [Watch notifications](https://calendarpit.dev/watch.md). ### Admin UI - Day and week views - Live updates pushed from the server over Server-Sent Events - A basic event editor - User and calendar management - Connection revocation - Watch and delivery logs - Masked request history - Fixture and reset controls - Calendar API rate-limit simulation (`off` by default, `production`, or `error-test`) - A command palette and keyboard shortcuts ### Test control - Startup JSON fixtures, with optional fixed IDs - `/__calendarpit/*` management endpoints that inspect state, load fixtures, reset to the baseline, and manage data See [Fixtures](https://calendarpit.dev/fixtures.md) and [Test control API](https://calendarpit.dev/test-control.md). ## Guarantees ### Loopback by default - The server binds to `127.0.0.1` unless you set `--host` or `CALENDARPIT_HOST`. - The `Dockerfile` explicitly binds `0.0.0.0` inside the container. - Webhook callbacks only target loopback hosts unless you configure `CALENDARPIT_WATCH_HOSTS`. ### Explicit errors for unsupported features Unsupported features return an explicit error. | Request | Status | Error | | ------------------------------------------------------- | ------ | ------------------------------ | | Unsupported Calendar API endpoint | `501` | `reason: "unsupportedFeature"` | | Unsupported query parameter, field, or recurrence rule | `400` | `reason: "unsupportedFeature"` | | `events.import` | `404` | `notFound` | | `events.quickAdd` with its `text` parameter | `400` | `unsupportedFeature` | | `events.quickAdd` without `text` | `404` | `notFound` | | OAuth authorization request with unsupported parameters | `400` | `error: "unsupported_feature"` | | Unsupported OAuth endpoint | `501` | `error: "unsupportedFeature"` | > [!WARNING] > > Calendarpit rejects an unsupported recurrence rule with `400 unsupportedFeature`. It does not store the event without the rule. > ### No real Google calls - Calendarpit never sends API, OAuth, or webhook requests to Google. - The admin UI loads the Roboto Mono font from Google Fonts, with a system-font fallback. ### Deterministic reset `POST /__calendarpit/reset` restores the startup fixture with the same IDs and calendar-list ETags. It clears: - Tokens - Channels - History - Calendar-list settings - Deleted-calendar tombstones - Edits Behavior across restarts depends on the storage mode: - **SQLite**: The reset baseline, calendar-list settings, and tombstones survive restarts. - **`:memory:`**: Set fixed IDs in the fixture to keep IDs stable across restarts. ## What is out of scope Calendarpit does not implement the following. ### ACLs, shared calendars, and delegation - Users only access their own calendars (`accessRole: "owner"`). - All `acl.*` methods return `501 unsupportedFeature`. - `calendarList.insert` only restores an owned calendar removed by `calendarList.delete`. - It never creates a calendar or subscribes to another user's calendar. - It returns `409 duplicate` if the calendar (including `primary`) is already on the list. ### Settings, ACL/settings watch, and CalendarList sync tokens These are unsupported: - All `settings.*` methods return `501 unsupportedFeature`. - ACL and settings watch subscriptions (`acl.watch`, `settings.watch`) return `501 unsupportedFeature`. - `calendarList.list` does not issue `nextSyncToken`. It rejects `syncToken` with `400 unsupportedFeature`. `calendarList.watch` is implemented for the owning user's list, with these limits: - It rejects any `params` object with `400 unsupportedFeature`. - It sends `exists` only on list writes that change stored settings. - It also sends `exists` on management calendar creates, updates, or deletes for that user's calendars. With `showDeleted=true`: - Entries removed by `calendarList.delete` keep their stored settings. - Tombstones of management-deleted calendars show default settings. They keep `primary: true` if the calendar was deleted while primary. ### Calendar writes, colors, and `events.import`/`quickAdd`/`move` These methods are not implemented: - `calendars.insert`, `update`, `patch`, `delete`, `clear`, and `transferOwnership` - `colors.get` - `events.import`, `quickAdd`, and `move` Manage calendars through the admin UI or the management API. See [Calendar API compatibility](https://calendarpit.dev/compatibility.md). ### Real invitation and reminder email - `sendUpdates` records notification intent in `/__calendarpit/state`. It does not send email. - Calendarpit stores reminders, `calendarList` `defaultReminders`, and `notificationSettings`. Nothing fires or sends email. - `notificationSettings` rejects duplicate notification `type` values with `400 invalidParameter`. ### Real Google Meet Conference requests generate deterministic `https://meet.calendarpit.invalid/` URLs. No real meeting is created. ### Full OIDC These are not supported: - Passwords - Real Google login - `id_token` issuance - JWKS and discovery endpoints ### Other protocols and real Google sync Microsoft Graph, CalDAV, and syncing with real Google Calendar are excluded. ### Dragging events in the admin UI - Moving or resizing events by dragging is not implemented. - The admin views show a recurring series (not its occurrences) only on its start date. Stored exceptions appear on their own dates. - The admin editor covers only basic fields. > [!WARNING] > > Saving an event in the admin editor replaces it with only the basic fields. This removes: > > - Recurrence, which also cancels stored exceptions > - Attendees, which also cancels their invitation copies > - Conference data > - Color > - Visibility > > Custom reminders reset to the default (`reminders: { useDefault: true }`). Set those fields through the API. > Fixtures store these fields as-is. They do not create invitation copies or synthetic meeting links. See [Fixtures](https://calendarpit.dev/fixtures.md). ## A workflow Calendarpit reproduces Calendarpit reproduces this end-to-end integration workflow. For the Google SDK sample flow, see [SDK examples](https://calendarpit.dev/sdks.md). 1. Authorize as a test user on the local consent page and select a calendar. 2. Register an `events.watch` channel and receive the initial `sync` notification. 3. Create an event and verify its busy interval with `freebusy.query`. 4. Update and delete the event, receive `exists` notifications, and refetch state. 5. Stop the watch channel with `channels.stop` and confirm further changes are not delivered. 6. Revoke the connection and reconnect through OAuth. 7. Deny consent and verify that `state` is preserved without losing existing tokens. 8. Reset with `POST /__calendarpit/reset` and repeat the flow with the same fixtures and IDs. 9. Fetch a full `events.list` snapshot, then consume changes and `status: "cancelled"` deletions with `syncToken`. 10. Exercise all-day events (including `dateTime: null`), recurring exceptions, local RSVP, and synthetic meeting links. ## Current status - **Distribution**: Docker images, the Homebrew tap, and standalone executables are available. See [Installation](https://calendarpit.dev/installation.md) for setup. - **Standalone executables**: They embed Bun, the API, and the admin UI. Release targets are macOS arm64/x64, Linux glibc arm64/x64, and Windows x64. Each target requires native validation before publication. - **Docker**: The image configures a non-root user, a persistent volume, a health check, and memory mode. Release checks cover amd64/arm64 startup and storage lifecycles. # Troubleshooting > Find the cause and fix for common startup, OAuth, Calendar API, sync, watch, and management API errors in Calendarpit. Source: https://calendarpit.dev/troubleshooting/ When a request fails, Calendarpit returns an explicit status code and error message. It does not silently ignore unsupported fields or parameters. To investigate a failure, open **API history** (`http://127.0.0.1:4173/history`) in the admin UI: - It shows the latest 200 Calendar API and OAuth exchanges. - Each entry records the HTTP method, path, status code, headers, and masked request and response bodies. - The **Errors** toggle filters for responses with status `400` or higher. Each entry on this page follows the same pattern: the exact **Error** output (when there is one), the likely **Cause**, and the **Fix**. ## Error response formats ### Google API error envelope Calendar API routes (`/calendar/v3/*`), `/userinfo`, and management API routes (`/__calendarpit/*`) return the Google API error envelope: ```json { "error": { "code": 404, "message": "Event not found.", "errors": [ { "domain": "calendarpit", "reason": "notFound", "message": "Event not found." } ] } } ``` - `domain` is `"calendarpit"` on top-level errors, except simulated Calendar API quota errors, which use `"usageLimits"` as Google does. Per-calendar errors inside a `freebusy.query` response use `"domain": "global"`. - `401` responses include the `WWW-Authenticate: Bearer` header. - `400` validation errors without a more specific reason use `"reason": "invalidParameter"`. ### OAuth error format OAuth routes (`/oauth/*` and `/oauth2/*`) return the OAuth error format. Most errors are HTTP `400`, with these exceptions: - Unimplemented paths return `501`. - Too many pending consent requests return `429`. - A cross-origin consent submission returns `403`. ```json { "error": "invalid_grant", "error_description": "Invalid, expired, or mismatched authorization code." } ``` Validation errors on `GET /oauth/authorize` are returned directly in the browser as HTTP `400` JSON. Calendarpit does not redirect invalid authorization requests back to `redirect_uri`. ## Starting Calendarpit CLI startup failures print `Calendarpit: ` to `stderr` and exit with code `1`. For Docker, inspect the server output with `docker compose logs calendarpit`. ### Port already in use - **Error**: `Calendarpit: Failed to start server. Is port 4173 in use?` - **Cause**: Another process is listening on port `4173`. - **Fix**: Stop that process, or choose another port with `--port `. With `--port 0`, read the actual `Admin` URL. In Docker, change the host side of the mapping, for example `127.0.0.1:4174:4173`, and open port `4174`. ### Database already in use - **Error**: `Calendarpit: Database is already in use: . Use a separate path or :memory:.` - **Cause**: Another process holds the lock on the same SQLite file. - **Fix**: Stop that process, or give each process its own `--database` path or `:memory:`. See [Storage and restarts](https://calendarpit.dev/storage.md). ### Fixture file not found - **Error**: `Calendarpit: Fixture file not found: . …` - **Cause**: The fixture path does not exist in the current working directory or inside the container. - **Fix**: Use a valid absolute path. In Docker, mount the file and pass its container path. See [Fixtures](https://calendarpit.dev/fixtures.md). ### Fixture path is a directory - **Error**: `Calendarpit: Fixture path is a directory, not a file: ` - **Cause**: In a container, the bind mount source was not shared with the container runtime's VM, so Docker mounted an empty directory at the target. This happens with Colima for paths outside your home directory. A source path that does not exist on the host has the same effect. - **Fix**: Share the host directory with the runtime (for Colima, add it to `mounts` in `colima.yaml` and restart Colima), or copy the file into the container with `docker cp` before starting it. See [Share the host directory with the container runtime](https://calendarpit.dev/fixtures.md#share-the-host-directory-with-the-container-runtime). ### Fixture file is not readable or not JSON - **Error**: `Calendarpit: Fixture file is not readable: . …` or `Calendarpit: Fixture file is not valid JSON: ()` - **Cause**: The container's non-root user cannot read the file, or the file is not valid JSON. - **Fix**: Make the file readable by other users (for example, mode `644`), or fix the JSON syntax. ### Fixture fails validation - **Error**: `Calendarpit: Each user with calendars must have exactly one primary calendar.` - **Cause**: The startup fixture fails validation. - **Fix**: Give each user with calendars exactly one `"primary": true` calendar. See the [fixture rules](https://calendarpit.dev/fixtures.md). ### Fixture edits have no effect after restart - **Cause**: Startup fixtures only seed a new database. Existing data and the reset baseline are retained. - **Fix**: - To replace current data, load the file via **Settings → Test data** or `POST /__calendarpit/fixtures`. - To use a new reset baseline, start with a new database path or `:memory:`. ### Data is missing after changing how Calendarpit starts - **Cause**: One of the following: - The working directory changed. - A different database path or volume was used. - The previous session used `:memory:`. - **Fix**: Check `Data ` in startup output and **Settings → Test data**. Use the same absolute database path or Docker volume. ### The browser, backend, or webhook receiver cannot connect in Docker - **Cause**: Loopback points to the requesting container itself. A browser cannot resolve a Compose service name. - **Fix**: Use the host-published URL in the browser and the service name between containers. For webhook receivers, configure `CALENDARPIT_WATCH_HOSTS`. See [container networking](https://calendarpit.dev/installation.md). ### A `CALENDARPIT_*` value seems ignored - **Cause**: A CLI flag overrides the environment variable, or the variable was set on the host but not passed to Docker. - **Fix**: Remove the overriding flag, or pass the variable with `docker run -e` or Compose `environment`. When you change the container port, also update its mapping and `CALENDARPIT_PORT` for the health check. ### Invalid option value, unknown option, or unknown command - **Cause**: The CLI received an invalid flag, empty value, or unsupported subcommand. - **Fix**: Run `calendarpit --help`. Only `serve` is supported. Ports must be integers from `0` to `65535`. ## OAuth ### A real Google consent screen appears - **Cause**: Your app's authorization URL still points to Google (`accounts.google.com`). - **Fix**: Set the authorization URL to `http://127.0.0.1:4173/oauth/authorize`. See [Connect your app](https://calendarpit.dev/connect.md). ### Token exchange or refresh contacts Google - **Cause**: Your OAuth client still uses Google's token endpoint. Setting the Calendar API endpoint does not redirect OAuth calls. - **Fix**: Override the token URL to `http://127.0.0.1:4173/oauth/token`. If you use `/oauth/revoke` and `/userinfo`, override them too. See [Local OAuth](https://calendarpit.dev/oauth.md). ### Google's default OAuth paths return `501` - **Error**: `501 unsupportedFeature` on `/oauth2/...` or `/oauth/tokeninfo` - **Cause**: Your SDK is calling Google's default OAuth paths: `/oauth2/v4/token`, `/oauth2/v3/userinfo`, or `/oauth/tokeninfo`. - **Fix**: Override the endpoints explicitly to `/oauth/authorize`, `/oauth/token`, `/oauth/revoke`, and `/userinfo`. ### Unregistered redirect URI - **Error**: `invalid_request`: `Unregistered redirect URI.` - **Cause**: `redirect_uri` does not exactly match an entry in `clients[].redirectUris`. - The match covers `localhost` vs `127.0.0.1`, port, path, and trailing slash. - Changing `SAMPLE_PORT` from `4175` also causes a mismatch with the built-in `sample-app` client. - **Fix**: Copy the exact `redirect_uri` string into `clients[].redirectUris` in your fixture. ### Unknown client - **Error**: `invalid_client`: `Unknown client.` - **Cause**: One of the following: - `client_id` is not registered in the fixture. - `POST /oauth/token` used a JSON body instead of `application/x-www-form-urlencoded`. With HTTP Basic authentication, a JSON body returns `unsupported_grant_type` instead. - **Fix**: Register the client in your fixture. Send token requests as `application/x-www-form-urlencoded`. ### Invalid client secret - **Error**: `invalid_client`: `Invalid client secret.` - **Cause**: `client_secret` is missing or wrong. Calendarpit requires a client secret on every token request, including PKCE flows. - **Fix**: Send the matching `client_secret` in the form body or via HTTP Basic authentication. ### Invalid authorization code - **Error**: `invalid_grant`: `Invalid, expired, or mismatched authorization code.` - **Cause**: One of the following: - The code is older than 60 seconds. - The code was already used once. - `redirect_uri` is missing or differs from the one sent to `/oauth/authorize`. - The client differs. - The connection was revoked. - The server restarted. - **Fix**: Exchange the code once within 60 seconds. Use the exact `redirect_uri` and client used at `/oauth/authorize`. ### Invalid PKCE verifier - **Error**: `invalid_grant`: `Invalid PKCE verifier.` - **Cause**: `code_verifier` does not match the `S256` `code_challenge`, or is not 43–128 characters of `[A-Za-z0-9._~-]`. - **Fix**: Send the original verifier string used to compute the `S256` challenge. ### Invalid refresh token - **Error**: `invalid_grant`: `Invalid refresh token.` - **Cause**: One of the following: - The connection was revoked. - The user was deleted. - The workspace was reset or a fixture was loaded. - An in-memory server restarted. - The token belongs to another client. - **Fix**: Run the authorization flow again to create a new connection. ### `state` is missing or mismatches on callback - **Cause**: One of the following: - `state` was omitted from `/oauth/authorize`. It is echoed only when sent. - Your app started on `localhost` and received the callback on `127.0.0.1`. Cookies holding `state` are not shared across hostnames. - **Fix**: Pass `state` on `/oauth/authorize`. Use the same hostname (`127.0.0.1` or `localhost`) for both your app and its `redirect_uri`. ### Unsupported or missing scope - **Error**: `invalid_scope`: `Unsupported or missing scope.` - **Cause**: `scope` is empty or includes an unsupported scope, such as `calendar.events.owned` or Drive scopes. - **Fix**: Request only [supported scopes](https://calendarpit.dev/oauth.md). ### Scope changes on refresh - **Error**: `invalid_scope`: `Refresh scope changes are unsupported.` - **Cause**: A `refresh_token` request included a `scope` parameter that does not exactly match the original grant string. Scope order counts. - **Fix**: Omit `scope` when refreshing a token. ### No `refresh_token` in the token response - **Cause**: One of the following: - `access_type=offline` was not sent on `/oauth/authorize`. - The response is from a `refresh_token` grant. Refresh responses return a new `access_token` only, and the original refresh token stays valid. - **Fix**: Add `access_type=offline` to `/oauth/authorize`, and keep the initial `refresh_token`. ### Unsupported authorization parameters - **Error**: `unsupported_feature` on `/oauth/authorize` - **Cause**: The request included one of the following: - `prompt=none` - `include_granted_scopes=true` - An unsupported parameter such as `nonce`, `login_hint`, `hd`, or `enable_granular_consent` - **Fix**: Remove unsupported parameters. Use interactive consent (`prompt=consent` or `prompt=select_account`). ### Invalid PKCE challenge - **Error**: `invalid_request`: `PKCE requires S256.` or `Missing PKCE challenge.` - **Cause**: One of the following: - `code_challenge` was sent without `code_challenge_method=S256` (including `plain`). - `code_challenge_method` was sent without `code_challenge`. - `code_challenge` is not 43 base64url characters. - **Fix**: Use `code_challenge_method=S256` with a 43-character base64url challenge. ### Consent request expired or already used - **Error**: `invalid_request`: `Consent request expired or already used.` - **Cause**: One of the following: - The consent page was left open longer than 5 minutes. - The consent page was submitted twice. - The server restarted before submission. - **Fix**: Start a fresh authorization request at `/oauth/authorize`. ### Too many pending consent requests - **Error**: `429 rateLimitExceeded`: `Too many pending consent requests.` - **Cause**: 1,000 consent requests are already pending. Each expires after 5 minutes. A loop in tests usually causes this. - **Fix**: Complete pending consent requests or stop opening new ones, or reset the workspace. ## Calendar API and SDKs ### Simulated Calendar API rate limit - **Error**: `403 userRateLimitExceeded` (`User Rate Limit Exceeded`), `403` or `429 rateLimitExceeded` (`Rate Limit Exceeded`), or `403 quotaExceeded` (`Calendar usage limits exceeded.`). - **Cause**: The rate-limit mode (**Settings → Developer**, `--rate-limit`, or `CALENDARPIT_RATE_LIMIT`) is `production` or `error-test`, and the request exceeded that mode's limits. `off` does not limit requests. The separate consent error `429 rateLimitExceeded`: `Too many pending consent requests.` is not this quota. - **Fix**: Set the mode to `off`, wait for the `Retry-After` window, or reset the workspace to clear the counters. See [Calendar API rate limits](https://calendarpit.dev/running.md#calendar-api-rate-limits). ### Invalid or expired access token - **Error**: `401 authError`: `Invalid or expired access token.` - **Cause**: One of the following: - The `Authorization: Bearer` header is missing or malformed. - The access token expired (1-hour TTL). - The connection was revoked. - The workspace was reset or a fixture was loaded. - An in-memory server restarted. - A real Google token was sent. - **Fix**: Refresh the token at `/oauth/token`. After a reset, fixture load, or revocation, authorize again. ### Insufficient scope - **Error**: `403 insufficientPermissions`: `Insufficient scope.` - **Cause**: The token lacks a required scope. For example: - Writing events with a `.readonly` scope. - Calling `calendarList.list` with only `calendar.events`. - Calling `/userinfo` without `openid`, `email`, or `profile`. - **Fix**: Request a scope that covers the endpoint and re-authorize. See [Local OAuth](https://calendarpit.dev/oauth.md). ### Unsupported API endpoint or method - **Error**: `501 unsupportedFeature`: `Unsupported API endpoint or method.` This includes doubled `/calendar/v3/calendar/v3/...` paths. - **Cause**: One of the following: - You called an unimplemented Google endpoint: `acl`, `settings`, `colors`, `calendars.insert`, or `events.move`. - You sent `HEAD` to an API path. Some paths answer `HEAD` differently, as listed below. - You sent `POST` to `/users/me/calendarList/{calendarId}`. - The SDK base URL is misconfigured, so the SDK doubled `/calendar/v3`. - **Fix**: Check [Calendar API compatibility](https://calendarpit.dev/compatibility.md). Set the SDK base URL as shown in the table below. See [SDK examples](https://calendarpit.dev/sdks.md). `HEAD` returns a different error on these paths: - Event paths respond with `405 methodNotAllowed`. - `/calendars/{calendarId}` returns `Unsupported calendar operation.` - An existing entry at `/users/me/calendarList/{calendarId}` returns `Unsupported calendar list operation.` | SDK | Base URL setting | | ------------------------------ | ---------------------------------------------------------------- | | JS/TS (`@googleapis/calendar`) | Set `rootUrl` to `http://127.0.0.1:4173/`. | | Kotlin | Set `rootUrl` to the origin and `servicePath` to `calendar/v3/`. | | PHP (`google/apiclient`) | Pass `http://127.0.0.1:4173/` as `$rootUrl`. | | Python, Go, and C# | Include `/calendar/v3/`. | ### Unsupported calendar or calendar list operation - **Error**: `501 unsupportedFeature`: `Unsupported calendar operation.` or `Unsupported calendar list operation.` - **Cause**: One of the following: - You called `PUT`, `PATCH`, `DELETE`, or `HEAD` on `/calendar/v3/calendars/{calendarId}`. - You called an unsupported method such as `HEAD` or `OPTIONS` on an existing entry at `/calendar/v3/users/me/calendarList/{calendarId}`. `POST` there returns `Unsupported API endpoint or method.` instead. - **Fix**: Manage calendars in the admin UI or via `/__calendarpit/calendars`. For per-user display settings, use `calendarList.patch`. See [Test control API](https://calendarpit.dev/test-control.md). ### Calendar not found - **Error**: `404 notFound`: `Calendar not found.` - **Cause**: One of the following: - The calendar ID is unknown. - The calendar is owned by a different test user. - You used `primary` for a user with no calendars. - The calendar was removed from the user's list with `calendarList.delete`. This applies to calendar-list methods only. - **Fix**: Use a calendar ID owned by the authenticated user, or authorize as that calendar's owner. Restore a removed list entry with `calendarList.insert`. ### Event not found - **Error**: `404 notFound`: `Event not found.` - **Cause**: One of the following: - The event ID is unknown in that calendar. - You called `POST .../events/import` or `POST .../events/quickAdd` (without `text`). Calendarpit treats `import` or `quickAdd` as an event ID. - **Fix**: Check the event ID. Use `events.insert` instead of `import` or `quickAdd`. ### Unsupported event method - **Error**: `405 methodNotAllowed`: `Unsupported event method.` or `Unsupported instances operation.` - **Cause**: The HTTP verb is invalid for the event route. For example: - `HEAD` - `DELETE` on `/events` - `POST` on an existing `/events/{eventId}` - A write to `/instances` - **Fix**: Use the supported HTTP method and path. ### Unsupported query parameter - **Error**: `400 unsupportedFeature`: `Unsupported query parameter: ` - **Cause**: The query parameter is not on the endpoint allowlist. Examples include `fields`, `q`, `eventTypes`, `sendNotifications`, `supportsAttachments`, `maxAttendees`, and `text`. - **Fix**: Remove the parameter. Disable automatic `fields` partial-response masks in your SDK. ### Unsupported field - **Error**: `400 unsupportedFeature`: `Unsupported field: ` - **Cause**: The request body contains an unsupported field. For example: - `eventType`, `attachments`, `source`, or `htmlLink` on events. - An `items[]` entry with keys other than `id` on FreeBusy. - **Fix**: Strip unsupported fields before sending the request. See [Calendar API compatibility](https://calendarpit.dev/compatibility.md). ### Non-JSON response format - **Error**: `400 invalidParameter`: `Only JSON responses are supported.` - **Cause**: The query included `alt=media` or `alt=proto`. - **Fix**: Omit `alt` or use `alt=json`. ### Timestamp without an offset - **Error**: `400`: `Expected an RFC3339 timestamp with an offset.` or `dateTime requires an offset or timeZone.` - **Cause**: One of the following: - `timeMin`, `timeMax`, `updatedMin`, or FreeBusy bounds lack `Z` or `±HH:MM`. - An event `dateTime` has neither an offset nor `timeZone`. - **Fix**: Add `Z` or a `±HH:MM` offset, or supply `timeZone` on the event `start`/`end`. ### Invalid or ambiguous local time - **Error**: `400`: `Invalid or ambiguous local time; supply an explicit offset.` - **Cause**: An offset-less `dateTime` falls inside a DST gap or overlap in `timeZone`. - **Fix**: Include an explicit numeric offset on `dateTime`. ### Recurring event time zone or `UNTIL` errors - **Error**: `400`: `Recurring timed events require start.timeZone.` or `Timed recurrence UNTIL must be UTC.` - **Cause**: A timed recurring event has no `start.timeZone`, or its `UNTIL` value does not end with `Z`. - **Fix**: Set `start.timeZone`. Write timed `UNTIL` timestamps in UTC (`...Z`). See [Events, recurrence and time](https://calendarpit.dev/recurrence.md). ### Unsupported recurrence rule or expansion - **Error**: `400 unsupportedFeature` on recurrence rules or expansion - **Cause**: One of the following: - The rule uses `HOURLY` or `MINUTELY`. - The rule uses an unsupported part: `BYHOUR`, `BYWEEKNO`, or `BYYEARDAY`. - The rule includes another iCalendar line (`DTSTART`). - An occurrence falls in a DST gap. - An unbounded rule is expanded without `timeMax`. - The expansion exceeds 10,000 instances or 100 years. - **Fix**: Use supported `DAILY`, `WEEKLY`, `MONTHLY`, or `YEARLY` rules. Supply `timeMax` and a narrower window. See [Events, recurrence and time](https://calendarpit.dev/recurrence.md). ### `orderBy=startTime` without `singleEvents` - **Error**: `400`: `startTime ordering requires singleEvents=true.` - **Cause**: `orderBy=startTime` was sent without `singleEvents=true`. - **Fix**: Add `singleEvents=true` to the `events.list` query. ### Event is not a recurring series - **Error**: `400`: `Event is not a recurring series.` - **Cause**: `events.instances` was called on a non-recurring event. - **Fix**: Call `events.instances` only on recurring series masters. ### Read-only field changed - **Error**: `400`: ` is read-only.` - **Cause**: One of the following: - A Calendar API write changed `organizer`, `creator`, `iCalUID`, `recurringEventId`, or `originalStartTime`. - A `calendarList` write changed `summary`, `timeZone`, `accessRole`, `primary`, `kind`, `deleted`, or `conferenceProperties`. - **Fix**: Omit the field or send the existing value unchanged. - For a per-user calendar name, set `summaryOverride`. - To set custom organizer metadata, use [Fixtures](https://calendarpit.dev/fixtures.md) or the [Test control API](https://calendarpit.dev/test-control.md). ### `conferenceData` without `conferenceDataVersion` - **Error**: `400`: `conferenceData requires conferenceDataVersion=1.` - **Cause**: The event payload includes `conferenceData` without `?conferenceDataVersion=1`. - **Fix**: Add `conferenceDataVersion=1` to the query string. ### Cannot remove the primary calendar - **Error**: `403 cannotDeletePrimaryCalendar`: `Cannot remove the primary calendar from the calendar list.` - **Cause**: `calendarList.delete` was called on the user's primary calendar. - **Fix**: Keep the primary calendar in the list. To hide it, use `calendarList.patch` with `hidden: true` or `selected: false`. ### Invitee edits are rejected - **Error**: `403 forbiddenForNonOrganizer` - **Cause**: An invitee editing an invitation copy did one of the following: - Used `PUT`. - Changed shared event fields. - Edited another attendee. - **Fix**: Use `PATCH`. Update only your own `responseStatus`/`comment`, `reminders`, `colorId`, `transparency`, or `extendedProperties`. ### Duplicate event or calendar list entry - **Error**: `409 duplicate` with one of these messages: - `Duplicate event ID.` - `Invitation event ID conflicts with an existing local event.` - `Calendar already exists in the calendar list.` - **Cause**: One of the following: - `events.insert` reused an existing ID in that calendar. - An attendee invitation copy matched an event ID in the attendee's primary calendar with a different `iCalUID`. For example, the existing event's `iCalUID` was set through a fixture or the Test control API. An existing event with the default `iCalUID` is overwritten instead. - `calendarList.insert` was called for a calendar already in the list, including `primary`. - **Fix**: Use a unique event ID. Call `calendarList.insert` only for a calendar that is not in the list. ### Event is already deleted - **Error**: `410 deleted`: `Event is already deleted.` - **Cause**: `events.delete` was called on an event that is already `cancelled`. - **Fix**: Treat `410` on delete as already deleted. ### `etag` mismatch - **Error**: `412 conditionNotMet`: `Event has changed.` or `Calendar list entry has changed.` - **Cause**: The `If-Match` header does not match the current `etag` of the event or calendar-list entry. - **Fix**: Re-fetch with `events.get` or `calendarList.get` and retry. ### Request body too large - **Error**: `413 payloadTooLarge`: `Request body too large.` - **Cause**: The request body exceeds 1,048,576 bytes (1 MiB). - **Fix**: Reduce the payload size. ### `maxResults` out of range - **Error**: `400`: `maxResults must be between 1 and 2500.` - **Cause**: `maxResults` is `0`, negative, or greater than `2500`. - **Fix**: Set `maxResults` between `1` and `2500`. ### Python SDK fetches discovery documents from Google - **Cause**: `googleapiclient.discovery.build` tried to download discovery metadata from Google. - **Fix**: Use `google-api-python-client` 2.x with `static_discovery=True` and `cache_discovery=False`. Do not set a remote discovery URL. See [SDK examples](https://calendarpit.dev/sdks.md). ## Incremental sync and pagination ### Sync token is invalid or expired - **Error**: `410 fullSyncRequired`: `Sync token is invalid or expired. Perform a full synchronization.` - **Cause**: One of the following: - The `syncToken` is older than 7 days. - The `syncToken` was evicted because the workspace has more than 100 tokens. - The `syncToken` belongs to another calendar or user. - A reset, fixture load, or in-memory restart cleared the `syncToken`. - **Fix**: Discard local sync state and run a full `events.list` without `syncToken`. See [Incremental sync](https://calendarpit.dev/sync.md). ### Sync query options changed - **Error**: `400`: `Sync query options must match the initial synchronization.` - **Cause**: `singleEvents` or the effective `timeZone` differs from the initial sync. When `timeZone` was omitted, a calendar time zone change also counts. - **Fix**: Repeat the exact `singleEvents` and `timeZone` options from the initial full sync. ### Invalid `syncToken` combination - **Error**: `400` with one of these messages: - ` cannot be combined with syncToken.` - `Incremental synchronization must include deleted events.` - `instances does not support syncToken.` - **Cause**: One of the following: - `syncToken` was combined with `timeMin`, `timeMax`, `orderBy`, `updatedMin`, `iCalUID`, or extended property filters. - `syncToken` was sent with `showDeleted=false`. - `syncToken` was used on `events.instances`. - **Fix**: Send only `syncToken` on `events.list`. You may also send matching `singleEvents`, `timeZone`, `maxResults`, `pageToken`, or `showDeleted=true`. ### Invalid or expired page token - **Error**: `410 invalidPageToken`: `Invalid or expired page token.` or `Invalid or stale page token.` - **Cause**: The page token is no longer valid. - An event `pageToken` expired (1-hour TTL), was evicted (over 1,000 frozen pages), or was invalidated because query options changed or the server restarted or reset. - A `calendarList` `pageToken` was used after any workspace data write. - **Fix**: Restart listing from the first page. ## Watch notifications ### Watch host is not allowed - **Error**: `400`: `Watch host is not allowed. Configure CALENDARPIT_WATCH_HOSTS explicitly.` - **Cause**: The callback `address` hostname is not `127.0.0.1`, `[::1]`, or `localhost`. For example, it is `host.docker.internal` or a container service name. - **Fix**: Start Calendarpit with `CALENDARPIT_WATCH_HOSTS=,`. List hostnames only, without ports. See [Watch notifications](https://calendarpit.dev/watch.md). ### Invalid watch callback URL - **Error**: `400`: `Invalid watch callback URL.` - **Cause**: `address` is not `http:` or `https:`, or includes credentials or a `#fragment`. - **Fix**: Use a plain `http://` or `https://` callback URL. ### Invalid channel fields - **Error**: `400` with one of these messages: - `Only web_hook channels are supported.` - `Invalid channel ID.` - `Invalid channel token.` - `Invalid expiration.` - **Cause**: One of the following: - `type` is not `"web_hook"`. - `id` does not match `[A-Za-z0-9_-]{1,64}`. - `token` exceeds 256 characters or contains newlines. - `expiration` is not a future Unix millisecond integer. - **Fix**: Fix the invalid field in the `events.watch` or `calendarList.watch` request body. ### Duplicate channel ID - **Error**: `409 duplicate`: `Duplicate channel ID.` - **Cause**: Another active watch channel in the workspace already uses that `id`. - **Fix**: Generate a new unique `id` (such as a UUID) for each channel. ### Watch succeeds, but no notifications arrive at your app - **Cause**: Delivery to your webhook receiver failed. After 3 attempts, the delivery is marked `failed`. An attempt fails when the receiver: - Is unreachable. - Takes more than 2,000 ms. - Returns a status other than `200`, `201`, `202`, or `204`. 3xx redirects are not followed. - **Fix**: Open **Watch** (`http://127.0.0.1:4173/watch`) in the admin UI to inspect the delivery log status and HTTP status code. In tests, call `POST /__calendarpit/deliveries/drain` to wait for pending deliveries. ### Notifications stop arriving after restart, reset, or revocation - **Cause**: One of the following: - Restarting cancels queued deliveries. - An in-memory restart drops channels. - A restart with a disallowed callback host drops channels. - Resetting, loading a fixture, or revoking the connection stops channels. - Deleting a calendar stops the event channels on that calendar. - The channel expired. Channels expire after 24 hours by default, and after 7 days at most. - **Fix**: Re-fetch state after a restart. If the channel was stopped or expired, register a new watch channel. ### Channel not found on `channels.stop` - **Error**: `404 notFound`: `Channel not found.` on `channels.stop` - **Cause**: One of the following: - The `resourceId` is wrong. - The channel ID is unknown. - The channel was already stopped, or pruned after expiry. - `channels.stop` was called with a token from a different connection than the one that created the channel. - **Fix**: Call `channels.stop` with the creating connection's token and the matching `resourceId`. An expired channel that has not yet been pruned still returns `204`. See [Watch notifications](https://calendarpit.dev/watch.md). ## Management API ### Management writes require JSON - **Error**: `415 unsupportedMediaType`: `Management writes require application/json.` - **Cause**: A `POST`, `PATCH`, `PUT`, or `DELETE` request to `/__calendarpit/*` was sent without `Content-Type: application/json`. This includes bodyless calls like `/reset` or `/deliveries/drain`. - **Fix**: Include `-H 'Content-Type: application/json'` on every management write request. See [Test control API](https://calendarpit.dev/test-control.md). ### Cross-origin management request - **Error**: `403 forbidden`: `Cross-origin management requests are not allowed.` - **Cause**: A browser script on another origin called `/__calendarpit/*`. - **Fix**: Call `/__calendarpit/*` from your test runner, CLI, or backend, without a cross-origin `Origin` header. Or use the admin UI. ### State response posted as a fixture - **Error**: `400 unsupportedFeature`: `Unsupported field: storage` on `POST /__calendarpit/fixtures` - **Cause**: You posted a `GET /__calendarpit/state` response directly as a fixture. - **Fix**: Post a valid fixture object containing only `users`, `calendars`, `events`, and `clients`. Include the client `secret` values. See [Fixtures](https://calendarpit.dev/fixtures.md).