primcli 3.0.0-preview.19 → 3.0.0-preview.20

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.
@@ -0,0 +1,109 @@
1
+ import { r as retryIdFields } from "./retry-ids-04ZPJCZY.js";
2
+ import { Errors } from "@oclif/core";
3
+ // src/oclif/required-body-fields.ts
4
+ function object(value) {
5
+ return value !== null && typeof value === "object" && !Array.isArray(value);
6
+ }
7
+ function jsonPath(parts) {
8
+ return parts.reduce((path, part) => typeof part === "number" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(part) ? `${path}[${JSON.stringify(part)}]` : `${path}.${part}`, "$");
9
+ }
10
+ /** Only exclude a union branch when a supplied literal contradicts it. */
11
+ function compatible(schema, value) {
12
+ if (!object(schema) || !object(value)) return true;
13
+ const properties = object(schema.properties) ? schema.properties : {};
14
+ for (const [name, property] of Object.entries(properties)) {
15
+ if (!Object.hasOwn(value, name) || !object(property)) continue;
16
+ const literal = value[name];
17
+ if (literal === void 0 || literal !== null && typeof literal === "object") continue;
18
+ if (Object.hasOwn(property, "const") && !object(property.const) && !Array.isArray(property.const) && property.const !== literal) return false;
19
+ if (Array.isArray(property.enum) && !property.enum.includes(literal)) return false;
20
+ }
21
+ return true;
22
+ }
23
+ /**
24
+ * Report missing properties, not type or permission failures. Alternative
25
+ * schemas contribute only omissions shared by every still-possible branch.
26
+ */
27
+ function missingBodyFields(schema, body, flags, required) {
28
+ if (body === void 0 && !required) return [];
29
+ function visit(node, value, path) {
30
+ if (!object(node)) return [];
31
+ const missing = [];
32
+ if (object(value)) {
33
+ const names = Array.isArray(node.required) ? node.required : [];
34
+ for (const name of names) {
35
+ if (typeof name !== "string") continue;
36
+ if (Object.hasOwn(value, name) && value[name] !== void 0) continue;
37
+ missing.push({
38
+ field: name,
39
+ flag: path.length === 0 ? flags.get(name) ?? null : null,
40
+ json_path: jsonPath([...path, name])
41
+ });
42
+ }
43
+ if (object(node.properties)) {
44
+ for (const [name, property] of Object.entries(node.properties)) if (Object.hasOwn(value, name) && value[name] !== void 0) missing.push(...visit(property, value[name], [...path, name]));
45
+ }
46
+ } else if (Array.isArray(value)) for (const [index, item] of value.entries()) missing.push(...visit(node.items, item, [...path, index]));
47
+ if (Array.isArray(node.allOf)) for (const branch of node.allOf) missing.push(...visit(branch, value, path));
48
+ for (const union of [node.oneOf, node.anyOf]) {
49
+ if (!Array.isArray(union)) continue;
50
+ const branches = union.filter((branch) => compatible(branch, value)).map((branch) => visit(branch, value, path));
51
+ if (branches.length === 0) continue;
52
+ missing.push(...branches[0].filter((field) => branches.every((branch) => branch.some((other) => other.json_path === field.json_path))));
53
+ }
54
+ return missing;
55
+ }
56
+ const missing = visit(schema, body === void 0 ? {} : body, []);
57
+ return [...new Map(missing.map((field) => [field.json_path, field])).values()];
58
+ }
59
+ function assertRequiredBodyFields(schema, body, flags, required) {
60
+ const missing = missingBodyFields(schema, body, flags, required);
61
+ if (missing.length === 0 && (!required || body !== void 0)) return;
62
+ const fields = missing.length ? missing : [{
63
+ field: "body",
64
+ flag: null,
65
+ json_path: "$"
66
+ }];
67
+ const message = `Missing required fields: ${fields.map((field) => field.flag ?? field.json_path).join(", ")}. Supply the fields as flags where available, or use --raw-body / --body-file JSON.`;
68
+ throw Object.assign(new Errors.CLIError(message, { exit: 2 }), {
69
+ code: "usage_error",
70
+ details: { missing: fields }
71
+ });
72
+ }
73
+ // src/oclif/help-inputs.ts
74
+ const HELP_GROUPS = [
75
+ "required",
76
+ "command",
77
+ "common"
78
+ ];
79
+ const HELP_GROUP_HEADERS = {
80
+ required: "REQUIRED INPUTS",
81
+ command: "COMMAND OPTIONS",
82
+ common: "COMMON FLAGS"
83
+ };
84
+ const COMMON_FLAGS = /* @__PURE__ */ new Set([
85
+ "api-key",
86
+ "api-base-url",
87
+ "json",
88
+ "time",
89
+ "raw-body",
90
+ "envelope",
91
+ "output",
92
+ "idempotency-key",
93
+ "step-up-token"
94
+ ]);
95
+ function helpFlagGroup(name, flag, inputs, flagNames) {
96
+ if (flag.required || flag.exactlyOne?.length || inputs?.requiredFlags.includes(name)) return "required";
97
+ if (COMMON_FLAGS.has(name) || name === "body-file" && flagNames.has("raw-body")) return "common";
98
+ return "command";
99
+ }
100
+ function operationHelpInputs(operation, bodyFlagToProperty, positionalFlag) {
101
+ const propertyFlags = new Map([...bodyFlagToProperty].map(([flag, property]) => [property, `--${flag}`]));
102
+ const generated = new Set(retryIdFields(operation.requestSchema));
103
+ const missing = operation.bodyRequired || generated.size > 0 ? missingBodyFields(operation.requestSchema, {}, propertyFlags, true).filter((field) => !generated.has(field.field)) : [];
104
+ return {
105
+ requiredFlags: [...missing.flatMap((field) => field.flag ? [field.flag.slice(2)] : []), ...positionalFlag ? [positionalFlag] : []],
106
+ requiredJsonFields: operation.bodyRequired && missing.length === 0 && generated.size === 0 ? ["$"] : missing.filter((field) => field.flag === null).map((field) => field.json_path)
107
+ };
108
+ }
109
+ export { assertRequiredBodyFields as a, operationHelpInputs as i, HELP_GROUP_HEADERS as n, helpFlagGroup as r, HELP_GROUPS as t };
@@ -1,3 +1,4 @@
1
+ import { i as takeRetryIds } from "./retry-ids-04ZPJCZY.js";
1
2
  import { Flags } from "@oclif/core";
2
3
  import { format } from "node:util";
3
4
  // src/oclif/json-output.ts
@@ -166,6 +167,14 @@ function thrownErrorBody(error) {
166
167
  * what it wrote to stdout and stderr and how it ended.
167
168
  */
168
169
  function composeJsonDocument(input) {
170
+ const document = composeResult(input);
171
+ if (!input.retryIds?.length) return document;
172
+ return {
173
+ ...isPlainObject(document) ? document : { data: document },
174
+ cli_retry_ids: input.retryIds
175
+ };
176
+ }
177
+ function composeResult(input) {
169
178
  const { errorPayload, warnings: stderrLines } = summarizeStderr(input.stderr);
170
179
  const failed = input.exitCode !== 0;
171
180
  let warnings = stderrLines;
@@ -242,7 +251,8 @@ function guardJsonOutput(cls) {
242
251
  exitCode: thrown ? isExitSignal(thrown.error) ? errorExitCode(thrown.error) ?? 0 : errorExitCode(thrown.error) ?? (typeof process.exitCode === "number" && process.exitCode !== 0 ? process.exitCode : 1) : typeof process.exitCode === "number" ? process.exitCode : 0,
243
252
  stderr: capture.stderr,
244
253
  stdout: capture.stdout.join(""),
245
- thrown
254
+ thrown,
255
+ retryIds: takeRetryIds(this)
246
256
  });
247
257
  console.log(JSON.stringify(document, null, 2));
248
258
  if (thrown) {
@@ -1,12 +1,12 @@
1
1
  import { B as parseOwnerMemberAddress, F as agentProfilesDirectory, I as connectedAgentIdentity, L as connectedApiBaseUrl, M as AgentConnectionSetupError, N as agentProfileDirectory, P as agentProfileName, R as loadConnectedAgentProfile, U as saveConnectedAgentProfile, V as profileAlreadyConnectedMessage, W as PrimitiveApiClient, b as loadCliCredentials, j as AGENT_PROFILE_ENV, z as parseConnectedAgentProfile } from "./cli-config-Ms_0vNjq.js";
2
- import { An as putAgentContactPolicy, Cn as listSentEmails, Ft as getContact, Pt as getAgentContactPolicy, St as deleteContact, Vn as searchEmails, Wn as sendEmail, dr as __exportAll, en as inviteAgentConnection, in as listAgentContacts, jn as putContact, kn as putAgentContact, ln as listDomains, on as listContacts, rn as listAgentConnections, xt as deleteAgentContact, zt as getEmail } from "./repeats-Dj_o6c-X-DTtFzwNd.js";
3
- import { Mt as cliInvocation, Pt as defaultConnectionName, Tn as refuseOrgSelectionForProfile, wn as refreshStoredCliCredentials, zt as detectAgentRuntime } from "./api-command--2ZkNMvH.js";
2
+ import { An as putAgentContact, Ft as getContact, Gn as sendEmail, Hn as searchEmails, Mn as putContact, Pt as getAgentContactPolicy, St as deleteContact, an as listAgentContacts, fr as __exportAll, in as listAgentConnections, jn as putAgentContactPolicy, sn as listContacts, tn as inviteAgentConnection, un as listDomains, wn as listSentEmails, xt as deleteAgentContact, zt as getEmail } from "./repeats-Dj_o6c-X-CliyH3ge.js";
3
+ import { Mt as cliInvocation, Pt as defaultConnectionName, Tn as refuseOrgSelectionForProfile, wn as refreshStoredCliCredentials, zt as detectAgentRuntime } from "./api-command-DXiAX_N2.js";
4
4
  import { _ as acquireListenLock, b as listenLockHeld, c as mailTime, d as readMailJson, f as removeMailFile, g as ListenStateError, h as writeMailJson, i as mailId, l as privateMailDirectory, o as mailObject, p as syncMailDirectory, r as mailAddress, s as mailString } from "./shared-mail-files-BAQSGxxz.js";
5
- import { C as readBundledConnectSkill, a as NotificationRetryError, b as installSkill, d as SESSION_UUID, f as connectNativeSession, m as NativeSessionDisconnectedError, p as defaultSessionSocket, t as notificationScope } from "./notify-session-06flGBgK.js";
5
+ import { C as readBundledConnectSkill, a as NotificationRetryError, b as installSkill, d as SESSION_UUID, f as connectNativeSession, m as NativeSessionDisconnectedError, p as defaultSessionSocket, t as notificationScope } from "./notify-session-C8USviF_.js";
6
6
  import { a as backgroundListenStatus, d as stopBackgroundListen } from "./listen-background-DyBYca28.js";
7
7
  import { t as readSharedMailOwner } from "./shared-mail-watch-BAPMsFNv.js";
8
8
  import { withoutOrgSelection } from "./oclif/global-org-flag.js";
9
- import { o as scopedChatSenderTrust } from "./scoped-chat-C7l2BSZr.js";
9
+ import { o as scopedChatSenderTrust } from "./scoped-chat-CUy0Ta_y.js";
10
10
  import { accessSync, chmodSync, closeSync, constants, copyFileSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
11
11
  import { createHash, randomUUID } from "node:crypto";
12
12
  import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
@@ -1,5 +1,5 @@
1
- import { _ as isTrustedSender, c as classifySignalContent, g as isEmailReceivedEvent, kt as downloadEmailAttachmentPart, v as parseWebhookEvent } from "./repeats-Dj_o6c-X-DTtFzwNd.js";
2
- import { H as wakeReadCommand, V as skillFirstLine, rt as wakeInteractionSentence } from "./api-command--2ZkNMvH.js";
1
+ import { _ as isTrustedSender, c as classifySignalContent, g as isEmailReceivedEvent, kt as downloadEmailAttachmentPart, v as parseWebhookEvent } from "./repeats-Dj_o6c-X-CliyH3ge.js";
2
+ import { H as wakeReadCommand, V as skillFirstLine, rt as wakeInteractionSentence } from "./api-command-DXiAX_N2.js";
3
3
  import { _ as acquireListenLock, g as ListenStateError, y as listenIdentity } from "./shared-mail-files-BAQSGxxz.js";
4
4
  import { closeSync, copyFileSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, opendirSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { createHash, randomUUID, scryptSync } from "node:crypto";
@@ -1,8 +1,8 @@
1
- import { Zt as getSentEmail } from "../repeats-Dj_o6c-X-DTtFzwNd.js";
2
- import { L as readThreadContext, Sn as createAuthenticatedCliApiClient } from "../api-command--2ZkNMvH.js";
1
+ import { Qt as getSentEmail } from "../repeats-Dj_o6c-X-CliyH3ge.js";
2
+ import { L as readThreadContext, Sn as createAuthenticatedCliApiClient } from "../api-command-DXiAX_N2.js";
3
3
  import { AUTO_SIGNAL_KIND_ENV, AUTO_WORKING_RENEW_MS, autoSignalsDisabled, clearWorkingSending, markWorkingSending, readAutoClaim, readWorkingLease, recordRenewer, stopWorkingLease, writeWorkingLease } from "./auto-signals.js";
4
4
  import { _ as acquireListenLock } from "../shared-mail-files-BAQSGxxz.js";
5
- import { t as sendSignal } from "../signal-command-D6oaza1W.js";
5
+ import { t as sendSignal } from "../signal-command-DHwFky03.js";
6
6
  import { join } from "node:path";
7
7
  import { homedir } from "node:os";
8
8
  // src/oclif/auto-signal-worker.ts
@@ -1,4 +1,4 @@
1
- import { n as isPlainChatReply, o as scopedChatSenderTrust } from "../scoped-chat-C7l2BSZr.js";
1
+ import { n as isPlainChatReply, o as scopedChatSenderTrust } from "../scoped-chat-CUy0Ta_y.js";
2
2
  import { d as readMailJson, h as writeMailJson, i as mailId, l as privateMailDirectory, r as mailAddress } from "../shared-mail-files-BAQSGxxz.js";
3
3
  import { existsSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
@@ -1,11 +1,11 @@
1
- import { r as jsonOutputRequested } from "../json-output-saHY68hr.js";
1
+ import { r as jsonOutputRequested } from "../json-output-xgN0ZLWP.js";
2
2
  // src/oclif/command-not-found.ts
3
3
  /** At most this many commands are suggested for one word. */
4
4
  const MOST_SUGGESTED = 3;
5
5
  /**
6
6
  * The commands in another group named by the word typed where a subcommand
7
7
  * was expected, said as a question (`email-rules list-email-rule-objections`
8
- * is `email-rule-oversight list-email-rule-objections`), or "" when there are
8
+ * is `email-rule-oversight list-email-rule-objections`), or none when there are
9
9
  * none or too many to be a likely meaning. Only those words are looked up,
10
10
  * never a value typed after them, which can be any word at all.
11
11
  */
@@ -13,10 +13,63 @@ function elsewhere(words, lookup) {
13
13
  for (const word of words) {
14
14
  const ids = lookup.named?.(word) ?? [];
15
15
  if (ids.length === 0) continue;
16
- if (ids.length > MOST_SUGGESTED) return "";
17
- return ` Did you mean ${ids.map((id) => `"primitive ${id.split(":").join(" ")}"`).join(" or ")}?`;
16
+ return ids.length > MOST_SUGGESTED ? [] : [...ids];
18
17
  }
19
- return "";
18
+ return [];
19
+ }
20
+ /** Damerau distance also catches adjacent transpositions such as `lsit`. */
21
+ function distance(left, right) {
22
+ let previous = Array.from({ length: right.length + 1 }, (_, i) => i);
23
+ let before = previous;
24
+ for (let i = 0; i < left.length; i += 1) {
25
+ const current = [i + 1];
26
+ for (let j = 0; j < right.length; j += 1) {
27
+ current[j + 1] = Math.min((current[j] ?? 0) + 1, (previous[j + 1] ?? 0) + 1, (previous[j] ?? 0) + (left[i] === right[j] ? 0 : 1));
28
+ if (i > 0 && j > 0 && left[i] === right[j - 1] && left[i - 1] === right[j]) current[j + 1] = Math.min(current[j + 1] ?? 0, (before[j - 1] ?? 0) + 1);
29
+ }
30
+ before = previous;
31
+ previous = current;
32
+ }
33
+ return previous[right.length] ?? Number.POSITIVE_INFINITY;
34
+ }
35
+ function nearby(word, ids) {
36
+ if (!word || word.length > 80) return [];
37
+ const singular = (value) => value.length > 3 ? value.replace(/s$/, "") : value;
38
+ const name = singular(word.toLowerCase());
39
+ const maximum = Math.max(1, Math.min(2, Math.floor(name.length / 3)));
40
+ return ids.map((id) => {
41
+ const candidate = id.split(":").at(-1) ?? id;
42
+ return {
43
+ id,
44
+ score: name.length >= 3 && candidate.startsWith(`${word.toLowerCase()}-`) ? .5 : distance(name, singular(candidate))
45
+ };
46
+ }).filter(({ score }) => score <= maximum).sort((a, b) => a.score - b.score || a.id.localeCompare(b.id)).slice(0, MOST_SUGGESTED).map(({ id }) => id);
47
+ }
48
+ function suggestions(words, lookup, topic) {
49
+ const visible = lookup.visible ?? [];
50
+ if (topic) {
51
+ const depth = topic.split(":").length + 1;
52
+ const siblings = visible.filter((id) => id.startsWith(`${topic}:`) && id.split(":").length === depth);
53
+ const matches = nearby(words[0] ?? "", siblings);
54
+ if (matches.length > 0) return matches;
55
+ }
56
+ const exact = elsewhere(words, lookup);
57
+ if (exact.length > 0) return exact;
58
+ const roots = (lookup.roots ?? visible.filter((id) => !id.includes(":"))).filter((id) => id !== topic);
59
+ return nearby(topic ?? words[0] ?? "", roots);
60
+ }
61
+ function unknown(typed, ids, help, lookup) {
62
+ const commands = ids.map((id) => `primitive ${id.split(":").join(" ")}${lookup.find(id) ? "" : " --help"}`);
63
+ return {
64
+ code: "command_not_found",
65
+ message: `Unknown command "${typed}".${commands.length ? ` Did you mean ${commands.map((command) => `"${command}"`).join(" or ")}?` : ""} ${help}`,
66
+ ...commands.length ? { details: { suggestions: commands } } : {}
67
+ };
68
+ }
69
+ /** A command owns its visibility; topic visibility applies only without one. */
70
+ function visibleEntries(commands, topics) {
71
+ const declared = new Set(commands.map((command) => command.id));
72
+ return [.../* @__PURE__ */ new Set([...commands.filter((command) => !command.hidden).map((command) => command.id), ...topics.filter((topic) => !declared.has(topic.name) && !topic.hidden).map((topic) => topic.name)])];
20
73
  }
21
74
  /**
22
75
  * What to say for an id no command has. oclif joins every word before the
@@ -34,10 +87,7 @@ function commandNotFoundMessage(id, lookup) {
34
87
  if (!command && !topic) continue;
35
88
  const shown = `primitive ${parts.slice(0, end).join(" ")}`;
36
89
  const rest = parts.slice(end).join(" ");
37
- if (topic || !command) return {
38
- code: "command_not_found",
39
- message: `Unknown command "${typed}".${elsewhere(parts.slice(end, end + 1), lookup)} Run "${shown} --help" to see the commands under it.`
40
- };
90
+ if (topic || !command) return unknown(typed, suggestions(parts.slice(end, end + 1), lookup, known), `Run "${shown} --help" to see the commands under it.`, lookup);
41
91
  if (command.takesArguments) return {
42
92
  code: "command_not_found",
43
93
  message: `Unknown command "${parts.join(":")}". To pass "${rest}" to "${shown}", run "${shown} ${rest}".`
@@ -47,10 +97,7 @@ function commandNotFoundMessage(id, lookup) {
47
97
  message: `Unexpected argument "${rest}" for "${shown}", which takes no arguments. Run "${shown} --help" to see the flags it takes.`
48
98
  };
49
99
  }
50
- return {
51
- code: "command_not_found",
52
- message: `Unknown command "${typed}".${elsewhere(parts.slice(0, 2), lookup)} Run "primitive --help" to see the commands.`
53
- };
100
+ return unknown(typed, suggestions(parts.slice(0, 2), lookup), "Run \"primitive --help\" to see the commands.", lookup);
54
101
  }
55
102
  /**
56
103
  * Say what went wrong in plain words, and under --json as one JSON document
@@ -59,23 +106,24 @@ function commandNotFoundMessage(id, lookup) {
59
106
  */
60
107
  const hook = async (options) => {
61
108
  const { config } = options;
62
- const { code, message } = commandNotFoundMessage(options.id, {
109
+ const visible = visibleEntries(config.commands, config.topics);
110
+ const roots = visible.filter((id) => !id.includes(":"));
111
+ const error = commandNotFoundMessage(options.id, {
63
112
  find: (id) => {
64
113
  const command = config.findCommand(id);
65
114
  return command ? { takesArguments: Object.keys(command.args ?? {}).length > 0 } : void 0;
66
115
  },
67
116
  hasSubcommands: (id) => config.commandIDs.some((other) => other.startsWith(`${id}:`)),
68
- named: (word) => config.commands.filter((command) => !command.hidden && command.id.split(":").at(-1) === word).map((command) => command.id).sort()
117
+ named: (word) => visible.filter((id) => id.split(":").at(-1) === word).sort(),
118
+ visible,
119
+ roots
69
120
  });
70
121
  if (jsonOutputRequested([...process.argv.slice(2), ...options.argv ?? []])) process.stdout.write(`${JSON.stringify({
71
- error: {
72
- code,
73
- message
74
- },
122
+ error,
75
123
  exit_code: 2
76
124
  }, null, 2)}\n`);
77
- else process.stderr.write(` › Error: ${message}\n`);
125
+ else process.stderr.write(` › Error: ${error.message}\n`);
78
126
  process.exitCode = 2;
79
- return message;
127
+ return error.message;
80
128
  };
81
129
  export { commandNotFoundMessage, hook as default };
@@ -1,9 +1,12 @@
1
- import { Help } from "@oclif/core";
1
+ import { n as HELP_GROUP_HEADERS, r as helpFlagGroup, t as HELP_GROUPS } from "../help-inputs-NGARVZL_.js";
2
+ import { CommandHelp, Help } from "@oclif/core";
2
3
  // src/oclif/help.ts
3
4
  const FULL_HELP_FLAG = "--help-full";
4
5
  const NON_TTY_WIDTH = 100;
5
6
  const MAX_FLAG_NAME_WIDTH = 32;
6
7
  const EXAMPLE_LIMIT = 2;
8
+ const SHORT_HELP_MAX_LINES = 40;
9
+ const SHORT_HELP_MAX_BYTES = 3e3;
7
10
  /**
8
11
  * Commands whose `--help` text is read as a capability check by code already
9
12
  * on users' machines: the bundled primitive-connect skill's preflight and
@@ -70,6 +73,7 @@ function formatShortHelp(command, { bin, subcommands = [], width }) {
70
73
  const summary = render(command.summary ?? firstSentence(command.description ?? ""));
71
74
  const flags = Object.entries(command.flags ?? {}).filter(([, flag]) => !flag.hidden).sort(([a], [b]) => a.localeCompare(b)).map(([name, flag]) => ({
72
75
  name: flagName(name, flag),
76
+ group: flag.helpGroup ?? "command",
73
77
  text: flagRule(flag) + render(firstSentence(flag.summary ?? flag.description ?? ""))
74
78
  }));
75
79
  const nameWidth = Math.min(MAX_FLAG_NAME_WIDTH, Math.max(0, ...flags.map(({ name }) => name.length)));
@@ -78,16 +82,52 @@ function formatShortHelp(command, { bin, subcommands = [], width }) {
78
82
  const described = (command.description ?? "").replaceAll(/\s+/g, " ").trim();
79
83
  const more = summary !== "" && described.length > firstSentence(command.description ?? "").length;
80
84
  const fullHelp = `${bin} ${command.id} ${FULL_HELP_FLAG}`;
81
- return [
85
+ const renderSections = (compactCommon) => HELP_GROUPS.flatMap((group) => {
86
+ const members = flags.filter((flag) => flag.group === group);
87
+ const rows = members.map(({ name, text }) => listLine(name, text));
88
+ if (group === "required") rows.push(...jsonInputRows(command.helpInputs).map(([name, text]) => listLine(name, text)));
89
+ const lines = section(HELP_GROUP_HEADERS[group], group === "common" && compactCommon ? compactFlagNames(members.map((flag) => flag.name), width - 2) : rows);
90
+ return group === "common" && compactCommon ? lines.slice(1) : lines;
91
+ });
92
+ const renderPage = (compactCommon) => [
82
93
  ...summary ? [summary] : [],
83
94
  ...more ? [`Summary only. Full description: \`${fullHelp}\`.`] : [],
84
95
  ...section("USAGE", [usageLine(command, bin)]),
85
- ...section("FLAGS", flags.map(({ name, text }) => listLine(name, text))),
96
+ ...renderSections(compactCommon),
86
97
  ...section("COMMANDS", subcommands.map(({ id, summary: text }) => listLine(id, render(firstSentence(text ?? ""))))),
87
98
  ...section("EXAMPLES", examples),
88
99
  ...more ? [] : ["", `Full help: ${fullHelp}`]
89
100
  ].join("\n");
101
+ const page = renderPage(false);
102
+ return page.split("\n").length > SHORT_HELP_MAX_LINES || Buffer.byteLength(page) + 1 > SHORT_HELP_MAX_BYTES ? renderPage(true) : page;
103
+ }
104
+ function jsonInputRows(inputs) {
105
+ return (inputs?.requiredJsonFields ?? []).map((path) => [path, path === "$" ? "Request body: use command fields or JSON." : "JSON field: supply via --raw-body or --body-file."]);
106
+ }
107
+ function compactFlagNames(names, width) {
108
+ const lines = [];
109
+ for (const name of names) {
110
+ const last = lines.length - 1;
111
+ if (last < 0 || (lines[last]?.length ?? 0) + name.length + 2 > width) lines.push(name);
112
+ else lines[last] += ` ${name}`;
113
+ }
114
+ return lines;
90
115
  }
116
+ var GroupedCommandHelp = class extends CommandHelp {
117
+ sections() {
118
+ return super.sections().map((section) => section.header !== "FLAGS" ? section : {
119
+ ...section,
120
+ generate: ({ flags }) => HELP_GROUPS.map((group) => {
121
+ const rows = this.flags(flags.filter((flag) => flag.helpGroup === group)) ?? [];
122
+ if (group === "required") rows.push(...jsonInputRows(this.command.helpInputs));
123
+ return rows.length ? {
124
+ header: HELP_GROUP_HEADERS[group],
125
+ body: rows
126
+ } : void 0;
127
+ })
128
+ });
129
+ }
130
+ };
91
131
  function terminalWidth() {
92
132
  return process.stdout.isTTY && process.stdout.columns ? process.stdout.columns : NON_TTY_WIDTH;
93
133
  }
@@ -97,13 +137,33 @@ function terminalWidth() {
97
137
  */
98
138
  var PrimitiveHelp = class extends Help {
99
139
  full = false;
140
+ CommandHelpClass = GroupedCommandHelp;
100
141
  async showHelp(argv) {
101
142
  this.full = argv.includes(FULL_HELP_FLAG);
102
143
  await super.showHelp(argv);
103
144
  }
104
145
  async showCommandHelp(command) {
146
+ const loaded = await command.load();
147
+ const helpInputs = loaded.helpInputs;
148
+ const flagNames = new Set(Object.keys(command.flags ?? {}));
149
+ const flags = Object.fromEntries(Object.entries(command.flags ?? {}).map(([name, flag]) => {
150
+ const exactlyOne = loaded.flags?.[name]?.exactlyOne;
151
+ return [name, {
152
+ ...flag,
153
+ exactlyOne,
154
+ helpGroup: helpFlagGroup(name, {
155
+ ...flag,
156
+ exactlyOne
157
+ }, helpInputs, flagNames)
158
+ }];
159
+ }));
160
+ const grouped = {
161
+ ...command,
162
+ flags,
163
+ helpInputs
164
+ };
105
165
  if (this.full || FULL_HELP_COMMANDS.has(command.id)) {
106
- await super.showCommandHelp(command);
166
+ await super.showCommandHelp(grouped);
107
167
  return;
108
168
  }
109
169
  const depth = command.id.split(":").length;
@@ -111,14 +171,8 @@ var PrimitiveHelp = class extends Help {
111
171
  id: sub.id.replaceAll(":", " "),
112
172
  summary: sub.summary ?? sub.description
113
173
  }));
114
- const loaded = await command.load();
115
- const flags = Object.fromEntries(Object.entries(command.flags ?? {}).map(([name, flag]) => [name, {
116
- ...flag,
117
- exactlyOne: loaded.flags?.[name]?.exactlyOne
118
- }]));
119
174
  this.log(formatShortHelp({
120
- ...command,
121
- flags,
175
+ ...grouped,
122
176
  id: command.id.replaceAll(":", " ")
123
177
  }, {
124
178
  bin: this.config.bin,