@xyd-js/opencli 0.1.0-build.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.
@@ -0,0 +1,68 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { opencliToReferences } from './converters';
4
+ import type { OpencliSpecJson } from './types';
5
+
6
+ const spec: OpencliSpecJson = {
7
+ opencli: '1.0.0',
8
+ info: { title: 'spice', version: '1.0.0' },
9
+ commands: [
10
+ {
11
+ name: 'install',
12
+ description: 'Install one or more packages.',
13
+ arguments: [{ name: 'packages', required: true, description: 'Packages to install.' }],
14
+ options: [
15
+ { name: 'global', aliases: ['g'], description: 'Install globally.' },
16
+ { name: 'save-dev', description: 'Add to devDependencies.' },
17
+ { name: 'secret', description: 'hidden', hidden: true },
18
+ ],
19
+ commands: [{ name: 'dev', description: 'Install as a dev dependency.' }],
20
+ },
21
+ { name: 'list', description: 'List installed packages.' },
22
+ { name: 'internal', description: 'hidden', hidden: true },
23
+ ],
24
+ };
25
+
26
+ describe('opencliToReferences', () => {
27
+ it('emits one reference per (visible) command, including nested', () => {
28
+ const refs = opencliToReferences(spec);
29
+ const titles = refs.map((r) => r.title).sort();
30
+ expect(titles).toEqual(['install', 'install dev', 'list']); // 'internal' (hidden) excluded
31
+ });
32
+
33
+ it('builds Arguments/Options/Commands definitions with required + alias info', () => {
34
+ const install = opencliToReferences(spec).find((r) => r.title === 'install')!;
35
+ expect(install.canonical).toBe('install');
36
+ expect(install.description).toBe('Install one or more packages.');
37
+
38
+ const byTitle = Object.fromEntries(install.definitions.map((d) => [d.title, d]));
39
+ expect(Object.keys(byTitle).sort()).toEqual(['Arguments', 'Commands', 'Options']);
40
+
41
+ // argument required meta
42
+ const packages = byTitle.Arguments.properties[0];
43
+ expect(packages.name).toBe('packages');
44
+ expect(packages.meta).toEqual([{ name: 'required', value: 'true' }]);
45
+
46
+ // options: kebab name with `--`, alias note, hidden one dropped
47
+ const optNames = byTitle.Options.properties.map((p) => p.name);
48
+ expect(optNames).toEqual(['--global', '--save-dev']); // 'secret' (hidden) excluded
49
+ expect(byTitle.Options.properties[0].description).toContain('alias: -g');
50
+
51
+ // nested subcommand listed
52
+ expect(byTitle.Commands.properties.map((p) => p.name)).toEqual(['dev']);
53
+
54
+ // context.path is the region key the engine round-trips
55
+ expect(install.context.path).toBe('install');
56
+ expect(install.examples).toEqual({ groups: [] });
57
+ });
58
+
59
+ it('filters by region (command path)', () => {
60
+ const refs = opencliToReferences(spec, { regions: ['install dev'] });
61
+ expect(refs.map((r) => r.title)).toEqual(['install dev']);
62
+ expect(refs[0].context.path).toBe('install dev');
63
+ });
64
+
65
+ it('returns [] for null spec', () => {
66
+ expect(opencliToReferences(null)).toEqual([]);
67
+ });
68
+ });
@@ -0,0 +1,140 @@
1
+ import { generateUsage } from './generate';
2
+ import type { Argument, Command, OpencliSpecJson, Option } from './types';
3
+
4
+ // Structural subset of @xyd-js/uniform's `Reference` — kept local so the OpenCLI
5
+ // core stays free of the (React-typed) uniform package. The docs engine consumes
6
+ // these as uniform References (api.cli → Atlas).
7
+ interface OpencliRefProperty {
8
+ name: string;
9
+ type: string;
10
+ description: string;
11
+ meta?: { name: string; value: unknown }[];
12
+ }
13
+ interface OpencliRefDefinition {
14
+ title: string;
15
+ properties: OpencliRefProperty[];
16
+ }
17
+ export interface OpencliReference {
18
+ title: string;
19
+ canonical: string;
20
+ description: string;
21
+ // `group` drives sidebar placement (the docs engine groups references by it);
22
+ // `path` is the region key round-tripped through the page frontmatter.
23
+ context: { path: string; fullPath: string; group: string[] };
24
+ examples: { groups: never[] };
25
+ definitions: OpencliRefDefinition[];
26
+ }
27
+
28
+ export interface OpencliToReferencesOptions {
29
+ /**
30
+ * Restrict output to specific commands. Each region is a command path,
31
+ * space-joined from the CLI root (e.g. `"install"`, `"remote add"`).
32
+ */
33
+ regions?: string[];
34
+ }
35
+
36
+ /**
37
+ * Convert an OpenCLI document to uniform `Reference[]` — one Reference per
38
+ * command — so the docs engine can render CLI reference pages the same way it
39
+ * renders OpenAPI/GraphQL (`api.cli`). Mirrors `oapSchemaToReferences`.
40
+ */
41
+ export function opencliToReferences(
42
+ spec: OpencliSpecJson | null | undefined,
43
+ options: OpencliToReferencesOptions = {},
44
+ ): OpencliReference[] {
45
+ if (!spec) return [];
46
+
47
+ const cliTitle = spec.info?.title || 'cli';
48
+ const regionSet = options.regions?.length ? new Set(options.regions) : null;
49
+ const refs: OpencliReference[] = [];
50
+
51
+ const walk = (commands: Command[] | undefined, parentPath: string[]) => {
52
+ for (const cmd of commands || []) {
53
+ if (cmd.hidden) continue;
54
+ const cmdPath = [...parentPath, cmd.name];
55
+ const region = cmdPath.join(' ');
56
+ if (!regionSet || regionSet.has(region)) {
57
+ refs.push(commandToReference(spec, cmd, cmdPath, cliTitle));
58
+ }
59
+ if (cmd.commands?.length) walk(cmd.commands, cmdPath);
60
+ }
61
+ };
62
+ walk(spec.commands, []);
63
+
64
+ return refs;
65
+ }
66
+
67
+ function commandToReference(
68
+ spec: OpencliSpecJson,
69
+ cmd: Command,
70
+ cmdPath: string[],
71
+ cliTitle: string,
72
+ ): OpencliReference {
73
+ const region = cmdPath.join(' ');
74
+ const displayPath = `${cliTitle} ${region}`.trim();
75
+
76
+ const definitions: OpencliRefDefinition[] = [];
77
+
78
+ const args = (cmd.arguments || []).filter((a) => !a.hidden);
79
+ if (args.length) {
80
+ definitions.push({ title: 'Arguments', properties: args.map(argumentToProperty) });
81
+ }
82
+
83
+ const opts = (cmd.options || []).filter((o) => !o.hidden);
84
+ if (opts.length) {
85
+ definitions.push({ title: 'Options', properties: opts.map(optionToProperty) });
86
+ }
87
+
88
+ const subs = (cmd.commands || []).filter((c) => !c.hidden);
89
+ if (subs.length) {
90
+ definitions.push({
91
+ title: 'Commands',
92
+ properties: subs.map((s) => ({
93
+ name: s.name,
94
+ type: 'command',
95
+ description: s.description || '',
96
+ })),
97
+ });
98
+ }
99
+
100
+ // Sidebar grouping: top-level commands sit under "Commands"; a subcommand sits
101
+ // under a group named after its parent path (e.g. `auth login` → group "auth").
102
+ // (One group level is required — the docs engine drops references with an empty
103
+ // group — and a group must not mix direct pages with subgroups.)
104
+ const group = cmdPath.length === 1 ? ['Commands'] : [cmdPath.slice(0, -1).join(' ')];
105
+
106
+ return {
107
+ title: region || cliTitle,
108
+ canonical: cmdPath.join('/') || cliTitle,
109
+ description: cmd.description || '',
110
+ // context.path is the region key the docs engine writes into the page
111
+ // frontmatter (`cli: <spec>#<path>`) and reads back to re-resolve the command.
112
+ context: { path: region, fullPath: generateUsage(spec, cmd, displayPath), group },
113
+ examples: { groups: [] },
114
+ definitions,
115
+ };
116
+ }
117
+
118
+ function argumentToProperty(arg: Argument): OpencliRefProperty {
119
+ const meta = arg.required ? [{ name: 'required', value: 'true' }] : undefined;
120
+ return {
121
+ name: arg.name,
122
+ type: arg.arity ? 'array' : 'string',
123
+ description: arg.description || '',
124
+ ...(meta ? { meta } : {}),
125
+ };
126
+ }
127
+
128
+ function optionToProperty(opt: Option): OpencliRefProperty {
129
+ const aliasNote = opt.aliases?.length
130
+ ? ` (alias: ${opt.aliases.map((a) => (a.length === 1 ? `-${a}` : `--${a}`)).join(', ')})`
131
+ : '';
132
+ const meta = opt.required ? [{ name: 'required', value: 'true' }] : undefined;
133
+ return {
134
+ name: `--${opt.name}`,
135
+ // an option that takes a value vs. a boolean flag
136
+ type: opt.arguments?.length ? 'string' : 'boolean',
137
+ description: `${opt.description || ''}${aliasNote}`,
138
+ ...(meta ? { meta } : {}),
139
+ };
140
+ }
@@ -0,0 +1,206 @@
1
+ import type { OpencliSpecJson, Command } from './types.js';
2
+
3
+ export type IndentStyle = 'code' | 'list';
4
+
5
+ /**
6
+ * Generate usage line for a command (like: "shadcn init [options] [components...]")
7
+ */
8
+ export function generateUsage(_spec: OpencliSpecJson, command: Command, commandPath: string): string {
9
+ const parts: string[] = [];
10
+
11
+ // Command path
12
+ parts.push(commandPath);
13
+
14
+ // Options indicator
15
+ if (command.options && command.options.length > 0) {
16
+ const visibleOptions = command.options.filter((opt) => !opt.hidden);
17
+ if (visibleOptions.length > 0) {
18
+ parts.push('[options]');
19
+ }
20
+ }
21
+
22
+ // Arguments
23
+ if (command.arguments && command.arguments.length > 0) {
24
+ const visibleArgs = command.arguments.filter((arg) => !arg.hidden);
25
+ const argParts = visibleArgs.map((arg) => {
26
+ const name = arg.name.toLowerCase();
27
+ // Use ... suffix if argument can accept multiple values (variadic)
28
+ const suffix = arg.variadic ? '...' : '';
29
+ return arg.required ? `<${name}${suffix}>` : `[${name}${suffix}]`;
30
+ });
31
+ parts.push(...argParts);
32
+ }
33
+
34
+ return parts.join(' ');
35
+ }
36
+
37
+ /**
38
+ * Generate description for a command
39
+ */
40
+ export function generateDescription(command: Command): string {
41
+ return command.description || '';
42
+ }
43
+
44
+ /**
45
+ * Generate arguments documentation
46
+ * @param indentStyle - 'code' for tab-indented CLI style, 'list' for markdown list style
47
+ */
48
+ export function generateArguments(command: Command, indentStyle: IndentStyle = 'code'): string {
49
+ if (!command.arguments || command.arguments.length === 0) {
50
+ return '';
51
+ }
52
+
53
+ const visibleArgs = command.arguments.filter((arg) => !arg.hidden);
54
+ if (visibleArgs.length === 0) {
55
+ return '';
56
+ }
57
+
58
+ const lines: string[] = [];
59
+
60
+ for (const arg of visibleArgs) {
61
+ const name = arg.name.toLowerCase();
62
+ const desc = arg.description || '';
63
+
64
+ if (indentStyle === 'list') {
65
+ // Markdown list format: - `package` Package name
66
+ lines.push(`- \`${name}\`${desc ? ` ${desc}` : ''}`);
67
+ } else {
68
+ // Code/CLI format with tab indentation
69
+ const paddedName = name.padEnd(30);
70
+ lines.push(`\t${paddedName}${desc}`);
71
+ }
72
+ }
73
+
74
+ return lines.join('\n');
75
+ }
76
+
77
+ /**
78
+ * Generate options documentation
79
+ * @param indentStyle - 'code' for tab-indented CLI style, 'list' for markdown list style
80
+ */
81
+ export function generateOptions(command: Command, indentStyle: IndentStyle = 'code'): string {
82
+ if (!command.options || command.options.length === 0) {
83
+ return '';
84
+ }
85
+
86
+ const visibleOptions = command.options.filter((opt) => !opt.hidden);
87
+ if (visibleOptions.length === 0) {
88
+ return '';
89
+ }
90
+
91
+ const lines: string[] = [];
92
+
93
+ for (const option of visibleOptions) {
94
+ // Build option signature
95
+ const aliases = option.aliases?.filter((a) => a.length === 1) || [];
96
+ const short = aliases.length > 0 ? `-${aliases[0]}` : '';
97
+ const long = `--${option.name}`;
98
+
99
+ // Add argument placeholder if option takes arguments
100
+ let argPlaceholder = '';
101
+ if (option.arguments && option.arguments.length > 0) {
102
+ const argNames = option.arguments.filter((arg) => !arg.hidden).map((arg) => `<${arg.name.toLowerCase()}>`);
103
+ argPlaceholder = ' ' + argNames.join(' ');
104
+ }
105
+
106
+ const desc = option.description || '';
107
+
108
+ if (indentStyle === 'list') {
109
+ // Markdown list format: - `-g`, `--global` Install globally
110
+ const shortPart = short ? `\`${short}\`, ` : '';
111
+ lines.push(`- ${shortPart}\`${long}\`${argPlaceholder}${desc ? ` ${desc}` : ''}`);
112
+ } else {
113
+ // Code/CLI format with tab indentation
114
+ const signature = `${short ? `${short}, ` : ''}${long}${argPlaceholder}`;
115
+ const paddedSignature = signature.padEnd(30);
116
+ lines.push(`\t${paddedSignature}${desc}`);
117
+ }
118
+ }
119
+
120
+ return lines.join('\n');
121
+ }
122
+
123
+ /**
124
+ * TODO: OPTIONS DO ALMOST THE SAME
125
+ * Generate flags/options documentation
126
+ */
127
+ export function generateFlags(command: Command): string {
128
+ if (!command.options || command.options.length === 0) {
129
+ return 'No flags available.';
130
+ }
131
+
132
+ const visibleOptions = command.options.filter((opt) => !opt.hidden);
133
+ if (visibleOptions.length === 0) {
134
+ return 'No flags available.';
135
+ }
136
+
137
+ const lines: string[] = [];
138
+
139
+ for (const option of visibleOptions) {
140
+ const optionParts: string[] = [];
141
+
142
+ // Option name and aliases
143
+ const aliases = option.aliases?.filter((a) => a.length === 1) || [];
144
+ const short = aliases.length > 0 ? `-${aliases[0]}` : '';
145
+ const long = `--${option.name}`;
146
+ const name = short ? `\`${short}\`, \`${long}\`` : `\`${long}\``;
147
+ optionParts.push(name);
148
+
149
+ // Required indicator
150
+ if (option.required) {
151
+ optionParts.push('**(required)**');
152
+ }
153
+
154
+ lines.push(`- ${optionParts.join(' ')}`);
155
+
156
+ // Description
157
+ if (option.description) {
158
+ lines.push(` ${option.description}`);
159
+ }
160
+
161
+ // Option arguments
162
+ if (option.arguments && option.arguments.length > 0) {
163
+ const argParts = option.arguments
164
+ .filter((arg) => !arg.hidden)
165
+ .map((arg) => {
166
+ const name = arg.name.toUpperCase();
167
+ return arg.required ? `<${name}>` : `[${name}]`;
168
+ });
169
+ if (argParts.length > 0) {
170
+ lines.push(` Arguments: ${argParts.join(' ')}`);
171
+ }
172
+ }
173
+ }
174
+
175
+ return lines.join('\n');
176
+ }
177
+
178
+ /**
179
+ * Generate subcommands documentation
180
+ */
181
+ export function generateCommands(command: Command): string {
182
+ if (!command.commands || command.commands.length === 0) {
183
+ return 'No subcommands available.';
184
+ }
185
+
186
+ const visibleCommands = command.commands.filter((cmd) => !cmd.hidden);
187
+ if (visibleCommands.length === 0) {
188
+ return 'No subcommands available.';
189
+ }
190
+
191
+ const lines: string[] = [];
192
+
193
+ for (const subcommand of visibleCommands) {
194
+ lines.push(`- \`${subcommand.name}\``);
195
+
196
+ if (subcommand.aliases && subcommand.aliases.length > 0) {
197
+ lines.push(` Aliases: ${subcommand.aliases.map((a) => `\`${a}\``).join(', ')}`);
198
+ }
199
+
200
+ if (subcommand.description) {
201
+ lines.push(` ${subcommand.description}`);
202
+ }
203
+ }
204
+
205
+ return lines.join('\n');
206
+ }
package/src/index.ts ADDED
@@ -0,0 +1,20 @@
1
+ // OpenCLI core: the data model (generated from opencli-spec.json) plus the
2
+ // pure spec/loader/generator helpers shared by opencli-remark and the
3
+ // openapi2opencli / opencli2* code generators.
4
+ export * from './types';
5
+
6
+ export { loadOpencliSpec, findCommand } from './spec';
7
+ export type { LoadOpencliSpecOptions } from './spec';
8
+
9
+ export {
10
+ generateUsage,
11
+ generateDescription,
12
+ generateArguments,
13
+ generateOptions,
14
+ generateCommands,
15
+ generateFlags,
16
+ } from './generate';
17
+ export type { IndentStyle } from './generate';
18
+
19
+ export { opencliToReferences } from './converters';
20
+ export type { OpencliReference, OpencliToReferencesOptions } from './converters';
package/src/spec.ts ADDED
@@ -0,0 +1,106 @@
1
+ import type { OpencliSpecJson, Command } from './types.js';
2
+
3
+ export interface LoadOpencliSpecOptions {
4
+ /**
5
+ * Base directory used to resolve a relative file `source`.
6
+ * Defaults to `process.cwd()`. (The remark plugin passes the markdown file's dirname.)
7
+ */
8
+ cwd?: string;
9
+ }
10
+
11
+ /**
12
+ * Load an OpenCLI spec from a file path or an HTTP(S) URL.
13
+ *
14
+ * Returns `null` (and logs) on any failure so callers can leave placeholders
15
+ * untouched rather than throwing.
16
+ */
17
+ export async function loadOpencliSpec(
18
+ source: string,
19
+ opts?: LoadOpencliSpecOptions,
20
+ ): Promise<OpencliSpecJson | null> {
21
+ try {
22
+ let content: string;
23
+
24
+ if (source.startsWith('http://') || source.startsWith('https://')) {
25
+ // Load from URL
26
+ const response = await fetch(source);
27
+ if (!response.ok) {
28
+ throw new Error(`Failed to fetch OpenCLI spec: ${response.statusText}`);
29
+ }
30
+ content = await response.text();
31
+ } else {
32
+ // Load from file
33
+ const fs = await import('node:fs/promises');
34
+ const path = await import('node:path');
35
+
36
+ // Resolve relative to the provided cwd (or process.cwd())
37
+ const base = opts?.cwd ?? process.cwd();
38
+ const resolvedPath = path.isAbsolute(source) ? source : path.resolve(base, source);
39
+
40
+ content = await fs.readFile(resolvedPath, 'utf-8');
41
+ }
42
+
43
+ return JSON.parse(content) as OpencliSpecJson;
44
+ } catch (error) {
45
+ console.error(`Error loading OpenCLI spec from ${source}:`, error);
46
+ return null;
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Find a command in the spec by path (e.g., "spice install").
52
+ * If the path is empty, returns a synthetic root command built from the spec root.
53
+ */
54
+ export function findCommand(spec: OpencliSpecJson, commandPath: string): Command | null {
55
+ let parts = commandPath.trim().split(/\s+/).filter(Boolean);
56
+
57
+ // If no path specified, create a synthetic root command from spec root
58
+ if (parts.length === 0) {
59
+ return {
60
+ name: spec.info?.title || 'root',
61
+ description: spec.info?.description || spec.info?.summary,
62
+ options: spec.options || [],
63
+ arguments: spec.arguments || [],
64
+ commands: spec.commands || [],
65
+ examples: spec.examples || [],
66
+ exitCodes: spec.exitCodes || [],
67
+ interactive: spec.interactive,
68
+ };
69
+ }
70
+
71
+ // Skip the CLI name if it matches the first part (e.g., "spice install" -> "install")
72
+ if (parts.length > 0 && spec.info?.title && parts[0] === spec.info.title) {
73
+ parts = parts.slice(1);
74
+ }
75
+
76
+ // If only the CLI name was provided, return root command
77
+ if (parts.length === 0) {
78
+ return {
79
+ name: spec.info?.title || 'root',
80
+ description: spec.info?.description || spec.info?.summary,
81
+ options: spec.options || [],
82
+ arguments: spec.arguments || [],
83
+ commands: spec.commands || [],
84
+ examples: spec.examples || [],
85
+ exitCodes: spec.exitCodes || [],
86
+ interactive: spec.interactive,
87
+ };
88
+ }
89
+
90
+ // Start from root commands
91
+ let currentCommands = spec.commands || [];
92
+ let foundCommand: Command | null = null;
93
+
94
+ for (const part of parts) {
95
+ foundCommand = currentCommands.find((cmd) => cmd.name === part || cmd.aliases?.includes(part)) || null;
96
+
97
+ if (!foundCommand) {
98
+ return null;
99
+ }
100
+
101
+ // Move to subcommands for next iteration
102
+ currentCommands = foundCommand.commands || [];
103
+ }
104
+
105
+ return foundCommand;
106
+ }