1
import { Command, Options } from '@effect/cli';
2
+import { FileSystem } from '@effect/platform';
3
import { Deferred, Effect, Option, Runtime } from 'effect';
4
import path from 'node:path';
4
-import process from 'node:process';
5
-import { promises as fs } from 'node:fs';
5
import { requireAuth } from 'src/effects/require-auth';
6
import { TerminalUI } from 'src/services/terminal-ui';
7
import { TriggersRealtime } from 'src/services/triggers-realtime';
11
formatTriggerListenTableHeader,
12
formatTriggerListenTableRow,
13
} from '../format';
14
+import { parseCsv } from '../parse-csv';
15
import { parseTriggerListenEvent } from '../parse';
16
import type { TriggerListenFilters } from '../types';
17
73
Options.optional
74
);
75
76
-const parseCsv = (value: string): ReadonlyArray<string> =>
77
- value
78
- .split(',')
79
- .map(item => item.trim())
80
- .filter(Boolean);
81
-
76
const randomUUID = () => crypto.randomUUID();
77
78
const signWebhookPayload = async ({
128
129
const emitTableLine = (line: string, ui: TerminalUI): Effect.Effect<void> =>
130
Effect.gen(function* () {
137
- if (process.stdout.isTTY) {
138
- yield* Effect.sync(() => {
139
- process.stderr.write(`${line}\n`);
140
- });
141
- return;
142
- }
131
+ yield* ui.log.message(line);
132
yield* ui.output(line);
133
});
134
135
+/**
136
+ * Listen to realtime trigger events for your project.
137
+ *
138
+ * @example
139
+ * ```bash
140
+ * composio triggers listen --toolkits gmail --table
141
+ * composio triggers listen --trigger-slug GMAIL_NEW_GMAIL_MESSAGE --json --max-events 5
142
+ * composio triggers listen --forward "http://localhost:8080/webhook" --out events.jsonl
143
+ * ```
144
+ */
145
export const triggersCmd$Listen = Command.make(
146
'listen',
147
{
172
if (!(yield* requireAuth)) return;
173
174
const ui = yield* TerminalUI;
175
+ const fs = yield* FileSystem.FileSystem;
176
const realtime = yield* TriggersRealtime;
177
const runtime = yield* Effect.runtime<never>();
178
const forwardUrl = Option.getOrUndefined(forward);
183
184
if (outputFilePath) {
185
// Ensure output directory exists before listening.
186
- yield* Effect.tryPromise({
187
- try: async () => {
188
- await fs.mkdir(path.dirname(outputFilePath), { recursive: true });
189
- },
190
- catch: error => new Error(`Failed to prepare output file directory: ${String(error)}`),
191
- }).pipe(
192
- Effect.catchAll(error =>
193
- Effect.gen(function* () {
194
- yield* ui.log.error(String(error));
195
- return yield* Effect.fail(error);
196
- })
197
- )
198
- );
186
+ yield* fs
187
+ .makeDirectory(path.dirname(outputFilePath), { recursive: true })
188
+ .pipe(Effect.tapError(error => ui.log.error(String(error))));
189
}
190
191
const filters: TriggerListenFilters = {
202
- toolkits: Option.isSome(toolkits) ? parseCsv(toolkits.value) : undefined,
192
+ toolkits: Option.isSome(toolkits)
193
+ ? parseCsv(toolkits.value).map(x => x.toLowerCase())
194
+ : undefined,
195
triggerId: Option.getOrUndefined(triggerId),
196
connectedAccountId: Option.getOrUndefined(connectedAccountId),
205
- triggerSlug: Option.isSome(triggerSlug) ? parseCsv(triggerSlug.value) : undefined,
197
+ triggerSlug: Option.isSome(triggerSlug)
198
+ ? parseCsv(triggerSlug.value).map(x => x.toLowerCase())
199
+ : undefined,
200
userId: Option.getOrUndefined(userId),
201
};
202
226
if (outputFilePath) {
227
yield* ui.log.info(`Writing matching events to: ${outputFilePath}`);
228
}
235
- if (forwardUrl) {
236
- yield* ui.log.info(`Forwarding matching events to: ${forwardUrl}`);
237
- }
229
230
if (maxEventsLimit !== undefined) {
231
yield* ui.log.info(`Auto-stop after ${maxEventsLimit} matching events.`);
269
const logLine = `${payloadForForwarding}\n`;
270
271
if (outputFilePath) {
281
- yield* Effect.tryPromise({
282
- try: () => fs.appendFile(outputFilePath, logLine, 'utf8'),
283
- catch: error => new Error(`Failed writing to ${outputFilePath}: ${String(error)}`),
284
- }).pipe(Effect.catchAll(error => ui.log.warn(String(error))));
272
+ yield* fs
273
+ .writeFileString(outputFilePath, logLine, { flag: 'a' })
274
+ .pipe(Effect.catchAll(error => ui.log.warn(String(error))));
275
}
276
277
if (forwardUrl && webhookSecret) {
288
- const webhookId =
289
- typeof eventData.id === 'string' && eventData.id.length > 0
290
- ? eventData.id
291
- : randomUUID();
292
- const webhookTimestamp = `${Math.floor(Date.now() / 1000)}`;
293
- const webhookSignature = yield* Effect.tryPromise(() =>
294
- signWebhookPayload({
295
- secret: webhookSecret,
296
- webhookId,
297
- webhookTimestamp,
298
- payload: payloadForForwarding,
299
- })
300
- );
301
- const webhookVersion = detectWebhookPayloadVersion(eventData);
302
-
303
- yield* Effect.tryPromise({
304
- try: async () => {
305
- const response = await fetch(forwardUrl, {
306
- method: 'POST',
307
- headers: {
308
- 'content-type': 'application/json',
309
- 'webhook-id': webhookId,
310
- 'webhook-timestamp': webhookTimestamp,
311
- 'webhook-signature': webhookSignature,
312
- 'x-composio-webhook-version': webhookVersion,
313
- },
314
- body: payloadForForwarding,
315
- });
316
- if (!response.ok) {
317
- throw new Error(`Forwarding failed with HTTP ${response.status}`);
318
- }
319
- },
320
- catch: error =>
321
- new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
278
+ yield* Effect.gen(function* () {
279
+ const webhookId =
280
+ typeof eventData.id === 'string' && eventData.id.length > 0
281
+ ? eventData.id
282
+ : randomUUID();
283
+ const webhookTimestamp = `${Math.floor(Date.now() / 1000)}`;
284
+ const webhookSignature = yield* Effect.tryPromise({
285
+ try: () =>
286
+ signWebhookPayload({
287
+ secret: webhookSecret,
288
+ webhookId,
289
+ webhookTimestamp,
290
+ payload: payloadForForwarding,
291
+ }),
292
+ catch: error => new Error(`Failed to sign webhook payload: ${String(error)}`),
293
+ });
294
+ const webhookVersion = detectWebhookPayloadVersion(eventData);
295
+
296
+ yield* Effect.tryPromise({
297
+ try: async () => {
298
+ const response = await fetch(forwardUrl, {
299
+ method: 'POST',
300
+ headers: {
301
+ 'content-type': 'application/json',
302
+ 'webhook-id': webhookId,
303
+ 'webhook-timestamp': webhookTimestamp,
304
+ 'webhook-signature': webhookSignature,
305
+ 'x-composio-webhook-version': webhookVersion,
306
+ },
307
+ body: payloadForForwarding,
308
+ });
309
+ if (!response.ok) {
310
+ throw new Error(`Forwarding failed with HTTP ${response.status}`);
311
+ }
312
+ },
313
+ catch: error =>
314
+ new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
315
+ });
316
}).pipe(Effect.catchAll(error => ui.log.warn(String(error))));
317
}
318