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