pinga-cli 0.0.0 → 0.2.1
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 +232 -2
- package/dist/api.js +64 -0
- package/dist/cli.js +12 -0
- package/dist/command.js +36 -0
- package/dist/commands/auth.js +89 -0
- package/dist/commands/deliveries.js +139 -0
- package/dist/commands/domains.js +99 -0
- package/dist/commands/emails.js +187 -0
- package/dist/commands/templates.js +252 -0
- package/dist/commands/webhooks.js +116 -0
- package/dist/config.js +93 -0
- package/dist/context.js +100 -0
- package/dist/errors.js +48 -0
- package/dist/format.js +24 -0
- package/dist/io.js +3 -0
- package/dist/main.js +190 -0
- package/dist/prompt.js +86 -0
- package/dist/render-error.js +77 -0
- package/dist/template-file.js +115 -0
- package/dist/version.js +2 -0
- package/package.json +51 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Pinga
|
|
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
CHANGED
|
@@ -1,5 +1,235 @@
|
|
|
1
1
|
# pinga-cli
|
|
2
2
|
|
|
3
|
-
CLI oficial
|
|
3
|
+
CLI oficial da [Pinga](https://pinga.api.br), API de email transacional. Escrito em TypeScript
|
|
4
|
+
sobre o [`@pinga/sdk`](https://github.com/pinga-api/pinga-node).
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
> Versão `0.x`: comandos e flags podem mudar entre versões menores.
|
|
7
|
+
|
|
8
|
+
## Instalação
|
|
9
|
+
|
|
10
|
+
**Homebrew** (macOS e Linux):
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
brew install pinga-api/tap/pinga
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
**npm** (Node 20 ou mais novo):
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install -g pinga-cli
|
|
20
|
+
# ou, sem instalar:
|
|
21
|
+
npx pinga-cli --help
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
**Binário** (sem Node): baixe o pacote do seu sistema na
|
|
25
|
+
[página de releases](https://github.com/pinga-api/pinga-cli/releases/latest) — `linux-x64`,
|
|
26
|
+
`linux-arm64`, `darwin-arm64` (Apple Silicon), `darwin-x64` (Intel) ou `windows-x64` — e confira o
|
|
27
|
+
`SHA256SUMS`:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
version=0.2.1 target=linux-x64
|
|
31
|
+
curl -fsSLO "https://github.com/pinga-api/pinga-cli/releases/download/v${version}/pinga-v${version}-${target}.tar.gz"
|
|
32
|
+
curl -fsSLO "https://github.com/pinga-api/pinga-cli/releases/download/v${version}/SHA256SUMS"
|
|
33
|
+
sha256sum --check --ignore-missing SHA256SUMS # no macOS: shasum -a 256 --check --ignore-missing SHA256SUMS
|
|
34
|
+
tar -xzf "pinga-v${version}-${target}.tar.gz"
|
|
35
|
+
sudo install pinga /usr/local/bin/pinga
|
|
36
|
+
pinga --version
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
No Windows, o pacote é um `.zip` com `pinga.exe`; extraia para uma pasta que esteja no `PATH`.
|
|
40
|
+
|
|
41
|
+
## Login
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pinga login
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Pede a API key (painel → **Configurações → API keys**) sem ecoar, confere a chave contra a API e
|
|
48
|
+
grava em `~/.config/pinga/config.json` (`$XDG_CONFIG_HOME/pinga/` se definido;
|
|
49
|
+
`%APPDATA%\pinga\` no Windows), com permissão `0600`.
|
|
50
|
+
|
|
51
|
+
- **Perfis:** `pinga login --profile staging`. Escolha o perfil por `--profile` (ou `-p`) em qualquer
|
|
52
|
+
comando, ou por `PINGA_PROFILE`.
|
|
53
|
+
- **Outra URL de API:** `pinga login --profile local --base-url http://localhost:8080` grava a URL
|
|
54
|
+
no perfil.
|
|
55
|
+
- **CI:** não precisa de login. Defina `PINGA_API_KEY`, que tem precedência sobre o arquivo de
|
|
56
|
+
configuração. Se quiser gravar mesmo assim, a chave vem da entrada padrão:
|
|
57
|
+
`printf '%s' "$PINGA_KEY" | pinga login --profile ci`.
|
|
58
|
+
- `pinga logout` apaga o perfil do arquivo. Não revoga a chave: isso é no painel.
|
|
59
|
+
|
|
60
|
+
## Envio
|
|
61
|
+
|
|
62
|
+
Por template (a versão publicada):
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
pinga emails send \
|
|
66
|
+
--template resgate_de_brinde \
|
|
67
|
+
--to ana@exemplo.com.br --to-name Ana \
|
|
68
|
+
--var nome=Ana --var brinde="camiseta tamanho M" \
|
|
69
|
+
--category transactional \
|
|
70
|
+
--idempotency-key pedido-8412-brinde
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
- `--var chave=valor` manda texto; para números, listas e objetos, use `--vars '{"itens": [1, 2]}'`
|
|
74
|
+
ou `--vars-file variaveis.json`. `--var` sobrescreve a mesma chave do JSON;
|
|
75
|
+
- `--test` renderiza o rascunho em vez da versão publicada.
|
|
76
|
+
|
|
77
|
+
HTML direto:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
pinga emails send \
|
|
81
|
+
--from no-reply@suaempresa.com.br --to ana@exemplo.com.br \
|
|
82
|
+
--subject "Seu recibo" --html-file recibo.html \
|
|
83
|
+
--category transactional
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`--html-file -` lê o HTML da entrada padrão. `--header "Reply-To: suporte@suaempresa.com.br"`
|
|
87
|
+
acrescenta header (repita para vários).
|
|
88
|
+
|
|
89
|
+
`--category` é obrigatório: é a categoria de consentimento do envio (`transactional` existe em toda
|
|
90
|
+
organização). O envio é assíncrono: a resposta diz que a Pinga aceitou o trabalho, não que o email
|
|
91
|
+
chegou.
|
|
92
|
+
|
|
93
|
+
## Entregas
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
pinga deliveries list --status bounced --since 2026-12-01T00:00:00Z
|
|
97
|
+
pinga deliveries list --recipient ana@exemplo.com.br --all --json
|
|
98
|
+
pinga deliveries get 0193a1b2-... # status e linha do tempo de eventos
|
|
99
|
+
pinga deliveries get 0193a1b2-... --html > email.html
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
A listagem mostra 20 por página (`--limit` até 100). Para a página seguinte, passe o `--cursor`
|
|
103
|
+
que o comando imprime; `--all` percorre todas.
|
|
104
|
+
|
|
105
|
+
## Templates como código
|
|
106
|
+
|
|
107
|
+
Versione os templates no git e publique pelo seu CI.
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
pinga templates pull # todos os templates → templates/<slug>/template.json
|
|
111
|
+
pinga templates pull boas_vindas # só esses slugs
|
|
112
|
+
git add templates && git commit -m "templates: estado atual"
|
|
113
|
+
|
|
114
|
+
# edite templates/boas_vindas/template.json, e então:
|
|
115
|
+
pinga templates push --dry-run # o que mudaria
|
|
116
|
+
pinga templates push --message "novo assunto"
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Cada `template.json` é o envelope `pinga.template.v1` da versão ativa, o mesmo do export do
|
|
120
|
+
painel, sem o `exported_at` (que mudaria a cada `pull` e sujaria o diff).
|
|
121
|
+
|
|
122
|
+
O `push` decide por template:
|
|
123
|
+
|
|
124
|
+
| Situação | O que acontece |
|
|
125
|
+
|---|---|
|
|
126
|
+
| Slug não existe na Pinga | importa o arquivo como versão 1 |
|
|
127
|
+
| Igual à versão ativa | nada — `pull` seguido de `push` não cria versão |
|
|
128
|
+
| Conteúdo diferente | grava o rascunho e publica a próxima versão |
|
|
129
|
+
| Só nome, descrição ou remetente diferentes | atualiza o template, sem versão nova |
|
|
130
|
+
|
|
131
|
+
- Num template visual (com `document`), só o `document` e as `variables` contam: `subject`, `mjml`
|
|
132
|
+
e `text_body` são derivados dele.
|
|
133
|
+
- Se um template falha, os demais seguem e o comando sai com código `1`. Arquivo inválido barra tudo
|
|
134
|
+
antes da primeira escrita.
|
|
135
|
+
- Os caminhos podem ser um `template.json`, o diretório de um slug ou um diretório com vários
|
|
136
|
+
(padrão: `templates/`, ou `--dir`).
|
|
137
|
+
|
|
138
|
+
No CI, com a chave num secret:
|
|
139
|
+
|
|
140
|
+
```yaml
|
|
141
|
+
- run: npx pinga-cli templates push --message "$COMMIT_MESSAGE"
|
|
142
|
+
env:
|
|
143
|
+
PINGA_API_KEY: ${{ secrets.PINGA_API_KEY }}
|
|
144
|
+
# Pela env, nunca interpolado no `run`: a mensagem de commit é texto de quem fez o commit.
|
|
145
|
+
COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## Domínios remetentes
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
pinga domains check # todos os domínios da organização
|
|
152
|
+
pinga domains check loja.com.br # só esse
|
|
153
|
+
pinga domains check --refresh # reconsulta DKIM e DNS antes de mostrar
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Mostra o estado do DKIM, do SPF, do DMARC e do MX. Domínio ainda não verificado vem com a tabela dos
|
|
157
|
+
registros DNS a configurar; domínio verificado sem SPF ou DMARC vem com o registro recomendado. Sai
|
|
158
|
+
com código `1` se algum domínio mostrado não estiver verificado, o que serve de checagem no CI.
|
|
159
|
+
`--refresh` faz escrita na API (reconsulta) e exige chave com escopo total.
|
|
160
|
+
|
|
161
|
+
## Verificar assinatura de webhook
|
|
162
|
+
|
|
163
|
+
Confere o header `X-Webhook-Signature` contra o corpo bruto e o segredo, localmente, do mesmo jeito
|
|
164
|
+
que o seu endpoint deve conferir. Útil para depurar uma integração que recusa entregas.
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
export PINGA_WEBHOOK_SECRET="whsec_..."
|
|
168
|
+
pinga webhooks verify --payload-file corpo.json --signature "t=1764950000,v1=5257a8..."
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
- o corpo precisa ser o **bruto**, exatamente como chegou: JSON reformatado não confere;
|
|
172
|
+
- o segredo vem de `PINGA_WEBHOOK_SECRET`, `--secret-file` ou `--secret` (este fica no histórico do
|
|
173
|
+
shell). Na rotação, passe o novo e o antigo: vale se conferir com qualquer um;
|
|
174
|
+
- assinatura com mais de 5 minutos é recusada; para um corpo capturado há tempo, use
|
|
175
|
+
`--ignore-timestamp` (ou `--tolerance <segundos>`);
|
|
176
|
+
- sai com `0` se confere e `1` se não, dizendo o motivo (`signature_mismatch`,
|
|
177
|
+
`timestamp_out_of_tolerance`, `malformed_signature`). O segredo nunca aparece na saída.
|
|
178
|
+
|
|
179
|
+
## Saída, erros e códigos de saída
|
|
180
|
+
|
|
181
|
+
- `--json` em qualquer comando: o resultado vai como JSON para o stdout. Avisos e dicas vão sempre
|
|
182
|
+
para o stderr, então `pinga ... --json | jq` recebe só o JSON.
|
|
183
|
+
- Erro da API mostra `title`, `detail`, os erros de campo e o `trace_id` do Problem Details — mande o
|
|
184
|
+
`trace_id` ao pedir suporte. Com `--json`, o erro sai como JSON no **stderr**:
|
|
185
|
+
`{ "error": { "type", "status", "title", "detail", "trace_id", "errors", "variable_errors" } }`.
|
|
186
|
+
- Códigos de saída: `0` sucesso, `1` falha (API, rede, configuração), `2` erro de uso (flag
|
|
187
|
+
desconhecida, argumento faltando).
|
|
188
|
+
- A API key nunca aparece na saída do CLI, nem em `--json`, nem em mensagem de erro. O mesmo vale
|
|
189
|
+
para o segredo de webhook.
|
|
190
|
+
|
|
191
|
+
## Ambiente
|
|
192
|
+
|
|
193
|
+
| Variável | Uso |
|
|
194
|
+
|---|---|
|
|
195
|
+
| `PINGA_API_KEY` | API key; tem precedência sobre o arquivo de configuração |
|
|
196
|
+
| `PINGA_PROFILE` | perfil padrão (padrão: `default`) |
|
|
197
|
+
| `PINGA_BASE_URL` | URL da API (padrão: `https://api.pinga.api.br`) |
|
|
198
|
+
| `PINGA_CONFIG_DIR` | diretório do `config.json` |
|
|
199
|
+
| `PINGA_WEBHOOK_SECRET` | segredo para `pinga webhooks verify` |
|
|
200
|
+
|
|
201
|
+
## Desenvolvimento
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
bun install
|
|
205
|
+
bun run test # testes unitários (o CLI inteiro em memória, com fetch falso)
|
|
206
|
+
bun run typecheck
|
|
207
|
+
bun run build
|
|
208
|
+
bun run dev -- --help
|
|
209
|
+
|
|
210
|
+
# Smoke: o binário construído contra a stack de E2E local do monorepo
|
|
211
|
+
bun run build && PINGA_SMOKE_BASE_URL=http://localhost:8080 PINGA_SMOKE_PROVISION=1 bun run smoke
|
|
212
|
+
|
|
213
|
+
# O mesmo smoke contra o binário compilado
|
|
214
|
+
bun run build:bin && PINGA_SMOKE_BIN=bin/pinga PINGA_SMOKE_BASE_URL=http://localhost:8080 PINGA_SMOKE_PROVISION=1 bun run smoke
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### Release
|
|
218
|
+
|
|
219
|
+
Fazer push de uma tag `v<maior>.<menor>.<patch>` que aponte para um commit da `main` (com o
|
|
220
|
+
`package.json` na mesma versão) dispara o `release.yml`, que cria o release no GitHub: testes, binários compilados com `bun build --compile` (os de macOS compilados e
|
|
221
|
+
assinados ad hoc num runner macOS), cada binário rodado no sistema nativo, npm por Trusted
|
|
222
|
+
Publishing, pacotes e `SHA256SUMS` anexados ao release e a fórmula regravada em
|
|
223
|
+
[`pinga-api/homebrew-tap`](https://github.com/pinga-api/homebrew-tap), seguida de um
|
|
224
|
+
`brew install` de verdade. O npm só publica se todos os binários passarem.
|
|
225
|
+
|
|
226
|
+
A publicação no tap usa o secret `HOMEBREW_TAP_TOKEN`: um token fine-grained com
|
|
227
|
+
**Contents: read and write** só no repositório `pinga-api/homebrew-tap`. Sem ele, o release segue e
|
|
228
|
+
a fórmula fica no resumo do job.
|
|
229
|
+
|
|
230
|
+
Argumentos são lidos com `parseArgs` de `node:util`, sem framework de CLI. A única dependência de
|
|
231
|
+
runtime é o `@pinga/sdk`.
|
|
232
|
+
|
|
233
|
+
## Licença
|
|
234
|
+
|
|
235
|
+
MIT
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { PingaError, SdkErrorType } from "@pinga/sdk";
|
|
2
|
+
import { CliError } from "./errors.js";
|
|
3
|
+
import { VERSION } from "./version.js";
|
|
4
|
+
/**
|
|
5
|
+
* Codifica um id vindo da API para entrar como um segmento do path. "." e ".." são recusados:
|
|
6
|
+
* `encodeURIComponent` não os altera e o parser de URL os resolve como segmentos de ponto
|
|
7
|
+
* (inclusive %2E%2E), o que tiraria a chamada de /v1/sender-domains/.
|
|
8
|
+
*/
|
|
9
|
+
export function pathSegment(id) {
|
|
10
|
+
if (id === "" || id === "." || id === "..")
|
|
11
|
+
throw new CliError(`A API devolveu um id inválido: ${JSON.stringify(id)}.`);
|
|
12
|
+
return encodeURIComponent(id);
|
|
13
|
+
}
|
|
14
|
+
const TIMEOUT_MS = 30_000;
|
|
15
|
+
/**
|
|
16
|
+
* Chamada direta à API para as operações que o `@pinga/sdk` ainda não cobre (domínios remetentes).
|
|
17
|
+
* Mesma autenticação, mesmo `User-Agent` e o mesmo `PingaError` do SDK, para o erro sair igual aos
|
|
18
|
+
* demais comandos. Quando o SDK ganhar o recurso, os comandos passam a usá-lo e este arquivo sai.
|
|
19
|
+
*/
|
|
20
|
+
export async function apiRequest(ctx, request) {
|
|
21
|
+
const { apiKey, baseUrl } = await ctx.credentials();
|
|
22
|
+
ctx.rememberSecret(apiKey);
|
|
23
|
+
const url = new URL(`${baseUrl.replace(/\/+$/, "")}${request.path}`);
|
|
24
|
+
for (const [key, value] of Object.entries(request.query ?? {})) {
|
|
25
|
+
if (value !== undefined)
|
|
26
|
+
url.searchParams.set(key, String(value));
|
|
27
|
+
}
|
|
28
|
+
const headers = {
|
|
29
|
+
Accept: "application/json",
|
|
30
|
+
Authorization: `Bearer ${apiKey}`,
|
|
31
|
+
"User-Agent": `pinga-cli/${VERSION}`,
|
|
32
|
+
};
|
|
33
|
+
if (request.idempotent)
|
|
34
|
+
headers["Idempotency-Key"] = globalThis.crypto.randomUUID();
|
|
35
|
+
const fetchImpl = ctx.io.fetch ?? globalThis.fetch;
|
|
36
|
+
let response;
|
|
37
|
+
try {
|
|
38
|
+
response = await fetchImpl(url, { method: request.method, headers, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
const timedOut = error instanceof Error && error.name === "TimeoutError";
|
|
42
|
+
throw new PingaError({
|
|
43
|
+
status: 0,
|
|
44
|
+
type: timedOut ? SdkErrorType.Timeout : SdkErrorType.Connection,
|
|
45
|
+
title: timedOut ? "Tempo esgotado esperando a API" : "Falha de conexão com a API",
|
|
46
|
+
detail: error instanceof Error ? error.message : String(error),
|
|
47
|
+
cause: error,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
const text = await response.text();
|
|
51
|
+
if (!response.ok)
|
|
52
|
+
throw PingaError.fromResponse(response, text);
|
|
53
|
+
try {
|
|
54
|
+
return JSON.parse(text);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
throw new PingaError({
|
|
58
|
+
status: response.status,
|
|
59
|
+
type: SdkErrorType.InvalidResponse,
|
|
60
|
+
title: "Resposta da API não é JSON válido",
|
|
61
|
+
cause: error,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import { main } from "./main.js";
|
|
4
|
+
const code = await main(process.argv.slice(2), {
|
|
5
|
+
stdin: process.stdin,
|
|
6
|
+
stdout: process.stdout,
|
|
7
|
+
stderr: process.stderr,
|
|
8
|
+
env: process.env,
|
|
9
|
+
platform: process.platform,
|
|
10
|
+
homedir: os.homedir(),
|
|
11
|
+
});
|
|
12
|
+
process.exitCode = code;
|
package/dist/command.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { UsageError } from "./errors.js";
|
|
2
|
+
export function stringFlag(values, name, required = false) {
|
|
3
|
+
const value = values[name];
|
|
4
|
+
if (typeof value === "string" && value.length > 0)
|
|
5
|
+
return value;
|
|
6
|
+
if (required)
|
|
7
|
+
throw new UsageError(`--${name} é obrigatório.`);
|
|
8
|
+
return undefined;
|
|
9
|
+
}
|
|
10
|
+
export function listFlag(values, name) {
|
|
11
|
+
const value = values[name];
|
|
12
|
+
if (Array.isArray(value))
|
|
13
|
+
return value.filter((item) => typeof item === "string");
|
|
14
|
+
return typeof value === "string" ? [value] : [];
|
|
15
|
+
}
|
|
16
|
+
export function booleanFlag(values, name) {
|
|
17
|
+
return values[name] === true;
|
|
18
|
+
}
|
|
19
|
+
export function integerFlag(values, name, range) {
|
|
20
|
+
const raw = stringFlag(values, name);
|
|
21
|
+
if (raw === undefined)
|
|
22
|
+
return undefined;
|
|
23
|
+
const value = Number(raw);
|
|
24
|
+
if (!Number.isInteger(value) || value < range.min || value > range.max) {
|
|
25
|
+
throw new UsageError(`--${name} precisa ser um inteiro entre ${range.min} e ${range.max}.`);
|
|
26
|
+
}
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
/** Converte `chave=valor` em par; o valor pode conter `=`. */
|
|
30
|
+
export function parsePair(raw, flag, separator = /=/) {
|
|
31
|
+
const match = separator.exec(raw);
|
|
32
|
+
if (!match || match.index === 0) {
|
|
33
|
+
throw new UsageError(`--${flag} espera chave=valor, recebeu "${raw}".`);
|
|
34
|
+
}
|
|
35
|
+
return [raw.slice(0, match.index).trim(), raw.slice(match.index + match[0].length)];
|
|
36
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { PingaError } from "@pinga/sdk";
|
|
2
|
+
import { booleanFlag } from "../command.js";
|
|
3
|
+
import { writeConfig } from "../config.js";
|
|
4
|
+
import { CliError } from "../errors.js";
|
|
5
|
+
import { readSecret } from "../prompt.js";
|
|
6
|
+
const API_KEY_FORMAT = /^pg_(live|test)_[A-Za-z0-9]{32}$/;
|
|
7
|
+
export const login = {
|
|
8
|
+
name: ["login"],
|
|
9
|
+
summary: "Grava a API key no arquivo de configuração",
|
|
10
|
+
help: `Uso: pinga login [--profile <nome>] [--base-url <url>] [--skip-verify]
|
|
11
|
+
|
|
12
|
+
Pede a API key sem ecoar e grava no perfil escolhido, em arquivo com permissão 0600.
|
|
13
|
+
Antes de gravar, confere a chave contra a API (uma listagem de entregas com limit 1).
|
|
14
|
+
|
|
15
|
+
Sem terminal, lê a chave da primeira linha da entrada padrão:
|
|
16
|
+
printf '%s' "$CHAVE" | pinga login --profile ci
|
|
17
|
+
|
|
18
|
+
Opções:
|
|
19
|
+
--skip-verify grava sem conferir a chave contra a API`,
|
|
20
|
+
options: {
|
|
21
|
+
"skip-verify": { type: "boolean" },
|
|
22
|
+
},
|
|
23
|
+
positionals: { min: 0, max: 0 },
|
|
24
|
+
async run(ctx, values) {
|
|
25
|
+
if (ctx.io.env["PINGA_API_KEY"]) {
|
|
26
|
+
ctx.err("Aviso: PINGA_API_KEY está definida e continua tendo precedência sobre o arquivo de configuração.");
|
|
27
|
+
}
|
|
28
|
+
const apiKey = (await readSecret(ctx.io.stdin, ctx.io.stderr, "API key (pg_live_... ou pg_test_...): ")).trim();
|
|
29
|
+
ctx.rememberSecret(apiKey);
|
|
30
|
+
if (!apiKey)
|
|
31
|
+
throw new CliError("Nenhuma API key informada.");
|
|
32
|
+
const match = API_KEY_FORMAT.exec(apiKey);
|
|
33
|
+
if (!match) {
|
|
34
|
+
// A chave digitada não entra na mensagem, nem mascarada.
|
|
35
|
+
throw new CliError("A chave não tem o formato esperado: pg_live_ ou pg_test_ seguido de 32 letras e números.");
|
|
36
|
+
}
|
|
37
|
+
const mode = match[1];
|
|
38
|
+
const config = await ctx.config();
|
|
39
|
+
const targetBaseUrl = await ctx.baseUrl();
|
|
40
|
+
const verify = !booleanFlag(values, "skip-verify");
|
|
41
|
+
if (verify) {
|
|
42
|
+
try {
|
|
43
|
+
await ctx.createClient(apiKey, targetBaseUrl).deliveries.list({ limit: 1 }, { maxRetries: 1 });
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (error instanceof PingaError && error.status === 401) {
|
|
47
|
+
throw new CliError(`A API recusou a chave (HTTP 401) em ${targetBaseUrl}. Confira se ela foi revogada ou se é de outro ambiente.${error.traceId ? ` trace_id: ${error.traceId}` : ""}`);
|
|
48
|
+
}
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const previous = config.profiles[ctx.profile] ?? {};
|
|
53
|
+
// Só `--base-url` fica gravado no perfil; `PINGA_BASE_URL` vale para a execução, não para sempre.
|
|
54
|
+
const baseUrl = typeof values["base-url"] === "string" ? values["base-url"] : previous.base_url;
|
|
55
|
+
config.profiles[ctx.profile] = { ...previous, api_key: apiKey, base_url: baseUrl };
|
|
56
|
+
await writeConfig(ctx.configFile, config);
|
|
57
|
+
if (ctx.json) {
|
|
58
|
+
ctx.outJson({ profile: ctx.profile, mode, verified: verify, config_path: ctx.configFile });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
ctx.out(`Chave ${mode} gravada no perfil "${ctx.profile}" (${ctx.configFile}).`);
|
|
62
|
+
if (!verify)
|
|
63
|
+
ctx.out("A chave não foi conferida contra a API (--skip-verify).");
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
export const logout = {
|
|
67
|
+
name: ["logout"],
|
|
68
|
+
summary: "Remove a API key de um perfil",
|
|
69
|
+
help: `Uso: pinga logout [--profile <nome>]
|
|
70
|
+
|
|
71
|
+
Apaga o perfil do arquivo de configuração. Não revoga a chave na Pinga: para isso, use o painel.`,
|
|
72
|
+
options: {},
|
|
73
|
+
positionals: { min: 0, max: 0 },
|
|
74
|
+
async run(ctx) {
|
|
75
|
+
const config = await ctx.config();
|
|
76
|
+
const removed = ctx.profile in config.profiles;
|
|
77
|
+
if (removed) {
|
|
78
|
+
delete config.profiles[ctx.profile];
|
|
79
|
+
await writeConfig(ctx.configFile, config);
|
|
80
|
+
}
|
|
81
|
+
if (ctx.json) {
|
|
82
|
+
ctx.outJson({ profile: ctx.profile, removed });
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
ctx.out(removed ? `Perfil "${ctx.profile}" removido.` : `Perfil "${ctx.profile}" não existe; nada a fazer.`);
|
|
86
|
+
if (ctx.io.env["PINGA_API_KEY"])
|
|
87
|
+
ctx.err("Aviso: PINGA_API_KEY continua definida no ambiente.");
|
|
88
|
+
},
|
|
89
|
+
};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { booleanFlag, integerFlag, stringFlag } from "../command.js";
|
|
2
|
+
import { escapeSlug, table } from "../format.js";
|
|
3
|
+
export const deliveriesList = {
|
|
4
|
+
name: ["deliveries", "list"],
|
|
5
|
+
summary: "Lista entregas, das mais recentes para as mais antigas",
|
|
6
|
+
help: `Uso: pinga deliveries list [filtros] [--limit <n>] [--cursor <cursor> | --all]
|
|
7
|
+
|
|
8
|
+
Filtros:
|
|
9
|
+
--status <status> queued, sent, delivered, bounced, failed...
|
|
10
|
+
--recipient <email> destinatário exato
|
|
11
|
+
--recipient-contains <texto> parte do email do destinatário
|
|
12
|
+
--template-id <id>
|
|
13
|
+
--notification-type <slug>
|
|
14
|
+
--query <texto> busca livre
|
|
15
|
+
--since <data> criadas a partir de (ISO 8601, ex.: 2026-12-01T00:00:00Z)
|
|
16
|
+
--until <data> criadas até
|
|
17
|
+
|
|
18
|
+
Paginação:
|
|
19
|
+
--limit <n> itens por página (1 a 100, padrão 20)
|
|
20
|
+
--cursor <cursor> continua de onde a página anterior parou
|
|
21
|
+
--all percorre todas as páginas`,
|
|
22
|
+
options: {
|
|
23
|
+
status: { type: "string" },
|
|
24
|
+
recipient: { type: "string" },
|
|
25
|
+
"recipient-contains": { type: "string" },
|
|
26
|
+
"template-id": { type: "string" },
|
|
27
|
+
"notification-type": { type: "string" },
|
|
28
|
+
query: { type: "string" },
|
|
29
|
+
since: { type: "string" },
|
|
30
|
+
until: { type: "string" },
|
|
31
|
+
limit: { type: "string" },
|
|
32
|
+
cursor: { type: "string" },
|
|
33
|
+
all: { type: "boolean" },
|
|
34
|
+
},
|
|
35
|
+
positionals: { min: 0, max: 0 },
|
|
36
|
+
async run(ctx, values) {
|
|
37
|
+
const params = {
|
|
38
|
+
status: stringFlag(values, "status"),
|
|
39
|
+
recipient_email: stringFlag(values, "recipient"),
|
|
40
|
+
recipient_email_contains: stringFlag(values, "recipient-contains"),
|
|
41
|
+
template_id: stringFlag(values, "template-id"),
|
|
42
|
+
notification_type_slug: stringFlag(values, "notification-type"),
|
|
43
|
+
q: stringFlag(values, "query"),
|
|
44
|
+
created_after: stringFlag(values, "since"),
|
|
45
|
+
created_before: stringFlag(values, "until"),
|
|
46
|
+
limit: integerFlag(values, "limit", { min: 1, max: 100 }) ?? 20,
|
|
47
|
+
cursor: stringFlag(values, "cursor"),
|
|
48
|
+
};
|
|
49
|
+
const pinga = await ctx.client();
|
|
50
|
+
let items;
|
|
51
|
+
let nextCursor = null;
|
|
52
|
+
let hasMore = false;
|
|
53
|
+
if (booleanFlag(values, "all")) {
|
|
54
|
+
items = [];
|
|
55
|
+
for await (const item of pinga.deliveries.list(params))
|
|
56
|
+
items.push(item);
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
const page = await pinga.deliveries.list(params);
|
|
60
|
+
items = page.data;
|
|
61
|
+
hasMore = page.hasNextPage();
|
|
62
|
+
nextCursor = hasMore ? page.next_cursor : null;
|
|
63
|
+
}
|
|
64
|
+
if (ctx.json) {
|
|
65
|
+
ctx.outJson({ data: items, has_more: hasMore, next_cursor: nextCursor });
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (items.length === 0) {
|
|
69
|
+
ctx.err("Nenhuma entrega encontrada.");
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
ctx.out(table(["ID", "STATUS", "DESTINATÁRIO", "ASSUNTO", "CRIADA EM"], items.map((item) => [item.id, item.status, item.recipient.email, item.subject, item.created_at])));
|
|
73
|
+
if (nextCursor)
|
|
74
|
+
ctx.err(`Há mais entregas. Próxima página: --cursor ${nextCursor}`);
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
export const deliveriesGet = {
|
|
78
|
+
name: ["deliveries", "get"],
|
|
79
|
+
summary: "Mostra uma entrega e a linha do tempo de eventos",
|
|
80
|
+
help: `Uso: pinga deliveries get <delivery_id> [--html]
|
|
81
|
+
|
|
82
|
+
Opções:
|
|
83
|
+
--html imprime só o HTML renderizado (útil para redirecionar para um arquivo)`,
|
|
84
|
+
options: {
|
|
85
|
+
html: { type: "boolean" },
|
|
86
|
+
},
|
|
87
|
+
positionals: { min: 1, max: 1, names: "<delivery_id>" },
|
|
88
|
+
async run(ctx, values, positionals) {
|
|
89
|
+
const id = positionals[0];
|
|
90
|
+
const pinga = await ctx.client();
|
|
91
|
+
const delivery = await pinga.deliveries.get(id);
|
|
92
|
+
if (booleanFlag(values, "html")) {
|
|
93
|
+
ctx.io.stdout.write(delivery.rendered_html);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (ctx.json) {
|
|
97
|
+
ctx.outJson(delivery);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
ctx.out(describeDelivery(delivery));
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
function describeDelivery(delivery) {
|
|
104
|
+
const recipient = delivery.recipient.name
|
|
105
|
+
? `${delivery.recipient.name} <${delivery.recipient.email}>`
|
|
106
|
+
: delivery.recipient.email;
|
|
107
|
+
const fields = [
|
|
108
|
+
["ID", delivery.id],
|
|
109
|
+
["Status", delivery.status],
|
|
110
|
+
["Modo", delivery.mode],
|
|
111
|
+
["Destinatário", recipient],
|
|
112
|
+
["Remetente", delivery.from.address],
|
|
113
|
+
["Assunto", delivery.subject],
|
|
114
|
+
[
|
|
115
|
+
"Template",
|
|
116
|
+
delivery.template
|
|
117
|
+
? `${escapeSlug(delivery.template.slug)}${delivery.template.version != null ? ` (v${delivery.template.version})` : ""}`
|
|
118
|
+
: null,
|
|
119
|
+
],
|
|
120
|
+
["Tipo de notificação", delivery.notification_type ? escapeSlug(delivery.notification_type.slug) : null],
|
|
121
|
+
["Provedor", delivery.provider],
|
|
122
|
+
["Falha", delivery.failure_reason],
|
|
123
|
+
["Reenvio de", delivery.resend_of_delivery_id],
|
|
124
|
+
["Criada em", delivery.created_at],
|
|
125
|
+
];
|
|
126
|
+
const lines = fields
|
|
127
|
+
.filter((field) => typeof field[1] === "string" && field[1].length > 0)
|
|
128
|
+
.map(([label, value]) => `${`${label}:`.padEnd(21)}${value}`);
|
|
129
|
+
lines.push("", "Eventos:");
|
|
130
|
+
if (delivery.events.length === 0) {
|
|
131
|
+
lines.push(" (nenhum ainda)");
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
const events = [...delivery.events].sort((a, b) => a.occurred_at.localeCompare(b.occurred_at));
|
|
135
|
+
for (const event of events)
|
|
136
|
+
lines.push(` ${event.occurred_at} ${event.type}`);
|
|
137
|
+
}
|
|
138
|
+
return lines.join("\n");
|
|
139
|
+
}
|