pinga-cli 0.0.0 → 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 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,122 @@
1
1
  # pinga-cli
2
2
 
3
- CLI oficial do Pinga — API de email transacional (pinga.api.br).
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
- Em desenvolvimento. Documentação: https://docs.pinga.api.br
6
+ > Versão `0.x`: comandos e flags podem mudar entre versões menores.
7
+
8
+ ## Instalação
9
+
10
+ ```bash
11
+ npm install -g pinga-cli
12
+ # ou
13
+ bun add -g pinga-cli
14
+ ```
15
+
16
+ Exige Node 20 ou mais novo. Para rodar uma vez, sem instalar: `npx pinga-cli --help`.
17
+
18
+ Binários compilados e tap do Homebrew entram numa versão seguinte.
19
+
20
+ ## Login
21
+
22
+ ```bash
23
+ pinga login
24
+ ```
25
+
26
+ Pede a API key (painel → **Configurações → API keys**) sem ecoar, confere a chave contra a API e
27
+ grava em `~/.config/pinga/config.json` (`$XDG_CONFIG_HOME/pinga/` se definido;
28
+ `%APPDATA%\pinga\` no Windows), com permissão `0600`.
29
+
30
+ - **Perfis:** `pinga login --profile staging`. Escolha o perfil por `--profile` (ou `-p`) em qualquer
31
+ comando, ou por `PINGA_PROFILE`.
32
+ - **Outra URL de API:** `pinga login --profile local --base-url http://localhost:8080` grava a URL
33
+ no perfil.
34
+ - **CI:** não precisa de login. Defina `PINGA_API_KEY`, que tem precedência sobre o arquivo de
35
+ configuração. Se quiser gravar mesmo assim, a chave vem da entrada padrão:
36
+ `printf '%s' "$PINGA_KEY" | pinga login --profile ci`.
37
+ - `pinga logout` apaga o perfil do arquivo. Não revoga a chave: isso é no painel.
38
+
39
+ ## Envio
40
+
41
+ Por template (a versão publicada):
42
+
43
+ ```bash
44
+ pinga emails send \
45
+ --template resgate_de_brinde \
46
+ --to ana@exemplo.com.br --to-name Ana \
47
+ --var nome=Ana --var brinde="camiseta tamanho M" \
48
+ --category transactional \
49
+ --idempotency-key pedido-8412-brinde
50
+ ```
51
+
52
+ - `--var chave=valor` manda texto; para números, listas e objetos, use `--vars '{"itens": [1, 2]}'`
53
+ ou `--vars-file variaveis.json`. `--var` sobrescreve a mesma chave do JSON;
54
+ - `--test` renderiza o rascunho em vez da versão publicada.
55
+
56
+ HTML direto:
57
+
58
+ ```bash
59
+ pinga emails send \
60
+ --from no-reply@suaempresa.com.br --to ana@exemplo.com.br \
61
+ --subject "Seu recibo" --html-file recibo.html \
62
+ --category transactional
63
+ ```
64
+
65
+ `--html-file -` lê o HTML da entrada padrão. `--header "Reply-To: suporte@suaempresa.com.br"`
66
+ acrescenta header (repita para vários).
67
+
68
+ `--category` é obrigatório: é a categoria de consentimento do envio (`transactional` existe em toda
69
+ organização). O envio é assíncrono: a resposta diz que a Pinga aceitou o trabalho, não que o email
70
+ chegou.
71
+
72
+ ## Entregas
73
+
74
+ ```bash
75
+ pinga deliveries list --status bounced --since 2026-12-01T00:00:00Z
76
+ pinga deliveries list --recipient ana@exemplo.com.br --all --json
77
+ pinga deliveries get 0193a1b2-... # status e linha do tempo de eventos
78
+ pinga deliveries get 0193a1b2-... --html > email.html
79
+ ```
80
+
81
+ A listagem mostra 20 por página (`--limit` até 100). Para a página seguinte, passe o `--cursor`
82
+ que o comando imprime; `--all` percorre todas.
83
+
84
+ ## Saída, erros e códigos de saída
85
+
86
+ - `--json` em qualquer comando: o resultado vai como JSON para o stdout. Avisos e dicas vão sempre
87
+ para o stderr, então `pinga ... --json | jq` recebe só o JSON.
88
+ - Erro da API mostra `title`, `detail`, os erros de campo e o `trace_id` do Problem Details — mande o
89
+ `trace_id` ao pedir suporte. Com `--json`, o erro sai como JSON no **stderr**:
90
+ `{ "error": { "type", "status", "title", "detail", "trace_id", "errors", "variable_errors" } }`.
91
+ - Códigos de saída: `0` sucesso, `1` falha (API, rede, configuração), `2` erro de uso (flag
92
+ desconhecida, argumento faltando).
93
+ - A API key nunca aparece na saída do CLI, nem em `--json`, nem em mensagem de erro.
94
+
95
+ ## Ambiente
96
+
97
+ | Variável | Uso |
98
+ |---|---|
99
+ | `PINGA_API_KEY` | API key; tem precedência sobre o arquivo de configuração |
100
+ | `PINGA_PROFILE` | perfil padrão (padrão: `default`) |
101
+ | `PINGA_BASE_URL` | URL da API (padrão: `https://api.pinga.api.br`) |
102
+ | `PINGA_CONFIG_DIR` | diretório do `config.json` |
103
+
104
+ ## Desenvolvimento
105
+
106
+ ```bash
107
+ bun install
108
+ bun run test # testes unitários (o CLI inteiro em memória, com fetch falso)
109
+ bun run typecheck
110
+ bun run build
111
+ bun run dev -- --help
112
+
113
+ # Smoke: o binário construído contra a stack de E2E local do monorepo
114
+ bun run build && PINGA_SMOKE_BASE_URL=http://localhost:8080 PINGA_SMOKE_PROVISION=1 bun run smoke
115
+ ```
116
+
117
+ Argumentos são lidos com `parseArgs` de `node:util`, sem framework de CLI. A única dependência de
118
+ runtime é o `@pinga/sdk`.
119
+
120
+ ## Licença
121
+
122
+ MIT
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;
@@ -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 { 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
+ ? `${delivery.template.slug}${delivery.template.version != null ? ` (v${delivery.template.version})` : ""}`
118
+ : null,
119
+ ],
120
+ ["Tipo de notificação", delivery.notification_type?.slug],
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
+ }
@@ -0,0 +1,187 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { booleanFlag, listFlag, parsePair, stringFlag } from "../command.js";
3
+ import { CliError, UsageError } from "../errors.js";
4
+ import { readAll } from "../prompt.js";
5
+ export const emailsSend = {
6
+ name: ["emails", "send"],
7
+ summary: "Envio transacional (HTML direto ou template com variáveis)",
8
+ help: `Uso: pinga emails send --to <email> (--template <slug> | --from <email> --subject <texto> --html <html>) [opções]
9
+
10
+ Enfileira um envio. A resposta diz que a Pinga aceitou o trabalho, não que o email chegou:
11
+ acompanhe com \`pinga deliveries get <delivery_id>\`.
12
+
13
+ Por template (a versão publicada; --test usa o rascunho):
14
+ pinga emails send --template boas_vindas --to ana@exemplo.com.br --var nome=Ana --category transactional
15
+
16
+ HTML direto:
17
+ pinga emails send --from no-reply@suaempresa.com.br --to ana@exemplo.com.br \\
18
+ --subject "Seu recibo" --html-file recibo.html --category transactional
19
+
20
+ Destinatário e remetente:
21
+ --to <email> destinatário (obrigatório)
22
+ --to-name <nome>
23
+ --from <email> remetente verificado (obrigatório no HTML direto; opcional no template)
24
+ --from-name <nome>
25
+
26
+ Template:
27
+ --template <slug> template pelo slug
28
+ --template-id <id> template pelo id
29
+ --var <chave=valor> variável de texto; repita para várias
30
+ --vars <json> variáveis como objeto JSON (números, listas, objetos)
31
+ --vars-file <arquivo> variáveis de um arquivo JSON
32
+ --test renderiza o rascunho em vez da versão publicada
33
+
34
+ HTML direto:
35
+ --subject <texto>
36
+ --html <html> | --html-file <arquivo> use "-" para ler da entrada padrão
37
+ --text <texto> | --text-file <arquivo> versão em texto puro (opcional)
38
+
39
+ Comum:
40
+ --category <slug> categoria de consentimento, obrigatória (ex.: transactional)
41
+ --header <Nome: valor> header extra; repita para vários
42
+ --idempotency-key <chave> chave de idempotência; prefira uma do seu domínio (ex.: pedido-123-recibo)`,
43
+ options: {
44
+ to: { type: "string" },
45
+ "to-name": { type: "string" },
46
+ from: { type: "string" },
47
+ "from-name": { type: "string" },
48
+ template: { type: "string" },
49
+ "template-id": { type: "string" },
50
+ var: { type: "string", multiple: true },
51
+ vars: { type: "string" },
52
+ "vars-file": { type: "string" },
53
+ test: { type: "boolean" },
54
+ subject: { type: "string" },
55
+ html: { type: "string" },
56
+ "html-file": { type: "string" },
57
+ text: { type: "string" },
58
+ "text-file": { type: "string" },
59
+ category: { type: "string" },
60
+ header: { type: "string", multiple: true },
61
+ "idempotency-key": { type: "string" },
62
+ },
63
+ positionals: { min: 0, max: 0 },
64
+ async run(ctx, values) {
65
+ const params = await buildSendParams(ctx, values);
66
+ const pinga = await ctx.client();
67
+ const response = await pinga.emails.send(params, {
68
+ test: booleanFlag(values, "test") || undefined,
69
+ idempotencyKey: stringFlag(values, "idempotency-key"),
70
+ });
71
+ if (ctx.json) {
72
+ ctx.outJson(response);
73
+ return;
74
+ }
75
+ ctx.out(`Envio aceito: ${response.delivery_id} (${response.status})`);
76
+ if (response.blocked_reason)
77
+ ctx.out(`Bloqueado: ${response.blocked_reason}`);
78
+ ctx.err(`Acompanhe com: pinga deliveries get ${response.delivery_id}`);
79
+ },
80
+ };
81
+ export async function buildSendParams(ctx, values) {
82
+ const to = stringFlag(values, "to", true);
83
+ const toName = stringFlag(values, "to-name");
84
+ const fromAddress = stringFlag(values, "from");
85
+ const from = fromAddress ? { address: fromAddress, name: stringFlag(values, "from-name") } : undefined;
86
+ const headers = parseHeaders(listFlag(values, "header"));
87
+ const category = stringFlag(values, "category");
88
+ const slug = stringFlag(values, "template");
89
+ const templateId = stringFlag(values, "template-id");
90
+ const isTemplate = slug !== undefined || templateId !== undefined;
91
+ if (isTemplate) {
92
+ if (slug && templateId)
93
+ throw new UsageError("Use --template ou --template-id, não os dois.");
94
+ for (const flag of ["subject", "html", "html-file", "text", "text-file"]) {
95
+ if (values[flag] !== undefined) {
96
+ throw new UsageError(`--${flag} não vale com template: assunto e corpo vêm do template.`);
97
+ }
98
+ }
99
+ return {
100
+ template: slug ? { slug } : { id: templateId },
101
+ recipient: { email: to, name: toName },
102
+ variables: await parseVariables(ctx, values),
103
+ from,
104
+ headers,
105
+ category,
106
+ };
107
+ }
108
+ if (booleanFlag(values, "test"))
109
+ throw new UsageError("--test só vale com --template ou --template-id.");
110
+ for (const flag of ["var", "vars", "vars-file"]) {
111
+ if (values[flag] !== undefined)
112
+ throw new UsageError(`--${flag} só vale com --template ou --template-id.`);
113
+ }
114
+ if (!from)
115
+ throw new UsageError("Informe --template, ou --from com --subject e --html para o HTML direto.");
116
+ const html = await textSource(ctx, values, "html");
117
+ if (html === undefined)
118
+ throw new UsageError("--html ou --html-file é obrigatório no HTML direto.");
119
+ return {
120
+ from,
121
+ to: { address: to, name: toName },
122
+ subject: stringFlag(values, "subject", true),
123
+ html,
124
+ text: await textSource(ctx, values, "text"),
125
+ headers,
126
+ category,
127
+ };
128
+ }
129
+ async function textSource(ctx, values, name) {
130
+ const inline = stringFlag(values, name);
131
+ const file = stringFlag(values, `${name}-file`);
132
+ if (inline !== undefined && file !== undefined)
133
+ throw new UsageError(`Use --${name} ou --${name}-file, não os dois.`);
134
+ if (file !== undefined)
135
+ return readInput(ctx, file);
136
+ return inline;
137
+ }
138
+ async function readInput(ctx, file) {
139
+ if (file === "-")
140
+ return readAll(ctx.io.stdin);
141
+ try {
142
+ return await readFile(file, "utf8");
143
+ }
144
+ catch (error) {
145
+ throw new CliError(`Não consegui ler ${file}: ${error instanceof Error ? error.message : String(error)}`);
146
+ }
147
+ }
148
+ async function parseVariables(ctx, values) {
149
+ const inline = stringFlag(values, "vars");
150
+ const file = stringFlag(values, "vars-file");
151
+ if (inline !== undefined && file !== undefined)
152
+ throw new UsageError("Use --vars ou --vars-file, não os dois.");
153
+ let variables = {};
154
+ if (inline !== undefined)
155
+ variables = parseObject(inline, "--vars");
156
+ if (file !== undefined)
157
+ variables = parseObject(await readInput(ctx, file), file);
158
+ // --var vem depois: sobrescreve a mesma chave vinda do JSON.
159
+ for (const raw of listFlag(values, "var")) {
160
+ const [key, value] = parsePair(raw, "var");
161
+ variables[key] = value;
162
+ }
163
+ return Object.keys(variables).length > 0 ? variables : undefined;
164
+ }
165
+ function parseObject(text, source) {
166
+ let parsed;
167
+ try {
168
+ parsed = JSON.parse(text);
169
+ }
170
+ catch {
171
+ throw new UsageError(`${source} não é um JSON válido.`);
172
+ }
173
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
174
+ throw new UsageError(`${source} precisa ser um objeto JSON ({"nome": "Ana"}).`);
175
+ }
176
+ return parsed;
177
+ }
178
+ function parseHeaders(raw) {
179
+ if (raw.length === 0)
180
+ return undefined;
181
+ const headers = {};
182
+ for (const item of raw) {
183
+ const [name, value] = parsePair(item, "header", /:\s*|=/);
184
+ headers[name] = value.trim();
185
+ }
186
+ return headers;
187
+ }
package/dist/config.js ADDED
@@ -0,0 +1,93 @@
1
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { CliError } from "./errors.js";
4
+ export const DEFAULT_PROFILE = "default";
5
+ const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
6
+ /**
7
+ * Onde fica o arquivo de configuração:
8
+ * - Windows: `%APPDATA%\pinga\config.json`;
9
+ * - demais: `$XDG_CONFIG_HOME/pinga/config.json`, com `~/.config` como padrão.
10
+ *
11
+ * `PINGA_CONFIG_DIR` troca o diretório inteiro (testes, CI, mais de uma conta na mesma máquina).
12
+ */
13
+ export function configPath(io) {
14
+ // O sistema vem do `Io`, não do módulo `path` nativo: assim o cálculo é o mesmo em qualquer máquina.
15
+ const paths = io.platform === "win32" ? path.win32 : path.posix;
16
+ const override = io.env["PINGA_CONFIG_DIR"];
17
+ if (override)
18
+ return paths.join(override, "config.json");
19
+ if (io.platform === "win32") {
20
+ const appData = io.env["APPDATA"] || paths.join(io.homedir, "AppData", "Roaming");
21
+ return paths.join(appData, "pinga", "config.json");
22
+ }
23
+ const xdg = io.env["XDG_CONFIG_HOME"];
24
+ const base = xdg && paths.isAbsolute(xdg) ? xdg : paths.join(io.homedir, ".config");
25
+ return paths.join(base, "pinga", "config.json");
26
+ }
27
+ export function assertProfileName(name) {
28
+ if (!PROFILE_NAME.test(name)) {
29
+ throw new CliError(`Nome de perfil inválido: "${name}". Use letras, números, "-" e "_" (até 64 caracteres).`);
30
+ }
31
+ return name;
32
+ }
33
+ export async function readConfig(file) {
34
+ let text;
35
+ try {
36
+ text = await readFile(file, "utf8");
37
+ }
38
+ catch (error) {
39
+ if (isNotFound(error))
40
+ return { profiles: {} };
41
+ throw new CliError(`Não consegui ler ${file}: ${describe(error)}`);
42
+ }
43
+ let parsed;
44
+ try {
45
+ parsed = JSON.parse(text);
46
+ }
47
+ catch {
48
+ throw new CliError(`${file} não é um JSON válido. Corrija o arquivo ou apague-o e rode \`pinga login\` de novo.`);
49
+ }
50
+ if (!isRecord(parsed) || (parsed["profiles"] !== undefined && !isRecord(parsed["profiles"]))) {
51
+ throw new CliError(`${file} não tem o formato esperado ({ "profiles": { ... } }).`);
52
+ }
53
+ const profiles = {};
54
+ for (const [name, value] of Object.entries((parsed["profiles"] ?? {}))) {
55
+ if (!isRecord(value))
56
+ continue;
57
+ profiles[name] = {
58
+ api_key: typeof value["api_key"] === "string" ? value["api_key"] : undefined,
59
+ base_url: typeof value["base_url"] === "string" ? value["base_url"] : undefined,
60
+ };
61
+ }
62
+ return { profiles };
63
+ }
64
+ /**
65
+ * Grava com permissão `0600` (diretório `0700`): o arquivo guarda a API key em texto puro, como o
66
+ * `~/.aws/credentials` e o `~/.npmrc`. A escrita é atômica (arquivo temporário + rename), então um
67
+ * Ctrl+C no meio não deixa a configuração pela metade.
68
+ */
69
+ export async function writeConfig(file, config) {
70
+ const dir = path.dirname(file);
71
+ await mkdir(dir, { recursive: true, mode: 0o700 });
72
+ const temp = `${file}.${process.pid}.tmp`;
73
+ const body = `${JSON.stringify(config, null, 2)}\n`;
74
+ try {
75
+ await writeFile(temp, body, { mode: 0o600 });
76
+ // `mode` do writeFile passa pela umask; o chmod garante 0600 mesmo assim.
77
+ await chmod(temp, 0o600);
78
+ await rename(temp, file);
79
+ }
80
+ catch (error) {
81
+ await rm(temp, { force: true });
82
+ throw new CliError(`Não consegui gravar ${file}: ${describe(error)}`);
83
+ }
84
+ }
85
+ function isNotFound(error) {
86
+ return isRecord(error) && error["code"] === "ENOENT";
87
+ }
88
+ function describe(error) {
89
+ return error instanceof Error ? error.message : String(error);
90
+ }
91
+ function isRecord(value) {
92
+ return typeof value === "object" && value !== null && !Array.isArray(value);
93
+ }
@@ -0,0 +1,92 @@
1
+ import { DEFAULT_BASE_URL, Pinga } from "@pinga/sdk";
2
+ import { assertProfileName, configPath, DEFAULT_PROFILE, readConfig } from "./config.js";
3
+ import { CliError, redact } from "./errors.js";
4
+ import { VERSION } from "./version.js";
5
+ /** Estado de uma execução: perfil escolhido, formato de saída e acesso ao cliente da API. */
6
+ export class Context {
7
+ io;
8
+ json;
9
+ profile;
10
+ configFile;
11
+ #baseUrlFlag;
12
+ /** Chaves conhecidas nesta execução, para a redação de toda saída. */
13
+ #secrets = [];
14
+ #config;
15
+ constructor(io, flags) {
16
+ this.io = io;
17
+ this.json = flags.json;
18
+ this.profile = assertProfileName(flags.profile ?? io.env["PINGA_PROFILE"] ?? DEFAULT_PROFILE);
19
+ this.configFile = configPath(io);
20
+ this.#baseUrlFlag = flags.baseUrl;
21
+ const envKey = io.env["PINGA_API_KEY"];
22
+ if (envKey)
23
+ this.#secrets.push(envKey);
24
+ }
25
+ rememberSecret(secret) {
26
+ this.#secrets.push(secret);
27
+ }
28
+ async config() {
29
+ if (this.#config === undefined) {
30
+ this.#config = await readConfig(this.configFile);
31
+ for (const profile of Object.values(this.#config.profiles)) {
32
+ if (profile.api_key)
33
+ this.#secrets.push(profile.api_key);
34
+ }
35
+ }
36
+ return this.#config;
37
+ }
38
+ /** `--base-url` > `PINGA_BASE_URL` > `base_url` do perfil > produção. */
39
+ async baseUrl() {
40
+ if (this.#baseUrlFlag)
41
+ return this.#baseUrlFlag;
42
+ const fromEnv = this.io.env["PINGA_BASE_URL"];
43
+ if (fromEnv)
44
+ return fromEnv;
45
+ const config = await this.config();
46
+ return config.profiles[this.profile]?.base_url ?? DEFAULT_BASE_URL;
47
+ }
48
+ /** `PINGA_API_KEY` no ambiente tem precedência sobre o perfil do arquivo de configuração. */
49
+ async credentials() {
50
+ const baseUrl = await this.baseUrl();
51
+ const fromEnv = this.io.env["PINGA_API_KEY"];
52
+ if (fromEnv)
53
+ return { apiKey: fromEnv, baseUrl, source: "env" };
54
+ const config = await this.config();
55
+ const apiKey = config.profiles[this.profile]?.api_key;
56
+ if (apiKey)
57
+ return { apiKey, baseUrl, source: "profile" };
58
+ const hint = this.profile === DEFAULT_PROFILE ? "pinga login" : `pinga login --profile ${this.profile}`;
59
+ throw new CliError(`Nenhuma API key para o perfil "${this.profile}". Rode \`${hint}\` ou defina PINGA_API_KEY.`);
60
+ }
61
+ createClient(apiKey, baseUrl) {
62
+ this.rememberSecret(apiKey);
63
+ return new Pinga({
64
+ apiKey,
65
+ baseUrl,
66
+ fetch: this.io.fetch,
67
+ defaultHeaders: { "User-Agent": `pinga-cli/${VERSION}` },
68
+ });
69
+ }
70
+ async client() {
71
+ const { apiKey, baseUrl } = await this.credentials();
72
+ return this.createClient(apiKey, baseUrl);
73
+ }
74
+ /** Escreve uma linha no stdout, já redigida. */
75
+ out(text = "") {
76
+ this.io.stdout.write(`${redact(text, this.#secrets)}\n`);
77
+ }
78
+ /** Escreve uma linha no stderr, já redigida. Avisos e progresso, nunca o resultado. */
79
+ err(text = "") {
80
+ this.io.stderr.write(`${redact(text, this.#secrets)}\n`);
81
+ }
82
+ /** Resultado em `--json`: um documento JSON no stdout. */
83
+ outJson(value) {
84
+ this.out(JSON.stringify(value, null, 2));
85
+ }
86
+ errJson(value) {
87
+ this.err(JSON.stringify(value, null, 2));
88
+ }
89
+ redact(text) {
90
+ return redact(text, this.#secrets);
91
+ }
92
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,33 @@
1
+ /** Erro de uso: flag desconhecida, argumento faltando, combinação inválida. Sai com código 2. */
2
+ export class UsageError extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "UsageError";
6
+ }
7
+ }
8
+ /** Erro do próprio CLI, sem resposta da API (configuração, arquivo, entrada). Sai com código 1. */
9
+ export class CliError extends Error {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = "CliError";
13
+ }
14
+ }
15
+ export const ExitCode = {
16
+ Ok: 0,
17
+ Failure: 1,
18
+ Usage: 2,
19
+ };
20
+ const API_KEY_PATTERN = /pg_(live|test)_[A-Za-z0-9]+/g;
21
+ /**
22
+ * Segunda barreira contra vazar a API key: todo texto que sai do CLI passa por aqui. A primeira é
23
+ * nunca pôr a chave numa mensagem; esta pega o que escapar (ex.: um erro de terceiro que ecoe a URL
24
+ * ou o header).
25
+ */
26
+ export function redact(text, secrets = []) {
27
+ let result = text.replace(API_KEY_PATTERN, "pg_$1_[redacted]");
28
+ for (const secret of secrets) {
29
+ if (secret.length >= 8)
30
+ result = result.split(secret).join("[redacted]");
31
+ }
32
+ return result;
33
+ }
package/dist/format.js ADDED
@@ -0,0 +1,14 @@
1
+ /** Tabela em colunas alinhadas, sem bordas — fácil de ler e de passar por `grep`/`awk`. */
2
+ export function table(headers, rawRows) {
3
+ const rows = rawRows.map((row) => row.map(clean));
4
+ const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length)));
5
+ const render = (cells) => cells
6
+ .map((cell, index) => (index === cells.length - 1 ? cell : cell.padEnd(widths[index] ?? 0)))
7
+ .join(" ")
8
+ .trimEnd();
9
+ return [render(headers), ...rows.map(render)].join("\n");
10
+ }
11
+ /** Quebras de linha e tabs numa célula desalinhariam a tabela. */
12
+ function clean(value) {
13
+ return value.replace(/[\r\n\t]+/g, " ");
14
+ }
package/dist/io.js ADDED
@@ -0,0 +1,3 @@
1
+ // Tudo o que o CLI toca no mundo de fora passa por aqui: processo, terminal, ambiente e rede.
2
+ // Os testes trocam cada peça por uma falsa e rodam o CLI inteiro em memória.
3
+ export {};
package/dist/main.js ADDED
@@ -0,0 +1,174 @@
1
+ import { parseArgs } from "node:util";
2
+ import { login, logout } from "./commands/auth.js";
3
+ import { deliveriesGet, deliveriesList } from "./commands/deliveries.js";
4
+ import { emailsSend } from "./commands/emails.js";
5
+ import { Context } from "./context.js";
6
+ import { ExitCode, redact, UsageError } from "./errors.js";
7
+ import { renderError } from "./render-error.js";
8
+ import { VERSION } from "./version.js";
9
+ export const COMMANDS = [login, logout, emailsSend, deliveriesList, deliveriesGet];
10
+ const GLOBAL_OPTIONS = {
11
+ profile: { type: "string", short: "p" },
12
+ "base-url": { type: "string" },
13
+ json: { type: "boolean" },
14
+ help: { type: "boolean", short: "h" },
15
+ version: { type: "boolean", short: "v" },
16
+ };
17
+ const GLOBAL_HELP = `Opções globais:
18
+ -p, --profile <nome> perfil do arquivo de configuração (padrão: PINGA_PROFILE ou "default")
19
+ --base-url <url> URL da API (padrão: PINGA_BASE_URL, o do perfil ou https://api.pinga.api.br)
20
+ --json saída em JSON no stdout; em erro, o JSON do erro vai para o stderr
21
+ -h, --help mostra a ajuda`;
22
+ const ENVIRONMENT_HELP = `Ambiente:
23
+ PINGA_API_KEY API key; tem precedência sobre o arquivo de configuração
24
+ PINGA_PROFILE perfil padrão
25
+ PINGA_BASE_URL URL da API
26
+ PINGA_CONFIG_DIR diretório do config.json (padrão: ~/.config/pinga; %APPDATA%\\pinga no Windows)`;
27
+ /**
28
+ * Executa o CLI e devolve o código de saída: `0` sucesso, `1` falha (API, rede, configuração),
29
+ * `2` erro de uso.
30
+ */
31
+ export async function main(argv, io) {
32
+ const { words, command, rest } = splitCommand(argv);
33
+ const wantsJson = argv.includes("--json");
34
+ let ctx;
35
+ try {
36
+ if (!command) {
37
+ if (words.length === 0) {
38
+ const flags = parseFlags(GLOBAL_OPTIONS, rest);
39
+ if (flags.values["version"]) {
40
+ io.stdout.write(`pinga ${VERSION}\n`);
41
+ return ExitCode.Ok;
42
+ }
43
+ io.stdout.write(`${rootHelp()}\n`);
44
+ return flags.values["help"] ? ExitCode.Ok : ExitCode.Usage;
45
+ }
46
+ if (words[0] === "help") {
47
+ const target = findCommand(words.slice(1));
48
+ io.stdout.write(`${target ? commandHelp(target) : groupHelp(words[1])}\n`);
49
+ return ExitCode.Ok;
50
+ }
51
+ const group = words[0];
52
+ if (words.length === 1 && COMMANDS.some((candidate) => candidate.name[0] === group)) {
53
+ io.stdout.write(`${groupHelp(group)}\n`);
54
+ return rest.includes("--help") || rest.includes("-h") ? ExitCode.Ok : ExitCode.Usage;
55
+ }
56
+ throw new UsageError(`Comando desconhecido: ${words.join(" ")}. Rode \`pinga --help\`.`);
57
+ }
58
+ const parsed = parseFlags({ ...GLOBAL_OPTIONS, ...command.options }, rest);
59
+ if (parsed.values["help"]) {
60
+ io.stdout.write(`${commandHelp(command)}\n`);
61
+ return ExitCode.Ok;
62
+ }
63
+ const { min, max, names } = command.positionals;
64
+ if (parsed.positionals.length < min || parsed.positionals.length > max) {
65
+ const expected = max === 0 ? "nenhum argumento" : `${names ?? "argumentos"}`;
66
+ throw new UsageError(`\`pinga ${command.name.join(" ")}\` espera ${expected}. Rode com --help.`);
67
+ }
68
+ ctx = new Context(io, {
69
+ profile: stringValue(parsed.values["profile"]),
70
+ baseUrl: stringValue(parsed.values["base-url"]),
71
+ json: parsed.values["json"] === true,
72
+ });
73
+ await command.run(ctx, parsed.values, parsed.positionals);
74
+ return ExitCode.Ok;
75
+ }
76
+ catch (error) {
77
+ const rendered = renderError(error);
78
+ const scrub = (text) => (ctx ? ctx.redact(text) : redact(text, [io.env["PINGA_API_KEY"] ?? ""]));
79
+ if (wantsJson) {
80
+ io.stderr.write(`${scrub(JSON.stringify(rendered.json, null, 2))}\n`);
81
+ }
82
+ else {
83
+ io.stderr.write(`${scrub(rendered.lines.join("\n"))}\n`);
84
+ }
85
+ return rendered.exitCode;
86
+ }
87
+ }
88
+ /**
89
+ * Acha o comando no começo da linha. As opções globais podem vir antes dele
90
+ * (`pinga --profile prod deliveries list`), por isso elas e o valor delas são pulados. Tudo depois do
91
+ * nome do comando fica para o `parseArgs`, já com as opções daquele comando: só ele sabe se `--html`
92
+ * leva valor (em `emails send` leva; em `deliveries get`, não).
93
+ */
94
+ function splitCommand(argv) {
95
+ const words = [];
96
+ const leading = [];
97
+ let index = 0;
98
+ while (index < argv.length && !findCommand(words)) {
99
+ const token = argv[index];
100
+ if (token.startsWith("-") && token !== "-") {
101
+ const option = globalOption(token);
102
+ if (!option)
103
+ break;
104
+ leading.push(token);
105
+ if (option.type === "string" && !token.includes("=") && index + 1 < argv.length) {
106
+ leading.push(argv[index + 1]);
107
+ index += 1;
108
+ }
109
+ }
110
+ else {
111
+ words.push(token);
112
+ }
113
+ index += 1;
114
+ }
115
+ return { words, command: findCommand(words), rest: [...leading, ...argv.slice(index)] };
116
+ }
117
+ function globalOption(token) {
118
+ const options = GLOBAL_OPTIONS;
119
+ if (token.startsWith("--"))
120
+ return options[token.slice(2).split("=")[0]];
121
+ return Object.values(options).find((option) => option.short === token.slice(1));
122
+ }
123
+ function findCommand(words) {
124
+ return COMMANDS.find((command) => command.name.length === words.length && command.name.every((part, index) => words[index] === part));
125
+ }
126
+ function parseFlags(options, args) {
127
+ try {
128
+ const { values, positionals } = parseArgs({ args, options, allowPositionals: true, strict: true });
129
+ return { values: values, positionals };
130
+ }
131
+ catch (error) {
132
+ // Mensagens do parseArgs vêm em inglês; reescreve as comuns.
133
+ const message = error instanceof Error ? error.message : String(error);
134
+ const unknown = /Unknown option '([^']+)'/.exec(message);
135
+ if (unknown)
136
+ throw new UsageError(`Opção desconhecida: ${unknown[1]}. Rode com --help.`);
137
+ const missing = /Option '([^']+?)(?: <value>)?' argument missing/.exec(message);
138
+ if (missing)
139
+ throw new UsageError(`${missing[1]?.replace(/^-\w, /, "")} precisa de um valor.`);
140
+ throw new UsageError(message);
141
+ }
142
+ }
143
+ function stringValue(value) {
144
+ return typeof value === "string" && value.length > 0 ? value : undefined;
145
+ }
146
+ function rootHelp() {
147
+ const width = Math.max(...COMMANDS.map((command) => command.name.join(" ").length));
148
+ const lines = COMMANDS.map((command) => ` ${command.name.join(" ").padEnd(width)} ${command.summary}`);
149
+ return `pinga ${VERSION} — CLI da Pinga (https://docs.pinga.api.br/cli)
150
+
151
+ Uso: pinga <comando> [opções]
152
+
153
+ Comandos:
154
+ ${lines.join("\n")}
155
+
156
+ ${GLOBAL_HELP}
157
+
158
+ ${ENVIRONMENT_HELP}
159
+
160
+ Rode \`pinga <comando> --help\` para as opções de cada comando.`;
161
+ }
162
+ function groupHelp(group) {
163
+ const commands = COMMANDS.filter((command) => command.name[0] === group);
164
+ if (commands.length === 0)
165
+ return rootHelp();
166
+ const width = Math.max(...commands.map((command) => command.name.join(" ").length));
167
+ return `Uso: pinga ${group} <subcomando> [opções]
168
+
169
+ Subcomandos:
170
+ ${commands.map((command) => ` ${command.name.join(" ").padEnd(width)} ${command.summary}`).join("\n")}`;
171
+ }
172
+ function commandHelp(command) {
173
+ return `${command.help}\n\n${GLOBAL_HELP}`;
174
+ }
package/dist/prompt.js ADDED
@@ -0,0 +1,76 @@
1
+ import { CliError } from "./errors.js";
2
+ const CTRL_C = "\u0003";
3
+ const CTRL_D = "\u0004";
4
+ const BACKSPACE = "\u007f";
5
+ const BACKSPACE_ALT = "\b";
6
+ /**
7
+ * Lê um segredo.
8
+ *
9
+ * - Terminal: modo raw, sem eco. O prompt vai para o stderr, para não sujar o stdout de quem redireciona.
10
+ * - Sem terminal (pipe, CI): lê a primeira linha da entrada padrão, ex.:
11
+ * `printf '%s' "$PINGA_KEY" | pinga login`.
12
+ */
13
+ export async function readSecret(stdin, stderr, prompt) {
14
+ if (stdin.isTTY && typeof stdin.setRawMode === "function") {
15
+ return readFromTerminal(stdin, stderr, prompt);
16
+ }
17
+ return readFirstLine(stdin);
18
+ }
19
+ function readFromTerminal(stdin, stderr, prompt) {
20
+ stderr.write(prompt);
21
+ stdin.setEncoding?.("utf8");
22
+ stdin.setRawMode?.(true);
23
+ stdin.resume?.();
24
+ return new Promise((resolve, reject) => {
25
+ let value = "";
26
+ const finish = (error) => {
27
+ stdin.removeListener("data", onData);
28
+ stdin.setRawMode?.(false);
29
+ stdin.pause?.();
30
+ stderr.write("\n");
31
+ if (error)
32
+ reject(error);
33
+ else
34
+ resolve(value);
35
+ };
36
+ const onData = (chunk) => {
37
+ const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
38
+ for (const char of text) {
39
+ if (char === "\r" || char === "\n" || char === CTRL_D) {
40
+ finish();
41
+ return;
42
+ }
43
+ if (char === CTRL_C) {
44
+ finish(new CliError("Cancelado."));
45
+ return;
46
+ }
47
+ if (char === BACKSPACE || char === BACKSPACE_ALT) {
48
+ value = value.slice(0, -1);
49
+ continue;
50
+ }
51
+ // Ignora sequências de controle (setas etc.): numa chave só entram caracteres imprimíveis.
52
+ if (char >= " ")
53
+ value += char;
54
+ }
55
+ };
56
+ stdin.on("data", onData);
57
+ });
58
+ }
59
+ async function readFirstLine(stdin) {
60
+ let buffer = "";
61
+ for await (const chunk of stdin) {
62
+ buffer += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
63
+ const newline = buffer.search(/\r?\n/);
64
+ if (newline >= 0)
65
+ return buffer.slice(0, newline);
66
+ }
67
+ return buffer;
68
+ }
69
+ /** Lê a entrada padrão inteira (`--html-file -`). */
70
+ export async function readAll(stdin) {
71
+ let buffer = "";
72
+ for await (const chunk of stdin) {
73
+ buffer += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
74
+ }
75
+ return buffer;
76
+ }
@@ -0,0 +1,74 @@
1
+ import { PingaError } from "@pinga/sdk";
2
+ import { CliError, ExitCode, UsageError } from "./errors.js";
3
+ /**
4
+ * Traduz qualquer falha para a saída do CLI. Erro da API mostra `title`, `detail` e `trace_id` do
5
+ * Problem Details, mais as listas de validação, que é o que o usuário precisa para corrigir o pedido
6
+ * ou abrir chamado.
7
+ */
8
+ export function renderError(error) {
9
+ if (error instanceof UsageError) {
10
+ return {
11
+ exitCode: ExitCode.Usage,
12
+ lines: [`Erro: ${error.message}`],
13
+ json: { error: { type: "usage_error", message: error.message } },
14
+ };
15
+ }
16
+ if (error instanceof PingaError) {
17
+ return renderApiError(error);
18
+ }
19
+ if (error instanceof CliError) {
20
+ return {
21
+ exitCode: ExitCode.Failure,
22
+ lines: [`Erro: ${error.message}`],
23
+ json: { error: { type: "cli_error", message: error.message } },
24
+ };
25
+ }
26
+ const message = error instanceof Error ? error.message : String(error);
27
+ return {
28
+ exitCode: ExitCode.Failure,
29
+ lines: [`Erro inesperado: ${message}`],
30
+ json: { error: { type: "unexpected_error", message } },
31
+ };
32
+ }
33
+ function renderApiError(error) {
34
+ const lines = [];
35
+ const title = error.title ?? error.type;
36
+ lines.push(error.status > 0 ? `Erro: ${title} (HTTP ${error.status})` : `Erro: ${title}`);
37
+ if (error.detail)
38
+ lines.push(` ${error.detail}`);
39
+ const errors = error.errors;
40
+ if (Array.isArray(errors)) {
41
+ for (const item of errors) {
42
+ const where = item.line != null ? ` (linha ${item.line}${item.column != null ? `, coluna ${item.column}` : ""})` : "";
43
+ lines.push(` - ${item.stage ? `${item.stage}: ` : ""}${item.message ?? ""}${where}`);
44
+ }
45
+ }
46
+ else if (errors && typeof errors === "object") {
47
+ for (const [field, messages] of Object.entries(errors)) {
48
+ for (const message of messages)
49
+ lines.push(` - ${field}: ${message}`);
50
+ }
51
+ }
52
+ for (const item of error.variableErrors ?? []) {
53
+ const name = item.name ?? item.field ?? "?";
54
+ lines.push(` - variável ${name}: ${item.message ?? item.reason ?? item.code ?? "inválida"}`);
55
+ }
56
+ if (error.traceId)
57
+ lines.push(` trace_id: ${error.traceId}`);
58
+ return {
59
+ exitCode: ExitCode.Failure,
60
+ lines,
61
+ json: {
62
+ error: {
63
+ type: error.type,
64
+ status: error.status,
65
+ title: error.title ?? null,
66
+ detail: error.detail ?? null,
67
+ trace_id: error.traceId ?? null,
68
+ code: error.code ?? null,
69
+ errors: error.errors ?? null,
70
+ variable_errors: error.variableErrors ?? null,
71
+ },
72
+ },
73
+ };
74
+ }
@@ -0,0 +1,2 @@
1
+ // Mantido em sincronia com package.json por test/version.test.ts.
2
+ export const VERSION = "0.1.0";
package/package.json CHANGED
@@ -1 +1,41 @@
1
- {"name":"pinga-cli","version":"0.0.0","description":"CLI oficial do Pinga — API de email transacional (pinga.api.br)","homepage":"https://pinga.api.br","repository":{"type":"git","url":"git+https://github.com/pinga-api/pinga-cli.git"},"license":"MIT","author":"Pinga <dev@pinga.api.br>","files":["README.md"]}
1
+ {
2
+ "name": "pinga-cli",
3
+ "version": "0.1.0",
4
+ "description": "CLI oficial do Pinga — API de email transacional (pinga.api.br)",
5
+ "license": "MIT",
6
+ "author": "Pinga <dev@pinga.api.br>",
7
+ "homepage": "https://docs.pinga.api.br/cli",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/pinga-api/pinga-cli.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/pinga-api/pinga-cli/issues"
14
+ },
15
+ "keywords": ["pinga", "email", "transactional-email", "cli"],
16
+ "type": "module",
17
+ "bin": {
18
+ "pinga": "dist/cli.js"
19
+ },
20
+ "files": ["dist", "README.md", "LICENSE"],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "scripts": {
25
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && chmod +x dist/cli.js",
26
+ "typecheck": "tsc -p tsconfig.json --noEmit",
27
+ "test": "vitest run",
28
+ "test:watch": "vitest",
29
+ "smoke": "vitest run --config vitest.smoke.config.ts",
30
+ "dev": "bun src/cli.ts",
31
+ "prepublishOnly": "bun run build"
32
+ },
33
+ "dependencies": {
34
+ "@pinga/sdk": "^0.1.0"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "^22.10.0",
38
+ "typescript": "^5.7.0",
39
+ "vitest": "^3.0.0"
40
+ }
41
+ }