@trigger.dev/sdk 0.2.22 → 2.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,14 +1,12 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
7
  var __export = (target, all) => {
10
- for (var name2 in all)
11
- __defProp(target, name2, { get: all[name2], enumerable: true });
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
12
10
  };
13
11
  var __copyProps = (to, from, except, desc) => {
14
12
  if (from && typeof from === "object" || typeof from === "function") {
@@ -18,10 +16,6 @@ var __copyProps = (to, from, except, desc) => {
18
16
  }
19
17
  return to;
20
18
  };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
- mod
24
- ));
25
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
20
  var __accessCheck = (obj, member, msg) => {
27
21
  if (!member.has(obj))
@@ -49,853 +43,174 @@ var __privateMethod = (obj, member, method) => {
49
43
  // src/index.ts
50
44
  var src_exports = {};
51
45
  __export(src_exports, {
52
- Trigger: () => Trigger,
53
- customEvent: () => customEvent,
54
- fetch: () => fetch2,
55
- getTriggerRun: () => getTriggerRun,
56
- scheduleEvent: () => scheduleEvent,
57
- secureString: () => secureString,
58
- sendEvent: () => sendEvent,
59
- webhookEvent: () => webhookEvent
46
+ CronTrigger: () => CronTrigger,
47
+ DynamicSchedule: () => DynamicSchedule,
48
+ DynamicTrigger: () => DynamicTrigger,
49
+ EventTrigger: () => EventTrigger,
50
+ ExternalSource: () => ExternalSource,
51
+ ExternalSourceTrigger: () => ExternalSourceTrigger,
52
+ IO: () => IO,
53
+ IOLogger: () => IOLogger,
54
+ IntervalTrigger: () => IntervalTrigger,
55
+ Job: () => Job,
56
+ MissingConnectionNotification: () => MissingConnectionNotification,
57
+ MissingConnectionResolvedNotification: () => MissingConnectionResolvedNotification,
58
+ ResumeWithTask: () => ResumeWithTask,
59
+ TriggerClient: () => TriggerClient,
60
+ authenticatedTask: () => authenticatedTask,
61
+ cronTrigger: () => cronTrigger,
62
+ eventTrigger: () => eventTrigger,
63
+ intervalTrigger: () => intervalTrigger,
64
+ missingConnectionNotification: () => missingConnectionNotification,
65
+ missingConnectionResolvedNotification: () => missingConnectionResolvedNotification,
66
+ omit: () => omit,
67
+ secureString: () => secureString
60
68
  });
61
69
  module.exports = __toCommonJS(src_exports);
62
70
 
63
- // ../common-schemas/src/json.ts
64
- var import_zod = require("zod");
65
- var LiteralSchema = import_zod.z.union([
66
- import_zod.z.string(),
67
- import_zod.z.number(),
68
- import_zod.z.boolean(),
69
- import_zod.z.null()
70
- ]);
71
- var JsonSchema = import_zod.z.lazy(() => import_zod.z.union([
72
- LiteralSchema,
73
- import_zod.z.array(JsonSchema),
74
- import_zod.z.record(JsonSchema)
75
- ]));
76
- var SerializableSchema = import_zod.z.union([
77
- import_zod.z.string(),
78
- import_zod.z.number(),
79
- import_zod.z.boolean(),
80
- import_zod.z.null(),
81
- import_zod.z.date(),
82
- import_zod.z.undefined()
83
- ]);
84
- var SerializableJsonSchema = import_zod.z.lazy(() => import_zod.z.union([
85
- SerializableSchema,
86
- import_zod.z.array(SerializableJsonSchema),
87
- import_zod.z.record(SerializableJsonSchema)
88
- ]));
89
-
90
- // ../common-schemas/src/error.ts
91
- var import_zod2 = require("zod");
92
- var ErrorSchema = import_zod2.z.object({
93
- name: import_zod2.z.string(),
94
- message: import_zod2.z.string(),
95
- stackTrace: import_zod2.z.string().optional()
96
- });
97
-
98
- // ../common-schemas/src/logs.ts
99
- var import_zod3 = require("zod");
100
- var LogMessageSchema = import_zod3.z.object({
101
- level: import_zod3.z.enum([
102
- "DEBUG",
103
- "INFO",
104
- "WARN",
105
- "ERROR"
106
- ]),
107
- message: import_zod3.z.string(),
108
- properties: JsonSchema.default({})
109
- });
110
-
111
- // ../common-schemas/src/waits.ts
112
- var import_zod4 = require("zod");
113
- var DelaySchema = import_zod4.z.object({
114
- type: import_zod4.z.literal("DELAY"),
115
- seconds: import_zod4.z.number().optional(),
116
- minutes: import_zod4.z.number().optional(),
117
- hours: import_zod4.z.number().optional(),
118
- days: import_zod4.z.number().optional()
119
- });
120
- var ScheduledForSchema = import_zod4.z.object({
121
- type: import_zod4.z.literal("SCHEDULE_FOR"),
122
- scheduledFor: import_zod4.z.string().datetime()
123
- });
124
- var WaitSchema = import_zod4.z.discriminatedUnion("type", [
125
- DelaySchema,
126
- ScheduledForSchema
127
- ]);
128
-
129
- // ../common-schemas/src/events.ts
130
- var import_zod5 = require("zod");
131
- var CustomEventSchema = import_zod5.z.object({
132
- name: import_zod5.z.string(),
133
- payload: JsonSchema,
134
- context: JsonSchema.optional(),
135
- timestamp: import_zod5.z.string().datetime().optional(),
136
- delay: import_zod5.z.union([
137
- import_zod5.z.object({
138
- seconds: import_zod5.z.number().int()
139
- }),
140
- import_zod5.z.object({
141
- minutes: import_zod5.z.number().int()
142
- }),
143
- import_zod5.z.object({
144
- hours: import_zod5.z.number().int()
145
- }),
146
- import_zod5.z.object({
147
- days: import_zod5.z.number().int()
148
- }),
149
- import_zod5.z.object({
150
- until: import_zod5.z.string().datetime()
151
- })
152
- ]).optional()
153
- });
154
- var SerializableCustomEventSchema = import_zod5.z.object({
155
- name: import_zod5.z.string(),
156
- payload: SerializableJsonSchema,
157
- context: SerializableJsonSchema.optional(),
158
- timestamp: import_zod5.z.string().datetime().optional(),
159
- delay: import_zod5.z.union([
160
- import_zod5.z.object({
161
- seconds: import_zod5.z.number().int()
162
- }),
163
- import_zod5.z.object({
164
- minutes: import_zod5.z.number().int()
165
- }),
166
- import_zod5.z.object({
167
- hours: import_zod5.z.number().int()
168
- }),
169
- import_zod5.z.object({
170
- days: import_zod5.z.number().int()
171
- }),
172
- import_zod5.z.object({
173
- until: import_zod5.z.date()
174
- })
175
- ]).optional()
176
- });
177
- var EventMatcherSchema = import_zod5.z.union([
178
- import_zod5.z.array(import_zod5.z.string()),
179
- import_zod5.z.array(import_zod5.z.number()),
180
- import_zod5.z.array(import_zod5.z.boolean())
181
- ]);
182
- var EventFilterSchema = import_zod5.z.lazy(() => import_zod5.z.record(import_zod5.z.union([
183
- EventMatcherSchema,
184
- EventFilterSchema
185
- ])));
186
- var ScheduledEventPayloadSchema = import_zod5.z.object({
187
- lastRunAt: import_zod5.z.coerce.date().optional(),
188
- scheduledTime: import_zod5.z.coerce.date()
189
- });
190
- var ScheduleSourceRateSchema = import_zod5.z.object({
191
- rateOf: import_zod5.z.union([
192
- import_zod5.z.object({
193
- minutes: import_zod5.z.number().min(1).max(1440).int()
194
- }),
195
- import_zod5.z.object({
196
- hours: import_zod5.z.number().min(1).max(720).int()
197
- }),
198
- import_zod5.z.object({
199
- days: import_zod5.z.number().min(1).max(365).int()
200
- })
201
- ])
202
- });
203
- var ScheduleSourceCronSchema = import_zod5.z.object({
204
- cron: import_zod5.z.string()
205
- });
206
- var ScheduleSourceSchema = import_zod5.z.union([
207
- ScheduleSourceRateSchema,
208
- ScheduleSourceCronSchema
209
- ]);
210
- var ManualWebhookSourceSchema = import_zod5.z.object({
211
- verifyPayload: import_zod5.z.object({
212
- enabled: import_zod5.z.boolean(),
213
- header: import_zod5.z.string().optional()
214
- }),
215
- event: import_zod5.z.string()
216
- });
217
- var SlackBlockInteractionSourceSchema = import_zod5.z.object({
218
- type: import_zod5.z.literal("block_action"),
219
- blockId: import_zod5.z.string(),
220
- actionIds: import_zod5.z.array(import_zod5.z.string())
221
- });
222
- var SlackViewSubmissionInteractionSourceSchema = import_zod5.z.object({
223
- type: import_zod5.z.literal("view_submission"),
224
- callbackIds: import_zod5.z.array(import_zod5.z.string())
225
- });
226
- var SlackInteractionSourceSchema = import_zod5.z.discriminatedUnion("type", [
227
- SlackBlockInteractionSourceSchema,
228
- SlackViewSubmissionInteractionSourceSchema
229
- ]);
230
-
231
- // ../common-schemas/src/triggers.ts
232
- var import_zod6 = require("zod");
233
- var CustomEventTriggerSchema = import_zod6.z.object({
234
- type: import_zod6.z.literal("CUSTOM_EVENT"),
235
- service: import_zod6.z.literal("trigger"),
236
- name: import_zod6.z.string(),
237
- filter: EventFilterSchema,
238
- schema: JsonSchema.optional()
239
- });
240
- var WebhookEventTriggerSchema = import_zod6.z.object({
241
- type: import_zod6.z.literal("WEBHOOK"),
242
- service: import_zod6.z.string(),
243
- name: import_zod6.z.string(),
244
- filter: EventFilterSchema,
245
- source: JsonSchema.optional(),
246
- manualRegistration: import_zod6.z.boolean().default(false),
247
- schema: JsonSchema.optional()
248
- });
249
- var HttpEventTriggerSchema = import_zod6.z.object({
250
- type: import_zod6.z.literal("HTTP_ENDPOINT"),
251
- service: import_zod6.z.literal("trigger"),
252
- name: import_zod6.z.string(),
253
- filter: EventFilterSchema
254
- });
255
- var ScheduledEventTriggerSchema = import_zod6.z.object({
256
- type: import_zod6.z.literal("SCHEDULE"),
257
- service: import_zod6.z.literal("scheduler"),
258
- name: import_zod6.z.string(),
259
- source: ScheduleSourceSchema
260
- });
261
- var SlackInteractionTriggerSchema = import_zod6.z.object({
262
- type: import_zod6.z.literal("SLACK_INTERACTION"),
263
- service: import_zod6.z.literal("slack"),
264
- name: import_zod6.z.string(),
265
- filter: EventFilterSchema,
266
- source: SlackInteractionSourceSchema
267
- });
268
- var TriggerMetadataSchema = import_zod6.z.discriminatedUnion("type", [
269
- CustomEventTriggerSchema,
270
- WebhookEventTriggerSchema,
271
- HttpEventTriggerSchema,
272
- ScheduledEventTriggerSchema,
273
- SlackInteractionTriggerSchema
274
- ]);
275
-
276
- // ../common-schemas/src/fetch.ts
277
- var import_zod7 = require("zod");
278
- var SecureStringSchema = import_zod7.z.object({
279
- __secureString: import_zod7.z.literal(true),
280
- strings: import_zod7.z.array(import_zod7.z.string()),
281
- interpolations: import_zod7.z.array(import_zod7.z.string())
282
- });
283
- var RetrySchema = import_zod7.z.object({
284
- enabled: import_zod7.z.boolean().default(true),
285
- factor: import_zod7.z.number().default(1.8),
286
- maxTimeout: import_zod7.z.number().default(6e4),
287
- minTimeout: import_zod7.z.number().default(1e3),
288
- maxAttempts: import_zod7.z.number().default(10),
289
- statusCodes: import_zod7.z.array(import_zod7.z.number()).default([
290
- 408,
291
- 429,
292
- 500,
293
- 502,
294
- 503,
295
- 504
296
- ])
297
- });
298
- var FetchRequestSchema = import_zod7.z.object({
299
- url: import_zod7.z.string(),
300
- headers: import_zod7.z.record(import_zod7.z.union([
301
- import_zod7.z.string(),
302
- SecureStringSchema
303
- ])).optional(),
304
- method: import_zod7.z.enum([
305
- "GET",
306
- "POST",
307
- "PUT",
308
- "DELETE",
309
- "PATCH",
310
- "HEAD",
311
- "OPTIONS",
312
- "TRACE"
313
- ]),
314
- body: import_zod7.z.any(),
315
- retry: RetrySchema.optional()
316
- });
317
- var FetchOutputSchema = import_zod7.z.object({
318
- status: import_zod7.z.number(),
319
- ok: import_zod7.z.boolean(),
320
- headers: import_zod7.z.record(import_zod7.z.string()),
321
- body: import_zod7.z.any().optional()
322
- });
323
- var FetchResponseSchema = import_zod7.z.object({
324
- status: import_zod7.z.number(),
325
- headers: import_zod7.z.record(import_zod7.z.string()),
326
- body: import_zod7.z.any().optional()
327
- });
328
-
329
- // ../common-schemas/src/runOnce.ts
330
- var import_zod8 = require("zod");
331
- var InitializeRunOnceSchema = import_zod8.z.object({
332
- type: import_zod8.z.enum([
333
- "REMOTE",
334
- "LOCAL_ONLY"
335
- ])
336
- });
337
- var CompleteRunOnceSchema = import_zod8.z.object({
338
- type: import_zod8.z.enum([
339
- "REMOTE",
340
- "LOCAL_ONLY"
341
- ]),
342
- idempotencyKey: import_zod8.z.string(),
343
- output: import_zod8.z.string().optional()
344
- });
345
- var ResolveRunOnceOuputSchema = import_zod8.z.object({
346
- idempotencyKey: import_zod8.z.string(),
347
- hasRun: import_zod8.z.boolean(),
348
- output: SerializableJsonSchema.optional()
349
- });
350
-
351
- // ../common-schemas/src/kv.ts
352
- var import_zod9 = require("zod");
353
- var KVGetSchema = import_zod9.z.object({
354
- key: import_zod9.z.string(),
355
- namespace: import_zod9.z.string()
356
- });
357
- var KVDeleteSchema = import_zod9.z.object({
358
- key: import_zod9.z.string(),
359
- namespace: import_zod9.z.string()
360
- });
361
- var KVSetSchema = import_zod9.z.object({
362
- key: import_zod9.z.string(),
363
- namespace: import_zod9.z.string(),
364
- value: SerializableJsonSchema
365
- });
366
-
367
- // src/events.ts
368
- var import_zod10 = require("zod");
369
- var import_slug = __toESM(require("slug"));
370
- var import_zod_to_json_schema = __toESM(require("zod-to-json-schema"));
371
- function customEvent(options) {
372
- const schema = options.schema ?? import_zod10.z.any();
373
- return {
374
- metadata: {
375
- type: "CUSTOM_EVENT",
376
- service: "trigger",
377
- name: options.name,
378
- filter: {
379
- event: [
380
- options.name
381
- ],
382
- payload: options.filter ?? {}
383
- },
384
- schema: (0, import_zod_to_json_schema.default)(schema)
385
- },
386
- schema
387
- };
388
- }
389
- __name(customEvent, "customEvent");
390
- function scheduleEvent(options) {
391
- return {
392
- metadata: {
393
- type: "SCHEDULE",
394
- service: "scheduler",
395
- name: "scheduled-event",
396
- source: options
397
- },
398
- schema: ScheduledEventPayloadSchema
399
- };
400
- }
401
- __name(scheduleEvent, "scheduleEvent");
402
- function webhookEvent(options) {
403
- const schema = options.schema ?? import_zod10.z.any();
404
- return {
405
- metadata: {
406
- type: "WEBHOOK",
407
- service: (0, import_slug.default)(options.service),
408
- name: options.eventName,
409
- filter: {
410
- service: [
411
- (0, import_slug.default)(options.service)
412
- ],
413
- payload: options.filter ?? {},
414
- event: [
415
- options.eventName
416
- ]
417
- },
418
- source: {
419
- verifyPayload: options.verifyPayload ?? {
420
- enabled: false
421
- },
422
- event: options.eventName
423
- },
424
- manualRegistration: true,
425
- schema: (0, import_zod_to_json_schema.default)(schema)
426
- },
427
- schema
428
- };
71
+ // src/utils.ts
72
+ function slugifyId(input) {
73
+ const replaceSpacesWithDash = input.toLowerCase().replace(/\s+/g, "-");
74
+ const removeNonUrlSafeChars = replaceSpacesWithDash.replace(/[^a-zA-Z0-9-._~]/g, "");
75
+ return removeNonUrlSafeChars;
429
76
  }
430
- __name(webhookEvent, "webhookEvent");
77
+ __name(slugifyId, "slugifyId");
431
78
 
432
- // ../internal-bridge/src/schemas/host.ts
433
- var import_zod11 = require("zod");
434
- var HostRPCSchema = {
435
- TRIGGER_WORKFLOW: {
436
- request: import_zod11.z.object({
437
- id: import_zod11.z.string(),
438
- trigger: import_zod11.z.object({
439
- input: JsonSchema.default({}),
440
- context: JsonSchema.default({})
441
- }),
442
- meta: import_zod11.z.object({
443
- environment: import_zod11.z.string(),
444
- workflowId: import_zod11.z.string(),
445
- organizationId: import_zod11.z.string(),
446
- apiKey: import_zod11.z.string(),
447
- isTest: import_zod11.z.boolean().default(false),
448
- appOrigin: import_zod11.z.string(),
449
- attempt: import_zod11.z.number().optional()
450
- })
451
- }),
452
- response: import_zod11.z.boolean()
453
- },
454
- RESOLVE_REQUEST: {
455
- request: import_zod11.z.object({
456
- id: import_zod11.z.string(),
457
- key: import_zod11.z.string(),
458
- output: JsonSchema.default({}),
459
- meta: import_zod11.z.object({
460
- environment: import_zod11.z.string(),
461
- workflowId: import_zod11.z.string(),
462
- organizationId: import_zod11.z.string(),
463
- apiKey: import_zod11.z.string(),
464
- runId: import_zod11.z.string()
465
- })
466
- }),
467
- response: import_zod11.z.boolean()
468
- },
469
- RESOLVE_DELAY: {
470
- request: import_zod11.z.object({
471
- id: import_zod11.z.string(),
472
- key: import_zod11.z.string(),
473
- meta: import_zod11.z.object({
474
- environment: import_zod11.z.string(),
475
- workflowId: import_zod11.z.string(),
476
- organizationId: import_zod11.z.string(),
477
- apiKey: import_zod11.z.string(),
478
- runId: import_zod11.z.string()
479
- })
480
- }),
481
- response: import_zod11.z.boolean()
482
- },
483
- REJECT_REQUEST: {
484
- request: import_zod11.z.object({
485
- id: import_zod11.z.string(),
486
- key: import_zod11.z.string(),
487
- error: JsonSchema.default({}),
488
- meta: import_zod11.z.object({
489
- environment: import_zod11.z.string(),
490
- workflowId: import_zod11.z.string(),
491
- organizationId: import_zod11.z.string(),
492
- apiKey: import_zod11.z.string(),
493
- runId: import_zod11.z.string()
494
- })
495
- }),
496
- response: import_zod11.z.boolean()
497
- },
498
- RESOLVE_FETCH_REQUEST: {
499
- request: import_zod11.z.object({
500
- id: import_zod11.z.string(),
501
- key: import_zod11.z.string(),
502
- output: FetchOutputSchema,
503
- meta: import_zod11.z.object({
504
- environment: import_zod11.z.string(),
505
- workflowId: import_zod11.z.string(),
506
- organizationId: import_zod11.z.string(),
507
- apiKey: import_zod11.z.string(),
508
- runId: import_zod11.z.string()
509
- })
510
- }),
511
- response: import_zod11.z.boolean()
512
- },
513
- REJECT_FETCH_REQUEST: {
514
- request: import_zod11.z.object({
515
- id: import_zod11.z.string(),
516
- key: import_zod11.z.string(),
517
- error: JsonSchema.default({}),
518
- meta: import_zod11.z.object({
519
- environment: import_zod11.z.string(),
520
- workflowId: import_zod11.z.string(),
521
- organizationId: import_zod11.z.string(),
522
- apiKey: import_zod11.z.string(),
523
- runId: import_zod11.z.string()
524
- })
525
- }),
526
- response: import_zod11.z.boolean()
527
- },
528
- RESOLVE_RUN_ONCE: {
529
- request: import_zod11.z.object({
530
- id: import_zod11.z.string(),
531
- key: import_zod11.z.string(),
532
- output: ResolveRunOnceOuputSchema,
533
- meta: import_zod11.z.object({
534
- environment: import_zod11.z.string(),
535
- workflowId: import_zod11.z.string(),
536
- organizationId: import_zod11.z.string(),
537
- apiKey: import_zod11.z.string(),
538
- runId: import_zod11.z.string()
539
- })
540
- }),
541
- response: import_zod11.z.boolean()
542
- },
543
- RESOLVE_KV_GET: {
544
- request: import_zod11.z.object({
545
- key: import_zod11.z.string(),
546
- output: SerializableJsonSchema,
547
- meta: import_zod11.z.object({
548
- environment: import_zod11.z.string(),
549
- workflowId: import_zod11.z.string(),
550
- organizationId: import_zod11.z.string(),
551
- apiKey: import_zod11.z.string(),
552
- runId: import_zod11.z.string()
553
- })
554
- }),
555
- response: import_zod11.z.boolean()
556
- },
557
- RESOLVE_KV_SET: {
558
- request: import_zod11.z.object({
559
- key: import_zod11.z.string(),
560
- meta: import_zod11.z.object({
561
- environment: import_zod11.z.string(),
562
- workflowId: import_zod11.z.string(),
563
- organizationId: import_zod11.z.string(),
564
- apiKey: import_zod11.z.string(),
565
- runId: import_zod11.z.string()
566
- })
567
- }),
568
- response: import_zod11.z.boolean()
569
- },
570
- RESOLVE_KV_DELETE: {
571
- request: import_zod11.z.object({
572
- key: import_zod11.z.string(),
573
- meta: import_zod11.z.object({
574
- environment: import_zod11.z.string(),
575
- workflowId: import_zod11.z.string(),
576
- organizationId: import_zod11.z.string(),
577
- apiKey: import_zod11.z.string(),
578
- runId: import_zod11.z.string()
579
- })
580
- }),
581
- response: import_zod11.z.boolean()
79
+ // src/job.ts
80
+ var _validate, validate_fn;
81
+ var Job = class {
82
+ constructor(client, options) {
83
+ __privateAdd(this, _validate);
84
+ this.client = client;
85
+ this.options = options;
86
+ __privateMethod(this, _validate, validate_fn).call(this);
87
+ client.attach(this);
582
88
  }
583
- };
584
-
585
- // ../internal-bridge/src/schemas/server.ts
586
- var import_zod12 = require("zod");
587
- var ServerRPCSchema = {
588
- INITIALIZE_DELAY: {
589
- request: import_zod12.z.object({
590
- runId: import_zod12.z.string(),
591
- key: import_zod12.z.string(),
592
- wait: WaitSchema,
593
- timestamp: import_zod12.z.string()
594
- }),
595
- response: import_zod12.z.boolean()
596
- },
597
- SEND_REQUEST: {
598
- request: import_zod12.z.object({
599
- runId: import_zod12.z.string(),
600
- key: import_zod12.z.string(),
601
- request: import_zod12.z.object({
602
- service: import_zod12.z.string(),
603
- endpoint: import_zod12.z.string(),
604
- params: import_zod12.z.any(),
605
- version: import_zod12.z.string().optional()
606
- }),
607
- timestamp: import_zod12.z.string()
608
- }),
609
- response: import_zod12.z.boolean()
610
- },
611
- SEND_FETCH: {
612
- request: import_zod12.z.object({
613
- runId: import_zod12.z.string(),
614
- key: import_zod12.z.string(),
615
- fetch: FetchRequestSchema,
616
- timestamp: import_zod12.z.string()
617
- }),
618
- response: import_zod12.z.boolean()
619
- },
620
- SEND_LOG: {
621
- request: import_zod12.z.object({
622
- runId: import_zod12.z.string(),
623
- key: import_zod12.z.string(),
624
- log: import_zod12.z.object({
625
- message: import_zod12.z.string(),
626
- level: import_zod12.z.enum([
627
- "DEBUG",
628
- "INFO",
629
- "WARN",
630
- "ERROR"
631
- ]),
632
- properties: import_zod12.z.string().optional()
633
- }),
634
- timestamp: import_zod12.z.string()
635
- }),
636
- response: import_zod12.z.boolean()
637
- },
638
- SEND_EVENT: {
639
- request: import_zod12.z.object({
640
- runId: import_zod12.z.string(),
641
- key: import_zod12.z.string(),
642
- event: CustomEventSchema,
643
- timestamp: import_zod12.z.string()
644
- }),
645
- response: import_zod12.z.boolean()
646
- },
647
- INITIALIZE_HOST: {
648
- request: import_zod12.z.object({
649
- apiKey: import_zod12.z.string(),
650
- workflowId: import_zod12.z.string(),
651
- workflowName: import_zod12.z.string(),
652
- trigger: TriggerMetadataSchema,
653
- packageVersion: import_zod12.z.string(),
654
- packageName: import_zod12.z.string(),
655
- triggerTTL: import_zod12.z.number().optional()
656
- }),
657
- response: import_zod12.z.discriminatedUnion("type", [
658
- import_zod12.z.object({
659
- type: import_zod12.z.literal("success")
660
- }),
661
- import_zod12.z.object({
662
- type: import_zod12.z.literal("error"),
663
- message: import_zod12.z.string()
664
- })
665
- ]).nullable()
666
- },
667
- INITIALIZE_HOST_V2: {
668
- request: import_zod12.z.object({
669
- apiKey: import_zod12.z.string(),
670
- workflowId: import_zod12.z.string(),
671
- workflowName: import_zod12.z.string(),
672
- trigger: TriggerMetadataSchema,
673
- packageVersion: import_zod12.z.string(),
674
- packageName: import_zod12.z.string(),
675
- triggerTTL: import_zod12.z.number().optional(),
676
- metadata: SerializableJsonSchema.optional()
677
- }),
678
- response: import_zod12.z.discriminatedUnion("type", [
679
- import_zod12.z.object({
680
- type: import_zod12.z.literal("success"),
681
- data: import_zod12.z.object({
682
- workflow: import_zod12.z.object({
683
- id: import_zod12.z.string(),
684
- slug: import_zod12.z.string()
685
- }),
686
- environment: import_zod12.z.object({
687
- id: import_zod12.z.string(),
688
- slug: import_zod12.z.string()
689
- }),
690
- organization: import_zod12.z.object({
691
- id: import_zod12.z.string(),
692
- slug: import_zod12.z.string()
693
- }),
694
- isNew: import_zod12.z.boolean(),
695
- url: import_zod12.z.string()
696
- })
697
- }),
698
- import_zod12.z.object({
699
- type: import_zod12.z.literal("error"),
700
- message: import_zod12.z.string()
701
- })
702
- ]).nullable()
703
- },
704
- START_WORKFLOW_RUN: {
705
- request: import_zod12.z.object({
706
- runId: import_zod12.z.string(),
707
- timestamp: import_zod12.z.string()
708
- }),
709
- response: import_zod12.z.boolean()
710
- },
711
- COMPLETE_WORKFLOW_RUN: {
712
- request: import_zod12.z.object({
713
- runId: import_zod12.z.string(),
714
- output: import_zod12.z.string().optional(),
715
- timestamp: import_zod12.z.string()
716
- }),
717
- response: import_zod12.z.boolean()
718
- },
719
- SEND_WORKFLOW_ERROR: {
720
- request: import_zod12.z.object({
721
- runId: import_zod12.z.string(),
722
- error: import_zod12.z.object({
723
- name: import_zod12.z.string(),
724
- message: import_zod12.z.string(),
725
- stackTrace: import_zod12.z.string().optional()
726
- }),
727
- timestamp: import_zod12.z.string()
728
- }),
729
- response: import_zod12.z.boolean()
730
- },
731
- INITIALIZE_RUN_ONCE: {
732
- request: import_zod12.z.object({
733
- runId: import_zod12.z.string(),
734
- key: import_zod12.z.string(),
735
- timestamp: import_zod12.z.string(),
736
- runOnce: InitializeRunOnceSchema
737
- }),
738
- response: import_zod12.z.boolean()
739
- },
740
- COMPLETE_RUN_ONCE: {
741
- request: import_zod12.z.object({
742
- runId: import_zod12.z.string(),
743
- key: import_zod12.z.string(),
744
- timestamp: import_zod12.z.string(),
745
- runOnce: CompleteRunOnceSchema
746
- }),
747
- response: import_zod12.z.boolean()
748
- },
749
- SEND_KV_GET: {
750
- request: import_zod12.z.object({
751
- runId: import_zod12.z.string(),
752
- key: import_zod12.z.string(),
753
- timestamp: import_zod12.z.string(),
754
- get: import_zod12.z.object({
755
- namespace: import_zod12.z.string(),
756
- key: import_zod12.z.string()
757
- })
758
- }),
759
- response: import_zod12.z.boolean()
760
- },
761
- SEND_KV_SET: {
762
- request: import_zod12.z.object({
763
- runId: import_zod12.z.string(),
764
- key: import_zod12.z.string(),
765
- timestamp: import_zod12.z.string(),
766
- set: import_zod12.z.object({
767
- namespace: import_zod12.z.string(),
768
- key: import_zod12.z.string(),
769
- value: SerializableJsonSchema
770
- })
771
- }),
772
- response: import_zod12.z.boolean()
773
- },
774
- SEND_KV_DELETE: {
775
- request: import_zod12.z.object({
776
- runId: import_zod12.z.string(),
777
- key: import_zod12.z.string(),
778
- timestamp: import_zod12.z.string(),
779
- delete: import_zod12.z.object({
780
- namespace: import_zod12.z.string(),
781
- key: import_zod12.z.string()
782
- })
783
- }),
784
- response: import_zod12.z.boolean()
89
+ get id() {
90
+ return slugifyId(this.options.id);
91
+ }
92
+ get enabled() {
93
+ return typeof this.options.enabled === "boolean" ? this.options.enabled : true;
94
+ }
95
+ get name() {
96
+ return this.options.name;
97
+ }
98
+ get trigger() {
99
+ return this.options.trigger;
100
+ }
101
+ get version() {
102
+ return this.options.version;
103
+ }
104
+ get integrations() {
105
+ return Object.keys(this.options.integrations ?? {}).reduce((acc, key) => {
106
+ const integration = this.options.integrations[key];
107
+ if (!integration.client.usesLocalAuth) {
108
+ acc[key] = {
109
+ id: integration.id,
110
+ metadata: integration.metadata
111
+ };
112
+ }
113
+ return acc;
114
+ }, {});
115
+ }
116
+ toJSON() {
117
+ const internal = this.options.__internal;
118
+ return {
119
+ id: this.id,
120
+ name: this.name,
121
+ version: this.version,
122
+ event: this.trigger.event,
123
+ trigger: this.trigger.toJSON(),
124
+ integrations: this.integrations,
125
+ queue: this.options.queue,
126
+ startPosition: this.options.startPosition ?? "latest",
127
+ enabled: typeof this.options.enabled === "boolean" ? this.options.enabled : true,
128
+ preprocessRuns: this.trigger.preprocessRuns,
129
+ internal
130
+ };
785
131
  }
786
132
  };
133
+ __name(Job, "Job");
134
+ _validate = new WeakSet();
135
+ validate_fn = /* @__PURE__ */ __name(function() {
136
+ if (!this.version.match(/^(\d+)\.(\d+)\.(\d+)$/)) {
137
+ throw new Error(`Invalid job version: "${this.version}". Job versions must be valid semver versions.`);
138
+ }
139
+ }, "#validate");
787
140
 
788
- // ../internal-bridge/src/schemas/common.ts
789
- var import_zod13 = require("zod");
790
- var MESSAGE_META = import_zod13.z.object({
791
- data: import_zod13.z.any(),
792
- id: import_zod13.z.string(),
793
- type: import_zod13.z.union([
794
- import_zod13.z.literal("ACK"),
795
- import_zod13.z.literal("MESSAGE")
796
- ])
797
- });
798
- var TriggerEnvironmentSchema = import_zod13.z.enum([
799
- "live",
800
- "development"
801
- ]);
802
-
803
- // ../internal-bridge/src/zodRPC.ts
804
- var import_zod14 = require("zod");
805
- var import_node_crypto = require("crypto");
806
-
807
- // ../internal-bridge/src/logger.ts
141
+ // ../internal/src/logger.ts
808
142
  var logLevels = [
809
- "disabled",
810
- "error",
811
143
  "log",
144
+ "error",
812
145
  "warn",
813
146
  "info",
814
147
  "debug"
815
148
  ];
816
- var _name, _tags, _level, _formatName, formatName_fn, _formatTags, formatTags_fn;
817
- var Logger = class {
818
- constructor(name2, level = "log") {
819
- __privateAdd(this, _formatName);
820
- __privateAdd(this, _formatTags);
149
+ var _name, _level, _filteredKeys;
150
+ var _Logger = class {
151
+ constructor(name, level = "info", filteredKeys = []) {
821
152
  __privateAdd(this, _name, void 0);
822
- __privateAdd(this, _tags, void 0);
823
153
  __privateAdd(this, _level, void 0);
824
- if (typeof name2 === "string") {
825
- __privateSet(this, _name, name2);
826
- __privateSet(this, _tags, []);
827
- } else {
828
- const [n, ...tags] = name2;
829
- __privateSet(this, _name, n);
830
- __privateSet(this, _tags, tags);
831
- }
154
+ __privateAdd(this, _filteredKeys, []);
155
+ __privateSet(this, _name, name);
832
156
  __privateSet(this, _level, logLevels.indexOf(process.env.TRIGGER_LOG_LEVEL ?? level));
157
+ __privateSet(this, _filteredKeys, filteredKeys);
833
158
  }
834
- log(...args) {
835
- if (__privateGet(this, _level) < 1)
836
- return;
837
- console.log(`${__privateMethod(this, _formatName, formatName_fn).call(this)} `, ...[
838
- ...args,
839
- ...__privateMethod(this, _formatTags, formatTags_fn).call(this)
840
- ]);
159
+ filter(...keys) {
160
+ return new _Logger(__privateGet(this, _name), logLevels[__privateGet(this, _level)], keys);
841
161
  }
842
- logClean(...args) {
843
- if (__privateGet(this, _level) < 1)
162
+ log(...args) {
163
+ if (__privateGet(this, _level) < 0)
844
164
  return;
845
- console.log(`${__privateMethod(this, _formatName, formatName_fn).call(this)} `, ...args);
165
+ console.log(`[${formattedDateTime()}] [${__privateGet(this, _name)}] `, ...args);
846
166
  }
847
167
  error(...args) {
848
- if (__privateGet(this, _level) < 2)
168
+ if (__privateGet(this, _level) < 1)
849
169
  return;
850
- console.error(`[${formattedDateTime()}] ${__privateMethod(this, _formatName, formatName_fn).call(this)} `, ...[
851
- ...args,
852
- ...__privateMethod(this, _formatTags, formatTags_fn).call(this)
853
- ]);
170
+ console.error(`[${formattedDateTime()}] [${__privateGet(this, _name)}] `, ...args);
854
171
  }
855
172
  warn(...args) {
856
- if (__privateGet(this, _level) < 3)
173
+ if (__privateGet(this, _level) < 2)
857
174
  return;
858
- console.warn(`[${formattedDateTime()}] ${__privateMethod(this, _formatName, formatName_fn).call(this)} `, ...[
859
- ...args,
860
- ...__privateMethod(this, _formatTags, formatTags_fn).call(this)
861
- ]);
175
+ console.warn(`[${formattedDateTime()}] [${__privateGet(this, _name)}] `, ...args);
862
176
  }
863
177
  info(...args) {
864
- if (__privateGet(this, _level) < 4)
178
+ if (__privateGet(this, _level) < 3)
865
179
  return;
866
- console.info(`[${formattedDateTime()}] ${__privateMethod(this, _formatName, formatName_fn).call(this)} `, ...[
867
- ...args,
868
- ...__privateMethod(this, _formatTags, formatTags_fn).call(this)
869
- ]);
180
+ console.info(`[${formattedDateTime()}] [${__privateGet(this, _name)}] `, ...args);
870
181
  }
871
182
  debug(message, ...args) {
872
- if (__privateGet(this, _level) < 5)
183
+ if (__privateGet(this, _level) < 4)
873
184
  return;
874
185
  const structuredLog = {
875
- timestamp: formattedDateTime(),
186
+ timestamp: new Date(),
876
187
  name: __privateGet(this, _name),
877
- tags: __privateGet(this, _tags),
878
188
  message,
879
- args: structureArgs(args)
189
+ args: structureArgs(safeJsonClone(args), __privateGet(this, _filteredKeys))
880
190
  };
881
- console.debug(JSON.stringify(structuredLog));
191
+ console.debug(JSON.stringify(structuredLog, bigIntReplacer));
882
192
  }
883
193
  };
194
+ var Logger = _Logger;
884
195
  __name(Logger, "Logger");
885
196
  _name = new WeakMap();
886
- _tags = new WeakMap();
887
197
  _level = new WeakMap();
888
- _formatName = new WeakSet();
889
- formatName_fn = /* @__PURE__ */ __name(function() {
890
- if (Array.isArray(__privateGet(this, _name))) {
891
- return __privateGet(this, _name).map((name2) => `[${name2}]`).join("");
892
- }
893
- return `[${__privateGet(this, _name)}]`;
894
- }, "#formatName");
895
- _formatTags = new WeakSet();
896
- formatTags_fn = /* @__PURE__ */ __name(function() {
897
- return __privateGet(this, _tags).map((tag) => `[${tag}]`);
898
- }, "#formatTags");
198
+ _filteredKeys = new WeakMap();
199
+ function bigIntReplacer(_key, value) {
200
+ if (typeof value === "bigint") {
201
+ return value.toString();
202
+ }
203
+ return value;
204
+ }
205
+ __name(bigIntReplacer, "bigIntReplacer");
206
+ function safeJsonClone(obj) {
207
+ try {
208
+ return JSON.parse(JSON.stringify(obj, bigIntReplacer));
209
+ } catch (e) {
210
+ return obj;
211
+ }
212
+ }
213
+ __name(safeJsonClone, "safeJsonClone");
899
214
  function formattedDateTime() {
900
215
  const date = new Date();
901
216
  const hours = date.getHours();
@@ -909,1297 +224,2337 @@ function formattedDateTime() {
909
224
  return `${formattedHours}:${formattedMinutes}:${formattedSeconds}.${formattedMilliseconds}`;
910
225
  }
911
226
  __name(formattedDateTime, "formattedDateTime");
912
- function structureArgs(args) {
227
+ function structureArgs(args, filteredKeys = []) {
913
228
  if (args.length === 0) {
914
229
  return;
915
230
  }
916
231
  if (args.length === 1 && typeof args[0] === "object") {
917
- return args[0];
232
+ return filterKeys(JSON.parse(JSON.stringify(args[0], bigIntReplacer)), filteredKeys);
918
233
  }
919
234
  return args;
920
235
  }
921
236
  __name(structureArgs, "structureArgs");
922
-
923
- // ../internal-bridge/src/zodRPC.ts
924
- var RPCMessageSchema = import_zod14.z.object({
925
- id: import_zod14.z.string(),
926
- methodName: import_zod14.z.string(),
927
- data: import_zod14.z.any(),
928
- kind: import_zod14.z.enum([
929
- "CALL",
930
- "RESPONSE"
931
- ])
932
- });
933
- var _connection, _sender, _receiver, _handlers, _pendingCalls, _logger, _onMessage, onMessage_fn, _onCall, onCall_fn, _onResponse, onResponse_fn, _handleCall, handleCall_fn, _handleResponse, handleResponse_fn;
934
- var ZodRPC = class {
935
- constructor(options) {
936
- __privateAdd(this, _onMessage);
937
- __privateAdd(this, _onCall);
938
- __privateAdd(this, _onResponse);
939
- __privateAdd(this, _handleCall);
940
- __privateAdd(this, _handleResponse);
941
- __privateAdd(this, _connection, void 0);
942
- __privateAdd(this, _sender, void 0);
943
- __privateAdd(this, _receiver, void 0);
944
- __privateAdd(this, _handlers, void 0);
945
- __privateAdd(this, _pendingCalls, /* @__PURE__ */ new Map());
946
- __privateAdd(this, _logger, new Logger("ZodRPC"));
947
- __privateSet(this, _connection, options.connection);
948
- __privateSet(this, _sender, options.sender);
949
- __privateSet(this, _receiver, options.receiver);
950
- __privateSet(this, _handlers, options.handlers);
951
- __privateGet(this, _connection).onMessage.attach(__privateMethod(this, _onMessage, onMessage_fn).bind(this));
952
- }
953
- resetConnection(connection) {
954
- __privateGet(this, _connection).onMessage.detach();
955
- __privateSet(this, _connection, connection);
956
- __privateGet(this, _connection).onMessage.attach(__privateMethod(this, _onMessage, onMessage_fn).bind(this));
957
- }
958
- send(key, data) {
959
- __privateGet(this, _logger).debug("Sending call", {
960
- key,
961
- data
962
- });
963
- const id = generateStableId(__privateGet(this, _connection).id, key, data);
964
- const message = packageMessage({
965
- id,
966
- methodName: key,
967
- data
968
- });
969
- return new Promise((resolve, reject) => {
970
- __privateGet(this, _pendingCalls).set(id, (rawResponseText) => {
971
- try {
972
- const parsed = __privateGet(this, _sender)[key]["response"].parse(rawResponseText);
973
- return resolve(parsed);
974
- } catch (err) {
975
- reject(err);
976
- }
977
- });
978
- __privateGet(this, _connection).send(message).catch((err) => reject(err));
979
- });
237
+ function filterKeys(obj, keys) {
238
+ if (typeof obj !== "object" || obj === null) {
239
+ return obj;
980
240
  }
981
- };
982
- __name(ZodRPC, "ZodRPC");
983
- _connection = new WeakMap();
984
- _sender = new WeakMap();
985
- _receiver = new WeakMap();
986
- _handlers = new WeakMap();
987
- _pendingCalls = new WeakMap();
988
- _logger = new WeakMap();
989
- _onMessage = new WeakSet();
990
- onMessage_fn = /* @__PURE__ */ __name(async function(rawData) {
991
- try {
992
- const data = RPCMessageSchema.parse(JSON.parse(rawData));
993
- if (data.kind === "CALL") {
994
- await __privateMethod(this, _onCall, onCall_fn).call(this, data);
995
- }
996
- if (data.kind === "RESPONSE") {
997
- await __privateMethod(this, _onResponse, onResponse_fn).call(this, data);
998
- }
999
- } catch (err) {
1000
- __privateGet(this, _logger).error(err);
241
+ if (Array.isArray(obj)) {
242
+ return obj.map((item) => filterKeys(item, keys));
1001
243
  }
1002
- }, "#onMessage");
1003
- _onCall = new WeakSet();
1004
- onCall_fn = /* @__PURE__ */ __name(async function(message) {
1005
- try {
1006
- await __privateMethod(this, _handleCall, handleCall_fn).call(this, message);
1007
- } catch (callError) {
1008
- if (callError instanceof import_zod14.ZodError) {
1009
- __privateGet(this, _logger).error(`[ZodRPC] Received invalid call:
1010
- ${JSON.stringify(message)}: `, callError.errors);
1011
- } else {
1012
- __privateGet(this, _logger).error(`[ZodRPC] Error handling call:
1013
- ${JSON.stringify(message)}: `, callError);
244
+ const filteredObj = {};
245
+ for (const [key, value] of Object.entries(obj)) {
246
+ if (keys.includes(key)) {
247
+ continue;
1014
248
  }
249
+ filteredObj[key] = filterKeys(value, keys);
1015
250
  }
1016
- }, "#onCall");
1017
- _onResponse = new WeakSet();
1018
- onResponse_fn = /* @__PURE__ */ __name(async function(message1) {
1019
- try {
1020
- await __privateMethod(this, _handleResponse, handleResponse_fn).call(this, message1);
1021
- } catch (callError) {
1022
- if (callError instanceof import_zod14.ZodError) {
1023
- __privateGet(this, _logger).error(`[ZodRPC] Received invalid response
251
+ return filteredObj;
252
+ }
253
+ __name(filterKeys, "filterKeys");
1024
254
 
1025
- ${JSON.stringify(message1)}: `, callError.flatten());
1026
- } else {
1027
- __privateGet(this, _logger).error(`[ZodRPC] Error handling response
255
+ // ../internal/src/schemas/api.ts
256
+ var import_ulid = require("ulid");
257
+ var import_zod8 = require("zod");
1028
258
 
1029
- ${JSON.stringify(message1)}: `, callError);
1030
- }
1031
- }
1032
- }, "#onResponse");
1033
- _handleCall = new WeakSet();
1034
- handleCall_fn = /* @__PURE__ */ __name(async function(message2) {
1035
- const receiver = __privateGet(this, _receiver);
1036
- const methodName = message2.methodName;
1037
- const method = __privateGet(this, _receiver)[methodName];
1038
- if (!method) {
1039
- throw new Error(`There is no method for ${message2.methodName}`);
1040
- }
1041
- __privateGet(this, _logger).debug("Received call", {
1042
- message: message2
1043
- });
1044
- const inputs = method.request.parse(message2.data);
1045
- const handler = __privateGet(this, _handlers)[methodName];
1046
- const returnValue = await handler(inputs);
1047
- const preparedResponseText = packageResponse({
1048
- id: message2.id,
1049
- methodName,
1050
- data: returnValue
1051
- });
1052
- try {
1053
- await __privateGet(this, _connection).send(preparedResponseText);
1054
- } catch (err) {
1055
- __privateGet(this, _logger).error("Failed sending response", preparedResponseText, err);
1056
- }
1057
- return;
1058
- }, "#handleCall");
1059
- _handleResponse = new WeakSet();
1060
- handleResponse_fn = /* @__PURE__ */ __name(async function(message3) {
1061
- const responseCallback = __privateGet(this, _pendingCalls).get(message3.id);
1062
- if (!responseCallback)
1063
- return;
1064
- responseCallback(message3.data);
1065
- __privateGet(this, _pendingCalls).delete(message3.id);
1066
- }, "#handleResponse");
1067
- function generateStableId(connId, reqKey, reqData) {
1068
- const serializedData = JSON.stringify(reqData);
1069
- const inputString = connId + reqKey + serializedData;
1070
- const hash = (0, import_node_crypto.createHash)("sha256").update(inputString).digest("hex");
1071
- return hash;
1072
- }
1073
- __name(generateStableId, "generateStableId");
1074
- function packageMessage({ id, methodName, data }) {
1075
- const callerData = {
1076
- id,
1077
- kind: "CALL",
1078
- data,
1079
- methodName
1080
- };
1081
- return JSON.stringify(callerData);
1082
- }
1083
- __name(packageMessage, "packageMessage");
1084
- function packageResponse({ id, methodName, data }) {
1085
- const preparedResponseText = {
1086
- id,
1087
- kind: "RESPONSE",
1088
- methodName,
1089
- data
1090
- };
1091
- return JSON.stringify(preparedResponseText);
1092
- }
1093
- __name(packageResponse, "packageResponse");
259
+ // ../internal/src/schemas/integrations.ts
260
+ var import_zod = require("zod");
261
+ var ConnectionAuthSchema = import_zod.z.object({
262
+ type: import_zod.z.enum([
263
+ "oauth2"
264
+ ]),
265
+ accessToken: import_zod.z.string(),
266
+ scopes: import_zod.z.array(import_zod.z.string()).optional(),
267
+ additionalFields: import_zod.z.record(import_zod.z.string()).optional()
268
+ });
269
+ var IntegrationMetadataSchema = import_zod.z.object({
270
+ key: import_zod.z.string(),
271
+ title: import_zod.z.string(),
272
+ icon: import_zod.z.string()
273
+ });
274
+ var IntegrationConfigSchema = import_zod.z.object({
275
+ id: import_zod.z.string(),
276
+ metadata: IntegrationMetadataSchema
277
+ });
1094
278
 
1095
- // src/client.ts
1096
- var import_uuid2 = require("uuid");
1097
- var import_ws = require("ws");
1098
- var import_zod15 = require("zod");
279
+ // ../internal/src/schemas/properties.ts
280
+ var import_zod2 = require("zod");
281
+ var DisplayPropertySchema = import_zod2.z.object({
282
+ label: import_zod2.z.string(),
283
+ text: import_zod2.z.string(),
284
+ url: import_zod2.z.string().optional()
285
+ });
286
+ var DisplayPropertiesSchema = import_zod2.z.array(DisplayPropertySchema);
287
+ var StyleSchema = import_zod2.z.object({
288
+ style: import_zod2.z.enum([
289
+ "normal",
290
+ "minimal"
291
+ ]),
292
+ variant: import_zod2.z.string().optional()
293
+ });
1099
294
 
1100
- // package.json
1101
- var name = "@trigger.dev/sdk";
1102
- var version = "0.2.22";
295
+ // ../internal/src/schemas/json.ts
296
+ var import_zod3 = require("zod");
297
+ var LiteralSchema = import_zod3.z.union([
298
+ import_zod3.z.string(),
299
+ import_zod3.z.number(),
300
+ import_zod3.z.boolean(),
301
+ import_zod3.z.null()
302
+ ]);
303
+ var DeserializedJsonSchema = import_zod3.z.lazy(() => import_zod3.z.union([
304
+ LiteralSchema,
305
+ import_zod3.z.array(DeserializedJsonSchema),
306
+ import_zod3.z.record(DeserializedJsonSchema)
307
+ ]));
308
+ var SerializableSchema = import_zod3.z.union([
309
+ import_zod3.z.string(),
310
+ import_zod3.z.number(),
311
+ import_zod3.z.boolean(),
312
+ import_zod3.z.null(),
313
+ import_zod3.z.date(),
314
+ import_zod3.z.undefined(),
315
+ import_zod3.z.symbol()
316
+ ]);
317
+ var SerializableJsonSchema = import_zod3.z.lazy(() => import_zod3.z.union([
318
+ SerializableSchema,
319
+ import_zod3.z.array(SerializableJsonSchema),
320
+ import_zod3.z.record(SerializableJsonSchema)
321
+ ]));
1103
322
 
1104
- // src/connection.ts
1105
- var import_uuid = require("uuid");
1106
- var import_evt = require("evt");
1107
- var TimeoutError = class extends Error {
1108
- };
1109
- __name(TimeoutError, "TimeoutError");
1110
- var NotConnectedError = class extends Error {
1111
- };
1112
- __name(NotConnectedError, "NotConnectedError");
1113
- var _socket, _connectTimeout, _sendTimeout, _pingTimeout, _isAuthenticated, _timeouts, _isClosed, _pendingMessages, _logger2, _pingIntervalHandle, _pingIntervalMs, _closeUnresponsiveConnectionTimeoutMs, _startPingInterval, startPingInterval_fn, _ping, ping_fn;
1114
- var HostConnection = class {
1115
- constructor(socket, options) {
1116
- __privateAdd(this, _startPingInterval);
1117
- __privateAdd(this, _ping);
1118
- __privateAdd(this, _socket, void 0);
1119
- __privateAdd(this, _connectTimeout, void 0);
1120
- __privateAdd(this, _sendTimeout, void 0);
1121
- __privateAdd(this, _pingTimeout, void 0);
1122
- __privateAdd(this, _isAuthenticated, false);
1123
- __privateAdd(this, _timeouts, void 0);
1124
- __privateAdd(this, _isClosed, false);
1125
- __privateAdd(this, _pendingMessages, /* @__PURE__ */ new Map());
1126
- __privateAdd(this, _logger2, void 0);
1127
- __privateAdd(this, _pingIntervalHandle, void 0);
1128
- __privateAdd(this, _pingIntervalMs, 3e4);
1129
- __privateAdd(this, _closeUnresponsiveConnectionTimeoutMs, 3 * 60 * 1e3);
1130
- __privateSet(this, _socket, socket);
1131
- this.id = options?.id ?? (0, import_uuid.v4)();
1132
- this.onMessage = new import_evt.Evt();
1133
- this.onAuthenticated = new import_evt.Evt();
1134
- this.onClose = new import_evt.Evt();
1135
- this.onOpen = new import_evt.Evt();
1136
- this.onError = new import_evt.Evt();
1137
- __privateSet(this, _connectTimeout, options?.connectTimeout ?? 5e3);
1138
- __privateSet(this, _sendTimeout, options?.sendTimeout ?? 5e3);
1139
- __privateSet(this, _pingTimeout, options?.pingTimeout ?? 5e3);
1140
- __privateSet(this, _timeouts, /* @__PURE__ */ new Set());
1141
- __privateSet(this, _logger2, new Logger("trigger.dev connection"));
1142
- this.onClose.attach(() => {
1143
- __privateSet(this, _isClosed, true);
1144
- if (__privateGet(this, _pingIntervalHandle)) {
1145
- clearInterval(__privateGet(this, _pingIntervalHandle));
1146
- __privateSet(this, _pingIntervalHandle, void 0);
1147
- }
1148
- for (const timeout of __privateGet(this, _timeouts)) {
1149
- clearTimeout(timeout);
1150
- }
1151
- __privateGet(this, _timeouts).clear();
1152
- });
1153
- __privateGet(this, _socket).onopen = () => {
1154
- __privateSet(this, _isClosed, false);
1155
- this.onOpen.post();
1156
- __privateMethod(this, _startPingInterval, startPingInterval_fn).call(this);
1157
- };
1158
- __privateGet(this, _socket).onclose = (ev) => {
1159
- this.onClose.post([
1160
- ev.code,
1161
- ev.reason
1162
- ]);
1163
- };
1164
- __privateGet(this, _socket).onerror = (ev) => {
1165
- const message = "message" in ev ? ev.message : "Unknown error";
1166
- this.onError.post(new Error(message));
1167
- };
1168
- __privateGet(this, _socket).onmessage = (event) => {
1169
- if (__privateGet(this, _isClosed))
1170
- return;
1171
- const data = JSON.parse(event.data.toString());
1172
- const metadata = MESSAGE_META.parse(data);
1173
- if (metadata.type === "ACK") {
1174
- const pendingMessage = __privateGet(this, _pendingMessages).get(metadata.id);
1175
- if (pendingMessage) {
1176
- pendingMessage.onAckReceived();
1177
- __privateGet(this, _pendingMessages).delete(metadata.id);
1178
- }
1179
- }
1180
- if (metadata.type === "MESSAGE") {
1181
- socket.send(JSON.stringify({
1182
- type: "ACK",
1183
- id: metadata.id
1184
- }));
1185
- if (metadata.data === "AUTHENTICATED") {
1186
- __privateSet(this, _isAuthenticated, true);
1187
- this.onAuthenticated.post();
1188
- return;
1189
- }
1190
- this.onMessage.post(metadata.data);
1191
- }
1192
- };
1193
- if ("pong" in socket) {
1194
- socket.on("pong", (buf) => {
1195
- const id = buf.toString();
1196
- const pendingMessage = __privateGet(this, _pendingMessages).get(id);
1197
- if (pendingMessage?.data === "ping") {
1198
- pendingMessage.onAckReceived();
1199
- }
1200
- });
1201
- }
1202
- }
1203
- async connect() {
1204
- __privateGet(this, _logger2).debug("[connect] Attempting to connect");
1205
- return new Promise((resolve, reject) => {
1206
- if (__privateGet(this, _socket).readyState === __privateGet(this, _socket).OPEN && __privateGet(this, _isAuthenticated)) {
1207
- __privateGet(this, _logger2).debug("[connect] Already connected, resolving");
1208
- return resolve();
1209
- }
1210
- const failTimeout = setTimeout(() => {
1211
- __privateGet(this, _logger2).debug("[connect] Connection timed out, rejecting");
1212
- reject(new TimeoutError());
1213
- }, __privateGet(this, _connectTimeout));
1214
- __privateGet(this, _timeouts).add(failTimeout);
1215
- this.onAuthenticated.attach(() => {
1216
- clearTimeout(failTimeout);
1217
- __privateGet(this, _timeouts).delete(failTimeout);
1218
- __privateGet(this, _logger2).debug("[connect] Connected, resolving");
1219
- resolve();
1220
- });
1221
- });
1222
- }
1223
- async send(data) {
1224
- if (__privateGet(this, _isClosed))
1225
- throw new NotConnectedError();
1226
- return new Promise((resolve, reject) => {
1227
- const id = (0, import_uuid.v4)();
1228
- const failTimeout = setTimeout(() => {
1229
- reject(new TimeoutError());
1230
- }, __privateGet(this, _sendTimeout));
1231
- __privateGet(this, _timeouts).add(failTimeout);
1232
- __privateGet(this, _pendingMessages).set(id, {
1233
- data,
1234
- onAckReceived: () => {
1235
- clearTimeout(failTimeout);
1236
- __privateGet(this, _timeouts).delete(failTimeout);
1237
- resolve();
1238
- }
1239
- });
1240
- __privateGet(this, _socket).send(JSON.stringify({
1241
- id,
1242
- data,
1243
- type: "MESSAGE"
1244
- }));
1245
- });
1246
- }
1247
- close(code, reason) {
1248
- __privateSet(this, _isClosed, true);
1249
- this.onMessage.detach();
1250
- return __privateGet(this, _socket).close(code, reason);
1251
- }
1252
- };
1253
- __name(HostConnection, "HostConnection");
1254
- _socket = new WeakMap();
1255
- _connectTimeout = new WeakMap();
1256
- _sendTimeout = new WeakMap();
1257
- _pingTimeout = new WeakMap();
1258
- _isAuthenticated = new WeakMap();
1259
- _timeouts = new WeakMap();
1260
- _isClosed = new WeakMap();
1261
- _pendingMessages = new WeakMap();
1262
- _logger2 = new WeakMap();
1263
- _pingIntervalHandle = new WeakMap();
1264
- _pingIntervalMs = new WeakMap();
1265
- _closeUnresponsiveConnectionTimeoutMs = new WeakMap();
1266
- _startPingInterval = new WeakSet();
1267
- startPingInterval_fn = /* @__PURE__ */ __name(function() {
1268
- let lastSuccessfulPing = new Date();
1269
- __privateSet(this, _pingIntervalHandle, setInterval(async () => {
1270
- if (!__privateGet(this, _socket).OPEN) {
1271
- if (__privateGet(this, _pingIntervalHandle)) {
1272
- clearInterval(__privateGet(this, _pingIntervalHandle));
1273
- __privateSet(this, _pingIntervalHandle, void 0);
1274
- }
1275
- return;
1276
- }
1277
- try {
1278
- await __privateMethod(this, _ping, ping_fn).call(this);
1279
- lastSuccessfulPing = new Date();
1280
- } catch (err) {
1281
- __privateGet(this, _logger2).warn("Pong not received in time");
1282
- if (!(err instanceof TimeoutError)) {
1283
- __privateGet(this, _logger2).error(err);
1284
- }
1285
- if (lastSuccessfulPing.getTime() < new Date().getTime() - __privateGet(this, _closeUnresponsiveConnectionTimeoutMs)) {
1286
- __privateGet(this, _logger2).error("No pong received in last three minutes, closing connection to Trigger.dev and retrying...");
1287
- if (__privateGet(this, _pingIntervalHandle)) {
1288
- clearInterval(__privateGet(this, _pingIntervalHandle));
1289
- __privateSet(this, _pingIntervalHandle, void 0);
1290
- }
1291
- __privateGet(this, _socket).close();
1292
- }
1293
- }
1294
- }, __privateGet(this, _pingIntervalMs)));
1295
- }, "#startPingInterval");
1296
- _ping = new WeakSet();
1297
- ping_fn = /* @__PURE__ */ __name(async function() {
1298
- if (!__privateGet(this, _socket).OPEN) {
1299
- throw new NotConnectedError();
1300
- }
1301
- if (!("ping" in __privateGet(this, _socket))) {
1302
- throw new Error("ping not supported in this underlying websocket connection");
1303
- }
1304
- const socket = __privateGet(this, _socket);
1305
- return new Promise((resolve, reject) => {
1306
- const id = (0, import_uuid.v4)();
1307
- const failTimeout = setTimeout(() => {
1308
- reject(new TimeoutError("Pong not received in time"));
1309
- }, __privateGet(this, _pingTimeout));
1310
- __privateGet(this, _timeouts).add(failTimeout);
1311
- __privateGet(this, _pendingMessages).set(id, {
1312
- data: "ping",
1313
- onAckReceived: () => {
1314
- clearTimeout(failTimeout);
1315
- __privateGet(this, _timeouts).delete(failTimeout);
1316
- __privateGet(this, _logger2).debug(`Resolving ping`);
1317
- resolve();
1318
- }
1319
- });
1320
- __privateGet(this, _logger2).debug(`Sending ping ${id} to ${socket.url}`);
1321
- socket.ping(id, void 0, (err) => {
1322
- if (err) {
1323
- reject(err);
1324
- }
1325
- });
1326
- });
1327
- }, "#ping");
323
+ // ../internal/src/schemas/tasks.ts
324
+ var import_zod4 = require("zod");
325
+ var TaskStatusSchema = import_zod4.z.enum([
326
+ "PENDING",
327
+ "WAITING",
328
+ "RUNNING",
329
+ "COMPLETED",
330
+ "ERRORED"
331
+ ]);
332
+ var TaskSchema = import_zod4.z.object({
333
+ id: import_zod4.z.string(),
334
+ name: import_zod4.z.string(),
335
+ icon: import_zod4.z.string().optional().nullable(),
336
+ noop: import_zod4.z.boolean(),
337
+ startedAt: import_zod4.z.coerce.date().optional().nullable(),
338
+ completedAt: import_zod4.z.coerce.date().optional().nullable(),
339
+ delayUntil: import_zod4.z.coerce.date().optional().nullable(),
340
+ status: TaskStatusSchema,
341
+ description: import_zod4.z.string().optional().nullable(),
342
+ properties: import_zod4.z.array(DisplayPropertySchema).optional().nullable(),
343
+ params: DeserializedJsonSchema.optional().nullable(),
344
+ output: DeserializedJsonSchema.optional().nullable(),
345
+ error: import_zod4.z.string().optional().nullable(),
346
+ parentId: import_zod4.z.string().optional().nullable(),
347
+ style: StyleSchema.optional().nullable()
348
+ });
349
+ var ServerTaskSchema = TaskSchema.extend({
350
+ idempotencyKey: import_zod4.z.string()
351
+ });
352
+ var CachedTaskSchema = import_zod4.z.object({
353
+ id: import_zod4.z.string(),
354
+ idempotencyKey: import_zod4.z.string(),
355
+ status: TaskStatusSchema,
356
+ noop: import_zod4.z.boolean().default(false),
357
+ output: DeserializedJsonSchema.optional().nullable(),
358
+ parentId: import_zod4.z.string().optional().nullable()
359
+ });
1328
360
 
1329
- // src/localStorage.ts
1330
- var import_node_async_hooks = require("async_hooks");
1331
- var triggerRunLocalStorage = new import_node_async_hooks.AsyncLocalStorage();
361
+ // ../internal/src/schemas/triggers.ts
362
+ var import_zod7 = require("zod");
1332
363
 
1333
- // src/logger.ts
1334
- var ContextLogger = class {
1335
- constructor(callback) {
1336
- this.callback = callback;
1337
- }
1338
- debug(message, properties) {
1339
- return this.callback("DEBUG", message, properties);
1340
- }
1341
- info(message, properties) {
1342
- return this.callback("INFO", message, properties);
1343
- }
1344
- warn(message, properties) {
1345
- return this.callback("WARN", message, properties);
1346
- }
1347
- error(message, properties) {
364
+ // ../internal/src/schemas/eventFilter.ts
365
+ var import_zod5 = require("zod");
366
+ var EventMatcherSchema = import_zod5.z.union([
367
+ import_zod5.z.array(import_zod5.z.string()),
368
+ import_zod5.z.array(import_zod5.z.number()),
369
+ import_zod5.z.array(import_zod5.z.boolean())
370
+ ]);
371
+ var EventFilterSchema = import_zod5.z.lazy(() => import_zod5.z.record(import_zod5.z.union([
372
+ EventMatcherSchema,
373
+ EventFilterSchema
374
+ ])));
375
+ var EventRuleSchema = import_zod5.z.object({
376
+ event: import_zod5.z.string(),
377
+ source: import_zod5.z.string(),
378
+ payload: EventFilterSchema.optional(),
379
+ context: EventFilterSchema.optional()
380
+ });
381
+
382
+ // ../internal/src/schemas/schedules.ts
383
+ var import_zod6 = require("zod");
384
+ var ScheduledPayloadSchema = import_zod6.z.object({
385
+ ts: import_zod6.z.coerce.date(),
386
+ lastTimestamp: import_zod6.z.coerce.date().optional()
387
+ });
388
+ var IntervalOptionsSchema = import_zod6.z.object({
389
+ seconds: import_zod6.z.number().int().positive().min(60).max(86400)
390
+ });
391
+ var CronOptionsSchema = import_zod6.z.object({
392
+ cron: import_zod6.z.string()
393
+ });
394
+ var CronMetadataSchema = import_zod6.z.object({
395
+ type: import_zod6.z.literal("cron"),
396
+ options: CronOptionsSchema,
397
+ metadata: import_zod6.z.any()
398
+ });
399
+ var IntervalMetadataSchema = import_zod6.z.object({
400
+ type: import_zod6.z.literal("interval"),
401
+ options: IntervalOptionsSchema,
402
+ metadata: import_zod6.z.any()
403
+ });
404
+ var ScheduleMetadataSchema = import_zod6.z.discriminatedUnion("type", [
405
+ IntervalMetadataSchema,
406
+ CronMetadataSchema
407
+ ]);
408
+ var RegisterDynamicSchedulePayloadSchema = import_zod6.z.object({
409
+ id: import_zod6.z.string(),
410
+ jobs: import_zod6.z.array(import_zod6.z.object({
411
+ id: import_zod6.z.string(),
412
+ version: import_zod6.z.string()
413
+ }))
414
+ });
415
+
416
+ // ../internal/src/schemas/triggers.ts
417
+ var EventSpecificationSchema = import_zod7.z.object({
418
+ name: import_zod7.z.string(),
419
+ title: import_zod7.z.string(),
420
+ source: import_zod7.z.string(),
421
+ icon: import_zod7.z.string(),
422
+ filter: EventFilterSchema.optional(),
423
+ properties: import_zod7.z.array(DisplayPropertySchema).optional(),
424
+ schema: import_zod7.z.any().optional(),
425
+ examples: import_zod7.z.array(import_zod7.z.any()).optional()
426
+ });
427
+ var DynamicTriggerMetadataSchema = import_zod7.z.object({
428
+ type: import_zod7.z.literal("dynamic"),
429
+ id: import_zod7.z.string()
430
+ });
431
+ var StaticTriggerMetadataSchema = import_zod7.z.object({
432
+ type: import_zod7.z.literal("static"),
433
+ title: import_zod7.z.string(),
434
+ properties: import_zod7.z.array(DisplayPropertySchema).optional(),
435
+ rule: EventRuleSchema
436
+ });
437
+ var ScheduledTriggerMetadataSchema = import_zod7.z.object({
438
+ type: import_zod7.z.literal("scheduled"),
439
+ schedule: ScheduleMetadataSchema
440
+ });
441
+ var TriggerMetadataSchema = import_zod7.z.discriminatedUnion("type", [
442
+ DynamicTriggerMetadataSchema,
443
+ StaticTriggerMetadataSchema,
444
+ ScheduledTriggerMetadataSchema
445
+ ]);
446
+
447
+ // ../internal/src/schemas/api.ts
448
+ var UpdateTriggerSourceBodySchema = import_zod8.z.object({
449
+ registeredEvents: import_zod8.z.array(import_zod8.z.string()),
450
+ secret: import_zod8.z.string().optional(),
451
+ data: SerializableJsonSchema.optional()
452
+ });
453
+ var HttpEventSourceSchema = UpdateTriggerSourceBodySchema.extend({
454
+ id: import_zod8.z.string(),
455
+ active: import_zod8.z.boolean(),
456
+ url: import_zod8.z.string().url()
457
+ });
458
+ var RegisterHTTPTriggerSourceBodySchema = import_zod8.z.object({
459
+ type: import_zod8.z.literal("HTTP"),
460
+ url: import_zod8.z.string().url()
461
+ });
462
+ var RegisterSMTPTriggerSourceBodySchema = import_zod8.z.object({
463
+ type: import_zod8.z.literal("SMTP")
464
+ });
465
+ var RegisterSQSTriggerSourceBodySchema = import_zod8.z.object({
466
+ type: import_zod8.z.literal("SQS")
467
+ });
468
+ var RegisterSourceChannelBodySchema = import_zod8.z.discriminatedUnion("type", [
469
+ RegisterHTTPTriggerSourceBodySchema,
470
+ RegisterSMTPTriggerSourceBodySchema,
471
+ RegisterSQSTriggerSourceBodySchema
472
+ ]);
473
+ var REGISTER_SOURCE_EVENT = "dev.trigger.source.register";
474
+ var RegisterTriggerSourceSchema = import_zod8.z.object({
475
+ key: import_zod8.z.string(),
476
+ params: import_zod8.z.any(),
477
+ active: import_zod8.z.boolean(),
478
+ secret: import_zod8.z.string(),
479
+ data: DeserializedJsonSchema.optional(),
480
+ channel: RegisterSourceChannelBodySchema,
481
+ clientId: import_zod8.z.string().optional()
482
+ });
483
+ var RegisterSourceEventSchema = import_zod8.z.object({
484
+ id: import_zod8.z.string(),
485
+ source: RegisterTriggerSourceSchema,
486
+ events: import_zod8.z.array(import_zod8.z.string()),
487
+ missingEvents: import_zod8.z.array(import_zod8.z.string()),
488
+ orphanedEvents: import_zod8.z.array(import_zod8.z.string()),
489
+ dynamicTriggerId: import_zod8.z.string().optional()
490
+ });
491
+ var TriggerSourceSchema = import_zod8.z.object({
492
+ id: import_zod8.z.string(),
493
+ key: import_zod8.z.string()
494
+ });
495
+ var HandleTriggerSourceSchema = import_zod8.z.object({
496
+ key: import_zod8.z.string(),
497
+ secret: import_zod8.z.string(),
498
+ data: import_zod8.z.any(),
499
+ params: import_zod8.z.any()
500
+ });
501
+ var HttpSourceRequestSchema = import_zod8.z.object({
502
+ url: import_zod8.z.string().url(),
503
+ method: import_zod8.z.string(),
504
+ headers: import_zod8.z.record(import_zod8.z.string()),
505
+ rawBody: import_zod8.z.instanceof(Buffer).optional().nullable()
506
+ });
507
+ var HttpSourceRequestHeadersSchema = import_zod8.z.object({
508
+ "x-ts-key": import_zod8.z.string(),
509
+ "x-ts-dynamic-id": import_zod8.z.string().optional(),
510
+ "x-ts-secret": import_zod8.z.string(),
511
+ "x-ts-data": import_zod8.z.string().transform((s) => JSON.parse(s)),
512
+ "x-ts-params": import_zod8.z.string().transform((s) => JSON.parse(s)),
513
+ "x-ts-http-url": import_zod8.z.string(),
514
+ "x-ts-http-method": import_zod8.z.string(),
515
+ "x-ts-http-headers": import_zod8.z.string().transform((s) => import_zod8.z.record(import_zod8.z.string()).parse(JSON.parse(s)))
516
+ });
517
+ var PongResponseSchema = import_zod8.z.object({
518
+ message: import_zod8.z.literal("PONG")
519
+ });
520
+ var QueueOptionsSchema = import_zod8.z.object({
521
+ name: import_zod8.z.string(),
522
+ maxConcurrent: import_zod8.z.number().optional()
523
+ });
524
+ var JobMetadataSchema = import_zod8.z.object({
525
+ id: import_zod8.z.string(),
526
+ name: import_zod8.z.string(),
527
+ version: import_zod8.z.string(),
528
+ event: EventSpecificationSchema,
529
+ trigger: TriggerMetadataSchema,
530
+ integrations: import_zod8.z.record(IntegrationConfigSchema),
531
+ internal: import_zod8.z.boolean().default(false),
532
+ queue: import_zod8.z.union([
533
+ QueueOptionsSchema,
534
+ import_zod8.z.string()
535
+ ]).optional(),
536
+ startPosition: import_zod8.z.enum([
537
+ "initial",
538
+ "latest"
539
+ ]),
540
+ enabled: import_zod8.z.boolean(),
541
+ preprocessRuns: import_zod8.z.boolean()
542
+ });
543
+ var SourceMetadataSchema = import_zod8.z.object({
544
+ channel: import_zod8.z.enum([
545
+ "HTTP",
546
+ "SQS",
547
+ "SMTP"
548
+ ]),
549
+ key: import_zod8.z.string(),
550
+ params: import_zod8.z.any(),
551
+ events: import_zod8.z.array(import_zod8.z.string()),
552
+ clientId: import_zod8.z.string().optional()
553
+ });
554
+ var DynamicTriggerEndpointMetadataSchema = import_zod8.z.object({
555
+ id: import_zod8.z.string(),
556
+ jobs: import_zod8.z.array(JobMetadataSchema.pick({
557
+ id: true,
558
+ version: true
559
+ }))
560
+ });
561
+ var GetEndpointDataResponseSchema = import_zod8.z.object({
562
+ jobs: import_zod8.z.array(JobMetadataSchema),
563
+ sources: import_zod8.z.array(SourceMetadataSchema),
564
+ dynamicTriggers: import_zod8.z.array(DynamicTriggerEndpointMetadataSchema),
565
+ dynamicSchedules: import_zod8.z.array(RegisterDynamicSchedulePayloadSchema)
566
+ });
567
+ var RawEventSchema = import_zod8.z.object({
568
+ id: import_zod8.z.string().default(() => (0, import_ulid.ulid)()),
569
+ name: import_zod8.z.string(),
570
+ source: import_zod8.z.string().optional(),
571
+ payload: import_zod8.z.any(),
572
+ context: import_zod8.z.any().optional(),
573
+ timestamp: import_zod8.z.string().datetime().optional()
574
+ });
575
+ var ApiEventLogSchema = import_zod8.z.object({
576
+ id: import_zod8.z.string(),
577
+ name: import_zod8.z.string(),
578
+ payload: DeserializedJsonSchema,
579
+ context: DeserializedJsonSchema.optional().nullable(),
580
+ timestamp: import_zod8.z.coerce.date(),
581
+ deliverAt: import_zod8.z.coerce.date().optional().nullable(),
582
+ deliveredAt: import_zod8.z.coerce.date().optional().nullable()
583
+ });
584
+ var SendEventOptionsSchema = import_zod8.z.object({
585
+ deliverAt: import_zod8.z.string().datetime().optional(),
586
+ deliverAfter: import_zod8.z.number().int().optional(),
587
+ accountId: import_zod8.z.string().optional()
588
+ });
589
+ var SendEventBodySchema = import_zod8.z.object({
590
+ event: RawEventSchema,
591
+ options: SendEventOptionsSchema.optional()
592
+ });
593
+ var DeliverEventResponseSchema = import_zod8.z.object({
594
+ deliveredAt: import_zod8.z.string().datetime()
595
+ });
596
+ var RuntimeEnvironmentTypeSchema = import_zod8.z.enum([
597
+ "PRODUCTION",
598
+ "STAGING",
599
+ "DEVELOPMENT",
600
+ "PREVIEW"
601
+ ]);
602
+ var RunJobBodySchema = import_zod8.z.object({
603
+ event: ApiEventLogSchema,
604
+ job: import_zod8.z.object({
605
+ id: import_zod8.z.string(),
606
+ version: import_zod8.z.string()
607
+ }),
608
+ run: import_zod8.z.object({
609
+ id: import_zod8.z.string(),
610
+ isTest: import_zod8.z.boolean(),
611
+ startedAt: import_zod8.z.coerce.date()
612
+ }),
613
+ environment: import_zod8.z.object({
614
+ id: import_zod8.z.string(),
615
+ slug: import_zod8.z.string(),
616
+ type: RuntimeEnvironmentTypeSchema
617
+ }),
618
+ organization: import_zod8.z.object({
619
+ id: import_zod8.z.string(),
620
+ title: import_zod8.z.string(),
621
+ slug: import_zod8.z.string()
622
+ }),
623
+ account: import_zod8.z.object({
624
+ id: import_zod8.z.string(),
625
+ metadata: import_zod8.z.any()
626
+ }).optional(),
627
+ tasks: import_zod8.z.array(CachedTaskSchema).optional(),
628
+ connections: import_zod8.z.record(ConnectionAuthSchema).optional()
629
+ });
630
+ var RunJobResponseSchema = import_zod8.z.object({
631
+ executionId: import_zod8.z.string(),
632
+ completed: import_zod8.z.boolean(),
633
+ output: DeserializedJsonSchema.optional(),
634
+ task: TaskSchema.optional()
635
+ });
636
+ var PreprocessRunBodySchema = import_zod8.z.object({
637
+ event: ApiEventLogSchema,
638
+ job: import_zod8.z.object({
639
+ id: import_zod8.z.string(),
640
+ version: import_zod8.z.string()
641
+ }),
642
+ run: import_zod8.z.object({
643
+ id: import_zod8.z.string(),
644
+ isTest: import_zod8.z.boolean()
645
+ }),
646
+ environment: import_zod8.z.object({
647
+ id: import_zod8.z.string(),
648
+ slug: import_zod8.z.string(),
649
+ type: RuntimeEnvironmentTypeSchema
650
+ }),
651
+ organization: import_zod8.z.object({
652
+ id: import_zod8.z.string(),
653
+ title: import_zod8.z.string(),
654
+ slug: import_zod8.z.string()
655
+ }),
656
+ account: import_zod8.z.object({
657
+ id: import_zod8.z.string(),
658
+ metadata: import_zod8.z.any()
659
+ }).optional()
660
+ });
661
+ var PreprocessRunResponseSchema = import_zod8.z.object({
662
+ abort: import_zod8.z.boolean(),
663
+ properties: import_zod8.z.array(DisplayPropertySchema).optional()
664
+ });
665
+ var CreateRunBodySchema = import_zod8.z.object({
666
+ client: import_zod8.z.string(),
667
+ job: JobMetadataSchema,
668
+ event: ApiEventLogSchema,
669
+ properties: import_zod8.z.array(DisplayPropertySchema).optional()
670
+ });
671
+ var CreateRunResponseOkSchema = import_zod8.z.object({
672
+ ok: import_zod8.z.literal(true),
673
+ data: import_zod8.z.object({
674
+ id: import_zod8.z.string()
675
+ })
676
+ });
677
+ var CreateRunResponseErrorSchema = import_zod8.z.object({
678
+ ok: import_zod8.z.literal(false),
679
+ error: import_zod8.z.string()
680
+ });
681
+ var CreateRunResponseBodySchema = import_zod8.z.discriminatedUnion("ok", [
682
+ CreateRunResponseOkSchema,
683
+ CreateRunResponseErrorSchema
684
+ ]);
685
+ var SecureStringSchema = import_zod8.z.object({
686
+ __secureString: import_zod8.z.literal(true),
687
+ strings: import_zod8.z.array(import_zod8.z.string()),
688
+ interpolations: import_zod8.z.array(import_zod8.z.string())
689
+ });
690
+ var LogMessageSchema = import_zod8.z.object({
691
+ level: import_zod8.z.enum([
692
+ "DEBUG",
693
+ "INFO",
694
+ "WARN",
695
+ "ERROR"
696
+ ]),
697
+ message: import_zod8.z.string(),
698
+ data: SerializableJsonSchema.optional()
699
+ });
700
+ var RedactSchema = import_zod8.z.object({
701
+ paths: import_zod8.z.array(import_zod8.z.string())
702
+ });
703
+ var RunTaskOptionsSchema = import_zod8.z.object({
704
+ name: import_zod8.z.string(),
705
+ icon: import_zod8.z.string().optional(),
706
+ displayKey: import_zod8.z.string().optional(),
707
+ noop: import_zod8.z.boolean().default(false),
708
+ delayUntil: import_zod8.z.coerce.date().optional(),
709
+ description: import_zod8.z.string().optional(),
710
+ properties: import_zod8.z.array(DisplayPropertySchema).optional(),
711
+ params: SerializableJsonSchema.optional(),
712
+ trigger: TriggerMetadataSchema.optional(),
713
+ redact: RedactSchema.optional(),
714
+ connectionKey: import_zod8.z.string().optional(),
715
+ style: StyleSchema.optional()
716
+ });
717
+ var RunTaskBodyInputSchema = RunTaskOptionsSchema.extend({
718
+ idempotencyKey: import_zod8.z.string(),
719
+ parentId: import_zod8.z.string().optional()
720
+ });
721
+ var RunTaskBodyOutputSchema = RunTaskBodyInputSchema.extend({
722
+ params: DeserializedJsonSchema.optional().nullable()
723
+ });
724
+ var CompleteTaskBodyInputSchema = RunTaskBodyInputSchema.pick({
725
+ properties: true,
726
+ description: true,
727
+ params: true
728
+ }).extend({
729
+ output: SerializableJsonSchema.optional().transform((v) => v ? DeserializedJsonSchema.parse(JSON.parse(JSON.stringify(v))) : {})
730
+ });
731
+ var NormalizedRequestSchema = import_zod8.z.object({
732
+ headers: import_zod8.z.record(import_zod8.z.string()),
733
+ method: import_zod8.z.string(),
734
+ query: import_zod8.z.record(import_zod8.z.string()),
735
+ url: import_zod8.z.string(),
736
+ body: import_zod8.z.any()
737
+ });
738
+ var NormalizedResponseSchema = import_zod8.z.object({
739
+ status: import_zod8.z.number(),
740
+ body: import_zod8.z.any(),
741
+ headers: import_zod8.z.record(import_zod8.z.string()).optional()
742
+ });
743
+ var HttpSourceResponseSchema = import_zod8.z.object({
744
+ response: NormalizedResponseSchema,
745
+ events: import_zod8.z.array(RawEventSchema)
746
+ });
747
+ var RegisterTriggerBodySchema = import_zod8.z.object({
748
+ rule: EventRuleSchema,
749
+ source: SourceMetadataSchema
750
+ });
751
+ var InitializeTriggerBodySchema = import_zod8.z.object({
752
+ id: import_zod8.z.string(),
753
+ params: import_zod8.z.any(),
754
+ accountId: import_zod8.z.string().optional()
755
+ });
756
+ var RegisterCommonScheduleBodySchema = import_zod8.z.object({
757
+ id: import_zod8.z.string(),
758
+ metadata: import_zod8.z.any(),
759
+ accountId: import_zod8.z.string().optional()
760
+ });
761
+ var RegisterIntervalScheduleBodySchema = RegisterCommonScheduleBodySchema.merge(IntervalMetadataSchema);
762
+ var InitializeCronScheduleBodySchema = RegisterCommonScheduleBodySchema.merge(CronMetadataSchema);
763
+ var RegisterScheduleBodySchema = import_zod8.z.discriminatedUnion("type", [
764
+ RegisterIntervalScheduleBodySchema,
765
+ InitializeCronScheduleBodySchema
766
+ ]);
767
+ var RegisterScheduleResponseBodySchema = import_zod8.z.object({
768
+ id: import_zod8.z.string(),
769
+ schedule: ScheduleMetadataSchema,
770
+ metadata: import_zod8.z.any(),
771
+ active: import_zod8.z.boolean()
772
+ });
773
+ var CreateExternalConnectionBodySchema = import_zod8.z.object({
774
+ accessToken: import_zod8.z.string(),
775
+ type: import_zod8.z.enum([
776
+ "oauth2"
777
+ ]),
778
+ scopes: import_zod8.z.array(import_zod8.z.string()).optional(),
779
+ metadata: import_zod8.z.any()
780
+ });
781
+
782
+ // ../internal/src/schemas/errors.ts
783
+ var import_zod9 = require("zod");
784
+ var ErrorWithMessage = import_zod9.z.object({
785
+ message: import_zod9.z.string()
786
+ });
787
+ var ErrorWithStackSchema = ErrorWithMessage.extend({
788
+ stack: import_zod9.z.string().optional()
789
+ });
790
+
791
+ // ../internal/src/schemas/notifications.ts
792
+ var import_zod10 = require("zod");
793
+ var MISSING_CONNECTION_NOTIFICATION = "dev.trigger.notifications.missingConnection";
794
+ var MISSING_CONNECTION_RESOLVED_NOTIFICATION = "dev.trigger.notifications.missingConnectionResolved";
795
+ var CommonMissingConnectionNotificationPayloadSchema = import_zod10.z.object({
796
+ id: import_zod10.z.string(),
797
+ client: import_zod10.z.object({
798
+ id: import_zod10.z.string(),
799
+ title: import_zod10.z.string(),
800
+ scopes: import_zod10.z.array(import_zod10.z.string()),
801
+ createdAt: import_zod10.z.coerce.date(),
802
+ updatedAt: import_zod10.z.coerce.date(),
803
+ integrationIdentifier: import_zod10.z.string(),
804
+ integrationAuthMethod: import_zod10.z.string()
805
+ }),
806
+ authorizationUrl: import_zod10.z.string()
807
+ });
808
+ var MissingDeveloperConnectionNotificationPayloadSchema = CommonMissingConnectionNotificationPayloadSchema.extend({
809
+ type: import_zod10.z.literal("DEVELOPER")
810
+ });
811
+ var MissingExternalConnectionNotificationPayloadSchema = CommonMissingConnectionNotificationPayloadSchema.extend({
812
+ type: import_zod10.z.literal("EXTERNAL"),
813
+ account: import_zod10.z.object({
814
+ id: import_zod10.z.string(),
815
+ metadata: import_zod10.z.any()
816
+ })
817
+ });
818
+ var MissingConnectionNotificationPayloadSchema = import_zod10.z.discriminatedUnion("type", [
819
+ MissingDeveloperConnectionNotificationPayloadSchema,
820
+ MissingExternalConnectionNotificationPayloadSchema
821
+ ]);
822
+ var CommonMissingConnectionNotificationResolvedPayloadSchema = import_zod10.z.object({
823
+ id: import_zod10.z.string(),
824
+ client: import_zod10.z.object({
825
+ id: import_zod10.z.string(),
826
+ title: import_zod10.z.string(),
827
+ scopes: import_zod10.z.array(import_zod10.z.string()),
828
+ createdAt: import_zod10.z.coerce.date(),
829
+ updatedAt: import_zod10.z.coerce.date(),
830
+ integrationIdentifier: import_zod10.z.string(),
831
+ integrationAuthMethod: import_zod10.z.string()
832
+ }),
833
+ expiresAt: import_zod10.z.coerce.date()
834
+ });
835
+ var MissingDeveloperConnectionResolvedNotificationPayloadSchema = CommonMissingConnectionNotificationResolvedPayloadSchema.extend({
836
+ type: import_zod10.z.literal("DEVELOPER")
837
+ });
838
+ var MissingExternalConnectionResolvedNotificationPayloadSchema = CommonMissingConnectionNotificationResolvedPayloadSchema.extend({
839
+ type: import_zod10.z.literal("EXTERNAL"),
840
+ account: import_zod10.z.object({
841
+ id: import_zod10.z.string(),
842
+ metadata: import_zod10.z.any()
843
+ })
844
+ });
845
+ var MissingConnectionResolvedNotificationPayloadSchema = import_zod10.z.discriminatedUnion("type", [
846
+ MissingDeveloperConnectionResolvedNotificationPayloadSchema,
847
+ MissingExternalConnectionResolvedNotificationPayloadSchema
848
+ ]);
849
+
850
+ // ../internal/src/utils.ts
851
+ function deepMergeFilters(filter, other) {
852
+ const result = {
853
+ ...filter
854
+ };
855
+ for (const key in other) {
856
+ if (other.hasOwnProperty(key)) {
857
+ const otherValue = other[key];
858
+ if (typeof otherValue === "object" && !Array.isArray(otherValue) && otherValue !== null) {
859
+ const filterValue = filter[key];
860
+ if (filterValue && typeof filterValue === "object" && !Array.isArray(filterValue)) {
861
+ result[key] = deepMergeFilters(filterValue, otherValue);
862
+ } else {
863
+ result[key] = {
864
+ ...other[key]
865
+ };
866
+ }
867
+ } else {
868
+ result[key] = other[key];
869
+ }
870
+ }
871
+ }
872
+ return result;
873
+ }
874
+ __name(deepMergeFilters, "deepMergeFilters");
875
+
876
+ // src/apiClient.ts
877
+ var import_zod11 = require("zod");
878
+ var _apiUrl, _options, _logger, _apiKey, apiKey_fn;
879
+ var ApiClient = class {
880
+ constructor(options) {
881
+ __privateAdd(this, _apiKey);
882
+ __privateAdd(this, _apiUrl, void 0);
883
+ __privateAdd(this, _options, void 0);
884
+ __privateAdd(this, _logger, void 0);
885
+ __privateSet(this, _options, options);
886
+ __privateSet(this, _apiUrl, __privateGet(this, _options).apiUrl ?? process.env.TRIGGER_API_URL ?? "https://api.trigger.dev");
887
+ __privateSet(this, _logger, new Logger("trigger.dev", __privateGet(this, _options).logLevel));
888
+ }
889
+ async registerEndpoint(options) {
890
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
891
+ __privateGet(this, _logger).debug("Registering endpoint", {
892
+ url: options.url,
893
+ name: options.name
894
+ });
895
+ const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
896
+ method: "POST",
897
+ headers: {
898
+ "Content-Type": "application/json",
899
+ Authorization: `Bearer ${apiKey}`
900
+ },
901
+ body: JSON.stringify({
902
+ url: options.url,
903
+ name: options.name
904
+ })
905
+ });
906
+ if (response.status >= 400 && response.status < 500) {
907
+ const body = await response.json();
908
+ throw new Error(body.error);
909
+ }
910
+ if (response.status !== 200) {
911
+ throw new Error(`Failed to register entry point, got status code ${response.status}`);
912
+ }
913
+ return await response.json();
914
+ }
915
+ async createRun(params) {
916
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
917
+ __privateGet(this, _logger).debug("Creating run", {
918
+ params
919
+ });
920
+ return await zodfetch(CreateRunResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/runs`, {
921
+ method: "POST",
922
+ headers: {
923
+ "Content-Type": "application/json",
924
+ Authorization: `Bearer ${apiKey}`
925
+ },
926
+ body: JSON.stringify(params)
927
+ });
928
+ }
929
+ async runTask(runId, task) {
930
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
931
+ __privateGet(this, _logger).debug("Running Task", {
932
+ task
933
+ });
934
+ return await zodfetch(ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
935
+ method: "POST",
936
+ headers: {
937
+ "Content-Type": "application/json",
938
+ Authorization: `Bearer ${apiKey}`,
939
+ "Idempotency-Key": task.idempotencyKey
940
+ },
941
+ body: JSON.stringify(task)
942
+ });
943
+ }
944
+ async completeTask(runId, id, task) {
945
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
946
+ __privateGet(this, _logger).debug("Complete Task", {
947
+ task
948
+ });
949
+ return await zodfetch(ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/complete`, {
950
+ method: "POST",
951
+ headers: {
952
+ "Content-Type": "application/json",
953
+ Authorization: `Bearer ${apiKey}`
954
+ },
955
+ body: JSON.stringify(task)
956
+ });
957
+ }
958
+ async sendEvent(event, options = {}) {
959
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
960
+ __privateGet(this, _logger).debug("Sending event", {
961
+ event
962
+ });
963
+ return await zodfetch(ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events`, {
964
+ method: "POST",
965
+ headers: {
966
+ "Content-Type": "application/json",
967
+ Authorization: `Bearer ${apiKey}`
968
+ },
969
+ body: JSON.stringify({
970
+ event,
971
+ options
972
+ })
973
+ });
974
+ }
975
+ async updateSource(client, key, source) {
976
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
977
+ __privateGet(this, _logger).debug("activating http source", {
978
+ source
979
+ });
980
+ const response = await zodfetch(TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/sources/${key}`, {
981
+ method: "PUT",
982
+ headers: {
983
+ "Content-Type": "application/json",
984
+ Authorization: `Bearer ${apiKey}`
985
+ },
986
+ body: JSON.stringify(source)
987
+ });
988
+ return response;
989
+ }
990
+ async registerTrigger(client, id, key, payload) {
991
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
992
+ __privateGet(this, _logger).debug("registering trigger", {
993
+ id,
994
+ payload
995
+ });
996
+ const response = await zodfetch(RegisterSourceEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/triggers/${id}/registrations/${key}`, {
997
+ method: "PUT",
998
+ headers: {
999
+ "Content-Type": "application/json",
1000
+ Authorization: `Bearer ${apiKey}`
1001
+ },
1002
+ body: JSON.stringify(payload)
1003
+ });
1004
+ return response;
1005
+ }
1006
+ async registerSchedule(client, id, key, payload) {
1007
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1008
+ __privateGet(this, _logger).debug("registering schedule", {
1009
+ id,
1010
+ payload
1011
+ });
1012
+ const response = await zodfetch(RegisterScheduleResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations`, {
1013
+ method: "POST",
1014
+ headers: {
1015
+ "Content-Type": "application/json",
1016
+ Authorization: `Bearer ${apiKey}`
1017
+ },
1018
+ body: JSON.stringify({
1019
+ id: key,
1020
+ ...payload
1021
+ })
1022
+ });
1023
+ return response;
1024
+ }
1025
+ async unregisterSchedule(client, id, key) {
1026
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1027
+ __privateGet(this, _logger).debug("unregistering schedule", {
1028
+ id
1029
+ });
1030
+ const response = await zodfetch(import_zod11.z.object({
1031
+ ok: import_zod11.z.boolean()
1032
+ }), `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`, {
1033
+ method: "DELETE",
1034
+ headers: {
1035
+ "Content-Type": "application/json",
1036
+ Authorization: `Bearer ${apiKey}`
1037
+ }
1038
+ });
1039
+ return response;
1040
+ }
1041
+ async getAuth(client, id) {
1042
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1043
+ __privateGet(this, _logger).debug("getting auth", {
1044
+ id
1045
+ });
1046
+ const response = await zodfetch(ConnectionAuthSchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/auth/${id}`, {
1047
+ method: "GET",
1048
+ headers: {
1049
+ Accept: "application/json",
1050
+ Authorization: `Bearer ${apiKey}`
1051
+ }
1052
+ }, {
1053
+ optional: true
1054
+ });
1055
+ return response;
1056
+ }
1057
+ };
1058
+ __name(ApiClient, "ApiClient");
1059
+ _apiUrl = new WeakMap();
1060
+ _options = new WeakMap();
1061
+ _logger = new WeakMap();
1062
+ _apiKey = new WeakSet();
1063
+ apiKey_fn = /* @__PURE__ */ __name(async function() {
1064
+ const apiKey = getApiKey(__privateGet(this, _options).apiKey);
1065
+ if (apiKey.status === "invalid") {
1066
+ throw new Error("Invalid API key");
1067
+ } else if (apiKey.status === "missing") {
1068
+ throw new Error("Missing API key");
1069
+ }
1070
+ return apiKey.apiKey;
1071
+ }, "#apiKey");
1072
+ function getApiKey(key) {
1073
+ const apiKey = key ?? process.env.TRIGGER_API_KEY;
1074
+ if (!apiKey) {
1075
+ return {
1076
+ status: "missing"
1077
+ };
1078
+ }
1079
+ const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);
1080
+ if (!isValid) {
1081
+ return {
1082
+ status: "invalid",
1083
+ apiKey
1084
+ };
1085
+ }
1086
+ return {
1087
+ status: "valid",
1088
+ apiKey
1089
+ };
1090
+ }
1091
+ __name(getApiKey, "getApiKey");
1092
+ async function zodfetch(schema, url, requestInit, options) {
1093
+ const response = await fetch(url, requestInit);
1094
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
1095
+ return;
1096
+ }
1097
+ if (response.status >= 400 && response.status < 500) {
1098
+ const body = await response.json();
1099
+ throw new Error(body.error);
1100
+ }
1101
+ if (response.status !== 200) {
1102
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
1103
+ }
1104
+ const jsonBody = await response.json();
1105
+ return schema.parse(jsonBody);
1106
+ }
1107
+ __name(zodfetch, "zodfetch");
1108
+
1109
+ // src/io.ts
1110
+ var import_node_async_hooks = require("async_hooks");
1111
+ var import_node_crypto = require("crypto");
1112
+
1113
+ // src/ioWithIntegrations.ts
1114
+ function createIOWithIntegrations(io, auths, integrations) {
1115
+ if (!integrations) {
1116
+ return io;
1117
+ }
1118
+ const connections = Object.entries(integrations).reduce((acc, [connectionKey, integration]) => {
1119
+ const connection = auths?.[connectionKey];
1120
+ const client = "client" in integration.client ? integration.client.client : connection ? integration.client.clientFactory?.(connection) : void 0;
1121
+ if (!client) {
1122
+ return acc;
1123
+ }
1124
+ const ioConnection = {
1125
+ client
1126
+ };
1127
+ if (integration.client.tasks) {
1128
+ const tasks = integration.client.tasks;
1129
+ Object.keys(tasks).forEach((taskName) => {
1130
+ const authenticatedTask2 = tasks[taskName];
1131
+ ioConnection[taskName] = async (key, params) => {
1132
+ const options = authenticatedTask2.init(params);
1133
+ options.connectionKey = connectionKey;
1134
+ return await io.runTask(key, options, async (ioTask) => {
1135
+ return authenticatedTask2.run(params, client, ioTask, io);
1136
+ });
1137
+ };
1138
+ });
1139
+ }
1140
+ acc[connectionKey] = ioConnection;
1141
+ return acc;
1142
+ }, {});
1143
+ return new Proxy(io, {
1144
+ get(target, prop, receiver) {
1145
+ if (prop === "__io") {
1146
+ return io;
1147
+ }
1148
+ if (prop in connections) {
1149
+ return connections[prop];
1150
+ }
1151
+ const value = Reflect.get(target, prop, receiver);
1152
+ return typeof value == "function" ? value.bind(target) : value;
1153
+ }
1154
+ });
1155
+ }
1156
+ __name(createIOWithIntegrations, "createIOWithIntegrations");
1157
+
1158
+ // src/io.ts
1159
+ var ResumeWithTask = class {
1160
+ constructor(task) {
1161
+ this.task = task;
1162
+ }
1163
+ };
1164
+ __name(ResumeWithTask, "ResumeWithTask");
1165
+ var _addToCachedTasks, addToCachedTasks_fn;
1166
+ var IO = class {
1167
+ constructor(options) {
1168
+ __privateAdd(this, _addToCachedTasks);
1169
+ this._id = options.id;
1170
+ this._apiClient = options.apiClient;
1171
+ this._triggerClient = options.client;
1172
+ this._logger = options.logger ?? new Logger("trigger.dev", options.logLevel);
1173
+ this._cachedTasks = /* @__PURE__ */ new Map();
1174
+ if (options.cachedTasks) {
1175
+ options.cachedTasks.forEach((task) => {
1176
+ this._cachedTasks.set(task.id, task);
1177
+ });
1178
+ }
1179
+ this._taskStorage = new import_node_async_hooks.AsyncLocalStorage();
1180
+ this._context = options.context;
1181
+ }
1182
+ get logger() {
1183
+ return new IOLogger(async (level, message, data) => {
1184
+ switch (level) {
1185
+ case "DEBUG": {
1186
+ this._logger.debug(message, data);
1187
+ break;
1188
+ }
1189
+ case "INFO": {
1190
+ this._logger.info(message, data);
1191
+ break;
1192
+ }
1193
+ case "WARN": {
1194
+ this._logger.warn(message, data);
1195
+ break;
1196
+ }
1197
+ case "ERROR": {
1198
+ this._logger.error(message, data);
1199
+ break;
1200
+ }
1201
+ }
1202
+ await this.runTask([
1203
+ message,
1204
+ level
1205
+ ], {
1206
+ name: "log",
1207
+ icon: "log",
1208
+ description: message,
1209
+ params: data,
1210
+ properties: [
1211
+ {
1212
+ label: "Level",
1213
+ text: level
1214
+ }
1215
+ ],
1216
+ style: {
1217
+ style: "minimal",
1218
+ variant: level.toLowerCase()
1219
+ },
1220
+ noop: true
1221
+ }, async (task) => {
1222
+ });
1223
+ });
1224
+ }
1225
+ async wait(key, seconds) {
1226
+ return await this.runTask(key, {
1227
+ name: "wait",
1228
+ icon: "clock",
1229
+ params: {
1230
+ seconds
1231
+ },
1232
+ noop: true,
1233
+ delayUntil: new Date(Date.now() + seconds * 1e3),
1234
+ style: {
1235
+ style: "minimal"
1236
+ }
1237
+ }, async (task) => {
1238
+ });
1239
+ }
1240
+ async sendEvent(key, event, options) {
1241
+ return await this.runTask(key, {
1242
+ name: "sendEvent",
1243
+ params: {
1244
+ event,
1245
+ options
1246
+ }
1247
+ }, async (task) => {
1248
+ return await this._triggerClient.sendEvent(event, options);
1249
+ });
1250
+ }
1251
+ async updateSource(key, options) {
1252
+ return this.runTask(key, {
1253
+ name: "Update Source",
1254
+ description: `Update Source ${options.key}`,
1255
+ properties: [
1256
+ {
1257
+ label: "key",
1258
+ text: options.key
1259
+ }
1260
+ ],
1261
+ redact: {
1262
+ paths: [
1263
+ "secret"
1264
+ ]
1265
+ }
1266
+ }, async (task) => {
1267
+ return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
1268
+ });
1269
+ }
1270
+ async registerInterval(key, dynamicSchedule, id, options) {
1271
+ return await this.runTask(key, {
1272
+ name: "register-interval",
1273
+ properties: [
1274
+ {
1275
+ label: "schedule",
1276
+ text: dynamicSchedule.id
1277
+ },
1278
+ {
1279
+ label: "id",
1280
+ text: id
1281
+ },
1282
+ {
1283
+ label: "seconds",
1284
+ text: options.seconds.toString()
1285
+ }
1286
+ ],
1287
+ params: options
1288
+ }, async (task) => {
1289
+ return dynamicSchedule.register(id, {
1290
+ type: "interval",
1291
+ options
1292
+ });
1293
+ });
1294
+ }
1295
+ async unregisterInterval(key, dynamicSchedule, id) {
1296
+ return await this.runTask(key, {
1297
+ name: "unregister-interval",
1298
+ properties: [
1299
+ {
1300
+ label: "schedule",
1301
+ text: dynamicSchedule.id
1302
+ },
1303
+ {
1304
+ label: "id",
1305
+ text: id
1306
+ }
1307
+ ]
1308
+ }, async (task) => {
1309
+ return dynamicSchedule.unregister(id);
1310
+ });
1311
+ }
1312
+ async registerCron(key, dynamicSchedule, id, options) {
1313
+ return await this.runTask(key, {
1314
+ name: "register-cron",
1315
+ properties: [
1316
+ {
1317
+ label: "schedule",
1318
+ text: dynamicSchedule.id
1319
+ },
1320
+ {
1321
+ label: "id",
1322
+ text: id
1323
+ },
1324
+ {
1325
+ label: "cron",
1326
+ text: options.cron
1327
+ }
1328
+ ],
1329
+ params: options
1330
+ }, async (task) => {
1331
+ return dynamicSchedule.register(id, {
1332
+ type: "cron",
1333
+ options
1334
+ });
1335
+ });
1336
+ }
1337
+ async unregisterCron(key, dynamicSchedule, id) {
1338
+ return await this.runTask(key, {
1339
+ name: "unregister-cron",
1340
+ properties: [
1341
+ {
1342
+ label: "schedule",
1343
+ text: dynamicSchedule.id
1344
+ },
1345
+ {
1346
+ label: "id",
1347
+ text: id
1348
+ }
1349
+ ]
1350
+ }, async (task) => {
1351
+ return dynamicSchedule.unregister(id);
1352
+ });
1353
+ }
1354
+ async registerTrigger(key, trigger, id, params) {
1355
+ return await this.runTask(key, {
1356
+ name: "register-trigger",
1357
+ properties: [
1358
+ {
1359
+ label: "trigger",
1360
+ text: trigger.id
1361
+ },
1362
+ {
1363
+ label: "id",
1364
+ text: id
1365
+ }
1366
+ ],
1367
+ params
1368
+ }, async (task) => {
1369
+ const registration = await this.runTask("register-source", {
1370
+ name: "register-source"
1371
+ }, async (subtask1) => {
1372
+ return trigger.register(id, params);
1373
+ });
1374
+ const connection = await this.getAuth("get-auth", registration.source.clientId);
1375
+ const io = createIOWithIntegrations(
1376
+ this,
1377
+ {
1378
+ integration: connection
1379
+ },
1380
+ {
1381
+ integration: trigger.source.integration
1382
+ }
1383
+ );
1384
+ const updates = await trigger.source.register(params, registration, io, this._context);
1385
+ if (!updates) {
1386
+ return;
1387
+ }
1388
+ return await this.updateSource("update-source", {
1389
+ key: registration.source.key,
1390
+ ...updates
1391
+ });
1392
+ });
1393
+ }
1394
+ async getAuth(key, clientId) {
1395
+ if (!clientId) {
1396
+ return;
1397
+ }
1398
+ return this.runTask(key, {
1399
+ name: "get-auth"
1400
+ }, async (task) => {
1401
+ return await this._triggerClient.getAuth(clientId);
1402
+ });
1403
+ }
1404
+ async runTask(key, options, callback) {
1405
+ const parentId = this._taskStorage.getStore()?.taskId;
1406
+ if (parentId) {
1407
+ this._logger.debug("Using parent task", {
1408
+ parentId,
1409
+ key,
1410
+ options
1411
+ });
1412
+ }
1413
+ const idempotencyKey = await generateIdempotencyKey([
1414
+ this._id,
1415
+ parentId ?? "",
1416
+ key
1417
+ ].flat());
1418
+ const cachedTask = this._cachedTasks.get(idempotencyKey);
1419
+ if (cachedTask) {
1420
+ this._logger.debug("Using cached task", {
1421
+ idempotencyKey,
1422
+ cachedTask
1423
+ });
1424
+ return cachedTask.output;
1425
+ }
1426
+ const task = await this._apiClient.runTask(this._id, {
1427
+ idempotencyKey,
1428
+ displayKey: typeof key === "string" ? key : void 0,
1429
+ noop: false,
1430
+ ...options,
1431
+ parentId
1432
+ });
1433
+ if (task.status === "COMPLETED") {
1434
+ this._logger.debug("Using task output", {
1435
+ idempotencyKey,
1436
+ task
1437
+ });
1438
+ __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1439
+ return task.output;
1440
+ }
1441
+ if (task.status === "ERRORED") {
1442
+ this._logger.debug("Task errored", {
1443
+ idempotencyKey,
1444
+ task
1445
+ });
1446
+ throw new Error(task.error ?? "Task errored");
1447
+ }
1448
+ if (task.status === "WAITING") {
1449
+ this._logger.debug("Task waiting", {
1450
+ idempotencyKey,
1451
+ task
1452
+ });
1453
+ throw new ResumeWithTask(task);
1454
+ }
1455
+ const executeTask = /* @__PURE__ */ __name(async () => {
1456
+ try {
1457
+ const result = await callback(task, this);
1458
+ this._logger.debug("Completing using output", {
1459
+ idempotencyKey,
1460
+ task
1461
+ });
1462
+ await this._apiClient.completeTask(this._id, task.id, {
1463
+ output: result ?? void 0
1464
+ });
1465
+ return result;
1466
+ } catch (error) {
1467
+ throw error;
1468
+ }
1469
+ }, "executeTask");
1470
+ return this._taskStorage.run({
1471
+ taskId: task.id
1472
+ }, executeTask);
1473
+ }
1474
+ };
1475
+ __name(IO, "IO");
1476
+ _addToCachedTasks = new WeakSet();
1477
+ addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
1478
+ this._cachedTasks.set(task.idempotencyKey, task);
1479
+ }, "#addToCachedTasks");
1480
+ async function generateIdempotencyKey(keyMaterial) {
1481
+ const keys = keyMaterial.map((key2) => {
1482
+ if (typeof key2 === "string") {
1483
+ return key2;
1484
+ }
1485
+ return stableStringify(key2);
1486
+ });
1487
+ const key = keys.join(":");
1488
+ const hash = await import_node_crypto.webcrypto.subtle.digest("SHA-256", Buffer.from(key));
1489
+ return Buffer.from(hash).toString("hex");
1490
+ }
1491
+ __name(generateIdempotencyKey, "generateIdempotencyKey");
1492
+ function stableStringify(obj) {
1493
+ function sortKeys(obj2) {
1494
+ if (typeof obj2 !== "object" || obj2 === null) {
1495
+ return obj2;
1496
+ }
1497
+ if (Array.isArray(obj2)) {
1498
+ return obj2.map(sortKeys);
1499
+ }
1500
+ const sortedKeys = Object.keys(obj2).sort();
1501
+ const sortedObj2 = {};
1502
+ for (const key of sortedKeys) {
1503
+ sortedObj2[key] = sortKeys(obj2[key]);
1504
+ }
1505
+ return sortedObj2;
1506
+ }
1507
+ __name(sortKeys, "sortKeys");
1508
+ const sortedObj = sortKeys(obj);
1509
+ return JSON.stringify(sortedObj);
1510
+ }
1511
+ __name(stableStringify, "stableStringify");
1512
+ var IOLogger = class {
1513
+ constructor(callback) {
1514
+ this.callback = callback;
1515
+ }
1516
+ debug(message, properties) {
1517
+ return this.callback("DEBUG", message, properties);
1518
+ }
1519
+ info(message, properties) {
1520
+ return this.callback("INFO", message, properties);
1521
+ }
1522
+ warn(message, properties) {
1523
+ return this.callback("WARN", message, properties);
1524
+ }
1525
+ error(message, properties) {
1348
1526
  return this.callback("ERROR", message, properties);
1349
1527
  }
1350
- };
1351
- __name(ContextLogger, "ContextLogger");
1352
-
1353
- // src/client.ts
1354
- var import_zod_error = require("zod-error");
1355
- var import_promises = require("fs/promises");
1356
-
1357
- // src/keyValueStorage.ts
1358
- var ContextKeyValueStorage = class {
1359
- constructor(namespace, onGet, onSet, onDelete) {
1360
- this.namespace = namespace;
1361
- this.onGet = onGet;
1362
- this.onSet = onSet;
1363
- this.onDelete = onDelete;
1364
- this.getCount = 0;
1365
- this.setCount = 0;
1366
- this.deleteCount = 0;
1367
- }
1368
- get(key) {
1369
- const operation = {
1370
- key,
1371
- namespace: this.namespace,
1372
- idempotencyKey: `get:${this.namespace}:${key}:${this.getCount++}`
1373
- };
1374
- return this.onGet(operation);
1375
- }
1376
- set(key, value) {
1377
- const operation = {
1378
- key,
1379
- namespace: this.namespace,
1380
- idempotencyKey: `set:${this.namespace}:${key}:${this.setCount++}`,
1381
- value
1382
- };
1383
- return this.onSet(operation);
1528
+ };
1529
+ __name(IOLogger, "IOLogger");
1530
+
1531
+ // src/triggers/eventTrigger.ts
1532
+ var _options2;
1533
+ var EventTrigger = class {
1534
+ constructor(options) {
1535
+ __privateAdd(this, _options2, void 0);
1536
+ __privateSet(this, _options2, options);
1537
+ }
1538
+ toJSON() {
1539
+ return {
1540
+ type: "static",
1541
+ title: __privateGet(this, _options2).name ?? __privateGet(this, _options2).event.title,
1542
+ rule: {
1543
+ event: __privateGet(this, _options2).name ?? __privateGet(this, _options2).event.name,
1544
+ source: __privateGet(this, _options2).source ?? "trigger.dev",
1545
+ payload: deepMergeFilters(__privateGet(this, _options2).filter ?? {}, __privateGet(this, _options2).event.filter ?? {})
1546
+ }
1547
+ };
1548
+ }
1549
+ get event() {
1550
+ return __privateGet(this, _options2).event;
1551
+ }
1552
+ attachToJob(triggerClient, job) {
1553
+ }
1554
+ get preprocessRuns() {
1555
+ return false;
1556
+ }
1557
+ };
1558
+ __name(EventTrigger, "EventTrigger");
1559
+ _options2 = new WeakMap();
1560
+ function eventTrigger(options) {
1561
+ return new EventTrigger({
1562
+ name: "Event Trigger",
1563
+ filter: options.filter,
1564
+ event: {
1565
+ name: options.name,
1566
+ title: "Event",
1567
+ source: options.source ?? "trigger.dev",
1568
+ icon: "custom-event",
1569
+ parsePayload: (rawPayload) => {
1570
+ if (options.schema) {
1571
+ return options.schema.parse(rawPayload);
1572
+ }
1573
+ return rawPayload;
1574
+ }
1575
+ }
1576
+ });
1577
+ }
1578
+ __name(eventTrigger, "eventTrigger");
1579
+
1580
+ // src/triggerClient.ts
1581
+ var registerSourceEvent = {
1582
+ name: REGISTER_SOURCE_EVENT,
1583
+ title: "Register Source",
1584
+ source: "internal",
1585
+ icon: "register-source",
1586
+ parsePayload: RegisterSourceEventSchema.parse
1587
+ };
1588
+ var _options3, _registeredJobs, _registeredSources, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _client, _logger2, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn;
1589
+ var TriggerClient = class {
1590
+ constructor(options) {
1591
+ __privateAdd(this, _preprocessRun);
1592
+ __privateAdd(this, _executeJob);
1593
+ __privateAdd(this, _createRunContext);
1594
+ __privateAdd(this, _createPreprocessRunContext);
1595
+ __privateAdd(this, _handleHttpSourceRequest);
1596
+ __privateAdd(this, _options3, void 0);
1597
+ __privateAdd(this, _registeredJobs, {});
1598
+ __privateAdd(this, _registeredSources, {});
1599
+ __privateAdd(this, _registeredHttpSourceHandlers, {});
1600
+ __privateAdd(this, _registeredDynamicTriggers, {});
1601
+ __privateAdd(this, _jobMetadataByDynamicTriggers, {});
1602
+ __privateAdd(this, _registeredSchedules, {});
1603
+ __privateAdd(this, _client, void 0);
1604
+ __privateAdd(this, _logger2, void 0);
1605
+ this.id = options.id;
1606
+ this._url = buildClientUrl(options.url);
1607
+ __privateSet(this, _options3, options);
1608
+ __privateSet(this, _client, new ApiClient(__privateGet(this, _options3)));
1609
+ __privateSet(this, _logger2, new Logger("trigger.dev", __privateGet(this, _options3).logLevel));
1610
+ }
1611
+ get url() {
1612
+ return `${this._url}${this.path ? `${this.path.startsWith("/") ? "" : "/"}${this.path}` : ""}`;
1613
+ }
1614
+ async handleRequest(request) {
1615
+ __privateGet(this, _logger2).debug("handling request", {
1616
+ url: request.url,
1617
+ headers: Object.fromEntries(request.headers.entries()),
1618
+ method: request.method
1619
+ });
1620
+ const apiKey = request.headers.get("x-trigger-api-key");
1621
+ if (!this.authorized(apiKey)) {
1622
+ return {
1623
+ status: 401,
1624
+ body: {
1625
+ message: "Unauthorized"
1626
+ }
1627
+ };
1628
+ }
1629
+ if (request.method !== "POST") {
1630
+ return {
1631
+ status: 405,
1632
+ body: {
1633
+ message: "Method not allowed"
1634
+ }
1635
+ };
1636
+ }
1637
+ const action = request.headers.get("x-trigger-action");
1638
+ if (!action) {
1639
+ return {
1640
+ status: 400,
1641
+ body: {
1642
+ message: "Missing x-trigger-action header"
1643
+ }
1644
+ };
1645
+ }
1646
+ switch (action) {
1647
+ case "PING": {
1648
+ return {
1649
+ status: 200,
1650
+ body: {
1651
+ message: "PONG"
1652
+ }
1653
+ };
1654
+ }
1655
+ case "GET_ENDPOINT_DATA": {
1656
+ const jobId = request.headers.get("x-trigger-job-id");
1657
+ if (jobId) {
1658
+ const job = __privateGet(this, _registeredJobs)[jobId];
1659
+ if (!job) {
1660
+ return {
1661
+ status: 404,
1662
+ body: {
1663
+ message: "Job not found"
1664
+ }
1665
+ };
1666
+ }
1667
+ return {
1668
+ status: 200,
1669
+ body: job.toJSON()
1670
+ };
1671
+ }
1672
+ const body = {
1673
+ jobs: Object.values(__privateGet(this, _registeredJobs)).map((job) => job.toJSON()),
1674
+ sources: Object.values(__privateGet(this, _registeredSources)),
1675
+ dynamicTriggers: Object.values(__privateGet(this, _registeredDynamicTriggers)).map((trigger) => ({
1676
+ id: trigger.id,
1677
+ jobs: __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] ?? []
1678
+ })),
1679
+ dynamicSchedules: Object.entries(__privateGet(this, _registeredSchedules)).map(([id, jobs]) => ({
1680
+ id,
1681
+ jobs
1682
+ }))
1683
+ };
1684
+ return {
1685
+ status: 200,
1686
+ body
1687
+ };
1688
+ }
1689
+ case "INITIALIZE": {
1690
+ await this.listen();
1691
+ return {
1692
+ status: 200,
1693
+ body: {
1694
+ message: "Initialized"
1695
+ }
1696
+ };
1697
+ }
1698
+ case "INITIALIZE_TRIGGER": {
1699
+ const json = await request.json();
1700
+ const body = InitializeTriggerBodySchema.safeParse(json);
1701
+ if (!body.success) {
1702
+ return {
1703
+ status: 400,
1704
+ body: {
1705
+ message: "Invalid trigger body"
1706
+ }
1707
+ };
1708
+ }
1709
+ const dynamicTrigger = __privateGet(this, _registeredDynamicTriggers)[body.data.id];
1710
+ if (!dynamicTrigger) {
1711
+ return {
1712
+ status: 404,
1713
+ body: {
1714
+ message: "Dynamic trigger not found"
1715
+ }
1716
+ };
1717
+ }
1718
+ return {
1719
+ status: 200,
1720
+ body: dynamicTrigger.registeredTriggerForParams(body.data.params)
1721
+ };
1722
+ }
1723
+ case "EXECUTE_JOB": {
1724
+ const json = await request.json();
1725
+ const execution = RunJobBodySchema.safeParse(json);
1726
+ if (!execution.success) {
1727
+ return {
1728
+ status: 400,
1729
+ body: {
1730
+ message: "Invalid execution"
1731
+ }
1732
+ };
1733
+ }
1734
+ const job = __privateGet(this, _registeredJobs)[execution.data.job.id];
1735
+ if (!job) {
1736
+ return {
1737
+ status: 404,
1738
+ body: {
1739
+ message: "Job not found"
1740
+ }
1741
+ };
1742
+ }
1743
+ const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job);
1744
+ if (results.error) {
1745
+ return {
1746
+ status: 500,
1747
+ body: results.error
1748
+ };
1749
+ }
1750
+ return {
1751
+ status: 200,
1752
+ body: {
1753
+ completed: results.completed,
1754
+ output: results.output,
1755
+ executionId: execution.data.run.id,
1756
+ task: results.task
1757
+ }
1758
+ };
1759
+ }
1760
+ case "PREPROCESS_RUN": {
1761
+ const json = await request.json();
1762
+ const body = PreprocessRunBodySchema.safeParse(json);
1763
+ if (!body.success) {
1764
+ return {
1765
+ status: 400,
1766
+ body: {
1767
+ message: "Invalid body"
1768
+ }
1769
+ };
1770
+ }
1771
+ const job = __privateGet(this, _registeredJobs)[body.data.job.id];
1772
+ if (!job) {
1773
+ return {
1774
+ status: 404,
1775
+ body: {
1776
+ message: "Job not found"
1777
+ }
1778
+ };
1779
+ }
1780
+ const results = await __privateMethod(this, _preprocessRun, preprocessRun_fn).call(this, body.data, job);
1781
+ return {
1782
+ status: 200,
1783
+ body: {
1784
+ abort: results.abort,
1785
+ properties: results.properties
1786
+ }
1787
+ };
1788
+ }
1789
+ case "DELIVER_HTTP_SOURCE_REQUEST": {
1790
+ const headers = HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1791
+ if (!headers.success) {
1792
+ return {
1793
+ status: 400,
1794
+ body: {
1795
+ message: "Invalid headers"
1796
+ }
1797
+ };
1798
+ }
1799
+ const sourceRequest = new Request(headers.data["x-ts-http-url"], {
1800
+ method: headers.data["x-ts-http-method"],
1801
+ headers: headers.data["x-ts-http-headers"],
1802
+ body: headers.data["x-ts-http-method"] !== "GET" ? request.body : void 0
1803
+ });
1804
+ const key = headers.data["x-ts-key"];
1805
+ const dynamicId = headers.data["x-ts-dynamic-id"];
1806
+ const secret = headers.data["x-ts-secret"];
1807
+ const params = headers.data["x-ts-params"];
1808
+ const data = headers.data["x-ts-data"];
1809
+ const source = {
1810
+ key,
1811
+ dynamicId,
1812
+ secret,
1813
+ params,
1814
+ data
1815
+ };
1816
+ const { response, events } = await __privateMethod(this, _handleHttpSourceRequest, handleHttpSourceRequest_fn).call(this, source, sourceRequest);
1817
+ return {
1818
+ status: 200,
1819
+ body: {
1820
+ events,
1821
+ response
1822
+ }
1823
+ };
1824
+ }
1825
+ }
1826
+ return {
1827
+ status: 405,
1828
+ body: {
1829
+ message: "Method not allowed"
1830
+ }
1831
+ };
1832
+ }
1833
+ attach(job) {
1834
+ if (!job.enabled) {
1835
+ return;
1836
+ }
1837
+ __privateGet(this, _registeredJobs)[job.id] = job;
1838
+ job.trigger.attachToJob(this, job);
1839
+ }
1840
+ attachDynamicTrigger(trigger) {
1841
+ __privateGet(this, _registeredDynamicTriggers)[trigger.id] = trigger;
1842
+ new Job(this, {
1843
+ id: `register-dynamic-trigger-${trigger.id}`,
1844
+ name: `Register dynamic trigger ${trigger.id}`,
1845
+ version: trigger.source.version,
1846
+ trigger: new EventTrigger({
1847
+ event: registerSourceEvent,
1848
+ filter: {
1849
+ dynamicTriggerId: [
1850
+ trigger.id
1851
+ ]
1852
+ }
1853
+ }),
1854
+ integrations: {
1855
+ integration: trigger.source.integration
1856
+ },
1857
+ run: async (event, io, ctx) => {
1858
+ const updates = await trigger.source.register(event.source.params, event, io, ctx);
1859
+ if (!updates) {
1860
+ return;
1861
+ }
1862
+ return await io.updateSource("update-source", {
1863
+ key: event.source.key,
1864
+ ...updates
1865
+ });
1866
+ },
1867
+ __internal: true
1868
+ });
1869
+ }
1870
+ attachJobToDynamicTrigger(job, trigger) {
1871
+ const jobs = __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] ?? [];
1872
+ jobs.push({
1873
+ id: job.id,
1874
+ version: job.version
1875
+ });
1876
+ __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] = jobs;
1877
+ }
1878
+ attachSource(options) {
1879
+ __privateGet(this, _registeredHttpSourceHandlers)[options.key] = async (s, r) => {
1880
+ return await options.source.handle(s, r, __privateGet(this, _logger2));
1881
+ };
1882
+ let registeredSource = __privateGet(this, _registeredSources)[options.key];
1883
+ if (!registeredSource) {
1884
+ registeredSource = {
1885
+ channel: options.source.channel,
1886
+ key: options.key,
1887
+ params: options.params,
1888
+ events: [],
1889
+ clientId: !options.source.integration.usesLocalAuth ? options.source.integration.id : void 0
1890
+ };
1891
+ }
1892
+ registeredSource.events = Array.from(/* @__PURE__ */ new Set([
1893
+ ...registeredSource.events,
1894
+ options.event.name
1895
+ ]));
1896
+ __privateGet(this, _registeredSources)[options.key] = registeredSource;
1897
+ new Job(this, {
1898
+ id: options.key,
1899
+ name: options.key,
1900
+ version: options.source.version,
1901
+ trigger: new EventTrigger({
1902
+ event: registerSourceEvent,
1903
+ filter: {
1904
+ source: {
1905
+ key: [
1906
+ options.key
1907
+ ]
1908
+ }
1909
+ }
1910
+ }),
1911
+ integrations: {
1912
+ integration: options.source.integration
1913
+ },
1914
+ queue: {
1915
+ name: options.key,
1916
+ maxConcurrent: 1
1917
+ },
1918
+ startPosition: "initial",
1919
+ run: async (event, io, ctx) => {
1920
+ const updates = await options.source.register(options.params, event, io, ctx);
1921
+ if (!updates) {
1922
+ return;
1923
+ }
1924
+ return await io.updateSource("update-source", {
1925
+ key: options.key,
1926
+ ...updates
1927
+ });
1928
+ },
1929
+ __internal: true
1930
+ });
1931
+ }
1932
+ attachDynamicSchedule(key, job) {
1933
+ const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
1934
+ jobs.push({
1935
+ id: job.id,
1936
+ version: job.version
1937
+ });
1938
+ __privateGet(this, _registeredSchedules)[key] = jobs;
1384
1939
  }
1385
- delete(key) {
1386
- const operation = {
1387
- key,
1388
- namespace: this.namespace,
1389
- idempotencyKey: `delete:${this.namespace}:${key}:${this.deleteCount++}`
1390
- };
1391
- return this.onDelete(operation);
1940
+ async registerTrigger(id, key, options) {
1941
+ return __privateGet(this, _client).registerTrigger(this.id, id, key, options);
1392
1942
  }
1393
- };
1394
- __name(ContextKeyValueStorage, "ContextKeyValueStorage");
1395
-
1396
- // src/client.ts
1397
- var zodErrorMessageOptions = {
1398
- delimiter: {
1399
- error: " \u{1F525} "
1943
+ async getAuth(id) {
1944
+ return __privateGet(this, _client).getAuth(this.id, id);
1400
1945
  }
1401
- };
1402
- var _trigger, _options, _connection2, _serverRPC, _apiKey, _endpoint, _isConnected, _retryIntervalMs, _logger3, _closedByUser, _registerResponse, _responseCompleteCallbacks, _waitForCallbacks, _fetchCallbacks, _runOnceCallbacks, _kvGetCallbacks, _kvSetCallbacks, _kvDeleteCallbacks, _initializeConnection, initializeConnection_fn, _initializeRPC, initializeRPC_fn, _initializeHost, initializeHost_fn, _send, send_fn;
1403
- var TriggerClient = class {
1404
- constructor(trigger, options) {
1405
- __privateAdd(this, _initializeConnection);
1406
- __privateAdd(this, _initializeRPC);
1407
- __privateAdd(this, _initializeHost);
1408
- __privateAdd(this, _send);
1409
- __privateAdd(this, _trigger, void 0);
1410
- __privateAdd(this, _options, void 0);
1411
- __privateAdd(this, _connection2, void 0);
1412
- __privateAdd(this, _serverRPC, void 0);
1413
- __privateAdd(this, _apiKey, void 0);
1414
- __privateAdd(this, _endpoint, void 0);
1415
- __privateAdd(this, _isConnected, false);
1416
- __privateAdd(this, _retryIntervalMs, 3e3);
1417
- __privateAdd(this, _logger3, void 0);
1418
- __privateAdd(this, _closedByUser, false);
1419
- __privateAdd(this, _registerResponse, void 0);
1420
- __privateAdd(this, _responseCompleteCallbacks, /* @__PURE__ */ new Map());
1421
- __privateAdd(this, _waitForCallbacks, /* @__PURE__ */ new Map());
1422
- __privateAdd(this, _fetchCallbacks, /* @__PURE__ */ new Map());
1423
- __privateAdd(this, _runOnceCallbacks, /* @__PURE__ */ new Map());
1424
- __privateAdd(this, _kvGetCallbacks, /* @__PURE__ */ new Map());
1425
- __privateAdd(this, _kvSetCallbacks, /* @__PURE__ */ new Map());
1426
- __privateAdd(this, _kvDeleteCallbacks, /* @__PURE__ */ new Map());
1427
- __privateSet(this, _trigger, trigger);
1428
- __privateSet(this, _options, options);
1429
- const apiKey = __privateGet(this, _options).apiKey ?? process.env.TRIGGER_API_KEY;
1430
- if (!apiKey) {
1431
- throw new Error("Cannot connect to Trigger because of invalid API Key: Please include an API Key in the `apiKey` option or in the `TRIGGER_API_KEY` environment variable.");
1432
- }
1433
- __privateSet(this, _apiKey, apiKey);
1434
- __privateSet(this, _endpoint, __privateGet(this, _options).endpoint ?? process.env.TRIGGER_WSS_URL ?? "wss://wss.trigger.dev/ws");
1435
- __privateSet(this, _logger3, new Logger([
1436
- "trigger.dev",
1437
- __privateGet(this, _options).id
1438
- ], __privateGet(this, _options).logLevel));
1439
- }
1440
- async listen(instanceId) {
1441
- try {
1442
- await __privateMethod(this, _initializeConnection, initializeConnection_fn).call(this, instanceId);
1443
- __privateMethod(this, _initializeRPC, initializeRPC_fn).call(this);
1444
- await __privateMethod(this, _initializeHost, initializeHost_fn).call(this);
1445
- const terminalLink = (await import("terminal-link")).default;
1446
- if (__privateGet(this, _registerResponse)?.isNew) {
1447
- __privateGet(this, _logger3).logClean(`\u{1F389} Successfully registered "${__privateGet(this, _trigger).name}" to trigger.dev \u{1F449} ${terminalLink("View on dashboard", __privateGet(this, _registerResponse).url, {
1448
- fallback: (text, url) => `${text}: (${url})`
1449
- })}. Listening for events...`);
1450
- } else {
1451
- __privateGet(this, _logger3).log(`\u2728 Connected and listening for events \u{1F449} ${terminalLink("View on dashboard", __privateGet(this, _registerResponse).url, {
1452
- fallback: (text, url) => `${text}: (${url})`
1453
- })}`);
1454
- }
1455
- } catch (error) {
1456
- __privateGet(this, _logger3).log(`\u{1F6A9} Could not connect to trigger.dev`);
1457
- this.close();
1458
- }
1946
+ async sendEvent(event, options) {
1947
+ return __privateGet(this, _client).sendEvent(event, options);
1948
+ }
1949
+ async registerSchedule(id, key, schedule) {
1950
+ return __privateGet(this, _client).registerSchedule(this.id, id, key, schedule);
1459
1951
  }
1460
- close() {
1461
- __privateSet(this, _closedByUser, true);
1462
- if (__privateGet(this, _serverRPC)) {
1463
- __privateSet(this, _serverRPC, void 0);
1952
+ async unregisterSchedule(id, key) {
1953
+ return __privateGet(this, _client).unregisterSchedule(this.id, id, key);
1954
+ }
1955
+ authorized(apiKey) {
1956
+ const localApiKey = __privateGet(this, _options3).apiKey ?? process.env.TRIGGER_API_KEY;
1957
+ if (!localApiKey) {
1958
+ return false;
1464
1959
  }
1465
- __privateGet(this, _connection2)?.close();
1466
- __privateSet(this, _isConnected, false);
1960
+ return apiKey === localApiKey;
1961
+ }
1962
+ apiKey() {
1963
+ return __privateGet(this, _options3).apiKey ?? process.env.TRIGGER_API_KEY;
1964
+ }
1965
+ async listen() {
1966
+ await __privateGet(this, _client).registerEndpoint({
1967
+ url: this.url,
1968
+ name: this.id
1969
+ });
1467
1970
  }
1468
1971
  };
1469
1972
  __name(TriggerClient, "TriggerClient");
1470
- _trigger = new WeakMap();
1471
- _options = new WeakMap();
1472
- _connection2 = new WeakMap();
1473
- _serverRPC = new WeakMap();
1474
- _apiKey = new WeakMap();
1475
- _endpoint = new WeakMap();
1476
- _isConnected = new WeakMap();
1477
- _retryIntervalMs = new WeakMap();
1478
- _logger3 = new WeakMap();
1479
- _closedByUser = new WeakMap();
1480
- _registerResponse = new WeakMap();
1481
- _responseCompleteCallbacks = new WeakMap();
1482
- _waitForCallbacks = new WeakMap();
1483
- _fetchCallbacks = new WeakMap();
1484
- _runOnceCallbacks = new WeakMap();
1485
- _kvGetCallbacks = new WeakMap();
1486
- _kvSetCallbacks = new WeakMap();
1487
- _kvDeleteCallbacks = new WeakMap();
1488
- _initializeConnection = new WeakSet();
1489
- initializeConnection_fn = /* @__PURE__ */ __name(async function(instanceId) {
1490
- const id = instanceId ?? (0, import_uuid2.v4)();
1491
- __privateGet(this, _logger3).debug("Initializing connection", {
1492
- id,
1493
- endpoint: __privateGet(this, _endpoint)
1494
- });
1495
- const headers = {
1496
- Authorization: `Bearer ${__privateGet(this, _apiKey)}`
1973
+ _options3 = new WeakMap();
1974
+ _registeredJobs = new WeakMap();
1975
+ _registeredSources = new WeakMap();
1976
+ _registeredHttpSourceHandlers = new WeakMap();
1977
+ _registeredDynamicTriggers = new WeakMap();
1978
+ _jobMetadataByDynamicTriggers = new WeakMap();
1979
+ _registeredSchedules = new WeakMap();
1980
+ _client = new WeakMap();
1981
+ _logger2 = new WeakMap();
1982
+ _preprocessRun = new WeakSet();
1983
+ preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
1984
+ const context = __privateMethod(this, _createPreprocessRunContext, createPreprocessRunContext_fn).call(this, body);
1985
+ const parsedPayload = job.trigger.event.parsePayload(body.event.payload ?? {});
1986
+ const properties = job.trigger.event.runProperties?.(parsedPayload) ?? [];
1987
+ return {
1988
+ abort: false,
1989
+ properties
1497
1990
  };
1498
- const connection = new HostConnection(new import_ws.WebSocket(__privateGet(this, _endpoint), {
1499
- headers,
1500
- followRedirects: true
1501
- }), {
1502
- id
1991
+ }, "#preprocessRun");
1992
+ _executeJob = new WeakSet();
1993
+ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
1994
+ __privateGet(this, _logger2).debug("executing job", {
1995
+ execution: body1,
1996
+ job: job1.toJSON()
1503
1997
  });
1504
- connection.onClose.attach(async ([code, reason]) => {
1505
- if (__privateGet(this, _closedByUser)) {
1506
- __privateGet(this, _logger3).debug("Connection closed by user, so we won't reconnect");
1507
- __privateSet(this, _closedByUser, false);
1508
- return;
1998
+ const context = __privateMethod(this, _createRunContext, createRunContext_fn).call(this, body1);
1999
+ const io = new IO({
2000
+ id: body1.run.id,
2001
+ cachedTasks: body1.tasks,
2002
+ apiClient: __privateGet(this, _client),
2003
+ logger: __privateGet(this, _logger2),
2004
+ client: this,
2005
+ context
2006
+ });
2007
+ const ioWithConnections = createIOWithIntegrations(io, body1.connections, job1.options.integrations);
2008
+ try {
2009
+ const output = await job1.options.run(job1.trigger.event.parsePayload(body1.event.payload ?? {}), ioWithConnections, context);
2010
+ return {
2011
+ completed: true,
2012
+ output
2013
+ };
2014
+ } catch (error) {
2015
+ if (error instanceof ResumeWithTask) {
2016
+ return {
2017
+ completed: false,
2018
+ task: error.task
2019
+ };
1509
2020
  }
1510
- const chalk = (await import("chalk")).default;
1511
- __privateGet(this, _logger3).error(`${chalk.red("error")} Could not connect to trigger.dev${reason ? `: ${reason}` : `(code ${code})`}`);
1512
- if (!__privateGet(this, _isConnected))
1513
- return;
1514
- __privateGet(this, _logger3).log("\u{1F50C} Reconnecting to trigger.dev...");
1515
- __privateSet(this, _isConnected, false);
1516
- while (!__privateGet(this, _isConnected)) {
1517
- __privateMethod(this, _initializeConnection, initializeConnection_fn).call(this, id).then(() => {
1518
- __privateGet(this, _logger3).log("\u26A1 Reconnection successful");
1519
- }).catch(() => {
1520
- });
1521
- __privateGet(this, _logger3).debug(`Reconnection failed, retrying in ${Math.round(__privateGet(this, _retryIntervalMs) / 1e3)} seconds`, id);
1522
- await new Promise((resolve) => setTimeout(resolve, __privateGet(this, _retryIntervalMs)));
2021
+ const errorWithStack = ErrorWithStackSchema.safeParse(error);
2022
+ if (errorWithStack.success) {
2023
+ return {
2024
+ completed: true,
2025
+ error: errorWithStack.data
2026
+ };
2027
+ }
2028
+ const errorWithMessage = ErrorWithMessage.safeParse(error);
2029
+ if (errorWithMessage.success) {
2030
+ return {
2031
+ completed: true,
2032
+ error: errorWithMessage.data
2033
+ };
1523
2034
  }
2035
+ return {
2036
+ completed: true,
2037
+ error: {
2038
+ message: "Unknown error"
2039
+ }
2040
+ };
2041
+ }
2042
+ }, "#executeJob");
2043
+ _createRunContext = new WeakSet();
2044
+ createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2045
+ const { event, organization, environment, job, run } = execution;
2046
+ return {
2047
+ event: {
2048
+ id: event.id,
2049
+ name: event.name,
2050
+ context: event.context,
2051
+ timestamp: event.timestamp
2052
+ },
2053
+ organization,
2054
+ environment,
2055
+ job,
2056
+ run,
2057
+ account: execution.account
2058
+ };
2059
+ }, "#createRunContext");
2060
+ _createPreprocessRunContext = new WeakSet();
2061
+ createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body2) {
2062
+ const { event, organization, environment, job, run, account } = body2;
2063
+ return {
2064
+ event: {
2065
+ id: event.id,
2066
+ name: event.name,
2067
+ context: event.context,
2068
+ timestamp: event.timestamp
2069
+ },
2070
+ organization,
2071
+ environment,
2072
+ job,
2073
+ run,
2074
+ account
2075
+ };
2076
+ }, "#createPreprocessRunContext");
2077
+ _handleHttpSourceRequest = new WeakSet();
2078
+ handleHttpSourceRequest_fn = /* @__PURE__ */ __name(async function(source, sourceRequest) {
2079
+ __privateGet(this, _logger2).debug("Handling HTTP source request", {
2080
+ source
1524
2081
  });
1525
- await connection.connect();
1526
- __privateGet(this, _logger3).debug("Connection initialized", id);
1527
- __privateSet(this, _connection2, connection);
1528
- __privateSet(this, _isConnected, true);
1529
- if (__privateGet(this, _serverRPC)) {
1530
- __privateGet(this, _serverRPC).resetConnection(connection);
1531
- await __privateMethod(this, _initializeHost, initializeHost_fn).call(this);
1532
- }
1533
- }, "#initializeConnection");
1534
- _initializeRPC = new WeakSet();
1535
- initializeRPC_fn = /* @__PURE__ */ __name(async function() {
1536
- if (!__privateGet(this, _connection2)) {
1537
- throw new Error("Cannot initialize RPC without a connection");
1538
- }
1539
- const serverRPC = new ZodRPC({
1540
- connection: __privateGet(this, _connection2),
1541
- sender: ServerRPCSchema,
1542
- receiver: HostRPCSchema,
1543
- handlers: {
1544
- RESOLVE_DELAY: async (data) => {
1545
- __privateGet(this, _logger3).debug("Handling RESOLVE_DELAY", data);
1546
- const waitCallbacks = __privateGet(this, _waitForCallbacks).get(messageKey(data.meta.runId, data.key));
1547
- if (!waitCallbacks) {
1548
- __privateGet(this, _logger3).debug(`Could not find wait callbacks for wait ID ${messageKey(data.meta.runId, data.key)}. This can happen when a workflow run is resumed`);
1549
- return true;
1550
- }
1551
- const { resolve } = waitCallbacks;
1552
- resolve();
1553
- return true;
1554
- },
1555
- RESOLVE_RUN_ONCE: async (data) => {
1556
- __privateGet(this, _logger3).debug("Handling RESOLVE_RUN_ONCE", data);
1557
- const runOnceCallbacks = __privateGet(this, _runOnceCallbacks).get(messageKey(data.meta.runId, data.key));
1558
- if (!runOnceCallbacks) {
1559
- __privateGet(this, _logger3).debug(`Could not find runOnce callbacks for request ID ${messageKey(data.meta.runId, data.key)}. This can happen when a workflow run is resumed`);
1560
- return true;
1561
- }
1562
- const { resolve } = runOnceCallbacks;
1563
- resolve(data.output);
1564
- return true;
1565
- },
1566
- RESOLVE_REQUEST: async (data) => {
1567
- __privateGet(this, _logger3).debug("Handling RESOLVE_REQUEST", data);
1568
- const requestCallbacks = __privateGet(this, _responseCompleteCallbacks).get(messageKey(data.meta.runId, data.key));
1569
- if (!requestCallbacks) {
1570
- __privateGet(this, _logger3).debug(`Could not find request callbacks for request ID ${messageKey(data.meta.runId, data.key)}. This can happen when a workflow run is resumed`);
1571
- return true;
1572
- }
1573
- const { resolve } = requestCallbacks;
1574
- resolve(data.output);
1575
- return true;
1576
- },
1577
- REJECT_REQUEST: async (data) => {
1578
- __privateGet(this, _logger3).debug("Handling REJECT_REQUEST", data);
1579
- const requestCallbacks = __privateGet(this, _responseCompleteCallbacks).get(messageKey(data.meta.runId, data.key));
1580
- if (!requestCallbacks) {
1581
- __privateGet(this, _logger3).debug(`Could not find request callbacks for request ID ${messageKey(data.meta.runId, data.key)}. This can happen when a workflow run is resumed`);
1582
- return true;
1583
- }
1584
- const { reject } = requestCallbacks;
1585
- reject(data.error);
1586
- return true;
1587
- },
1588
- RESOLVE_FETCH_REQUEST: async (data) => {
1589
- __privateGet(this, _logger3).debug("Handling RESOLVE_FETCH_REQUEST", data);
1590
- const fetchCallbacks = __privateGet(this, _fetchCallbacks).get(messageKey(data.meta.runId, data.key));
1591
- if (!fetchCallbacks) {
1592
- __privateGet(this, _logger3).debug(`Could not find fetch callbacks for request ID ${messageKey(data.meta.runId, data.key)}. This can happen when a workflow run is resumed`);
1593
- return true;
1594
- }
1595
- const { resolve } = fetchCallbacks;
1596
- resolve(data.output);
1597
- return true;
1598
- },
1599
- REJECT_FETCH_REQUEST: async (data) => {
1600
- __privateGet(this, _logger3).debug("Handling REJECT_FETCH_REQUEST", data);
1601
- const fetchCallbacks = __privateGet(this, _fetchCallbacks).get(messageKey(data.meta.runId, data.key));
1602
- if (!fetchCallbacks) {
1603
- __privateGet(this, _logger3).debug(`Could not find fetch callbacks for request ID ${messageKey(data.meta.runId, data.key)}. This can happen when a workflow run is resumed`);
1604
- return true;
1605
- }
1606
- const { reject } = fetchCallbacks;
1607
- reject(data.error);
1608
- return true;
1609
- },
1610
- RESOLVE_KV_GET: async (data) => {
1611
- __privateGet(this, _logger3).debug("Handling RESOLVE_KV_GET", data);
1612
- const getCallbacks = __privateGet(this, _kvGetCallbacks).get(messageKey(data.meta.runId, data.key));
1613
- if (!getCallbacks) {
1614
- __privateGet(this, _logger3).debug(`Could not find kvGet callbacks for request ID ${messageKey(data.meta.runId, data.key)}. This can happen when a workflow run is resumed`);
1615
- return true;
2082
+ if (source.dynamicId) {
2083
+ const dynamicTrigger = __privateGet(this, _registeredDynamicTriggers)[source.dynamicId];
2084
+ if (!dynamicTrigger) {
2085
+ __privateGet(this, _logger2).debug("No dynamic trigger registered for HTTP source", {
2086
+ source
2087
+ });
2088
+ return {
2089
+ response: {
2090
+ status: 200,
2091
+ body: {
2092
+ ok: true
2093
+ }
2094
+ },
2095
+ events: []
2096
+ };
2097
+ }
2098
+ const results2 = await dynamicTrigger.source.handle(source, sourceRequest, __privateGet(this, _logger2));
2099
+ if (!results2) {
2100
+ return {
2101
+ events: [],
2102
+ response: {
2103
+ status: 200,
2104
+ body: {
2105
+ ok: true
2106
+ }
1616
2107
  }
1617
- const { resolve } = getCallbacks;
1618
- resolve(data.output);
1619
- return true;
1620
- },
1621
- RESOLVE_KV_SET: async (data) => {
1622
- __privateGet(this, _logger3).debug("Handling RESOLVE_KV_SET", data);
1623
- const setCallbacks = __privateGet(this, _kvSetCallbacks).get(messageKey(data.meta.runId, data.key));
1624
- if (!setCallbacks) {
1625
- __privateGet(this, _logger3).debug(`Could not find kvSet callbacks for request ID ${messageKey(data.meta.runId, data.key)}. This can happen when a workflow run is resumed`);
1626
- return true;
2108
+ };
2109
+ }
2110
+ return {
2111
+ events: results2.events,
2112
+ response: results2.response ?? {
2113
+ status: 200,
2114
+ body: {
2115
+ ok: true
1627
2116
  }
1628
- const { resolve } = setCallbacks;
1629
- resolve();
1630
- return true;
1631
- },
1632
- RESOLVE_KV_DELETE: async (data) => {
1633
- __privateGet(this, _logger3).debug("Handling RESOLVE_KV_DELETE", data);
1634
- const deleteCallbacks = __privateGet(this, _kvDeleteCallbacks).get(messageKey(data.meta.runId, data.key));
1635
- if (!deleteCallbacks) {
1636
- __privateGet(this, _logger3).debug(`Could not find kvDelete callbacks for request ID ${messageKey(data.meta.runId, data.key)}. This can happen when a workflow run is resumed`);
1637
- return true;
2117
+ }
2118
+ };
2119
+ }
2120
+ const handler = __privateGet(this, _registeredHttpSourceHandlers)[source.key];
2121
+ if (!handler) {
2122
+ __privateGet(this, _logger2).debug("No handler registered for HTTP source", {
2123
+ source
2124
+ });
2125
+ return {
2126
+ response: {
2127
+ status: 200,
2128
+ body: {
2129
+ ok: true
1638
2130
  }
1639
- const { resolve } = deleteCallbacks;
1640
- resolve();
1641
- return true;
1642
2131
  },
1643
- TRIGGER_WORKFLOW: async (data) => {
1644
- __privateGet(this, _logger3).debug("Handling TRIGGER_WORKFLOW", data);
1645
- const parsedEventData = __privateGet(this, _options).on.schema.safeParse(data.trigger.input);
1646
- if (!parsedEventData.success) {
1647
- await serverRPC.send("SEND_WORKFLOW_ERROR", {
1648
- runId: data.id,
1649
- timestamp: String(highPrecisionTimestamp()),
1650
- error: {
1651
- name: "Event validation error",
1652
- message: (0, import_zod_error.generateErrorMessage)(parsedEventData.error.issues, zodErrorMessageOptions)
1653
- }
1654
- });
1655
- return true;
2132
+ events: []
2133
+ };
2134
+ }
2135
+ const results = await handler(source, sourceRequest);
2136
+ if (!results) {
2137
+ return {
2138
+ events: [],
2139
+ response: {
2140
+ status: 200,
2141
+ body: {
2142
+ ok: true
1656
2143
  }
1657
- const fetchFunction = /* @__PURE__ */ __name(async (key, url, options) => {
1658
- const result = new Promise((resolve, reject) => {
1659
- __privateGet(this, _fetchCallbacks).set(messageKey(data.id, key), {
1660
- resolve,
1661
- reject
1662
- });
1663
- });
1664
- await serverRPC.send("SEND_FETCH", {
1665
- runId: data.id,
1666
- key,
1667
- fetch: {
1668
- url: url.toString(),
1669
- method: options.method ?? "GET",
1670
- headers: options.headers,
1671
- body: options.body,
1672
- retry: options.retry
1673
- },
1674
- timestamp: String(highPrecisionTimestamp())
1675
- });
1676
- const response = await result;
1677
- return {
1678
- status: response.status,
1679
- ok: response.ok,
1680
- headers: response.headers,
1681
- body: response.body ? (options.responseSchema ?? import_zod15.z.any()).parse(response.body) : void 0
1682
- };
1683
- }, "fetchFunction");
1684
- const kvGetFunction = /* @__PURE__ */ __name(async (op) => {
1685
- const result = new Promise((resolve, reject) => {
1686
- __privateGet(this, _kvGetCallbacks).set(messageKey(data.id, op.idempotencyKey), {
1687
- resolve,
1688
- reject
1689
- });
1690
- });
1691
- await serverRPC.send("SEND_KV_GET", {
1692
- runId: data.id,
1693
- key: op.idempotencyKey,
1694
- get: {
1695
- namespace: op.namespace,
1696
- key: op.key
1697
- },
1698
- timestamp: String(highPrecisionTimestamp())
1699
- });
1700
- const output = await result;
1701
- return output;
1702
- }, "kvGetFunction");
1703
- const kvSetFunction = /* @__PURE__ */ __name(async (op) => {
1704
- const result = new Promise((resolve, reject) => {
1705
- __privateGet(this, _kvSetCallbacks).set(messageKey(data.id, op.idempotencyKey), {
1706
- resolve,
1707
- reject
1708
- });
1709
- });
1710
- await serverRPC.send("SEND_KV_SET", {
1711
- runId: data.id,
1712
- key: op.idempotencyKey,
1713
- set: {
1714
- namespace: op.namespace,
1715
- key: op.key,
1716
- value: op.value
1717
- },
1718
- timestamp: String(highPrecisionTimestamp())
1719
- });
1720
- await result;
1721
- return;
1722
- }, "kvSetFunction");
1723
- const kvDeleteFunction = /* @__PURE__ */ __name(async (op) => {
1724
- const result = new Promise((resolve, reject) => {
1725
- __privateGet(this, _kvDeleteCallbacks).set(messageKey(data.id, op.idempotencyKey), {
1726
- resolve,
1727
- reject
1728
- });
1729
- });
1730
- await serverRPC.send("SEND_KV_DELETE", {
1731
- runId: data.id,
1732
- key: op.idempotencyKey,
1733
- delete: {
1734
- namespace: op.namespace,
1735
- key: op.key
1736
- },
1737
- timestamp: String(highPrecisionTimestamp())
1738
- });
1739
- await result;
1740
- return;
1741
- }, "kvDeleteFunction");
1742
- const ctx = {
1743
- id: data.id,
1744
- environment: data.meta.environment,
1745
- apiKey: data.meta.apiKey,
1746
- organizationId: data.meta.organizationId,
1747
- isTest: data.meta.isTest,
1748
- kv: new ContextKeyValueStorage(`workflow:${data.meta.workflowId}`, kvGetFunction, kvSetFunction, kvDeleteFunction),
1749
- globalKv: new ContextKeyValueStorage(`org:${data.meta.organizationId}`, kvGetFunction, kvSetFunction, kvDeleteFunction),
1750
- runKv: new ContextKeyValueStorage(`run:${data.id}`, kvGetFunction, kvSetFunction, kvDeleteFunction),
1751
- logger: new ContextLogger(async (level, message, properties) => {
1752
- await serverRPC.send("SEND_LOG", {
1753
- runId: data.id,
1754
- key: message,
1755
- log: {
1756
- level,
1757
- message,
1758
- properties: JSON.stringify(properties ?? {})
1759
- },
1760
- timestamp: String(highPrecisionTimestamp())
1761
- });
1762
- }),
1763
- sendEvent: async (key, event) => {
1764
- await serverRPC.send("SEND_EVENT", {
1765
- runId: data.id,
1766
- key,
1767
- event: JSON.parse(JSON.stringify(event)),
1768
- timestamp: String(highPrecisionTimestamp())
1769
- });
1770
- },
1771
- waitFor: async (key, options) => {
1772
- const result = new Promise((resolve, reject) => {
1773
- __privateGet(this, _waitForCallbacks).set(messageKey(data.id, key), {
1774
- resolve,
1775
- reject
1776
- });
1777
- });
1778
- await serverRPC.send("INITIALIZE_DELAY", {
1779
- runId: data.id,
1780
- key,
1781
- wait: {
1782
- type: "DELAY",
1783
- seconds: options.seconds,
1784
- minutes: options.minutes,
1785
- hours: options.hours,
1786
- days: options.days
1787
- },
1788
- timestamp: String(highPrecisionTimestamp())
1789
- });
1790
- await result;
1791
- return;
1792
- },
1793
- waitUntil: async (key, date) => {
1794
- const result = new Promise((resolve, reject) => {
1795
- __privateGet(this, _waitForCallbacks).set(messageKey(data.id, key), {
1796
- resolve,
1797
- reject
1798
- });
1799
- });
1800
- await serverRPC.send("INITIALIZE_DELAY", {
1801
- runId: data.id,
1802
- key,
1803
- wait: {
1804
- type: "SCHEDULE_FOR",
1805
- scheduledFor: date.toISOString()
1806
- },
1807
- timestamp: String(highPrecisionTimestamp())
1808
- });
1809
- await result;
1810
- return;
1811
- },
1812
- runOnce: async (key, callback) => {
1813
- const result = new Promise((resolve, reject) => {
1814
- __privateGet(this, _runOnceCallbacks).set(messageKey(data.id, key), {
1815
- resolve,
1816
- reject
1817
- });
1818
- });
1819
- await serverRPC.send("INITIALIZE_RUN_ONCE", {
1820
- runId: data.id,
1821
- key,
1822
- runOnce: {
1823
- type: "REMOTE"
1824
- },
1825
- timestamp: String(highPrecisionTimestamp())
1826
- });
1827
- const { idempotencyKey, hasRun, output } = await result;
1828
- if (hasRun) {
1829
- return output;
1830
- }
1831
- const callbackResult = await callback(idempotencyKey);
1832
- await serverRPC.send("COMPLETE_RUN_ONCE", {
1833
- runId: data.id,
1834
- key,
1835
- runOnce: {
1836
- type: "REMOTE",
1837
- idempotencyKey,
1838
- output: callbackResult ? JSON.stringify(callbackResult) : void 0
1839
- },
1840
- timestamp: String(highPrecisionTimestamp())
1841
- });
1842
- return callbackResult;
1843
- },
1844
- runOnceLocalOnly: async (key, callback) => {
1845
- const result = new Promise((resolve, reject) => {
1846
- __privateGet(this, _runOnceCallbacks).set(messageKey(data.id, key), {
1847
- resolve,
1848
- reject
1849
- });
1850
- });
1851
- await serverRPC.send("INITIALIZE_RUN_ONCE", {
1852
- runId: data.id,
1853
- key,
1854
- runOnce: {
1855
- type: "LOCAL_ONLY"
1856
- },
1857
- timestamp: String(highPrecisionTimestamp())
1858
- });
1859
- const { idempotencyKey } = await result;
1860
- return callback(idempotencyKey);
1861
- },
1862
- fetch: fetchFunction
1863
- };
1864
- const eventData = parsedEventData.data;
1865
- __privateGet(this, _logger3).debug("Parsed event data", eventData);
1866
- const terminalLink = (await import("terminal-link")).default;
1867
- triggerRunLocalStorage.run({
1868
- performRequest: async (key, options) => {
1869
- const result = new Promise((resolve, reject) => {
1870
- __privateGet(this, _responseCompleteCallbacks).set(messageKey(data.id, key), {
1871
- resolve,
1872
- reject
1873
- });
1874
- });
1875
- await serverRPC.send("SEND_REQUEST", {
1876
- runId: data.id,
1877
- key,
1878
- request: {
1879
- service: options.service,
1880
- endpoint: options.endpoint,
1881
- params: options.params,
1882
- version: options.version
1883
- },
1884
- timestamp: String(highPrecisionTimestamp())
1885
- });
1886
- const output = await result;
1887
- if (!options.response?.schema) {
1888
- return output;
1889
- }
1890
- return options.response.schema.parse(output);
1891
- },
1892
- sendEvent: async (key, event) => {
1893
- await serverRPC.send("SEND_EVENT", {
1894
- runId: data.id,
1895
- key,
1896
- event: JSON.parse(JSON.stringify(event)),
1897
- timestamp: String(highPrecisionTimestamp())
1898
- });
1899
- },
1900
- fetch: fetchFunction,
1901
- workflowId: data.meta.workflowId,
1902
- appOrigin: data.meta.appOrigin,
1903
- id: data.id
1904
- }, () => {
1905
- __privateGet(this, _logger3).debug("Running trigger...");
1906
- if (typeof data.meta.attempt === "number" && data.meta.attempt === 0) {
1907
- __privateGet(this, _logger3).log(`Run ${data.id} started \u{1F449} ${terminalLink("View on dashboard", `${__privateGet(this, _registerResponse).url}/runs/${data.id}`, {
1908
- fallback: (text, url) => `${text}: (${url})`
1909
- })}`);
1910
- }
1911
- serverRPC.send("START_WORKFLOW_RUN", {
1912
- runId: data.id,
1913
- timestamp: String(highPrecisionTimestamp())
1914
- }).then(() => {
1915
- return __privateGet(this, _trigger).options.run(eventData, ctx).then((output) => {
1916
- __privateGet(this, _logger3).log(`Run ${data.id} complete \u{1F449} ${terminalLink("View on dashboard", `${__privateGet(this, _registerResponse).url}/runs/${data.id}`, {
1917
- fallback: (text, url) => `${text}: (${url})`
1918
- })}`);
1919
- return serverRPC.send("COMPLETE_WORKFLOW_RUN", {
1920
- runId: data.id,
1921
- output: JSON.stringify(output),
1922
- timestamp: String(highPrecisionTimestamp())
1923
- });
1924
- }).catch((anyError) => {
1925
- const parseAnyError = /* @__PURE__ */ __name((error2) => {
1926
- if (error2 instanceof Error) {
1927
- return {
1928
- name: error2.name,
1929
- message: error2.message,
1930
- stackTrace: error2.stack
1931
- };
1932
- }
1933
- const parsedError = import_zod15.z.object({
1934
- name: import_zod15.z.string(),
1935
- message: import_zod15.z.string()
1936
- }).passthrough().safeParse(error2);
1937
- if (parsedError.success) {
1938
- return parsedError.data;
1939
- }
1940
- return {
1941
- name: "UnknownError",
1942
- message: "An unknown error occurred"
1943
- };
1944
- }, "parseAnyError");
1945
- const error = parseAnyError(anyError);
1946
- return serverRPC.send("SEND_WORKFLOW_ERROR", {
1947
- runId: data.id,
1948
- error,
1949
- timestamp: String(highPrecisionTimestamp())
1950
- });
1951
- });
1952
- }).catch((anyError) => {
1953
- return serverRPC.send("SEND_WORKFLOW_ERROR", {
1954
- runId: data.id,
1955
- error: anyError,
1956
- timestamp: String(highPrecisionTimestamp())
1957
- });
1958
- });
1959
- });
1960
- return true;
1961
- }
1962
- }
1963
- });
1964
- __privateGet(this, _logger3).debug("Successfully initialized RPC with server");
1965
- __privateSet(this, _serverRPC, serverRPC);
1966
- }, "#initializeRPC");
1967
- _initializeHost = new WeakSet();
1968
- initializeHost_fn = /* @__PURE__ */ __name(async function() {
1969
- if (!__privateGet(this, _connection2)) {
1970
- throw new Error("Cannot initialize host without a connection");
1971
- }
1972
- if (!__privateGet(this, _serverRPC)) {
1973
- throw new Error("Cannot initialize host without an RPC connection");
1974
- }
1975
- const repoInfo = await safeGetRepoInfo();
1976
- const remoteUrl = repoInfo ? await getRemoteUrl(repoInfo.commonGitDir) : void 0;
1977
- const packageMetadata = await getTriggerPackageEnvVars(process.env);
1978
- const response = await __privateMethod(this, _send, send_fn).call(this, "INITIALIZE_HOST_V2", {
1979
- apiKey: __privateGet(this, _apiKey),
1980
- workflowId: __privateGet(this, _trigger).id,
1981
- workflowName: __privateGet(this, _trigger).name,
1982
- trigger: __privateGet(this, _trigger).on.metadata,
1983
- packageVersion: version,
1984
- packageName: name,
1985
- triggerTTL: __privateGet(this, _options).triggerTTL,
1986
- metadata: {
1987
- git: repoInfo ? {
1988
- sha: repoInfo.sha,
1989
- branch: repoInfo.branch,
1990
- committer: repoInfo.committer,
1991
- committerDate: repoInfo.committerDate,
1992
- commitMessage: repoInfo.commitMessage,
1993
- origin: remoteUrl
1994
- } : void 0,
1995
- packageMetadata,
1996
- env: gatherEnvVars(process.env)
1997
- }
1998
- });
1999
- if (!response) {
2000
- throw new Error("Could not initialize workflow with server");
2001
- }
2002
- if (response?.type === "error") {
2003
- throw new Error(response.message);
2004
- }
2005
- __privateSet(this, _registerResponse, response.data);
2006
- __privateGet(this, _logger3).debug("Successfully initialized workflow with server");
2007
- }, "#initializeHost");
2008
- _send = new WeakSet();
2009
- send_fn = /* @__PURE__ */ __name(async function(methodName, request) {
2010
- if (!__privateGet(this, _serverRPC))
2011
- throw new Error("serverRPC not initialized");
2012
- while (true) {
2013
- try {
2014
- __privateGet(this, _logger3).debug(`Sending RPC request to server: ${methodName}`, request);
2015
- return await __privateGet(this, _serverRPC).send(methodName, request);
2016
- } catch (err) {
2017
- if (err instanceof TimeoutError) {
2018
- __privateGet(this, _logger3).log(`RPC call timed out, retrying in ${Math.round(__privateGet(this, _retryIntervalMs) / 1e3)}s...`);
2019
- __privateGet(this, _logger3).error(err);
2020
- await sleep(__privateGet(this, _retryIntervalMs));
2021
- } else {
2022
- throw err;
2023
2144
  }
2024
- }
2145
+ };
2025
2146
  }
2026
- }, "#send");
2027
- var sleep = /* @__PURE__ */ __name((ms) => new Promise((resolve) => setTimeout(resolve, ms)), "sleep");
2028
- var messageKey = /* @__PURE__ */ __name((runId, key) => `${runId}:${key}`, "messageKey");
2029
- function highPrecisionTimestamp() {
2030
- const [seconds, nanoseconds] = process.hrtime();
2031
- return seconds * 1e9 + nanoseconds;
2032
- }
2033
- __name(highPrecisionTimestamp, "highPrecisionTimestamp");
2034
- async function getTriggerPackageEnvVars(env) {
2035
- if (!env) {
2036
- return {};
2037
- }
2038
- if (env.npm_package_json) {
2039
- try {
2040
- const packageJson = JSON.parse(await (0, import_promises.readFile)(env.npm_package_json, "utf8"));
2041
- if (packageJson.triggerdotdev) {
2042
- return packageJson.triggerdotdev;
2147
+ return {
2148
+ events: results.events,
2149
+ response: results.response ?? {
2150
+ status: 200,
2151
+ body: {
2152
+ ok: true
2043
2153
  }
2044
- } catch (err) {
2045
2154
  }
2155
+ };
2156
+ }, "#handleHttpSourceRequest");
2157
+ function buildClientUrl(url) {
2158
+ if (!url) {
2159
+ const host = process.env.TRIGGER_CLIENT_HOST ?? process.env.HOST ?? process.env.HOSTNAME ?? process.env.NOW_URL ?? process.env.VERCEL_URL;
2160
+ if (host) {
2161
+ return "https://" + host;
2162
+ }
2163
+ throw new Error("Could not determine the url for this TriggerClient. Please set the TRIGGER_CLIENT_HOST environment variable or pass in the `url` option to the TriggerClient constructor.");
2164
+ }
2165
+ if (!url.startsWith("http")) {
2166
+ return "https://" + url;
2046
2167
  }
2047
- const envVars = Object.entries(env).filter(([key]) => key.startsWith("npm_package_triggerdotdev_")).map(([key, value]) => [
2048
- key.replace("npm_package_triggerdotdev_", ""),
2049
- value
2050
- ]);
2051
- return Object.fromEntries(envVars);
2168
+ return url;
2052
2169
  }
2053
- __name(getTriggerPackageEnvVars, "getTriggerPackageEnvVars");
2054
- async function getRemoteUrl(cwd) {
2055
- try {
2056
- const gitRemoteOriginUrl = (await import("git-remote-origin-url")).default;
2057
- return await gitRemoteOriginUrl({
2058
- cwd
2170
+ __name(buildClientUrl, "buildClientUrl");
2171
+
2172
+ // src/integrations.ts
2173
+ function authenticatedTask(options) {
2174
+ return options;
2175
+ }
2176
+ __name(authenticatedTask, "authenticatedTask");
2177
+
2178
+ // src/triggers/externalSource.ts
2179
+ var ExternalSource = class {
2180
+ constructor(channel, options) {
2181
+ this.options = options;
2182
+ this.channel = channel;
2183
+ }
2184
+ async handle(source, rawEvent, logger) {
2185
+ return this.options.handler({
2186
+ source: {
2187
+ ...source,
2188
+ params: source.params
2189
+ },
2190
+ rawEvent
2191
+ }, logger);
2192
+ }
2193
+ filter(params) {
2194
+ return this.options.filter(params);
2195
+ }
2196
+ properties(params) {
2197
+ return this.options.properties?.(params) ?? [];
2198
+ }
2199
+ async register(params, registerEvent, io, ctx) {
2200
+ const { result: event, ommited: source } = omit(registerEvent, "source");
2201
+ const { result: sourceWithoutChannel, ommited: channel } = omit(source, "channel");
2202
+ const { result: channelWithoutType } = omit(channel, "type");
2203
+ const updates = await this.options.register({
2204
+ ...event,
2205
+ source: {
2206
+ ...sourceWithoutChannel,
2207
+ ...channelWithoutType
2208
+ },
2209
+ params
2210
+ }, io, ctx);
2211
+ return updates;
2212
+ }
2213
+ key(params) {
2214
+ const parts = [
2215
+ this.options.id,
2216
+ this.channel
2217
+ ];
2218
+ parts.push(this.options.key(params));
2219
+ parts.push(this.integration.id);
2220
+ return parts.join("-");
2221
+ }
2222
+ get integration() {
2223
+ return this.options.integration;
2224
+ }
2225
+ get integrationConfig() {
2226
+ return {
2227
+ id: this.integration.id,
2228
+ metadata: this.integration.metadata
2229
+ };
2230
+ }
2231
+ get id() {
2232
+ return this.options.id;
2233
+ }
2234
+ get version() {
2235
+ return this.options.version;
2236
+ }
2237
+ };
2238
+ __name(ExternalSource, "ExternalSource");
2239
+ var ExternalSourceTrigger = class {
2240
+ constructor(options) {
2241
+ this.options = options;
2242
+ }
2243
+ get event() {
2244
+ return this.options.event;
2245
+ }
2246
+ toJSON() {
2247
+ return {
2248
+ type: "static",
2249
+ title: "External Source",
2250
+ rule: {
2251
+ event: this.event.name,
2252
+ payload: deepMergeFilters(this.options.source.filter(this.options.params), this.event.filter ?? {}),
2253
+ source: this.event.source
2254
+ },
2255
+ properties: this.options.source.properties(this.options.params)
2256
+ };
2257
+ }
2258
+ attachToJob(triggerClient, job) {
2259
+ triggerClient.attachSource({
2260
+ key: slugifyId(this.options.source.key(this.options.params)),
2261
+ source: this.options.source,
2262
+ event: this.options.event,
2263
+ params: this.options.params
2059
2264
  });
2060
- } catch (err) {
2061
- return;
2062
2265
  }
2063
- }
2064
- __name(getRemoteUrl, "getRemoteUrl");
2065
- async function safeGetRepoInfo() {
2066
- try {
2067
- const gitRepoInfo = (await import("git-repo-info")).default;
2068
- return gitRepoInfo();
2069
- } catch (err) {
2070
- return;
2266
+ get preprocessRuns() {
2267
+ return true;
2071
2268
  }
2269
+ };
2270
+ __name(ExternalSourceTrigger, "ExternalSourceTrigger");
2271
+ function omit(obj, key) {
2272
+ const result = {};
2273
+ for (const k of Object.keys(obj)) {
2274
+ if (k === key)
2275
+ continue;
2276
+ result[k] = obj[k];
2277
+ }
2278
+ return {
2279
+ result,
2280
+ ommited: obj[key]
2281
+ };
2072
2282
  }
2073
- __name(safeGetRepoInfo, "safeGetRepoInfo");
2074
- function gatherEnvVars(env) {
2075
- if (!env) {
2076
- return {};
2077
- }
2078
- const envVars = Object.entries(env).filter(([key]) => key.startsWith("TRIGGER_") && key !== "TRIGGER_API_KEY").map(([key, value]) => [
2079
- key.replace("TRIGGER_", ""),
2080
- `${value}`
2081
- ]);
2082
- return Object.fromEntries(envVars);
2083
- }
2084
- __name(gatherEnvVars, "gatherEnvVars");
2283
+ __name(omit, "omit");
2284
+
2285
+ // src/triggers/dynamic.ts
2286
+ var _client2, _options4;
2287
+ var DynamicTrigger = class {
2288
+ constructor(client, options) {
2289
+ __privateAdd(this, _client2, void 0);
2290
+ __privateAdd(this, _options4, void 0);
2291
+ __privateSet(this, _client2, client);
2292
+ __privateSet(this, _options4, options);
2293
+ this.source = options.source;
2294
+ client.attachDynamicTrigger(this);
2295
+ }
2296
+ toJSON() {
2297
+ return {
2298
+ type: "dynamic",
2299
+ id: __privateGet(this, _options4).id
2300
+ };
2301
+ }
2302
+ get id() {
2303
+ return __privateGet(this, _options4).id;
2304
+ }
2305
+ get event() {
2306
+ return __privateGet(this, _options4).event;
2307
+ }
2308
+ registeredTriggerForParams(params) {
2309
+ return {
2310
+ rule: {
2311
+ event: this.event.name,
2312
+ source: this.event.source,
2313
+ payload: deepMergeFilters(this.source.filter(params), this.event.filter ?? {})
2314
+ },
2315
+ source: {
2316
+ key: slugifyId(this.source.key(params)),
2317
+ channel: this.source.channel,
2318
+ params,
2319
+ events: [
2320
+ this.event.name
2321
+ ],
2322
+ clientId: !this.source.integration.usesLocalAuth ? this.source.integration.id : void 0
2323
+ }
2324
+ };
2325
+ }
2326
+ async register(key, params) {
2327
+ return __privateGet(this, _client2).registerTrigger(this.id, key, this.registeredTriggerForParams(params));
2328
+ }
2329
+ attachToJob(triggerClient, job) {
2330
+ triggerClient.attachJobToDynamicTrigger(job, this);
2331
+ }
2332
+ get preprocessRuns() {
2333
+ return false;
2334
+ }
2335
+ };
2336
+ __name(DynamicTrigger, "DynamicTrigger");
2337
+ _client2 = new WeakMap();
2338
+ _options4 = new WeakMap();
2085
2339
 
2086
- // src/trigger/index.ts
2087
- var _client, _getApiKey, getApiKey_fn;
2088
- var Trigger = class {
2340
+ // src/triggers/scheduled.ts
2341
+ var IntervalTrigger = class {
2089
2342
  constructor(options) {
2090
- __privateAdd(this, _getApiKey);
2091
- __privateAdd(this, _client, void 0);
2092
2343
  this.options = options;
2093
2344
  }
2094
- async listen() {
2095
- const apiKey = __privateMethod(this, _getApiKey, getApiKey_fn).call(this);
2096
- const chalk = (await import("chalk")).default;
2097
- const terminalLink = (await import("terminal-link")).default;
2098
- if (apiKey.status === "invalid") {
2099
- console.log(`${chalk.red("Trigger.dev error")}: ${chalk.bold(this.id)} is has an invalid API key ("${chalk.italic(apiKey.apiKey)}"), please set the TRIGGER_API_KEY environment variable or pass the apiKey option to a valid value. ${terminalLink("Get your API key here", "https://app.trigger.dev", {
2100
- fallback(text, url) {
2101
- return `${text} \u{1F449} ${url}`;
2345
+ get event() {
2346
+ return {
2347
+ name: "trigger.scheduled",
2348
+ title: "Schedule",
2349
+ source: "trigger.dev",
2350
+ icon: "schedule-interval",
2351
+ parsePayload: ScheduledPayloadSchema.parse,
2352
+ properties: [
2353
+ {
2354
+ label: "Interval",
2355
+ text: `${this.options.seconds}s`
2102
2356
  }
2103
- })}`);
2104
- return;
2105
- } else if (apiKey.status === "missing") {
2106
- console.log(`${chalk.red("Trigger.dev error")}: ${chalk.bold(this.id)} is missing an API key, please set the TRIGGER_API_KEY environment variable or pass the apiKey option to the Trigger constructor. ${terminalLink("Get your API key here", "https://app.trigger.dev", {
2107
- fallback(text, url) {
2108
- return `${text} \u{1F449} ${url}`;
2357
+ ]
2358
+ };
2359
+ }
2360
+ attachToJob(triggerClient, job) {
2361
+ }
2362
+ get preprocessRuns() {
2363
+ return false;
2364
+ }
2365
+ toJSON() {
2366
+ return {
2367
+ type: "scheduled",
2368
+ schedule: {
2369
+ type: "interval",
2370
+ options: {
2371
+ seconds: this.options.seconds
2109
2372
  }
2110
- })}`);
2111
- return;
2112
- }
2113
- if (!__privateGet(this, _client)) {
2114
- __privateSet(this, _client, new TriggerClient(this, this.options));
2115
- }
2116
- return __privateGet(this, _client).listen();
2373
+ }
2374
+ };
2117
2375
  }
2118
- get id() {
2119
- return this.options.id;
2376
+ };
2377
+ __name(IntervalTrigger, "IntervalTrigger");
2378
+ function intervalTrigger(options) {
2379
+ return new IntervalTrigger(options);
2380
+ }
2381
+ __name(intervalTrigger, "intervalTrigger");
2382
+ var CronTrigger = class {
2383
+ constructor(options) {
2384
+ this.options = options;
2120
2385
  }
2121
- get name() {
2122
- return this.options.name;
2386
+ get event() {
2387
+ return {
2388
+ name: "trigger.scheduled",
2389
+ title: "Cron Schedule",
2390
+ source: "trigger.dev",
2391
+ icon: "schedule-cron",
2392
+ parsePayload: ScheduledPayloadSchema.parse,
2393
+ properties: [
2394
+ {
2395
+ label: "Expression",
2396
+ text: this.options.cron
2397
+ }
2398
+ ]
2399
+ };
2400
+ }
2401
+ attachToJob(triggerClient, job) {
2123
2402
  }
2124
- get endpoint() {
2125
- return this.options.endpoint;
2403
+ get preprocessRuns() {
2404
+ return false;
2126
2405
  }
2127
- get on() {
2128
- return this.options.on;
2406
+ toJSON() {
2407
+ return {
2408
+ type: "scheduled",
2409
+ schedule: {
2410
+ type: "cron",
2411
+ options: {
2412
+ cron: this.options.cron
2413
+ }
2414
+ }
2415
+ };
2129
2416
  }
2130
2417
  };
2131
- __name(Trigger, "Trigger");
2132
- _client = new WeakMap();
2133
- _getApiKey = new WeakSet();
2134
- getApiKey_fn = /* @__PURE__ */ __name(function() {
2135
- const apiKey = this.options.apiKey ?? process.env.TRIGGER_API_KEY;
2136
- if (!apiKey) {
2418
+ __name(CronTrigger, "CronTrigger");
2419
+ function cronTrigger(options) {
2420
+ return new CronTrigger(options);
2421
+ }
2422
+ __name(cronTrigger, "cronTrigger");
2423
+ var DynamicSchedule = class {
2424
+ constructor(client, options) {
2425
+ this.client = client;
2426
+ this.options = options;
2427
+ }
2428
+ get id() {
2429
+ return this.options.id;
2430
+ }
2431
+ get event() {
2137
2432
  return {
2138
- status: "missing"
2433
+ name: "trigger.scheduled",
2434
+ title: "Dynamic Schedule",
2435
+ source: "trigger.dev",
2436
+ icon: "schedule-dynamic",
2437
+ parsePayload: ScheduledPayloadSchema.parse
2139
2438
  };
2140
2439
  }
2141
- const isValid = apiKey.match(/^trigger_[a-z]+_[a-zA-Z0-9]+$/);
2142
- if (!isValid) {
2440
+ async register(key, metadata) {
2441
+ return this.client.registerSchedule(this.id, key, metadata);
2442
+ }
2443
+ async unregister(key) {
2444
+ return this.client.unregisterSchedule(this.id, key);
2445
+ }
2446
+ attachToJob(triggerClient, job) {
2447
+ triggerClient.attachDynamicSchedule(this.options.id, job);
2448
+ }
2449
+ get preprocessRuns() {
2450
+ return false;
2451
+ }
2452
+ toJSON() {
2143
2453
  return {
2144
- status: "invalid",
2145
- apiKey
2454
+ type: "dynamic",
2455
+ id: this.options.id
2146
2456
  };
2147
2457
  }
2148
- return {
2149
- status: "valid",
2150
- apiKey
2151
- };
2152
- }, "#getApiKey");
2458
+ };
2459
+ __name(DynamicSchedule, "DynamicSchedule");
2153
2460
 
2154
- // src/customEvents.ts
2155
- var import_node_fetch = __toESM(require("node-fetch"));
2156
- function sendEvent(idOrKey, event) {
2157
- const triggerRun = triggerRunLocalStorage.getStore();
2158
- if (!triggerRun) {
2159
- return sendEventFetch(idOrKey, event);
2160
- }
2161
- return triggerRun.sendEvent(idOrKey, event);
2461
+ // src/triggers/notifications.ts
2462
+ function missingConnectionNotification(integrations) {
2463
+ return new MissingConnectionNotification({
2464
+ integrations
2465
+ });
2162
2466
  }
2163
- __name(sendEvent, "sendEvent");
2164
- async function sendEventFetch(id, event) {
2165
- if (!process.env.TRIGGER_API_KEY) {
2166
- throw new Error(`There was a problem sending a custom event: the TRIGGER_API_KEY environment variable is not set`);
2167
- }
2168
- const baseUrl = process.env.TRIGGER_API_URL || "https://app.trigger.dev";
2169
- const url = `${baseUrl}/api/v1/events`;
2170
- const response = await (0, import_node_fetch.default)(url, {
2171
- method: "POST",
2172
- headers: {
2173
- "Content-Type": "application/json",
2174
- Authorization: `Bearer ${process.env.TRIGGER_API_KEY}`
2175
- },
2176
- body: JSON.stringify({
2177
- id,
2178
- event
2179
- })
2467
+ __name(missingConnectionNotification, "missingConnectionNotification");
2468
+ function missingConnectionResolvedNotification(integrations) {
2469
+ return new MissingConnectionResolvedNotification({
2470
+ integrations
2180
2471
  });
2181
- if (!response.ok) {
2182
- throw new Error(`There was a problem sending a custom event: ${response.statusText}`);
2183
- }
2184
- return;
2185
2472
  }
2186
- __name(sendEventFetch, "sendEventFetch");
2187
-
2188
- // src/fetch.ts
2189
- function fetch2(key, url, options) {
2190
- const triggerRun = triggerRunLocalStorage.getStore();
2191
- if (!triggerRun) {
2192
- throw new Error("Cannot call fetch outside of a trigger run");
2473
+ __name(missingConnectionResolvedNotification, "missingConnectionResolvedNotification");
2474
+ var MissingConnectionNotification = class {
2475
+ constructor(options) {
2476
+ this.options = options;
2193
2477
  }
2194
- return triggerRun.fetch(key, url, options);
2195
- }
2196
- __name(fetch2, "fetch");
2478
+ get event() {
2479
+ return {
2480
+ name: MISSING_CONNECTION_NOTIFICATION,
2481
+ title: "Missing Connection Notification",
2482
+ source: "trigger.dev",
2483
+ icon: "connection-alert",
2484
+ parsePayload: MissingConnectionNotificationPayloadSchema.parse,
2485
+ properties: [
2486
+ {
2487
+ label: "Integrations",
2488
+ text: this.options.integrations.map((i) => i.id).join(", ")
2489
+ }
2490
+ ]
2491
+ };
2492
+ }
2493
+ attachToJob(triggerClient, job) {
2494
+ }
2495
+ get preprocessRuns() {
2496
+ return false;
2497
+ }
2498
+ toJSON() {
2499
+ return {
2500
+ type: "static",
2501
+ title: this.event.title,
2502
+ rule: {
2503
+ event: this.event.name,
2504
+ source: "trigger.dev",
2505
+ payload: {
2506
+ client: {
2507
+ id: this.options.integrations.map((i) => i.id)
2508
+ }
2509
+ }
2510
+ }
2511
+ };
2512
+ }
2513
+ };
2514
+ __name(MissingConnectionNotification, "MissingConnectionNotification");
2515
+ var MissingConnectionResolvedNotification = class {
2516
+ constructor(options) {
2517
+ this.options = options;
2518
+ }
2519
+ get event() {
2520
+ return {
2521
+ name: MISSING_CONNECTION_RESOLVED_NOTIFICATION,
2522
+ title: "Missing Connection Resolved Notification",
2523
+ source: "trigger.dev",
2524
+ icon: "connection-alert",
2525
+ parsePayload: MissingConnectionResolvedNotificationPayloadSchema.parse,
2526
+ properties: [
2527
+ {
2528
+ label: "Integrations",
2529
+ text: this.options.integrations.map((i) => i.id).join(", ")
2530
+ }
2531
+ ]
2532
+ };
2533
+ }
2534
+ attachToJob(triggerClient, job) {
2535
+ }
2536
+ get preprocessRuns() {
2537
+ return false;
2538
+ }
2539
+ toJSON() {
2540
+ return {
2541
+ type: "static",
2542
+ title: this.event.title,
2543
+ rule: {
2544
+ event: this.event.name,
2545
+ source: "trigger.dev",
2546
+ payload: {
2547
+ client: {
2548
+ id: this.options.integrations.map((i) => i.id)
2549
+ }
2550
+ }
2551
+ }
2552
+ };
2553
+ }
2554
+ };
2555
+ __name(MissingConnectionResolvedNotification, "MissingConnectionResolvedNotification");
2197
2556
 
2198
2557
  // src/index.ts
2199
- function getTriggerRun() {
2200
- return triggerRunLocalStorage.getStore();
2201
- }
2202
- __name(getTriggerRun, "getTriggerRun");
2203
2558
  function secureString(strings, ...interpolations) {
2204
2559
  return {
2205
2560
  __secureString: true,
@@ -2210,13 +2565,27 @@ function secureString(strings, ...interpolations) {
2210
2565
  __name(secureString, "secureString");
2211
2566
  // Annotate the CommonJS export names for ESM import in node:
2212
2567
  0 && (module.exports = {
2213
- Trigger,
2214
- customEvent,
2215
- fetch,
2216
- getTriggerRun,
2217
- scheduleEvent,
2218
- secureString,
2219
- sendEvent,
2220
- webhookEvent
2568
+ CronTrigger,
2569
+ DynamicSchedule,
2570
+ DynamicTrigger,
2571
+ EventTrigger,
2572
+ ExternalSource,
2573
+ ExternalSourceTrigger,
2574
+ IO,
2575
+ IOLogger,
2576
+ IntervalTrigger,
2577
+ Job,
2578
+ MissingConnectionNotification,
2579
+ MissingConnectionResolvedNotification,
2580
+ ResumeWithTask,
2581
+ TriggerClient,
2582
+ authenticatedTask,
2583
+ cronTrigger,
2584
+ eventTrigger,
2585
+ intervalTrigger,
2586
+ missingConnectionNotification,
2587
+ missingConnectionResolvedNotification,
2588
+ omit,
2589
+ secureString
2221
2590
  });
2222
2591
  //# sourceMappingURL=index.js.map