@botozap/sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +229 -0
- package/dist/index.cjs +793 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +675 -0
- package/dist/index.d.ts +675 -0
- package/dist/index.js +765 -0
- package/dist/index.js.map +1 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bytecraft Consultoria em Tecnologia LTDA
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
# @botozap/sdk
|
|
2
|
+
|
|
3
|
+
SDK oficial da [BotoZap](https://botozap.com.br) para Node.js. Envie mensagens e gerencie clientes na WhatsApp Cloud API oficial, em modelo multi-tenant.
|
|
4
|
+
|
|
5
|
+
O core da plataforma é fechado. Este cliente é a camada pública sobre a API HTTP: um envelope fino, tipado, sem dependências de runtime.
|
|
6
|
+
|
|
7
|
+
> **Ainda não publicado no npm — em preparação.** O pacote está em migração para o monorepo `botozap-js`; o comando de instalação abaixo passará a funcionar quando a primeira versão for publicada.
|
|
8
|
+
|
|
9
|
+
## Status: preview `0.x`
|
|
10
|
+
|
|
11
|
+
- Versão `0.x`, **sem promessa de estabilidade de API**: métodos e tipos podem
|
|
12
|
+
mudar entre minors até a `1.0`. Fixe a versão exata no seu `package.json`.
|
|
13
|
+
- A [API REST](https://botozap.com.br/docs) é a interface oficial e estável —
|
|
14
|
+
se algo faltar ou quebrar no SDK, o fallback é sempre chamar
|
|
15
|
+
`https://botozap.com.br/api/v1` direto (o SDK é um envelope fino sobre ela).
|
|
16
|
+
- Bugs e pedidos: [issues do monorepo](https://github.com/bytecraft-fernando/botozap-js/issues).
|
|
17
|
+
Nunca inclua sua chave de API no relato.
|
|
18
|
+
|
|
19
|
+
## Sandbox
|
|
20
|
+
|
|
21
|
+
Uma chave de ambiente **sandbox** (`bz_sandbox_...`, criada em `/chaves`) testa o
|
|
22
|
+
fluxo completo sem credencial Meta, sem número real e sem custo: `POST /messages`
|
|
23
|
+
responde `201` com `sandbox: true` e `wamid.sandbox.<...>`, e os eventos
|
|
24
|
+
simulados percorrem o pipeline real (webhook assinado com retry). Números
|
|
25
|
+
mágicos: `+5500000000001` (sent→delivered→read, janela de 24h sempre aberta),
|
|
26
|
+
`+5500000000002` (falha `131026`), `+5500000000003` (delivered + resposta
|
|
27
|
+
inbound que abre a janela real). A chave sandbox só acessa `POST /messages`,
|
|
28
|
+
`GET /messages` e `GET /messages/:id` — as demais rotas respondem
|
|
29
|
+
`403 sandbox_forbidden`.
|
|
30
|
+
|
|
31
|
+
## Garantias de entrega (leia antes de ir a produção)
|
|
32
|
+
|
|
33
|
+
Espelha [a documentação de confiabilidade](https://botozap.com.br/docs):
|
|
34
|
+
|
|
35
|
+
- **Webhooks são at-least-once**: duplicatas raras acontecem — deduplique pelo
|
|
36
|
+
header `X-Idempotency-Key` do evento recebido.
|
|
37
|
+
- **Sem ordem global**: ordene pelo timestamp do evento, não pela chegada.
|
|
38
|
+
- **Envio não é exactly-once**: num erro ambíguo (ex.: timeout depois do envio
|
|
39
|
+
aceito pela Meta), o SDK lança `BotoZapError` mas a mensagem PODE ter saído.
|
|
40
|
+
Em produção, persista sua própria chave de idempotência → `wamid` antes de
|
|
41
|
+
reenviar. Transmissões (broadcasts) são at-least-once por natureza.
|
|
42
|
+
|
|
43
|
+
## Instalação
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pnpm add @botozap/sdk
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Requer Node 20.19 ou superior.
|
|
50
|
+
|
|
51
|
+
## Início rápido
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { BotoZap } from "@botozap/sdk";
|
|
55
|
+
|
|
56
|
+
const boto = new BotoZap({ apiKey: process.env.BOTOZAP_KEY! });
|
|
57
|
+
|
|
58
|
+
const result = await boto.messages.send({
|
|
59
|
+
to: "+5531988887777",
|
|
60
|
+
text: "Seu pão tá saindo do forno",
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
console.log(result.wamid, result.status);
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
A conta é derivada da chave de API. Você nunca passa um id de conta: o isolamento multi-tenant é garantido no servidor.
|
|
67
|
+
|
|
68
|
+
## Mensagens
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
// Texto
|
|
72
|
+
await boto.messages.send({ to: "+5531988887777", text: "Olá!" });
|
|
73
|
+
|
|
74
|
+
// Template aprovado
|
|
75
|
+
await boto.messages.sendTemplate({
|
|
76
|
+
to: "+5531988887777",
|
|
77
|
+
template: { name: "boas_vindas", language: { code: "pt_BR" } },
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// De um número específico (obrigatório se a conta tem mais de um)
|
|
81
|
+
await boto.messages.send({
|
|
82
|
+
to: "+5531988887777",
|
|
83
|
+
text: "Olá!",
|
|
84
|
+
from: "phone_number_id_aqui",
|
|
85
|
+
});
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Clientes e templates
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
const { data: customers, meta } = await boto.customers.list({ per_page: 20 });
|
|
92
|
+
const customer = await boto.customers.get("uuid-do-cliente");
|
|
93
|
+
|
|
94
|
+
const { data: templates } = await boto.templates.list();
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Retornos e paginação
|
|
98
|
+
|
|
99
|
+
O SDK **desempacota o envelope `{ data }`** da API pra você:
|
|
100
|
+
|
|
101
|
+
- **Item** (`get`, `create`, `update`, `send` de broadcast…): devolve a entidade
|
|
102
|
+
direto — `boto.customers.get(id)` resolve para `Customer`, não `{ data: Customer }`.
|
|
103
|
+
- **Lista**: devolve o objeto com os itens **e** a paginação — `{ data, paging }`
|
|
104
|
+
(cursor) ou `{ data, meta }` (offset/página). Nunca só o array.
|
|
105
|
+
- **`messages.send` / `sendTemplate`**: essa rota responde o objeto direto (sem
|
|
106
|
+
envelope), então você recebe `SendResult` cru.
|
|
107
|
+
- **`delete`**: responde `204` — retorno `void`.
|
|
108
|
+
|
|
109
|
+
Dois modelos de paginação, conforme a coleção:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
// Cursor (contacts, conversations, webhooks, apiLogs, webhookDeliveries,
|
|
113
|
+
// broadcasts.listRecipients): params { limit, after, before }.
|
|
114
|
+
let page = await boto.contacts.list({ limit: 50 });
|
|
115
|
+
if (page.paging.next) {
|
|
116
|
+
page = await boto.contacts.list({ limit: 50, after: page.paging.next });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Offset/página (customers, templates, broadcasts, phoneNumbers, users, flows,
|
|
120
|
+
// conversations.listAssignments): params { page, per_page }.
|
|
121
|
+
const { data, meta } = await boto.templates.list({ page: 2, per_page: 20 });
|
|
122
|
+
console.log(meta.total_count, meta.total_pages);
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Tratamento de erro
|
|
126
|
+
|
|
127
|
+
Respostas fora de 2xx viram `BotoZapError`, com o `code` e a `message` do envelope da API.
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
import { BotoZap, BotoZapError } from "@botozap/sdk";
|
|
131
|
+
|
|
132
|
+
try {
|
|
133
|
+
await boto.messages.send({ to: "+5531988887777", text: "Olá!" });
|
|
134
|
+
} catch (err) {
|
|
135
|
+
if (err instanceof BotoZapError) {
|
|
136
|
+
console.error(err.code, err.status, err.message);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Quando houve resposta HTTP (`status > 0`), o erro expõe também `err.headers` (os headers da resposta). Útil num `429`, para ler `Retry-After` / `X-RateLimit-*` e decidir quando reenviar:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
catch (err) {
|
|
145
|
+
if (err instanceof BotoZapError && err.status === 429) {
|
|
146
|
+
const retryAfter = err.headers?.["retry-after"];
|
|
147
|
+
// aguarde `retryAfter` segundos antes de tentar de novo
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
`err.headers` traz só os headers da resposta — nenhuma credencial de request entra nele.
|
|
153
|
+
|
|
154
|
+
## Configuração
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
new BotoZap({
|
|
158
|
+
apiKey: "...",
|
|
159
|
+
baseUrl: "https://botozap.com.br/api/v1", // padrão
|
|
160
|
+
fetch: customFetch, // opcional
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
> `baseUrl` existe para testes e ambientes controlados. A chave de API é
|
|
165
|
+
> enviada como `Authorization: Bearer` para o host configurado — nunca aponte
|
|
166
|
+
> `baseUrl`/`BOTOZAP_API_URL` para um host que não seja de sua confiança.
|
|
167
|
+
|
|
168
|
+
## Recursos
|
|
169
|
+
|
|
170
|
+
O SDK cobre os recursos da API `/v1`:
|
|
171
|
+
|
|
172
|
+
- `messages` — enviar texto e template, **listar** e buscar por id
|
|
173
|
+
- `customers` — listar, buscar, criar, **atualizar**, **remover**, e **links de setup** (listar/criar/atualizar)
|
|
174
|
+
- `templates` — listar, buscar, **criar**
|
|
175
|
+
- `broadcasts` — criar, destinatários, agendar, enviar, cancelar
|
|
176
|
+
- `contacts` — listar, buscar, criar, atualizar, remover
|
|
177
|
+
- `conversations` — listar, buscar, atualizar, atribuições
|
|
178
|
+
- `webhooks` — CRUD e teste
|
|
179
|
+
- `phoneNumbers` — listar, buscar, remover, saúde (a rota de update não expõe campos editáveis, então o SDK não tem `phoneNumbers.update`)
|
|
180
|
+
- `flows` — criar, versionar, publicar, data endpoint (as operações por flow exigem `phone_number_id`, que amarra o flow à sua WABA)
|
|
181
|
+
- `media` — subir arquivo e obter um media_id
|
|
182
|
+
- `users`, `apiLogs`, `webhookDeliveries` — leitura
|
|
183
|
+
|
|
184
|
+
```ts
|
|
185
|
+
// Transmissão: template_name + template_language são obrigatórios.
|
|
186
|
+
await boto.broadcasts.create({
|
|
187
|
+
name: "Promo de sexta",
|
|
188
|
+
phone_number_id,
|
|
189
|
+
template_name: "promo_sexta",
|
|
190
|
+
template_language: "pt_BR",
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// Criar um template (submetido à Meta para análise).
|
|
194
|
+
await boto.templates.create({
|
|
195
|
+
name: "boas_vindas",
|
|
196
|
+
language: "pt_BR",
|
|
197
|
+
category: "MARKETING",
|
|
198
|
+
components: [{ type: "BODY", text: "Olá {{1}}, seja bem-vindo!" }],
|
|
199
|
+
phone_number_id,
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
// Listar mensagens (paginação por cursor + filtros).
|
|
203
|
+
const msgs = await boto.messages.list({ limit: 50, direction: "inbound" });
|
|
204
|
+
|
|
205
|
+
// Cliente + link de setup (Embedded Signup).
|
|
206
|
+
await boto.customers.update(customerId, { name: "Padaria do João" });
|
|
207
|
+
const link = await boto.customers.createSetupLink(customerId, {
|
|
208
|
+
allowed_connection_types: ["dedicated"],
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
await boto.webhooks.create({
|
|
212
|
+
url: "https://seu-app.com/hooks",
|
|
213
|
+
events: ["messages", "statuses"], // categorias aceitas pela API (a rota rejeita nomes finos)
|
|
214
|
+
});
|
|
215
|
+
const { data: numeros } = await boto.phoneNumbers.list({ customer_id });
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
## Exemplos
|
|
219
|
+
|
|
220
|
+
Exemplos mínimos e rodáveis na raiz do monorepo, em [`examples/`](../../examples):
|
|
221
|
+
|
|
222
|
+
- [`node-javascript`](../../examples/node-javascript) — envio sandbox e tratamento de `BotoZapError`
|
|
223
|
+
- [`node-typescript`](../../examples/node-typescript) — envio tipado, leitura paginada e erro estruturado
|
|
224
|
+
- [`webhook-receiver`](../../examples/webhook-receiver) — receber os eventos encaminhados (valida `X-Webhook-Signature`)
|
|
225
|
+
- [`mcp-sandbox`](../../examples/mcp-sandbox) — servidor MCP com chave sandbox
|
|
226
|
+
|
|
227
|
+
## Licença
|
|
228
|
+
|
|
229
|
+
MIT
|