Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Fix Add support for userid in trigger creation (#1648)
Musthaq Ahamad committed
Jun 17, 2025 at 13:56 UTC
28b09d6eebade19c1ed3b82ee05472201a96b65e
8 files changed
+353
-30
pnpm-lock.yaml
+26
-5
@@ -451,8 +451,8 @@ importers:
451
ts/packages/core:
452
dependencies:
453
'@composio/client':
454
- specifier: 0.1.0-alpha.22
455
- version: 0.1.0-alpha.22
454
+ specifier: 0.1.0-alpha.23
455
+ version: 0.1.0-alpha.23
456
'@composio/json-schema-to-zod':
457
specifier: 0.1.9
458
version: 0.1.9
@@ -925,6 +925,9 @@ packages:
925
'@composio/client@0.1.0-alpha.22':
926
resolution: {integrity: sha512-b9KCO5gy0EsCG+nXikOdm17PiZZ85rw3vwu9aNRIse9rEj2FA1SScpP+P9GN4G0lQHl+QPyDuVvGa6U9AATFeg==}
927
928
+ '@composio/client@0.1.0-alpha.23':
929
+ resolution: {integrity: sha512-zDbOJZVR+Ug0a622mjMGsREELKOG6DLF3qKI7qJ9FLP/GpAT7xekyEE7DR0g37zs6ytCy0oV/KMi+KaxxNp+zA==}
930
+
931
'@composio/core@0.1.22':
932
resolution: {integrity: sha512-ehu0OdwAgjShWjRaXBVlFnaqykDj6rxWcH3GeE179luNqLIb1p0L+Nazb1IMJ1CFl+DQC/NWkI80K8lgRLBQNQ==}
933
@@ -5870,6 +5873,8 @@ snapshots:
5873
5874
'@composio/client@0.1.0-alpha.22': {}
5875
5876
+ '@composio/client@0.1.0-alpha.23': {}
5877
+
5878
'@composio/core@0.1.22(ws@8.18.2)':
5879
dependencies:
5880
'@composio/client': 0.1.0-alpha.22
@@ -7915,6 +7920,14 @@ snapshots:
7920
chai: 5.2.0
7921
tinyrainbow: 2.0.0
7922
7923
+ '@vitest/mocker@3.2.3(vite@6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))':
7924
+ dependencies:
7925
+ '@vitest/spy': 3.2.3
7926
+ estree-walker: 3.0.3
7927
+ magic-string: 0.30.17
7928
+ optionalDependencies:
7929
+ vite: 6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
7930
+
7931
'@vitest/mocker@3.2.3(vite@6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))':
7932
dependencies:
7933
'@vitest/spy': 3.2.3
@@ -7923,6 +7936,14 @@ snapshots:
7936
optionalDependencies:
7937
vite: 6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
7938
7939
+ '@vitest/mocker@3.2.3(vite@6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))':
7940
+ dependencies:
7941
+ '@vitest/spy': 3.2.3
7942
+ estree-walker: 3.0.3
7943
+ magic-string: 0.30.17
7944
+ optionalDependencies:
7945
+ vite: 6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
7946
+
7947
'@vitest/pretty-format@3.2.3':
7948
dependencies:
7949
tinyrainbow: 2.0.0
@@ -7952,7 +7973,7 @@ snapshots:
7973
sirv: 3.0.1
7974
tinyglobby: 0.2.14
7975
tinyrainbow: 2.0.0
7955
- vitest: 3.2.3(@types/node@22.15.31)(@vitest/ui@3.2.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
7976
+ vitest: 3.2.3(@types/node@24.0.3)(@vitest/ui@3.2.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
7977
7978
'@vitest/utils@3.2.3':
7979
dependencies:
@@ -10540,7 +10561,7 @@ snapshots:
10561
dependencies:
10562
'@types/chai': 5.2.2
10563
'@vitest/expect': 3.2.3
10543
- '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
10564
+ '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
10565
'@vitest/pretty-format': 3.2.3
10566
'@vitest/runner': 3.2.3
10567
'@vitest/snapshot': 3.2.3
@@ -10624,7 +10645,7 @@ snapshots:
10645
dependencies:
10646
'@types/chai': 5.2.2
10647
'@vitest/expect': 3.2.3
10627
- '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
10648
+ '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
10649
'@vitest/pretty-format': 3.2.3
10650
'@vitest/runner': 3.2.3
10651
'@vitest/snapshot': 3.2.3
ts/docs/api/triggers.md
+78
-4
@@ -33,17 +33,91 @@ const triggers = await composio.triggers.listActive({
33
34
### Create Trigger Instance
35
36
-Create a new trigger instance for a specific trigger type:
36
+Create a new trigger instance for a specific user and trigger type. If a connected account ID is not provided, the SDK will automatically use the first available connected account for the user and toolkit.
37
+
38
+**With Connected Account ID:**
39
40
```typescript
39
-const trigger = await composio.triggers.create('trigger-slug', {
40
- connectedAccountId: 'connected-account-id',
41
+const trigger = await composio.triggers.create('default', 'GMAIL_NEW_GMAIL_MESSAGE', {
42
+ connectedAccountId: 'ca_jjYIG9L40LDIS', // Specify which connected account to use
43
triggerConfig: {
42
- // Trigger specific configuration
44
+ labelIds: 'INBOX',
45
+ userId: 'me',
46
+ interval: 60,
47
},
48
});
49
```
50
51
+**Without Connected Account ID (Using First Available):**
52
+
53
+```typescript
54
+const trigger = await composio.triggers.create('default', 'GMAIL_NEW_GMAIL_MESSAGE', {
55
+ triggerConfig: {
56
+ labelIds: 'INBOX',
57
+ userId: 'me',
58
+ interval: 60,
59
+ },
60
+}); // Will use the first available connected account
61
+```
62
+
63
+> **Note:** It's recommended to provide a `connectedAccountId` when you have multiple connected accounts for the same toolkit to ensure the trigger is created for the intended account. If not provided, the SDK will use the first available connected account and log a warning.
64
+
65
+**Parameters:**
66
+
67
+- `userId` (string, required): The ID of the user to create the trigger instance for
68
+- `slug` (string, required): The slug of the trigger type to create
69
+- `body` (TriggerInstanceUpsertParams, optional): Configuration for the trigger instance
70
+ - `connectedAccountId` (string, optional): ID of the connected account to use. If not provided, will use the first available connected account for the user and toolkit
71
+ - `triggerConfig` (object, optional): Trigger-specific configuration parameters
72
+
73
+**Returns:** Promise<TriggerInstanceUpsertResponse> - The created trigger instance with the following structure:
74
+
75
+```typescript
76
+{
77
+ triggerId: string; // The ID of the created trigger instance
78
+}
79
+```
80
+
81
+**Throws:**
82
+
83
+- `ValidationError`: If the provided parameters are invalid
84
+- `ComposioTriggerTypeNotFoundError`: If the trigger type with the given slug is not found
85
+- `ComposioConnectedAccountNotFoundError`: If no connected account is found for the user, or if the specified connected account ID is not found
86
+
87
+**Example with Error Handling:**
88
+
89
+```typescript
90
+try {
91
+ const trigger = await composio.triggers.create('default', 'GMAIL_NEW_GMAIL_MESSAGE', {
92
+ // Connected account ID is optional - if not provided, will use first available
93
+ connectedAccountId: 'ca_jjYIG9L40LDIS',
94
+ triggerConfig: {
95
+ labelIds: 'INBOX',
96
+ userId: 'me',
97
+ interval: 60,
98
+ },
99
+ });
100
+ console.log('Trigger created:', trigger.triggerId);
101
+} catch (error) {
102
+ if (error instanceof ComposioTriggerTypeNotFoundError) {
103
+ console.error('Trigger type not found:', error.message);
104
+ // Handle invalid trigger type
105
+ } else if (error instanceof ComposioConnectedAccountNotFoundError) {
106
+ console.error('Connected account issue:', error.message);
107
+ // Handle missing or invalid connected account
108
+ // This can happen if:
109
+ // 1. No connected accounts exist for the user and toolkit
110
+ // 2. The specified connectedAccountId was not found
111
+ } else if (error instanceof ValidationError) {
112
+ console.error('Invalid parameters:', error.message);
113
+ // Handle validation errors
114
+ } else {
115
+ console.error('Unexpected error:', error);
116
+ // Handle other errors
117
+ }
118
+}
119
+```
120
+
121
### Update Trigger Instance
122
123
Update an existing trigger instance:
ts/examples/triggers/src/create.ts
new
+22
@@ -0,0 +1,22 @@
1
+import { Composio } from '@composio/core';
2
+
3
+const composio = new Composio({
4
+ apiKey: process.env.COMPOSIO_API_KEY,
5
+});
6
+
7
+// fetch a trigger type
8
+const triggerType = await composio.triggers.getType('GMAIL_NEW_GMAIL_MESSAGE');
9
+
10
+console.log(JSON.stringify(triggerType, null, 2));
11
+
12
+// create a trigger
13
+const trigger = await composio.triggers.create('default', triggerType.slug, {
14
+ connectedAccountId: 'ca_jjYIG9L40LDIS',
15
+ triggerConfig: {
16
+ labelIds: 'INBOX',
17
+ userId: 'me',
18
+ interval: 60,
19
+ },
20
+});
21
+
22
+console.log(trigger);
ts/packages/core/package.json
+1
-1
@@ -37,7 +37,7 @@
37
"vitest": "^3.1.4"
38
},
39
"dependencies": {
40
- "@composio/client": "0.1.0-alpha.22",
40
+ "@composio/client": "0.1.0-alpha.23",
41
"@composio/json-schema-to-zod": "0.1.9",
42
"chalk": "^5.4.1",
43
"openai": "^4.94.0",
ts/packages/core/src/errors/TriggerErrors.ts
+17
-4
@@ -1,4 +1,5 @@
1
import { ComposioError } from '@composio/client';
2
+import { ComposioErrorOptions } from './ComposioError';
3
4
export const TriggerErrorCodes = {
5
TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS: 'TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS',
@@ -6,6 +7,7 @@ export const TriggerErrorCodes = {
7
TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL: 'TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL',
8
TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL:
9
'TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL',
10
+ TRIGGER_TYPE_NOT_FOUND: 'TRIGGER_TYPE_NOT_FOUND',
11
} as const;
12
13
export class ComposioFailedToGetSDKRealtimeCredentialsError extends ComposioError {
@@ -14,7 +16,7 @@ export class ComposioFailedToGetSDKRealtimeCredentialsError extends ComposioErro
16
public statusCode = 500;
17
public possibleFixes = ['Please contact support.'];
18
17
- constructor(message: string, options?: ErrorOptions) {
19
+ constructor(message: string, options?: ComposioErrorOptions) {
20
super(message, options);
21
}
22
}
@@ -25,7 +27,7 @@ export class ComposioFailedToCreatePusherClientError extends ComposioError {
27
public statusCode = 500;
28
public possibleFixes = ['Please contact support.'];
29
28
- constructor(message: string, options?: ErrorOptions) {
30
+ constructor(message: string, options?: ComposioErrorOptions) {
31
super(message, options);
32
}
33
}
@@ -36,7 +38,7 @@ export class ComposioFailedToSubscribeToPusherChannelError extends ComposioError
38
public statusCode = 500;
39
public possibleFixes = ['Please contact support.'];
40
39
- constructor(message: string, options?: ErrorOptions) {
41
+ constructor(message: string, options?: ComposioErrorOptions) {
42
super(message, options);
43
}
44
}
@@ -47,7 +49,18 @@ export class ComposioFailedToUnsubscribeFromPusherChannelError extends ComposioE
49
public statusCode = 500;
50
public possibleFixes = ['Please contact support.'];
51
50
- constructor(message: string, options?: ErrorOptions) {
52
+ constructor(message: string, options?: ComposioErrorOptions) {
53
+ super(message, options);
54
+ }
55
+}
56
+
57
+export class ComposioTriggerTypeNotFoundError extends ComposioError {
58
+ public name = 'ComposioTriggerTypeNotFoundError';
59
+ public code = TriggerErrorCodes.TRIGGER_TYPE_NOT_FOUND;
60
+ public statusCode = 404;
61
+ public possibleFixes = ['Please contact support.'];
62
+
63
+ constructor(message: string = 'Trigger type not found', options?: ComposioErrorOptions) {
64
super(message, options);
65
}
66
}
ts/packages/core/src/models/Triggers.ts
+88
-6
@@ -1,4 +1,4 @@
1
-import ComposioClient from '@composio/client';
1
+import ComposioClient, { APIError } from '@composio/client';
2
import {
3
TriggerInstanceListActiveResponse as TriggerInstanceListActiveResponseComposio,
4
TriggersTypeListParams,
@@ -28,8 +28,9 @@ import {
28
} from '../types/triggers.types';
29
import logger from '../utils/logger';
30
import { telemetry } from '../telemetry/Telemetry';
31
-import { ValidationError } from '../errors';
31
+import { ComposioConnectedAccountNotFoundError, ValidationError } from '../errors';
32
import { PusherService } from '../services/pusher/Pusher';
33
+import { ComposioTriggerTypeNotFoundError } from '../errors/TriggerErrors';
34
/**
35
* Trigger (Instance) class
36
* /api/v3/trigger_instances
@@ -133,17 +134,20 @@ export class Triggers {
134
}
135
136
/**
136
- * Create a new trigger instance
137
+ * Create a new trigger instance for a user
138
+ * If the connected account id is not provided, the first connected account for the user and toolkit will be used
139
*
140
+ * @param {string} userId - The user id of the trigger instance
141
* @param {string} slug - The slug of the trigger instance
142
* @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
143
* @returns {Promise<TriggerInstanceUpsertResponse>} The created trigger instance
144
*/
145
async create(
146
+ userId: string,
147
slug: string,
144
- body: TriggerInstanceUpsertParams
148
+ body?: TriggerInstanceUpsertParams
149
): Promise<TriggerInstanceUpsertResponse> {
146
- const parsedBody = TriggerInstanceUpsertParamsSchema.safeParse(body);
150
+ const parsedBody = TriggerInstanceUpsertParamsSchema.safeParse(body ?? {});
151
152
if (!parsedBody.success) {
153
throw new ValidationError(`Invalid parameters passed to create trigger`, {
@@ -151,10 +155,88 @@ export class Triggers {
155
});
156
}
157
158
+ // Get the connected account id from the user id
159
+ let triggerType: TriggersTypeRetrieveResponse;
160
+ let toolkitSlug: string;
161
+ try {
162
+ triggerType = await this.getType(slug);
163
+ toolkitSlug = triggerType.toolkit.slug;
164
+ } catch (error) {
165
+ // for some reason, the triggers types list endpoint returns 400 for invalid user ids
166
+ if (error instanceof APIError && (error.status === 400 || error.status === 404)) {
167
+ throw new ComposioTriggerTypeNotFoundError(`Trigger type ${slug} not found`, {
168
+ cause: error,
169
+ possibleFixes: [
170
+ `Please check the trigger slug`,
171
+ `Visit the toolkit page to see the available triggers`,
172
+ ],
173
+ });
174
+ } else {
175
+ throw error;
176
+ }
177
+ }
178
+
179
+ // Attempt to get connected account ID
180
+ let connectedAccountId: string | undefined = body?.connectedAccountId;
181
+
182
+ try {
183
+ const { items: connectedAccounts } = await this.client.connectedAccounts.list({
184
+ user_ids: [userId],
185
+ toolkit_slugs: [toolkitSlug],
186
+ });
187
+
188
+ if (connectedAccounts.length === 0) {
189
+ throw new ComposioConnectedAccountNotFoundError(
190
+ `No connected account found for user ${userId} for toolkit ${toolkitSlug}`,
191
+ {
192
+ cause: new Error(`No connected account found for user ${userId}`),
193
+ possibleFixes: [`Create a new connected account for user ${userId}`],
194
+ }
195
+ );
196
+ }
197
+
198
+ const accountExists = connectedAccounts.some(acc => acc.id === connectedAccountId);
199
+ // if the connected account id is provided and it does not exist, throw an error
200
+ if (connectedAccountId && !accountExists) {
201
+ throw new ComposioConnectedAccountNotFoundError(
202
+ `Connected account ID ${connectedAccountId} not found for user ${userId}`,
203
+ {
204
+ cause: new Error(
205
+ `Connected account ID ${connectedAccountId} not found for user ${userId}`
206
+ ),
207
+ possibleFixes: [
208
+ `Create a new connected account for user ${userId}`,
209
+ `Verify the connected account ID`,
210
+ ],
211
+ }
212
+ );
213
+ }
214
+
215
+ // if the connected account id is not provided, use the first connected account
216
+ if (!connectedAccountId) {
217
+ connectedAccountId = connectedAccounts[0].id;
218
+ logger.warn(
219
+ `[Warn] Multiple connected accounts found for user ${userId}, using the first one. Pass connectedAccountId to select a specific account.`
220
+ );
221
+ }
222
+ } catch (error) {
223
+ if (error instanceof APIError && [400, 404].includes(error.status)) {
224
+ throw new ComposioConnectedAccountNotFoundError(
225
+ `No connected account found for user ${userId} for toolkit ${toolkitSlug}`,
226
+ {
227
+ cause: error,
228
+ possibleFixes: [`Create a new connected account for user ${userId}`],
229
+ }
230
+ );
231
+ }
232
+ throw error;
233
+ }
234
+
235
const result = await this.client.triggerInstances.upsert(slug, {
155
- connected_account_id: parsedBody.data.connectedAccountId,
236
+ connected_account_id: connectedAccountId,
237
trigger_config: parsedBody.data.triggerConfig,
238
});
239
+
240
const parsedResult = TriggerInstanceUpsertResponseSchema.safeParse({
241
triggerId: result.trigger_id,
242
} as TriggerInstanceUpsertResponse);
ts/packages/core/src/types/connectedAccounts.types.ts
+1
@@ -10,6 +10,7 @@ export const ConnectedAccountStatuses = {
10
ACTIVE: 'ACTIVE',
11
FAILED: 'FAILED',
12
EXPIRED: 'EXPIRED',
13
+ INACTIVE: 'INACTIVE',
14
} as const;
15
export const ConnectedAccountStatusSchema = z.enum([
16
ConnectedAccountStatuses.INITIALIZING,
ts/packages/core/test/models/triggers.test.ts
+120
-10
@@ -1,6 +1,6 @@
1
import { describe, it, expect, vi, beforeEach, afterEach, Mock } from 'vitest';
2
import { Triggers } from '../../src/models/Triggers';
3
-import ComposioClient from '@composio/client';
3
+import ComposioClient, { APIError } from '@composio/client';
4
import logger from '../../src/utils/logger';
5
import {
6
TriggerSubscribeParams,
@@ -9,9 +9,12 @@ import {
9
IncomingTriggerPayloadSchema,
10
} from '../../src/types/triggers.types';
11
import { telemetry } from '../../src/telemetry/Telemetry';
12
-import { ValidationError } from '../../src/errors';
12
+import { ComposioConnectedAccountNotFoundError, ValidationError } from '../../src/errors';
13
import { PusherService } from '../../src/services/pusher/Pusher';
14
-import { ComposioFailedToSubscribeToPusherChannelError } from '../../src/errors/TriggerErrors';
14
+import {
15
+ ComposioFailedToSubscribeToPusherChannelError,
16
+ ComposioTriggerTypeNotFoundError,
17
+} from '../../src/errors/TriggerErrors';
18
19
// Mock dependencies
20
vi.mock('../../src/utils/logger');
@@ -39,6 +42,9 @@ const createMockClient = () => ({
42
retrieve: vi.fn(),
43
retrieveEnum: vi.fn(),
44
},
45
+ connectedAccounts: {
46
+ list: vi.fn(),
47
+ },
48
});
49
50
// Mock response data
@@ -107,6 +113,9 @@ const mockTriggerType = {
113
required: ['webhook_url'],
114
optional: ['secret'],
115
},
116
+ toolkit: {
117
+ slug: 'github',
118
+ },
119
};
120
121
const mockTriggerEnum = {
@@ -270,22 +279,123 @@ describe('Triggers', () => {
279
});
280
281
describe('create', () => {
273
- it('should create a new trigger instance', async () => {
274
- const slug = 'github_webhook';
275
- const body = {
276
- connectedAccountId: 'conn-123',
277
- triggerConfig: { webhook_url: 'https://example.com/webhook' },
278
- };
282
+ const userId = 'user-123';
283
+ const slug = 'github_webhook';
284
+ const body = {
285
+ connectedAccountId: 'conn-123',
286
+ triggerConfig: { webhook_url: 'https://example.com/webhook' },
287
+ };
288
+
289
+ beforeEach(() => {
290
+ mockClient.triggersTypes.retrieve.mockResolvedValue(mockTriggerType);
291
mockClient.triggerInstances.upsert.mockResolvedValue(mockTriggerUpsertResponse);
292
+ });
293
281
- const result = await triggers.create(slug, body);
294
+ it('should create a new trigger instance with provided connected account ID', async () => {
295
+ mockClient.connectedAccounts.list.mockResolvedValue({
296
+ items: [{ id: 'conn-123' }],
297
+ });
298
+
299
+ const result = await triggers.create(userId, slug, body);
300
301
+ expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(slug);
302
+ expect(mockClient.connectedAccounts.list).toHaveBeenCalledWith({
303
+ user_ids: [userId],
304
+ toolkit_slugs: [mockTriggerType.toolkit.slug],
305
+ });
306
expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(slug, {
307
connected_account_id: body.connectedAccountId,
308
trigger_config: body.triggerConfig,
309
});
310
expect(result).toEqual({ triggerId: mockTriggerUpsertResponse.trigger_id });
311
});
312
+
313
+ it('should use first connected account if no connected account ID is provided', async () => {
314
+ const bodyWithoutConnectedAccount = {
315
+ triggerConfig: body.triggerConfig,
316
+ };
317
+ mockClient.connectedAccounts.list.mockResolvedValue({
318
+ items: [{ id: 'conn-456' }, { id: 'conn-789' }],
319
+ });
320
+
321
+ const result = await triggers.create(userId, slug, bodyWithoutConnectedAccount);
322
+
323
+ expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(slug, {
324
+ connected_account_id: 'conn-456',
325
+ trigger_config: bodyWithoutConnectedAccount.triggerConfig,
326
+ });
327
+ expect(logger.warn).toHaveBeenCalledWith(
328
+ `[Warn] Multiple connected accounts found for user ${userId}, using the first one. Pass connectedAccountId to select a specific account.`
329
+ );
330
+ expect(result).toEqual({ triggerId: mockTriggerUpsertResponse.trigger_id });
331
+ });
332
+
333
+ it('should throw validation error for invalid body parameters', async () => {
334
+ const invalidBody = {
335
+ connectedAccountId: 123, // should be string
336
+ triggerConfig: null,
337
+ };
338
+
339
+ await expect(triggers.create(userId, slug, invalidBody as any)).rejects.toThrow(
340
+ ValidationError
341
+ );
342
+ expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
343
+ });
344
+
345
+ it('should throw error when trigger type is not found', async () => {
346
+ mockClient.triggersTypes.retrieve.mockRejectedValue(
347
+ new APIError(400, 'Trigger type not found', 'Trigger type not found', new Headers())
348
+ );
349
+
350
+ await expect(triggers.create(userId, slug, body)).rejects.toThrow(
351
+ ComposioTriggerTypeNotFoundError
352
+ );
353
+ expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
354
+ });
355
+
356
+ it('should throw error when no connected accounts are found', async () => {
357
+ mockClient.connectedAccounts.list.mockResolvedValue({
358
+ items: [],
359
+ });
360
+
361
+ await expect(triggers.create(userId, slug, body)).rejects.toThrow(
362
+ 'No connected account found for user user-123'
363
+ );
364
+ expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
365
+ });
366
+
367
+ it('should throw error when provided connected account ID is not found', async () => {
368
+ mockClient.connectedAccounts.list.mockResolvedValue({
369
+ items: [{ id: 'conn-456' }],
370
+ });
371
+
372
+ await expect(triggers.create(userId, slug, body)).rejects.toThrow(
373
+ 'Connected account ID conn-123 not found for user user-123'
374
+ );
375
+ expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
376
+ });
377
+
378
+ it('should throw error when connected accounts list request fails', async () => {
379
+ mockClient.connectedAccounts.list.mockRejectedValue(
380
+ new APIError(404, 'Not Connected Account', 'Not Connected Account', new Headers())
381
+ );
382
+
383
+ await expect(triggers.create(userId, slug, body)).rejects.toThrow(
384
+ ComposioConnectedAccountNotFoundError
385
+ );
386
+ expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
387
+ });
388
+
389
+ it('should throw validation error for invalid upsert response', async () => {
390
+ mockClient.connectedAccounts.list.mockResolvedValue({
391
+ items: [{ id: 'conn-123' }],
392
+ });
393
+ mockClient.triggerInstances.upsert.mockResolvedValue({
394
+ invalid_field: 'value',
395
+ });
396
+
397
+ await expect(triggers.create(userId, slug, body)).rejects.toThrow(ValidationError);
398
+ });
399
});
400
401
describe('update', () => {