# TypeScript SDK

> @sunnysdk/client, the typed client for the /v1 API: install, authenticate, call resources, page through lists, and verify webhooks.

`@sunnysdk/client` is the typed TypeScript client for the [`/v1` API](/docs/api#v1-beta). It is generated from the `/v1` OpenAPI document, so every resource, request body and response is typed, and it adds retries, idempotency keys, pagination and webhook verification. It has one small dependency and runs in Node 20+, Cloudflare Workers, Deno, Bun and browsers.

Beta

The SDK and `/v1` are in beta, and anything marked beta can still change shape. Releases are `1.0.0-beta.N` under the `beta` tag, and each one’s changes are in the package’s changelog.

## Install

```bash
npm install @sunnysdk/client@beta
```

## Quick start

```ts
import { createSunnyClient } from "@sunnysdk/client";


const sunny = createSunnyClient({ apiKey: process.env.SUNNY_API_KEY });


const customer = await sunny.customers.create({ name: "Acme Corp" });
const quote = await sunny.quotes.create({ customer_id: customer.id, name: "Level 3 fit-out" });
await sunny.quotes.lines.create(quote.id, { catalog_item_id: "itm_abc", qty: 12 });


console.log((await sunny.quotes.get(quote.id)).totals.sell_total);
```

Every `/v1` operation is a method, grouped by resource: `sunny.quotes.get(id)`, `sunny.quotes.lines.update(quoteId, lineId, body)`, `sunny.quotes.presentLink.send(id, body)`. Arguments are the path ids in order, then the JSON body when there is one, then an options object with `query`, `headers` and `signal`. Your editor shows each method’s types and the endpoint it calls.

The [`/v1` reference](/docs/api-reference) shows the SDK call for every operation: pick **@sunnysdk/client** in an endpoint’s example panel.

## Projects, floors and rooms

Build the structure of a job, then read or replace each room’s furniture as a [layout document](/docs/layout-interchange). Dimensions are meters, measured from the floor plate’s top-left corner.

```ts
const project = await sunny.projects.create({ name: "Acme HQ" });
const floor = await sunny.projects.floors.create(project.id, { name: "Level 3", width: 40, depth: 25 });
const room = await sunny.floors.rooms.create(floor.id, {
  name: "Boardroom",
  x: 2,
  y: 2,
  width: 8,
  depth: 5,
  target_seats: 12,
});


const layout = await sunny.rooms.layout.get(room.id);
const saved = await sunny.rooms.layout.replace(room.id, { ...layout, placements: [...] });
console.log(saved.placed, saved.skipped, saved.problems);
```

A room that would overlap another room or reach off the plate is refused with a `409` and the `conflict` code.

## Authentication

| Option          | Use it for                                                                                                                                           |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`        | Server code. A workspace key (`sunny_wsk_…`) belongs to the workspace; a personal key (`sunny_sk_…`) acts as you. See [API keys](/docs/api#api-key). |
| `bearer`        | An app acting for a Sunny user, with an [OAuth](/docs/oauth) access token. Pass a string or a function that returns the current token.               |
| `refreshBearer` | With `bearer`: called once on a 401, and the request is resent with the new token.                                                                   |

Keep keys on the server. `/v1` doesn’t allow browser cross-origin requests.

## Environments

The client calls `https://api.sunnysdk.com` by default. Pass `baseUrl` to point it anywhere else. A [sandbox workspace](/docs/api#sandbox) uses the live host with its own test key, so trying writes needs no other change.

## Errors

A method returns the response data, or throws a `SunnyApiError` for an error response:

```ts
import { SunnyApiError } from "@sunnysdk/client";


try {
  await sunny.quotes.get("qte_missing");
} catch (err) {
  if (err instanceof SunnyApiError) {
    console.log(err.status, err.type, err.code, err.param, err.requestId);
  }
}
```

Quote `requestId` when you report a problem.

## Retries and idempotency

The client retries 429 and 5xx responses twice by default (`maxRetries`), waiting for `Retry-After` when the response sends it. Every POST carries an `Idempotency-Key`, reused across its retries, so a retried create never creates twice. Pass your own `Idempotency-Key` header to make a retry across process restarts safe:

```ts
await sunny.quotes.create(body, { headers: { "Idempotency-Key": orderId } });
```

## Pagination

Await a list method for one page, or iterate it to walk every item across pages:

```ts
const page = await sunny.quotes.list({ query: { limit: 25 } });
console.log(page.data, page.next_cursor);


for await (const quote of sunny.quotes.list({ query: { limit: 100 } })) {
  console.log(quote.id);
}
```

## Types

Every schema in the `/v1` document is exported as a type:

```ts
import type { Schema } from "@sunnysdk/client";


function total(quote: Schema<"Quote">) {
  return quote.totals.sell_total;
}
```

`paths`, `operations` and `components` cover the whole document.

## Webhooks

Verify the `X-Sunny-Signature` header against the raw request body before you trust a delivery:

```ts
import { constructWebhookEvent } from "@sunnysdk/client";


const event = await constructWebhookEvent({
  secret: process.env.SUNNY_WEBHOOK_SECRET!,
  payload: rawBody, // the body exactly as received
  header: request.headers.get("x-sunny-signature"),
});
```

See [Webhooks](/docs/webhooks) for the event types.

## Lower-level calls

The client also has path-keyed methods for when you need the raw `Response` or a non-JSON request body:

```ts
const { data, error, response } = await sunny.GET("/v1/quotes/{id}", {
  params: { path: { id: "qte_123" } },
});
```