@batadata/cli 0.1.2 → 0.1.3

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/dist/api.js CHANGED
@@ -14,7 +14,7 @@ export async function request(method, path, options = {}) {
14
14
  }
15
15
  const headers = {
16
16
  "Content-Type": "application/json",
17
- "User-Agent": "@batadata/cli 0.1.2",
17
+ "User-Agent": "@batadata/cli 0.1.3",
18
18
  };
19
19
  if (options.token) {
20
20
  headers["Authorization"] = `Bearer ${options.token}`;
@@ -4,5 +4,5 @@ export declare function branches(): Promise<void>;
4
4
  export declare function branchCreate(name?: string): Promise<void>;
5
5
  export declare function branchDelete(name?: string): Promise<void>;
6
6
  export declare function studio(): Promise<void>;
7
- export declare function query(sql?: string): Promise<void>;
7
+ export declare function query(args?: string[]): Promise<void>;
8
8
  export declare function handleDb(args: string[]): Promise<void>;
@@ -4,7 +4,7 @@ import { requireToken, loadConfig, isJsonMode } from "../config.js";
4
4
  import { colors, log, json, error, spinner, table, heading, info as logInfo } from "../utils/logger.js";
5
5
  import { prompt, confirmDestructive } from "../utils/prompts.js";
6
6
  import { openBrowser } from "../utils/open.js";
7
- import { emitError } from "../utils/errors.js";
7
+ import { emitError, isRetryable } from "../utils/errors.js";
8
8
  async function getConnectionInfo(projectId, token) {
9
9
  // reveal=true so the returned string is actually usable (the owner is asking).
10
10
  const res = await api.get(`/v1/connection-info/${projectId}`, token, { reveal: "true" });
@@ -30,6 +30,17 @@ function formatDate(iso) {
30
30
  const d = new Date(iso);
31
31
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
32
32
  }
33
+ /**
34
+ * Human-readable STATUS cell for a branch. Prefers the live compute lifecycle
35
+ * (computeStatus) over the static branch row status, and appends a green check
36
+ * when the compute is ready to serve a query without a cold start.
37
+ */
38
+ function branchStatusLabel(b) {
39
+ const base = b.computeStatus || b.status || "-";
40
+ if (b.ready === true)
41
+ return `${base} ${colors.green("✓")}`;
42
+ return base;
43
+ }
33
44
  /**
34
45
  * Resolve a project's primary branch (the one to run a query against). Lists
35
46
  * branches the same way `db branches` does (GET /v1/projects/:id) and returns
@@ -133,6 +144,10 @@ export async function branches() {
133
144
  name: b.name,
134
145
  is_primary: b.is_primary,
135
146
  status: b.status,
147
+ // Compute readiness — what agents poll on between a create/cold start
148
+ // and a successful query.
149
+ computeStatus: b.computeStatus ?? null,
150
+ ready: b.ready ?? null,
136
151
  created_at: b.created_at,
137
152
  })),
138
153
  count: branchList.length,
@@ -148,7 +163,9 @@ export async function branches() {
148
163
  table(["NAME", "PRIMARY", "STATUS", "CREATED"], branchList.map((b) => [
149
164
  b.name,
150
165
  b.is_primary ? colors.green("yes") : "-",
151
- b.status || "-",
166
+ // Prefer the live compute lifecycle (computeStatus); fall back to the
167
+ // branch row status. Mark ready with a check so the column is scannable.
168
+ branchStatusLabel(b),
152
169
  formatDate(b.created_at),
153
170
  ]));
154
171
  log();
@@ -257,8 +274,33 @@ export async function studio() {
257
274
  log();
258
275
  openBrowser(studioUrl);
259
276
  }
260
- export async function query(sql) {
277
+ /**
278
+ * Pull a `--branch <id>` / `--branch=<id>` flag out of the query args and return
279
+ * the explicit branch id (if any) plus the remaining args, which join into the
280
+ * SQL string. Keeps `db query` order-independent (the flag can sit before or
281
+ * after the SQL) and consistent with how global flags are parsed.
282
+ */
283
+ function parseBranchFlag(args) {
284
+ let branchId;
285
+ const rest = [];
286
+ for (let i = 0; i < args.length; i++) {
287
+ const arg = args[i];
288
+ if (arg === "--branch") {
289
+ branchId = args[++i];
290
+ }
291
+ else if (arg.startsWith("--branch=")) {
292
+ branchId = arg.slice("--branch=".length);
293
+ }
294
+ else {
295
+ rest.push(arg);
296
+ }
297
+ }
298
+ return { branchId, rest };
299
+ }
300
+ export async function query(args = []) {
261
301
  const jsonMode = isJsonMode();
302
+ const { branchId, rest } = parseBranchFlag(args);
303
+ const sql = rest.join(" ").trim();
262
304
  if (!sql) {
263
305
  emitError("MISSING_ARG", "SQL query is required.", 'Usage: bata db query "SELECT 1"');
264
306
  }
@@ -269,19 +311,30 @@ export async function query(sql) {
269
311
  emitError("NO_PROJECT", "No default project set.", "Set one with: bata projects info <id>");
270
312
  }
271
313
  const s = jsonMode ? null : spinner("Running query");
272
- // Resolve the primary branch /v1/sql/execute is keyed on branch_id, not
314
+ // Target branch: an explicit --branch <id> wins; otherwise resolve the
315
+ // project's primary branch. /v1/sql/execute is keyed on branch_id, not
273
316
  // project. (The old code POSTed to /v1/query/:projectId, which 404s.)
274
- const branch = await getPrimaryBranch(projectId, token, config.defaultTeam);
275
- if (!branch) {
276
- s?.stop();
277
- emitError("BRANCH_NOT_FOUND", "No branch found for this project to run the query against.", "Check the project with: bata db branches --json");
317
+ let branchId_ = branchId;
318
+ if (!branchId_) {
319
+ const branch = await getPrimaryBranch(projectId, token, config.defaultTeam);
320
+ if (!branch) {
321
+ s?.stop();
322
+ emitError("BRANCH_NOT_FOUND", "No branch found for this project to run the query against.", "Check the project with: bata db branches --json");
323
+ }
324
+ branchId_ = branch.id;
278
325
  }
279
- const res = await api.post("/v1/sql/execute", { branch_id: branch.id, query: sql }, token);
326
+ const res = await api.post("/v1/sql/execute", { branch_id: branchId_, query: sql }, token);
280
327
  s?.stop();
281
328
  if (!res.ok) {
282
- const code = res.status === 401 || res.status === 403 ? "INVALID_KEY"
283
- : res.status >= 500 || res.status === 0 ? "API_UNAVAILABLE"
284
- : "CLI_ERROR";
329
+ // Cold-start / upstream blips are retryable (exit 6) so an agent backs off
330
+ // and retries instead of treating it as a hard CLI bug. The backend returns
331
+ // 503 + { code: "COMPUTE_STARTING" } while a just-created/idle branch's
332
+ // compute is still waking; connection-refused transients land here too.
333
+ const body = res.data;
334
+ if (isRetryable({ status: res.status, code: body?.code, message: body?.error })) {
335
+ emitError("COMPUTE_STARTING", apiError(res, "Compute is starting"), "compute is starting; retry in a few seconds");
336
+ }
337
+ const code = res.status === 401 || res.status === 403 ? "INVALID_KEY" : "CLI_ERROR";
285
338
  emitError(code, apiError(res, "Query failed"), "");
286
339
  }
287
340
  // The endpoint returns 200 even when the SQL itself errored (it executed and
@@ -330,8 +383,85 @@ function fmtCell(v) {
330
383
  return JSON.stringify(v);
331
384
  return String(v);
332
385
  }
386
+ /** Was a `--help` / `-h` flag passed anywhere in the args? */
387
+ function hasHelpFlag(args) {
388
+ return args.some((a) => a === "--help" || a === "-h");
389
+ }
390
+ /**
391
+ * Print usage for a `db` subcommand (or general `db` help if none/unknown) and
392
+ * return. Pure stdout — NEVER touches the network. `db query --help` must print
393
+ * this, not run the SQL "--help".
394
+ */
395
+ function dbHelp(sub) {
396
+ const usage = (line) => log(` ${colors.cyan(line)}`);
397
+ const note = (line) => log(` ${colors.dim(line)}`);
398
+ log();
399
+ switch (sub) {
400
+ case "query":
401
+ log(` ${colors.bold("bata db query")} — run a SQL query against a branch`);
402
+ log();
403
+ usage('bata db query "SELECT 1"');
404
+ usage("bata db query <sql> [--branch <branch_id>] [--json]");
405
+ log();
406
+ note("--branch <branch_id> Target a specific branch (default: the project's primary)");
407
+ note("--json Emit rows as JSON objects + row_count");
408
+ note("Cold-start note: a just-created/idle branch may answer with exit 6");
409
+ note("(retryable) while its compute wakes — retry in a few seconds.");
410
+ break;
411
+ case "branches":
412
+ log(` ${colors.bold("bata db branches")} — list branches and their compute status`);
413
+ log();
414
+ usage("bata db branches [--json]");
415
+ log();
416
+ note("STATUS shows the live compute state; a ✓ means ready to query.");
417
+ note("--json includes computeStatus + ready — poll these after create/cold start.");
418
+ break;
419
+ case "branch":
420
+ log(` ${colors.bold("bata db branch")} — create or delete a branch`);
421
+ log();
422
+ usage("bata db branch create <name>");
423
+ usage("bata db branch delete <name> [--yes]");
424
+ break;
425
+ case "url":
426
+ log(` ${colors.bold("bata db url")} — print the connection string`);
427
+ log();
428
+ usage("bata db url [--json]");
429
+ break;
430
+ case "connect":
431
+ log(` ${colors.bold("bata db connect")} — open an interactive psql session`);
432
+ log();
433
+ usage("bata db connect");
434
+ note("Interactive only — use `bata db query` / `bata db url` headlessly.");
435
+ break;
436
+ case "studio":
437
+ log(` ${colors.bold("bata db studio")} — open the table browser in your browser`);
438
+ log();
439
+ usage("bata db studio");
440
+ break;
441
+ default:
442
+ log(` ${colors.bold("bata db")} — database commands`);
443
+ log();
444
+ usage("bata db connect Open psql to your database");
445
+ usage("bata db url Print connection string");
446
+ usage("bata db branches List branches + compute status");
447
+ usage("bata db branch create Create a new branch");
448
+ usage("bata db branch delete Delete a branch");
449
+ usage("bata db studio Open the table browser");
450
+ usage("bata db query <sql> Run a SQL query (--branch <id> to target a branch)");
451
+ log();
452
+ note("Add --help to any subcommand for details (e.g. bata db query --help).");
453
+ }
454
+ log();
455
+ }
333
456
  export async function handleDb(args) {
334
457
  const sub = args[0];
458
+ // A --help / -h anywhere prints usage for the subcommand and exits 0 WITHOUT
459
+ // any network call. This must run before dispatch so `db query --help` never
460
+ // treats "--help" as SQL and hits /v1/sql/execute.
461
+ if (hasHelpFlag(args)) {
462
+ dbHelp(sub);
463
+ return;
464
+ }
335
465
  switch (sub) {
336
466
  case "connect":
337
467
  return connect();
@@ -350,7 +480,7 @@ export async function handleDb(args) {
350
480
  case "studio":
351
481
  return studio();
352
482
  case "query":
353
- return query(args.slice(1).join(" "));
483
+ return query(args.slice(1));
354
484
  default:
355
485
  emitError("INVALID_FLAG", `Unknown subcommand: db ${sub || ""}`, "Available: connect, url, branches, branch, studio, query");
356
486
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,173 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+ const { get, post } = vi.hoisted(() => ({
6
+ get: vi.fn(async () => ({
7
+ ok: true,
8
+ status: 200,
9
+ data: { id: "proj_1", name: "demo", branches: [{ id: "br_primary", name: "main", is_primary: true, status: "ready" }] },
10
+ })),
11
+ post: vi.fn(async () => ({ ok: true, status: 200, data: { columns: ["n"], rows: [{ n: "1" }], rowCount: 1 } })),
12
+ }));
13
+ vi.mock("../api.js", () => ({
14
+ api: { get, post, del: vi.fn() },
15
+ resolveTeamId: vi.fn(async () => "team_test"),
16
+ // Mirror the real apiError so retryable mapping (which reads the server code)
17
+ // gets a realistic message; we don't need its exact format here.
18
+ apiError: (res, fallback) => {
19
+ const msg = res?.data?.error ?? fallback;
20
+ const code = res?.data?.code ? ` (${res.data.code})` : "";
21
+ return `${msg}${code}`;
22
+ },
23
+ asList: (data) => (Array.isArray(data) ? data : []),
24
+ }));
25
+ import { query, handleDb } from "./db.js";
26
+ import { setRuntime } from "../config.js";
27
+ let tmpHome;
28
+ let logSpy;
29
+ // process.exit must NOT actually exit the test runner. Throw a tagged error so
30
+ // the handler unwinds at the exit point; tests catch it and read the code.
31
+ class ExitError extends Error {
32
+ code;
33
+ constructor(code) {
34
+ super(`exit ${code}`);
35
+ this.code = code;
36
+ }
37
+ }
38
+ beforeEach(() => {
39
+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "bata-cli-db-test-"));
40
+ vi.stubEnv("HOME", tmpHome);
41
+ vi.stubEnv("USERPROFILE", tmpHome);
42
+ // A real credential + a default project so query() reaches the network seam.
43
+ fs.writeFileSync(path.join(tmpHome, ".batarc"), JSON.stringify({ defaultProject: "proj_1" }));
44
+ setRuntime({ apiKey: "test-token", apiUrl: "https://api.test.local", json: true, yes: false });
45
+ get.mockClear();
46
+ post.mockClear();
47
+ vi.spyOn(process, "exit").mockImplementation(((code) => {
48
+ throw new ExitError(code ?? 0);
49
+ }));
50
+ // Silence the JSON/decorative output so test logs stay clean.
51
+ logSpy = vi.spyOn(console, "log").mockImplementation(() => { });
52
+ vi.spyOn(console, "error").mockImplementation(() => { });
53
+ });
54
+ afterEach(() => {
55
+ vi.unstubAllEnvs();
56
+ vi.restoreAllMocks();
57
+ setRuntime({ json: false, yes: false });
58
+ fs.rmSync(tmpHome, { recursive: true, force: true });
59
+ });
60
+ /** Run a handler that's expected to call process.exit; return the exit code. */
61
+ async function exitCodeOf(run) {
62
+ try {
63
+ await run();
64
+ }
65
+ catch (e) {
66
+ if (e instanceof ExitError)
67
+ return e.code;
68
+ throw e;
69
+ }
70
+ return 0; // handler returned without exiting (success path)
71
+ }
72
+ describe("db query — --help short-circuits before any network call", () => {
73
+ it("`db query --help` prints help and makes NO api call (exit 0)", async () => {
74
+ const code = await exitCodeOf(() => handleDb(["query", "--help"]));
75
+ expect(post).not.toHaveBeenCalled();
76
+ expect(get).not.toHaveBeenCalled();
77
+ expect(code).toBe(0);
78
+ // It actually printed usage, not a row result.
79
+ const printed = logSpy.mock.calls.map((c) => String(c[0])).join("\n");
80
+ expect(printed).toContain("bata db query");
81
+ expect(printed).toContain("--branch");
82
+ });
83
+ it("`db query -h` (short flag) also short-circuits with no api call", async () => {
84
+ const code = await exitCodeOf(() => handleDb(["query", "-h"]));
85
+ expect(post).not.toHaveBeenCalled();
86
+ expect(get).not.toHaveBeenCalled();
87
+ expect(code).toBe(0);
88
+ });
89
+ it("`db --help` prints general db help with no api call", async () => {
90
+ const code = await exitCodeOf(() => handleDb(["--help"]));
91
+ expect(post).not.toHaveBeenCalled();
92
+ expect(get).not.toHaveBeenCalled();
93
+ expect(code).toBe(0);
94
+ });
95
+ });
96
+ describe("db query — branch targeting", () => {
97
+ it("--branch <id> sets branch_id in the request body and skips primary lookup", async () => {
98
+ await exitCodeOf(() => query(["SELECT 1", "--branch", "br_explicit"]));
99
+ expect(post).toHaveBeenCalledTimes(1);
100
+ expect(post).toHaveBeenCalledWith("/v1/sql/execute", expect.objectContaining({ branch_id: "br_explicit", query: "SELECT 1" }), "test-token");
101
+ // Explicit branch → no need to resolve the primary.
102
+ expect(get).not.toHaveBeenCalled();
103
+ });
104
+ it("--branch=<id> (equals form) is also honored", async () => {
105
+ await exitCodeOf(() => query(["--branch=br_eq", "SELECT 2"]));
106
+ expect(post).toHaveBeenCalledWith("/v1/sql/execute", expect.objectContaining({ branch_id: "br_eq", query: "SELECT 2" }), "test-token");
107
+ });
108
+ it("without --branch, resolves the project's primary branch (default behavior)", async () => {
109
+ await exitCodeOf(() => query(["SELECT 1"]));
110
+ expect(get).toHaveBeenCalledTimes(1); // resolved primary
111
+ expect(post).toHaveBeenCalledWith("/v1/sql/execute", expect.objectContaining({ branch_id: "br_primary", query: "SELECT 1" }), "test-token");
112
+ });
113
+ });
114
+ describe("db query — retryable cold-start mapping (exit 6)", () => {
115
+ it("503 + { code: COMPUTE_STARTING } maps to exit 6 (retryable), not 1", async () => {
116
+ post.mockResolvedValueOnce({
117
+ ok: false,
118
+ status: 503,
119
+ data: { error: "compute is starting", code: "COMPUTE_STARTING" },
120
+ });
121
+ const code = await exitCodeOf(() => query(["SELECT 1", "--branch", "br_cold"]));
122
+ expect(code).toBe(6);
123
+ });
124
+ it("REGRESSION GUARD: a non-5xx status carrying { code: COMPUTE_STARTING } still maps to exit 6", async () => {
125
+ // The pre-fix code only looked at the HTTP status (>=500 || 0), so a
126
+ // COMPUTE_STARTING surfaced on, say, a 425 would have been CLI_ERROR (exit
127
+ // 1). This is the exact guard for the body-code inspection.
128
+ post.mockResolvedValueOnce({
129
+ ok: false,
130
+ status: 425,
131
+ data: { error: "compute is starting", code: "COMPUTE_STARTING" },
132
+ });
133
+ const code = await exitCodeOf(() => query(["SELECT 1", "--branch", "br_cold"]));
134
+ expect(code).toBe(6);
135
+ });
136
+ it("a connection-refused error body maps to exit 6", async () => {
137
+ post.mockResolvedValueOnce({
138
+ ok: false,
139
+ status: 0,
140
+ data: { error: "connect ECONNREFUSED 127.0.0.1:5432" },
141
+ });
142
+ const code = await exitCodeOf(() => query(["SELECT 1", "--branch", "br_cold"]));
143
+ expect(code).toBe(6);
144
+ });
145
+ it("a generic 5xx maps to exit 6", async () => {
146
+ post.mockResolvedValueOnce({ ok: false, status: 502, data: { error: "bad gateway" } });
147
+ const code = await exitCodeOf(() => query(["SELECT 1", "--branch", "br_cold"]));
148
+ expect(code).toBe(6);
149
+ });
150
+ it("a genuine SQL syntax error (200 with error field) stays exit 1, NOT retryable", async () => {
151
+ post.mockResolvedValueOnce({
152
+ ok: true,
153
+ status: 200,
154
+ data: { error: 'syntax error at or near "SELCT"' },
155
+ });
156
+ const code = await exitCodeOf(() => query(["SELCT 1", "--branch", "br_ok"]));
157
+ expect(code).toBe(1);
158
+ });
159
+ it("a 400 bad-input SQL error stays exit 1, NOT retryable", async () => {
160
+ post.mockResolvedValueOnce({
161
+ ok: false,
162
+ status: 400,
163
+ data: { error: "relation does not exist" },
164
+ });
165
+ const code = await exitCodeOf(() => query(["SELECT * FROM nope", "--branch", "br_ok"]));
166
+ expect(code).toBe(1);
167
+ });
168
+ it("a 401 stays auth (exit 4), not retryable", async () => {
169
+ post.mockResolvedValueOnce({ ok: false, status: 401, data: { error: "invalid key" } });
170
+ const code = await exitCodeOf(() => query(["SELECT 1", "--branch", "br_ok"]));
171
+ expect(code).toBe(4);
172
+ });
173
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,104 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+ // --- Mock the network layer so no real HTTP happens and we can assert that the
6
+ // --- DELETE call is (or isn't) invoked. This is the seam: deleteProject() calls
7
+ // --- `api.del(...)`, so a spy here proves whether the delete actually proceeds.
8
+ // `vi.hoisted` so the spy exists before the hoisted vi.mock factory runs.
9
+ const { del, readlineQuestion } = vi.hoisted(() => ({
10
+ del: vi.fn(async () => ({ ok: true, status: 200, data: {} })),
11
+ // The interactive prompt seam: confirm() -> prompt() -> readline.question().
12
+ // Default answer is empty; a TTY test sets it to "n" to decline.
13
+ readlineQuestion: vi.fn((_q, cb) => cb("")),
14
+ }));
15
+ vi.mock("../api.js", () => ({
16
+ api: {
17
+ get: vi.fn(async () => ({ ok: true, status: 200, data: {} })),
18
+ post: vi.fn(async () => ({ ok: true, status: 200, data: {} })),
19
+ del,
20
+ },
21
+ // No real /v1/teams round-trip; deleteProject only needs an optional team id.
22
+ resolveTeamId: vi.fn(async () => "team_test"),
23
+ apiError: (_res, fallback) => fallback,
24
+ asList: (data) => (Array.isArray(data) ? data : []),
25
+ }));
26
+ // Mock readline so the interactive confirm() branch never blocks on real stdin.
27
+ vi.mock("node:readline", () => ({
28
+ default: { createInterface: () => ({ question: readlineQuestion, close: () => { } }) },
29
+ createInterface: () => ({ question: readlineQuestion, close: () => { } }),
30
+ }));
31
+ // We deliberately do NOT mock ../config.js or ../utils/prompts.js — the whole
32
+ // point of this test is to exercise the REAL confirmDestructive() + the REAL
33
+ // runtime flag plumbing (setRuntime/isYes/isJsonMode), since that branch is the
34
+ // destructive-headless contract under test.
35
+ import { deleteProject } from "./projects.js";
36
+ import { setRuntime } from "../config.js";
37
+ let tmpHome;
38
+ let realIsTTY;
39
+ beforeEach(() => {
40
+ // Point ~/.batarc at a throwaway HOME so loadConfig/saveConfig never touch the
41
+ // developer's real config. os.homedir() reads HOME at call time (verified).
42
+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "bata-cli-test-"));
43
+ vi.stubEnv("HOME", tmpHome);
44
+ vi.stubEnv("USERPROFILE", tmpHome); // Windows parity
45
+ // requireToken() resolves the --api-key runtime value first, so a real
46
+ // credential exists without writing a config file.
47
+ setRuntime({ apiKey: "test-token", apiUrl: "https://api.test.local", json: false, yes: false });
48
+ del.mockClear();
49
+ readlineQuestion.mockClear();
50
+ readlineQuestion.mockImplementation((_q, cb) => cb(""));
51
+ // Snapshot isTTY so individual tests can override it and we restore after.
52
+ realIsTTY = Object.getOwnPropertyDescriptor(process.stdin, "isTTY");
53
+ });
54
+ afterEach(() => {
55
+ vi.unstubAllEnvs();
56
+ vi.restoreAllMocks();
57
+ setRuntime({ json: false, yes: false });
58
+ if (realIsTTY) {
59
+ Object.defineProperty(process.stdin, "isTTY", realIsTTY);
60
+ }
61
+ fs.rmSync(tmpHome, { recursive: true, force: true });
62
+ });
63
+ function setTTY(value) {
64
+ Object.defineProperty(process.stdin, "isTTY", { value, configurable: true });
65
+ }
66
+ describe("projects delete — destructive headless contract", () => {
67
+ it("REGRESSION GUARD: with --yes, does NOT prompt and the DELETE actually proceeds", async () => {
68
+ // The original bug: headless `--yes` exited 0 having deleted NOTHING.
69
+ // This is the exact guard — if deleteProject silently skipped the delete,
70
+ // `del` would never be called and this expectation would fail.
71
+ setTTY(true); // even on a TTY, --yes must skip the prompt and proceed
72
+ setRuntime({ yes: true });
73
+ await deleteProject("proj_123");
74
+ expect(del).toHaveBeenCalledTimes(1);
75
+ expect(del).toHaveBeenCalledWith("/v1/projects/proj_123", "test-token", expect.objectContaining({ team_id: "team_test" }));
76
+ });
77
+ it("in --json mode, proceeds without prompting and deletes", async () => {
78
+ setTTY(true);
79
+ setRuntime({ json: true });
80
+ await deleteProject("proj_json");
81
+ expect(del).toHaveBeenCalledTimes(1);
82
+ expect(del).toHaveBeenCalledWith("/v1/projects/proj_json", "test-token", expect.anything());
83
+ });
84
+ it("when stdin is not a TTY (agent / piped / CI), proceeds and deletes without --yes", async () => {
85
+ // This is the CLI's whole purpose: unattended deletes must go through.
86
+ setTTY(false);
87
+ setRuntime({ yes: false, json: false });
88
+ await deleteProject("proj_pipe");
89
+ expect(del).toHaveBeenCalledTimes(1);
90
+ expect(del).toHaveBeenCalledWith("/v1/projects/proj_pipe", "test-token", expect.anything());
91
+ });
92
+ it("interactive TTY without --yes WOULD prompt; answering no aborts (no DELETE)", async () => {
93
+ // Covers the interactive branch of confirmDestructive(): it must ask, and a
94
+ // "no" answer must NOT call the delete API. The mocked readline (above) is
95
+ // the seam confirm() -> prompt() uses; we answer "n" to decline.
96
+ setTTY(true);
97
+ setRuntime({ yes: false, json: false });
98
+ readlineQuestion.mockImplementation((_q, cb) => cb("n"));
99
+ await deleteProject("proj_keep");
100
+ expect(readlineQuestion).toHaveBeenCalledTimes(1); // it DID prompt
101
+ expect(readlineQuestion.mock.calls[0][0]).toContain("Delete project");
102
+ expect(del).not.toHaveBeenCalled(); // declined → no destructive call
103
+ });
104
+ });
package/dist/index.js CHANGED
@@ -14,8 +14,8 @@ import { usage } from "./commands/usage.js";
14
14
  import { parseGlobalFlags } from "./args.js";
15
15
  import { isJsonMode } from "./config.js";
16
16
  import { colors, log, banner } from "./utils/logger.js";
17
- import { exitCodeFor } from "./utils/errors.js";
18
- const VERSION = "0.1.2";
17
+ import { exitCodeFor, isRetryable } from "./utils/errors.js";
18
+ const VERSION = "0.1.3";
19
19
  function help() {
20
20
  banner();
21
21
  log(` ${colors.bold("Usage")}`);
@@ -43,11 +43,11 @@ function help() {
43
43
  log(` ${colors.bold("Database")}`);
44
44
  log(` ${colors.cyan("db connect")} Open psql to your database`);
45
45
  log(` ${colors.cyan("db url")} Print connection string`);
46
- log(` ${colors.cyan("db branches")} List database branches`);
46
+ log(` ${colors.cyan("db branches")} List database branches ${colors.dim("(STATUS shows compute readiness)")}`);
47
47
  log(` ${colors.cyan("db branch create")} Create a new branch`);
48
48
  log(` ${colors.cyan("db branch delete")} Delete a branch`);
49
49
  log(` ${colors.cyan("db studio")} Open table browser in browser`);
50
- log(` ${colors.cyan("db query")} Run a SQL query`);
50
+ log(` ${colors.cyan("db query")} Run a SQL query ${colors.dim("(--branch <id> to target a branch)")}`);
51
51
  log();
52
52
  log(` ${colors.bold("Schema & Types")}`);
53
53
  log(` ${colors.cyan("generate")} Generate types from database schema`);
@@ -84,7 +84,7 @@ function help() {
84
84
  log(` ${colors.dim("3")} not implemented ${colors.dim("(NOT_IMPLEMENTED)")}`);
85
85
  log(` ${colors.dim("4")} auth / credentials ${colors.dim("(NO_CREDENTIALS, INVALID_KEY)")}`);
86
86
  log(` ${colors.dim("5")} not-found / bad input ${colors.dim("(NO_PROJECT, BRANCH_NOT_FOUND, INVALID_FLAG, INTERACTIVE_ONLY)")}`);
87
- log(` ${colors.dim("6")} upstream / transient ${colors.dim("(API_UNAVAILABLE, TIMEOUT — retryable)")}`);
87
+ log(` ${colors.dim("6")} upstream / transient ${colors.dim("(API_UNAVAILABLE, TIMEOUT, COMPUTE_STARTING — retryable)")}`);
88
88
  log();
89
89
  log(` ${colors.dim("Documentation:")} ${colors.cyan("https://www.npmjs.com/package/@batadata/cli")}`);
90
90
  log();
@@ -188,8 +188,11 @@ async function main() {
188
188
  // Network/transport throws (e.g. the request timed out, DNS/connection
189
189
  // refused) are upstream/transient — surface them with a retryable code so
190
190
  // agents know to back off rather than treating it as a hard CLI bug.
191
- const transient = /timed out|ECONNREFUSED|ENOTFOUND|ECONNRESET|EAI_AGAIN|socket hang up/i.test(message);
192
- const code = transient ? (/timed out/i.test(message) ? "TIMEOUT" : "API_UNAVAILABLE") : "CLI_ERROR";
191
+ const timedOut = /timed out/i.test(message);
192
+ const transient = timedOut
193
+ || /ENOTFOUND|ECONNRESET|EAI_AGAIN|socket hang up/i.test(message)
194
+ || isRetryable({ message });
195
+ const code = transient ? (timedOut ? "TIMEOUT" : "API_UNAVAILABLE") : "CLI_ERROR";
193
196
  if (isJsonMode()) {
194
197
  log(JSON.stringify({ error: message, code, hint: "" }, null, 2));
195
198
  }
@@ -13,9 +13,27 @@
13
13
  * 3 NOT_IMPLEMENTED (coming-soon command — never a silent no-op exit 0)
14
14
  * 4 auth / creds — NO_CREDENTIALS, INVALID_KEY
15
15
  * 5 not-found/bad-input — NO_PROJECT, BRANCH_NOT_FOUND, INVALID_FLAG, INTERACTIVE_ONLY, ...
16
- * 6 upstream/transient — API_UNAVAILABLE, TIMEOUT (retryable)
16
+ * 6 upstream/transient — API_UNAVAILABLE, TIMEOUT, COMPUTE_STARTING (retryable)
17
17
  */
18
- export type ErrorCode = "CLI_ERROR" | "NOT_IMPLEMENTED" | "NO_CREDENTIALS" | "INVALID_KEY" | "NO_PROJECT" | "BRANCH_NOT_FOUND" | "INVALID_FLAG" | "INTERACTIVE_ONLY" | "NO_TEAM" | "EMPTY_INPUT" | "FILE_NOT_FOUND" | "MISSING_ARG" | "NOT_FOUND" | "API_UNAVAILABLE" | "TIMEOUT" | "GATE_TRIPPED";
18
+ export type ErrorCode = "CLI_ERROR" | "NOT_IMPLEMENTED" | "NO_CREDENTIALS" | "INVALID_KEY" | "NO_PROJECT" | "BRANCH_NOT_FOUND" | "INVALID_FLAG" | "INTERACTIVE_ONLY" | "NO_TEAM" | "EMPTY_INPUT" | "FILE_NOT_FOUND" | "MISSING_ARG" | "NOT_FOUND" | "API_UNAVAILABLE" | "TIMEOUT" | "COMPUTE_STARTING" | "GATE_TRIPPED";
19
+ /**
20
+ * Decide whether a failed request is upstream/transient (retryable, exit 6)
21
+ * rather than a hard CLI error. An agent that sees exit 6 should back off and
22
+ * retry; exit 1 means "don't bother, it won't fix itself".
23
+ *
24
+ * Retryable signals:
25
+ * - HTTP 503 (compute waking up) or 0 (no response / connection refused)
26
+ * - HTTP >= 500 (any upstream blip)
27
+ * - an error `code` of COMPUTE_STARTING / API_UNAVAILABLE / TIMEOUT
28
+ * - a connection-refused / ECONNREFUSED transport message
29
+ *
30
+ * Genuine SQL errors (syntax, etc.) carry none of these and stay exit 1.
31
+ */
32
+ export declare function isRetryable(opts: {
33
+ status?: number;
34
+ code?: string;
35
+ message?: string;
36
+ }): boolean;
19
37
  /** Map an error code to its documented process exit code. */
20
38
  export declare function exitCodeFor(code: string): number;
21
39
  /**
@@ -13,10 +13,35 @@
13
13
  * 3 NOT_IMPLEMENTED (coming-soon command — never a silent no-op exit 0)
14
14
  * 4 auth / creds — NO_CREDENTIALS, INVALID_KEY
15
15
  * 5 not-found/bad-input — NO_PROJECT, BRANCH_NOT_FOUND, INVALID_FLAG, INTERACTIVE_ONLY, ...
16
- * 6 upstream/transient — API_UNAVAILABLE, TIMEOUT (retryable)
16
+ * 6 upstream/transient — API_UNAVAILABLE, TIMEOUT, COMPUTE_STARTING (retryable)
17
17
  */
18
18
  import { isJsonMode } from "../config.js";
19
19
  import { colors, log, json, error } from "./logger.js";
20
+ /**
21
+ * Decide whether a failed request is upstream/transient (retryable, exit 6)
22
+ * rather than a hard CLI error. An agent that sees exit 6 should back off and
23
+ * retry; exit 1 means "don't bother, it won't fix itself".
24
+ *
25
+ * Retryable signals:
26
+ * - HTTP 503 (compute waking up) or 0 (no response / connection refused)
27
+ * - HTTP >= 500 (any upstream blip)
28
+ * - an error `code` of COMPUTE_STARTING / API_UNAVAILABLE / TIMEOUT
29
+ * - a connection-refused / ECONNREFUSED transport message
30
+ *
31
+ * Genuine SQL errors (syntax, etc.) carry none of these and stay exit 1.
32
+ */
33
+ export function isRetryable(opts) {
34
+ const { status, code, message } = opts;
35
+ if (status === 503 || status === 0)
36
+ return true;
37
+ if (typeof status === "number" && status >= 500)
38
+ return true;
39
+ if (code === "COMPUTE_STARTING" || code === "API_UNAVAILABLE" || code === "TIMEOUT")
40
+ return true;
41
+ if (message && /ECONNREFUSED|connection refused/i.test(message))
42
+ return true;
43
+ return false;
44
+ }
20
45
  /** Map an error code to its documented process exit code. */
21
46
  export function exitCodeFor(code) {
22
47
  switch (code) {
@@ -37,6 +62,7 @@ export function exitCodeFor(code) {
37
62
  return 5;
38
63
  case "API_UNAVAILABLE":
39
64
  case "TIMEOUT":
65
+ case "COMPUTE_STARTING":
40
66
  return 6;
41
67
  case "GATE_TRIPPED":
42
68
  return 2;
@@ -124,6 +124,6 @@ export function kvList(items) {
124
124
  // Banner
125
125
  export function banner() {
126
126
  log();
127
- log(` ${colors.cyan(colors.bold("BataDB"))} ${colors.dim("v0.1.2")} ${colors.dim("— serverless Postgres platform")}`);
127
+ log(` ${colors.cyan(colors.bold("BataDB"))} ${colors.dim("v0.1.3")} ${colors.dim("— serverless Postgres platform")}`);
128
128
  log();
129
129
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@batadata/cli",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "CLI for BataDB — serverless Postgres platform",
5
5
  "bin": {
6
6
  "bata": "./dist/index.js"
@@ -8,15 +8,16 @@
8
8
  "type": "module",
9
9
  "scripts": {
10
10
  "build": "tsc",
11
- "dev": "tsc --watch"
11
+ "dev": "tsc --watch",
12
+ "test": "vitest run"
12
13
  },
13
14
  "engines": {
14
15
  "node": ">=20.0.0"
15
16
  },
16
- "dependencies": {},
17
17
  "devDependencies": {
18
+ "@types/node": "^22.10.0",
18
19
  "typescript": "^5.7.0",
19
- "@types/node": "^22.10.0"
20
+ "vitest": "^3.2.6"
20
21
  },
21
22
  "files": [
22
23
  "dist"