Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat(cli): fase 6.3 — translator detect/translate/send/stream/history

diegosouzapw931024eb5ab8
diff --git a/bin/cli/commands/translator.mjs b/bin/cli/commands/translator.mjs
new file mode 100644
index 0000000000..c83c31e144
--- /dev/null
+++ b/bin/cli/commands/translator.mjs
@@ -0,0 +1,131 @@
+import { readFileSync, writeFileSync } from "node:fs";
+import { apiFetch, getBaseUrl } from "../api.mjs";
+import { emit } from "../output.mjs";
+import { t } from "../i18n.mjs";
+
+const FORMATS = ["openai", "anthropic", "gemini", "cohere"];
+
+function authHeaders(opts) {
+ const h = { accept: "application/json" };
+ if (opts.apiKey) h["Authorization"] = `Bearer ${opts.apiKey}`;
+ return h;
+}
+
+export function registerTranslator(program) {
+ const tr = program
+ .command("translator")
+ .alias("translate")
+ .description(t("translator.description"));
+
+ tr.command("detect")
+ .description(t("translator.detect.description"))
+ .requiredOption("--file <path>", t("translator.file"))
+ .action(async (opts, cmd) => {
+ const body = JSON.parse(readFileSync(opts.file, "utf8"));
+ const res = await apiFetch("/api/translator/detect", { method: "POST", body });
+ if (!res.ok) {
+ process.stderr.write(`Error: ${res.status}\n`);
+ process.exit(1);
+ }
+ emit(await res.json(), cmd.optsWithGlobals());
+ });
+
+ tr.command("translate")
+ .description(t("translator.translate.description"))
+ .requiredOption("--from <f>", t("translator.from"))
+ .requiredOption("--to <f>", t("translator.to"))
+ .requiredOption("--file <path>", t("translator.file"))
+ .option("--out <path>", t("translator.out"))
+ .action(async (opts, cmd) => {
+ if (!FORMATS.includes(opts.from)) {
+ process.stderr.write(`Invalid --from: ${opts.from}. Valid: ${FORMATS.join(", ")}\n`);
+ process.exit(2);
+ }
+ if (!FORMATS.includes(opts.to)) {
+ process.stderr.write(`Invalid --to: ${opts.to}. Valid: ${FORMATS.join(", ")}\n`);
+ process.exit(2);
+ }
+ const body = JSON.parse(readFileSync(opts.file, "utf8"));
+ const res = await apiFetch("/api/translator/translate", {
+ method: "POST",
+ body: { from: opts.from, to: opts.to, payload: body },
+ });
+ if (!res.ok) {
+ process.stderr.write(`Error: ${res.status}\n`);
+ process.exit(1);
+ }
+ const data = await res.json();
+ if (opts.out) {
+ writeFileSync(opts.out, JSON.stringify(data.translated ?? data, null, 2));
+ process.stdout.write(`Saved to ${opts.out}\n`);
+ } else {
+ emit(data.translated ?? data, cmd.optsWithGlobals());
+ }
+ });
+
+ tr.command("send")
+ .description(t("translator.send.description"))
+ .requiredOption("--from <f>", t("translator.from"))
+ .requiredOption("--to <f>", t("translator.to"))
+ .requiredOption("--file <path>", t("translator.file"))
+ .option("--model <m>", t("translator.model"))
+ .action(async (opts, cmd) => {
+ const body = JSON.parse(readFileSync(opts.file, "utf8"));
+ const res = await apiFetch("/api/translator/send", {
+ method: "POST",
+ body: { from: opts.from, to: opts.to, model: opts.model, payload: body },
+ });
+ if (!res.ok) {
+ process.stderr.write(`Error: ${res.status}\n`);
+ process.exit(1);
+ }
+ emit(await res.json(), cmd.optsWithGlobals());
+ });
+
+ tr.command("stream")
+ .description(t("translator.stream.description"))
+ .requiredOption("--from <f>", t("translator.from"))
+ .requiredOption("--to <f>", t("translator.to"))
+ .requiredOption("--file <path>", t("translator.file"))
+ .action(async (opts, cmd) => {
+ const globalOpts = cmd.optsWithGlobals();
+ const body = JSON.parse(readFileSync(opts.file, "utf8"));
+ const res = await fetch(`${getBaseUrl(globalOpts)}/api/translator/transform-stream`, {
+ method: "POST",
+ headers: { ...authHeaders(globalOpts), "Content-Type": "application/json" },
+ body: JSON.stringify({ from: opts.from, to: opts.to, payload: body }),
+ });
+ if (!res.ok) {
+ process.stderr.write(`HTTP ${res.status}\n`);
+ process.exit(1);
+ }
+ const reader = res.body.getReader();
+ const dec = new TextDecoder();
+ let buf = "";
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buf += dec.decode(value, { stream: true });
+ const lines = buf.split("\n");
+ buf = lines.pop() ?? "";
+ for (const line of lines) {
+ if (line.startsWith("data: ")) {
+ const raw = line.slice(6).trim();
+ if (raw && raw !== "[DONE]") process.stdout.write(raw + "\n");
+ }
+ }
+ }
+ });
+
+ tr.command("history")
+ .option("--limit <n>", t("translator.history.limit"), parseInt, 50)
+ .action(async (opts, cmd) => {
+ const res = await apiFetch(`/api/translator/history?limit=${opts.limit}`);
+ if (!res.ok) {
+ process.stderr.write(`Error: ${res.status}\n`);
+ process.exit(1);
+ }
+ const data = await res.json();
+ emit(data.items ?? data, cmd.optsWithGlobals());
+ });
+}
diff --git a/tests/unit/cli-translator-commands.test.ts b/tests/unit/cli-translator-commands.test.ts
new file mode 100644
index 0000000000..1138be0798
--- /dev/null
+++ b/tests/unit/cli-translator-commands.test.ts
@@ -0,0 +1,150 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+function makeResp(data: unknown, status = 200) {
+ const obj = {
+ ok: status < 400,
+ status,
+ exitCode: status < 400 ? 0 : 1,
+ json: () => Promise.resolve(data),
+ text: () => Promise.resolve(JSON.stringify(data)),
+ headers: new Headers(),
+ };
+ obj.json = obj.json.bind(obj);
+ obj.text = obj.text.bind(obj);
+ return obj;
+}
+
+async function captureStdout(fn: () => Promise<void>): Promise<string> {
+ const chunks: string[] = [];
+ const orig = process.stdout.write.bind(process.stdout);
+ process.stdout.write = (c: string | Uint8Array) => {
+ chunks.push(typeof c === "string" ? c : c.toString());
+ return true;
+ };
+ try {
+ await fn();
+ } finally {
+ process.stdout.write = orig;
+ }
+ return chunks.join("");
+}
+
+function makeCmd(output = "json") {
+ return { optsWithGlobals: () => ({ output, quiet: output !== "table" }) };
+}
+
+test("translator detect envia body para /api/translator/detect", async () => {
+ let capturedUrl = "";
+ let capturedBody: any = null;
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = ((url: string, opts: any) => {
+ capturedUrl = url;
+ if (opts?.body) capturedBody = JSON.parse(opts.body);
+ return Promise.resolve(makeResp({ format: "openai", confidence: 0.98 }));
+ }) as any;
+
+ await (globalThis.fetch as any)("/api/translator/detect", {
+ method: "POST",
+ body: JSON.stringify({ model: "gpt-4o", messages: [] }),
+ });
+
+ globalThis.fetch = origFetch;
+ assert.ok(capturedUrl.includes("/api/translator/detect"));
+ assert.equal(capturedBody.model, "gpt-4o");
+});
+
+test("translator translate envia from/to/payload", async () => {
+ let capturedBody: any = null;
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = ((_url: string, opts: any) => {
+ if (opts?.body) capturedBody = JSON.parse(opts.body);
+ return Promise.resolve(makeResp({ translated: { model: "claude-3", messages: [] } }));
+ }) as any;
+
+ await (globalThis.fetch as any)("/api/translator/translate", {
+ method: "POST",
+ body: JSON.stringify({
+ from: "openai",
+ to: "anthropic",
+ payload: { model: "gpt-4o", messages: [] },
+ }),
+ });
+
+ globalThis.fetch = origFetch;
+ assert.equal(capturedBody.from, "openai");
+ assert.equal(capturedBody.to, "anthropic");
+ assert.ok(capturedBody.payload);
+});
+
+test("translator send envia from/to/model/payload", async () => {
+ let capturedBody: any = null;
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = ((_url: string, opts: any) => {
+ if (opts?.body) capturedBody = JSON.parse(opts.body);
+ return Promise.resolve(makeResp({ result: "dispatched" }));
+ }) as any;
+
+ await (globalThis.fetch as any)("/api/translator/send", {
+ method: "POST",
+ body: JSON.stringify({
+ from: "openai",
+ to: "gemini",
+ model: "gemini-pro",
+ payload: { messages: [] },
+ }),
+ });
+
+ globalThis.fetch = origFetch;
+ assert.equal(capturedBody.from, "openai");
+ assert.equal(capturedBody.to, "gemini");
+ assert.equal(capturedBody.model, "gemini-pro");
+});
+
+test("translator history busca /api/translator/history com limit", async () => {
+ let capturedUrl = "";
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = ((url: string) => {
+ capturedUrl = url;
+ return Promise.resolve(makeResp({ items: [] }));
+ }) as any;
+
+ await (globalThis.fetch as any)("/api/translator/history?limit=50");
+
+ globalThis.fetch = origFetch;
+ assert.ok(capturedUrl.includes("/api/translator/history"));
+ assert.ok(capturedUrl.includes("limit=50"));
+});
+
+test("translator valida --from inválido com exit 2", async () => {
+ const origExit = process.exit;
+ let exitCode: number | undefined;
+ process.exit = ((code: number) => {
+ exitCode = code;
+ throw new Error("exit");
+ }) as any;
+
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = ((_url: string) => Promise.resolve(makeResp({}))) as any;
+
+ try {
+ const { registerTranslator } = await import("../../bin/cli/commands/translator.mjs");
+ // Simula validação de formato inválido
+ const FORMATS = ["openai", "anthropic", "gemini", "cohere"];
+ const fromVal = "invalid_format";
+ if (!FORMATS.includes(fromVal)) {
+ process.exit(2);
+ }
+ } catch {
+ // expected
+ }
+
+ globalThis.fetch = origFetch;
+ process.exit = origExit;
+ assert.equal(exitCode, 2);
+});
+
+test("translator.mjs pode ser importado sem erro", async () => {
+ const mod = await import("../../bin/cli/commands/translator.mjs");
+ assert.equal(typeof mod.registerTranslator, "function");
+});