@cognelis/jira-cli 0.0.0-stage → 0.7.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/cli.js ADDED
@@ -0,0 +1,1330 @@
1
+ // src/cli.ts
2
+ import { parseArgs } from "node:util";
3
+ import { readFile as readFile2 } from "node:fs/promises";
4
+ import { resolve as resolve2 } from "node:path";
5
+
6
+ // src/errors.ts
7
+ class CliError extends Error {
8
+ code;
9
+ exitCode;
10
+ hint;
11
+ status;
12
+ reason;
13
+ constructor(code, message, exitCode = 2, hint, status, reason) {
14
+ super(message);
15
+ this.code = code;
16
+ this.exitCode = exitCode;
17
+ this.hint = hint;
18
+ this.status = status;
19
+ this.reason = reason;
20
+ }
21
+ }
22
+ function networkError(error) {
23
+ const pending = [error];
24
+ const visited = new Set;
25
+ let reason = "network";
26
+ for (let i = 0;i < 12 && pending.length; i++) {
27
+ const current = pending.shift();
28
+ if (!current || typeof current !== "object" || visited.has(current))
29
+ continue;
30
+ visited.add(current);
31
+ const e = current;
32
+ if (["ENOTFOUND", "EAI_AGAIN"].includes(String(e.code)))
33
+ reason = "dns";
34
+ else if (["TimeoutError", "AbortError"].includes(String(e.name)) || ["ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT"].includes(String(e.code)))
35
+ reason = "timeout";
36
+ else if (["CERT_HAS_EXPIRED", "CERT_NOT_YET_VALID", "DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "ERR_TLS_CERT_ALTNAME_INVALID"].includes(String(e.code)))
37
+ reason = "tls";
38
+ else if (["ECONNREFUSED", "ECONNRESET", "EHOSTUNREACH", "ENETUNREACH"].includes(String(e.code)))
39
+ reason = "connection";
40
+ if (reason !== "network")
41
+ break;
42
+ if (e.cause !== undefined)
43
+ pending.push(e.cause);
44
+ if (Array.isArray(e.errors))
45
+ pending.push(...e.errors.slice(0, 8));
46
+ }
47
+ const diagnosis = {
48
+ dns: ["Jira hostname could not be resolved.", "Check the Jira base URL, DNS and VPN connectivity in this execution environment."],
49
+ timeout: ["Jira request timed out.", "Check server responsiveness, VPN/proxy connectivity and --timeout."],
50
+ tls: ["Jira TLS certificate verification failed.", "Check certificate validity and trust; use NODE_EXTRA_CA_CERTS for an approved enterprise CA."],
51
+ connection: ["Could not establish or maintain the Jira connection.", "Check the server address/port, VPN, proxy and firewall."],
52
+ network: ["Jira request failed or timed out.", "Check DNS, VPN/proxy, TLS trust and --timeout. No TLS verification bypass is provided."]
53
+ }[reason];
54
+ return new CliError("NETWORK_ERROR", diagnosis[0], 4, diagnosis[1], undefined, reason);
55
+ }
56
+ function object(value) {
57
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
58
+ throw new CliError("INVALID_RESPONSE", "Expected a JSON object.", 5);
59
+ }
60
+ return value;
61
+ }
62
+ function items(value) {
63
+ if (!Array.isArray(value))
64
+ throw new CliError("INVALID_RESPONSE", "Expected a JSON array.", 5);
65
+ return value;
66
+ }
67
+ function integer(value, name, min, max) {
68
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max) {
69
+ throw new CliError("INVALID_ARGUMENT", `${name} must be an integer from ${min} to ${max}.`);
70
+ }
71
+ return Number(value);
72
+ }
73
+ function clean(value) {
74
+ return value.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "");
75
+ }
76
+
77
+ // src/config.ts
78
+ import { constants } from "node:fs";
79
+ import { mkdir, open, readFile, rename, rm } from "node:fs/promises";
80
+ import { homedir } from "node:os";
81
+ import { dirname, join, resolve } from "node:path";
82
+ import { randomUUID } from "node:crypto";
83
+
84
+ // src/keychain.ts
85
+ import { spawnSync } from "node:child_process";
86
+ import { createHash } from "node:crypto";
87
+ var service = "com.cognelis.jira-cli";
88
+ function accountFor(path, name, p) {
89
+ return createHash("sha256").update(JSON.stringify([path, name, p.baseUrl, p.auth, p.username, p.keychainId])).digest("hex");
90
+ }
91
+ function security(args, input, allowMissing = false) {
92
+ if (process.platform !== "darwin")
93
+ throw new CliError("KEYCHAIN_UNAVAILABLE", "This profile requires macOS Keychain.", 3);
94
+ const result = spawnSync("/usr/bin/security", args, { input, encoding: "utf8", stdio: "pipe", timeout: 60000 });
95
+ if (allowMissing && result.status === 44)
96
+ return "";
97
+ if (result.status !== 0)
98
+ throw new CliError("KEYCHAIN_ERROR", "macOS Keychain operation failed.", 3, "Unlock the login keychain and allow access. If the entry was removed, run jira-cli init again.");
99
+ return result.stdout.replace(/\n$/, "");
100
+ }
101
+ var keychain = {
102
+ read(account) {
103
+ return security(["find-generic-password", "-s", service, "-a", account, "-w"]);
104
+ },
105
+ write(account, token) {
106
+ const line = `add-generic-password -s ${service} -a ${account} -X ${Buffer.from(token).toString("hex")}
107
+ `;
108
+ if (line.length >= 4096)
109
+ throw new CliError("INVALID_CREDENTIAL", "Token exceeds the macOS security input limit.", 3);
110
+ security(["-i"], line);
111
+ },
112
+ remove(account) {
113
+ security(["delete-generic-password", "-s", service, "-a", account], undefined, true);
114
+ }
115
+ };
116
+ function retireKeychainEntry(path, name, previous) {
117
+ if (!previous?.keychainId)
118
+ return;
119
+ try {
120
+ keychain.remove(accountFor(path, name, previous));
121
+ } catch {
122
+ throw new CliError("KEYCHAIN_CLEANUP", "Profile saved, but its previous Keychain entry could not be removed.", 3);
123
+ }
124
+ }
125
+
126
+ // src/config.ts
127
+ function stringFlag(flags, key) {
128
+ return typeof flags[key] === "string" ? flags[key] : undefined;
129
+ }
130
+ function configPath(flags, env) {
131
+ return resolve(stringFlag(flags, "config") ?? env.JIRA_CONFIG ?? join(homedir(), ".config/jira-cli/config.json"));
132
+ }
133
+ function baseUrl(value) {
134
+ if (/[\\%\s]/.test(value))
135
+ throw new CliError("INVALID_URL", "Base URL must not contain whitespace, backslashes or encoded segments.");
136
+ let url;
137
+ try {
138
+ url = new URL(value);
139
+ } catch {
140
+ throw new CliError("INVALID_URL", "Base URL must be an absolute HTTPS URL.");
141
+ }
142
+ if (url.username || url.password || url.search || url.hash || !["https:", "http:"].includes(url.protocol)) {
143
+ throw new CliError("INVALID_URL", "Base URL cannot contain credentials, query parameters or a fragment.");
144
+ }
145
+ if (url.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
146
+ throw new CliError("INSECURE_URL", "HTTPS is required except for loopback test servers.");
147
+ }
148
+ if (/%|\\/.test(url.pathname) || /(?:^|\/)\.{1,2}(?:\/|$)/.test(value.split("://")[1] ?? "")) {
149
+ throw new CliError("INVALID_URL", "Base URL path must not contain encoded or traversal segments.");
150
+ }
151
+ return url.href.replace(/\/+$/, "");
152
+ }
153
+ function inferFlavor(value) {
154
+ const host = new URL(baseUrl(value)).hostname;
155
+ return host.endsWith(".atlassian.net") || host === "api.atlassian.com" ? "cloud" : "datacenter";
156
+ }
157
+ function profile(value) {
158
+ const p = object(value);
159
+ const allowed = ["baseUrl", "flavor", "auth", "username", "tokenFile", "siteUrl", "keychainId"];
160
+ if (Object.keys(p).some((k) => !allowed.includes(k)))
161
+ throw new CliError("INVALID_CONFIG", "Unknown profile field; credentials must not be stored in config.");
162
+ if (typeof p.baseUrl !== "string" || !["datacenter", "cloud"].includes(String(p.flavor)) || !["bearer", "basic", "none"].includes(String(p.auth))) {
163
+ throw new CliError("INVALID_CONFIG", "Profile requires baseUrl, flavor (datacenter/cloud) and auth (bearer/basic/none).");
164
+ }
165
+ for (const key of ["username", "tokenFile", "siteUrl"]) {
166
+ if (p[key] !== undefined && (typeof p[key] !== "string" || !p[key].trim()))
167
+ throw new CliError("INVALID_CONFIG", `${key} must be a nonempty string.`);
168
+ }
169
+ if (p.username && /[:\r\n]/.test(p.username))
170
+ throw new CliError("INVALID_CONFIG", "Username cannot contain a colon or newline.");
171
+ if (p.flavor === "cloud" && p.auth === "bearer")
172
+ throw new CliError("INVALID_CONFIG", "Cloud uses email + API token with auth=basic; OAuth is not implemented.");
173
+ if (p.tokenFile && !String(p.tokenFile).startsWith("/"))
174
+ throw new CliError("INVALID_CONFIG", "tokenFile must be an absolute path.");
175
+ if (p.keychainId !== undefined && (typeof p.keychainId !== "string" || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(p.keychainId) || p.auth !== "basic" || !p.username || p.tokenFile))
176
+ throw new CliError("INVALID_CONFIG", "Invalid keychain profile.");
177
+ return { ...p, baseUrl: baseUrl(p.baseUrl), ...p.siteUrl ? { siteUrl: baseUrl(p.siteUrl) } : {} };
178
+ }
179
+ async function readConfig(path) {
180
+ try {
181
+ const parsed = object(JSON.parse(await readFile(path, "utf8")));
182
+ if (parsed.schemaVersion !== 1)
183
+ throw new Error("version");
184
+ const profiles = object(parsed.profiles);
185
+ const validated = Object.create(null);
186
+ for (const [name, value] of Object.entries(profiles)) {
187
+ checkName(name);
188
+ validated[name] = profile(value);
189
+ }
190
+ if (parsed.current !== undefined && (typeof parsed.current !== "string" || !Object.hasOwn(validated, parsed.current)))
191
+ throw new Error("current");
192
+ return { schemaVersion: 1, current: parsed.current, profiles: validated };
193
+ } catch (error) {
194
+ if (error.code === "ENOENT")
195
+ return { schemaVersion: 1, profiles: Object.create(null) };
196
+ throw new CliError("INVALID_CONFIG", "Cannot read a valid jira-cli configuration.", 2, "Check the JSON schema, profile fields and file permissions; existing data was not changed.");
197
+ }
198
+ }
199
+ function checkName(name) {
200
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(name) || ["__proto__", "constructor", "prototype"].includes(name)) {
201
+ throw new CliError("INVALID_PROFILE", "Profile names must be 1–64 letters, digits, underscores or hyphens.");
202
+ }
203
+ }
204
+ async function atomicWrite(path, data) {
205
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
206
+ const temporary = `${path}.${randomUUID()}.tmp`;
207
+ try {
208
+ const handle = await open(temporary, "wx", 384);
209
+ try {
210
+ await handle.writeFile(data);
211
+ await handle.sync();
212
+ } finally {
213
+ await handle.close();
214
+ }
215
+ await rename(temporary, path);
216
+ } finally {
217
+ await rm(temporary, { force: true });
218
+ }
219
+ }
220
+ async function updateConfig(path, change) {
221
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
222
+ const lock = path + ".lock";
223
+ const handle = await open(lock, "wx", 384).catch((error) => {
224
+ if (error.code === "EEXIST")
225
+ throw new CliError("CONFIG_BUSY", "Another profile update is in progress.", 2, "Retry after it finishes. If the writer exited unexpectedly, remove the stale config .lock file.");
226
+ throw error;
227
+ });
228
+ try {
229
+ const config = await readConfig(path);
230
+ change(config);
231
+ await atomicWrite(path, JSON.stringify(config, null, 2) + `
232
+ `);
233
+ return config;
234
+ } finally {
235
+ await handle.close();
236
+ await rm(lock);
237
+ }
238
+ }
239
+ async function readToken(path) {
240
+ try {
241
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
242
+ try {
243
+ const stat = await file.stat();
244
+ if (!stat.isFile() || stat.size > 65536 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
245
+ throw new Error("permissions");
246
+ }
247
+ return (await file.readFile("utf8")).trim();
248
+ } finally {
249
+ await file.close();
250
+ }
251
+ } catch {
252
+ throw new CliError("CREDENTIAL_FILE", "Cannot read the token file.", 3, "Use a regular file owned by you with mode 0600; symlinks are rejected.");
253
+ }
254
+ }
255
+ async function connection(flags, env, authenticate = true) {
256
+ const path = configPath(flags, env);
257
+ const config = await readConfig(path);
258
+ const name = stringFlag(flags, "profile") ?? env.JIRA_PROFILE ?? config.current;
259
+ if (name && !Object.hasOwn(config.profiles, name))
260
+ throw new CliError("UNKNOWN_PROFILE", "Selected Jira profile does not exist.");
261
+ const saved = name ? config.profiles[name] : undefined;
262
+ const base = stringFlag(flags, "base-url") ?? env.JIRA_BASE_URL ?? saved?.baseUrl;
263
+ if (!base)
264
+ throw new CliError("CONFIG_REQUIRED", "Set JIRA_BASE_URL or run jira-cli config set.", 2);
265
+ const normalized = baseUrl(base);
266
+ if (saved && normalized !== saved.baseUrl) {
267
+ throw new CliError("PROFILE_MISMATCH", "Base URL override differs from the selected profile.", 2, "Use a separate profile so credentials cannot silently move to another server.");
268
+ }
269
+ const flavor = stringFlag(flags, "flavor") ?? env.JIRA_FLAVOR ?? saved?.flavor ?? inferFlavor(normalized);
270
+ const p = profile({
271
+ baseUrl: normalized,
272
+ flavor,
273
+ auth: stringFlag(flags, "auth") ?? env.JIRA_AUTH ?? saved?.auth ?? (flavor === "cloud" ? "basic" : "bearer"),
274
+ ...saved?.siteUrl ? { siteUrl: saved.siteUrl } : {},
275
+ ...stringFlag(flags, "username") ?? env.JIRA_USERNAME ?? saved?.username ? { username: stringFlag(flags, "username") ?? env.JIRA_USERNAME ?? saved?.username } : {},
276
+ ...stringFlag(flags, "token-file") ?? env.JIRA_TOKEN_FILE ?? saved?.tokenFile ? { tokenFile: resolve(stringFlag(flags, "token-file") ?? env.JIRA_TOKEN_FILE ?? saved.tokenFile) } : {}
277
+ });
278
+ if (saved?.keychainId && !p.tokenFile && p.auth !== "none") {
279
+ if (p.auth === saved.auth && p.username === saved.username)
280
+ p.keychainId = saved.keychainId;
281
+ else if (!env.JIRA_TOKEN)
282
+ throw new CliError("PROFILE_MISMATCH", "Keychain credential belongs to a different login identity.");
283
+ }
284
+ let token;
285
+ if (authenticate && p.auth !== "none") {
286
+ token = env.JIRA_TOKEN;
287
+ if (token === undefined && p.tokenFile)
288
+ token = await readToken(p.tokenFile);
289
+ if (token === undefined && p.keychainId)
290
+ token = keychain.read(accountFor(path, name, p));
291
+ if (!token || /[\r\n]/.test(token))
292
+ throw new CliError("AUTH_REQUIRED", "A nonempty Jira credential is required.", 3, "Set JIRA_TOKEN in the process environment or use --token-file; do not pass secrets as command arguments.");
293
+ if (p.auth === "basic" && !p.username)
294
+ throw new CliError("AUTH_REQUIRED", "Basic authentication requires JIRA_USERNAME (Cloud: account email).", 3);
295
+ }
296
+ return { ...p, token, timeout: integer(stringFlag(flags, "timeout") ?? env.JIRA_TIMEOUT ?? "30", "timeout", 1, 300) * 1000, retries: integer(stringFlag(flags, "retries") ?? "2", "retries", 0, 3) };
297
+ }
298
+
299
+ // src/client.ts
300
+ import { createHash as createHash2 } from "node:crypto";
301
+ import { setTimeout as delay } from "node:timers/promises";
302
+ // package.json
303
+ var package_default = {
304
+ name: "@cognelis/jira-cli",
305
+ version: "0.7.0",
306
+ description: "Read Jira issues, comments and JQL results from Data Center and Cloud",
307
+ type: "module",
308
+ license: "MIT",
309
+ author: "dnvyrn",
310
+ repository: {
311
+ type: "git",
312
+ url: "git+https://github.com/cognelis/jira-cli.git"
313
+ },
314
+ publishConfig: {
315
+ access: "public",
316
+ registry: "https://registry.npmjs.org/"
317
+ },
318
+ bin: {
319
+ "jira-cli": "bin/jira-cli.mjs"
320
+ },
321
+ files: [
322
+ "bin",
323
+ "dist",
324
+ "README.md",
325
+ "CHANGELOG.md",
326
+ "LICENSE",
327
+ "docs",
328
+ "skills"
329
+ ],
330
+ engines: {
331
+ node: ">=22"
332
+ },
333
+ scripts: {
334
+ build: "bun scripts/build.ts",
335
+ test: "bun test",
336
+ typecheck: "tsc --noEmit",
337
+ check: "bun run typecheck && bun test && python3 scripts/release.py check",
338
+ "test:package": "node scripts/package-smoke.mjs",
339
+ "test:live": "node scripts/live-smoke.mjs",
340
+ prepack: "bun run build",
341
+ prepublishOnly: "bun run check && npm run test:package"
342
+ },
343
+ devDependencies: {
344
+ "@types/bun": "1.3.14",
345
+ typescript: "7.0.2"
346
+ }
347
+ };
348
+
349
+ // src/client.ts
350
+ var defaultFields = "summary,description,status,assignee,reporter,priority,issuetype,project,created,updated,labels,components,attachment,issuelinks,subtasks,duedate,comment";
351
+
352
+ class JiraClient {
353
+ config;
354
+ fetcher;
355
+ prefix;
356
+ constructor(config, fetcher = fetch) {
357
+ this.config = config;
358
+ this.fetcher = fetcher;
359
+ this.prefix = `/rest/api/${config.flavor === "cloud" ? "3" : "2"}`;
360
+ }
361
+ redact(message) {
362
+ let result = clean(message);
363
+ if (this.config.token) {
364
+ result = result.replaceAll(this.config.token, "[REDACTED]");
365
+ result = result.replaceAll(Buffer.from(`${this.config.username ?? ""}:${this.config.token}`).toString("base64"), "[REDACTED]");
366
+ }
367
+ return result.slice(0, 1000);
368
+ }
369
+ async request(path, query = {}, body) {
370
+ if (!/^\/[a-zA-Z0-9/_-]+$/.test(path))
371
+ throw new CliError("INVALID_ROUTE", "Invalid Jira API route.");
372
+ const url = new URL(`${this.config.baseUrl}${this.prefix}${path}`);
373
+ for (const [key, value] of Object.entries(query))
374
+ url.searchParams.set(key, value);
375
+ const headers = { accept: "application/json", "user-agent": `jira-cli/${package_default.version}` };
376
+ if (this.config.auth === "bearer")
377
+ headers.authorization = `Bearer ${this.config.token}`;
378
+ if (this.config.auth === "basic")
379
+ headers.authorization = `Basic ${Buffer.from(`${this.config.username}:${this.config.token}`).toString("base64")}`;
380
+ if (body !== undefined)
381
+ headers["content-type"] = "application/json";
382
+ for (let attempt = 0;; attempt++) {
383
+ let response;
384
+ let text;
385
+ try {
386
+ response = await this.fetcher(url, {
387
+ method: body === undefined ? "GET" : "POST",
388
+ headers,
389
+ body: body === undefined ? undefined : JSON.stringify(body),
390
+ redirect: "manual",
391
+ signal: AbortSignal.timeout(this.config.timeout)
392
+ });
393
+ if (response.status >= 300 && response.status < 400) {
394
+ await response.body?.cancel();
395
+ throw new CliError("AUTH_REDIRECT", "Jira redirected the API request.", 3, "Check the base URL and API authentication; browser SSO cookies are not reused.", response.status);
396
+ }
397
+ if ([429, 502, 503, 504].includes(response.status) && attempt < this.config.retries) {
398
+ const retry = response.headers.get("retry-after");
399
+ const seconds = retry === null ? 2 ** attempt : /^\d+$/.test(retry) ? Number(retry) : Math.max(0, (Date.parse(retry) - Date.now()) / 1000);
400
+ if (Number.isFinite(seconds) && seconds <= 10) {
401
+ await response.body?.cancel();
402
+ await delay(seconds * 1000);
403
+ continue;
404
+ }
405
+ }
406
+ const reader = response.body?.getReader();
407
+ const chunks = [];
408
+ let size = 0;
409
+ if (reader) {
410
+ for (;; ) {
411
+ const { done, value } = await reader.read();
412
+ if (done)
413
+ break;
414
+ size += value.byteLength;
415
+ if (size > 10 * 1024 * 1024) {
416
+ await reader.cancel();
417
+ throw new CliError("RESPONSE_TOO_LARGE", "Response exceeds 10 MiB; request fewer fields or a smaller page.", 5);
418
+ }
419
+ chunks.push(value);
420
+ }
421
+ }
422
+ text = Buffer.concat(chunks).toString("utf8");
423
+ } catch (error) {
424
+ if (error instanceof CliError)
425
+ throw error;
426
+ throw networkError(error);
427
+ }
428
+ let data;
429
+ try {
430
+ data = JSON.parse(text);
431
+ } catch {
432
+ data = undefined;
433
+ }
434
+ if (!response.ok) {
435
+ const code = response.status === 401 ? "UNAUTHORIZED" : response.status === 403 ? "FORBIDDEN" : response.status === 404 ? "NOT_FOUND" : response.status === 429 ? "RATE_LIMITED" : "HTTP_ERROR";
436
+ let detail = "";
437
+ if (data && typeof data === "object" && !Array.isArray(data)) {
438
+ const d = data;
439
+ const messages = Array.isArray(d.errorMessages) ? d.errorMessages.filter((v) => typeof v === "string") : [];
440
+ if (d.errors && typeof d.errors === "object")
441
+ messages.push(...Object.values(d.errors).filter((v) => typeof v === "string"));
442
+ detail = messages.join("; ");
443
+ }
444
+ const hints = {
445
+ 401: {
446
+ none: "auth=none sent no credential. Configure a Jira-specific REST credential for this site.",
447
+ basic: "auth=basic was rejected. Check the Jira username and credential, and confirm the site permits REST Basic authentication.",
448
+ bearer: "auth=bearer was rejected. Check the Jira token and site support. Native Jira PATs require 8.14+."
449
+ }[this.config.auth],
450
+ 404: "The issue may not exist or may be hidden by project/issue security permissions.",
451
+ 429: "Wait before retrying; server Retry-After may exceed the automatic retry budget."
452
+ };
453
+ throw new CliError(code, this.redact(`Jira returned HTTP ${response.status}${detail ? `: ${detail}` : "."}`), [401, 403].includes(response.status) ? 3 : 5, hints[response.status], response.status);
454
+ }
455
+ if (!response.headers.get("content-type")?.includes("json") || data === undefined) {
456
+ throw new CliError("INVALID_RESPONSE", "Jira returned non-JSON content, possibly an SSO login page.", 5, "Use a REST API credential supported by this Jira instance.");
457
+ }
458
+ return data;
459
+ }
460
+ }
461
+ async identity() {
462
+ const user = object(await this.request("/myself"));
463
+ const username = [user.name, user.accountId, user.key].find((id) => typeof id === "string" && id.trim());
464
+ if (!username)
465
+ throw new CliError("INVALID_RESPONSE", "Jira /myself returned no account identifier.", 5);
466
+ return { username, displayName: user.displayName ?? null };
467
+ }
468
+ issueKey(ref) {
469
+ if (/^\d+$/.test(ref) || /^[A-Za-z][A-Za-z0-9_]*-\d+$/.test(ref))
470
+ return ref.toUpperCase();
471
+ let url;
472
+ try {
473
+ url = new URL(ref);
474
+ } catch {
475
+ throw new CliError("INVALID_ISSUE", "Expected an issue key, numeric ID or Jira /browse/KEY URL.");
476
+ }
477
+ const site = new URL(this.config.siteUrl ?? this.config.baseUrl);
478
+ if (url.origin !== site.origin || url.username || url.password)
479
+ throw new CliError("ISSUE_HOST_MISMATCH", "Issue URL does not match the configured Jira site.", 2, "Select the matching profile; scoped Cloud API profiles need --site-url when configured.");
480
+ const prefix = site.pathname.replace(/\/$/, "");
481
+ const expected = url.pathname.slice(prefix.length);
482
+ if (!url.pathname.startsWith(prefix) || !/^\/browse\/[A-Za-z][A-Za-z0-9_]*-\d+\/?$/.test(expected))
483
+ throw new CliError("INVALID_ISSUE", "Expected a /browse/KEY URL within the configured site path.");
484
+ return expected.split("/")[2].toUpperCase();
485
+ }
486
+ async issue(ref, fields = defaultFields, expand) {
487
+ return object(await this.request(`/issue/${this.issueKey(ref)}`, { fields, ...expand ? { expand } : {} }));
488
+ }
489
+ fingerprint(path, query) {
490
+ return createHash2("sha256").update(JSON.stringify([this.config.baseUrl, this.config.flavor, path, query])).digest("hex").slice(0, 24);
491
+ }
492
+ decode(cursor, scope, tokenMode) {
493
+ if (!cursor)
494
+ return tokenMode ? "" : 0;
495
+ try {
496
+ if (cursor.length > 16384 || !/^[A-Za-z0-9_-]+$/.test(cursor))
497
+ throw new Error;
498
+ const c = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
499
+ if (c.v !== 1 || c.scope !== scope || (tokenMode ? typeof c.pos !== "string" || !c.pos : !Number.isSafeInteger(c.pos) || c.pos < 0))
500
+ throw new Error;
501
+ return c.pos;
502
+ } catch {
503
+ throw new CliError("INVALID_CURSOR", "Cursor does not belong to this server, query or command.");
504
+ }
505
+ }
506
+ async paginate(path, key, params, options, post = false, tokenMode = false) {
507
+ const scope = this.fingerprint(path, params);
508
+ let pos = this.decode(options.cursor, scope, tokenMode);
509
+ const seen = new Set([pos]);
510
+ const collected = [];
511
+ for (let pageNumber = 0;pageNumber < options.maxPages; pageNumber++) {
512
+ const pagination = tokenMode ? pos ? { nextPageToken: pos } : {} : { startAt: pos };
513
+ const payload = { ...params, ...pagination, maxResults: options.limit };
514
+ const result = object(await this.request(path, post ? {} : Object.fromEntries(Object.entries(payload).map(([k, v]) => [k, String(v)])), post ? payload : undefined));
515
+ const rows = items(result[key]);
516
+ for (const field of ["total", "startAt", "maxResults"]) {
517
+ if (result[field] !== undefined && (typeof result[field] !== "number" || !Number.isSafeInteger(result[field]) || result[field] < 0)) {
518
+ throw new CliError("INVALID_PAGINATION", `Server returned invalid ${field} pagination metadata.`, 5);
519
+ }
520
+ }
521
+ if (result.isLast !== undefined && typeof result.isLast !== "boolean")
522
+ throw new CliError("INVALID_PAGINATION", "Server returned invalid isLast pagination metadata.", 5);
523
+ if (tokenMode && result.nextPageToken !== undefined && result.nextPageToken !== null && typeof result.nextPageToken !== "string")
524
+ throw new CliError("INVALID_PAGINATION", "Server returned invalid nextPageToken pagination metadata.", 5);
525
+ const total = typeof result.total === "number" && Number.isSafeInteger(result.total) && result.total >= 0 ? result.total : undefined;
526
+ let next;
527
+ if (tokenMode) {
528
+ next = typeof result.nextPageToken === "string" && result.nextPageToken ? result.nextPageToken : null;
529
+ if (result.isLast === true)
530
+ next = null;
531
+ if (result.isLast === false && next === null)
532
+ throw new CliError("INVALID_PAGINATION", "Cloud reports more results but provides no nextPageToken.", 5);
533
+ } else {
534
+ if (result.startAt !== undefined && result.startAt !== pos)
535
+ throw new CliError("INVALID_PAGINATION", "Server returned a different pagination offset.", 5);
536
+ const end = pos + rows.length;
537
+ const pageSize = typeof result.maxResults === "number" && result.maxResults > 0 ? result.maxResults : options.limit;
538
+ next = result.isLast === true ? null : result.isLast === false ? end : (total !== undefined ? end >= total : rows.length < pageSize) ? null : end;
539
+ if (rows.length === 0 && (result.isLast === false || total !== undefined && end < total))
540
+ throw new CliError("INVALID_PAGINATION", "Server returned an empty page while reporting more results.", 5);
541
+ }
542
+ collected.push(...rows);
543
+ if (next !== null && seen.has(next))
544
+ throw new CliError("INVALID_PAGINATION", "Server repeated a pagination position.", 5);
545
+ const cursor = next === null ? null : Buffer.from(JSON.stringify({ v: 1, scope, pos: next })).toString("base64url");
546
+ if (!options.all || next === null)
547
+ return { items: collected, hasMore: next !== null, nextCursor: cursor, ...total === undefined ? {} : { total } };
548
+ seen.add(next);
549
+ pos = next;
550
+ }
551
+ throw new CliError("PAGE_LIMIT", "Reached --max-pages before exhausting the results; no partial result was emitted.", 5, "Narrow the JQL, increase --max-pages, or consume one page at a time with --cursor.");
552
+ }
553
+ search(jql, options, fields = "summary,status,assignee,priority,issuetype,project,updated") {
554
+ return this.paginate(this.config.flavor === "cloud" ? "/search/jql" : "/search", "issues", { jql, fields: fields.split(",") }, options, true, this.config.flavor === "cloud");
555
+ }
556
+ comments(ref, options) {
557
+ return this.paginate(`/issue/${this.issueKey(ref)}/comment`, "comments", {}, options);
558
+ }
559
+ async projects(options) {
560
+ if (this.config.flavor === "cloud")
561
+ return this.paginate("/project/search", "values", {}, options);
562
+ if (options.cursor)
563
+ throw new CliError("INVALID_CURSOR", "Data Center project list is unpaginated.");
564
+ return { items: items(await this.request("/project")), nextCursor: null, hasMore: false };
565
+ }
566
+ }
567
+
568
+ // src/completion.ts
569
+ var zshCompletion = `#compdef jira-cli
570
+ _jira-cli() {
571
+ local -a candidates
572
+ case "\${words[CURRENT-1]}" in
573
+ --config|--out|--token-file) _files; return ;;
574
+ esac
575
+ if compset -P '--(config|out|token-file)='; then _files; return; fi
576
+ candidates=("\${(@f)$(command jira-cli __complete --describe "\${words[@]:1:$((CURRENT - 2))}" "$PREFIX")}")
577
+ [[ -n "$candidates[1]" ]] && _describe 'jira-cli' candidates
578
+ }
579
+ if [[ "$funcstack[1]" == _jira-cli ]]; then
580
+ _jira-cli "$@"
581
+ else
582
+ compdef _jira-cli jira-cli
583
+ fi
584
+ `;
585
+ var enums = { auth: ["basic", "bearer", "none"], flavor: ["cloud", "datacenter"] };
586
+ var lists = ["search", "comment list", "attachment list", "project list", "field list", "issue transitions", "profile list"];
587
+ var descriptions = {
588
+ skills: "查看 Agent Skill",
589
+ "skills show": "输出内置 Skill 的 Markdown",
590
+ issue: "查看任务",
591
+ "issue get": "查看任务详情",
592
+ "issue transitions": "列出可用的状态流转",
593
+ comment: "查看评论",
594
+ "comment list": "列出任务评论",
595
+ attachment: "查看附件",
596
+ "attachment list": "列出附件元数据",
597
+ project: "查看项目",
598
+ "project list": "列出项目",
599
+ "project get": "查看项目详情",
600
+ field: "查看字段",
601
+ "field list": "列出 Jira 字段",
602
+ search: "用 JQL 搜索任务",
603
+ config: "管理本地配置",
604
+ "config set": "保存连接配置",
605
+ "config use": "切换当前 profile",
606
+ "config show": "查看本地配置",
607
+ profile: "管理 Jira profile",
608
+ "profile list": "列出已保存的 profile",
609
+ "profile show": "查看单个 profile",
610
+ "profile add": "添加 profile",
611
+ "profile use": "切换默认 profile",
612
+ auth: "检查凭据配置",
613
+ "auth status": "查看凭据来源",
614
+ init: "验证 Jira 登录并保存命名 profile",
615
+ doctor: "检查连接和登录状态",
616
+ whoami: "查看当前 Jira 用户",
617
+ version: "显示版本",
618
+ completion: "生成补全脚本",
619
+ "--profile": "选择已保存的 profile",
620
+ "--config": "指定配置文件",
621
+ "--base-url": "指定 Jira API 地址",
622
+ "--flavor": "选择 Jira 部署类型",
623
+ "--auth": "选择认证方式",
624
+ "--username": "指定 Jira 用户名",
625
+ "--token-file": "指定凭据文件",
626
+ "--timeout": "设置请求超时秒数",
627
+ "--retries": "设置重试次数",
628
+ "--format": "选择输出格式",
629
+ "--out": "写入指定文件",
630
+ "--fields": "选择返回的字段",
631
+ "--expand": "展开附加信息",
632
+ "--all": "读取所有分页",
633
+ "--limit": "设置每页条数",
634
+ "--cursor": "从游标继续读取",
635
+ "--max-pages": "设置最多读取页数",
636
+ "--site-url": "指定 Jira 网页地址",
637
+ "--activate": "设为当前 profile",
638
+ "--overwrite": "替换已有配置",
639
+ "--help": "显示帮助",
640
+ "--version": "显示版本"
641
+ };
642
+ function formats(command) {
643
+ return ["json", "text", ...command === "issue get" ? ["markdown"] : [], ...lists.includes(command) ? ["ndjson"] : []];
644
+ }
645
+ function commandGlobals(command, globals) {
646
+ if (command.startsWith("profile "))
647
+ return ["config", "format", "out"];
648
+ if (command === "init")
649
+ return ["config", "format"];
650
+ return command === "completion" || command === "skills show" ? [] : globals;
651
+ }
652
+ async function suggestions(words, env, commands, globals, strings, describe = false) {
653
+ const partial = words.at(-1) ?? "";
654
+ const positional = [];
655
+ const used = new Set;
656
+ const flags = {};
657
+ let pending = "";
658
+ for (const word of words.slice(0, -1)) {
659
+ if (pending) {
660
+ flags[pending] = word;
661
+ pending = "";
662
+ continue;
663
+ }
664
+ if (!word.startsWith("-")) {
665
+ positional.push(word);
666
+ continue;
667
+ }
668
+ const [option, ...value] = word.replace(/^--/, "").split("=");
669
+ used.add(option);
670
+ if (value.length)
671
+ flags[option] = value.join("=");
672
+ else if (strings.includes(option))
673
+ pending = option;
674
+ }
675
+ const keys = Object.keys(commands);
676
+ const command = Object.hasOwn(commands, positional.slice(0, 2).join(" ")) ? positional.slice(0, 2).join(" ") : positional[0] ?? "";
677
+ const equal = !pending && /^(--([\w-]+)=)/.exec(partial);
678
+ const profileArg = ["profile use", "profile show", "config use"].includes(command) && positional.length === 2 && !partial.startsWith("-");
679
+ const option = pending || equal && equal[2] || (profileArg ? "profile" : "");
680
+ const definition = Object.hasOwn(commands, command) ? commands[command] : undefined;
681
+ const argsComplete = definition && positional.length >= command.split(" ").length + definition.args;
682
+ let choices;
683
+ if (option) {
684
+ if (option === "profile") {
685
+ try {
686
+ choices = Object.keys((await readConfig(configPath(flags, env))).profiles);
687
+ } catch {
688
+ choices = [];
689
+ }
690
+ } else
691
+ choices = option === "format" ? formats(command) : Object.hasOwn(enums, option) ? enums[option] : [];
692
+ if (equal)
693
+ choices = choices.map((value) => equal[1] + value);
694
+ } else if (partial.startsWith("-") || !partial && argsComplete) {
695
+ const options = commandGlobals(command, globals);
696
+ const local = definition?.options ?? [];
697
+ choices = [...options, ...local, "help", ...!positional.length ? ["version"] : []].filter((x) => !used.has(x)).map((x) => "--" + x);
698
+ } else if (!positional.length)
699
+ choices = keys.map((k) => k.split(" ")[0]);
700
+ else if (command === "completion" && positional.length === 1)
701
+ choices = ["zsh"];
702
+ else if (positional.length === 1)
703
+ choices = keys.filter((k) => k.startsWith(command + " ")).map((k) => k.split(" ")[1]);
704
+ else
705
+ choices = [];
706
+ return [...new Set(choices)].filter((value) => value.startsWith(partial)).map((value) => {
707
+ const key = !positional.length || value.startsWith("-") ? value : command + " " + value;
708
+ return describe && !option && Object.hasOwn(descriptions, key) ? value + ":" + descriptions[key] : value;
709
+ });
710
+ }
711
+
712
+ // src/render.ts
713
+ function adfText(value, depth = 0) {
714
+ if (depth > 60)
715
+ return "[nested content omitted]";
716
+ if (typeof value === "string")
717
+ return clean(value);
718
+ if (!value || typeof value !== "object" || Array.isArray(value))
719
+ return "";
720
+ const n = value;
721
+ const attrs = n.attrs && typeof n.attrs === "object" ? n.attrs : {};
722
+ if (n.type === "text")
723
+ return clean(String(n.text ?? ""));
724
+ if (n.type === "status" && typeof attrs.text === "string" && attrs.text.trim())
725
+ return clean(attrs.text);
726
+ if (n.type === "hardBreak")
727
+ return `
728
+ `;
729
+ if (n.type === "mention")
730
+ return clean(String(attrs.text ?? attrs.id ?? "@mention"));
731
+ if (n.type === "emoji")
732
+ return clean(String(attrs.text ?? attrs.shortName ?? ""));
733
+ if (n.type === "inlineCard")
734
+ return clean(String(attrs.url ?? "[link]"));
735
+ if (n.type === "media" || n.type === "mediaInline")
736
+ return "[attachment: see attachment list]";
737
+ const content = Array.isArray(n.content) ? n.content.map((c) => adfText(c, depth + 1)).join("") : "";
738
+ if (n.type === "heading")
739
+ return `${"#".repeat(Math.min(6, Math.max(1, Number(attrs.level) || 2)))} ${content}
740
+
741
+ `;
742
+ if (n.type === "paragraph")
743
+ return `${content}
744
+
745
+ `;
746
+ if (n.type === "listItem")
747
+ return `- ${content.trim()}
748
+ `;
749
+ if (n.type === "codeBlock")
750
+ return `
751
+ \`\`\`
752
+ ${content}
753
+ \`\`\`
754
+
755
+ `;
756
+ if (n.type === "rule")
757
+ return `
758
+ ---
759
+ `;
760
+ if (n.type === "tableCell" || n.type === "tableHeader")
761
+ return `${content.trim()} | `;
762
+ if (n.type === "tableRow")
763
+ return `${content}
764
+ `;
765
+ if (!content && !["doc", "paragraph"].includes(String(n.type)))
766
+ return `[${clean(String(n.type ?? "unsupported content"))}]`;
767
+ return content;
768
+ }
769
+ function name(value) {
770
+ if (!value || typeof value !== "object")
771
+ return "—";
772
+ const v = value;
773
+ return clean(String(v.displayName ?? v.name ?? v.key ?? "—"));
774
+ }
775
+ function issueMarkdown(issue) {
776
+ const f = object(issue.fields);
777
+ const lines = [
778
+ `# ${clean(String(issue.key ?? issue.id))}: ${clean(String(f.summary ?? ""))}`,
779
+ "",
780
+ `- 状态:${name(f.status)}`,
781
+ `- 负责人:${name(f.assignee)}`,
782
+ `- 优先级:${name(f.priority)}`,
783
+ `- 更新时间:${clean(String(f.updated ?? "—"))}`,
784
+ "",
785
+ "## 描述",
786
+ "",
787
+ adfText(f.description).trim() || "(没有描述,或未请求 description 字段)"
788
+ ];
789
+ if (f.comment && typeof f.comment === "object") {
790
+ const comments = f.comment;
791
+ const rows = Array.isArray(comments.comments) ? comments.comments : [];
792
+ lines.push("", "## 评论预览", "", `已返回 ${rows.length} 条;完整分页请使用 comment list --all。`);
793
+ for (const row of rows) {
794
+ if (!row || typeof row !== "object")
795
+ continue;
796
+ const c = row;
797
+ lines.push("", `### ${name(c.author)} · ${clean(String(c.created ?? ""))}`, "", adfText(c.body).trim());
798
+ }
799
+ }
800
+ lines.push("", "> Markdown 是有损阅读视图。自定义字段、附件、富文本和完整响应请使用 JSON。", "");
801
+ return lines.join(`
802
+ `);
803
+ }
804
+ function display(value) {
805
+ if (value === null || value === undefined || value === "")
806
+ return "—";
807
+ if (typeof value === "boolean")
808
+ return value ? "是" : "否";
809
+ return clean(String(value));
810
+ }
811
+ function timestamp(value) {
812
+ return display(value).replace(/^(\d{4}-\d\d-\d\d)T(\d\d:\d\d:\d\d)(?:\.\d+)?(Z|[+-]\d\d:?\d\d)$/, (_, date, time, zone) => `${date} ${time} ${zone.replace(/^([+-]\d\d)(\d\d)$/, "$1:$2")}`);
813
+ }
814
+ function bodyText(value) {
815
+ const text = adfText(value).trim();
816
+ if (typeof value !== "string")
817
+ return text;
818
+ return text.replace(/\[(?:([^\[\]|\n]+)\|)?(https?:\/\/[^\s\[\]|]+)\]/g, (_, label, url) => label ? `${label}(${url})` : url);
819
+ }
820
+ function indent(text) {
821
+ return text.replace(/^(?=.)/gm, " ");
822
+ }
823
+ function listHeading(label, count, total) {
824
+ const partial = typeof total === "number" && total !== count;
825
+ return `${label}(${count}${partial ? " / " + total : ""} 条)`;
826
+ }
827
+ function humanOutput(command, data, terminal) {
828
+ const color = terminal && !terminal.NO_COLOR && terminal.TERM !== "dumb";
829
+ const accent = /256color|direct/i.test(terminal?.TERM ?? "") || terminal?.COLORTERM ? "38;5;174" : "33";
830
+ const style = (code, text) => color ? `\x1B[${code}m${text}\x1B[0m` : text;
831
+ const issueHeading = (key, summary) => style(accent, "◆ " + key) + " " + style("1", display(summary));
832
+ const detail = (label, value) => " " + style("2", label) + value;
833
+ const assignee = (value) => value === null ? "未分配" : name(value);
834
+ function commentText(value) {
835
+ const row = object(value);
836
+ return [
837
+ style(accent, "●") + " " + style("1", name(row.author)),
838
+ " " + style("2", `${timestamp(row.created)} · #${display(row.id)}`),
839
+ indent(bodyText(row.body))
840
+ ].join(`
841
+ `);
842
+ }
843
+ const d = object(data);
844
+ if (command === "issue get") {
845
+ const f = object(d.fields);
846
+ const key = display(d.key ?? d.id);
847
+ const lines = [issueHeading(key, f.summary)];
848
+ if ("status" in f)
849
+ lines.push(detail("状态 ", name(f.status)));
850
+ if ("assignee" in f)
851
+ lines.push(detail("负责人 ", assignee(f.assignee)));
852
+ if ("priority" in f)
853
+ lines.push(detail("优先级 ", name(f.priority)));
854
+ if ("updated" in f)
855
+ lines.push(detail("更新时间 ", timestamp(f.updated)));
856
+ if ("description" in f)
857
+ lines.push("", style("1", "描述"), indent(bodyText(f.description) || style("2", "(无描述)")));
858
+ if (f.comment && typeof f.comment === "object") {
859
+ const comments = object(f.comment);
860
+ if (Array.isArray(comments.comments)) {
861
+ const count = comments.comments.length;
862
+ const total = comments.total;
863
+ const preview = total !== count;
864
+ lines.push("", style("1", listHeading(preview ? "评论预览" : "评论", count, total)));
865
+ if (preview)
866
+ lines.push(indent(`jira-cli comment list ${key} --all`));
867
+ for (const row of comments.comments)
868
+ lines.push("", commentText(row));
869
+ }
870
+ }
871
+ return lines.join(`
872
+ `).trimEnd() + `
873
+ `;
874
+ }
875
+ if (command === "version")
876
+ return `jira-cli ${display(d.version)}
877
+ `;
878
+ if (command === "doctor") {
879
+ return [
880
+ style(accent, "◆") + " " + style("1", "Jira 连接诊断"),
881
+ detail("站点 ", display(d.baseUrl)),
882
+ detail("部署类型 ", display(d.deploymentType)),
883
+ detail("接口类型 ", display(d.flavor)),
884
+ detail("服务版本 ", display(d.serverVersion)),
885
+ detail("CLI 版本 ", display(d.cliVersion)),
886
+ "",
887
+ style(accent, "●") + " " + style("1", d.authenticated === true ? "身份已验证" : "身份未验证"),
888
+ detail("用户名 ", display(d.username)),
889
+ detail("显示名称 ", display(d.displayName)),
890
+ ""
891
+ ].join(`
892
+ `);
893
+ }
894
+ if (Array.isArray(d.items)) {
895
+ const count = d.items.length;
896
+ if (command === "profile list") {
897
+ const lines = [style("1", `已保存的 profile(${count} 个)`)];
898
+ for (const item of d.items) {
899
+ const p = object(item);
900
+ const marker = p.name === d.current ? "* " : " ";
901
+ lines.push(style(accent, marker + display(p.name)) + " " + display(p.baseUrl) + " " + display(p.auth));
902
+ }
903
+ return lines.join(`
904
+ `) + `
905
+ `;
906
+ }
907
+ const title = command === "comment list" ? "评论" : command === "search" ? "搜索结果" : "";
908
+ const lines = [title ? style("1", listHeading(title, count, d.total)) : `共返回 ${count} 条${typeof d.total === "number" ? `(共 ${d.total} 条)` : ""}`];
909
+ for (const item of d.items) {
910
+ const row = object(item);
911
+ if (command === "search") {
912
+ const fields = object(row.fields ?? {});
913
+ lines.push("", issueHeading(display(row.key ?? row.id), fields.summary));
914
+ const meta = [];
915
+ if ("status" in fields)
916
+ meta.push("状态 " + name(fields.status));
917
+ if ("assignee" in fields)
918
+ meta.push("负责人 " + assignee(fields.assignee));
919
+ if ("priority" in fields)
920
+ meta.push("优先级 " + name(fields.priority));
921
+ if (meta.length)
922
+ lines.push(indent(style("2", meta.join(" · "))));
923
+ } else if (command === "comment list") {
924
+ lines.push("", commentText(row));
925
+ } else if (command === "attachment list") {
926
+ lines.push(`${display(row.filename)} ${display(row.mimeType)} ${display(row.size)} 字节 (ID ${display(row.id)})`);
927
+ } else
928
+ lines.push(`${display(row.key ?? row.id)} ${display(row.name)}`);
929
+ }
930
+ if (d.hasMore)
931
+ lines.push("", `下一页:--cursor ${display(d.nextCursor)}`);
932
+ return lines.join(`
933
+ `) + `
934
+ `;
935
+ }
936
+ if (command === "config show") {
937
+ const lines = [`配置文件:${display(d.path)}`, `当前 profile:${display(d.current)}`];
938
+ for (const [key, value] of Object.entries(object(d.profiles))) {
939
+ const p = object(value);
940
+ lines.push(`${display(key)} ${display(p.baseUrl)} ${display(p.auth)}`);
941
+ }
942
+ return lines.join(`
943
+ `) + `
944
+ `;
945
+ }
946
+ const labels = {
947
+ baseUrl: "Jira 地址",
948
+ flavor: "接口类型",
949
+ serverVersion: "服务端版本",
950
+ deploymentType: "部署类型",
951
+ username: "用户名",
952
+ name: "名称",
953
+ displayName: "显示名称",
954
+ accountId: "账号 ID",
955
+ authenticated: "登录已验证",
956
+ cliVersion: "CLI 版本",
957
+ auth: "认证方式",
958
+ credentialSource: "凭据来源",
959
+ verified: "本次已验证身份",
960
+ profile: "profile",
961
+ current: "当前 profile",
962
+ path: "配置文件",
963
+ key: "标识",
964
+ id: "ID",
965
+ description: "描述",
966
+ siteUrl: "网页地址"
967
+ };
968
+ return Object.entries(labels).filter(([key]) => Object.hasOwn(d, key)).map(([key, label]) => `${label}:${display(d[key])}`).join(`
969
+ `) + `
970
+ `;
971
+ }
972
+
973
+ // src/init.ts
974
+ import { spawnSync as spawnSync2 } from "node:child_process";
975
+ import { randomUUID as randomUUID2 } from "node:crypto";
976
+ function prompt(label, hidden = false) {
977
+ if (process.platform !== "darwin")
978
+ throw new CliError("KEYCHAIN_UNAVAILABLE", "jira-cli init requires macOS Keychain.", 3, "On this platform, use config set with JIRA_TOKEN or a restricted token file.");
979
+ if (!process.stdin.isTTY || !process.stderr.isTTY)
980
+ throw new CliError("TTY_REQUIRED", "Run jira-cli init in an interactive terminal.");
981
+ const script = `IFS= read ${hidden ? "-rs" : "-r"} -p "$1" answer || exit 1; printf '%s' "$answer"`;
982
+ const result = spawnSync2("/bin/bash", ["--noprofile", "--norc", "-c", script, "jira-cli", label], { env: {}, encoding: "utf8", stdio: ["inherit", "pipe", "inherit"] });
983
+ if (hidden)
984
+ process.stderr.write(`
985
+ `);
986
+ if (result.status !== 0)
987
+ throw new CliError("INIT_CANCELLED", "Jira setup was cancelled.");
988
+ return result.stdout;
989
+ }
990
+ function checkSite(config, name, site) {
991
+ if (config.profiles[name] && config.profiles[name].baseUrl !== site) {
992
+ throw new CliError("PROFILE_MISMATCH", "This profile already belongs to another Jira site.", 2, "Choose a different profile name.");
993
+ }
994
+ }
995
+ async function initProfile(flags, env, askTarget = () => ({ site: prompt("Jira 地址: "), name: prompt("Profile 名称: ") }), askLogin = () => ({ username: prompt("Jira 用户名(Cloud 使用邮箱): ").trim(), token: prompt("Jira API Token: ", true) })) {
996
+ const path = configPath(flags, env);
997
+ const target = askTarget();
998
+ const site = baseUrl(target.site.trim());
999
+ const name = target.name.trim();
1000
+ checkName(name);
1001
+ const config = await readConfig(path);
1002
+ checkSite(config, name, site);
1003
+ const saved = config.profiles[name];
1004
+ const { username, token } = askLogin();
1005
+ if (!username || !token?.trim() || /[\r\n\0]/.test(token))
1006
+ throw new CliError("AUTH_REQUIRED", "Enter a Jira username and API token.", 3);
1007
+ const next = profile({
1008
+ baseUrl: site,
1009
+ flavor: saved?.flavor ?? inferFlavor(site),
1010
+ ...saved?.siteUrl ? { siteUrl: saved.siteUrl } : {},
1011
+ auth: "basic",
1012
+ username,
1013
+ keychainId: randomUUID2()
1014
+ });
1015
+ await new JiraClient({ ...next, token, timeout: 1e4, retries: 0 }).identity();
1016
+ const account = accountFor(path, name, next);
1017
+ let previous;
1018
+ keychain.write(account, token);
1019
+ try {
1020
+ if (keychain.read(account) !== token)
1021
+ throw new CliError("KEYCHAIN_ERROR", "Could not verify the saved Keychain entry.", 3);
1022
+ await updateConfig(path, (config) => {
1023
+ checkSite(config, name, site);
1024
+ previous = config.profiles[name];
1025
+ config.profiles[name] = next;
1026
+ config.current = name;
1027
+ });
1028
+ } catch (error) {
1029
+ keychain.remove(account);
1030
+ throw error;
1031
+ }
1032
+ retireKeychainEntry(path, name, previous);
1033
+ return { profile: name, baseUrl: site, credentialSource: "keychain", verified: true };
1034
+ }
1035
+
1036
+ // src/cli.ts
1037
+ var globals = ["config", "profile", "base-url", "flavor", "auth", "username", "token-file", "timeout", "retries", "format", "out"];
1038
+ var pagination = ["limit", "cursor", "all", "max-pages"];
1039
+ var commands = {
1040
+ "skills show": { args: 0, options: [], usage: "skills show (print the bundled Agent Skill as Markdown, offline)" },
1041
+ completion: { args: 1, options: [], usage: "completion zsh (print shell completion script)" },
1042
+ init: { args: 0, options: [], usage: "init (macOS: enter a Jira URL and profile name, verify login and save to Keychain)" },
1043
+ "issue get": { args: 1, options: ["fields", "expand"], usage: "issue get <KEY|ID|URL> [--fields summary,description] [--expand names] [--format markdown]" },
1044
+ "issue transitions": { args: 1, options: [], usage: "issue transitions <KEY|ID|URL> (list available transitions)" },
1045
+ search: { args: 1, options: [...pagination, "fields"], usage: "search <JQL> [--all] [--limit 50] [--cursor CURSOR] [--max-pages 100]" },
1046
+ "comment list": { args: 1, options: pagination, usage: "comment list <KEY|ID|URL> [--all] [--cursor CURSOR]" },
1047
+ "attachment list": { args: 1, options: [], usage: "attachment list <KEY|ID|URL> (metadata; no file download)" },
1048
+ "project list": { args: 0, options: pagination, usage: "project list [--all]" },
1049
+ "project get": { args: 1, options: [], usage: "project get <KEY|ID>" },
1050
+ "field list": { args: 0, options: [], usage: "field list (discover customfield_NNN identifiers)" },
1051
+ whoami: { args: 0, options: [], usage: "whoami" },
1052
+ doctor: { args: 0, options: [], usage: "doctor (verify serverInfo and authenticated identity)" },
1053
+ "auth status": { args: 0, options: [], usage: "auth status (local configuration only; does not authenticate)" },
1054
+ "profile list": { args: 0, options: [], usage: "profile [list] (list saved profiles and mark the default)" },
1055
+ "profile show": { args: 1, options: ["profile"], usage: "profile show [NAME] (show one saved profile)" },
1056
+ "profile add": { args: 1, options: ["base-url", "site-url", "flavor", "auth", "username", "token-file", "activate"], usage: "profile add <NAME> --base-url URL [--activate]" },
1057
+ "profile use": { args: 1, options: [], usage: "profile use <NAME> (set the default profile)" },
1058
+ "config set": { args: 1, options: ["site-url", "activate", "overwrite"], usage: "config set <NAME> --base-url URL --flavor datacenter|cloud [--auth bearer|basic|none] [--username USER] [--token-file PATH] [--site-url URL] [--activate] [--overwrite]" },
1059
+ "config use": { args: 1, options: [], usage: "config use <NAME>" },
1060
+ "config show": { args: 0, options: [], usage: "config show" },
1061
+ version: { args: 0, options: [], usage: "version" }
1062
+ };
1063
+ var booleans = ["help", "version", "all", "activate", "overwrite"];
1064
+ var strings = [...new Set([...globals, ...Object.values(commands).flatMap((c) => c.options)])].filter((k) => !booleans.includes(k));
1065
+ function help() {
1066
+ return `jira-cli ${package_default.version} — read-only Jira Data Center / Cloud CLI
1067
+
1068
+ ${Object.values(commands).map((c) => ` jira-cli ${c.usage}`).join(`
1069
+ `)}
1070
+
1071
+ Global options (before or after commands):
1072
+ --profile NAME, --config FILE, --base-url URL, --flavor datacenter|cloud
1073
+ --auth bearer|basic|none, --username USER, --token-file FILE
1074
+ --timeout SECONDS (30), --retries 0..3 (2)
1075
+ --format text|json|ndjson|markdown (terminal: text; pipes/files: json), --out FILE, --help, --version
1076
+
1077
+ Credentials: macOS Keychain (init), JIRA_TOKEN or a mode-0600 token file.
1078
+ No token argument, browser credential extraction or Jira write commands.
1079
+ JSON is lossless. Markdown is only supported by issue get. NDJSON is only for lists.
1080
+ --limit is the page size; --all follows pages up to --max-pages (100).
1081
+ See README.md and docs/api-research.md for setup, endpoints and limitations.
1082
+ `;
1083
+ }
1084
+ var defaultIO = { isTTY: process.stdout.isTTY, out: (text) => {
1085
+ process.stdout.write(text);
1086
+ }, err: (text) => {
1087
+ process.stderr.write(text);
1088
+ } };
1089
+ function parse(argv) {
1090
+ let parsed;
1091
+ try {
1092
+ parsed = parseArgs({ args: argv, allowPositionals: true, strict: true, tokens: true, options: {
1093
+ ...Object.fromEntries(strings.map((k) => [k, { type: "string" }])),
1094
+ ...Object.fromEntries(booleans.map((k) => [k, { type: "boolean", ...k === "help" ? { short: "h" } : k === "version" ? { short: "v" } : {} }]))
1095
+ } });
1096
+ } catch {
1097
+ throw new CliError("INVALID_ARGUMENT", "Unknown option or missing option value.", 2, "Run jira-cli --help. Tokens must be supplied through JIRA_TOKEN or --token-file.");
1098
+ }
1099
+ const seen = new Set;
1100
+ for (const token of parsed.tokens ?? []) {
1101
+ if (token.kind !== "option")
1102
+ continue;
1103
+ if (seen.has(token.name))
1104
+ throw new CliError("INVALID_ARGUMENT", `Option --${token.name} was provided more than once.`);
1105
+ seen.add(token.name);
1106
+ }
1107
+ const flags = parsed.values;
1108
+ const positionals = parsed.positionals;
1109
+ if (flags.help || !positionals.length && !flags.version)
1110
+ return { command: "help", args: [], flags };
1111
+ if (flags.version) {
1112
+ if (positionals.length)
1113
+ throw new CliError("INVALID_ARGUMENT", "--version does not take a command.");
1114
+ return { command: "version", args: [], flags };
1115
+ }
1116
+ const joined = positionals.slice(0, 2).join(" ");
1117
+ const command = joined === "profile" ? "profile list" : Object.hasOwn(commands, joined) ? joined : positionals[0];
1118
+ const definition = commands[command];
1119
+ if (!Object.hasOwn(commands, command))
1120
+ throw new CliError("UNKNOWN_COMMAND", "Unknown command.", 2, "Run jira-cli --help.");
1121
+ const args = positionals.slice(command.includes(" ") ? 2 : 1);
1122
+ const optionalName = command === "profile show" && !args.length;
1123
+ if (!optionalName && args.length !== definition.args || args.some((arg) => !arg.trim()))
1124
+ throw new CliError("INVALID_ARGUMENT", `Usage: jira-cli ${definition.usage}`);
1125
+ const globalOptions = commandGlobals(command, globals);
1126
+ const allowed = new Set([...globalOptions, ...definition.options, "help", "version"]);
1127
+ for (const key of Object.keys(flags))
1128
+ if (!allowed.has(key))
1129
+ throw new CliError("INVALID_ARGUMENT", `--${key} is not supported by ${command}.`);
1130
+ return { command, args, flags };
1131
+ }
1132
+ async function run(argv, env = process.env, io = defaultIO) {
1133
+ let humanErrors = Boolean(io.isTTY) && !argv.some((word) => word === "--format" || word.startsWith("--format="));
1134
+ try {
1135
+ if (argv[0] === "__complete") {
1136
+ const describe = argv[1] === "--describe";
1137
+ for (const word of await suggestions(argv.slice(describe ? 2 : 1), env, commands, globals, strings, describe))
1138
+ io.out(word + `
1139
+ `);
1140
+ return 0;
1141
+ }
1142
+ const { command, args, flags } = parse(argv);
1143
+ if (command === "help") {
1144
+ io.out(help());
1145
+ return 0;
1146
+ }
1147
+ if (command === "skills show") {
1148
+ io.out(await readFile2(new URL("../skills/jira-cli/SKILL.md", import.meta.url), "utf8"));
1149
+ return 0;
1150
+ }
1151
+ if (command === "completion") {
1152
+ if (args[0] !== "zsh")
1153
+ throw new CliError("INVALID_ARGUMENT", "Usage: jira-cli completion zsh");
1154
+ io.out(zshCompletion);
1155
+ return 0;
1156
+ }
1157
+ const format = stringFlag(flags, "format") ?? (io.isTTY && !flags.out ? "text" : "json");
1158
+ humanErrors = format === "text";
1159
+ if (!formats(command).includes(format))
1160
+ throw new CliError("INVALID_ARGUMENT", `Formats for ${command}: ${formats(command).join(", ")}.`);
1161
+ const list = {
1162
+ limit: integer(stringFlag(flags, "limit") ?? "50", "limit", 1, 100),
1163
+ maxPages: integer(stringFlag(flags, "max-pages") ?? "100", "max-pages", 1, 1000),
1164
+ cursor: stringFlag(flags, "cursor"),
1165
+ all: flags.all === true
1166
+ };
1167
+ let data;
1168
+ const notices = [];
1169
+ if (command === "version")
1170
+ data = { version: package_default.version, schemaVersion: 1 };
1171
+ else if (command === "init")
1172
+ data = await initProfile(flags, env);
1173
+ else if (command.startsWith("config ") || command.startsWith("profile ")) {
1174
+ const path = configPath(flags, env);
1175
+ if (command === "config show")
1176
+ data = { path, ...await readConfig(path) };
1177
+ else if (command === "profile list" || command === "profile show") {
1178
+ const { current, profiles } = await readConfig(path);
1179
+ if (command === "profile list") {
1180
+ data = { current: current ?? null, items: Object.entries(profiles).map(([name, p]) => ({ name, baseUrl: p.baseUrl, auth: p.auth })), hasMore: false, nextCursor: null };
1181
+ } else {
1182
+ const name = args[0] ?? stringFlag(flags, "profile") ?? env.JIRA_PROFILE ?? current;
1183
+ if (!name || !Object.hasOwn(profiles, name))
1184
+ throw new CliError("UNKNOWN_PROFILE", "No matching saved profile.", 2, "Run jira-cli profile list.");
1185
+ const { baseUrl, flavor, auth, username, siteUrl } = profiles[name];
1186
+ data = {
1187
+ profile: name,
1188
+ current: current ?? null,
1189
+ baseUrl,
1190
+ flavor,
1191
+ auth,
1192
+ ...siteUrl ? { siteUrl } : {},
1193
+ ...username ? { username } : {}
1194
+ };
1195
+ }
1196
+ } else {
1197
+ const name = args[0];
1198
+ checkName(name);
1199
+ let previous;
1200
+ const config = await updateConfig(path, (config) => {
1201
+ if (command === "config set" || command === "profile add") {
1202
+ if (Object.hasOwn(config.profiles, name) && !flags.overwrite)
1203
+ throw new CliError("PROFILE_EXISTS", "Profile already exists; use config set --overwrite to replace it.");
1204
+ previous = config.profiles[name];
1205
+ const configuredBase = stringFlag(flags, "base-url");
1206
+ if (!configuredBase)
1207
+ throw new CliError("INVALID_ARGUMENT", `${command} requires --base-url URL.`);
1208
+ const flavor = stringFlag(flags, "flavor") ?? inferFlavor(configuredBase);
1209
+ config.profiles[name] = profile({
1210
+ baseUrl: configuredBase,
1211
+ flavor,
1212
+ auth: stringFlag(flags, "auth") ?? (flavor === "cloud" ? "basic" : "bearer"),
1213
+ ...stringFlag(flags, "username") ? { username: stringFlag(flags, "username") } : {},
1214
+ ...stringFlag(flags, "token-file") ? { tokenFile: resolve2(stringFlag(flags, "token-file")) } : {},
1215
+ ...stringFlag(flags, "site-url") ? { siteUrl: stringFlag(flags, "site-url") } : {}
1216
+ });
1217
+ if (flags.activate || !config.current)
1218
+ config.current = name;
1219
+ } else {
1220
+ if (!Object.hasOwn(config.profiles, name))
1221
+ throw new CliError("UNKNOWN_PROFILE", "Selected Jira profile does not exist.");
1222
+ config.current = name;
1223
+ }
1224
+ });
1225
+ retireKeychainEntry(path, name, previous);
1226
+ data = { path, current: config.current, profile: name };
1227
+ }
1228
+ } else {
1229
+ const config = await connection(flags, env, command !== "auth status");
1230
+ const client = new JiraClient(config);
1231
+ if (command === "auth status") {
1232
+ data = {
1233
+ baseUrl: config.baseUrl,
1234
+ flavor: config.flavor,
1235
+ auth: config.auth,
1236
+ username: config.username ?? null,
1237
+ credentialSource: env.JIRA_TOKEN ? "environment" : config.tokenFile ? "file" : config.keychainId ? "keychain" : "none",
1238
+ verified: false
1239
+ };
1240
+ } else if (command === "whoami")
1241
+ data = await client.request("/myself");
1242
+ else if (command === "doctor") {
1243
+ const server = object(await client.request("/serverInfo"));
1244
+ const identity = await client.identity();
1245
+ data = {
1246
+ baseUrl: config.baseUrl,
1247
+ flavor: config.flavor,
1248
+ serverVersion: server.version ?? null,
1249
+ deploymentType: server.deploymentType ?? null,
1250
+ ...identity,
1251
+ authenticated: true,
1252
+ cliVersion: package_default.version
1253
+ };
1254
+ } else if (command === "issue get") {
1255
+ data = await client.issue(args[0], stringFlag(flags, "fields"), stringFlag(flags, "expand"));
1256
+ const f = object(object(data).fields);
1257
+ if (f.comment) {
1258
+ const c = object(f.comment);
1259
+ if (typeof c.total === "number" && Array.isArray(c.comments) && c.total > c.comments.length)
1260
+ notices.push("Embedded comments are incomplete; use comment list --all.");
1261
+ }
1262
+ if (stringFlag(flags, "expand")?.split(",").includes("changelog"))
1263
+ notices.push("Expanded changelog can be truncated by Jira; this CLI does not claim complete change history.");
1264
+ } else if (command === "issue transitions")
1265
+ data = { items: items(object(await client.request(`/issue/${client.issueKey(args[0])}/transitions`)).transitions), hasMore: false, nextCursor: null };
1266
+ else if (command === "search")
1267
+ data = await client.search(args[0], list, stringFlag(flags, "fields"));
1268
+ else if (command === "comment list")
1269
+ data = await client.comments(args[0], list);
1270
+ else if (command === "project list")
1271
+ data = await client.projects(list);
1272
+ else if (command === "project get") {
1273
+ if (!/^[A-Za-z0-9_]+$/.test(args[0]))
1274
+ throw new CliError("INVALID_ARGUMENT", "Project key or numeric ID is required.");
1275
+ data = await client.request(`/project/${args[0]}`);
1276
+ } else if (command === "field list")
1277
+ data = { items: items(await client.request("/field")), hasMore: false, nextCursor: null };
1278
+ else if (command === "attachment list")
1279
+ data = { items: items(object((await client.issue(args[0], "attachment")).fields).attachment), hasMore: false, nextCursor: null };
1280
+ }
1281
+ let text;
1282
+ if (format === "text")
1283
+ text = humanOutput(command, data, io.isTTY && !flags.out ? env : undefined);
1284
+ else if (format === "markdown")
1285
+ text = issueMarkdown(object(data));
1286
+ else if (format === "ndjson") {
1287
+ const page = object(data);
1288
+ text = items(page.items).map((row) => JSON.stringify(row) + `
1289
+ `).join("");
1290
+ if (page.hasMore)
1291
+ io.err(JSON.stringify({ _notice: { pagination: { hasMore: true, nextCursor: page.nextCursor } } }) + `
1292
+ `);
1293
+ } else
1294
+ text = JSON.stringify({ schemaVersion: 1, ok: true, command, data, ...notices.length ? { notices } : {} }, null, 2) + `
1295
+ `;
1296
+ for (const notice of notices)
1297
+ if (format !== "json")
1298
+ io.err((format === "text" ? notice : JSON.stringify({ _notice: { message: notice } })) + `
1299
+ `);
1300
+ const output = stringFlag(flags, "out");
1301
+ if (output) {
1302
+ const path = resolve2(output);
1303
+ await atomicWrite(path, text);
1304
+ if (io.isTTY && (!flags.format || format === "text"))
1305
+ io.out(`已写入 ${clean(path)}(${Buffer.byteLength(text)} 字节)
1306
+ `);
1307
+ else
1308
+ io.out(JSON.stringify({ schemaVersion: 1, ok: true, command, data: { outputPath: path, bytes: Buffer.byteLength(text) } }) + `
1309
+ `);
1310
+ } else
1311
+ io.out(text);
1312
+ return 0;
1313
+ } catch (error) {
1314
+ const e = error instanceof CliError ? error : new CliError("LOCAL_ERROR", "Local operation failed.", 2, "Check input, file permissions and destination directory.");
1315
+ if (humanErrors)
1316
+ io.err(`${e.code} ${clean(e.message)}
1317
+ ${e.hint ? clean(e.hint) + `
1318
+ ` : ""}`);
1319
+ else
1320
+ io.err(JSON.stringify({ schemaVersion: 1, ok: false, error: { code: e.code, message: e.message, ...e.hint ? { hint: e.hint } : {}, ...e.status ? { status: e.status } : {}, ...e.reason ? { reason: e.reason } : {} } }) + `
1321
+ `);
1322
+ return e.exitCode;
1323
+ }
1324
+ }
1325
+ export {
1326
+ help,
1327
+ run
1328
+ };
1329
+
1330
+ //# debugId=1EA8E15506A02F1564756E2164756E21