@crustjs/man 0.1.2 → 0.2.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chenxin Yan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,11 +1,13 @@
1
1
  # @crustjs/man
2
2
 
3
- Generate **mdoc(7)** manual pages (section 1) from a Crust CLI definition.
3
+ Generate mdoc(7) manual pages from Crust CLI definitions
4
4
 
5
- See the [Man module docs](https://crustjs.com/docs/modules/man) for install steps, `writeManPage`, `crust build --man`, and packaging notes.
5
+ ## Install
6
6
 
7
- ## Roadmap (v2+)
7
+ ```sh
8
+ bun add -d @crustjs/man
9
+ ```
8
10
 
9
- - Optional **one man page per subcommand** (or a mode switch)
10
- - Extra **meta** or sidecar content for long **DESCRIPTION**, **EXAMPLES**, **SEE ALSO**
11
- - **Subprocess**-based tree export when in-process `prepareCommandTree` is not enough
11
+ ## Documentation
12
+
13
+ Full docs: [crustjs.com/docs/modules/man](https://crustjs.com/docs/modules/man)
package/dist/index.d.ts CHANGED
@@ -1,44 +1,43 @@
1
- import { CommandNode } from "@crustjs/core";
1
+ import { ExtensionFactory } from "@crustjs/core";
2
+ import { CommandSnapshot } from "@crustjs/core/tooling";
3
+ //#region src/extension.d.ts
4
+ interface ManOptions {
5
+ /** Manual section. Defaults to 1. */
6
+ readonly section?: number;
7
+ /**
8
+ * Installed command name used for the page title and filename. Defaults to
9
+ * the application name; set it when `crust build --name` or the npm bin key
10
+ * installs the CLI under a different name.
11
+ */
12
+ readonly name?: string;
13
+ }
14
+ /** Adds build-time mdoc generation for the application. */
15
+ export declare const man: ExtensionFactory<[options?: ManOptions]>;
16
+ //#endregion
17
+ //#region src/mdoc.d.ts
2
18
  interface RenderManPageMdocOptions {
3
- /** Frozen root command node (e.g. from `prepareCommandTree()`). */
4
- root: CommandNode;
5
- /** Name shown in `man <name>` / `.Nm` (often matches the binary). */
6
- name: string;
7
- /** Manual section; user commands use `1`. */
8
- section?: number;
9
- /**
10
- * Override the `.Dd` date (e.g. `"April 1, 2026"`). If omitted, uses
11
- * `SOURCE_DATE_EPOCH` when set, otherwise today.
12
- */
13
- date?: string;
19
+ /** Prepared, validated Command Snapshot for the CLI. */
20
+ root: CommandSnapshot;
21
+ /** Name for `.Nm` / `man <name>` (usually the installed binary name). */
22
+ name: string;
23
+ /**
24
+ * Manual section.
25
+ *
26
+ * @default 1
27
+ */
28
+ section?: number;
29
+ /** Override `.Dd` in the mdoc output (see `renderManPageMdoc` `date`). */
30
+ date?: string;
14
31
  }
15
- /**
16
- * Render an mdoc(7) manual page (section 1) for the root command tree.
17
- */
18
- declare function renderManPageMdoc(options: RenderManPageMdocOptions): string;
19
- import { Crust } from "@crustjs/core";
20
- interface WriteManPageOptions {
21
- /** Root Crust builder for your CLI. */
22
- app: Crust;
23
- /** Name for `.Nm` / `man <name>` (usually the installed binary name). */
24
- name: string;
25
- /** Output path (e.g. `man/mycli.1`). Parent directories are created. */
26
- outfile: string;
27
- /** Manual section; defaults to `1`. */
28
- section?: number;
29
- /** Override `.Dd` in the mdoc output (see `renderManPageMdoc` `date`). */
30
- date?: string;
31
- /** Synthetic argv passed to plugin `setup()`; defaults to `[]`. */
32
- argv?: readonly string[];
33
- /**
34
- * When `true` (default), print plugin-setup warnings to `console.warn`.
35
- * Set to `false` in tests or CI if you handle warnings yourself.
36
- */
37
- logWarnings?: boolean;
32
+ /** Render an mdoc(7) manual page for the root command. */
33
+ export declare function renderManPageMdoc(options: RenderManPageMdocOptions): string;
34
+ //#endregion
35
+ //#region src/write-man-page.d.ts
36
+ interface WriteManPageOptions extends RenderManPageMdocOptions {
37
+ /** Output path (e.g. `man/mycli.1`). Parent directories are created. */
38
+ outfile: string;
38
39
  }
39
- /**
40
- * Freeze and validate the command tree, render an mdoc(7) manual page, and
41
- * write it to `outfile`.
42
- */
43
- declare function writeManPage(options: WriteManPageOptions): Promise<void>;
44
- export { writeManPage, renderManPageMdoc, WriteManPageOptions, RenderManPageMdocOptions };
40
+ /** Render an mdoc(7) manual page from a Command Snapshot and write it to `outfile`. */
41
+ export declare function writeManPage(options: WriteManPageOptions): Promise<void>;
42
+ //#endregion
43
+ export type { ManOptions, RenderManPageMdocOptions, WriteManPageOptions };
package/dist/index.js CHANGED
@@ -1,10 +1,166 @@
1
- // @bun
2
- var C=["January","February","March","April","May","June","July","August","September","October","November","December"];function $(R){if(R.startsWith("."))return`\\&${R}`;return R}function F(R){if(typeof R==="number"&&!Number.isFinite(R))return String(R);if(Array.isArray(R))return R.map(String).join(", ");return JSON.stringify(R)}function T(R){return`[default: ${F(R)}]`}function w(R,P){if(P===void 0)return R??"";let q=T(P);if(!R)return q;return`${R} ${q}`}function M(R){let P=R.variadic?`${R.name}...`:R.name;return R.required?`<${P}>`:`[${P}]`}function D(R,P,q){if(R.usage)return R.usage;let j=[q.join(" ")];if(Object.keys(P.subCommands).length>0&&!P.run)j.push("<command>");if(P.args)for(let G of P.args)j.push(M(G));if(Object.keys(P.effectiveFlags).length>0)j.push("[options]");return j.join(" ")}function W(R,P){let q=[R];if(P.aliases)for(let G of P.aliases)q.push(G);let j=[];if(P.short)j.push(`-${P.short}`);for(let G of q)j.push(`--${G}`);if(P.type==="boolean"&&!P.noNegate)for(let G of q)j.push(`--no-${G}`);return j.join(", ")}function E(R){if(!R||R.length===0)return"";return`[choices: ${R.join(", ")}]`}function B(R,P,q){let j=w(R,P),G=E(q);if(!G)return j;if(!j)return G;return`${j} ${G}`}function V(R){return R.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_|_$/g,"")||"COMMAND"}function y(R){return R.replace(/\s+/g," ").trim()}function N(R){let P=y(R);if(P.startsWith("."))return`\\&${P}`;return P}function L(R){let P=8;for(let[q,j]of Object.entries(R))P=Math.max(P,W(q,j).length);return`${P}n`}function A(R,P){if(!P||P.length===0)return R;return`${R} (${P.join(", ")})`}function S(R){let P=8;for(let[q,j]of Object.entries(R.subCommands)){if(j.meta.hidden===!0)continue;let G=A(q,j.meta.aliases);P=Math.max(P,G.length)}return`${P}n`}function x(R){if(R)return R;let P=process.env.SOURCE_DATE_EPOCH;if(P!==void 0){let j=Number.parseInt(P,10);if(!Number.isNaN(j)&&j>=0){let G=new Date(j*1000);return`${C[G.getUTCMonth()]} ${G.getUTCDate()}, ${G.getUTCFullYear()}`}}let q=new Date;return`${C[q.getMonth()]} ${q.getDate()}, ${q.getFullYear()}`}function _(R){let{root:P,name:q,section:j=1,date:G}=R,z=x(G),O=[P.meta.name],U=D(P.meta,P,O),X=P.meta.description?.trim()||"No description provided.",I=[`.Dd ${z}`,`.Dt ${V(q)} ${j}`,".Os",".Sh NAME",`.Nm ${q}`,`.Nd ${N(X)}`,".Sh SYNOPSIS",".Bd -literal",U,".Ed",".Sh DESCRIPTION"];for(let J of X.split(`
3
- `))I.push($(J));let Y=Object.entries(P.subCommands).filter(([,J])=>J.meta.hidden!==!0);if(Y.length>0){I.push(".Sh SUBCOMMANDS"),I.push(`.Bl -tag -width ${S(P)}`);for(let[J,K]of Y.sort(([Q],[H])=>Q.localeCompare(H))){I.push(`.It Nm ${A(J,K.meta.aliases)}`);let Q=K.meta.description?.trim()||"";if(Q)I.push(Q.split(`
4
- `).map($).join(`
5
- `))}I.push(".El")}let Z=Object.entries(P.effectiveFlags).sort(([J],[K])=>J.localeCompare(K));if(Z.length>0){I.push(".Sh OPTIONS"),I.push(`.Bl -tag -width ${L(P.effectiveFlags)}`);for(let[J,K]of Z){let Q=W(J,K);I.push(`.It Sy ${Q}`);let H=K.type==="string"?K.choices:void 0,k=B(K.description,K.default,H).trim();if(k)I.push(k.split(`
6
- `).map($).join(`
7
- `))}I.push(".El")}if(P.args&&P.args.length>0){I.push(".Sh ARGUMENTS"),I.push(".Bl -tag -width 12n");for(let J of P.args){I.push(`.It Ql ${M(J)}`);let K=J.type==="string"?J.choices:void 0,Q=B(J.description,J.default,K).trim();if(Q)I.push(Q.split(`
8
- `).map($).join(`
9
- `))}I.push(".El")}return I.push(""),I.join(`
10
- `)}import{mkdirSync as v,writeFileSync as h}from"fs";import{dirname as p}from"path";async function g(R){let{app:P,name:q,outfile:j,section:G=1,date:z,argv:O,logWarnings:U=!0}=R,{root:X,warnings:I}=await P.prepareCommandTree({argv:O});if(U)for(let Z of I)console.warn(`Warning: ${Z}`);let Y=_({root:X,name:q,section:G,date:z});v(p(j),{recursive:!0}),h(j,Y,"utf8")}export{g as writeManPage,_ as renderManPageMdoc};
1
+ import { dirname, join } from "node:path";
2
+ import { defineExtension, defineExtensionId } from "@crustjs/core";
3
+ import { buildCommandDocumentation, formatDescription, sectionsFor } from "@crustjs/core/tooling";
4
+ import { mkdir, writeFile } from "node:fs/promises";
5
+ //#region \0rolldown/runtime.js
6
+ var __defProp = Object.defineProperty;
7
+ var __exportAll = (all, no_symbols) => {
8
+ let target = {};
9
+ for (var name in all) __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true
12
+ });
13
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
14
+ return target;
15
+ };
16
+ //#endregion
17
+ //#region src/extension.ts
18
+ const MAN = defineExtensionId("crust:man");
19
+ /** Adds build-time mdoc generation for the application. */
20
+ const man = defineExtension(MAN, (options = {}) => {
21
+ const section = options.section ?? 1;
22
+ return { async build({ snapshot, outDir }) {
23
+ const { writeManPage } = await Promise.resolve().then(() => write_man_page_exports);
24
+ const name = options.name ?? snapshot.meta.name;
25
+ if (/[\\/]/.test(name)) throw new Error(`Manual name "${name}" must not contain path separators.`);
26
+ const outfile = join("man", `${name}.${section}`);
27
+ await writeManPage({
28
+ root: snapshot,
29
+ name,
30
+ section,
31
+ outfile: join(outDir, outfile)
32
+ });
33
+ return [outfile];
34
+ } };
35
+ });
36
+ //#endregion
37
+ //#region src/mdoc.ts
38
+ function escapeMdocBodyLine(line) {
39
+ return /^[.']/.test(line) ? `\\&${line}` : line;
40
+ }
41
+ function macroArgument(text) {
42
+ return text.replace(/\\/g, "\\e");
43
+ }
44
+ function shTitle(title) {
45
+ return macroArgument(title.toUpperCase());
46
+ }
47
+ function dtTitle(name) {
48
+ return name.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_|_$/g, "") || "COMMAND";
49
+ }
50
+ function ndArgument(text) {
51
+ return escapeMdocBodyLine(text.replace(/\s+/g, " ").trim());
52
+ }
53
+ function flagMacro(spelling) {
54
+ return spelling.startsWith("--") ? `Fl Fl ${spelling.slice(2)}` : `Fl ${spelling.slice(1)}`;
55
+ }
56
+ function flagMacros(flag) {
57
+ return flag.spellings.map(flagMacro).join(" , ");
58
+ }
59
+ function commandLabel(command) {
60
+ return command.aliases.length === 0 ? command.name : `${command.name} (${command.aliases.join(", ")})`;
61
+ }
62
+ function commandSectionGroups(command) {
63
+ const groups = [];
64
+ function visit(node, path) {
65
+ const sections = [...sectionsFor(node.sections, MAN)];
66
+ if (sections.length > 0) groups.push({
67
+ path,
68
+ sections
69
+ });
70
+ for (const child of [...node.children].sort((a, b) => a.name.localeCompare(b.name))) visit(child, [...path, child.name]);
71
+ }
72
+ visit(command, []);
73
+ return groups;
74
+ }
75
+ function resolveDdLine(explicit) {
76
+ if (explicit) return explicit;
77
+ const sec = Number.parseInt(process.env.SOURCE_DATE_EPOCH ?? "", 10);
78
+ const fromEpoch = !Number.isNaN(sec) && sec >= 0;
79
+ return new Date(fromEpoch ? sec * 1e3 : Date.now()).toLocaleDateString("en-US", {
80
+ month: "long",
81
+ day: "numeric",
82
+ year: "numeric",
83
+ timeZone: fromEpoch ? "UTC" : void 0
84
+ });
85
+ }
86
+ /** Render an mdoc(7) manual page for the root command. */
87
+ function renderManPageMdoc(options) {
88
+ const { root, name, section = 1, date } = options;
89
+ const model = buildCommandDocumentation(root);
90
+ const description = model.description?.trim() || "No description provided.";
91
+ const lines = [
92
+ `.Dd ${resolveDdLine(date)}`,
93
+ `.Dt ${dtTitle(name)} ${section}`,
94
+ ".Os",
95
+ ".Sh NAME",
96
+ `.Nm ${name}`,
97
+ `.Nd ${ndArgument(description)}`,
98
+ ".Sh SYNOPSIS",
99
+ ".Bd -literal",
100
+ model.usage,
101
+ ".Ed",
102
+ ".Sh DESCRIPTION"
103
+ ];
104
+ for (const line of description.split("\n")) lines.push(escapeMdocBodyLine(line));
105
+ if (model.children.length > 0) {
106
+ lines.push(".Sh SUBCOMMANDS", `.Bl -tag -width ${Math.max(8, ...model.children.map((child) => commandLabel(child).length))}n`);
107
+ for (const child of [...model.children].sort((a, b) => a.name.localeCompare(b.name))) {
108
+ lines.push(`.It Nm ${commandLabel(child)}`);
109
+ if (child.description) lines.push(child.description.trim().split("\n").map(escapeMdocBodyLine).join("\n"));
110
+ }
111
+ lines.push(".El");
112
+ }
113
+ if (model.flags.length > 0) {
114
+ lines.push(".Sh OPTIONS", `.Bl -tag -width ${Math.max(8, ...model.flags.map((flag) => flag.spellings.join(", ").length))}n`);
115
+ for (const flag of [...model.flags].sort((a, b) => a.name.localeCompare(b.name))) {
116
+ lines.push(`.It ${flagMacros(flag)}`);
117
+ const body = formatDescription(flag.description, flag.default, flag.choices);
118
+ if (body) lines.push(body.split("\n").map(escapeMdocBodyLine).join("\n"));
119
+ }
120
+ lines.push(".El");
121
+ }
122
+ if (model.args.length > 0) {
123
+ lines.push(".Sh ARGUMENTS", ".Bl -tag -width 12n");
124
+ for (const arg of model.args) {
125
+ lines.push(`.It Ar ${arg.name}${arg.variadic ? " ..." : ""}`);
126
+ const body = formatDescription(arg.description, arg.default, arg.choices);
127
+ if (body) lines.push(body.split("\n").map(escapeMdocBodyLine).join("\n"));
128
+ }
129
+ lines.push(".El");
130
+ }
131
+ for (const metadataSection of sectionsFor(model.sections, MAN)) {
132
+ lines.push(`.Sh ${shTitle(metadataSection.title)}`);
133
+ for (const line of metadataSection.body.split("\n")) lines.push(escapeMdocBodyLine(line));
134
+ }
135
+ const commandSections = commandSectionGroups(model).filter(({ path }) => path.length > 0);
136
+ if (commandSections.length > 0) {
137
+ lines.push(".Sh COMMANDS");
138
+ for (const group of commandSections) {
139
+ lines.push(`.Ss ${macroArgument(group.path.join(" "))}`);
140
+ group.sections.forEach((commandSection, index) => {
141
+ if (index > 0) lines.push(".Pp");
142
+ lines.push(`.Sy ${shTitle(commandSection.title)}`);
143
+ for (const line of commandSection.body.split("\n")) lines.push(escapeMdocBodyLine(line));
144
+ });
145
+ }
146
+ }
147
+ lines.push("");
148
+ return lines.join("\n");
149
+ }
150
+ //#endregion
151
+ //#region src/write-man-page.ts
152
+ var write_man_page_exports = /* @__PURE__ */ __exportAll({ writeManPage: () => writeManPage });
153
+ /** Render an mdoc(7) manual page from a Command Snapshot and write it to `outfile`. */
154
+ async function writeManPage(options) {
155
+ const { root, name, outfile, section = 1, date } = options;
156
+ const mdoc = renderManPageMdoc({
157
+ root,
158
+ name,
159
+ section,
160
+ date
161
+ });
162
+ await mkdir(dirname(outfile), { recursive: true });
163
+ await writeFile(outfile, mdoc);
164
+ }
165
+ //#endregion
166
+ export { man, renderManPageMdoc, writeManPage };
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@crustjs/man",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "description": "Generate mdoc(7) manual pages from Crust CLI definitions",
5
5
  "type": "module",
6
+ "sideEffects": false,
6
7
  "license": "MIT",
7
8
  "author": "chenxin-yan",
8
9
  "repository": {
@@ -27,28 +28,40 @@
27
28
  ],
28
29
  "exports": {
29
30
  ".": {
30
- "import": "./dist/index.js",
31
- "types": "./dist/index.d.ts"
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js"
32
33
  }
33
34
  },
34
35
  "publishConfig": {
35
36
  "access": "public"
36
37
  },
37
38
  "scripts": {
38
- "build": "bunup",
39
- "dev": "bunup --watch",
39
+ "build": "tsdown",
40
+ "dev": "tsdown --watch",
40
41
  "check:types": "tsc --noEmit",
41
42
  "test": "bun test",
42
- "publish": "bun publish --no-git-checks || true"
43
+ "prepack": "cp ../../LICENSE LICENSE",
44
+ "postpack": "rm -f LICENSE"
43
45
  },
44
46
  "devDependencies": {
45
47
  "@crustjs/config": "0.0.0",
46
- "@crustjs/core": "0.0.19",
47
- "@crustjs/plugins": "0.1.2",
48
- "bunup": "^0.16.31"
48
+ "@crustjs/core": "0.2.1",
49
+ "@crustjs/extensions": "0.2.1",
50
+ "@crustjs/skills": "0.2.1",
51
+ "tsdown": "^0.23.0"
49
52
  },
50
53
  "peerDependencies": {
51
- "@crustjs/core": "0.0.19",
52
- "typescript": "^6.0.3"
54
+ "@crustjs/core": "^0.2.1",
55
+ "typescript": "^7.0.0"
56
+ },
57
+ "peerDependenciesMeta": {
58
+ "typescript": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "engines": {
63
+ "bun": ">=1.4.0",
64
+ "node": ">=22",
65
+ "deno": ">=2.8"
53
66
  }
54
67
  }