@kanorio/cli 0.0.0-stage → 1.0.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/output.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * 輸出:`--json` 原樣印 JSON;否則印人看的扁平格式。錯誤一律到 stderr 並以 code 開頭,方便腳本 grep。
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
+ /** 物件陣列 → 對齊欄位的表格(只取頂層原始值欄位,巢狀用 --json 看) */
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
+ // 常見形狀 { sites: [...] }/{ pages: [...] }:單一陣列欄位直接畫表
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
+ }
@@ -0,0 +1,367 @@
1
+ /**
2
+ * `kanorio types`:從 `/api/v1/collections`(或 Management API `/v1/sites/:id/collections`)自描述 schema
3
+ * 產生 TypeScript 型別定義。
4
+ *
5
+ * - `DeliveryAsset`/`assets` map、`expanded` 一層展開、每個集合的 `FieldData`/`Expanded`/`Item`
6
+ * - 系統集合的投影欄位(blog `segments`/`toc`/`contentHtml`、taxonomy `counts`)不硬編碼,
7
+ * 改讀 `/collections` 回的 `virtualFields`(scope `item` 掛項目頂層、`fieldData` 掛欄位資料)
8
+ * - 附上 `/pages`、`/globals/*`、`/forms/*`、`/redirects`、`/site` 的回應型別,一份檔案覆蓋整個 Delivery API
9
+ */
10
+ function toPascalCase(key) {
11
+ const parts = key
12
+ .replace(/[^a-zA-Z0-9]+/g, " ")
13
+ .trim()
14
+ .split(/\s+/)
15
+ .filter(Boolean);
16
+ const joined = parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1).toLowerCase()).join("");
17
+ return /^[A-Za-z_]/.test(joined) ? joined : `Collection${joined}`;
18
+ }
19
+ function escapeStringLiteral(val) {
20
+ return JSON.stringify(val);
21
+ }
22
+ function isValidIdent(id) {
23
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(id);
24
+ }
25
+ function formatPropertyKey(id) {
26
+ return isValidIdent(id) ? id : escapeStringLiteral(id);
27
+ }
28
+ /** 欄位型別 → TS;日期、網址、email 等仍是 string,但以 JSDoc 標出格式讓 IDE 提示 */
29
+ function fieldTsType(field) {
30
+ switch (field.type) {
31
+ case "number":
32
+ return { type: "number" };
33
+ case "boolean":
34
+ return { type: "boolean" };
35
+ case "date":
36
+ return { type: "string", doc: "ISO date `YYYY-MM-DD`" };
37
+ case "datetime":
38
+ return { type: "string", doc: "ISO 8601 datetime (UTC)" };
39
+ case "url":
40
+ return { type: "string", doc: "Absolute URL" };
41
+ case "email":
42
+ return { type: "string", doc: "Email address" };
43
+ case "phone":
44
+ return { type: "string", doc: "Phone number (E.164)" };
45
+ case "image":
46
+ case "file":
47
+ return { type: "string", doc: "assetId — look it up in the top-level `assets` map" };
48
+ case "reference":
49
+ return { type: "string", doc: "Referenced item id — see `expanded` when `?expand=` is used" };
50
+ case "select":
51
+ if (field.options && field.options.length > 0) {
52
+ return { type: field.options.map((o) => escapeStringLiteral(o.id)).join(" | ") };
53
+ }
54
+ return { type: "string" };
55
+ case "multi_select":
56
+ if (field.options && field.options.length > 0) {
57
+ return { type: `Array<${field.options.map((o) => escapeStringLiteral(o.id)).join(" | ")}>` };
58
+ }
59
+ return { type: "string[]" };
60
+ case "gallery":
61
+ return { type: "string[]", doc: "assetIds — look them up in the top-level `assets` map" };
62
+ case "multi_reference":
63
+ return { type: "string[]", doc: "Referenced item ids — see `expanded` when `?expand=` is used" };
64
+ case "json":
65
+ return { type: "Record<string, unknown>" };
66
+ case "rich_text":
67
+ return { type: "string", doc: "Markdown" };
68
+ default:
69
+ return { type: "string" };
70
+ }
71
+ }
72
+ const COMMON_TYPES = `// Generated by \`kanorio types\` — do not edit by hand.
73
+
74
+ export type DeliveryAssetKind = "image" | "video" | "audio" | "pdf" | "document";
75
+
76
+ export interface DeliveryAsset {
77
+ assetId: string;
78
+ url: string;
79
+ width: number | null;
80
+ height: number | null;
81
+ /** Alt written where the image is used, otherwise the asset's default alt text */
82
+ alt: string | null;
83
+ /** Default focal point (0-1 on the original) for object-position or crop gravity; null when unset or centered */
84
+ focus: { x: number; y: number } | null;
85
+ /** url is the watermarked version (or a placeholder while it is being made) */
86
+ watermarked: boolean;
87
+ mimeType: string;
88
+ fileSize: number | null;
89
+ kind: DeliveryAssetKind;
90
+ /** Low-quality image placeholder data URL (16px WebP); null for SVG, animated images and legacy uploads */
91
+ placeholder: string | null;
92
+ }
93
+
94
+ export type DeliveryAssetMap = Record<string, DeliveryAsset>;
95
+
96
+ export interface ExpandedReference<TFieldData = Record<string, unknown>> {
97
+ id: string;
98
+ slug: string;
99
+ title: string;
100
+ fieldData: TFieldData;
101
+ }
102
+
103
+ export interface DeliveryItemEnvelope<TFieldData, TExpanded = Record<string, unknown>> {
104
+ id: string;
105
+ slug: string;
106
+ publishedAt: string | null;
107
+ updatedAt: string;
108
+ fieldData: TFieldData;
109
+ expanded?: TExpanded;
110
+ }
111
+
112
+ export interface DeliveryListResponse<TItem> {
113
+ data: TItem[];
114
+ hasMore: boolean;
115
+ nextCursor: string | null;
116
+ /** 只在請求帶 total=true 時出現 */
117
+ total?: number;
118
+ assets: DeliveryAssetMap;
119
+ }
120
+
121
+ export interface DeliverySingleResponse<TItem> {
122
+ item: TItem;
123
+ assets: DeliveryAssetMap;
124
+ }
125
+
126
+ export interface DeliveryError {
127
+ error: { code: string; message: string; issues?: unknown };
128
+ }
129
+
130
+ // ---- /site ----
131
+
132
+ export type DeliverySiteBrandLogo = { type: "image"; url: string } | { type: "icon"; icon: string };
133
+
134
+ export interface DeliverySiteBrandColor {
135
+ background: string;
136
+ foreground: string;
137
+ }
138
+
139
+ export interface DeliverySiteBrandFont {
140
+ id: string;
141
+ family: string;
142
+ stylesheetUrl: string | null;
143
+ locales: string[];
144
+ }
145
+
146
+ /** Brand identity from Site settings › Brand: resolved colors, logo, fonts, corner radius and color scheme (same as hosted checkout, sign-in and emails). */
147
+ export interface DeliverySiteBrand {
148
+ displayName: string | null;
149
+ logo: { light: DeliverySiteBrandLogo | null; dark: DeliverySiteBrandLogo | null };
150
+ colors: { primary: { light: DeliverySiteBrandColor; dark: DeliverySiteBrandColor } };
151
+ cornerRadius: "soft" | "normal" | "sharp";
152
+ /** system follows the visitor's device; light or dark fixes Kanorio's hosted checkout, sign-in and customer account */
153
+ colorScheme: "system" | "light" | "dark";
154
+ radius: Record<string, string>;
155
+ typography: {
156
+ bodyEnFontId: string;
157
+ bodyZhHantFontId: string;
158
+ bodyZhHansFontId: string;
159
+ bodyJaFontId: string;
160
+ bodyKoFontId: string;
161
+ };
162
+ fonts: DeliverySiteBrandFont[];
163
+ }
164
+
165
+ export interface DeliverySiteMeta {
166
+ id: string;
167
+ name: string | null;
168
+ description: string | null;
169
+ locale: string | null;
170
+ timezone: string | null;
171
+ currency: string | null;
172
+ frontendMode: "HOSTED" | "HEADLESS";
173
+ homeUrl: string | null;
174
+ publicVersion: string | null;
175
+ brand: DeliverySiteBrand;
176
+ }
177
+
178
+ // ---- /pages ----
179
+
180
+ export interface DeliveryPageSeo {
181
+ seoTitle: string | null;
182
+ seoDescription: string | null;
183
+ seoKeywords: string[];
184
+ ogTitle: string | null;
185
+ ogDescription: string | null;
186
+ ogImage: string | null;
187
+ ogImageAlt: string | null;
188
+ ogImageFraming?: Record<string, unknown> | null;
189
+ canonicalUrl: string | null;
190
+ robotsIndex: string | null;
191
+ robotsFollow: string | null;
192
+ twitterCard: string | null;
193
+ }
194
+
195
+ export interface DeliveryPageSummary {
196
+ id: string;
197
+ slug: string;
198
+ path: string;
199
+ parentSlug: string | null;
200
+ isDirectory: boolean;
201
+ depth: number;
202
+ ancestors: Array<{ slug: string; path: string; title: string }>;
203
+ breadcrumbs: Array<{ label: string; href: string }>;
204
+ breadcrumbSource: "path" | "override";
205
+ title: string;
206
+ pageType: string;
207
+ isHomePage: boolean;
208
+ order: number;
209
+ globalHeaderId: string | null;
210
+ globalFooterId: string | null;
211
+ seo: DeliveryPageSeo;
212
+ publishedAt: string | null;
213
+ updatedAt: string;
214
+ }
215
+
216
+ export interface DeliveryPageDetail extends DeliveryPageSummary {
217
+ /** Published sections, media URLs resolved. Shapes follow the section catalog (GET /v1/sections on the Management API). */
218
+ sections: Array<Record<string, unknown> & { id: string; type: string }>;
219
+ }
220
+
221
+ export interface DeliveryPagesResponse {
222
+ data: DeliveryPageSummary[];
223
+ hasMore: boolean;
224
+ nextCursor: string | null;
225
+ }
226
+
227
+ export interface DeliveryPageResponse {
228
+ page: DeliveryPageDetail;
229
+ assets: DeliveryAssetMap;
230
+ }
231
+
232
+ // ---- /globals ----
233
+
234
+ export interface DeliveryHeaderResponse {
235
+ key: string;
236
+ isPrimary: boolean;
237
+ header: Record<string, unknown> & { id: string; type: "header"; navItems?: unknown[] };
238
+ siteSettings: Record<string, unknown> | null;
239
+ assets: DeliveryAssetMap;
240
+ }
241
+
242
+ export interface DeliveryFooterResponse {
243
+ footer: Record<string, unknown> & { id: string; type: "footer" };
244
+ siteSettings: Record<string, unknown> | null;
245
+ assets: DeliveryAssetMap;
246
+ }
247
+
248
+ // ---- /redirects ----
249
+
250
+ export interface DeliveryRedirect {
251
+ sourcePath: string;
252
+ targetUrl: string;
253
+ statusCode: 301 | 302;
254
+ source: "user" | "system";
255
+ updatedAt: string;
256
+ }
257
+
258
+ export interface DeliveryRedirectsResponse {
259
+ /** 完整清單,一次回完 */
260
+ data: DeliveryRedirect[];
261
+ hasMore: false;
262
+ nextCursor: null;
263
+ }
264
+
265
+ // ---- /forms ----
266
+
267
+ export interface DeliveryFormResponse {
268
+ form: Record<string, unknown> & {
269
+ id: string;
270
+ name: string;
271
+ availability: "open" | "closed" | "not_open" | "full";
272
+ fields: Array<Record<string, unknown> & { id: string; type: string; label: string; required?: boolean }>;
273
+ };
274
+ }
275
+
276
+ export interface DeliveryFormChallenge {
277
+ nonce: string;
278
+ ts: number;
279
+ sig: string;
280
+ ttl: number;
281
+ }
282
+
283
+ export interface DeliveryFormSubmitBody {
284
+ answers: Record<string, unknown>;
285
+ consent?: boolean;
286
+ consentTextId?: string;
287
+ locale?: string;
288
+ pagePath?: string;
289
+ _hp?: string;
290
+ _challenge: { nonce: string; ts: number; sig: string };
291
+ }
292
+
293
+ export interface DeliveryFormSubmitResponse {
294
+ ok: true;
295
+ state?: "closed" | "not_open" | "full";
296
+ }
297
+ `;
298
+ export function generateCollectionTypes(collections) {
299
+ const knownByKey = new Map();
300
+ for (const col of collections) {
301
+ knownByKey.set(col.key, toPascalCase(col.key));
302
+ }
303
+ const lines = [COMMON_TYPES, "// ---- /collections ----", ""];
304
+ for (const col of collections) {
305
+ const pascal = knownByKey.get(col.key) ?? toPascalCase(col.key);
306
+ const virtualFieldData = (col.virtualFields ?? []).filter((v) => v.scope === "fieldData");
307
+ const virtualItem = (col.virtualFields ?? []).filter((v) => v.scope === "item");
308
+ if (col.displayName || col.description) {
309
+ lines.push(`/** ${[col.displayName, col.description].filter(Boolean).join(" — ")} (${col.key}) */`);
310
+ }
311
+ lines.push(`export interface ${pascal}FieldData {`);
312
+ for (const field of col.fields) {
313
+ const prop = formatPropertyKey(field.id);
314
+ const { type, doc } = fieldTsType(field);
315
+ if (doc)
316
+ lines.push(` /** ${doc} */`);
317
+ lines.push(field.required ? ` ${prop}: ${type};` : ` ${prop}?: ${type} | null;`);
318
+ }
319
+ for (const v of virtualFieldData) {
320
+ if (v.description)
321
+ lines.push(` /** ${v.description} */`);
322
+ lines.push(` ${formatPropertyKey(v.id)}?: ${v.tsType};`);
323
+ }
324
+ lines.push("}");
325
+ lines.push("");
326
+ const refFields = col.fields.filter((f) => f.type === "reference" || f.type === "multi_reference");
327
+ lines.push(`export interface ${pascal}Expanded {`);
328
+ for (const rf of refFields) {
329
+ const prop = formatPropertyKey(rf.id);
330
+ const targetPascal = rf.targetCollectionKey ? knownByKey.get(rf.targetCollectionKey) : undefined;
331
+ const targetType = targetPascal ? `${targetPascal}FieldData` : "Record<string, unknown>";
332
+ lines.push(rf.type === "reference" ? ` ${prop}?: ExpandedReference<${targetType}> | null;` : ` ${prop}?: Array<ExpandedReference<${targetType}>>;`);
333
+ }
334
+ lines.push("}");
335
+ lines.push("");
336
+ if (virtualItem.length > 0) {
337
+ lines.push(`export interface ${pascal}Item extends DeliveryItemEnvelope<${pascal}FieldData, ${pascal}Expanded> {`);
338
+ for (const v of virtualItem) {
339
+ const doc = [v.description, v.when ? `Present when ${v.when}.` : null].filter(Boolean).join(" ");
340
+ if (doc)
341
+ lines.push(` /** ${doc} */`);
342
+ lines.push(` ${formatPropertyKey(v.id)}?: ${v.tsType};`);
343
+ }
344
+ lines.push("}");
345
+ }
346
+ else {
347
+ lines.push(`export type ${pascal}Item = DeliveryItemEnvelope<${pascal}FieldData, ${pascal}Expanded>;`);
348
+ }
349
+ lines.push("");
350
+ }
351
+ lines.push("export interface KanorioCollectionsMap {");
352
+ for (const col of collections) {
353
+ const pascal = knownByKey.get(col.key) ?? toPascalCase(col.key);
354
+ lines.push(` ${formatPropertyKey(col.key)}: {`);
355
+ lines.push(` fieldData: ${pascal}FieldData;`);
356
+ lines.push(` expanded: ${pascal}Expanded;`);
357
+ lines.push(` item: ${pascal}Item;`);
358
+ lines.push(` list: DeliveryListResponse<${pascal}Item>;`);
359
+ lines.push(` single: DeliverySingleResponse<${pascal}Item>;`);
360
+ lines.push(" };");
361
+ }
362
+ lines.push("}");
363
+ lines.push("");
364
+ lines.push("export type KanorioCollectionKey = keyof KanorioCollectionsMap;");
365
+ lines.push("");
366
+ return lines.join("\n");
367
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@kanorio/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Thin command-line wrapper around the Kanorio Management API (/api/v1), TypeScript codegen (kanorio types), and external frontend doctor (kanorio doctor).",
5
+ "license": "MIT",
6
+ "private": false,
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "homepage": "https://kanorio.com/en/developers/cli",
11
+ "bugs": {
12
+ "email": "support@kanorio.com"
13
+ },
14
+ "keywords": [
15
+ "kanorio",
16
+ "cli",
17
+ "headless",
18
+ "typescript",
19
+ "codegen"
20
+ ],
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/Kanorio-Inc/kanorio.git",
24
+ "directory": "packages/cli"
25
+ },
26
+ "type": "module",
27
+ "bin": {
28
+ "kanorio": "./dist/bin.js"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "engines": {
36
+ "node": ">=20"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^20",
40
+ "typescript": "^5",
41
+ "vitest": "^4.1.11"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.build.json",
45
+ "typecheck": "tsc --noEmit",
46
+ "test": "vitest run",
47
+ "lint": "echo \"@kanorio/cli: no eslint config yet\""
48
+ }
6
49
  }