forked from triggerdotdev/trigger.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
335 lines (283 loc) · 8.34 KB
/
Copy pathindex.ts
File metadata and controls
335 lines (283 loc) · 8.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import { safeParseBody } from "@trigger.dev/integration-kit";
import {
ConnectionAuth,
EventSpecification,
ExternalSource,
ExternalSourceTrigger,
HandlerEvent,
IO,
IOTask,
IntegrationTaskKey,
Json,
Logger,
RunTaskErrorCallback,
RunTaskOptions,
TriggerIntegration,
retry,
} from "@trigger.dev/sdk";
import { createClient } from "@typeform/api-client";
import { createHmac } from "node:crypto";
import { z } from "zod";
import { SOURCE } from "./consts";
import { Forms } from "./forms";
import { formResponseExample } from "./payload-examples";
import { Responses } from "./responses";
import {
FormResponseEvent,
GetWebhookResponse,
TypeformIntegrationOptions,
TypeformSDK,
} from "./types";
import { Webhooks } from "./webhooks";
export * from "./types";
type TypeformSource = ReturnType<typeof createWebhookEventSource>;
type TypeformTrigger = ReturnType<typeof createWebhookEventTrigger>;
export type TypeformRunTask = InstanceType<typeof Typeform>["runTask"];
export class Typeform implements TriggerIntegration {
private _options: TypeformIntegrationOptions;
private _client?: TypeformSDK;
private _io?: IO;
private _connectionKey?: string;
constructor(private options: TypeformIntegrationOptions) {
if (Object.keys(options).includes("token") && !options.token) {
throw `Can't create Typeform integration (${options.id}) as token was undefined`;
}
this._options = options;
}
get authSource() {
return "LOCAL" as const;
}
get id() {
return this.options.id;
}
get metadata() {
return { id: "typeform", name: "Typeform" };
}
cloneForRun(io: IO, connectionKey: string, auth?: ConnectionAuth) {
const typeform = new Typeform(this._options);
typeform._io = io;
typeform._connectionKey = connectionKey;
typeform._client = createClient({ token: this._options.token });
return typeform;
}
runTask<T, TResult extends Json<T> | void>(
key: IntegrationTaskKey,
callback: (client: TypeformSDK, task: IOTask, io: IO) => Promise<TResult>,
options?: RunTaskOptions,
errorCallback?: RunTaskErrorCallback
): Promise<TResult> {
if (!this._io) throw new Error("No IO");
if (!this._connectionKey) throw new Error("No connection key");
return this._io.runTask(
key,
(task, io) => {
if (!this._client) throw new Error("No client");
return callback(this._client, task, io);
},
{
icon: "typeform",
retry: retry.standardBackoff,
...(options ?? {}),
connectionKey: this._connectionKey,
},
errorCallback
);
}
get forms() {
return new Forms(this.runTask.bind(this));
}
listForms = this.forms.list;
getForm = this.forms.get;
get responses() {
return new Responses(this.runTask.bind(this));
}
listResponses = this.responses.list;
/** @deprecated this is being replaced by responses.all */
getAllResponses = this.responses.all.bind(this.responses);
get webhooks() {
return new Webhooks(this.runTask.bind(this));
}
createWebhook = this.webhooks.create;
listWebhooks = this.webhooks.list;
updateWebhook = this.webhooks.update;
getWebhook = this.webhooks.get;
deleteWebhook = this.webhooks.delete;
get source(): TypeformSource {
return createWebhookEventSource(this);
}
get trigger(): TypeformTrigger {
return createWebhookEventTrigger(this.source);
}
onFormResponse(params: { uid: string; tag: string }) {
return this.trigger({
event: events.onFormResponse,
uid: params.uid,
tag: params.tag,
});
}
}
const onFormResponse: EventSpecification<FormResponseEvent> = {
name: "form_response",
title: "On issue",
source: SOURCE,
icon: "typeform",
examples: [formResponseExample],
parsePayload: (payload) => payload as FormResponseEvent,
runProperties: (payload) => [{ label: "Form ID", text: payload.form_response.form_id }],
};
export const events = {
onFormResponse,
};
type TypeformEvents = (typeof events)[keyof typeof events];
type CreateTypeformTriggerReturnType = <TEventSpecification extends TypeformEvents>(args: {
event: TEventSpecification;
uid: string;
tag: string;
}) => ExternalSourceTrigger<TEventSpecification, ReturnType<typeof createWebhookEventSource>>;
function createWebhookEventTrigger(
source: ReturnType<typeof createWebhookEventSource>
): CreateTypeformTriggerReturnType {
return <TEventSpecification extends TypeformEvents>({
event,
uid,
tag,
}: {
event: TEventSpecification;
uid: string;
tag: string;
}) => {
return new ExternalSourceTrigger({
event,
params: { uid, tag },
source,
options: {},
});
};
}
const WebhookSchema = z.object({
uid: z.string(),
tag: z.string(),
});
export function createWebhookEventSource(
integration: Typeform
): ExternalSource<Typeform, { uid: string; tag: string }, "HTTP", {}> {
return new ExternalSource("HTTP", {
id: "typeform.forms",
schema: WebhookSchema,
version: "0.1.1",
integration,
filter: (params) => {
return {
event_type: ["form_response"],
};
},
key: (params) => `${params.uid}/${params.tag}`,
properties: (params) => [
{
label: "Form ID",
text: params.uid,
},
{
label: "Tag",
text: params.tag,
},
],
handler: webhookHandler,
register: async (event, io, ctx) => {
const { params, source: httpSource } = event;
const registeredOptions = {
event: ["form_response"],
};
if (httpSource.active && isWebhookData(httpSource.data) && !httpSource.data.enabled) {
// Update the webhook to re-enable it
const newWebhookData = await io.integration.updateWebhook("update-webhook", {
uid: params.uid,
tag: params.tag,
url: httpSource.url,
enabled: true,
secret: httpSource.secret,
verifySSL: true,
});
return {
data: newWebhookData,
options: registeredOptions,
};
}
const createWebhook = async () => {
const newWebhookData = await io.integration.createWebhook("create-webhook", {
uid: params.uid,
tag: params.tag,
url: httpSource.url,
enabled: true,
secret: httpSource.secret,
verifySSL: true,
});
return {
data: newWebhookData,
options: registeredOptions,
};
};
try {
const existingWebhook = await io.integration.getWebhook("get-webhook", params);
if (existingWebhook.url !== httpSource.url) {
return createWebhook();
}
if (existingWebhook.enabled) {
return {
data: existingWebhook,
options: registeredOptions,
};
}
const newWebhookData = await io.integration.updateWebhook("update-webhook", {
uid: params.uid,
tag: params.tag,
url: httpSource.url,
enabled: true,
secret: httpSource.secret,
verifySSL: true,
});
return {
data: newWebhookData,
options: registeredOptions,
};
} catch (error) {
return createWebhook();
}
},
});
}
async function webhookHandler(event: HandlerEvent<"HTTP">, logger: Logger) {
logger.debug("[inside typeform integration] Handling typeform webhook handler");
const { rawEvent: request, source } = event;
if (!request.body) {
logger.debug("[inside typeform integration] No body found");
return;
}
const rawBody = await request.text();
const signature = request.headers.get("typeform-signature");
if (!signature) {
logger.debug("[inside typeform integration] No signature found");
return { events: [] };
}
const hash = createHmac("sha256", source.secret).update(rawBody).digest("base64");
const actualSig = `sha256=${hash}`;
if (signature !== actualSig) {
logger.debug("[inside typeform integration] Signature does not match, ignoring");
return { events: [] };
}
const payload = safeParseBody(rawBody);
return {
events: [
{
id: payload.event_id,
name: payload.event_type,
source: SOURCE,
payload,
context: {},
},
],
};
}
function isWebhookData(data: any): data is GetWebhookResponse {
return typeof data === "object" && data !== null && typeof data.id === "string";
}