# TypeScript SDK

> Guard costly work with one call, and call every API operation from TypeScript, with types from the API itself.

The TypeScript SDK is a small typed client for Node.js, browsers and Cloudflare Workers. `guard` and `reserve` put a limit around your code in one call. Every API operation is also a typed method, and its types come from the same definitions the API uses to validate requests. The SDK always matches the [API reference](/docs/reference/).

## Install

```bash
npm install @limitry/sdk
```

## Your key

Create an API key in the app under **Settings → Developers**. Give the key your app runs with **Check limits**. Give a script that also creates limits, subjects or credits **Manage limits**.

* `createClient()` reads your key from the `LIMITRY_API_KEY` environment variable. If that isn’t set, it reads `LIMITRY_TOKEN`, the variable the CLI uses. If you set neither, it throws an error naming the variable.
* Where there’s no `process.env`, such as in a browser or a Cloudflare Worker, pass the key yourself: `createClient({ apiKey: env.LIMITRY_API_KEY })`.
* A test key (`lim_test_…`) acts in test, and a live key (`lim_live_…`) acts in live. [Test and live](/docs/test-and-live/) explains the difference.
* With a **personal access token**, pass it as `token` and name the workspace. The token acts in test unless you name live: `createClient({ token, workspace: "acme", environment: "live" })`.

## Guard costly work

Say each of your users has a $2 AI budget a month, counted in cents. You only know what a reply cost once it’s done. `reserve` holds what the reply will probably cost (5 cents here), runs your code, then charges what it actually cost. If your code throws, `reserve` releases the hold:

```ts
import {
  createClient,
  LimitReachedError,
  UnavailableError,
} from "@limitry/sdk";

const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable

try {
  const reply = await limitry.reserve(
    { subject: { kind: "user", id: "user_123" }, action: "ai-call", cost: 5 },
    async (reservation) => {
      const response = await callModel(prompt);
      reservation.cost(priceCents(response.usage)); // your prices, in cents
      return response;
    },
  );
  console.log(reply);
} catch (error) {
  if (error instanceof LimitReachedError) {
    console.log(`Try again in ${error.retryAfterSeconds} seconds`);
  } else if (error instanceof UnavailableError) {
    console.log(`No decision (${error.reason}), and this limit fails closed`);
  } else {
    throw error;
  }
}
```

A refusal throws `LimitReachedError`. Its `reason` is `limit_reached` or `too_many_reservations`. It also carries `limitId`, `limitName`, `retryAfterSeconds` and the whole `decision`.

Both errors share the base class `LimitryError`, as every error the SDK throws does. A mistake in your request, such as a cost that isn’t a whole number, throws the API’s error instead, such as `BadRequestError`.

When every request costs the same, `guard` is simpler. It checks the limit, then runs your code only if Limitry allows it. Here it counts one request to your API against a limit of 60 a minute for each key:

```ts
import { createClient } from "@limitry/sdk";

const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable

const response = await limitry.guard(
  { subject: { kind: "apikey", id: "key_42" }, action: "api-request" },
  () => handleRequest(request),
);
console.log(response);
```

## If your code can’t reach Limitry

If `guard` or `reserve` gets no decision, each limit’s fail mode decides. With `open`, the work runs. With `closed`, they throw `UnavailableError`, and never `LimitReachedError`. Its `reason` says what happened: `timeout`, `unreachable`, `plan_limit_reached` or `rate_limited`. Its `cause` holds the failure itself.

“No decision” means one of these, within `timeout` (1.5 seconds by default) and counting every retry:

| What happened                                                    | What the SDK does                                                                |
| ---------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| A network error, or a `408`, `429`, `500`, `502`, `503` or `504` | Retries at most twice with the same key, then the fail mode decides.             |
| A `402`, because the workspace is past its plan                  | The fail mode decides.                                                           |
| A `503` with the code `moving` or `busy`                         | Retries with the same key while the wait still fits, then the fail mode decides. |

A `503` with `moving` means a busy workspace’s counts are moving between Limitry’s servers, which takes a few seconds. One with `busy` means there were too many checks at once, and Limitry charged nothing. Each retry waits for the response’s `Retry-After`, or a second if that’s shorter. It then adds a random backoff that grows each time, so clients don’t all retry together.

A `concurrent` limit that fails `open` still runs no more than its `amount` at once in your process. Past that, `reserve` throws `UnavailableError`. [Concurrency](/docs/rolling-and-concurrency/#concurrency) explains why.

The commit or release after the work gets the same time as the check. If a commit doesn’t get through in that time, the SDK lets it go. Your work’s result still comes back. The reservation expires with no charge. Limitry never counts that work. This happens only while Limitry is moving counts or has too much to do.

* `reservation.cost()` takes a whole number from 0 to 1,000,000,000. It throws a `RangeError` for anything else, before the work’s usage could be lost.
* `reservation.extend()` throws the API’s error, for example when the reservation has already expired.

[How Limitry works](/docs/how-it-works/#when-your-code-cant-reach-limitry) has the details.

## Methods

Every API operation is a method, named after the operation in the [API reference](/docs/reference/). For example, `limits.create` is `limitry.limits.create()`:

```ts
import { createClient } from "@limitry/sdk";

const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable

const limit = await limitry.limits.create({
  name: "AI budget",
  subject: { kind: "user" },
  action: "ai-call",
  amount: 200,
  unit: "cents",
  window: "month",
});
const { items } = await limitry.limits.list();
console.log(limit.id, items.length);
```

* Ids in the path are arguments, and everything else goes in one object:

  ```ts
  limitry.limits.get(limitId);
  ```

* A method returns the response’s data.

* Because the types come from the API itself, your editor completes every method, field and response.

Here is every method. Each one links to its fields and a full example under **Endpoints**:

### Checks

* [`checks.create()`](/docs/reference/checks/#check-whether-a-subject-may-act)

  Check whether a subject may act

* [`checks.list()`](/docs/reference/checks/#list-checks)

  List checks

### Reservations

* [`reservations.commit()`](/docs/reference/reservations/#commit-a-reservation)

  Commit a reservation

* [`reservations.extend()`](/docs/reference/reservations/#extend-a-reservation)

  Extend a reservation

* [`reservations.get()`](/docs/reference/reservations/#get-a-reservation)

  Get a reservation

* [`reservations.release()`](/docs/reference/reservations/#release-a-reservation)

  Release a reservation

### Limits

* [`limits.archive()`](/docs/reference/limits/#archive-a-limit)

  Archive a limit

* [`limits.create()`](/docs/reference/limits/#create-a-limit)

  Create a limit

* [`limits.credits.create()`](/docs/reference/limits/#add-credits-to-a-balance)

  Add credits to a balance

* [`limits.credits.get()`](/docs/reference/limits/#get-a-credit)

  Get a credit

* [`limits.credits.list()`](/docs/reference/limits/#list-a-balances-credits)

  List a balance's credits

* [`limits.get()`](/docs/reference/limits/#get-a-limit)

  Get a limit

* [`limits.list()`](/docs/reference/limits/#list-limits)

  List limits

* [`limits.restore()`](/docs/reference/limits/#restore-an-archived-limit)

  Restore an archived limit

* [`limits.sync()`](/docs/reference/limits/#sync-limits-from-a-list)

  Sync limits from a list

* [`limits.update()`](/docs/reference/limits/#change-a-limit)

  Change a limit

### Subjects

* [`subjects.get()`](/docs/reference/subjects/#get-a-subject)

  Get a subject

* [`subjects.import()`](/docs/reference/subjects/#name-many-subjects)

  Name many subjects

* [`subjects.list()`](/docs/reference/subjects/#list-subjects)

  List subjects

* [`subjects.names.delete()`](/docs/reference/subjects/#erase-a-subjects-name-and-labels)

  Erase a subject's name and labels

* [`subjects.reset()`](/docs/reference/subjects/#reset-a-subjects-limits)

  Reset a subject's limits

* [`subjects.standing()`](/docs/reference/subjects/#get-where-a-subject-stands)

  Get where a subject stands

* [`subjects.update()`](/docs/reference/subjects/#update-a-subject)

  Update a subject

### Usage

* [`usage.overview()`](/docs/reference/usage/#get-every-limits-usage-at-once)

  Get every limit's usage at once

* [`usage.query()`](/docs/reference/usage/#get-a-limits-usage-over-time)

  Get a limit's usage over time

* [`usage.subjects()`](/docs/reference/usage/#list-who-is-using-a-limit)

  List who is using a limit

### Workspace

* [`workspace.get()`](/docs/reference/workspace/#get-the-current-workspace)

  Get the current workspace

* [`workspace.invitations.list()`](/docs/reference/workspace/#list-pending-invitations)

  List pending invitations

* [`workspace.members.list()`](/docs/reference/workspace/#list-workspace-members)

  List workspace members

* [`workspace.planUsage.get()`](/docs/reference/workspace/#get-your-plans-usage-this-period)

  Get your plan's usage this period

* [`workspace.teams.list()`](/docs/reference/workspace/#list-teams)

  List teams

### Webhooks

* [`workspace.eventTypes.list()`](/docs/reference/webhooks/#list-event-types)

  List event types

* [`workspace.webhookDeliveries.list()`](/docs/reference/webhooks/#list-an-endpoints-deliveries)

  List an endpoint's deliveries

* [`workspace.webhookDeliveries.redeliver()`](/docs/reference/webhooks/#redeliver-an-event)

  Redeliver an event

* [`workspace.webhookEndpoints.create()`](/docs/reference/webhooks/#add-a-webhook-endpoint)

  Add a webhook endpoint

* [`workspace.webhookEndpoints.delete()`](/docs/reference/webhooks/#remove-a-webhook-endpoint)

  Remove a webhook endpoint

* [`workspace.webhookEndpoints.enable()`](/docs/reference/webhooks/#re-enable-a-webhook-endpoint)

  Re-enable a webhook endpoint

* [`workspace.webhookEndpoints.get()`](/docs/reference/webhooks/#get-a-webhook-endpoint)

  Get a webhook endpoint

* [`workspace.webhookEndpoints.list()`](/docs/reference/webhooks/#list-webhook-endpoints)

  List webhook endpoints

* [`workspace.webhookEndpoints.test()`](/docs/reference/webhooks/#send-a-test-event)

  Send a test event

* [`workspace.webhookEndpoints.update()`](/docs/reference/webhooks/#update-a-webhook-endpoint)

  Update a webhook endpoint

### Approvals

* [`workspace.approvalActions.list()`](/docs/reference/approvals/#list-the-actions-you-can-ask-approval-for)

  List the actions you can ask approval for

* [`workspace.approvalRequests.create()`](/docs/reference/approvals/#ask-a-person-to-approve-an-action)

  Ask a person to approve an action

* [`workspace.approvalRequests.get()`](/docs/reference/approvals/#check-an-approval-request)

  Check an approval request

* [`workspace.approvalRequests.redeem()`](/docs/reference/approvals/#redeem-an-approved-request)

  Redeem an approved request

### Audit events

* [`workspace.auditEvents.list()`](/docs/reference/audit-events/#list-workspace-audit-events)

  List workspace audit events

### Personal access tokens

* [`user.me()`](/docs/reference/personal-access-tokens/#get-the-current-user)

  Get the current user

* [`user.revokeToken()`](/docs/reference/personal-access-tokens/#revoke-the-token-making-this-request)

  Revoke the token making this request

## Lists

A list method returns its first page when you `await` it. The page has the response’s `items` and `nextCursor`:

```ts
import { createClient } from "@limitry/sdk";

const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable

const page = await limitry.limits.list({ limit: 50 });
console.log(page.items);

if (page.hasNextPage()) {
  const next = await page.getNextPage();
  console.log(next.items);
}
```

To go through every item, use `for await`. The SDK fetches each next page when it needs it:

```ts
for await (const limit of limitry.limits.list()) {
  console.log(limit.name);
}
```

Each next page is the same call with `cursor` set, so your other fields and options hold for every page. Read more about [pagination](/docs/pagination/).

## Errors

When the API refuses a call, the method throws an `APIError`. It has the [error](/docs/errors/)’s `code`, `message`, `status` and `requestId`. It also has:

* `details`: what is wrong with each field, as `{ path, message }`, when the API refused the input.
* `docs`: a link to the error on the Errors page.
* `headers`: the response’s headers, such as `Retry-After` and the rate-limit headers.

Each status has its own class, so you can catch one kind of failure:

| Status | Class                      |
| ------ | -------------------------- |
| 400    | `BadRequestError`          |
| 401    | `AuthenticationError`      |
| 402    | `PlanLimitError`           |
| 403    | `PermissionDeniedError`    |
| 404    | `NotFoundError`            |
| 409    | `ConflictError`            |
| 422    | `UnprocessableEntityError` |
| 429    | `RateLimitError`           |
| 500+   | `InternalServerError`      |

Any other status is an `APIError` itself.

When the SDK can’t reach the API, the method throws an `APIConnectionError`, with the network’s error as its `cause`. When every attempt timed out, it throws an `APITimeoutError`, which is an `APIConnectionError` too.

Every error the SDK throws is a `LimitryError`, including `LimitReachedError` and `UnavailableError`:

```ts
import { createClient, LimitryError, NotFoundError } from "@limitry/sdk";

const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable

try {
  const limit = await limitry.limits.get("lmt_123");
  console.log(limit.name);
} catch (error) {
  if (error instanceof NotFoundError) {
    console.log("No such limit");
  } else if (error instanceof LimitryError) {
    console.log(error.message);
  } else {
    throw error;
  }
}
```

## Retries and time limits

These apply to every method. `guard` and `reserve` keep their own, shorter time limit, as [Your own timeout or fail mode](#your-own-timeout-or-fail-mode) shows.

* Every write sends an [idempotency key](/docs/idempotency/). When the SDK retries a failed attempt, such as after a network error or a `503`, the write still happens only once.

* The SDK retries a failed attempt twice. To change that, pass `maxRetries` to `createClient`. `0` turns retries off.

* When the API says how long to wait with `Retry-After`, the SDK waits that long, up to 60 seconds. If it must wait longer, it throws the error, such as a `RateLimitError`, instead.

* To make your own retries safe too, pass your key as the last argument:

  ```ts
  limitry.checks.create(check, { idempotencyKey: id });
  ```

* Each attempt waits up to 60 seconds for a response. A timed-out attempt is retried with the same key. To change the limit, pass `timeout` in milliseconds to `createClient`, or to one call:

  ```ts
  limitry.limits.list({}, { timeout: 5000 });
  ```

* To limit a whole call, retries included, pass a `signal`. With `AbortSignal.timeout()`, the call stops at once when time is up, even while it waits to retry. It then throws the signal’s `TimeoutError`, not an SDK error:

  ```ts
  limitry.limits.list({}, { signal: AbortSignal.timeout(2000) });
  ```

## Client options

| Option           | What it does                                                                    |
| ---------------- | ------------------------------------------------------------------------------- |
| `apiKey`         | Your API key. By default, `LIMITRY_API_KEY`.                                    |
| `token`          | A personal access token, instead of a key.                                      |
| `workspace`      | The workspace a personal access token acts in.                                  |
| `environment`    | `test` or `live`, for a personal access token. By default, test.                |
| `baseURL`        | The API’s address, without `/v1`. By default, `LIMITRY_BASE_URL`, else our API. |
| `defaultHeaders` | Headers to send with every request. A call’s own `headers` win.                 |
| `maxRetries`     | How many times to retry a failed attempt. By default, 2.                        |
| `timeout`        | How long each attempt may take, in milliseconds. By default, 60 000.            |
| `fetch`          | Your own `fetch`, such as a Cloudflare service binding.                         |

Outside a browser, every request names the SDK and its version in its `User-Agent` header, such as `limitry-node/1.0.0`.

Each method takes these options for one call, as its last argument: `idempotencyKey`, `headers`, `timeout` and `signal`.

## Your own timeout or fail mode

`createLimits(client, options)` gives you `guard` and `reserve` with your own settings. `timeout` is the most a check adds to your request, its tries included. It’s in milliseconds, 1,500 by default. `failMode` fixes the fail mode for every limit:

```ts
import { createClient, createLimits } from "@limitry/sdk";

const limits = createLimits(createClient(), { timeout: 500 });
```

Each `guard` or `reserve` call also takes `timeout`, `failMode`, `signal` and `idempotencyKey`, for that call only:

```ts
import { createClient } from "@limitry/sdk";

const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable

const response = await limitry.guard(
  {
    subject: { kind: "apikey", id: "key_42" },
    action: "api-request",
    timeout: 300,
    signal: request.signal,
    idempotencyKey: request.headers.get("idempotency-key") ?? undefined,
  },
  () => handleRequest(request),
);
console.log(response);
```

A `signal` that aborts ends the check at once and throws its reason. The work never runs, and no fail mode applies.

## Calling a path directly

`limitry.GET`, `limitry.POST` and the other HTTP methods call any path, with the same types. They return `{ data, error, response }` instead of throwing, and `unwrap` turns that into the data or an `APIError`:

```ts
import { createClient, unwrap } from "@limitry/sdk";

const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable
const limits = unwrap(await limitry.GET("/limits"));
console.log(limits.items.length);
```
