@kanorio/cli 1.2.0 → 1.4.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/args.js CHANGED
@@ -75,6 +75,10 @@ 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,
80
84
  scope: (values.scope ?? []).flatMap((value) => value.split(/[\s,]+/)).filter(Boolean),
@@ -122,6 +126,10 @@ const OPTIONS = {
122
126
  "key-name": { type: "string" },
123
127
  data: { type: "string" },
124
128
  "idempotency-key": { type: "string" },
129
+ alt: { type: "string" },
130
+ tag: { type: "string", multiple: true },
131
+ credit: { type: "string" },
132
+ "source-url": { type: "string" },
125
133
  "with-token": { type: "boolean", default: false },
126
134
  "no-browser": { type: "boolean", default: false },
127
135
  scope: { type: "string", multiple: true },
package/dist/bin.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createRequire } from "node:module";
3
3
  import { parseCliArgs, UsageError } from "./args.js";
4
4
  import { formatDeprecationWarning } from "./client.js";
5
- import { resolveCommand } from "./commands.js";
5
+ import { printsRawJson, resolveCommand } from "./commands.js";
6
6
  import { HELP } from "./help.js";
7
7
  import { formatError, formatResult } from "./output.js";
8
8
  const require = createRequire(import.meta.url);
@@ -29,7 +29,7 @@ async function main(argv) {
29
29
  // Deprecation warnings go to stderr: with --json, stdout stays clean JSON
30
30
  onDeprecation: (notice) => process.stderr.write(`${formatDeprecationWarning(notice)}\n`),
31
31
  });
32
- process.stdout.write(`${formatResult(result, json)}\n`);
32
+ process.stdout.write(`${formatResult(result, json || printsRawJson(cli.command))}\n`);
33
33
  return 0;
34
34
  }
35
35
  catch (error) {
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";
@@ -407,13 +407,19 @@ const domainsBind = async (cli, ctx) => authed(cli, ctx).call("PUT", `/sites/${e
407
407
  const mediaList = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media`);
408
408
  const mediaUpload = async (cli, ctx) => {
409
409
  const siteId = encodeURIComponent(need(cli, 0, "siteId"));
410
- if (cli.flags.url) {
411
- return authed(cli, ctx).call("POST", `/sites/${siteId}/media`, { body: { url: cli.flags.url } });
412
- }
413
- if (!cli.flags.file)
414
- throw new UsageError("media upload needs --url <https://…> or --file <image>.");
415
- const base64 = readFileSync(cli.flags.file).toString("base64");
416
- return authed(cli, ctx).call("POST", `/sites/${siteId}/media`, { body: { base64 } });
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 });
417
423
  };
418
424
  const mediaUploadLink = async (cli, ctx) => authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/upload-links`, {
419
425
  body: {
@@ -482,8 +488,16 @@ const typesGenerate = async (cli, ctx) => {
482
488
  collections = Array.isArray(body.data) ? body.data : [];
483
489
  }
484
490
  else {
485
- const res = await authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(target)}/collections`);
486
- collections = Array.isArray(res.data) ? res.data : [];
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
+ }
487
501
  }
488
502
  const code = generateCollectionTypes(collections);
489
503
  if (cli.flags.out) {
@@ -698,3 +712,8 @@ export const COMMANDS = {
698
712
  export function resolveCommand(command) {
699
713
  return COMMANDS[command.join(" ")] ?? null;
700
714
  }
715
+ /** Passthrough commands print the response as JSON even without --json: a table would drop nested fields */
716
+ const RAW_JSON_COMMANDS = new Set(["api"]);
717
+ export function printsRawJson(command) {
718
+ return RAW_JSON_COMMANDS.has(command.join(" "));
719
+ }
package/dist/help.js CHANGED
@@ -70,7 +70,10 @@ Domains
70
70
 
71
71
  Images
72
72
  media list <siteId>
73
- media upload <siteId> --url <https://…> | --file <image>
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.
74
77
  media upload-link <siteId> [--max <n>] [--purpose <text>] Page for the user to send photos (15 min)
75
78
  media upload-link-status <siteId> --upload-token <token>
76
79
  media search-stock <siteId> <query…> [--orientation landscape] [--provider pexels|pixabay] [--max <n>]
@@ -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
+ }
@@ -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
- return { type: "Record<string, unknown>" };
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
- /** Alt written where the image is used, otherwise the asset's default alt text */
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,14 +129,27 @@ 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
- /** Multilingual sites: the locale this item was served in (the requested locale when a translation exists, otherwise the primary locale) */
135
+ /**
136
+ * Multilingual sites: the locale this item was served in (the requested locale when at least one field has a translation,
137
+ * otherwise the primary locale). Fields fall back one by one: check \`fieldLocales\` for a particular field
138
+ */
121
139
  resolvedLocale?: string;
122
140
  /** Multilingual sites: secondary locales that have a published translation of this item */
123
141
  availableLocales?: string[];
142
+ /**
143
+ * Multilingual sites: the locale each translatable field was served in, keyed by its path in \`fieldData\` (\`content\`,
144
+ * \`seo.title\`). A field without a translation shows the primary locale. json, image and gallery fields are never machine-translated
145
+ */
146
+ fieldLocales?: Record<string, string>;
124
147
  /** Multilingual sites: the slug in every live locale */
125
148
  localeSlugs?: Record<string, string>;
126
- /** Multilingual sites, system collections: the path in every live locale (for hreflang and a language switcher) */
149
+ /**
150
+ * Multilingual sites, items that have a page (\`path\`): the item's path in every live locale, without the locale prefix. Pass it to
151
+ * \`seoMetadata\`, \`buildAlternates\` or \`languageSwitcher\`, which add each locale's prefix; \`path\` already has the prefix of the response's locale.
152
+ */
127
153
  localePaths?: Record<string, string>;
128
154
  }
129
155
 
@@ -340,7 +366,11 @@ export function generateCollectionTypes(collections) {
340
366
  lines.push(` /** ${doc} */`);
341
367
  lines.push(field.required ? ` ${prop}: ${type};` : ` ${prop}?: ${type} | null;`);
342
368
  }
369
+ const fieldIds = new Set(col.fields.map((field) => field.id));
343
370
  for (const v of virtualFieldData) {
371
+ // A virtual field with the id of a real field (the taxonomies' counts) is already declared above: declaring it twice is a type error
372
+ if (fieldIds.has(v.id))
373
+ continue;
344
374
  if (v.description)
345
375
  lines.push(` /** ${v.description} */`);
346
376
  lines.push(` ${formatPropertyKey(v.id)}?: ${v.tsType};`);
@@ -385,6 +415,8 @@ export function generateCollectionTypes(collections) {
385
415
  lines.push("export interface KanorioCollectionsMap {");
386
416
  for (const col of collections) {
387
417
  const pascal = knownByKey.get(col.key) ?? toPascalCase(col.key);
418
+ if (col.singleton)
419
+ lines.push(` /** Single-item collection: GET /api/v1/collections/${col.key}/item returns \`single\` */`);
388
420
  lines.push(` ${formatPropertyKey(col.key)}: {`);
389
421
  lines.push(` fieldData: ${pascal}FieldData;`);
390
422
  lines.push(` expanded: ${pascal}Expanded;`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanorio/cli",
3
- "version": "1.2.0",
3
+ "version": "1.4.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\""