> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hyzecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript / Node / Bun

> SDK oficial @hyzecloud/sdk para Node.js e Bun — cliente tipado da API Hyze Cloud.

Pacote oficial **`@hyzecloud/sdk`** para **Node.js 18+** e **Bun**.

* Zero dependências de runtime (`fetch` nativo)
* Helpers tipados para apps, databases, API keys, invoices, GitHub, plans
* `HyzeError` consistente com status, code e `Retry-After`

## Instalação

```bash theme={"system"}
npm install @hyzecloud/sdk
# ou
bun add @hyzecloud/sdk
```

## Quickstart

```ts theme={"system"}
import { HyzeCloud, HyzeError } from "@hyzecloud/sdk";

const hyze = new HyzeCloud({
  apiKey: process.env.HYZE_API_KEY, // hyze_...
  // baseUrl: "https://api.hyzecloud.com/api", // default
  // workspaceId: "org_...", // opcional
});

const { apps } = await hyze.apps.list();
console.log(apps.map((a) => `${a.name} (${a.status})`));

try {
  await hyze.apps.restart("app_001");
} catch (err) {
  if (err instanceof HyzeError) {
    console.error(err.status, err.code, err.message);
    if (err.isRateLimited) {
      console.error("Tente de novo em", err.retryAfterSeconds, "s");
    }
  }
  throw err;
}
```

## Configuração

| Opção         | Default                         | Descrição                      |
| ------------- | ------------------------------- | ------------------------------ |
| `apiKey`      | `process.env.HYZE_API_KEY`      | Bearer token (`hyze_...`)      |
| `baseUrl`     | `https://api.hyzecloud.com/api` | URL base da API                |
| `workspaceId` | —                               | Escopo de workspace (opcional) |
| `fetch`       | `fetch` global                  | Implementação custom de fetch  |
| `headers`     | —                               | Headers extras em toda request |
| `signal`      | —                               | `AbortSignal` padrão           |

### Variáveis de ambiente

| Variável       | Descrição                              |
| -------------- | -------------------------------------- |
| `HYZE_API_KEY` | API key padrão se `apiKey` for omitido |
| `HYZE_API_URL` | Override da URL base                   |

Crie a key no [dashboard](http://hyzecloud.com/dashboard) ou via API. Veja [Autenticação](/pt/getting-started/authentication).

## Apps

```ts theme={"system"}
// Listar / obter
const list = await hyze.apps.list();
const detail = await hyze.apps.get("app_001");
// detail.container: status, publicUrl, stats, runtime, ...

// Lifecycle
await hyze.apps.start("app_001");
await hyze.apps.stop("app_001");
await hyze.apps.restart("app_001");

// Logs e env
await hyze.apps.logs("app_001", { tail: 200, timestamps: true });
await hyze.apps.getEnv("app_001");
await hyze.apps.setEnv("app_001", {
  APP_ENV: "production",
  LOG_LEVEL: "info",
});

// Settings
await hyze.apps.updateSettings("app_001", {
  name: "my-api",
  memoryMB: 512,
  autoRestart: true,
});
```

### Deploy a partir de ZIP

Com porta exposta, o **subdomain deve ser o host completo** no domínio da plataforma (ex.: `my-api.hyzecloud.app`), não só o prefixo.

```ts theme={"system"}
import { readFileSync } from "node:fs";

await hyze.apps.deployFromZip({
  file: readFileSync("./app.zip"),
  name: "my-api",
  runtime: "node", // "node" | "bun" | "python"
  memoryMB: 512,
  // startupCommand opcional — omita ou "auto" para a Hyze detectar
  exposePort: 3000,
  subdomain: "my-api.hyzecloud.app",
  envVars: {
    APP_ENV: "production",
  },
});

// Start custom quando precisar de controle total:
// await hyze.apps.deployFromZip({ ..., startupCommand: "node server.js" });
```

### Deploy a partir do GitHub

```ts theme={"system"}
await hyze.apps.deployFromRepo({
  name: "my-api",
  runtime: "bun",
  memoryMB: 512,
  exposePort: 3000,
  subdomain: "my-api.hyzecloud.app",
  repository: {
    id: 123,
    owner: "acme",
    name: "api",
    branch: "main",
  },
});
```

### Backups de app

```ts theme={"system"}
await hyze.apps.createBackup("app_001");
await hyze.apps.listBackups("app_001");
await hyze.apps.restoreBackup("app_001", "backup_001");
```

### Regras de env vars

A API rejeita chaves reservadas como `NODE_ENV`, `PORT`, `PATH`, `HOME` e prefixos como `HYZE_`, `DOCKER_`, `AWS_`. Prefira nomes da aplicação (`APP_ENV`, `DATABASE_URL`, …).

## Databases

```ts theme={"system"}
await hyze.databases.create({
  name: "prod-postgres",
  engine: "postgresql", // postgresql | mysql | mongodb | redis
  memoryMB: 1024,
  storageGB: 20,
});

const { databases } = await hyze.databases.list();
await hyze.databases.get("db_001");
await hyze.databases.stats("db_001");
await hyze.databases.logs("db_001", { tail: 100 });

await hyze.databases.start("db_001");
await hyze.databases.stop("db_001");

await hyze.databases.createBackup("db_001");
await hyze.databases.listBackups("db_001");
```

## API keys, invoices, GitHub, plans

```ts theme={"system"}
const { keys } = await hyze.apiKeys.list();
const created = await hyze.apiKeys.create({ name: "ci" });
// created.key.key — secret de uso único (só no create)

const { invoices } = await hyze.invoices.list();
const pix = await hyze.invoices.createPix({
  planId: "pro",
  interval: "month",
});
// pix.invoice.brCode / brCodeBase64

await hyze.github.status();
await hyze.github.repos();

const current = await hyze.plans.current();
// current.plan + current.usage
```

## Mapa de recursos

| Recurso          | Métodos                                                                                                                                                                                    |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `hyze.apps`      | list, get, delete, start, stop, restart, logs, builds, getEnv, setEnv, updateSettings, deployFromZip, deployFromRepo, inspectEnv, createBackup, listBackups, restoreBackup, downloadBackup |
| `hyze.databases` | list, get, create, delete, updateSettings, stats, logs, start, stop, rotatePassword, createBackup, listBackups, downloadBackup, restore, operations                                        |
| `hyze.apiKeys`   | list, create, update, delete                                                                                                                                                               |
| `hyze.invoices`  | list, createPix, status                                                                                                                                                                    |
| `hyze.github`    | status, repos, branches, detectRuntime, …                                                                                                                                                  |
| `hyze.plans`     | current, list                                                                                                                                                                              |

## Requests de baixo nível

Qualquer path sob a base da API:

```ts theme={"system"}
await hyze.get("/apps/");
await hyze.post("/apps/app_001/restart");
await hyze.request("/apps/", {
  method: "GET",
  query: { workspaceId: "org_1" },
});
```

## Erros

`HyzeError` é lançado em respostas não-2xx (e em alguns bodies de erro com 200):

| Propriedade         | Descrição                             |
| ------------------- | ------------------------------------- |
| `status`            | Status HTTP                           |
| `code`              | Código de erro da API (quando houver) |
| `message`           | Mensagem legível                      |
| `body`              | Body parseado                         |
| `retryAfterSeconds` | Do header `Retry-After`               |
| `isRateLimited`     | `status === 429`                      |
| `isUnauthorized`    | `401` / `403`                         |
| `isNotFound`        | `404`                                 |

## Links

* npm: [`@hyzecloud/sdk`](https://www.npmjs.com/package/@hyzecloud/sdk)
* Código: [github.com/hyze-cloud/hyzecloud-sdk-ts](https://github.com/hyze-cloud/hyzecloud-sdk-ts)
* [Referência da API](/api-reference/introduction)
* [Rate limits](/pt/concepts/rate-limits)

## Próximos passos

<CardGroup cols={2}>
  <Card title="Autenticação" icon="key" href="/pt/getting-started/authentication">
    Como funcionam as API keys.
  </Card>

  <Card title="Deploy de app" icon="rocket" href="/pt/guides/deploy-an-app">
    Guia de deploy via ZIP.
  </Card>

  <Card title="Provisionar database" icon="database" href="/pt/guides/provision-a-database">
    Criar bancos gerenciados.
  </Card>

  <Card title="Referência da API" icon="book-open" href="/api-reference/introduction">
    Todos os endpoints REST.
  </Card>
</CardGroup>
