# Corti JavaScript Library

[![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen)](https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=https%3A%2F%2Fgithub.com%2Fcorticph%2Fcorti-sdk-javascript)
[![npm shield](https://img.shields.io/npm/v/@corti/sdk)](https://www.npmjs.com/package/@corti/sdk)

The Corti JavaScript library provides convenient access to the Corti APIs from JavaScript and TypeScript.

## Table of Contents

- [Documentation](#documentation)
- [Installation](#installation)
- [Usage](#usage)
- [Authentication](#authentication)
- [Request and Response Types](#request-and-response-types)
- [Exception Handling](#exception-handling)
- [File Uploads](#file-uploads)
- [Binary Response](#binary-response)
- [Pagination](#pagination)
- [Advanced](#advanced)
  - [Additional Headers](#additional-headers)
  - [Additional Query String Parameters](#additional-query-string-parameters)
  - [Analytics](#analytics)
  - [Retries](#retries)
  - [Timeouts](#timeouts)
  - [Aborting Requests](#aborting-requests)
  - [Access Raw Response Data](#access-raw-response-data)
  - [Logging](#logging)
  - [Runtime Compatibility](#runtime-compatibility)
- [Contributing](#contributing)

## Documentation

- [Documentation](https://docs.corti.ai/sdk/js)
- [API Reference](https://docs.corti.ai/api-reference)
- [Console](https://console.corti.app/) — get your credentials here
- [Examples](https://github.com/corticph/corti-examples)

## Installation

```sh
npm i -s @corti/sdk
```

## Usage

Instantiate and use the client with the following:

```typescript
import { CortiClient } from "@corti/sdk";

const client = new CortiClient({
    tenantName: "YOUR_TENANT_NAME",
    environment: "YOUR_ENVIRONMENT_ID",
    auth: { clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET" },
});
await client.interactions.create({
    encounter: {
        identifier: "identifier",
        status: "planned",
        type: "first_consultation"
    }
});
```

## Authentication

The SDK supports several OAuth 2.0 flows. In all cases the SDK manages tokens in memory — before each request it checks whether the stored access token is still valid, and if not, calls the appropriate token endpoint transparently. No manual token management is needed.

### Client Credentials (recommended for server-side apps)

The SDK fetches and refreshes tokens automatically using your client credentials.

```typescript
import { CortiClient } from "@corti/sdk";

const client = new CortiClient({
    tenantName: "YOUR_TENANT_NAME",
    environment: "YOUR_ENVIRONMENT_ID",
    auth: { clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET" },
});
```

### Bearer token (pre-obtained)

Use when you already have a valid access token. Pass `refreshToken` + `clientId` to enable automatic renewal when the token expires.

```typescript
// Static token — no automatic renewal
const client = new CortiClient({
    auth: { accessToken: "YOUR_ACCESS_TOKEN" },
});

// Token with automatic refresh via stored refresh token
const client = new CortiClient({
    auth: {
        accessToken: "YOUR_ACCESS_TOKEN",
        clientId: "YOUR_CLIENT_ID",
        refreshToken: "YOUR_REFRESH_TOKEN",
        expiresIn: 300,         // seconds until access token expires
        refreshExpiresIn: 1800, // seconds until refresh token expires
    },
});
```

### Bearer token with custom refresh

Use when your application manages token renewal (e.g. via a proxy or an external identity provider). The SDK calls `refreshAccessToken` whenever the stored token expires.

```typescript
const client = new CortiClient({
    auth: {
        accessToken: "YOUR_ACCESS_TOKEN",
        refreshAccessToken: async (refreshToken) => {
            // call your own token endpoint and return the new token
            return { accessToken: "NEW_TOKEN", expiresIn: 300 };
        },
    },
});
```

### Resource Owner Password Credentials (ROPC)

```typescript
const client = new CortiClient({
    tenantName: "YOUR_TENANT_NAME",
    environment: "YOUR_ENVIRONMENT_ID",
    auth: { clientId: "YOUR_CLIENT_ID", username: "USERNAME", password: "PASSWORD" },
});
```

### Authorization Code

```typescript
const client = new CortiClient({
    tenantName: "YOUR_TENANT_NAME",
    environment: "YOUR_ENVIRONMENT_ID",
    auth: {
        clientId: "YOUR_CLIENT_ID",
        clientSecret: "YOUR_CLIENT_SECRET",
        code: "AUTH_CODE",
        redirectUri: "YOUR_REDIRECT_URI",
    },
});
```

### PKCE

```typescript
const client = new CortiClient({
    tenantName: "YOUR_TENANT_NAME",
    environment: "YOUR_ENVIRONMENT_ID",
    auth: {
        clientId: "YOUR_CLIENT_ID",
        code: "AUTH_CODE",
        redirectUri: "YOUR_REDIRECT_URI",
        codeVerifier: "YOUR_CODE_VERIFIER",
    },
});
```

## Request and Response Types

The SDK exports all request and response types as TypeScript interfaces. Simply import them with the
following namespace:

```typescript
import { Corti } from "@corti/sdk";

const request: Corti.InteractionsListRequest = {
    ...
};
```

## Exception Handling

When the API returns a non-success status code (4xx or 5xx response), a subclass of the following error
will be thrown.

```typescript
import { CortiError, CortiSDKError, CortiSDKErrorCodes, ParseError, JsonError } from "@corti/sdk";

try {
    await client.interactions.create(...);
} catch (err) {
    if (err instanceof CortiError) {
        // HTTP API error (4xx / 5xx)
        console.log(err.statusCode);
        console.log(err.message);
        console.log(err.body);
        console.log(err.rawResponse);
    } else if (err instanceof CortiSDKError) {
        // SDK infrastructure error (e.g. localStorage unavailable)
        console.log(err.code);    // e.g. CortiSDKErrorCodes.LOCAL_STORAGE_ERROR
        console.log(err.message);
        console.log(err.cause);   // original Error, if any
    } else if (err instanceof ParseError) {
        // Input validation failed (e.g. missing PKCE verifier, invalid JWT)
        console.log(err.errors);  // ValidationError[]
        console.log(err.message);
    } else if (err instanceof JsonError) {
        // Response body could not be parsed as JSON
        console.log(err.errors);  // ValidationError[]
        console.log(err.message);
    }
}
```

## File Uploads

You can upload files using the client:

```typescript
import { createReadStream } from "fs";

await client.recordings.upload(createReadStream("path/to/file"), ...);
await client.recordings.upload(new ReadableStream(), ...);
await client.recordings.upload(Buffer.from('binary data'), ...);
await client.recordings.upload(new Blob(['binary data'], { type: 'audio/mpeg' }), ...);
await client.recordings.upload(new File(['binary data'], 'file.mp3'), ...);
await client.recordings.upload(new ArrayBuffer(8), ...);
await client.recordings.upload(new Uint8Array([0, 1, 2]), ...);
```
The client accepts a variety of types for file upload parameters:
* Stream types: `fs.ReadStream`, `stream.Readable`, and `ReadableStream`
* Buffered types: `Buffer`, `Blob`, `File`, `ArrayBuffer`, `ArrayBufferView`, and `Uint8Array`

### Metadata

You can configure metadata when uploading a file:
```typescript
const file: Uploadable.WithMetadata = {
    data: createReadStream("path/to/file"),
    filename: "my-file",       // optional
    contentType: "audio/mpeg", // optional
    contentLength: 1949,       // optional
};
```

Alternatively, you can upload a file directly from a file path:
```typescript
const file : Uploadable.FromPath = {
    path: "path/to/file",
    filename: "my-file",        // optional
    contentType: "audio/mpeg",  // optional
    contentLength: 1949,        // optional
};
```

The metadata is used to set the `Content-Length`, `Content-Type`, and `Content-Disposition` headers. If not provided, the client will attempt to determine them automatically.
For example, `fs.ReadStream` has a `path` property which the SDK uses to retrieve the file size from the filesystem without loading it into memory.


## Binary Response

You can consume binary data from endpoints using the `BinaryResponse` type which lets you choose how to consume the data:

```typescript
const response = await client.recordings.get(...);
const stream: ReadableStream<Uint8Array> = response.stream();
// const arrayBuffer: ArrayBuffer = await response.arrayBuffer();
// const blob: Blob = response.blob();
// const bytes: Uint8Array = response.bytes();
// You can only use the response body once, so you must choose one of the above methods.
// If you want to check if the response body has been used, you can use the following property.
const bodyUsed = response.bodyUsed;
```
<details>
<summary>Save binary response to a file</summary>

<blockquote>
<details>
<summary>Node.js</summary>

<blockquote>
<details>
<summary>ReadableStream (most-efficient)</summary>

```ts
import { createWriteStream } from 'fs';
import { Readable } from 'stream';
import { pipeline } from 'stream/promises';

const response = await client.recordings.get(...);

const stream = response.stream();
const nodeStream = Readable.fromWeb(stream);
const writeStream = createWriteStream('path/to/file');

await pipeline(nodeStream, writeStream);
```

</details>
</blockquote>

<blockquote>
<details>
<summary>ArrayBuffer</summary>

```ts
import { writeFile } from 'fs/promises';

const response = await client.recordings.get(...);

const arrayBuffer = await response.arrayBuffer();
await writeFile('path/to/file', Buffer.from(arrayBuffer));
```

</details>
</blockquote>

<blockquote>
<details>
<summary>Blob</summary>

```ts
import { writeFile } from 'fs/promises';

const response = await client.recordings.get(...);

const blob = await response.blob();
const arrayBuffer = await blob.arrayBuffer();
await writeFile('output.bin', Buffer.from(arrayBuffer));
```

</details>
</blockquote>

<blockquote>
<details>
<summary>Bytes (UIntArray8)</summary>

```ts
import { writeFile } from 'fs/promises';

const response = await client.recordings.get(...);

const bytes = await response.bytes();
await writeFile('path/to/file', bytes);
```

</details>
</blockquote>

</details>
</blockquote>

<blockquote>
<details>
<summary>Bun</summary>

<blockquote>
<details>
<summary>ReadableStream (most-efficient)</summary>

```ts
const response = await client.recordings.get(...);

const stream = response.stream();
await Bun.write('path/to/file', stream);
```

</details>
</blockquote>

<blockquote>
<details>
<summary>ArrayBuffer</summary>

```ts
const response = await client.recordings.get(...);

const arrayBuffer = await response.arrayBuffer();
await Bun.write('path/to/file', arrayBuffer);
```

</details>
</blockquote>

<blockquote>
<details>
<summary>Blob</summary>

```ts
const response = await client.recordings.get(...);

const blob = await response.blob();
await Bun.write('path/to/file', blob);
```

</details>
</blockquote>

<blockquote>
<details>
<summary>Bytes (UIntArray8)</summary>

```ts
const response = await client.recordings.get(...);

const bytes = await response.bytes();
await Bun.write('path/to/file', bytes);
```

</details>
</blockquote>

</details>
</blockquote>

<blockquote>
<details>
<summary>Deno</summary>

<blockquote>
<details>
<summary>ReadableStream (most-efficient)</summary>

```ts
const response = await client.recordings.get(...);

const stream = response.stream();
const file = await Deno.open('path/to/file', { write: true, create: true });
await stream.pipeTo(file.writable);
```

</details>
</blockquote>

<blockquote>
<details>
<summary>ArrayBuffer</summary>

```ts
const response = await client.recordings.get(...);

const arrayBuffer = await response.arrayBuffer();
await Deno.writeFile('path/to/file', new Uint8Array(arrayBuffer));
```

</details>
</blockquote>

<blockquote>
<details>
<summary>Blob</summary>

```ts
const response = await client.recordings.get(...);

const blob = await response.blob();
const arrayBuffer = await blob.arrayBuffer();
await Deno.writeFile('path/to/file', new Uint8Array(arrayBuffer));
```

</details>
</blockquote>

<blockquote>
<details>
<summary>Bytes (UIntArray8)</summary>

```ts
const response = await client.recordings.get(...);

const bytes = await response.bytes();
await Deno.writeFile('path/to/file', bytes);
```

</details>
</blockquote>

</details>
</blockquote>

<blockquote>
<details>
<summary>Browser</summary>

<blockquote>
<details>
<summary>Blob (most-efficient)</summary>

```ts
const response = await client.recordings.get(...);

const blob = await response.blob();
const url = URL.createObjectURL(blob);

// trigger download
const a = document.createElement('a');
a.href = url;
a.download = 'filename';
a.click();
URL.revokeObjectURL(url);
```

</details>
</blockquote>

<blockquote>
<details>
<summary>ReadableStream</summary>

```ts
const response = await client.recordings.get(...);

const stream = response.stream();
const reader = stream.getReader();
const chunks = [];

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  chunks.push(value);
}

const blob = new Blob(chunks);
const url = URL.createObjectURL(blob);

// trigger download
const a = document.createElement('a');
a.href = url;
a.download = 'filename';
a.click();
URL.revokeObjectURL(url);
```

</details>
</blockquote>

<blockquote>
<details>
<summary>ArrayBuffer</summary>

```ts
const response = await client.recordings.get(...);

const arrayBuffer = await response.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);

// trigger download
const a = document.createElement('a');
a.href = url;
a.download = 'filename';
a.click();
URL.revokeObjectURL(url);
```

</details>
</blockquote>

<blockquote>
<details>
<summary>Bytes (UIntArray8)</summary>

```ts
const response = await client.recordings.get(...);

const bytes = await response.bytes();
const blob = new Blob([bytes]);
const url = URL.createObjectURL(blob);

// trigger download
const a = document.createElement('a');
a.href = url;
a.download = 'filename';
a.click();
URL.revokeObjectURL(url);
```

</details>
</blockquote>

</details>
</blockquote>

</details>
</blockquote>

<details>
<summary>Convert binary response to text</summary>

<blockquote>
<details>
<summary>ReadableStream</summary>

```ts
const response = await client.recordings.get(...);

const stream = response.stream();
const text = await new Response(stream).text();
```

</details>
</blockquote>

<blockquote>
<details>
<summary>ArrayBuffer</summary>

```ts
const response = await client.recordings.get(...);

const arrayBuffer = await response.arrayBuffer();
const text = new TextDecoder().decode(arrayBuffer);
```

</details>
</blockquote>

<blockquote>
<details>
<summary>Blob</summary>

```ts
const response = await client.recordings.get(...);

const blob = await response.blob();
const text = await blob.text();
```

</details>
</blockquote>

<blockquote>
<details>
<summary>Bytes (UIntArray8)</summary>

```ts
const response = await client.recordings.get(...);

const bytes = await response.bytes();
const text = new TextDecoder().decode(bytes);
```

</details>
</blockquote>

</details>

## Pagination

List endpoints are paginated. The SDK provides an iterator so that you can simply loop over the items:

```typescript
import { CortiClient } from "@corti/sdk";

const client = new CortiClient({
    tenantName: "YOUR_TENANT_NAME",
    environment: "YOUR_ENVIRONMENT_ID",
    auth: { clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET" },
});
const pageableResponse = await client.interactions.list();
for await (const item of pageableResponse) {
    console.log(item);
}

// Or you can manually iterate page-by-page
let page = await client.interactions.list();
while (page.hasNextPage()) {
    page = page.getNextPage();
}

// You can also access the underlying response
const response = page.response;
```

## Advanced

### Additional Headers

If you would like to send additional headers as part of the request, use the `headers` request option.

```typescript
import { CortiClient } from "@corti/sdk";

const client = new CortiClient({
    ...
    headers: {
        'X-Custom-Header': 'custom value'
    }
});

const response = await client.interactions.create(..., {
    headers: {
        'X-Custom-Header': 'custom value'
    }
});
```

Use `await client.getHeaders()` to retrieve a `Headers` object containing all configured client headers: authentication, tenant, custom headers, analytics, and SDK metadata. Tokens are refreshed if needed and header suppliers are resolved on each call. Request-specific overrides and endpoint-specific headers such as `Accept` and `Content-Type` are not included. The existing `getAuthHeaders()` helper still returns only authentication and tenant headers.

```typescript
const headers = await client.getHeaders();
```

### Additional Query String Parameters

If you would like to send additional query string parameters as part of the request, use the `queryParams` request option.

```typescript
const response = await client.interactions.create(..., {
    queryParams: {
        'customQueryParamKey': 'custom query param value'
    }
});
```

### Analytics

The SDK sends metadata about itself (`sdk_version`, `sdk_type`) with every request via the `X-Corti-Analytics` header (REST) or the `x-corti-analytics` query parameter (WebSocket). You can extend this payload with your own fields on the client constructor, and overlay extra fields on individual REST calls or WebSocket connections.

> **Reserved keys**: `sdk_version` and `sdk_type` are always set by the SDK and cannot be overridden at any level.

#### Client-level

Pass `analytics` when constructing the client. The payload is sent with every request.

```typescript
import { CortiClient } from "@corti/sdk";

const client = new CortiClient({
    ...
    analytics: { integration: "epic-hyperspace", workflow: "ambient-scribe" },
});

// Every REST call includes: X-Corti-Analytics: {"sdk_version":"...","sdk_type":"corti-sdk-javascript","integration":"epic-hyperspace","workflow":"ambient-scribe"}
await client.interactions.list();
```

#### Per-request (HTTP)

For a single REST call, pass an `x-corti-analytics` header in `requestOptions.headers`. The value is a JSON string. Per-request fields are merged with the client-level context — they extend rather than replace it.

```typescript
await client.documents.generate({ ... }, {
    headers: {
        "x-corti-analytics": JSON.stringify({ document_type: "progress-note" }),
    },
});
// X-Corti-Analytics includes: {"sdk_version":"...","sdk_type":"corti-sdk-javascript","integration":"epic-hyperspace","workflow":"ambient-scribe","document_type":"progress-note"}
```

#### Per-connection (WebSocket)

Browsers cannot set custom headers on the WebSocket handshake, so pass `x-corti-analytics` in `queryParams`. Per-connection fields are merged with the client-level context.

```typescript
const socket = await client.stream.connect({
    id: interactionId,
    queryParams: {
        "x-corti-analytics": JSON.stringify({ visit_type: "inpatient" }),
    },
});
// Handshake query includes: x-corti-analytics={"sdk_version":"...","sdk_type":"corti-sdk-javascript","integration":"epic-hyperspace","workflow":"ambient-scribe","visit_type":"inpatient"}
```

> **Note**: This value is in the query string and may appear in access logs — avoid personally identifiable information.

### Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long
as the request is deemed retryable and the number of retry attempts has not grown larger than the configured
retry limit (default: 2).

A request is deemed retryable when any of the following HTTP status codes is returned:

- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout)
- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests)
- [5XX](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) (Internal Server Errors)

Use the `maxRetries` request option to configure this behavior.

```typescript
const response = await client.interactions.create(..., {
    maxRetries: 0 // override maxRetries at the request level
});
```

### Timeouts

The SDK defaults to a 60 second timeout. Use the `timeoutInSeconds` option to configure this behavior.

```typescript
const response = await client.interactions.create(..., {
    timeoutInSeconds: 30 // override timeout to 30s
});
```

### Aborting Requests

The SDK allows users to abort requests at any point by passing in an abort signal.

```typescript
const controller = new AbortController();
const response = await client.interactions.create(..., {
    abortSignal: controller.signal
});
controller.abort(); // aborts the request
```

### Access Raw Response Data

The SDK provides access to raw response data, including headers, through the `.withRawResponse()` method.
The `.withRawResponse()` method returns a promise that results to an object with a `data` and a `rawResponse` property.

```typescript
const { data, rawResponse } = await client.interactions.create(...).withRawResponse();

console.log(data);
console.log(rawResponse.headers['X-My-Header']);
```

### Logging

The SDK supports logging. You can configure the logger by passing in a `logging` object to the client options.

```typescript
import { CortiClient, logging } from "@corti/sdk";

const client = new CortiClient({
    ...
    logging: {
        level: logging.LogLevel.Debug, // defaults to logging.LogLevel.Info
        logger: new logging.ConsoleLogger(), // defaults to ConsoleLogger
        silent: false, // defaults to true, set to false to enable logging
    }
});
```
The `logging` object can have the following properties:
- `level`: The log level to use. Defaults to `logging.LogLevel.Info`.
- `logger`: The logger to use. Defaults to a `logging.ConsoleLogger`.
- `silent`: Whether to silence the logger. Defaults to `true`.

The `level` property can be one of the following values:
- `logging.LogLevel.Debug`
- `logging.LogLevel.Info`
- `logging.LogLevel.Warn`
- `logging.LogLevel.Error`

To provide a custom logger, you can pass in an object that implements the `logging.ILogger` interface.

<details>
<summary>Custom logger examples</summary>

Here's an example using the popular `winston` logging library.
```ts
import winston from 'winston';

const winstonLogger = winston.createLogger({...});

const logger: logging.ILogger = {
    debug: (msg, ...args) => winstonLogger.debug(msg, ...args),
    info: (msg, ...args) => winstonLogger.info(msg, ...args),
    warn: (msg, ...args) => winstonLogger.warn(msg, ...args),
    error: (msg, ...args) => winstonLogger.error(msg, ...args),
};
```

Here's an example using the popular `pino` logging library.

```ts
import pino from 'pino';

const pinoLogger = pino({...});

const logger: logging.ILogger = {
  debug: (msg, ...args) => pinoLogger.debug(args, msg),
  info: (msg, ...args) => pinoLogger.info(args, msg),
  warn: (msg, ...args) => pinoLogger.warn(args, msg),
  error: (msg, ...args) => pinoLogger.error(args, msg),
};
```
</details>


### Runtime Compatibility


The SDK works in the following runtimes:



- Node.js 18+
- Vercel
- Cloudflare Workers
- Deno v1.25+
- Bun 1.0+
- React Native

### Customizing Fetch Client

The SDK provides a way for you to customize the underlying HTTP client / Fetch function. If you're running in an
unsupported environment, this provides a way for you to break glass and ensure the SDK works.

```typescript
import { CortiClient } from "@corti/sdk";

const client = new CortiClient({
    ...
    fetcher: // provide your implementation here
});
```

## Contributing

While we value open-source contributions to this SDK, this library is generated programmatically.
Additions made directly to this library would have to be moved over to our generation code,
otherwise they would be overwritten upon the next generated release. Feel free to open a PR as
a proof of concept, but know that we will not be able to merge it as-is. We suggest opening
an issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!
