@trigger.dev/sdk 3.0.0-beta.5 → 3.0.0-beta.51

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,408 +1,32 @@
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';
1
+ import { TriggerTracer, SemanticInternalAttributes, apiClientManager, isRequestOptions, mergeRequestOptions, accessoryAttributes, flattenAttributes, taskContext, runtime, usage as usage$1, UnprocessableEntityError, logger, taskCatalog, TimezonesResult, defaultRetryOptions, calculateNextRetryDelay, defaultFetchRetryOptions, calculateResetAt, eventFilterMatches, stringifyIO, conditionallyImportPacket, parsePacket, createErrorTaskError } from '@trigger.dev/core/v3';
2
+ export { AbortTaskRunError, ApiError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PermissionDeniedError, RateLimitError, UnprocessableEntityError, logger } from '@trigger.dev/core/v3';
3
+ import { trace, context, SpanStatusCode, SpanKind } from '@opentelemetry/api';
4
+ 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_SYSTEM, SEMATTRS_MESSAGING_DESTINATION } from '@opentelemetry/semantic-conventions';
5
5
  import { AsyncLocalStorage } from 'node:async_hooks';
6
+ import { zodfetch } from '@trigger.dev/core/v3/zodfetch';
6
7
 
7
8
  var __defProp = Object.defineProperty;
8
9
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
10
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
11
+ var __export = (target, all) => {
12
+ for (var name2 in all)
13
+ __defProp(target, name2, { get: all[name2], enumerable: true });
14
+ };
10
15
  var __publicField = (obj, key, value) => {
11
16
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
12
17
  return value;
13
18
  };
14
19
 
15
20
  // package.json
16
- var version = "3.0.0-beta.5";
21
+ var version = "3.0.0-beta.51";
22
+
23
+ // src/v3/tracer.ts
17
24
  var tracer = new TriggerTracer({
18
25
  name: "@trigger.dev/sdk",
19
26
  version
20
27
  });
21
28
 
22
- // src/v3/shared.ts
23
- function createTask(params) {
24
- const task2 = {
25
- trigger: async ({ payload, options }) => {
26
- const apiClient = apiClientManager.client;
27
- if (!apiClient) {
28
- throw apiClientMissingError();
29
- }
30
- const taskMetadata = runtime.getTaskMetadata(params.id);
31
- const handle = await tracer.startActiveSpan(taskMetadata ? "Trigger" : `${params.id} trigger()`, async (span) => {
32
- const response = await apiClient.triggerTask(params.id, {
33
- payload,
34
- options: {
35
- queue: params.queue,
36
- concurrencyKey: options?.concurrencyKey,
37
- test: taskContextManager.ctx?.run.isTest
38
- }
39
- }, {
40
- spanParentAsLink: true
41
- });
42
- if (!response.ok) {
43
- throw new Error(response.error);
44
- }
45
- span.setAttribute("messaging.message.id", response.data.id);
46
- return response.data;
47
- }, {
48
- kind: SpanKind.PRODUCER,
49
- attributes: {
50
- [SEMATTRS_MESSAGING_OPERATION]: "publish",
51
- [SemanticInternalAttributes.STYLE_ICON]: "trigger",
52
- ["messaging.client_id"]: taskContextManager.worker?.id,
53
- [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
54
- ["messaging.message.body.size"]: JSON.stringify(payload).length,
55
- [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
56
- ...taskMetadata ? accessoryAttributes({
57
- items: [
58
- {
59
- text: `${taskMetadata.exportName}.trigger()`,
60
- variant: "normal"
61
- }
62
- ],
63
- style: "codepath"
64
- }) : {}
65
- }
66
- });
67
- return handle;
68
- },
69
- batchTrigger: async ({ items }) => {
70
- const apiClient = apiClientManager.client;
71
- if (!apiClient) {
72
- throw apiClientMissingError();
73
- }
74
- const taskMetadata = runtime.getTaskMetadata(params.id);
75
- const response = await tracer.startActiveSpan(taskMetadata ? "Batch trigger" : `${params.id} batchTrigger()`, async (span) => {
76
- 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
- }
84
- }))
85
- }, {
86
- spanParentAsLink: true
87
- });
88
- if (!response2.ok) {
89
- throw new Error(response2.error);
90
- }
91
- span.setAttribute("messaging.message.id", response2.data.batchId);
92
- return response2.data;
93
- }, {
94
- kind: SpanKind.PRODUCER,
95
- attributes: {
96
- [SEMATTRS_MESSAGING_OPERATION]: "publish",
97
- ["messaging.batch.message_count"]: items.length,
98
- ["messaging.client_id"]: taskContextManager.worker?.id,
99
- [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
100
- ["messaging.message.body.size"]: items.map((item) => JSON.stringify(item.payload)).join("").length,
101
- [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
102
- [SemanticInternalAttributes.STYLE_ICON]: "trigger",
103
- ...taskMetadata ? accessoryAttributes({
104
- items: [
105
- {
106
- text: `${taskMetadata.exportName}.batchTrigger()`,
107
- variant: "normal"
108
- }
109
- ],
110
- style: "codepath"
111
- }) : {}
112
- }
113
- });
114
- return response;
115
- },
116
- triggerAndWait: async ({ payload, options }) => {
117
- const ctx = taskContextManager.ctx;
118
- if (!ctx) {
119
- throw new Error("triggerAndWait can only be used from inside a task.run()");
120
- }
121
- const apiClient = apiClientManager.client;
122
- if (!apiClient) {
123
- throw apiClientMissingError();
124
- }
125
- const taskMetadata = runtime.getTaskMetadata(params.id);
126
- return await tracer.startActiveSpan(taskMetadata ? "Trigger" : `${params.id} triggerAndWait()`, async (span) => {
127
- const response = await apiClient.triggerTask(params.id, {
128
- payload,
129
- options: {
130
- dependentAttempt: ctx.attempt.id,
131
- lockToVersion: taskContextManager.worker?.version,
132
- queue: params.queue,
133
- concurrencyKey: options?.concurrencyKey,
134
- test: taskContextManager.ctx?.run.isTest
135
- }
136
- });
137
- if (!response.ok) {
138
- throw new Error(response.error);
139
- }
140
- span.setAttribute("messaging.message.id", response.data.id);
141
- const result = await runtime.waitForTask({
142
- id: response.data.id,
143
- ctx
144
- });
145
- const runResult = await handleTaskRunExecutionResult(result);
146
- if (!runResult.ok) {
147
- throw runResult.error;
148
- }
149
- return runResult.output;
150
- }, {
151
- kind: SpanKind.PRODUCER,
152
- attributes: {
153
- [SemanticInternalAttributes.STYLE_ICON]: "trigger",
154
- [SEMATTRS_MESSAGING_OPERATION]: "publish",
155
- ["messaging.client_id"]: taskContextManager.worker?.id,
156
- [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
157
- [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
158
- ...taskMetadata ? accessoryAttributes({
159
- items: [
160
- {
161
- text: `${taskMetadata.exportName}.triggerAndWait()`,
162
- variant: "normal"
163
- }
164
- ],
165
- style: "codepath"
166
- }) : {}
167
- }
168
- });
169
- },
170
- batchTriggerAndWait: async ({ items }) => {
171
- const ctx = taskContextManager.ctx;
172
- if (!ctx) {
173
- throw new Error("batchTriggerAndWait can only be used from inside a task.run()");
174
- }
175
- const apiClient = apiClientManager.client;
176
- if (!apiClient) {
177
- throw apiClientMissingError();
178
- }
179
- const taskMetadata = runtime.getTaskMetadata(params.id);
180
- return await tracer.startActiveSpan(taskMetadata ? "Batch trigger" : `${params.id} batchTriggerAndWait()`, async (span) => {
181
- 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
- }
190
- })),
191
- dependentAttempt: ctx.attempt.id
192
- });
193
- if (!response.ok) {
194
- throw new Error(response.error);
195
- }
196
- span.setAttribute("messaging.message.id", response.data.batchId);
197
- const result = await runtime.waitForBatch({
198
- id: response.data.batchId,
199
- runs: response.data.runs,
200
- ctx
201
- });
202
- const runs = await handleBatchTaskRunExecutionResult(result.items);
203
- return {
204
- id: result.id,
205
- runs
206
- };
207
- }, {
208
- kind: SpanKind.PRODUCER,
209
- attributes: {
210
- [SEMATTRS_MESSAGING_OPERATION]: "publish",
211
- ["messaging.batch.message_count"]: items.length,
212
- ["messaging.client_id"]: taskContextManager.worker?.id,
213
- [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
214
- ["messaging.message.body.size"]: items.map((item) => JSON.stringify(item.payload)).join("").length,
215
- [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
216
- [SemanticInternalAttributes.STYLE_ICON]: "trigger",
217
- ...taskMetadata ? accessoryAttributes({
218
- items: [
219
- {
220
- text: `${taskMetadata.exportName}.batchTriggerAndWait()`,
221
- variant: "normal"
222
- }
223
- ],
224
- style: "codepath"
225
- }) : {}
226
- }
227
- });
228
- }
229
- };
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
249
- });
250
- return task2;
251
- }
252
- __name(createTask, "createTask");
253
- async function handleBatchTaskRunExecutionResult(items) {
254
- const someObjectStoreOutputs = items.some((item) => item.ok && item.outputType === "application/store");
255
- if (!someObjectStoreOutputs) {
256
- const results = await Promise.all(items.map(async (item) => {
257
- return await handleTaskRunExecutionResult(item);
258
- }));
259
- return results;
260
- }
261
- return await tracer.startActiveSpan("store.downloadPayloads", async (span) => {
262
- const results = await Promise.all(items.map(async (item) => {
263
- return await handleTaskRunExecutionResult(item);
264
- }));
265
- return results;
266
- }, {
267
- kind: SpanKind.INTERNAL,
268
- [SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
269
- });
270
- }
271
- __name(handleBatchTaskRunExecutionResult, "handleBatchTaskRunExecutionResult");
272
- async function handleTaskRunExecutionResult(execution) {
273
- if (execution.ok) {
274
- const outputPacket = {
275
- data: execution.output,
276
- dataType: execution.outputType
277
- };
278
- const importedPacket = await conditionallyImportPacket(outputPacket, tracer);
279
- return {
280
- ok: true,
281
- id: execution.id,
282
- output: await parsePacket(importedPacket)
283
- };
284
- } else {
285
- return {
286
- ok: false,
287
- id: execution.id,
288
- error: createErrorTaskError(execution.error)
289
- };
290
- }
291
- }
292
- __name(handleTaskRunExecutionResult, "handleTaskRunExecutionResult");
293
- function apiClientMissingError() {
294
- const hasBaseUrl = !!apiClientManager.baseURL;
295
- const hasAccessToken = !!apiClientManager.accessToken;
296
- if (!hasBaseUrl && !hasAccessToken) {
297
- return `You need to set the TRIGGER_API_URL and TRIGGER_SECRET_KEY environment variables.`;
298
- } else if (!hasBaseUrl) {
299
- return `You need to set the TRIGGER_API_URL environment variable.`;
300
- } else if (!hasAccessToken) {
301
- return `You need to set the TRIGGER_SECRET_KEY environment variable.`;
302
- }
303
- return `Unknown error`;
304
- }
305
- __name(apiClientMissingError, "apiClientMissingError");
306
-
307
- // src/v3/tasks.ts
308
- function task(options) {
309
- return createTask(options);
310
- }
311
- __name(task, "task");
312
- var wait = {
313
- for: async (options) => {
314
- return tracer.startActiveSpan(`wait.for()`, async (span) => {
315
- const durationInMs = calculateDurationInMs(options);
316
- await runtime.waitForDuration(durationInMs);
317
- }, {
318
- attributes: {
319
- [SemanticInternalAttributes.STYLE_ICON]: "wait",
320
- ...accessoryAttributes({
321
- items: [
322
- {
323
- text: nameForWaitOptions(options),
324
- variant: "normal"
325
- }
326
- ],
327
- style: "codepath"
328
- })
329
- }
330
- });
331
- },
332
- until: async (options) => {
333
- return tracer.startActiveSpan(`wait.until()`, async (span) => {
334
- const start = Date.now();
335
- if (options.throwIfInThePast && options.date < /* @__PURE__ */ new Date()) {
336
- throw new Error("Date is in the past");
337
- }
338
- const durationInMs = options.date.getTime() - start;
339
- await runtime.waitForDuration(durationInMs);
340
- }, {
341
- attributes: {
342
- [SemanticInternalAttributes.STYLE_ICON]: "wait",
343
- ...accessoryAttributes({
344
- items: [
345
- {
346
- text: options.date.toISOString(),
347
- variant: "normal"
348
- }
349
- ],
350
- style: "codepath"
351
- })
352
- }
353
- });
354
- }
355
- };
356
- function nameForWaitOptions(options) {
357
- if ("seconds" in options) {
358
- return options.seconds === 1 ? `1 second` : `${options.seconds} seconds`;
359
- }
360
- if ("minutes" in options) {
361
- return options.minutes === 1 ? `1 minute` : `${options.minutes} minutes`;
362
- }
363
- if ("hours" in options) {
364
- return options.hours === 1 ? `1 hour` : `${options.hours} hours`;
365
- }
366
- if ("days" in options) {
367
- return options.days === 1 ? `1 day` : `${options.days} days`;
368
- }
369
- if ("weeks" in options) {
370
- return options.weeks === 1 ? `1 week` : `${options.weeks} weeks`;
371
- }
372
- if ("months" in options) {
373
- return options.months === 1 ? `1 month` : `${options.months} months`;
374
- }
375
- if ("years" in options) {
376
- return options.years === 1 ? `1 year` : `${options.years} years`;
377
- }
378
- return "NaN";
379
- }
380
- __name(nameForWaitOptions, "nameForWaitOptions");
381
- function calculateDurationInMs(options) {
382
- if ("seconds" in options) {
383
- return options.seconds * 1e3;
384
- }
385
- if ("minutes" in options) {
386
- return options.minutes * 1e3 * 60;
387
- }
388
- if ("hours" in options) {
389
- return options.hours * 1e3 * 60 * 60;
390
- }
391
- if ("days" in options) {
392
- return options.days * 1e3 * 60 * 60 * 24;
393
- }
394
- if ("weeks" in options) {
395
- return options.weeks * 1e3 * 60 * 60 * 24 * 7;
396
- }
397
- if ("months" in options) {
398
- return options.months * 1e3 * 60 * 60 * 24 * 30;
399
- }
400
- if ("years" in options) {
401
- return options.years * 1e3 * 60 * 60 * 24 * 365;
402
- }
403
- throw new Error("Invalid options");
404
- }
405
- __name(calculateDurationInMs, "calculateDurationInMs");
29
+ // src/v3/cache.ts
406
30
  var _InMemoryCache = class _InMemoryCache {
407
31
  constructor() {
408
32
  __publicField(this, "_cache", /* @__PURE__ */ new Map());
@@ -499,6 +123,10 @@ function onThrow(fn, options) {
499
123
  innerSpan.setStatus({
500
124
  code: SpanStatusCode.ERROR
501
125
  });
126
+ if (e instanceof Error && e.name === "AbortTaskRunError") {
127
+ innerSpan.end();
128
+ throw e;
129
+ }
502
130
  const nextRetryDelay = calculateNextRetryDelay(opts, attempt);
503
131
  if (!nextRetryDelay) {
504
132
  innerSpan.end();
@@ -877,7 +505,1336 @@ var retry = {
877
505
  fetch: retryFetch,
878
506
  interceptFetch
879
507
  };
508
+ var runs = {
509
+ replay: replayRun,
510
+ cancel: cancelRun,
511
+ retrieve: retrieveRun,
512
+ list: listRuns,
513
+ reschedule: rescheduleRun,
514
+ poll
515
+ };
516
+ function listRuns(paramsOrProjectRef, paramsOrOptions, requestOptions) {
517
+ const apiClient = apiClientManager.client;
518
+ if (!apiClient) {
519
+ throw apiClientMissingError();
520
+ }
521
+ const $requestOptions = listRunsRequestOptions(paramsOrProjectRef, paramsOrOptions, requestOptions);
522
+ if (typeof paramsOrProjectRef === "string") {
523
+ if (isRequestOptions(paramsOrOptions)) {
524
+ return apiClient.listProjectRuns(paramsOrProjectRef, {}, $requestOptions);
525
+ } else {
526
+ return apiClient.listProjectRuns(paramsOrProjectRef, paramsOrOptions, $requestOptions);
527
+ }
528
+ }
529
+ return apiClient.listRuns(paramsOrProjectRef, $requestOptions);
530
+ }
531
+ __name(listRuns, "listRuns");
532
+ function listRunsRequestOptions(paramsOrProjectRef, paramsOrOptions, requestOptions) {
533
+ if (typeof paramsOrProjectRef === "string") {
534
+ if (isRequestOptions(paramsOrOptions)) {
535
+ return mergeRequestOptions({
536
+ tracer,
537
+ name: "runs.list()",
538
+ icon: "runs",
539
+ attributes: {
540
+ projectRef: paramsOrProjectRef,
541
+ ...accessoryAttributes({
542
+ items: [
543
+ {
544
+ text: paramsOrProjectRef,
545
+ variant: "normal"
546
+ }
547
+ ],
548
+ style: "codepath"
549
+ })
550
+ }
551
+ }, paramsOrOptions);
552
+ } else {
553
+ return mergeRequestOptions({
554
+ tracer,
555
+ name: "runs.list()",
556
+ icon: "runs",
557
+ attributes: {
558
+ projectRef: paramsOrProjectRef,
559
+ ...flattenAttributes(paramsOrOptions, "queryParams"),
560
+ ...accessoryAttributes({
561
+ items: [
562
+ {
563
+ text: paramsOrProjectRef,
564
+ variant: "normal"
565
+ }
566
+ ],
567
+ style: "codepath"
568
+ })
569
+ }
570
+ }, requestOptions);
571
+ }
572
+ }
573
+ return mergeRequestOptions({
574
+ tracer,
575
+ name: "runs.list()",
576
+ icon: "runs",
577
+ attributes: {
578
+ ...flattenAttributes(paramsOrProjectRef, "queryParams")
579
+ }
580
+ }, isRequestOptions(paramsOrOptions) ? paramsOrOptions : requestOptions);
581
+ }
582
+ __name(listRunsRequestOptions, "listRunsRequestOptions");
583
+ function retrieveRun(runId, requestOptions) {
584
+ const apiClient = apiClientManager.client;
585
+ if (!apiClient) {
586
+ throw apiClientMissingError();
587
+ }
588
+ const $requestOptions = mergeRequestOptions({
589
+ tracer,
590
+ name: "runs.retrieve()",
591
+ icon: "runs",
592
+ attributes: {
593
+ runId: typeof runId === "string" ? runId : runId.id,
594
+ ...accessoryAttributes({
595
+ items: [
596
+ {
597
+ text: typeof runId === "string" ? runId : runId.id,
598
+ variant: "normal"
599
+ }
600
+ ],
601
+ style: "codepath"
602
+ })
603
+ }
604
+ }, requestOptions);
605
+ if (typeof runId === "string") {
606
+ return apiClient.retrieveRun(runId, $requestOptions);
607
+ } else {
608
+ return apiClient.retrieveRun(runId.id, $requestOptions);
609
+ }
610
+ }
611
+ __name(retrieveRun, "retrieveRun");
612
+ function replayRun(runId, requestOptions) {
613
+ const apiClient = apiClientManager.client;
614
+ if (!apiClient) {
615
+ throw apiClientMissingError();
616
+ }
617
+ const $requestOptions = mergeRequestOptions({
618
+ tracer,
619
+ name: "runs.replay()",
620
+ icon: "runs",
621
+ attributes: {
622
+ runId,
623
+ ...accessoryAttributes({
624
+ items: [
625
+ {
626
+ text: runId,
627
+ variant: "normal"
628
+ }
629
+ ],
630
+ style: "codepath"
631
+ })
632
+ }
633
+ }, requestOptions);
634
+ return apiClient.replayRun(runId, $requestOptions);
635
+ }
636
+ __name(replayRun, "replayRun");
637
+ function cancelRun(runId, requestOptions) {
638
+ const apiClient = apiClientManager.client;
639
+ if (!apiClient) {
640
+ throw apiClientMissingError();
641
+ }
642
+ const $requestOptions = mergeRequestOptions({
643
+ tracer,
644
+ name: "runs.cancel()",
645
+ icon: "runs",
646
+ attributes: {
647
+ runId,
648
+ ...accessoryAttributes({
649
+ items: [
650
+ {
651
+ text: runId,
652
+ variant: "normal"
653
+ }
654
+ ],
655
+ style: "codepath"
656
+ })
657
+ }
658
+ }, requestOptions);
659
+ return apiClient.cancelRun(runId, $requestOptions);
660
+ }
661
+ __name(cancelRun, "cancelRun");
662
+ function rescheduleRun(runId, body, requestOptions) {
663
+ const apiClient = apiClientManager.client;
664
+ if (!apiClient) {
665
+ throw apiClientMissingError();
666
+ }
667
+ const $requestOptions = mergeRequestOptions({
668
+ tracer,
669
+ name: "runs.reschedule()",
670
+ icon: "runs",
671
+ attributes: {
672
+ runId,
673
+ ...accessoryAttributes({
674
+ items: [
675
+ {
676
+ text: runId,
677
+ variant: "normal"
678
+ }
679
+ ],
680
+ style: "codepath"
681
+ })
682
+ }
683
+ }, requestOptions);
684
+ return apiClient.rescheduleRun(runId, body, $requestOptions);
685
+ }
686
+ __name(rescheduleRun, "rescheduleRun");
687
+ var MAX_POLL_ATTEMPTS = 500;
688
+ async function poll(runId, options, requestOptions) {
689
+ let attempts = 0;
690
+ while (attempts++ < MAX_POLL_ATTEMPTS) {
691
+ const run = await runs.retrieve(runId, requestOptions);
692
+ if (run.isCompleted) {
693
+ return run;
694
+ }
695
+ await new Promise((resolve) => setTimeout(resolve, options?.pollIntervalMs ?? 1e3));
696
+ }
697
+ throw new Error(`Run ${typeof runId === "string" ? runId : runId.id} did not complete after ${MAX_POLL_ATTEMPTS} attempts`);
698
+ }
699
+ __name(poll, "poll");
700
+ var idempotencyKeys = {
701
+ create: createIdempotencyKey
702
+ };
703
+ function isIdempotencyKey(value) {
704
+ return typeof value === "string" && value.length === 64;
705
+ }
706
+ __name(isIdempotencyKey, "isIdempotencyKey");
707
+ async function createIdempotencyKey(key, options) {
708
+ const idempotencyKey = await generateIdempotencyKey([
709
+ ...Array.isArray(key) ? key : [
710
+ key
711
+ ]
712
+ ].concat(injectScope(options?.scope ?? "run")));
713
+ return idempotencyKey;
714
+ }
715
+ __name(createIdempotencyKey, "createIdempotencyKey");
716
+ function injectScope(scope) {
717
+ switch (scope) {
718
+ case "run": {
719
+ if (taskContext?.ctx) {
720
+ return [
721
+ taskContext.ctx.run.id
722
+ ];
723
+ }
724
+ }
725
+ case "attempt": {
726
+ if (taskContext?.ctx) {
727
+ return [
728
+ taskContext.ctx.attempt.id
729
+ ];
730
+ }
731
+ }
732
+ }
733
+ return [];
734
+ }
735
+ __name(injectScope, "injectScope");
736
+ async function generateIdempotencyKey(keyMaterial) {
737
+ const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(keyMaterial.join("-")));
738
+ return Array.from(new Uint8Array(hash)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
739
+ }
740
+ __name(generateIdempotencyKey, "generateIdempotencyKey");
741
+
742
+ // src/v3/shared.ts
743
+ function queue(options) {
744
+ return options;
745
+ }
746
+ __name(queue, "queue");
747
+ function createTask(params) {
748
+ const task3 = {
749
+ id: params.id,
750
+ trigger: async (payload, options) => {
751
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
752
+ return await trigger_internal(taskMetadata && taskMetadata.exportName ? `${taskMetadata.exportName}.trigger()` : `trigger()`, params.id, payload, options);
753
+ },
754
+ batchTrigger: async (items) => {
755
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
756
+ return await batchTrigger_internal(taskMetadata && taskMetadata.exportName ? `${taskMetadata.exportName}.batchTrigger()` : `batchTrigger()`, params.id, items);
757
+ },
758
+ triggerAndWait: async (payload, options) => {
759
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
760
+ return await triggerAndWait_internal(taskMetadata && taskMetadata.exportName ? `${taskMetadata.exportName}.triggerAndWait()` : `triggerAndWait()`, params.id, payload, options);
761
+ },
762
+ batchTriggerAndWait: async (items) => {
763
+ const taskMetadata = taskCatalog.getTaskMetadata(params.id);
764
+ return await batchTriggerAndWait_internal(taskMetadata && taskMetadata.exportName ? `${taskMetadata.exportName}.batchTriggerAndWait()` : `batchTriggerAndWait()`, params.id, items);
765
+ }
766
+ };
767
+ taskCatalog.registerTaskMetadata({
768
+ id: params.id,
769
+ packageVersion: version,
770
+ queue: params.queue,
771
+ retry: params.retry ? {
772
+ ...defaultRetryOptions,
773
+ ...params.retry
774
+ } : void 0,
775
+ machine: params.machine,
776
+ fns: {
777
+ run: params.run,
778
+ init: params.init,
779
+ cleanup: params.cleanup,
780
+ middleware: params.middleware,
781
+ handleError: params.handleError,
782
+ onSuccess: params.onSuccess,
783
+ onFailure: params.onFailure,
784
+ onStart: params.onStart
785
+ }
786
+ });
787
+ return task3;
788
+ }
789
+ __name(createTask, "createTask");
790
+ async function trigger(id, payload, options, requestOptions) {
791
+ return await trigger_internal("tasks.trigger()", id, payload, options, requestOptions);
792
+ }
793
+ __name(trigger, "trigger");
794
+ async function triggerAndWait(id, payload, options, requestOptions) {
795
+ return await triggerAndWait_internal("tasks.triggerAndWait()", id, payload, options, requestOptions);
796
+ }
797
+ __name(triggerAndWait, "triggerAndWait");
798
+ async function batchTriggerAndWait(id, items, requestOptions) {
799
+ return await batchTriggerAndWait_internal("tasks.batchTriggerAndWait()", id, items, requestOptions);
800
+ }
801
+ __name(batchTriggerAndWait, "batchTriggerAndWait");
802
+ async function triggerAndPoll(id, payload, options, requestOptions) {
803
+ const handle = await trigger(id, payload, options, requestOptions);
804
+ return runs.poll(handle, options, requestOptions);
805
+ }
806
+ __name(triggerAndPoll, "triggerAndPoll");
807
+ async function batchTrigger(id, items, requestOptions) {
808
+ return await batchTrigger_internal("tasks.batchTrigger()", id, items, requestOptions);
809
+ }
810
+ __name(batchTrigger, "batchTrigger");
811
+ async function trigger_internal(name2, id, payload, options, requestOptions) {
812
+ const apiClient = apiClientManager.client;
813
+ if (!apiClient) {
814
+ throw apiClientMissingError();
815
+ }
816
+ const payloadPacket = await stringifyIO(payload);
817
+ const handle = await apiClient.triggerTask(id, {
818
+ payload: payloadPacket.data,
819
+ options: {
820
+ queue: options?.queue,
821
+ concurrencyKey: options?.concurrencyKey,
822
+ test: taskContext.ctx?.run.isTest,
823
+ payloadType: payloadPacket.dataType,
824
+ idempotencyKey: await makeKey(options?.idempotencyKey),
825
+ delay: options?.delay,
826
+ ttl: options?.ttl,
827
+ tags: options?.tags,
828
+ maxAttempts: options?.maxAttempts
829
+ }
830
+ }, {
831
+ spanParentAsLink: true
832
+ }, {
833
+ name: name2,
834
+ tracer,
835
+ icon: "trigger",
836
+ attributes: {
837
+ [SEMATTRS_MESSAGING_OPERATION]: "publish",
838
+ ["messaging.client_id"]: taskContext.worker?.id,
839
+ [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
840
+ ...accessoryAttributes({
841
+ items: [
842
+ {
843
+ text: id,
844
+ variant: "normal"
845
+ }
846
+ ],
847
+ style: "codepath"
848
+ })
849
+ },
850
+ onResponseBody: (body, span) => {
851
+ body && typeof body === "object" && !Array.isArray(body) && "id" in body && typeof body.id === "string" && span.setAttribute("messaging.message.id", body.id);
852
+ },
853
+ ...requestOptions
854
+ });
855
+ return handle;
856
+ }
857
+ __name(trigger_internal, "trigger_internal");
858
+ async function batchTrigger_internal(name2, id, items, requestOptions) {
859
+ const apiClient = apiClientManager.client;
860
+ if (!apiClient) {
861
+ throw apiClientMissingError();
862
+ }
863
+ const response = await apiClient.batchTriggerTask(id, {
864
+ items: await Promise.all(items.map(async (item) => {
865
+ const payloadPacket = await stringifyIO(item.payload);
866
+ return {
867
+ payload: payloadPacket.data,
868
+ options: {
869
+ queue: item.options?.queue,
870
+ concurrencyKey: item.options?.concurrencyKey,
871
+ test: taskContext.ctx?.run.isTest,
872
+ payloadType: payloadPacket.dataType,
873
+ idempotencyKey: await makeKey(item.options?.idempotencyKey),
874
+ delay: item.options?.delay,
875
+ ttl: item.options?.ttl,
876
+ tags: item.options?.tags,
877
+ maxAttempts: item.options?.maxAttempts
878
+ }
879
+ };
880
+ }))
881
+ }, {
882
+ spanParentAsLink: true
883
+ }, {
884
+ name: name2,
885
+ tracer,
886
+ icon: "trigger",
887
+ attributes: {
888
+ [SEMATTRS_MESSAGING_OPERATION]: "publish",
889
+ ["messaging.client_id"]: taskContext.worker?.id,
890
+ [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
891
+ ...accessoryAttributes({
892
+ items: [
893
+ {
894
+ text: id,
895
+ variant: "normal"
896
+ }
897
+ ],
898
+ style: "codepath"
899
+ })
900
+ },
901
+ ...requestOptions
902
+ });
903
+ const handle = {
904
+ batchId: response.batchId,
905
+ runs: response.runs.map((id2) => ({
906
+ id: id2
907
+ }))
908
+ };
909
+ return handle;
910
+ }
911
+ __name(batchTrigger_internal, "batchTrigger_internal");
912
+ async function triggerAndWait_internal(name2, id, payload, options, requestOptions) {
913
+ const ctx = taskContext.ctx;
914
+ if (!ctx) {
915
+ throw new Error("triggerAndWait can only be used from inside a task.run()");
916
+ }
917
+ const apiClient = apiClientManager.client;
918
+ if (!apiClient) {
919
+ throw apiClientMissingError();
920
+ }
921
+ const payloadPacket = await stringifyIO(payload);
922
+ return await tracer.startActiveSpan(name2, async (span) => {
923
+ const response = await apiClient.triggerTask(id, {
924
+ payload: payloadPacket.data,
925
+ options: {
926
+ dependentAttempt: ctx.attempt.id,
927
+ lockToVersion: taskContext.worker?.version,
928
+ queue: options?.queue,
929
+ concurrencyKey: options?.concurrencyKey,
930
+ test: taskContext.ctx?.run.isTest,
931
+ payloadType: payloadPacket.dataType,
932
+ idempotencyKey: await makeKey(options?.idempotencyKey),
933
+ delay: options?.delay,
934
+ ttl: options?.ttl,
935
+ tags: options?.tags,
936
+ maxAttempts: options?.maxAttempts
937
+ }
938
+ }, {}, requestOptions);
939
+ span.setAttribute("messaging.message.id", response.id);
940
+ if (options?.idempotencyKey) {
941
+ const result2 = await apiClient.getRunResult(response.id);
942
+ if (result2) {
943
+ logger.log(`Result reused from previous task run with idempotency key '${options.idempotencyKey}'.`, {
944
+ runId: response.id,
945
+ idempotencyKey: options.idempotencyKey
946
+ });
947
+ return await handleTaskRunExecutionResult(result2);
948
+ }
949
+ }
950
+ const result = await runtime.waitForTask({
951
+ id: response.id,
952
+ ctx
953
+ });
954
+ return await handleTaskRunExecutionResult(result);
955
+ }, {
956
+ kind: SpanKind.PRODUCER,
957
+ attributes: {
958
+ [SemanticInternalAttributes.STYLE_ICON]: "trigger",
959
+ [SEMATTRS_MESSAGING_OPERATION]: "publish",
960
+ ["messaging.client_id"]: taskContext.worker?.id,
961
+ [SEMATTRS_MESSAGING_DESTINATION]: id,
962
+ [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
963
+ ...accessoryAttributes({
964
+ items: [
965
+ {
966
+ text: id,
967
+ variant: "normal"
968
+ }
969
+ ],
970
+ style: "codepath"
971
+ })
972
+ }
973
+ });
974
+ }
975
+ __name(triggerAndWait_internal, "triggerAndWait_internal");
976
+ async function batchTriggerAndWait_internal(name2, id, items, requestOptions) {
977
+ const ctx = taskContext.ctx;
978
+ if (!ctx) {
979
+ throw new Error("batchTriggerAndWait can only be used from inside a task.run()");
980
+ }
981
+ const apiClient = apiClientManager.client;
982
+ if (!apiClient) {
983
+ throw apiClientMissingError();
984
+ }
985
+ return await tracer.startActiveSpan(name2, async (span) => {
986
+ const response = await apiClient.batchTriggerTask(id, {
987
+ items: await Promise.all(items.map(async (item) => {
988
+ const payloadPacket = await stringifyIO(item.payload);
989
+ return {
990
+ payload: payloadPacket.data,
991
+ options: {
992
+ lockToVersion: taskContext.worker?.version,
993
+ queue: item.options?.queue,
994
+ concurrencyKey: item.options?.concurrencyKey,
995
+ test: taskContext.ctx?.run.isTest,
996
+ payloadType: payloadPacket.dataType,
997
+ idempotencyKey: await makeKey(item.options?.idempotencyKey),
998
+ delay: item.options?.delay,
999
+ ttl: item.options?.ttl,
1000
+ tags: item.options?.tags,
1001
+ maxAttempts: item.options?.maxAttempts
1002
+ }
1003
+ };
1004
+ })),
1005
+ dependentAttempt: ctx.attempt.id
1006
+ }, {}, requestOptions);
1007
+ span.setAttribute("messaging.message.id", response.batchId);
1008
+ const getBatchResults = /* @__PURE__ */ __name(async () => {
1009
+ const hasIdempotencyKey = items.some((item) => item.options?.idempotencyKey);
1010
+ if (hasIdempotencyKey) {
1011
+ const results = await apiClient.getBatchResults(response.batchId);
1012
+ if (results) {
1013
+ return results;
1014
+ }
1015
+ }
1016
+ return {
1017
+ id: response.batchId,
1018
+ items: []
1019
+ };
1020
+ }, "getBatchResults");
1021
+ const existingResults = await getBatchResults();
1022
+ const incompleteRuns = response.runs.filter((runId) => !existingResults.items.some((item) => item.id === runId));
1023
+ if (incompleteRuns.length === 0) {
1024
+ logger.log(`Results reused from previous task runs because of the provided idempotency keys.`);
1025
+ const runs3 = await handleBatchTaskRunExecutionResult(existingResults.items);
1026
+ return {
1027
+ id: existingResults.id,
1028
+ runs: runs3
1029
+ };
1030
+ }
1031
+ const result = await runtime.waitForBatch({
1032
+ id: response.batchId,
1033
+ runs: incompleteRuns,
1034
+ ctx
1035
+ });
1036
+ const combinedItems = [];
1037
+ for (const runId of response.runs) {
1038
+ const existingItem = existingResults.items.find((item) => item.id === runId);
1039
+ if (existingItem) {
1040
+ combinedItems.push(existingItem);
1041
+ } else {
1042
+ const newItem = result.items.find((item) => item.id === runId);
1043
+ if (newItem) {
1044
+ combinedItems.push(newItem);
1045
+ }
1046
+ }
1047
+ }
1048
+ const runs2 = await handleBatchTaskRunExecutionResult(combinedItems);
1049
+ return {
1050
+ id: result.id,
1051
+ runs: runs2
1052
+ };
1053
+ }, {
1054
+ kind: SpanKind.PRODUCER,
1055
+ attributes: {
1056
+ [SemanticInternalAttributes.STYLE_ICON]: "trigger",
1057
+ ["messaging.batch.message_count"]: items.length,
1058
+ [SEMATTRS_MESSAGING_OPERATION]: "publish",
1059
+ ["messaging.client_id"]: taskContext.worker?.id,
1060
+ [SEMATTRS_MESSAGING_DESTINATION]: id,
1061
+ [SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
1062
+ ...accessoryAttributes({
1063
+ items: [
1064
+ {
1065
+ text: id,
1066
+ variant: "normal"
1067
+ }
1068
+ ],
1069
+ style: "codepath"
1070
+ })
1071
+ }
1072
+ });
1073
+ }
1074
+ __name(batchTriggerAndWait_internal, "batchTriggerAndWait_internal");
1075
+ async function handleBatchTaskRunExecutionResult(items) {
1076
+ const someObjectStoreOutputs = items.some((item) => item.ok && item.outputType === "application/store");
1077
+ if (!someObjectStoreOutputs) {
1078
+ const results = await Promise.all(items.map(async (item) => {
1079
+ return await handleTaskRunExecutionResult(item);
1080
+ }));
1081
+ return results;
1082
+ }
1083
+ return await tracer.startActiveSpan("store.downloadPayloads", async (span) => {
1084
+ const results = await Promise.all(items.map(async (item) => {
1085
+ return await handleTaskRunExecutionResult(item);
1086
+ }));
1087
+ return results;
1088
+ }, {
1089
+ kind: SpanKind.INTERNAL,
1090
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
1091
+ });
1092
+ }
1093
+ __name(handleBatchTaskRunExecutionResult, "handleBatchTaskRunExecutionResult");
1094
+ async function handleTaskRunExecutionResult(execution) {
1095
+ if (execution.ok) {
1096
+ const outputPacket = {
1097
+ data: execution.output,
1098
+ dataType: execution.outputType
1099
+ };
1100
+ const importedPacket = await conditionallyImportPacket(outputPacket, tracer);
1101
+ return {
1102
+ ok: true,
1103
+ id: execution.id,
1104
+ output: await parsePacket(importedPacket)
1105
+ };
1106
+ } else {
1107
+ return {
1108
+ ok: false,
1109
+ id: execution.id,
1110
+ error: createErrorTaskError(execution.error)
1111
+ };
1112
+ }
1113
+ }
1114
+ __name(handleTaskRunExecutionResult, "handleTaskRunExecutionResult");
1115
+ function apiClientMissingError() {
1116
+ const hasBaseUrl = !!apiClientManager.baseURL;
1117
+ const hasAccessToken = !!apiClientManager.accessToken;
1118
+ if (!hasBaseUrl && !hasAccessToken) {
1119
+ return `You need to set the TRIGGER_API_URL and TRIGGER_SECRET_KEY environment variables.`;
1120
+ } else if (!hasBaseUrl) {
1121
+ return `You need to set the TRIGGER_API_URL environment variable.`;
1122
+ } else if (!hasAccessToken) {
1123
+ return `You need to set the TRIGGER_SECRET_KEY environment variable.`;
1124
+ }
1125
+ return `Unknown error`;
1126
+ }
1127
+ __name(apiClientMissingError, "apiClientMissingError");
1128
+ async function makeKey(idempotencyKey) {
1129
+ if (!idempotencyKey) {
1130
+ return;
1131
+ }
1132
+ if (isIdempotencyKey(idempotencyKey)) {
1133
+ return idempotencyKey;
1134
+ }
1135
+ return await idempotencyKeys.create(idempotencyKey, {
1136
+ scope: "global"
1137
+ });
1138
+ }
1139
+ __name(makeKey, "makeKey");
1140
+
1141
+ // src/v3/tasks.ts
1142
+ function task(options) {
1143
+ return createTask(options);
1144
+ }
1145
+ __name(task, "task");
1146
+ var tasks = {
1147
+ trigger,
1148
+ triggerAndPoll,
1149
+ batchTrigger,
1150
+ triggerAndWait,
1151
+ batchTriggerAndWait
1152
+ };
1153
+ var wait = {
1154
+ for: async (options) => {
1155
+ return tracer.startActiveSpan(`wait.for()`, async (span) => {
1156
+ const durationInMs = calculateDurationInMs(options);
1157
+ await runtime.waitForDuration(durationInMs);
1158
+ }, {
1159
+ attributes: {
1160
+ [SemanticInternalAttributes.STYLE_ICON]: "wait",
1161
+ ...accessoryAttributes({
1162
+ items: [
1163
+ {
1164
+ text: nameForWaitOptions(options),
1165
+ variant: "normal"
1166
+ }
1167
+ ],
1168
+ style: "codepath"
1169
+ })
1170
+ }
1171
+ });
1172
+ },
1173
+ until: async (options) => {
1174
+ return tracer.startActiveSpan(`wait.until()`, async (span) => {
1175
+ const start = Date.now();
1176
+ if (options.throwIfInThePast && options.date < /* @__PURE__ */ new Date()) {
1177
+ throw new Error("Date is in the past");
1178
+ }
1179
+ const durationInMs = options.date.getTime() - start;
1180
+ await runtime.waitForDuration(durationInMs);
1181
+ }, {
1182
+ attributes: {
1183
+ [SemanticInternalAttributes.STYLE_ICON]: "wait",
1184
+ ...accessoryAttributes({
1185
+ items: [
1186
+ {
1187
+ text: options.date.toISOString(),
1188
+ variant: "normal"
1189
+ }
1190
+ ],
1191
+ style: "codepath"
1192
+ })
1193
+ }
1194
+ });
1195
+ }
1196
+ };
1197
+ function nameForWaitOptions(options) {
1198
+ if ("seconds" in options) {
1199
+ return options.seconds === 1 ? `1 second` : `${options.seconds} seconds`;
1200
+ }
1201
+ if ("minutes" in options) {
1202
+ return options.minutes === 1 ? `1 minute` : `${options.minutes} minutes`;
1203
+ }
1204
+ if ("hours" in options) {
1205
+ return options.hours === 1 ? `1 hour` : `${options.hours} hours`;
1206
+ }
1207
+ if ("days" in options) {
1208
+ return options.days === 1 ? `1 day` : `${options.days} days`;
1209
+ }
1210
+ if ("weeks" in options) {
1211
+ return options.weeks === 1 ? `1 week` : `${options.weeks} weeks`;
1212
+ }
1213
+ if ("months" in options) {
1214
+ return options.months === 1 ? `1 month` : `${options.months} months`;
1215
+ }
1216
+ if ("years" in options) {
1217
+ return options.years === 1 ? `1 year` : `${options.years} years`;
1218
+ }
1219
+ return "NaN";
1220
+ }
1221
+ __name(nameForWaitOptions, "nameForWaitOptions");
1222
+ function calculateDurationInMs(options) {
1223
+ if ("seconds" in options) {
1224
+ return options.seconds * 1e3;
1225
+ }
1226
+ if ("minutes" in options) {
1227
+ return options.minutes * 1e3 * 60;
1228
+ }
1229
+ if ("hours" in options) {
1230
+ return options.hours * 1e3 * 60 * 60;
1231
+ }
1232
+ if ("days" in options) {
1233
+ return options.days * 1e3 * 60 * 60 * 24;
1234
+ }
1235
+ if ("weeks" in options) {
1236
+ return options.weeks * 1e3 * 60 * 60 * 24 * 7;
1237
+ }
1238
+ if ("months" in options) {
1239
+ return options.months * 1e3 * 60 * 60 * 24 * 30;
1240
+ }
1241
+ if ("years" in options) {
1242
+ return options.years * 1e3 * 60 * 60 * 24 * 365;
1243
+ }
1244
+ throw new Error("Invalid options");
1245
+ }
1246
+ __name(calculateDurationInMs, "calculateDurationInMs");
1247
+ var usage = {
1248
+ /**
1249
+ * Get the current running usage of this task run.
1250
+ *
1251
+ * @example
1252
+ *
1253
+ * ```typescript
1254
+ * import { usage, task } from "@trigger.dev/sdk/v3";
1255
+ *
1256
+ * export const myTask = task({
1257
+ * id: "my-task",
1258
+ * run: async (payload, { ctx }) => {
1259
+ * // ... Do a bunch of work
1260
+ *
1261
+ * const currentUsage = usage.getCurrent();
1262
+ *
1263
+ * // You have access to the current compute cost and duration up to this point
1264
+ * console.log("Current attempt compute cost and duration", {
1265
+ * cost: currentUsage.compute.attempt.costInCents,
1266
+ * duration: currentUsage.compute.attempt.durationMs,
1267
+ * });
1268
+ *
1269
+ * // You also can see the total compute cost and duration up to this point in the run, across all attempts
1270
+ * console.log("Current total compute cost and duration", {
1271
+ * cost: currentUsage.compute.total.costInCents,
1272
+ * duration: currentUsage.compute.total.durationMs,
1273
+ * });
1274
+ *
1275
+ * // You can see the base cost of the run, which is the cost of the run before any compute costs
1276
+ * console.log("Total cost", {
1277
+ * cost: currentUsage.totalCostInCents,
1278
+ * baseCost: currentUsage.baseCostInCents,
1279
+ * });
1280
+ * },
1281
+ * });
1282
+ * ```
1283
+ */
1284
+ getCurrent: () => {
1285
+ const sample = usage$1.sample();
1286
+ const machine = taskContext.ctx?.machine;
1287
+ const run = taskContext.ctx?.run;
1288
+ if (!sample) {
1289
+ return {
1290
+ compute: {
1291
+ attempt: {
1292
+ costInCents: 0,
1293
+ durationMs: 0
1294
+ },
1295
+ total: {
1296
+ costInCents: run?.costInCents ?? 0,
1297
+ durationMs: run?.durationMs ?? 0
1298
+ }
1299
+ },
1300
+ baseCostInCents: run?.baseCostInCents ?? 0,
1301
+ totalCostInCents: (run?.costInCents ?? 0) + (run?.baseCostInCents ?? 0)
1302
+ };
1303
+ }
1304
+ const currentCostInCents = machine?.centsPerMs ? sample.cpuTime * machine.centsPerMs : 0;
1305
+ return {
1306
+ compute: {
1307
+ attempt: {
1308
+ costInCents: currentCostInCents,
1309
+ durationMs: sample.cpuTime
1310
+ },
1311
+ total: {
1312
+ costInCents: (run?.costInCents ?? 0) + currentCostInCents,
1313
+ durationMs: (run?.durationMs ?? 0) + sample.cpuTime
1314
+ }
1315
+ },
1316
+ baseCostInCents: run?.baseCostInCents ?? 0,
1317
+ totalCostInCents: (run?.costInCents ?? 0) + currentCostInCents + (run?.baseCostInCents ?? 0)
1318
+ };
1319
+ },
1320
+ /**
1321
+ * Measure the cost and duration of a function.
1322
+ *
1323
+ * @example
1324
+ *
1325
+ * ```typescript
1326
+ * import { usage } from "@trigger.dev/sdk/v3";
1327
+ *
1328
+ * export const myTask = task({
1329
+ * id: "my-task",
1330
+ * run: async (payload, { ctx }) => {
1331
+ * const { result, compute } = await usage.measure(async () => {
1332
+ * // Do some work
1333
+ * return "result";
1334
+ * });
1335
+ *
1336
+ * console.log("Result", result);
1337
+ * console.log("Cost and duration", { cost: compute.costInCents, duration: compute.durationMs });
1338
+ * },
1339
+ * });
1340
+ * ```
1341
+ */
1342
+ measure: async (cb) => {
1343
+ const measurement = usage$1.start();
1344
+ const result = await cb();
1345
+ const sample = usage$1.stop(measurement);
1346
+ const machine = taskContext.ctx?.machine;
1347
+ const costInCents = machine?.centsPerMs ? sample.cpuTime * machine.centsPerMs : 0;
1348
+ return {
1349
+ result,
1350
+ compute: {
1351
+ costInCents,
1352
+ durationMs: sample.cpuTime
1353
+ }
1354
+ };
1355
+ }
1356
+ };
1357
+ var tags = {
1358
+ add: addTags
1359
+ };
1360
+ async function addTags(tags2, requestOptions) {
1361
+ const apiClient = apiClientManager.client;
1362
+ if (!apiClient) {
1363
+ throw apiClientMissingError();
1364
+ }
1365
+ const run = taskContext.ctx?.run;
1366
+ if (!run) {
1367
+ throw new Error("Can't set tags outside of a run. You can trigger a task and set tags in the options.");
1368
+ }
1369
+ const $requestOptions = mergeRequestOptions({
1370
+ tracer,
1371
+ name: "tags.set()",
1372
+ icon: "tag",
1373
+ attributes: {
1374
+ ...accessoryAttributes({
1375
+ items: [
1376
+ {
1377
+ text: typeof tags2 === "string" ? tags2 : tags2.join(", "),
1378
+ variant: "normal"
1379
+ }
1380
+ ],
1381
+ style: "codepath"
1382
+ })
1383
+ }
1384
+ }, requestOptions);
1385
+ try {
1386
+ await apiClient.addTags(run.id, {
1387
+ tags: tags2
1388
+ }, $requestOptions);
1389
+ } catch (error) {
1390
+ if (error instanceof UnprocessableEntityError) {
1391
+ logger.error(error.message, {
1392
+ existingTags: run.tags,
1393
+ newTags: tags2
1394
+ });
1395
+ return;
1396
+ }
1397
+ logger.error("Failed to set tags", {
1398
+ error
1399
+ });
1400
+ throw error;
1401
+ }
1402
+ }
1403
+ __name(addTags, "addTags");
1404
+
1405
+ // src/v3/schedules/index.ts
1406
+ var schedules_exports = {};
1407
+ __export(schedules_exports, {
1408
+ activate: () => activate,
1409
+ create: () => create,
1410
+ deactivate: () => deactivate,
1411
+ del: () => del,
1412
+ list: () => list,
1413
+ retrieve: () => retrieve,
1414
+ task: () => task2,
1415
+ timezones: () => timezones,
1416
+ update: () => update
1417
+ });
1418
+ function task2(params) {
1419
+ const task3 = createTask(params);
1420
+ const cron = params.cron ? typeof params.cron === "string" ? params.cron : params.cron.pattern : void 0;
1421
+ const timezone = (params.cron && typeof params.cron !== "string" ? params.cron.timezone : "UTC") ?? "UTC";
1422
+ taskCatalog.updateTaskMetadata(task3.id, {
1423
+ triggerSource: "schedule",
1424
+ schedule: cron ? {
1425
+ cron,
1426
+ timezone
1427
+ } : void 0
1428
+ });
1429
+ return task3;
1430
+ }
1431
+ __name(task2, "task");
1432
+ function create(options, requestOptions) {
1433
+ const apiClient = apiClientManager.client;
1434
+ if (!apiClient) {
1435
+ throw apiClientMissingError();
1436
+ }
1437
+ const $requestOptions = mergeRequestOptions({
1438
+ tracer,
1439
+ name: "schedules.create()",
1440
+ icon: "clock",
1441
+ attributes: {
1442
+ ...accessoryAttributes({
1443
+ items: [
1444
+ {
1445
+ text: options.cron,
1446
+ variant: "normal"
1447
+ }
1448
+ ],
1449
+ style: "codepath"
1450
+ })
1451
+ }
1452
+ }, requestOptions);
1453
+ return apiClient.createSchedule(options, $requestOptions);
1454
+ }
1455
+ __name(create, "create");
1456
+ function retrieve(scheduleId, requestOptions) {
1457
+ const apiClient = apiClientManager.client;
1458
+ if (!apiClient) {
1459
+ throw apiClientMissingError();
1460
+ }
1461
+ const $requestOptions = mergeRequestOptions({
1462
+ tracer,
1463
+ name: "schedules.retrieve()",
1464
+ icon: "clock",
1465
+ attributes: {
1466
+ scheduleId,
1467
+ ...accessoryAttributes({
1468
+ items: [
1469
+ {
1470
+ text: scheduleId,
1471
+ variant: "normal"
1472
+ }
1473
+ ],
1474
+ style: "codepath"
1475
+ })
1476
+ }
1477
+ }, requestOptions);
1478
+ return apiClient.retrieveSchedule(scheduleId, $requestOptions);
1479
+ }
1480
+ __name(retrieve, "retrieve");
1481
+ function update(scheduleId, options, requestOptions) {
1482
+ const apiClient = apiClientManager.client;
1483
+ if (!apiClient) {
1484
+ throw apiClientMissingError();
1485
+ }
1486
+ const $requestOptions = mergeRequestOptions({
1487
+ tracer,
1488
+ name: "schedules.update()",
1489
+ icon: "clock",
1490
+ attributes: {
1491
+ scheduleId,
1492
+ ...accessoryAttributes({
1493
+ items: [
1494
+ {
1495
+ text: scheduleId,
1496
+ variant: "normal"
1497
+ }
1498
+ ],
1499
+ style: "codepath"
1500
+ })
1501
+ }
1502
+ }, requestOptions);
1503
+ return apiClient.updateSchedule(scheduleId, options, $requestOptions);
1504
+ }
1505
+ __name(update, "update");
1506
+ function del(scheduleId, requestOptions) {
1507
+ const apiClient = apiClientManager.client;
1508
+ if (!apiClient) {
1509
+ throw apiClientMissingError();
1510
+ }
1511
+ const $requestOptions = mergeRequestOptions({
1512
+ tracer,
1513
+ name: "schedules.delete()",
1514
+ icon: "clock",
1515
+ attributes: {
1516
+ scheduleId,
1517
+ ...accessoryAttributes({
1518
+ items: [
1519
+ {
1520
+ text: scheduleId,
1521
+ variant: "normal"
1522
+ }
1523
+ ],
1524
+ style: "codepath"
1525
+ })
1526
+ }
1527
+ }, requestOptions);
1528
+ return apiClient.deleteSchedule(scheduleId, $requestOptions);
1529
+ }
1530
+ __name(del, "del");
1531
+ function deactivate(scheduleId, requestOptions) {
1532
+ const apiClient = apiClientManager.client;
1533
+ if (!apiClient) {
1534
+ throw apiClientMissingError();
1535
+ }
1536
+ const $requestOptions = mergeRequestOptions({
1537
+ tracer,
1538
+ name: "schedules.deactivate()",
1539
+ icon: "clock",
1540
+ attributes: {
1541
+ scheduleId,
1542
+ ...accessoryAttributes({
1543
+ items: [
1544
+ {
1545
+ text: scheduleId,
1546
+ variant: "normal"
1547
+ }
1548
+ ],
1549
+ style: "codepath"
1550
+ })
1551
+ }
1552
+ }, requestOptions);
1553
+ return apiClient.deactivateSchedule(scheduleId, $requestOptions);
1554
+ }
1555
+ __name(deactivate, "deactivate");
1556
+ function activate(scheduleId, requestOptions) {
1557
+ const apiClient = apiClientManager.client;
1558
+ if (!apiClient) {
1559
+ throw apiClientMissingError();
1560
+ }
1561
+ const $requestOptions = mergeRequestOptions({
1562
+ tracer,
1563
+ name: "schedules.activate()",
1564
+ icon: "clock",
1565
+ attributes: {
1566
+ scheduleId,
1567
+ ...accessoryAttributes({
1568
+ items: [
1569
+ {
1570
+ text: scheduleId,
1571
+ variant: "normal"
1572
+ }
1573
+ ],
1574
+ style: "codepath"
1575
+ })
1576
+ }
1577
+ }, requestOptions);
1578
+ return apiClient.activateSchedule(scheduleId, $requestOptions);
1579
+ }
1580
+ __name(activate, "activate");
1581
+ function list(options, requestOptions) {
1582
+ const apiClient = apiClientManager.client;
1583
+ if (!apiClient) {
1584
+ throw apiClientMissingError();
1585
+ }
1586
+ const $requestOptions = mergeRequestOptions({
1587
+ tracer,
1588
+ name: "schedules.list()",
1589
+ icon: "clock"
1590
+ }, requestOptions);
1591
+ return apiClient.listSchedules(options, $requestOptions);
1592
+ }
1593
+ __name(list, "list");
1594
+ function timezones(options) {
1595
+ const baseUrl = apiClientManager.baseURL;
1596
+ if (!baseUrl) {
1597
+ throw apiClientMissingError();
1598
+ }
1599
+ return zodfetch(TimezonesResult, `${baseUrl}/api/v1/timezones${options?.excludeUtc === true ? "?excludeUtc=true" : ""}`, {
1600
+ method: "GET",
1601
+ headers: {
1602
+ "Content-Type": "application/json"
1603
+ }
1604
+ });
1605
+ }
1606
+ __name(timezones, "timezones");
1607
+
1608
+ // src/v3/envvars.ts
1609
+ var envvars_exports = {};
1610
+ __export(envvars_exports, {
1611
+ create: () => create2,
1612
+ del: () => del2,
1613
+ list: () => list2,
1614
+ retrieve: () => retrieve2,
1615
+ update: () => update2,
1616
+ upload: () => upload
1617
+ });
1618
+ function upload(projectRefOrParams, slugOrRequestOptions, params, requestOptions) {
1619
+ let $projectRef;
1620
+ let $params;
1621
+ let $slug;
1622
+ const $requestOptions = overloadRequestOptions("upload", slugOrRequestOptions, requestOptions);
1623
+ if (taskContext.ctx) {
1624
+ if (typeof projectRefOrParams === "string") {
1625
+ $projectRef = projectRefOrParams;
1626
+ $slug = typeof slugOrRequestOptions === "string" ? slugOrRequestOptions : taskContext.ctx.environment.slug;
1627
+ if (!params) {
1628
+ throw new Error("params is required");
1629
+ }
1630
+ $params = params;
1631
+ } else {
1632
+ $params = projectRefOrParams;
1633
+ $projectRef = taskContext.ctx.project.ref;
1634
+ $slug = taskContext.ctx.environment.slug;
1635
+ }
1636
+ } else {
1637
+ if (typeof projectRefOrParams !== "string") {
1638
+ throw new Error("projectRef is required");
1639
+ }
1640
+ if (!slugOrRequestOptions || typeof slugOrRequestOptions !== "string") {
1641
+ throw new Error("slug is required");
1642
+ }
1643
+ if (!params) {
1644
+ throw new Error("params is required");
1645
+ }
1646
+ $projectRef = projectRefOrParams;
1647
+ $slug = slugOrRequestOptions;
1648
+ $params = params;
1649
+ }
1650
+ const apiClient = apiClientManager.client;
1651
+ if (!apiClient) {
1652
+ throw apiClientMissingError();
1653
+ }
1654
+ return apiClient.importEnvVars($projectRef, $slug, $params, $requestOptions);
1655
+ }
1656
+ __name(upload, "upload");
1657
+ function list2(projectRefOrRequestOptions, slug, requestOptions) {
1658
+ const $projectRef = !isRequestOptions(projectRefOrRequestOptions) ? projectRefOrRequestOptions : taskContext.ctx?.project.ref;
1659
+ const $slug = slug ?? taskContext.ctx?.environment.slug;
1660
+ let $requestOptions = isRequestOptions(projectRefOrRequestOptions) ? projectRefOrRequestOptions : requestOptions;
1661
+ if (!$projectRef) {
1662
+ throw new Error("projectRef is required");
1663
+ }
1664
+ if (!$slug) {
1665
+ throw new Error("slug is required");
1666
+ }
1667
+ $requestOptions = mergeRequestOptions({
1668
+ tracer,
1669
+ name: "envvars.list()",
1670
+ icon: "id-badge"
1671
+ }, $requestOptions);
1672
+ const apiClient = apiClientManager.client;
1673
+ if (!apiClient) {
1674
+ throw apiClientMissingError();
1675
+ }
1676
+ return apiClient.listEnvVars($projectRef, $slug, $requestOptions);
1677
+ }
1678
+ __name(list2, "list");
1679
+ function create2(projectRefOrParams, slugOrRequestOptions, params, requestOptions) {
1680
+ let $projectRef;
1681
+ let $slug;
1682
+ let $params;
1683
+ const $requestOptions = overloadRequestOptions("create", slugOrRequestOptions, requestOptions);
1684
+ if (taskContext.ctx) {
1685
+ if (typeof projectRefOrParams === "string") {
1686
+ $projectRef = projectRefOrParams;
1687
+ $slug = typeof slugOrRequestOptions === "string" ? slugOrRequestOptions : taskContext.ctx.environment.slug;
1688
+ if (!params) {
1689
+ throw new Error("params is required");
1690
+ }
1691
+ $params = params;
1692
+ } else {
1693
+ $params = projectRefOrParams;
1694
+ $projectRef = taskContext.ctx.project.ref;
1695
+ $slug = taskContext.ctx.environment.slug;
1696
+ }
1697
+ } else {
1698
+ if (typeof projectRefOrParams !== "string") {
1699
+ throw new Error("projectRef is required");
1700
+ }
1701
+ if (!slugOrRequestOptions || typeof slugOrRequestOptions !== "string") {
1702
+ throw new Error("slug is required");
1703
+ }
1704
+ if (!params) {
1705
+ throw new Error("params is required");
1706
+ }
1707
+ $projectRef = projectRefOrParams;
1708
+ $slug = slugOrRequestOptions;
1709
+ $params = params;
1710
+ }
1711
+ const apiClient = apiClientManager.client;
1712
+ if (!apiClient) {
1713
+ throw apiClientMissingError();
1714
+ }
1715
+ return apiClient.createEnvVar($projectRef, $slug, $params, $requestOptions);
1716
+ }
1717
+ __name(create2, "create");
1718
+ function retrieve2(projectRefOrName, slugOrRequestOptions, name1, requestOptions) {
1719
+ let $projectRef;
1720
+ let $slug;
1721
+ let $name;
1722
+ const $requestOptions = overloadRequestOptions("retrieve", slugOrRequestOptions, requestOptions);
1723
+ if (typeof name1 === "string") {
1724
+ $projectRef = projectRefOrName;
1725
+ $slug = typeof slugOrRequestOptions === "string" ? slugOrRequestOptions : taskContext.ctx?.environment.slug;
1726
+ $name = name1;
1727
+ } else {
1728
+ $projectRef = taskContext.ctx?.project.ref;
1729
+ $slug = taskContext.ctx?.environment.slug;
1730
+ $name = projectRefOrName;
1731
+ }
1732
+ if (!$projectRef) {
1733
+ throw new Error("projectRef is required");
1734
+ }
1735
+ if (!$slug) {
1736
+ throw new Error("slug is required");
1737
+ }
1738
+ const apiClient = apiClientManager.client;
1739
+ if (!apiClient) {
1740
+ throw apiClientMissingError();
1741
+ }
1742
+ return apiClient.retrieveEnvVar($projectRef, $slug, $name, $requestOptions);
1743
+ }
1744
+ __name(retrieve2, "retrieve");
1745
+ function del2(projectRefOrName, slugOrRequestOptions, name1, requestOptions) {
1746
+ let $projectRef;
1747
+ let $slug;
1748
+ let $name;
1749
+ const $requestOptions = overloadRequestOptions("del", slugOrRequestOptions, requestOptions);
1750
+ if (typeof name1 === "string") {
1751
+ $projectRef = projectRefOrName;
1752
+ $slug = typeof slugOrRequestOptions === "string" ? slugOrRequestOptions : taskContext.ctx?.environment.slug;
1753
+ $name = name1;
1754
+ } else {
1755
+ $projectRef = taskContext.ctx?.project.ref;
1756
+ $slug = taskContext.ctx?.environment.slug;
1757
+ $name = projectRefOrName;
1758
+ }
1759
+ if (!$projectRef) {
1760
+ throw new Error("projectRef is required");
1761
+ }
1762
+ if (!$slug) {
1763
+ throw new Error("slug is required");
1764
+ }
1765
+ const apiClient = apiClientManager.client;
1766
+ if (!apiClient) {
1767
+ throw apiClientMissingError();
1768
+ }
1769
+ return apiClient.deleteEnvVar($projectRef, $slug, $name, $requestOptions);
1770
+ }
1771
+ __name(del2, "del");
1772
+ function update2(projectRefOrName, slugOrParams, nameOrRequestOptions, params, requestOptions) {
1773
+ let $projectRef;
1774
+ let $slug;
1775
+ let $name;
1776
+ let $params;
1777
+ const $requestOptions = overloadRequestOptions("update", nameOrRequestOptions, requestOptions);
1778
+ if (taskContext.ctx) {
1779
+ if (typeof slugOrParams === "string") {
1780
+ $projectRef = slugOrParams;
1781
+ $slug = slugOrParams ?? taskContext.ctx.environment.slug;
1782
+ $name = typeof nameOrRequestOptions === "string" ? nameOrRequestOptions : taskContext.ctx.environment.slug;
1783
+ if (!params) {
1784
+ throw new Error("params is required");
1785
+ }
1786
+ $params = params;
1787
+ } else {
1788
+ $params = slugOrParams;
1789
+ $projectRef = taskContext.ctx.project.ref;
1790
+ $slug = taskContext.ctx.environment.slug;
1791
+ $name = projectRefOrName;
1792
+ }
1793
+ } else {
1794
+ if (typeof slugOrParams !== "string") {
1795
+ throw new Error("slug is required");
1796
+ }
1797
+ if (!projectRefOrName) {
1798
+ throw new Error("projectRef is required");
1799
+ }
1800
+ if (!params) {
1801
+ throw new Error("params is required");
1802
+ }
1803
+ $projectRef = projectRefOrName;
1804
+ $slug = slugOrParams;
1805
+ $name = name;
1806
+ $params = params;
1807
+ }
1808
+ const apiClient = apiClientManager.client;
1809
+ if (!apiClient) {
1810
+ throw apiClientMissingError();
1811
+ }
1812
+ return apiClient.updateEnvVar($projectRef, $slug, $name, $params, $requestOptions);
1813
+ }
1814
+ __name(update2, "update");
1815
+ function overloadRequestOptions(name1, slugOrRequestOptions, requestOptions) {
1816
+ if (isRequestOptions(slugOrRequestOptions)) {
1817
+ return mergeRequestOptions({
1818
+ tracer,
1819
+ name: `envvars.${name1}()`,
1820
+ icon: "id-badge"
1821
+ }, slugOrRequestOptions);
1822
+ } else {
1823
+ return mergeRequestOptions({
1824
+ tracer,
1825
+ name: `envvars.${name1}()`,
1826
+ icon: "id-badge"
1827
+ }, requestOptions);
1828
+ }
1829
+ }
1830
+ __name(overloadRequestOptions, "overloadRequestOptions");
1831
+
1832
+ // src/v3/index.ts
1833
+ function configure(options) {
1834
+ apiClientManager.setGlobalAPIClientConfiguration(options);
1835
+ }
1836
+ __name(configure, "configure");
880
1837
 
881
- export { InMemoryCache, createCache, retry, task, wait };
1838
+ export { InMemoryCache, configure, createCache, envvars_exports as envvars, idempotencyKeys, isIdempotencyKey, queue, retry, runs, schedules_exports as schedules, tags, task, tasks, usage, wait };
882
1839
  //# sourceMappingURL=out.js.map
883
1840
  //# sourceMappingURL=index.mjs.map