@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 273 lines 8.85 KB
Raw
1 import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
2 import type { LinkCreateResponse } from '@composio/client/resources/link';
3 import { Array as Arr, Effect, Layer, Stream } from 'effect';
4 import type { AuthConfigCreateResponse, AuthConfigItem } from 'src/models/auth-configs';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
6 import {
7 ComposioToolkitsRepository,
8 type ComposioToolkitsRepositoryShape,
9 } from 'src/services/composio-clients';
10 import { makeToolkitsRepositoryStub } from '../services/toolkits-repository-stub';
11 import { notFoundError } from './not-found';
12 import { DEFAULT_PAGE_LIMIT } from './page';
13
14 /**
15 * The decoded auth config responses a test repository returns.
16 */
17 export interface AuthConfigsTestData {
18 items?: AuthConfigItem[];
19 createResponse?: AuthConfigCreateResponse;
20 onCreate?: (params: AuthConfigCreateParams) => void;
21 }
22
23 /**
24 * The connected accounts a test serves, and what linking a new one answers.
25 */
26 export interface ConnectedAccountsTestData {
27 items?: ConnectedAccountItem[];
28 linkResponse?: LinkCreateResponse;
29 onDelete?: (nanoid: string) => void;
30 }
31
32 /**
33 * `AuthConfigsTestData` with no auth configs and the default create response
34 * when the test left them out.
35 */
36 export const resolveAuthConfigsTestData = (data?: AuthConfigsTestData) => {
37 const defaults = {
38 items: [] as AuthConfigItem[],
39 createResponse: undefined as AuthConfigCreateResponse | undefined,
40 } satisfies AuthConfigsTestData;
41 return {
42 ...defaults,
43 ...(data ?? {}),
44 };
45 };
46
47 /**
48 * `ConnectedAccountsTestData` with no connected accounts and the default link
49 * response when the test left them out.
50 */
51 export const resolveConnectedAccountsTestData = (data?: ConnectedAccountsTestData) => {
52 const defaults = {
53 items: [] as ConnectedAccountItem[],
54 linkResponse: undefined as LinkCreateResponse | undefined,
55 } satisfies ConnectedAccountsTestData;
56 return {
57 ...defaults,
58 ...(data ?? {}),
59 };
60 };
61
62 export type ResolvedAuthConfigsTestData = ReturnType<typeof resolveAuthConfigsTestData>;
63 export type ResolvedConnectedAccountsTestData = ReturnType<typeof resolveConnectedAccountsTestData>;
64
65 /**
66 * The item with `id`, or the 404 `notFound` describes.
67 */
68 const findById = <A extends { readonly id: string }>(
69 items: ReadonlyArray<A>,
70 id: string,
71 notFound: () => ReturnType<typeof notFoundError>
72 ) =>
73 Effect.fromOption(
74 Arr.findFirst(items, item => item.id === id),
75 notFound
76 );
77
78 /**
79 * The repository's auth-config methods.
80 */
81 export type AuthConfigRepositoryMethod = 'listAuthConfigs' | 'getAuthConfig' | 'createAuthConfig';
82
83 export type AuthConfigRepositoryMethods = Pick<
84 ComposioToolkitsRepositoryShape,
85 AuthConfigRepositoryMethod
86 >;
87
88 /**
89 * The repository methods this family serves.
90 */
91 export type ConnectedAccountRepositoryMethod =
92 'listAuthConfigs' | 'getAuthConfig' | 'createAuthConfig' | 'getConnectedAccount';
93
94 export type ConnectedAccountRepositoryMethods = Pick<
95 ComposioToolkitsRepositoryShape,
96 ConnectedAccountRepositoryMethod
97 >;
98
99 /**
100 * The repository's auth-config methods, answering from the test data the way
101 * the API would.
102 */
103 export const authConfigRepositoryMethods = (
104 authConfigsData: ResolvedAuthConfigsTestData
105 ): AuthConfigRepositoryMethods => ({
106 listAuthConfigs: (
107 _scope,
108 params: {
109 search?: string;
110 toolkit_slug?: string;
111 limit?: number;
112 show_disabled?: boolean;
113 }
114 ) => {
115 let results = [...authConfigsData.items];
116
117 if (params.toolkit_slug) {
118 const slugs = params.toolkit_slug.split(',').map(s => s.trim().toLowerCase());
119 results = results.filter(item => slugs.includes(item.toolkit.slug.toLowerCase()));
120 }
121
122 if (params.search) {
123 const q = params.search.toLowerCase();
124 results = results.filter(
125 item => item.name.toLowerCase().includes(q) || item.id.toLowerCase().includes(q)
126 );
127 }
128
129 const limit = params.limit ?? DEFAULT_PAGE_LIMIT;
130 const items = results.slice(0, limit);
131 return Effect.succeed({
132 items,
133 total_items: results.length,
134 total_pages: Math.ceil(results.length / limit),
135 current_page: 1,
136 next_cursor: null,
137 });
138 },
139 getAuthConfig: (_scope, nanoid: string) =>
140 findById(authConfigsData.items, nanoid, () =>
141 notFoundError(`Auth config "${nanoid}" not found`, {
142 message: `Auth config "${nanoid}" not found.`,
143 suggested_fix: 'Check the auth config ID and try again.',
144 })
145 ),
146 createAuthConfig: (_scope, params: AuthConfigCreateParams) => {
147 authConfigsData.onCreate?.(params);
148 return Effect.succeed(
149 authConfigsData.createResponse ?? {
150 auth_config: { id: 'ac_test', auth_scheme: 'OAUTH2', is_composio_managed: true },
151 toolkit: { slug: 'test' },
152 }
153 );
154 },
155 });
156
157 /**
158 * The repository's auth-config and connected-account methods, answering from
159 * the test data the way the API would.
160 */
161 export const connectedAccountRepositoryMethods = (
162 authConfigsData: ResolvedAuthConfigsTestData,
163 connectedAccountsData: ResolvedConnectedAccountsTestData
164 ): ConnectedAccountRepositoryMethods => ({
165 ...authConfigRepositoryMethods(authConfigsData),
166 getConnectedAccount: (_scope, nanoid: string) =>
167 findById(connectedAccountsData.items, nanoid, () =>
168 notFoundError(`Connected account "${nanoid}" not found`, {
169 message: `Connected account "${nanoid}" not found.`,
170 suggested_fix: 'Check the connected account ID and try again.',
171 })
172 ),
173 });
174
175 /**
176 * The mock client's `link` and `connectedAccounts` resources, answering from
177 * `connectedAccountsData`. The `connectedAccounts.list` answer never pages
178 * (`next_cursor` is null).
179 */
180 export const mockConnectedAccountResources = (
181 connectedAccountsData: ResolvedConnectedAccountsTestData
182 ) => {
183 const resources = {
184 link: {
185 create: (_params: { auth_config_id: string; user_id: string }) =>
186 Effect.succeed(
187 connectedAccountsData.linkResponse ?? {
188 connected_account_id: 'con_test_link',
189 expires_at: '2026-12-31T23:59:59Z',
190 link_token: 'lt_test_token',
191 redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
192 }
193 ),
194 },
195 connectedAccounts: {
196 list: (params?: {
197 toolkit_slugs?: string[];
198 user_ids?: string[];
199 statuses?: string[];
200 limit?: number;
201 }) => {
202 let results = [...connectedAccountsData.items];
203
204 if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
205 const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
206 results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
207 }
208
209 if (params?.user_ids && params.user_ids.length > 0) {
210 const userIds = new Set(params.user_ids);
211 results = results.filter(item => userIds.has(item.user_id));
212 }
213
214 if (params?.statuses && params.statuses.length > 0) {
215 const statuses = new Set(params.statuses);
216 results = results.filter(item => statuses.has(item.status));
217 }
218
219 const limit = params?.limit ?? DEFAULT_PAGE_LIMIT;
220 return Effect.succeed({
221 items: results.slice(0, limit),
222 total_items: results.length,
223 total_pages: Math.ceil(results.length / limit),
224 current_page: 1,
225 next_cursor: null,
226 });
227 },
228 retrieve: (nanoid: string) =>
229 findById(connectedAccountsData.items, nanoid, () =>
230 notFoundError(`Connected account "${nanoid}" not found`)
231 ),
232 delete: (nanoid: string) =>
233 findById(connectedAccountsData.items, nanoid, () =>
234 notFoundError(`Connected account "${nanoid}" not found`)
235 ).pipe(
236 Effect.tap(() => Effect.sync(() => connectedAccountsData.onDelete?.(nanoid))),
237 Effect.as({})
238 ),
239 },
240 };
241 return {
242 ...resources,
243 connectedAccounts: {
244 ...resources.connectedAccounts,
245 listStream: (params?: Parameters<typeof resources.connectedAccounts.list>[0]) =>
246 Stream.fromEffect(
247 resources.connectedAccounts.list({
248 ...params,
249 limit: Math.max(connectedAccountsData.items.length, 1),
250 })
251 ).pipe(Stream.flatMap(page => Stream.fromIterable(page.items))),
252 },
253 };
254 };
255
256 /**
257 * A `ComposioToolkitsRepository` that serves only auth configs and connected
258 * accounts, for a test that needs nothing else from the full `TestLive` layer.
259 * Any other repository method dies.
260 */
261 export const ConnectedAccountsTest = (data?: {
262 readonly authConfigsData?: AuthConfigsTestData;
263 readonly connectedAccountsData?: ConnectedAccountsTestData;
264 }) =>
265 Layer.succeed(
266 ComposioToolkitsRepository,
267 makeToolkitsRepositoryStub(
268 connectedAccountRepositoryMethods(
269 resolveAuthConfigsTestData(data?.authConfigsData),
270 resolveConnectedAccountsTestData(data?.connectedAccountsData)
271 )
272 )
273 );