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

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