@clerc/plugin-help 1.0.0-beta.1 → 1.0.0-beta.11

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/index.d.ts CHANGED
@@ -1,22 +1,137 @@
1
1
  import { Plugin } from "@clerc/core";
2
2
 
3
+ //#region ../parser/src/types.d.ts
4
+
5
+ /**
6
+ * Defines how a string input is converted to the target type T.
7
+ *
8
+ * @template T The target type.
9
+ */
10
+ type FlagTypeFunction<T = unknown> = ((value: string) => T) & {
11
+ /**
12
+ * Optional display name for the type, useful in help output.
13
+ * If provided, this will be shown instead of the function name.
14
+ */
15
+ displayName?: string;
16
+ };
17
+ type FlagType<T = unknown> = FlagTypeFunction<T> | readonly [FlagTypeFunction<T>];
18
+ //#endregion
19
+ //#region src/types.d.ts
20
+ interface Formatters {
21
+ formatFlagType: (type: FlagType) => string;
22
+ }
23
+ /**
24
+ * A group definition as a tuple of [key, displayName].
25
+ * The key is used in help options to assign items to groups.
26
+ * The displayName is shown in the help output.
27
+ */
28
+ type GroupDefinition = [key: string, name: string];
29
+ /**
30
+ * Options for defining groups in help output.
31
+ */
32
+ interface GroupsOptions {
33
+ /**
34
+ * Groups for commands.
35
+ * Each group is defined as `[key, name]`.
36
+ */
37
+ commands?: GroupDefinition[];
38
+ /**
39
+ * Groups for command-specific flags.
40
+ * Each group is defined as `[key, name]`.
41
+ */
42
+ flags?: GroupDefinition[];
43
+ /**
44
+ * Groups for global flags.
45
+ * Each group is defined as `[key, name]`.
46
+ */
47
+ globalFlags?: GroupDefinition[];
48
+ }
49
+ //#endregion
50
+ //#region src/formatters.d.ts
51
+ declare const defaultFormatters: Formatters;
52
+ //#endregion
3
53
  //#region src/index.d.ts
54
+ interface HelpOptions {
55
+ /**
56
+ * The group this item belongs to.
57
+ * The group must be defined in the `groups` option of `helpPlugin()`.
58
+ */
59
+ group?: string;
60
+ }
61
+ interface CommandHelpOptions extends HelpOptions {
62
+ /**
63
+ * Whether to show the command in help output.
64
+ *
65
+ * @default true
66
+ */
67
+ show?: boolean;
68
+ /**
69
+ * Notes to show in the help output.
70
+ */
71
+ notes?: string[];
72
+ /**
73
+ * Examples to show in the help output.
74
+ * Each example is a tuple of `[command, description]`.
75
+ */
76
+ examples?: [string, string][];
77
+ }
4
78
  declare module "@clerc/core" {
5
79
  interface CommandCustomOptions {
6
- help?: {
7
- showInHelp?: boolean;
8
- notes?: string[];
9
- examples?: [string, string][];
10
- };
80
+ /**
81
+ * Help options for the command.
82
+ */
83
+ help?: CommandHelpOptions;
84
+ }
85
+ interface FlagCustomOptions {
86
+ /**
87
+ * Help options for the flag.
88
+ */
89
+ help?: HelpOptions;
11
90
  }
12
91
  }
13
92
  interface HelpPluginOptions {
93
+ /**
94
+ * Whether to register the `help` command.
95
+ *
96
+ * @default true
97
+ */
14
98
  command?: boolean;
99
+ /**
100
+ * Whether to register the `--help` global flag.
101
+ *
102
+ * @default true
103
+ */
15
104
  flag?: boolean;
105
+ /**
106
+ * Whether to show help when no command is specified.
107
+ *
108
+ * @default true
109
+ */
16
110
  showHelpWhenNoCommandSpecified?: boolean;
111
+ /**
112
+ * Notes to show in the help output.
113
+ */
17
114
  notes?: string[];
115
+ /**
116
+ * Examples to show in the help output.
117
+ * Each example is a tuple of `[command, description]`.
118
+ */
18
119
  examples?: [string, string][];
120
+ /**
121
+ * A banner to show before the help output.
122
+ */
19
123
  banner?: string;
124
+ /**
125
+ * Custom formatters for rendering help.
126
+ */
127
+ formatters?: Partial<Formatters>;
128
+ /**
129
+ * Group definitions for commands and flags.
130
+ * Groups allow organizing commands and flags into logical sections in help output.
131
+ * Each group is defined as `[key, name]` where `key` is the identifier used in help options
132
+ * and `name` is the display name shown in help output.
133
+ */
134
+ groups?: GroupsOptions;
20
135
  }
21
136
  declare const helpPlugin: ({
22
137
  command,
@@ -24,7 +139,9 @@ declare const helpPlugin: ({
24
139
  showHelpWhenNoCommandSpecified,
25
140
  notes,
26
141
  examples,
27
- banner
142
+ banner,
143
+ formatters,
144
+ groups
28
145
  }?: HelpPluginOptions) => Plugin;
29
146
  //#endregion
30
- export { HelpPluginOptions, helpPlugin };
147
+ export { CommandHelpOptions, type GroupDefinition, type GroupsOptions, HelpOptions, HelpPluginOptions, defaultFormatters, helpPlugin };
package/dist/index.js CHANGED
@@ -1,27 +1,58 @@
1
1
  import { definePlugin, resolveCommand } from "@clerc/core";
2
- import { formatFlagName, formatVersion, isTruthy, objectIsEmpty, toArray } from "@clerc/utils";
3
2
  import stringWidth from "string-width";
4
3
  import textTable from "text-table";
5
4
  import * as yc from "yoctocolors";
6
5
 
6
+ //#region ../utils/src/index.ts
7
+ const toArray = (a) => Array.isArray(a) ? a : [a];
8
+ const kebabCase = (s) => s.replace(/([A-Z])/g, (_, c) => `-${c.toLowerCase()}`);
9
+ const formatFlagName = (n) => n.length <= 1 ? `-${n}` : `--${kebabCase(n)}`;
10
+ const formatVersion = (v) => v.length === 0 ? "" : v.startsWith("v") ? v : `v${v}`;
11
+ const isTruthy = Boolean;
12
+ const objectIsEmpty = (obj) => Object.keys(obj).length === 0;
13
+
14
+ //#endregion
7
15
  //#region src/utils.ts
8
16
  function formatFlagType(type) {
9
- if (typeof type === "function") return type.name;
10
- return `Array<${type[0].name}>`;
17
+ if (typeof type === "function") return type.displayName ?? type.name;
18
+ const innerType = type[0];
19
+ return `Array<${innerType.displayName ?? innerType.name}>`;
11
20
  }
12
21
 
22
+ //#endregion
23
+ //#region src/formatters.ts
24
+ const defaultFormatters = { formatFlagType };
25
+
13
26
  //#endregion
14
27
  //#region src/renderer.ts
28
+ const DEFAULT_GROUP_KEY = "default";
15
29
  const table = (items) => textTable(items, { stringLength: stringWidth });
16
30
  const splitTable = (items) => table(items).split("\n");
17
31
  const DELIMITER = yc.yellow("-");
32
+ const INDENT = " ".repeat(2);
33
+ const withIndent = (str) => `${INDENT}${str}`;
34
+ function groupDefinitionsToMap(definitions) {
35
+ const map = /* @__PURE__ */ new Map();
36
+ if (definitions) for (const [key, name] of definitions) map.set(key, name);
37
+ return map;
38
+ }
39
+ function validateGroup(group, groupMap, itemType, itemName) {
40
+ if (group && group !== DEFAULT_GROUP_KEY && !groupMap.has(group)) throw new Error(`Unknown ${itemType} group "${group}" for "${itemName}". Available groups: ${[...groupMap.keys()].join(", ") || "(none)"}`);
41
+ }
18
42
  var HelpRenderer = class {
19
- constructor(_cli, _globalFlags, _command, _notes, _examples) {
43
+ _commandGroups;
44
+ _flagGroups;
45
+ _globalFlagGroups;
46
+ constructor(_formatters, _cli, _globalFlags, _command, _notes, _examples, groups) {
47
+ this._formatters = _formatters;
20
48
  this._cli = _cli;
21
49
  this._globalFlags = _globalFlags;
22
50
  this._command = _command;
23
51
  this._notes = _notes;
24
52
  this._examples = _examples;
53
+ this._commandGroups = groupDefinitionsToMap(groups?.commands);
54
+ this._flagGroups = groupDefinitionsToMap(groups?.flags);
55
+ this._globalFlagGroups = groupDefinitionsToMap(groups?.globalFlags);
25
56
  }
26
57
  render() {
27
58
  return [
@@ -33,9 +64,9 @@ var HelpRenderer = class {
33
64
  this.renderNotes(),
34
65
  this.renderExamples()
35
66
  ].filter(isTruthy).filter((section) => section.body.length > 0).map((section) => {
36
- const body = Array.isArray(section.body) ? section.body.filter(Boolean).join("\n") : section.body;
67
+ const body = Array.isArray(section.body) ? section.body.filter((s) => s !== void 0).join("\n") : section.body;
37
68
  if (!section.title) return body;
38
- return `${yc.bold(section.title)}\n${body.split("\n").map((line) => ` ${line}`).join("\n")}`;
69
+ return `${yc.bold(section.title)}\n${body.split("\n").map(withIndent).join("\n")}`;
39
70
  }).join("\n\n");
40
71
  }
41
72
  renderHeader() {
@@ -44,7 +75,7 @@ var HelpRenderer = class {
44
75
  const description = command?.description ?? _description;
45
76
  const formattedCommandName = command?.name ? ` ${yc.cyan(command.name)}` : "";
46
77
  const headerLine = command ? `${yc.green(_name)}${formattedCommandName}` : `${yc.green(_name)} ${yc.yellow(formatVersion(_version))}`;
47
- const alias = command?.alias ? `Alias${toArray(command.alias).length > 1 ? "es" : ""}: ${toArray(command.alias).map((a) => yc.cyan(a)).join(", ")}` : "";
78
+ const alias = command?.alias ? `Alias${toArray(command.alias).length > 1 ? "es" : ""}: ${toArray(command.alias).map((a) => yc.cyan(a)).join(", ")}` : void 0;
48
79
  return { body: [`${headerLine}${description ? ` ${DELIMITER} ${description}` : ""}`, alias] };
49
80
  }
50
81
  renderUsage() {
@@ -52,54 +83,103 @@ var HelpRenderer = class {
52
83
  const command = this._command;
53
84
  let usage = `$ ${_scriptName}`;
54
85
  if (command) {
55
- usage += command.name ? ` ${command.name}` : "";
86
+ if (command.name) usage += ` ${command.name}`;
56
87
  if (command.parameters) usage += ` ${command.parameters.join(" ")}`;
57
- }
58
- if (command?.flags && !objectIsEmpty(command.flags) || !objectIsEmpty(this._globalFlags)) usage += " [FLAGS]";
88
+ } else usage += this._cli._commands.has("") ? " [command]" : " <command>";
89
+ if (command?.flags && !objectIsEmpty(command.flags) || !objectIsEmpty(this._globalFlags)) usage += " [flags]";
59
90
  return {
60
91
  title: "Usage",
61
- body: [usage]
92
+ body: [yc.magenta(usage)]
62
93
  };
63
94
  }
64
95
  renderCommands() {
65
96
  const commands = this._cli._commands;
66
97
  if (this._command || commands.size === 0) return;
98
+ const groupedCommands = /* @__PURE__ */ new Map();
99
+ const defaultCommands = [];
100
+ for (const command of commands.values()) {
101
+ if (command.__isAlias || command.help?.show === false) continue;
102
+ const group = command.help?.group;
103
+ validateGroup(group, this._commandGroups, "command", command.name);
104
+ const item = [`${yc.cyan(command.name)}${command.alias ? ` (${toArray(command.alias).join(", ")})` : ""}`, command.description];
105
+ if (group && group !== DEFAULT_GROUP_KEY) {
106
+ const groupItems = groupedCommands.get(group) ?? [];
107
+ groupItems.push(item);
108
+ groupedCommands.set(group, groupItems);
109
+ } else defaultCommands.push(item);
110
+ }
111
+ const body = [];
112
+ for (const [key, name] of this._commandGroups) {
113
+ const items = groupedCommands.get(key);
114
+ if (items && items.length > 0) {
115
+ if (body.length > 0) body.push("");
116
+ body.push(`${yc.dim(name)}`);
117
+ body.push(...splitTable(items).map(withIndent));
118
+ }
119
+ }
120
+ if (defaultCommands.length > 0) if (body.length > 0) {
121
+ body.push("");
122
+ body.push(`${yc.dim("Other")}`);
123
+ body.push(...splitTable(defaultCommands).map(withIndent));
124
+ } else body.push(...splitTable(defaultCommands));
67
125
  return {
68
126
  title: "Commands",
69
- body: splitTable([...commands.values()].map((command) => {
70
- if (command.__isAlias || command.help?.showInHelp === false) return null;
71
- return [`${yc.cyan(command.name)}${command.alias ? ` (${toArray(command.alias).join(", ")})` : ""}`, command.description];
72
- }).filter(isTruthy))
127
+ body
73
128
  };
74
129
  }
75
- renderFlags(flags) {
76
- return Object.entries(flags).map(([name, flag]) => {
77
- const flagName = formatFlagName(name);
78
- const aliases = (Array.isArray(flag.alias) ? flag.alias : flag.alias ? [flag.alias] : []).map(formatFlagName).join(", ");
79
- const description = flag.description ?? "";
80
- const type = formatFlagType(flag.type);
81
- const defaultValue = flag.default === void 0 ? "" : `[default: ${String(flag.default)}]`;
82
- return [
83
- yc.blue([flagName, aliases].filter(Boolean).join(", ")),
84
- yc.gray(type),
85
- description,
86
- yc.gray(defaultValue)
87
- ];
88
- });
130
+ renderFlagItem(name, flag) {
131
+ const flagName = formatFlagName(name);
132
+ const aliases = (Array.isArray(flag.alias) ? flag.alias : flag.alias ? [flag.alias] : []).map(formatFlagName).join(", ");
133
+ const type = this._formatters.formatFlagType(flag.type);
134
+ return [
135
+ yc.blue([flagName, aliases].filter(Boolean).join(", ")),
136
+ yc.gray(type),
137
+ flag.description,
138
+ flag.default !== void 0 && yc.gray(`[default: ${String(flag.default)}]`)
139
+ ].filter(isTruthy);
140
+ }
141
+ renderGroupedFlags(flags, groupMap, itemType) {
142
+ const groupedFlags = /* @__PURE__ */ new Map();
143
+ const defaultFlags = [];
144
+ for (const [name, flag] of Object.entries(flags)) {
145
+ const group = flag.help?.group;
146
+ validateGroup(group, groupMap, itemType, name);
147
+ const item = this.renderFlagItem(name, flag);
148
+ if (group && group !== DEFAULT_GROUP_KEY) {
149
+ const groupItems = groupedFlags.get(group) ?? [];
150
+ groupItems.push(item);
151
+ groupedFlags.set(group, groupItems);
152
+ } else defaultFlags.push(item);
153
+ }
154
+ const body = [];
155
+ for (const [key, name] of groupMap) {
156
+ const items = groupedFlags.get(key);
157
+ if (items && items.length > 0) {
158
+ if (body.length > 0) body.push("");
159
+ body.push(`${yc.dim(name)}`);
160
+ body.push(...splitTable(items).map(withIndent));
161
+ }
162
+ }
163
+ if (defaultFlags.length > 0) if (body.length > 0) {
164
+ body.push("");
165
+ body.push(`${yc.dim("Other")}`);
166
+ body.push(...splitTable(defaultFlags).map(withIndent));
167
+ } else body.push(...splitTable(defaultFlags));
168
+ return body;
89
169
  }
90
170
  renderCommandFlags() {
91
171
  const command = this._command;
92
172
  if (!command?.flags || objectIsEmpty(command.flags)) return;
93
173
  return {
94
174
  title: "Flags",
95
- body: splitTable(this.renderFlags(command.flags))
175
+ body: this.renderGroupedFlags(command.flags, this._flagGroups, "flag")
96
176
  };
97
177
  }
98
178
  renderGlobalFlags() {
99
179
  if (!this._globalFlags || objectIsEmpty(this._globalFlags)) return;
100
180
  return {
101
181
  title: "Global Flags",
102
- body: splitTable(this.renderFlags(this._globalFlags))
182
+ body: this.renderGroupedFlags(this._globalFlags, this._globalFlagGroups, "global flag")
103
183
  };
104
184
  }
105
185
  renderNotes() {
@@ -126,7 +206,11 @@ var HelpRenderer = class {
126
206
 
127
207
  //#endregion
128
208
  //#region src/index.ts
129
- const helpPlugin = ({ command = true, flag = true, showHelpWhenNoCommandSpecified = true, notes, examples, banner } = {}) => definePlugin({ setup: (cli) => {
209
+ const helpPlugin = ({ command = true, flag = true, showHelpWhenNoCommandSpecified = true, notes, examples, banner, formatters, groups } = {}) => definePlugin({ setup: (cli) => {
210
+ const mergedFormatters = {
211
+ ...defaultFormatters,
212
+ ...formatters
213
+ };
130
214
  const generalHelpNotes = [
131
215
  "If no command is specified, show help for the CLI.",
132
216
  "If a command is specified, show help for the command.",
@@ -140,7 +224,7 @@ const helpPlugin = ({ command = true, flag = true, showHelpWhenNoCommandSpecifie
140
224
  const effectiveNotes = notes ?? generalHelpNotes;
141
225
  const effectiveExamples = examples ?? generalHelpExamples;
142
226
  function printHelp(s) {
143
- if (banner) console.log(`${banner}`);
227
+ if (banner) console.log(banner);
144
228
  console.log(s);
145
229
  }
146
230
  if (command) cli.command("help", "Show help", {
@@ -159,7 +243,7 @@ const helpPlugin = ({ command = true, flag = true, showHelpWhenNoCommandSpecifie
159
243
  return;
160
244
  }
161
245
  }
162
- printHelp(new HelpRenderer(cli, cli._globalFlags, command$1, command$1 ? command$1.help?.notes : effectiveNotes, command$1 ? command$1.help?.examples : effectiveExamples).render());
246
+ printHelp(new HelpRenderer(mergedFormatters, cli, cli._globalFlags, command$1, command$1 ? command$1.help?.notes : effectiveNotes, command$1 ? command$1.help?.examples : effectiveExamples, groups).render());
163
247
  });
164
248
  if (flag) cli.globalFlag("help", "Show help", {
165
249
  alias: "h",
@@ -169,12 +253,12 @@ const helpPlugin = ({ command = true, flag = true, showHelpWhenNoCommandSpecifie
169
253
  cli.interceptor({
170
254
  enforce: "pre",
171
255
  handler: async (ctx, next) => {
172
- if (ctx.flags.help) printHelp(new HelpRenderer(cli, cli._globalFlags, ctx.command, ctx.command ? ctx.command.help?.notes : effectiveNotes, ctx.command ? ctx.command.help?.examples : effectiveExamples).render());
173
- else if (showHelpWhenNoCommandSpecified && !ctx.command && ctx.rawParsed.parameters.length === 0) printHelp(new HelpRenderer(cli, cli._globalFlags, void 0, effectiveNotes, effectiveExamples).render());
256
+ if (ctx.flags.help) printHelp(new HelpRenderer(mergedFormatters, cli, cli._globalFlags, ctx.command, ctx.command ? ctx.command.help?.notes : effectiveNotes, ctx.command ? ctx.command.help?.examples : effectiveExamples, groups).render());
257
+ else if (showHelpWhenNoCommandSpecified && !ctx.command && ctx.rawParsed.parameters.length === 0) printHelp(new HelpRenderer(mergedFormatters, cli, cli._globalFlags, void 0, effectiveNotes, effectiveExamples, groups).render());
174
258
  else await next();
175
259
  }
176
260
  });
177
261
  } });
178
262
 
179
263
  //#endregion
180
- export { helpPlugin };
264
+ export { defaultFormatters, helpPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clerc/plugin-help",
3
- "version": "1.0.0-beta.1",
3
+ "version": "1.0.0-beta.11",
4
4
  "author": "Ray <i@mk1.io> (https://github.com/so1ve)",
5
5
  "type": "module",
6
6
  "description": "Clerc plugin help",
@@ -48,18 +48,14 @@
48
48
  "@types/text-table": "^0.2.5",
49
49
  "string-width": "^8.1.0",
50
50
  "text-table": "^0.2.0",
51
- "yoctocolors": "^2.1.2",
52
- "@clerc/utils": "1.0.0-beta.1"
51
+ "yoctocolors": "^2.1.2"
53
52
  },
54
53
  "devDependencies": {
55
- "@clerc/parser": "1.0.0-beta.1",
56
- "@clerc/core": "1.0.0-beta.1"
54
+ "@clerc/parser": "1.0.0-beta.11",
55
+ "@clerc/core": "1.0.0-beta.11",
56
+ "@clerc/utils": "1.0.0-beta.11"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "@clerc/core": "*"
60
- },
61
- "scripts": {
62
- "build": "tsdown",
63
- "watch": "tsdown --watch"
64
60
  }
65
61
  }