@trigger.dev/sdk 0.0.0-isomorphic-sdk-20230918151405 → 0.0.0-node-18-20231010094401

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
@@ -5,6 +5,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
9
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
10
  var __export = (target, all) => {
10
11
  for (var name in all)
@@ -23,6 +24,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
24
  mod
24
25
  ));
25
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var __publicField = (obj, key, value) => {
28
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
29
+ return value;
30
+ };
26
31
  var __accessCheck = (obj, member, msg) => {
27
32
  if (!member.has(obj))
28
33
  throw TypeError("Cannot " + msg);
@@ -107,6 +112,9 @@ var Job = class {
107
112
  get version() {
108
113
  return this.options.version;
109
114
  }
115
+ get logLevel() {
116
+ return this.options.logLevel;
117
+ }
110
118
  get integrations() {
111
119
  return Object.keys(this.options.integrations ?? {}).reduce((acc, key) => {
112
120
  const integration = this.options.integrations[key];
@@ -118,9 +126,6 @@ var Job = class {
118
126
  return acc;
119
127
  }, {});
120
128
  }
121
- get logLevel() {
122
- return this.options.logLevel;
123
- }
124
129
  toJSON() {
125
130
  const internal = this.options.__internal;
126
131
  return {
@@ -146,7 +151,7 @@ validate_fn = /* @__PURE__ */ __name(function() {
146
151
  }, "#validate");
147
152
 
148
153
  // src/triggerClient.ts
149
- var import_core5 = require("@trigger.dev/core");
154
+ var import_core7 = require("@trigger.dev/core");
150
155
 
151
156
  // src/apiClient.ts
152
157
  var import_core = require("@trigger.dev/core");
@@ -162,17 +167,47 @@ var ApiClient = class {
162
167
  __privateSet(this, _apiUrl, __privateGet(this, _options).apiUrl ?? process.env.TRIGGER_API_URL ?? "https://api.trigger.dev");
163
168
  __privateSet(this, _logger, new import_core.Logger("trigger.dev", __privateGet(this, _options).logLevel));
164
169
  }
165
- async runTask(runId, task) {
170
+ async registerEndpoint(options) {
171
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
172
+ __privateGet(this, _logger).debug("Registering endpoint", {
173
+ url: options.url,
174
+ name: options.name
175
+ });
176
+ const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
177
+ method: "POST",
178
+ headers: {
179
+ "Content-Type": "application/json",
180
+ Authorization: `Bearer ${apiKey}`
181
+ },
182
+ body: JSON.stringify({
183
+ url: options.url,
184
+ name: options.name
185
+ })
186
+ });
187
+ if (response.status >= 400 && response.status < 500) {
188
+ const body = await response.json();
189
+ throw new Error(body.error);
190
+ }
191
+ if (response.status !== 200) {
192
+ throw new Error(`Failed to register entry point, got status code ${response.status}`);
193
+ }
194
+ return await response.json();
195
+ }
196
+ async runTask(runId, task, options = {}) {
166
197
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
167
198
  __privateGet(this, _logger).debug("Running Task", {
168
199
  task
169
200
  });
170
- return await zodfetch(import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
201
+ return await zodfetchWithVersions({
202
+ [import_core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: import_core.RunTaskResponseWithCachedTasksBodySchema
203
+ }, import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
171
204
  method: "POST",
172
205
  headers: {
173
206
  "Content-Type": "application/json",
174
207
  Authorization: `Bearer ${apiKey}`,
175
- "Idempotency-Key": task.idempotencyKey
208
+ "Idempotency-Key": task.idempotencyKey,
209
+ "X-Cached-Tasks-Cursor": options.cachedTasksCursor ?? "",
210
+ "Trigger-Version": import_core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS
176
211
  },
177
212
  body: JSON.stringify(task)
178
213
  });
@@ -237,6 +272,21 @@ var ApiClient = class {
237
272
  }
238
273
  });
239
274
  }
275
+ async updateStatus(runId, id, status) {
276
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
277
+ __privateGet(this, _logger).debug("Update status", {
278
+ id,
279
+ status
280
+ });
281
+ return await zodfetch(import_core.JobRunStatusRecordSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses/${id}`, {
282
+ method: "PUT",
283
+ headers: {
284
+ "Content-Type": "application/json",
285
+ Authorization: `Bearer ${apiKey}`
286
+ },
287
+ body: JSON.stringify(status)
288
+ });
289
+ }
240
290
  async updateSource(client, key, source) {
241
291
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
242
292
  __privateGet(this, _logger).debug("activating http source", {
@@ -343,6 +393,31 @@ var ApiClient = class {
343
393
  }
344
394
  });
345
395
  }
396
+ async cancelRun(runId) {
397
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
398
+ __privateGet(this, _logger).debug("Cancelling Run", {
399
+ runId
400
+ });
401
+ return await zodfetch(import_core.GetRunSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/cancel`, {
402
+ method: "POST",
403
+ headers: {
404
+ "Content-Type": "application/json",
405
+ Authorization: `Bearer ${apiKey}`
406
+ }
407
+ });
408
+ }
409
+ async getRunStatuses(runId) {
410
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
411
+ __privateGet(this, _logger).debug("Getting Run statuses", {
412
+ runId
413
+ });
414
+ return await zodfetch(import_core.GetRunStatusesSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses`, {
415
+ method: "GET",
416
+ headers: {
417
+ Authorization: `Bearer ${apiKey}`
418
+ }
419
+ });
420
+ }
346
421
  async getRuns(jobSlug, options) {
347
422
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
348
423
  __privateGet(this, _logger).debug("Getting Runs", {
@@ -390,6 +465,36 @@ function getApiKey(key) {
390
465
  };
391
466
  }
392
467
  __name(getApiKey, "getApiKey");
468
+ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options) {
469
+ const response = await fetch(url, requestInit);
470
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
471
+ return;
472
+ }
473
+ if (response.status >= 400 && response.status < 500) {
474
+ const body = await response.json();
475
+ throw new Error(body.error);
476
+ }
477
+ if (response.status !== 200) {
478
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
479
+ }
480
+ const jsonBody = await response.json();
481
+ const version = response.headers.get("trigger-version");
482
+ if (!version) {
483
+ return {
484
+ version: "unversioned",
485
+ body: unversionedSchema.parse(jsonBody)
486
+ };
487
+ }
488
+ const versionedSchema = versionedSchemaMap[version];
489
+ if (!versionedSchema) {
490
+ throw new Error(`Unknown version ${version}`);
491
+ }
492
+ return {
493
+ version,
494
+ body: versionedSchema.parse(jsonBody)
495
+ };
496
+ }
497
+ __name(zodfetchWithVersions, "zodfetchWithVersions");
393
498
  async function zodfetch(schema, url, requestInit, options) {
394
499
  const response = await fetch(url, requestInit);
395
500
  if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
@@ -428,14 +533,27 @@ var CanceledWithTaskError = class {
428
533
  }
429
534
  };
430
535
  __name(CanceledWithTaskError, "CanceledWithTaskError");
536
+ var YieldExecutionError = class {
537
+ constructor(key) {
538
+ this.key = key;
539
+ }
540
+ };
541
+ __name(YieldExecutionError, "YieldExecutionError");
542
+ var ParsedPayloadSchemaError = class {
543
+ constructor(schemaErrors) {
544
+ this.schemaErrors = schemaErrors;
545
+ }
546
+ };
547
+ __name(ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
431
548
  function isTriggerError(err) {
432
- return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError;
549
+ return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError;
433
550
  }
434
551
  __name(isTriggerError, "isTriggerError");
435
552
 
436
553
  // src/io.ts
437
554
  var import_core3 = require("@trigger.dev/core");
438
- var import_node_async_hooks = require("node:async_hooks");
555
+ var import_node_async_hooks = require("async_hooks");
556
+ var import_node_crypto = require("crypto");
439
557
 
440
558
  // src/retry.ts
441
559
  var import_core2 = require("@trigger.dev/core");
@@ -449,12 +567,46 @@ var retry = {
449
567
  }
450
568
  };
451
569
 
570
+ // src/status.ts
571
+ var TriggerStatus = class {
572
+ constructor(id, io) {
573
+ this.id = id;
574
+ this.io = io;
575
+ }
576
+ async update(key, status) {
577
+ const properties = [];
578
+ if (status.label) {
579
+ properties.push({
580
+ label: "Label",
581
+ text: status.label
582
+ });
583
+ }
584
+ if (status.state) {
585
+ properties.push({
586
+ label: "State",
587
+ text: status.state
588
+ });
589
+ }
590
+ return await this.io.runTask(key, async (task) => {
591
+ return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);
592
+ }, {
593
+ name: status.label ?? `Status update`,
594
+ icon: "bell",
595
+ params: {
596
+ ...status
597
+ },
598
+ properties
599
+ });
600
+ }
601
+ };
602
+ __name(TriggerStatus, "TriggerStatus");
603
+
452
604
  // src/io.ts
453
- var import_node_buffer = require("buffer");
454
605
  var _addToCachedTasks, addToCachedTasks_fn;
455
606
  var IO = class {
456
607
  constructor(options) {
457
608
  __privateAdd(this, _addToCachedTasks);
609
+ __publicField(this, "brb", this.yield.bind(this));
458
610
  this._id = options.id;
459
611
  this._apiClient = options.apiClient;
460
612
  this._triggerClient = options.client;
@@ -462,49 +614,74 @@ var IO = class {
462
614
  this._cachedTasks = /* @__PURE__ */ new Map();
463
615
  this._jobLogger = options.jobLogger;
464
616
  this._jobLogLevel = options.jobLogLevel;
617
+ this._stats = {
618
+ initialCachedTasks: 0,
619
+ lazyLoadedCachedTasks: 0,
620
+ executedTasks: 0,
621
+ cachedTaskHits: 0,
622
+ cachedTaskMisses: 0,
623
+ noopCachedTaskHits: 0,
624
+ noopCachedTaskMisses: 0
625
+ };
465
626
  if (options.cachedTasks) {
466
627
  options.cachedTasks.forEach((task) => {
467
628
  this._cachedTasks.set(task.idempotencyKey, task);
468
629
  });
630
+ this._stats.initialCachedTasks = options.cachedTasks.length;
469
631
  }
470
632
  this._taskStorage = new import_node_async_hooks.AsyncLocalStorage();
471
633
  this._context = options.context;
634
+ this._yieldedExecutions = options.yieldedExecutions ?? [];
635
+ if (options.noopTasksSet) {
636
+ this._noopTasksBloomFilter = import_core3.BloomFilter.deserialize(options.noopTasksSet, import_core3.BloomFilter.NOOP_TASK_SET_SIZE);
637
+ }
638
+ this._cachedTasksCursor = options.cachedTasksCursor;
639
+ this._serverVersion = options.serverVersion ?? "unversioned";
640
+ }
641
+ get stats() {
642
+ return this._stats;
643
+ }
644
+ get runId() {
645
+ return this._id;
646
+ }
647
+ get triggerClient() {
648
+ return this._triggerClient;
472
649
  }
473
650
  get logger() {
474
651
  return new IOLogger(async (level, message, data) => {
475
652
  let logLevel = "info";
476
- switch (level) {
477
- case "LOG": {
478
- this._jobLogger?.log(message, data);
479
- logLevel = "log";
480
- break;
481
- }
482
- case "DEBUG": {
483
- this._jobLogger?.debug(message, data);
484
- logLevel = "debug";
485
- break;
486
- }
487
- case "INFO": {
488
- this._jobLogger?.info(message, data);
489
- logLevel = "info";
490
- break;
491
- }
492
- case "WARN": {
493
- this._jobLogger?.warn(message, data);
494
- logLevel = "warn";
495
- break;
496
- }
497
- case "ERROR": {
498
- this._jobLogger?.error(message, data);
499
- logLevel = "error";
500
- break;
501
- }
502
- }
503
653
  if (import_core3.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
504
654
  await this.runTask([
505
655
  message,
506
656
  level
507
657
  ], async (task) => {
658
+ switch (level) {
659
+ case "LOG": {
660
+ this._jobLogger?.log(message, data);
661
+ logLevel = "log";
662
+ break;
663
+ }
664
+ case "DEBUG": {
665
+ this._jobLogger?.debug(message, data);
666
+ logLevel = "debug";
667
+ break;
668
+ }
669
+ case "INFO": {
670
+ this._jobLogger?.info(message, data);
671
+ logLevel = "info";
672
+ break;
673
+ }
674
+ case "WARN": {
675
+ this._jobLogger?.warn(message, data);
676
+ logLevel = "warn";
677
+ break;
678
+ }
679
+ case "ERROR": {
680
+ this._jobLogger?.error(message, data);
681
+ logLevel = "error";
682
+ break;
683
+ }
684
+ }
508
685
  }, {
509
686
  name: "log",
510
687
  icon: "log",
@@ -540,6 +717,12 @@ var IO = class {
540
717
  }
541
718
  });
542
719
  }
720
+ async createStatus(key, initialStatus) {
721
+ const id = typeof key === "string" ? key : key.join("-");
722
+ const status = new TriggerStatus(id, this);
723
+ await status.update(key, initialStatus);
724
+ return status;
725
+ }
543
726
  async backgroundFetch(key, url, requestInit, retry2) {
544
727
  const urlObject = new URL(url);
545
728
  return await this.runTask(key, async (task) => {
@@ -783,18 +966,42 @@ var IO = class {
783
966
  const cachedTask = this._cachedTasks.get(idempotencyKey);
784
967
  if (cachedTask && cachedTask.status === "COMPLETED") {
785
968
  this._logger.debug("Using completed cached task", {
786
- idempotencyKey,
787
- cachedTask
969
+ idempotencyKey
788
970
  });
971
+ this._stats.cachedTaskHits++;
789
972
  return cachedTask.output;
790
973
  }
791
- const task = await this._apiClient.runTask(this._id, {
974
+ if (options?.noop && this._noopTasksBloomFilter) {
975
+ if (this._noopTasksBloomFilter.test(idempotencyKey)) {
976
+ this._logger.debug("task idempotency key exists in noopTasksBloomFilter", {
977
+ idempotencyKey
978
+ });
979
+ this._stats.noopCachedTaskHits++;
980
+ return {};
981
+ }
982
+ }
983
+ const response = await this._apiClient.runTask(this._id, {
792
984
  idempotencyKey,
793
985
  displayKey: typeof key === "string" ? key : void 0,
794
986
  noop: false,
795
987
  ...options ?? {},
796
988
  parentId
989
+ }, {
990
+ cachedTasksCursor: this._cachedTasksCursor
797
991
  });
992
+ const task = response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
993
+ if (response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
994
+ this._cachedTasksCursor = response.body.cachedTasks?.cursor;
995
+ for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
996
+ if (!this._cachedTasks.has(cachedTask2.idempotencyKey)) {
997
+ this._cachedTasks.set(cachedTask2.idempotencyKey, cachedTask2);
998
+ this._logger.debug("Injecting lazy loaded task into task cache", {
999
+ idempotencyKey: cachedTask2.idempotencyKey
1000
+ });
1001
+ this._stats.lazyLoadedCachedTasks++;
1002
+ }
1003
+ }
1004
+ }
798
1005
  if (task.status === "CANCELED") {
799
1006
  this._logger.debug("Task canceled", {
800
1007
  idempotencyKey,
@@ -803,11 +1010,18 @@ var IO = class {
803
1010
  throw new CanceledWithTaskError(task);
804
1011
  }
805
1012
  if (task.status === "COMPLETED") {
806
- this._logger.debug("Using task output", {
807
- idempotencyKey,
808
- task
809
- });
810
- __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1013
+ if (task.noop) {
1014
+ this._logger.debug("Noop Task completed", {
1015
+ idempotencyKey
1016
+ });
1017
+ this._noopTasksBloomFilter?.add(task.idempotencyKey);
1018
+ } else {
1019
+ this._logger.debug("Cache miss", {
1020
+ idempotencyKey
1021
+ });
1022
+ this._stats.cachedTaskMisses++;
1023
+ __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1024
+ }
811
1025
  return task.output;
812
1026
  }
813
1027
  if (task.status === "ERRORED") {
@@ -817,23 +1031,16 @@ var IO = class {
817
1031
  });
818
1032
  throw new Error(task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
819
1033
  }
820
- if (task.status === "WAITING") {
821
- this._logger.debug("Task waiting", {
822
- idempotencyKey,
823
- task
824
- });
825
- throw new ResumeWithTaskError(task);
826
- }
827
- if (task.status === "RUNNING" && typeof task.operation === "string") {
828
- this._logger.debug("Task running operation", {
829
- idempotencyKey,
830
- task
831
- });
832
- throw new ResumeWithTaskError(task);
833
- }
834
1034
  const executeTask = /* @__PURE__ */ __name(async () => {
835
1035
  try {
836
1036
  const result = await callback(task, this);
1037
+ if (task.status === "WAITING" && task.callbackUrl) {
1038
+ this._logger.debug("Waiting for remote callback", {
1039
+ idempotencyKey,
1040
+ task
1041
+ });
1042
+ return {};
1043
+ }
837
1044
  const output = import_core3.SerializableJsonSchema.parse(result);
838
1045
  this._logger.debug("Completing using output", {
839
1046
  idempotencyKey,
@@ -843,6 +1050,7 @@ var IO = class {
843
1050
  output: output ?? void 0,
844
1051
  properties: task.outputProperties ?? void 0
845
1052
  });
1053
+ this._stats.executedTasks++;
846
1054
  if (completedTask.status === "CANCELED") {
847
1055
  throw new CanceledWithTaskError(completedTask);
848
1056
  }
@@ -851,6 +1059,7 @@ var IO = class {
851
1059
  if (isTriggerError(error)) {
852
1060
  throw error;
853
1061
  }
1062
+ let skipRetrying = false;
854
1063
  if (onError) {
855
1064
  try {
856
1065
  const onErrorResult = onError(error, task, this);
@@ -858,10 +1067,13 @@ var IO = class {
858
1067
  if (onErrorResult instanceof Error) {
859
1068
  error = onErrorResult;
860
1069
  } else {
861
- const parsedError2 = import_core3.ErrorWithStackSchema.safeParse(onErrorResult.error);
862
- throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
863
- message: "Unknown error"
864
- }, task, onErrorResult.retryAt);
1070
+ skipRetrying = !!onErrorResult.skipRetrying;
1071
+ if (onErrorResult.retryAt && !skipRetrying) {
1072
+ const parsedError2 = import_core3.ErrorWithStackSchema.safeParse(onErrorResult.error);
1073
+ throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
1074
+ message: "Unknown error"
1075
+ }, task, onErrorResult.retryAt);
1076
+ }
865
1077
  }
866
1078
  }
867
1079
  } catch (innerError) {
@@ -872,7 +1084,7 @@ var IO = class {
872
1084
  }
873
1085
  }
874
1086
  const parsedError = import_core3.ErrorWithStackSchema.safeParse(error);
875
- if (options?.retry) {
1087
+ if (options?.retry && !skipRetrying) {
876
1088
  const retryAt = (0, import_core2.calculateRetryAt)(options.retry, task.attempts - 1);
877
1089
  if (retryAt) {
878
1090
  throw new RetryWithTaskError(parsedError.success ? parsedError.data : {
@@ -895,10 +1107,39 @@ var IO = class {
895
1107
  throw error;
896
1108
  }
897
1109
  }, "executeTask");
1110
+ if (task.status === "WAITING") {
1111
+ this._logger.debug("Task waiting", {
1112
+ idempotencyKey,
1113
+ task
1114
+ });
1115
+ if (task.callbackUrl) {
1116
+ await this._taskStorage.run({
1117
+ taskId: task.id
1118
+ }, executeTask);
1119
+ }
1120
+ throw new ResumeWithTaskError(task);
1121
+ }
1122
+ if (task.status === "RUNNING" && typeof task.operation === "string") {
1123
+ this._logger.debug("Task running operation", {
1124
+ idempotencyKey,
1125
+ task
1126
+ });
1127
+ throw new ResumeWithTaskError(task);
1128
+ }
898
1129
  return this._taskStorage.run({
899
1130
  taskId: task.id
900
1131
  }, executeTask);
901
1132
  }
1133
+ yield(key) {
1134
+ if (!(0, import_core3.supportsFeature)("yieldExecution", this._serverVersion)) {
1135
+ console.warn("[trigger.dev] io.yield() is not support by the version of the Trigger.dev server you are using, you will need to upgrade your self-hosted Trigger.dev instance.");
1136
+ return;
1137
+ }
1138
+ if (this._yieldedExecutions.includes(key)) {
1139
+ return;
1140
+ }
1141
+ throw new YieldExecutionError(key);
1142
+ }
902
1143
  async try(tryCallback, catchCallback) {
903
1144
  try {
904
1145
  return await tryCallback();
@@ -923,8 +1164,8 @@ async function generateIdempotencyKey(keyMaterial) {
923
1164
  return stableStringify(key2);
924
1165
  });
925
1166
  const key = keys.join(":");
926
- const hash = await crypto.subtle.digest("SHA-256", import_node_buffer.Buffer.from(key));
927
- return import_node_buffer.Buffer.from(hash).toString("hex");
1167
+ const hash = await import_node_crypto.webcrypto.subtle.digest("SHA-256", Buffer.from(key));
1168
+ return Buffer.from(hash).toString("hex");
928
1169
  }
929
1170
  __name(generateIdempotencyKey, "generateIdempotencyKey");
930
1171
  function stableStringify(obj) {
@@ -998,27 +1239,147 @@ function createIOWithIntegrations(io, auths, integrations) {
998
1239
  }
999
1240
  __name(createIOWithIntegrations, "createIOWithIntegrations");
1000
1241
 
1001
- // src/triggers/eventTrigger.ts
1242
+ // src/utils/typedAsyncLocalStorage.ts
1243
+ var import_node_async_hooks2 = require("async_hooks");
1244
+ var TypedAsyncLocalStorage = class {
1245
+ constructor() {
1246
+ this.storage = new import_node_async_hooks2.AsyncLocalStorage();
1247
+ }
1248
+ runWith(context, fn) {
1249
+ return this.storage.run(context, fn);
1250
+ }
1251
+ getStore() {
1252
+ return this.storage.getStore();
1253
+ }
1254
+ };
1255
+ __name(TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
1256
+
1257
+ // src/runLocalStorage.ts
1258
+ var runLocalStorage = new TypedAsyncLocalStorage();
1259
+
1260
+ // src/triggers/dynamic.ts
1002
1261
  var import_core4 = require("@trigger.dev/core");
1003
- var _options2;
1004
- var EventTrigger = class {
1005
- constructor(options) {
1262
+ var _client, _options2;
1263
+ var DynamicTrigger = class {
1264
+ constructor(client, options) {
1265
+ __privateAdd(this, _client, void 0);
1006
1266
  __privateAdd(this, _options2, void 0);
1267
+ __privateSet(this, _client, client);
1007
1268
  __privateSet(this, _options2, options);
1269
+ this.source = options.source;
1270
+ client.attachDynamicTrigger(this);
1271
+ }
1272
+ toJSON() {
1273
+ return {
1274
+ type: "dynamic",
1275
+ id: __privateGet(this, _options2).id
1276
+ };
1277
+ }
1278
+ get id() {
1279
+ return __privateGet(this, _options2).id;
1280
+ }
1281
+ get event() {
1282
+ return __privateGet(this, _options2).event;
1283
+ }
1284
+ registeredTriggerForParams(params, options = {}) {
1285
+ const key = slugifyId(this.source.key(params));
1286
+ return {
1287
+ rule: {
1288
+ event: this.event.name,
1289
+ source: this.event.source,
1290
+ payload: (0, import_core4.deepMergeFilters)(this.source.filter(params), this.event.filter ?? {}, options.filter ?? {})
1291
+ },
1292
+ source: {
1293
+ version: "2",
1294
+ key,
1295
+ channel: this.source.channel,
1296
+ params,
1297
+ options: {
1298
+ event: typeof this.event.name === "string" ? [
1299
+ this.event.name
1300
+ ] : this.event.name
1301
+ },
1302
+ integration: {
1303
+ id: this.source.integration.id,
1304
+ metadata: this.source.integration.metadata,
1305
+ authSource: this.source.integration.authSource
1306
+ }
1307
+ },
1308
+ accountId: options.accountId
1309
+ };
1310
+ }
1311
+ async register(key, params, options = {}) {
1312
+ const runStore = runLocalStorage.getStore();
1313
+ if (!runStore) {
1314
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options));
1315
+ }
1316
+ const { io } = runStore;
1317
+ return await io.runTask([
1318
+ key,
1319
+ "register"
1320
+ ], async (task) => {
1321
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options));
1322
+ }, {
1323
+ name: "Register Dynamic Trigger",
1324
+ properties: [
1325
+ {
1326
+ label: "Dynamic Trigger ID",
1327
+ text: this.id
1328
+ },
1329
+ {
1330
+ label: "ID",
1331
+ text: key
1332
+ }
1333
+ ],
1334
+ params
1335
+ });
1336
+ }
1337
+ attachToJob(triggerClient, job) {
1338
+ triggerClient.attachJobToDynamicTrigger(job, this);
1339
+ }
1340
+ get preprocessRuns() {
1341
+ return true;
1342
+ }
1343
+ };
1344
+ __name(DynamicTrigger, "DynamicTrigger");
1345
+ _client = new WeakMap();
1346
+ _options2 = new WeakMap();
1347
+
1348
+ // src/triggers/eventTrigger.ts
1349
+ var import_core5 = require("@trigger.dev/core");
1350
+
1351
+ // src/utils/formatSchemaErrors.ts
1352
+ function formatSchemaErrors(errors) {
1353
+ return errors.map((error) => {
1354
+ const { path, message } = error;
1355
+ return {
1356
+ path: path.map(String),
1357
+ message
1358
+ };
1359
+ });
1360
+ }
1361
+ __name(formatSchemaErrors, "formatSchemaErrors");
1362
+
1363
+ // src/triggers/eventTrigger.ts
1364
+ var _options3;
1365
+ var EventTrigger = class {
1366
+ constructor(options) {
1367
+ __privateAdd(this, _options3, void 0);
1368
+ __privateSet(this, _options3, options);
1008
1369
  }
1009
1370
  toJSON() {
1010
1371
  return {
1011
1372
  type: "static",
1012
- title: __privateGet(this, _options2).name ?? __privateGet(this, _options2).event.title,
1373
+ title: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.title,
1013
1374
  rule: {
1014
- event: __privateGet(this, _options2).name ?? __privateGet(this, _options2).event.name,
1015
- source: __privateGet(this, _options2).source ?? "trigger.dev",
1016
- payload: (0, import_core4.deepMergeFilters)(__privateGet(this, _options2).filter ?? {}, __privateGet(this, _options2).event.filter ?? {})
1375
+ event: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.name,
1376
+ source: __privateGet(this, _options3).source ?? "trigger.dev",
1377
+ payload: (0, import_core5.deepMergeFilters)(__privateGet(this, _options3).filter ?? {}, __privateGet(this, _options3).event.filter ?? {})
1017
1378
  }
1018
1379
  };
1019
1380
  }
1020
1381
  get event() {
1021
- return __privateGet(this, _options2).event;
1382
+ return __privateGet(this, _options3).event;
1022
1383
  }
1023
1384
  attachToJob(triggerClient, job) {
1024
1385
  }
@@ -1027,7 +1388,7 @@ var EventTrigger = class {
1027
1388
  }
1028
1389
  };
1029
1390
  __name(EventTrigger, "EventTrigger");
1030
- _options2 = new WeakMap();
1391
+ _options3 = new WeakMap();
1031
1392
  function eventTrigger(options) {
1032
1393
  return new EventTrigger({
1033
1394
  name: options.name,
@@ -1040,7 +1401,11 @@ function eventTrigger(options) {
1040
1401
  examples: options.examples,
1041
1402
  parsePayload: (rawPayload) => {
1042
1403
  if (options.schema) {
1043
- return options.schema.parse(rawPayload);
1404
+ const results = options.schema.safeParse(rawPayload);
1405
+ if (!results.success) {
1406
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
1407
+ }
1408
+ return results.data;
1044
1409
  }
1045
1410
  return rawPayload;
1046
1411
  }
@@ -1049,35 +1414,239 @@ function eventTrigger(options) {
1049
1414
  }
1050
1415
  __name(eventTrigger, "eventTrigger");
1051
1416
 
1052
- // src/triggerClient.ts
1053
- var registerSourceEvent = {
1054
- name: import_core5.REGISTER_SOURCE_EVENT_V2,
1055
- title: "Register Source",
1056
- source: "internal",
1057
- icon: "register-source",
1058
- parsePayload: import_core5.RegisterSourceEventSchemaV2.parse
1059
- };
1060
- var _options3, _registeredJobs, _registeredSources, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _client, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn;
1061
- var TriggerClient = class {
1062
- constructor(options) {
1063
- __privateAdd(this, _preprocessRun);
1064
- __privateAdd(this, _executeJob);
1065
- __privateAdd(this, _createRunContext);
1417
+ // src/triggers/scheduled.ts
1418
+ var import_core6 = require("@trigger.dev/core");
1419
+ var import_cronstrue = __toESM(require("cronstrue"));
1420
+ var examples = [
1421
+ {
1422
+ id: "now",
1423
+ name: "Now",
1424
+ icon: "clock",
1425
+ payload: {
1426
+ ts: import_core6.currentDate.marker,
1427
+ lastTimestamp: import_core6.currentDate.marker
1428
+ }
1429
+ }
1430
+ ];
1431
+ var IntervalTrigger = class {
1432
+ constructor(options) {
1433
+ this.options = options;
1434
+ }
1435
+ get event() {
1436
+ return {
1437
+ name: "trigger.scheduled",
1438
+ title: "Schedule",
1439
+ source: "trigger.dev",
1440
+ icon: "schedule-interval",
1441
+ examples,
1442
+ parsePayload: import_core6.ScheduledPayloadSchema.parse,
1443
+ properties: [
1444
+ {
1445
+ label: "Interval",
1446
+ text: `${this.options.seconds}s`
1447
+ }
1448
+ ]
1449
+ };
1450
+ }
1451
+ attachToJob(triggerClient, job) {
1452
+ }
1453
+ get preprocessRuns() {
1454
+ return false;
1455
+ }
1456
+ toJSON() {
1457
+ return {
1458
+ type: "scheduled",
1459
+ schedule: {
1460
+ type: "interval",
1461
+ options: {
1462
+ seconds: this.options.seconds
1463
+ }
1464
+ }
1465
+ };
1466
+ }
1467
+ };
1468
+ __name(IntervalTrigger, "IntervalTrigger");
1469
+ function intervalTrigger(options) {
1470
+ return new IntervalTrigger(options);
1471
+ }
1472
+ __name(intervalTrigger, "intervalTrigger");
1473
+ var CronTrigger = class {
1474
+ constructor(options) {
1475
+ this.options = options;
1476
+ }
1477
+ get event() {
1478
+ const humanReadable = import_cronstrue.default.toString(this.options.cron, {
1479
+ throwExceptionOnParseError: false
1480
+ });
1481
+ return {
1482
+ name: "trigger.scheduled",
1483
+ title: "Cron Schedule",
1484
+ source: "trigger.dev",
1485
+ icon: "schedule-cron",
1486
+ examples,
1487
+ parsePayload: import_core6.ScheduledPayloadSchema.parse,
1488
+ properties: [
1489
+ {
1490
+ label: "cron",
1491
+ text: this.options.cron
1492
+ },
1493
+ {
1494
+ label: "Schedule",
1495
+ text: humanReadable
1496
+ }
1497
+ ]
1498
+ };
1499
+ }
1500
+ attachToJob(triggerClient, job) {
1501
+ }
1502
+ get preprocessRuns() {
1503
+ return false;
1504
+ }
1505
+ toJSON() {
1506
+ return {
1507
+ type: "scheduled",
1508
+ schedule: {
1509
+ type: "cron",
1510
+ options: {
1511
+ cron: this.options.cron
1512
+ }
1513
+ }
1514
+ };
1515
+ }
1516
+ };
1517
+ __name(CronTrigger, "CronTrigger");
1518
+ function cronTrigger(options) {
1519
+ return new CronTrigger(options);
1520
+ }
1521
+ __name(cronTrigger, "cronTrigger");
1522
+ var DynamicSchedule = class {
1523
+ constructor(client, options) {
1524
+ this.client = client;
1525
+ this.options = options;
1526
+ client.attachDynamicSchedule(this.options.id);
1527
+ }
1528
+ get id() {
1529
+ return this.options.id;
1530
+ }
1531
+ get event() {
1532
+ return {
1533
+ name: "trigger.scheduled",
1534
+ title: "Dynamic Schedule",
1535
+ source: "trigger.dev",
1536
+ icon: "schedule-dynamic",
1537
+ examples,
1538
+ parsePayload: import_core6.ScheduledPayloadSchema.parse
1539
+ };
1540
+ }
1541
+ async register(key, metadata) {
1542
+ const runStore = runLocalStorage.getStore();
1543
+ if (!runStore) {
1544
+ return this.client.registerSchedule(this.id, key, metadata);
1545
+ }
1546
+ const { io } = runStore;
1547
+ return await io.runTask([
1548
+ key,
1549
+ "register"
1550
+ ], async (task) => {
1551
+ return this.client.registerSchedule(this.id, key, metadata);
1552
+ }, {
1553
+ name: "Register Schedule",
1554
+ icon: metadata.type === "cron" ? "schedule-cron" : "schedule-interval",
1555
+ properties: [
1556
+ {
1557
+ label: "Dynamic Schedule",
1558
+ text: this.id
1559
+ },
1560
+ {
1561
+ label: "Schedule ID",
1562
+ text: key
1563
+ }
1564
+ ],
1565
+ params: metadata
1566
+ });
1567
+ }
1568
+ async unregister(key) {
1569
+ const runStore = runLocalStorage.getStore();
1570
+ if (!runStore) {
1571
+ return this.client.unregisterSchedule(this.id, key);
1572
+ }
1573
+ const { io } = runStore;
1574
+ return await io.runTask([
1575
+ key,
1576
+ "unregister"
1577
+ ], async (task) => {
1578
+ return this.client.unregisterSchedule(this.id, key);
1579
+ }, {
1580
+ name: "Unregister Schedule",
1581
+ icon: "schedule",
1582
+ properties: [
1583
+ {
1584
+ label: "Dynamic Schedule",
1585
+ text: this.id
1586
+ },
1587
+ {
1588
+ label: "Schedule ID",
1589
+ text: key
1590
+ }
1591
+ ]
1592
+ });
1593
+ }
1594
+ attachToJob(triggerClient, job) {
1595
+ triggerClient.attachDynamicScheduleToJob(this.options.id, job);
1596
+ }
1597
+ get preprocessRuns() {
1598
+ return false;
1599
+ }
1600
+ toJSON() {
1601
+ return {
1602
+ type: "dynamic",
1603
+ id: this.options.id
1604
+ };
1605
+ }
1606
+ };
1607
+ __name(DynamicSchedule, "DynamicSchedule");
1608
+
1609
+ // src/triggerClient.ts
1610
+ var registerSourceEvent = {
1611
+ name: import_core7.REGISTER_SOURCE_EVENT_V2,
1612
+ title: "Register Source",
1613
+ source: "internal",
1614
+ icon: "register-source",
1615
+ parsePayload: import_core7.RegisterSourceEventSchemaV2.parse
1616
+ };
1617
+ var _options4, _registeredJobs, _registeredSources, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _authResolvers, _client2, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn, _resolveConnections, resolveConnections_fn, _resolveConnection, resolveConnection_fn, _buildJobsIndex, buildJobsIndex_fn, _buildJobIndex, buildJobIndex_fn, _buildJobIntegrations, buildJobIntegrations_fn, _buildJobIntegration, buildJobIntegration_fn, _logIOStats, logIOStats_fn, _standardResponseHeaders, standardResponseHeaders_get;
1618
+ var TriggerClient = class {
1619
+ constructor(options) {
1620
+ __privateAdd(this, _preprocessRun);
1621
+ __privateAdd(this, _executeJob);
1622
+ __privateAdd(this, _createRunContext);
1066
1623
  __privateAdd(this, _createPreprocessRunContext);
1067
1624
  __privateAdd(this, _handleHttpSourceRequest);
1068
- __privateAdd(this, _options3, void 0);
1625
+ __privateAdd(this, _resolveConnections);
1626
+ __privateAdd(this, _resolveConnection);
1627
+ __privateAdd(this, _buildJobsIndex);
1628
+ __privateAdd(this, _buildJobIndex);
1629
+ __privateAdd(this, _buildJobIntegrations);
1630
+ __privateAdd(this, _buildJobIntegration);
1631
+ __privateAdd(this, _logIOStats);
1632
+ __privateAdd(this, _standardResponseHeaders);
1633
+ __privateAdd(this, _options4, void 0);
1069
1634
  __privateAdd(this, _registeredJobs, {});
1070
1635
  __privateAdd(this, _registeredSources, {});
1071
1636
  __privateAdd(this, _registeredHttpSourceHandlers, {});
1072
1637
  __privateAdd(this, _registeredDynamicTriggers, {});
1073
1638
  __privateAdd(this, _jobMetadataByDynamicTriggers, {});
1074
1639
  __privateAdd(this, _registeredSchedules, {});
1075
- __privateAdd(this, _client, void 0);
1640
+ __privateAdd(this, _authResolvers, {});
1641
+ __privateAdd(this, _client2, void 0);
1076
1642
  __privateAdd(this, _internalLogger, void 0);
1077
1643
  this.id = options.id;
1078
- __privateSet(this, _options3, options);
1079
- __privateSet(this, _client, new ApiClient(__privateGet(this, _options3)));
1080
- __privateSet(this, _internalLogger, new import_core5.Logger("trigger.dev", __privateGet(this, _options3).verbose ? "debug" : "log"));
1644
+ __privateSet(this, _options4, options);
1645
+ __privateSet(this, _client2, new ApiClient(__privateGet(this, _options4)));
1646
+ __privateSet(this, _internalLogger, new import_core7.Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log", [
1647
+ "output",
1648
+ "noopTasksSet"
1649
+ ]));
1081
1650
  }
1082
1651
  async handleRequest(request) {
1083
1652
  __privateGet(this, _internalLogger).debug("handling request", {
@@ -1086,6 +1655,7 @@ var TriggerClient = class {
1086
1655
  method: request.method
1087
1656
  });
1088
1657
  const apiKey = request.headers.get("x-trigger-api-key");
1658
+ const triggerVersion = request.headers.get("x-trigger-version");
1089
1659
  const authorization = this.authorized(apiKey);
1090
1660
  switch (authorization) {
1091
1661
  case "authorized": {
@@ -1096,7 +1666,8 @@ var TriggerClient = class {
1096
1666
  status: 401,
1097
1667
  body: {
1098
1668
  message: "Unauthorized: client missing apiKey"
1099
- }
1669
+ },
1670
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1100
1671
  };
1101
1672
  }
1102
1673
  case "missing-header": {
@@ -1104,7 +1675,8 @@ var TriggerClient = class {
1104
1675
  status: 401,
1105
1676
  body: {
1106
1677
  message: "Unauthorized: missing x-trigger-api-key header"
1107
- }
1678
+ },
1679
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1108
1680
  };
1109
1681
  }
1110
1682
  case "unauthorized": {
@@ -1112,7 +1684,8 @@ var TriggerClient = class {
1112
1684
  status: 401,
1113
1685
  body: {
1114
1686
  message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`
1115
- }
1687
+ },
1688
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1116
1689
  };
1117
1690
  }
1118
1691
  }
@@ -1121,7 +1694,8 @@ var TriggerClient = class {
1121
1694
  status: 405,
1122
1695
  body: {
1123
1696
  message: "Method not allowed (only POST is allowed)"
1124
- }
1697
+ },
1698
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1125
1699
  };
1126
1700
  }
1127
1701
  const action = request.headers.get("x-trigger-action");
@@ -1130,7 +1704,8 @@ var TriggerClient = class {
1130
1704
  status: 400,
1131
1705
  body: {
1132
1706
  message: "Missing x-trigger-action header"
1133
- }
1707
+ },
1708
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1134
1709
  };
1135
1710
  }
1136
1711
  switch (action) {
@@ -1142,7 +1717,8 @@ var TriggerClient = class {
1142
1717
  body: {
1143
1718
  ok: false,
1144
1719
  error: "Missing endpoint ID"
1145
- }
1720
+ },
1721
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1146
1722
  };
1147
1723
  }
1148
1724
  if (this.id !== endpointId) {
@@ -1151,35 +1727,21 @@ var TriggerClient = class {
1151
1727
  body: {
1152
1728
  ok: false,
1153
1729
  error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`
1154
- }
1730
+ },
1731
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1155
1732
  };
1156
1733
  }
1157
1734
  return {
1158
1735
  status: 200,
1159
1736
  body: {
1160
1737
  ok: true
1161
- }
1738
+ },
1739
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1162
1740
  };
1163
1741
  }
1164
1742
  case "INDEX_ENDPOINT": {
1165
- const jobId = request.headers.get("x-trigger-job-id");
1166
- if (jobId) {
1167
- const job = __privateGet(this, _registeredJobs)[jobId];
1168
- if (!job) {
1169
- return {
1170
- status: 404,
1171
- body: {
1172
- message: "Job not found"
1173
- }
1174
- };
1175
- }
1176
- return {
1177
- status: 200,
1178
- body: job.toJSON()
1179
- };
1180
- }
1181
1743
  const body = {
1182
- jobs: Object.values(__privateGet(this, _registeredJobs)).map((job) => job.toJSON()),
1744
+ jobs: __privateMethod(this, _buildJobsIndex, buildJobsIndex_fn).call(this),
1183
1745
  sources: Object.values(__privateGet(this, _registeredSources)),
1184
1746
  dynamicTriggers: Object.values(__privateGet(this, _registeredDynamicTriggers)).map((trigger) => ({
1185
1747
  id: trigger.id,
@@ -1196,12 +1758,13 @@ var TriggerClient = class {
1196
1758
  };
1197
1759
  return {
1198
1760
  status: 200,
1199
- body
1761
+ body,
1762
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1200
1763
  };
1201
1764
  }
1202
1765
  case "INITIALIZE_TRIGGER": {
1203
1766
  const json = await request.json();
1204
- const body = import_core5.InitializeTriggerBodySchema.safeParse(json);
1767
+ const body = import_core7.InitializeTriggerBodySchema.safeParse(json);
1205
1768
  if (!body.success) {
1206
1769
  return {
1207
1770
  status: 400,
@@ -1221,12 +1784,13 @@ var TriggerClient = class {
1221
1784
  }
1222
1785
  return {
1223
1786
  status: 200,
1224
- body: dynamicTrigger.registeredTriggerForParams(body.data.params)
1787
+ body: dynamicTrigger.registeredTriggerForParams(body.data.params),
1788
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1225
1789
  };
1226
1790
  }
1227
1791
  case "EXECUTE_JOB": {
1228
1792
  const json = await request.json();
1229
- const execution = import_core5.RunJobBodySchema.safeParse(json);
1793
+ const execution = import_core7.RunJobBodySchema.safeParse(json);
1230
1794
  if (!execution.success) {
1231
1795
  return {
1232
1796
  status: 400,
@@ -1244,15 +1808,16 @@ var TriggerClient = class {
1244
1808
  }
1245
1809
  };
1246
1810
  }
1247
- const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job);
1811
+ const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job, triggerVersion);
1248
1812
  return {
1249
1813
  status: 200,
1250
- body: results
1814
+ body: results,
1815
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1251
1816
  };
1252
1817
  }
1253
1818
  case "PREPROCESS_RUN": {
1254
1819
  const json = await request.json();
1255
- const body = import_core5.PreprocessRunBodySchema.safeParse(json);
1820
+ const body = import_core7.PreprocessRunBodySchema.safeParse(json);
1256
1821
  if (!body.success) {
1257
1822
  return {
1258
1823
  status: 400,
@@ -1276,11 +1841,12 @@ var TriggerClient = class {
1276
1841
  body: {
1277
1842
  abort: results.abort,
1278
1843
  properties: results.properties
1279
- }
1844
+ },
1845
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1280
1846
  };
1281
1847
  }
1282
1848
  case "DELIVER_HTTP_SOURCE_REQUEST": {
1283
- const headers = import_core5.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1849
+ const headers = import_core7.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1284
1850
  if (!headers.success) {
1285
1851
  return {
1286
1852
  status: 400,
@@ -1325,7 +1891,8 @@ var TriggerClient = class {
1325
1891
  events,
1326
1892
  response,
1327
1893
  metadata
1328
- }
1894
+ },
1895
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1329
1896
  };
1330
1897
  }
1331
1898
  case "VALIDATE": {
@@ -1334,7 +1901,8 @@ var TriggerClient = class {
1334
1901
  body: {
1335
1902
  ok: true,
1336
1903
  endpointId: this.id
1337
- }
1904
+ },
1905
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1338
1906
  };
1339
1907
  }
1340
1908
  }
@@ -1342,16 +1910,30 @@ var TriggerClient = class {
1342
1910
  status: 405,
1343
1911
  body: {
1344
1912
  message: "Method not allowed"
1345
- }
1913
+ },
1914
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1346
1915
  };
1347
1916
  }
1917
+ defineJob(options) {
1918
+ return new Job(this, options);
1919
+ }
1920
+ defineAuthResolver(integration, resolver) {
1921
+ __privateGet(this, _authResolvers)[integration.id] = resolver;
1922
+ return this;
1923
+ }
1924
+ defineDynamicSchedule(options) {
1925
+ return new DynamicSchedule(this, options);
1926
+ }
1927
+ defineDynamicTrigger(options) {
1928
+ return new DynamicTrigger(this, options);
1929
+ }
1348
1930
  attach(job) {
1349
1931
  __privateGet(this, _registeredJobs)[job.id] = job;
1350
1932
  job.trigger.attachToJob(this, job);
1351
1933
  }
1352
1934
  attachDynamicTrigger(trigger) {
1353
1935
  __privateGet(this, _registeredDynamicTriggers)[trigger.id] = trigger;
1354
- new Job(this, {
1936
+ this.defineJob({
1355
1937
  id: dynamicTriggerRegisterSourceJobId(trigger.id),
1356
1938
  name: `Register dynamic trigger ${trigger.id}`,
1357
1939
  version: trigger.source.version,
@@ -1447,7 +2029,11 @@ var TriggerClient = class {
1447
2029
  __internal: true
1448
2030
  });
1449
2031
  }
1450
- attachDynamicSchedule(key, job) {
2032
+ attachDynamicSchedule(key) {
2033
+ const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
2034
+ __privateGet(this, _registeredSchedules)[key] = jobs;
2035
+ }
2036
+ attachDynamicScheduleToJob(key, job) {
1451
2037
  const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
1452
2038
  jobs.push({
1453
2039
  id: job.id,
@@ -1456,58 +2042,65 @@ var TriggerClient = class {
1456
2042
  __privateGet(this, _registeredSchedules)[key] = jobs;
1457
2043
  }
1458
2044
  async registerTrigger(id, key, options) {
1459
- return __privateGet(this, _client).registerTrigger(this.id, id, key, options);
2045
+ return __privateGet(this, _client2).registerTrigger(this.id, id, key, options);
1460
2046
  }
1461
2047
  async getAuth(id) {
1462
- return __privateGet(this, _client).getAuth(this.id, id);
2048
+ return __privateGet(this, _client2).getAuth(this.id, id);
1463
2049
  }
1464
2050
  async sendEvent(event, options) {
1465
- return __privateGet(this, _client).sendEvent(event, options);
2051
+ return __privateGet(this, _client2).sendEvent(event, options);
1466
2052
  }
1467
2053
  async cancelEvent(eventId) {
1468
- return __privateGet(this, _client).cancelEvent(eventId);
2054
+ return __privateGet(this, _client2).cancelEvent(eventId);
2055
+ }
2056
+ async updateStatus(runId, id, status) {
2057
+ return __privateGet(this, _client2).updateStatus(runId, id, status);
1469
2058
  }
1470
2059
  async registerSchedule(id, key, schedule) {
1471
- return __privateGet(this, _client).registerSchedule(this.id, id, key, schedule);
2060
+ return __privateGet(this, _client2).registerSchedule(this.id, id, key, schedule);
1472
2061
  }
1473
2062
  async unregisterSchedule(id, key) {
1474
- return __privateGet(this, _client).unregisterSchedule(this.id, id, key);
2063
+ return __privateGet(this, _client2).unregisterSchedule(this.id, id, key);
1475
2064
  }
1476
2065
  async getEvent(eventId) {
1477
- return __privateGet(this, _client).getEvent(eventId);
2066
+ return __privateGet(this, _client2).getEvent(eventId);
1478
2067
  }
1479
2068
  async getRun(runId, options) {
1480
- return __privateGet(this, _client).getRun(runId, options);
2069
+ return __privateGet(this, _client2).getRun(runId, options);
2070
+ }
2071
+ async cancelRun(runId) {
2072
+ return __privateGet(this, _client2).cancelRun(runId);
1481
2073
  }
1482
2074
  async getRuns(jobSlug, options) {
1483
- return __privateGet(this, _client).getRuns(jobSlug, options);
2075
+ return __privateGet(this, _client2).getRuns(jobSlug, options);
2076
+ }
2077
+ async getRunStatuses(runId) {
2078
+ return __privateGet(this, _client2).getRunStatuses(runId);
1484
2079
  }
1485
2080
  authorized(apiKey) {
1486
2081
  if (typeof apiKey !== "string") {
1487
2082
  return "missing-header";
1488
2083
  }
1489
- const localApiKey = __privateGet(this, _options3).apiKey ?? process.env.TRIGGER_API_KEY;
2084
+ const localApiKey = __privateGet(this, _options4).apiKey ?? process.env.TRIGGER_API_KEY;
1490
2085
  if (!localApiKey) {
1491
2086
  return "missing-client";
1492
2087
  }
1493
2088
  return apiKey === localApiKey ? "authorized" : "unauthorized";
1494
2089
  }
1495
2090
  apiKey() {
1496
- return __privateGet(this, _options3).apiKey ?? process.env.TRIGGER_API_KEY;
1497
- }
1498
- defineJob(options) {
1499
- return new Job(this, options);
2091
+ return __privateGet(this, _options4).apiKey ?? process.env.TRIGGER_API_KEY;
1500
2092
  }
1501
2093
  };
1502
2094
  __name(TriggerClient, "TriggerClient");
1503
- _options3 = new WeakMap();
2095
+ _options4 = new WeakMap();
1504
2096
  _registeredJobs = new WeakMap();
1505
2097
  _registeredSources = new WeakMap();
1506
2098
  _registeredHttpSourceHandlers = new WeakMap();
1507
2099
  _registeredDynamicTriggers = new WeakMap();
1508
2100
  _jobMetadataByDynamicTriggers = new WeakMap();
1509
2101
  _registeredSchedules = new WeakMap();
1510
- _client = new WeakMap();
2102
+ _authResolvers = new WeakMap();
2103
+ _client2 = new WeakMap();
1511
2104
  _internalLogger = new WeakMap();
1512
2105
  _preprocessRun = new WeakSet();
1513
2106
  preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
@@ -1520,30 +2113,66 @@ preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
1520
2113
  };
1521
2114
  }, "#preprocessRun");
1522
2115
  _executeJob = new WeakSet();
1523
- executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
2116
+ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, triggerVersion) {
1524
2117
  __privateGet(this, _internalLogger).debug("executing job", {
1525
2118
  execution: body1,
1526
- job: job1.toJSON()
2119
+ job: job1.id,
2120
+ version: job1.version,
2121
+ triggerVersion
1527
2122
  });
1528
2123
  const context = __privateMethod(this, _createRunContext, createRunContext_fn).call(this, body1);
1529
2124
  const io = new IO({
1530
2125
  id: body1.run.id,
1531
2126
  cachedTasks: body1.tasks,
1532
- apiClient: __privateGet(this, _client),
2127
+ cachedTasksCursor: body1.cachedTaskCursor,
2128
+ yieldedExecutions: body1.yieldedExecutions ?? [],
2129
+ noopTasksSet: body1.noopTasksSet,
2130
+ apiClient: __privateGet(this, _client2),
1533
2131
  logger: __privateGet(this, _internalLogger),
1534
2132
  client: this,
1535
2133
  context,
1536
- jobLogLevel: job1.logLevel ?? __privateGet(this, _options3).logLevel ?? "info",
1537
- jobLogger: __privateGet(this, _options3).ioLogLocalEnabled ? new import_core5.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options3).logLevel ?? "info") : void 0
2134
+ jobLogLevel: job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info",
2135
+ jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new import_core7.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0,
2136
+ serverVersion: triggerVersion
1538
2137
  });
1539
- const ioWithConnections = createIOWithIntegrations(io, body1.connections, job1.options.integrations);
2138
+ const resolvedConnections = await __privateMethod(this, _resolveConnections, resolveConnections_fn).call(this, context, job1.options.integrations, body1.connections);
2139
+ if (!resolvedConnections.ok) {
2140
+ return {
2141
+ status: "UNRESOLVED_AUTH_ERROR",
2142
+ issues: resolvedConnections.issues
2143
+ };
2144
+ }
2145
+ const ioWithConnections = createIOWithIntegrations(io, resolvedConnections.data, job1.options.integrations);
1540
2146
  try {
1541
- const output = await job1.options.run(job1.trigger.event.parsePayload(body1.event.payload ?? {}), ioWithConnections, context);
2147
+ const output = await runLocalStorage.runWith({
2148
+ io,
2149
+ ctx: context
2150
+ }, () => {
2151
+ return job1.options.run(job1.trigger.event.parsePayload(body1.event.payload ?? {}), ioWithConnections, context);
2152
+ });
2153
+ if (__privateGet(this, _options4).verbose) {
2154
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2155
+ }
1542
2156
  return {
1543
2157
  status: "SUCCESS",
1544
2158
  output
1545
2159
  };
1546
2160
  } catch (error) {
2161
+ if (__privateGet(this, _options4).verbose) {
2162
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2163
+ }
2164
+ if (error instanceof YieldExecutionError) {
2165
+ return {
2166
+ status: "YIELD_EXECUTION",
2167
+ key: error.key
2168
+ };
2169
+ }
2170
+ if (error instanceof ParsedPayloadSchemaError) {
2171
+ return {
2172
+ status: "INVALID_PAYLOAD",
2173
+ errors: error.schemaErrors
2174
+ };
2175
+ }
1547
2176
  if (error instanceof ResumeWithTaskError) {
1548
2177
  return {
1549
2178
  status: "RESUME_WITH_TASK",
@@ -1565,7 +2194,7 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
1565
2194
  };
1566
2195
  }
1567
2196
  if (error instanceof RetryWithTaskError) {
1568
- const errorWithStack2 = import_core5.ErrorWithStackSchema.safeParse(error.cause);
2197
+ const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause);
1569
2198
  if (errorWithStack2.success) {
1570
2199
  return {
1571
2200
  status: "ERROR",
@@ -1581,7 +2210,7 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
1581
2210
  task: error.task
1582
2211
  };
1583
2212
  }
1584
- const errorWithStack = import_core5.ErrorWithStackSchema.safeParse(error);
2213
+ const errorWithStack = import_core7.ErrorWithStackSchema.safeParse(error);
1585
2214
  if (errorWithStack.success) {
1586
2215
  return {
1587
2216
  status: "ERROR",
@@ -1713,6 +2342,166 @@ handleHttpSourceRequest_fn = /* @__PURE__ */ __name(async function(source, sourc
1713
2342
  metadata: results.metadata
1714
2343
  };
1715
2344
  }, "#handleHttpSourceRequest");
2345
+ _resolveConnections = new WeakSet();
2346
+ resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx, integrations, connections) {
2347
+ if (!integrations) {
2348
+ return {
2349
+ ok: true,
2350
+ data: {}
2351
+ };
2352
+ }
2353
+ const resolvedAuthResults = await Promise.all(Object.keys(integrations).map(async (key) => {
2354
+ const integration = integrations[key];
2355
+ const auth = (connections ?? {})[key];
2356
+ const result = await __privateMethod(this, _resolveConnection, resolveConnection_fn).call(this, ctx, integration, auth);
2357
+ if (result.ok) {
2358
+ return {
2359
+ ok: true,
2360
+ auth: result.auth,
2361
+ key
2362
+ };
2363
+ } else {
2364
+ return {
2365
+ ok: false,
2366
+ error: result.error,
2367
+ key
2368
+ };
2369
+ }
2370
+ }));
2371
+ const allResolved = resolvedAuthResults.every((result) => result.ok);
2372
+ if (allResolved) {
2373
+ return {
2374
+ ok: true,
2375
+ data: resolvedAuthResults.reduce((acc, result) => {
2376
+ acc[result.key] = result.auth;
2377
+ return acc;
2378
+ }, {})
2379
+ };
2380
+ } else {
2381
+ return {
2382
+ ok: false,
2383
+ issues: resolvedAuthResults.reduce((acc, result) => {
2384
+ if (result.ok) {
2385
+ return acc;
2386
+ }
2387
+ const integration = integrations[result.key];
2388
+ acc[result.key] = {
2389
+ id: integration.id,
2390
+ error: result.error
2391
+ };
2392
+ return acc;
2393
+ }, {})
2394
+ };
2395
+ }
2396
+ }, "#resolveConnections");
2397
+ _resolveConnection = new WeakSet();
2398
+ resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx1, integration, auth) {
2399
+ if (auth) {
2400
+ return {
2401
+ ok: true,
2402
+ auth
2403
+ };
2404
+ }
2405
+ const authResolver = __privateGet(this, _authResolvers)[integration.id];
2406
+ if (!authResolver) {
2407
+ if (integration.authSource === "HOSTED") {
2408
+ return {
2409
+ ok: false,
2410
+ error: `Something went wrong: Integration ${integration.id} is missing auth credentials from Trigger.dev`
2411
+ };
2412
+ }
2413
+ return {
2414
+ ok: true,
2415
+ auth: void 0
2416
+ };
2417
+ }
2418
+ try {
2419
+ const resolvedAuth = await authResolver(ctx1, integration);
2420
+ if (!resolvedAuth) {
2421
+ return {
2422
+ ok: false,
2423
+ error: `Auth could not be resolved for ${integration.id}: auth resolver returned null or undefined`
2424
+ };
2425
+ }
2426
+ return {
2427
+ ok: true,
2428
+ auth: resolvedAuth.type === "apiKey" ? {
2429
+ type: "apiKey",
2430
+ accessToken: resolvedAuth.token,
2431
+ additionalFields: resolvedAuth.additionalFields
2432
+ } : {
2433
+ type: "oauth2",
2434
+ accessToken: resolvedAuth.token,
2435
+ additionalFields: resolvedAuth.additionalFields
2436
+ }
2437
+ };
2438
+ } catch (resolverError) {
2439
+ if (resolverError instanceof Error) {
2440
+ return {
2441
+ ok: false,
2442
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw. ${resolverError.name}: ${resolverError.message}`
2443
+ };
2444
+ } else if (typeof resolverError === "string") {
2445
+ return {
2446
+ ok: false,
2447
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw an error: ${resolverError}`
2448
+ };
2449
+ }
2450
+ return {
2451
+ ok: false,
2452
+ error: `Auth could not be resolved for ${integration.id}: auth resolver threw an unknown error: ${JSON.stringify(resolverError)}`
2453
+ };
2454
+ }
2455
+ }, "#resolveConnection");
2456
+ _buildJobsIndex = new WeakSet();
2457
+ buildJobsIndex_fn = /* @__PURE__ */ __name(function() {
2458
+ return Object.values(__privateGet(this, _registeredJobs)).map((job) => __privateMethod(this, _buildJobIndex, buildJobIndex_fn).call(this, job));
2459
+ }, "#buildJobsIndex");
2460
+ _buildJobIndex = new WeakSet();
2461
+ buildJobIndex_fn = /* @__PURE__ */ __name(function(job2) {
2462
+ const internal = job2.options.__internal;
2463
+ return {
2464
+ id: job2.id,
2465
+ name: job2.name,
2466
+ version: job2.version,
2467
+ event: job2.trigger.event,
2468
+ trigger: job2.trigger.toJSON(),
2469
+ integrations: __privateMethod(this, _buildJobIntegrations, buildJobIntegrations_fn).call(this, job2),
2470
+ startPosition: "latest",
2471
+ enabled: job2.enabled,
2472
+ preprocessRuns: job2.trigger.preprocessRuns,
2473
+ internal
2474
+ };
2475
+ }, "#buildJobIndex");
2476
+ _buildJobIntegrations = new WeakSet();
2477
+ buildJobIntegrations_fn = /* @__PURE__ */ __name(function(job3) {
2478
+ return Object.keys(job3.options.integrations ?? {}).reduce((acc, key) => {
2479
+ const integration = job3.options.integrations[key];
2480
+ acc[key] = __privateMethod(this, _buildJobIntegration, buildJobIntegration_fn).call(this, integration);
2481
+ return acc;
2482
+ }, {});
2483
+ }, "#buildJobIntegrations");
2484
+ _buildJobIntegration = new WeakSet();
2485
+ buildJobIntegration_fn = /* @__PURE__ */ __name(function(integration1) {
2486
+ const authSource = __privateGet(this, _authResolvers)[integration1.id] ? "RESOLVER" : integration1.authSource;
2487
+ return {
2488
+ id: integration1.id,
2489
+ metadata: integration1.metadata,
2490
+ authSource
2491
+ };
2492
+ }, "#buildJobIntegration");
2493
+ _logIOStats = new WeakSet();
2494
+ logIOStats_fn = /* @__PURE__ */ __name(function(stats) {
2495
+ __privateGet(this, _internalLogger).debug("IO stats", {
2496
+ stats
2497
+ });
2498
+ }, "#logIOStats");
2499
+ _standardResponseHeaders = new WeakSet();
2500
+ standardResponseHeaders_get = /* @__PURE__ */ __name(function() {
2501
+ return {
2502
+ "Trigger-Version": import_core7.API_VERSIONS.LAZY_LOADED_CACHED_TASKS
2503
+ };
2504
+ }, "#standardResponseHeaders");
1716
2505
  function dynamicTriggerRegisterSourceJobId(id) {
1717
2506
  return `register-dynamic-trigger-${id}`;
1718
2507
  }
@@ -1738,7 +2527,7 @@ function deepMergeOptions(obj1, obj2) {
1738
2527
  __name(deepMergeOptions, "deepMergeOptions");
1739
2528
 
1740
2529
  // src/triggers/externalSource.ts
1741
- var import_core6 = require("@trigger.dev/core");
2530
+ var import_core8 = require("@trigger.dev/core");
1742
2531
  var ExternalSource = class {
1743
2532
  constructor(channel, options) {
1744
2533
  this.options = options;
@@ -1812,7 +2601,7 @@ var ExternalSourceTrigger = class {
1812
2601
  title: "External Source",
1813
2602
  rule: {
1814
2603
  event: this.event.name,
1815
- payload: (0, import_core6.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
2604
+ payload: (0, import_core8.deepMergeFilters)(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
1816
2605
  source: this.event.source
1817
2606
  },
1818
2607
  properties: this.options.source.properties(this.options.params)
@@ -1846,214 +2635,6 @@ function omit(obj, key) {
1846
2635
  }
1847
2636
  __name(omit, "omit");
1848
2637
 
1849
- // src/triggers/dynamic.ts
1850
- var import_core7 = require("@trigger.dev/core");
1851
- var _client2, _options4;
1852
- var DynamicTrigger = class {
1853
- constructor(client, options) {
1854
- __privateAdd(this, _client2, void 0);
1855
- __privateAdd(this, _options4, void 0);
1856
- __privateSet(this, _client2, client);
1857
- __privateSet(this, _options4, options);
1858
- this.source = options.source;
1859
- client.attachDynamicTrigger(this);
1860
- }
1861
- toJSON() {
1862
- return {
1863
- type: "dynamic",
1864
- id: __privateGet(this, _options4).id
1865
- };
1866
- }
1867
- get id() {
1868
- return __privateGet(this, _options4).id;
1869
- }
1870
- get event() {
1871
- return __privateGet(this, _options4).event;
1872
- }
1873
- registeredTriggerForParams(params) {
1874
- const key = slugifyId(this.source.key(params));
1875
- return {
1876
- rule: {
1877
- event: this.event.name,
1878
- source: this.event.source,
1879
- payload: (0, import_core7.deepMergeFilters)(this.source.filter(params), this.event.filter ?? {})
1880
- },
1881
- source: {
1882
- version: "2",
1883
- key,
1884
- channel: this.source.channel,
1885
- params,
1886
- options: {
1887
- event: typeof this.event.name === "string" ? [
1888
- this.event.name
1889
- ] : this.event.name
1890
- },
1891
- integration: {
1892
- id: this.source.integration.id,
1893
- metadata: this.source.integration.metadata,
1894
- authSource: this.source.integration.authSource
1895
- }
1896
- }
1897
- };
1898
- }
1899
- async register(key, params) {
1900
- return __privateGet(this, _client2).registerTrigger(this.id, key, this.registeredTriggerForParams(params));
1901
- }
1902
- attachToJob(triggerClient, job) {
1903
- triggerClient.attachJobToDynamicTrigger(job, this);
1904
- }
1905
- get preprocessRuns() {
1906
- return true;
1907
- }
1908
- };
1909
- __name(DynamicTrigger, "DynamicTrigger");
1910
- _client2 = new WeakMap();
1911
- _options4 = new WeakMap();
1912
-
1913
- // src/triggers/scheduled.ts
1914
- var import_core8 = require("@trigger.dev/core");
1915
- var import_cronstrue = __toESM(require("cronstrue"));
1916
- var examples = [
1917
- {
1918
- id: "now",
1919
- name: "Now",
1920
- icon: "clock",
1921
- payload: {
1922
- ts: import_core8.currentDate.marker,
1923
- lastTimestamp: import_core8.currentDate.marker
1924
- }
1925
- }
1926
- ];
1927
- var IntervalTrigger = class {
1928
- constructor(options) {
1929
- this.options = options;
1930
- }
1931
- get event() {
1932
- return {
1933
- name: "trigger.scheduled",
1934
- title: "Schedule",
1935
- source: "trigger.dev",
1936
- icon: "schedule-interval",
1937
- examples,
1938
- parsePayload: import_core8.ScheduledPayloadSchema.parse,
1939
- properties: [
1940
- {
1941
- label: "Interval",
1942
- text: `${this.options.seconds}s`
1943
- }
1944
- ]
1945
- };
1946
- }
1947
- attachToJob(triggerClient, job) {
1948
- }
1949
- get preprocessRuns() {
1950
- return false;
1951
- }
1952
- toJSON() {
1953
- return {
1954
- type: "scheduled",
1955
- schedule: {
1956
- type: "interval",
1957
- options: {
1958
- seconds: this.options.seconds
1959
- }
1960
- }
1961
- };
1962
- }
1963
- };
1964
- __name(IntervalTrigger, "IntervalTrigger");
1965
- function intervalTrigger(options) {
1966
- return new IntervalTrigger(options);
1967
- }
1968
- __name(intervalTrigger, "intervalTrigger");
1969
- var CronTrigger = class {
1970
- constructor(options) {
1971
- this.options = options;
1972
- }
1973
- get event() {
1974
- const humanReadable = import_cronstrue.default.toString(this.options.cron, {
1975
- throwExceptionOnParseError: false
1976
- });
1977
- return {
1978
- name: "trigger.scheduled",
1979
- title: "Cron Schedule",
1980
- source: "trigger.dev",
1981
- icon: "schedule-cron",
1982
- examples,
1983
- parsePayload: import_core8.ScheduledPayloadSchema.parse,
1984
- properties: [
1985
- {
1986
- label: "cron",
1987
- text: this.options.cron
1988
- },
1989
- {
1990
- label: "Schedule",
1991
- text: humanReadable
1992
- }
1993
- ]
1994
- };
1995
- }
1996
- attachToJob(triggerClient, job) {
1997
- }
1998
- get preprocessRuns() {
1999
- return false;
2000
- }
2001
- toJSON() {
2002
- return {
2003
- type: "scheduled",
2004
- schedule: {
2005
- type: "cron",
2006
- options: {
2007
- cron: this.options.cron
2008
- }
2009
- }
2010
- };
2011
- }
2012
- };
2013
- __name(CronTrigger, "CronTrigger");
2014
- function cronTrigger(options) {
2015
- return new CronTrigger(options);
2016
- }
2017
- __name(cronTrigger, "cronTrigger");
2018
- var DynamicSchedule = class {
2019
- constructor(client, options) {
2020
- this.client = client;
2021
- this.options = options;
2022
- }
2023
- get id() {
2024
- return this.options.id;
2025
- }
2026
- get event() {
2027
- return {
2028
- name: "trigger.scheduled",
2029
- title: "Dynamic Schedule",
2030
- source: "trigger.dev",
2031
- icon: "schedule-dynamic",
2032
- examples,
2033
- parsePayload: import_core8.ScheduledPayloadSchema.parse
2034
- };
2035
- }
2036
- async register(key, metadata) {
2037
- return this.client.registerSchedule(this.id, key, metadata);
2038
- }
2039
- async unregister(key) {
2040
- return this.client.unregisterSchedule(this.id, key);
2041
- }
2042
- attachToJob(triggerClient, job) {
2043
- triggerClient.attachDynamicSchedule(this.options.id, job);
2044
- }
2045
- get preprocessRuns() {
2046
- return false;
2047
- }
2048
- toJSON() {
2049
- return {
2050
- type: "dynamic",
2051
- id: this.options.id
2052
- };
2053
- }
2054
- };
2055
- __name(DynamicSchedule, "DynamicSchedule");
2056
-
2057
2638
  // src/triggers/notifications.ts
2058
2639
  var import_core9 = require("@trigger.dev/core");
2059
2640
  function missingConnectionNotification(integrations) {