pinga-cli 0.2.1 → 0.2.2

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
@@ -27,7 +27,7 @@ npx pinga-cli --help
27
27
  `SHA256SUMS`:
28
28
 
29
29
  ```bash
30
- version=0.2.1 target=linux-x64
30
+ version=0.2.2 target=linux-x64
31
31
  curl -fsSLO "https://github.com/pinga-api/pinga-cli/releases/download/v${version}/pinga-v${version}-${target}.tar.gz"
32
32
  curl -fsSLO "https://github.com/pinga-api/pinga-cli/releases/download/v${version}/SHA256SUMS"
33
33
  sha256sum --check --ignore-missing SHA256SUMS # no macOS: shasum -a 256 --check --ignore-missing SHA256SUMS
package/dist/command.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { quoteSlug } from "./format.js";
1
2
  import { UsageError } from "./errors.js";
2
3
  export function stringFlag(values, name, required = false) {
3
4
  const value = values[name];
@@ -30,7 +31,7 @@ export function integerFlag(values, name, range) {
30
31
  export function parsePair(raw, flag, separator = /=/) {
31
32
  const match = separator.exec(raw);
32
33
  if (!match || match.index === 0) {
33
- throw new UsageError(`--${flag} espera chave=valor, recebeu "${raw}".`);
34
+ throw new UsageError(`--${flag} espera chave=valor, recebeu ${quoteSlug(raw)}.`);
34
35
  }
35
36
  return [raw.slice(0, match.index).trim(), raw.slice(match.index + match[0].length)];
36
37
  }
@@ -1,3 +1,4 @@
1
+ import { escapeSlug } from "../format.js";
1
2
  import { PingaError } from "@pinga/sdk";
2
3
  import { booleanFlag } from "../command.js";
3
4
  import { writeConfig } from "../config.js";
@@ -58,7 +59,7 @@ Opções:
58
59
  ctx.outJson({ profile: ctx.profile, mode, verified: verify, config_path: ctx.configFile });
59
60
  return;
60
61
  }
61
- ctx.out(`Chave ${mode} gravada no perfil "${ctx.profile}" (${ctx.configFile}).`);
62
+ ctx.out(`Chave ${mode} gravada no perfil "${ctx.profile}" (${escapeSlug(ctx.configFile)}).`);
62
63
  if (!verify)
63
64
  ctx.out("A chave não foi conferida contra a API (--skip-verify).");
64
65
  },
@@ -71,7 +71,7 @@ Paginação:
71
71
  }
72
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
73
  if (nextCursor)
74
- ctx.err(`Há mais entregas. Próxima página: --cursor ${nextCursor}`);
74
+ ctx.err(`Há mais entregas. Próxima página: --cursor ${escapeSlug(nextCursor)}`);
75
75
  },
76
76
  };
77
77
  export const deliveriesGet = {
@@ -125,7 +125,7 @@ function describeDelivery(delivery) {
125
125
  ];
126
126
  const lines = fields
127
127
  .filter((field) => typeof field[1] === "string" && field[1].length > 0)
128
- .map(([label, value]) => `${`${label}:`.padEnd(21)}${value}`);
128
+ .map(([label, value]) => `${`${label}:`.padEnd(21)}${label === "Template" || label === "Tipo de notificação" ? value : escapeSlug(value)}`);
129
129
  lines.push("", "Eventos:");
130
130
  if (delivery.events.length === 0) {
131
131
  lines.push(" (nenhum ainda)");
@@ -133,7 +133,7 @@ function describeDelivery(delivery) {
133
133
  else {
134
134
  const events = [...delivery.events].sort((a, b) => a.occurred_at.localeCompare(b.occurred_at));
135
135
  for (const event of events)
136
- lines.push(` ${event.occurred_at} ${event.type}`);
136
+ lines.push(` ${escapeSlug(event.occurred_at)} ${escapeSlug(event.type)}`);
137
137
  }
138
138
  return lines.join("\n");
139
139
  }
@@ -1,7 +1,7 @@
1
1
  import { apiRequest, pathSegment } from "../api.js";
2
2
  import { booleanFlag } from "../command.js";
3
3
  import { CliError, ReportedFailure } from "../errors.js";
4
- import { table } from "../format.js";
4
+ import { escapeSlug, table } from "../format.js";
5
5
  const VERIFIED = "verified";
6
6
  export const domainsCheck = {
7
7
  name: ["domains", "check"],
@@ -25,7 +25,7 @@ Opções:
25
25
  const wanted = names.map((name) => name.toLowerCase().replace(/\.$/, ""));
26
26
  const missing = wanted.filter((name) => !all.some((domain) => domain.domain.toLowerCase() === name));
27
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.`);
28
+ throw new CliError(`Domínio não encontrado nesta organização: ${missing.map(escapeSlug).join(", ")}. Rode \`pinga domains check\` para ver todos.`);
29
29
  }
30
30
  const selected = wanted.length > 0 ? all.filter((domain) => wanted.includes(domain.domain.toLowerCase())) : all;
31
31
  const refresh = booleanFlag(values, "refresh");
@@ -70,18 +70,18 @@ async function listDomains(ctx) {
70
70
  }
71
71
  }
72
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))`);
73
+ const lines = [`${escapeSlug(domain.domain)} ${escapeSlug(domain.status)}${domain.nickname ? ` (${escapeSlug(domain.nickname)})` : ""}${domain.managed ? " [gerenciado pela Pinga]" : ""}`];
74
+ lines.push(` DKIM ${escapeSlug(domain.dkim.status)} (${domain.dkim.tokens_count} chave(s))`);
75
75
  for (const [label, check] of [["SPF", domain.spf], ["DMARC", domain.dmarc], ["MX", domain.mx]]) {
76
76
  if (check)
77
- lines.push(` ${label.padEnd(5)} ${check.status}${check.record ? ` ${check.record}` : ""}`);
77
+ lines.push(` ${label.padEnd(5)} ${escapeSlug(check.status)}${check.record ? ` ${escapeSlug(check.record)}` : ""}`);
78
78
  }
79
79
  if (domain.verified_at)
80
- lines.push(` Verificado em ${domain.verified_at}`);
80
+ lines.push(` Verificado em ${escapeSlug(domain.verified_at)}`);
81
81
  if (domain.last_checked_at)
82
- lines.push(` Última checagem ${domain.last_checked_at}`);
82
+ lines.push(` Última checagem ${escapeSlug(domain.last_checked_at)}`);
83
83
  if (domain.last_check_error)
84
- lines.push(` Erro na última checagem: ${domain.last_check_error}`);
84
+ lines.push(` Erro na última checagem: ${escapeSlug(domain.last_check_error)}`);
85
85
  // Domínio pendente: todos os registros. Verificado: só o SPF/DMARC recomendado que a última checagem
86
86
  // de DNS achou ausente ou em conflito (o DKIM já está resolvido).
87
87
  const records = domain.status !== VERIFIED
@@ -1,3 +1,4 @@
1
+ import { escapeSlug } from "../format.js";
1
2
  import { readFile } from "node:fs/promises";
2
3
  import { booleanFlag, listFlag, parsePair, stringFlag } from "../command.js";
3
4
  import { CliError, UsageError } from "../errors.js";
@@ -72,10 +73,10 @@ Comum:
72
73
  ctx.outJson(response);
73
74
  return;
74
75
  }
75
- ctx.out(`Envio aceito: ${response.delivery_id} (${response.status})`);
76
+ ctx.out(`Envio aceito: ${escapeSlug(response.delivery_id)} (${escapeSlug(response.status)})`);
76
77
  if (response.blocked_reason)
77
- ctx.out(`Bloqueado: ${response.blocked_reason}`);
78
- ctx.err(`Acompanhe com: pinga deliveries get ${response.delivery_id}`);
78
+ ctx.out(`Bloqueado: ${escapeSlug(response.blocked_reason)}`);
79
+ ctx.err(`Acompanhe com: pinga deliveries get ${escapeSlug(response.delivery_id)}`);
79
80
  },
80
81
  };
81
82
  export async function buildSendParams(ctx, values) {
@@ -142,7 +143,7 @@ async function readInput(ctx, file) {
142
143
  return await readFile(file, "utf8");
143
144
  }
144
145
  catch (error) {
145
- throw new CliError(`Não consegui ler ${file}: ${error instanceof Error ? error.message : String(error)}`);
146
+ throw new CliError(`Não consegui ler ${escapeSlug(file)}: ${escapeSlug(error instanceof Error ? error.message : String(error))}`);
146
147
  }
147
148
  }
148
149
  async function parseVariables(ctx, values) {
@@ -70,7 +70,7 @@ Opções:
70
70
  }
71
71
  for (const result of results) {
72
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)" : ""}`);
73
+ ctx.out(`${result.status === "written" ? "↓" : "="} ${escapeSlug(result.slug)}${version} ${escapeSlug(result.path)}${result.status === "unchanged" ? " (sem mudanças)" : ""}`);
74
74
  }
75
75
  },
76
76
  };
@@ -105,7 +105,7 @@ Opções:
105
105
  const roots = paths.length > 0 ? paths : [stringFlag(values, "dir") ?? DEFAULT_DIR];
106
106
  const files = await findTemplateFiles(roots);
107
107
  if (files.length === 0)
108
- throw new CliError(`Nenhum ${TEMPLATE_FILE} encontrado em ${roots.join(", ")}.`);
108
+ throw new CliError(`Nenhum ${TEMPLATE_FILE} encontrado em ${roots.map(escapeSlug).join(", ")}.`);
109
109
  const dryRun = booleanFlag(values, "dry-run");
110
110
  const message = stringFlag(values, "message") ?? "pinga templates push";
111
111
  const pinga = await ctx.client();
@@ -117,7 +117,7 @@ Opções:
117
117
  const local = parseTemplateFile(await readFile(file, "utf8"), file);
118
118
  const other = seen.get(local.template.slug);
119
119
  if (other)
120
- throw new CliError(`Slug ${quoteSlug(local.template.slug)} aparece em ${other} e em ${file}.`);
120
+ throw new CliError(`Slug ${quoteSlug(local.template.slug)} aparece em ${escapeSlug(other)} e em ${escapeSlug(file)}.`);
121
121
  seen.set(local.template.slug, file);
122
122
  locals.push({ file, local });
123
123
  }
@@ -138,7 +138,7 @@ Opções:
138
138
  error: rendered.json.error,
139
139
  });
140
140
  if (!ctx.json)
141
- ctx.err(`✗ ${escapeSlug(local.template.slug)} (${file})\n${rendered.lines.map((line) => ` ${line}`).join("\n")}`);
141
+ ctx.err(`✗ ${escapeSlug(local.template.slug)} (${escapeSlug(file)})\n${rendered.lines.map((line) => ` ${line}`).join("\n")}`);
142
142
  }
143
143
  }
144
144
  report(ctx, results, dryRun);
@@ -202,7 +202,7 @@ async function findTemplateFiles(roots) {
202
202
  for (const root of roots) {
203
203
  const info = await stat(root).catch(() => undefined);
204
204
  if (!info)
205
- throw new CliError(`${root} não existe.`);
205
+ throw new CliError(`${escapeSlug(root)} não existe.`);
206
206
  if (info.isFile()) {
207
207
  found.push(root);
208
208
  continue;
@@ -242,7 +242,7 @@ function report(ctx, results, dryRun) {
242
242
  const detail = fields.length > 0 && result.action !== "unchanged" ? `: ${fields.join(", ")}` : "";
243
243
  ctx.out(`${label.symbol} ${escapeSlug(result.slug)} ${dryRun ? label.planned : label.done}${version}${detail}`);
244
244
  for (const warning of result.warnings)
245
- ctx.err(` aviso: ${warning}`);
245
+ ctx.err(` aviso: ${escapeSlug(warning)}`);
246
246
  }
247
247
  const failed = results.filter((result) => result.action === "failed").length;
248
248
  if (failed > 0)
@@ -3,6 +3,7 @@ import { constructWebhookEvent, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, PingaWebhookV
3
3
  import { booleanFlag, integerFlag, listFlag, stringFlag } from "../command.js";
4
4
  import { CliError, ReportedFailure, UsageError } from "../errors.js";
5
5
  import { readAllBytes } from "../prompt.js";
6
+ import { escapeSlug } from "../format.js";
6
7
  export const webhooksVerify = {
7
8
  name: ["webhooks", "verify"],
8
9
  summary: "Confere a assinatura de um webhook (corpo, header e segredo)",
@@ -64,9 +65,9 @@ Sai com código 0 se a assinatura confere e 1 se não confere.`,
64
65
  ctx.outJson({ valid: true, event });
65
66
  return;
66
67
  }
67
- ctx.out(`Assinatura válida: evento ${event.type} (${event.id}), criado em ${event.created_at}.`);
68
+ ctx.out(`Assinatura válida: evento ${escapeSlug(event.type)} (${escapeSlug(String(event.id))}), criado em ${escapeSlug(String(event.created_at))}.`);
68
69
  if (event.data?.delivery?.id)
69
- ctx.out(`Entrega: ${event.data.delivery.id} (${event.data.delivery.status})`);
70
+ ctx.out(`Entrega: ${escapeSlug(String(event.data.delivery.id))} (${escapeSlug(String(event.data.delivery.status))})`);
70
71
  }
71
72
  catch (error) {
72
73
  if (!(error instanceof PingaWebhookVerificationError)) {
@@ -76,7 +77,7 @@ Sai com código 0 se a assinatura confere e 1 se não confere.`,
76
77
  ctx.outJson({ valid: false, reason: error.reason, message: error.message });
77
78
  }
78
79
  else {
79
- ctx.err(`Assinatura inválida: ${error.message} (${error.reason}).`);
80
+ ctx.err(`Assinatura inválida: ${escapeSlug(error.message)} (${escapeSlug(String(error.reason))}).`);
80
81
  if (error.reason === "timestamp_out_of_tolerance") {
81
82
  ctx.err("Para um corpo capturado há mais tempo, use --ignore-timestamp.");
82
83
  }
@@ -93,7 +94,7 @@ async function readSecrets(values, fromEnv) {
93
94
  const file = stringFlag(values, "secret-file");
94
95
  if (file !== undefined) {
95
96
  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
+ throw new CliError(`Não consegui ler ${escapeSlug(file)}: ${escapeSlug(error instanceof Error ? error.message : String(error))}`);
97
98
  });
98
99
  const firstLine = text.split(/\r?\n/)[0]?.trim();
99
100
  if (firstLine)
@@ -111,6 +112,6 @@ async function readBytes(file) {
111
112
  return new Uint8Array(await readFile(file));
112
113
  }
113
114
  catch (error) {
114
- throw new CliError(`Não consegui ler ${file}: ${error instanceof Error ? error.message : String(error)}`);
115
+ throw new CliError(`Não consegui ler ${escapeSlug(file)}: ${escapeSlug(error instanceof Error ? error.message : String(error))}`);
115
116
  }
116
117
  }
package/dist/config.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { CliError } from "./errors.js";
4
+ import { escapeSlug, quoteSlug } from "./format.js";
4
5
  export const DEFAULT_PROFILE = "default";
5
6
  const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
6
7
  /**
@@ -26,7 +27,7 @@ export function configPath(io) {
26
27
  }
27
28
  export function assertProfileName(name) {
28
29
  if (!PROFILE_NAME.test(name)) {
29
- throw new CliError(`Nome de perfil inválido: "${name}". Use letras, números, "-" e "_" (até 64 caracteres).`);
30
+ throw new CliError(`Nome de perfil inválido: ${quoteSlug(name)}. Use letras, números, "-" e "_" (até 64 caracteres).`);
30
31
  }
31
32
  return name;
32
33
  }
@@ -38,17 +39,17 @@ export async function readConfig(file) {
38
39
  catch (error) {
39
40
  if (isNotFound(error))
40
41
  return { profiles: {} };
41
- throw new CliError(`Não consegui ler ${file}: ${describe(error)}`);
42
+ throw new CliError(`Não consegui ler ${escapeSlug(file)}: ${describe(error)}`);
42
43
  }
43
44
  let parsed;
44
45
  try {
45
46
  parsed = JSON.parse(text);
46
47
  }
47
48
  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
+ throw new CliError(`${escapeSlug(file)} não é um JSON válido. Corrija o arquivo ou apague-o e rode \`pinga login\` de novo.`);
49
50
  }
50
51
  if (!isRecord(parsed) || (parsed["profiles"] !== undefined && !isRecord(parsed["profiles"]))) {
51
- throw new CliError(`${file} não tem o formato esperado ({ "profiles": { ... } }).`);
52
+ throw new CliError(`${escapeSlug(file)} não tem o formato esperado ({ "profiles": { ... } }).`);
52
53
  }
53
54
  const profiles = {};
54
55
  for (const [name, value] of Object.entries((parsed["profiles"] ?? {}))) {
@@ -79,14 +80,15 @@ export async function writeConfig(file, config) {
79
80
  }
80
81
  catch (error) {
81
82
  await rm(temp, { force: true });
82
- throw new CliError(`Não consegui gravar ${file}: ${describe(error)}`);
83
+ throw new CliError(`Não consegui gravar ${escapeSlug(file)}: ${describe(error)}`);
83
84
  }
84
85
  }
85
86
  function isNotFound(error) {
86
87
  return isRecord(error) && error["code"] === "ENOENT";
87
88
  }
89
+ /** Mensagem do sistema de arquivos traz o caminho cru: escapa ESC, C1 e bidi. */
88
90
  function describe(error) {
89
- return error instanceof Error ? error.message : String(error);
91
+ return escapeSlug(error instanceof Error ? error.message : String(error));
90
92
  }
91
93
  function isRecord(value) {
92
94
  return typeof value === "object" && value !== null && !Array.isArray(value);
package/dist/context.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { DEFAULT_BASE_URL, Pinga } from "@pinga/sdk";
2
2
  import { assertProfileName, configPath, DEFAULT_PROFILE, readConfig } from "./config.js";
3
3
  import { CliError, redact } from "./errors.js";
4
+ import { stringifyJson } from "./format.js";
4
5
  import { VERSION } from "./version.js";
5
6
  /** Estado de uma execução: perfil escolhido, formato de saída e acesso ao cliente da API. */
6
7
  export class Context {
@@ -89,10 +90,7 @@ export class Context {
89
90
  }
90
91
  /** Resultado em `--json`: um documento JSON no stdout. */
91
92
  outJson(value) {
92
- this.out(JSON.stringify(value, null, 2));
93
- }
94
- errJson(value) {
95
- this.err(JSON.stringify(value, null, 2));
93
+ this.out(stringifyJson(value));
96
94
  }
97
95
  redact(text) {
98
96
  return redact(text, this.#secrets, this.#shortSecrets);
package/dist/format.js CHANGED
@@ -10,7 +10,7 @@ export function table(headers, rawRows) {
10
10
  }
11
11
  /** Quebras de linha e tabs numa célula desalinhariam a tabela. */
12
12
  function clean(value) {
13
- return value.replace(/[\r\n\t]+/g, " ");
13
+ return escapeSlug(value.replace(/[\r\n\t]+/g, " "));
14
14
  }
15
15
  /** Controles C0/C1, DEL, zero-width, separadores de linha e bidi que mexeriam no terminal. */
16
16
  const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff]/g;
@@ -18,6 +18,15 @@ const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2060-\u20
18
18
  export function escapeSlug(slug) {
19
19
  return slug.replace(UNSAFE, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
20
20
  }
21
+ /**
22
+ * JSON para `--json`: `JSON.stringify` já escapa C0, mas deixa passar DEL, C1, bidi e U+2028/2029.
23
+ * Fora das strings só há C0 da indentação (`\n`), que fica como está; o resto vira `\uXXXX`, JSON válido.
24
+ * Valor não serializável (undefined, função, símbolo) vira `null`, não exceção.
25
+ */
26
+ export function stringifyJson(value) {
27
+ const json = JSON.stringify(value, null, 2) ?? "null";
28
+ return json.replace(UNSAFE, (c) => (c.charCodeAt(0) < 0x20 ? c : escapeSlug(c)));
29
+ }
21
30
  /** Slug entre aspas para mensagens de erro; escapa o que `JSON.stringify` deixa passar (DEL, C1, bidi...). */
22
31
  export function quoteSlug(slug) {
23
32
  return escapeSlug(JSON.stringify(slug));
package/dist/main.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { escapeSlug, stringifyJson } from "./format.js";
1
2
  import { parseArgs } from "node:util";
2
3
  import { login, logout } from "./commands/auth.js";
3
4
  import { deliveriesGet, deliveriesList } from "./commands/deliveries.js";
@@ -67,7 +68,7 @@ export async function main(argv, io) {
67
68
  io.stdout.write(`${groupHelp(group)}\n`);
68
69
  return rest.includes("--help") || rest.includes("-h") ? ExitCode.Ok : ExitCode.Usage;
69
70
  }
70
- throw new UsageError(`Comando desconhecido: ${words.join(" ")}. Rode \`pinga --help\`.`);
71
+ throw new UsageError(`Comando desconhecido: ${escapeSlug(words.join(" "))}. Rode \`pinga --help\`.`);
71
72
  }
72
73
  const parsed = parseFlags({ ...GLOBAL_OPTIONS, ...command.options }, rest);
73
74
  if (parsed.values["help"]) {
@@ -93,7 +94,7 @@ export async function main(argv, io) {
93
94
  return rendered.exitCode;
94
95
  const scrub = (text) => (ctx ? ctx.redact(text) : redact(text, [io.env["PINGA_API_KEY"] ?? ""]));
95
96
  if (wantsJson) {
96
- io.stderr.write(`${scrub(JSON.stringify(rendered.json, null, 2))}\n`);
97
+ io.stderr.write(`${scrub(stringifyJson(rendered.json))}\n`);
97
98
  }
98
99
  else {
99
100
  io.stderr.write(`${scrub(rendered.lines.join("\n"))}\n`);
@@ -149,7 +150,7 @@ function parseFlags(options, args) {
149
150
  const message = error instanceof Error ? error.message : String(error);
150
151
  const unknown = /Unknown option '([^']+)'/.exec(message);
151
152
  if (unknown)
152
- throw new UsageError(`Opção desconhecida: ${unknown[1]}. Rode com --help.`);
153
+ throw new UsageError(`Opção desconhecida: ${escapeSlug(unknown[1] ?? "")}. Rode com --help.`);
153
154
  const missing = /Option '([^']+?)(?: <value>)?' argument missing/.exec(message);
154
155
  if (missing)
155
156
  throw new UsageError(`${missing[1]?.replace(/^-\w, /, "")} precisa de um valor.`);
@@ -1,4 +1,5 @@
1
1
  import { PingaError } from "@pinga/sdk";
2
+ import { escapeSlug as e } from "./format.js";
2
3
  import { CliError, ExitCode, ReportedFailure, UsageError } from "./errors.js";
3
4
  /**
4
5
  * Traduz qualquer falha para a saída do CLI. Erro da API mostra `title`, `detail` e `trace_id` do
@@ -12,7 +13,7 @@ export function renderError(error) {
12
13
  if (error instanceof UsageError) {
13
14
  return {
14
15
  exitCode: ExitCode.Usage,
15
- lines: [`Erro: ${error.message}`],
16
+ lines: [`Erro: ${e(error.message)}`],
16
17
  json: { error: { type: "usage_error", message: error.message } },
17
18
  };
18
19
  }
@@ -22,42 +23,42 @@ export function renderError(error) {
22
23
  if (error instanceof CliError) {
23
24
  return {
24
25
  exitCode: ExitCode.Failure,
25
- lines: [`Erro: ${error.message}`],
26
+ lines: [`Erro: ${e(error.message)}`],
26
27
  json: { error: { type: "cli_error", message: error.message } },
27
28
  };
28
29
  }
29
30
  const message = error instanceof Error ? error.message : String(error);
30
31
  return {
31
32
  exitCode: ExitCode.Failure,
32
- lines: [`Erro inesperado: ${message}`],
33
+ lines: [`Erro inesperado: ${e(message)}`],
33
34
  json: { error: { type: "unexpected_error", message } },
34
35
  };
35
36
  }
36
37
  function renderApiError(error) {
37
38
  const lines = [];
38
- const title = error.title ?? error.type;
39
+ const title = e(error.title ?? error.type);
39
40
  lines.push(error.status > 0 ? `Erro: ${title} (HTTP ${error.status})` : `Erro: ${title}`);
40
41
  if (error.detail)
41
- lines.push(` ${error.detail}`);
42
+ lines.push(` ${e(error.detail)}`);
42
43
  const errors = error.errors;
43
44
  if (Array.isArray(errors)) {
44
45
  for (const item of errors) {
45
46
  const where = item.line != null ? ` (linha ${item.line}${item.column != null ? `, coluna ${item.column}` : ""})` : "";
46
- lines.push(` - ${item.stage ? `${item.stage}: ` : ""}${item.message ?? ""}${where}`);
47
+ lines.push(` - ${item.stage ? `${e(item.stage)}: ` : ""}${e(item.message ?? "")}${where}`);
47
48
  }
48
49
  }
49
50
  else if (errors && typeof errors === "object") {
50
51
  for (const [field, messages] of Object.entries(errors)) {
51
52
  for (const message of messages)
52
- lines.push(` - ${field}: ${message}`);
53
+ lines.push(` - ${e(field)}: ${e(message)}`);
53
54
  }
54
55
  }
55
56
  for (const item of error.variableErrors ?? []) {
56
- const name = item.name ?? item.field ?? "?";
57
- lines.push(` - variável ${name}: ${item.message ?? item.reason ?? item.code ?? "inválida"}`);
57
+ const name = e(item.name ?? item.field ?? "?");
58
+ lines.push(` - variável ${name}: ${e(item.message ?? item.reason ?? item.code ?? "inválida")}`);
58
59
  }
59
60
  if (error.traceId)
60
- lines.push(` trace_id: ${error.traceId}`);
61
+ lines.push(` trace_id: ${e(error.traceId)}`);
61
62
  return {
62
63
  exitCode: ExitCode.Failure,
63
64
  lines,
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "./errors.js";
2
+ import { escapeSlug } from "./format.js";
2
3
  export const ENVELOPE_VERSION = "pinga.template.v1";
3
4
  export const TEMPLATE_FILE = "template.json";
4
5
  /**
@@ -14,7 +15,9 @@ export function serialize(file) {
14
15
  return `${JSON.stringify(file, null, 2)}\n`;
15
16
  }
16
17
  /** Lê e confere o mínimo do envelope; o resto quem valida é a API. */
17
- export function parseTemplateFile(text, source) {
18
+ export function parseTemplateFile(text, rawSource) {
19
+ // O caminho vem do disco e pode ter ESC, bidi etc.: só sai escapado.
20
+ const source = escapeSlug(rawSource);
18
21
  let parsed;
19
22
  try {
20
23
  parsed = JSON.parse(text);
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.2.1";
2
+ export const VERSION = "0.2.2";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pinga-cli",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
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>",