# API Reference (/docs/api-reference)



Import core APIs and provider factories from:

```ts
import {
  UploadSDKError,
  createUploader,
  defineAssets,
  defineStorageProfiles,
  defineUploadConfig,
  isUploadSDKError,
  toUploadSDKError,
  uploadFile,
  uploadMultipartParts,
} from "@evensurface/upload-sdk";
import {
  awsS3,
  imageKit,
  neonStorage,
} from "@evensurface/upload-sdk/providers";
```

## `defineStorageProfiles()` [#definestorageprofiles]

Defines named provider configurations and preserves their names for TypeScript.

```ts
function defineStorageProfiles<
  const TStorageProfiles extends Record<
    string,
    StorageProvider
  >,
>(
  storageProfiles: TStorageProfiles,
): TStorageProfiles
```

### Parameters [#parameters]

| Parameter         | Description                                        |
| ----------------- | -------------------------------------------------- |
| `storageProfiles` | An object containing named provider configurations |

### Returns [#returns]

The same object passed to the function.

`defineStorageProfiles()` does not change the profiles or validate provider credentials. Its main purpose is to preserve profile names for type checking.

### Example [#example]

```ts
const storageProfiles = defineStorageProfiles({
  userUploads: awsS3({
    bucket: process.env.AWS_BUCKET!,
    region: process.env.AWS_REGION!,
    credentials: {
      accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
      secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
    },
  }),
});
```

See [Storage Profiles](/docs/core-concepts/storage-profiles).

## `defineAssets()` [#defineassets]

Defines named upload assets and connects their `storageProfile` values to the available storage profiles.

```ts
function defineAssets<
  const TStorageProfiles extends Record<
    string,
    StorageProvider
  >,
  const TAssets extends Record<
    string,
    AssetUploadConfig<
      keyof TStorageProfiles & string
    >
  >,
>(
  storageProfiles: TStorageProfiles,
  assets: TAssets,
): TAssets
```

### Parameters [#parameters-1]

| Parameter         | Description                                         |
| ----------------- | --------------------------------------------------- |
| `storageProfiles` | The profiles created with `defineStorageProfiles()` |
| `assets`          | Named upload asset configurations                   |

### Returns [#returns-1]

The same asset object passed to the function.

`defineAssets()` preserves asset names and checks profile references through TypeScript. Runtime validation happens later when `prepareUpload()` is called.

### Example [#example-1]

```ts
const assets = defineAssets(storageProfiles, {
  avatar: {
    storageProfile: "userUploads",
    keyPrefix: "avatars",
    accept: {
      mimeTypes: ["image/png", "image/jpeg"],
      extensions: [".png", ".jpg", ".jpeg"],
    },
    limits: {
      maxFileSize: {
        value: 2,
        unit: "MB",
      },
    },
  },
});
```

See [Upload Assets](/docs/core-concepts/upload-assets).

## `defineUploadConfig()` [#defineuploadconfig]

Defines the complete uploader configuration as one object.

```ts
function defineUploadConfig<
  const TStorageProfiles extends Record<
    string,
    StorageProvider
  >,
  const TAssets extends Record<
    string,
    AssetUploadConfig<
      keyof TStorageProfiles & string
    >
  >,
>(config: {
  storageProfiles: TStorageProfiles;
  defaultStorageProfile:
    keyof TStorageProfiles & string;
  assets: TAssets;
}): {
  storageProfiles: TStorageProfiles;
  defaultStorageProfile:
    keyof TStorageProfiles & string;
  assets: TAssets;
}
```

### Parameters [#parameters-2]

| Property                | Description                                    |
| ----------------------- | ---------------------------------------------- |
| `storageProfiles`       | Named provider configurations                  |
| `defaultStorageProfile` | Profile used when an asset does not select one |
| `assets`                | Named upload asset configurations              |

### Returns [#returns-2]

The same configuration object passed to the function.

### Example [#example-2]

```ts
const uploadConfig = defineUploadConfig({
  storageProfiles,
  defaultStorageProfile: "userUploads",
  assets,
});
```

The result can be passed directly to `createUploader()`:

```ts
const uploader = createUploader(uploadConfig);
```

## `createUploader()` [#createuploader]

Creates an uploader from storage profiles and upload assets.

```ts
const uploader = createUploader({
  storageProfiles,
  defaultStorageProfile,
  assets,
});
```

### Parameters [#parameters-3]

| Property                | Description                                     |
| ----------------------- | ----------------------------------------------- |
| `storageProfiles`       | Profiles created with `defineStorageProfiles()` |
| `defaultStorageProfile` | Profile used when an asset does not select one  |
| `assets`                | Assets created with `defineAssets()`            |

`defaultStorageProfile` must match a name in `storageProfiles`.

### Returns [#returns-3]

An uploader with direct-upload and provider multipart methods:

```ts
{
  prepareUpload(
    assetName,
    input,
  ): Promise<PrepareUploadOutput>;

  createMultipartUpload(
    assetName,
    input,
  ): Promise<CreateMultipartUploadOutput>;

  prepareMultipartUploadParts(
    input,
  ): Promise<PrepareMultipartUploadPartsOutput>;

  completeMultipartUpload(
    input,
  ): Promise<CompleteMultipartUploadOutput>;

  abortMultipartUpload(input): Promise<void>;
}
```

### Example [#example-3]

```ts
export const uploader = createUploader({
  storageProfiles,
  defaultStorageProfile: "userUploads",
  assets,
});
```

## `uploader.prepareUpload()` [#uploaderprepareupload]

Validates client-reported file information and asks the selected provider to create a signed upload target.

```ts
uploader.prepareUpload(
  assetName,
  input,
): Promise<PrepareUploadOutput>
```

### Parameters [#parameters-4]

#### `assetName` [#assetname]

The name of an asset passed to `defineAssets()`.

```ts
"avatar"
```

Asset names are checked by TypeScript.

#### `input` [#input]

```ts
{
  filename: string;
  contentType: string;
  size: number;
}
```

| Property      | Description                   |
| ------------- | ----------------------------- |
| `filename`    | Client-reported filename      |
| `contentType` | Client-reported MIME type     |
| `size`        | Client-reported size in bytes |

### Returns [#returns-4]

A promise that resolves to `PrepareUploadOutput`.

```ts
const preparedUpload =
  await uploader.prepareUpload("avatar", {
    filename: "profile.png",
    contentType: "image/png",
    size: 120_000,
  });
```

### Throws [#throws]

Throws an `UploadSDKError` when validation, configuration, or provider preparation fails.

```ts
try {
  const preparedUpload =
    await uploader.prepareUpload("avatar", input);
} catch (error) {
  if (isUploadSDKError(error)) {
    console.error(error.code, error.message);
  }
}
```

See [Prepared Uploads](/docs/core-concepts/prepared-uploads).

## `uploader.createMultipartUpload()` [#uploadercreatemultipartupload]

Starts an S3 multipart upload session for an asset.

```ts
uploader.createMultipartUpload(
  assetName,
  input,
): Promise<CreateMultipartUploadOutput>
```

This method validates the same file metadata as `prepareUpload()`, generates a key, and returns the selected `storageProfile` with the S3 `uploadId`.

Only providers that support multipart sessions implement this operation.

## `uploader.prepareMultipartUploadParts()` [#uploaderpreparemultipartuploadparts]

Creates signed `PUT` URLs for multipart upload part numbers.

```ts
uploader.prepareMultipartUploadParts({
  storageProfile,
  key,
  uploadId,
  partNumbers,
}): Promise<PrepareMultipartUploadPartsOutput>
```

Pass the object returned by `createMultipartUpload()` and the part numbers your browser will upload.

## `uploader.completeMultipartUpload()` [#uploadercompletemultipartupload]

Completes an S3 multipart upload after the browser returns part ETags.

```ts
uploader.completeMultipartUpload({
  storageProfile,
  key,
  uploadId,
  parts,
}): Promise<CompleteMultipartUploadOutput>
```

## `uploader.abortMultipartUpload()` [#uploaderabortmultipartupload]

Aborts an incomplete S3 multipart upload.

```ts
uploader.abortMultipartUpload({
  storageProfile,
  key,
  uploadId,
}): Promise<void>
```

See [S3 Large File Uploads](/docs/guides/s3-large-file-uploads).

## `uploadFile()` [#uploadfile]

Uploads a regular prepared multipart `POST` target from browser code.

```ts
uploadFile(
  preparedUpload,
  file,
  options,
): Promise<UploadFileResult>
```

Options include `fieldName`, `filename`, `signal`, and `onProgress`.

Use this helper with values returned by `uploader.prepareUpload()`.

## `uploadMultipartParts()` [#uploadmultipartparts]

Uploads S3 multipart part URLs from browser code.

```ts
uploadMultipartParts(
  preparedParts,
  file,
  {
    chunkSize,
    concurrency,
    signal,
    onProgress,
  },
): Promise<UploadMultipartPartsResult>
```

The result includes `storageProfile`, `key`, `uploadId`, and completed part ETags. Pass it to `uploader.completeMultipartUpload()` on the server.

Use this helper with values returned by `uploader.prepareMultipartUploadParts()`.

## `awsS3()` [#awss3]

Creates an AWS S3 provider.

```ts
function awsS3(
  config: AwsS3Config,
): StorageProvider
```

### Configuration [#configuration]

```ts
type AwsS3Config = {
  bucket: string;
  region: string;
  credentials: {
    accessKeyId: string;
    secretAccessKey: string;
    sessionToken?: string;
  };
};
```

| Property                      | Required | Description                             |
| ----------------------------- | -------- | --------------------------------------- |
| `bucket`                      | Yes      | S3 bucket name                          |
| `region`                      | Yes      | AWS region containing the bucket        |
| `credentials.accessKeyId`     | Yes      | AWS access key ID                       |
| `credentials.secretAccessKey` | Yes      | AWS secret access key                   |
| `credentials.sessionToken`    | No       | Session token for temporary credentials |

### Example [#example-4]

```ts
const provider = awsS3({
  bucket: process.env.AWS_BUCKET!,
  region: process.env.AWS_REGION!,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey:
      process.env.AWS_SECRET_ACCESS_KEY!,
    sessionToken: process.env.AWS_SESSION_TOKEN,
  },
});
```

Keep AWS credentials in server-only code.

See [AWS S3](/docs/providers/aws-s3).

## `imageKit()` [#imagekit]

Creates an ImageKit provider.

```ts
function imageKit(
  config: ImageKitConfig,
): StorageProvider
```

### Configuration [#configuration-1]

```ts
type ImageKitConfig = {
  publicKey: string;
  privateKey: string;
};
```

| Property     | Required | Description                           |
| ------------ | -------- | ------------------------------------- |
| `publicKey`  | Yes      | ImageKit public key                   |
| `privateKey` | Yes      | ImageKit private key used for signing |

### Example [#example-5]

```ts
const provider = imageKit({
  publicKey: process.env.IMAGEKIT_PUBLIC_KEY!,
  privateKey: process.env.IMAGEKIT_PRIVATE_KEY!,
});
```

Keep the private key in server-only code.

See [ImageKit](/docs/providers/imagekit).

## `neonStorage()` [#neonstorage]

Creates a Neon Object Storage provider.

```ts
function neonStorage(
  config: NeonStorageConfig,
): StorageProvider
```

### Configuration [#configuration-2]

```ts
type NeonStorageConfig = {
  bucket: string;
  endpoint: string;
  region: string;
  credentials: {
    accessKeyId: string;
    secretAccessKey: string;
  };
};
```

| Property                      | Required | Description                                     |
| ----------------------------- | -------- | ----------------------------------------------- |
| `bucket`                      | Yes      | Bucket name on the branch                       |
| `endpoint`                    | Yes      | Branch storage endpoint (`AWS_ENDPOINT_URL_S3`) |
| `region`                      | Yes      | Object storage region used for signing          |
| `credentials.accessKeyId`     | Yes      | Neon credential `token_id`                      |
| `credentials.secretAccessKey` | Yes      | Neon credential `s3_secret_access_key`          |

`endpoint` must be an `https` URL. The provider uses path-style addressing, which Neon requires.

### Example [#example-6]

```ts
const provider = neonStorage({
  bucket: process.env.NEON_STORAGE_BUCKET!,
  endpoint: process.env.AWS_ENDPOINT_URL_S3!,
  region: process.env.AWS_REGION!,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey:
      process.env.AWS_SECRET_ACCESS_KEY!,
  },
});
```

Keep Neon credentials in server-only code.

See [Neon Object Storage](/docs/providers/neon-object-storage).

## `isUploadSDKError()` [#isuploadsdkerror]

Checks whether an unknown value is an `UploadSDKError`.

```ts
function isUploadSDKError(
  error: unknown,
): error is UploadSDKError
```

### Parameters [#parameters-5]

| Parameter | Description        |
| --------- | ------------------ |
| `error`   | The value to check |

### Returns [#returns-5]

`true` when the value is an `UploadSDKError`.

### Example [#example-7]

```ts
try {
  await uploader.prepareUpload("avatar", input);
} catch (error) {
  if (isUploadSDKError(error)) {
    console.error({
      code: error.code,
      message: error.message,
      statusCode: error.statusCode,
      details: error.details,
    });
  }
}
```

## `UploadSDKError` [#uploadsdkerror]

The error class used for expected SDK failures.

```ts
class UploadSDKError extends Error {
  readonly name: "UploadSDKError";
  readonly code: UploadSDKErrorCode;
  readonly statusCode: number;
  readonly cause?: unknown;
  readonly details?: unknown;
}
```

### Constructor [#constructor]

```ts
new UploadSDKError(message, {
  code,
  statusCode,
  cause,
  details,
});
```

| Parameter    | Required | Description                     |
| ------------ | -------- | ------------------------------- |
| `message`    | Yes      | Readable error message          |
| `code`       | Yes      | Machine-readable SDK error code |
| `statusCode` | No       | Suggested HTTP status           |
| `cause`      | No       | Original error                  |
| `details`    | No       | Extra diagnostic information    |

### Example [#example-8]

```ts
throw new UploadSDKError(
  "The reported file type is not allowed.",
  {
    code: "INVALID_UPLOAD_INPUT",
    statusCode: 400,
  },
);
```

The default status is `400` for `INVALID_UPLOAD_INPUT` and `500` for other SDK error codes.

Most applications should catch errors created by the SDK rather than create them directly.

## `toUploadSDKError()` [#touploadsdkerror]

Converts an unknown error into an `UploadSDKError`.

```ts
function toUploadSDKError(
  error: unknown,
  fallback: {
    code: UploadSDKErrorCode;
    message: string;
    statusCode?: number;
    details?: unknown;
  },
): UploadSDKError
```

When `error` is already an `UploadSDKError`, it is returned unchanged.

Otherwise, the function creates a new error using the fallback values and keeps the original error as its cause.

### Example [#example-9]

```ts
try {
  await performOperation();
} catch (error) {
  throw toUploadSDKError(error, {
    code: "UPLOAD_PROVIDER_ERROR",
    message: "Upload could not be prepared.",
    statusCode: 500,
  });
}
```

Most applications only need `isUploadSDKError()`. `toUploadSDKError()` is useful when normalizing errors in server-side SDK integrations.

## Error codes [#error-codes]

```ts
type UploadSDKErrorCode =
  | "INVALID_UPLOAD_INPUT"
  | "INVALID_UPLOAD_CONFIG"
  | "UNSUPPORTED_UPLOAD_OPERATION"
  | "UPLOAD_PROVIDER_ERROR";
```

| Code                           | Meaning                                             |
| ------------------------------ | --------------------------------------------------- |
| `INVALID_UPLOAD_INPUT`         | Reported file information is invalid or not allowed |
| `INVALID_UPLOAD_CONFIG`        | Asset or provider configuration is invalid          |
| `UNSUPPORTED_UPLOAD_OPERATION` | The selected operation is not supported             |
| `UPLOAD_PROVIDER_ERROR`        | The provider could not prepare the upload           |

See [Validation and Errors](/docs/guides/validation-and-errors) for error-handling examples.

## Next steps [#next-steps]

* [Types:](/docs/api-reference/types)
  View all exported TypeScript types.

* [Validation and Errors:](/docs/guides/validation-and-errors)
  Handle validation and provider preparation failures.

* [Quick Start:](/docs/getting-started/quick-start)
  Configure the SDK and prepare your first upload.
