@tamai/hub-cli 0.1.5 → 0.1.6

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @tamai/hub-cli
2
2
 
3
- hub(tamai個人のパーソナルハブ)のタスク看板とプロジェクトを操作する CLI。
3
+ hub(tamai個人のパーソナルハブ)のタスク看板、プロジェクト、インフラ資産を操作する CLI。
4
4
  状態の正本は hub の D1 であり、この CLI はそれを読み書きする唯一の道具である。
5
5
  依存ゼロ(`node:` のみ)。**認証は tamai の Cloudflare Access service token が要る**ので、
6
6
  それを持っていない環境では何もできない。API の契約・権限・エラーの意味は
@@ -63,10 +63,12 @@ service token を複数のエージェントで共有するので、**誰の操
63
63
  hub --help
64
64
  hub task help
65
65
  hub project help
66
+ hub infra help
66
67
  ```
67
68
 
68
69
  動詞は `task` が `new` / `add` / `claim` / `next` / `show` / `report` / `note` / `list` / `audit`、
69
- `project` が `list` / `show` / `create` / `update` / `move`。
70
+ `project` が `list` / `show` / `create` / `update` / `move`、
71
+ `infra` が `list` / `show` / `update` / `link` / `unlink`。
70
72
  **正確なオプションは常に `--help` を見る**(ここにも、スキルにも写経しない)。
71
73
  全動詞が `--json` を受ける。機械が読むときは必ず `--json` を使い、人向けの整形を parse しない。
72
74
 
@@ -96,6 +98,31 @@ URL から決める。`"<ラベル>=<URL>"` の形は従来どおり最初の `=
96
98
  入力した URL は資格情報を抱えていることがあるため、**どのエラー文にも再掲しない**
97
99
  (何番目の `--add-link` か・既存側のラベルだけを出す)。
98
100
 
101
+ ### インフラ資産を読む・更新する
102
+
103
+ ```bash
104
+ hub infra list # 自分で管理する資産だけ(既定)
105
+ hub infra list --management all # 他社管理を含む全件
106
+ hub infra show example.jp
107
+ hub infra update example.jp --status to_cancel --append-note '解約申請済み'
108
+ hub infra update example.jp --prod-platform none # 本番の置き場なし(確定値)
109
+ hub infra link example.jp --project hub
110
+ hub infra unlink example.jp --project hub
111
+ hub infra unlink example.jp # 紐付けを全部外す
112
+ ```
113
+
114
+ `show` / `update` / `link` / `unlink` は資産名の完全一致またはIDで指定し、見つからない場合は
115
+ 近い候補を3件まで出す。`update` は指定した項目だけをPATCHし、version競合時は最新を取り直して
116
+ 1回だけ再試行する。`link` は現在の紐付けへ追加、`unlink` は指定分を削除し、APIへはどちらも
117
+ `PUT /:id/projects` の全置換として送る。
118
+
119
+ `--dns-host` / `--mail-host` / `--migration-plan` / `--contract` / `--hosted-on-basis`は
120
+ `none`で未記入(`null`)へ戻せる。`--prod-platform none`だけは「本番の置き場は無い」という
121
+ 確定済みのenum値を送り、未記入には戻さない。
122
+
123
+ 資産の作成と削除はCLIに持たせない。正確なオプションとserver資産へ指定できない項目は
124
+ `hub infra help` を正本とする。
125
+
99
126
  ### `--repo-card` の出力先は cwd 基準
100
127
 
101
128
  ```bash
@@ -0,0 +1,25 @@
1
+ import { requireSinglePositional, usageError } from "../lib/args.mjs";
2
+ import { printInfraResult } from "../lib/format.mjs";
3
+ import { getInfraAsset, projectSlugs, requireInfraVersion } from "../lib/infra.mjs";
4
+
5
+ export const infraLinkCommand = {
6
+ name: "link",
7
+ options: { allowed: ["project"], repeatable: ["project"] },
8
+ async run({ options, positional, flags, dependencies, api }) {
9
+ const reference = requireSinglePositional(positional, "資産名またはid");
10
+ if (!flags.project || options.project.length === 0) {
11
+ throw usageError("--project <slug> を1つ以上指定してください");
12
+ }
13
+ const additions = options.project.map((slug) => slug.trim());
14
+ if (additions.some((slug) => slug === "")) throw usageError("--project に空文字は指定できません");
15
+
16
+ const current = await getInfraAsset(reference, api);
17
+ const slugs = [...projectSlugs(current.item)];
18
+ for (const slug of additions) if (!slugs.includes(slug)) slugs.push(slug);
19
+ const payload = await api(`/api/infra/assets/${encodeURIComponent(current.item.id)}/projects`, {
20
+ method: "PUT",
21
+ body: JSON.stringify({ version: requireInfraVersion(current.item), project_slugs: slugs }),
22
+ });
23
+ printInfraResult(payload, options.json, dependencies.stdout, "projects");
24
+ },
25
+ };
@@ -0,0 +1,20 @@
1
+ import { usageError } from "../lib/args.mjs";
2
+ import { printInfraResult } from "../lib/format.mjs";
3
+
4
+ export const infraListCommand = {
5
+ name: "list",
6
+ options: { allowed: ["kind", "status", "management", "project", "q"] },
7
+ async run({ options, positional, flags, dependencies, api }) {
8
+ if (positional.length !== 0) throw usageError("listに位置引数は指定できません");
9
+
10
+ const query = new URLSearchParams();
11
+ if (flags.kind) query.set("kind", options.kind);
12
+ if (flags.status) query.set("status", options.status);
13
+ query.set("management", flags.management ? options.management : "self");
14
+ if (flags.project) query.set("project", options.project);
15
+ if (flags.q) query.set("q", options.q);
16
+
17
+ const payload = await api(`/api/infra/assets?${query.toString()}`);
18
+ printInfraResult(payload, options.json, dependencies.stdout, "list");
19
+ },
20
+ };
@@ -0,0 +1,13 @@
1
+ import { requireSinglePositional } from "../lib/args.mjs";
2
+ import { printInfraResult } from "../lib/format.mjs";
3
+ import { getInfraAsset } from "../lib/infra.mjs";
4
+
5
+ export const infraShowCommand = {
6
+ name: "show",
7
+ options: {},
8
+ async run({ options, positional, dependencies, api }) {
9
+ const reference = requireSinglePositional(positional, "資産名またはid");
10
+ const payload = await getInfraAsset(reference, api);
11
+ printInfraResult(payload, options.json, dependencies.stdout, "show");
12
+ },
13
+ };
@@ -0,0 +1,24 @@
1
+ import { requireSinglePositional, usageError } from "../lib/args.mjs";
2
+ import { printInfraResult } from "../lib/format.mjs";
3
+ import { getInfraAsset, projectSlugs, requireInfraVersion } from "../lib/infra.mjs";
4
+
5
+ export const infraUnlinkCommand = {
6
+ name: "unlink",
7
+ options: { allowed: ["project"], repeatable: ["project"] },
8
+ async run({ options, positional, dependencies, api }) {
9
+ const reference = requireSinglePositional(positional, "資産名またはid");
10
+ const removals = options.project.map((slug) => slug.trim());
11
+ if (removals.some((slug) => slug === "")) throw usageError("--project に空文字は指定できません");
12
+
13
+ const current = await getInfraAsset(reference, api);
14
+ const removed = new Set(removals);
15
+ const slugs = removals.length === 0
16
+ ? []
17
+ : projectSlugs(current.item).filter((slug) => !removed.has(slug));
18
+ const payload = await api(`/api/infra/assets/${encodeURIComponent(current.item.id)}/projects`, {
19
+ method: "PUT",
20
+ body: JSON.stringify({ version: requireInfraVersion(current.item), project_slugs: slugs }),
21
+ });
22
+ printInfraResult(payload, options.json, dependencies.stdout, "projects");
23
+ },
24
+ };
@@ -0,0 +1,124 @@
1
+ import { isConflictError, withGuidance } from "../lib/api.mjs";
2
+ import { cliError, requireSinglePositional, usageError } from "../lib/args.mjs";
3
+ import { printInfraResult } from "../lib/format.mjs";
4
+ import {
5
+ INFRA_DOMAIN_ONLY_OPTIONS,
6
+ getInfraAsset,
7
+ getInfraAssetById,
8
+ requireInfraVersion,
9
+ } from "../lib/infra.mjs";
10
+
11
+ const OPTION_FIELDS = {
12
+ status: "status",
13
+ "auto-renew": "auto_renew",
14
+ expires: "expires_on",
15
+ "dns-host": "dns_host",
16
+ "mail-host": "mail_host",
17
+ "migration-plan": "migration_plan",
18
+ management: "management",
19
+ purpose: "purpose",
20
+ provider: "provider",
21
+ "prod-platform": "prod_platform",
22
+ "prod-ref": "prod_ref",
23
+ contract: "contract",
24
+ amount: "amount_yen",
25
+ payer: "payer",
26
+ holder: "holder",
27
+ account: "account",
28
+ "account-ref": "account_ref",
29
+ note: "note",
30
+ "hosted-on-basis": "hosted_on_basis",
31
+ };
32
+
33
+ const ALLOWED_OPTIONS = [...Object.keys(OPTION_FIELDS), "append-note", "hosted-on"];
34
+ const NULLABLE_VALUE_OPTIONS = new Set([
35
+ "dns-host",
36
+ "mail-host",
37
+ "migration-plan",
38
+ "contract",
39
+ "hosted-on-basis",
40
+ ]);
41
+
42
+ function amountValue(value) {
43
+ if (value === "none") return null;
44
+ if (!/^\d+$/.test(value)) throw usageError("--amount は0以上の整数か none を指定してください");
45
+ const parsed = Number(value);
46
+ if (!Number.isSafeInteger(parsed)) throw usageError("--amount は安全な整数の範囲で指定してください");
47
+ return parsed;
48
+ }
49
+
50
+ function bodyFor(current, prepared, appendNote) {
51
+ const body = { version: requireInfraVersion(current), ...prepared };
52
+ if (appendNote !== null) {
53
+ const note = typeof current.note === "string" ? current.note.trim() : "";
54
+ body.note = note === "" ? appendNote : `${note} / ${appendNote}`;
55
+ }
56
+ return body;
57
+ }
58
+
59
+ export const infraUpdateCommand = {
60
+ name: "update",
61
+ options: { allowed: ALLOWED_OPTIONS },
62
+ async run({ options, positional, flags, dependencies, api }) {
63
+ const reference = requireSinglePositional(positional, "資産名またはid");
64
+ if (!ALLOWED_OPTIONS.some((name) => flags[name])) {
65
+ throw usageError(`更新するオプションを指定してください: ${ALLOWED_OPTIONS.map((name) => `--${name}`).join(" / ")}`);
66
+ }
67
+ if (flags.note && flags["append-note"]) {
68
+ throw usageError("--note と --append-note は同時に指定できません");
69
+ }
70
+
71
+ let currentPayload = await getInfraAsset(reference, api);
72
+ let current = currentPayload.item;
73
+ const forbidden = INFRA_DOMAIN_ONLY_OPTIONS.filter((name) => flags[name]);
74
+ if (current.kind === "server" && forbidden.length > 0) {
75
+ throw usageError(`server資産にはドメイン専用オプションを指定できません: ${forbidden.map((name) => `--${name}`).join(" / ")}`);
76
+ }
77
+
78
+ const prepared = {};
79
+ for (const [option, field] of Object.entries(OPTION_FIELDS)) {
80
+ if (!flags[option] || option === "note") continue;
81
+ const value = options[option].trim();
82
+ if (option === "expires") prepared[field] = value === "none" ? null : value;
83
+ else if (option === "amount") prepared[field] = amountValue(value);
84
+ else if (NULLABLE_VALUE_OPTIONS.has(option) && value === "none") prepared[field] = null;
85
+ else prepared[field] = value;
86
+ }
87
+ if (flags.note) prepared.note = options.note.trim();
88
+
89
+ let appendNote = null;
90
+ if (flags["append-note"]) {
91
+ appendNote = options["append-note"].trim();
92
+ if (appendNote === "") throw usageError("--append-note に空文字は指定できません");
93
+ }
94
+
95
+ if (flags["hosted-on"]) {
96
+ const hostReference = options["hosted-on"].trim();
97
+ if (hostReference === "none") {
98
+ prepared.hosted_on = null;
99
+ } else {
100
+ const host = await getInfraAsset(hostReference, api, { kind: "server" });
101
+ if (host.item.kind !== "server") throw cliError("--hosted-on にはserver資産の名前またはidを指定してください");
102
+ prepared.hosted_on = host.item.id;
103
+ }
104
+ }
105
+
106
+ for (let attempt = 0; attempt < 2; attempt += 1) {
107
+ try {
108
+ const payload = await api(`/api/infra/assets/${encodeURIComponent(current.id)}`, {
109
+ method: "PATCH",
110
+ body: JSON.stringify(bodyFor(current, prepared, appendNote)),
111
+ });
112
+ printInfraResult(payload, options.json, dependencies.stdout, "update");
113
+ return;
114
+ } catch (error) {
115
+ if (!isConflictError(error)) throw error;
116
+ if (attempt === 1) {
117
+ throw withGuidance(error, "再取得後にも競合しました。最新の内容を確認してから、もう一度実行してください");
118
+ }
119
+ currentPayload = await getInfraAssetById(current.id, api);
120
+ current = currentPayload.item;
121
+ }
122
+ }
123
+ },
124
+ };
package/lib/args.mjs CHANGED
@@ -77,11 +77,43 @@ export const PROJECT_USAGE = `使い方:
77
77
  オプションは --name=value の形でも書ける(値が -- で始まるときはこの形で渡す)。
78
78
  `;
79
79
 
80
+ export const INFRA_USAGE = `使い方:
81
+ hub infra list [--kind server|domain] [--status <status[,status...]>] [--management self|external|all]
82
+ [--project <slug>] [--q <text>] [--json]
83
+ hub infra show <name|id> [--json]
84
+ hub infra update <name|id> [--status <status>] [--auto-renew on|off|unknown]
85
+ [--expires YYYY-MM-DD|none] [--dns-host <value>|none]
86
+ [--mail-host <value>|none] [--migration-plan <value>|none]
87
+ [--management self|external] [--purpose <text>]
88
+ [--provider <value>] [--prod-platform <value>]
89
+ [--prod-ref <text>] [--contract <value>|none]
90
+ [--amount <円>|none] [--payer <text>] [--holder <text>]
91
+ [--account <text>] [--account-ref <text>]
92
+ [--note <text>] [--append-note <text>]
93
+ [--hosted-on <server name|id>|none]
94
+ [--hosted-on-basis <value>|none] [--json]
95
+ hub infra link <name|id> --project <slug> [--project <slug>]... [--json]
96
+ hub infra unlink <name|id> [--project <slug>]... [--json]
97
+
98
+ list は期限の近い順。既定は --management self で、--management all は全件を返す。
99
+ list の --status はカンマ区切りで複数指定できる。
100
+ show / update / link / unlink の資産は名前の完全一致またはidで指定する。
101
+ update は指定した項目だけを更新する。version競合時は最新を取り直して1回だけ再試行する。
102
+ --append-note は既存noteの末尾へ「 / 」で追記する。
103
+ server資産には dns-host / mail-host / migration-plan / hosted-on / hosted-on-basis /
104
+ prod-platform / prod-ref を指定できない。
105
+ link は現在の紐付けへ追加し、unlink は指定分を外す。unlink の --project 省略は全解除。
106
+ 作成・削除はCLIから行えない。
107
+ オプションは --name=value の形でも書ける(値が -- で始まるときはこの形で渡す)。
108
+ `;
109
+
80
110
  export const USAGE = `使い方:
81
111
  hub task <verb> ... タスク操作(new / add / claim / next / show / report / note / list)
82
112
  hub task help
83
113
  hub project <verb> ... プロジェクト操作(list / show / create / update / move)
84
114
  hub project help
115
+ hub infra <verb> ... インフラ資産操作(list / show / update / link / unlink)
116
+ hub infra help
85
117
  hub --version 入っているCLIの版を出す(hub version も同じ)
86
118
 
87
119
  環境変数:
@@ -118,7 +150,7 @@ export function usageError(message) {
118
150
  }
119
151
 
120
152
  export function usageLineFor(group, verb) {
121
- const usage = group === "task" ? TASK_USAGE : PROJECT_USAGE;
153
+ const usage = group === "task" ? TASK_USAGE : group === "project" ? PROJECT_USAGE : INFRA_USAGE;
122
154
  const lines = usage.split("\n");
123
155
  const prefix = ` hub ${group} ${verb}`;
124
156
  const start = lines.findIndex((line) => line === prefix || line.startsWith(`${prefix} `));
package/lib/cli.mjs CHANGED
@@ -4,6 +4,7 @@
4
4
  //
5
5
  // hub task <verb> ... タスク操作
6
6
  // hub project <verb> ... プロジェクト操作(読み取り + 作成・更新)
7
+ // hub infra <verb> ... インフラ資産操作(読み取り + 更新・紐付け)
7
8
  //
8
9
  // 全サブコマンドが `--json` を受け付け、付けると生のAPI応答をそのまま出力する。
9
10
  //
@@ -22,6 +23,7 @@ import {
22
23
  redactSecrets,
23
24
  } from "./api.mjs";
24
25
  import {
26
+ INFRA_USAGE,
25
27
  PROJECT_USAGE,
26
28
  TASK_USAGE,
27
29
  USAGE,
@@ -29,6 +31,11 @@ import {
29
31
  parseCommandArgs,
30
32
  usageLineFor,
31
33
  } from "./args.mjs";
34
+ import { infraLinkCommand } from "../commands/infra-link.mjs";
35
+ import { infraListCommand } from "../commands/infra-list.mjs";
36
+ import { infraShowCommand } from "../commands/infra-show.mjs";
37
+ import { infraUnlinkCommand } from "../commands/infra-unlink.mjs";
38
+ import { infraUpdateCommand } from "../commands/infra-update.mjs";
32
39
  import { projectCreateCommand } from "../commands/project-create.mjs";
33
40
  import { projectListCommand } from "../commands/project-list.mjs";
34
41
  import { projectMoveCommand } from "../commands/project-move.mjs";
@@ -87,6 +94,16 @@ const COMMAND_GROUPS = {
87
94
  projectUpdateCommand,
88
95
  ]),
89
96
  },
97
+ infra: {
98
+ usage: INFRA_USAGE,
99
+ commands: commandMap([
100
+ infraListCommand,
101
+ infraShowCommand,
102
+ infraUpdateCommand,
103
+ infraLinkCommand,
104
+ infraUnlinkCommand,
105
+ ]),
106
+ },
90
107
  };
91
108
 
92
109
  /**
package/lib/format.mjs CHANGED
@@ -158,3 +158,84 @@ function formatEventValue(value) {
158
158
  if (typeof value === "boolean") return value ? "オン" : "オフ";
159
159
  return String(value) || "なし";
160
160
  }
161
+
162
+ function displayValue(value) {
163
+ if (value === null || value === undefined || value === "") return "-";
164
+ if (typeof value === "object") return JSON.stringify(value);
165
+ return String(value).replace(/\s+/g, " ").trim();
166
+ }
167
+
168
+ function remainingDays(expiresOn, now = new Date()) {
169
+ if (typeof expiresOn !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(expiresOn)) return "-";
170
+ const today = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
171
+ const expiry = Date.parse(`${expiresOn}T00:00:00.000Z`);
172
+ if (Number.isNaN(expiry)) return "-";
173
+ const days = Math.round((expiry - today) / 86_400_000);
174
+ if (days < 0) return `${Math.abs(days)}日超過`;
175
+ if (days === 0) return "本日期限";
176
+ return `残${days}日`;
177
+ }
178
+
179
+ export function infraListLine(item, now = new Date()) {
180
+ const projects = Array.isArray(item?.projects)
181
+ ? item.projects.map((project) => displayValue(project?.slug)).filter((slug) => slug !== "-")
182
+ : [];
183
+ const external = item?.management === "external" ? " [他社管理]" : "";
184
+ return [
185
+ displayValue(item?.name),
186
+ `[${displayValue(item?.kind)}]`,
187
+ `provider:${displayValue(item?.provider)}`,
188
+ `status:${displayValue(item?.status)}`,
189
+ `auto-renew:${displayValue(item?.auto_renew)}`,
190
+ `expires:${displayValue(item?.expires_on)} (${remainingDays(item?.expires_on, now)})`,
191
+ `projects:${projects.join(",") || "-"}${external}`,
192
+ ].join(" ");
193
+ }
194
+
195
+ export function infraAssetLines(item) {
196
+ const fields = [
197
+ "id", "provider", "status", "management", "auto_renew", "expires_on", "purpose",
198
+ "dns_host", "mail_host", "migration_plan", "hosted_on_basis", "prod_platform", "prod_ref",
199
+ "contract", "amount_yen", "payer", "holder", "account", "account_ref", "note", "version",
200
+ "created_at", "updated_at",
201
+ ];
202
+ const lines = [`${displayValue(item?.name)} [${displayValue(item?.kind)}]`];
203
+ for (const field of fields) lines.push(`${field}: ${displayValue(item?.[field])}`);
204
+ if (item?.hosted_on !== undefined) {
205
+ const hosted = item.hosted_on === null
206
+ ? "-"
207
+ : `${displayValue(item.hosted_on.name)} (${displayValue(item.hosted_on.id)})`;
208
+ lines.splice(11, 0, `hosted_on: ${hosted}`);
209
+ }
210
+ const projects = Array.isArray(item?.projects)
211
+ ? item.projects.map((project) => `${displayValue(project?.slug)}(${displayValue(project?.name)})`)
212
+ : [];
213
+ lines.push(`projects: ${projects.join(", ") || "-"}`);
214
+ if (item?.kind === "server") lines.push(`hosted_count: ${displayValue(item?.hosted_count)}`);
215
+ return lines;
216
+ }
217
+
218
+ export function printInfraResult(payload, json, stdout, kind) {
219
+ if (json) {
220
+ stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
221
+ return;
222
+ }
223
+ if (kind === "list") {
224
+ const items = payload?.items ?? [];
225
+ if (items.length === 0) {
226
+ stdout.write("インフラ資産はありません。\n");
227
+ return;
228
+ }
229
+ stdout.write(`${items.map((item) => infraListLine(item)).join("\n")}\n`);
230
+ return;
231
+ }
232
+ const lines = infraAssetLines(payload?.item);
233
+ if (kind === "show" && Array.isArray(payload?.events) && payload.events.length > 0) {
234
+ lines.push("", "events:");
235
+ for (const event of payload.events.slice(0, 5)) {
236
+ const note = event?.note ? ` — ${displayValue(event.note)}` : "";
237
+ lines.push(`- ${displayValue(event?.at)} ${displayValue(event?.kind)} (${displayValue(event?.actor)})${note}`);
238
+ }
239
+ }
240
+ stdout.write(`${lines.join("\n")}\n`);
241
+ }
package/lib/infra.mjs ADDED
@@ -0,0 +1,110 @@
1
+ import { cliError } from "./args.mjs";
2
+
3
+ const ULID_PATTERN = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
4
+
5
+ /** server 行では API の PATCH に送れない、domain 専用のCLIオプション。 */
6
+ export const INFRA_DOMAIN_ONLY_OPTIONS = [
7
+ "dns-host",
8
+ "mail-host",
9
+ "migration-plan",
10
+ "hosted-on",
11
+ "hosted-on-basis",
12
+ "prod-platform",
13
+ "prod-ref",
14
+ ];
15
+
16
+ function oneLine(value) {
17
+ return String(value ?? "").replace(/\s+/g, " ").trim();
18
+ }
19
+
20
+ function levenshtein(left, right) {
21
+ const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
22
+ for (let leftIndex = 0; leftIndex < left.length; leftIndex += 1) {
23
+ const current = [leftIndex + 1];
24
+ for (let rightIndex = 0; rightIndex < right.length; rightIndex += 1) {
25
+ current.push(Math.min(
26
+ current[rightIndex] + 1,
27
+ previous[rightIndex + 1] + 1,
28
+ previous[rightIndex] + (left[leftIndex] === right[rightIndex] ? 0 : 1),
29
+ ));
30
+ }
31
+ previous.splice(0, previous.length, ...current);
32
+ }
33
+ return previous[right.length];
34
+ }
35
+
36
+ function candidateLines(items, reference) {
37
+ const query = reference.toLowerCase();
38
+ return items
39
+ .map((item) => {
40
+ const name = oneLine(item.name);
41
+ const normalized = name.toLowerCase();
42
+ const contains = normalized.includes(query) || query.includes(normalized) ? 0 : 1;
43
+ return { item, name, contains, distance: levenshtein(normalized, query) };
44
+ })
45
+ .sort((left, right) => left.contains - right.contains
46
+ || left.distance - right.distance
47
+ || left.name.localeCompare(right.name, "ja"))
48
+ .slice(0, 3)
49
+ .map(({ item, name }) => `- ${name} [${oneLine(item.kind)}] (${oneLine(item.id)})`);
50
+ }
51
+
52
+ function assertItem(item) {
53
+ if (item === null || typeof item !== "object" || Array.isArray(item)
54
+ || typeof item.id !== "string" || typeof item.name !== "string") {
55
+ throw cliError("infra API応答のitemが不正です");
56
+ }
57
+ return item;
58
+ }
59
+
60
+ export function requireInfraVersion(item) {
61
+ if (!Number.isSafeInteger(item?.version) || item.version < 1) {
62
+ throw cliError("infra API応答のversionが不正です");
63
+ }
64
+ return item.version;
65
+ }
66
+
67
+ /**
68
+ * CLIが受ける `<name|id>` を資産IDへ解決する。
69
+ *
70
+ * 名前は一覧全体(management=all)に対する完全一致だけを採用する。同じ名前が server / domain
71
+ * の両方にあれば曖昧なので勝手に選ばない。候補は表示密度を守るため近い順の3件まで。
72
+ */
73
+ export async function resolveInfraAssetId(reference, api, { kind } = {}) {
74
+ const target = reference.trim();
75
+ if (ULID_PATTERN.test(target)) return target.toUpperCase();
76
+
77
+ const payload = await api("/api/infra/assets?management=all");
78
+ if (!Array.isArray(payload?.items)) throw cliError("infra一覧のAPI応答が不正です");
79
+ const items = payload.items.filter((item) => item !== null && typeof item === "object"
80
+ && typeof item.id === "string" && typeof item.name === "string"
81
+ && (kind === undefined || item.kind === kind));
82
+ const normalized = target.toLowerCase();
83
+ const exact = items.filter((item) => item.name.toLowerCase() === normalized);
84
+ if (exact.length === 1) return exact[0].id;
85
+
86
+ const candidates = candidateLines(exact.length > 1 ? exact : items, target);
87
+ const reason = exact.length > 1
88
+ ? `同名の資産が複数あります: ${target}`
89
+ : kind === "server"
90
+ ? `サーバーの資産を指定してください: ${target}`
91
+ : `資産が見つかりません: ${target}`;
92
+ throw cliError(`${reason}\n候補:\n${candidates.join("\n") || "- 該当なし"}`);
93
+ }
94
+
95
+ export async function getInfraAssetById(id, api) {
96
+ const payload = await api(`/api/infra/assets/${encodeURIComponent(id)}`);
97
+ return { ...payload, item: assertItem(payload?.item) };
98
+ }
99
+
100
+ export async function getInfraAsset(reference, api, options = {}) {
101
+ const id = await resolveInfraAssetId(reference, api, options);
102
+ return await getInfraAssetById(id, api);
103
+ }
104
+
105
+ export function projectSlugs(item) {
106
+ if (!Array.isArray(item?.projects)) return [];
107
+ return item.projects
108
+ .map((project) => oneLine(project?.slug))
109
+ .filter((slug, index, all) => slug !== "" && all.indexOf(slug) === index);
110
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tamai/hub-cli",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "CLI for the hub personal dashboard: D1-backed task board and project registry.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",