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

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