1
import path from 'node:path';
2
import * as tempy from 'tempy';
3
-import type {
4
- AuthConfigCreateParams,
5
- AuthConfigCreateResponse,
6
-} from '@composio/client/resources/auth-configs';
3
import {
8
- APIConnectionError,
4
make as makeComposioClient,
5
type ComposioError,
6
type RequestOptions,
7
} from '@composio/client/effect';
13
-import type { LinkCreateResponse } from '@composio/client/resources/link';
8
import type {
9
TriggerInstanceListActiveParams,
10
TriggerInstanceUpsertParams,
11
} from '@composio/client/resources/trigger-instances';
18
-import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
12
import { TIMESTAMP } from '../models/account';
13
import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
14
import * as BunPath from '@effect/platform-bun/BunPath';
39
ComposioSessionRepository,
40
ComposioToolkitsRepository,
41
} from 'src/services/composio-clients';
49
-import { type OrganizationSummary, type OrgProject } from 'src/services/composio-account';
42
import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
51
-import type { AuthConfigItem } from 'src/models/auth-configs';
52
-import type { ConnectedAccountItem } from 'src/models/connected-accounts';
43
import type { TriggerInstanceItem } from 'src/models/triggers';
44
import { ComposioUserContextLive } from 'src/services/user-context';
45
import { ComposioCliUserConfig } from 'src/services/cli-user-config';
78
import { FetchHttpClient, HttpClient } from 'effect/http';
79
import * as BunServices from '@effect/platform-bun/BunServices';
80
import { notFoundError } from '../layers/not-found';
81
+import { DEFAULT_PAGE_LIMIT } from '../layers/page';
82
import {
83
resolveToolkitsTestData,
84
toolkitCatalogMethods,
85
type ToolkitsTestData,
86
} from '../layers/toolkits';
87
+import {
88
+ mockAccountResources,
89
+ type AccountTestData,
90
+ type MockRequestScope,
91
+} from '../layers/accounts';
92
+import {
93
+ connectedAccountRepositoryMethods,
94
+ mockConnectedAccountResources,
95
+ resolveAuthConfigsTestData,
96
+ resolveConnectedAccountsTestData,
97
+ type AuthConfigsTestData,
98
+ type ConnectedAccountsTestData,
99
+} from '../layers/connected-accounts';
100
97
-/**
98
- * The credentials and scope one mock-client request carries: the parameters
99
- * the client was obtained with, overridden by per-request headers.
100
- */
101
-export interface MockRequestScope {
102
- readonly userApiKey?: string;
103
- readonly apiKey?: string;
104
- readonly orgId?: string;
105
- readonly projectId?: string;
106
-}
107
-
108
-/**
109
- * One call to an account, session-info, or consumer endpoint of the mock client.
110
- */
111
-export interface MockAccountRequest {
112
- readonly operation:
113
- | 'org.list'
114
- | 'org.project.list'
115
- | 'org.consumer.project.resolve'
116
- | 'org.consumer.listConnectedToolkits'
117
- | 'auth.session.retrieveInfo'
118
- | 'tools.getLatestVersion'
119
- | 'org.project.createApiKey'
120
- | 'org.consumer.config'
121
- | 'consumer.permissions.resolve';
122
- readonly scope: MockRequestScope;
123
- readonly params?: unknown;
124
- readonly options?: RequestOptions;
125
-}
101
+export type { MockAccountRequest, MockRequestScope } from '../layers/accounts';
102
103
export interface TestLiveInput {
104
/**
134
/**
135
* Account, session-info, and consumer data served by the mock client's
136
* `org.*` and `auth.session.retrieveInfo` resources and its `get`/`post`
161
- * escape hatch. An endpoint without data rejects with a connection error,
162
- * as an unreachable backend would; consumer project resolution always
163
- * answers, echoing the requested org.
137
+ * escape hatch.
138
*/
165
- accountData?: {
166
- sessionInfo?:
167
- SessionRetrieveInfoResponse | ((scope: MockRequestScope) => SessionRetrieveInfoResponse);
168
- organizations?: ReadonlyArray<OrganizationSummary>;
169
- projects?: ReadonlyArray<OrgProject>;
170
- connectedToolkits?: ReadonlyArray<string>;
171
- latestToolVersion?: { readonly tool_slug: string; readonly version: string };
172
- projectApiKey?: string;
173
- onRequest?: (request: MockAccountRequest) => void;
174
- };
139
+ accountData?: AccountTestData;
140
141
/**
142
* Mock auth-config data to use in test.
143
*/
179
- authConfigsData?: {
180
- items?: AuthConfigItem[];
181
- createResponse?: AuthConfigCreateResponse;
182
- onCreate?: (params: AuthConfigCreateParams) => void;
183
- };
144
+ authConfigsData?: AuthConfigsTestData;
145
146
/**
147
* Mock connected-account data to use in test.
148
*/
188
- connectedAccountsData?: {
189
- items?: ConnectedAccountItem[];
190
- linkResponse?: LinkCreateResponse;
191
- onDelete?: (nanoid: string) => void;
192
- };
149
+ connectedAccountsData?: ConnectedAccountsTestData;
150
151
/**
152
* Mock trigger instance data to use in test.
288
const fixture = input?.fixture;
289
const toolkitsData = resolveToolkitsTestData(input?.toolkitsData);
290
334
- const defaultAuthConfigsData = {
335
- items: [] as AuthConfigItem[],
336
- createResponse: undefined as AuthConfigCreateResponse | undefined,
337
- } satisfies TestLiveInput['authConfigsData'];
338
- const authConfigsData = {
339
- ...defaultAuthConfigsData,
340
- ...(input?.authConfigsData ?? {}),
341
- };
342
-
343
- const defaultConnectedAccountsData = {
344
- items: [] as ConnectedAccountItem[],
345
- linkResponse: undefined as LinkCreateResponse | undefined,
346
- } satisfies TestLiveInput['connectedAccountsData'];
347
- const connectedAccountsData = {
348
- ...defaultConnectedAccountsData,
349
- ...(input?.connectedAccountsData ?? {}),
350
- };
291
+ const authConfigsData = resolveAuthConfigsTestData(input?.authConfigsData);
292
+ const connectedAccountsData = resolveConnectedAccountsTestData(input?.connectedAccountsData);
293
294
const defaultRealtimeData = {
295
events: [] as ReadonlyArray<Record<string, unknown>>,
314
ComposioToolkitsRepository,
315
ComposioToolkitsRepository.of({
316
...toolkitCatalogMethods(toolkitsData),
375
- listAuthConfigs: (params: {
376
- search?: string;
377
- toolkit_slug?: string;
378
- limit?: number;
379
- show_disabled?: boolean;
380
- }) => {
381
- let results = [...authConfigsData.items];
382
-
383
- if (params.toolkit_slug) {
384
- const slugs = params.toolkit_slug.split(',').map(s => s.trim().toLowerCase());
385
- results = results.filter(item => slugs.includes(item.toolkit.slug.toLowerCase()));
386
- }
387
-
388
- if (params.search) {
389
- const q = params.search.toLowerCase();
390
- results = results.filter(
391
- item => item.name.toLowerCase().includes(q) || item.id.toLowerCase().includes(q)
392
- );
393
- }
394
-
395
- const limit = params.limit ?? 30;
396
- const items = results.slice(0, limit);
397
- return Effect.succeed({
398
- items,
399
- total_items: results.length,
400
- total_pages: Math.ceil(results.length / limit),
401
- current_page: 1,
402
- next_cursor: null,
403
- });
404
- },
405
- getAuthConfig: (nanoid: string) => {
406
- const found = authConfigsData.items.find(item => item.id === nanoid);
407
- if (!found) {
408
- return Effect.fail(
409
- notFoundError(`Auth config "${nanoid}" not found`, {
410
- message: `Auth config "${nanoid}" not found.`,
411
- suggested_fix: 'Check the auth config ID and try again.',
412
- })
413
- );
414
- }
415
- return Effect.succeed(found);
416
- },
417
- createAuthConfig: (params: AuthConfigCreateParams) => {
418
- authConfigsData.onCreate?.(params);
419
- return Effect.succeed(
420
- authConfigsData.createResponse ?? {
421
- auth_config: { id: 'ac_test', auth_scheme: 'OAUTH2', is_composio_managed: true },
422
- toolkit: { slug: 'test' },
423
- }
424
- );
425
- },
426
- getConnectedAccount: (nanoid: string) => {
427
- const found = connectedAccountsData.items.find(item => item.id === nanoid);
428
- if (!found) {
429
- return Effect.fail(
430
- notFoundError(`Connected account "${nanoid}" not found`, {
431
- message: `Connected account "${nanoid}" not found.`,
432
- suggested_fix: 'Check the connected account ID and try again.',
433
- })
434
- );
435
- }
436
- return Effect.succeed(found);
437
- },
317
+ ...connectedAccountRepositoryMethods(authConfigsData, connectedAccountsData),
318
listActiveTriggers: (params: TriggerInstanceListActiveParams) => {
319
let results = [...triggersData.items];
320
353
results = results.filter(item => item.disabled_at === null);
354
}
355
476
- const limit = params.limit ?? 30;
356
+ const limit = params.limit ?? DEFAULT_PAGE_LIMIT;
357
const items = results.slice(0, limit);
358
return Effect.succeed({
359
items,
596
597
// What the mock client answers with instead of calling the network.
598
const resourceShadows = {
719
- link: {
720
- create: async (params: { auth_config_id: string; user_id: string }) => {
721
- const response = connectedAccountsData.linkResponse ?? {
722
- connected_account_id: 'con_test_link',
723
- expires_at: '2026-12-31T23:59:59Z',
724
- link_token: 'lt_test_token',
725
- redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
726
- };
727
- return response;
728
- },
729
- },
730
- connectedAccounts: {
731
- list: async (params?: {
732
- toolkit_slugs?: string[];
733
- user_ids?: string[];
734
- statuses?: string[];
735
- limit?: number;
736
- }) => {
737
- let results = [...connectedAccountsData.items];
738
-
739
- if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
740
- const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
741
- results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
742
- }
743
-
744
- if (params?.user_ids && params.user_ids.length > 0) {
745
- const userIds = new Set(params.user_ids);
746
- results = results.filter(item => userIds.has(item.user_id));
747
- }
748
-
749
- if (params?.statuses && params.statuses.length > 0) {
750
- const statuses = new Set(params.statuses);
751
- results = results.filter(item => statuses.has(item.status));
752
- }
753
-
754
- const limit = params?.limit ?? 30;
755
- return {
756
- items: results.slice(0, limit),
757
- total_items: results.length,
758
- total_pages: Math.ceil(results.length / limit),
759
- current_page: 1,
760
- next_cursor: null,
761
- };
762
- },
763
- retrieve: (nanoid: string) => {
764
- const found = connectedAccountsData.items.find(item => item.id === nanoid);
765
- return found
766
- ? Effect.succeed(found)
767
- : Effect.fail(notFoundError(`Connected account "${nanoid}" not found`));
768
- },
769
- delete: (nanoid: string) => {
770
- const found = connectedAccountsData.items.find(item => item.id === nanoid);
771
- if (!found) {
772
- return Effect.fail(notFoundError(`Connected account "${nanoid}" not found`));
773
- }
774
- connectedAccountsData.onDelete?.(nanoid);
775
- return Effect.succeed({});
776
- },
777
- },
599
+ ...mockConnectedAccountResources(connectedAccountsData),
600
triggersTypes: {
601
retrieve: (slug: string) => {
602
const found = toolkitsData.triggerTypes.find(
778
);
779
780
// --- Account, session-info, and consumer endpoints ---
959
- // Served per client scope, so a handler sees the credentials and org or
960
- // project the real client would have placed in its default headers.
781
+ // Served per client scope; see `mockAccountResources`.
782
const accountData = input?.accountData ?? {};
962
- const noTestData = (operation: MockAccountRequest['operation']) =>
963
- new APIConnectionError({
964
- message: `No test data for ${operation}`,
965
- method: 'GET',
966
- url: 'https://mock.invalid',
967
- reason: 'TransportError',
968
- description: `No test data for ${operation}`,
969
- });
970
-
971
- const scopeOf = (base: MockRequestScope, options?: RequestOptions): MockRequestScope => {
972
- // The CLI only ever passes plain header records.
973
- const headers = (options?.headers ?? {}) as Record<string, string | null | undefined>;
974
- const userApiKey = headers['x-user-api-key'];
975
- return {
976
- userApiKey: userApiKey === null ? undefined : (userApiKey ?? base.userApiKey),
977
- apiKey: headers['x-api-key'] ?? undefined,
978
- orgId: headers['x-org-id'] ?? base.orgId,
979
- projectId: headers['x-project-id'] ?? base.projectId,
980
- };
981
- };
982
-
983
- const accountBranches = (base: MockRequestScope) => {
984
- const record = (
985
- operation: MockAccountRequest['operation'],
986
- options: RequestOptions | undefined,
987
- params?: unknown
988
- ): MockRequestScope => {
989
- const scope = scopeOf(base, options);
990
- accountData.onRequest?.({ operation, scope, params, options });
991
- return scope;
992
- };
993
- const timestamps = {
994
- created_at: TIMESTAMP,
995
- updated_at: TIMESTAMP,
996
- };
997
-
998
- return {
999
- org: {
1000
- list: async (query?: { limit?: number } | null, options?: RequestOptions) => {
1001
- record('org.list', options, query);
1002
- if (!accountData.organizations) throw noTestData('org.list');
1003
- const organizations = accountData.organizations.map(org => ({ ...org, ...timestamps }));
1004
- return {
1005
- organizations,
1006
- next_cursor: null,
1007
- total_pages: 1,
1008
- current_page: 1,
1009
- total_items: organizations.length,
1010
- };
1011
- },
1012
- project: {
1013
- list: async (
1014
- query?: { limit?: number; list_all_org_projects?: boolean | null } | null,
1015
- options?: RequestOptions
1016
- ) => {
1017
- record('org.project.list', options, query);
1018
- if (!accountData.projects) throw noTestData('org.project.list');
1019
- return {
1020
- data: [...accountData.projects],
1021
- next_cursor: null,
1022
- total_pages: 1,
1023
- current_page: 1,
1024
- total_items: accountData.projects.length,
1025
- };
1026
- },
1027
- },
1028
- consumer: {
1029
- project: {
1030
- resolve: async (
1031
- params: { 'x-user-api-key': string; 'x-org-id': string },
1032
- options?: RequestOptions
1033
- ) => {
1034
- record('org.consumer.project.resolve', options, params);
1035
- const orgId = params['x-org-id'];
1036
- return {
1037
- project_id: 'consumer_project_id_test',
1038
- project_nano_id: 'consumer_project_test',
1039
- project_name: 'Consumer Project',
1040
- org_id: orgId,
1041
- project_type: 'CONSUMER' as const,
1042
- config: { consumer_experience_enabled: true, enhanced_controls: false },
1043
- consumer_user_id: `consumer-user-${orgId}`,
1044
- };
1045
- },
1046
- },
1047
- listConnectedToolkits: async (
1048
- params: { user_id: string; 'x-user-api-key': string; 'x-org-id': string },
1049
- options?: RequestOptions
1050
- ) => {
1051
- record('org.consumer.listConnectedToolkits', options, params);
1052
- if (!accountData.connectedToolkits) {
1053
- throw noTestData('org.consumer.listConnectedToolkits');
1054
- }
1055
- return { toolkits: [...accountData.connectedToolkits] };
1056
- },
1057
- },
1058
- },
1059
- auth: {
1060
- session: {
1061
- retrieveInfo: async (options?: RequestOptions) => {
1062
- const scope = record('auth.session.retrieveInfo', options);
1063
- const sessionInfo = accountData.sessionInfo;
1064
- if (sessionInfo === undefined) throw noTestData('auth.session.retrieveInfo');
1065
- return typeof sessionInfo === 'function' ? sessionInfo(scope) : sessionInfo;
1066
- },
1067
- },
1068
- },
1069
- get: async (path: string, options?: RequestOptions) => {
1070
- if (/^\/api\/v3\/tools\/[^/]+\/get_latest_version$/.test(path)) {
1071
- record('tools.getLatestVersion', options, { path });
1072
- if (!accountData.latestToolVersion) throw noTestData('tools.getLatestVersion');
1073
- return accountData.latestToolVersion;
1074
- }
1075
- throw new Error(`Unhandled GET path "${path}"`);
1076
- },
1077
- post: async (path: string, options?: RequestOptions & { body?: unknown }) => {
1078
- if (/^\/api\/v3\/org\/project\/[^/]+\/api_keys\/create$/.test(path)) {
1079
- record('org.project.createApiKey', options, { path, body: options?.body });
1080
- if (!accountData.projectApiKey) throw noTestData('org.project.createApiKey');
1081
- return { api_key: accountData.projectApiKey };
1082
- }
1083
- throw new Error(`Unhandled POST path "${path}"`);
1084
- },
1085
- };
1086
- };
783
784
const scopedClients = new Map<string, typeof mockComposioClient>();
785
const mockClientFor = (scope: MockRequestScope) => {
786
const key = JSON.stringify([scope.userApiKey, scope.orgId, scope.projectId]);
787
const cached = scopedClients.get(key);
788
if (cached) return cached;
1093
- const scoped = withShadows(mockComposioClient, accountBranches(scope));
789
+ const scoped = withShadows(mockComposioClient, mockAccountResources(accountData, scope));
790
scopedClients.set(key, scoped);
791
return scoped;
792
};