@trigger.dev/sdk 3.0.0-beta.3 → 3.0.0-beta.30

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.
@@ -1,7 +1,53 @@
1
- import { TaskRunContext, InitOutput, RetryOptions, QueueOptions, MachineCpu, MachineMemory, RunFnParams, InitFnParams, HandleErrorFnParams, HandleErrorResult, MiddlewareFnParams, SuccessFnParams, FetchRetryOptions } from '@trigger.dev/core/v3';
2
- export { HandleErrorArgs, HandleErrorFunction, LogLevel, RetryOptions, ProjectConfig as TriggerConfig, logger } from '@trigger.dev/core/v3';
1
+ import { RetryOptions, FetchRetryOptions, TaskRunContext, QueueOptions, InitOutput, MachineCpu, MachineMemory, RunFnParams, InitFnParams, HandleErrorFnParams, HandleErrorResult, MiddlewareFnParams, StartFnParams, SuccessFnParams, FailureFnParams, RetrieveRunResponse, ReplayRunResponse, CanceledRunResponse, ScheduledTaskPayload, CreateScheduleOptions, ScheduleObject, UpdateScheduleOptions, DeletedScheduleObject, ListScheduleOptions, ListSchedulesResult, ApiClientConfiguration } from '@trigger.dev/core/v3';
2
+ export { APIError, ApiClientConfiguration, AuthenticationError, BadRequestError, ConflictError, HandleErrorArgs, HandleErrorFunction, InternalServerError, LogLevel, NotFoundError, PermissionDeniedError, RateLimitError, RetryOptions, ProjectConfig as TriggerConfig, UnprocessableEntityError, logger } from '@trigger.dev/core/v3';
3
3
  import { HttpHandler } from 'msw';
4
4
 
5
+ type CacheMetadata = {
6
+ createdTime: number;
7
+ ttl?: number | null;
8
+ };
9
+ type CacheEntry<Value = unknown> = {
10
+ metadata: CacheMetadata;
11
+ value: Value;
12
+ };
13
+ type Eventually<Value> = Value | null | undefined | Promise<Value | null | undefined>;
14
+ type CacheStore<Value = any> = {
15
+ name?: string;
16
+ get: (key: string) => Eventually<CacheEntry<Value>>;
17
+ set: (key: string, value: CacheEntry<Value>) => unknown | Promise<unknown>;
18
+ delete: (key: string) => unknown | Promise<unknown>;
19
+ };
20
+ type CacheFunction = <Value>(cacheKey: string, fn: () => Promise<Value> | Value) => Promise<Value> | Value;
21
+ declare class InMemoryCache<Value = any> {
22
+ private _cache;
23
+ get(key: string): Eventually<CacheEntry<Value>>;
24
+ set(key: string, value: CacheEntry<Value>): unknown;
25
+ delete(key: string): unknown;
26
+ }
27
+ /**
28
+ * Create a cache function that uses the provided store to cache values. Using InMemoryCache is safe because each task run is isolated.
29
+ * @param store
30
+ * @returns
31
+ */
32
+ declare function createCache(store: CacheStore): CacheFunction;
33
+
34
+ declare function onThrow<T>(fn: (options: {
35
+ attempt: number;
36
+ maxAttempts: number;
37
+ }) => Promise<T>, options: RetryOptions): Promise<T>;
38
+ interface RetryFetchRequestInit extends RequestInit {
39
+ retry?: FetchRetryOptions;
40
+ timeoutInMs?: number;
41
+ }
42
+ declare function retryFetch(input: RequestInfo | URL, init?: RetryFetchRequestInit | undefined): Promise<Response>;
43
+ declare const retry: {
44
+ onThrow: typeof onThrow;
45
+ fetch: typeof retryFetch;
46
+ interceptFetch: (...handlers: Array<HttpHandler>) => {
47
+ run: <T>(fn: (...args: any[]) => Promise<T>) => Promise<T>;
48
+ };
49
+ };
50
+
5
51
  type Context = TaskRunContext;
6
52
  type RequireOne<T, K extends keyof T> = {
7
53
  [X in Exclude<keyof T, K>]?: T[X];
@@ -9,7 +55,10 @@ type RequireOne<T, K extends keyof T> = {
9
55
  [P in K]-?: T[P];
10
56
  };
11
57
  type Queue = RequireOne<QueueOptions, "name">;
12
- type TaskOptions<TPayload, TOutput = any, TInitOutput extends InitOutput = any> = {
58
+ declare function queue(options: {
59
+ name: string;
60
+ } & QueueOptions): Queue;
61
+ type TaskOptions<TPayload = void, TOutput = unknown, TInitOutput extends InitOutput = any> = {
13
62
  /** An id for your task. This must be unique inside your project and not change between versions. */
14
63
  id: string;
15
64
  /** The retry settings when an uncaught error is thrown.
@@ -99,11 +148,48 @@ type TaskOptions<TPayload, TOutput = any, TInitOutput extends InitOutput = any>
99
148
  * @param params - Metadata about the run.
100
149
  */
101
150
  run: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<TOutput>;
151
+ /**
152
+ * init is called before the run function is called. It's useful for setting up any global state.
153
+ */
102
154
  init?: (payload: TPayload, params: InitFnParams) => Promise<TInitOutput>;
103
- handleError?: (payload: TPayload, error: unknown, params: HandleErrorFnParams<TInitOutput>) => HandleErrorResult;
155
+ /**
156
+ * cleanup is called after the run function has completed.
157
+ */
104
158
  cleanup?: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<void>;
159
+ /**
160
+ * handleError is called when the run function throws an error. It can be used to modify the error or return new retry options.
161
+ */
162
+ handleError?: (payload: TPayload, error: unknown, params: HandleErrorFnParams<TInitOutput>) => HandleErrorResult;
163
+ /**
164
+ * middleware allows you to run code "around" the run function. This can be useful for logging, metrics, or other cross-cutting concerns.
165
+ *
166
+ * When writing middleware, you should always call `next()` to continue the execution of the task:
167
+ *
168
+ * ```ts
169
+ * export const middlewareTask = task({
170
+ * id: "middleware-task",
171
+ * middleware: async (payload, { ctx, next }) => {
172
+ * console.log("Before run");
173
+ * await next();
174
+ * console.log("After run");
175
+ * },
176
+ * run: async (payload, { ctx }) => {}
177
+ * });
178
+ * ```
179
+ */
105
180
  middleware?: (payload: TPayload, params: MiddlewareFnParams) => Promise<void>;
106
- onSuccess?: (payload: TPayload, params: SuccessFnParams<TOutput, TInitOutput>) => Promise<void>;
181
+ /**
182
+ * onStart is called the first time a task is executed in a run (not before every retry)
183
+ */
184
+ onStart?: (payload: TPayload, params: StartFnParams) => Promise<void>;
185
+ /**
186
+ * onSuccess is called after the run function has successfully completed.
187
+ */
188
+ onSuccess?: (payload: TPayload, output: TOutput, params: SuccessFnParams<TInitOutput>) => Promise<void>;
189
+ /**
190
+ * onFailure is called after a task run has failed (meaning the run function threw an error and won't be retried anymore)
191
+ */
192
+ onFailure?: (payload: TPayload, error: unknown, params: FailureFnParams<TInitOutput>) => Promise<void>;
107
193
  };
108
194
  type InvokeHandle = {
109
195
  id: string;
@@ -119,36 +205,79 @@ type TaskRunResult<TOutput = any> = {
119
205
  } | {
120
206
  ok: false;
121
207
  id: string;
122
- error: any;
208
+ error: unknown;
123
209
  };
124
210
  type BatchResult<TOutput = any> = {
125
211
  id: string;
126
212
  runs: TaskRunResult<TOutput>[];
127
213
  };
128
- type Task<TInput, TOutput = any> = {
129
- trigger: (params: {
130
- payload: TInput;
131
- options?: TaskRunOptions;
132
- }) => Promise<InvokeHandle>;
133
- batchTrigger: (params: {
134
- items: {
135
- payload: TInput;
136
- options?: TaskRunOptions;
137
- }[];
138
- batchOptions?: BatchRunOptions;
139
- }) => Promise<InvokeBatchHandle>;
140
- triggerAndWait: (params: {
141
- payload: TInput;
142
- options?: TaskRunOptions;
143
- }) => Promise<TOutput>;
144
- batchTriggerAndWait: (params: {
145
- items: {
146
- payload: TInput;
147
- options?: TaskRunOptions;
148
- }[];
149
- batchOptions?: BatchRunOptions;
150
- }) => Promise<BatchResult<TOutput>>;
214
+ type BatchItem<TInput> = TInput extends void ? {
215
+ payload?: TInput;
216
+ options?: TaskRunOptions;
217
+ } : {
218
+ payload: TInput;
219
+ options?: TaskRunOptions;
151
220
  };
221
+ interface Task<TInput = void, TOutput = any> {
222
+ /**
223
+ * The id of the task.
224
+ */
225
+ id: string;
226
+ /**
227
+ * Trigger a task with the given payload, and continue without waiting for the result. If you want to wait for the result, use `triggerAndWait`. Returns the id of the triggered task run.
228
+ * @param payload
229
+ * @param options
230
+ * @returns InvokeHandle
231
+ * - `id` - The id of the triggered task run.
232
+ */
233
+ trigger: (payload: TInput, options?: TaskRunOptions) => Promise<InvokeHandle>;
234
+ /**
235
+ * Batch trigger multiple task runs with the given payloads, and continue without waiting for the results. If you want to wait for the results, use `batchTriggerAndWait`. Returns the id of the triggered batch.
236
+ * @param items
237
+ * @returns InvokeBatchHandle
238
+ * - `batchId` - The id of the triggered batch.
239
+ * - `runs` - The ids of the triggered task runs.
240
+ */
241
+ batchTrigger: (items: Array<BatchItem<TInput>>) => Promise<InvokeBatchHandle>;
242
+ /**
243
+ * Trigger a task with the given payload, and wait for the result. Returns the result of the task run
244
+ * @param payload
245
+ * @param options - Options for the task run
246
+ * @returns TaskRunResult
247
+ * @example
248
+ * ```
249
+ * const result = await task.triggerAndWait({ foo: "bar" });
250
+ *
251
+ * if (result.ok) {
252
+ * console.log(result.output);
253
+ * } else {
254
+ * console.error(result.error);
255
+ * }
256
+ * ```
257
+ */
258
+ triggerAndWait: (payload: TInput, options?: TaskRunOptions) => Promise<TaskRunResult<TOutput>>;
259
+ /**
260
+ * Batch trigger multiple task runs with the given payloads, and wait for the results. Returns the results of the task runs.
261
+ * @param items
262
+ * @returns BatchResult
263
+ * @example
264
+ * ```
265
+ * const result = await task.batchTriggerAndWait([
266
+ * { payload: { foo: "bar" } },
267
+ * { payload: { foo: "baz" } },
268
+ * ]);
269
+ *
270
+ * for (const run of result.runs) {
271
+ * if (run.ok) {
272
+ * console.log(run.output);
273
+ * } else {
274
+ * console.error(run.error);
275
+ * }
276
+ * }
277
+ * ```
278
+ */
279
+ batchTriggerAndWait: (items: Array<BatchItem<TInput>>) => Promise<BatchResult<TOutput>>;
280
+ }
152
281
  type TaskRunOptions = {
153
282
  idempotencyKey?: string;
154
283
  maxAttempts?: number;
@@ -158,9 +287,6 @@ type TaskRunOptions = {
158
287
  concurrencyKey?: string;
159
288
  };
160
289
  type TaskRunConcurrencyOptions = Queue;
161
- type BatchRunOptions = TaskRunOptions & {
162
- maxConcurrency?: number;
163
- };
164
290
 
165
291
  /** Creates a task that can be triggered
166
292
  * @param options - Task options
@@ -180,7 +306,7 @@ type BatchRunOptions = TaskRunOptions & {
180
306
  *
181
307
  * @returns A task that can be triggered
182
308
  */
183
- declare function task<TInput, TOutput = any, TInitOutput extends InitOutput = any>(options: TaskOptions<TInput, TOutput, TInitOutput>): Task<TInput, TOutput>;
309
+ declare function task$1<TInput = void, TOutput = unknown, TInitOutput extends InitOutput = any>(options: TaskOptions<TInput, TOutput, TInitOutput>): Task<TInput, TOutput>;
184
310
 
185
311
  type WaitOptions = {
186
312
  seconds: number;
@@ -205,50 +331,95 @@ declare const wait: {
205
331
  }) => Promise<void>;
206
332
  };
207
333
 
208
- type CacheMetadata = {
209
- createdTime: number;
210
- ttl?: number | null;
211
- };
212
- type CacheEntry<Value = unknown> = {
213
- metadata: CacheMetadata;
214
- value: Value;
215
- };
216
- type Eventually<Value> = Value | null | undefined | Promise<Value | null | undefined>;
217
- type CacheStore<Value = any> = {
218
- name?: string;
219
- get: (key: string) => Eventually<CacheEntry<Value>>;
220
- set: (key: string, value: CacheEntry<Value>) => unknown | Promise<unknown>;
221
- delete: (key: string) => unknown | Promise<unknown>;
334
+ declare const runs: {
335
+ replay: typeof replayRun;
336
+ cancel: typeof cancelRun;
337
+ retrieve: typeof retrieveRun;
222
338
  };
223
- type CacheFunction = <Value>(cacheKey: string, fn: () => Promise<Value> | Value) => Promise<Value> | Value;
224
- declare class InMemoryCache<Value = any> {
225
- private _cache;
226
- get(key: string): Eventually<CacheEntry<Value>>;
227
- set(key: string, value: CacheEntry<Value>): unknown;
228
- delete(key: string): unknown;
229
- }
339
+ declare function retrieveRun(runId: string): Promise<RetrieveRunResponse>;
340
+ declare function replayRun(runId: string): Promise<ReplayRunResponse>;
341
+ declare function cancelRun(runId: string): Promise<CanceledRunResponse>;
342
+
343
+ declare function task<TOutput, TInitOutput extends InitOutput>(params: TaskOptions<ScheduledTaskPayload, TOutput, TInitOutput>): Task<ScheduledTaskPayload, TOutput>;
230
344
  /**
231
- * Create a cache function that uses the provided store to cache values. Using InMemoryCache is safe because each task run is isolated.
232
- * @param store
233
- * @returns
345
+ * Creates a new schedule
346
+ * @param options
347
+ * @param options.task - The identifier of the task to be scheduled (Must already exist and be a scheduled task)
348
+ * @param options.cron - The cron expression for the schedule (e.g. `0 0 * * *`)
349
+ * @param options.externalId - An optional external identifier for the schedule
350
+ * @param options.deduplicationKey - An optional deduplication key for the schedule
351
+ * @returns The created schedule
234
352
  */
235
- declare function createCache(store: CacheStore): CacheFunction;
353
+ declare function create(options: CreateScheduleOptions): Promise<ScheduleObject>;
354
+ /**
355
+ * Retrieves a schedule
356
+ * @param scheduleId - The ID of the schedule to retrieve
357
+ * @returns The retrieved schedule
358
+ */
359
+ declare function retrieve(scheduleId: string): Promise<ScheduleObject>;
360
+ /**
361
+ * Updates a schedule
362
+ * @param scheduleId - The ID of the schedule to update
363
+ * @param options - The updated schedule options
364
+ * @param options.task - The identifier of the task to be scheduled (Must already exist and be a scheduled task)
365
+ * @param options.cron - The cron expression for the schedule (e.g. `0 0 * * *`)
366
+ * @param options.externalId - An optional external identifier for the schedule
367
+ * @returns The updated schedule
368
+ */
369
+ declare function update(scheduleId: string, options: UpdateScheduleOptions): Promise<ScheduleObject>;
370
+ /**
371
+ * Deletes a schedule
372
+ * @param scheduleId - The ID of the schedule to delete
373
+ */
374
+ declare function del(scheduleId: string): Promise<DeletedScheduleObject>;
375
+ /**
376
+ * Deactivates a schedule
377
+ * @param scheduleId - The ID of the schedule to deactivate
378
+ */
379
+ declare function deactivate(scheduleId: string): Promise<ScheduleObject>;
380
+ /**
381
+ * Activates a schedule
382
+ * @param scheduleId - The ID of the schedule to activate
383
+ */
384
+ declare function activate(scheduleId: string): Promise<ScheduleObject>;
385
+ /**
386
+ * Lists schedules
387
+ * @param options - The list options
388
+ * @param options.page - The page number
389
+ * @param options.perPage - The number of schedules per page
390
+ * @returns The list of schedules
391
+ */
392
+ declare function list(options?: ListScheduleOptions): Promise<ListSchedulesResult>;
236
393
 
237
- declare function onThrow<T>(fn: (options: {
238
- attempt: number;
239
- maxAttempts: number;
240
- }) => Promise<T>, options: RetryOptions): Promise<T>;
241
- interface RetryFetchRequestInit extends RequestInit {
242
- retry?: FetchRetryOptions;
243
- timeoutInMs?: number;
394
+ declare const index_activate: typeof activate;
395
+ declare const index_create: typeof create;
396
+ declare const index_deactivate: typeof deactivate;
397
+ declare const index_del: typeof del;
398
+ declare const index_list: typeof list;
399
+ declare const index_retrieve: typeof retrieve;
400
+ declare const index_task: typeof task;
401
+ declare const index_update: typeof update;
402
+ declare namespace index {
403
+ export { index_activate as activate, index_create as create, index_deactivate as deactivate, index_del as del, index_list as list, index_retrieve as retrieve, index_task as task, index_update as update };
244
404
  }
245
- declare function retryFetch(input: RequestInfo | URL, init?: RetryFetchRequestInit | undefined): Promise<Response>;
246
- declare const retry: {
247
- onThrow: typeof onThrow;
248
- fetch: typeof retryFetch;
249
- interceptFetch: (...handlers: Array<HttpHandler>) => {
250
- run: <T>(fn: (...args: any[]) => Promise<T>) => Promise<T>;
251
- };
252
- };
253
405
 
254
- export { type CacheEntry, type CacheFunction, type CacheMetadata, type CacheStore, type Context, type Eventually, InMemoryCache, type WaitOptions, createCache, retry, task, wait };
406
+ /**
407
+ * Register the global API client configuration. Alternatively, you can set the `TRIGGER_SECRET_KEY` and `TRIGGER_API_URL` environment variables.
408
+ * @param options The API client configuration.
409
+ * @param options.baseURL The base URL of the Trigger API. (default: `https://api.trigger.dev`)
410
+ * @param options.secretKey The secret key to authenticate with the Trigger API. (default: `process.env.TRIGGER_SECRET_KEY`) This can be found in your Trigger.dev project "API Keys" settings.
411
+ *
412
+ * @example
413
+ *
414
+ * ```typescript
415
+ * import { configure } from "@trigger.dev/sdk/v3";
416
+ *
417
+ * configure({
418
+ * baseURL: "https://api.trigger.dev",
419
+ * secretKey: "tr_dev_1234567890"
420
+ * });
421
+ * ```
422
+ */
423
+ declare function configure(options: ApiClientConfiguration): void;
424
+
425
+ export { type CacheEntry, type CacheFunction, type CacheMetadata, type CacheStore, type Context, type Eventually, InMemoryCache, type Task, type TaskOptions, type WaitOptions, configure, createCache, queue, retry, runs, index as schedules, task$1 as task, wait };