@trigger.dev/sdk 0.0.0-cliframeworks-20230929110149 → 0.0.0-invoke-trigger-20231103104037

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);
@@ -58,6 +63,8 @@ __export(src_exports, {
58
63
  IO: () => IO,
59
64
  IOLogger: () => IOLogger,
60
65
  IntervalTrigger: () => IntervalTrigger,
66
+ InvokeTrigger: () => InvokeTrigger,
67
+ JSONOutputSerializer: () => JSONOutputSerializer,
61
68
  Job: () => Job,
62
69
  MissingConnectionNotification: () => MissingConnectionNotification,
63
70
  MissingConnectionResolvedNotification: () => MissingConnectionResolvedNotification,
@@ -65,6 +72,7 @@ __export(src_exports, {
65
72
  cronTrigger: () => cronTrigger,
66
73
  eventTrigger: () => eventTrigger,
67
74
  intervalTrigger: () => intervalTrigger,
75
+ invokeTrigger: () => invokeTrigger,
68
76
  isTriggerError: () => isTriggerError,
69
77
  missingConnectionNotification: () => missingConnectionNotification,
70
78
  missingConnectionResolvedNotification: () => missingConnectionResolvedNotification,
@@ -82,6 +90,24 @@ function slugifyId(input) {
82
90
  }
83
91
  __name(slugifyId, "slugifyId");
84
92
 
93
+ // src/utils/typedAsyncLocalStorage.ts
94
+ var import_node_async_hooks = require("async_hooks");
95
+ var TypedAsyncLocalStorage = class {
96
+ constructor() {
97
+ this.storage = new import_node_async_hooks.AsyncLocalStorage();
98
+ }
99
+ runWith(context, fn) {
100
+ return this.storage.run(context, fn);
101
+ }
102
+ getStore() {
103
+ return this.storage.getStore();
104
+ }
105
+ };
106
+ __name(TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
107
+
108
+ // src/runLocalStorage.ts
109
+ var runLocalStorage = new TypedAsyncLocalStorage();
110
+
85
111
  // src/job.ts
86
112
  var _validate, validate_fn;
87
113
  var Job = class {
@@ -136,6 +162,118 @@ var Job = class {
136
162
  internal
137
163
  };
138
164
  }
165
+ async invoke(param1, param2 = void 0, param3 = void 0) {
166
+ const runStore = runLocalStorage.getStore();
167
+ if (typeof param1 === "string") {
168
+ if (!runStore) {
169
+ throw new Error("Cannot invoke a job from outside of a run when passing a cacheKey. Make sure you are running the job from within a run or use the invoke method without the cacheKey.");
170
+ }
171
+ const options = param3 ?? {};
172
+ return await runStore.io.runTask(param1, async (task) => {
173
+ const result = await this.client.invokeJob(this.id, param2, {
174
+ idempotencyKey: task.idempotencyKey,
175
+ ...options
176
+ });
177
+ task.outputProperties = [
178
+ {
179
+ label: "Run",
180
+ text: result.id,
181
+ url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
182
+ }
183
+ ];
184
+ return result;
185
+ }, {
186
+ name: `Manually Invoke '${this.name}'`,
187
+ params: param2,
188
+ properties: [
189
+ {
190
+ label: "Job",
191
+ text: this.id,
192
+ url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}`
193
+ },
194
+ {
195
+ label: "Env",
196
+ text: runStore.ctx.environment.slug
197
+ }
198
+ ]
199
+ });
200
+ }
201
+ if (runStore) {
202
+ throw new Error("Cannot invoke a job from within a run without a cacheKey.");
203
+ }
204
+ return await this.client.invokeJob(this.id, param1, param3);
205
+ }
206
+ async invokeAndWaitForCompletion(cacheKey, payload, timeoutInSeconds = 60 * 60, options = {}) {
207
+ const runStore = runLocalStorage.getStore();
208
+ if (!runStore) {
209
+ throw new Error("Cannot invoke a job from outside of a run using invokeAndWaitForCompletion. Make sure you are running the job from within a run or use the invoke method instead.");
210
+ }
211
+ const { io, ctx } = runStore;
212
+ return await io.runTask(cacheKey, async (task) => {
213
+ const parsedPayload = this.trigger.event.parseInvokePayload ? this.trigger.event.parseInvokePayload(payload) ? payload : void 0 : payload;
214
+ const result = await this.client.invokeJob(this.id, parsedPayload, {
215
+ idempotencyKey: task.idempotencyKey,
216
+ callbackUrl: task.callbackUrl ?? void 0,
217
+ ...options
218
+ });
219
+ task.outputProperties = [
220
+ {
221
+ label: "Run",
222
+ text: result.id,
223
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
224
+ }
225
+ ];
226
+ return {};
227
+ }, {
228
+ name: `Manually Invoke '${this.name}' and wait for completion`,
229
+ params: payload,
230
+ properties: [
231
+ {
232
+ label: "Job",
233
+ text: this.id,
234
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
235
+ },
236
+ {
237
+ label: "Env",
238
+ text: ctx.environment.slug
239
+ }
240
+ ],
241
+ callback: {
242
+ enabled: true,
243
+ timeoutInSeconds
244
+ }
245
+ });
246
+ }
247
+ async batchInvokeAndWaitForCompletion(cacheKey, batch) {
248
+ const runStore = runLocalStorage.getStore();
249
+ if (!runStore) {
250
+ throw new Error("Cannot invoke a job from outside of a run using batchInvokeAndWaitForCompletion.");
251
+ }
252
+ if (batch.length === 0) {
253
+ return [];
254
+ }
255
+ if (batch.length > 25) {
256
+ throw new Error(`Cannot batch invoke more than 25 items. You tried to batch invoke ${batch.length} items.`);
257
+ }
258
+ const { io, ctx } = runStore;
259
+ const results = await io.parallel(cacheKey, batch, async (item, index) => {
260
+ return await this.invokeAndWaitForCompletion(String(index), item.payload, item.timeoutInSeconds ?? 60 * 60, item.options);
261
+ }, {
262
+ name: `Batch Invoke '${this.name}'`,
263
+ properties: [
264
+ {
265
+ label: "Job",
266
+ text: this.id,
267
+ url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
268
+ },
269
+ {
270
+ label: "Env",
271
+ text: ctx.environment.slug
272
+ }
273
+ ]
274
+ });
275
+ return results;
276
+ }
139
277
  };
140
278
  __name(Job, "Job");
141
279
  _validate = new WeakSet();
@@ -150,7 +288,6 @@ var import_core7 = require("@trigger.dev/core");
150
288
 
151
289
  // src/apiClient.ts
152
290
  var import_core = require("@trigger.dev/core");
153
- var import_node_fetch = __toESM(require("node-fetch"));
154
291
  var import_zod = require("zod");
155
292
  var _apiUrl, _options, _logger, _apiKey, apiKey_fn;
156
293
  var ApiClient = class {
@@ -169,7 +306,7 @@ var ApiClient = class {
169
306
  url: options.url,
170
307
  name: options.name
171
308
  });
172
- const response = await (0, import_node_fetch.default)(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
309
+ const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
173
310
  method: "POST",
174
311
  headers: {
175
312
  "Content-Type": "application/json",
@@ -189,17 +326,21 @@ var ApiClient = class {
189
326
  }
190
327
  return await response.json();
191
328
  }
192
- async runTask(runId, task) {
329
+ async runTask(runId, task, options = {}) {
193
330
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
194
331
  __privateGet(this, _logger).debug("Running Task", {
195
332
  task
196
333
  });
197
- return await zodfetch(import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
334
+ return await zodfetchWithVersions({
335
+ [import_core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: import_core.RunTaskResponseWithCachedTasksBodySchema
336
+ }, import_core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
198
337
  method: "POST",
199
338
  headers: {
200
339
  "Content-Type": "application/json",
201
340
  Authorization: `Bearer ${apiKey}`,
202
- "Idempotency-Key": task.idempotencyKey
341
+ "Idempotency-Key": task.idempotencyKey,
342
+ "X-Cached-Tasks-Cursor": options.cachedTasksCursor ?? "",
343
+ "Trigger-Version": import_core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS
203
344
  },
204
345
  body: JSON.stringify(task)
205
346
  });
@@ -213,7 +354,8 @@ var ApiClient = class {
213
354
  method: "POST",
214
355
  headers: {
215
356
  "Content-Type": "application/json",
216
- Authorization: `Bearer ${apiKey}`
357
+ Authorization: `Bearer ${apiKey}`,
358
+ "Trigger-Version": import_core.API_VERSIONS.SERIALIZED_TASK_OUTPUT
217
359
  },
218
360
  body: JSON.stringify(task)
219
361
  });
@@ -264,6 +406,19 @@ var ApiClient = class {
264
406
  }
265
407
  });
266
408
  }
409
+ async cancelRunsForEvent(eventId) {
410
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
411
+ __privateGet(this, _logger).debug("Cancelling runs for event", {
412
+ eventId
413
+ });
414
+ return await zodfetch(import_core.CancelRunsForEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel-runs`, {
415
+ method: "POST",
416
+ headers: {
417
+ "Content-Type": "application/json",
418
+ Authorization: `Bearer ${apiKey}`
419
+ }
420
+ });
421
+ }
267
422
  async updateStatus(runId, id, status) {
268
423
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
269
424
  __privateGet(this, _logger).debug("Update status", {
@@ -294,18 +449,22 @@ var ApiClient = class {
294
449
  });
295
450
  return response;
296
451
  }
297
- async registerTrigger(client, id, key, payload) {
452
+ async registerTrigger(client, id, key, payload, idempotencyKey) {
298
453
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
299
454
  __privateGet(this, _logger).debug("registering trigger", {
300
455
  id,
301
456
  payload
302
457
  });
458
+ const headers = {
459
+ "Content-Type": "application/json",
460
+ Authorization: `Bearer ${apiKey}`
461
+ };
462
+ if (idempotencyKey) {
463
+ headers["Idempotency-Key"] = idempotencyKey;
464
+ }
303
465
  const response = await zodfetch(import_core.RegisterSourceEventSchemaV2, `${__privateGet(this, _apiUrl)}/api/v2/${client}/triggers/${id}/registrations/${key}`, {
304
466
  method: "PUT",
305
- headers: {
306
- "Content-Type": "application/json",
307
- Authorization: `Bearer ${apiKey}`
308
- },
467
+ headers,
309
468
  body: JSON.stringify(payload)
310
469
  });
311
470
  return response;
@@ -385,6 +544,19 @@ var ApiClient = class {
385
544
  }
386
545
  });
387
546
  }
547
+ async cancelRun(runId) {
548
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
549
+ __privateGet(this, _logger).debug("Cancelling Run", {
550
+ runId
551
+ });
552
+ return await zodfetch(import_core.GetRunSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/cancel`, {
553
+ method: "POST",
554
+ headers: {
555
+ "Content-Type": "application/json",
556
+ Authorization: `Bearer ${apiKey}`
557
+ }
558
+ });
559
+ }
388
560
  async getRunStatuses(runId) {
389
561
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
390
562
  __privateGet(this, _logger).debug("Getting Run statuses", {
@@ -409,6 +581,31 @@ var ApiClient = class {
409
581
  }
410
582
  });
411
583
  }
584
+ async invokeJob(jobId, payload, options = {}) {
585
+ const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
586
+ __privateGet(this, _logger).debug("Invoking Job", {
587
+ jobId
588
+ });
589
+ const body = {
590
+ payload,
591
+ context: options.context ?? {},
592
+ options: {
593
+ accountId: options.accountId,
594
+ callbackUrl: options.callbackUrl
595
+ }
596
+ };
597
+ return await zodfetch(import_core.InvokeJobResponseSchema, `${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobId}/invoke`, {
598
+ method: "POST",
599
+ headers: {
600
+ "Content-Type": "application/json",
601
+ Authorization: `Bearer ${apiKey}`,
602
+ ...options.idempotencyKey ? {
603
+ "Idempotency-Key": options.idempotencyKey
604
+ } : {}
605
+ },
606
+ body: JSON.stringify(body)
607
+ });
608
+ }
412
609
  };
413
610
  __name(ApiClient, "ApiClient");
414
611
  _apiUrl = new WeakMap();
@@ -444,8 +641,43 @@ function getApiKey(key) {
444
641
  };
445
642
  }
446
643
  __name(getApiKey, "getApiKey");
447
- async function zodfetch(schema, url, requestInit, options) {
448
- const response = await (0, import_node_fetch.default)(url, requestInit);
644
+ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount = 0) {
645
+ const response = await fetch(url, requestInit);
646
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
647
+ return;
648
+ }
649
+ if (response.status >= 400 && response.status < 500) {
650
+ const body = await response.json();
651
+ throw new Error(body.error);
652
+ }
653
+ if (response.status >= 500 && retryCount < 6) {
654
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
655
+ await new Promise((resolve) => setTimeout(resolve, delay));
656
+ return zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount + 1);
657
+ }
658
+ if (response.status !== 200) {
659
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
660
+ }
661
+ const jsonBody = await response.json();
662
+ const version2 = response.headers.get("trigger-version");
663
+ if (!version2) {
664
+ return {
665
+ version: "unversioned",
666
+ body: unversionedSchema.parse(jsonBody)
667
+ };
668
+ }
669
+ const versionedSchema = versionedSchemaMap[version2];
670
+ if (!versionedSchema) {
671
+ throw new Error(`Unknown version ${version2}`);
672
+ }
673
+ return {
674
+ version: version2,
675
+ body: versionedSchema.parse(jsonBody)
676
+ };
677
+ }
678
+ __name(zodfetchWithVersions, "zodfetchWithVersions");
679
+ async function zodfetch(schema, url, requestInit, options, retryCount = 0) {
680
+ const response = await fetch(url, requestInit);
449
681
  if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
450
682
  return;
451
683
  }
@@ -453,6 +685,11 @@ async function zodfetch(schema, url, requestInit, options) {
453
685
  const body = await response.json();
454
686
  throw new Error(body.error);
455
687
  }
688
+ if (response.status >= 500 && retryCount < 6) {
689
+ const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
690
+ await new Promise((resolve) => setTimeout(resolve, delay));
691
+ return zodfetch(schema, url, requestInit, options, retryCount + 1);
692
+ }
456
693
  if (response.status !== 200) {
457
694
  throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
458
695
  }
@@ -460,6 +697,12 @@ async function zodfetch(schema, url, requestInit, options) {
460
697
  return schema.parse(jsonBody);
461
698
  }
462
699
  __name(zodfetch, "zodfetch");
700
+ function exponentialBackoff(retryCount, exponential, minDelay, maxDelay, jitter) {
701
+ const delay = Math.min(Math.pow(exponential, retryCount) * minDelay, maxDelay);
702
+ const jitterValue = Math.random() * jitter;
703
+ return delay + jitterValue;
704
+ }
705
+ __name(exponentialBackoff, "exponentialBackoff");
463
706
 
464
707
  // src/errors.ts
465
708
  var ResumeWithTaskError = class {
@@ -468,6 +711,13 @@ var ResumeWithTaskError = class {
468
711
  }
469
712
  };
470
713
  __name(ResumeWithTaskError, "ResumeWithTaskError");
714
+ var ResumeWithParallelTaskError = class {
715
+ constructor(task, childErrors) {
716
+ this.task = task;
717
+ this.childErrors = childErrors;
718
+ }
719
+ };
720
+ __name(ResumeWithParallelTaskError, "ResumeWithParallelTaskError");
471
721
  var RetryWithTaskError = class {
472
722
  constructor(cause, task, retryAt) {
473
723
  this.cause = cause;
@@ -482,6 +732,29 @@ var CanceledWithTaskError = class {
482
732
  }
483
733
  };
484
734
  __name(CanceledWithTaskError, "CanceledWithTaskError");
735
+ var YieldExecutionError = class {
736
+ constructor(key) {
737
+ this.key = key;
738
+ }
739
+ };
740
+ __name(YieldExecutionError, "YieldExecutionError");
741
+ var AutoYieldExecutionError = class {
742
+ constructor(location, timeRemaining, timeElapsed) {
743
+ this.location = location;
744
+ this.timeRemaining = timeRemaining;
745
+ this.timeElapsed = timeElapsed;
746
+ }
747
+ };
748
+ __name(AutoYieldExecutionError, "AutoYieldExecutionError");
749
+ var AutoYieldWithCompletedTaskExecutionError = class {
750
+ constructor(id, properties, data, output) {
751
+ this.id = id;
752
+ this.properties = properties;
753
+ this.data = data;
754
+ this.output = output;
755
+ }
756
+ };
757
+ __name(AutoYieldWithCompletedTaskExecutionError, "AutoYieldWithCompletedTaskExecutionError");
485
758
  var ParsedPayloadSchemaError = class {
486
759
  constructor(schemaErrors) {
487
760
  this.schemaErrors = schemaErrors;
@@ -489,13 +762,21 @@ var ParsedPayloadSchemaError = class {
489
762
  };
490
763
  __name(ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
491
764
  function isTriggerError(err) {
492
- return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError;
765
+ return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError || err instanceof ResumeWithParallelTaskError;
493
766
  }
494
767
  __name(isTriggerError, "isTriggerError");
768
+ var ErrorWithTask = class extends Error {
769
+ constructor(cause, message) {
770
+ super(message);
771
+ this.cause = cause;
772
+ }
773
+ };
774
+ __name(ErrorWithTask, "ErrorWithTask");
495
775
 
496
776
  // src/io.ts
497
777
  var import_core3 = require("@trigger.dev/core");
498
- var import_node_async_hooks = require("async_hooks");
778
+ var import_core_backend = require("@trigger.dev/core-backend");
779
+ var import_node_async_hooks2 = require("async_hooks");
499
780
  var import_node_crypto = require("crypto");
500
781
 
501
782
  // src/retry.ts
@@ -545,10 +826,26 @@ var TriggerStatus = class {
545
826
  __name(TriggerStatus, "TriggerStatus");
546
827
 
547
828
  // src/io.ts
548
- var _addToCachedTasks, addToCachedTasks_fn;
829
+ var JSONOutputSerializer = class {
830
+ serialize(value) {
831
+ return JSON.stringify(value);
832
+ }
833
+ deserialize(value) {
834
+ return value ? JSON.parse(value) : void 0;
835
+ }
836
+ };
837
+ __name(JSONOutputSerializer, "JSONOutputSerializer");
838
+ var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
549
839
  var IO = class {
550
840
  constructor(options) {
551
841
  __privateAdd(this, _addToCachedTasks);
842
+ __privateAdd(this, _detectAutoYield);
843
+ __privateAdd(this, _forceYield);
844
+ __privateAdd(this, _getTimeElapsed);
845
+ __privateAdd(this, _getRemainingTimeInMillis);
846
+ __publicField(this, "_outputSerializer", new JSONOutputSerializer());
847
+ __publicField(this, "_visitedCacheKeys", /* @__PURE__ */ new Set());
848
+ __publicField(this, "brb", this.yield.bind(this));
552
849
  this._id = options.id;
553
850
  this._apiClient = options.apiClient;
554
851
  this._triggerClient = options.client;
@@ -556,13 +853,34 @@ var IO = class {
556
853
  this._cachedTasks = /* @__PURE__ */ new Map();
557
854
  this._jobLogger = options.jobLogger;
558
855
  this._jobLogLevel = options.jobLogLevel;
856
+ this._timeOrigin = options.timeOrigin;
857
+ this._executionTimeout = options.executionTimeout;
858
+ this._stats = {
859
+ initialCachedTasks: 0,
860
+ lazyLoadedCachedTasks: 0,
861
+ executedTasks: 0,
862
+ cachedTaskHits: 0,
863
+ cachedTaskMisses: 0,
864
+ noopCachedTaskHits: 0,
865
+ noopCachedTaskMisses: 0
866
+ };
559
867
  if (options.cachedTasks) {
560
868
  options.cachedTasks.forEach((task) => {
561
869
  this._cachedTasks.set(task.idempotencyKey, task);
562
870
  });
871
+ this._stats.initialCachedTasks = options.cachedTasks.length;
563
872
  }
564
- this._taskStorage = new import_node_async_hooks.AsyncLocalStorage();
873
+ this._taskStorage = new import_node_async_hooks2.AsyncLocalStorage();
565
874
  this._context = options.context;
875
+ this._yieldedExecutions = options.yieldedExecutions ?? [];
876
+ if (options.noopTasksSet) {
877
+ this._noopTasksBloomFilter = import_core_backend.BloomFilter.deserialize(options.noopTasksSet, import_core_backend.BloomFilter.NOOP_TASK_SET_SIZE);
878
+ }
879
+ this._cachedTasksCursor = options.cachedTasksCursor;
880
+ this._serverVersion = options.serverVersion ?? "unversioned";
881
+ }
882
+ get stats() {
883
+ return this._stats;
566
884
  }
567
885
  get runId() {
568
886
  return this._id;
@@ -573,38 +891,38 @@ var IO = class {
573
891
  get logger() {
574
892
  return new IOLogger(async (level, message, data) => {
575
893
  let logLevel = "info";
576
- switch (level) {
577
- case "LOG": {
578
- this._jobLogger?.log(message, data);
579
- logLevel = "log";
580
- break;
581
- }
582
- case "DEBUG": {
583
- this._jobLogger?.debug(message, data);
584
- logLevel = "debug";
585
- break;
586
- }
587
- case "INFO": {
588
- this._jobLogger?.info(message, data);
589
- logLevel = "info";
590
- break;
591
- }
592
- case "WARN": {
593
- this._jobLogger?.warn(message, data);
594
- logLevel = "warn";
595
- break;
596
- }
597
- case "ERROR": {
598
- this._jobLogger?.error(message, data);
599
- logLevel = "error";
600
- break;
601
- }
602
- }
603
894
  if (import_core3.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
604
895
  await this.runTask([
605
896
  message,
606
897
  level
607
898
  ], async (task) => {
899
+ switch (level) {
900
+ case "LOG": {
901
+ this._jobLogger?.log(message, data);
902
+ logLevel = "log";
903
+ break;
904
+ }
905
+ case "DEBUG": {
906
+ this._jobLogger?.debug(message, data);
907
+ logLevel = "debug";
908
+ break;
909
+ }
910
+ case "INFO": {
911
+ this._jobLogger?.info(message, data);
912
+ logLevel = "info";
913
+ break;
914
+ }
915
+ case "WARN": {
916
+ this._jobLogger?.warn(message, data);
917
+ logLevel = "warn";
918
+ break;
919
+ }
920
+ case "ERROR": {
921
+ this._jobLogger?.error(message, data);
922
+ logLevel = "error";
923
+ break;
924
+ }
925
+ }
608
926
  }, {
609
927
  name: "log",
610
928
  icon: "log",
@@ -625,8 +943,8 @@ var IO = class {
625
943
  }
626
944
  });
627
945
  }
628
- async wait(key, seconds) {
629
- return await this.runTask(key, async (task) => {
946
+ async wait(cacheKey, seconds) {
947
+ return await this.runTask(cacheKey, async (task) => {
630
948
  }, {
631
949
  name: "wait",
632
950
  icon: "clock",
@@ -640,22 +958,23 @@ var IO = class {
640
958
  }
641
959
  });
642
960
  }
643
- async createStatus(key, initialStatus) {
644
- const id = typeof key === "string" ? key : key.join("-");
961
+ async createStatus(cacheKey, initialStatus) {
962
+ const id = typeof cacheKey === "string" ? cacheKey : cacheKey.join("-");
645
963
  const status = new TriggerStatus(id, this);
646
- await status.update(key, initialStatus);
964
+ await status.update(cacheKey, initialStatus);
647
965
  return status;
648
966
  }
649
- async backgroundFetch(key, url, requestInit, retry2) {
967
+ async backgroundFetch(cacheKey, url, requestInit, retry2, timeout) {
650
968
  const urlObject = new URL(url);
651
- return await this.runTask(key, async (task) => {
969
+ return await this.runTask(cacheKey, async (task) => {
652
970
  return task.output;
653
971
  }, {
654
972
  name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
655
973
  params: {
656
974
  url,
657
975
  requestInit,
658
- retry: retry2
976
+ retry: retry2,
977
+ timeout
659
978
  },
660
979
  operation: "fetch",
661
980
  icon: "background",
@@ -673,12 +992,21 @@ var IO = class {
673
992
  {
674
993
  label: "background",
675
994
  text: "true"
676
- }
677
- ]
995
+ },
996
+ ...timeout ? [
997
+ {
998
+ label: "timeout",
999
+ text: `${timeout.durationInMs}ms`
1000
+ }
1001
+ ] : []
1002
+ ],
1003
+ retry: {
1004
+ limit: 0
1005
+ }
678
1006
  });
679
1007
  }
680
- async sendEvent(key, event, options) {
681
- return await this.runTask(key, async (task) => {
1008
+ async sendEvent(cacheKey, event, options) {
1009
+ return await this.runTask(cacheKey, async (task) => {
682
1010
  return await this._triggerClient.sendEvent(event, options);
683
1011
  }, {
684
1012
  name: "sendEvent",
@@ -700,8 +1028,8 @@ var IO = class {
700
1028
  ]
701
1029
  });
702
1030
  }
703
- async getEvent(key, id) {
704
- return await this.runTask(key, async (task) => {
1031
+ async getEvent(cacheKey, id) {
1032
+ return await this.runTask(cacheKey, async (task) => {
705
1033
  return await this._triggerClient.getEvent(id);
706
1034
  }, {
707
1035
  name: "getEvent",
@@ -716,8 +1044,8 @@ var IO = class {
716
1044
  ]
717
1045
  });
718
1046
  }
719
- async cancelEvent(key, eventId) {
720
- return await this.runTask(key, async (task) => {
1047
+ async cancelEvent(cacheKey, eventId) {
1048
+ return await this.runTask(cacheKey, async (task) => {
721
1049
  return await this._triggerClient.cancelEvent(eventId);
722
1050
  }, {
723
1051
  name: "cancelEvent",
@@ -732,8 +1060,8 @@ var IO = class {
732
1060
  ]
733
1061
  });
734
1062
  }
735
- async updateSource(key, options) {
736
- return this.runTask(key, async (task) => {
1063
+ async updateSource(cacheKey, options) {
1064
+ return this.runTask(cacheKey, async (task) => {
737
1065
  return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
738
1066
  }, {
739
1067
  name: "Update Source",
@@ -752,8 +1080,8 @@ var IO = class {
752
1080
  }
753
1081
  });
754
1082
  }
755
- async registerInterval(key, dynamicSchedule, id, options) {
756
- return await this.runTask(key, async (task) => {
1083
+ async registerInterval(cacheKey, dynamicSchedule, id, options) {
1084
+ return await this.runTask(cacheKey, async (task) => {
757
1085
  return dynamicSchedule.register(id, {
758
1086
  type: "interval",
759
1087
  options
@@ -777,8 +1105,8 @@ var IO = class {
777
1105
  params: options
778
1106
  });
779
1107
  }
780
- async unregisterInterval(key, dynamicSchedule, id) {
781
- return await this.runTask(key, async (task) => {
1108
+ async unregisterInterval(cacheKey, dynamicSchedule, id) {
1109
+ return await this.runTask(cacheKey, async (task) => {
782
1110
  return dynamicSchedule.unregister(id);
783
1111
  }, {
784
1112
  name: "unregister-interval",
@@ -794,8 +1122,8 @@ var IO = class {
794
1122
  ]
795
1123
  });
796
1124
  }
797
- async registerCron(key, dynamicSchedule, id, options) {
798
- return await this.runTask(key, async (task) => {
1125
+ async registerCron(cacheKey, dynamicSchedule, id, options) {
1126
+ return await this.runTask(cacheKey, async (task) => {
799
1127
  return dynamicSchedule.register(id, {
800
1128
  type: "cron",
801
1129
  options
@@ -819,8 +1147,8 @@ var IO = class {
819
1147
  params: options
820
1148
  });
821
1149
  }
822
- async unregisterCron(key, dynamicSchedule, id) {
823
- return await this.runTask(key, async (task) => {
1150
+ async unregisterCron(cacheKey, dynamicSchedule, id) {
1151
+ return await this.runTask(cacheKey, async (task) => {
824
1152
  return dynamicSchedule.unregister(id);
825
1153
  }, {
826
1154
  name: "unregister-cron",
@@ -836,8 +1164,8 @@ var IO = class {
836
1164
  ]
837
1165
  });
838
1166
  }
839
- async registerTrigger(key, trigger, id, params) {
840
- return await this.runTask(key, async (task) => {
1167
+ async registerTrigger(cacheKey, trigger, id, params) {
1168
+ return await this.runTask(cacheKey, async (task) => {
841
1169
  const registration = await this.runTask("register-source", async (subtask1) => {
842
1170
  return trigger.register(id, params);
843
1171
  }, {
@@ -862,45 +1190,103 @@ var IO = class {
862
1190
  params
863
1191
  });
864
1192
  }
865
- async getAuth(key, clientId) {
1193
+ async getAuth(cacheKey, clientId) {
866
1194
  if (!clientId) {
867
1195
  return;
868
1196
  }
869
- return this.runTask(key, async (task) => {
1197
+ return this.runTask(cacheKey, async (task) => {
870
1198
  return await this._triggerClient.getAuth(clientId);
871
1199
  }, {
872
1200
  name: "get-auth"
873
1201
  });
874
1202
  }
875
- async runTask(key, callback, options, onError) {
1203
+ async parallel(cacheKey, items, callback, options) {
1204
+ const results = await this.runTask(cacheKey, async (task) => {
1205
+ const outcomes = await Promise.allSettled(items.map((item, index) => spaceOut(() => callback(item, index), index, 15)));
1206
+ if (outcomes.every((outcome) => outcome.status === "fulfilled")) {
1207
+ return outcomes.map((outcome) => outcome.value);
1208
+ }
1209
+ const nonInternalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && !isTriggerError(outcome.reason)).map((outcome) => outcome);
1210
+ if (nonInternalErrors.length > 0) {
1211
+ throw nonInternalErrors[0].reason;
1212
+ }
1213
+ const internalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && isTriggerError(outcome.reason)).map((outcome) => outcome).map((outcome) => outcome.reason);
1214
+ throw new ResumeWithParallelTaskError(task, internalErrors);
1215
+ }, {
1216
+ name: "parallel",
1217
+ parallel: true,
1218
+ ...options ?? {}
1219
+ });
1220
+ return results;
1221
+ }
1222
+ async runTask(cacheKey, callback, options, onError) {
1223
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "start_task", 500);
876
1224
  const parentId = this._taskStorage.getStore()?.taskId;
877
1225
  if (parentId) {
878
1226
  this._logger.debug("Using parent task", {
879
1227
  parentId,
880
- key,
1228
+ cacheKey,
881
1229
  options
882
1230
  });
883
1231
  }
884
1232
  const idempotencyKey = await generateIdempotencyKey([
885
1233
  this._id,
886
1234
  parentId ?? "",
887
- key
1235
+ cacheKey
888
1236
  ].flat());
1237
+ if (this._visitedCacheKeys.has(idempotencyKey)) {
1238
+ if (typeof cacheKey === "string") {
1239
+ throw new Error(`Task with cacheKey "${cacheKey}" has already been executed in this run. Each task must have a unique cacheKey.`);
1240
+ } else {
1241
+ throw new Error(`Task with cacheKey "${cacheKey.join("-")}" has already been executed in this run. Each task must have a unique cacheKey.`);
1242
+ }
1243
+ }
1244
+ this._visitedCacheKeys.add(idempotencyKey);
889
1245
  const cachedTask = this._cachedTasks.get(idempotencyKey);
890
1246
  if (cachedTask && cachedTask.status === "COMPLETED") {
891
1247
  this._logger.debug("Using completed cached task", {
892
- idempotencyKey,
893
- cachedTask
1248
+ idempotencyKey
894
1249
  });
1250
+ this._stats.cachedTaskHits++;
895
1251
  return cachedTask.output;
896
1252
  }
897
- const task = await this._apiClient.runTask(this._id, {
1253
+ if (options?.noop && this._noopTasksBloomFilter) {
1254
+ if (this._noopTasksBloomFilter.test(idempotencyKey)) {
1255
+ this._logger.debug("task idempotency key exists in noopTasksBloomFilter", {
1256
+ idempotencyKey
1257
+ });
1258
+ this._stats.noopCachedTaskHits++;
1259
+ return {};
1260
+ }
1261
+ }
1262
+ const response = await this._apiClient.runTask(this._id, {
898
1263
  idempotencyKey,
899
- displayKey: typeof key === "string" ? key : key.join("."),
1264
+ displayKey: typeof cacheKey === "string" ? cacheKey : void 0,
900
1265
  noop: false,
901
1266
  ...options ?? {},
902
1267
  parentId
1268
+ }, {
1269
+ cachedTasksCursor: this._cachedTasksCursor
903
1270
  });
1271
+ const task = response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1272
+ if (task.forceYield) {
1273
+ this._logger.debug("Forcing yield after run task", {
1274
+ idempotencyKey
1275
+ });
1276
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_run_task");
1277
+ }
1278
+ if (response.version === import_core3.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
1279
+ this._cachedTasksCursor = response.body.cachedTasks?.cursor;
1280
+ for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
1281
+ if (!this._cachedTasks.has(cachedTask2.idempotencyKey)) {
1282
+ this._cachedTasks.set(cachedTask2.idempotencyKey, cachedTask2);
1283
+ this._logger.debug("Injecting lazy loaded task into task cache", {
1284
+ idempotencyKey: cachedTask2.idempotencyKey
1285
+ });
1286
+ this._stats.lazyLoadedCachedTasks++;
1287
+ }
1288
+ }
1289
+ }
904
1290
  if (task.status === "CANCELED") {
905
1291
  this._logger.debug("Task canceled", {
906
1292
  idempotencyKey,
@@ -909,11 +1295,18 @@ var IO = class {
909
1295
  throw new CanceledWithTaskError(task);
910
1296
  }
911
1297
  if (task.status === "COMPLETED") {
912
- this._logger.debug("Using task output", {
913
- idempotencyKey,
914
- task
915
- });
916
- __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1298
+ if (task.noop) {
1299
+ this._logger.debug("Noop Task completed", {
1300
+ idempotencyKey
1301
+ });
1302
+ this._noopTasksBloomFilter?.add(task.idempotencyKey);
1303
+ } else {
1304
+ this._logger.debug("Cache miss", {
1305
+ idempotencyKey
1306
+ });
1307
+ this._stats.cachedTaskMisses++;
1308
+ __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1309
+ }
917
1310
  return task.output;
918
1311
  }
919
1312
  if (task.status === "ERRORED") {
@@ -921,38 +1314,41 @@ var IO = class {
921
1314
  idempotencyKey,
922
1315
  task
923
1316
  });
924
- throw new Error(task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
925
- }
926
- if (task.status === "WAITING") {
927
- this._logger.debug("Task waiting", {
928
- idempotencyKey,
929
- task
930
- });
931
- throw new ResumeWithTaskError(task);
932
- }
933
- if (task.status === "RUNNING" && typeof task.operation === "string") {
934
- this._logger.debug("Task running operation", {
935
- idempotencyKey,
936
- task
937
- });
938
- throw new ResumeWithTaskError(task);
1317
+ throw new ErrorWithTask(task, task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
939
1318
  }
1319
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_execute_task", 1500);
940
1320
  const executeTask = /* @__PURE__ */ __name(async () => {
941
1321
  try {
942
1322
  const result = await callback(task, this);
943
- const output = import_core3.SerializableJsonSchema.parse(result);
1323
+ if (task.status === "WAITING" && task.callbackUrl) {
1324
+ this._logger.debug("Waiting for remote callback", {
1325
+ idempotencyKey,
1326
+ task
1327
+ });
1328
+ return {};
1329
+ }
1330
+ const output = this._outputSerializer.serialize(result);
944
1331
  this._logger.debug("Completing using output", {
945
1332
  idempotencyKey,
946
1333
  task
947
1334
  });
1335
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
948
1336
  const completedTask = await this._apiClient.completeTask(this._id, task.id, {
949
- output: output ?? void 0,
1337
+ output,
950
1338
  properties: task.outputProperties ?? void 0
951
1339
  });
1340
+ if (completedTask.forceYield) {
1341
+ this._logger.debug("Forcing yield after task completed", {
1342
+ idempotencyKey
1343
+ });
1344
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_complete_task");
1345
+ }
1346
+ this._stats.executedTasks++;
952
1347
  if (completedTask.status === "CANCELED") {
953
1348
  throw new CanceledWithTaskError(completedTask);
954
1349
  }
955
- return output;
1350
+ __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "after_complete_task", 500);
1351
+ return this._outputSerializer.deserialize(output);
956
1352
  } catch (error) {
957
1353
  if (isTriggerError(error)) {
958
1354
  throw error;
@@ -981,6 +1377,11 @@ var IO = class {
981
1377
  error = innerError;
982
1378
  }
983
1379
  }
1380
+ if (error instanceof ErrorWithTask) {
1381
+ await this._apiClient.failTask(this._id, task.id, {
1382
+ error: error.cause.output
1383
+ });
1384
+ }
984
1385
  const parsedError = import_core3.ErrorWithStackSchema.safeParse(error);
985
1386
  if (options?.retry && !skipRetrying) {
986
1387
  const retryAt = (0, import_core2.calculateRetryAt)(options.retry, task.attempts - 1);
@@ -995,20 +1396,50 @@ var IO = class {
995
1396
  error: parsedError.data
996
1397
  });
997
1398
  } else {
1399
+ const message = typeof error === "string" ? error : JSON.stringify(error);
998
1400
  await this._apiClient.failTask(this._id, task.id, {
999
1401
  error: {
1000
- message: JSON.stringify(error),
1001
- name: "Unknown Error"
1402
+ name: "Unknown error",
1403
+ message
1002
1404
  }
1003
1405
  });
1004
1406
  }
1005
1407
  throw error;
1006
1408
  }
1007
1409
  }, "executeTask");
1410
+ if (task.status === "WAITING") {
1411
+ this._logger.debug("Task waiting", {
1412
+ idempotencyKey,
1413
+ task
1414
+ });
1415
+ if (task.callbackUrl) {
1416
+ await this._taskStorage.run({
1417
+ taskId: task.id
1418
+ }, executeTask);
1419
+ }
1420
+ throw new ResumeWithTaskError(task);
1421
+ }
1422
+ if (task.status === "RUNNING" && typeof task.operation === "string") {
1423
+ this._logger.debug("Task running operation", {
1424
+ idempotencyKey,
1425
+ task
1426
+ });
1427
+ throw new ResumeWithTaskError(task);
1428
+ }
1008
1429
  return this._taskStorage.run({
1009
1430
  taskId: task.id
1010
1431
  }, executeTask);
1011
1432
  }
1433
+ yield(cacheKey) {
1434
+ if (!(0, import_core3.supportsFeature)("yieldExecution", this._serverVersion)) {
1435
+ 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.");
1436
+ return;
1437
+ }
1438
+ if (this._yieldedExecutions.includes(cacheKey)) {
1439
+ return;
1440
+ }
1441
+ throw new YieldExecutionError(cacheKey);
1442
+ }
1012
1443
  async try(tryCallback, catchCallback) {
1013
1444
  try {
1014
1445
  return await tryCallback();
@@ -1025,6 +1456,39 @@ _addToCachedTasks = new WeakSet();
1025
1456
  addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
1026
1457
  this._cachedTasks.set(task.idempotencyKey, task);
1027
1458
  }, "#addToCachedTasks");
1459
+ _detectAutoYield = new WeakSet();
1460
+ detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task1, output) {
1461
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1462
+ if (timeRemaining && timeRemaining < threshold) {
1463
+ if (task1) {
1464
+ throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], {
1465
+ location,
1466
+ timeRemaining,
1467
+ timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1468
+ }, output);
1469
+ } else {
1470
+ throw new AutoYieldExecutionError(location, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1471
+ }
1472
+ }
1473
+ }, "#detectAutoYield");
1474
+ _forceYield = new WeakSet();
1475
+ forceYield_fn = /* @__PURE__ */ __name(function(location1) {
1476
+ const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1477
+ if (timeRemaining) {
1478
+ throw new AutoYieldExecutionError(location1, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1479
+ }
1480
+ }, "#forceYield");
1481
+ _getTimeElapsed = new WeakSet();
1482
+ getTimeElapsed_fn = /* @__PURE__ */ __name(function() {
1483
+ return performance.now() - this._timeOrigin;
1484
+ }, "#getTimeElapsed");
1485
+ _getRemainingTimeInMillis = new WeakSet();
1486
+ getRemainingTimeInMillis_fn = /* @__PURE__ */ __name(function() {
1487
+ if (this._executionTimeout) {
1488
+ return this._executionTimeout - (performance.now() - this._timeOrigin);
1489
+ }
1490
+ return void 0;
1491
+ }, "#getRemainingTimeInMillis");
1028
1492
  async function generateIdempotencyKey(keyMaterial) {
1029
1493
  const keys = keyMaterial.map((key2) => {
1030
1494
  if (typeof key2 === "string") {
@@ -1078,6 +1542,11 @@ var IOLogger = class {
1078
1542
  }
1079
1543
  };
1080
1544
  __name(IOLogger, "IOLogger");
1545
+ async function spaceOut(callback, index, delay) {
1546
+ await new Promise((resolve) => setTimeout(resolve, index * delay));
1547
+ return await callback();
1548
+ }
1549
+ __name(spaceOut, "spaceOut");
1081
1550
 
1082
1551
  // src/ioWithIntegrations.ts
1083
1552
  function createIOWithIntegrations(io, auths, integrations) {
@@ -1108,24 +1577,6 @@ function createIOWithIntegrations(io, auths, integrations) {
1108
1577
  }
1109
1578
  __name(createIOWithIntegrations, "createIOWithIntegrations");
1110
1579
 
1111
- // src/utils/typedAsyncLocalStorage.ts
1112
- var import_node_async_hooks2 = require("async_hooks");
1113
- var TypedAsyncLocalStorage = class {
1114
- constructor() {
1115
- this.storage = new import_node_async_hooks2.AsyncLocalStorage();
1116
- }
1117
- runWith(context, fn) {
1118
- return this.storage.run(context, fn);
1119
- }
1120
- getStore() {
1121
- return this.storage.getStore();
1122
- }
1123
- };
1124
- __name(TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
1125
-
1126
- // src/runLocalStorage.ts
1127
- var runLocalStorage = new TypedAsyncLocalStorage();
1128
-
1129
1580
  // src/triggers/dynamic.ts
1130
1581
  var import_core4 = require("@trigger.dev/core");
1131
1582
  var _client, _options2;
@@ -1187,7 +1638,7 @@ var DynamicTrigger = class {
1187
1638
  key,
1188
1639
  "register"
1189
1640
  ], async (task) => {
1190
- return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options));
1641
+ return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options), task.idempotencyKey);
1191
1642
  }, {
1192
1643
  name: "Register Dynamic Trigger",
1193
1644
  properties: [
@@ -1475,6 +1926,9 @@ var DynamicSchedule = class {
1475
1926
  };
1476
1927
  __name(DynamicSchedule, "DynamicSchedule");
1477
1928
 
1929
+ // package.json
1930
+ var version = "0.0.0-invoke-trigger-20231103104037";
1931
+
1478
1932
  // src/triggerClient.ts
1479
1933
  var registerSourceEvent = {
1480
1934
  name: import_core7.REGISTER_SOURCE_EVENT_V2,
@@ -1483,11 +1937,12 @@ var registerSourceEvent = {
1483
1937
  icon: "register-source",
1484
1938
  parsePayload: import_core7.RegisterSourceEventSchemaV2.parse
1485
1939
  };
1486
- 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;
1940
+ var _options4, _registeredJobs, _registeredSources, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _authResolvers, _client2, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_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_fn;
1487
1941
  var TriggerClient = class {
1488
1942
  constructor(options) {
1489
1943
  __privateAdd(this, _preprocessRun);
1490
1944
  __privateAdd(this, _executeJob);
1945
+ __privateAdd(this, _convertErrorToExecutionResponse);
1491
1946
  __privateAdd(this, _createRunContext);
1492
1947
  __privateAdd(this, _createPreprocessRunContext);
1493
1948
  __privateAdd(this, _handleHttpSourceRequest);
@@ -1497,6 +1952,8 @@ var TriggerClient = class {
1497
1952
  __privateAdd(this, _buildJobIndex);
1498
1953
  __privateAdd(this, _buildJobIntegrations);
1499
1954
  __privateAdd(this, _buildJobIntegration);
1955
+ __privateAdd(this, _logIOStats);
1956
+ __privateAdd(this, _standardResponseHeaders);
1500
1957
  __privateAdd(this, _options4, void 0);
1501
1958
  __privateAdd(this, _registeredJobs, {});
1502
1959
  __privateAdd(this, _registeredSources, {});
@@ -1510,15 +1967,19 @@ var TriggerClient = class {
1510
1967
  this.id = options.id;
1511
1968
  __privateSet(this, _options4, options);
1512
1969
  __privateSet(this, _client2, new ApiClient(__privateGet(this, _options4)));
1513
- __privateSet(this, _internalLogger, new import_core7.Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log"));
1970
+ __privateSet(this, _internalLogger, new import_core7.Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log", [
1971
+ "output",
1972
+ "noopTasksSet"
1973
+ ]));
1514
1974
  }
1515
- async handleRequest(request) {
1975
+ async handleRequest(request, timeOrigin = performance.now()) {
1516
1976
  __privateGet(this, _internalLogger).debug("handling request", {
1517
1977
  url: request.url,
1518
1978
  headers: Object.fromEntries(request.headers.entries()),
1519
1979
  method: request.method
1520
1980
  });
1521
1981
  const apiKey = request.headers.get("x-trigger-api-key");
1982
+ const triggerVersion = request.headers.get("x-trigger-version");
1522
1983
  const authorization = this.authorized(apiKey);
1523
1984
  switch (authorization) {
1524
1985
  case "authorized": {
@@ -1529,7 +1990,8 @@ var TriggerClient = class {
1529
1990
  status: 401,
1530
1991
  body: {
1531
1992
  message: "Unauthorized: client missing apiKey"
1532
- }
1993
+ },
1994
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1533
1995
  };
1534
1996
  }
1535
1997
  case "missing-header": {
@@ -1537,7 +1999,8 @@ var TriggerClient = class {
1537
1999
  status: 401,
1538
2000
  body: {
1539
2001
  message: "Unauthorized: missing x-trigger-api-key header"
1540
- }
2002
+ },
2003
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1541
2004
  };
1542
2005
  }
1543
2006
  case "unauthorized": {
@@ -1545,7 +2008,8 @@ var TriggerClient = class {
1545
2008
  status: 401,
1546
2009
  body: {
1547
2010
  message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`
1548
- }
2011
+ },
2012
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1549
2013
  };
1550
2014
  }
1551
2015
  }
@@ -1554,7 +2018,8 @@ var TriggerClient = class {
1554
2018
  status: 405,
1555
2019
  body: {
1556
2020
  message: "Method not allowed (only POST is allowed)"
1557
- }
2021
+ },
2022
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1558
2023
  };
1559
2024
  }
1560
2025
  const action = request.headers.get("x-trigger-action");
@@ -1563,7 +2028,8 @@ var TriggerClient = class {
1563
2028
  status: 400,
1564
2029
  body: {
1565
2030
  message: "Missing x-trigger-action header"
1566
- }
2031
+ },
2032
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1567
2033
  };
1568
2034
  }
1569
2035
  switch (action) {
@@ -1575,7 +2041,8 @@ var TriggerClient = class {
1575
2041
  body: {
1576
2042
  ok: false,
1577
2043
  error: "Missing endpoint ID"
1578
- }
2044
+ },
2045
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1579
2046
  };
1580
2047
  }
1581
2048
  if (this.id !== endpointId) {
@@ -1584,14 +2051,16 @@ var TriggerClient = class {
1584
2051
  body: {
1585
2052
  ok: false,
1586
2053
  error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`
1587
- }
2054
+ },
2055
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1588
2056
  };
1589
2057
  }
1590
2058
  return {
1591
2059
  status: 200,
1592
2060
  body: {
1593
2061
  ok: true
1594
- }
2062
+ },
2063
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1595
2064
  };
1596
2065
  }
1597
2066
  case "INDEX_ENDPOINT": {
@@ -1613,7 +2082,8 @@ var TriggerClient = class {
1613
2082
  };
1614
2083
  return {
1615
2084
  status: 200,
1616
- body
2085
+ body,
2086
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1617
2087
  };
1618
2088
  }
1619
2089
  case "INITIALIZE_TRIGGER": {
@@ -1638,7 +2108,8 @@ var TriggerClient = class {
1638
2108
  }
1639
2109
  return {
1640
2110
  status: 200,
1641
- body: dynamicTrigger.registeredTriggerForParams(body.data.params)
2111
+ body: dynamicTrigger.registeredTriggerForParams(body.data.params),
2112
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1642
2113
  };
1643
2114
  }
1644
2115
  case "EXECUTE_JOB": {
@@ -1661,10 +2132,17 @@ var TriggerClient = class {
1661
2132
  }
1662
2133
  };
1663
2134
  }
1664
- const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job);
2135
+ const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job, timeOrigin, triggerVersion);
2136
+ __privateGet(this, _internalLogger).debug("executed job", {
2137
+ results,
2138
+ job: job.id,
2139
+ version: job.version,
2140
+ triggerVersion
2141
+ });
1665
2142
  return {
1666
2143
  status: 200,
1667
- body: results
2144
+ body: results,
2145
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1668
2146
  };
1669
2147
  }
1670
2148
  case "PREPROCESS_RUN": {
@@ -1693,7 +2171,8 @@ var TriggerClient = class {
1693
2171
  body: {
1694
2172
  abort: results.abort,
1695
2173
  properties: results.properties
1696
- }
2174
+ },
2175
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1697
2176
  };
1698
2177
  }
1699
2178
  case "DELIVER_HTTP_SOURCE_REQUEST": {
@@ -1742,7 +2221,8 @@ var TriggerClient = class {
1742
2221
  events,
1743
2222
  response,
1744
2223
  metadata
1745
- }
2224
+ },
2225
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1746
2226
  };
1747
2227
  }
1748
2228
  case "VALIDATE": {
@@ -1751,7 +2231,20 @@ var TriggerClient = class {
1751
2231
  body: {
1752
2232
  ok: true,
1753
2233
  endpointId: this.id
1754
- }
2234
+ },
2235
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
2236
+ };
2237
+ }
2238
+ case "PROBE_EXECUTION_TIMEOUT": {
2239
+ const json = await request.json();
2240
+ const timeout = json?.timeout ?? 15 * 60 * 1e3;
2241
+ await new Promise((resolve) => setTimeout(resolve, timeout));
2242
+ return {
2243
+ status: 200,
2244
+ body: {
2245
+ ok: true
2246
+ },
2247
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1755
2248
  };
1756
2249
  }
1757
2250
  }
@@ -1759,7 +2252,8 @@ var TriggerClient = class {
1759
2252
  status: 405,
1760
2253
  body: {
1761
2254
  message: "Method not allowed"
1762
- }
2255
+ },
2256
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
1763
2257
  };
1764
2258
  }
1765
2259
  defineJob(options) {
@@ -1889,8 +2383,8 @@ var TriggerClient = class {
1889
2383
  });
1890
2384
  __privateGet(this, _registeredSchedules)[key] = jobs;
1891
2385
  }
1892
- async registerTrigger(id, key, options) {
1893
- return __privateGet(this, _client2).registerTrigger(this.id, id, key, options);
2386
+ async registerTrigger(id, key, options, idempotencyKey) {
2387
+ return __privateGet(this, _client2).registerTrigger(this.id, id, key, options, idempotencyKey);
1894
2388
  }
1895
2389
  async getAuth(id) {
1896
2390
  return __privateGet(this, _client2).getAuth(this.id, id);
@@ -1901,6 +2395,9 @@ var TriggerClient = class {
1901
2395
  async cancelEvent(eventId) {
1902
2396
  return __privateGet(this, _client2).cancelEvent(eventId);
1903
2397
  }
2398
+ async cancelRunsForEvent(eventId) {
2399
+ return __privateGet(this, _client2).cancelRunsForEvent(eventId);
2400
+ }
1904
2401
  async updateStatus(runId, id, status) {
1905
2402
  return __privateGet(this, _client2).updateStatus(runId, id, status);
1906
2403
  }
@@ -1916,12 +2413,18 @@ var TriggerClient = class {
1916
2413
  async getRun(runId, options) {
1917
2414
  return __privateGet(this, _client2).getRun(runId, options);
1918
2415
  }
2416
+ async cancelRun(runId) {
2417
+ return __privateGet(this, _client2).cancelRun(runId);
2418
+ }
1919
2419
  async getRuns(jobSlug, options) {
1920
2420
  return __privateGet(this, _client2).getRuns(jobSlug, options);
1921
2421
  }
1922
2422
  async getRunStatuses(runId) {
1923
2423
  return __privateGet(this, _client2).getRunStatuses(runId);
1924
2424
  }
2425
+ async invokeJob(jobId, payload, options) {
2426
+ return __privateGet(this, _client2).invokeJob(jobId, payload, options);
2427
+ }
1925
2428
  authorized(apiKey) {
1926
2429
  if (typeof apiKey !== "string") {
1927
2430
  return "missing-header";
@@ -1958,22 +2461,29 @@ preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
1958
2461
  };
1959
2462
  }, "#preprocessRun");
1960
2463
  _executeJob = new WeakSet();
1961
- executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
2464
+ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, triggerVersion) {
1962
2465
  __privateGet(this, _internalLogger).debug("executing job", {
1963
2466
  execution: body1,
1964
2467
  job: job1.id,
1965
- version: job1.version
2468
+ version: job1.version,
2469
+ triggerVersion
1966
2470
  });
1967
2471
  const context = __privateMethod(this, _createRunContext, createRunContext_fn).call(this, body1);
1968
2472
  const io = new IO({
1969
2473
  id: body1.run.id,
1970
2474
  cachedTasks: body1.tasks,
2475
+ cachedTasksCursor: body1.cachedTaskCursor,
2476
+ yieldedExecutions: body1.yieldedExecutions ?? [],
2477
+ noopTasksSet: body1.noopTasksSet,
1971
2478
  apiClient: __privateGet(this, _client2),
1972
2479
  logger: __privateGet(this, _internalLogger),
1973
2480
  client: this,
1974
2481
  context,
1975
2482
  jobLogLevel: job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info",
1976
- jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new import_core7.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0
2483
+ jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new import_core7.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0,
2484
+ serverVersion: triggerVersion,
2485
+ timeOrigin,
2486
+ executionTimeout: body1.runChunkExecutionLimit
1977
2487
  });
1978
2488
  const resolvedConnections = await __privateMethod(this, _resolveConnections, resolveConnections_fn).call(this, context, job1.options.integrations, body1.connections);
1979
2489
  if (!resolvedConnections.ok) {
@@ -1990,72 +2500,137 @@ executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1) {
1990
2500
  }, () => {
1991
2501
  return job1.options.run(job1.trigger.event.parsePayload(body1.event.payload ?? {}), ioWithConnections, context);
1992
2502
  });
2503
+ if (__privateGet(this, _options4).verbose) {
2504
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2505
+ }
1993
2506
  return {
1994
2507
  status: "SUCCESS",
1995
2508
  output
1996
2509
  };
1997
2510
  } catch (error) {
1998
- if (error instanceof ParsedPayloadSchemaError) {
1999
- return {
2000
- status: "INVALID_PAYLOAD",
2001
- errors: error.schemaErrors
2002
- };
2003
- }
2004
- if (error instanceof ResumeWithTaskError) {
2005
- return {
2006
- status: "RESUME_WITH_TASK",
2007
- task: error.task
2008
- };
2511
+ if (__privateGet(this, _options4).verbose) {
2512
+ __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
2009
2513
  }
2010
- if (error instanceof RetryWithTaskError) {
2514
+ if (error instanceof ResumeWithParallelTaskError) {
2011
2515
  return {
2012
- status: "RETRY_WITH_TASK",
2516
+ status: "RESUME_WITH_PARALLEL_TASK",
2013
2517
  task: error.task,
2014
- error: error.cause,
2015
- retryAt: error.retryAt
2016
- };
2017
- }
2018
- if (error instanceof CanceledWithTaskError) {
2019
- return {
2020
- status: "CANCELED",
2021
- task: error.task
2518
+ childErrors: error.childErrors.map((childError) => {
2519
+ return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, childError, body1);
2520
+ })
2022
2521
  };
2023
2522
  }
2024
- if (error instanceof RetryWithTaskError) {
2025
- const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause);
2026
- if (errorWithStack2.success) {
2027
- return {
2028
- status: "ERROR",
2029
- error: errorWithStack2.data,
2030
- task: error.task
2031
- };
2523
+ return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, error, body1);
2524
+ }
2525
+ }, "#executeJob");
2526
+ _convertErrorToExecutionResponse = new WeakSet();
2527
+ convertErrorToExecutionResponse_fn = /* @__PURE__ */ __name(function(error, body2) {
2528
+ if (error instanceof AutoYieldExecutionError) {
2529
+ return {
2530
+ status: "AUTO_YIELD_EXECUTION",
2531
+ location: error.location,
2532
+ timeRemaining: error.timeRemaining,
2533
+ timeElapsed: error.timeElapsed,
2534
+ limit: body2.runChunkExecutionLimit
2535
+ };
2536
+ }
2537
+ if (error instanceof AutoYieldWithCompletedTaskExecutionError) {
2538
+ return {
2539
+ status: "AUTO_YIELD_EXECUTION_WITH_COMPLETED_TASK",
2540
+ id: error.id,
2541
+ properties: error.properties,
2542
+ output: error.output,
2543
+ data: {
2544
+ ...error.data,
2545
+ limit: body2.runChunkExecutionLimit
2032
2546
  }
2547
+ };
2548
+ }
2549
+ if (error instanceof YieldExecutionError) {
2550
+ return {
2551
+ status: "YIELD_EXECUTION",
2552
+ key: error.key
2553
+ };
2554
+ }
2555
+ if (error instanceof ParsedPayloadSchemaError) {
2556
+ return {
2557
+ status: "INVALID_PAYLOAD",
2558
+ errors: error.schemaErrors
2559
+ };
2560
+ }
2561
+ if (error instanceof ResumeWithTaskError) {
2562
+ return {
2563
+ status: "RESUME_WITH_TASK",
2564
+ task: error.task
2565
+ };
2566
+ }
2567
+ if (error instanceof RetryWithTaskError) {
2568
+ return {
2569
+ status: "RETRY_WITH_TASK",
2570
+ task: error.task,
2571
+ error: error.cause,
2572
+ retryAt: error.retryAt
2573
+ };
2574
+ }
2575
+ if (error instanceof CanceledWithTaskError) {
2576
+ return {
2577
+ status: "CANCELED",
2578
+ task: error.task
2579
+ };
2580
+ }
2581
+ if (error instanceof ErrorWithTask) {
2582
+ const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause.output);
2583
+ if (errorWithStack2.success) {
2033
2584
  return {
2034
2585
  status: "ERROR",
2035
- error: {
2036
- message: "Unknown error"
2037
- },
2038
- task: error.task
2586
+ error: errorWithStack2.data,
2587
+ task: error.cause
2039
2588
  };
2040
2589
  }
2041
- const errorWithStack = import_core7.ErrorWithStackSchema.safeParse(error);
2042
- if (errorWithStack.success) {
2590
+ return {
2591
+ status: "ERROR",
2592
+ error: {
2593
+ message: JSON.stringify(error.cause.output)
2594
+ },
2595
+ task: error.cause
2596
+ };
2597
+ }
2598
+ if (error instanceof RetryWithTaskError) {
2599
+ const errorWithStack2 = import_core7.ErrorWithStackSchema.safeParse(error.cause);
2600
+ if (errorWithStack2.success) {
2043
2601
  return {
2044
2602
  status: "ERROR",
2045
- error: errorWithStack.data
2603
+ error: errorWithStack2.data,
2604
+ task: error.task
2046
2605
  };
2047
2606
  }
2048
2607
  return {
2049
2608
  status: "ERROR",
2050
2609
  error: {
2051
2610
  message: "Unknown error"
2052
- }
2611
+ },
2612
+ task: error.task
2053
2613
  };
2054
2614
  }
2055
- }, "#executeJob");
2615
+ const errorWithStack = import_core7.ErrorWithStackSchema.safeParse(error);
2616
+ if (errorWithStack.success) {
2617
+ return {
2618
+ status: "ERROR",
2619
+ error: errorWithStack.data
2620
+ };
2621
+ }
2622
+ const message = typeof error === "string" ? error : JSON.stringify(error);
2623
+ return {
2624
+ status: "ERROR",
2625
+ error: {
2626
+ name: "Unknown error",
2627
+ message
2628
+ }
2629
+ };
2630
+ }, "#convertErrorToExecutionResponse");
2056
2631
  _createRunContext = new WeakSet();
2057
2632
  createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2058
- const { event, organization, environment, job, run, source } = execution;
2633
+ const { event, organization, project, environment, job, run, source } = execution;
2059
2634
  return {
2060
2635
  event: {
2061
2636
  id: event.id,
@@ -2064,6 +2639,11 @@ createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2064
2639
  timestamp: event.timestamp
2065
2640
  },
2066
2641
  organization,
2642
+ project: project ?? {
2643
+ id: "unknown",
2644
+ name: "unknown",
2645
+ slug: "unknown"
2646
+ },
2067
2647
  environment,
2068
2648
  job,
2069
2649
  run,
@@ -2072,8 +2652,8 @@ createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
2072
2652
  };
2073
2653
  }, "#createRunContext");
2074
2654
  _createPreprocessRunContext = new WeakSet();
2075
- createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body2) {
2076
- const { event, organization, environment, job, run, account } = body2;
2655
+ createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body3) {
2656
+ const { event, organization, environment, job, run, account } = body3;
2077
2657
  return {
2078
2658
  event: {
2079
2659
  id: event.id,
@@ -2318,6 +2898,20 @@ buildJobIntegration_fn = /* @__PURE__ */ __name(function(integration1) {
2318
2898
  authSource
2319
2899
  };
2320
2900
  }, "#buildJobIntegration");
2901
+ _logIOStats = new WeakSet();
2902
+ logIOStats_fn = /* @__PURE__ */ __name(function(stats) {
2903
+ __privateGet(this, _internalLogger).debug("IO stats", {
2904
+ stats
2905
+ });
2906
+ }, "#logIOStats");
2907
+ _standardResponseHeaders = new WeakSet();
2908
+ standardResponseHeaders_fn = /* @__PURE__ */ __name(function(start) {
2909
+ return {
2910
+ "Trigger-Version": import_core7.API_VERSIONS.LAZY_LOADED_CACHED_TASKS,
2911
+ "Trigger-SDK-Version": version,
2912
+ "X-Trigger-Request-Timing": `dur=${performance.now() - start / 1e3}`
2913
+ };
2914
+ }, "#standardResponseHeaders");
2321
2915
  function dynamicTriggerRegisterSourceJobId(id) {
2322
2916
  return `register-dynamic-trigger-${id}`;
2323
2917
  }
@@ -2548,6 +3142,60 @@ var MissingConnectionResolvedNotification = class {
2548
3142
  };
2549
3143
  __name(MissingConnectionResolvedNotification, "MissingConnectionResolvedNotification");
2550
3144
 
3145
+ // src/triggers/invokeTrigger.ts
3146
+ var _options5;
3147
+ var InvokeTrigger = class {
3148
+ constructor(options) {
3149
+ __privateAdd(this, _options5, void 0);
3150
+ __privateSet(this, _options5, options);
3151
+ }
3152
+ toJSON() {
3153
+ return {
3154
+ type: "invoke"
3155
+ };
3156
+ }
3157
+ get event() {
3158
+ return {
3159
+ name: "invoke",
3160
+ title: "Manual Invoke",
3161
+ source: "trigger.dev",
3162
+ examples: __privateGet(this, _options5).examples ?? [],
3163
+ icon: "trigger",
3164
+ parsePayload: (rawPayload) => {
3165
+ if (__privateGet(this, _options5).schema) {
3166
+ const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
3167
+ if (!results.success) {
3168
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
3169
+ }
3170
+ return results.data;
3171
+ }
3172
+ return rawPayload;
3173
+ },
3174
+ parseInvokePayload: (rawPayload) => {
3175
+ if (__privateGet(this, _options5).schema) {
3176
+ const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
3177
+ if (!results.success) {
3178
+ throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
3179
+ }
3180
+ return results.data;
3181
+ }
3182
+ return rawPayload;
3183
+ }
3184
+ };
3185
+ }
3186
+ attachToJob(triggerClient, job) {
3187
+ }
3188
+ get preprocessRuns() {
3189
+ return false;
3190
+ }
3191
+ };
3192
+ __name(InvokeTrigger, "InvokeTrigger");
3193
+ _options5 = new WeakMap();
3194
+ function invokeTrigger(options) {
3195
+ return new InvokeTrigger(options ?? {});
3196
+ }
3197
+ __name(invokeTrigger, "invokeTrigger");
3198
+
2551
3199
  // src/index.ts
2552
3200
  function redactString(strings, ...interpolations) {
2553
3201
  return {
@@ -2568,6 +3216,8 @@ __name(redactString, "redactString");
2568
3216
  IO,
2569
3217
  IOLogger,
2570
3218
  IntervalTrigger,
3219
+ InvokeTrigger,
3220
+ JSONOutputSerializer,
2571
3221
  Job,
2572
3222
  MissingConnectionNotification,
2573
3223
  MissingConnectionResolvedNotification,
@@ -2575,6 +3225,7 @@ __name(redactString, "redactString");
2575
3225
  cronTrigger,
2576
3226
  eventTrigger,
2577
3227
  intervalTrigger,
3228
+ invokeTrigger,
2578
3229
  isTriggerError,
2579
3230
  missingConnectionNotification,
2580
3231
  missingConnectionResolvedNotification,