@trigger.dev/sdk 3.0.0-beta.2 → 3.0.0-beta.21

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/v3/index.mjs CHANGED
@@ -1,57 +1,65 @@
1
1
  import { SpanKind, trace, context, SpanStatusCode } from '@opentelemetry/api';
2
- import { SEMATTRS_HTTP_STATUS_CODE, SEMATTRS_HTTP_METHOD, SEMATTRS_HTTP_URL, SEMATTRS_HTTP_HOST, SEMATTRS_HTTP_SCHEME, SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH, SEMATTRS_MESSAGING_OPERATION, SEMATTRS_MESSAGING_DESTINATION, SEMATTRS_MESSAGING_SYSTEM } from '@opentelemetry/semantic-conventions';
3
- import { TriggerTracer, runtime, SemanticInternalAttributes, accessoryAttributes, defaultRetryOptions, conditionallyImportPacket, parsePacket, createErrorTaskError, apiClientManager, calculateNextRetryDelay, defaultFetchRetryOptions, calculateResetAt, eventFilterMatches, flattenAttributes, taskContextManager } from '@trigger.dev/core/v3';
4
- export { logger } from '@trigger.dev/core/v3';
2
+ import { SEMATTRS_MESSAGING_OPERATION, SEMATTRS_MESSAGING_DESTINATION, SEMATTRS_MESSAGING_SYSTEM, SEMATTRS_HTTP_STATUS_CODE, SEMATTRS_HTTP_METHOD, SEMATTRS_HTTP_URL, SEMATTRS_HTTP_HOST, SEMATTRS_HTTP_SCHEME, SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH } from '@opentelemetry/semantic-conventions';
3
+ import { TriggerTracer, runtime, SemanticInternalAttributes, accessoryAttributes, apiClientManager, taskCatalog, stringifyIO, taskContext, logger, defaultRetryOptions, conditionallyImportPacket, parsePacket, createErrorTaskError, calculateNextRetryDelay, defaultFetchRetryOptions, calculateResetAt, eventFilterMatches, flattenAttributes } from '@trigger.dev/core/v3';
4
+ export { APIError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PermissionDeniedError, RateLimitError, UnprocessableEntityError, logger } from '@trigger.dev/core/v3';
5
5
  import { AsyncLocalStorage } from 'node:async_hooks';
6
6
 
7
7
  var __defProp = Object.defineProperty;
8
8
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
9
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
10
14
  var __publicField = (obj, key, value) => {
11
15
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
12
16
  return value;
13
17
  };
14
18
 
15
19
  // package.json
16
- var version = "3.0.0-beta.2";
20
+ var version = "3.0.0-beta.21";
17
21
  var tracer = new TriggerTracer({
18
22
  name: "@trigger.dev/sdk",
19
23
  version
20
24
  });
21
25
 
22
26
  // src/v3/shared.ts
27
+ function queue(options) {
28
+ return options;
29
+ }
30
+ __name(queue, "queue");
23
31
  function createTask(params) {
24
- const task2 = {
25
- trigger: async ({ payload, options }) => {
32
+ const task3 = {
33
+ id: params.id,
34
+ trigger: async (payload, options) => {
26
35
  const apiClient = apiClientManager.client;
27
36
  if (!apiClient) {
28
37
  throw apiClientMissingError();
29
38
  }
30
- const taskMetadata = runtime.getTaskMetadata(params.id);
39
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
40
+ const payloadPacket = await stringifyIO(payload);
31
41
  const handle = await tracer.startActiveSpan(taskMetadata ? "Trigger" : `${params.id} trigger()`, async (span) => {
32
42
  const response = await apiClient.triggerTask(params.id, {
33
- payload,
43
+ payload: payloadPacket.data,
34
44
  options: {
35
45
  queue: params.queue,
36
46
  concurrencyKey: options?.concurrencyKey,
37
- test: taskContextManager.ctx?.run.isTest
47
+ test: taskContext.ctx?.run.isTest,
48
+ payloadType: payloadPacket.dataType,
49
+ idempotencyKey: options?.idempotencyKey
38
50
  }
39
51
  }, {
40
52
  spanParentAsLink: true
41
53
  });
42
- if (!response.ok) {
43
- throw new Error(response.error);
44
- }
45
- span.setAttribute("messaging.message.id", response.data.id);
46
- return response.data;
54
+ span.setAttribute("messaging.message.id", response.id);
55
+ return response;
47
56
  }, {
48
57
  kind: SpanKind.PRODUCER,
49
58
  attributes: {
50
59
  [SEMATTRS_MESSAGING_OPERATION]: "publish",
51
60
  [SemanticInternalAttributes.STYLE_ICON]: "trigger",
52
- ["messaging.client_id"]: taskContextManager.worker?.id,
61
+ ["messaging.client_id"]: taskContext.worker?.id,
53
62
  [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
54
- ["messaging.message.body.size"]: JSON.stringify(payload).length,
55
63
  [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
56
64
  ...taskMetadata ? accessoryAttributes({
57
65
  items: [
@@ -66,38 +74,39 @@ function createTask(params) {
66
74
  });
67
75
  return handle;
68
76
  },
69
- batchTrigger: async ({ items }) => {
77
+ batchTrigger: async (items) => {
70
78
  const apiClient = apiClientManager.client;
71
79
  if (!apiClient) {
72
80
  throw apiClientMissingError();
73
81
  }
74
- const taskMetadata = runtime.getTaskMetadata(params.id);
82
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
75
83
  const response = await tracer.startActiveSpan(taskMetadata ? "Batch trigger" : `${params.id} batchTrigger()`, async (span) => {
76
84
  const response2 = await apiClient.batchTriggerTask(params.id, {
77
- items: items.map((item) => ({
78
- payload: item.payload,
79
- options: {
80
- queue: item.options?.queue ?? params.queue,
81
- concurrencyKey: item.options?.concurrencyKey,
82
- test: taskContextManager.ctx?.run.isTest
83
- }
85
+ items: await Promise.all(items.map(async (item) => {
86
+ const payloadPacket = await stringifyIO(item.payload);
87
+ return {
88
+ payload: payloadPacket.data,
89
+ options: {
90
+ queue: item.options?.queue ?? params.queue,
91
+ concurrencyKey: item.options?.concurrencyKey,
92
+ test: taskContext.ctx?.run.isTest,
93
+ payloadType: payloadPacket.dataType,
94
+ idempotencyKey: item.options?.idempotencyKey
95
+ }
96
+ };
84
97
  }))
85
98
  }, {
86
99
  spanParentAsLink: true
87
100
  });
88
- if (!response2.ok) {
89
- throw new Error(response2.error);
90
- }
91
- span.setAttribute("messaging.message.id", response2.data.batchId);
92
- return response2.data;
101
+ span.setAttribute("messaging.message.id", response2.batchId);
102
+ return response2;
93
103
  }, {
94
104
  kind: SpanKind.PRODUCER,
95
105
  attributes: {
96
106
  [SEMATTRS_MESSAGING_OPERATION]: "publish",
97
107
  ["messaging.batch.message_count"]: items.length,
98
- ["messaging.client_id"]: taskContextManager.worker?.id,
108
+ ["messaging.client_id"]: taskContext.worker?.id,
99
109
  [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
100
- ["messaging.message.body.size"]: items.map((item) => JSON.stringify(item.payload)).join("").length,
101
110
  [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
102
111
  [SemanticInternalAttributes.STYLE_ICON]: "trigger",
103
112
  ...taskMetadata ? accessoryAttributes({
@@ -113,8 +122,8 @@ function createTask(params) {
113
122
  });
114
123
  return response;
115
124
  },
116
- triggerAndWait: async ({ payload, options }) => {
117
- const ctx = taskContextManager.ctx;
125
+ triggerAndWait: async (payload, options) => {
126
+ const ctx = taskContext.ctx;
118
127
  if (!ctx) {
119
128
  throw new Error("triggerAndWait can only be used from inside a task.run()");
120
129
  }
@@ -122,37 +131,43 @@ function createTask(params) {
122
131
  if (!apiClient) {
123
132
  throw apiClientMissingError();
124
133
  }
125
- const taskMetadata = runtime.getTaskMetadata(params.id);
134
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
135
+ const payloadPacket = await stringifyIO(payload);
126
136
  return await tracer.startActiveSpan(taskMetadata ? "Trigger" : `${params.id} triggerAndWait()`, async (span) => {
127
137
  const response = await apiClient.triggerTask(params.id, {
128
- payload,
138
+ payload: payloadPacket.data,
129
139
  options: {
130
140
  dependentAttempt: ctx.attempt.id,
131
- lockToVersion: taskContextManager.worker?.version,
141
+ lockToVersion: taskContext.worker?.version,
132
142
  queue: params.queue,
133
143
  concurrencyKey: options?.concurrencyKey,
134
- test: taskContextManager.ctx?.run.isTest
144
+ test: taskContext.ctx?.run.isTest,
145
+ payloadType: payloadPacket.dataType,
146
+ idempotencyKey: options?.idempotencyKey
135
147
  }
136
148
  });
137
- if (!response.ok) {
138
- throw new Error(response.error);
149
+ span.setAttribute("messaging.message.id", response.id);
150
+ if (options?.idempotencyKey) {
151
+ const result2 = await apiClient.getRunResult(response.id);
152
+ if (result2) {
153
+ logger.log(`Result reused from previous task run with idempotency key '${options.idempotencyKey}'.`, {
154
+ runId: response.id,
155
+ idempotencyKey: options.idempotencyKey
156
+ });
157
+ return await handleTaskRunExecutionResult(result2);
158
+ }
139
159
  }
140
- span.setAttribute("messaging.message.id", response.data.id);
141
160
  const result = await runtime.waitForTask({
142
- id: response.data.id,
161
+ id: response.id,
143
162
  ctx
144
163
  });
145
- const runResult = await handleTaskRunExecutionResult(result);
146
- if (!runResult.ok) {
147
- throw runResult.error;
148
- }
149
- return runResult.output;
164
+ return await handleTaskRunExecutionResult(result);
150
165
  }, {
151
166
  kind: SpanKind.PRODUCER,
152
167
  attributes: {
153
168
  [SemanticInternalAttributes.STYLE_ICON]: "trigger",
154
169
  [SEMATTRS_MESSAGING_OPERATION]: "publish",
155
- ["messaging.client_id"]: taskContextManager.worker?.id,
170
+ ["messaging.client_id"]: taskContext.worker?.id,
156
171
  [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
157
172
  [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
158
173
  ...taskMetadata ? accessoryAttributes({
@@ -167,8 +182,8 @@ function createTask(params) {
167
182
  }
168
183
  });
169
184
  },
170
- batchTriggerAndWait: async ({ items }) => {
171
- const ctx = taskContextManager.ctx;
185
+ batchTriggerAndWait: async (items) => {
186
+ const ctx = taskContext.ctx;
172
187
  if (!ctx) {
173
188
  throw new Error("batchTriggerAndWait can only be used from inside a task.run()");
174
189
  }
@@ -176,42 +191,78 @@ function createTask(params) {
176
191
  if (!apiClient) {
177
192
  throw apiClientMissingError();
178
193
  }
179
- const taskMetadata = runtime.getTaskMetadata(params.id);
194
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
180
195
  return await tracer.startActiveSpan(taskMetadata ? "Batch trigger" : `${params.id} batchTriggerAndWait()`, async (span) => {
181
196
  const response = await apiClient.batchTriggerTask(params.id, {
182
- items: items.map((item) => ({
183
- payload: item.payload,
184
- options: {
185
- lockToVersion: taskContextManager.worker?.version,
186
- queue: item.options?.queue ?? params.queue,
187
- concurrencyKey: item.options?.concurrencyKey,
188
- test: taskContextManager.ctx?.run.isTest
189
- }
197
+ items: await Promise.all(items.map(async (item) => {
198
+ const payloadPacket = await stringifyIO(item.payload);
199
+ return {
200
+ payload: payloadPacket.data,
201
+ options: {
202
+ lockToVersion: taskContext.worker?.version,
203
+ queue: item.options?.queue ?? params.queue,
204
+ concurrencyKey: item.options?.concurrencyKey,
205
+ test: taskContext.ctx?.run.isTest,
206
+ payloadType: payloadPacket.dataType,
207
+ idempotencyKey: item.options?.idempotencyKey
208
+ }
209
+ };
190
210
  })),
191
211
  dependentAttempt: ctx.attempt.id
192
212
  });
193
- if (!response.ok) {
194
- throw new Error(response.error);
213
+ span.setAttribute("messaging.message.id", response.batchId);
214
+ const getBatchResults = /* @__PURE__ */ __name(async () => {
215
+ const hasIdempotencyKey = items.some((item) => item.options?.idempotencyKey);
216
+ if (hasIdempotencyKey) {
217
+ const results = await apiClient.getBatchResults(response.batchId);
218
+ if (results) {
219
+ return results;
220
+ }
221
+ }
222
+ return {
223
+ id: response.batchId,
224
+ items: []
225
+ };
226
+ }, "getBatchResults");
227
+ const existingResults = await getBatchResults();
228
+ const incompleteRuns = response.runs.filter((runId) => !existingResults.items.some((item) => item.id === runId));
229
+ if (incompleteRuns.length === 0) {
230
+ logger.log(`Results reused from previous task runs because of the provided idempotency keys.`);
231
+ const runs3 = await handleBatchTaskRunExecutionResult(existingResults.items);
232
+ return {
233
+ id: existingResults.id,
234
+ runs: runs3
235
+ };
195
236
  }
196
- span.setAttribute("messaging.message.id", response.data.batchId);
197
237
  const result = await runtime.waitForBatch({
198
- id: response.data.batchId,
199
- runs: response.data.runs,
238
+ id: response.batchId,
239
+ runs: incompleteRuns,
200
240
  ctx
201
241
  });
202
- const runs = await handleBatchTaskRunExecutionResult(result.items);
242
+ const combinedItems = [];
243
+ for (const runId of response.runs) {
244
+ const existingItem = existingResults.items.find((item) => item.id === runId);
245
+ if (existingItem) {
246
+ combinedItems.push(existingItem);
247
+ } else {
248
+ const newItem = result.items.find((item) => item.id === runId);
249
+ if (newItem) {
250
+ combinedItems.push(newItem);
251
+ }
252
+ }
253
+ }
254
+ const runs2 = await handleBatchTaskRunExecutionResult(combinedItems);
203
255
  return {
204
256
  id: result.id,
205
- runs
257
+ runs: runs2
206
258
  };
207
259
  }, {
208
260
  kind: SpanKind.PRODUCER,
209
261
  attributes: {
210
262
  [SEMATTRS_MESSAGING_OPERATION]: "publish",
211
263
  ["messaging.batch.message_count"]: items.length,
212
- ["messaging.client_id"]: taskContextManager.worker?.id,
264
+ ["messaging.client_id"]: taskContext.worker?.id,
213
265
  [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
214
- ["messaging.message.body.size"]: items.map((item) => JSON.stringify(item.payload)).join("").length,
215
266
  [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
216
267
  [SemanticInternalAttributes.STYLE_ICON]: "trigger",
217
268
  ...taskMetadata ? accessoryAttributes({
@@ -227,27 +278,27 @@ function createTask(params) {
227
278
  });
228
279
  }
229
280
  };
230
- Object.defineProperty(task2, "__trigger", {
231
- value: {
232
- id: params.id,
233
- packageVersion: version,
234
- queue: params.queue,
235
- retry: params.retry ? {
236
- ...defaultRetryOptions,
237
- ...params.retry
238
- } : void 0,
239
- machine: params.machine,
240
- fns: {
241
- run: params.run,
242
- init: params.init,
243
- cleanup: params.cleanup,
244
- middleware: params.middleware,
245
- handleError: params.handleError
246
- }
247
- },
248
- enumerable: false
281
+ taskCatalog.registerTaskMetadata({
282
+ id: params.id,
283
+ packageVersion: version,
284
+ queue: params.queue,
285
+ retry: params.retry ? {
286
+ ...defaultRetryOptions,
287
+ ...params.retry
288
+ } : void 0,
289
+ machine: params.machine,
290
+ fns: {
291
+ run: params.run,
292
+ init: params.init,
293
+ cleanup: params.cleanup,
294
+ middleware: params.middleware,
295
+ handleError: params.handleError,
296
+ onSuccess: params.onSuccess,
297
+ onFailure: params.onFailure,
298
+ onStart: params.onStart
299
+ }
249
300
  });
250
- return task2;
301
+ return task3;
251
302
  }
252
303
  __name(createTask, "createTask");
253
304
  async function handleBatchTaskRunExecutionResult(items) {
@@ -877,7 +928,104 @@ var retry = {
877
928
  fetch: retryFetch,
878
929
  interceptFetch
879
930
  };
931
+ var runs = {
932
+ replay: replayRun,
933
+ cancel: cancelRun
934
+ };
935
+ async function replayRun(runId) {
936
+ const apiClient = apiClientManager.client;
937
+ if (!apiClient) {
938
+ throw apiClientMissingError();
939
+ }
940
+ return await apiClient.replayRun(runId);
941
+ }
942
+ __name(replayRun, "replayRun");
943
+ async function cancelRun(runId) {
944
+ const apiClient = apiClientManager.client;
945
+ if (!apiClient) {
946
+ throw apiClientMissingError();
947
+ }
948
+ return await apiClient.cancelRun(runId);
949
+ }
950
+ __name(cancelRun, "cancelRun");
951
+
952
+ // src/v3/schedules/index.ts
953
+ var schedules_exports = {};
954
+ __export(schedules_exports, {
955
+ activate: () => activate,
956
+ create: () => create,
957
+ deactivate: () => deactivate,
958
+ del: () => del,
959
+ list: () => list,
960
+ retrieve: () => retrieve,
961
+ task: () => task2,
962
+ update: () => update
963
+ });
964
+ function task2(params) {
965
+ const task3 = createTask(params);
966
+ taskCatalog.updateTaskMetadata(task3.id, {
967
+ triggerSource: "schedule"
968
+ });
969
+ return task3;
970
+ }
971
+ __name(task2, "task");
972
+ async function create(options) {
973
+ const apiClient = apiClientManager.client;
974
+ if (!apiClient) {
975
+ throw apiClientMissingError();
976
+ }
977
+ return apiClient.createSchedule(options);
978
+ }
979
+ __name(create, "create");
980
+ async function retrieve(scheduleId) {
981
+ const apiClient = apiClientManager.client;
982
+ if (!apiClient) {
983
+ throw apiClientMissingError();
984
+ }
985
+ return apiClient.retrieveSchedule(scheduleId);
986
+ }
987
+ __name(retrieve, "retrieve");
988
+ async function update(scheduleId, options) {
989
+ const apiClient = apiClientManager.client;
990
+ if (!apiClient) {
991
+ throw apiClientMissingError();
992
+ }
993
+ return apiClient.updateSchedule(scheduleId, options);
994
+ }
995
+ __name(update, "update");
996
+ async function del(scheduleId) {
997
+ const apiClient = apiClientManager.client;
998
+ if (!apiClient) {
999
+ throw apiClientMissingError();
1000
+ }
1001
+ return apiClient.deleteSchedule(scheduleId);
1002
+ }
1003
+ __name(del, "del");
1004
+ async function deactivate(scheduleId) {
1005
+ const apiClient = apiClientManager.client;
1006
+ if (!apiClient) {
1007
+ throw apiClientMissingError();
1008
+ }
1009
+ return apiClient.deactivateSchedule(scheduleId);
1010
+ }
1011
+ __name(deactivate, "deactivate");
1012
+ async function activate(scheduleId) {
1013
+ const apiClient = apiClientManager.client;
1014
+ if (!apiClient) {
1015
+ throw apiClientMissingError();
1016
+ }
1017
+ return apiClient.activateSchedule(scheduleId);
1018
+ }
1019
+ __name(activate, "activate");
1020
+ async function list(options) {
1021
+ const apiClient = apiClientManager.client;
1022
+ if (!apiClient) {
1023
+ throw apiClientMissingError();
1024
+ }
1025
+ return apiClient.listSchedules(options);
1026
+ }
1027
+ __name(list, "list");
880
1028
 
881
- export { InMemoryCache, createCache, retry, task, wait };
1029
+ export { InMemoryCache, createCache, queue, retry, runs, schedules_exports as schedules, task, wait };
882
1030
  //# sourceMappingURL=out.js.map
883
1031
  //# sourceMappingURL=index.mjs.map