pinga-cli 0.1.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/README.md CHANGED
@@ -7,15 +7,36 @@ sobre o [`@pinga/sdk`](https://github.com/pinga-api/pinga-node).
7
7
 
8
8
  ## Instalação
9
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
+
10
18
  ```bash
11
19
  npm install -g pinga-cli
12
- # ou
13
- bun add -g pinga-cli
20
+ # ou, sem instalar:
21
+ npx pinga-cli --help
14
22
  ```
15
23
 
16
- Exige Node 20 ou mais novo. Para rodar uma vez, sem instalar: `npx pinga-cli --help`.
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`:
17
28
 
18
- Binários compilados e tap do Homebrew entram numa versão seguinte.
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`.
19
40
 
20
41
  ## Login
21
42
 
@@ -81,6 +102,80 @@ pinga deliveries get 0193a1b2-... --html > email.html
81
102
  A listagem mostra 20 por página (`--limit` até 100). Para a página seguinte, passe o `--cursor`
82
103
  que o comando imprime; `--all` percorre todas.
83
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
+
84
179
  ## Saída, erros e códigos de saída
85
180
 
86
181
  - `--json` em qualquer comando: o resultado vai como JSON para o stdout. Avisos e dicas vão sempre
@@ -90,7 +185,8 @@ que o comando imprime; `--all` percorre todas.
90
185
  `{ "error": { "type", "status", "title", "detail", "trace_id", "errors", "variable_errors" } }`.
91
186
  - Códigos de saída: `0` sucesso, `1` falha (API, rede, configuração), `2` erro de uso (flag
92
187
  desconhecida, argumento faltando).
93
- - A API key nunca aparece na saída do CLI, nem em `--json`, nem em mensagem de erro.
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.
94
190
 
95
191
  ## Ambiente
96
192
 
@@ -100,6 +196,7 @@ que o comando imprime; `--all` percorre todas.
100
196
  | `PINGA_PROFILE` | perfil padrão (padrão: `default`) |
101
197
  | `PINGA_BASE_URL` | URL da API (padrão: `https://api.pinga.api.br`) |
102
198
  | `PINGA_CONFIG_DIR` | diretório do `config.json` |
199
+ | `PINGA_WEBHOOK_SECRET` | segredo para `pinga webhooks verify` |
103
200
 
104
201
  ## Desenvolvimento
105
202
 
@@ -112,8 +209,24 @@ bun run dev -- --help
112
209
 
113
210
  # Smoke: o binário construído contra a stack de E2E local do monorepo
114
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
115
215
  ```
116
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
+
117
230
  Argumentos são lidos com `parseArgs` de `node:util`, sem framework de CLI. A única dependência de
118
231
  runtime é o `@pinga/sdk`.
119
232
 
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
+ }
@@ -1,5 +1,5 @@
1
1
  import { booleanFlag, integerFlag, stringFlag } from "../command.js";
2
- import { table } from "../format.js";
2
+ import { escapeSlug, table } from "../format.js";
3
3
  export const deliveriesList = {
4
4
  name: ["deliveries", "list"],
5
5
  summary: "Lista entregas, das mais recentes para as mais antigas",
@@ -114,10 +114,10 @@ function describeDelivery(delivery) {
114
114
  [
115
115
  "Template",
116
116
  delivery.template
117
- ? `${delivery.template.slug}${delivery.template.version != null ? ` (v${delivery.template.version})` : ""}`
117
+ ? `${escapeSlug(delivery.template.slug)}${delivery.template.version != null ? ` (v${delivery.template.version})` : ""}`
118
118
  : null,
119
119
  ],
120
- ["Tipo de notificação", delivery.notification_type?.slug],
120
+ ["Tipo de notificação", delivery.notification_type ? escapeSlug(delivery.notification_type.slug) : null],
121
121
  ["Provedor", delivery.provider],
122
122
  ["Falha", delivery.failure_reason],
123
123
  ["Reenvio de", delivery.resend_of_delivery_id],
@@ -0,0 +1,99 @@
1
+ import { apiRequest, pathSegment } from "../api.js";
2
+ import { booleanFlag } from "../command.js";
3
+ import { CliError, ReportedFailure } from "../errors.js";
4
+ import { table } from "../format.js";
5
+ const VERIFIED = "verified";
6
+ export const domainsCheck = {
7
+ name: ["domains", "check"],
8
+ summary: "Estado da verificação (DKIM, SPF, DMARC) dos domínios remetentes",
9
+ help: `Uso: pinga domains check [domínio...] [--refresh]
10
+
11
+ Mostra o estado de cada domínio remetente: verificação de DKIM, SPF, DMARC e MX. Para domínio
12
+ ainda não verificado, lista os registros DNS que faltam configurar. Sem domínio, mostra todos.
13
+
14
+ Sai com código 1 se algum domínio mostrado não estiver verificado — serve de checagem no CI.
15
+
16
+ Opções:
17
+ --refresh antes de mostrar, pede à Pinga para reconsultar o DKIM no provedor e o DNS
18
+ (SPF, DMARC, MX). Exige chave com escopo total`,
19
+ options: {
20
+ refresh: { type: "boolean" },
21
+ },
22
+ positionals: { min: 0, max: Number.POSITIVE_INFINITY, names: "[domínio...]" },
23
+ async run(ctx, values, names) {
24
+ const all = await listDomains(ctx);
25
+ const wanted = names.map((name) => name.toLowerCase().replace(/\.$/, ""));
26
+ const missing = wanted.filter((name) => !all.some((domain) => domain.domain.toLowerCase() === name));
27
+ if (missing.length > 0) {
28
+ throw new CliError(`Domínio não encontrado nesta organização: ${missing.join(", ")}. Rode \`pinga domains check\` para ver todos.`);
29
+ }
30
+ const selected = wanted.length > 0 ? all.filter((domain) => wanted.includes(domain.domain.toLowerCase())) : all;
31
+ const refresh = booleanFlag(values, "refresh");
32
+ const domains = [];
33
+ for (const item of selected) {
34
+ if (refresh) {
35
+ await apiRequest(ctx, { method: "POST", path: `/v1/sender-domains/${pathSegment(item.id)}/verify`, idempotent: true });
36
+ domains.push(await apiRequest(ctx, { method: "POST", path: `/v1/sender-domains/${pathSegment(item.id)}/check-dns`, idempotent: true }));
37
+ }
38
+ else {
39
+ domains.push(await apiRequest(ctx, { method: "GET", path: `/v1/sender-domains/${pathSegment(item.id)}` }));
40
+ }
41
+ }
42
+ const allVerified = domains.every((domain) => domain.status === VERIFIED);
43
+ if (ctx.json) {
44
+ ctx.outJson({ all_verified: allVerified, domains });
45
+ }
46
+ else if (domains.length === 0) {
47
+ ctx.err("Nenhum domínio remetente cadastrado. Cadastre um no painel, em Configurações → Domínios.");
48
+ }
49
+ else {
50
+ ctx.out(domains.map(describe).join("\n\n"));
51
+ }
52
+ if (!allVerified)
53
+ throw new ReportedFailure();
54
+ },
55
+ };
56
+ async function listDomains(ctx) {
57
+ const items = [];
58
+ let cursor;
59
+ for (;;) {
60
+ // O contrato declara `Cursor`/`Limit` em PascalCase; o binding do ASP.NET não diferencia caixa.
61
+ const page = await apiRequest(ctx, {
62
+ method: "GET",
63
+ path: "/v1/sender-domains",
64
+ query: { limit: 100, cursor },
65
+ });
66
+ items.push(...page.data);
67
+ if (!page.has_more || !page.next_cursor)
68
+ return items;
69
+ cursor = page.next_cursor;
70
+ }
71
+ }
72
+ function describe(domain) {
73
+ const lines = [`${domain.domain} ${domain.status}${domain.nickname ? ` (${domain.nickname})` : ""}${domain.managed ? " [gerenciado pela Pinga]" : ""}`];
74
+ lines.push(` DKIM ${domain.dkim.status} (${domain.dkim.tokens_count} chave(s))`);
75
+ for (const [label, check] of [["SPF", domain.spf], ["DMARC", domain.dmarc], ["MX", domain.mx]]) {
76
+ if (check)
77
+ lines.push(` ${label.padEnd(5)} ${check.status}${check.record ? ` ${check.record}` : ""}`);
78
+ }
79
+ if (domain.verified_at)
80
+ lines.push(` Verificado em ${domain.verified_at}`);
81
+ if (domain.last_checked_at)
82
+ lines.push(` Última checagem ${domain.last_checked_at}`);
83
+ if (domain.last_check_error)
84
+ lines.push(` Erro na última checagem: ${domain.last_check_error}`);
85
+ // Domínio pendente: todos os registros. Verificado: só o SPF/DMARC recomendado que a última checagem
86
+ // de DNS achou ausente ou em conflito (o DKIM já está resolvido).
87
+ const records = domain.status !== VERIFIED
88
+ ? domain.dns_records
89
+ : domain.dns_records.filter((record) => {
90
+ const check = record.purpose === "spf_recommended" ? domain.spf : record.purpose === "dmarc_recommended" ? domain.dmarc : undefined;
91
+ return check != null && check.status !== "ok" && check.status !== "unknown";
92
+ });
93
+ if (records.length > 0) {
94
+ lines.push("", domain.status !== VERIFIED ? " Registros DNS a configurar:" : " Registros DNS recomendados:");
95
+ const rendered = table(["TIPO", "NOME", "VALOR", "PARA"], records.map((record) => [record.type, record.name, record.value, record.purpose ?? "dkim"]));
96
+ lines.push(...rendered.split("\n").map((line) => ` ${line}`));
97
+ }
98
+ return lines.join("\n");
99
+ }
@@ -0,0 +1,252 @@
1
+ import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { PingaError } from "@pinga/sdk";
4
+ import { booleanFlag, stringFlag } from "../command.js";
5
+ import { CliError, ReportedFailure } from "../errors.js";
6
+ import { escapeSlug, quoteSlug } from "../format.js";
7
+ import { renderError } from "../render-error.js";
8
+ import { diff, importParams, kindOf, parseTemplateFile, serialize, TEMPLATE_FILE, toFile, updateParams, } from "../template-file.js";
9
+ const DEFAULT_DIR = "templates";
10
+ const SAFE_SLUG = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
11
+ export const templatesPull = {
12
+ name: ["templates", "pull"],
13
+ summary: "Baixa templates como arquivos (um diretório por slug)",
14
+ help: `Uso: pinga templates pull [slug...] [--dir <diretório>] [--include-archived]
15
+
16
+ Grava a versão ativa de cada template em <diretório>/<slug>/template.json, no envelope
17
+ pinga.template.v1 do export (sem o exported_at, para o git só mostrar mudança de verdade).
18
+ Sem slug, baixa todos os templates não arquivados.
19
+
20
+ Opções:
21
+ --dir <diretório> destino (padrão: ${DEFAULT_DIR})
22
+ --include-archived inclui os arquivados (só sem slug)`,
23
+ options: {
24
+ dir: { type: "string" },
25
+ "include-archived": { type: "boolean" },
26
+ },
27
+ positionals: { min: 0, max: Number.POSITIVE_INFINITY, names: "[slug...]" },
28
+ async run(ctx, values, slugs) {
29
+ const dir = stringFlag(values, "dir") ?? DEFAULT_DIR;
30
+ const pinga = await ctx.client();
31
+ const targets = [];
32
+ if (slugs.length > 0) {
33
+ for (const slug of slugs) {
34
+ const template = await pinga.templates.getBySlug(slug);
35
+ targets.push({ id: template.id, slug: template.slug });
36
+ }
37
+ }
38
+ else {
39
+ const includeArchived = booleanFlag(values, "include-archived");
40
+ for await (const item of pinga.templates.list({ limit: 100, include_archived: includeArchived || undefined })) {
41
+ targets.push({ id: item.id, slug: item.slug });
42
+ }
43
+ }
44
+ // Valida todos os slugs antes da primeira escrita: um slug inválido no meio não deixa o
45
+ // diretório com metade dos templates gravada.
46
+ const invalid = targets.filter((target) => !SAFE_SLUG.test(target.slug)).map((target) => target.slug);
47
+ if (invalid.length > 0) {
48
+ throw new CliError(`Slug ${invalid.map((slug) => quoteSlug(slug)).join(", ")} não serve como nome de diretório; nada foi gravado. Baixe com outro nome à mão.`);
49
+ }
50
+ const results = [];
51
+ for (const target of targets) {
52
+ const file = toFile(await pinga.templates.export(target.id));
53
+ const filePath = path.join(dir, target.slug, TEMPLATE_FILE);
54
+ const text = serialize(file);
55
+ const current = await readFile(filePath, "utf8").catch(() => undefined);
56
+ const status = current === text ? "unchanged" : "written";
57
+ if (status === "written") {
58
+ await mkdir(path.dirname(filePath), { recursive: true });
59
+ await writeFile(filePath, text);
60
+ }
61
+ results.push({ slug: target.slug, version: file.version_data.version ?? null, path: filePath, status });
62
+ }
63
+ if (ctx.json) {
64
+ ctx.outJson({ dir, templates: results });
65
+ return;
66
+ }
67
+ if (results.length === 0) {
68
+ ctx.err("Nenhum template encontrado.");
69
+ return;
70
+ }
71
+ for (const result of results) {
72
+ const version = result.version != null ? ` v${result.version}` : "";
73
+ ctx.out(`${result.status === "written" ? "↓" : "="} ${escapeSlug(result.slug)}${version} ${result.path}${result.status === "unchanged" ? " (sem mudanças)" : ""}`);
74
+ }
75
+ },
76
+ };
77
+ export const templatesPush = {
78
+ name: ["templates", "push"],
79
+ summary: "Publica templates a partir dos arquivos",
80
+ help: `Uso: pinga templates push [caminho...] [--dir <diretório>] [--dry-run] [--message <texto>]
81
+
82
+ Para cada template.json:
83
+ - slug que não existe na Pinga: importa (vira a versão 1);
84
+ - slug que existe: compara com a versão ativa. Igual, não faz nada. Diferente, grava o
85
+ rascunho e publica a próxima versão. Se só mudaram nome, descrição ou remetente, atualiza
86
+ o template sem criar versão.
87
+
88
+ Num template visual (com "document"), só o document e as variáveis contam: subject, mjml e
89
+ text_body são derivados dele e são ignorados no push.
90
+
91
+ Caminho pode ser um template.json, o diretório de um slug ou um diretório com vários slugs.
92
+ Sem caminho, usa --dir.
93
+
94
+ Opções:
95
+ --dir <diretório> origem (padrão: ${DEFAULT_DIR})
96
+ --dry-run mostra o que mudaria, sem escrever nada
97
+ --message <texto> resumo da mudança gravado na versão publicada`,
98
+ options: {
99
+ dir: { type: "string" },
100
+ "dry-run": { type: "boolean" },
101
+ message: { type: "string" },
102
+ },
103
+ positionals: { min: 0, max: Number.POSITIVE_INFINITY, names: "[caminho...]" },
104
+ async run(ctx, values, paths) {
105
+ const roots = paths.length > 0 ? paths : [stringFlag(values, "dir") ?? DEFAULT_DIR];
106
+ const files = await findTemplateFiles(roots);
107
+ if (files.length === 0)
108
+ throw new CliError(`Nenhum ${TEMPLATE_FILE} encontrado em ${roots.join(", ")}.`);
109
+ const dryRun = booleanFlag(values, "dry-run");
110
+ const message = stringFlag(values, "message") ?? "pinga templates push";
111
+ const pinga = await ctx.client();
112
+ // Valida todos os arquivos antes de escrever qualquer coisa: um JSON quebrado no meio não deixa
113
+ // metade dos templates publicada.
114
+ const locals = [];
115
+ const seen = new Map();
116
+ for (const file of files) {
117
+ const local = parseTemplateFile(await readFile(file, "utf8"), file);
118
+ const other = seen.get(local.template.slug);
119
+ if (other)
120
+ throw new CliError(`Slug ${quoteSlug(local.template.slug)} aparece em ${other} e em ${file}.`);
121
+ seen.set(local.template.slug, file);
122
+ locals.push({ file, local });
123
+ }
124
+ const results = [];
125
+ for (const { file, local } of locals) {
126
+ try {
127
+ results.push(await pushOne(pinga, file, local, { dryRun, message }));
128
+ }
129
+ catch (error) {
130
+ const rendered = renderError(error);
131
+ results.push({
132
+ slug: local.template.slug,
133
+ path: file,
134
+ action: "failed",
135
+ version: null,
136
+ changes: null,
137
+ warnings: [],
138
+ error: rendered.json.error,
139
+ });
140
+ if (!ctx.json)
141
+ ctx.err(`✗ ${escapeSlug(local.template.slug)} (${file})\n${rendered.lines.map((line) => ` ${line}`).join("\n")}`);
142
+ }
143
+ }
144
+ report(ctx, results, dryRun);
145
+ if (results.some((result) => result.action === "failed"))
146
+ throw new ReportedFailure();
147
+ },
148
+ };
149
+ async function pushOne(pinga, file, local, options) {
150
+ const slug = local.template.slug;
151
+ const base = { slug, path: file, warnings: [] };
152
+ const dirName = path.basename(path.dirname(file));
153
+ if (path.basename(file) === TEMPLATE_FILE && dirName !== slug && dirName !== ".") {
154
+ base.warnings.push(`o diretório ${quoteSlug(dirName)} não tem o nome do slug ${quoteSlug(slug)}; vale o slug do arquivo.`);
155
+ }
156
+ const existing = await findBySlug(pinga, slug);
157
+ if (!existing) {
158
+ if (options.dryRun)
159
+ return { ...base, action: "created", version: 1, changes: null };
160
+ const imported = await pinga.templates.import(importParams(local));
161
+ return {
162
+ ...base,
163
+ action: "created",
164
+ version: imported.template.active_version?.version ?? 1,
165
+ changes: null,
166
+ warnings: [...base.warnings, ...imported.warnings],
167
+ };
168
+ }
169
+ const remote = toFile(await pinga.templates.export(existing.id));
170
+ const activeVersion = remote.version_data.version ?? null;
171
+ if (kindOf(local) !== kindOf(remote)) {
172
+ throw new CliError(`o arquivo é um template ${kindOf(local) === "visual" ? "visual (com document)" : "cru (sem document)"}, e o da Pinga é ${kindOf(remote) === "visual" ? "visual" : "cru"}. O tipo é fixo na criação.`);
173
+ }
174
+ const changes = diff(local, remote);
175
+ if (changes.metadata.length === 0 && changes.content.length === 0) {
176
+ return { ...base, action: "unchanged", version: activeVersion, changes };
177
+ }
178
+ const publishes = changes.content.length > 0;
179
+ const action = publishes ? "published" : "metadata_updated";
180
+ if (options.dryRun) {
181
+ return { ...base, action, version: publishes && activeVersion != null ? activeVersion + 1 : activeVersion, changes };
182
+ }
183
+ await pinga.templates.update(existing.id, updateParams(local, remote, changes));
184
+ if (!publishes)
185
+ return { ...base, action, version: activeVersion, changes };
186
+ const published = await pinga.templates.publish(existing.id, { change_summary: options.message });
187
+ return { ...base, action, version: published.active_version?.version ?? null, changes };
188
+ }
189
+ async function findBySlug(pinga, slug) {
190
+ try {
191
+ return await pinga.templates.getBySlug(slug);
192
+ }
193
+ catch (error) {
194
+ if (error instanceof PingaError && error.status === 404)
195
+ return undefined;
196
+ throw error;
197
+ }
198
+ }
199
+ /** `template.json` direto, diretório de um slug, ou diretório com um subdiretório por slug. */
200
+ async function findTemplateFiles(roots) {
201
+ const found = [];
202
+ for (const root of roots) {
203
+ const info = await stat(root).catch(() => undefined);
204
+ if (!info)
205
+ throw new CliError(`${root} não existe.`);
206
+ if (info.isFile()) {
207
+ found.push(root);
208
+ continue;
209
+ }
210
+ const direct = path.join(root, TEMPLATE_FILE);
211
+ if (await stat(direct).then((s) => s.isFile()).catch(() => false)) {
212
+ found.push(direct);
213
+ continue;
214
+ }
215
+ const entries = await readdir(root, { withFileTypes: true });
216
+ for (const entry of entries.filter((item) => item.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))) {
217
+ const candidate = path.join(root, entry.name, TEMPLATE_FILE);
218
+ if (await stat(candidate).then((s) => s.isFile()).catch(() => false))
219
+ found.push(candidate);
220
+ }
221
+ }
222
+ return found;
223
+ }
224
+ const LABELS = {
225
+ unchanged: { symbol: "=", done: "sem mudanças", planned: "sem mudanças" },
226
+ created: { symbol: "+", done: "criado", planned: "seria criado" },
227
+ published: { symbol: "~", done: "publicado", planned: "seria publicado" },
228
+ metadata_updated: { symbol: "~", done: "metadados atualizados", planned: "teria os metadados atualizados" },
229
+ failed: { symbol: "✗", done: "falhou", planned: "falhou" },
230
+ };
231
+ function report(ctx, results, dryRun) {
232
+ if (ctx.json) {
233
+ ctx.outJson({ dry_run: dryRun, templates: results });
234
+ return;
235
+ }
236
+ for (const result of results) {
237
+ if (result.action === "failed")
238
+ continue;
239
+ const label = LABELS[result.action];
240
+ const version = result.version != null ? ` (v${result.version})` : "";
241
+ const fields = result.changes ? [...result.changes.metadata, ...result.changes.content] : [];
242
+ const detail = fields.length > 0 && result.action !== "unchanged" ? `: ${fields.join(", ")}` : "";
243
+ ctx.out(`${label.symbol} ${escapeSlug(result.slug)} ${dryRun ? label.planned : label.done}${version}${detail}`);
244
+ for (const warning of result.warnings)
245
+ ctx.err(` aviso: ${warning}`);
246
+ }
247
+ const failed = results.filter((result) => result.action === "failed").length;
248
+ if (failed > 0)
249
+ ctx.err(`${failed} de ${results.length} template(s) falharam.`);
250
+ if (dryRun)
251
+ ctx.err("--dry-run: nada foi escrito.");
252
+ }
@@ -0,0 +1,116 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { constructWebhookEvent, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, PingaWebhookVerificationError } from "@pinga/sdk";
3
+ import { booleanFlag, integerFlag, listFlag, stringFlag } from "../command.js";
4
+ import { CliError, ReportedFailure, UsageError } from "../errors.js";
5
+ import { readAllBytes } from "../prompt.js";
6
+ export const webhooksVerify = {
7
+ name: ["webhooks", "verify"],
8
+ summary: "Confere a assinatura de um webhook (corpo, header e segredo)",
9
+ help: `Uso: pinga webhooks verify --signature <header> (--payload <corpo> | --payload-file <arquivo>) [opções]
10
+
11
+ Confere o header X-Webhook-Signature contra o corpo bruto e o segredo do webhook, do mesmo jeito
12
+ que o seu endpoint deve conferir. Não chama a API: tudo acontece localmente.
13
+
14
+ pinga webhooks verify --payload-file corpo.json \\
15
+ --signature "t=1764950000,v1=5257a8..." --secret-file segredo.txt
16
+
17
+ Segredo (whsec_...); as fontes se somam, e a assinatura vale se conferir com qualquer um:
18
+ PINGA_WEBHOOK_SECRET no ambiente
19
+ --secret-file <arquivo> primeira linha do arquivo
20
+ --secret <segredo> na linha de comando (fica no histórico do shell)
21
+ Na rotação, passe o novo e o antigo (ex.: repetindo --secret).
22
+
23
+ Opções:
24
+ --signature <header> valor do header X-Webhook-Signature (obrigatório)
25
+ --payload <corpo> corpo bruto, exatamente como chegou
26
+ --payload-file <arquivo> corpo bruto de um arquivo; "-" lê da entrada padrão
27
+ --tolerance <segundos> diferença máxima entre o t= da assinatura e agora (padrão ${DEFAULT_WEBHOOK_TOLERANCE_SECONDS})
28
+ --ignore-timestamp não confere o horário (útil para um corpo capturado há tempo)
29
+
30
+ Sai com código 0 se a assinatura confere e 1 se não confere.`,
31
+ options: {
32
+ signature: { type: "string" },
33
+ payload: { type: "string" },
34
+ "payload-file": { type: "string" },
35
+ secret: { type: "string", multiple: true },
36
+ "secret-file": { type: "string" },
37
+ tolerance: { type: "string" },
38
+ "ignore-timestamp": { type: "boolean" },
39
+ },
40
+ positionals: { min: 0, max: 0 },
41
+ async run(ctx, values) {
42
+ const signature = stringFlag(values, "signature", true);
43
+ const secrets = await readSecrets(values, ctx.io.env["PINGA_WEBHOOK_SECRET"]);
44
+ for (const secret of secrets)
45
+ ctx.rememberSecret(secret, { anyLength: true });
46
+ const inline = stringFlag(values, "payload");
47
+ const file = stringFlag(values, "payload-file");
48
+ if ((inline === undefined) === (file === undefined))
49
+ throw new UsageError("Informe --payload ou --payload-file (um dos dois).");
50
+ // O corpo vai como bytes, sem nenhuma conversão: um \n a mais ou a menos muda o HMAC.
51
+ const payload = inline !== undefined ? inline : file === "-" ? await readAllBytes(ctx.io.stdin) : await readBytes(file);
52
+ if (booleanFlag(values, "ignore-timestamp") && values["tolerance"] !== undefined) {
53
+ throw new UsageError("Use --tolerance ou --ignore-timestamp, não os dois.");
54
+ }
55
+ const toleranceSeconds = booleanFlag(values, "ignore-timestamp")
56
+ ? Number.POSITIVE_INFINITY
57
+ : integerFlag(values, "tolerance", { min: 0, max: 31_536_000 });
58
+ try {
59
+ const event = await constructWebhookEvent({ payload, signature, secret: secrets, toleranceSeconds });
60
+ if (typeof event !== "object" || event === null || Array.isArray(event) || typeof event.type !== "string") {
61
+ throw new CliError("A assinatura confere, mas o corpo não é um evento de webhook (esperava um objeto JSON com \"type\").");
62
+ }
63
+ if (ctx.json) {
64
+ ctx.outJson({ valid: true, event });
65
+ return;
66
+ }
67
+ ctx.out(`Assinatura válida: evento ${event.type} (${event.id}), criado em ${event.created_at}.`);
68
+ if (event.data?.delivery?.id)
69
+ ctx.out(`Entrega: ${event.data.delivery.id} (${event.data.delivery.status})`);
70
+ }
71
+ catch (error) {
72
+ if (!(error instanceof PingaWebhookVerificationError)) {
73
+ throw error instanceof SyntaxError ? new CliError("A assinatura confere, mas o corpo não é JSON válido.") : error;
74
+ }
75
+ if (ctx.json) {
76
+ ctx.outJson({ valid: false, reason: error.reason, message: error.message });
77
+ }
78
+ else {
79
+ ctx.err(`Assinatura inválida: ${error.message} (${error.reason}).`);
80
+ if (error.reason === "timestamp_out_of_tolerance") {
81
+ ctx.err("Para um corpo capturado há mais tempo, use --ignore-timestamp.");
82
+ }
83
+ if (error.reason === "signature_mismatch") {
84
+ ctx.err("Confira se o corpo é o bruto (sem reformatar o JSON) e se o segredo é o atual.");
85
+ }
86
+ }
87
+ throw new ReportedFailure();
88
+ }
89
+ },
90
+ };
91
+ async function readSecrets(values, fromEnv) {
92
+ const secrets = [...listFlag(values, "secret")];
93
+ const file = stringFlag(values, "secret-file");
94
+ if (file !== undefined) {
95
+ const text = await readFile(file, "utf8").catch((error) => {
96
+ throw new CliError(`Não consegui ler ${file}: ${error instanceof Error ? error.message : String(error)}`);
97
+ });
98
+ const firstLine = text.split(/\r?\n/)[0]?.trim();
99
+ if (firstLine)
100
+ secrets.push(firstLine);
101
+ }
102
+ if (fromEnv)
103
+ secrets.push(fromEnv);
104
+ if (secrets.length === 0) {
105
+ throw new UsageError("Informe o segredo: PINGA_WEBHOOK_SECRET, --secret-file ou --secret.");
106
+ }
107
+ return secrets;
108
+ }
109
+ async function readBytes(file) {
110
+ try {
111
+ return new Uint8Array(await readFile(file));
112
+ }
113
+ catch (error) {
114
+ throw new CliError(`Não consegui ler ${file}: ${error instanceof Error ? error.message : String(error)}`);
115
+ }
116
+ }
package/dist/context.js CHANGED
@@ -11,6 +11,7 @@ export class Context {
11
11
  #baseUrlFlag;
12
12
  /** Chaves conhecidas nesta execução, para a redação de toda saída. */
13
13
  #secrets = [];
14
+ #shortSecrets = [];
14
15
  #config;
15
16
  constructor(io, flags) {
16
17
  this.io = io;
@@ -22,8 +23,15 @@ export class Context {
22
23
  if (envKey)
23
24
  this.#secrets.push(envKey);
24
25
  }
25
- rememberSecret(secret) {
26
- this.#secrets.push(secret);
26
+ /**
27
+ * `anyLength`: redige mesmo se for curto (segredo de webhook informado pelo usuário). Sem ele,
28
+ * vale o mínimo de 8 caracteres do `redact`, para não mutilar a saída com trechos comuns.
29
+ */
30
+ rememberSecret(secret, options = {}) {
31
+ if (options.anyLength)
32
+ this.#shortSecrets.push(secret);
33
+ else
34
+ this.#secrets.push(secret);
27
35
  }
28
36
  async config() {
29
37
  if (this.#config === undefined) {
@@ -73,11 +81,11 @@ export class Context {
73
81
  }
74
82
  /** Escreve uma linha no stdout, já redigida. */
75
83
  out(text = "") {
76
- this.io.stdout.write(`${redact(text, this.#secrets)}\n`);
84
+ this.io.stdout.write(`${redact(text, this.#secrets, this.#shortSecrets)}\n`);
77
85
  }
78
86
  /** Escreve uma linha no stderr, já redigida. Avisos e progresso, nunca o resultado. */
79
87
  err(text = "") {
80
- this.io.stderr.write(`${redact(text, this.#secrets)}\n`);
88
+ this.io.stderr.write(`${redact(text, this.#secrets, this.#shortSecrets)}\n`);
81
89
  }
82
90
  /** Resultado em `--json`: um documento JSON no stdout. */
83
91
  outJson(value) {
@@ -87,6 +95,6 @@ export class Context {
87
95
  this.err(JSON.stringify(value, null, 2));
88
96
  }
89
97
  redact(text) {
90
- return redact(text, this.#secrets);
98
+ return redact(text, this.#secrets, this.#shortSecrets);
91
99
  }
92
100
  }
package/dist/errors.js CHANGED
@@ -12,6 +12,16 @@ export class CliError extends Error {
12
12
  this.name = "CliError";
13
13
  }
14
14
  }
15
+ /**
16
+ * Falha que o comando já relatou na própria saída (ex.: `templates push` com um template recusado
17
+ * entre vários). Só muda o código de saída para 1; o despachante não imprime mais nada.
18
+ */
19
+ export class ReportedFailure extends Error {
20
+ constructor() {
21
+ super("falha já relatada");
22
+ this.name = "ReportedFailure";
23
+ }
24
+ }
15
25
  export const ExitCode = {
16
26
  Ok: 0,
17
27
  Failure: 1,
@@ -23,11 +33,16 @@ const API_KEY_PATTERN = /pg_(live|test)_[A-Za-z0-9]+/g;
23
33
  * nunca pôr a chave numa mensagem; esta pega o que escapar (ex.: um erro de terceiro que ecoe a URL
24
34
  * ou o header).
25
35
  */
26
- export function redact(text, secrets = []) {
36
+ export function redact(text, secrets = [], anyLength = []) {
27
37
  let result = text.replace(API_KEY_PATTERN, "pg_$1_[redacted]");
28
38
  for (const secret of secrets) {
29
39
  if (secret.length >= 8)
30
40
  result = result.split(secret).join("[redacted]");
31
41
  }
42
+ // Mais longos primeiro, para um segredo que contém outro não sair parcialmente redigido.
43
+ for (const secret of [...anyLength].sort((a, b) => b.length - a.length)) {
44
+ if (secret.length > 0)
45
+ result = result.split(secret).join("[redacted]");
46
+ }
32
47
  return result;
33
48
  }
package/dist/format.js CHANGED
@@ -12,3 +12,13 @@ export function table(headers, rawRows) {
12
12
  function clean(value) {
13
13
  return value.replace(/[\r\n\t]+/g, " ");
14
14
  }
15
+ /** Controles C0/C1, DEL, zero-width, separadores de linha e bidi que mexeriam no terminal. */
16
+ const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff]/g;
17
+ /** Slug para saída comum: igual ao original, mas com caracteres perigosos como `\uXXXX`. */
18
+ export function escapeSlug(slug) {
19
+ return slug.replace(UNSAFE, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
20
+ }
21
+ /** Slug entre aspas para mensagens de erro; escapa o que `JSON.stringify` deixa passar (DEL, C1, bidi...). */
22
+ export function quoteSlug(slug) {
23
+ return escapeSlug(JSON.stringify(slug));
24
+ }
package/dist/main.js CHANGED
@@ -2,11 +2,24 @@ import { parseArgs } from "node:util";
2
2
  import { login, logout } from "./commands/auth.js";
3
3
  import { deliveriesGet, deliveriesList } from "./commands/deliveries.js";
4
4
  import { emailsSend } from "./commands/emails.js";
5
+ import { domainsCheck } from "./commands/domains.js";
6
+ import { templatesPull, templatesPush } from "./commands/templates.js";
7
+ import { webhooksVerify } from "./commands/webhooks.js";
5
8
  import { Context } from "./context.js";
6
9
  import { ExitCode, redact, UsageError } from "./errors.js";
7
10
  import { renderError } from "./render-error.js";
8
11
  import { VERSION } from "./version.js";
9
- export const COMMANDS = [login, logout, emailsSend, deliveriesList, deliveriesGet];
12
+ export const COMMANDS = [
13
+ login,
14
+ logout,
15
+ emailsSend,
16
+ deliveriesList,
17
+ deliveriesGet,
18
+ templatesPull,
19
+ templatesPush,
20
+ domainsCheck,
21
+ webhooksVerify,
22
+ ];
10
23
  const GLOBAL_OPTIONS = {
11
24
  profile: { type: "string", short: "p" },
12
25
  "base-url": { type: "string" },
@@ -20,10 +33,11 @@ const GLOBAL_HELP = `Opções globais:
20
33
  --json saída em JSON no stdout; em erro, o JSON do erro vai para o stderr
21
34
  -h, --help mostra a ajuda`;
22
35
  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)`;
36
+ PINGA_API_KEY API key; tem precedência sobre o arquivo de configuração
37
+ PINGA_PROFILE perfil padrão
38
+ PINGA_BASE_URL URL da API
39
+ PINGA_CONFIG_DIR diretório do config.json (padrão: ~/.config/pinga; %APPDATA%\\pinga no Windows)
40
+ PINGA_WEBHOOK_SECRET segredo para \`pinga webhooks verify\``;
27
41
  /**
28
42
  * Executa o CLI e devolve o código de saída: `0` sucesso, `1` falha (API, rede, configuração),
29
43
  * `2` erro de uso.
@@ -75,6 +89,8 @@ export async function main(argv, io) {
75
89
  }
76
90
  catch (error) {
77
91
  const rendered = renderError(error);
92
+ if (rendered.reported)
93
+ return rendered.exitCode;
78
94
  const scrub = (text) => (ctx ? ctx.redact(text) : redact(text, [io.env["PINGA_API_KEY"] ?? ""]));
79
95
  if (wantsJson) {
80
96
  io.stderr.write(`${scrub(JSON.stringify(rendered.json, null, 2))}\n`);
package/dist/prompt.js CHANGED
@@ -66,6 +66,16 @@ async function readFirstLine(stdin) {
66
66
  }
67
67
  return buffer;
68
68
  }
69
+ /**
70
+ * Lê a entrada padrão inteira como bytes, sem decodificar: um caractere multibyte partido entre
71
+ * chunks, ou um byte que não é UTF-8, chega intacto (`webhooks verify` assina sobre os bytes).
72
+ */
73
+ export async function readAllBytes(stdin) {
74
+ const chunks = [];
75
+ for await (const chunk of stdin)
76
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk, "utf8") : Buffer.from(chunk));
77
+ return new Uint8Array(Buffer.concat(chunks));
78
+ }
69
79
  /** Lê a entrada padrão inteira (`--html-file -`). */
70
80
  export async function readAll(stdin) {
71
81
  let buffer = "";
@@ -1,11 +1,14 @@
1
1
  import { PingaError } from "@pinga/sdk";
2
- import { CliError, ExitCode, UsageError } from "./errors.js";
2
+ import { CliError, ExitCode, ReportedFailure, UsageError } from "./errors.js";
3
3
  /**
4
4
  * Traduz qualquer falha para a saída do CLI. Erro da API mostra `title`, `detail` e `trace_id` do
5
5
  * Problem Details, mais as listas de validação, que é o que o usuário precisa para corrigir o pedido
6
6
  * ou abrir chamado.
7
7
  */
8
8
  export function renderError(error) {
9
+ if (error instanceof ReportedFailure) {
10
+ return { exitCode: ExitCode.Failure, lines: [], json: { error: {} }, reported: true };
11
+ }
9
12
  if (error instanceof UsageError) {
10
13
  return {
11
14
  exitCode: ExitCode.Usage,
@@ -0,0 +1,115 @@
1
+ import { CliError } from "./errors.js";
2
+ export const ENVELOPE_VERSION = "pinga.template.v1";
3
+ export const TEMPLATE_FILE = "template.json";
4
+ /**
5
+ * Prepara o export para ir para o git. Sai só o `exported_at`: muda a cada `pull`, e um diff que
6
+ * sempre aparece esconde o que mudou de verdade. O resto é o envelope `pinga.template.v1` como a
7
+ * API devolve, e o `import` aceita o arquivo de volta.
8
+ */
9
+ export function toFile(envelope) {
10
+ const { exported_at: _exportedAt, ...rest } = envelope;
11
+ return rest;
12
+ }
13
+ export function serialize(file) {
14
+ return `${JSON.stringify(file, null, 2)}\n`;
15
+ }
16
+ /** Lê e confere o mínimo do envelope; o resto quem valida é a API. */
17
+ export function parseTemplateFile(text, source) {
18
+ let parsed;
19
+ try {
20
+ parsed = JSON.parse(text);
21
+ }
22
+ catch {
23
+ throw new CliError(`${source} não é um JSON válido.`);
24
+ }
25
+ if (!isRecord(parsed))
26
+ throw new CliError(`${source} não é um envelope de template.`);
27
+ if (parsed["version"] !== ENVELOPE_VERSION) {
28
+ throw new CliError(`${source}: "version" precisa ser "${ENVELOPE_VERSION}".`);
29
+ }
30
+ const template = parsed["template"];
31
+ const versionData = parsed["version_data"];
32
+ if (!isRecord(template) || typeof template["slug"] !== "string" || template["slug"].length === 0) {
33
+ throw new CliError(`${source}: falta "template.slug".`);
34
+ }
35
+ if (!isRecord(versionData))
36
+ throw new CliError(`${source}: falta "version_data".`);
37
+ return parsed;
38
+ }
39
+ /** Template visual é editado pelo `document`; o cru, por `subject`/`mjml`/`text_body`. */
40
+ export function kindOf(file) {
41
+ return file.version_data.document ? "visual" : "raw";
42
+ }
43
+ const METADATA_FIELDS = ["name", "description", "from_address"];
44
+ /**
45
+ * Compara o arquivo com o export da versão ativa. Só entram os campos que o cliente edita: num
46
+ * template visual, `subject`, `mjml` e `text_body` são derivados do `document` e ficam de fora.
47
+ * `version_data.version`, `source` e `blocks` são informativos e nunca contam.
48
+ */
49
+ export function diff(local, remote) {
50
+ const metadata = METADATA_FIELDS.filter((field) => !sameValue(local.template[field], remote.template[field]));
51
+ const contentFields = kindOf(remote) === "visual"
52
+ ? ["document", "variables"]
53
+ : ["subject", "mjml", "text_body", "variables"];
54
+ const content = contentFields.filter((field) => !sameValue(contentDefault(field, local.version_data[field]), contentDefault(field, remote.version_data[field])));
55
+ return { metadata: [...metadata], content: [...content] };
56
+ }
57
+ /**
58
+ * Aplica na comparação os mesmos defaults que o envio usa (`updateParams`): `variables` ausente
59
+ * vira `[]` e `text_body` vazio vira `null`. Sem isso, um arquivo sem `variables` nunca converge
60
+ * com o remoto (que guarda `[]`) e cada push cria uma versão nova.
61
+ */
62
+ function contentDefault(field, value) {
63
+ if (field === "variables")
64
+ return value ?? [];
65
+ if (field === "text_body")
66
+ return value === "" ? null : value;
67
+ return value;
68
+ }
69
+ /** Corpo do `PUT /v1/templates/{id}` com só o que mudou. */
70
+ export function updateParams(local, remote, changes) {
71
+ const params = {};
72
+ for (const field of changes.metadata)
73
+ params[field] = local.template[field] ?? null;
74
+ if (changes.content.length > 0) {
75
+ params.variables = local.version_data.variables ?? [];
76
+ if (kindOf(remote) === "visual") {
77
+ params.document = local.version_data.document ?? null;
78
+ }
79
+ else {
80
+ params.subject = local.version_data.subject;
81
+ params.body = local.version_data.mjml;
82
+ params.text_body = local.version_data.text_body || null;
83
+ }
84
+ }
85
+ return params;
86
+ }
87
+ export function importParams(local) {
88
+ return local;
89
+ }
90
+ /** Igualdade estrutural: ignora a ordem das chaves e trata `null` e ausente como iguais. */
91
+ export function sameValue(a, b) {
92
+ return canonical(a) === canonical(b);
93
+ }
94
+ function canonical(value) {
95
+ return JSON.stringify(normalize(value)) ?? "null";
96
+ }
97
+ function normalize(value) {
98
+ if (value === undefined || value === null)
99
+ return null;
100
+ if (Array.isArray(value))
101
+ return value.map(normalize);
102
+ if (isRecord(value)) {
103
+ const out = {};
104
+ for (const key of Object.keys(value).sort()) {
105
+ const item = normalize(value[key]);
106
+ if (item !== null)
107
+ out[key] = item;
108
+ }
109
+ return out;
110
+ }
111
+ return value;
112
+ }
113
+ function isRecord(value) {
114
+ return typeof value === "object" && value !== null && !Array.isArray(value);
115
+ }
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // Mantido em sincronia com package.json por test/version.test.ts.
2
- export const VERSION = "0.1.0";
2
+ export const VERSION = "0.2.1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pinga-cli",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "CLI oficial do Pinga — API de email transacional (pinga.api.br)",
5
5
  "license": "MIT",
6
6
  "author": "Pinga <dev@pinga.api.br>",
@@ -12,12 +12,21 @@
12
12
  "bugs": {
13
13
  "url": "https://github.com/pinga-api/pinga-cli/issues"
14
14
  },
15
- "keywords": ["pinga", "email", "transactional-email", "cli"],
15
+ "keywords": [
16
+ "pinga",
17
+ "email",
18
+ "transactional-email",
19
+ "cli"
20
+ ],
16
21
  "type": "module",
17
22
  "bin": {
18
23
  "pinga": "dist/cli.js"
19
24
  },
20
- "files": ["dist", "README.md", "LICENSE"],
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
21
30
  "engines": {
22
31
  "node": ">=20"
23
32
  },
@@ -28,7 +37,8 @@
28
37
  "test:watch": "vitest",
29
38
  "smoke": "vitest run --config vitest.smoke.config.ts",
30
39
  "dev": "bun src/cli.ts",
31
- "prepublishOnly": "bun run build"
40
+ "prepublishOnly": "bun run build",
41
+ "build:bin": "bun build src/cli.ts --compile --minify --outfile bin/pinga"
32
42
  },
33
43
  "dependencies": {
34
44
  "@pinga/sdk": "^0.1.0"