@trigger.dev/sdk 0.2.22-next.0 → 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,849 +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);
158
+ }
159
+ filter(...keys) {
160
+ return new _Logger(__privateGet(this, _name), logLevels[__privateGet(this, _level)], keys);
833
161
  }
834
162
  log(...args) {
835
- if (__privateGet(this, _level) < 1)
163
+ if (__privateGet(this, _level) < 0)
836
164
  return;
837
- console.log(`${__privateMethod(this, _formatName, formatName_fn).call(this)} `, ...[
838
- ...args,
839
- ...__privateMethod(this, _formatTags, formatTags_fn).call(this)
840
- ]);
165
+ console.log(`[${formattedDateTime()}] [${__privateGet(this, _name)}] `, ...args);
841
166
  }
842
- logClean(...args) {
167
+ error(...args) {
843
168
  if (__privateGet(this, _level) < 1)
844
169
  return;
845
- console.log(`${__privateMethod(this, _formatName, formatName_fn).call(this)} `, ...args);
170
+ console.error(`[${formattedDateTime()}] [${__privateGet(this, _name)}] `, ...args);
846
171
  }
847
- error(...args) {
172
+ warn(...args) {
848
173
  if (__privateGet(this, _level) < 2)
849
174
  return;
850
- console.error(`[${formattedDateTime()}] ${__privateMethod(this, _formatName, formatName_fn).call(this)} `, ...[
851
- ...args,
852
- ...__privateMethod(this, _formatTags, formatTags_fn).call(this)
853
- ]);
175
+ console.warn(`[${formattedDateTime()}] [${__privateGet(this, _name)}] `, ...args);
854
176
  }
855
- warn(...args) {
177
+ info(...args) {
856
178
  if (__privateGet(this, _level) < 3)
857
179
  return;
858
- console.warn(`[${formattedDateTime()}] ${__privateMethod(this, _formatName, formatName_fn).call(this)} `, ...[
859
- ...args,
860
- ...__privateMethod(this, _formatTags, formatTags_fn).call(this)
861
- ]);
180
+ console.info(`[${formattedDateTime()}] [${__privateGet(this, _name)}] `, ...args);
862
181
  }
863
- info(...args) {
182
+ debug(message, ...args) {
864
183
  if (__privateGet(this, _level) < 4)
865
184
  return;
866
- console.info(`[${formattedDateTime()}] ${__privateMethod(this, _formatName, formatName_fn).call(this)} `, ...[
867
- ...args,
868
- ...__privateMethod(this, _formatTags, formatTags_fn).call(this)
869
- ]);
870
- }
871
- debug(...args) {
872
- if (__privateGet(this, _level) < 5)
873
- return;
874
- console.debug(`[${formattedDateTime()}] ${__privateMethod(this, _formatName, formatName_fn).call(this)} `, ...[
875
- ...args,
876
- ...__privateMethod(this, _formatTags, formatTags_fn).call(this)
877
- ]);
185
+ const structuredLog = {
186
+ timestamp: new Date(),
187
+ name: __privateGet(this, _name),
188
+ message,
189
+ args: structureArgs(safeJsonClone(args), __privateGet(this, _filteredKeys))
190
+ };
191
+ console.debug(JSON.stringify(structuredLog, bigIntReplacer));
878
192
  }
879
193
  };
194
+ var Logger = _Logger;
880
195
  __name(Logger, "Logger");
881
196
  _name = new WeakMap();
882
- _tags = new WeakMap();
883
197
  _level = new WeakMap();
884
- _formatName = new WeakSet();
885
- formatName_fn = /* @__PURE__ */ __name(function() {
886
- if (Array.isArray(__privateGet(this, _name))) {
887
- return __privateGet(this, _name).map((name2) => `[${name2}]`).join("");
888
- }
889
- return `[${__privateGet(this, _name)}]`;
890
- }, "#formatName");
891
- _formatTags = new WeakSet();
892
- formatTags_fn = /* @__PURE__ */ __name(function() {
893
- return __privateGet(this, _tags).map((tag) => `[${tag}]`);
894
- }, "#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");
895
214
  function formattedDateTime() {
896
215
  const date = new Date();
897
216
  const hours = date.getHours();
@@ -905,1287 +224,2337 @@ function formattedDateTime() {
905
224
  return `${formattedHours}:${formattedMinutes}:${formattedSeconds}.${formattedMilliseconds}`;
906
225
  }
907
226
  __name(formattedDateTime, "formattedDateTime");
908
-
909
- // ../internal-bridge/src/zodRPC.ts
910
- var RPCMessageSchema = import_zod14.z.object({
911
- id: import_zod14.z.string(),
912
- methodName: import_zod14.z.string(),
913
- data: import_zod14.z.any(),
914
- kind: import_zod14.z.enum([
915
- "CALL",
916
- "RESPONSE"
917
- ])
918
- });
919
- var _connection, _sender, _receiver, _handlers, _pendingCalls, _logger, _onMessage, onMessage_fn, _onCall, onCall_fn, _onResponse, onResponse_fn, _handleCall, handleCall_fn, _handleResponse, handleResponse_fn;
920
- var ZodRPC = class {
921
- constructor(options) {
922
- __privateAdd(this, _onMessage);
923
- __privateAdd(this, _onCall);
924
- __privateAdd(this, _onResponse);
925
- __privateAdd(this, _handleCall);
926
- __privateAdd(this, _handleResponse);
927
- __privateAdd(this, _connection, void 0);
928
- __privateAdd(this, _sender, void 0);
929
- __privateAdd(this, _receiver, void 0);
930
- __privateAdd(this, _handlers, void 0);
931
- __privateAdd(this, _pendingCalls, /* @__PURE__ */ new Map());
932
- __privateAdd(this, _logger, new Logger("ZodRPC"));
933
- __privateSet(this, _connection, options.connection);
934
- __privateSet(this, _sender, options.sender);
935
- __privateSet(this, _receiver, options.receiver);
936
- __privateSet(this, _handlers, options.handlers);
937
- __privateGet(this, _connection).onMessage.attach(__privateMethod(this, _onMessage, onMessage_fn).bind(this));
938
- }
939
- resetConnection(connection) {
940
- __privateGet(this, _connection).onMessage.detach();
941
- __privateSet(this, _connection, connection);
942
- __privateGet(this, _connection).onMessage.attach(__privateMethod(this, _onMessage, onMessage_fn).bind(this));
943
- }
944
- send(key, data) {
945
- __privateGet(this, _logger).debug("Sending call", {
946
- key,
947
- data
948
- });
949
- const id = generateStableId(__privateGet(this, _connection).id, key, data);
950
- const message = packageMessage({
951
- id,
952
- methodName: key,
953
- data
954
- });
955
- return new Promise((resolve, reject) => {
956
- __privateGet(this, _pendingCalls).set(id, (rawResponseText) => {
957
- try {
958
- const parsed = __privateGet(this, _sender)[key]["response"].parse(rawResponseText);
959
- return resolve(parsed);
960
- } catch (err) {
961
- reject(err);
962
- }
963
- });
964
- __privateGet(this, _connection).send(message).catch((err) => reject(err));
965
- });
227
+ function structureArgs(args, filteredKeys = []) {
228
+ if (args.length === 0) {
229
+ return;
966
230
  }
967
- };
968
- __name(ZodRPC, "ZodRPC");
969
- _connection = new WeakMap();
970
- _sender = new WeakMap();
971
- _receiver = new WeakMap();
972
- _handlers = new WeakMap();
973
- _pendingCalls = new WeakMap();
974
- _logger = new WeakMap();
975
- _onMessage = new WeakSet();
976
- onMessage_fn = /* @__PURE__ */ __name(async function(rawData) {
977
- try {
978
- const data = RPCMessageSchema.parse(JSON.parse(rawData));
979
- if (data.kind === "CALL") {
980
- await __privateMethod(this, _onCall, onCall_fn).call(this, data);
981
- }
982
- if (data.kind === "RESPONSE") {
983
- await __privateMethod(this, _onResponse, onResponse_fn).call(this, data);
984
- }
985
- } catch (err) {
986
- __privateGet(this, _logger).error(err);
231
+ if (args.length === 1 && typeof args[0] === "object") {
232
+ return filterKeys(JSON.parse(JSON.stringify(args[0], bigIntReplacer)), filteredKeys);
987
233
  }
988
- }, "#onMessage");
989
- _onCall = new WeakSet();
990
- onCall_fn = /* @__PURE__ */ __name(async function(message) {
991
- try {
992
- await __privateMethod(this, _handleCall, handleCall_fn).call(this, message);
993
- } catch (callError) {
994
- if (callError instanceof import_zod14.ZodError) {
995
- __privateGet(this, _logger).error(`[ZodRPC] Received invalid call:
996
- ${JSON.stringify(message)}: `, callError.errors);
997
- } else {
998
- __privateGet(this, _logger).error(`[ZodRPC] Error handling call:
999
- ${JSON.stringify(message)}: `, callError);
1000
- }
234
+ return args;
235
+ }
236
+ __name(structureArgs, "structureArgs");
237
+ function filterKeys(obj, keys) {
238
+ if (typeof obj !== "object" || obj === null) {
239
+ return obj;
1001
240
  }
1002
- }, "#onCall");
1003
- _onResponse = new WeakSet();
1004
- onResponse_fn = /* @__PURE__ */ __name(async function(message1) {
1005
- try {
1006
- await __privateMethod(this, _handleResponse, handleResponse_fn).call(this, message1);
1007
- } catch (callError) {
1008
- if (callError instanceof import_zod14.ZodError) {
1009
- __privateGet(this, _logger).error(`[ZodRPC] Received invalid response
1010
-
1011
- ${JSON.stringify(message1)}: `, callError.flatten());
1012
- } else {
1013
- __privateGet(this, _logger).error(`[ZodRPC] Error handling response
1014
-
1015
- ${JSON.stringify(message1)}: `, callError);
241
+ if (Array.isArray(obj)) {
242
+ return obj.map((item) => filterKeys(item, keys));
243
+ }
244
+ const filteredObj = {};
245
+ for (const [key, value] of Object.entries(obj)) {
246
+ if (keys.includes(key)) {
247
+ continue;
1016
248
  }
249
+ filteredObj[key] = filterKeys(value, keys);
1017
250
  }
1018
- }, "#onResponse");
1019
- _handleCall = new WeakSet();
1020
- handleCall_fn = /* @__PURE__ */ __name(async function(message2) {
1021
- const receiver = __privateGet(this, _receiver);
1022
- const methodName = message2.methodName;
1023
- const method = __privateGet(this, _receiver)[methodName];
1024
- if (!method) {
1025
- throw new Error(`There is no method for ${message2.methodName}`);
1026
- }
1027
- __privateGet(this, _logger).debug("Received call", {
1028
- message: message2
1029
- });
1030
- const inputs = method.request.parse(message2.data);
1031
- const handler = __privateGet(this, _handlers)[methodName];
1032
- const returnValue = await handler(inputs);
1033
- const preparedResponseText = packageResponse({
1034
- id: message2.id,
1035
- methodName,
1036
- data: returnValue
1037
- });
1038
- try {
1039
- await __privateGet(this, _connection).send(preparedResponseText);
1040
- } catch (err) {
1041
- __privateGet(this, _logger).error("Failed sending response", preparedResponseText, err);
1042
- }
1043
- return;
1044
- }, "#handleCall");
1045
- _handleResponse = new WeakSet();
1046
- handleResponse_fn = /* @__PURE__ */ __name(async function(message3) {
1047
- const responseCallback = __privateGet(this, _pendingCalls).get(message3.id);
1048
- if (!responseCallback)
1049
- return;
1050
- responseCallback(message3.data);
1051
- __privateGet(this, _pendingCalls).delete(message3.id);
1052
- }, "#handleResponse");
1053
- function generateStableId(connId, reqKey, reqData) {
1054
- const serializedData = JSON.stringify(reqData);
1055
- const inputString = connId + reqKey + serializedData;
1056
- const hash = (0, import_node_crypto.createHash)("sha256").update(inputString).digest("hex");
1057
- return hash;
1058
- }
1059
- __name(generateStableId, "generateStableId");
1060
- function packageMessage({ id, methodName, data }) {
1061
- const callerData = {
1062
- id,
1063
- kind: "CALL",
1064
- data,
1065
- methodName
1066
- };
1067
- return JSON.stringify(callerData);
1068
- }
1069
- __name(packageMessage, "packageMessage");
1070
- function packageResponse({ id, methodName, data }) {
1071
- const preparedResponseText = {
1072
- id,
1073
- kind: "RESPONSE",
1074
- methodName,
1075
- data
1076
- };
1077
- return JSON.stringify(preparedResponseText);
251
+ return filteredObj;
1078
252
  }
1079
- __name(packageResponse, "packageResponse");
253
+ __name(filterKeys, "filterKeys");
1080
254
 
1081
- // src/client.ts
1082
- var import_uuid2 = require("uuid");
1083
- var import_ws = require("ws");
1084
- var import_zod15 = require("zod");
255
+ // ../internal/src/schemas/api.ts
256
+ var import_ulid = require("ulid");
257
+ var import_zod8 = require("zod");
1085
258
 
1086
- // package.json
1087
- var name = "@trigger.dev/sdk";
1088
- var version = "0.2.22-next.0";
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
+ });
1089
278
 
1090
- // src/connection.ts
1091
- var import_uuid = require("uuid");
1092
- var import_evt = require("evt");
1093
- var TimeoutError = class extends Error {
1094
- };
1095
- __name(TimeoutError, "TimeoutError");
1096
- var NotConnectedError = class extends Error {
1097
- };
1098
- __name(NotConnectedError, "NotConnectedError");
1099
- var _socket, _connectTimeout, _sendTimeout, _pingTimeout, _isAuthenticated, _timeouts, _isClosed, _pendingMessages, _logger2, _pingIntervalHandle, _pingIntervalMs, _closeUnresponsiveConnectionTimeoutMs, _startPingInterval, startPingInterval_fn, _ping, ping_fn;
1100
- var HostConnection = class {
1101
- constructor(socket, options) {
1102
- __privateAdd(this, _startPingInterval);
1103
- __privateAdd(this, _ping);
1104
- __privateAdd(this, _socket, void 0);
1105
- __privateAdd(this, _connectTimeout, void 0);
1106
- __privateAdd(this, _sendTimeout, void 0);
1107
- __privateAdd(this, _pingTimeout, void 0);
1108
- __privateAdd(this, _isAuthenticated, false);
1109
- __privateAdd(this, _timeouts, void 0);
1110
- __privateAdd(this, _isClosed, false);
1111
- __privateAdd(this, _pendingMessages, /* @__PURE__ */ new Map());
1112
- __privateAdd(this, _logger2, void 0);
1113
- __privateAdd(this, _pingIntervalHandle, void 0);
1114
- __privateAdd(this, _pingIntervalMs, 3e4);
1115
- __privateAdd(this, _closeUnresponsiveConnectionTimeoutMs, 3 * 60 * 1e3);
1116
- __privateSet(this, _socket, socket);
1117
- this.id = options?.id ?? (0, import_uuid.v4)();
1118
- this.onMessage = new import_evt.Evt();
1119
- this.onAuthenticated = new import_evt.Evt();
1120
- this.onClose = new import_evt.Evt();
1121
- this.onOpen = new import_evt.Evt();
1122
- this.onError = new import_evt.Evt();
1123
- __privateSet(this, _connectTimeout, options?.connectTimeout ?? 5e3);
1124
- __privateSet(this, _sendTimeout, options?.sendTimeout ?? 5e3);
1125
- __privateSet(this, _pingTimeout, options?.pingTimeout ?? 5e3);
1126
- __privateSet(this, _timeouts, /* @__PURE__ */ new Set());
1127
- __privateSet(this, _logger2, new Logger("trigger.dev connection"));
1128
- this.onClose.attach(() => {
1129
- __privateSet(this, _isClosed, true);
1130
- if (__privateGet(this, _pingIntervalHandle)) {
1131
- clearInterval(__privateGet(this, _pingIntervalHandle));
1132
- __privateSet(this, _pingIntervalHandle, void 0);
1133
- }
1134
- for (const timeout of __privateGet(this, _timeouts)) {
1135
- clearTimeout(timeout);
1136
- }
1137
- __privateGet(this, _timeouts).clear();
1138
- });
1139
- __privateGet(this, _socket).onopen = () => {
1140
- __privateSet(this, _isClosed, false);
1141
- this.onOpen.post();
1142
- __privateMethod(this, _startPingInterval, startPingInterval_fn).call(this);
1143
- };
1144
- __privateGet(this, _socket).onclose = (ev) => {
1145
- this.onClose.post([
1146
- ev.code,
1147
- ev.reason
1148
- ]);
1149
- };
1150
- __privateGet(this, _socket).onerror = (ev) => {
1151
- const message = "message" in ev ? ev.message : "Unknown error";
1152
- this.onError.post(new Error(message));
1153
- };
1154
- __privateGet(this, _socket).onmessage = (event) => {
1155
- if (__privateGet(this, _isClosed))
1156
- return;
1157
- const data = JSON.parse(event.data.toString());
1158
- const metadata = MESSAGE_META.parse(data);
1159
- if (metadata.type === "ACK") {
1160
- const pendingMessage = __privateGet(this, _pendingMessages).get(metadata.id);
1161
- if (pendingMessage) {
1162
- pendingMessage.onAckReceived();
1163
- __privateGet(this, _pendingMessages).delete(metadata.id);
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
+ });
294
+
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
+ ]));
322
+
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
+ });
360
+
361
+ // ../internal/src/schemas/triggers.ts
362
+ var import_zod7 = require("zod");
363
+
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) {
1526
+ return this.callback("ERROR", message, properties);
1527
+ }
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;
1939
+ }
1940
+ async registerTrigger(id, key, options) {
1941
+ return __privateGet(this, _client).registerTrigger(this.id, id, key, options);
1942
+ }
1943
+ async getAuth(id) {
1944
+ return __privateGet(this, _client).getAuth(this.id, id);
1945
+ }
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);
1951
+ }
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;
1959
+ }
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
+ });
1970
+ }
1971
+ };
1972
+ __name(TriggerClient, "TriggerClient");
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
1990
+ };
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()
1997
+ });
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
+ };
2020
+ }
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
+ };
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
2081
+ });
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
+ }
1164
2107
  }
1165
- }
1166
- if (metadata.type === "MESSAGE") {
1167
- socket.send(JSON.stringify({
1168
- type: "ACK",
1169
- id: metadata.id
1170
- }));
1171
- if (metadata.data === "AUTHENTICATED") {
1172
- __privateSet(this, _isAuthenticated, true);
1173
- this.onAuthenticated.post();
1174
- return;
2108
+ };
2109
+ }
2110
+ return {
2111
+ events: results2.events,
2112
+ response: results2.response ?? {
2113
+ status: 200,
2114
+ body: {
2115
+ ok: true
1175
2116
  }
1176
- this.onMessage.post(metadata.data);
1177
2117
  }
1178
2118
  };
1179
- if ("pong" in socket) {
1180
- socket.on("pong", (buf) => {
1181
- const id = buf.toString();
1182
- const pendingMessage = __privateGet(this, _pendingMessages).get(id);
1183
- if (pendingMessage?.data === "ping") {
1184
- pendingMessage.onAckReceived();
1185
- }
1186
- });
1187
- }
1188
2119
  }
1189
- async connect() {
1190
- __privateGet(this, _logger2).debug("[connect] Attempting to connect");
1191
- return new Promise((resolve, reject) => {
1192
- if (__privateGet(this, _socket).readyState === __privateGet(this, _socket).OPEN && __privateGet(this, _isAuthenticated)) {
1193
- __privateGet(this, _logger2).debug("[connect] Already connected, resolving");
1194
- return resolve();
1195
- }
1196
- const failTimeout = setTimeout(() => {
1197
- __privateGet(this, _logger2).debug("[connect] Connection timed out, rejecting");
1198
- reject(new TimeoutError());
1199
- }, __privateGet(this, _connectTimeout));
1200
- __privateGet(this, _timeouts).add(failTimeout);
1201
- this.onAuthenticated.attach(() => {
1202
- clearTimeout(failTimeout);
1203
- __privateGet(this, _timeouts).delete(failTimeout);
1204
- __privateGet(this, _logger2).debug("[connect] Connected, resolving");
1205
- resolve();
1206
- });
2120
+ const handler = __privateGet(this, _registeredHttpSourceHandlers)[source.key];
2121
+ if (!handler) {
2122
+ __privateGet(this, _logger2).debug("No handler registered for HTTP source", {
2123
+ source
1207
2124
  });
1208
- }
1209
- async send(data) {
1210
- if (__privateGet(this, _isClosed))
1211
- throw new NotConnectedError();
1212
- return new Promise((resolve, reject) => {
1213
- const id = (0, import_uuid.v4)();
1214
- const failTimeout = setTimeout(() => {
1215
- reject(new TimeoutError());
1216
- }, __privateGet(this, _sendTimeout));
1217
- __privateGet(this, _timeouts).add(failTimeout);
1218
- __privateGet(this, _pendingMessages).set(id, {
1219
- data,
1220
- onAckReceived: () => {
1221
- clearTimeout(failTimeout);
1222
- __privateGet(this, _timeouts).delete(failTimeout);
1223
- resolve();
2125
+ return {
2126
+ response: {
2127
+ status: 200,
2128
+ body: {
2129
+ ok: true
1224
2130
  }
1225
- });
1226
- __privateGet(this, _socket).send(JSON.stringify({
1227
- id,
1228
- data,
1229
- type: "MESSAGE"
1230
- }));
1231
- });
2131
+ },
2132
+ events: []
2133
+ };
1232
2134
  }
1233
- close(code, reason) {
1234
- __privateSet(this, _isClosed, true);
1235
- this.onMessage.detach();
1236
- return __privateGet(this, _socket).close(code, reason);
2135
+ const results = await handler(source, sourceRequest);
2136
+ if (!results) {
2137
+ return {
2138
+ events: [],
2139
+ response: {
2140
+ status: 200,
2141
+ body: {
2142
+ ok: true
2143
+ }
2144
+ }
2145
+ };
1237
2146
  }
1238
- };
1239
- __name(HostConnection, "HostConnection");
1240
- _socket = new WeakMap();
1241
- _connectTimeout = new WeakMap();
1242
- _sendTimeout = new WeakMap();
1243
- _pingTimeout = new WeakMap();
1244
- _isAuthenticated = new WeakMap();
1245
- _timeouts = new WeakMap();
1246
- _isClosed = new WeakMap();
1247
- _pendingMessages = new WeakMap();
1248
- _logger2 = new WeakMap();
1249
- _pingIntervalHandle = new WeakMap();
1250
- _pingIntervalMs = new WeakMap();
1251
- _closeUnresponsiveConnectionTimeoutMs = new WeakMap();
1252
- _startPingInterval = new WeakSet();
1253
- startPingInterval_fn = /* @__PURE__ */ __name(function() {
1254
- let lastSuccessfulPing = new Date();
1255
- __privateSet(this, _pingIntervalHandle, setInterval(async () => {
1256
- if (!__privateGet(this, _socket).OPEN) {
1257
- if (__privateGet(this, _pingIntervalHandle)) {
1258
- clearInterval(__privateGet(this, _pingIntervalHandle));
1259
- __privateSet(this, _pingIntervalHandle, void 0);
2147
+ return {
2148
+ events: results.events,
2149
+ response: results.response ?? {
2150
+ status: 200,
2151
+ body: {
2152
+ ok: true
1260
2153
  }
1261
- return;
1262
2154
  }
1263
- try {
1264
- await __privateMethod(this, _ping, ping_fn).call(this);
1265
- lastSuccessfulPing = new Date();
1266
- } catch (err) {
1267
- __privateGet(this, _logger2).warn("Pong not received in time");
1268
- if (!(err instanceof TimeoutError)) {
1269
- __privateGet(this, _logger2).error(err);
1270
- }
1271
- if (lastSuccessfulPing.getTime() < new Date().getTime() - __privateGet(this, _closeUnresponsiveConnectionTimeoutMs)) {
1272
- __privateGet(this, _logger2).error("No pong received in last three minutes, closing connection to Trigger.dev and retrying...");
1273
- if (__privateGet(this, _pingIntervalHandle)) {
1274
- clearInterval(__privateGet(this, _pingIntervalHandle));
1275
- __privateSet(this, _pingIntervalHandle, void 0);
1276
- }
1277
- __privateGet(this, _socket).close();
1278
- }
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;
1279
2162
  }
1280
- }, __privateGet(this, _pingIntervalMs)));
1281
- }, "#startPingInterval");
1282
- _ping = new WeakSet();
1283
- ping_fn = /* @__PURE__ */ __name(async function() {
1284
- if (!__privateGet(this, _socket).OPEN) {
1285
- throw new NotConnectedError();
1286
- }
1287
- if (!("ping" in __privateGet(this, _socket))) {
1288
- throw new Error("ping not supported in this underlying websocket connection");
1289
- }
1290
- const socket = __privateGet(this, _socket);
1291
- return new Promise((resolve, reject) => {
1292
- const id = (0, import_uuid.v4)();
1293
- const failTimeout = setTimeout(() => {
1294
- reject(new TimeoutError("Pong not received in time"));
1295
- }, __privateGet(this, _pingTimeout));
1296
- __privateGet(this, _timeouts).add(failTimeout);
1297
- __privateGet(this, _pendingMessages).set(id, {
1298
- data: "ping",
1299
- onAckReceived: () => {
1300
- clearTimeout(failTimeout);
1301
- __privateGet(this, _timeouts).delete(failTimeout);
1302
- __privateGet(this, _logger2).debug(`Resolving ping`);
1303
- resolve();
1304
- }
1305
- });
1306
- __privateGet(this, _logger2).debug(`Sending ping ${id} to ${socket.url}`);
1307
- socket.ping(id, void 0, (err) => {
1308
- if (err) {
1309
- reject(err);
1310
- }
1311
- });
1312
- });
1313
- }, "#ping");
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;
2167
+ }
2168
+ return url;
2169
+ }
2170
+ __name(buildClientUrl, "buildClientUrl");
1314
2171
 
1315
- // src/localStorage.ts
1316
- var import_node_async_hooks = require("async_hooks");
1317
- var triggerRunLocalStorage = new import_node_async_hooks.AsyncLocalStorage();
2172
+ // src/integrations.ts
2173
+ function authenticatedTask(options) {
2174
+ return options;
2175
+ }
2176
+ __name(authenticatedTask, "authenticatedTask");
1318
2177
 
1319
- // src/logger.ts
1320
- var ContextLogger = class {
1321
- constructor(callback) {
1322
- this.callback = callback;
2178
+ // src/triggers/externalSource.ts
2179
+ var ExternalSource = class {
2180
+ constructor(channel, options) {
2181
+ this.options = options;
2182
+ this.channel = channel;
1323
2183
  }
1324
- debug(message, properties) {
1325
- return this.callback("DEBUG", message, properties);
2184
+ async handle(source, rawEvent, logger) {
2185
+ return this.options.handler({
2186
+ source: {
2187
+ ...source,
2188
+ params: source.params
2189
+ },
2190
+ rawEvent
2191
+ }, logger);
1326
2192
  }
1327
- info(message, properties) {
1328
- return this.callback("INFO", message, properties);
2193
+ filter(params) {
2194
+ return this.options.filter(params);
1329
2195
  }
1330
- warn(message, properties) {
1331
- return this.callback("WARN", message, properties);
2196
+ properties(params) {
2197
+ return this.options.properties?.(params) ?? [];
1332
2198
  }
1333
- error(message, properties) {
1334
- return this.callback("ERROR", message, properties);
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;
1335
2212
  }
1336
- };
1337
- __name(ContextLogger, "ContextLogger");
1338
-
1339
- // src/client.ts
1340
- var import_zod_error = require("zod-error");
1341
- var import_promises = require("fs/promises");
1342
-
1343
- // src/keyValueStorage.ts
1344
- var ContextKeyValueStorage = class {
1345
- constructor(namespace, onGet, onSet, onDelete) {
1346
- this.namespace = namespace;
1347
- this.onGet = onGet;
1348
- this.onSet = onSet;
1349
- this.onDelete = onDelete;
1350
- this.getCount = 0;
1351
- this.setCount = 0;
1352
- this.deleteCount = 0;
1353
- }
1354
- get(key) {
1355
- const operation = {
1356
- key,
1357
- namespace: this.namespace,
1358
- idempotencyKey: `get:${this.namespace}:${key}:${this.getCount++}`
1359
- };
1360
- return this.onGet(operation);
1361
- }
1362
- set(key, value) {
1363
- const operation = {
1364
- key,
1365
- namespace: this.namespace,
1366
- idempotencyKey: `set:${this.namespace}:${key}:${this.setCount++}`,
1367
- value
1368
- };
1369
- return this.onSet(operation);
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;
1370
2224
  }
1371
- delete(key) {
1372
- const operation = {
1373
- key,
1374
- namespace: this.namespace,
1375
- idempotencyKey: `delete:${this.namespace}:${key}:${this.deleteCount++}`
2225
+ get integrationConfig() {
2226
+ return {
2227
+ id: this.integration.id,
2228
+ metadata: this.integration.metadata
1376
2229
  };
1377
- return this.onDelete(operation);
1378
2230
  }
1379
- };
1380
- __name(ContextKeyValueStorage, "ContextKeyValueStorage");
1381
-
1382
- // src/client.ts
1383
- var zodErrorMessageOptions = {
1384
- delimiter: {
1385
- error: " \u{1F525} "
2231
+ get id() {
2232
+ return this.options.id;
2233
+ }
2234
+ get version() {
2235
+ return this.options.version;
1386
2236
  }
1387
2237
  };
1388
- 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;
1389
- var TriggerClient = class {
1390
- constructor(trigger, options) {
1391
- __privateAdd(this, _initializeConnection);
1392
- __privateAdd(this, _initializeRPC);
1393
- __privateAdd(this, _initializeHost);
1394
- __privateAdd(this, _send);
1395
- __privateAdd(this, _trigger, void 0);
1396
- __privateAdd(this, _options, void 0);
1397
- __privateAdd(this, _connection2, void 0);
1398
- __privateAdd(this, _serverRPC, void 0);
1399
- __privateAdd(this, _apiKey, void 0);
1400
- __privateAdd(this, _endpoint, void 0);
1401
- __privateAdd(this, _isConnected, false);
1402
- __privateAdd(this, _retryIntervalMs, 3e3);
1403
- __privateAdd(this, _logger3, void 0);
1404
- __privateAdd(this, _closedByUser, false);
1405
- __privateAdd(this, _registerResponse, void 0);
1406
- __privateAdd(this, _responseCompleteCallbacks, /* @__PURE__ */ new Map());
1407
- __privateAdd(this, _waitForCallbacks, /* @__PURE__ */ new Map());
1408
- __privateAdd(this, _fetchCallbacks, /* @__PURE__ */ new Map());
1409
- __privateAdd(this, _runOnceCallbacks, /* @__PURE__ */ new Map());
1410
- __privateAdd(this, _kvGetCallbacks, /* @__PURE__ */ new Map());
1411
- __privateAdd(this, _kvSetCallbacks, /* @__PURE__ */ new Map());
1412
- __privateAdd(this, _kvDeleteCallbacks, /* @__PURE__ */ new Map());
1413
- __privateSet(this, _trigger, trigger);
1414
- __privateSet(this, _options, options);
1415
- const apiKey = __privateGet(this, _options).apiKey ?? process.env.TRIGGER_API_KEY;
1416
- if (!apiKey) {
1417
- 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.");
1418
- }
1419
- __privateSet(this, _apiKey, apiKey);
1420
- __privateSet(this, _endpoint, __privateGet(this, _options).endpoint ?? process.env.TRIGGER_WSS_URL ?? "wss://wss.trigger.dev/ws");
1421
- __privateSet(this, _logger3, new Logger([
1422
- "trigger.dev",
1423
- __privateGet(this, _options).id
1424
- ], __privateGet(this, _options).logLevel));
1425
- }
1426
- async listen(instanceId) {
1427
- try {
1428
- await __privateMethod(this, _initializeConnection, initializeConnection_fn).call(this, instanceId);
1429
- __privateMethod(this, _initializeRPC, initializeRPC_fn).call(this);
1430
- await __privateMethod(this, _initializeHost, initializeHost_fn).call(this);
1431
- const terminalLink = (await import("terminal-link")).default;
1432
- if (__privateGet(this, _registerResponse)?.isNew) {
1433
- __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, {
1434
- fallback: (text, url) => `${text}: (${url})`
1435
- })}. Listening for events...`);
1436
- } else {
1437
- __privateGet(this, _logger3).log(`\u2728 Connected and listening for events \u{1F449} ${terminalLink("View on dashboard", __privateGet(this, _registerResponse).url, {
1438
- fallback: (text, url) => `${text}: (${url})`
1439
- })}`);
1440
- }
1441
- } catch (error) {
1442
- __privateGet(this, _logger3).log(`\u{1F6A9} Could not connect to trigger.dev`);
1443
- this.close();
1444
- }
2238
+ __name(ExternalSource, "ExternalSource");
2239
+ var ExternalSourceTrigger = class {
2240
+ constructor(options) {
2241
+ this.options = options;
1445
2242
  }
1446
- close() {
1447
- __privateSet(this, _closedByUser, true);
1448
- if (__privateGet(this, _serverRPC)) {
1449
- __privateSet(this, _serverRPC, void 0);
1450
- }
1451
- __privateGet(this, _connection2)?.close();
1452
- __privateSet(this, _isConnected, false);
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
2264
+ });
2265
+ }
2266
+ get preprocessRuns() {
2267
+ return true;
1453
2268
  }
1454
2269
  };
1455
- __name(TriggerClient, "TriggerClient");
1456
- _trigger = new WeakMap();
1457
- _options = new WeakMap();
1458
- _connection2 = new WeakMap();
1459
- _serverRPC = new WeakMap();
1460
- _apiKey = new WeakMap();
1461
- _endpoint = new WeakMap();
1462
- _isConnected = new WeakMap();
1463
- _retryIntervalMs = new WeakMap();
1464
- _logger3 = new WeakMap();
1465
- _closedByUser = new WeakMap();
1466
- _registerResponse = new WeakMap();
1467
- _responseCompleteCallbacks = new WeakMap();
1468
- _waitForCallbacks = new WeakMap();
1469
- _fetchCallbacks = new WeakMap();
1470
- _runOnceCallbacks = new WeakMap();
1471
- _kvGetCallbacks = new WeakMap();
1472
- _kvSetCallbacks = new WeakMap();
1473
- _kvDeleteCallbacks = new WeakMap();
1474
- _initializeConnection = new WeakSet();
1475
- initializeConnection_fn = /* @__PURE__ */ __name(async function(instanceId) {
1476
- const id = instanceId ?? (0, import_uuid2.v4)();
1477
- __privateGet(this, _logger3).debug("Initializing connection", {
1478
- id,
1479
- endpoint: __privateGet(this, _endpoint)
1480
- });
1481
- const headers = {
1482
- Authorization: `Bearer ${__privateGet(this, _apiKey)}`
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]
1483
2281
  };
1484
- const connection = new HostConnection(new import_ws.WebSocket(__privateGet(this, _endpoint), {
1485
- headers,
1486
- followRedirects: true
1487
- }), {
1488
- id
1489
- });
1490
- connection.onClose.attach(async ([code, reason]) => {
1491
- if (__privateGet(this, _closedByUser)) {
1492
- __privateGet(this, _logger3).debug("Connection closed by user, so we won't reconnect");
1493
- __privateSet(this, _closedByUser, false);
1494
- return;
1495
- }
1496
- const chalk = (await import("chalk")).default;
1497
- __privateGet(this, _logger3).error(`${chalk.red("error")} Could not connect to trigger.dev${reason ? `: ${reason}` : `(code ${code})`}`);
1498
- if (!__privateGet(this, _isConnected))
1499
- return;
1500
- __privateGet(this, _logger3).log("\u{1F50C} Reconnecting to trigger.dev...");
1501
- __privateSet(this, _isConnected, false);
1502
- while (!__privateGet(this, _isConnected)) {
1503
- __privateMethod(this, _initializeConnection, initializeConnection_fn).call(this, id).then(() => {
1504
- __privateGet(this, _logger3).log("\u26A1 Reconnection successful");
1505
- }).catch(() => {
1506
- });
1507
- __privateGet(this, _logger3).debug(`Reconnection failed, retrying in ${Math.round(__privateGet(this, _retryIntervalMs) / 1e3)} seconds`, id);
1508
- await new Promise((resolve) => setTimeout(resolve, __privateGet(this, _retryIntervalMs)));
1509
- }
1510
- });
1511
- await connection.connect();
1512
- __privateGet(this, _logger3).debug("Connection initialized", id);
1513
- __privateSet(this, _connection2, connection);
1514
- __privateSet(this, _isConnected, true);
1515
- if (__privateGet(this, _serverRPC)) {
1516
- __privateGet(this, _serverRPC).resetConnection(connection);
1517
- await __privateMethod(this, _initializeHost, initializeHost_fn).call(this);
1518
- }
1519
- }, "#initializeConnection");
1520
- _initializeRPC = new WeakSet();
1521
- initializeRPC_fn = /* @__PURE__ */ __name(async function() {
1522
- if (!__privateGet(this, _connection2)) {
1523
- throw new Error("Cannot initialize RPC without a connection");
1524
- }
1525
- const serverRPC = new ZodRPC({
1526
- connection: __privateGet(this, _connection2),
1527
- sender: ServerRPCSchema,
1528
- receiver: HostRPCSchema,
1529
- handlers: {
1530
- RESOLVE_DELAY: async (data) => {
1531
- __privateGet(this, _logger3).debug("Handling RESOLVE_DELAY", data);
1532
- const waitCallbacks = __privateGet(this, _waitForCallbacks).get(messageKey(data.meta.runId, data.key));
1533
- if (!waitCallbacks) {
1534
- __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`);
1535
- return true;
1536
- }
1537
- const { resolve } = waitCallbacks;
1538
- resolve();
1539
- return true;
1540
- },
1541
- RESOLVE_RUN_ONCE: async (data) => {
1542
- __privateGet(this, _logger3).debug("Handling RESOLVE_RUN_ONCE", data);
1543
- const runOnceCallbacks = __privateGet(this, _runOnceCallbacks).get(messageKey(data.meta.runId, data.key));
1544
- if (!runOnceCallbacks) {
1545
- __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`);
1546
- return true;
1547
- }
1548
- const { resolve } = runOnceCallbacks;
1549
- resolve(data.output);
1550
- return true;
1551
- },
1552
- RESOLVE_REQUEST: async (data) => {
1553
- __privateGet(this, _logger3).debug("Handling RESOLVE_REQUEST", data);
1554
- const requestCallbacks = __privateGet(this, _responseCompleteCallbacks).get(messageKey(data.meta.runId, data.key));
1555
- if (!requestCallbacks) {
1556
- __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`);
1557
- return true;
1558
- }
1559
- const { resolve } = requestCallbacks;
1560
- resolve(data.output);
1561
- return true;
1562
- },
1563
- REJECT_REQUEST: async (data) => {
1564
- __privateGet(this, _logger3).debug("Handling REJECT_REQUEST", data);
1565
- const requestCallbacks = __privateGet(this, _responseCompleteCallbacks).get(messageKey(data.meta.runId, data.key));
1566
- if (!requestCallbacks) {
1567
- __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`);
1568
- return true;
1569
- }
1570
- const { reject } = requestCallbacks;
1571
- reject(data.error);
1572
- return true;
1573
- },
1574
- RESOLVE_FETCH_REQUEST: async (data) => {
1575
- __privateGet(this, _logger3).debug("Handling RESOLVE_FETCH_REQUEST", data);
1576
- const fetchCallbacks = __privateGet(this, _fetchCallbacks).get(messageKey(data.meta.runId, data.key));
1577
- if (!fetchCallbacks) {
1578
- __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`);
1579
- return true;
1580
- }
1581
- const { resolve } = fetchCallbacks;
1582
- resolve(data.output);
1583
- return true;
1584
- },
1585
- REJECT_FETCH_REQUEST: async (data) => {
1586
- __privateGet(this, _logger3).debug("Handling REJECT_FETCH_REQUEST", data);
1587
- const fetchCallbacks = __privateGet(this, _fetchCallbacks).get(messageKey(data.meta.runId, data.key));
1588
- if (!fetchCallbacks) {
1589
- __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`);
1590
- return true;
1591
- }
1592
- const { reject } = fetchCallbacks;
1593
- reject(data.error);
1594
- return true;
1595
- },
1596
- RESOLVE_KV_GET: async (data) => {
1597
- __privateGet(this, _logger3).debug("Handling RESOLVE_KV_GET", data);
1598
- const getCallbacks = __privateGet(this, _kvGetCallbacks).get(messageKey(data.meta.runId, data.key));
1599
- if (!getCallbacks) {
1600
- __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`);
1601
- return true;
1602
- }
1603
- const { resolve } = getCallbacks;
1604
- resolve(data.output);
1605
- return true;
1606
- },
1607
- RESOLVE_KV_SET: async (data) => {
1608
- __privateGet(this, _logger3).debug("Handling RESOLVE_KV_SET", data);
1609
- const setCallbacks = __privateGet(this, _kvSetCallbacks).get(messageKey(data.meta.runId, data.key));
1610
- if (!setCallbacks) {
1611
- __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`);
1612
- return true;
1613
- }
1614
- const { resolve } = setCallbacks;
1615
- resolve();
1616
- return true;
1617
- },
1618
- RESOLVE_KV_DELETE: async (data) => {
1619
- __privateGet(this, _logger3).debug("Handling RESOLVE_KV_DELETE", data);
1620
- const deleteCallbacks = __privateGet(this, _kvDeleteCallbacks).get(messageKey(data.meta.runId, data.key));
1621
- if (!deleteCallbacks) {
1622
- __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`);
1623
- return true;
1624
- }
1625
- const { resolve } = deleteCallbacks;
1626
- resolve();
1627
- return true;
2282
+ }
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 ?? {})
1628
2314
  },
1629
- TRIGGER_WORKFLOW: async (data) => {
1630
- __privateGet(this, _logger3).debug("Handling TRIGGER_WORKFLOW", data);
1631
- const parsedEventData = __privateGet(this, _options).on.schema.safeParse(data.trigger.input);
1632
- if (!parsedEventData.success) {
1633
- await serverRPC.send("SEND_WORKFLOW_ERROR", {
1634
- runId: data.id,
1635
- timestamp: String(highPrecisionTimestamp()),
1636
- error: {
1637
- name: "Event validation error",
1638
- message: (0, import_zod_error.generateErrorMessage)(parsedEventData.error.issues, zodErrorMessageOptions)
1639
- }
1640
- });
1641
- return true;
1642
- }
1643
- const fetchFunction = /* @__PURE__ */ __name(async (key, url, options) => {
1644
- const result = new Promise((resolve, reject) => {
1645
- __privateGet(this, _fetchCallbacks).set(messageKey(data.id, key), {
1646
- resolve,
1647
- reject
1648
- });
1649
- });
1650
- await serverRPC.send("SEND_FETCH", {
1651
- runId: data.id,
1652
- key,
1653
- fetch: {
1654
- url: url.toString(),
1655
- method: options.method ?? "GET",
1656
- headers: options.headers,
1657
- body: options.body,
1658
- retry: options.retry
1659
- },
1660
- timestamp: String(highPrecisionTimestamp())
1661
- });
1662
- const response = await result;
1663
- return {
1664
- status: response.status,
1665
- ok: response.ok,
1666
- headers: response.headers,
1667
- body: response.body ? (options.responseSchema ?? import_zod15.z.any()).parse(response.body) : void 0
1668
- };
1669
- }, "fetchFunction");
1670
- const kvGetFunction = /* @__PURE__ */ __name(async (op) => {
1671
- const result = new Promise((resolve, reject) => {
1672
- __privateGet(this, _kvGetCallbacks).set(messageKey(data.id, op.idempotencyKey), {
1673
- resolve,
1674
- reject
1675
- });
1676
- });
1677
- await serverRPC.send("SEND_KV_GET", {
1678
- runId: data.id,
1679
- key: op.idempotencyKey,
1680
- get: {
1681
- namespace: op.namespace,
1682
- key: op.key
1683
- },
1684
- timestamp: String(highPrecisionTimestamp())
1685
- });
1686
- const output = await result;
1687
- return output;
1688
- }, "kvGetFunction");
1689
- const kvSetFunction = /* @__PURE__ */ __name(async (op) => {
1690
- const result = new Promise((resolve, reject) => {
1691
- __privateGet(this, _kvSetCallbacks).set(messageKey(data.id, op.idempotencyKey), {
1692
- resolve,
1693
- reject
1694
- });
1695
- });
1696
- await serverRPC.send("SEND_KV_SET", {
1697
- runId: data.id,
1698
- key: op.idempotencyKey,
1699
- set: {
1700
- namespace: op.namespace,
1701
- key: op.key,
1702
- value: op.value
1703
- },
1704
- timestamp: String(highPrecisionTimestamp())
1705
- });
1706
- await result;
1707
- return;
1708
- }, "kvSetFunction");
1709
- const kvDeleteFunction = /* @__PURE__ */ __name(async (op) => {
1710
- const result = new Promise((resolve, reject) => {
1711
- __privateGet(this, _kvDeleteCallbacks).set(messageKey(data.id, op.idempotencyKey), {
1712
- resolve,
1713
- reject
1714
- });
1715
- });
1716
- await serverRPC.send("SEND_KV_DELETE", {
1717
- runId: data.id,
1718
- key: op.idempotencyKey,
1719
- delete: {
1720
- namespace: op.namespace,
1721
- key: op.key
1722
- },
1723
- timestamp: String(highPrecisionTimestamp())
1724
- });
1725
- await result;
1726
- return;
1727
- }, "kvDeleteFunction");
1728
- const ctx = {
1729
- id: data.id,
1730
- environment: data.meta.environment,
1731
- apiKey: data.meta.apiKey,
1732
- organizationId: data.meta.organizationId,
1733
- isTest: data.meta.isTest,
1734
- kv: new ContextKeyValueStorage(`workflow:${data.meta.workflowId}`, kvGetFunction, kvSetFunction, kvDeleteFunction),
1735
- globalKv: new ContextKeyValueStorage(`org:${data.meta.organizationId}`, kvGetFunction, kvSetFunction, kvDeleteFunction),
1736
- runKv: new ContextKeyValueStorage(`run:${data.id}`, kvGetFunction, kvSetFunction, kvDeleteFunction),
1737
- logger: new ContextLogger(async (level, message, properties) => {
1738
- await serverRPC.send("SEND_LOG", {
1739
- runId: data.id,
1740
- key: message,
1741
- log: {
1742
- level,
1743
- message,
1744
- properties: JSON.stringify(properties ?? {})
1745
- },
1746
- timestamp: String(highPrecisionTimestamp())
1747
- });
1748
- }),
1749
- sendEvent: async (key, event) => {
1750
- await serverRPC.send("SEND_EVENT", {
1751
- runId: data.id,
1752
- key,
1753
- event: JSON.parse(JSON.stringify(event)),
1754
- timestamp: String(highPrecisionTimestamp())
1755
- });
1756
- },
1757
- waitFor: async (key, options) => {
1758
- const result = new Promise((resolve, reject) => {
1759
- __privateGet(this, _waitForCallbacks).set(messageKey(data.id, key), {
1760
- resolve,
1761
- reject
1762
- });
1763
- });
1764
- await serverRPC.send("INITIALIZE_DELAY", {
1765
- runId: data.id,
1766
- key,
1767
- wait: {
1768
- type: "DELAY",
1769
- seconds: options.seconds,
1770
- minutes: options.minutes,
1771
- hours: options.hours,
1772
- days: options.days
1773
- },
1774
- timestamp: String(highPrecisionTimestamp())
1775
- });
1776
- await result;
1777
- return;
1778
- },
1779
- waitUntil: async (key, date) => {
1780
- const result = new Promise((resolve, reject) => {
1781
- __privateGet(this, _waitForCallbacks).set(messageKey(data.id, key), {
1782
- resolve,
1783
- reject
1784
- });
1785
- });
1786
- await serverRPC.send("INITIALIZE_DELAY", {
1787
- runId: data.id,
1788
- key,
1789
- wait: {
1790
- type: "SCHEDULE_FOR",
1791
- scheduledFor: date.toISOString()
1792
- },
1793
- timestamp: String(highPrecisionTimestamp())
1794
- });
1795
- await result;
1796
- return;
1797
- },
1798
- runOnce: async (key, callback) => {
1799
- const result = new Promise((resolve, reject) => {
1800
- __privateGet(this, _runOnceCallbacks).set(messageKey(data.id, key), {
1801
- resolve,
1802
- reject
1803
- });
1804
- });
1805
- await serverRPC.send("INITIALIZE_RUN_ONCE", {
1806
- runId: data.id,
1807
- key,
1808
- runOnce: {
1809
- type: "REMOTE"
1810
- },
1811
- timestamp: String(highPrecisionTimestamp())
1812
- });
1813
- const { idempotencyKey, hasRun, output } = await result;
1814
- if (hasRun) {
1815
- return output;
1816
- }
1817
- const callbackResult = await callback(idempotencyKey);
1818
- await serverRPC.send("COMPLETE_RUN_ONCE", {
1819
- runId: data.id,
1820
- key,
1821
- runOnce: {
1822
- type: "REMOTE",
1823
- idempotencyKey,
1824
- output: callbackResult ? JSON.stringify(callbackResult) : void 0
1825
- },
1826
- timestamp: String(highPrecisionTimestamp())
1827
- });
1828
- return callbackResult;
1829
- },
1830
- runOnceLocalOnly: async (key, callback) => {
1831
- const result = new Promise((resolve, reject) => {
1832
- __privateGet(this, _runOnceCallbacks).set(messageKey(data.id, key), {
1833
- resolve,
1834
- reject
1835
- });
1836
- });
1837
- await serverRPC.send("INITIALIZE_RUN_ONCE", {
1838
- runId: data.id,
1839
- key,
1840
- runOnce: {
1841
- type: "LOCAL_ONLY"
1842
- },
1843
- timestamp: String(highPrecisionTimestamp())
1844
- });
1845
- const { idempotencyKey } = await result;
1846
- return callback(idempotencyKey);
1847
- },
1848
- fetch: fetchFunction
1849
- };
1850
- const eventData = parsedEventData.data;
1851
- __privateGet(this, _logger3).debug("Parsed event data", eventData);
1852
- const terminalLink = (await import("terminal-link")).default;
1853
- triggerRunLocalStorage.run({
1854
- performRequest: async (key, options) => {
1855
- const result = new Promise((resolve, reject) => {
1856
- __privateGet(this, _responseCompleteCallbacks).set(messageKey(data.id, key), {
1857
- resolve,
1858
- reject
1859
- });
1860
- });
1861
- await serverRPC.send("SEND_REQUEST", {
1862
- runId: data.id,
1863
- key,
1864
- request: {
1865
- service: options.service,
1866
- endpoint: options.endpoint,
1867
- params: options.params,
1868
- version: options.version
1869
- },
1870
- timestamp: String(highPrecisionTimestamp())
1871
- });
1872
- const output = await result;
1873
- if (!options.response?.schema) {
1874
- return output;
1875
- }
1876
- return options.response.schema.parse(output);
1877
- },
1878
- sendEvent: async (key, event) => {
1879
- await serverRPC.send("SEND_EVENT", {
1880
- runId: data.id,
1881
- key,
1882
- event: JSON.parse(JSON.stringify(event)),
1883
- timestamp: String(highPrecisionTimestamp())
1884
- });
1885
- },
1886
- fetch: fetchFunction,
1887
- workflowId: data.meta.workflowId,
1888
- appOrigin: data.meta.appOrigin,
1889
- id: data.id
1890
- }, () => {
1891
- __privateGet(this, _logger3).debug("Running trigger...");
1892
- if (typeof data.meta.attempt === "number" && data.meta.attempt === 0) {
1893
- __privateGet(this, _logger3).log(`Run ${data.id} started \u{1F449} ${terminalLink("View on dashboard", `${__privateGet(this, _registerResponse).url}/runs/${data.id}`, {
1894
- fallback: (text, url) => `${text}: (${url})`
1895
- })}`);
1896
- }
1897
- serverRPC.send("START_WORKFLOW_RUN", {
1898
- runId: data.id,
1899
- timestamp: String(highPrecisionTimestamp())
1900
- }).then(() => {
1901
- return __privateGet(this, _trigger).options.run(eventData, ctx).then((output) => {
1902
- __privateGet(this, _logger3).log(`Run ${data.id} complete \u{1F449} ${terminalLink("View on dashboard", `${__privateGet(this, _registerResponse).url}/runs/${data.id}`, {
1903
- fallback: (text, url) => `${text}: (${url})`
1904
- })}`);
1905
- return serverRPC.send("COMPLETE_WORKFLOW_RUN", {
1906
- runId: data.id,
1907
- output: JSON.stringify(output),
1908
- timestamp: String(highPrecisionTimestamp())
1909
- });
1910
- }).catch((anyError) => {
1911
- const parseAnyError = /* @__PURE__ */ __name((error2) => {
1912
- if (error2 instanceof Error) {
1913
- return {
1914
- name: error2.name,
1915
- message: error2.message,
1916
- stackTrace: error2.stack
1917
- };
1918
- }
1919
- const parsedError = import_zod15.z.object({
1920
- name: import_zod15.z.string(),
1921
- message: import_zod15.z.string()
1922
- }).passthrough().safeParse(error2);
1923
- if (parsedError.success) {
1924
- return parsedError.data;
1925
- }
1926
- return {
1927
- name: "UnknownError",
1928
- message: "An unknown error occurred"
1929
- };
1930
- }, "parseAnyError");
1931
- const error = parseAnyError(anyError);
1932
- return serverRPC.send("SEND_WORKFLOW_ERROR", {
1933
- runId: data.id,
1934
- error,
1935
- timestamp: String(highPrecisionTimestamp())
1936
- });
1937
- });
1938
- }).catch((anyError) => {
1939
- return serverRPC.send("SEND_WORKFLOW_ERROR", {
1940
- runId: data.id,
1941
- error: anyError,
1942
- timestamp: String(highPrecisionTimestamp())
1943
- });
1944
- });
1945
- });
1946
- return true;
1947
- }
1948
- }
1949
- });
1950
- __privateGet(this, _logger3).debug("Successfully initialized RPC with server");
1951
- __privateSet(this, _serverRPC, serverRPC);
1952
- }, "#initializeRPC");
1953
- _initializeHost = new WeakSet();
1954
- initializeHost_fn = /* @__PURE__ */ __name(async function() {
1955
- if (!__privateGet(this, _connection2)) {
1956
- throw new Error("Cannot initialize host without a connection");
1957
- }
1958
- if (!__privateGet(this, _serverRPC)) {
1959
- throw new Error("Cannot initialize host without an RPC connection");
1960
- }
1961
- const repoInfo = await safeGetRepoInfo();
1962
- const remoteUrl = repoInfo ? await getRemoteUrl(repoInfo.commonGitDir) : void 0;
1963
- const packageMetadata = await getTriggerPackageEnvVars(process.env);
1964
- const response = await __privateMethod(this, _send, send_fn).call(this, "INITIALIZE_HOST_V2", {
1965
- apiKey: __privateGet(this, _apiKey),
1966
- workflowId: __privateGet(this, _trigger).id,
1967
- workflowName: __privateGet(this, _trigger).name,
1968
- trigger: __privateGet(this, _trigger).on.metadata,
1969
- packageVersion: version,
1970
- packageName: name,
1971
- triggerTTL: __privateGet(this, _options).triggerTTL,
1972
- metadata: {
1973
- git: repoInfo ? {
1974
- sha: repoInfo.sha,
1975
- branch: repoInfo.branch,
1976
- committer: repoInfo.committer,
1977
- committerDate: repoInfo.committerDate,
1978
- commitMessage: repoInfo.commitMessage,
1979
- origin: remoteUrl
1980
- } : void 0,
1981
- packageMetadata,
1982
- env: gatherEnvVars(process.env)
1983
- }
1984
- });
1985
- if (!response) {
1986
- throw new Error("Could not initialize workflow with server");
1987
- }
1988
- if (response?.type === "error") {
1989
- throw new Error(response.message);
1990
- }
1991
- __privateSet(this, _registerResponse, response.data);
1992
- __privateGet(this, _logger3).debug("Successfully initialized workflow with server");
1993
- }, "#initializeHost");
1994
- _send = new WeakSet();
1995
- send_fn = /* @__PURE__ */ __name(async function(methodName, request) {
1996
- if (!__privateGet(this, _serverRPC))
1997
- throw new Error("serverRPC not initialized");
1998
- while (true) {
1999
- try {
2000
- __privateGet(this, _logger3).debug(`Sending RPC request to server: ${methodName}`, request);
2001
- return await __privateGet(this, _serverRPC).send(methodName, request);
2002
- } catch (err) {
2003
- if (err instanceof TimeoutError) {
2004
- __privateGet(this, _logger3).log(`RPC call timed out, retrying in ${Math.round(__privateGet(this, _retryIntervalMs) / 1e3)}s...`);
2005
- __privateGet(this, _logger3).error(err);
2006
- await sleep(__privateGet(this, _retryIntervalMs));
2007
- } else {
2008
- throw err;
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
2009
2323
  }
2010
- }
2324
+ };
2011
2325
  }
2012
- }, "#send");
2013
- var sleep = /* @__PURE__ */ __name((ms) => new Promise((resolve) => setTimeout(resolve, ms)), "sleep");
2014
- var messageKey = /* @__PURE__ */ __name((runId, key) => `${runId}:${key}`, "messageKey");
2015
- function highPrecisionTimestamp() {
2016
- const [seconds, nanoseconds] = process.hrtime();
2017
- return seconds * 1e9 + nanoseconds;
2018
- }
2019
- __name(highPrecisionTimestamp, "highPrecisionTimestamp");
2020
- async function getTriggerPackageEnvVars(env) {
2021
- if (!env) {
2022
- return {};
2023
- }
2024
- if (env.npm_package_json) {
2025
- try {
2026
- const packageJson = JSON.parse(await (0, import_promises.readFile)(env.npm_package_json, "utf8"));
2027
- if (packageJson.triggerdotdev) {
2028
- return packageJson.triggerdotdev;
2029
- }
2030
- } catch (err) {
2031
- }
2326
+ async register(key, params) {
2327
+ return __privateGet(this, _client2).registerTrigger(this.id, key, this.registeredTriggerForParams(params));
2032
2328
  }
2033
- const envVars = Object.entries(env).filter(([key]) => key.startsWith("npm_package_triggerdotdev_")).map(([key, value]) => [
2034
- key.replace("npm_package_triggerdotdev_", ""),
2035
- value
2036
- ]);
2037
- return Object.fromEntries(envVars);
2038
- }
2039
- __name(getTriggerPackageEnvVars, "getTriggerPackageEnvVars");
2040
- async function getRemoteUrl(cwd) {
2041
- try {
2042
- const gitRemoteOriginUrl = (await import("git-remote-origin-url")).default;
2043
- return await gitRemoteOriginUrl({
2044
- cwd
2045
- });
2046
- } catch (err) {
2047
- return;
2329
+ attachToJob(triggerClient, job) {
2330
+ triggerClient.attachJobToDynamicTrigger(job, this);
2048
2331
  }
2049
- }
2050
- __name(getRemoteUrl, "getRemoteUrl");
2051
- async function safeGetRepoInfo() {
2052
- try {
2053
- const gitRepoInfo = (await import("git-repo-info")).default;
2054
- return gitRepoInfo();
2055
- } catch (err) {
2056
- return;
2332
+ get preprocessRuns() {
2333
+ return false;
2057
2334
  }
2058
- }
2059
- __name(safeGetRepoInfo, "safeGetRepoInfo");
2060
- function gatherEnvVars(env) {
2061
- if (!env) {
2062
- return {};
2063
- }
2064
- const envVars = Object.entries(env).filter(([key]) => key.startsWith("TRIGGER_") && key !== "TRIGGER_API_KEY").map(([key, value]) => [
2065
- key.replace("TRIGGER_", ""),
2066
- `${value}`
2067
- ]);
2068
- return Object.fromEntries(envVars);
2069
- }
2070
- __name(gatherEnvVars, "gatherEnvVars");
2335
+ };
2336
+ __name(DynamicTrigger, "DynamicTrigger");
2337
+ _client2 = new WeakMap();
2338
+ _options4 = new WeakMap();
2071
2339
 
2072
- // src/trigger/index.ts
2073
- var _client, _getApiKey, getApiKey_fn;
2074
- var Trigger = class {
2340
+ // src/triggers/scheduled.ts
2341
+ var IntervalTrigger = class {
2075
2342
  constructor(options) {
2076
- __privateAdd(this, _getApiKey);
2077
- __privateAdd(this, _client, void 0);
2078
2343
  this.options = options;
2079
2344
  }
2080
- async listen() {
2081
- const apiKey = __privateMethod(this, _getApiKey, getApiKey_fn).call(this);
2082
- const chalk = (await import("chalk")).default;
2083
- const terminalLink = (await import("terminal-link")).default;
2084
- if (apiKey.status === "invalid") {
2085
- 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", {
2086
- fallback(text, url) {
2087
- 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`
2088
2356
  }
2089
- })}`);
2090
- return;
2091
- } else if (apiKey.status === "missing") {
2092
- 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", {
2093
- fallback(text, url) {
2094
- 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
2095
2372
  }
2096
- })}`);
2097
- return;
2098
- }
2099
- if (!__privateGet(this, _client)) {
2100
- __privateSet(this, _client, new TriggerClient(this, this.options));
2101
- }
2102
- return __privateGet(this, _client).listen();
2373
+ }
2374
+ };
2103
2375
  }
2104
- get id() {
2105
- 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;
2106
2385
  }
2107
- get name() {
2108
- 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) {
2109
2402
  }
2110
- get endpoint() {
2111
- return this.options.endpoint;
2403
+ get preprocessRuns() {
2404
+ return false;
2112
2405
  }
2113
- get on() {
2114
- 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
+ };
2115
2416
  }
2116
2417
  };
2117
- __name(Trigger, "Trigger");
2118
- _client = new WeakMap();
2119
- _getApiKey = new WeakSet();
2120
- getApiKey_fn = /* @__PURE__ */ __name(function() {
2121
- const apiKey = this.options.apiKey ?? process.env.TRIGGER_API_KEY;
2122
- 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() {
2123
2432
  return {
2124
- status: "missing"
2433
+ name: "trigger.scheduled",
2434
+ title: "Dynamic Schedule",
2435
+ source: "trigger.dev",
2436
+ icon: "schedule-dynamic",
2437
+ parsePayload: ScheduledPayloadSchema.parse
2125
2438
  };
2126
2439
  }
2127
- const isValid = apiKey.match(/^trigger_[a-z]+_[a-zA-Z0-9]+$/);
2128
- 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() {
2129
2453
  return {
2130
- status: "invalid",
2131
- apiKey
2454
+ type: "dynamic",
2455
+ id: this.options.id
2132
2456
  };
2133
2457
  }
2134
- return {
2135
- status: "valid",
2136
- apiKey
2137
- };
2138
- }, "#getApiKey");
2458
+ };
2459
+ __name(DynamicSchedule, "DynamicSchedule");
2139
2460
 
2140
- // src/customEvents.ts
2141
- var import_node_fetch = __toESM(require("node-fetch"));
2142
- function sendEvent(idOrKey, event) {
2143
- const triggerRun = triggerRunLocalStorage.getStore();
2144
- if (!triggerRun) {
2145
- return sendEventFetch(idOrKey, event);
2146
- }
2147
- return triggerRun.sendEvent(idOrKey, event);
2461
+ // src/triggers/notifications.ts
2462
+ function missingConnectionNotification(integrations) {
2463
+ return new MissingConnectionNotification({
2464
+ integrations
2465
+ });
2148
2466
  }
2149
- __name(sendEvent, "sendEvent");
2150
- async function sendEventFetch(id, event) {
2151
- if (!process.env.TRIGGER_API_KEY) {
2152
- throw new Error(`There was a problem sending a custom event: the TRIGGER_API_KEY environment variable is not set`);
2153
- }
2154
- const baseUrl = process.env.TRIGGER_API_URL || "https://app.trigger.dev";
2155
- const url = `${baseUrl}/api/v1/events`;
2156
- const response = await (0, import_node_fetch.default)(url, {
2157
- method: "POST",
2158
- headers: {
2159
- "Content-Type": "application/json",
2160
- Authorization: `Bearer ${process.env.TRIGGER_API_KEY}`
2161
- },
2162
- body: JSON.stringify({
2163
- id,
2164
- event
2165
- })
2467
+ __name(missingConnectionNotification, "missingConnectionNotification");
2468
+ function missingConnectionResolvedNotification(integrations) {
2469
+ return new MissingConnectionResolvedNotification({
2470
+ integrations
2166
2471
  });
2167
- if (!response.ok) {
2168
- throw new Error(`There was a problem sending a custom event: ${response.statusText}`);
2169
- }
2170
- return;
2171
2472
  }
2172
- __name(sendEventFetch, "sendEventFetch");
2173
-
2174
- // src/fetch.ts
2175
- function fetch2(key, url, options) {
2176
- const triggerRun = triggerRunLocalStorage.getStore();
2177
- if (!triggerRun) {
2178
- 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;
2179
2477
  }
2180
- return triggerRun.fetch(key, url, options);
2181
- }
2182
- __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");
2183
2556
 
2184
2557
  // src/index.ts
2185
- function getTriggerRun() {
2186
- return triggerRunLocalStorage.getStore();
2187
- }
2188
- __name(getTriggerRun, "getTriggerRun");
2189
2558
  function secureString(strings, ...interpolations) {
2190
2559
  return {
2191
2560
  __secureString: true,
@@ -2196,13 +2565,27 @@ function secureString(strings, ...interpolations) {
2196
2565
  __name(secureString, "secureString");
2197
2566
  // Annotate the CommonJS export names for ESM import in node:
2198
2567
  0 && (module.exports = {
2199
- Trigger,
2200
- customEvent,
2201
- fetch,
2202
- getTriggerRun,
2203
- scheduleEvent,
2204
- secureString,
2205
- sendEvent,
2206
- 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
2207
2590
  });
2208
2591
  //# sourceMappingURL=index.js.map