@kanorio/cli 1.1.0 → 1.3.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/README.md +8 -0
- package/dist/args.js +10 -0
- package/dist/commands.js +45 -13
- package/dist/help.js +8 -1
- package/dist/oauth.js +7 -0
- package/dist/output.js +23 -0
- package/dist/shared/json-schema-ts.js +92 -0
- package/dist/types-codegen.js +33 -4
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -24,6 +24,14 @@ Without a browser, or in CI and scripts:
|
|
|
24
24
|
|
|
25
25
|
`kanorio whoami` shows who the credential acts as, its permissions, and the operations it cannot call.
|
|
26
26
|
|
|
27
|
+
A browser sign-in starts with the permissions you chose on the approval page. When a command answers `FORBIDDEN` with `reason: missing_scope`, the error names the permission and the command that adds it:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
kanorio login --scope marketing:manage
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The approval page then lists only the added permission; what the CLI already had is kept. You can also allow it in the dashboard: the error's `manageUrl` opens the Kanorio CLI connection, where the requested permission is listed. A personal access token is edited under Account settings > API access instead, and the error links to it.
|
|
34
|
+
|
|
27
35
|
## Any API operation
|
|
28
36
|
|
|
29
37
|
```bash
|
package/dist/args.js
CHANGED
|
@@ -75,8 +75,13 @@ export function parseCliArgs(argv) {
|
|
|
75
75
|
force: values.force === true,
|
|
76
76
|
data: values.data,
|
|
77
77
|
idempotencyKey: values["idempotency-key"],
|
|
78
|
+
alt: values.alt,
|
|
79
|
+
tag: values.tag ?? [],
|
|
80
|
+
credit: values.credit,
|
|
81
|
+
sourceUrl: values["source-url"],
|
|
78
82
|
withToken: values["with-token"] === true,
|
|
79
83
|
noBrowser: values["no-browser"] === true,
|
|
84
|
+
scope: (values.scope ?? []).flatMap((value) => value.split(/[\s,]+/)).filter(Boolean),
|
|
80
85
|
},
|
|
81
86
|
};
|
|
82
87
|
}
|
|
@@ -121,7 +126,12 @@ const OPTIONS = {
|
|
|
121
126
|
"key-name": { type: "string" },
|
|
122
127
|
data: { type: "string" },
|
|
123
128
|
"idempotency-key": { type: "string" },
|
|
129
|
+
alt: { type: "string" },
|
|
130
|
+
tag: { type: "string", multiple: true },
|
|
131
|
+
credit: { type: "string" },
|
|
132
|
+
"source-url": { type: "string" },
|
|
124
133
|
"with-token": { type: "boolean", default: false },
|
|
125
134
|
"no-browser": { type: "boolean", default: false },
|
|
135
|
+
scope: { type: "string", multiple: true },
|
|
126
136
|
force: { type: "boolean", default: false },
|
|
127
137
|
};
|
package/dist/commands.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { execFileSync, spawn } from "node:child_process";
|
|
6
6
|
import { accessSync, chmodSync, constants as fsConstants, existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
-
import { dirname, resolve } from "node:path";
|
|
7
|
+
import { basename, dirname, resolve } from "node:path";
|
|
8
8
|
import { createInterface } from "node:readline";
|
|
9
9
|
import { Writable } from "node:stream";
|
|
10
10
|
import { UsageError } from "./args.js";
|
|
@@ -185,15 +185,23 @@ function openInBrowser(url) {
|
|
|
185
185
|
* Browser sign-in: prints (and tries to open) Kanorio's approval page, waits for the user to approve, then stores the tokens in the config file.
|
|
186
186
|
* No key is copied or pasted along the way; when a coding assistant runs the command, it only has to hand the link to the user.
|
|
187
187
|
*/
|
|
188
|
+
/** A permission name as the API spells it, for example `marketing:manage` (the API decides which ones exist) */
|
|
189
|
+
const SCOPE_SHAPE = /^[a-z][a-z_]*:[a-z][a-z_]*$/;
|
|
188
190
|
async function loginWithBrowser(cli, ctx) {
|
|
189
191
|
const apiUrl = resolveAuth({ api: cli.flags.api }, ctx.env).apiUrl;
|
|
192
|
+
const scopes = [...new Set(cli.flags.scope)];
|
|
193
|
+
const malformed = scopes.find((scope) => !SCOPE_SHAPE.test(scope));
|
|
194
|
+
if (malformed)
|
|
195
|
+
throw new UsageError(`"${malformed}" is not a permission name. Use the name from the error or from \`kanorio whoami\`, for example --scope marketing:manage.`);
|
|
190
196
|
const log = ctx.log ?? ((line) => void process.stderr.write(`${line}\n`));
|
|
191
197
|
const listener = await startLoopbackListener();
|
|
192
198
|
try {
|
|
193
199
|
const { verifier, challenge } = createPkce();
|
|
194
200
|
const state = randomState();
|
|
195
|
-
const url = buildAuthorizeUrl({ apiUrl, redirectUri: listener.redirectUri, challenge, state });
|
|
196
|
-
log(
|
|
201
|
+
const url = buildAuthorizeUrl({ apiUrl, redirectUri: listener.redirectUri, challenge, state, scopes });
|
|
202
|
+
log(scopes.length > 0
|
|
203
|
+
? `Open this link to approve the added permission${scopes.length > 1 ? "s" : ""} (${scopes.join(", ")}) for the CLI:`
|
|
204
|
+
: "Open this link to sign in to Kanorio and choose what the CLI may do:");
|
|
197
205
|
log(` ${url}`);
|
|
198
206
|
log("Waiting for approval in the browser (the link works for 5 minutes)…");
|
|
199
207
|
if (!cli.flags.noBrowser)
|
|
@@ -202,7 +210,13 @@ async function loginWithBrowser(cli, ctx) {
|
|
|
202
210
|
const tokens = await exchangeAuthorizationCode({ apiUrl, code, verifier, redirectUri: listener.redirectUri, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
|
|
203
211
|
const { token: _replaced, ...current } = readConfig(ctx.env);
|
|
204
212
|
void _replaced;
|
|
213
|
+
const previous = current.oauth;
|
|
205
214
|
const path = writeConfig({ ...current, oauth: { ...tokens, apiUrl }, ...(cli.flags.api ? { apiUrl } : {}) }, ctx.env);
|
|
215
|
+
// The session this sign-in replaces is no longer reachable from this machine: revoke it, so the account lists one CLI
|
|
216
|
+
// connection with the permissions just approved instead of the old and the new one side by side. Best effort.
|
|
217
|
+
if (previous && previous.apiUrl === apiUrl && previous.refreshToken !== tokens.refreshToken) {
|
|
218
|
+
await revokeToken({ apiUrl, token: previous.refreshToken, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
|
|
219
|
+
}
|
|
206
220
|
// Show the user who is signed in and which sites can be changed; failing to ask does not affect the sign-in
|
|
207
221
|
const who = await request({
|
|
208
222
|
apiUrl,
|
|
@@ -224,10 +238,14 @@ async function loginWithBrowser(cli, ctx) {
|
|
|
224
238
|
}
|
|
225
239
|
}
|
|
226
240
|
/**
|
|
227
|
-
* `kanorio login`: opens the browser for approval by default (no key to copy).
|
|
241
|
+
* `kanorio login`: opens the browser for approval by default (no key to copy). `--scope <permission>` asks for more
|
|
242
|
+
* permissions on top of what the CLI already has; the approval page lists the additions.
|
|
228
243
|
* `--token <pat>` or a PAT on stdin stores that token; `--with-token` pastes one in the terminal (not echoed).
|
|
229
244
|
*/
|
|
230
245
|
const login = async (cli, ctx) => {
|
|
246
|
+
if (cli.flags.scope.length > 0 && (cli.flags.token !== undefined || cli.flags.withToken)) {
|
|
247
|
+
throw new UsageError("--scope asks for permissions during browser sign-in. A token's permissions are set where the token was created.");
|
|
248
|
+
}
|
|
231
249
|
if (cli.flags.token !== undefined)
|
|
232
250
|
return storePersonalToken(cli, ctx, cli.flags.token);
|
|
233
251
|
if (cli.flags.withToken) {
|
|
@@ -389,13 +407,19 @@ const domainsBind = async (cli, ctx) => authed(cli, ctx).call("PUT", `/sites/${e
|
|
|
389
407
|
const mediaList = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media`);
|
|
390
408
|
const mediaUpload = async (cli, ctx) => {
|
|
391
409
|
const siteId = encodeURIComponent(need(cli, 0, "siteId"));
|
|
392
|
-
if (cli.flags.url)
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
410
|
+
if (!cli.flags.url && !cli.flags.file)
|
|
411
|
+
throw new UsageError("media upload needs --url <https://…> or --file <path>.");
|
|
412
|
+
// The file's details travel with the upload; the file name comes from --name, otherwise from --file
|
|
413
|
+
const details = {
|
|
414
|
+
...(cli.flags.name ? { fileName: cli.flags.name } : cli.flags.file ? { fileName: basename(cli.flags.file) } : {}),
|
|
415
|
+
...(cli.flags.alt ? { altText: cli.flags.alt } : {}),
|
|
416
|
+
...(cli.flags.tag.length > 0 ? { tags: cli.flags.tag } : {}),
|
|
417
|
+
...(cli.flags.credit ? { credit: cli.flags.credit } : {}),
|
|
418
|
+
...(cli.flags.sourceUrl ? { sourceUrl: cli.flags.sourceUrl } : {}),
|
|
419
|
+
};
|
|
420
|
+
const headers = cli.flags.idempotencyKey ? { "idempotency-key": cli.flags.idempotencyKey } : undefined;
|
|
421
|
+
const source = cli.flags.url ? { url: cli.flags.url } : { base64: readFileSync(cli.flags.file).toString("base64") };
|
|
422
|
+
return authed(cli, ctx).call("POST", `/sites/${siteId}/media`, { body: { ...source, ...details }, headers });
|
|
399
423
|
};
|
|
400
424
|
const mediaUploadLink = async (cli, ctx) => authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/upload-links`, {
|
|
401
425
|
body: {
|
|
@@ -464,8 +488,16 @@ const typesGenerate = async (cli, ctx) => {
|
|
|
464
488
|
collections = Array.isArray(body.data) ? body.data : [];
|
|
465
489
|
}
|
|
466
490
|
else {
|
|
467
|
-
|
|
468
|
-
collections =
|
|
491
|
+
// collections.list is paginated: follow nextCursor so a site with many collections gets all of its types
|
|
492
|
+
collections = [];
|
|
493
|
+
let cursor;
|
|
494
|
+
for (let page = 0; page < 50; page += 1) {
|
|
495
|
+
const res = await authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(target)}/collections`, { query: { limit: "100", ...(cursor ? { cursor } : {}) } });
|
|
496
|
+
collections.push(...(Array.isArray(res.data) ? res.data : []));
|
|
497
|
+
cursor = res.nextCursor ?? undefined;
|
|
498
|
+
if (!cursor)
|
|
499
|
+
break;
|
|
500
|
+
}
|
|
469
501
|
}
|
|
470
502
|
const code = generateCollectionTypes(collections);
|
|
471
503
|
if (cli.flags.out) {
|
package/dist/help.js
CHANGED
|
@@ -7,6 +7,10 @@ Auth
|
|
|
7
7
|
and permissions, then stores the session (~/.config/kanorio/config.json, 0600).
|
|
8
8
|
No key is copied or pasted, so a coding assistant can run it for you: it prints the
|
|
9
9
|
link, you open it. --no-browser prints the link without opening it.
|
|
10
|
+
login --scope <permission> Ask for more permissions on top of what the CLI already has, for example
|
|
11
|
+
--scope marketing:manage (repeat the flag or separate names with commas). The approval
|
|
12
|
+
page lists only the additions. Use it when a command answers FORBIDDEN with
|
|
13
|
+
reason missing_scope; the error names the permission.
|
|
10
14
|
login --with-token Paste a personal access token instead (hidden prompt); or pipe it: echo $TOKEN | kanorio login
|
|
11
15
|
login --token <pat> Store a personal access token given on the command line
|
|
12
16
|
logout Remove the stored session or token (a browser session is also revoked on the server)
|
|
@@ -66,7 +70,10 @@ Domains
|
|
|
66
70
|
|
|
67
71
|
Images
|
|
68
72
|
media list <siteId>
|
|
69
|
-
media upload <siteId> --url <https://…> | --file <
|
|
73
|
+
media upload <siteId> --url <https://…> | --file <path> [--name <file name>] [--alt <text>] [--tag <tag>]...
|
|
74
|
+
[--credit <text>] [--source-url <url>] [--idempotency-key <key>]
|
|
75
|
+
The file name defaults to the --file name (or the last part of --url); --alt is for images.
|
|
76
|
+
With --idempotency-key a retried upload returns the first one instead of storing the file twice.
|
|
70
77
|
media upload-link <siteId> [--max <n>] [--purpose <text>] Page for the user to send photos (15 min)
|
|
71
78
|
media upload-link-status <siteId> --upload-token <token>
|
|
72
79
|
media search-stock <siteId> <query…> [--orientation landscape] [--provider pexels|pixabay] [--max <n>]
|
package/dist/oauth.js
CHANGED
|
@@ -34,6 +34,11 @@ export function createPkce() {
|
|
|
34
34
|
export function managementResource(apiUrl) {
|
|
35
35
|
return `${apiUrl.replace(/\/+$/, "")}/api/v1`;
|
|
36
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* `scopes` are the permissions this sign-in asks for. Without them the approval page starts from Kanorio's default set
|
|
39
|
+
* (or from what this CLI was already granted); with them it adds these to what was already granted and lists the additions,
|
|
40
|
+
* so the user approves exactly the new permissions. The user can still change the selection on the page.
|
|
41
|
+
*/
|
|
37
42
|
export function buildAuthorizeUrl(params) {
|
|
38
43
|
const url = new URL(`${params.apiUrl.replace(/\/+$/, "")}/oauth/authorize`);
|
|
39
44
|
url.searchParams.set("response_type", "code");
|
|
@@ -43,6 +48,8 @@ export function buildAuthorizeUrl(params) {
|
|
|
43
48
|
url.searchParams.set("code_challenge_method", "S256");
|
|
44
49
|
url.searchParams.set("state", params.state);
|
|
45
50
|
url.searchParams.set("resource", managementResource(params.apiUrl));
|
|
51
|
+
if (params.scopes && params.scopes.length > 0)
|
|
52
|
+
url.searchParams.set("scope", params.scopes.join(" "));
|
|
46
53
|
return url.toString();
|
|
47
54
|
}
|
|
48
55
|
const page = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title>` +
|
package/dist/output.js
CHANGED
|
@@ -74,6 +74,26 @@ export function formatResult(data, json) {
|
|
|
74
74
|
}
|
|
75
75
|
return renderObject(obj);
|
|
76
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* The credential lacks a permission. Where to add it depends on the credential, so the hint names the exact next step:
|
|
79
|
+
* a browser sign-in asks for the permission again (or the user allows the request in the dashboard), a personal access
|
|
80
|
+
* token is edited in the dashboard.
|
|
81
|
+
*/
|
|
82
|
+
function missingPermissionHint(details) {
|
|
83
|
+
if (!details || typeof details !== "object")
|
|
84
|
+
return null;
|
|
85
|
+
const { reason, requiredScope, credentialKind, manageUrl } = details;
|
|
86
|
+
if (reason !== "missing_scope" || typeof requiredScope !== "string")
|
|
87
|
+
return null;
|
|
88
|
+
if (credentialKind === "OAUTH") {
|
|
89
|
+
const dashboard = typeof manageUrl === "string" ? `, or allow it in the dashboard at ${manageUrl}` : "";
|
|
90
|
+
return `hint: this sign-in was not granted "${requiredScope}". To add it, run: kanorio login --scope ${requiredScope}${dashboard}`;
|
|
91
|
+
}
|
|
92
|
+
if (credentialKind === "PAT" && typeof manageUrl === "string") {
|
|
93
|
+
return `hint: this token was not granted "${requiredScope}". Add it to the token at ${manageUrl}`;
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
77
97
|
export function formatError(error, json) {
|
|
78
98
|
if (error instanceof ApiError) {
|
|
79
99
|
const payload = {
|
|
@@ -94,6 +114,9 @@ export function formatError(error, json) {
|
|
|
94
114
|
lines.push(`retry after ${error.retryAfter}s`);
|
|
95
115
|
if (error.code === "UNAUTHORIZED")
|
|
96
116
|
lines.push("hint: run `kanorio login` or set KANORIO_TOKEN.");
|
|
117
|
+
const permissionHint = missingPermissionHint(error.details);
|
|
118
|
+
if (permissionHint)
|
|
119
|
+
lines.push(permissionHint);
|
|
97
120
|
if (error.code === "CONFLICT")
|
|
98
121
|
lines.push("hint: re-run `pages get` and retry with the new updatedAt.");
|
|
99
122
|
return { text: lines.join("\n"), exitCode: error.exitCode };
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Copied from Kanorio's shared code by `pnpm --filter @kanorio/cli gen`. Do not edit by hand; a contract test keeps the two copies identical.
|
|
2
|
+
/**
|
|
3
|
+
* JSON Schema (the subset collection `json` fields accept) → a TypeScript type literal, for `kanorio types`.
|
|
4
|
+
* The server puts the result in the `tsType` of `GET /api/v1/collections`; the CLI keeps a copy of this module
|
|
5
|
+
* for collections read through the Management API. No imports: the CLI copies this file as is.
|
|
6
|
+
*/
|
|
7
|
+
/** The type of a `json` field without a schema: any JSON value (null is the field being empty, typed separately) */
|
|
8
|
+
export const JSON_VALUE_TS_TYPE = "string | number | boolean | unknown[] | { [key: string]: unknown }";
|
|
9
|
+
function isSchema(value) {
|
|
10
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
11
|
+
}
|
|
12
|
+
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
13
|
+
function propertyKey(key) {
|
|
14
|
+
return IDENTIFIER.test(key) ? key : JSON.stringify(key);
|
|
15
|
+
}
|
|
16
|
+
/** A comment that cannot end the comment block early */
|
|
17
|
+
function jsDoc(text) {
|
|
18
|
+
if (typeof text !== "string" || !text.trim())
|
|
19
|
+
return "";
|
|
20
|
+
return `/** ${text.replace(/\*\//g, "*\\/").replace(/\s+/g, " ").trim()} */ `;
|
|
21
|
+
}
|
|
22
|
+
function literal(value) {
|
|
23
|
+
return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? JSON.stringify(value) : "unknown";
|
|
24
|
+
}
|
|
25
|
+
function union(types) {
|
|
26
|
+
const unique = [...new Set(types)];
|
|
27
|
+
if (unique.length === 0)
|
|
28
|
+
return "never";
|
|
29
|
+
if (unique.length === 1)
|
|
30
|
+
return unique[0];
|
|
31
|
+
return unique.map((t) => (t.includes(" | ") && !t.startsWith("(") ? `(${t})` : t)).join(" | ");
|
|
32
|
+
}
|
|
33
|
+
function objectType(schema) {
|
|
34
|
+
const properties = isSchema(schema.properties) ? schema.properties : {};
|
|
35
|
+
const required = new Set(Array.isArray(schema.required) ? schema.required.filter((k) => typeof k === "string") : []);
|
|
36
|
+
const members = Object.entries(properties)
|
|
37
|
+
.filter(([, sub]) => isSchema(sub))
|
|
38
|
+
.map(([key, sub]) => `${jsDoc(sub.description)}${propertyKey(key)}${required.has(key) ? "" : "?"}: ${jsonSchemaTsType(sub)};`);
|
|
39
|
+
const extra = schema.additionalProperties;
|
|
40
|
+
if (members.length === 0) {
|
|
41
|
+
// No declared properties: a map; `additionalProperties: false` leaves only the empty object
|
|
42
|
+
if (extra === false)
|
|
43
|
+
return "Record<string, never>";
|
|
44
|
+
return `{ [key: string]: ${isSchema(extra) ? jsonSchemaTsType(extra) : "unknown"} }`;
|
|
45
|
+
}
|
|
46
|
+
// Declared properties plus extra keys: the index signature has to accept the declared ones too, so it stays unknown
|
|
47
|
+
if (extra === true || isSchema(extra))
|
|
48
|
+
members.push("[key: string]: unknown;");
|
|
49
|
+
return `{ ${members.join(" ")} }`;
|
|
50
|
+
}
|
|
51
|
+
function typeOf(name, schema) {
|
|
52
|
+
switch (name) {
|
|
53
|
+
case "object":
|
|
54
|
+
return objectType(schema);
|
|
55
|
+
case "array":
|
|
56
|
+
return isSchema(schema.items) ? `Array<${jsonSchemaTsType(schema.items)}>` : "unknown[]";
|
|
57
|
+
case "string":
|
|
58
|
+
return "string";
|
|
59
|
+
case "number":
|
|
60
|
+
case "integer":
|
|
61
|
+
return "number";
|
|
62
|
+
case "boolean":
|
|
63
|
+
return "boolean";
|
|
64
|
+
case "null":
|
|
65
|
+
return "null";
|
|
66
|
+
default:
|
|
67
|
+
return "unknown";
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** The TypeScript type of a value that matches `schema` */
|
|
71
|
+
export function jsonSchemaTsType(schema) {
|
|
72
|
+
if (!isSchema(schema))
|
|
73
|
+
return "unknown";
|
|
74
|
+
if ("const" in schema)
|
|
75
|
+
return literal(schema.const);
|
|
76
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0)
|
|
77
|
+
return union(schema.enum.map(literal));
|
|
78
|
+
const branches = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : null;
|
|
79
|
+
if (branches)
|
|
80
|
+
return union(branches.map((branch) => jsonSchemaTsType(branch)));
|
|
81
|
+
const type = schema.type;
|
|
82
|
+
if (typeof type === "string")
|
|
83
|
+
return typeOf(type, schema);
|
|
84
|
+
if (Array.isArray(type))
|
|
85
|
+
return union(type.filter((t) => typeof t === "string").map((t) => typeOf(t, schema)));
|
|
86
|
+
// No type: infer from the keywords that only apply to one type
|
|
87
|
+
if (isSchema(schema.properties) || "additionalProperties" in schema)
|
|
88
|
+
return objectType(schema);
|
|
89
|
+
if ("items" in schema)
|
|
90
|
+
return typeOf("array", schema);
|
|
91
|
+
return "unknown";
|
|
92
|
+
}
|
package/dist/types-codegen.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* they come from `virtualFields` in the `/collections` response (scope `item` goes on the item, `fieldData` goes in the field data)
|
|
8
8
|
* - Response types for `/pages`, `/globals/*`, `/forms/*`, `/redirects` and `/site` are included, so one file covers the whole Delivery API
|
|
9
9
|
*/
|
|
10
|
+
import { JSON_VALUE_TS_TYPE, jsonSchemaTsType } from "./shared/json-schema-ts.js";
|
|
10
11
|
function toPascalCase(key) {
|
|
11
12
|
const parts = key
|
|
12
13
|
.replace(/[^a-zA-Z0-9]+/g, " ")
|
|
@@ -65,7 +66,8 @@ function fieldTsType(field) {
|
|
|
65
66
|
case "multi_reference":
|
|
66
67
|
return { type: "string[]", doc: "Referenced item ids — see `expanded` when `?expand=` is used" };
|
|
67
68
|
case "json":
|
|
68
|
-
|
|
69
|
+
// The Management API sends the schema without tsType; without a schema the value is any JSON value, not only an object
|
|
70
|
+
return field.schema !== undefined ? { type: jsonSchemaTsType(field.schema) } : { type: JSON_VALUE_TS_TYPE };
|
|
69
71
|
case "rich_text":
|
|
70
72
|
return { type: "string", doc: "Markdown" };
|
|
71
73
|
default:
|
|
@@ -81,7 +83,7 @@ export interface DeliveryAsset {
|
|
|
81
83
|
url: string;
|
|
82
84
|
width: number | null;
|
|
83
85
|
height: number | null;
|
|
84
|
-
/**
|
|
86
|
+
/** The asset's default alt text, or the alt written next to the image in rich text and the share image. For an image or gallery field, the item's \`imageAlt\` wins where set */
|
|
85
87
|
alt: string | null;
|
|
86
88
|
/** Default focal point (0-1 on the original) for object-position or crop gravity; null when unset or centered */
|
|
87
89
|
focus: { x: number; y: number } | null;
|
|
@@ -92,15 +94,26 @@ export interface DeliveryAsset {
|
|
|
92
94
|
kind: DeliveryAssetKind;
|
|
93
95
|
/** Low-quality image placeholder data URL (16px WebP); null for SVG, animated images and legacy uploads */
|
|
94
96
|
placeholder: string | null;
|
|
97
|
+
/** Credit line set in the media library (photographer or rights holder); filled automatically for stock photos */
|
|
98
|
+
credit: string | null;
|
|
99
|
+
/** Where the file came from (the stock photo's page, the original source) */
|
|
100
|
+
sourceUrl: string | null;
|
|
95
101
|
}
|
|
96
102
|
|
|
97
103
|
export type DeliveryAssetMap = Record<string, DeliveryAsset>;
|
|
98
104
|
|
|
105
|
+
/**
|
|
106
|
+
* Alt text written for an image where the item uses it, keyed by field id and then asset id:
|
|
107
|
+
* \`imageAlt.cover?.[fieldData.cover]\`. Use it instead of \`assets[id].alt\` when present. The same text in every locale.
|
|
108
|
+
*/
|
|
109
|
+
export type ImageAltMap = Record<string, Record<string, string>>;
|
|
110
|
+
|
|
99
111
|
export interface ExpandedReference<TFieldData = Record<string, unknown>> {
|
|
100
112
|
id: string;
|
|
101
113
|
slug: string;
|
|
102
114
|
title: string;
|
|
103
115
|
fieldData: TFieldData;
|
|
116
|
+
imageAlt: ImageAltMap;
|
|
104
117
|
}
|
|
105
118
|
|
|
106
119
|
export interface DeliveryItemEnvelope<TFieldData, TExpanded = Record<string, unknown>> {
|
|
@@ -116,6 +129,8 @@ export interface DeliveryItemEnvelope<TFieldData, TExpanded = Record<string, unk
|
|
|
116
129
|
publishedAt: string | null;
|
|
117
130
|
updatedAt: string;
|
|
118
131
|
fieldData: TFieldData;
|
|
132
|
+
/** Alt text written for an image where this item uses it (image and gallery fields that \`fieldData\` includes) */
|
|
133
|
+
imageAlt: ImageAltMap;
|
|
119
134
|
expanded?: TExpanded;
|
|
120
135
|
/** Multilingual sites: the locale this item was served in (the requested locale when a translation exists, otherwise the primary locale) */
|
|
121
136
|
resolvedLocale?: string;
|
|
@@ -123,7 +138,10 @@ export interface DeliveryItemEnvelope<TFieldData, TExpanded = Record<string, unk
|
|
|
123
138
|
availableLocales?: string[];
|
|
124
139
|
/** Multilingual sites: the slug in every live locale */
|
|
125
140
|
localeSlugs?: Record<string, string>;
|
|
126
|
-
/**
|
|
141
|
+
/**
|
|
142
|
+
* Multilingual sites, items that have a page (\`path\`): the item's path in every live locale, without the locale prefix. Pass it to
|
|
143
|
+
* \`seoMetadata\`, \`buildAlternates\` or \`languageSwitcher\`, which add each locale's prefix; \`path\` already has the prefix of the response's locale.
|
|
144
|
+
*/
|
|
127
145
|
localePaths?: Record<string, string>;
|
|
128
146
|
}
|
|
129
147
|
|
|
@@ -311,6 +329,10 @@ export interface DeliveryFormSubmitBody {
|
|
|
311
329
|
export interface DeliveryFormSubmitResponse {
|
|
312
330
|
ok: true;
|
|
313
331
|
state?: "closed" | "not_open" | "full";
|
|
332
|
+
/** Id of this submission; absent when state is present */
|
|
333
|
+
submissionId?: string;
|
|
334
|
+
/** Where to send the visitor now, when the form has a redirect after submit; answers are already filled in */
|
|
335
|
+
redirectUrl?: string;
|
|
314
336
|
}
|
|
315
337
|
`;
|
|
316
338
|
export function generateCollectionTypes(collections) {
|
|
@@ -330,12 +352,17 @@ export function generateCollectionTypes(collections) {
|
|
|
330
352
|
lines.push(`export interface ${pascal}FieldData {`);
|
|
331
353
|
for (const field of col.fields) {
|
|
332
354
|
const prop = formatPropertyKey(field.id);
|
|
333
|
-
const { type, doc } = fieldTsType(field);
|
|
355
|
+
const { type, doc: typeDoc } = fieldTsType(field);
|
|
356
|
+
const doc = typeof field.tsDoc === "string" && field.tsDoc.trim() ? field.tsDoc.trim().replaceAll("*/", "*\\/") : typeDoc;
|
|
334
357
|
if (doc)
|
|
335
358
|
lines.push(` /** ${doc} */`);
|
|
336
359
|
lines.push(field.required ? ` ${prop}: ${type};` : ` ${prop}?: ${type} | null;`);
|
|
337
360
|
}
|
|
361
|
+
const fieldIds = new Set(col.fields.map((field) => field.id));
|
|
338
362
|
for (const v of virtualFieldData) {
|
|
363
|
+
// A virtual field with the id of a real field (the taxonomies' counts) is already declared above: declaring it twice is a type error
|
|
364
|
+
if (fieldIds.has(v.id))
|
|
365
|
+
continue;
|
|
339
366
|
if (v.description)
|
|
340
367
|
lines.push(` /** ${v.description} */`);
|
|
341
368
|
lines.push(` ${formatPropertyKey(v.id)}?: ${v.tsType};`);
|
|
@@ -380,6 +407,8 @@ export function generateCollectionTypes(collections) {
|
|
|
380
407
|
lines.push("export interface KanorioCollectionsMap {");
|
|
381
408
|
for (const col of collections) {
|
|
382
409
|
const pascal = knownByKey.get(col.key) ?? toPascalCase(col.key);
|
|
410
|
+
if (col.singleton)
|
|
411
|
+
lines.push(` /** Single-item collection: GET /api/v1/collections/${col.key}/item returns \`single\` */`);
|
|
383
412
|
lines.push(` ${formatPropertyKey(col.key)}: {`);
|
|
384
413
|
lines.push(` fieldData: ${pascal}FieldData;`);
|
|
385
414
|
lines.push(` expanded: ${pascal}Expanded;`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kanorio/cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "Thin command-line wrapper around the Kanorio Management API (/api/v1), TypeScript codegen (kanorio types), and external frontend doctor (kanorio doctor).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"private": false,
|
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
},
|
|
43
43
|
"scripts": {
|
|
44
44
|
"build": "tsc -p tsconfig.build.json",
|
|
45
|
+
"gen": "node scripts/copy-shared.mjs",
|
|
45
46
|
"typecheck": "tsc --noEmit",
|
|
46
47
|
"test": "vitest run",
|
|
47
48
|
"lint": "echo \"@kanorio/cli: no eslint config yet\""
|