@devries-cameron20 / composio Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 284 lines 9.3 KB
Raw
1 import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
2 import { tmpdir } from 'node:os';
3 import { join } from 'node:path';
4 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5 import {
6 discoverModelFiles,
7 escapeTableTextForMdx,
8 escapeTextForMdx,
9 escapeTypeForMdx,
10 generateClassMdx,
11 getSourceFileText,
12 isParameterRequired,
13 parseSourceSignatureTypesAtLine,
14 runTypeDocCommand,
15 simplifyTypeForSignature,
16 simplifyTypeForTable,
17 } from '../../scripts/generate-docs';
18
19 describe('generate-docs usage examples', () => {
20 it('uses the public get method in the Toolkits usage block', () => {
21 const mdx = generateClassMdx({
22 name: 'Toolkits',
23 description: 'Toolkits API',
24 constructor: undefined,
25 methods: [],
26 properties: [],
27 });
28
29 expect(mdx).toContain(
30 '```typescript\n' +
31 "const composio = new Composio({ apiKey: 'your-api-key' });\n" +
32 'const result = await composio.toolkits.get({});\n' +
33 '```'
34 );
35 expect(mdx).not.toContain('composio.toolkits.list()');
36 });
37 });
38
39 describe('generate-docs type rendering', () => {
40 it('preserves inline object shapes in signatures', () => {
41 const type =
42 '{ cursor?: string; isComposioManaged?: boolean; limit?: number; toolkit?: string }';
43
44 expect(simplifyTypeForSignature(type)).toBe(type);
45 });
46
47 it('preserves inline object shapes in parameter tables', () => {
48 const type = '{ arguments?: Record<string, unknown>; sessionId: string }';
49
50 expect(simplifyTypeForTable(type)).toBe(type);
51 });
52
53 it('preserves nested object shapes instead of collapsing them to object', () => {
54 const type = '{ account?: { id?: string; label?: string }; timeout?: number }';
55
56 expect(simplifyTypeForSignature(type)).toBe(type);
57 expect(simplifyTypeForTable(type)).toBe(type);
58 });
59
60 it('escapes pipes and braces for MDX tables', () => {
61 expect(escapeTypeForMdx("{ status: 'enable' | 'disable' }")).toBe(
62 "\\{ status: 'enable' \\| 'disable' \\}"
63 );
64 });
65
66 it('escapes existing backslashes before adding MDX table escapes', () => {
67 expect(escapeTypeForMdx(String.raw`{ pattern: '\|' }`)).toBe(String.raw`\{ pattern: '\\\|' \}`);
68 });
69
70 it('escapes existing backslashes before MDX text and table metacharacters', () => {
71 expect(escapeTextForMdx(String.raw`Use \{value\}, \|, or <literal>`)).toBe(
72 String.raw`Use \\\{value\\\}, \\\|, or &lt;literal&gt;`
73 );
74 });
75
76 it('keeps multiline descriptions in one table cell', () => {
77 expect(escapeTableTextForMdx('First line\n second line')).toBe('First line second line');
78 });
79
80 it('treats optional and default-valued parameters as optional', () => {
81 expect(isParameterRequired({ flags: { isOptional: true } })).toBe(false);
82 expect(isParameterRequired({ defaultValue: '{}' })).toBe(false);
83 expect(isParameterRequired({})).toBe(true);
84 });
85
86 it('reads named parameter and return types from source signatures', () => {
87 const source = `
88 class Example {
89 async list(
90 query?: AuthConfigListParams,
91 requestOptions?: ComposioRequestOptions
92 ): Promise<AuthConfigListResponse> {
93 return undefined as never;
94 }
95 }
96 `;
97 const line = source.split('\n').findIndex(line => line.includes('async list(')) + 1;
98
99 const signature = parseSourceSignatureTypesAtLine(source, line);
100
101 expect(signature?.parameters.get('query')).toBe('AuthConfigListParams');
102 expect(signature?.parameters.get('requestOptions')).toBe('ComposioRequestOptions');
103 expect(signature?.returnType).toBe('Promise<AuthConfigListResponse>');
104 });
105
106 it('reads authored inline object types from source signatures', () => {
107 const source = `
108 class Example {
109 getResult(input: { id: string; mode?: 'fast' | 'safe' }): { ok: boolean; value?: string } {
110 return { ok: true };
111 }
112 }
113 `;
114 const line = source.split('\n').findIndex(line => line.includes('getResult(')) + 1;
115
116 const signature = parseSourceSignatureTypesAtLine(source, line);
117
118 expect(signature?.parameters.get('input')).toBe("{ id: string; mode?: 'fast' | 'safe' }");
119 expect(signature?.returnType).toBe('{ ok: boolean; value?: string }');
120 });
121
122 it('does not infer a return type when the source signature omits one', () => {
123 const source = `
124 class Example {
125 async toolkits(options?: ToolRouterToolkitsOptions, requestOptions?: ComposioRequestOptions) {
126 const params = { search: options?.search };
127 return params;
128 }
129
130 async search(params: { query: string }): Promise<ToolRouterSessionSearchResponse> {
131 return undefined as never;
132 }
133 }
134 `;
135 const line = source.split('\n').findIndex(line => line.includes('async toolkits(')) + 1;
136
137 const signature = parseSourceSignatureTypesAtLine(source, line);
138
139 expect(signature?.parameters.get('options')).toBe('ToolRouterToolkitsOptions');
140 expect(signature?.parameters.get('requestOptions')).toBe('ComposioRequestOptions');
141 expect(signature?.returnType).toBeUndefined();
142 });
143
144 it('keeps arrow function parameter types intact', () => {
145 const source = `
146 class Example {
147 subscribe(fn: (event: TriggerEvent) => void, filters?: TriggerSubscribeParams): void {
148 fn(undefined as never);
149 }
150 }
151 `;
152 const line = source.split('\n').findIndex(line => line.includes('subscribe(')) + 1;
153
154 const signature = parseSourceSignatureTypesAtLine(source, line);
155
156 expect(signature?.parameters.get('fn')).toBe('(event: TriggerEvent) => void');
157 expect(signature?.parameters.get('filters')).toBe('TriggerSubscribeParams');
158 expect(signature?.returnType).toBe('void');
159 });
160 });
161
162 describe('generate-docs type truncation', () => {
163 const slugUnion = [
164 'COMPOSIO_GET_TOOL_SCHEMAS',
165 'COMPOSIO_SEARCH_TOOLS',
166 'COMPOSIO_MULTI_EXECUTE_TOOL',
167 'COMPOSIO_MANAGE_CONNECTIONS',
168 'COMPOSIO_WAIT_FOR_CONNECTIONS',
169 ]
170 .map(slug => `'${slug}'`)
171 .join(' | ');
172
173 it('cuts a long union between members in signatures', () => {
174 expect(simplifyTypeForSignature(slugUnion)).toBe(
175 "'COMPOSIO_GET_TOOL_SCHEMAS' | 'COMPOSIO_SEARCH_TOOLS' | 'COMPOSIO_MULTI_EXECUTE_TOOL' | ..."
176 );
177 });
178
179 it('cuts a long union between members in parameter tables', () => {
180 expect(simplifyTypeForTable(slugUnion)).toBe(
181 "'COMPOSIO_GET_TOOL_SCHEMAS' | 'COMPOSIO_SEARCH_TOOLS' | ..."
182 );
183 });
184
185 it('does not split a union member that contains a pipe', () => {
186 const type = `'${'a|'.repeat(30)}' | 'COMPOSIO_SEARCH_TOOLS' | ${slugUnion}`;
187
188 expect(simplifyTypeForSignature(type)).toBe(
189 `'${'a|'.repeat(30)}' | 'COMPOSIO_SEARCH_TOOLS' | ...`
190 );
191 });
192
193 it('elides a union whose first member does not fit', () => {
194 const type = `'${'a'.repeat(110)}' | 'COMPOSIO_SEARCH_TOOLS'`;
195
196 expect(simplifyTypeForSignature(type)).toBe('...');
197 expect(simplifyTypeForTable(type)).toBe('...');
198 });
199 });
200
201 describe('generate-docs source lookup', () => {
202 let packageDir: string;
203
204 beforeEach(async () => {
205 packageDir = await mkdtemp(join(tmpdir(), 'composio-generate-docs-'));
206 });
207
208 afterEach(async () => {
209 await rm(packageDir, { recursive: true, force: true });
210 });
211
212 it('resolves TypeDoc source paths against the package directory', async () => {
213 await mkdir(join(packageDir, 'src/models'), { recursive: true });
214 await writeFile(join(packageDir, 'src/models/Example.ts'), 'export class Example {}\n');
215
216 expect(getSourceFileText('src/models/Example.ts', packageDir)).toBe(
217 'export class Example {}\n'
218 );
219 });
220
221 it('throws when a TypeDoc source path does not resolve', () => {
222 expect(() => getSourceFileText('ts/packages/core/src/models/Example.ts', packageDir)).toThrow(
223 /ENOENT/
224 );
225 });
226 });
227
228 describe('generate-docs command construction', () => {
229 let modelsDir: string;
230
231 beforeEach(async () => {
232 modelsDir = await mkdtemp(join(tmpdir(), 'composio-generate-docs-'));
233 });
234
235 afterEach(async () => {
236 await rm(modelsDir, { recursive: true, force: true });
237 vi.restoreAllMocks();
238 });
239
240 it('keeps only plainly named model files and drops shell metacharacter names', async () => {
241 vi.spyOn(console, 'warn').mockImplementation(() => undefined);
242 for (const name of [
243 'Files.ts',
244 'tool_router.ts',
245 'x;touch pwned.ts',
246 '$(id).ts',
247 'a b.ts',
248 'Files.test.ts',
249 'notes.md',
250 ]) {
251 await writeFile(join(modelsDir, name), '');
252 }
253
254 const discovered = await discoverModelFiles(modelsDir);
255
256 expect(discovered.sort()).toEqual(['src/models/Files.ts', 'src/models/tool_router.ts']);
257 });
258
259 it('runs TypeDoc with Node and passes every entry point as its own argument', async () => {
260 const typedocBin = join(modelsDir, 'typedoc');
261 const outputJson = join(modelsDir, 'typedoc-args.txt');
262 await writeFile(
263 typedocBin,
264 `const { writeFileSync } = require('node:fs');
265 const args = process.argv.slice(2);
266 const outputJson = args[args.indexOf('--json') + 1];
267 writeFileSync(outputJson, args.join('\\n'));
268 `
269 );
270
271 runTypeDocCommand(['src/composio.ts', 'src/models/a b.ts'], {
272 outputJson,
273 packageDir: modelsDir,
274 typedocBin,
275 });
276
277 const args = (await readFile(outputJson, 'utf8')).split('\n');
278 expect(args[0]).toBe('--json');
279 expect(args).toContain('src/models/a b.ts');
280 expect(args[args.indexOf('--displayBasePath') + 1]).toBe(modelsDir);
281 expect(args.some(arg => arg.includes('npx'))).toBe(false);
282 expect(args.slice(-2)).toEqual(['src/composio.ts', 'src/models/a b.ts']);
283 });
284 });