Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 1,367 lines 38.8 KB
Raw
1 /**
2 * TypeScript SDK Documentation Generator
3 *
4 * Generates MDX documentation from TypeScript source code using TypeDoc.
5 * Output is written to the docs content directory.
6 *
7 * Run: pnpm --filter @composio/core generate:docs
8 */
9
10 import { readFileSync } from 'fs';
11 import { mkdir, writeFile, rm, readdir, readFile } from 'fs/promises';
12 import { join, dirname, resolve } from 'path';
13 import { execFileSync } from 'child_process';
14 import { fileURLToPath, pathToFileURL } from 'url';
15
16 // Paths (relative to ts/packages/core)
17 const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
18 const PACKAGE_DIR = join(SCRIPT_DIR, '..');
19 const MODELS_DIR = join(PACKAGE_DIR, 'src/models');
20 const OUTPUT_DIR = join(PACKAGE_DIR, '../../../docs/content/reference/sdk-reference/typescript');
21 const TEMP_JSON = join(PACKAGE_DIR, '.typedoc-output.json');
22 const TYPEDOC_BIN = join(
23 dirname(fileURLToPath(import.meta.resolve('typedoc/package.json'))),
24 'bin',
25 'typedoc'
26 );
27
28 // Internal classes that should NOT be documented (accessed via other APIs)
29 const INTERNAL_CLASSES = new Set([
30 'AuthScheme', // Utility class
31 'ConnectionRequest', // Utility
32 'Files', // Not yet stable API
33 'ToolRouter', // Experimental
34 ]);
35
36 // Classes that users instantiate directly (show constructor)
37 const USER_INSTANTIATED_CLASSES = new Set(['Composio']);
38
39 // Pure-docs presentation overrides. The public class names retain their
40 // legacy "ToolRouter*" names in source (renaming them is a breaking change),
41 // but the SDK reference presents them under the canonical "Session" naming.
42 // Keys are the source class names.
43 const DISPLAY_NAME_OVERRIDES: Record<string, string> = {
44 ToolRouterSession: 'Session',
45 ToolRouterSessionFilesMount: 'Session files',
46 };
47
48 const SLUG_OVERRIDES: Record<string, string> = {
49 ToolRouterSession: 'session',
50 ToolRouterSessionFilesMount: 'session-files',
51 };
52
53 // Resolve the display title for a class (falls back to the class name).
54 function displayNameFor(className: string): string {
55 return DISPLAY_NAME_OVERRIDES[className] ?? className;
56 }
57
58 // Resolve the URL slug / filename stem for a class (falls back to kebab-case).
59 function slugFor(className: string): string {
60 return SLUG_OVERRIDES[className] ?? toKebabCase(className);
61 }
62
63 // Model file names become typedoc arguments. They are never interpolated into a
64 // shell, but a name outside this charset is still not a model and is skipped
65 // rather than passed through.
66 const MODEL_FILE_NAME = /^[A-Za-z0-9_.-]+\.ts$/;
67
68 // Discover model files automatically
69 export async function discoverModelFiles(modelsDir: string = MODELS_DIR): Promise<string[]> {
70 const files = await readdir(modelsDir);
71 return files
72 .filter(f => f.endsWith('.ts') && !f.includes('.test.') && !f.includes('.spec.'))
73 .filter(f => {
74 if (MODEL_FILE_NAME.test(f)) {
75 return true;
76 }
77 console.warn(` Skipping model file with an unexpected name: ${JSON.stringify(f)}`);
78 return false;
79 })
80 .map(f => `src/models/${f}`);
81 }
82
83 // TypeDoc arguments, one array element per argument so the entry points are
84 // never joined into a shell command line.
85 function buildTypeDocArgs(
86 entryPoints: readonly string[],
87 outputJson: string = TEMP_JSON,
88 packageDir: string = PACKAGE_DIR
89 ): string[] {
90 return [
91 '--json',
92 outputJson,
93 '--tsconfig',
94 'tsconfig.json',
95 // Without this, TypeDoc reports source paths relative to the common
96 // directory of every file it visited, which moves whenever a model pulls in
97 // a file outside `src/`. Pinning it keeps `sources[].fileName` resolvable.
98 '--displayBasePath',
99 packageDir,
100 '--excludePrivate',
101 '--excludeProtected',
102 '--excludeInternal',
103 '--skipErrorChecking', // Skip TS errors, we just want the documentation
104 ...entryPoints,
105 ];
106 }
107
108 interface TypeDocCommandOptions {
109 outputJson?: string;
110 packageDir?: string;
111 typedocBin?: string;
112 }
113
114 export function runTypeDocCommand(
115 entryPoints: readonly string[],
116 {
117 outputJson = TEMP_JSON,
118 packageDir = PACKAGE_DIR,
119 typedocBin = TYPEDOC_BIN,
120 }: TypeDocCommandOptions = {}
121 ): void {
122 execFileSync(
123 process.execPath,
124 [typedocBin, ...buildTypeDocArgs(entryPoints, outputJson, packageDir)],
125 {
126 stdio: 'pipe',
127 cwd: packageDir,
128 }
129 );
130 }
131
132 // Discover classes to document from TypeDoc output
133 function discoverClassesToDocument(project: TypeDocProject): string[] {
134 const classes: string[] = [];
135
136 // Always include Composio first
137 classes.push('Composio');
138
139 if (!project.children) return classes;
140
141 for (const child of project.children) {
142 // Direct class
143 if (child.kind === TYPEDOC_KIND.Class && !INTERNAL_CLASSES.has(child.name)) {
144 if (!classes.includes(child.name)) {
145 classes.push(child.name);
146 }
147 }
148
149 // Class inside a module
150 if (child.kind === TYPEDOC_KIND.Module && child.children) {
151 for (const nested of child.children) {
152 if (nested.kind === TYPEDOC_KIND.Class && !INTERNAL_CLASSES.has(nested.name)) {
153 if (!classes.includes(nested.name)) {
154 classes.push(nested.name);
155 }
156 }
157 }
158 }
159 }
160
161 return classes;
162 }
163
164 // TypeDoc kind numbers (v2.0 schema)
165 const TYPEDOC_KIND = {
166 Module: 2,
167 Class: 128,
168 Constructor: 512,
169 Method: 2048,
170 Property: 1024,
171 Accessor: 262144,
172 } as const;
173
174 // Helper to find a class by name, searching through modules
175 function findClass(project: TypeDocProject, className: string): TypeDocReflection | undefined {
176 if (!project.children) return undefined;
177
178 for (const child of project.children) {
179 // Check if this child is the class we're looking for
180 if (child.name === className && child.kind === TYPEDOC_KIND.Class) {
181 return child;
182 }
183
184 // If it's a module, search inside it
185 if (child.kind === TYPEDOC_KIND.Module && child.children) {
186 for (const nested of child.children) {
187 if (nested.name === className && nested.kind === TYPEDOC_KIND.Class) {
188 return nested;
189 }
190 }
191 }
192 }
193
194 return undefined;
195 }
196
197 interface TypeDocReflection {
198 id: number;
199 name: string;
200 kind: number;
201 kindString?: string;
202 comment?: {
203 summary?: Array<{ kind: string; text: string }>;
204 blockTags?: Array<{
205 tag: string;
206 content: Array<{ kind: string; text: string }>;
207 }>;
208 };
209 signatures?: TypeDocSignature[];
210 type?: TypeDocType;
211 children?: TypeDocReflection[];
212 flags?: {
213 isPrivate?: boolean;
214 isProtected?: boolean;
215 isPublic?: boolean;
216 isOptional?: boolean;
217 isStatic?: boolean;
218 };
219 sources?: Array<{ fileName: string; line: number }>;
220 typeParameters?: TypeDocTypeParameter[];
221 defaultValue?: string;
222 }
223
224 interface TypeDocSignature {
225 id: number;
226 name: string;
227 kind: number;
228 kindString?: string;
229 comment?: TypeDocReflection['comment'];
230 parameters?: TypeDocParameter[];
231 type?: TypeDocType;
232 typeParameter?: TypeDocTypeParameter[];
233 sources?: Array<{ fileName: string; line: number }>;
234 }
235
236 interface TypeDocParameter {
237 id: number;
238 name: string;
239 kind: number;
240 flags?: { isOptional?: boolean };
241 type?: TypeDocType;
242 comment?: TypeDocReflection['comment'];
243 defaultValue?: string;
244 }
245
246 export function isParameterRequired(
247 param: Pick<TypeDocParameter, 'flags' | 'defaultValue'>
248 ): boolean {
249 return !param.flags?.isOptional && param.defaultValue === undefined;
250 }
251
252 interface TypeDocType {
253 type: string;
254 name?: string;
255 value?: string | number | boolean;
256 elementType?: TypeDocType;
257 types?: TypeDocType[];
258 typeArguments?: TypeDocType[];
259 declaration?: TypeDocReflection;
260 target?: number | TypeDocType;
261 package?: string;
262 qualifiedName?: string;
263 }
264
265 interface TypeDocTypeParameter {
266 id: number;
267 name: string;
268 kind: number;
269 type?: TypeDocType;
270 default?: TypeDocType;
271 }
272
273 interface TypeDocProject {
274 id: number;
275 name: string;
276 kind: number;
277 children?: TypeDocReflection[];
278 }
279
280 interface MethodDoc {
281 name: string;
282 description: string;
283 signatures: {
284 parameters: {
285 name: string;
286 type: string;
287 required: boolean;
288 description: string;
289 default?: string;
290 }[];
291 returnType: string;
292 returnDescription?: string;
293 }[];
294 examples: string[];
295 isAsync: boolean;
296 /** Present when the symbol carries an `@deprecated` JSDoc tag. The string is
297 * the (possibly empty) tag body, e.g. the recommended replacement. */
298 deprecated?: string;
299 source?: { file: string; line: number };
300 }
301
302 interface PropertyDoc {
303 name: string;
304 type: string;
305 description: string;
306 default?: string;
307 }
308
309 interface ClassDoc {
310 name: string;
311 description: string;
312 constructor?: MethodDoc;
313 methods: MethodDoc[];
314 properties: PropertyDoc[];
315 source?: { file: string; line: number };
316 /** Present when the class carries a class-level `@deprecated` JSDoc tag. */
317 deprecated?: string;
318 }
319
320 interface SourceSignatureTypes {
321 parameters: Map<string, string>;
322 returnType?: string;
323 }
324
325 const sourceFileCache = new Map<string, string>();
326
327 function extractText(content?: Array<{ kind: string; text: string }>): string {
328 if (!content) return '';
329 return content
330 .map(c => c.text)
331 .join('')
332 .trim();
333 }
334
335 function extractDescription(comment?: TypeDocReflection['comment']): string {
336 if (!comment) return '';
337 let desc = extractText(comment.summary);
338
339 // Clean up bare API paths that shouldn't be in user-facing docs, while
340 // preserving intentional route references inside inline code spans.
341 desc = desc
342 .split(/(`[^`]*`)/g)
343 .map(segment =>
344 segment.startsWith('`') ? segment : segment.replace(/\/?api\/v\d+\/[^\s`),.;]*/g, '')
345 )
346 .join('')
347 .trim();
348
349 // Clean up multiple newlines and spaces
350 desc = desc
351 .replace(/\n{3,}/g, '\n\n')
352 .replace(/ +/g, ' ')
353 .trim();
354
355 return desc;
356 }
357
358 function extractTag(comment: TypeDocReflection['comment'] | undefined, tagName: string): string[] {
359 if (!comment?.blockTags) return [];
360 return comment.blockTags.filter(t => t.tag === tagName).map(t => extractText(t.content));
361 }
362
363 // TypeDoc source paths are relative to `--displayBasePath`, which is the package
364 // directory. A path that does not resolve means the two have drifted apart, and
365 // every signature would silently fall back to TypeDoc's expanded types, so the
366 // read is left to throw.
367 export function getSourceFileText(fileName: string, packageDir: string = PACKAGE_DIR): string {
368 const filePath = resolve(packageDir, fileName);
369 const cached = sourceFileCache.get(filePath);
370 if (cached !== undefined) return cached;
371
372 const text = readFileSync(filePath, 'utf-8');
373 sourceFileCache.set(filePath, text);
374 return text;
375 }
376
377 function getLineOffset(text: string, line: number): number {
378 let offset = 0;
379 for (let currentLine = 1; currentLine < line; currentLine++) {
380 const nextLine = text.indexOf('\n', offset);
381 if (nextLine === -1) return text.length;
382 offset = nextLine + 1;
383 }
384 return offset;
385 }
386
387 function updateTypeDepth(
388 char: string,
389 depth: { angle: number; brace: number; bracket: number; paren: number }
390 ) {
391 switch (char) {
392 case '<':
393 depth.angle++;
394 break;
395 case '>':
396 depth.angle = Math.max(0, depth.angle - 1);
397 break;
398 case '{':
399 depth.brace++;
400 break;
401 case '}':
402 depth.brace = Math.max(0, depth.brace - 1);
403 break;
404 case '[':
405 depth.bracket++;
406 break;
407 case ']':
408 depth.bracket = Math.max(0, depth.bracket - 1);
409 break;
410 case '(':
411 depth.paren++;
412 break;
413 case ')':
414 depth.paren = Math.max(0, depth.paren - 1);
415 break;
416 }
417 }
418
419 function splitTopLevel(input: string, delimiter: string): string[] {
420 const parts: string[] = [];
421 const depth = { angle: 0, brace: 0, bracket: 0, paren: 0 };
422 let quote: string | null = null;
423 let start = 0;
424
425 for (let i = 0; i < input.length; i++) {
426 const char = input[i];
427 const prev = input[i - 1];
428
429 if (quote) {
430 if (char === quote && prev !== '\\') {
431 quote = null;
432 }
433 continue;
434 }
435
436 if (char === "'" || char === '"' || char === '`') {
437 quote = char;
438 continue;
439 }
440
441 updateTypeDepth(char, depth);
442
443 if (
444 char === delimiter &&
445 depth.angle === 0 &&
446 depth.brace === 0 &&
447 depth.bracket === 0 &&
448 depth.paren === 0
449 ) {
450 parts.push(input.slice(start, i).trim());
451 start = i + 1;
452 }
453 }
454
455 const finalPart = input.slice(start).trim();
456 if (finalPart) {
457 parts.push(finalPart);
458 }
459 return parts;
460 }
461
462 function findMatchingParen(text: string, openIndex: number): number {
463 const depth = { angle: 0, brace: 0, bracket: 0, paren: 0 };
464 let quote: string | null = null;
465
466 for (let i = openIndex; i < text.length; i++) {
467 const char = text[i];
468 const prev = text[i - 1];
469
470 if (quote) {
471 if (char === quote && prev !== '\\') {
472 quote = null;
473 }
474 continue;
475 }
476
477 if (char === "'" || char === '"' || char === '`') {
478 quote = char;
479 continue;
480 }
481
482 if (char === '(') {
483 depth.paren++;
484 } else if (char === ')') {
485 depth.paren--;
486 if (depth.paren === 0) return i;
487 } else {
488 updateTypeDepth(char, depth);
489 }
490 }
491
492 return -1;
493 }
494
495 function findTopLevelChar(input: string, target: string): number {
496 const depth = { angle: 0, brace: 0, bracket: 0, paren: 0 };
497 let quote: string | null = null;
498
499 for (let i = 0; i < input.length; i++) {
500 const char = input[i];
501 const prev = input[i - 1];
502
503 if (quote) {
504 if (char === quote && prev !== '\\') {
505 quote = null;
506 }
507 continue;
508 }
509
510 if (char === "'" || char === '"' || char === '`') {
511 quote = char;
512 continue;
513 }
514
515 if (
516 char === target &&
517 !(target === '=' && input[i + 1] === '>') &&
518 depth.angle === 0 &&
519 depth.brace === 0 &&
520 depth.bracket === 0 &&
521 depth.paren === 0
522 ) {
523 return i;
524 }
525
526 updateTypeDepth(char, depth);
527 }
528
529 return -1;
530 }
531
532 function findReturnTypeColon(text: string, start: number): number {
533 const depth = { angle: 0, brace: 0, bracket: 0, paren: 0 };
534 let quote: string | null = null;
535
536 for (let i = start; i < text.length; i++) {
537 const char = text[i];
538 const prev = text[i - 1];
539
540 if (quote) {
541 if (char === quote && prev !== '\\') {
542 quote = null;
543 }
544 continue;
545 }
546
547 if (char === "'" || char === '"' || char === '`') {
548 quote = char;
549 continue;
550 }
551
552 const isTopLevel =
553 depth.angle === 0 && depth.brace === 0 && depth.bracket === 0 && depth.paren === 0;
554 if (isTopLevel) {
555 if (char === ':') return i;
556 if (char === '{' || char === ';') return -1;
557 }
558
559 updateTypeDepth(char, depth);
560 }
561
562 return -1;
563 }
564
565 function findSignatureEnd(text: string, start: number): number {
566 const depth = { angle: 0, brace: 0, bracket: 0, paren: 0 };
567 let quote: string | null = null;
568
569 for (let i = start; i < text.length; i++) {
570 const char = text[i];
571 const prev = text[i - 1];
572
573 if (quote) {
574 if (char === quote && prev !== '\\') {
575 quote = null;
576 }
577 continue;
578 }
579
580 if (char === "'" || char === '"' || char === '`') {
581 quote = char;
582 continue;
583 }
584
585 const isTopLevel =
586 depth.angle === 0 && depth.brace === 0 && depth.bracket === 0 && depth.paren === 0;
587 const startsInlineObjectType =
588 char === '{' &&
589 [':', '|', '&', '(', ',', '='].includes(previousNonWhitespace(text, i - 1) ?? '');
590
591 if ((char === ';' || (char === '{' && !startsInlineObjectType)) && isTopLevel) {
592 return i;
593 }
594
595 updateTypeDepth(char, depth);
596 }
597
598 return -1;
599 }
600
601 function previousNonWhitespace(text: string, index: number): string | undefined {
602 for (let i = index; i >= 0; i--) {
603 const char = text[i];
604 if (!/\s/.test(char)) {
605 return char;
606 }
607 }
608 return undefined;
609 }
610
611 function normalizeSourceParamName(name: string): string | undefined {
612 const normalized = name
613 .trim()
614 .replace(/^\.\.\./, '')
615 .split(/\s+/)
616 .pop()
617 ?.replace(/\?$/, '');
618
619 if (!normalized || normalized.startsWith('{') || normalized.startsWith('[')) {
620 return undefined;
621 }
622 return normalized;
623 }
624
625 function parseSourceParameter(param: string): [string, string] | undefined {
626 const colonIndex = findTopLevelChar(param, ':');
627 if (colonIndex === -1) return undefined;
628
629 const name = normalizeSourceParamName(param.slice(0, colonIndex));
630 if (!name) return undefined;
631
632 let type = param.slice(colonIndex + 1).trim();
633 const defaultIndex = findTopLevelChar(type, '=');
634 if (defaultIndex !== -1) {
635 type = type.slice(0, defaultIndex).trim();
636 }
637 return [name, type];
638 }
639
640 export function parseSourceSignatureTypesAtLine(
641 text: string,
642 line: number
643 ): SourceSignatureTypes | undefined {
644 const lineOffset = getLineOffset(text, line);
645 const openParen = text.indexOf('(', lineOffset);
646 if (openParen === -1) return undefined;
647
648 const closeParen = findMatchingParen(text, openParen);
649 if (closeParen === -1) return undefined;
650
651 const parameters = new Map<string, string>();
652 const paramsText = text.slice(openParen + 1, closeParen).trim();
653 for (const param of splitTopLevel(paramsText, ',')) {
654 const parsed = parseSourceParameter(param);
655 if (parsed) {
656 parameters.set(parsed[0], parsed[1]);
657 }
658 }
659
660 const colonIndex = findReturnTypeColon(text, closeParen + 1);
661 if (colonIndex === -1) return { parameters };
662
663 const absoluteReturnStart = colonIndex + 1;
664 const returnEnd = findSignatureEnd(text, absoluteReturnStart);
665 const returnType =
666 returnEnd === -1
667 ? text.slice(absoluteReturnStart).trim()
668 : text.slice(absoluteReturnStart, returnEnd).trim();
669
670 return { parameters, returnType };
671 }
672
673 function getSourceSignatureTypes(signature: TypeDocSignature): SourceSignatureTypes | undefined {
674 const source = signature.sources?.[0];
675 if (!source) return undefined;
676
677 const text = getSourceFileText(source.fileName);
678 return parseSourceSignatureTypesAtLine(text, source.line);
679 }
680
681 function formatYamlFrontmatterString(value: string): string {
682 return JSON.stringify(value);
683 }
684
685 function formatType(type?: TypeDocType, depth = 0): string {
686 if (!type) return 'unknown';
687 if (depth > 5) return '...'; // Prevent infinite recursion
688
689 switch (type.type) {
690 case 'intrinsic':
691 return type.name || 'unknown';
692
693 case 'literal':
694 if (typeof type.value === 'string') return `'${type.value}'`;
695 return String(type.value);
696
697 case 'reference':
698 if (type.typeArguments && type.typeArguments.length > 0) {
699 const args = type.typeArguments.map(t => formatType(t, depth + 1)).join(', ');
700 return `${type.name}<${args}>`;
701 }
702 return type.name || 'unknown';
703
704 case 'array':
705 return `${formatType(type.elementType, depth + 1)}[]`;
706
707 case 'union':
708 if (type.types) {
709 return type.types.map(t => formatType(t, depth + 1)).join(' | ');
710 }
711 return 'unknown';
712
713 case 'intersection':
714 if (type.types) {
715 return type.types.map(t => formatType(t, depth + 1)).join(' & ');
716 }
717 return 'unknown';
718
719 case 'reflection':
720 if (type.declaration?.signatures) {
721 // Function type
722 const sig = type.declaration.signatures[0];
723 const params =
724 sig.parameters?.map(p => `${p.name}: ${formatType(p.type, depth + 1)}`).join(', ') || '';
725 return `(${params}) => ${formatType(sig.type, depth + 1)}`;
726 }
727 if (type.declaration?.children) {
728 // Object type
729 const props = type.declaration.children
730 .map(c => {
731 const opt = c.flags?.isOptional ? '?' : '';
732 return `${c.name}${opt}: ${formatType(c.type, depth + 1)}`;
733 })
734 .join('; ');
735 return `{ ${props} }`;
736 }
737 return 'object';
738
739 case 'tuple':
740 if (type.types) {
741 return `[${type.types.map(t => formatType(t, depth + 1)).join(', ')}]`;
742 }
743 return '[]';
744
745 case 'query':
746 return `typeof ${formatType(type.target as TypeDocType, depth + 1)}`;
747
748 case 'typeOperator':
749 return type.name || 'unknown';
750
751 default:
752 return type.name || 'unknown';
753 }
754 }
755
756 function extractMethod(reflection: TypeDocReflection): MethodDoc | null {
757 if (!reflection.signatures || reflection.signatures.length === 0) {
758 return null;
759 }
760
761 const signatures = reflection.signatures.map(sig => {
762 const sourceTypes = getSourceSignatureTypes(sig);
763 const parameters = (sig.parameters || []).map(param => ({
764 // Clean up ugly TypeScript internal names
765 name: param.name.startsWith('__') ? 'options' : param.name,
766 type: sourceTypes?.parameters.get(param.name) ?? formatType(param.type),
767 required: isParameterRequired(param),
768 description: extractDescription(param.comment),
769 default: param.defaultValue,
770 }));
771
772 return {
773 parameters,
774 returnType: sourceTypes?.returnType ?? formatType(sig.type),
775 returnDescription: extractTag(sig.comment, '@returns')[0],
776 };
777 });
778
779 // Use the first signature's comment for the method description
780 const primarySig = reflection.signatures[0];
781 const description = extractDescription(primarySig.comment);
782 const examples = extractTag(primarySig.comment, '@example');
783 // `@deprecated` may live on the signature comment or the reflection comment.
784 const deprecated =
785 extractTag(primarySig.comment, '@deprecated')[0] ??
786 extractTag(reflection.comment, '@deprecated')[0];
787
788 return {
789 name: reflection.name,
790 description,
791 signatures,
792 examples,
793 isAsync:
794 signatures[0]?.returnType.startsWith('Promise') ??
795 formatType(primarySig.type).startsWith('Promise'),
796 deprecated,
797 source: reflection.sources?.[0]
798 ? { file: reflection.sources[0].fileName, line: reflection.sources[0].line }
799 : undefined,
800 };
801 }
802
803 function extractClass(reflection: TypeDocReflection): ClassDoc {
804 const classDoc: ClassDoc = {
805 name: reflection.name,
806 description: extractDescription(reflection.comment),
807 methods: [],
808 properties: [],
809 source: reflection.sources?.[0]
810 ? { file: reflection.sources[0].fileName, line: reflection.sources[0].line }
811 : undefined,
812 deprecated: extractTag(reflection.comment, '@deprecated')[0],
813 };
814
815 if (!reflection.children) return classDoc;
816
817 for (const child of reflection.children) {
818 // Skip private/protected members
819 if (child.flags?.isPrivate || child.flags?.isProtected) continue;
820
821 // Constructor (kind 512)
822 if (child.kind === TYPEDOC_KIND.Constructor) {
823 const method = extractMethod(child);
824 if (method) {
825 classDoc.constructor = method;
826 }
827 continue;
828 }
829
830 // Methods (kind 2048)
831 if (child.kind === TYPEDOC_KIND.Method) {
832 const method = extractMethod(child);
833 if (method) {
834 classDoc.methods.push(method);
835 }
836 continue;
837 }
838
839 // Properties (kind 1024, public only)
840 if (child.kind === TYPEDOC_KIND.Property && !child.flags?.isPrivate) {
841 classDoc.properties.push({
842 name: child.name,
843 type: formatType(child.type),
844 description: extractDescription(child.comment),
845 default: child.defaultValue,
846 });
847 }
848 }
849
850 return classDoc;
851 }
852
853 function generateMethodMdx(method: MethodDoc): string {
854 const lines: string[] = [];
855
856 // Method header. Flag deprecated methods in the heading so they read clearly
857 // in the sidebar/anchor and at a glance.
858 const deprecatedSuffix = method.deprecated !== undefined ? ' (deprecated)' : '';
859 lines.push(`### ${method.name}()${deprecatedSuffix}`);
860 lines.push('');
861
862 // Deprecation callout (rendered as a fumadocs warning callout).
863 if (method.deprecated !== undefined) {
864 const note = method.deprecated.trim();
865 lines.push('<Callout type="warn" title="Deprecated">');
866 lines.push(note.length > 0 ? escapeTextForMdx(note) : 'This method is deprecated.');
867 lines.push('</Callout>');
868 lines.push('');
869 }
870
871 // Description
872 if (method.description) {
873 lines.push(method.description);
874 lines.push('');
875 }
876
877 // Handle multiple overloads
878 for (let i = 0; i < method.signatures.length; i++) {
879 const sig = method.signatures[i];
880
881 if (method.signatures.length > 1) {
882 lines.push(`**Overload ${i + 1}**`);
883 lines.push('');
884 }
885
886 // Signature
887 const params = sig.parameters
888 .map(p => {
889 const opt = p.required ? '' : '?';
890 const paramType = simplifyTypeForSignature(p.type);
891 return `${p.name}${opt}: ${paramType}`;
892 })
893 .join(', ');
894 const asyncPrefix = method.isAsync ? 'async ' : '';
895 const returnType = simplifyTypeForSignature(sig.returnType);
896 lines.push('```typescript');
897 lines.push(`${asyncPrefix}${method.name}(${params}): ${returnType}`);
898 lines.push('```');
899 lines.push('');
900
901 // Parameters table
902 if (sig.parameters.length > 0) {
903 lines.push('**Parameters**');
904 lines.push('');
905
906 // Check if any parameter has a description
907 const hasDescriptions = sig.parameters.some(p => p.description);
908
909 if (hasDescriptions) {
910 lines.push('| Name | Type | Description |');
911 lines.push('|------|------|-------------|');
912 for (const param of sig.parameters) {
913 const opt = param.required ? '' : '?';
914 const desc = escapeTableTextForMdx(param.description || '');
915 const typeCell = escapeTypeForMdx(simplifyTypeForTable(param.type));
916 lines.push(`| \`${param.name}${opt}\` | \`${typeCell}\` | ${desc} |`);
917 }
918 } else {
919 // No descriptions - use simpler table
920 lines.push('| Name | Type |');
921 lines.push('|------|------|');
922 for (const param of sig.parameters) {
923 const opt = param.required ? '' : '?';
924 const typeCell = escapeTypeForMdx(simplifyTypeForTable(param.type));
925 lines.push(`| \`${param.name}${opt}\` | \`${typeCell}\` |`);
926 }
927 }
928 lines.push('');
929 }
930
931 // Return type
932 if (sig.returnType !== 'void') {
933 lines.push('**Returns**');
934 lines.push('');
935 const returnTypeDisplay = escapeTypeForMdx(simplifyTypeForTable(sig.returnType));
936 let returnLine = `\`${returnTypeDisplay}\``;
937 if (sig.returnDescription) {
938 returnLine += ` — ${escapeTextForMdx(sig.returnDescription)}`;
939 }
940 lines.push(returnLine);
941 lines.push('');
942 }
943 }
944
945 // Examples
946 if (method.examples.length > 0) {
947 lines.push('**Example**');
948 lines.push('');
949 for (const example of method.examples) {
950 // Clean up the example - remove surrounding ```typescript blocks if present
951 let cleanExample = example.trim();
952 if (cleanExample.startsWith('```typescript')) {
953 cleanExample = cleanExample.slice('```typescript'.length);
954 }
955 if (cleanExample.startsWith('```ts')) {
956 cleanExample = cleanExample.slice('```ts'.length);
957 }
958 if (cleanExample.endsWith('```')) {
959 cleanExample = cleanExample.slice(0, -3);
960 }
961 cleanExample = cleanExample.trim();
962
963 lines.push('```typescript');
964 lines.push(cleanExample);
965 lines.push('```');
966 lines.push('');
967 }
968 }
969
970 lines.push('---');
971 lines.push('');
972
973 return lines.join('\n');
974 }
975
976 export function generateClassMdx(classDoc: ClassDoc): string {
977 const lines: string[] = [];
978
979 // Build full description for frontmatter (first sentence + additional context)
980 const fullDescription = classDoc.description
981 ? classDoc.description.replace(/\n/g, ' ').trim()
982 : `${classDoc.name} class reference`;
983
984 // Frontmatter - fumadocs renders title and description automatically
985 lines.push('---');
986 lines.push(`title: ${formatYamlFrontmatterString(displayNameFor(classDoc.name))}`);
987 lines.push(`description: ${formatYamlFrontmatterString(fullDescription)}`);
988 lines.push('---');
989 lines.push('');
990
991 // Class-level deprecation callout (rendered as a fumadocs warning callout).
992 if (classDoc.deprecated !== undefined) {
993 const note = classDoc.deprecated.trim();
994 lines.push('<Callout type="warn" title="Deprecated">');
995 lines.push(note.length > 0 ? escapeTextForMdx(note) : 'This class is deprecated.');
996 lines.push('</Callout>');
997 lines.push('');
998 }
999
1000 // Content starts directly with Constructor or Usage (no duplicate title/description)
1001
1002 // Constructor - only show for user-instantiated classes
1003 if (classDoc.constructor && USER_INSTANTIATED_CLASSES.has(classDoc.name)) {
1004 lines.push('## Constructor');
1005 lines.push('');
1006 lines.push(generateMethodMdx(classDoc.constructor));
1007 } else if (!USER_INSTANTIATED_CLASSES.has(classDoc.name) && !(classDoc.name in SLUG_OVERRIDES)) {
1008 // Skip the `composio.<accessor>` Usage block for session-object classes —
1009 // they are not accessed as a `composio` sub-client property; the class
1010 // description explains how to obtain them (via `composio.sessions`).
1011 lines.push('## Usage');
1012 lines.push('');
1013
1014 // Handle acronyms (e.g., "MCP" -> "mcp") vs PascalCase (e.g., "AuthConfigs" -> "authConfigs")
1015 const accessorName =
1016 classDoc.name === classDoc.name.toUpperCase()
1017 ? classDoc.name.toLowerCase()
1018 : classDoc.name.charAt(0).toLowerCase() + classDoc.name.slice(1);
1019 lines.push(`Access this class through the \`composio.${accessorName}\` property:`);
1020 lines.push('');
1021 lines.push('```typescript');
1022 lines.push(`const composio = new Composio({ apiKey: 'your-api-key' });`);
1023 const usageCall = classDoc.name === 'Toolkits' ? 'get({})' : 'list()';
1024 lines.push(`const result = await composio.${accessorName}.${usageCall};`);
1025 lines.push('```');
1026 lines.push('');
1027 }
1028
1029 // Properties (if any public ones exist)
1030 const publicProps = classDoc.properties.filter(p => !p.name.startsWith('_'));
1031 if (publicProps.length > 0) {
1032 lines.push('## Properties');
1033 lines.push('');
1034
1035 // Check if any property has a description
1036 const hasDescriptions = publicProps.some(p => p.description);
1037
1038 if (hasDescriptions) {
1039 lines.push('| Name | Type | Description |');
1040 lines.push('|------|------|-------------|');
1041 for (const prop of publicProps) {
1042 const typeCell = escapeTypeForMdx(simplifyTypeForTable(prop.type));
1043 const safeDesc = escapeTableTextForMdx(prop.description || '');
1044 lines.push(`| \`${prop.name}\` | \`${typeCell}\` | ${safeDesc} |`);
1045 }
1046 } else {
1047 lines.push('| Name | Type |');
1048 lines.push('|------|------|');
1049 for (const prop of publicProps) {
1050 const typeCell = escapeTypeForMdx(simplifyTypeForTable(prop.type));
1051 lines.push(`| \`${prop.name}\` | \`${typeCell}\` |`);
1052 }
1053 }
1054 lines.push('');
1055 }
1056
1057 // Methods
1058 if (classDoc.methods.length > 0) {
1059 lines.push('## Methods');
1060 lines.push('');
1061 for (const method of classDoc.methods) {
1062 lines.push(generateMethodMdx(method));
1063 }
1064 }
1065
1066 return lines.join('\n');
1067 }
1068
1069 function toKebabCase(str: string): string {
1070 return str
1071 .replace(/([a-z])([A-Z])/g, '$1-$2')
1072 .replace(/[\s_]+/g, '-')
1073 .toLowerCase();
1074 }
1075
1076 // Escape text content for MDX (descriptions, etc. that appear outside backticks)
1077 // Handles both curly braces and angle brackets (which MDX interprets as JSX tags)
1078 export function escapeTextForMdx(str: string): string {
1079 return str
1080 .replace(/\\/g, '\\\\')
1081 .replace(/\|/g, '\\|')
1082 .replace(/\{/g, '\\{')
1083 .replace(/\}/g, '\\}')
1084 .replace(/</g, '&lt;')
1085 .replace(/>/g, '&gt;');
1086 }
1087
1088 export function escapeTableTextForMdx(str: string): string {
1089 return escapeTextForMdx(str).replace(/\s*\n\s*/g, ' ');
1090 }
1091
1092 // Clean up internal generic type parameters that don't add value for users
1093 function cleanupGenericTypes(type: string): string {
1094 // Remove generic parameters that are just implementation details
1095 // e.g., "Tools<unknown, unknown, TProvider>" -> "Tools"
1096 // e.g., "Composio<TProvider>" -> "Composio"
1097 // e.g., "Uint8Array<ArrayBufferLike>" -> "Uint8Array"
1098 let cleaned = type;
1099
1100 // Remove type parameters that are just unknowns or TProvider
1101 cleaned = cleaned.replace(/<unknown(?:,\s*unknown)*(?:,\s*TProvider)?>/g, '');
1102 cleaned = cleaned.replace(/<TProvider>/g, '');
1103 cleaned = cleaned.replace(/<unknown>/g, '');
1104
1105 // Remove TypeScript internal generic parameters (e.g., <ArrayBufferLike>)
1106 // that add no value for users and break MDX parsing
1107 cleaned = cleaned.replace(/<ArrayBufferLike>/g, '');
1108
1109 // Clean up double spaces and trailing commas
1110 cleaned = cleaned.replace(/\s+/g, ' ').trim();
1111
1112 return cleaned;
1113 }
1114
1115 // Escape type strings for safe use in MDX backtick code spans.
1116 // Escapes backslashes first so later Markdown escapes cannot be neutralized.
1117 export function escapeTypeForMdx(type: string): string {
1118 return type
1119 .replace(/\\/g, '\\\\')
1120 .replace(/\{/g, '\\{')
1121 .replace(/\}/g, '\\}')
1122 .replace(/\|/g, '\\|');
1123 }
1124
1125 function isInlineObjectType(type: string): boolean {
1126 return type.startsWith('{') || type.includes(': {');
1127 }
1128
1129 // Shorten a type to at most `maxLength` characters. A union is cut between
1130 // members, or elided entirely when not even its first member fits, so it never
1131 // ends inside a string literal.
1132 function truncateType(type: string, maxLength: number): string {
1133 const members = splitTopLevel(type, '|');
1134 if (members.length > 1) {
1135 const suffix = ' | ...';
1136 let kept = members[0];
1137 for (const member of members.slice(1)) {
1138 const next = `${kept} | ${member}`;
1139 if (next.length + suffix.length > maxLength) break;
1140 kept = next;
1141 }
1142 return kept.length + suffix.length <= maxLength ? kept + suffix : '...';
1143 }
1144 return type.substring(0, maxLength - 3) + '...';
1145 }
1146
1147 // Simplify complex types for table display while preserving public object shapes.
1148 export function simplifyTypeForTable(type: string): string {
1149 // First clean up internal generics
1150 const cleaned = cleanupGenericTypes(type);
1151
1152 if (isInlineObjectType(cleaned)) {
1153 return cleaned;
1154 }
1155
1156 // If type is too long or complex, simplify it
1157 if (cleaned.length > 80) {
1158 // Extract just the outer type name if it's a generic
1159 const genericMatch = cleaned.match(/^([A-Za-z]+)<.*>$/);
1160 if (genericMatch) {
1161 return `${genericMatch[1]}<...>`;
1162 }
1163
1164 // For function types, simplify
1165 if (cleaned.includes('=>')) {
1166 const returnMatch = cleaned.match(/=>\s*(.+)$/);
1167 const returnType = returnMatch ? returnMatch[1] : 'unknown';
1168 return `(...) => ${simplifyTypeForTable(returnType)}`;
1169 }
1170
1171 // Truncate very long types
1172 if (cleaned.length > 80) {
1173 return truncateType(cleaned, 80);
1174 }
1175 }
1176 return cleaned;
1177 }
1178
1179 // Simplify types for code block display (less aggressive, preserves structure)
1180 export function simplifyTypeForSignature(type: string): string {
1181 // First clean up internal generics
1182 const cleaned = cleanupGenericTypes(type);
1183
1184 if (isInlineObjectType(cleaned)) {
1185 return cleaned;
1186 }
1187
1188 // Keep types under 100 chars as-is
1189 if (cleaned.length <= 100) {
1190 return cleaned;
1191 }
1192
1193 // For Promise<...> with complex inner type, simplify inner
1194 const promiseMatch = cleaned.match(/^Promise<(.+)>$/);
1195 if (promiseMatch) {
1196 const inner = promiseMatch[1];
1197 if (inner.length > 60 || inner.includes(': {')) {
1198 return 'Promise<...>';
1199 }
1200 }
1201
1202 // For generics with complex type arguments
1203 const genericMatch = cleaned.match(/^([A-Za-z]+)<(.+)>$/);
1204 if (genericMatch) {
1205 const [, name, args] = genericMatch;
1206 if (args.length > 60 || args.includes(': {')) {
1207 return `${name}<...>`;
1208 }
1209 }
1210
1211 // Truncate very long types
1212 if (cleaned.length > 100) {
1213 return truncateType(cleaned, 100);
1214 }
1215
1216 return cleaned;
1217 }
1218
1219 async function runTypeDoc(): Promise<TypeDocProject> {
1220 console.log('Running TypeDoc...');
1221
1222 // Auto-discover entry points from models directory
1223 const modelFiles = await discoverModelFiles();
1224 const entryPoints = ['src/composio.ts', ...modelFiles];
1225
1226 console.log(` Found ${entryPoints.length} entry points`);
1227
1228 try {
1229 runTypeDocCommand(entryPoints);
1230 } catch (error) {
1231 console.error('TypeDoc failed:', error);
1232 throw error;
1233 }
1234
1235 const jsonContent = await readFile(TEMP_JSON, 'utf-8');
1236 return JSON.parse(jsonContent) as TypeDocProject;
1237 }
1238
1239 async function main() {
1240 console.log('Starting TypeScript SDK documentation generation...\n');
1241 console.log(`Package dir: ${PACKAGE_DIR}`);
1242 console.log(`Output dir: ${OUTPUT_DIR}\n`);
1243
1244 // Clean output directory
1245 try {
1246 await rm(OUTPUT_DIR, { recursive: true, force: true });
1247 } catch {
1248 // Directory doesn't exist, that's fine
1249 }
1250 await mkdir(OUTPUT_DIR, { recursive: true });
1251
1252 // Run TypeDoc
1253 const project = await runTypeDoc();
1254
1255 if (!project.children) {
1256 throw new Error('No classes found in TypeDoc output');
1257 }
1258
1259 // Auto-discover classes to document (excludes internal classes)
1260 const classesToDocument = discoverClassesToDocument(project);
1261 console.log(
1262 ` Found ${classesToDocument.length} classes to document: ${classesToDocument.join(', ')}`
1263 );
1264
1265 // Find and document each class
1266 const documented: { name: string; description: string }[] = [];
1267
1268 for (const className of classesToDocument) {
1269 const reflection = findClass(project, className);
1270
1271 if (!reflection) {
1272 console.warn(` Warning: ${className} not found in TypeDoc output`);
1273 continue;
1274 }
1275
1276 console.log(` Processing ${className}...`);
1277
1278 const classDoc = extractClass(reflection);
1279 const mdx = generateClassMdx(classDoc);
1280 const fileName = slugFor(className) + '.mdx';
1281 const filePath = join(OUTPUT_DIR, fileName);
1282
1283 await writeFile(filePath, mdx);
1284 documented.push({
1285 name: className,
1286 description: classDoc.description.split('\n')[0] || `${className} API`,
1287 });
1288 }
1289
1290 // Generate index page
1291 const classesTable = documented
1292 .map(
1293 ({ name, description }) =>
1294 `| [\`${displayNameFor(name)}\`](/reference/sdk-reference/typescript/${slugFor(name)}) | ${escapeTableTextForMdx(description)} |`
1295 )
1296 .join('\n');
1297
1298 const indexContent = `---
1299 title: ${formatYamlFrontmatterString('TypeScript SDK Reference')}
1300 description: ${formatYamlFrontmatterString('Complete API reference for the Composio TypeScript SDK (@composio/core).')}
1301 ---
1302
1303 ## Installation
1304
1305 <PackageInstall packages="@composio/core" />
1306
1307 ## Classes
1308
1309 | Class | Description |
1310 |-------|-------------|
1311 ${classesTable}
1312
1313 ## Quick Start
1314
1315 \`\`\`typescript
1316 import { Composio } from '@composio/core';
1317
1318 const composio = new Composio({
1319 apiKey: process.env.COMPOSIO_API_KEY
1320 });
1321
1322 // Get tools for a user
1323 const tools = await composio.tools.get('user-123', {
1324 toolkits: ['github']
1325 });
1326
1327 // Execute a tool
1328 const result = await composio.tools.execute('GITHUB_GET_REPOS', {
1329 userId: 'user-123',
1330 arguments: { owner: 'composio' }
1331 });
1332 \`\`\`
1333 `;
1334
1335 await writeFile(join(OUTPUT_DIR, 'index.mdx'), indexContent);
1336
1337 // Generate meta.json for sidebar
1338 const meta = {
1339 title: 'TypeScript SDK',
1340 pages: documented.map(({ name }) => slugFor(name)),
1341 };
1342 await writeFile(join(OUTPUT_DIR, 'meta.json'), JSON.stringify(meta, null, 2));
1343
1344 // Clean up temp file
1345 try {
1346 await rm(TEMP_JSON);
1347 } catch {
1348 // Ignore cleanup errors
1349 }
1350
1351 console.log('\nGeneration complete!');
1352 console.log(` Output: ${OUTPUT_DIR}`);
1353 console.log(` Classes: ${documented.map(d => d.name).join(', ')}`);
1354 console.log(` Files generated: ${documented.length + 2}`); // +2 for index.mdx and meta.json
1355 }
1356
1357 function isDirectRun(): boolean {
1358 const entrypoint = process.argv[1];
1359 return Boolean(entrypoint && import.meta.url === pathToFileURL(resolve(entrypoint)).href);
1360 }
1361
1362 if (isDirectRun()) {
1363 main().catch(error => {
1364 console.error('Fatal error:', error);
1365 process.exit(1);
1366 });
1367 }