@trigger.dev/sdk 0.0.0-isomorphic-sdk-20230918150523 → 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,11 +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
605
  var _addToCachedTasks, addToCachedTasks_fn;
454
606
  var IO = class {
455
607
  constructor(options) {
456
608
  __privateAdd(this, _addToCachedTasks);
609
+ __publicField(this, "brb", this.yield.bind(this));
457
610
  this._id = options.id;
458
611
  this._apiClient = options.apiClient;
459
612
  this._triggerClient = options.client;
@@ -461,49 +614,74 @@ var IO = class {
461
614
  this._cachedTasks = /* @__PURE__ */ new Map();
462
615
  this._jobLogger = options.jobLogger;
463
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
+ };
464
626
  if (options.cachedTasks) {
465
627
  options.cachedTasks.forEach((task) => {
466
628
  this._cachedTasks.set(task.idempotencyKey, task);
467
629
  });
630
+ this._stats.initialCachedTasks = options.cachedTasks.length;
468
631
  }
469
632
  this._taskStorage = new import_node_async_hooks.AsyncLocalStorage();
470
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;
471
649
  }
472
650
  get logger() {
473
651
  return new IOLogger(async (level, message, data) => {
474
652
  let logLevel = "info";
475
- switch (level) {
476
- case "LOG": {
477
- this._jobLogger?.log(message, data);
478
- logLevel = "log";
479
- break;
480
- }
481
- case "DEBUG": {
482
- this._jobLogger?.debug(message, data);
483
- logLevel = "debug";
484
- break;
485
- }
486
- case "INFO": {
487
- this._jobLogger?.info(message, data);
488
- logLevel = "info";
489
- break;
490
- }
491
- case "WARN": {
492
- this._jobLogger?.warn(message, data);
493
- logLevel = "warn";
494
- break;
495
- }
496
- case "ERROR": {
497
- this._jobLogger?.error(message, data);
498
- logLevel = "error";
499
- break;
500
- }
501
- }
502
653
  if (import_core3.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
503
654
  await this.runTask([
504
655
  message,
505
656
  level
506
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
+ }
507
685
  }, {
508
686
  name: "log",
509
687
  icon: "log",
@@ -539,6 +717,12 @@ var IO = class {
539
717
  }
540
718
  });
541
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
+ }
542
726
  async backgroundFetch(key, url, requestInit, retry2) {
543
727
  const urlObject = new URL(url);
544
728
  return await this.runTask(key, async (task) => {
@@ -782,18 +966,42 @@ var IO = class {
782
966
  const cachedTask = this._cachedTasks.get(idempotencyKey);
783
967
  if (cachedTask && cachedTask.status === "COMPLETED") {
784
968
  this._logger.debug("Using completed cached task", {
785
- idempotencyKey,
786
- cachedTask
969
+ idempotencyKey
787
970
  });
971
+ this._stats.cachedTaskHits++;
788
972
  return cachedTask.output;
789
973
  }
790
- 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, {
791
984
  idempotencyKey,
792
985
  displayKey: typeof key === "string" ? key : void 0,
793
986
  noop: false,
794
987
  ...options ?? {},
795
988
  parentId
989
+ }, {
990
+ cachedTasksCursor: this._cachedTasksCursor
796
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
+ }
797
1005
  if (task.status === "CANCELED") {
798
1006
  this._logger.debug("Task canceled", {
799
1007
  idempotencyKey,
@@ -802,11 +1010,18 @@ var IO = class {
802
1010
  throw new CanceledWithTaskError(task);
803
1011
  }
804
1012
  if (task.status === "COMPLETED") {
805
- this._logger.debug("Using task output", {
806
- idempotencyKey,
807
- task
808
- });
809
- __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
+ }
810
1025
  return task.output;
811
1026
  }
812
1027
  if (task.status === "ERRORED") {
@@ -816,23 +1031,16 @@ var IO = class {
816
1031
  });
817
1032
  throw new Error(task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
818
1033
  }
819
- if (task.status === "WAITING") {
820
- this._logger.debug("Task waiting", {
821
- idempotencyKey,
822
- task
823
- });
824
- throw new ResumeWithTaskError(task);
825
- }
826
- if (task.status === "RUNNING" && typeof task.operation === "string") {
827
- this._logger.debug("Task running operation", {
828
- idempotencyKey,
829
- task
830
- });
831
- throw new ResumeWithTaskError(task);
832
- }
833
1034
  const executeTask = /* @__PURE__ */ __name(async () => {
834
1035
  try {
835
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
+ }
836
1044
  const output = import_core3.SerializableJsonSchema.parse(result);
837
1045
  this._logger.debug("Completing using output", {
838
1046
  idempotencyKey,
@@ -842,6 +1050,7 @@ var IO = class {
842
1050
  output: output ?? void 0,
843
1051
  properties: task.outputProperties ?? void 0
844
1052
  });
1053
+ this._stats.executedTasks++;
845
1054
  if (completedTask.status === "CANCELED") {
846
1055
  throw new CanceledWithTaskError(completedTask);
847
1056
  }
@@ -850,6 +1059,7 @@ var IO = class {
850
1059
  if (isTriggerError(error)) {
851
1060
  throw error;
852
1061
  }
1062
+ let skipRetrying = false;
853
1063
  if (onError) {
854
1064
  try {
855
1065
  const onErrorResult = onError(error, task, this);
@@ -857,10 +1067,13 @@ var IO = class {
857
1067
  if (onErrorResult instanceof Error) {
858
1068
  error = onErrorResult;
859
1069
  } else {
860
- const parsedError2 = import_core3.ErrorWithStackSchema.safeParse(onErrorResult.error);
861
- throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
862
- message: "Unknown error"
863
- }, 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
+ }
864
1077
  }
865
1078
  }
866
1079
  } catch (innerError) {
@@ -871,7 +1084,7 @@ var IO = class {
871
1084
  }
872
1085
  }
873
1086
  const parsedError = import_core3.ErrorWithStackSchema.safeParse(error);
874
- if (options?.retry) {
1087
+ if (options?.retry && !skipRetrying) {
875
1088
  const retryAt = (0, import_core2.calculateRetryAt)(options.retry, task.attempts - 1);
876
1089
  if (retryAt) {
877
1090
  throw new RetryWithTaskError(parsedError.success ? parsedError.data : {
@@ -894,10 +1107,39 @@ var IO = class {
894
1107
  throw error;
895
1108
  }
896
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
+ }
897
1129
  return this._taskStorage.run({
898
1130
  taskId: task.id
899
1131
  }, executeTask);
900
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
+ }
901
1143
  async try(tryCallback, catchCallback) {
902
1144
  try {
903
1145
  return await tryCallback();
@@ -922,7 +1164,7 @@ async function generateIdempotencyKey(keyMaterial) {
922
1164
  return stableStringify(key2);
923
1165
  });
924
1166
  const key = keys.join(":");
925
- const hash = await crypto.subtle.digest("SHA-256", Buffer.from(key));
1167
+ const hash = await import_node_crypto.webcrypto.subtle.digest("SHA-256", Buffer.from(key));
926
1168
  return Buffer.from(hash).toString("hex");
927
1169
  }
928
1170
  __name(generateIdempotencyKey, "generateIdempotencyKey");
@@ -997,27 +1239,147 @@ function createIOWithIntegrations(io, auths, integrations) {
997
1239
  }
998
1240
  __name(createIOWithIntegrations, "createIOWithIntegrations");
999
1241
 
1000
- // 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
1001
1261
  var import_core4 = require("@trigger.dev/core");
1002
- var _options2;
1003
- var EventTrigger = class {
1004
- constructor(options) {
1262
+ var _client, _options2;
1263
+ var DynamicTrigger = class {
1264
+ constructor(client, options) {
1265
+ __privateAdd(this, _client, void 0);
1005
1266
  __privateAdd(this, _options2, void 0);
1267
+ __privateSet(this, _client, client);
1006
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);
1007
1369
  }
1008
1370
  toJSON() {
1009
1371
  return {
1010
1372
  type: "static",
1011
- title: __privateGet(this, _options2).name ?? __privateGet(this, _options2).event.title,
1373
+ title: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.title,
1012
1374
  rule: {
1013
- event: __privateGet(this, _options2).name ?? __privateGet(this, _options2).event.name,
1014
- source: __privateGet(this, _options2).source ?? "trigger.dev",
1015
- 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 ?? {})
1016
1378
  }
1017
1379
  };
1018
1380
  }
1019
1381
  get event() {
1020
- return __privateGet(this, _options2).event;
1382
+ return __privateGet(this, _options3).event;
1021
1383
  }
1022
1384
  attachToJob(triggerClient, job) {
1023
1385
  }
@@ -1026,7 +1388,7 @@ var EventTrigger = class {
1026
1388
  }
1027
1389
  };
1028
1390
  __name(EventTrigger, "EventTrigger");
1029
- _options2 = new WeakMap();
1391
+ _options3 = new WeakMap();
1030
1392
  function eventTrigger(options) {
1031
1393
  return new EventTrigger({
1032
1394
  name: options.name,
@@ -1039,7 +1401,11 @@ function eventTrigger(options) {
1039
1401
  examples: options.examples,
1040
1402
  parsePayload: (rawPayload) => {
1041
1403
  if (options.schema) {
1042
- 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;
1043
1409
  }
1044
1410
  return rawPayload;
1045
1411
  }
@@ -1048,35 +1414,239 @@ function eventTrigger(options) {
1048
1414
  }
1049
1415
  __name(eventTrigger, "eventTrigger");
1050
1416
 
1051
- // src/triggerClient.ts
1052
- var registerSourceEvent = {
1053
- name: import_core5.REGISTER_SOURCE_EVENT_V2,
1054
- title: "Register Source",
1055
- source: "internal",
1056
- icon: "register-source",
1057
- parsePayload: import_core5.RegisterSourceEventSchemaV2.parse
1058
- };
1059
- 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;
1060
- var TriggerClient = class {
1061
- constructor(options) {
1062
- __privateAdd(this, _preprocessRun);
1063
- __privateAdd(this, _executeJob);
1064
- __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);
1065
1623
  __privateAdd(this, _createPreprocessRunContext);
1066
1624
  __privateAdd(this, _handleHttpSourceRequest);
1067
- __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);
1068
1634
  __privateAdd(this, _registeredJobs, {});
1069
1635
  __privateAdd(this, _registeredSources, {});
1070
1636
  __privateAdd(this, _registeredHttpSourceHandlers, {});
1071
1637
  __privateAdd(this, _registeredDynamicTriggers, {});
1072
1638
  __privateAdd(this, _jobMetadataByDynamicTriggers, {});
1073
1639
  __privateAdd(this, _registeredSchedules, {});
1074
- __privateAdd(this, _client, void 0);
1640
+ __privateAdd(this, _authResolvers, {});
1641
+ __privateAdd(this, _client2, void 0);
1075
1642
  __privateAdd(this, _internalLogger, void 0);
1076
1643
  this.id = options.id;
1077
- __privateSet(this, _options3, options);
1078
- __privateSet(this, _client, new ApiClient(__privateGet(this, _options3)));
1079
- __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
+ ]));
1080
1650
  }
1081
1651
  async handleRequest(request) {
1082
1652
  __privateGet(this, _internalLogger).debug("handling request", {
@@ -1085,6 +1655,7 @@ var TriggerClient = class {
1085
1655
  method: request.method
1086
1656
  });
1087
1657
  const apiKey = request.headers.get("x-trigger-api-key");
1658
+ const triggerVersion = request.headers.get("x-trigger-version");
1088
1659
  const authorization = this.authorized(apiKey);
1089
1660
  switch (authorization) {
1090
1661
  case "authorized": {
@@ -1095,7 +1666,8 @@ var TriggerClient = class {
1095
1666
  status: 401,
1096
1667
  body: {
1097
1668
  message: "Unauthorized: client missing apiKey"
1098
- }
1669
+ },
1670
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1099
1671
  };
1100
1672
  }
1101
1673
  case "missing-header": {
@@ -1103,7 +1675,8 @@ var TriggerClient = class {
1103
1675
  status: 401,
1104
1676
  body: {
1105
1677
  message: "Unauthorized: missing x-trigger-api-key header"
1106
- }
1678
+ },
1679
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1107
1680
  };
1108
1681
  }
1109
1682
  case "unauthorized": {
@@ -1111,7 +1684,8 @@ var TriggerClient = class {
1111
1684
  status: 401,
1112
1685
  body: {
1113
1686
  message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`
1114
- }
1687
+ },
1688
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1115
1689
  };
1116
1690
  }
1117
1691
  }
@@ -1120,7 +1694,8 @@ var TriggerClient = class {
1120
1694
  status: 405,
1121
1695
  body: {
1122
1696
  message: "Method not allowed (only POST is allowed)"
1123
- }
1697
+ },
1698
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1124
1699
  };
1125
1700
  }
1126
1701
  const action = request.headers.get("x-trigger-action");
@@ -1129,7 +1704,8 @@ var TriggerClient = class {
1129
1704
  status: 400,
1130
1705
  body: {
1131
1706
  message: "Missing x-trigger-action header"
1132
- }
1707
+ },
1708
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1133
1709
  };
1134
1710
  }
1135
1711
  switch (action) {
@@ -1141,7 +1717,8 @@ var TriggerClient = class {
1141
1717
  body: {
1142
1718
  ok: false,
1143
1719
  error: "Missing endpoint ID"
1144
- }
1720
+ },
1721
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1145
1722
  };
1146
1723
  }
1147
1724
  if (this.id !== endpointId) {
@@ -1150,35 +1727,21 @@ var TriggerClient = class {
1150
1727
  body: {
1151
1728
  ok: false,
1152
1729
  error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`
1153
- }
1730
+ },
1731
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1154
1732
  };
1155
1733
  }
1156
1734
  return {
1157
1735
  status: 200,
1158
1736
  body: {
1159
1737
  ok: true
1160
- }
1738
+ },
1739
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1161
1740
  };
1162
1741
  }
1163
1742
  case "INDEX_ENDPOINT": {
1164
- const jobId = request.headers.get("x-trigger-job-id");
1165
- if (jobId) {
1166
- const job = __privateGet(this, _registeredJobs)[jobId];
1167
- if (!job) {
1168
- return {
1169
- status: 404,
1170
- body: {
1171
- message: "Job not found"
1172
- }
1173
- };
1174
- }
1175
- return {
1176
- status: 200,
1177
- body: job.toJSON()
1178
- };
1179
- }
1180
1743
  const body = {
1181
- jobs: Object.values(__privateGet(this, _registeredJobs)).map((job) => job.toJSON()),
1744
+ jobs: __privateMethod(this, _buildJobsIndex, buildJobsIndex_fn).call(this),
1182
1745
  sources: Object.values(__privateGet(this, _registeredSources)),
1183
1746
  dynamicTriggers: Object.values(__privateGet(this, _registeredDynamicTriggers)).map((trigger) => ({
1184
1747
  id: trigger.id,
@@ -1195,12 +1758,13 @@ var TriggerClient = class {
1195
1758
  };
1196
1759
  return {
1197
1760
  status: 200,
1198
- body
1761
+ body,
1762
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1199
1763
  };
1200
1764
  }
1201
1765
  case "INITIALIZE_TRIGGER": {
1202
1766
  const json = await request.json();
1203
- const body = import_core5.InitializeTriggerBodySchema.safeParse(json);
1767
+ const body = import_core7.InitializeTriggerBodySchema.safeParse(json);
1204
1768
  if (!body.success) {
1205
1769
  return {
1206
1770
  status: 400,
@@ -1220,12 +1784,13 @@ var TriggerClient = class {
1220
1784
  }
1221
1785
  return {
1222
1786
  status: 200,
1223
- body: dynamicTrigger.registeredTriggerForParams(body.data.params)
1787
+ body: dynamicTrigger.registeredTriggerForParams(body.data.params),
1788
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1224
1789
  };
1225
1790
  }
1226
1791
  case "EXECUTE_JOB": {
1227
1792
  const json = await request.json();
1228
- const execution = import_core5.RunJobBodySchema.safeParse(json);
1793
+ const execution = import_core7.RunJobBodySchema.safeParse(json);
1229
1794
  if (!execution.success) {
1230
1795
  return {
1231
1796
  status: 400,
@@ -1243,15 +1808,16 @@ var TriggerClient = class {
1243
1808
  }
1244
1809
  };
1245
1810
  }
1246
- 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);
1247
1812
  return {
1248
1813
  status: 200,
1249
- body: results
1814
+ body: results,
1815
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1250
1816
  };
1251
1817
  }
1252
1818
  case "PREPROCESS_RUN": {
1253
1819
  const json = await request.json();
1254
- const body = import_core5.PreprocessRunBodySchema.safeParse(json);
1820
+ const body = import_core7.PreprocessRunBodySchema.safeParse(json);
1255
1821
  if (!body.success) {
1256
1822
  return {
1257
1823
  status: 400,
@@ -1275,11 +1841,12 @@ var TriggerClient = class {
1275
1841
  body: {
1276
1842
  abort: results.abort,
1277
1843
  properties: results.properties
1278
- }
1844
+ },
1845
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1279
1846
  };
1280
1847
  }
1281
1848
  case "DELIVER_HTTP_SOURCE_REQUEST": {
1282
- const headers = import_core5.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1849
+ const headers = import_core7.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
1283
1850
  if (!headers.success) {
1284
1851
  return {
1285
1852
  status: 400,
@@ -1324,7 +1891,8 @@ var TriggerClient = class {
1324
1891
  events,
1325
1892
  response,
1326
1893
  metadata
1327
- }
1894
+ },
1895
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1328
1896
  };
1329
1897
  }
1330
1898
  case "VALIDATE": {
@@ -1333,7 +1901,8 @@ var TriggerClient = class {
1333
1901
  body: {
1334
1902
  ok: true,
1335
1903
  endpointId: this.id
1336
- }
1904
+ },
1905
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1337
1906
  };
1338
1907
  }
1339
1908
  }
@@ -1341,16 +1910,30 @@ var TriggerClient = class {
1341
1910
  status: 405,
1342
1911
  body: {
1343
1912
  message: "Method not allowed"
1344
- }
1913
+ },
1914
+ headers: __privateGet(this, _standardResponseHeaders, standardResponseHeaders_get)
1345
1915
  };
1346
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
+ }
1347
1930
  attach(job) {
1348
1931
  __privateGet(this, _registeredJobs)[job.id] = job;
1349
1932
  job.trigger.attachToJob(this, job);
1350
1933
  }
1351
1934
  attachDynamicTrigger(trigger) {
1352
1935
  __privateGet(this, _registeredDynamicTriggers)[trigger.id] = trigger;
1353
- new Job(this, {
1936
+ this.defineJob({
1354
1937
  id: dynamicTriggerRegisterSourceJobId(trigger.id),
1355
1938
  name: `Register dynamic trigger ${trigger.id}`,
1356
1939
  version: trigger.source.version,
@@ -1446,7 +2029,11 @@ var TriggerClient = class {
1446
2029
  __internal: true
1447
2030
  });
1448
2031
  }
1449
- attachDynamicSchedule(key, job) {
2032
+ attachDynamicSchedule(key) {
2033
+ const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
2034
+ __privateGet(this, _registeredSchedules)[key] = jobs;
2035
+ }
2036
+ attachDynamicScheduleToJob(key, job) {
1450
2037
  const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
1451
2038
  jobs.push({
1452
2039
  id: job.id,
@@ -1455,58 +2042,65 @@ var TriggerClient = class {
1455
2042
  __privateGet(this, _registeredSchedules)[key] = jobs;
1456
2043
  }
1457
2044
  async registerTrigger(id, key, options) {
1458
- return __privateGet(this, _client).registerTrigger(this.id, id, key, options);
2045
+ return __privateGet(this, _client2).registerTrigger(this.id, id, key, options);
1459
2046
  }
1460
2047
  async getAuth(id) {
1461
- return __privateGet(this, _client).getAuth(this.id, id);
2048
+ return __privateGet(this, _client2).getAuth(this.id, id);
1462
2049
  }
1463
2050
  async sendEvent(event, options) {
1464
- return __privateGet(this, _client).sendEvent(event, options);
2051
+ return __privateGet(this, _client2).sendEvent(event, options);
1465
2052
  }
1466
2053
  async cancelEvent(eventId) {
1467
- 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);
1468
2058
  }
1469
2059
  async registerSchedule(id, key, schedule) {
1470
- return __privateGet(this, _client).registerSchedule(this.id, id, key, schedule);
2060
+ return __privateGet(this, _client2).registerSchedule(this.id, id, key, schedule);
1471
2061
  }
1472
2062
  async unregisterSchedule(id, key) {
1473
- return __privateGet(this, _client).unregisterSchedule(this.id, id, key);
2063
+ return __privateGet(this, _client2).unregisterSchedule(this.id, id, key);
1474
2064
  }
1475
2065
  async getEvent(eventId) {
1476
- return __privateGet(this, _client).getEvent(eventId);
2066
+ return __privateGet(this, _client2).getEvent(eventId);
1477
2067
  }
1478
2068
  async getRun(runId, options) {
1479
- 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);
1480
2073
  }
1481
2074
  async getRuns(jobSlug, options) {
1482
- 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);
1483
2079
  }
1484
2080
  authorized(apiKey) {
1485
2081
  if (typeof apiKey !== "string") {
1486
2082
  return "missing-header";
1487
2083
  }
1488
- const localApiKey = __privateGet(this, _options3).apiKey ?? process.env.TRIGGER_API_KEY;
2084
+ const localApiKey = __privateGet(this, _options4).apiKey ?? process.env.TRIGGER_API_KEY;
1489
2085
  if (!localApiKey) {
1490
2086
  return "missing-client";
1491
2087
  }
1492
2088
  return apiKey === localApiKey ? "authorized" : "unauthorized";
1493
2089
  }
1494
2090
  apiKey() {
1495
- return __privateGet(this, _options3).apiKey ?? process.env.TRIGGER_API_KEY;
1496
- }
1497
- defineJob(options) {
1498
- return new Job(this, options);
2091
+ return __privateGet(this, _options4).apiKey ?? process.env.TRIGGER_API_KEY;
1499
2092
  }
1500
2093
  };
1501
2094
  __name(TriggerClient, "TriggerClient");
1502
- _options3 = new WeakMap();
2095
+ _options4 = new WeakMap();
1503
2096
  _registeredJobs = new WeakMap();
1504
2097
  _registeredSources = new WeakMap();
1505
2098
  _registeredHttpSourceHandlers = new WeakMap();
1506
2099
  _registeredDynamicTriggers = new WeakMap();
1507
2100
  _jobMetadataByDynamicTriggers = new WeakMap();
1508
2101
  _registeredSchedules = new WeakMap();
1509
- _client = new WeakMap();
2102
+ _authResolvers = new WeakMap();
2103
+ _client2 = new WeakMap();
1510
2104
  _internalLogger = new WeakMap();
1511
2105
  _preprocessRun = new WeakSet();
1512
2106
  preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
@@ -1519,30 +2113,66 @@ preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
1519
2113
  };
1520
2114
  }, "#preprocessRun");
1521
2115
  _executeJob = new WeakSet();
1522
- executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
2116
+ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, triggerVersion) {
1523
2117
  __privateGet(this, _internalLogger).debug("executing job", {
1524
2118
  execution: body1,
1525
- job: job1.toJSON()
2119
+ job: job1.id,
2120
+ version: job1.version,
2121
+ triggerVersion
1526
2122
  });
1527
2123
  const context = __privateMethod(this, _createRunContext, createRunContext_fn).call(this, body1);
1528
2124
  const io = new IO({
1529
2125
  id: body1.run.id,
1530
2126
  cachedTasks: body1.tasks,
1531
- apiClient: __privateGet(this, _client),
2127
+ cachedTasksCursor: body1.cachedTaskCursor,
2128
+ yieldedExecutions: body1.yieldedExecutions ?? [],
2129
+ noopTasksSet: body1.noopTasksSet,
2130
+ apiClient: __privateGet(this, _client2),
1532
2131
  logger: __privateGet(this, _internalLogger),
1533
2132
  client: this,
1534
2133
  context,
1535
- jobLogLevel: job1.logLevel ?? __privateGet(this, _options3).logLevel ?? "info",
1536
- 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
1537
2137
  });
1538
- 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);
1539
2146
  try {
1540
- 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
+ }
1541
2156
  return {
1542
2157
  status: "SUCCESS",
1543
2158
  output
1544
2159
  };
1545
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
+ }
1546
2176
  if (error instanceof ResumeWithTaskError) {
1547
2177
  return {
1548
2178
  status: "RESUME_WITH_TASK",
@@ -1564,7 +2194,7 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
1564
2194
  };
1565
2195
  }
1566
2196
  if (error instanceof RetryWithTaskError) {
1567
- const errorWithStack2 = import_core5.ErrorWithStackSchema.safeParse(error.cause);
2197
+ const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause);
1568
2198
  if (errorWithStack2.success) {
1569
2199
  return {
1570
2200
  status: "ERROR",
@@ -1580,7 +2210,7 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
1580
2210
  task: error.task
1581
2211
  };
1582
2212
  }
1583
- const errorWithStack = import_core5.ErrorWithStackSchema.safeParse(error);
2213
+ const errorWithStack = import_core7.ErrorWithStackSchema.safeParse(error);
1584
2214
  if (errorWithStack.success) {
1585
2215
  return {
1586
2216
  status: "ERROR",
@@ -1712,6 +2342,166 @@ handleHttpSourceRequest_fn = /* @__PURE__ */ __name(async function(source, sourc
1712
2342
  metadata: results.metadata
1713
2343
  };
1714
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");
1715
2505
  function dynamicTriggerRegisterSourceJobId(id) {
1716
2506
  return `register-dynamic-trigger-${id}`;
1717
2507
  }
@@ -1737,7 +2527,7 @@ function deepMergeOptions(obj1, obj2) {
1737
2527
  __name(deepMergeOptions, "deepMergeOptions");
1738
2528
 
1739
2529
  // src/triggers/externalSource.ts
1740
- var import_core6 = require("@trigger.dev/core");
2530
+ var import_core8 = require("@trigger.dev/core");
1741
2531
  var ExternalSource = class {
1742
2532
  constructor(channel, options) {
1743
2533
  this.options = options;
@@ -1811,7 +2601,7 @@ var ExternalSourceTrigger = class {
1811
2601
  title: "External Source",
1812
2602
  rule: {
1813
2603
  event: this.event.name,
1814
- 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 ?? {}),
1815
2605
  source: this.event.source
1816
2606
  },
1817
2607
  properties: this.options.source.properties(this.options.params)
@@ -1845,214 +2635,6 @@ function omit(obj, key) {
1845
2635
  }
1846
2636
  __name(omit, "omit");
1847
2637
 
1848
- // src/triggers/dynamic.ts
1849
- var import_core7 = require("@trigger.dev/core");
1850
- var _client2, _options4;
1851
- var DynamicTrigger = class {
1852
- constructor(client, options) {
1853
- __privateAdd(this, _client2, void 0);
1854
- __privateAdd(this, _options4, void 0);
1855
- __privateSet(this, _client2, client);
1856
- __privateSet(this, _options4, options);
1857
- this.source = options.source;
1858
- client.attachDynamicTrigger(this);
1859
- }
1860
- toJSON() {
1861
- return {
1862
- type: "dynamic",
1863
- id: __privateGet(this, _options4).id
1864
- };
1865
- }
1866
- get id() {
1867
- return __privateGet(this, _options4).id;
1868
- }
1869
- get event() {
1870
- return __privateGet(this, _options4).event;
1871
- }
1872
- registeredTriggerForParams(params) {
1873
- const key = slugifyId(this.source.key(params));
1874
- return {
1875
- rule: {
1876
- event: this.event.name,
1877
- source: this.event.source,
1878
- payload: (0, import_core7.deepMergeFilters)(this.source.filter(params), this.event.filter ?? {})
1879
- },
1880
- source: {
1881
- version: "2",
1882
- key,
1883
- channel: this.source.channel,
1884
- params,
1885
- options: {
1886
- event: typeof this.event.name === "string" ? [
1887
- this.event.name
1888
- ] : this.event.name
1889
- },
1890
- integration: {
1891
- id: this.source.integration.id,
1892
- metadata: this.source.integration.metadata,
1893
- authSource: this.source.integration.authSource
1894
- }
1895
- }
1896
- };
1897
- }
1898
- async register(key, params) {
1899
- return __privateGet(this, _client2).registerTrigger(this.id, key, this.registeredTriggerForParams(params));
1900
- }
1901
- attachToJob(triggerClient, job) {
1902
- triggerClient.attachJobToDynamicTrigger(job, this);
1903
- }
1904
- get preprocessRuns() {
1905
- return true;
1906
- }
1907
- };
1908
- __name(DynamicTrigger, "DynamicTrigger");
1909
- _client2 = new WeakMap();
1910
- _options4 = new WeakMap();
1911
-
1912
- // src/triggers/scheduled.ts
1913
- var import_core8 = require("@trigger.dev/core");
1914
- var import_cronstrue = __toESM(require("cronstrue"));
1915
- var examples = [
1916
- {
1917
- id: "now",
1918
- name: "Now",
1919
- icon: "clock",
1920
- payload: {
1921
- ts: import_core8.currentDate.marker,
1922
- lastTimestamp: import_core8.currentDate.marker
1923
- }
1924
- }
1925
- ];
1926
- var IntervalTrigger = class {
1927
- constructor(options) {
1928
- this.options = options;
1929
- }
1930
- get event() {
1931
- return {
1932
- name: "trigger.scheduled",
1933
- title: "Schedule",
1934
- source: "trigger.dev",
1935
- icon: "schedule-interval",
1936
- examples,
1937
- parsePayload: import_core8.ScheduledPayloadSchema.parse,
1938
- properties: [
1939
- {
1940
- label: "Interval",
1941
- text: `${this.options.seconds}s`
1942
- }
1943
- ]
1944
- };
1945
- }
1946
- attachToJob(triggerClient, job) {
1947
- }
1948
- get preprocessRuns() {
1949
- return false;
1950
- }
1951
- toJSON() {
1952
- return {
1953
- type: "scheduled",
1954
- schedule: {
1955
- type: "interval",
1956
- options: {
1957
- seconds: this.options.seconds
1958
- }
1959
- }
1960
- };
1961
- }
1962
- };
1963
- __name(IntervalTrigger, "IntervalTrigger");
1964
- function intervalTrigger(options) {
1965
- return new IntervalTrigger(options);
1966
- }
1967
- __name(intervalTrigger, "intervalTrigger");
1968
- var CronTrigger = class {
1969
- constructor(options) {
1970
- this.options = options;
1971
- }
1972
- get event() {
1973
- const humanReadable = import_cronstrue.default.toString(this.options.cron, {
1974
- throwExceptionOnParseError: false
1975
- });
1976
- return {
1977
- name: "trigger.scheduled",
1978
- title: "Cron Schedule",
1979
- source: "trigger.dev",
1980
- icon: "schedule-cron",
1981
- examples,
1982
- parsePayload: import_core8.ScheduledPayloadSchema.parse,
1983
- properties: [
1984
- {
1985
- label: "cron",
1986
- text: this.options.cron
1987
- },
1988
- {
1989
- label: "Schedule",
1990
- text: humanReadable
1991
- }
1992
- ]
1993
- };
1994
- }
1995
- attachToJob(triggerClient, job) {
1996
- }
1997
- get preprocessRuns() {
1998
- return false;
1999
- }
2000
- toJSON() {
2001
- return {
2002
- type: "scheduled",
2003
- schedule: {
2004
- type: "cron",
2005
- options: {
2006
- cron: this.options.cron
2007
- }
2008
- }
2009
- };
2010
- }
2011
- };
2012
- __name(CronTrigger, "CronTrigger");
2013
- function cronTrigger(options) {
2014
- return new CronTrigger(options);
2015
- }
2016
- __name(cronTrigger, "cronTrigger");
2017
- var DynamicSchedule = class {
2018
- constructor(client, options) {
2019
- this.client = client;
2020
- this.options = options;
2021
- }
2022
- get id() {
2023
- return this.options.id;
2024
- }
2025
- get event() {
2026
- return {
2027
- name: "trigger.scheduled",
2028
- title: "Dynamic Schedule",
2029
- source: "trigger.dev",
2030
- icon: "schedule-dynamic",
2031
- examples,
2032
- parsePayload: import_core8.ScheduledPayloadSchema.parse
2033
- };
2034
- }
2035
- async register(key, metadata) {
2036
- return this.client.registerSchedule(this.id, key, metadata);
2037
- }
2038
- async unregister(key) {
2039
- return this.client.unregisterSchedule(this.id, key);
2040
- }
2041
- attachToJob(triggerClient, job) {
2042
- triggerClient.attachDynamicSchedule(this.options.id, job);
2043
- }
2044
- get preprocessRuns() {
2045
- return false;
2046
- }
2047
- toJSON() {
2048
- return {
2049
- type: "dynamic",
2050
- id: this.options.id
2051
- };
2052
- }
2053
- };
2054
- __name(DynamicSchedule, "DynamicSchedule");
2055
-
2056
2638
  // src/triggers/notifications.ts
2057
2639
  var import_core9 = require("@trigger.dev/core");
2058
2640
  function missingConnectionNotification(integrations) {