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