From 1891c3373d4bceb59a3a0bea9be75dc3db0a1e50 Mon Sep 17 00:00:00 2001 From: Gainer Date: Tue, 24 Nov 2026 06:10:11 +0100 Subject: [PATCH 1/2] feat: add SDK API reference documentation generator --- docs/API_REFERENCE_GENERATOR.md | 38 +++++++ src/apiDocGenerator.ts | 187 ++++++++++++++++++++++++++++++-- src/docs/index.ts | 1 + test/apiDocGenerator.test.ts | 98 +++++++++++++++++ 4 files changed, 316 insertions(+), 8 deletions(-) create mode 100644 docs/API_REFERENCE_GENERATOR.md create mode 100644 test/apiDocGenerator.test.ts diff --git a/docs/API_REFERENCE_GENERATOR.md b/docs/API_REFERENCE_GENERATOR.md new file mode 100644 index 00000000..4b12ce9f --- /dev/null +++ b/docs/API_REFERENCE_GENERATOR.md @@ -0,0 +1,38 @@ +# API Reference Generator + +The SDK exports `ApiDocGenerator` for creating API references from TypeScript +source text and JSDoc comments. It can produce complete Markdown and HTML +documents, or a JSON manifest for integration with other documentation tools. + +```ts +import { ApiDocGenerator } from '@stellar-split/sdk'; + +const generator = new ApiDocGenerator({ + version: '1.2.0', + title: 'SDK API Reference', + sources: { + client: clientSourceText, + wallets: walletSourceText, + }, + categories: { + client: 'Core', + wallets: 'Wallets', + }, + includeDeprecated: false, +}); + +const markdown = generator.generate('markdown'); +const html = generator.generate('html'); +const manifest = generator.generate('json'); +``` + +`generate()` accepts `markdown`, `html`, or `json`. The JSON output is a +serialized `DocManifest` containing the SDK version, parsed entries, navigation +tree, and sorted entry index. `generateManifest()` returns that typed object +directly. `generateModuleMarkdown()`, `generateIndex()`, `search()`, and the +entry accessors are also available for custom documentation workflows. + +Sources are keyed by module name and should contain JSDoc comments immediately +before the declarations they describe. Supported metadata includes +`@param`, `@returns`, `@example`, `@deprecated`, and `@since`. Entries default +to the `General` category when no category mapping is provided. diff --git a/src/apiDocGenerator.ts b/src/apiDocGenerator.ts index 1b2c946e..92a66ae6 100644 --- a/src/apiDocGenerator.ts +++ b/src/apiDocGenerator.ts @@ -92,6 +92,9 @@ export interface DocManifest { index: string[]; } +/** Supported API reference output formats. */ +export type DocOutputFormat = 'markdown' | 'html' | 'json'; + // --------------------------------------------------------------------------- // Internal helpers // --------------------------------------------------------------------------- @@ -158,13 +161,14 @@ function extractJsDocBlocks(source: string): Array<{ comment: string; afterText: /** Guess the entry kind from the token immediately following the comment. */ function guessKind(afterText: string): DocEntryKind { - const first = afterText.split(/[\s({]/)[0] ?? ''; - if (first === 'class') return 'class'; - if (first === 'interface') return 'interface'; - if (first === 'type') return 'type'; - if (first === 'function' || first === 'async') return 'function'; - if (first === 'export' || first === 'const' || first === 'let' || first === 'var') { - if (/=\s*(async\s+)?function|=\s*\(|=>\s*{/.test(afterText)) return 'function'; + const declaration = /^(?:(?:export|default|declare|abstract|async)\s+)*(class|interface|type|function|const|let|var)\b/.exec(afterText); + const kind = declaration?.[1]; + if (kind === 'class') return 'class'; + if (kind === 'interface') return 'interface'; + if (kind === 'type') return 'type'; + if (kind === 'function') return 'function'; + if (kind === 'const' || kind === 'let' || kind === 'var') { + if (/=\s*(?:async\s+)?function\b|=\s*(?:async\s*)?\([^)]*\)\s*=>|=\s*[A-Za-z_$][\w$]*\s*=>/.test(afterText)) return 'function'; return 'variable'; } return 'function'; @@ -283,6 +287,10 @@ export interface ApiDocGeneratorOptions { * Modules without an entry are grouped under "General". */ categories?: Record; + /** Heading used by complete-document exporters. Defaults to "API Reference". */ + title?: string; + /** Whether deprecated entries are included in generated output. Defaults to true. */ + includeDeprecated?: boolean; } /** @@ -301,12 +309,16 @@ export class ApiDocGenerator { private readonly version: string; private readonly sources: Record; private readonly categories: Record; + private readonly title: string; + private readonly includeDeprecated: boolean; private entries: Map = new Map(); constructor(options: ApiDocGeneratorOptions) { this.version = options.version; this.sources = options.sources; this.categories = options.categories ?? {}; + this.title = options.title ?? 'API Reference'; + this.includeDeprecated = options.includeDeprecated ?? true; } // ------------------------------------------------------------------------- @@ -332,6 +344,7 @@ export class ApiDocGenerator { const name = extractName(afterText); if (!name) continue; const parsed = parseJsDoc(comment); + if (parsed.deprecated && !this.includeDeprecated) continue; const id = `${moduleName}/${name}`; const entry: DocEntry = { id, @@ -529,7 +542,7 @@ export class ApiDocGenerator { const moduleNames = [...new Set(Array.from(this.entries.values()).map((e) => e.module))].sort(); const lines: string[] = [ - `# API Reference — v${this.version}`, + `# ${this.title} — v${this.version}`, '', `> Generated at ${new Date().toISOString()}`, '', @@ -551,6 +564,164 @@ export class ApiDocGenerator { return lines.join('\n'); } + /** + * Generate the complete API reference as a single Markdown document. + */ + generateMarkdown(): string { + if (this.entries.size === 0) this.parse(); + + const lines = [ + `# ${this.title}`, + '', + `Version: \`${this.version}\``, + '', + this.generateIndex().replace(/^#[^\n]*\n\n/, ''), + '---', + '', + ]; + const navigation = this.buildNavigation(); + + for (const category of navigation.children) { + lines.push(`## ${category.label}`, ''); + for (const module of category.children) { + lines.push(`### ${module.label}`, ''); + for (const id of module.entryIds) { + const entry = this.entries.get(id); + if (!entry) continue; + lines.push(`#### ${entry.name}`, ''); + if (entry.deprecated) { + lines.push(`> **Deprecated** ${entry.deprecationMessage ?? ''}`, ''); + } + if (entry.since) lines.push(`*Since: ${entry.since}*`, ''); + if (entry.description) lines.push(entry.description, ''); + if (entry.params.length > 0) { + lines.push('##### Parameters', '', '| Name | Type | Optional | Description |', '|------|------|----------|-------------|'); + for (const param of entry.params) { + const description = param.description.replace(/\|/g, '\\|').replace(/\n/g, ' '); + lines.push(`| \`${param.name}\` | ${param.type ? `\`${param.type}\`` : '—'} | ${param.optional ? 'Yes' : 'No'} | ${description} |`); + } + lines.push(''); + } + if (entry.returns) lines.push('##### Returns', '', entry.returns, ''); + if (entry.examples.length > 0) { + lines.push('##### Examples', ''); + for (const example of entry.examples) lines.push('```ts', example, '```', ''); + } + if (entry.tags.length > 0) { + lines.push('##### Additional documentation', ''); + for (const tag of entry.tags) { + const description = tag.description.replace(/\n/g, ' '); + lines.push(`- **@${tag.tag}**${tag.name ? ` \`${tag.name}\`` : ''}${description ? ` — ${description}` : ''}`); + } + lines.push(''); + } + lines.push('---', ''); + } + } + } + + return lines.join('\n'); + } + + /** + * Generate a self-contained HTML API reference. + */ + generateHtml(): string { + if (this.entries.size === 0) this.parse(); + + const escapeHtml = (value: string): string => + value.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); + const navigation = this.buildNavigation(); + const html: string[] = [ + '', + '', + '', + '', + '', + `${escapeHtml(this.title)}`, + '', + '', + `

${escapeHtml(this.title)}

`, + `

Version: ${escapeHtml(this.version)}

`, + ''); + for (const category of navigation.children) { + html.push(`

${escapeHtml(category.label)}

`); + for (const module of category.children) { + html.push(`

${escapeHtml(module.label)}

`); + for (const id of module.entryIds) { + const entry = this.entries.get(id); + if (!entry) continue; + html.push(`

${escapeHtml(entry.name)}

`); + if (entry.deprecated) html.push(`

Deprecated ${escapeHtml(entry.deprecationMessage ?? '')}

`); + if (entry.since) html.push(`

Since: ${escapeHtml(entry.since)}

`); + if (entry.description) html.push(`

${escapeHtml(entry.description).replace(/\n/g, '
')}

`); + if (entry.params.length > 0) { + html.push('
Parameters
'); + for (const param of entry.params) { + html.push(``); + } + html.push('
NameTypeOptionalDescription
${escapeHtml(param.name)}${escapeHtml(param.type ?? '')}${param.optional ? 'Yes' : 'No'}${escapeHtml(param.description)}
'); + } + if (entry.returns) html.push(`
Returns

${escapeHtml(entry.returns)}

`); + for (const example of entry.examples) html.push(`
${escapeHtml(example)}
`); + if (entry.tags.length > 0) { + html.push('
Additional documentation
    '); + for (const tag of entry.tags) { + const name = tag.name ? ` ${escapeHtml(tag.name)}` : ''; + const description = tag.description ? ` — ${escapeHtml(tag.description)}` : ''; + html.push(`
  • @${escapeHtml(tag.tag)}${name}${description}
  • `); + } + html.push('
'); + } + html.push('
'); + } + html.push('
'); + } + html.push('
'); + } + + html.push('
', '', ''); + return html.join('\n'); + } + + /** Serialize the versioned documentation manifest as JSON. */ + generateJson(): string { + return JSON.stringify(this.generateManifest(), null, 2); + } + + /** Generate the complete reference in the requested output format. */ + generate(format: DocOutputFormat): string { + switch (format) { + case 'markdown': + return this.generateMarkdown(); + case 'html': + return this.generateHtml(); + case 'json': + return this.generateJson(); + default: { + const exhaustiveCheck: never = format; + throw new Error(`Unsupported API reference format: ${String(exhaustiveCheck)}`); + } + } + } + // ------------------------------------------------------------------------- // Manifest // ------------------------------------------------------------------------- diff --git a/src/docs/index.ts b/src/docs/index.ts index 54af7cb2..4d98ec28 100644 --- a/src/docs/index.ts +++ b/src/docs/index.ts @@ -14,4 +14,5 @@ export type { DocTagName, NavNode, ApiDocGeneratorOptions, + DocOutputFormat, } from '../apiDocGenerator.js'; diff --git a/test/apiDocGenerator.test.ts b/test/apiDocGenerator.test.ts new file mode 100644 index 00000000..ac85af63 --- /dev/null +++ b/test/apiDocGenerator.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest'; +import { ApiDocGenerator } from '../src/apiDocGenerator.js'; + +const source = ` +/** Runs a task. + * @param {string} name - Task name + * @returns Task result + * @example + * runTask("build") + * @since 1.2.0 + * @throws {Error} - + */ +export function runTask(name: string): string { + return name; +} + +/** An old helper. + * @deprecated Use runTask instead. + */ +export const oldTask = () => {}; + +/** A task runner. */ +export class TaskRunner {} + +/** Configuration for a task. */ +export interface TaskConfig {} + +/** A task name. */ +export type TaskName = string; +`; + +describe('ApiDocGenerator', () => { + it('parses exported declaration kinds and JSDoc metadata', () => { + const generator = new ApiDocGenerator({ version: '1.2.0', sources: { tasks: source } }); + const entries = generator.getEntries(); + + expect(entries.map(({ name, kind }) => [name, kind])).toEqual([ + ['runTask', 'function'], + ['oldTask', 'function'], + ['TaskRunner', 'class'], + ['TaskConfig', 'interface'], + ['TaskName', 'type'], + ]); + expect(generator.getEntry('tasks/runTask')).toMatchObject({ + description: 'Runs a task.', + params: [{ name: 'name', type: 'string', description: 'Task name', optional: false }], + returns: 'Task result', + examples: ['runTask("build")'], + since: '1.2.0', + }); + }); + + it('generates customized Markdown, HTML, and JSON references', () => { + const generator = new ApiDocGenerator({ + version: '1.2.0', + sources: { tasks: source }, + categories: { tasks: 'Task Management' }, + title: 'SDK Reference', + }); + + const markdown = generator.generate('markdown'); + expect(markdown).toContain('# SDK Reference'); + expect(markdown).toContain('## Task Management'); + expect(markdown).toContain('#### runTask'); + expect(markdown).toContain('### Parameters'); + expect(markdown).toContain('Since: 1.2.0'); + expect(markdown).toContain('@throws'); + + const html = generator.generate('html'); + expect(html).toContain('SDK Reference'); + expect(html).toContain('

Task Management

'); + expect(html).toContain('