# TypeScript SDK

Install @dcloud/sdk, sign in, launch, query, upload, page through lists, handle errors.

`@dcloud/sdk` calls the Deutsche Cloud API from Node.js: one method per API operation, typed inputs,
the same sign-in chain as the `dcloud` CLI, retries, iterators over paged lists and waiters. It has
no dependencies.

## What it is

Every API operation `service.resource.operation` is a method `client.service.resource.operation()`
in camelCase: `ec2.instances.run` is `client.ec2.instances.run()`, `s3.bucket-objects.upload-url`
is `client.s3.bucketObjects.uploadUrl()`. Each operation's page in the _API Reference_ shows the
call under **TypeScript**, and each method's documentation in your editor names the IAM action it
needs.

| Needs       | Version                                                       |
| ----------- | ------------------------------------------------------------- |
| Node.js     | 20.3 or later                                                 |
| Module type | ES modules; `require()` from CommonJS works on Node.js 20.19+ |
| TypeScript  | Optional; the package carries its own types                   |

## Install

`@dcloud/sdk` is public in Deutsche Cloud's npm registry: no account or token is needed. One line in
`.npmrc` sends the `@dcloud` scope there and leaves every other package on npmjs.org. Replace
`example.com` with the domain your console is under (`console.example.com` → `example.com`);
**My account → CLI & Git → SDKs** in the console shows the line filled in:

```sh
echo '@dcloud:registry=https://npm.example.com/' >> .npmrc
npm install @dcloud/sdk
```

A version's tarball never changes, so `package-lock.json` keeps its integrity hash valid.

## Sign in

`new DcloudClient()` takes the first credentials it finds, in the order the CLI uses:

| Order | Source                                                                                                  |
| ----- | ------------------------------------------------------------------------------------------------------- |
| 1     | `credentials` passed to the client: `'<key id>:<secret>'`, `{ accessKeyId, secretKey }` or a provider   |
| 2     | `DCLOUD_ACCESS_KEY` (`<key id>:<secret>`)                                                               |
| 3     | `DCLOUD_SESSION_TOKEN`, a token of your `dcloud login` session                                         |
| 4     | `DCLOUD_WEB_IDENTITY_TOKEN_FILE` and `DCLOUD_ROLE_RN`: an OIDC token, exchanged for a key valid an hour |
| 5     | The profile in `~/.dcloud/credentials.json` that `dcloud login` writes (`DCLOUD_PROFILE` picks one)   |

The console address is `endpoint`, else `DCLOUD_API_URL`, else the profile's. The region is
`region`, else `DCLOUD_REGION`, else the profile's.

```ts
import { DcloudClient } from '@dcloud/sdk';

// From the environment: DCLOUD_API_URL and DCLOUD_ACCESS_KEY.
const client = new DcloudClient();

// Or explicitly.
const explicit = new DcloudClient({
  endpoint: 'https://console.example.com',
  credentials: process.env.MY_ACCESS_KEY,
  region: 'de1',
});
console.log(client.endpoint, explicit.endpoint);
```

Create an access key under **IAM → Access keys**. The SDK can do exactly what that key's IAM user
is allowed to do.

## First call

```ts
import { DcloudClient } from '@dcloud/sdk';

const client = new DcloudClient();
const buckets = await client.s3.buckets.list();
console.log(buckets);
```

A method takes one object holding the path parameters, the query parameters and the body fields
side by side, and resolves to the `data` of the API's `{ "success": true, "data": … }` answer.

## Types

Inputs are typed: a misspelt field, a missing required one or a value outside an enum fails to
compile, and your editor completes field names and shows their documentation. Responses are typed
where the API documents their shape (Managed PostgreSQL, Apps and Git so far): those methods check
the answer and return a typed value. Every other method resolves to `unknown`; describe the fields
you use:

```ts
import { DcloudClient } from '@dcloud/sdk';

type Instance = { id: string; state: string; publicIp: string | null };

const client = new DcloudClient();
const instances = (await client.ec2.instances.list({ state: 'running' })) as Instance[];
for (const instance of instances) console.log(instance.id, instance.publicIp);
```

## Launch an instance and wait for it

`ec2.osImages.list` gives the OS images; an image has one id per CPU architecture. A waiter polls
until the resource is in the state, and throws `DcloudWaiterError` if it reaches a failure state or
runs out of time. You pay for the instance from launch until it is terminated.

```ts
import { DcloudClient } from '@dcloud/sdk';

const client = new DcloudClient();

const images = (await client.ec2.osImages.list({ architecture: 'x86_64' })) as {
  id: number;
  name: string;
}[];
const ubuntu = images.find((image) => image.name === 'ubuntu-24.04');
if (ubuntu === undefined) throw new Error('no Ubuntu 24.04 image');

const launched = (await client.ec2.instances.run({
  regionId: 'de1',
  imageId: ubuntu.id,
  sizeClass: 's-2',
  name: 'my-app',
})) as { id: string };

const running = (await client.ec2.instances.waitUntilRunning({ id: launched.id })) as {
  publicIp: string;
};
console.log(`running at ${running.publicIp}`);

await client.ec2.instances.terminate({ id: launched.id });
await client.ec2.instances.waitUntilTerminated({ id: launched.id });
```

| Resource             | Waiters                                                       |
| -------------------- | ------------------------------------------------------------- |
| `ec2.instances`      | `waitUntilRunning`, `waitUntilStopped`, `waitUntilTerminated` |
| `ec2.volumes`        | `waitUntilAvailable`, `waitUntilDeleted`                      |
| `ec2.vpcs`           | `waitUntilAvailable`, `waitUntilDeleted`                      |
| `ec2.natGateways`    | `waitUntilAvailable`, `waitUntilDeleted`                      |
| `rds.instances`      | `waitUntilAvailable`, `waitUntilDeleted`                      |
| `cache.clusters`     | `waitUntilAvailable`, `waitUntilDeleted`                      |
| `deploy.deployments` | `waitUntilFinished`, `waitUntilLive`                          |
| `deploy.apps`        | `waitUntilActive`                                             |
| `eks.clusters`       | `waitUntilActive`, `waitUntilDeleted`                         |
| `lb.loadBalancers`   | `waitUntilActive`                                             |

Each waiter has its own interval and time limit; `{ intervalMs, maxWaitMs }` as the second argument
overrides them.

## Create a database and run a query

```ts
import { DcloudClient } from '@dcloud/sdk';

const client = new DcloudClient();

const db = await client.rds.instances.create({
  identifier: 'orders',
  instanceClass: 'standard-2',
  dbName: 'app',
});
await client.rds.instances.waitUntilAvailable({ id: db.id }, { maxWaitMs: 30 * 60_000 });

const result = await client.rds.data.runQuery({ id: db.id, sql: 'select count(*) from pg_tables' });
console.log(result.columns, result.rows);
```

`rds.data.runQuery` runs one read-only statement. For your application's own traffic, connect with
a PostgreSQL driver to the endpoint and credentials the database shows.

## Upload a file to a bucket

`s3.bucketObjects.uploadUrl` returns a pre-signed URL with the method and headers to send. Send
them unchanged: an added or repeated header breaks the signature.

```ts
import { readFile } from 'node:fs/promises';
import { DcloudClient } from '@dcloud/sdk';

const client = new DcloudClient();

const upload = (await client.s3.bucketObjects.uploadUrl({
  name: 'my-bucket',
  key: 'reports/2026-11.pdf',
  contentType: 'application/pdf',
})) as { url: string; method: string; headers: Record<string, string> };

const res = await fetch(upload.url, {
  method: upload.method,
  headers: upload.headers,
  body: await readFile('2026-11.pdf'),
});
if (!res.ok) throw new Error(`upload failed: ${res.status}`);
```

To move many or large files, use an S3 client (the AWS SDK for JavaScript, `rclone`) against the
bucket's S3 endpoint, with temporary credentials from `s3.temporaryCredentials.create` or a key from
`s3.accessKeys.create`.

## Paged lists

A list the API returns a page at a time has an `…All` method: an async iterator over every item that
fetches the next page when the loop needs it. `limit` sets the page size.

```ts
import { DcloudClient } from '@dcloud/sdk';

const client = new DcloudClient();

let stopped = 0;
for await (const instance of client.ec2.instances.listAll({ state: 'stopped', limit: 100 })) {
  stopped += 1;
  console.log(instance);
}
console.log(`${stopped} stopped instances`);

for await (const entry of client.iam.auditLogs.listAll({ outcome: 'failure' })) {
  console.log(entry);
  break; // stop whenever you have enough; no further page is fetched
}
```

The iterators: `ec2.instances.listAll`, `iam.auditLogs.listAll`, `ecr.images.listAll`,
`ecr.images.listScansAll`, `ecr.packages.searchAll`, `posture.findings.listAll`,
`errors.issues.listAll`, `errors.events.listAll`, `ai.usage.listAll`, `email.messages.listAll`,
`git.commits.listAll`, `rds.data.readRowsAll` and `ci.jobs.logsAll`. Every other list returns the
whole array at once.

## Errors

```ts
import { DcloudApiError, DcloudClient, isConflict, isForbidden, isNotFound } from '@dcloud/sdk';

const client = new DcloudClient();

try {
  await client.s3.buckets.create({ name: 'my-bucket' });
} catch (err) {
  if (isForbidden(err)) {
    console.error(`missing permission ${err.action} on ${err.resource}`);
  } else if (isConflict(err)) {
    console.error(err.apiMessage); // the name is taken
  } else if (isNotFound(err)) {
    console.error('not found');
  } else if (err instanceof DcloudApiError) {
    console.error(err.status, err.apiMessage, err.issues, err.requestId);
  } else {
    throw err;
  }
}
```

| Class                 | When                                                                   |
| --------------------- | ---------------------------------------------------------------------- |
| `DcloudApiError`      | The API answered with an error status                                  |
| `DcloudNetworkError`  | No answer: DNS, connection refused or reset, timeout (`code` names it) |
| `DcloudConfigError`   | No endpoint or credentials, or a credentials file that cannot be read  |
| `DcloudWaiterError`   | A waiter saw a failure state (`reason: 'failure'`) or timed out        |
| `DcloudResponseError` | A successful answer that does not have the documented shape            |

All of them extend `DcloudError`. A `DcloudApiError` carries:

| Field        | Contents                                                                                    |
| ------------ | ------------------------------------------------------------------------------------------- |
| `status`     | The HTTP status                                                                             |
| `apiMessage` | The API's sentence, e.g. `Not allowed: s3:CreateBucket on rn:ews::… Ask an administrator …` |
| `action`     | On a 403, the IAM action that was denied                                                    |
| `resource`   | On a 403, the resource it was denied on                                                     |
| `code`       | A machine-readable reason where the API gives one, e.g. `STEP_UP_REQUIRED`                  |
| `issues`     | On a 400, one `{ path, message }` per invalid field                                         |
| `requestId`  | The request's id; give it to support, and find it in the audit log                          |
| `operation`  | The operation, e.g. `s3.buckets.create`                                                     |

## Retries, timeouts and cancelling

The SDK retries 429, 502, 503 and 504 answers and connection errors, waiting with jittered
exponential backoff and honouring `Retry-After`. GET, PUT and DELETE are retried on all of them;
POST and PATCH only on 429 and on connection errors from before the request was sent, so a create is
never sent twice. A 429 that outlasts the retries throws with `isThrottled(err)` true.

```ts
import { DcloudClient } from '@dcloud/sdk';

const client = new DcloudClient({
  maxAttempts: 6,
  retryBaseMs: 500,
  retryMaxMs: 30_000,
  timeoutMs: 60_000,
});

// One call: no retries, give up after five seconds.
await client.ec2.vpcs.list({}, { maxAttempts: 1, signal: AbortSignal.timeout(5_000) });
```

`timeoutMs` is per attempt (default 120 seconds); `maxAttempts` counts the first attempt (default
4).

## Versions

`SDK_VERSION` is the installed version, sent as the User-Agent `dcloud-sdk-typescript/<version>`.
Versions follow semantic versioning. While the version starts with `0.`, a change that can break
your code (an operation or field removed, a field that becomes required or changes type) raises
the minor version (0.2.0 → 0.3.0), and everything else the patch version.
`https://<your console>/api/sdk/changelog` lists what changed in each version: new operations, new
fields, new iterators and waiters, and every breaking change.

## Not supported

- npmjs.org: install from Deutsche Cloud's npm registry as above.
- Browsers and edge runtimes (Cloudflare Workers, Vercel Edge): the SDK needs Node.js. An access
  key in a browser would be readable by anyone using the page.
- Following a log as it grows (a build log): call the operation again with the position the last
  answer gave.
- Responses typed for every service: see [Types](#types).

## Troubleshooting

| Symptom                                    | Cause                                                      | Fix                                                                   |
| ------------------------------------------ | ---------------------------------------------------------- | --------------------------------------------------------------------- |
| `No endpoint`                              | No `endpoint`, no `DCLOUD_API_URL`, no profile             | Set `DCLOUD_API_URL` to your console's address                        |
| `No credentials`                           | None of the five sources is set                            | Set `DCLOUD_ACCESS_KEY`, or run `dcloud login`                       |
| 403 with `action` set                      | The key's IAM user lacks that action                       | Attach a policy allowing `err.action` on `err.resource`               |
| `ERR_REQUIRE_ESM`                          | `require()` on Node.js older than 20.19                    | Use `import`, or Node.js 20.19 or later                               |
| Upload answers 403 `SignatureDoesNotMatch` | A header was added to, or changed from, `upload.headers`   | Send exactly `upload.method` and `upload.headers`                     |
| `fetch failed (ECONNRESET)`                | The connection dropped and the call was not safe to repeat | Check the resource's state, then repeat the call if it did not happen |
