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

next
ts 303 lines 11 KB
Raw
1 import { Option, Schema, SchemaTransformation } from 'effect';
2
3 /**
4 * Tolerant normalization of trigger-log API payloads.
5 *
6 * The `@composio/client` type (`Logs.TriggerListResponse.Data`) declares
7 * trigger metadata under `meta` in camelCase, but the API has historically
8 * served camelCase and snake_case variants at both the top level and under
9 * `meta`. Instead of mining those aliases with `as ... as Record` casts at
10 * every call site, payloads are decoded once at the API boundary into the
11 * canonical {@link TriggerLogRecord} shape.
12 *
13 * Decoding is deliberately lenient: wrongly-typed fields behave as absent and
14 * a completely garbage payload decodes to an empty record, so formatting
15 * falls back to `'-'` placeholders instead of failing the command.
16 */
17
18 /** Decodes to the string value when present, treating any other type as absent. */
19 const LenientString = Schema.Unknown.pipe(
20 Schema.decodeTo(
21 Schema.UndefinedOr(Schema.String),
22 SchemaTransformation.transform({
23 decode: value => (typeof value === 'string' ? value : undefined),
24 encode: value => value,
25 })
26 )
27 );
28
29 /** Decodes to the string or number value when present, treating any other type as absent. */
30 const LenientTimestamp = Schema.Unknown.pipe(
31 Schema.decodeTo(
32 Schema.UndefinedOr(Schema.Union([Schema.String, Schema.Number])),
33 SchemaTransformation.transform({
34 decode: value => (typeof value === 'string' || typeof value === 'number' ? value : undefined),
35 encode: value => value,
36 })
37 )
38 );
39
40 /**
41 * Every alias the CLI has ever mined from trigger logs. The same aliases can
42 * appear at the top level of a record and under its `meta` object.
43 */
44 const aliasFields = {
45 id: Schema.optional(LenientString),
46 logId: Schema.optional(LenientString),
47 log_id: Schema.optional(LenientString),
48 triggerId: Schema.optional(LenientString),
49 trigger_id: Schema.optional(LenientString),
50 triggerNanoId: Schema.optional(LenientString),
51 trigger_nano_id: Schema.optional(LenientString),
52 triggerName: Schema.optional(LenientString),
53 trigger_name: Schema.optional(LenientString),
54 status: Schema.optional(LenientString),
55 appName: Schema.optional(LenientString),
56 toolkit: Schema.optional(LenientString),
57 toolkit_key: Schema.optional(LenientString),
58 connectionId: Schema.optional(LenientString),
59 connection_id: Schema.optional(LenientString),
60 connectedAccountId: Schema.optional(LenientString),
61 entityId: Schema.optional(LenientString),
62 entity_id: Schema.optional(LenientString),
63 userId: Schema.optional(LenientString),
64 createdAt: Schema.optional(LenientTimestamp),
65 created_at: Schema.optional(LenientTimestamp),
66 };
67
68 const RawTriggerLogMeta = Schema.Struct({
69 ...aliasFields,
70 triggerProviderPayload: Schema.optional(Schema.Unknown),
71 triggerClientPayload: Schema.optional(Schema.Unknown),
72 triggerClientResponse: Schema.optional(Schema.Unknown),
73 triggerProviderResponse: Schema.optional(Schema.Unknown),
74 });
75 type RawTriggerLogMeta = typeof RawTriggerLogMeta.Type;
76
77 const decodeMetaOption = Schema.decodeUnknownOption(RawTriggerLogMeta);
78
79 /** Any non-record `meta` behaves like an absent one. */
80 const LenientMeta = Schema.Unknown.pipe(
81 Schema.decodeTo(
82 Schema.UndefinedOr(Schema.toType(RawTriggerLogMeta)),
83 SchemaTransformation.transform({
84 decode: value => Option.getOrUndefined(decodeMetaOption(value)),
85 encode: value => value,
86 })
87 )
88 );
89
90 const rawLevelFields = {
91 ...aliasFields,
92 payloadReceived: Schema.optional(Schema.Unknown),
93 payload: Schema.optional(Schema.Unknown),
94 response: Schema.optional(Schema.Unknown),
95 meta: Schema.optional(LenientMeta),
96 };
97
98 const RawTriggerLogLevel = Schema.Struct(rawLevelFields);
99 type RawTriggerLogLevel = typeof RawTriggerLogLevel.Type;
100
101 const decodeLevelOption = Schema.decodeUnknownOption(RawTriggerLogLevel);
102
103 /**
104 * `logs.triggers.retrieve` responses wrap the record under `log`. Any object
105 * there is used as the record (even one that yields no fields); everything
106 * else falls back to the top level.
107 */
108 const LenientNestedLog = Schema.Unknown.pipe(
109 Schema.decodeTo(
110 Schema.UndefinedOr(Schema.toType(RawTriggerLogLevel)),
111 SchemaTransformation.transform({
112 decode: value =>
113 typeof value === 'object' && value !== null
114 ? Option.getOrElse(decodeLevelOption(value), (): RawTriggerLogLevel => ({}))
115 : undefined,
116 encode: value => value,
117 })
118 )
119 );
120
121 const RawTriggerLog = Schema.Struct({
122 ...rawLevelFields,
123 log: Schema.optional(LenientNestedLog),
124 });
125
126 /**
127 * Canonical trigger-log shape consumed by the `logs triggers` formatting code.
128 *
129 * - Top-level fields hold the values exactly as the client type declares them
130 * (the plain list-table columns).
131 * - `detail` holds alias-resolved fields for the info block. Precedence: the
132 * listed aliases at the top level of the record first, then the same
133 * aliases under `meta`.
134 * - `table` holds the trigger columns of the list table, which historically
135 * resolved `meta` aliases first (nano id preferred over plain id) and only
136 * then the top level.
137 */
138 export const TriggerLogRecord = Schema.Struct({
139 id: Schema.optional(Schema.String),
140 appName: Schema.optional(Schema.String),
141 entityId: Schema.optional(Schema.String),
142 connectionId: Schema.optional(Schema.String),
143 createdAt: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
144 detail: Schema.Struct({
145 /** `id` → `logId` → `log_id`, top level then `meta`. */
146 logId: Schema.optional(Schema.String),
147 /** `triggerId` → `trigger_id`, top level then `meta`. */
148 triggerId: Schema.optional(Schema.String),
149 /** `triggerNanoId` → `trigger_nano_id`, top level then `meta`. */
150 triggerNanoId: Schema.optional(Schema.String),
151 /** `triggerName` → `trigger_name`, top level then `meta`. */
152 triggerName: Schema.optional(Schema.String),
153 /** `status`, top level then `meta`. */
154 status: Schema.optional(Schema.String),
155 /** `appName` → `toolkit` → `toolkit_key`, top level then `meta`. */
156 toolkit: Schema.optional(Schema.String),
157 /** `connectionId` → `connection_id` → `connectedAccountId`, top level then `meta`. */
158 connectionId: Schema.optional(Schema.String),
159 /** `entityId` → `entity_id` → `userId`, top level then `meta`. */
160 entityId: Schema.optional(Schema.String),
161 /** `createdAt` → `created_at`, top level then `meta`. */
162 createdAt: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
163 }),
164 table: Schema.Struct({
165 /** Nano id preferred over plain id; `meta` aliases before top-level ones. */
166 triggerId: Schema.optional(Schema.String),
167 /** `triggerName` → `trigger_name`, `meta` then top level. */
168 triggerName: Schema.optional(Schema.String),
169 }),
170 /**
171 * `meta.triggerProviderPayload` → `meta.triggerClientPayload` →
172 * `payloadReceived` → `payload` → `null`, JSON-parsed when it looks like JSON.
173 */
174 payload: Schema.Unknown,
175 /**
176 * `meta.triggerClientResponse` → `meta.triggerProviderResponse` →
177 * `response` → `null`, JSON-parsed when it looks like JSON.
178 */
179 response: Schema.Unknown,
180 });
181 export type TriggerLogRecord = typeof TriggerLogRecord.Type;
182
183 /** Parses strings that look like JSON objects/arrays, passing everything else through. */
184 export const parseMaybeJson = (value: unknown): unknown => {
185 if (typeof value !== 'string') return value;
186 const trimmed = value.trim();
187 if (
188 (trimmed.startsWith('{') && trimmed.endsWith('}')) ||
189 (trimmed.startsWith('[') && trimmed.endsWith(']'))
190 ) {
191 return Option.getOrElse(
192 Option.liftThrowable((input: string): unknown => JSON.parse(input))(trimmed),
193 () => value
194 );
195 }
196 return value;
197 };
198
199 const normalizeLevel = (level: RawTriggerLogLevel): TriggerLogRecord => {
200 const meta = level.meta;
201
202 return {
203 id: level.id,
204 appName: level.appName,
205 entityId: level.entityId,
206 connectionId: level.connectionId,
207 createdAt: level.createdAt,
208 detail: {
209 logId: level.id ?? level.logId ?? level.log_id ?? meta?.id ?? meta?.logId ?? meta?.log_id,
210 triggerId: level.triggerId ?? level.trigger_id ?? meta?.triggerId ?? meta?.trigger_id,
211 triggerNanoId:
212 level.triggerNanoId ??
213 level.trigger_nano_id ??
214 meta?.triggerNanoId ??
215 meta?.trigger_nano_id,
216 triggerName:
217 level.triggerName ?? level.trigger_name ?? meta?.triggerName ?? meta?.trigger_name,
218 status: level.status ?? meta?.status,
219 toolkit:
220 level.appName ??
221 level.toolkit ??
222 level.toolkit_key ??
223 meta?.appName ??
224 meta?.toolkit ??
225 meta?.toolkit_key,
226 connectionId:
227 level.connectionId ??
228 level.connection_id ??
229 level.connectedAccountId ??
230 meta?.connectionId ??
231 meta?.connection_id ??
232 meta?.connectedAccountId,
233 entityId:
234 level.entityId ??
235 level.entity_id ??
236 level.userId ??
237 meta?.entityId ??
238 meta?.entity_id ??
239 meta?.userId,
240 createdAt: level.createdAt ?? level.created_at ?? meta?.createdAt ?? meta?.created_at,
241 },
242 table: {
243 triggerId:
244 meta?.triggerNanoId ??
245 meta?.trigger_nano_id ??
246 meta?.triggerId ??
247 meta?.trigger_id ??
248 level.triggerNanoId ??
249 level.trigger_nano_id ??
250 level.triggerId ??
251 level.trigger_id,
252 triggerName:
253 meta?.triggerName ?? meta?.trigger_name ?? level.triggerName ?? level.trigger_name,
254 },
255 payload: parseMaybeJson(
256 meta?.triggerProviderPayload ??
257 meta?.triggerClientPayload ??
258 level.payloadReceived ??
259 level.payload ??
260 null
261 ),
262 response: parseMaybeJson(
263 meta?.triggerClientResponse ?? meta?.triggerProviderResponse ?? level.response ?? null
264 ),
265 };
266 };
267
268 const TriggerLogRecordFromRaw = RawTriggerLog.pipe(
269 Schema.decodeTo(
270 TriggerLogRecord,
271 SchemaTransformation.transform({
272 decode: raw => normalizeLevel(raw.log ?? raw),
273 encode: record => ({
274 id: record.id,
275 appName: record.appName,
276 entityId: record.entityId,
277 connectionId: record.connectionId,
278 createdAt: record.createdAt,
279 logId: record.detail.logId,
280 triggerId: record.detail.triggerId,
281 triggerNanoId: record.detail.triggerNanoId,
282 triggerName: record.detail.triggerName,
283 status: record.detail.status,
284 toolkit: record.detail.toolkit,
285 payload: record.payload,
286 response: record.response,
287 }),
288 })
289 )
290 );
291
292 const decodeTriggerLogRecordOption = Schema.decodeUnknownOption(TriggerLogRecordFromRaw);
293
294 /** Canonical record produced when a payload cannot be decoded at all. */
295 export const emptyTriggerLogRecord: TriggerLogRecord = normalizeLevel({});
296
297 /**
298 * Decodes an unknown trigger-log payload into the canonical
299 * {@link TriggerLogRecord}, falling back to {@link emptyTriggerLogRecord}
300 * (which formats as `'-'` placeholders) when the payload is not an object.
301 */
302 export const decodeTriggerLogRecord = (input: unknown): TriggerLogRecord =>
303 Option.getOrElse(decodeTriggerLogRecordOption(input), () => emptyTriggerLogRecord);