@kanorio/cli 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/config.js ADDED
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Local config: `$XDG_CONFIG_HOME/kanorio/config.json` (default `~/.config/kanorio/config.json`).
3
+ * Stores the sign-in credential (OAuth tokens from browser sign-in, or a pasted PAT, one or the other) and the API base; file mode 0600, directory 0700.
4
+ * The `KANORIO_TOKEN` environment variable always wins over the file.
5
+ */
6
+ import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+ export const DEFAULT_API_URL = "https://app.kanorio.com";
10
+ function parseOAuthSession(value) {
11
+ if (typeof value !== "object" || value === null)
12
+ return null;
13
+ const o = value;
14
+ if (typeof o.accessToken !== "string" || typeof o.refreshToken !== "string" || typeof o.expiresAt !== "number" || typeof o.apiUrl !== "string")
15
+ return null;
16
+ return { accessToken: o.accessToken, refreshToken: o.refreshToken, expiresAt: o.expiresAt, apiUrl: o.apiUrl };
17
+ }
18
+ export function configDir(env = process.env) {
19
+ const base = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.trim() ? env.XDG_CONFIG_HOME : join(env.HOME ?? homedir(), ".config");
20
+ return join(base, "kanorio");
21
+ }
22
+ export function configPath(env = process.env) {
23
+ return join(configDir(env), "config.json");
24
+ }
25
+ export function readConfig(env = process.env) {
26
+ const path = configPath(env);
27
+ if (!existsSync(path))
28
+ return {};
29
+ try {
30
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
31
+ if (typeof parsed !== "object" || parsed === null)
32
+ return {};
33
+ const obj = parsed;
34
+ const oauth = parseOAuthSession(obj.oauth);
35
+ return {
36
+ ...(typeof obj.token === "string" ? { token: obj.token } : {}),
37
+ ...(typeof obj.apiUrl === "string" ? { apiUrl: obj.apiUrl } : {}),
38
+ ...(oauth ? { oauth } : {}),
39
+ };
40
+ }
41
+ catch {
42
+ return {};
43
+ }
44
+ }
45
+ export function writeConfig(config, env = process.env) {
46
+ const dir = configDir(env);
47
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
48
+ const path = configPath(env);
49
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
50
+ // writeFileSync's mode only applies on creation; an existing file (created by hand, for example) is tightened too
51
+ chmodSync(path, 0o600);
52
+ return path;
53
+ }
54
+ /** Removes the sign-in credential (PAT and browser sign-in tokens); other settings (apiUrl) stay, and the file is deleted when nothing is left */
55
+ export function clearToken(env = process.env) {
56
+ const rest = { ...readConfig(env) };
57
+ delete rest.token;
58
+ delete rest.oauth;
59
+ if (Object.keys(rest).length === 0) {
60
+ if (existsSync(configPath(env)))
61
+ unlinkSync(configPath(env));
62
+ return;
63
+ }
64
+ writeConfig(rest, env);
65
+ }
66
+ export function resolveAuth(flags, env = process.env, config = readConfig(env)) {
67
+ const apiUrl = (flags.api ?? env.KANORIO_API_URL ?? config.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, "");
68
+ if (flags.token)
69
+ return { token: flags.token, apiUrl, tokenSource: "flag" };
70
+ if (env.KANORIO_TOKEN)
71
+ return { token: env.KANORIO_TOKEN, apiUrl, tokenSource: "env" };
72
+ if (config.token)
73
+ return { token: config.token, apiUrl, tokenSource: "config" };
74
+ // Browser sign-in tokens are valid only for the host that issued them; they are not used when --api points elsewhere
75
+ if (config.oauth && config.oauth.apiUrl === apiUrl)
76
+ return { token: config.oauth.accessToken, apiUrl, tokenSource: "oauth", oauth: config.oauth };
77
+ return { token: null, apiUrl, tokenSource: null };
78
+ }
79
+ const LOCK_STALE_MS = 30_000;
80
+ const LOCK_WAIT_MS = 15_000;
81
+ /**
82
+ * A lock file lets only one process refresh the tokens at a time. Each refresh revokes the previous refresh token, and replaying an old one revokes the whole grant;
83
+ * two commands running at once (coding assistants often do this) would each refresh with the same token and the later one would lose the sign-in.
84
+ * The process that gets the lock must read the config file again: the previous process may already have refreshed.
85
+ */
86
+ export async function withConfigLock(env, fn) {
87
+ const dir = configDir(env);
88
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
89
+ const lock = join(dir, "config.lock");
90
+ const deadline = Date.now() + LOCK_WAIT_MS;
91
+ for (;;) {
92
+ try {
93
+ closeSync(openSync(lock, "wx", 0o600));
94
+ break;
95
+ }
96
+ catch {
97
+ // Another process holds it; a stale lock left by a crashed process is removed
98
+ try {
99
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS)
100
+ unlinkSync(lock);
101
+ }
102
+ catch {
103
+ // Released just now
104
+ }
105
+ if (Date.now() > deadline)
106
+ throw new Error("Another kanorio command is refreshing the session. Try again.");
107
+ await new Promise((resolve) => setTimeout(resolve, 50));
108
+ }
109
+ }
110
+ try {
111
+ return await fn();
112
+ }
113
+ finally {
114
+ try {
115
+ unlinkSync(lock);
116
+ }
117
+ catch {
118
+ // Already removed
119
+ }
120
+ }
121
+ }
package/dist/help.js ADDED
@@ -0,0 +1,98 @@
1
+ export const HELP = `kanorio - command-line wrapper around the Kanorio Management API
2
+
3
+ Usage: kanorio <command> [args] [--json] [--api <url>] [--token <pat>]
4
+
5
+ Auth
6
+ login [--no-browser] Sign in through the browser: opens Kanorio's approval page, where you choose the sites
7
+ and permissions, then stores the session (~/.config/kanorio/config.json, 0600).
8
+ No key is copied or pasted, so a coding assistant can run it for you: it prints the
9
+ link, you open it. --no-browser prints the link without opening it.
10
+ login --with-token Paste a personal access token instead (hidden prompt); or pipe it: echo $TOKEN | kanorio login
11
+ login --token <pat> Store a personal access token given on the command line
12
+ logout Remove the stored session or token (a browser session is also revoked on the server)
13
+ KANORIO_TOKEN=<token> Environment variable; takes precedence over the stored session
14
+
15
+ Any API operation
16
+ api <METHOD> <path> [--file <body.json> | --data '<json>'] [--idempotency-key <key>]
17
+ Call any Management API operation with the stored token and print the JSON response:
18
+ kanorio api GET '/sites/<siteId>/posts?limit=5'
19
+ kanorio api POST /sites/<siteId>/posts --file post.json
20
+ kanorio api POST /sites/<siteId>/posts/<postId>/publish
21
+ <path> is relative to /api/v1 (the API reference lists every operation). --file - reads the body from stdin.
22
+ A coding assistant can run this for you without ever seeing the token.
23
+ whoami [--site <siteId>] Who the stored token acts as, its permissions, and the operations it cannot call (with the reason)
24
+
25
+ Sites
26
+ sites list
27
+ sites get <siteId>
28
+ sites create --name <n> --locale <bcp47> [--timezone <tz>] [--profile <siteProfile>] [--description <text>]
29
+ Blank site with default header/footer, returns websiteId
30
+ sites create --brief <brief.json> AI site from a brief, returns jobId
31
+ jobs get <jobId> Poll a generation job
32
+
33
+ Brand and site-wide layout
34
+ settings get <siteId> Brand (colors, fonts, corner radius, color scheme; live immediately), layout (draft), locale, currency
35
+ settings update <siteId> [--brand-color <#hex> [--brand-color-dark <#hex>]] [--corner-radius sharp|normal|soft]
36
+ [--color-scheme system|light|dark] [--density standard|compact] [--locale <bcp47>]
37
+ [--currency <code>] [--file <settings.json>]
38
+ --brand-color / --corner-radius / --color-scheme write settings.brand (live immediately on site, checkout, sign-in, emails);
39
+ --density writes the hosted layout draft (publish to go live).
40
+ globals get <siteId> Header, footer, siteSettings, contentUpdatedAt
41
+ globals update-site-settings <siteId> --file <siteSettings.json> [--if-unmodified-since <iso>]
42
+ Partial: { "customButtons": [...], "socialLinks": [...] }. Button ids come back in the response (use them in ctaIds).
43
+ globals replace-header <siteId> --file <header.json> [--if-unmodified-since <iso>]
44
+ globals replace-footer <siteId> --file <footer.json> [--if-unmodified-since <iso>]
45
+ Without --if-unmodified-since the CLI reads globals first and uses its current contentUpdatedAt.
46
+
47
+ Pages
48
+ pages list <siteId>
49
+ pages get <siteId> <pageId>
50
+ pages create <siteId> --title <t> [--slug </path>] [--hidden]
51
+ pages update <siteId> <pageId> [--title <t>] [--slug </path>] [--hidden | --visible] [--file <patch.json>]
52
+ pages reorder <siteId> <pageId> [pageId...] Every non-home page, in order
53
+ pages delete <siteId> <pageId>
54
+ pages replace-sections <siteId> <pageId> --file <sections.json> [--if-unmodified-since <iso>]
55
+ sections.json is either an array of sections or { "sections": [...], "ifUnmodifiedSince": "..." }.
56
+ Without --if-unmodified-since the CLI reads the page first and uses its current updatedAt.
57
+
58
+ Publish
59
+ publish <siteId> [--subdomain <name>]
60
+ unpublish <siteId>
61
+
62
+ Domains
63
+ domains list <siteId>
64
+ domains status <siteId>
65
+ domains bind <siteId> <hostname> [hostname...] First hostname is primary; empty list removes all
66
+
67
+ Images
68
+ media list <siteId>
69
+ media upload <siteId> --url <https://…> | --file <image>
70
+ media upload-link <siteId> [--max <n>] [--purpose <text>] Page for the user to send photos (15 min)
71
+ media upload-link-status <siteId> --upload-token <token>
72
+ media search-stock <siteId> <query…> [--orientation landscape] [--provider pexels|pixabay] [--max <n>]
73
+ media import-stock <siteId> --provider <p> --stock-id <id> --url <downloadURL>
74
+ media page-images <siteId> <url> [--max <n>] Images found on a page the user owns
75
+
76
+ Sections & Types
77
+ sections describe [type...] [--detail full] [--site <siteId>]
78
+ types --site <siteId|https://site> [--out <kanorio.d.ts>] Generate TypeScript types for collections (assets + expanded)
79
+ doctor --site <siteId> Check external storefront health (--switching is deprecated and ignored)
80
+
81
+ Server keys
82
+ keys create --site <siteId> [--name <account>] [--key-name <label>] [--write-env <.env.local>] [--force]
83
+ Issue a server key (knr_sk_…) so your own server can submit forms, exchange customer sign-in codes and report
84
+ crawler hits on behalf of visitors. The key cannot call the Management API.
85
+ --write-env writes KANORIO_SERVER_KEY=… into that file (created with mode 0600) and does not print the key;
86
+ an existing KANORIO_SERVER_KEY line is only replaced with --force. Without --write-env the key is printed once.
87
+ Rotate by running it again, deploying the new key, then revoking the old one under Site settings > Developer.
88
+
89
+ Global flags
90
+ --json Print raw JSON (errors too) for scripting
91
+ --api <url> API origin (default https://app.kanorio.com; or KANORIO_API_URL)
92
+ --token <pat> One-off token (not stored)
93
+ -h, --help Show this help
94
+ -v, --version Print version
95
+
96
+ Errors print as "<CODE> (HTTP <status>): <message>" on stderr and exit 1; usage errors exit 2.
97
+ OpenAPI: https://app.kanorio.com/api/v1/openapi.json
98
+ `;
package/dist/oauth.js ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Browser sign-in (OAuth 2.1 authorization code + PKCE, loopback redirect for native apps, RFC 8252).
3
+ *
4
+ * `kanorio login` opens the browser on Kanorio's approval page, where the user picks sites and permissions; after approval the browser returns to a temporary local
5
+ * `http://127.0.0.1:<port>/callback`, and the CLI exchanges the authorization code for an access token and a refresh token. No key is copied or pasted along the way,
6
+ * and a coding assistant running the command never sees the tokens.
7
+ *
8
+ * The tokens' audience (RFC 8707 resource) is the Management API: they work on `/api/v1` only and MCP refuses them, just as MCP's OAuth tokens
9
+ * do not work here. The access token expires after an hour and is refreshed with the refresh token; every refresh revokes the previous refresh token (a replay revokes the whole grant),
10
+ * so refreshes are serialized (the lock in config.ts).
11
+ */
12
+ import { createHash, randomBytes } from "node:crypto";
13
+ import { createServer } from "node:http";
14
+ /** The Kanorio CLI's client id (the URL of its Client ID Metadata Document; the authorization server knows this first-party client) */
15
+ export const CLI_OAUTH_CLIENT_ID = "https://kanorio.com/oauth/kanorio-cli.json";
16
+ /** Callback path; the port differs every time (RFC 8252 section 7.3: the authorization server ignores the port when matching loopback addresses) */
17
+ export const CLI_OAUTH_CALLBACK_PATH = "/callback";
18
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
19
+ export class OAuthLoginError extends Error {
20
+ code;
21
+ exitCode = 1;
22
+ constructor(code, message) {
23
+ super(message);
24
+ this.code = code;
25
+ this.name = "OAuthLoginError";
26
+ }
27
+ }
28
+ const base64url = (bytes) => bytes.toString("base64url");
29
+ export function createPkce() {
30
+ const verifier = base64url(randomBytes(32));
31
+ return { verifier, challenge: base64url(createHash("sha256").update(verifier).digest()) };
32
+ }
33
+ /** The tokens' audience: the Management API on this API host */
34
+ export function managementResource(apiUrl) {
35
+ return `${apiUrl.replace(/\/+$/, "")}/api/v1`;
36
+ }
37
+ export function buildAuthorizeUrl(params) {
38
+ const url = new URL(`${params.apiUrl.replace(/\/+$/, "")}/oauth/authorize`);
39
+ url.searchParams.set("response_type", "code");
40
+ url.searchParams.set("client_id", CLI_OAUTH_CLIENT_ID);
41
+ url.searchParams.set("redirect_uri", params.redirectUri);
42
+ url.searchParams.set("code_challenge", params.challenge);
43
+ url.searchParams.set("code_challenge_method", "S256");
44
+ url.searchParams.set("state", params.state);
45
+ url.searchParams.set("resource", managementResource(params.apiUrl));
46
+ return url.toString();
47
+ }
48
+ const page = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title>` +
49
+ `<meta name="viewport" content="width=device-width, initial-scale=1"><style>body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 1.5rem;color:#1c1917}h1{font-size:1.25rem}</style></head>` +
50
+ `<body><h1>${title}</h1><p>${body}</p></body></html>`;
51
+ /** Starts a one-off callback server on a random port of 127.0.0.1 (local only, not exposed) */
52
+ export async function startLoopbackListener(options = {}) {
53
+ let settle = null;
54
+ let expected = null;
55
+ let early = null;
56
+ const server = createServer((req, res) => {
57
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
58
+ if (url.pathname !== CLI_OAUTH_CALLBACK_PATH) {
59
+ res.writeHead(404, { "content-type": "text/plain" }).end("Not found");
60
+ return;
61
+ }
62
+ const finish = (status, title, body, outcome) => {
63
+ res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(page(title, body));
64
+ if (settle) {
65
+ if (outcome.code)
66
+ settle.resolve(outcome.code);
67
+ else
68
+ settle.reject(outcome.error ?? new OAuthLoginError("login_failed", "Sign-in failed."));
69
+ }
70
+ else {
71
+ early = outcome;
72
+ }
73
+ };
74
+ const error = url.searchParams.get("error");
75
+ if (error) {
76
+ const description = url.searchParams.get("error_description") ?? error;
77
+ finish(400, "Sign-in was not completed", "You can close this tab and run <code>kanorio login</code> again.", {
78
+ error: new OAuthLoginError(error, error === "access_denied" ? "Access was not approved." : description),
79
+ });
80
+ return;
81
+ }
82
+ const code = url.searchParams.get("code");
83
+ const state = url.searchParams.get("state");
84
+ if (!code || !state || (expected !== null && state !== expected)) {
85
+ finish(400, "Sign-in was not completed", "This sign-in link does not match the request that started it. Run <code>kanorio login</code> again.", {
86
+ error: new OAuthLoginError("invalid_state", "The sign-in response did not match this request."),
87
+ });
88
+ return;
89
+ }
90
+ finish(200, "Kanorio CLI is connected", "You can close this tab and go back to your terminal.", { code });
91
+ });
92
+ await new Promise((resolve, reject) => {
93
+ server.once("error", reject);
94
+ server.listen(0, "127.0.0.1", () => resolve());
95
+ });
96
+ const { port } = server.address();
97
+ const timeoutMs = options.timeoutMs ?? LOGIN_TIMEOUT_MS;
98
+ return {
99
+ redirectUri: `http://127.0.0.1:${port}${CLI_OAUTH_CALLBACK_PATH}`,
100
+ waitForCode(expectedState) {
101
+ expected = expectedState;
102
+ return new Promise((resolve, reject) => {
103
+ const timer = setTimeout(() => reject(new OAuthLoginError("timeout", "Timed out waiting for the browser. Run `kanorio login` again.")), timeoutMs);
104
+ timer.unref?.();
105
+ const done = (fn) => (value) => {
106
+ clearTimeout(timer);
107
+ fn(value);
108
+ };
109
+ settle = { resolve: done(resolve), reject: done(reject) };
110
+ if (early) {
111
+ if (early.code)
112
+ settle.resolve(early.code);
113
+ else
114
+ settle.reject(early.error ?? new OAuthLoginError("login_failed", "Sign-in failed."));
115
+ }
116
+ });
117
+ },
118
+ close() {
119
+ server.close();
120
+ server.closeAllConnections?.();
121
+ },
122
+ };
123
+ }
124
+ async function tokenRequest(apiUrl, form, fetchImpl, userAgent) {
125
+ const res = await fetchImpl(`${apiUrl.replace(/\/+$/, "")}/oauth/token`, {
126
+ method: "POST",
127
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json", "user-agent": userAgent },
128
+ body: new URLSearchParams({ ...form, client_id: CLI_OAUTH_CLIENT_ID }).toString(),
129
+ });
130
+ const body = (await res.json().catch(() => ({})));
131
+ if (!res.ok || typeof body.access_token !== "string" || typeof body.refresh_token !== "string") {
132
+ const code = typeof body.error === "string" ? body.error : `http_${res.status}`;
133
+ const description = typeof body.error_description === "string" ? body.error_description : "The authorization server refused the request.";
134
+ throw new OAuthLoginError(code, description);
135
+ }
136
+ const expiresIn = typeof body.expires_in === "number" && body.expires_in > 0 ? body.expires_in : 3600;
137
+ return { accessToken: body.access_token, refreshToken: body.refresh_token, expiresAt: Date.now() + expiresIn * 1000 };
138
+ }
139
+ export function exchangeAuthorizationCode(params) {
140
+ return tokenRequest(params.apiUrl, { grant_type: "authorization_code", code: params.code, code_verifier: params.verifier, redirect_uri: params.redirectUri, resource: managementResource(params.apiUrl) }, params.fetchImpl ?? fetch, params.userAgent);
141
+ }
142
+ export function refreshTokens(params) {
143
+ return tokenRequest(params.apiUrl, { grant_type: "refresh_token", refresh_token: params.refreshToken, resource: managementResource(params.apiUrl) }, params.fetchImpl ?? fetch, params.userAgent);
144
+ }
145
+ /** Revokes the grant on sign-out (best effort: the local tokens are always cleared, and a failed server-side revoke does not block) */
146
+ export async function revokeToken(params) {
147
+ try {
148
+ const res = await (params.fetchImpl ?? fetch)(`${params.apiUrl.replace(/\/+$/, "")}/oauth/revoke`, {
149
+ method: "POST",
150
+ headers: { "content-type": "application/x-www-form-urlencoded", "user-agent": params.userAgent },
151
+ body: new URLSearchParams({ token: params.token, client_id: CLI_OAUTH_CLIENT_ID }).toString(),
152
+ });
153
+ return res.ok;
154
+ }
155
+ catch {
156
+ return false;
157
+ }
158
+ }
159
+ export function randomState() {
160
+ return base64url(randomBytes(16));
161
+ }
package/dist/output.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Output: `--json` prints the JSON as is; otherwise a flat format for people. Errors always go to stderr and start with the code, so scripts can grep them.
3
+ */
4
+ import { ApiError } from "./client.js";
5
+ import { UsageError } from "./args.js";
6
+ function isPrimitive(value) {
7
+ return value === null || ["string", "number", "boolean"].includes(typeof value);
8
+ }
9
+ function cell(value) {
10
+ if (value === null || value === undefined)
11
+ return "-";
12
+ if (isPrimitive(value))
13
+ return String(value);
14
+ if (Array.isArray(value))
15
+ return value.length === 0 ? "[]" : `[${value.length}]`;
16
+ return "{…}";
17
+ }
18
+ /** Array of objects to an aligned table (top-level primitive fields only; use --json for nested values) */
19
+ function renderTable(rows) {
20
+ const columns = [];
21
+ for (const row of rows) {
22
+ for (const [key, value] of Object.entries(row)) {
23
+ if ((isPrimitive(value) || value === undefined) && !columns.includes(key))
24
+ columns.push(key);
25
+ }
26
+ }
27
+ if (columns.length === 0)
28
+ return rows.map((row) => JSON.stringify(row)).join("\n");
29
+ const widths = columns.map((col) => Math.max(col.length, ...rows.map((row) => cell(row[col]).length)));
30
+ const line = (values) => values.map((v, i) => v.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
31
+ return [line(columns), line(widths.map((w) => "-".repeat(w))), ...rows.map((row) => line(columns.map((col) => cell(row[col]))))].join("\n");
32
+ }
33
+ function renderObject(obj, indent = "") {
34
+ const lines = [];
35
+ for (const [key, value] of Object.entries(obj)) {
36
+ if (isPrimitive(value) || value === undefined) {
37
+ lines.push(`${indent}${key}: ${cell(value)}`);
38
+ }
39
+ else if (Array.isArray(value)) {
40
+ if (value.length > 0 && value.every((v) => typeof v === "object" && v !== null && !Array.isArray(v))) {
41
+ lines.push(`${indent}${key}:`);
42
+ lines.push(renderTable(value)
43
+ .split("\n")
44
+ .map((l) => `${indent} ${l}`)
45
+ .join("\n"));
46
+ }
47
+ else {
48
+ lines.push(`${indent}${key}: ${value.length === 0 ? "[]" : value.map(cell).join(", ")}`);
49
+ }
50
+ }
51
+ else {
52
+ lines.push(`${indent}${key}:`);
53
+ lines.push(renderObject(value, `${indent} `));
54
+ }
55
+ }
56
+ return lines.join("\n");
57
+ }
58
+ export function formatResult(data, json) {
59
+ if (json)
60
+ return JSON.stringify(data, null, 2);
61
+ if (isPrimitive(data) || data === undefined)
62
+ return cell(data);
63
+ if (Array.isArray(data)) {
64
+ if (data.every((v) => typeof v === "object" && v !== null && !Array.isArray(v))) {
65
+ return renderTable(data);
66
+ }
67
+ return data.map(cell).join("\n");
68
+ }
69
+ const obj = data;
70
+ // Common shapes { sites: [...] } and { pages: [...] }: a single array field is drawn as a table
71
+ const keys = Object.keys(obj);
72
+ if (keys.length === 1 && Array.isArray(obj[keys[0] ?? ""])) {
73
+ return formatResult(obj[keys[0] ?? ""], false);
74
+ }
75
+ return renderObject(obj);
76
+ }
77
+ export function formatError(error, json) {
78
+ if (error instanceof ApiError) {
79
+ const payload = {
80
+ error: {
81
+ code: error.code,
82
+ status: error.status,
83
+ message: error.message,
84
+ ...(error.details === undefined ? {} : { details: error.details }),
85
+ ...(error.retryAfter === undefined ? {} : { retryAfter: error.retryAfter }),
86
+ },
87
+ };
88
+ if (json)
89
+ return { text: JSON.stringify(payload, null, 2), exitCode: error.exitCode };
90
+ const lines = [`${error.code} (HTTP ${error.status}): ${error.message}`];
91
+ if (error.details !== undefined)
92
+ lines.push(`details: ${JSON.stringify(error.details)}`);
93
+ if (error.retryAfter !== undefined)
94
+ lines.push(`retry after ${error.retryAfter}s`);
95
+ if (error.code === "UNAUTHORIZED")
96
+ lines.push("hint: run `kanorio login` or set KANORIO_TOKEN.");
97
+ if (error.code === "CONFLICT")
98
+ lines.push("hint: re-run `pages get` and retry with the new updatedAt.");
99
+ return { text: lines.join("\n"), exitCode: error.exitCode };
100
+ }
101
+ if (error instanceof UsageError) {
102
+ const text = json ? JSON.stringify({ error: { code: "USAGE", message: error.message } }) : `USAGE: ${error.message}\nRun \`kanorio --help\`.`;
103
+ return { text, exitCode: error.exitCode };
104
+ }
105
+ const message = error instanceof Error ? error.message : String(error);
106
+ const code = typeof error?.code === "string" ? error.code : "CLI_ERROR";
107
+ return {
108
+ text: json ? JSON.stringify({ error: { code, message } }) : `${code}: ${message}`,
109
+ exitCode: 1,
110
+ };
111
+ }