@trigger.dev/sdk 3.0.0-beta.4 → 3.0.0-beta.41

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,524 +1,149 @@
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 promises = require('timers/promises');
8
+ var zodfetch = require('@trigger.dev/core/v3/zodfetch');
7
9
 
8
10
  var __defProp = Object.defineProperty;
9
11
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
12
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
11
17
  var __publicField = (obj, key, value) => {
12
18
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
13
19
  return value;
14
20
  };
15
21
 
16
22
  // package.json
17
- var version = "3.0.0-beta.4";
23
+ var version = "3.0.0-beta.41";
24
+
25
+ // src/v3/tracer.ts
18
26
  var tracer = new v3.TriggerTracer({
19
27
  name: "@trigger.dev/sdk",
20
28
  version
21
29
  });
22
30
 
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();
31
+ // src/v3/cache.ts
32
+ var _InMemoryCache = class _InMemoryCache {
33
+ constructor() {
34
+ __publicField(this, "_cache", /* @__PURE__ */ new Map());
35
+ }
36
+ get(key) {
37
+ return this._cache.get(key);
38
+ }
39
+ set(key, value) {
40
+ this._cache.set(key, value);
41
+ return void 0;
42
+ }
43
+ delete(key) {
44
+ this._cache.delete(key);
45
+ return void 0;
46
+ }
47
+ };
48
+ __name(_InMemoryCache, "InMemoryCache");
49
+ var InMemoryCache = _InMemoryCache;
50
+ function createCache(store) {
51
+ return /* @__PURE__ */ __name(function cache(cacheKey, fn) {
52
+ return tracer.startActiveSpan("cache", async (span) => {
53
+ span.setAttribute("cache.key", cacheKey);
54
+ span.setAttribute(v3.SemanticInternalAttributes.STYLE_ICON, "device-sd-card");
55
+ const cacheEntry = await store.get(cacheKey);
56
+ if (cacheEntry) {
57
+ span.updateName(`cache.hit ${cacheKey}`);
58
+ return cacheEntry.value;
30
59
  }
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;
60
+ span.updateName(`cache.miss ${cacheKey}`);
61
+ const value = await tracer.startActiveSpan("cache.getFreshValue", async (span2) => {
62
+ return await fn();
48
63
  }, {
49
- kind: api.SpanKind.PRODUCER,
50
64
  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
- }) : {}
65
+ "cache.key": cacheKey,
66
+ [v3.SemanticInternalAttributes.STYLE_ICON]: "device-sd-card"
66
67
  }
67
68
  });
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
69
+ await tracer.startActiveSpan("cache.set", async (span2) => {
70
+ await store.set(cacheKey, {
71
+ value,
72
+ metadata: {
73
+ createdTime: Date.now()
74
+ }
88
75
  });
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
76
  }, {
95
- kind: api.SpanKind.PRODUCER,
96
77
  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
- }) : {}
78
+ "cache.key": cacheKey,
79
+ [v3.SemanticInternalAttributes.STYLE_ICON]: "device-sd-card"
113
80
  }
114
81
  });
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,
82
+ return value;
83
+ });
84
+ }, "cache");
85
+ }
86
+ __name(createCache, "createCache");
87
+ function onThrow(fn, options) {
88
+ const opts = {
89
+ ...v3.defaultRetryOptions,
90
+ ...options
91
+ };
92
+ return tracer.startActiveSpan(`retry.onThrow()`, async (span) => {
93
+ let attempt = 1;
94
+ while (attempt <= opts.maxAttempts) {
95
+ const innerSpan = tracer.startSpan("retry.fn()", {
153
96
  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({
97
+ [v3.SemanticInternalAttributes.STYLE_ICON]: "function",
98
+ ...v3.accessoryAttributes({
160
99
  items: [
161
100
  {
162
- text: `${taskMetadata.exportName}.triggerAndWait()`,
101
+ text: `${attempt}/${opts.maxAttempts}`,
163
102
  variant: "normal"
164
103
  }
165
104
  ],
166
105
  style: "codepath"
167
- }) : {}
106
+ })
168
107
  }
169
108
  });
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
109
+ const contextWithSpanSet = api.trace.setSpan(api.context.active(), innerSpan);
110
+ try {
111
+ const result = await api.context.with(contextWithSpanSet, async () => {
112
+ return fn({
113
+ attempt,
114
+ maxAttempts: opts.maxAttempts
115
+ });
193
116
  });
194
- if (!response.ok) {
195
- throw new Error(response.error);
117
+ innerSpan.end();
118
+ return result;
119
+ } catch (e) {
120
+ if (e instanceof Error || typeof e === "string") {
121
+ innerSpan.recordException(e);
122
+ } else {
123
+ innerSpan.recordException(String(e));
196
124
  }
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
125
+ innerSpan.setStatus({
126
+ code: api.SpanStatusCode.ERROR
202
127
  });
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
- }) : {}
128
+ const nextRetryDelay = v3.calculateNextRetryDelay(opts, attempt);
129
+ if (!nextRetryDelay) {
130
+ innerSpan.end();
131
+ throw e;
227
132
  }
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
133
+ innerSpan.setAttribute(v3.SemanticInternalAttributes.RETRY_AT, new Date(Date.now() + nextRetryDelay).toISOString());
134
+ innerSpan.setAttribute(v3.SemanticInternalAttributes.RETRY_COUNT, attempt);
135
+ innerSpan.setAttribute(v3.SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);
136
+ innerSpan.end();
137
+ await v3.runtime.waitForDuration(nextRetryDelay);
138
+ } finally {
139
+ attempt++;
247
140
  }
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;
141
+ }
142
+ throw new Error("Max attempts reached");
267
143
  }, {
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");
407
- var _InMemoryCache = class _InMemoryCache {
408
- constructor() {
409
- __publicField(this, "_cache", /* @__PURE__ */ new Map());
410
- }
411
- get(key) {
412
- return this._cache.get(key);
413
- }
414
- set(key, value) {
415
- this._cache.set(key, value);
416
- return void 0;
417
- }
418
- delete(key) {
419
- this._cache.delete(key);
420
- return void 0;
421
- }
422
- };
423
- __name(_InMemoryCache, "InMemoryCache");
424
- var InMemoryCache = _InMemoryCache;
425
- function createCache(store) {
426
- return /* @__PURE__ */ __name(function cache(cacheKey, fn) {
427
- return tracer.startActiveSpan("cache", async (span) => {
428
- span.setAttribute("cache.key", cacheKey);
429
- span.setAttribute(v3.SemanticInternalAttributes.STYLE_ICON, "device-sd-card");
430
- const cacheEntry = await store.get(cacheKey);
431
- if (cacheEntry) {
432
- span.updateName(`cache.hit ${cacheKey}`);
433
- return cacheEntry.value;
434
- }
435
- span.updateName(`cache.miss ${cacheKey}`);
436
- const value = await tracer.startActiveSpan("cache.getFreshValue", async (span2) => {
437
- return await fn();
438
- }, {
439
- attributes: {
440
- "cache.key": cacheKey,
441
- [v3.SemanticInternalAttributes.STYLE_ICON]: "device-sd-card"
442
- }
443
- });
444
- await tracer.startActiveSpan("cache.set", async (span2) => {
445
- await store.set(cacheKey, {
446
- value,
447
- metadata: {
448
- createdTime: Date.now()
449
- }
450
- });
451
- }, {
452
- attributes: {
453
- "cache.key": cacheKey,
454
- [v3.SemanticInternalAttributes.STYLE_ICON]: "device-sd-card"
455
- }
456
- });
457
- return value;
458
- });
459
- }, "cache");
460
- }
461
- __name(createCache, "createCache");
462
- function onThrow(fn, options) {
463
- const opts = {
464
- ...v3.defaultRetryOptions,
465
- ...options
466
- };
467
- return tracer.startActiveSpan(`retry.onThrow()`, async (span) => {
468
- let attempt = 1;
469
- while (attempt <= opts.maxAttempts) {
470
- const innerSpan = tracer.startSpan("retry.fn()", {
471
- attributes: {
472
- [v3.SemanticInternalAttributes.STYLE_ICON]: "function",
473
- ...v3.accessoryAttributes({
474
- items: [
475
- {
476
- text: `${attempt}/${opts.maxAttempts}`,
477
- variant: "normal"
478
- }
479
- ],
480
- style: "codepath"
481
- })
482
- }
483
- });
484
- const contextWithSpanSet = api.trace.setSpan(api.context.active(), innerSpan);
485
- try {
486
- const result = await api.context.with(contextWithSpanSet, async () => {
487
- return fn({
488
- attempt,
489
- maxAttempts: opts.maxAttempts
490
- });
491
- });
492
- innerSpan.end();
493
- return result;
494
- } catch (e) {
495
- if (e instanceof Error || typeof e === "string") {
496
- innerSpan.recordException(e);
497
- } else {
498
- innerSpan.recordException(String(e));
499
- }
500
- innerSpan.setStatus({
501
- code: api.SpanStatusCode.ERROR
502
- });
503
- const nextRetryDelay = v3.calculateNextRetryDelay(opts, attempt);
504
- if (!nextRetryDelay) {
505
- innerSpan.end();
506
- throw e;
507
- }
508
- innerSpan.setAttribute(v3.SemanticInternalAttributes.RETRY_AT, new Date(Date.now() + nextRetryDelay).toISOString());
509
- innerSpan.setAttribute(v3.SemanticInternalAttributes.RETRY_COUNT, attempt);
510
- innerSpan.setAttribute(v3.SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);
511
- innerSpan.end();
512
- await v3.runtime.waitForDuration(nextRetryDelay);
513
- } finally {
514
- attempt++;
515
- }
516
- }
517
- throw new Error("Max attempts reached");
518
- }, {
519
- attributes: {
520
- [v3.SemanticInternalAttributes.STYLE_ICON]: "arrow-capsule"
521
- }
144
+ attributes: {
145
+ [v3.SemanticInternalAttributes.STYLE_ICON]: "arrow-capsule"
146
+ }
522
147
  });
523
148
  }
524
149
  __name(onThrow, "onThrow");
@@ -878,15 +503,1014 @@ var retry = {
878
503
  fetch: retryFetch,
879
504
  interceptFetch
880
505
  };
506
+ var runs = {
507
+ replay: replayRun,
508
+ cancel: cancelRun,
509
+ retrieve: retrieveRun,
510
+ list: listRuns,
511
+ poll
512
+ };
513
+ function listRuns(paramsOrProjectRef, params) {
514
+ const apiClient = v3.apiClientManager.client;
515
+ if (!apiClient) {
516
+ throw apiClientMissingError();
517
+ }
518
+ if (typeof paramsOrProjectRef === "string") {
519
+ return apiClient.listProjectRuns(paramsOrProjectRef, params);
520
+ }
521
+ return apiClient.listRuns(params);
522
+ }
523
+ __name(listRuns, "listRuns");
524
+ function retrieveRun(runId) {
525
+ const apiClient = v3.apiClientManager.client;
526
+ if (!apiClient) {
527
+ throw apiClientMissingError();
528
+ }
529
+ if (typeof runId === "string") {
530
+ return apiClient.retrieveRun(runId);
531
+ } else {
532
+ return apiClient.retrieveRun(runId.id);
533
+ }
534
+ }
535
+ __name(retrieveRun, "retrieveRun");
536
+ function replayRun(runId) {
537
+ const apiClient = v3.apiClientManager.client;
538
+ if (!apiClient) {
539
+ throw apiClientMissingError();
540
+ }
541
+ return apiClient.replayRun(runId);
542
+ }
543
+ __name(replayRun, "replayRun");
544
+ function cancelRun(runId) {
545
+ const apiClient = v3.apiClientManager.client;
546
+ if (!apiClient) {
547
+ throw apiClientMissingError();
548
+ }
549
+ return apiClient.cancelRun(runId);
550
+ }
551
+ __name(cancelRun, "cancelRun");
552
+ async function poll(handle, options) {
553
+ while (true) {
554
+ const run = await runs.retrieve(handle);
555
+ if (run.isCompleted) {
556
+ return run;
557
+ }
558
+ await promises.setTimeout(Math.max(options?.pollIntervalMs ?? 5e3, 1e3));
559
+ }
560
+ }
561
+ __name(poll, "poll");
881
562
 
882
- Object.defineProperty(exports, 'logger', {
563
+ // src/v3/shared.ts
564
+ function queue(options) {
565
+ return options;
566
+ }
567
+ __name(queue, "queue");
568
+ function createTask(params) {
569
+ const task3 = {
570
+ id: params.id,
571
+ trigger: async (payload, options) => {
572
+ const apiClient = v3.apiClientManager.client;
573
+ if (!apiClient) {
574
+ throw apiClientMissingError();
575
+ }
576
+ const taskMetadata = v3.taskCatalog.getTaskMetadata(params.id);
577
+ const payloadPacket = await v3.stringifyIO(payload);
578
+ const handle = await tracer.startActiveSpan(taskMetadata ? "Trigger" : `${params.id} trigger()`, async (span) => {
579
+ const response = await apiClient.triggerTask(params.id, {
580
+ payload: payloadPacket.data,
581
+ options: {
582
+ queue: options?.queue ?? params.queue,
583
+ concurrencyKey: options?.concurrencyKey,
584
+ test: v3.taskContext.ctx?.run.isTest,
585
+ payloadType: payloadPacket.dataType,
586
+ idempotencyKey: options?.idempotencyKey
587
+ }
588
+ }, {
589
+ spanParentAsLink: true
590
+ });
591
+ span.setAttribute("messaging.message.id", response.id);
592
+ return response;
593
+ }, {
594
+ kind: api.SpanKind.PRODUCER,
595
+ attributes: {
596
+ [semanticConventions.SEMATTRS_MESSAGING_OPERATION]: "publish",
597
+ [v3.SemanticInternalAttributes.STYLE_ICON]: "trigger",
598
+ ["messaging.client_id"]: v3.taskContext.worker?.id,
599
+ [semanticConventions.SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
600
+ [semanticConventions.SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
601
+ ...taskMetadata ? v3.accessoryAttributes({
602
+ items: [
603
+ {
604
+ text: `${taskMetadata.exportName}.trigger()`,
605
+ variant: "normal"
606
+ }
607
+ ],
608
+ style: "codepath"
609
+ }) : {}
610
+ }
611
+ });
612
+ return handle;
613
+ },
614
+ batchTrigger: async (items) => {
615
+ const apiClient = v3.apiClientManager.client;
616
+ if (!apiClient) {
617
+ throw apiClientMissingError();
618
+ }
619
+ const taskMetadata = v3.taskCatalog.getTaskMetadata(params.id);
620
+ const response = await tracer.startActiveSpan(taskMetadata ? "Batch trigger" : `${params.id} batchTrigger()`, async (span) => {
621
+ const response2 = await apiClient.batchTriggerTask(params.id, {
622
+ items: await Promise.all(items.map(async (item) => {
623
+ const payloadPacket = await v3.stringifyIO(item.payload);
624
+ return {
625
+ payload: payloadPacket.data,
626
+ options: {
627
+ queue: item.options?.queue ?? params.queue,
628
+ concurrencyKey: item.options?.concurrencyKey,
629
+ test: v3.taskContext.ctx?.run.isTest,
630
+ payloadType: payloadPacket.dataType,
631
+ idempotencyKey: item.options?.idempotencyKey
632
+ }
633
+ };
634
+ }))
635
+ }, {
636
+ spanParentAsLink: true
637
+ });
638
+ span.setAttribute("messaging.message.id", response2.batchId);
639
+ const handle = {
640
+ batchId: response2.batchId,
641
+ runs: response2.runs.map((id) => ({
642
+ id
643
+ }))
644
+ };
645
+ return handle;
646
+ }, {
647
+ kind: api.SpanKind.PRODUCER,
648
+ attributes: {
649
+ [semanticConventions.SEMATTRS_MESSAGING_OPERATION]: "publish",
650
+ ["messaging.batch.message_count"]: items.length,
651
+ ["messaging.client_id"]: v3.taskContext.worker?.id,
652
+ [semanticConventions.SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
653
+ [semanticConventions.SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
654
+ [v3.SemanticInternalAttributes.STYLE_ICON]: "trigger",
655
+ ...taskMetadata ? v3.accessoryAttributes({
656
+ items: [
657
+ {
658
+ text: `${taskMetadata.exportName}.batchTrigger()`,
659
+ variant: "normal"
660
+ }
661
+ ],
662
+ style: "codepath"
663
+ }) : {}
664
+ }
665
+ });
666
+ return response;
667
+ },
668
+ triggerAndWait: async (payload, options) => {
669
+ const ctx = v3.taskContext.ctx;
670
+ if (!ctx) {
671
+ throw new Error("triggerAndWait can only be used from inside a task.run()");
672
+ }
673
+ const apiClient = v3.apiClientManager.client;
674
+ if (!apiClient) {
675
+ throw apiClientMissingError();
676
+ }
677
+ const taskMetadata = v3.taskCatalog.getTaskMetadata(params.id);
678
+ const payloadPacket = await v3.stringifyIO(payload);
679
+ return await tracer.startActiveSpan(taskMetadata ? "Trigger" : `${params.id} triggerAndWait()`, async (span) => {
680
+ const response = await apiClient.triggerTask(params.id, {
681
+ payload: payloadPacket.data,
682
+ options: {
683
+ dependentAttempt: ctx.attempt.id,
684
+ lockToVersion: v3.taskContext.worker?.version,
685
+ queue: options?.queue ?? params.queue,
686
+ concurrencyKey: options?.concurrencyKey,
687
+ test: v3.taskContext.ctx?.run.isTest,
688
+ payloadType: payloadPacket.dataType,
689
+ idempotencyKey: options?.idempotencyKey
690
+ }
691
+ });
692
+ span.setAttribute("messaging.message.id", response.id);
693
+ if (options?.idempotencyKey) {
694
+ const result2 = await apiClient.getRunResult(response.id);
695
+ if (result2) {
696
+ v3.logger.log(`Result reused from previous task run with idempotency key '${options.idempotencyKey}'.`, {
697
+ runId: response.id,
698
+ idempotencyKey: options.idempotencyKey
699
+ });
700
+ return await handleTaskRunExecutionResult(result2);
701
+ }
702
+ }
703
+ const result = await v3.runtime.waitForTask({
704
+ id: response.id,
705
+ ctx
706
+ });
707
+ return await handleTaskRunExecutionResult(result);
708
+ }, {
709
+ kind: api.SpanKind.PRODUCER,
710
+ attributes: {
711
+ [v3.SemanticInternalAttributes.STYLE_ICON]: "trigger",
712
+ [semanticConventions.SEMATTRS_MESSAGING_OPERATION]: "publish",
713
+ ["messaging.client_id"]: v3.taskContext.worker?.id,
714
+ [semanticConventions.SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
715
+ [semanticConventions.SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
716
+ ...taskMetadata ? v3.accessoryAttributes({
717
+ items: [
718
+ {
719
+ text: `${taskMetadata.exportName}.triggerAndWait()`,
720
+ variant: "normal"
721
+ }
722
+ ],
723
+ style: "codepath"
724
+ }) : {}
725
+ }
726
+ });
727
+ },
728
+ batchTriggerAndWait: async (items) => {
729
+ const ctx = v3.taskContext.ctx;
730
+ if (!ctx) {
731
+ throw new Error("batchTriggerAndWait can only be used from inside a task.run()");
732
+ }
733
+ const apiClient = v3.apiClientManager.client;
734
+ if (!apiClient) {
735
+ throw apiClientMissingError();
736
+ }
737
+ const taskMetadata = v3.taskCatalog.getTaskMetadata(params.id);
738
+ return await tracer.startActiveSpan(taskMetadata ? "Batch trigger" : `${params.id} batchTriggerAndWait()`, async (span) => {
739
+ const response = await apiClient.batchTriggerTask(params.id, {
740
+ items: await Promise.all(items.map(async (item) => {
741
+ const payloadPacket = await v3.stringifyIO(item.payload);
742
+ return {
743
+ payload: payloadPacket.data,
744
+ options: {
745
+ lockToVersion: v3.taskContext.worker?.version,
746
+ queue: item.options?.queue ?? params.queue,
747
+ concurrencyKey: item.options?.concurrencyKey,
748
+ test: v3.taskContext.ctx?.run.isTest,
749
+ payloadType: payloadPacket.dataType,
750
+ idempotencyKey: item.options?.idempotencyKey
751
+ }
752
+ };
753
+ })),
754
+ dependentAttempt: ctx.attempt.id
755
+ });
756
+ span.setAttribute("messaging.message.id", response.batchId);
757
+ const getBatchResults = /* @__PURE__ */ __name(async () => {
758
+ const hasIdempotencyKey = items.some((item) => item.options?.idempotencyKey);
759
+ if (hasIdempotencyKey) {
760
+ const results = await apiClient.getBatchResults(response.batchId);
761
+ if (results) {
762
+ return results;
763
+ }
764
+ }
765
+ return {
766
+ id: response.batchId,
767
+ items: []
768
+ };
769
+ }, "getBatchResults");
770
+ const existingResults = await getBatchResults();
771
+ const incompleteRuns = response.runs.filter((runId) => !existingResults.items.some((item) => item.id === runId));
772
+ if (incompleteRuns.length === 0) {
773
+ v3.logger.log(`Results reused from previous task runs because of the provided idempotency keys.`);
774
+ const runs3 = await handleBatchTaskRunExecutionResult(existingResults.items);
775
+ return {
776
+ id: existingResults.id,
777
+ runs: runs3
778
+ };
779
+ }
780
+ const result = await v3.runtime.waitForBatch({
781
+ id: response.batchId,
782
+ runs: incompleteRuns,
783
+ ctx
784
+ });
785
+ const combinedItems = [];
786
+ for (const runId of response.runs) {
787
+ const existingItem = existingResults.items.find((item) => item.id === runId);
788
+ if (existingItem) {
789
+ combinedItems.push(existingItem);
790
+ } else {
791
+ const newItem = result.items.find((item) => item.id === runId);
792
+ if (newItem) {
793
+ combinedItems.push(newItem);
794
+ }
795
+ }
796
+ }
797
+ const runs2 = await handleBatchTaskRunExecutionResult(combinedItems);
798
+ return {
799
+ id: result.id,
800
+ runs: runs2
801
+ };
802
+ }, {
803
+ kind: api.SpanKind.PRODUCER,
804
+ attributes: {
805
+ [semanticConventions.SEMATTRS_MESSAGING_OPERATION]: "publish",
806
+ ["messaging.batch.message_count"]: items.length,
807
+ ["messaging.client_id"]: v3.taskContext.worker?.id,
808
+ [semanticConventions.SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,
809
+ [semanticConventions.SEMATTRS_MESSAGING_SYSTEM]: "trigger.dev",
810
+ [v3.SemanticInternalAttributes.STYLE_ICON]: "trigger",
811
+ ...taskMetadata ? v3.accessoryAttributes({
812
+ items: [
813
+ {
814
+ text: `${taskMetadata.exportName}.batchTriggerAndWait()`,
815
+ variant: "normal"
816
+ }
817
+ ],
818
+ style: "codepath"
819
+ }) : {}
820
+ }
821
+ });
822
+ }
823
+ };
824
+ v3.taskCatalog.registerTaskMetadata({
825
+ id: params.id,
826
+ packageVersion: version,
827
+ queue: params.queue,
828
+ retry: params.retry ? {
829
+ ...v3.defaultRetryOptions,
830
+ ...params.retry
831
+ } : void 0,
832
+ machine: params.machine,
833
+ fns: {
834
+ run: params.run,
835
+ init: params.init,
836
+ cleanup: params.cleanup,
837
+ middleware: params.middleware,
838
+ handleError: params.handleError,
839
+ onSuccess: params.onSuccess,
840
+ onFailure: params.onFailure,
841
+ onStart: params.onStart
842
+ }
843
+ });
844
+ return task3;
845
+ }
846
+ __name(createTask, "createTask");
847
+ async function trigger(id, payload, options) {
848
+ const apiClient = v3.apiClientManager.client;
849
+ if (!apiClient) {
850
+ throw apiClientMissingError();
851
+ }
852
+ const payloadPacket = await v3.stringifyIO(payload);
853
+ const handle = await apiClient.triggerTask(id, {
854
+ payload: payloadPacket.data,
855
+ options: {
856
+ queue: options?.queue,
857
+ concurrencyKey: options?.concurrencyKey,
858
+ test: v3.taskContext.ctx?.run.isTest,
859
+ payloadType: payloadPacket.dataType,
860
+ idempotencyKey: options?.idempotencyKey
861
+ }
862
+ });
863
+ return handle;
864
+ }
865
+ __name(trigger, "trigger");
866
+ async function triggerAndPoll(id, payload, options) {
867
+ const handle = await trigger(id, payload, options);
868
+ return runs.poll(handle);
869
+ }
870
+ __name(triggerAndPoll, "triggerAndPoll");
871
+ async function batchTrigger(id, items) {
872
+ const apiClient = v3.apiClientManager.client;
873
+ if (!apiClient) {
874
+ throw apiClientMissingError();
875
+ }
876
+ const response = await apiClient.batchTriggerTask(id, {
877
+ items: await Promise.all(items.map(async (item) => {
878
+ const payloadPacket = await v3.stringifyIO(item.payload);
879
+ return {
880
+ payload: payloadPacket.data,
881
+ options: {
882
+ queue: item.options?.queue,
883
+ concurrencyKey: item.options?.concurrencyKey,
884
+ test: v3.taskContext.ctx?.run.isTest,
885
+ payloadType: payloadPacket.dataType,
886
+ idempotencyKey: item.options?.idempotencyKey
887
+ }
888
+ };
889
+ }))
890
+ });
891
+ const handle = {
892
+ batchId: response.batchId,
893
+ runs: response.runs.map((id2) => ({
894
+ id: id2
895
+ }))
896
+ };
897
+ return handle;
898
+ }
899
+ __name(batchTrigger, "batchTrigger");
900
+ async function handleBatchTaskRunExecutionResult(items) {
901
+ const someObjectStoreOutputs = items.some((item) => item.ok && item.outputType === "application/store");
902
+ if (!someObjectStoreOutputs) {
903
+ const results = await Promise.all(items.map(async (item) => {
904
+ return await handleTaskRunExecutionResult(item);
905
+ }));
906
+ return results;
907
+ }
908
+ return await tracer.startActiveSpan("store.downloadPayloads", async (span) => {
909
+ const results = await Promise.all(items.map(async (item) => {
910
+ return await handleTaskRunExecutionResult(item);
911
+ }));
912
+ return results;
913
+ }, {
914
+ kind: api.SpanKind.INTERNAL,
915
+ [v3.SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
916
+ });
917
+ }
918
+ __name(handleBatchTaskRunExecutionResult, "handleBatchTaskRunExecutionResult");
919
+ async function handleTaskRunExecutionResult(execution) {
920
+ if (execution.ok) {
921
+ const outputPacket = {
922
+ data: execution.output,
923
+ dataType: execution.outputType
924
+ };
925
+ const importedPacket = await v3.conditionallyImportPacket(outputPacket, tracer);
926
+ return {
927
+ ok: true,
928
+ id: execution.id,
929
+ output: await v3.parsePacket(importedPacket)
930
+ };
931
+ } else {
932
+ return {
933
+ ok: false,
934
+ id: execution.id,
935
+ error: v3.createErrorTaskError(execution.error)
936
+ };
937
+ }
938
+ }
939
+ __name(handleTaskRunExecutionResult, "handleTaskRunExecutionResult");
940
+ function apiClientMissingError() {
941
+ const hasBaseUrl = !!v3.apiClientManager.baseURL;
942
+ const hasAccessToken = !!v3.apiClientManager.accessToken;
943
+ if (!hasBaseUrl && !hasAccessToken) {
944
+ return `You need to set the TRIGGER_API_URL and TRIGGER_SECRET_KEY environment variables.`;
945
+ } else if (!hasBaseUrl) {
946
+ return `You need to set the TRIGGER_API_URL environment variable.`;
947
+ } else if (!hasAccessToken) {
948
+ return `You need to set the TRIGGER_SECRET_KEY environment variable.`;
949
+ }
950
+ return `Unknown error`;
951
+ }
952
+ __name(apiClientMissingError, "apiClientMissingError");
953
+
954
+ // src/v3/tasks.ts
955
+ function task(options) {
956
+ return createTask(options);
957
+ }
958
+ __name(task, "task");
959
+ var tasks = {
960
+ trigger,
961
+ triggerAndPoll,
962
+ batchTrigger
963
+ };
964
+ var wait = {
965
+ for: async (options) => {
966
+ return tracer.startActiveSpan(`wait.for()`, async (span) => {
967
+ const durationInMs = calculateDurationInMs(options);
968
+ await v3.runtime.waitForDuration(durationInMs);
969
+ }, {
970
+ attributes: {
971
+ [v3.SemanticInternalAttributes.STYLE_ICON]: "wait",
972
+ ...v3.accessoryAttributes({
973
+ items: [
974
+ {
975
+ text: nameForWaitOptions(options),
976
+ variant: "normal"
977
+ }
978
+ ],
979
+ style: "codepath"
980
+ })
981
+ }
982
+ });
983
+ },
984
+ until: async (options) => {
985
+ return tracer.startActiveSpan(`wait.until()`, async (span) => {
986
+ const start = Date.now();
987
+ if (options.throwIfInThePast && options.date < /* @__PURE__ */ new Date()) {
988
+ throw new Error("Date is in the past");
989
+ }
990
+ const durationInMs = options.date.getTime() - start;
991
+ await v3.runtime.waitForDuration(durationInMs);
992
+ }, {
993
+ attributes: {
994
+ [v3.SemanticInternalAttributes.STYLE_ICON]: "wait",
995
+ ...v3.accessoryAttributes({
996
+ items: [
997
+ {
998
+ text: options.date.toISOString(),
999
+ variant: "normal"
1000
+ }
1001
+ ],
1002
+ style: "codepath"
1003
+ })
1004
+ }
1005
+ });
1006
+ }
1007
+ };
1008
+ function nameForWaitOptions(options) {
1009
+ if ("seconds" in options) {
1010
+ return options.seconds === 1 ? `1 second` : `${options.seconds} seconds`;
1011
+ }
1012
+ if ("minutes" in options) {
1013
+ return options.minutes === 1 ? `1 minute` : `${options.minutes} minutes`;
1014
+ }
1015
+ if ("hours" in options) {
1016
+ return options.hours === 1 ? `1 hour` : `${options.hours} hours`;
1017
+ }
1018
+ if ("days" in options) {
1019
+ return options.days === 1 ? `1 day` : `${options.days} days`;
1020
+ }
1021
+ if ("weeks" in options) {
1022
+ return options.weeks === 1 ? `1 week` : `${options.weeks} weeks`;
1023
+ }
1024
+ if ("months" in options) {
1025
+ return options.months === 1 ? `1 month` : `${options.months} months`;
1026
+ }
1027
+ if ("years" in options) {
1028
+ return options.years === 1 ? `1 year` : `${options.years} years`;
1029
+ }
1030
+ return "NaN";
1031
+ }
1032
+ __name(nameForWaitOptions, "nameForWaitOptions");
1033
+ function calculateDurationInMs(options) {
1034
+ if ("seconds" in options) {
1035
+ return options.seconds * 1e3;
1036
+ }
1037
+ if ("minutes" in options) {
1038
+ return options.minutes * 1e3 * 60;
1039
+ }
1040
+ if ("hours" in options) {
1041
+ return options.hours * 1e3 * 60 * 60;
1042
+ }
1043
+ if ("days" in options) {
1044
+ return options.days * 1e3 * 60 * 60 * 24;
1045
+ }
1046
+ if ("weeks" in options) {
1047
+ return options.weeks * 1e3 * 60 * 60 * 24 * 7;
1048
+ }
1049
+ if ("months" in options) {
1050
+ return options.months * 1e3 * 60 * 60 * 24 * 30;
1051
+ }
1052
+ if ("years" in options) {
1053
+ return options.years * 1e3 * 60 * 60 * 24 * 365;
1054
+ }
1055
+ throw new Error("Invalid options");
1056
+ }
1057
+ __name(calculateDurationInMs, "calculateDurationInMs");
1058
+ var usage = {
1059
+ /**
1060
+ * Get the current running usage of this task run.
1061
+ *
1062
+ * @example
1063
+ *
1064
+ * ```typescript
1065
+ * import { usage, task } from "@trigger.dev/sdk/v3";
1066
+ *
1067
+ * export const myTask = task({
1068
+ * id: "my-task",
1069
+ * run: async (payload, { ctx }) => {
1070
+ * // ... Do a bunch of work
1071
+ *
1072
+ * const currentUsage = usage.getCurrent();
1073
+ *
1074
+ * // You have access to the current compute cost and duration up to this point
1075
+ * console.log("Current attempt compute cost and duration", {
1076
+ * cost: currentUsage.compute.attempt.costInCents,
1077
+ * duration: currentUsage.compute.attempt.durationMs,
1078
+ * });
1079
+ *
1080
+ * // You also can see the total compute cost and duration up to this point in the run, across all attempts
1081
+ * console.log("Current total compute cost and duration", {
1082
+ * cost: currentUsage.compute.total.costInCents,
1083
+ * duration: currentUsage.compute.total.durationMs,
1084
+ * });
1085
+ *
1086
+ * // You can see the base cost of the run, which is the cost of the run before any compute costs
1087
+ * console.log("Total cost", {
1088
+ * cost: currentUsage.totalCostInCents,
1089
+ * baseCost: currentUsage.baseCostInCents,
1090
+ * });
1091
+ * },
1092
+ * });
1093
+ * ```
1094
+ */
1095
+ getCurrent: () => {
1096
+ const sample = v3.usage.sample();
1097
+ const machine = v3.taskContext.ctx?.machine;
1098
+ const run = v3.taskContext.ctx?.run;
1099
+ if (!sample) {
1100
+ return {
1101
+ compute: {
1102
+ attempt: {
1103
+ costInCents: 0,
1104
+ durationMs: 0
1105
+ },
1106
+ total: {
1107
+ costInCents: run?.costInCents ?? 0,
1108
+ durationMs: run?.durationMs ?? 0
1109
+ }
1110
+ },
1111
+ baseCostInCents: run?.baseCostInCents ?? 0,
1112
+ totalCostInCents: (run?.costInCents ?? 0) + (run?.baseCostInCents ?? 0)
1113
+ };
1114
+ }
1115
+ const currentCostInCents = machine?.centsPerMs ? sample.cpuTime * machine.centsPerMs : 0;
1116
+ return {
1117
+ compute: {
1118
+ attempt: {
1119
+ costInCents: currentCostInCents,
1120
+ durationMs: sample.cpuTime
1121
+ },
1122
+ total: {
1123
+ costInCents: (run?.costInCents ?? 0) + currentCostInCents,
1124
+ durationMs: (run?.durationMs ?? 0) + sample.cpuTime
1125
+ }
1126
+ },
1127
+ baseCostInCents: run?.baseCostInCents ?? 0,
1128
+ totalCostInCents: (run?.costInCents ?? 0) + currentCostInCents + (run?.baseCostInCents ?? 0)
1129
+ };
1130
+ },
1131
+ /**
1132
+ * Measure the cost and duration of a function.
1133
+ *
1134
+ * @example
1135
+ *
1136
+ * ```typescript
1137
+ * import { usage } from "@trigger.dev/sdk/v3";
1138
+ *
1139
+ * export const myTask = task({
1140
+ * id: "my-task",
1141
+ * run: async (payload, { ctx }) => {
1142
+ * const { result, compute } = await usage.measure(async () => {
1143
+ * // Do some work
1144
+ * return "result";
1145
+ * });
1146
+ *
1147
+ * console.log("Result", result);
1148
+ * console.log("Cost and duration", { cost: compute.costInCents, duration: compute.durationMs });
1149
+ * },
1150
+ * });
1151
+ * ```
1152
+ */
1153
+ measure: async (cb) => {
1154
+ const measurement = v3.usage.start();
1155
+ const result = await cb();
1156
+ const sample = v3.usage.stop(measurement);
1157
+ const machine = v3.taskContext.ctx?.machine;
1158
+ const costInCents = machine?.centsPerMs ? sample.cpuTime * machine.centsPerMs : 0;
1159
+ return {
1160
+ result,
1161
+ compute: {
1162
+ costInCents,
1163
+ durationMs: sample.cpuTime
1164
+ }
1165
+ };
1166
+ }
1167
+ };
1168
+
1169
+ // src/v3/schedules/index.ts
1170
+ var schedules_exports = {};
1171
+ __export(schedules_exports, {
1172
+ activate: () => activate,
1173
+ create: () => create,
1174
+ deactivate: () => deactivate,
1175
+ del: () => del,
1176
+ list: () => list,
1177
+ retrieve: () => retrieve,
1178
+ task: () => task2,
1179
+ timezones: () => timezones,
1180
+ update: () => update
1181
+ });
1182
+ function task2(params) {
1183
+ const task3 = createTask(params);
1184
+ v3.taskCatalog.updateTaskMetadata(task3.id, {
1185
+ triggerSource: "schedule"
1186
+ });
1187
+ return task3;
1188
+ }
1189
+ __name(task2, "task");
1190
+ function create(options) {
1191
+ const apiClient = v3.apiClientManager.client;
1192
+ if (!apiClient) {
1193
+ throw apiClientMissingError();
1194
+ }
1195
+ return apiClient.createSchedule(options);
1196
+ }
1197
+ __name(create, "create");
1198
+ function retrieve(scheduleId) {
1199
+ const apiClient = v3.apiClientManager.client;
1200
+ if (!apiClient) {
1201
+ throw apiClientMissingError();
1202
+ }
1203
+ return apiClient.retrieveSchedule(scheduleId);
1204
+ }
1205
+ __name(retrieve, "retrieve");
1206
+ function update(scheduleId, options) {
1207
+ const apiClient = v3.apiClientManager.client;
1208
+ if (!apiClient) {
1209
+ throw apiClientMissingError();
1210
+ }
1211
+ return apiClient.updateSchedule(scheduleId, options);
1212
+ }
1213
+ __name(update, "update");
1214
+ function del(scheduleId) {
1215
+ const apiClient = v3.apiClientManager.client;
1216
+ if (!apiClient) {
1217
+ throw apiClientMissingError();
1218
+ }
1219
+ return apiClient.deleteSchedule(scheduleId);
1220
+ }
1221
+ __name(del, "del");
1222
+ function deactivate(scheduleId) {
1223
+ const apiClient = v3.apiClientManager.client;
1224
+ if (!apiClient) {
1225
+ throw apiClientMissingError();
1226
+ }
1227
+ return apiClient.deactivateSchedule(scheduleId);
1228
+ }
1229
+ __name(deactivate, "deactivate");
1230
+ function activate(scheduleId) {
1231
+ const apiClient = v3.apiClientManager.client;
1232
+ if (!apiClient) {
1233
+ throw apiClientMissingError();
1234
+ }
1235
+ return apiClient.activateSchedule(scheduleId);
1236
+ }
1237
+ __name(activate, "activate");
1238
+ function list(options) {
1239
+ const apiClient = v3.apiClientManager.client;
1240
+ if (!apiClient) {
1241
+ throw apiClientMissingError();
1242
+ }
1243
+ return apiClient.listSchedules(options);
1244
+ }
1245
+ __name(list, "list");
1246
+ function timezones(options) {
1247
+ const baseUrl = v3.apiClientManager.baseURL;
1248
+ if (!baseUrl) {
1249
+ throw apiClientMissingError();
1250
+ }
1251
+ return zodfetch.zodfetch(v3.TimezonesResult, `${baseUrl}/api/v1/timezones${options?.excludeUtc === true ? "?excludeUtc=true" : ""}`, {
1252
+ method: "GET",
1253
+ headers: {
1254
+ "Content-Type": "application/json"
1255
+ }
1256
+ });
1257
+ }
1258
+ __name(timezones, "timezones");
1259
+
1260
+ // src/v3/envvars.ts
1261
+ var envvars_exports = {};
1262
+ __export(envvars_exports, {
1263
+ create: () => create2,
1264
+ del: () => del2,
1265
+ list: () => list2,
1266
+ retrieve: () => retrieve2,
1267
+ update: () => update2,
1268
+ upload: () => upload
1269
+ });
1270
+ function upload(projectRefOrParams, slug, params) {
1271
+ let $projectRef;
1272
+ let $params;
1273
+ let $slug;
1274
+ if (v3.taskContext.ctx) {
1275
+ if (typeof projectRefOrParams === "string") {
1276
+ $projectRef = projectRefOrParams;
1277
+ $slug = slug ?? v3.taskContext.ctx.environment.slug;
1278
+ if (!params) {
1279
+ throw new Error("params is required");
1280
+ }
1281
+ $params = params;
1282
+ } else {
1283
+ $params = projectRefOrParams;
1284
+ $projectRef = v3.taskContext.ctx.project.ref;
1285
+ $slug = v3.taskContext.ctx.environment.slug;
1286
+ }
1287
+ } else {
1288
+ if (typeof projectRefOrParams !== "string") {
1289
+ throw new Error("projectRef is required");
1290
+ }
1291
+ if (!slug) {
1292
+ throw new Error("slug is required");
1293
+ }
1294
+ if (!params) {
1295
+ throw new Error("params is required");
1296
+ }
1297
+ $projectRef = projectRefOrParams;
1298
+ $slug = slug;
1299
+ $params = params;
1300
+ }
1301
+ const apiClient = v3.apiClientManager.client;
1302
+ if (!apiClient) {
1303
+ throw apiClientMissingError();
1304
+ }
1305
+ return apiClient.importEnvVars($projectRef, $slug, $params);
1306
+ }
1307
+ __name(upload, "upload");
1308
+ function list2(projectRef, slug) {
1309
+ const $projectRef = projectRef ?? v3.taskContext.ctx?.project.ref;
1310
+ const $slug = slug ?? v3.taskContext.ctx?.environment.slug;
1311
+ if (!$projectRef) {
1312
+ throw new Error("projectRef is required");
1313
+ }
1314
+ if (!$slug) {
1315
+ throw new Error("slug is required");
1316
+ }
1317
+ const apiClient = v3.apiClientManager.client;
1318
+ if (!apiClient) {
1319
+ throw apiClientMissingError();
1320
+ }
1321
+ return apiClient.listEnvVars($projectRef, $slug);
1322
+ }
1323
+ __name(list2, "list");
1324
+ function create2(projectRefOrParams, slug, params) {
1325
+ let $projectRef;
1326
+ let $slug;
1327
+ let $params;
1328
+ if (v3.taskContext.ctx) {
1329
+ if (typeof projectRefOrParams === "string") {
1330
+ $projectRef = projectRefOrParams;
1331
+ $slug = slug ?? v3.taskContext.ctx.environment.slug;
1332
+ if (!params) {
1333
+ throw new Error("params is required");
1334
+ }
1335
+ $params = params;
1336
+ } else {
1337
+ $params = projectRefOrParams;
1338
+ $projectRef = v3.taskContext.ctx.project.ref;
1339
+ $slug = v3.taskContext.ctx.environment.slug;
1340
+ }
1341
+ } else {
1342
+ if (typeof projectRefOrParams !== "string") {
1343
+ throw new Error("projectRef is required");
1344
+ }
1345
+ if (!slug) {
1346
+ throw new Error("slug is required");
1347
+ }
1348
+ if (!params) {
1349
+ throw new Error("params is required");
1350
+ }
1351
+ $projectRef = projectRefOrParams;
1352
+ $slug = slug;
1353
+ $params = params;
1354
+ }
1355
+ const apiClient = v3.apiClientManager.client;
1356
+ if (!apiClient) {
1357
+ throw apiClientMissingError();
1358
+ }
1359
+ return apiClient.createEnvVar($projectRef, $slug, $params);
1360
+ }
1361
+ __name(create2, "create");
1362
+ function retrieve2(projectRefOrName, slug, name) {
1363
+ let $projectRef;
1364
+ let $slug;
1365
+ let $name;
1366
+ if (typeof name === "string") {
1367
+ $projectRef = projectRefOrName;
1368
+ $slug = slug;
1369
+ $name = name;
1370
+ } else {
1371
+ $projectRef = v3.taskContext.ctx?.project.ref;
1372
+ $slug = v3.taskContext.ctx?.environment.slug;
1373
+ $name = projectRefOrName;
1374
+ }
1375
+ if (!$projectRef) {
1376
+ throw new Error("projectRef is required");
1377
+ }
1378
+ if (!$slug) {
1379
+ throw new Error("slug is required");
1380
+ }
1381
+ const apiClient = v3.apiClientManager.client;
1382
+ if (!apiClient) {
1383
+ throw apiClientMissingError();
1384
+ }
1385
+ return apiClient.retrieveEnvVar($projectRef, $slug, $name);
1386
+ }
1387
+ __name(retrieve2, "retrieve");
1388
+ function del2(projectRefOrName, slug, name) {
1389
+ let $projectRef;
1390
+ let $slug;
1391
+ let $name;
1392
+ if (typeof name === "string") {
1393
+ $projectRef = projectRefOrName;
1394
+ $slug = slug;
1395
+ $name = name;
1396
+ } else {
1397
+ $projectRef = v3.taskContext.ctx?.project.ref;
1398
+ $slug = v3.taskContext.ctx?.environment.slug;
1399
+ $name = projectRefOrName;
1400
+ }
1401
+ if (!$projectRef) {
1402
+ throw new Error("projectRef is required");
1403
+ }
1404
+ if (!$slug) {
1405
+ throw new Error("slug is required");
1406
+ }
1407
+ const apiClient = v3.apiClientManager.client;
1408
+ if (!apiClient) {
1409
+ throw apiClientMissingError();
1410
+ }
1411
+ return apiClient.deleteEnvVar($projectRef, $slug, $name);
1412
+ }
1413
+ __name(del2, "del");
1414
+ function update2(projectRefOrName, slugOrParams, name, params) {
1415
+ let $projectRef;
1416
+ let $slug;
1417
+ let $name;
1418
+ let $params;
1419
+ if (v3.taskContext.ctx) {
1420
+ if (typeof slugOrParams === "string") {
1421
+ $projectRef = slugOrParams;
1422
+ $slug = slugOrParams ?? v3.taskContext.ctx.environment.slug;
1423
+ $name = name;
1424
+ if (!params) {
1425
+ throw new Error("params is required");
1426
+ }
1427
+ $params = params;
1428
+ } else {
1429
+ $params = slugOrParams;
1430
+ $projectRef = v3.taskContext.ctx.project.ref;
1431
+ $slug = v3.taskContext.ctx.environment.slug;
1432
+ $name = projectRefOrName;
1433
+ }
1434
+ } else {
1435
+ if (typeof slugOrParams !== "string") {
1436
+ throw new Error("slug is required");
1437
+ }
1438
+ if (!projectRefOrName) {
1439
+ throw new Error("projectRef is required");
1440
+ }
1441
+ if (!params) {
1442
+ throw new Error("params is required");
1443
+ }
1444
+ $projectRef = projectRefOrName;
1445
+ $slug = slugOrParams;
1446
+ $name = name;
1447
+ $params = params;
1448
+ }
1449
+ const apiClient = v3.apiClientManager.client;
1450
+ if (!apiClient) {
1451
+ throw apiClientMissingError();
1452
+ }
1453
+ return apiClient.updateEnvVar($projectRef, $slug, $name, $params);
1454
+ }
1455
+ __name(update2, "update");
1456
+
1457
+ // src/v3/index.ts
1458
+ function configure(options) {
1459
+ v3.apiClientManager.setGlobalAPIClientConfiguration(options);
1460
+ }
1461
+ __name(configure, "configure");
1462
+
1463
+ Object.defineProperty(exports, "ApiError", {
1464
+ enumerable: true,
1465
+ get: function () { return v3.ApiError; }
1466
+ });
1467
+ Object.defineProperty(exports, "AuthenticationError", {
1468
+ enumerable: true,
1469
+ get: function () { return v3.AuthenticationError; }
1470
+ });
1471
+ Object.defineProperty(exports, "BadRequestError", {
1472
+ enumerable: true,
1473
+ get: function () { return v3.BadRequestError; }
1474
+ });
1475
+ Object.defineProperty(exports, "ConflictError", {
1476
+ enumerable: true,
1477
+ get: function () { return v3.ConflictError; }
1478
+ });
1479
+ Object.defineProperty(exports, "InternalServerError", {
1480
+ enumerable: true,
1481
+ get: function () { return v3.InternalServerError; }
1482
+ });
1483
+ Object.defineProperty(exports, "NotFoundError", {
1484
+ enumerable: true,
1485
+ get: function () { return v3.NotFoundError; }
1486
+ });
1487
+ Object.defineProperty(exports, "PermissionDeniedError", {
1488
+ enumerable: true,
1489
+ get: function () { return v3.PermissionDeniedError; }
1490
+ });
1491
+ Object.defineProperty(exports, "RateLimitError", {
1492
+ enumerable: true,
1493
+ get: function () { return v3.RateLimitError; }
1494
+ });
1495
+ Object.defineProperty(exports, "UnprocessableEntityError", {
1496
+ enumerable: true,
1497
+ get: function () { return v3.UnprocessableEntityError; }
1498
+ });
1499
+ Object.defineProperty(exports, "logger", {
883
1500
  enumerable: true,
884
1501
  get: function () { return v3.logger; }
885
1502
  });
886
1503
  exports.InMemoryCache = InMemoryCache;
1504
+ exports.configure = configure;
887
1505
  exports.createCache = createCache;
1506
+ exports.envvars = envvars_exports;
1507
+ exports.queue = queue;
888
1508
  exports.retry = retry;
1509
+ exports.runs = runs;
1510
+ exports.schedules = schedules_exports;
889
1511
  exports.task = task;
1512
+ exports.tasks = tasks;
1513
+ exports.usage = usage;
890
1514
  exports.wait = wait;
891
1515
  //# sourceMappingURL=out.js.map
892
1516
  //# sourceMappingURL=index.js.map