@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kanorio, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # @kanorio/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `kanorio` is a thin command-line wrapper around the Kanorio Management API (`https://app.kanorio.com/api/v1`). It has no business logic of its own and no third-party dependencies; the list of operations and their inputs and outputs follow the [OpenAPI document](https://app.kanorio.com/api/v1/openapi.json).
4
+
5
+ ```bash
6
+ npm install -g @kanorio/cli # or: npx @kanorio/cli --help
7
+ kanorio --help
8
+ ```
9
+
10
+ Requires Node.js 20 or later.
11
+
12
+ ## Sign in
13
+
14
+ ```bash
15
+ kanorio login
16
+ ```
17
+
18
+ `login` opens Kanorio's approval page in your browser. You choose the sites and permissions there, and the CLI stores the session in `~/.config/kanorio/config.json` (file mode 0600, directory 0700; `XDG_CONFIG_HOME` is respected). No key is copied or pasted. The link is also printed, so a coding assistant can run the command and hand you the link; `--no-browser` prints it without opening it. `kanorio logout` ends the session, and you can change its sites or revoke it under Account settings > API access.
19
+
20
+ Without a browser, or in CI and scripts:
21
+
22
+ - Set `KANORIO_TOKEN` (a personal access token `knr_pat_…` or a service account token `knr_sa_…`); it takes precedence over the stored session.
23
+ - `kanorio login --with-token` prompts for a personal access token without echo; `echo "$TOKEN" | kanorio login` and `kanorio login --token knr_pat_…` store one too.
24
+
25
+ `kanorio whoami` shows who the credential acts as, its permissions, and the operations it cannot call.
26
+
27
+ ## Any API operation
28
+
29
+ ```bash
30
+ kanorio api GET '/sites/<siteId>/posts?limit=5'
31
+ kanorio api POST /sites/<siteId>/posts --file post.json
32
+ kanorio api POST /sites/<siteId>/posts/<postId>/publish
33
+ ```
34
+
35
+ `api` calls any Management API operation with the stored credential and prints the JSON response. Paths are relative to `/api/v1`; pass a body with `--file <path>`, `--file -` (stdin) or `--data '<json>'`, and an `Idempotency-Key` with `--idempotency-key`. A coding assistant can run these commands for you without ever seeing a token.
36
+
37
+ ## Common commands
38
+
39
+ ```bash
40
+ kanorio sites list
41
+ kanorio sites create --name "Sunny Bakery" --locale en --timezone Asia/Taipei --profile local_food
42
+ kanorio sites create --brief brief.json && kanorio jobs get <jobId>
43
+ kanorio settings update <siteId> --brand-color "#C8553D" --corner-radius soft
44
+ kanorio pages list <siteId>
45
+ kanorio pages create <siteId> --title "About" --slug /about
46
+ kanorio pages get <siteId> <pageId> --json > page.json
47
+ kanorio pages replace-sections <siteId> <pageId> --file sections.json
48
+ kanorio globals replace-header <siteId> --file header.json
49
+ kanorio publish <siteId> --subdomain sunny-bakery
50
+ kanorio domains bind <siteId> www.example.com example.com
51
+ kanorio types --site https://example.com --out kanorio.d.ts # TypeScript types for the site's collections
52
+ kanorio doctor --site <siteId> # check a self-hosted front end against the site
53
+ kanorio keys create --site <siteId> --write-env .env.local # issue a server key without printing it
54
+ ```
55
+
56
+ `kanorio --help` lists every command with its capability domain.
57
+
58
+ ### Server keys
59
+
60
+ `keys create` issues a **server key** (`knr_sk_…`) so the server of a self-hosted front end can act on behalf of a visitor: submit a form, complete a customer sign-in, report an AI crawler hit. A server key cannot call the Management API. `--write-env <file>` writes `KANORIO_SERVER_KEY=…` into that file (created with mode 0600) and does not print the key; if the line already exists, add `--force` to replace it. The CLI warns when the file is not ignored by git. Without `--write-env` the key is printed once. To rotate: run the command again, deploy the new key, then revoke the old one under Site settings > Developer.
61
+
62
+ ### Output and errors
63
+
64
+ `--json` makes both stdout and stderr JSON. Errors are printed as `<CODE> (HTTP <status>): <message>` with exit code 1; usage errors exit with 2. `CONFLICT` means the page changed since you read it: run `pages get` again for the current `updatedAt` and resend. The same applies to `globals *` with `contentUpdatedAt`.
65
+
66
+ ## Documentation and support
67
+
68
+ - Documentation: <https://kanorio.com/en/developers/cli>
69
+ - Changes: [CHANGELOG.md](./CHANGELOG.md). The package follows semantic versioning and is released together with `@kanorio/sdk` and `@kanorio/elements` under one version number.
70
+ - Questions and bug reports: <support@kanorio.com>. To report a security issue, write to <security@kanorio.com> instead of opening a public report.
package/dist/args.js ADDED
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Argument parsing: node:util parseArgs only, no third-party dependency.
3
+ * Every flag is declared globally (parseArgs has no per-subcommand declarations); each command reads the ones it needs.
4
+ */
5
+ import { parseArgs } from "node:util";
6
+ /** Subcommands made of two segments; every other command has one */
7
+ const TWO_PART_COMMANDS = new Set(["sites", "pages", "domains", "sections", "jobs", "settings", "globals", "media", "keys"]);
8
+ export class UsageError extends Error {
9
+ exitCode = 2;
10
+ }
11
+ function rawParse(argv) {
12
+ try {
13
+ return parseArgs({ args: [...argv], options: OPTIONS, allowPositionals: true, strict: true });
14
+ }
15
+ catch (error) {
16
+ throw new UsageError(error instanceof Error ? error.message : String(error));
17
+ }
18
+ }
19
+ export function parseCliArgs(argv) {
20
+ const parsed = rawParse(argv);
21
+ const values = parsed.values;
22
+ const positionals = [...parsed.positionals];
23
+ const command = [];
24
+ const head = positionals.shift();
25
+ if (head) {
26
+ command.push(head);
27
+ if (TWO_PART_COMMANDS.has(head)) {
28
+ const sub = positionals.shift();
29
+ if (sub)
30
+ command.push(sub);
31
+ }
32
+ }
33
+ return {
34
+ command,
35
+ positionals,
36
+ flags: {
37
+ json: values.json === true,
38
+ help: values.help === true,
39
+ version: values.version === true,
40
+ hidden: values.hidden === true,
41
+ visible: values.visible === true,
42
+ profile: values.profile,
43
+ description: values.description,
44
+ brandColor: values["brand-color"],
45
+ brandColorDark: values["brand-color-dark"],
46
+ cornerRadius: values["corner-radius"],
47
+ colorScheme: values["color-scheme"],
48
+ density: values.density,
49
+ currency: values.currency,
50
+ url: values.url,
51
+ query: values.query,
52
+ orientation: values.orientation,
53
+ provider: values.provider,
54
+ max: values.max,
55
+ purpose: values.purpose,
56
+ uploadToken: values["upload-token"],
57
+ stockId: values["stock-id"],
58
+ api: values.api,
59
+ token: values.token,
60
+ file: values.file,
61
+ name: values.name,
62
+ locale: values.locale,
63
+ timezone: values.timezone,
64
+ brief: values.brief,
65
+ subdomain: values.subdomain,
66
+ title: values.title,
67
+ slug: values.slug,
68
+ detail: values.detail,
69
+ site: values.site,
70
+ ifUnmodifiedSince: values["if-unmodified-since"],
71
+ out: values.out,
72
+ switching: values.switching === true,
73
+ writeEnv: values["write-env"],
74
+ keyName: values["key-name"],
75
+ force: values.force === true,
76
+ data: values.data,
77
+ idempotencyKey: values["idempotency-key"],
78
+ withToken: values["with-token"] === true,
79
+ noBrowser: values["no-browser"] === true,
80
+ },
81
+ };
82
+ }
83
+ const OPTIONS = {
84
+ json: { type: "boolean", default: false },
85
+ help: { type: "boolean", short: "h", default: false },
86
+ version: { type: "boolean", short: "v", default: false },
87
+ hidden: { type: "boolean", default: false },
88
+ visible: { type: "boolean", default: false },
89
+ profile: { type: "string" },
90
+ description: { type: "string" },
91
+ "brand-color": { type: "string" },
92
+ "brand-color-dark": { type: "string" },
93
+ "corner-radius": { type: "string" },
94
+ "color-scheme": { type: "string" },
95
+ density: { type: "string" },
96
+ currency: { type: "string" },
97
+ url: { type: "string" },
98
+ query: { type: "string", short: "q" },
99
+ orientation: { type: "string" },
100
+ provider: { type: "string" },
101
+ max: { type: "string" },
102
+ purpose: { type: "string" },
103
+ "upload-token": { type: "string" },
104
+ "stock-id": { type: "string" },
105
+ api: { type: "string" },
106
+ token: { type: "string" },
107
+ file: { type: "string", short: "f" },
108
+ name: { type: "string" },
109
+ locale: { type: "string" },
110
+ timezone: { type: "string" },
111
+ brief: { type: "string" },
112
+ subdomain: { type: "string" },
113
+ title: { type: "string" },
114
+ slug: { type: "string" },
115
+ detail: { type: "string" },
116
+ site: { type: "string" },
117
+ "if-unmodified-since": { type: "string" },
118
+ out: { type: "string", short: "o" },
119
+ switching: { type: "boolean", default: false },
120
+ "write-env": { type: "string" },
121
+ "key-name": { type: "string" },
122
+ data: { type: "string" },
123
+ "idempotency-key": { type: "string" },
124
+ "with-token": { type: "boolean", default: false },
125
+ "no-browser": { type: "boolean", default: false },
126
+ force: { type: "boolean", default: false },
127
+ };
package/dist/bin.js ADDED
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { parseCliArgs, UsageError } from "./args.js";
4
+ import { formatDeprecationWarning } from "./client.js";
5
+ import { resolveCommand } from "./commands.js";
6
+ import { HELP } from "./help.js";
7
+ import { formatError, formatResult } from "./output.js";
8
+ const require = createRequire(import.meta.url);
9
+ const { version } = require("../package.json");
10
+ async function main(argv) {
11
+ let json = argv.includes("--json");
12
+ try {
13
+ const cli = parseCliArgs(argv);
14
+ json = cli.flags.json;
15
+ if (cli.flags.version) {
16
+ process.stdout.write(`${version}\n`);
17
+ return 0;
18
+ }
19
+ if (cli.flags.help || cli.command.length === 0) {
20
+ process.stdout.write(HELP);
21
+ return cli.command.length === 0 && !cli.flags.help ? 2 : 0;
22
+ }
23
+ const handler = resolveCommand(cli.command);
24
+ if (!handler)
25
+ throw new UsageError(`Unknown command "${cli.command.join(" ")}".`);
26
+ const result = await handler(cli, {
27
+ env: process.env,
28
+ userAgent: `kanorio-cli/${version}`,
29
+ // Deprecation warnings go to stderr: with --json, stdout stays clean JSON
30
+ onDeprecation: (notice) => process.stderr.write(`${formatDeprecationWarning(notice)}\n`),
31
+ });
32
+ process.stdout.write(`${formatResult(result, json)}\n`);
33
+ return 0;
34
+ }
35
+ catch (error) {
36
+ const { text, exitCode } = formatError(error, json);
37
+ process.stderr.write(`${text}\n`);
38
+ return exitCode;
39
+ }
40
+ }
41
+ main(process.argv.slice(2)).then((code) => {
42
+ process.exitCode = code;
43
+ }, (error) => {
44
+ process.stderr.write(`${formatError(error, false).text}\n`);
45
+ process.exitCode = 1;
46
+ });
package/dist/client.js ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Thin REST wrapper: builds the URL, sends the bearer token, parses JSON and turns `{ error: { code, message, details } }` into ApiError.
3
+ * No business logic; whatever the server answers is passed through.
4
+ */
5
+ export function isErrorEnvelope(value) {
6
+ if (typeof value !== "object" || value === null)
7
+ return false;
8
+ const error = value.error;
9
+ if (typeof error !== "object" || error === null)
10
+ return false;
11
+ const { code, message } = error;
12
+ return typeof code === "string" && typeof message === "string";
13
+ }
14
+ export class ApiError extends Error {
15
+ code;
16
+ status;
17
+ details;
18
+ retryAfter;
19
+ exitCode = 1;
20
+ constructor(code, status, message, details, retryAfter) {
21
+ super(message);
22
+ this.code = code;
23
+ this.status = status;
24
+ this.details = details;
25
+ this.retryAfter = retryAfter;
26
+ this.name = "ApiError";
27
+ }
28
+ }
29
+ /** Responses that are not JSON or not an envelope (blocked by Cloudflare, a proxy error) still need a printable code */
30
+ export function toApiError(status, body, retryAfterHeader) {
31
+ const retryAfter = retryAfterHeader ? Number.parseInt(retryAfterHeader, 10) : undefined;
32
+ if (isErrorEnvelope(body)) {
33
+ return new ApiError(body.error.code, status, body.error.message, body.error.details, retryAfter);
34
+ }
35
+ const code = status === 401 ? "UNAUTHORIZED" : status === 404 ? "NOT_FOUND" : status >= 500 ? "UPSTREAM_ERROR" : "HTTP_ERROR";
36
+ const text = typeof body === "string" ? body.slice(0, 200) : "";
37
+ return new ApiError(code, status, text || `Request failed with HTTP ${status}.`, undefined, retryAfter);
38
+ }
39
+ export function parseDeprecation(headers, method, path) {
40
+ if (!headers.has("deprecation"))
41
+ return null;
42
+ const link = headers.get("link") ?? "";
43
+ const rel = (name) => {
44
+ const match = link.match(new RegExp(`<([^>]+)>;\\s*rel="${name}"`));
45
+ return match?.[1] ?? null;
46
+ };
47
+ return { method, path, sunset: headers.get("sunset"), successor: rel("successor-version"), policy: rel("deprecation") };
48
+ }
49
+ export function formatDeprecationWarning(notice) {
50
+ const parts = [`warning: ${notice.method} ${notice.path} is deprecated`];
51
+ if (notice.sunset)
52
+ parts.push(`and will be removed after ${notice.sunset}`);
53
+ let text = parts.join(" ");
54
+ if (notice.successor)
55
+ text += `; use ${notice.successor}`;
56
+ if (notice.policy)
57
+ text += ` (${notice.policy})`;
58
+ return text;
59
+ }
60
+ export function buildUrl(apiUrl, path, query) {
61
+ const url = new URL(`${apiUrl}/api/v1${path.startsWith("/") ? path : `/${path}`}`);
62
+ for (const [key, value] of Object.entries(query ?? {})) {
63
+ if (value === undefined)
64
+ continue;
65
+ if (Array.isArray(value)) {
66
+ if (value.length > 0)
67
+ url.searchParams.set(key, value.join(","));
68
+ }
69
+ else {
70
+ url.searchParams.set(key, value);
71
+ }
72
+ }
73
+ return url.toString();
74
+ }
75
+ export async function request(options) {
76
+ const fetchImpl = options.fetchImpl ?? fetch;
77
+ const headers = {
78
+ ...options.headers,
79
+ authorization: `Bearer ${options.token}`,
80
+ accept: "application/json",
81
+ "user-agent": options.userAgent ?? "kanorio-cli",
82
+ };
83
+ const init = { method: options.method, headers };
84
+ if (options.body !== undefined) {
85
+ headers["content-type"] = "application/json";
86
+ init.body = JSON.stringify(options.body);
87
+ }
88
+ const res = await fetchImpl(buildUrl(options.apiUrl, options.path, options.query), init);
89
+ const deprecation = parseDeprecation(res.headers, options.method, options.path);
90
+ if (deprecation)
91
+ options.onDeprecation?.(deprecation);
92
+ const text = await res.text();
93
+ let body = text;
94
+ if (text) {
95
+ try {
96
+ body = JSON.parse(text);
97
+ }
98
+ catch {
99
+ body = text;
100
+ }
101
+ }
102
+ else {
103
+ body = null;
104
+ }
105
+ if (!res.ok)
106
+ throw toApiError(res.status, body, res.headers.get("retry-after"));
107
+ return body;
108
+ }