@trigger.dev/sdk 3.0.0-beta.20 → 3.0.0-beta.21
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/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/v3/index.d.mts +40 -3
- package/dist/v3/index.d.ts +40 -3
- package/dist/v3/index.js +5 -2
- package/dist/v3/index.js.map +1 -1
- package/dist/v3/index.mjs +5 -2
- package/dist/v3/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/v3/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TaskRunContext, QueueOptions, InitOutput, RetryOptions, MachineCpu, MachineMemory, RunFnParams, InitFnParams, HandleErrorFnParams, HandleErrorResult, MiddlewareFnParams, SuccessFnParams, FetchRetryOptions, ReplayRunResponse, CanceledRunResponse, ScheduledTaskPayload, CreateScheduleOptions, ScheduleObject, UpdateScheduleOptions, DeletedScheduleObject, ListScheduleOptions, ListSchedulesResult } from '@trigger.dev/core/v3';
|
|
1
|
+
import { TaskRunContext, QueueOptions, InitOutput, RetryOptions, MachineCpu, MachineMemory, RunFnParams, InitFnParams, HandleErrorFnParams, HandleErrorResult, MiddlewareFnParams, StartFnParams, SuccessFnParams, FailureFnParams, FetchRetryOptions, ReplayRunResponse, CanceledRunResponse, ScheduledTaskPayload, CreateScheduleOptions, ScheduleObject, UpdateScheduleOptions, DeletedScheduleObject, ListScheduleOptions, ListSchedulesResult } from '@trigger.dev/core/v3';
|
|
2
2
|
export { APIError, 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
|
|
|
@@ -102,11 +102,48 @@ type TaskOptions<TPayload = void, TOutput = unknown, TInitOutput extends InitOut
|
|
|
102
102
|
* @param params - Metadata about the run.
|
|
103
103
|
*/
|
|
104
104
|
run: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<TOutput>;
|
|
105
|
+
/**
|
|
106
|
+
* init is called before the run function is called. It's useful for setting up any global state.
|
|
107
|
+
*/
|
|
105
108
|
init?: (payload: TPayload, params: InitFnParams) => Promise<TInitOutput>;
|
|
106
|
-
|
|
109
|
+
/**
|
|
110
|
+
* cleanup is called after the run function has completed.
|
|
111
|
+
*/
|
|
107
112
|
cleanup?: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<void>;
|
|
113
|
+
/**
|
|
114
|
+
* handleError is called when the run function throws an error. It can be used to modify the error or return new retry options.
|
|
115
|
+
*/
|
|
116
|
+
handleError?: (payload: TPayload, error: unknown, params: HandleErrorFnParams<TInitOutput>) => HandleErrorResult;
|
|
117
|
+
/**
|
|
118
|
+
* middleware allows you to run code "around" the run function. This can be useful for logging, metrics, or other cross-cutting concerns.
|
|
119
|
+
*
|
|
120
|
+
* When writing middleware, you should always call `next()` to continue the execution of the task:
|
|
121
|
+
*
|
|
122
|
+
* ```ts
|
|
123
|
+
* export const middlewareTask = task({
|
|
124
|
+
* id: "middleware-task",
|
|
125
|
+
* middleware: async (payload, { ctx, next }) => {
|
|
126
|
+
* console.log("Before run");
|
|
127
|
+
* await next();
|
|
128
|
+
* console.log("After run");
|
|
129
|
+
* },
|
|
130
|
+
* run: async (payload, { ctx }) => {}
|
|
131
|
+
* });
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
108
134
|
middleware?: (payload: TPayload, params: MiddlewareFnParams) => Promise<void>;
|
|
109
|
-
|
|
135
|
+
/**
|
|
136
|
+
* onStart is called the first time a task is executed in a run (not before every retry)
|
|
137
|
+
*/
|
|
138
|
+
onStart?: (payload: TPayload, params: StartFnParams) => Promise<void>;
|
|
139
|
+
/**
|
|
140
|
+
* onSuccess is called after the run function has successfully completed.
|
|
141
|
+
*/
|
|
142
|
+
onSuccess?: (payload: TPayload, output: TOutput, params: SuccessFnParams<TInitOutput>) => Promise<void>;
|
|
143
|
+
/**
|
|
144
|
+
* onFailure is called after a task run has failed (meaning the run function threw an error and won't be retried anymore)
|
|
145
|
+
*/
|
|
146
|
+
onFailure?: (payload: TPayload, error: unknown, params: FailureFnParams<TInitOutput>) => Promise<void>;
|
|
110
147
|
};
|
|
111
148
|
type InvokeHandle = {
|
|
112
149
|
id: string;
|
package/dist/v3/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TaskRunContext, QueueOptions, InitOutput, RetryOptions, MachineCpu, MachineMemory, RunFnParams, InitFnParams, HandleErrorFnParams, HandleErrorResult, MiddlewareFnParams, SuccessFnParams, FetchRetryOptions, ReplayRunResponse, CanceledRunResponse, ScheduledTaskPayload, CreateScheduleOptions, ScheduleObject, UpdateScheduleOptions, DeletedScheduleObject, ListScheduleOptions, ListSchedulesResult } from '@trigger.dev/core/v3';
|
|
1
|
+
import { TaskRunContext, QueueOptions, InitOutput, RetryOptions, MachineCpu, MachineMemory, RunFnParams, InitFnParams, HandleErrorFnParams, HandleErrorResult, MiddlewareFnParams, StartFnParams, SuccessFnParams, FailureFnParams, FetchRetryOptions, ReplayRunResponse, CanceledRunResponse, ScheduledTaskPayload, CreateScheduleOptions, ScheduleObject, UpdateScheduleOptions, DeletedScheduleObject, ListScheduleOptions, ListSchedulesResult } from '@trigger.dev/core/v3';
|
|
2
2
|
export { APIError, 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
|
|
|
@@ -102,11 +102,48 @@ type TaskOptions<TPayload = void, TOutput = unknown, TInitOutput extends InitOut
|
|
|
102
102
|
* @param params - Metadata about the run.
|
|
103
103
|
*/
|
|
104
104
|
run: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<TOutput>;
|
|
105
|
+
/**
|
|
106
|
+
* init is called before the run function is called. It's useful for setting up any global state.
|
|
107
|
+
*/
|
|
105
108
|
init?: (payload: TPayload, params: InitFnParams) => Promise<TInitOutput>;
|
|
106
|
-
|
|
109
|
+
/**
|
|
110
|
+
* cleanup is called after the run function has completed.
|
|
111
|
+
*/
|
|
107
112
|
cleanup?: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<void>;
|
|
113
|
+
/**
|
|
114
|
+
* handleError is called when the run function throws an error. It can be used to modify the error or return new retry options.
|
|
115
|
+
*/
|
|
116
|
+
handleError?: (payload: TPayload, error: unknown, params: HandleErrorFnParams<TInitOutput>) => HandleErrorResult;
|
|
117
|
+
/**
|
|
118
|
+
* middleware allows you to run code "around" the run function. This can be useful for logging, metrics, or other cross-cutting concerns.
|
|
119
|
+
*
|
|
120
|
+
* When writing middleware, you should always call `next()` to continue the execution of the task:
|
|
121
|
+
*
|
|
122
|
+
* ```ts
|
|
123
|
+
* export const middlewareTask = task({
|
|
124
|
+
* id: "middleware-task",
|
|
125
|
+
* middleware: async (payload, { ctx, next }) => {
|
|
126
|
+
* console.log("Before run");
|
|
127
|
+
* await next();
|
|
128
|
+
* console.log("After run");
|
|
129
|
+
* },
|
|
130
|
+
* run: async (payload, { ctx }) => {}
|
|
131
|
+
* });
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
108
134
|
middleware?: (payload: TPayload, params: MiddlewareFnParams) => Promise<void>;
|
|
109
|
-
|
|
135
|
+
/**
|
|
136
|
+
* onStart is called the first time a task is executed in a run (not before every retry)
|
|
137
|
+
*/
|
|
138
|
+
onStart?: (payload: TPayload, params: StartFnParams) => Promise<void>;
|
|
139
|
+
/**
|
|
140
|
+
* onSuccess is called after the run function has successfully completed.
|
|
141
|
+
*/
|
|
142
|
+
onSuccess?: (payload: TPayload, output: TOutput, params: SuccessFnParams<TInitOutput>) => Promise<void>;
|
|
143
|
+
/**
|
|
144
|
+
* onFailure is called after a task run has failed (meaning the run function threw an error and won't be retried anymore)
|
|
145
|
+
*/
|
|
146
|
+
onFailure?: (payload: TPayload, error: unknown, params: FailureFnParams<TInitOutput>) => Promise<void>;
|
|
110
147
|
};
|
|
111
148
|
type InvokeHandle = {
|
|
112
149
|
id: string;
|
package/dist/v3/index.js
CHANGED
|
@@ -18,7 +18,7 @@ var __publicField = (obj, key, value) => {
|
|
|
18
18
|
};
|
|
19
19
|
|
|
20
20
|
// package.json
|
|
21
|
-
var version = "3.0.0-beta.
|
|
21
|
+
var version = "3.0.0-beta.21";
|
|
22
22
|
var tracer = new v3.TriggerTracer({
|
|
23
23
|
name: "@trigger.dev/sdk",
|
|
24
24
|
version
|
|
@@ -293,7 +293,10 @@ function createTask(params) {
|
|
|
293
293
|
init: params.init,
|
|
294
294
|
cleanup: params.cleanup,
|
|
295
295
|
middleware: params.middleware,
|
|
296
|
-
handleError: params.handleError
|
|
296
|
+
handleError: params.handleError,
|
|
297
|
+
onSuccess: params.onSuccess,
|
|
298
|
+
onFailure: params.onFailure,
|
|
299
|
+
onStart: params.onStart
|
|
297
300
|
}
|
|
298
301
|
});
|
|
299
302
|
return task3;
|
package/dist/v3/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/v3/shared.ts","../../package.json","../../src/v3/tracer.ts","../../src/v3/tasks.ts","../../src/v3/wait.ts","../../src/v3/cache.ts","../../src/v3/retry.ts","../../src/v3/index.ts","../../src/v3/management.ts","../../src/v3/schedules/index.ts"],"names":["SpanKind","SEMATTRS_MESSAGING_DESTINATION","SEMATTRS_MESSAGING_OPERATION","SEMATTRS_MESSAGING_SYSTEM","SemanticInternalAttributes","accessoryAttributes","apiClientManager","conditionallyImportPacket","createErrorTaskError","defaultRetryOptions","logger","parsePacket","runtime","stringifyIO","taskCatalog","taskContext","TriggerTracer","tracer","name","version","queue","options","createTask","params","task","id","trigger","payload","apiClient","client","apiClientMissingError","taskMetadata","getTaskMetadata","payloadPacket","handle","startActiveSpan","span","response","triggerTask","data","concurrencyKey","test","ctx","run","isTest","payloadType","dataType","idempotencyKey","spanParentAsLink","setAttribute","kind","PRODUCER","attributes","STYLE_ICON","worker","items","text","exportName","variant","style","batchTrigger","batchTriggerTask","Promise","all","map","item","batchId","length","triggerAndWait","Error","dependentAttempt","attempt","lockToVersion","result","getRunResult","log","runId","handleTaskRunExecutionResult","waitForTask","batchTriggerAndWait","getBatchResults","hasIdempotencyKey","some","results","existingResults","incompleteRuns","runs","filter","handleBatchTaskRunExecutionResult","waitForBatch","combinedItems","existingItem","find","push","newItem","registerTaskMetadata","packageVersion","retry","undefined","machine","fns","init","cleanup","middleware","handleError","someObjectStoreOutputs","ok","outputType","INTERNAL","execution","outputPacket","output","importedPacket","error","hasBaseUrl","baseURL","hasAccessToken","accessToken","wait","for","start","Date","now","durationInMs","calculateDurationInMs","waitForDuration","nameForWaitOptions","until","throwIfInThePast","date","getTime","toISOString","seconds","minutes","hours","days","weeks","months","years","InMemoryCache","_cache","Map","get","key","set","value","delete","createCache","store","cache","cacheKey","fn","cacheEntry","updateName","metadata","createdTime","SpanStatusCode","context","trace","SEMATTRS_HTTP_HOST","SEMATTRS_HTTP_METHOD","SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH","SEMATTRS_HTTP_SCHEME","SEMATTRS_HTTP_STATUS_CODE","SEMATTRS_HTTP_URL","calculateNextRetryDelay","calculateResetAt","eventFilterMatches","flattenAttributes","defaultFetchRetryOptions","AsyncLocalStorage","onThrow","opts","maxAttempts","innerSpan","startSpan","contextWithSpanSet","setSpan","active","with","end","e","recordException","String","setStatus","code","ERROR","nextRetryDelay","RETRY_AT","RETRY_COUNT","RETRY_DELAY","normalizeUrlFromInput","input","URL","url","normalizeHttpMethod","method","toUpperCase","fetchHttpHandlerStorage","fetchWithInterceptors","handlers","getStore","getResponse","request","Request","fetch","FetchErrorWithSpan","constructor","originalError","MAX_ATTEMPTS","retryFetch","abortController","AbortController","timeoutId","timeoutInMs","setTimeout","abort","signal","addEventListener","doFetchRequest","clearTimeout","setAttributes","createFetchResponseAttributes","nextRetry","calculateRetryDelayForResponse","resolveDefaults","byStatus","type","nextRetryDate","isInFuture","waitUntil","timeout","cause","connectionError","createFetchAttributes","createFetchRetryOptionsAttributes","attemptCount","httpMethod","headers","toString","status","statusText","message","strategy","getRetryStrategyForResponse","resetAt","resetHeader","resetTimestamp","resetFormat","statusCodes","Object","keys","clonedResponse","clone","i","statusRange","isStatusCodeInRange","bodyFilter","body","safeJsonParse","statusCode","includes","split","s","trim","parseInt","endsWith","prefix","slice","statusCodePrefix","Math","floor","statusCodeString","rangePrefix","startsWith","createAttributesFromHeaders","normalizedHeaderKey","toLowerCase","forEach","json","JSON","parse","interceptFetch","current","obj","defaults","href","hostname","port","protocol","replace","APIError","BadRequestError","AuthenticationError","PermissionDeniedError","NotFoundError","ConflictError","UnprocessableEntityError","RateLimitError","InternalServerError","replay","replayRun","cancel","cancelRun","updateTaskMetadata","triggerSource","create","createSchedule","retrieve","scheduleId","retrieveSchedule","update","updateSchedule","del","deleteSchedule","deactivate","deactivateSchedule","activate","activateSchedule","list","listSchedules"],"mappings":";;;;;;;;;;;;;AAAA,SAASA,gBAAgB;AACzB,SACEC,gCACAC,8BACAC,iCACK;AACP,SAYEC,4BAIAC,qBACAC,kBACAC,2BACAC,sBACAC,qBACAC,QACAC,aACAC,SACAC,aACAC,aACAC,mBACK;;;AC/BL,cAAW;;;ACFb,SAASC,qBAAqB;AAGvB,IAAMC,SAAS,IAAID,cAAc;EAAEE,MAAM;EAAoBC;AAA6B,CAAA;;;AF4C1F,SAASC,MAAMC,SAAiD;AACrE,SAAOA;AACT;AAFgBD;AA8NT,SAASE,WACdC,QACuB;AACvB,QAAMC,QAA8B;IAClCC,IAAIF,OAAOE;IACXC,SAAS,OAAOC,SAASN,YAAY;AACnC,YAAMO,YAAYtB,iB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AAU0R,iBAAiBD,UAAAA;AACpC;AARsBD;AAmBtB,eAAsBG,OACpBF,YACAhS,SACyB;AACzB,QAAMO,YAAYtB,kBAAiBuB;AAEnC,MAAI,CAACD,WAAW;AACd,UAAME,sBAAAA;EACR;AAEA,SAAOF,UAAU4R,eAAeH,YAAYhS,OAAAA;AAC9C;AAXsBkS;AAiBtB,eAAsBE,IAAIJ,YAAoD;AAC5E,QAAMzR,YAAYtB,kBAAiBuB;AAEnC,MAAI,CAACD,WAAW;AACd,UAAME,sBAAAA;EACR;AAEA,SAAOF,UAAU8R,eAAeL,UAAAA;AAClC;AARsBI;AActB,eAAsBE,WAAWN,YAA6C;AAC5E,QAAMzR,YAAYtB,kBAAiBuB;AAEnC,MAAI,CAACD,WAAW;AACd,UAAME,sBAAAA;EACR;AAEA,SAAOF,UAAUgS,mBAAmBP,UAAAA;AACtC;AARsBM;AActB,eAAsBE,SAASR,YAA6C;AAC1E,QAAMzR,YAAYtB,kBAAiBuB;AAEnC,MAAI,CAACD,WAAW;AACd,UAAME,sBAAAA;EACR;AAEA,SAAOF,UAAUkS,iBAAiBT,UAAAA;AACpC;AARsBQ;AAiBtB,eAAsBE,KACpB1S,SAC8B;AAC9B,QAAMO,YAAYtB,kBAAiBuB;AAEnC,MAAI,CAACD,WAAW;AACd,UAAME,sBAAAA;EACR;AAEA,SAAOF,UAAUoS,cAAc3S,OAAAA;AACjC;AAVsB0S","sourcesContent":["import { SpanKind } from \"@opentelemetry/api\";\nimport {\n SEMATTRS_MESSAGING_DESTINATION,\n SEMATTRS_MESSAGING_OPERATION,\n SEMATTRS_MESSAGING_SYSTEM,\n} from \"@opentelemetry/semantic-conventions\";\nimport {\n BatchTaskRunExecutionResult,\n HandleErrorFnParams,\n HandleErrorResult,\n InitFnParams,\n InitOutput,\n MachineCpu,\n MachineMemory,\n MiddlewareFnParams,\n QueueOptions,\n RetryOptions,\n RunFnParams,\n SemanticInternalAttributes,\n SuccessFnParams,\n TaskRunContext,\n TaskRunExecutionResult,\n accessoryAttributes,\n apiClientManager,\n conditionallyImportPacket,\n createErrorTaskError,\n defaultRetryOptions,\n logger,\n parsePacket,\n runtime,\n stringifyIO,\n taskCatalog,\n taskContext,\n} from \"@trigger.dev/core/v3\";\nimport * as packageJson from \"../../package.json\";\nimport { tracer } from \"./tracer\";\n\nexport type Context = TaskRunContext;\n\ntype RequireOne<T, K extends keyof T> = {\n [X in Exclude<keyof T, K>]?: T[X];\n} & {\n [P in K]-?: T[P];\n};\n\nexport type Queue = RequireOne<QueueOptions, \"name\">;\n\nexport function queue(options: { name: string } & QueueOptions): Queue {\n return options;\n}\n\nexport type TaskOptions<\n TPayload = void,\n TOutput = unknown,\n TInitOutput extends InitOutput = any,\n> = {\n /** An id for your task. This must be unique inside your project and not change between versions. */\n id: string;\n /** The retry settings when an uncaught error is thrown.\n *\n * If omitted it will use the values in your `trigger.config.ts` file.\n * \n * @example\n * \n * ```\n * export const taskWithRetries = task({\n id: \"task-with-retries\",\n retry: {\n maxAttempts: 10,\n factor: 1.8,\n minTimeoutInMs: 500,\n maxTimeoutInMs: 30_000,\n randomize: false,\n },\n run: async ({ payload, ctx }) => {\n //...\n },\n });\n * ```\n * */\n retry?: RetryOptions;\n /** Used to configure what should happen when more than one run is triggered at the same time.\n * \n * @example \n * one at a time execution\n * \n * ```ts\n * export const oneAtATime = task({\n id: \"one-at-a-time\",\n queue: {\n concurrencyLimit: 1,\n },\n run: async ({ payload, ctx }) => {\n //...\n },\n });\n * ```\n */\n queue?: QueueOptions;\n /** Configure the spec of the machine you want your task to run on.\n * \n * @example\n * \n * ```ts\n * export const heavyTask = task({\n id: \"heavy-task\",\n machine: {\n cpu: 2,\n memory: 4,\n },\n run: async ({ payload, ctx }) => {\n //...\n },\n });\n * ```\n */\n machine?: {\n /** vCPUs. The default is 0.5.\n *\n * Possible values:\n * - 0.25\n * - 0.5\n * - 1\n * - 2\n * - 4\n */\n cpu?: MachineCpu;\n /** In GBs of RAM. The default is 1.\n *\n * Possible values:\n * - 0.25\n * - 0.5\n * - 1\n * - 2\n * - 4\n * - 8\n */\n memory?: MachineMemory;\n };\n /** This gets called when a task is triggered. It's where you put the code you want to execute.\n *\n * @param payload - The payload that is passed to your task when it's triggered. This must be JSON serializable.\n * @param params - Metadata about the run.\n */\n run: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<TOutput>;\n init?: (payload: TPayload, params: InitFnParams) => Promise<TInitOutput>;\n handleError?: (\n payload: TPayload,\n error: unknown,\n params: HandleErrorFnParams<TInitOutput>\n ) => HandleErrorResult;\n cleanup?: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<void>;\n middleware?: (payload: TPayload, params: MiddlewareFnParams) => Promise<void>;\n onSuccess?: (payload: TPayload, params: SuccessFnParams<TOutput, TInitOutput>) => Promise<void>;\n};\n\ntype InvokeHandle = {\n id: string;\n};\n\ntype InvokeBatchHandle = {\n batchId: string;\n runs: string[];\n};\n\nexport type TaskRunResult<TOutput = any> =\n | {\n ok: true;\n id: string;\n output: TOutput;\n }\n | {\n ok: false;\n id: string;\n error: unknown;\n };\n\nexport type BatchResult<TOutput = any> = {\n id: string;\n runs: TaskRunResult<TOutput>[];\n};\n\ntype BatchItem<TInput> = TInput extends void\n ? { payload?: TInput; options?: TaskRunOptions }\n : { payload: TInput; options?: TaskRunOptions };\n\nexport interface Task<TInput = void, TOutput = any> {\n /**\n * The id of the task.\n */\n id: string;\n /**\n * 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.\n * @param payload\n * @param options\n * @returns InvokeHandle\n * - `id` - The id of the triggered task run.\n */\n trigger: (payload: TInput, options?: TaskRunOptions) => Promise<InvokeHandle>;\n\n /**\n * 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.\n * @param items\n * @returns InvokeBatchHandle\n * - `batchId` - The id of the triggered batch.\n * - `runs` - The ids of the triggered task runs.\n */\n batchTrigger: (items: Array<BatchItem<TInput>>) => Promise<InvokeBatchHandle>;\n\n /**\n * Trigger a task with the given payload, and wait for the result. Returns the result of the task run\n * @param payload\n * @param options - Options for the task run\n * @returns TaskRunResult\n * @example\n * ```\n * const result = await task.triggerAndWait({ foo: \"bar\" });\n *\n * if (result.ok) {\n * console.log(result.output);\n * } else {\n * console.error(result.error);\n * }\n * ```\n */\n triggerAndWait: (payload: TInput, options?: TaskRunOptions) => Promise<TaskRunResult<TOutput>>;\n\n /**\n * Batch trigger multiple task runs with the given payloads, and wait for the results. Returns the results of the task runs.\n * @param items\n * @returns BatchResult\n * @example\n * ```\n * const result = await task.batchTriggerAndWait([\n * { payload: { foo: \"bar\" } },\n * { payload: { foo: \"baz\" } },\n * ]);\n *\n * for (const run of result.runs) {\n * if (run.ok) {\n * console.log(run.output);\n * } else {\n * console.error(run.error);\n * }\n * }\n * ```\n */\n batchTriggerAndWait: (items: Array<BatchItem<TInput>>) => Promise<BatchResult<TOutput>>;\n}\n\ntype TaskRunOptions = {\n idempotencyKey?: string;\n maxAttempts?: number;\n startAt?: Date;\n startAfter?: number;\n queue?: TaskRunConcurrencyOptions;\n concurrencyKey?: string;\n};\n\ntype TaskRunConcurrencyOptions = Queue;\n\nexport type Prettify<T> = {\n [K in keyof T]: T[K];\n} & {};\n\nexport type DynamicBaseOptions = {\n id: string;\n};\n\nexport function createTask<TInput = void, TOutput = unknown, TInitOutput extends InitOutput = any>(\n params: TaskOptions<TInput, TOutput, TInitOutput>\n): Task<TInput, TOutput> {\n const task: Task<TInput, TOutput> = {\n id: params.id,\n trigger: async (payload, options) => {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n const taskMetadata = taskCatalog.getTaskMetadata(params.id);\n\n const payloadPacket = await stringifyIO(payload);\n\n const handle = await tracer.startActiveSpan(\n taskMetadata ? \"Trigger\" : `${params.id} trigger()`,\n async (span) => {\n const response = await apiClient.triggerTask(\n params.id,\n {\n payload: payloadPacket.data,\n options: {\n queue: params.queue,\n concurrencyKey: options?.concurrencyKey,\n test: taskContext.ctx?.run.isTest,\n payloadType: payloadPacket.dataType,\n idempotencyKey: options?.idempotencyKey,\n },\n },\n { spanParentAsLink: true }\n );\n\n span.setAttribute(\"messaging.message.id\", response.id);\n\n return response;\n },\n {\n kind: SpanKind.PRODUCER,\n attributes: {\n [SEMATTRS_MESSAGING_OPERATION]: \"publish\",\n [SemanticInternalAttributes.STYLE_ICON]: \"trigger\",\n [\"messaging.client_id\"]: taskContext.worker?.id,\n [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,\n [SEMATTRS_MESSAGING_SYSTEM]: \"trigger.dev\",\n ...(taskMetadata\n ? accessoryAttributes({\n items: [\n {\n text: `${taskMetadata.exportName}.trigger()`,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n })\n : {}),\n },\n }\n );\n\n return handle;\n },\n batchTrigger: async (items) => {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n const taskMetadata = taskCatalog.getTaskMetadata(params.id);\n\n const response = await tracer.startActiveSpan(\n taskMetadata ? \"Batch trigger\" : `${params.id} batchTrigger()`,\n async (span) => {\n const response = await apiClient.batchTriggerTask(\n params.id,\n {\n items: await Promise.all(\n items.map(async (item) => {\n const payloadPacket = await stringifyIO(item.payload);\n\n return {\n payload: payloadPacket.data,\n options: {\n queue: item.options?.queue ?? params.queue,\n concurrencyKey: item.options?.concurrencyKey,\n test: taskContext.ctx?.run.isTest,\n payloadType: payloadPacket.dataType,\n idempotencyKey: item.options?.idempotencyKey,\n },\n };\n })\n ),\n },\n { spanParentAsLink: true }\n );\n\n span.setAttribute(\"messaging.message.id\", response.batchId);\n\n return response;\n },\n {\n kind: SpanKind.PRODUCER,\n attributes: {\n [SEMATTRS_MESSAGING_OPERATION]: \"publish\",\n [\"messaging.batch.message_count\"]: items.length,\n [\"messaging.client_id\"]: taskContext.worker?.id,\n [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,\n [SEMATTRS_MESSAGING_SYSTEM]: \"trigger.dev\",\n [SemanticInternalAttributes.STYLE_ICON]: \"trigger\",\n ...(taskMetadata\n ? accessoryAttributes({\n items: [\n {\n text: `${taskMetadata.exportName}.batchTrigger()`,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n })\n : {}),\n },\n }\n );\n\n return response;\n },\n triggerAndWait: async (payload, options) => {\n const ctx = taskContext.ctx;\n\n if (!ctx) {\n throw new Error(\"triggerAndWait can only be used from inside a task.run()\");\n }\n\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n const taskMetadata = taskCatalog.getTaskMetadata(params.id);\n\n const payloadPacket = await stringifyIO(payload);\n\n return await tracer.startActiveSpan(\n taskMetadata ? \"Trigger\" : `${params.id} triggerAndWait()`,\n async (span) => {\n const response = await apiClient.triggerTask(params.id, {\n payload: payloadPacket.data,\n options: {\n dependentAttempt: ctx.attempt.id,\n lockToVersion: taskContext.worker?.version, // Lock to current version because we're waiting for it to finish\n queue: params.queue,\n concurrencyKey: options?.concurrencyKey,\n test: taskContext.ctx?.run.isTest,\n payloadType: payloadPacket.dataType,\n idempotencyKey: options?.idempotencyKey,\n },\n });\n\n span.setAttribute(\"messaging.message.id\", response.id);\n\n if (options?.idempotencyKey) {\n // If an idempotency key is provided, we can check if the result is already available\n const result = await apiClient.getRunResult(response.id);\n\n if (result) {\n logger.log(\n `Result reused from previous task run with idempotency key '${options.idempotencyKey}'.`,\n {\n runId: response.id,\n idempotencyKey: options.idempotencyKey,\n }\n );\n\n return await handleTaskRunExecutionResult<TOutput>(result);\n }\n }\n\n const result = await runtime.waitForTask({\n id: response.id,\n ctx,\n });\n\n return await handleTaskRunExecutionResult<TOutput>(result);\n },\n {\n kind: SpanKind.PRODUCER,\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"trigger\",\n [SEMATTRS_MESSAGING_OPERATION]: \"publish\",\n [\"messaging.client_id\"]: taskContext.worker?.id,\n [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,\n [SEMATTRS_MESSAGING_SYSTEM]: \"trigger.dev\",\n ...(taskMetadata\n ? accessoryAttributes({\n items: [\n {\n text: `${taskMetadata.exportName}.triggerAndWait()`,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n })\n : {}),\n },\n }\n );\n },\n batchTriggerAndWait: async (items) => {\n const ctx = taskContext.ctx;\n\n if (!ctx) {\n throw new Error(\"batchTriggerAndWait can only be used from inside a task.run()\");\n }\n\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n const taskMetadata = taskCatalog.getTaskMetadata(params.id);\n\n return await tracer.startActiveSpan(\n taskMetadata ? \"Batch trigger\" : `${params.id} batchTriggerAndWait()`,\n async (span) => {\n const response = await apiClient.batchTriggerTask(params.id, {\n items: await Promise.all(\n items.map(async (item) => {\n const payloadPacket = await stringifyIO(item.payload);\n\n return {\n payload: payloadPacket.data,\n options: {\n lockToVersion: taskContext.worker?.version,\n queue: item.options?.queue ?? params.queue,\n concurrencyKey: item.options?.concurrencyKey,\n test: taskContext.ctx?.run.isTest,\n payloadType: payloadPacket.dataType,\n idempotencyKey: item.options?.idempotencyKey,\n },\n };\n })\n ),\n dependentAttempt: ctx.attempt.id,\n });\n\n span.setAttribute(\"messaging.message.id\", response.batchId);\n\n const getBatchResults = async (): Promise<BatchTaskRunExecutionResult> => {\n // We need to check if the results are already available, but only if any of the items options has an idempotency key\n const hasIdempotencyKey = items.some((item) => item.options?.idempotencyKey);\n\n if (hasIdempotencyKey) {\n const results = await apiClient.getBatchResults(response.batchId);\n\n if (results) {\n return results;\n }\n }\n\n return {\n id: response.batchId,\n items: [],\n };\n };\n\n const existingResults = await getBatchResults();\n\n const incompleteRuns = response.runs.filter(\n (runId) => !existingResults.items.some((item) => item.id === runId)\n );\n\n if (incompleteRuns.length === 0) {\n logger.log(\n `Results reused from previous task runs because of the provided idempotency keys.`\n );\n\n // All runs are already completed\n const runs = await handleBatchTaskRunExecutionResult<TOutput>(existingResults.items);\n\n return {\n id: existingResults.id,\n runs,\n };\n }\n\n const result = await runtime.waitForBatch({\n id: response.batchId,\n runs: incompleteRuns,\n ctx,\n });\n\n // Combine the already completed runs with the newly completed runs, ordered by the original order\n const combinedItems: BatchTaskRunExecutionResult[\"items\"] = [];\n\n for (const runId of response.runs) {\n const existingItem = existingResults.items.find((item) => item.id === runId);\n\n if (existingItem) {\n combinedItems.push(existingItem);\n } else {\n const newItem = result.items.find((item) => item.id === runId);\n\n if (newItem) {\n combinedItems.push(newItem);\n }\n }\n }\n\n const runs = await handleBatchTaskRunExecutionResult<TOutput>(combinedItems);\n\n return {\n id: result.id,\n runs,\n };\n },\n {\n kind: SpanKind.PRODUCER,\n attributes: {\n [SEMATTRS_MESSAGING_OPERATION]: \"publish\",\n [\"messaging.batch.message_count\"]: items.length,\n [\"messaging.client_id\"]: taskContext.worker?.id,\n [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,\n [SEMATTRS_MESSAGING_SYSTEM]: \"trigger.dev\",\n [SemanticInternalAttributes.STYLE_ICON]: \"trigger\",\n ...(taskMetadata\n ? accessoryAttributes({\n items: [\n {\n text: `${taskMetadata.exportName}.batchTriggerAndWait()`,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n })\n : {}),\n },\n }\n );\n },\n };\n\n taskCatalog.registerTaskMetadata({\n id: params.id,\n packageVersion: packageJson.version,\n queue: params.queue,\n retry: params.retry ? { ...defaultRetryOptions, ...params.retry } : undefined,\n machine: params.machine,\n fns: {\n run: params.run,\n init: params.init,\n cleanup: params.cleanup,\n middleware: params.middleware,\n handleError: params.handleError,\n },\n });\n\n return task;\n}\n\nasync function handleBatchTaskRunExecutionResult<TOutput>(\n items: Array<TaskRunExecutionResult>\n): Promise<Array<TaskRunResult<TOutput>>> {\n const someObjectStoreOutputs = items.some(\n (item) => item.ok && item.outputType === \"application/store\"\n );\n\n if (!someObjectStoreOutputs) {\n const results = await Promise.all(\n items.map(async (item) => {\n return await handleTaskRunExecutionResult<TOutput>(item);\n })\n );\n\n return results;\n }\n\n return await tracer.startActiveSpan(\n \"store.downloadPayloads\",\n async (span) => {\n const results = await Promise.all(\n items.map(async (item) => {\n return await handleTaskRunExecutionResult<TOutput>(item);\n })\n );\n\n return results;\n },\n {\n kind: SpanKind.INTERNAL,\n [SemanticInternalAttributes.STYLE_ICON]: \"cloud-download\",\n }\n );\n}\n\nasync function handleTaskRunExecutionResult<TOutput>(\n execution: TaskRunExecutionResult\n): Promise<TaskRunResult<TOutput>> {\n if (execution.ok) {\n const outputPacket = { data: execution.output, dataType: execution.outputType };\n const importedPacket = await conditionallyImportPacket(outputPacket, tracer);\n\n return {\n ok: true,\n id: execution.id,\n output: await parsePacket(importedPacket),\n };\n } else {\n return {\n ok: false,\n id: execution.id,\n error: createErrorTaskError(execution.error),\n };\n }\n}\n\nexport function apiClientMissingError() {\n const hasBaseUrl = !!apiClientManager.baseURL;\n const hasAccessToken = !!apiClientManager.accessToken;\n if (!hasBaseUrl && !hasAccessToken) {\n return `You need to set the TRIGGER_API_URL and TRIGGER_SECRET_KEY environment variables.`;\n } else if (!hasBaseUrl) {\n return `You need to set the TRIGGER_API_URL environment variable.`;\n } else if (!hasAccessToken) {\n return `You need to set the TRIGGER_SECRET_KEY environment variable.`;\n }\n\n return `Unknown error`;\n}\n","{\n \"name\": \"@trigger.dev/sdk\",\n \"version\": \"3.0.0-beta.20\",\n \"description\": \"trigger.dev Node.JS SDK\",\n \"license\": \"MIT\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"module\": \"./dist/index.mjs\",\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"files\": [\n \"dist\"\n ],\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.mts\",\n \"default\": \"./dist/index.mjs\"\n },\n \"require\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\"\n },\n \"./v3\": {\n \"import\": {\n \"types\": \"./dist/v3/index.d.mts\",\n \"default\": \"./dist/v3/index.mjs\"\n },\n \"require\": \"./dist/v3/index.js\",\n \"types\": \"./dist/v3/index.d.ts\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"typesVersions\": {\n \"*\": {\n \"v3\": [\n \"./dist/v3/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"clean\": \"rimraf dist\",\n \"build\": \"npm run clean && npm run build:tsup\",\n \"build:tsup\": \"tsup --dts-resolve\",\n \"typecheck\": \"tsc --noEmit\"\n },\n \"dependencies\": {\n \"@opentelemetry/api\": \"^1.8.0\",\n \"@opentelemetry/api-logs\": \"^0.48.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.22.0\",\n \"@trigger.dev/core\": \"workspace:3.0.0-beta.20\",\n \"@trigger.dev/core-backend\": \"workspace:3.0.0-beta.20\",\n \"chalk\": \"^5.2.0\",\n \"cronstrue\": \"^2.21.0\",\n \"debug\": \"^4.3.4\",\n \"evt\": \"^2.4.13\",\n \"get-caller-file\": \"^2.0.5\",\n \"git-remote-origin-url\": \"^4.0.0\",\n \"git-repo-info\": \"^2.1.1\",\n \"slug\": \"^6.0.0\",\n \"terminal-link\": \"^3.0.0\",\n \"ulid\": \"^2.3.0\",\n \"uuid\": \"^9.0.0\",\n \"ws\": \"^8.11.0\",\n \"zod\": \"3.22.3\",\n \"msw\": \"^2.2.1\"\n },\n \"devDependencies\": {\n \"@trigger.dev/tsconfig\": \"workspace:*\",\n \"@trigger.dev/tsup\": \"workspace:*\",\n \"@types/debug\": \"^4.1.7\",\n \"@types/node\": \"18\",\n \"@types/slug\": \"^5.0.3\",\n \"@types/uuid\": \"^9.0.0\",\n \"@types/ws\": \"^8.5.3\",\n \"encoding\": \"^0.1.13\",\n \"msw\": \"^2.2.1\",\n \"rimraf\": \"^3.0.2\",\n \"tsup\": \"^8.0.1\",\n \"typed-emitter\": \"^2.1.0\",\n \"typescript\": \"^5.3.0\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n }\n}","import { TriggerTracer } from \"@trigger.dev/core/v3\";\nimport * as packageJson from \"../../package.json\";\n\nexport const tracer = new TriggerTracer({ name: \"@trigger.dev/sdk\", version: packageJson.version });\n","import { InitOutput } from \"@trigger.dev/core/v3\";\nimport { TaskOptions, Task, createTask } from \"./shared\";\n\n/** Creates a task that can be triggered\n * @param options - Task options\n * @example \n * \n * ```ts\n * import { task } from \"@trigger.dev/sdk/v3\";\n *\n * export const helloWorld = task({\n id: \"hello-world\",\n * run: async (payload: { url: string }) => {\n * return { hello: \"world\" };\n * },\n * });\n *\n * ```\n * \n * @returns A task that can be triggered\n */\nexport function task<TInput = void, TOutput = unknown, TInitOutput extends InitOutput = any>(\n options: TaskOptions<TInput, TOutput, TInitOutput>\n): Task<TInput, TOutput> {\n return createTask<TInput, TOutput, TInitOutput>(options);\n}\n\nexport type { TaskOptions, Task };\n","import { SemanticInternalAttributes, accessoryAttributes, runtime } from \"@trigger.dev/core/v3\";\nimport { tracer } from \"./tracer\";\n\nexport type WaitOptions =\n | {\n seconds: number;\n }\n | {\n minutes: number;\n }\n | {\n hours: number;\n }\n | {\n days: number;\n }\n | {\n weeks: number;\n }\n | {\n months: number;\n }\n | {\n years: number;\n };\n\nexport const wait = {\n for: async (options: WaitOptions) => {\n return tracer.startActiveSpan(\n `wait.for()`,\n async (span) => {\n const start = Date.now();\n const durationInMs = calculateDurationInMs(options);\n\n await runtime.waitForDuration(durationInMs);\n },\n {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"wait\",\n ...accessoryAttributes({\n items: [\n {\n text: nameForWaitOptions(options),\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n }),\n },\n }\n );\n },\n until: async (options: { date: Date; throwIfInThePast?: boolean }) => {\n return tracer.startActiveSpan(\n `wait.until()`,\n async (span) => {\n const start = Date.now();\n\n if (options.throwIfInThePast && options.date < new Date()) {\n throw new Error(\"Date is in the past\");\n }\n\n const durationInMs = options.date.getTime() - start;\n\n await runtime.waitForDuration(durationInMs);\n },\n {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"wait\",\n ...accessoryAttributes({\n items: [\n {\n text: options.date.toISOString(),\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n }),\n },\n }\n );\n },\n};\n\nfunction nameForWaitOptions(options: WaitOptions): string {\n if (\"seconds\" in options) {\n return options.seconds === 1 ? `1 second` : `${options.seconds} seconds`;\n }\n\n if (\"minutes\" in options) {\n return options.minutes === 1 ? `1 minute` : `${options.minutes} minutes`;\n }\n\n if (\"hours\" in options) {\n return options.hours === 1 ? `1 hour` : `${options.hours} hours`;\n }\n\n if (\"days\" in options) {\n return options.days === 1 ? `1 day` : `${options.days} days`;\n }\n\n if (\"weeks\" in options) {\n return options.weeks === 1 ? `1 week` : `${options.weeks} weeks`;\n }\n\n if (\"months\" in options) {\n return options.months === 1 ? `1 month` : `${options.months} months`;\n }\n\n if (\"years\" in options) {\n return options.years === 1 ? `1 year` : `${options.years} years`;\n }\n\n return \"NaN\";\n}\n\nfunction calculateDurationInMs(options: WaitOptions): number {\n if (\"seconds\" in options) {\n return options.seconds * 1000;\n }\n\n if (\"minutes\" in options) {\n return options.minutes * 1000 * 60;\n }\n\n if (\"hours\" in options) {\n return options.hours * 1000 * 60 * 60;\n }\n\n if (\"days\" in options) {\n return options.days * 1000 * 60 * 60 * 24;\n }\n\n if (\"weeks\" in options) {\n return options.weeks * 1000 * 60 * 60 * 24 * 7;\n }\n\n if (\"months\" in options) {\n return options.months * 1000 * 60 * 60 * 24 * 30;\n }\n\n if (\"years\" in options) {\n return options.years * 1000 * 60 * 60 * 24 * 365;\n }\n\n throw new Error(\"Invalid options\");\n}\n\ntype RequestOptions = {\n to: (url: string) => Promise<void>;\n timeout: WaitOptions;\n};\n","import { SemanticInternalAttributes } from \"@trigger.dev/core/v3\";\nimport { tracer } from \"./tracer\";\n\nexport type CacheMetadata = {\n createdTime: number;\n ttl?: number | null;\n};\n\nexport type CacheEntry<Value = unknown> = {\n metadata: CacheMetadata;\n value: Value;\n};\n\nexport type Eventually<Value> = Value | null | undefined | Promise<Value | null | undefined>;\n\nexport type CacheStore<Value = any> = {\n name?: string;\n get: (key: string) => Eventually<CacheEntry<Value>>;\n set: (key: string, value: CacheEntry<Value>) => unknown | Promise<unknown>;\n delete: (key: string) => unknown | Promise<unknown>;\n};\n\nexport type CacheFunction = <Value>(\n cacheKey: string,\n fn: () => Promise<Value> | Value\n) => Promise<Value> | Value;\n\nexport class InMemoryCache<Value = any> {\n private _cache: Map<string, CacheEntry<Value>> = new Map();\n\n get(key: string): Eventually<CacheEntry<Value>> {\n return this._cache.get(key);\n }\n\n set(key: string, value: CacheEntry<Value>): unknown {\n this._cache.set(key, value);\n\n return undefined;\n }\n\n delete(key: string): unknown {\n this._cache.delete(key);\n\n return undefined;\n }\n}\n\n/**\n * Create a cache function that uses the provided store to cache values. Using InMemoryCache is safe because each task run is isolated.\n * @param store\n * @returns\n */\nexport function createCache(store: CacheStore): CacheFunction {\n return function cache<Value>(\n cacheKey: string,\n fn: () => Promise<Value> | Value\n ): Promise<Value> | Value {\n return tracer.startActiveSpan(\"cache\", async (span) => {\n span.setAttribute(\"cache.key\", cacheKey);\n span.setAttribute(SemanticInternalAttributes.STYLE_ICON, \"device-sd-card\");\n\n const cacheEntry = await store.get(cacheKey);\n\n if (cacheEntry) {\n span.updateName(`cache.hit ${cacheKey}`);\n\n return cacheEntry.value;\n }\n\n span.updateName(`cache.miss ${cacheKey}`);\n\n const value = await tracer.startActiveSpan(\n \"cache.getFreshValue\",\n async (span) => {\n return await fn();\n },\n {\n attributes: {\n \"cache.key\": cacheKey,\n [SemanticInternalAttributes.STYLE_ICON]: \"device-sd-card\",\n },\n }\n );\n\n await tracer.startActiveSpan(\n \"cache.set\",\n async (span) => {\n await store.set(cacheKey, {\n value,\n metadata: {\n createdTime: Date.now(),\n },\n });\n },\n {\n attributes: {\n \"cache.key\": cacheKey,\n [SemanticInternalAttributes.STYLE_ICON]: \"device-sd-card\",\n },\n }\n );\n\n return value;\n });\n };\n}\n","import { Attributes, Span, SpanStatusCode, context, trace } from \"@opentelemetry/api\";\nimport {\n SEMATTRS_HTTP_HOST,\n SEMATTRS_HTTP_METHOD,\n SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,\n SEMATTRS_HTTP_SCHEME,\n SEMATTRS_HTTP_STATUS_CODE,\n SEMATTRS_HTTP_URL,\n} from \"@opentelemetry/semantic-conventions\";\nimport {\n FetchRetryByStatusOptions,\n FetchRetryOptions,\n FetchRetryStrategy,\n RetryOptions,\n SemanticInternalAttributes,\n accessoryAttributes,\n calculateNextRetryDelay,\n calculateResetAt,\n defaultRetryOptions,\n eventFilterMatches,\n flattenAttributes,\n runtime,\n} from \"@trigger.dev/core/v3\";\nimport { defaultFetchRetryOptions } from \"@trigger.dev/core/v3\";\nimport type { HttpHandler } from \"msw\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { tracer } from \"./tracer\";\n\nexport type { RetryOptions };\n\nfunction onThrow<T>(\n fn: (options: { attempt: number; maxAttempts: number }) => Promise<T>,\n options: RetryOptions\n): Promise<T> {\n const opts = {\n ...defaultRetryOptions,\n ...options,\n };\n\n return tracer.startActiveSpan(\n `retry.onThrow()`,\n async (span) => {\n let attempt = 1;\n\n while (attempt <= opts.maxAttempts) {\n const innerSpan = tracer.startSpan(\"retry.fn()\", {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"function\",\n ...accessoryAttributes({\n items: [\n {\n text: `${attempt}/${opts.maxAttempts}`,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n }),\n },\n });\n\n const contextWithSpanSet = trace.setSpan(context.active(), innerSpan);\n\n try {\n const result = await context.with(contextWithSpanSet, async () => {\n return fn({ attempt, maxAttempts: opts.maxAttempts });\n });\n\n innerSpan.end();\n\n return result;\n } catch (e) {\n if (e instanceof Error || typeof e === \"string\") {\n innerSpan.recordException(e);\n } else {\n innerSpan.recordException(String(e));\n }\n\n innerSpan.setStatus({ code: SpanStatusCode.ERROR });\n\n const nextRetryDelay = calculateNextRetryDelay(opts, attempt);\n\n if (!nextRetryDelay) {\n innerSpan.end();\n\n throw e;\n }\n\n innerSpan.setAttribute(\n SemanticInternalAttributes.RETRY_AT,\n new Date(Date.now() + nextRetryDelay).toISOString()\n );\n innerSpan.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);\n innerSpan.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);\n innerSpan.end();\n\n await runtime.waitForDuration(nextRetryDelay);\n } finally {\n attempt++;\n }\n }\n\n throw new Error(\"Max attempts reached\");\n },\n {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"arrow-capsule\",\n },\n }\n );\n}\n\nexport interface RetryFetchRequestInit extends RequestInit {\n retry?: FetchRetryOptions;\n timeoutInMs?: number;\n}\n\nconst normalizeUrlFromInput = (input: RequestInfo | URL | string): URL => {\n if (typeof input === \"string\") {\n return new URL(input);\n }\n\n if (input instanceof URL) {\n return input;\n }\n\n return new URL(input.url);\n};\n\nconst normalizeHttpMethod = (input: RequestInfo | URL | string, init?: RequestInit): string => {\n if (typeof input === \"string\" || input instanceof URL) {\n return (init?.method || \"GET\").toUpperCase();\n }\n\n return (input.method ?? init?.method ?? \"GET\").toUpperCase();\n};\n\nconst fetchHttpHandlerStorage = new AsyncLocalStorage<Array<HttpHandler>>();\n\nconst fetchWithInterceptors = async (\n input: RequestInfo | URL,\n init?: RequestInit\n): Promise<Response> => {\n const handlers = fetchHttpHandlerStorage.getStore();\n\n if (handlers) {\n try {\n const { getResponse } = await import(\"msw\");\n\n const request = new Request(input, init);\n\n const response = await getResponse(handlers, request);\n\n if (response) {\n return response;\n }\n } catch (e) {\n // Do nothing\n return fetch(input, init);\n }\n }\n\n return fetch(input, init);\n};\n\nclass FetchErrorWithSpan extends Error {\n constructor(\n public readonly originalError: unknown,\n public readonly span: Span\n ) {\n super(\"Fetch error\");\n }\n}\n\nconst MAX_ATTEMPTS = 10;\n\nasync function retryFetch(\n input: RequestInfo | URL,\n init?: RetryFetchRequestInit | undefined\n): Promise<Response> {\n return tracer.startActiveSpan(\n \"retry.fetch()\",\n async (span) => {\n let attempt = 1;\n\n while (true) {\n try {\n const abortController = new AbortController();\n\n const timeoutId = init?.timeoutInMs\n ? setTimeout(\n () => {\n abortController.abort();\n },\n init?.timeoutInMs\n )\n : undefined;\n\n init?.signal?.addEventListener(\"abort\", () => {\n abortController.abort();\n });\n\n const [response, span] = await doFetchRequest(\n input,\n { ...(init ?? {}), signal: abortController.signal },\n attempt\n );\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n if (response.ok) {\n span.setAttributes(createFetchResponseAttributes(response));\n\n span.end();\n\n return response;\n }\n\n const nextRetry = await calculateRetryDelayForResponse(\n resolveDefaults(init?.retry, \"byStatus\", defaultFetchRetryOptions.byStatus),\n response,\n attempt\n );\n\n if (!nextRetry) {\n span.setAttributes(createFetchResponseAttributes(response));\n\n span.end();\n\n return response;\n }\n\n if (attempt >= MAX_ATTEMPTS) {\n span.setAttributes(createFetchResponseAttributes(response));\n\n span.end();\n\n return response;\n }\n\n if (nextRetry.type === \"delay\") {\n span.setAttribute(\n SemanticInternalAttributes.RETRY_AT,\n new Date(Date.now() + nextRetry.value).toISOString()\n );\n span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);\n span.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetry.value}ms`);\n\n span.end();\n\n await runtime.waitForDuration(nextRetry.value);\n } else {\n const now = Date.now();\n const nextRetryDate = new Date(nextRetry.value);\n const isInFuture = nextRetryDate.getTime() > now;\n\n span.setAttribute(\n SemanticInternalAttributes.RETRY_AT,\n new Date(nextRetry.value).toISOString()\n );\n span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);\n\n if (isInFuture) {\n span.setAttribute(\n SemanticInternalAttributes.RETRY_DELAY,\n `${nextRetry.value - now}ms`\n );\n }\n\n span.end();\n\n await runtime.waitUntil(new Date(nextRetry.value));\n }\n } catch (e) {\n if (e instanceof FetchErrorWithSpan && e.originalError instanceof Error) {\n if (e.originalError.name === \"AbortError\") {\n const nextRetryDelay = calculateNextRetryDelay(\n resolveDefaults(init?.retry, \"timeout\", defaultFetchRetryOptions.timeout),\n attempt\n );\n\n if (!nextRetryDelay) {\n e.span.end();\n throw e;\n }\n\n if (attempt >= MAX_ATTEMPTS) {\n e.span.end();\n throw e;\n }\n\n e.span.setAttribute(\n SemanticInternalAttributes.RETRY_AT,\n new Date(Date.now() + nextRetryDelay).toISOString()\n );\n e.span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);\n e.span.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);\n\n e.span.end();\n\n await runtime.waitForDuration(nextRetryDelay);\n\n continue; // Move to the next attempt\n } else if (\n e.originalError.name === \"TypeError\" &&\n \"cause\" in e.originalError &&\n e.originalError.cause instanceof Error\n ) {\n const nextRetryDelay = calculateNextRetryDelay(\n resolveDefaults(\n init?.retry,\n \"connectionError\",\n defaultFetchRetryOptions.connectionError\n ),\n attempt\n );\n\n if (!nextRetryDelay) {\n e.span.end();\n throw e;\n }\n\n if (attempt >= MAX_ATTEMPTS) {\n e.span.end();\n throw e;\n }\n\n e.span.setAttribute(\n SemanticInternalAttributes.RETRY_AT,\n new Date(Date.now() + nextRetryDelay).toISOString()\n );\n e.span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);\n e.span.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);\n\n e.span.end();\n\n await runtime.waitForDuration(nextRetryDelay);\n\n continue; // Move to the next attempt\n }\n }\n\n if (e instanceof FetchErrorWithSpan) {\n e.span.end();\n }\n\n throw e;\n } finally {\n attempt++;\n }\n }\n },\n {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"arrow-capsule\",\n ...createFetchAttributes(input, init),\n ...createFetchRetryOptionsAttributes(init?.retry),\n },\n }\n );\n}\n\nconst doFetchRequest = async (\n input: RequestInfo | URL | string,\n init?: RequestInit,\n attemptCount: number = 0\n): Promise<[Response, Span]> => {\n const httpMethod = normalizeHttpMethod(input, init);\n\n const span = tracer.startSpan(`HTTP ${httpMethod}`, {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"world\",\n ...(attemptCount > 1 ? { [\"http.request.resend_count\"]: attemptCount - 1 } : {}),\n ...createFetchAttributes(input, init),\n },\n });\n\n try {\n const response = await fetchWithInterceptors(input, {\n ...init,\n headers: {\n ...init?.headers,\n \"x-retry-count\": attemptCount.toString(),\n },\n });\n\n span.setAttributes(createFetchResponseAttributes(response));\n\n if (!response.ok) {\n span.recordException(`${response.status}: ${response.statusText}`);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `${response.status}: ${response.statusText}`,\n });\n }\n\n return [response, span];\n } catch (e) {\n if (typeof e === \"string\" || e instanceof Error) {\n span.recordException(e);\n }\n\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.setAttribute(SEMATTRS_HTTP_STATUS_CODE, 0);\n span.setAttribute(\"http.status_text\", \"This operation was aborted.\");\n\n throw new FetchErrorWithSpan(e, span);\n }\n};\n\nconst calculateRetryDelayForResponse = async (\n retry: FetchRetryByStatusOptions | undefined,\n response: Response,\n attemptCount: number\n): Promise<{ type: \"delay\"; value: number } | { type: \"timestamp\"; value: number } | undefined> => {\n if (!retry) {\n return;\n }\n\n const strategy = await getRetryStrategyForResponse(response, retry);\n\n if (!strategy) {\n return;\n }\n\n switch (strategy.strategy) {\n case \"backoff\": {\n const value = calculateNextRetryDelay({ ...defaultRetryOptions, ...strategy }, attemptCount);\n\n if (value) {\n return { type: \"delay\", value };\n }\n\n break;\n }\n case \"headers\": {\n const resetAt = response.headers.get(strategy.resetHeader);\n\n if (typeof resetAt === \"string\") {\n const resetTimestamp = calculateResetAt(\n resetAt,\n strategy.resetFormat ?? \"unix_timestamp_in_ms\"\n );\n\n if (resetTimestamp) {\n return { type: \"timestamp\", value: resetTimestamp };\n }\n }\n\n break;\n }\n }\n};\n\nconst getRetryStrategyForResponse = async (\n response: Response,\n retry: FetchRetryByStatusOptions\n): Promise<FetchRetryStrategy | undefined> => {\n const statusCodes = Object.keys(retry);\n const clonedResponse = response.clone();\n\n for (let i = 0; i < statusCodes.length; i++) {\n const statusRange = statusCodes[i];\n const strategy = retry[statusRange];\n\n if (isStatusCodeInRange(response.status, statusRange)) {\n if (strategy.bodyFilter) {\n const body = safeJsonParse(await clonedResponse.text());\n\n if (!body) {\n continue;\n }\n\n if (eventFilterMatches(body, strategy.bodyFilter)) {\n return strategy;\n } else {\n continue;\n }\n }\n\n return strategy;\n }\n }\n};\n\n/**\n * Checks if a given status code falls within a given range.\n * The range can be a single status code (e.g. \"200\"),\n * a range of status codes (e.g. \"500-599\"),\n * a range of status codes with a wildcard (e.g. \"4xx\" for any 4xx status code),\n * or a list of status codes separated by commas (e.g. \"401,403,404,409-412,5xx\").\n * Returns `true` if the status code falls within the range, and `false` otherwise.\n */\nconst isStatusCodeInRange = (statusCode: number, statusRange: string): boolean => {\n if (statusRange === \"all\") {\n return true;\n }\n\n if (statusRange.includes(\",\")) {\n const statusCodes = statusRange.split(\",\").map((s) => s.trim());\n\n return statusCodes.some((s) => isStatusCodeInRange(statusCode, s));\n }\n\n const [start, end] = statusRange.split(\"-\");\n\n if (end) {\n return statusCode >= parseInt(start, 10) && statusCode <= parseInt(end, 10);\n }\n\n if (start.endsWith(\"xx\")) {\n const prefix = start.slice(0, -2);\n const statusCodePrefix = Math.floor(statusCode / 100).toString();\n return statusCodePrefix === prefix;\n }\n\n const statusCodeString = statusCode.toString();\n const rangePrefix = start.slice(0, -1);\n\n if (start.endsWith(\"x\") && statusCodeString.startsWith(rangePrefix)) {\n return true;\n }\n\n return statusCode === parseInt(start, 10);\n};\n\nconst createAttributesFromHeaders = (headers: Headers): Attributes => {\n const attributes: Attributes = {};\n\n const normalizedHeaderKey = (key: string) => {\n return key.toLowerCase();\n };\n\n headers.forEach((value, key) => {\n attributes[`http.response.header.${normalizedHeaderKey(key)}`] = value;\n });\n\n return attributes;\n};\n\nconst safeJsonParse = (json: string): unknown => {\n try {\n return JSON.parse(json);\n } catch (e) {\n return null;\n }\n};\n\nconst interceptFetch = (...handlers: Array<HttpHandler>) => {\n return {\n run: async <T>(fn: (...args: any[]) => Promise<T>): Promise<T> => {\n const current = fetchHttpHandlerStorage.getStore();\n\n if (current) {\n current.push(...handlers);\n return fn();\n } else {\n return fetchHttpHandlerStorage.run(handlers, fn);\n }\n },\n };\n};\n\n// This function will resolve the defaults of a property within an options object.\n// If the options object is undefined, it will return the defaults for that property (passed in as the 3rd arg).\n// if the options object is defined, and the property exists, then it will return the defaults if the value of the property is undefined or null\nconst resolveDefaults = <\n TObject extends Record<string, unknown>,\n K extends keyof TObject,\n TValue extends TObject[K],\n>(\n obj: TObject | undefined,\n key: K,\n defaults: TValue\n): TValue => {\n if (!obj) {\n return defaults;\n }\n\n if (obj[key] === undefined || obj[key] === null) {\n return defaults;\n }\n\n return obj[key] as TValue;\n};\n\nconst createFetchAttributes = (\n input: RequestInfo | URL,\n init?: RetryFetchRequestInit | undefined\n): Attributes => {\n const url = normalizeUrlFromInput(input);\n const httpMethod = normalizeHttpMethod(input, init);\n\n return {\n [SEMATTRS_HTTP_METHOD]: httpMethod,\n [SEMATTRS_HTTP_URL]: url.href,\n [SEMATTRS_HTTP_HOST]: url.hostname,\n [\"server.host\"]: url.hostname,\n [\"server.port\"]: url.port,\n [SEMATTRS_HTTP_SCHEME]: url.protocol.replace(\":\", \"\"),\n ...accessoryAttributes({\n items: [\n {\n text: url.hostname,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n }),\n };\n};\n\nconst createFetchResponseAttributes = (response: Response): Attributes => {\n return {\n [SEMATTRS_HTTP_STATUS_CODE]: response.status,\n \"http.status_text\": response.statusText,\n [SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH]: response.headers.get(\"content-length\") || \"0\",\n ...createAttributesFromHeaders(response.headers),\n };\n};\n\nconst createFetchRetryOptionsAttributes = (retry?: FetchRetryOptions): Attributes => {\n const byStatus = resolveDefaults(retry, \"byStatus\", defaultFetchRetryOptions.byStatus);\n const connectionError = resolveDefaults(\n retry,\n \"connectionError\",\n defaultFetchRetryOptions.connectionError\n );\n const timeout = resolveDefaults(retry, \"timeout\", defaultFetchRetryOptions.timeout);\n\n return {\n ...flattenAttributes(byStatus, \"retry.byStatus\"),\n ...flattenAttributes(connectionError, \"retry.connectionError\"),\n ...flattenAttributes(timeout, \"retry.timeout\"),\n };\n};\n\nexport const retry = {\n onThrow,\n fetch: retryFetch,\n interceptFetch,\n};\n","export * from \"./tasks\";\nexport * from \"./config\";\nexport * from \"./wait\";\nexport * from \"./cache\";\nexport { retry, type RetryOptions } from \"./retry\";\nexport { queue } from \"./shared\";\n\nimport type { Context } from \"./shared\";\nexport type { Context };\n\nexport {\n logger,\n type LogLevel,\n APIError,\n BadRequestError,\n AuthenticationError,\n PermissionDeniedError,\n NotFoundError,\n ConflictError,\n UnprocessableEntityError,\n RateLimitError,\n InternalServerError,\n} from \"@trigger.dev/core/v3\";\n\nexport { runs } from \"./management\";\nexport * as schedules from \"./schedules\";\n","import { CanceledRunResponse, ReplayRunResponse, apiClientManager } from \"@trigger.dev/core/v3\";\nimport { apiClientMissingError } from \"./shared\";\n\nexport const runs = {\n replay: replayRun,\n cancel: cancelRun,\n};\n\nasync function replayRun(runId: string): Promise<ReplayRunResponse> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return await apiClient.replayRun(runId);\n}\n\nasync function cancelRun(runId: string): Promise<CanceledRunResponse> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return await apiClient.cancelRun(runId);\n}\n","import {\n DeletedScheduleObject,\n InitOutput,\n ListSchedulesResult,\n ScheduleObject,\n apiClientManager,\n taskCatalog,\n} from \"@trigger.dev/core/v3\";\nimport { Task, TaskOptions, apiClientMissingError, createTask } from \"../shared\";\nimport * as SchedulesAPI from \"./api\";\n\nexport function task<TOutput, TInitOutput extends InitOutput>(\n params: TaskOptions<SchedulesAPI.ScheduledTaskPayload, TOutput, TInitOutput>\n): Task<SchedulesAPI.ScheduledTaskPayload, TOutput> {\n const task = createTask(params);\n\n taskCatalog.updateTaskMetadata(task.id, {\n triggerSource: \"schedule\",\n });\n\n return task;\n}\n\n/**\n * Creates a new schedule\n * @param options\n * @param options.task - The identifier of the task to be scheduled (Must already exist and be a scheduled task)\n * @param options.cron - The cron expression for the schedule (e.g. `0 0 * * *`)\n * @param options.externalId - An optional external identifier for the schedule\n * @param options.deduplicationKey - An optional deduplication key for the schedule\n * @returns The created schedule\n */\nexport async function create(options: SchedulesAPI.CreateScheduleOptions): Promise<ScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.createSchedule(options);\n}\n\n/**\n * Retrieves a schedule\n * @param scheduleId - The ID of the schedule to retrieve\n * @returns The retrieved schedule\n */\nexport async function retrieve(scheduleId: string): Promise<ScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.retrieveSchedule(scheduleId);\n}\n\n/**\n * Updates a schedule\n * @param scheduleId - The ID of the schedule to update\n * @param options - The updated schedule options\n * @param options.task - The identifier of the task to be scheduled (Must already exist and be a scheduled task)\n * @param options.cron - The cron expression for the schedule (e.g. `0 0 * * *`)\n * @param options.externalId - An optional external identifier for the schedule\n * @returns The updated schedule\n */\nexport async function update(\n scheduleId: string,\n options: SchedulesAPI.UpdateScheduleOptions\n): Promise<ScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.updateSchedule(scheduleId, options);\n}\n\n/**\n * Deletes a schedule\n * @param scheduleId - The ID of the schedule to delete\n */\nexport async function del(scheduleId: string): Promise<DeletedScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.deleteSchedule(scheduleId);\n}\n\n/**\n * Deactivates a schedule\n * @param scheduleId - The ID of the schedule to deactivate\n */\nexport async function deactivate(scheduleId: string): Promise<ScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.deactivateSchedule(scheduleId);\n}\n\n/**\n * Activates a schedule\n * @param scheduleId - The ID of the schedule to activate\n */\nexport async function activate(scheduleId: string): Promise<ScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.activateSchedule(scheduleId);\n}\n\n/**\n * Lists schedules\n * @param options - The list options\n * @param options.page - The page number\n * @param options.perPage - The number of schedules per page\n * @returns The list of schedules\n */\nexport async function list(\n options?: SchedulesAPI.ListScheduleOptions\n): Promise<ListSchedulesResult> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.listSchedules(options);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/v3/shared.ts","../../package.json","../../src/v3/tracer.ts","../../src/v3/tasks.ts","../../src/v3/wait.ts","../../src/v3/cache.ts","../../src/v3/retry.ts","../../src/v3/index.ts","../../src/v3/management.ts","../../src/v3/schedules/index.ts"],"names":["SpanKind","SEMATTRS_MESSAGING_DESTINATION","SEMATTRS_MESSAGING_OPERATION","SEMATTRS_MESSAGING_SYSTEM","SemanticInternalAttributes","accessoryAttributes","apiClientManager","conditionallyImportPacket","createErrorTaskError","defaultRetryOptions","logger","parsePacket","runtime","stringifyIO","taskCatalog","taskContext","TriggerTracer","tracer","name","version","queue","options","createTask","params","task","id","trigger","payload","apiClient","client","apiClientMissingError","taskMetadata","getTaskMetadata","payloadPacket","handle","startActiveSpan","span","response","triggerTask","data","concurrencyKey","test","ctx","run","isTest","payloadType","dataType","idempotencyKey","spanParentAsLink","setAttribute","kind","PRODUCER","attributes","STYLE_ICON","worker","items","text","exportName","variant","style","batchTrigger","batchTriggerTask","Promise","all","map","item","batchId","length","triggerAndWait","Error","dependentAttempt","attempt","lockToVersion","result","getRunResult","log","runId","handleTaskRunExecutionResult","waitForTask","batchTriggerAndWait","getBatchResults","hasIdempotencyKey","some","results","existingResults","incompleteRuns","runs","filter","handleBatchTaskRunExecutionResult","waitForBatch","combinedItems","existingItem","find","push","newItem","registerTaskMetadata","packageVersion","retry","undefined","machine","fns","init","cleanup","middleware","handleError","onSuccess","onFailure","onStart","someObjectStoreOutputs","ok","outputType","INTERNAL","execution","outputPacket","output","importedPacket","error","hasBaseUrl","baseURL","hasAccessToken","accessToken","wait","for","start","Date","now","durationInMs","calculateDurationInMs","waitForDuration","nameForWaitOptions","until","throwIfInThePast","date","getTime","toISOString","seconds","minutes","hours","days","weeks","months","years","InMemoryCache","_cache","Map","get","key","set","value","delete","createCache","store","cache","cacheKey","fn","cacheEntry","updateName","metadata","createdTime","SpanStatusCode","context","trace","SEMATTRS_HTTP_HOST","SEMATTRS_HTTP_METHOD","SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH","SEMATTRS_HTTP_SCHEME","SEMATTRS_HTTP_STATUS_CODE","SEMATTRS_HTTP_URL","calculateNextRetryDelay","calculateResetAt","eventFilterMatches","flattenAttributes","defaultFetchRetryOptions","AsyncLocalStorage","onThrow","opts","maxAttempts","innerSpan","startSpan","contextWithSpanSet","setSpan","active","with","end","e","recordException","String","setStatus","code","ERROR","nextRetryDelay","RETRY_AT","RETRY_COUNT","RETRY_DELAY","normalizeUrlFromInput","input","URL","url","normalizeHttpMethod","method","toUpperCase","fetchHttpHandlerStorage","fetchWithInterceptors","handlers","getStore","getResponse","request","Request","fetch","FetchErrorWithSpan","constructor","originalError","MAX_ATTEMPTS","retryFetch","abortController","AbortController","timeoutId","timeoutInMs","setTimeout","abort","signal","addEventListener","doFetchRequest","clearTimeout","setAttributes","createFetchResponseAttributes","nextRetry","calculateRetryDelayForResponse","resolveDefaults","byStatus","type","nextRetryDate","isInFuture","waitUntil","timeout","cause","connectionError","createFetchAttributes","createFetchRetryOptionsAttributes","attemptCount","httpMethod","headers","toString","status","statusText","message","strategy","getRetryStrategyForResponse","resetAt","resetHeader","resetTimestamp","resetFormat","statusCodes","Object","keys","clonedResponse","clone","i","statusRange","isStatusCodeInRange","bodyFilter","body","safeJsonParse","statusCode","includes","split","s","trim","parseInt","endsWith","prefix","slice","statusCodePrefix","Math","floor","statusCodeString","rangePrefix","startsWith","createAttributesFromHeaders","normalizedHeaderKey","toLowerCase","forEach","json","JSON","parse","interceptFetch","current","obj","defaults","href","hostname","port","protocol","replace","APIError","BadRequestError","AuthenticationError","PermissionDeniedError","NotFoundError","ConflictError","UnprocessableEntityError","RateLimitError","InternalServerError","replay","replayRun","cancel","cancelRun","updateTaskMetadata","triggerSource","create","createSchedule","retrieve","scheduleId","retrieveSchedule","update","updateSchedule","del","deleteSchedule","deactivate","deactivateSchedule","activate","activateSchedule","list","listSchedules"],"mappings":";;;;;;;;;;;;;AAAA,SAASA,gBAAgB;AACzB,SACEC,gCACAC,8BACAC,iCACK;AACP,SAaEC,4BAKAC,qBACAC,kBACAC,2BACAC,sBACAC,qBACAC,QACAC,aACAC,SACAC,aACAC,aACAC,mBACK;;;ACjCL,cAAW;;;ACFb,SAASC,qBAAqB;AAGvB,IAAMC,SAAS,IAAID,cAAc;EAAEE,MAAM;EAAoBC;AAA6B,CAAA;;;AF8C1F,SAASC,MAAMC,SAAiD;AACrE,SAAOA;AACT;AAFgBD;AA0RT,SAASE,WACdC,QACuB;AACvB,QAAMC,QAA8B;IAClCC,IAAIF,OAAOE;IACXC,SAAS,OAAOC,SAASN,YAAY;AACnC,YAAMO,YAAYtB,iBAAiBuB;AAEnC,UAAI,CAACD,WAAW;AACd,cAAME,sBAAAA;MACR;AAEA,YAAMC,eAAejB,YAAYkB,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A;AACpC;AARsBD;AAmBtB,eAAsBG,OACpBF,YACAnS,SACyB;AACzB,QAAMO,YAAYtB,kBAAiBuB;AAEnC,MAAI,CAACD,WAAW;AACd,UAAME,sBAAAA;EACR;AAEA,SAAOF,UAAU+R,eAAeH,YAAYnS,OAAAA;AAC9C;AAXsBqS;AAiBtB,eAAsBE,IAAIJ,YAAoD;AAC5E,QAAM5R,YAAYtB,kBAAiBuB;AAEnC,MAAI,CAACD,WAAW;AACd,UAAME,sBAAAA;EACR;AAEA,SAAOF,UAAUiS,eAAeL,UAAAA;AAClC;AARsBI;AActB,eAAsBE,WAAWN,YAA6C;AAC5E,QAAM5R,YAAYtB,kBAAiBuB;AAEnC,MAAI,CAACD,WAAW;AACd,UAAME,sBAAAA;EACR;AAEA,SAAOF,UAAUmS,mBAAmBP,UAAAA;AACtC;AARsBM;AActB,eAAsBE,SAASR,YAA6C;AAC1E,QAAM5R,YAAYtB,kBAAiBuB;AAEnC,MAAI,CAACD,WAAW;AACd,UAAME,sBAAAA;EACR;AAEA,SAAOF,UAAUqS,iBAAiBT,UAAAA;AACpC;AARsBQ;AAiBtB,eAAsBE,KACpB7S,SAC8B;AAC9B,QAAMO,YAAYtB,kBAAiBuB;AAEnC,MAAI,CAACD,WAAW;AACd,UAAME,sBAAAA;EACR;AAEA,SAAOF,UAAUuS,cAAc9S,OAAAA;AACjC;AAVsB6S","sourcesContent":["import { SpanKind } from \"@opentelemetry/api\";\nimport {\n SEMATTRS_MESSAGING_DESTINATION,\n SEMATTRS_MESSAGING_OPERATION,\n SEMATTRS_MESSAGING_SYSTEM,\n} from \"@opentelemetry/semantic-conventions\";\nimport {\n BatchTaskRunExecutionResult,\n FailureFnParams,\n HandleErrorFnParams,\n HandleErrorResult,\n InitFnParams,\n InitOutput,\n MachineCpu,\n MachineMemory,\n MiddlewareFnParams,\n QueueOptions,\n RetryOptions,\n RunFnParams,\n SemanticInternalAttributes,\n StartFnParams,\n SuccessFnParams,\n TaskRunContext,\n TaskRunExecutionResult,\n accessoryAttributes,\n apiClientManager,\n conditionallyImportPacket,\n createErrorTaskError,\n defaultRetryOptions,\n logger,\n parsePacket,\n runtime,\n stringifyIO,\n taskCatalog,\n taskContext,\n} from \"@trigger.dev/core/v3\";\nimport * as packageJson from \"../../package.json\";\nimport { tracer } from \"./tracer\";\n\nexport type Context = TaskRunContext;\n\ntype RequireOne<T, K extends keyof T> = {\n [X in Exclude<keyof T, K>]?: T[X];\n} & {\n [P in K]-?: T[P];\n};\n\nexport type Queue = RequireOne<QueueOptions, \"name\">;\n\nexport function queue(options: { name: string } & QueueOptions): Queue {\n return options;\n}\n\nexport type TaskOptions<\n TPayload = void,\n TOutput = unknown,\n TInitOutput extends InitOutput = any,\n> = {\n /** An id for your task. This must be unique inside your project and not change between versions. */\n id: string;\n /** The retry settings when an uncaught error is thrown.\n *\n * If omitted it will use the values in your `trigger.config.ts` file.\n * \n * @example\n * \n * ```\n * export const taskWithRetries = task({\n id: \"task-with-retries\",\n retry: {\n maxAttempts: 10,\n factor: 1.8,\n minTimeoutInMs: 500,\n maxTimeoutInMs: 30_000,\n randomize: false,\n },\n run: async ({ payload, ctx }) => {\n //...\n },\n });\n * ```\n * */\n retry?: RetryOptions;\n /** Used to configure what should happen when more than one run is triggered at the same time.\n * \n * @example \n * one at a time execution\n * \n * ```ts\n * export const oneAtATime = task({\n id: \"one-at-a-time\",\n queue: {\n concurrencyLimit: 1,\n },\n run: async ({ payload, ctx }) => {\n //...\n },\n });\n * ```\n */\n queue?: QueueOptions;\n /** Configure the spec of the machine you want your task to run on.\n * \n * @example\n * \n * ```ts\n * export const heavyTask = task({\n id: \"heavy-task\",\n machine: {\n cpu: 2,\n memory: 4,\n },\n run: async ({ payload, ctx }) => {\n //...\n },\n });\n * ```\n */\n machine?: {\n /** vCPUs. The default is 0.5.\n *\n * Possible values:\n * - 0.25\n * - 0.5\n * - 1\n * - 2\n * - 4\n */\n cpu?: MachineCpu;\n /** In GBs of RAM. The default is 1.\n *\n * Possible values:\n * - 0.25\n * - 0.5\n * - 1\n * - 2\n * - 4\n * - 8\n */\n memory?: MachineMemory;\n };\n /** This gets called when a task is triggered. It's where you put the code you want to execute.\n *\n * @param payload - The payload that is passed to your task when it's triggered. This must be JSON serializable.\n * @param params - Metadata about the run.\n */\n run: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<TOutput>;\n\n /**\n * init is called before the run function is called. It's useful for setting up any global state.\n */\n init?: (payload: TPayload, params: InitFnParams) => Promise<TInitOutput>;\n\n /**\n * cleanup is called after the run function has completed.\n */\n cleanup?: (payload: TPayload, params: RunFnParams<TInitOutput>) => Promise<void>;\n\n /**\n * handleError is called when the run function throws an error. It can be used to modify the error or return new retry options.\n */\n handleError?: (\n payload: TPayload,\n error: unknown,\n params: HandleErrorFnParams<TInitOutput>\n ) => HandleErrorResult;\n\n /**\n * middleware allows you to run code \"around\" the run function. This can be useful for logging, metrics, or other cross-cutting concerns.\n *\n * When writing middleware, you should always call `next()` to continue the execution of the task:\n *\n * ```ts\n * export const middlewareTask = task({\n * id: \"middleware-task\",\n * middleware: async (payload, { ctx, next }) => {\n * console.log(\"Before run\");\n * await next();\n * console.log(\"After run\");\n * },\n * run: async (payload, { ctx }) => {}\n * });\n * ```\n */\n middleware?: (payload: TPayload, params: MiddlewareFnParams) => Promise<void>;\n\n /**\n * onStart is called the first time a task is executed in a run (not before every retry)\n */\n onStart?: (payload: TPayload, params: StartFnParams) => Promise<void>;\n\n /**\n * onSuccess is called after the run function has successfully completed.\n */\n onSuccess?: (\n payload: TPayload,\n output: TOutput,\n params: SuccessFnParams<TInitOutput>\n ) => Promise<void>;\n\n /**\n * onFailure is called after a task run has failed (meaning the run function threw an error and won't be retried anymore)\n */\n onFailure?: (\n payload: TPayload,\n error: unknown,\n params: FailureFnParams<TInitOutput>\n ) => Promise<void>;\n};\n\ntype InvokeHandle = {\n id: string;\n};\n\ntype InvokeBatchHandle = {\n batchId: string;\n runs: string[];\n};\n\nexport type TaskRunResult<TOutput = any> =\n | {\n ok: true;\n id: string;\n output: TOutput;\n }\n | {\n ok: false;\n id: string;\n error: unknown;\n };\n\nexport type BatchResult<TOutput = any> = {\n id: string;\n runs: TaskRunResult<TOutput>[];\n};\n\ntype BatchItem<TInput> = TInput extends void\n ? { payload?: TInput; options?: TaskRunOptions }\n : { payload: TInput; options?: TaskRunOptions };\n\nexport interface Task<TInput = void, TOutput = any> {\n /**\n * The id of the task.\n */\n id: string;\n /**\n * 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.\n * @param payload\n * @param options\n * @returns InvokeHandle\n * - `id` - The id of the triggered task run.\n */\n trigger: (payload: TInput, options?: TaskRunOptions) => Promise<InvokeHandle>;\n\n /**\n * 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.\n * @param items\n * @returns InvokeBatchHandle\n * - `batchId` - The id of the triggered batch.\n * - `runs` - The ids of the triggered task runs.\n */\n batchTrigger: (items: Array<BatchItem<TInput>>) => Promise<InvokeBatchHandle>;\n\n /**\n * Trigger a task with the given payload, and wait for the result. Returns the result of the task run\n * @param payload\n * @param options - Options for the task run\n * @returns TaskRunResult\n * @example\n * ```\n * const result = await task.triggerAndWait({ foo: \"bar\" });\n *\n * if (result.ok) {\n * console.log(result.output);\n * } else {\n * console.error(result.error);\n * }\n * ```\n */\n triggerAndWait: (payload: TInput, options?: TaskRunOptions) => Promise<TaskRunResult<TOutput>>;\n\n /**\n * Batch trigger multiple task runs with the given payloads, and wait for the results. Returns the results of the task runs.\n * @param items\n * @returns BatchResult\n * @example\n * ```\n * const result = await task.batchTriggerAndWait([\n * { payload: { foo: \"bar\" } },\n * { payload: { foo: \"baz\" } },\n * ]);\n *\n * for (const run of result.runs) {\n * if (run.ok) {\n * console.log(run.output);\n * } else {\n * console.error(run.error);\n * }\n * }\n * ```\n */\n batchTriggerAndWait: (items: Array<BatchItem<TInput>>) => Promise<BatchResult<TOutput>>;\n}\n\nexport type TaskPayload<TTask extends Task> = TTask extends Task<infer TInput, any>\n ? TInput\n : never;\n\nexport type TaskOutput<TTask extends Task> = TTask extends Task<any, infer TOutput>\n ? TOutput\n : never;\n\ntype TaskRunOptions = {\n idempotencyKey?: string;\n maxAttempts?: number;\n startAt?: Date;\n startAfter?: number;\n queue?: TaskRunConcurrencyOptions;\n concurrencyKey?: string;\n};\n\ntype TaskRunConcurrencyOptions = Queue;\n\nexport type Prettify<T> = {\n [K in keyof T]: T[K];\n} & {};\n\nexport type DynamicBaseOptions = {\n id: string;\n};\n\nexport function createTask<TInput = void, TOutput = unknown, TInitOutput extends InitOutput = any>(\n params: TaskOptions<TInput, TOutput, TInitOutput>\n): Task<TInput, TOutput> {\n const task: Task<TInput, TOutput> = {\n id: params.id,\n trigger: async (payload, options) => {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n const taskMetadata = taskCatalog.getTaskMetadata(params.id);\n\n const payloadPacket = await stringifyIO(payload);\n\n const handle = await tracer.startActiveSpan(\n taskMetadata ? \"Trigger\" : `${params.id} trigger()`,\n async (span) => {\n const response = await apiClient.triggerTask(\n params.id,\n {\n payload: payloadPacket.data,\n options: {\n queue: params.queue,\n concurrencyKey: options?.concurrencyKey,\n test: taskContext.ctx?.run.isTest,\n payloadType: payloadPacket.dataType,\n idempotencyKey: options?.idempotencyKey,\n },\n },\n { spanParentAsLink: true }\n );\n\n span.setAttribute(\"messaging.message.id\", response.id);\n\n return response;\n },\n {\n kind: SpanKind.PRODUCER,\n attributes: {\n [SEMATTRS_MESSAGING_OPERATION]: \"publish\",\n [SemanticInternalAttributes.STYLE_ICON]: \"trigger\",\n [\"messaging.client_id\"]: taskContext.worker?.id,\n [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,\n [SEMATTRS_MESSAGING_SYSTEM]: \"trigger.dev\",\n ...(taskMetadata\n ? accessoryAttributes({\n items: [\n {\n text: `${taskMetadata.exportName}.trigger()`,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n })\n : {}),\n },\n }\n );\n\n return handle;\n },\n batchTrigger: async (items) => {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n const taskMetadata = taskCatalog.getTaskMetadata(params.id);\n\n const response = await tracer.startActiveSpan(\n taskMetadata ? \"Batch trigger\" : `${params.id} batchTrigger()`,\n async (span) => {\n const response = await apiClient.batchTriggerTask(\n params.id,\n {\n items: await Promise.all(\n items.map(async (item) => {\n const payloadPacket = await stringifyIO(item.payload);\n\n return {\n payload: payloadPacket.data,\n options: {\n queue: item.options?.queue ?? params.queue,\n concurrencyKey: item.options?.concurrencyKey,\n test: taskContext.ctx?.run.isTest,\n payloadType: payloadPacket.dataType,\n idempotencyKey: item.options?.idempotencyKey,\n },\n };\n })\n ),\n },\n { spanParentAsLink: true }\n );\n\n span.setAttribute(\"messaging.message.id\", response.batchId);\n\n return response;\n },\n {\n kind: SpanKind.PRODUCER,\n attributes: {\n [SEMATTRS_MESSAGING_OPERATION]: \"publish\",\n [\"messaging.batch.message_count\"]: items.length,\n [\"messaging.client_id\"]: taskContext.worker?.id,\n [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,\n [SEMATTRS_MESSAGING_SYSTEM]: \"trigger.dev\",\n [SemanticInternalAttributes.STYLE_ICON]: \"trigger\",\n ...(taskMetadata\n ? accessoryAttributes({\n items: [\n {\n text: `${taskMetadata.exportName}.batchTrigger()`,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n })\n : {}),\n },\n }\n );\n\n return response;\n },\n triggerAndWait: async (payload, options) => {\n const ctx = taskContext.ctx;\n\n if (!ctx) {\n throw new Error(\"triggerAndWait can only be used from inside a task.run()\");\n }\n\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n const taskMetadata = taskCatalog.getTaskMetadata(params.id);\n\n const payloadPacket = await stringifyIO(payload);\n\n return await tracer.startActiveSpan(\n taskMetadata ? \"Trigger\" : `${params.id} triggerAndWait()`,\n async (span) => {\n const response = await apiClient.triggerTask(params.id, {\n payload: payloadPacket.data,\n options: {\n dependentAttempt: ctx.attempt.id,\n lockToVersion: taskContext.worker?.version, // Lock to current version because we're waiting for it to finish\n queue: params.queue,\n concurrencyKey: options?.concurrencyKey,\n test: taskContext.ctx?.run.isTest,\n payloadType: payloadPacket.dataType,\n idempotencyKey: options?.idempotencyKey,\n },\n });\n\n span.setAttribute(\"messaging.message.id\", response.id);\n\n if (options?.idempotencyKey) {\n // If an idempotency key is provided, we can check if the result is already available\n const result = await apiClient.getRunResult(response.id);\n\n if (result) {\n logger.log(\n `Result reused from previous task run with idempotency key '${options.idempotencyKey}'.`,\n {\n runId: response.id,\n idempotencyKey: options.idempotencyKey,\n }\n );\n\n return await handleTaskRunExecutionResult<TOutput>(result);\n }\n }\n\n const result = await runtime.waitForTask({\n id: response.id,\n ctx,\n });\n\n return await handleTaskRunExecutionResult<TOutput>(result);\n },\n {\n kind: SpanKind.PRODUCER,\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"trigger\",\n [SEMATTRS_MESSAGING_OPERATION]: \"publish\",\n [\"messaging.client_id\"]: taskContext.worker?.id,\n [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,\n [SEMATTRS_MESSAGING_SYSTEM]: \"trigger.dev\",\n ...(taskMetadata\n ? accessoryAttributes({\n items: [\n {\n text: `${taskMetadata.exportName}.triggerAndWait()`,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n })\n : {}),\n },\n }\n );\n },\n batchTriggerAndWait: async (items) => {\n const ctx = taskContext.ctx;\n\n if (!ctx) {\n throw new Error(\"batchTriggerAndWait can only be used from inside a task.run()\");\n }\n\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n const taskMetadata = taskCatalog.getTaskMetadata(params.id);\n\n return await tracer.startActiveSpan(\n taskMetadata ? \"Batch trigger\" : `${params.id} batchTriggerAndWait()`,\n async (span) => {\n const response = await apiClient.batchTriggerTask(params.id, {\n items: await Promise.all(\n items.map(async (item) => {\n const payloadPacket = await stringifyIO(item.payload);\n\n return {\n payload: payloadPacket.data,\n options: {\n lockToVersion: taskContext.worker?.version,\n queue: item.options?.queue ?? params.queue,\n concurrencyKey: item.options?.concurrencyKey,\n test: taskContext.ctx?.run.isTest,\n payloadType: payloadPacket.dataType,\n idempotencyKey: item.options?.idempotencyKey,\n },\n };\n })\n ),\n dependentAttempt: ctx.attempt.id,\n });\n\n span.setAttribute(\"messaging.message.id\", response.batchId);\n\n const getBatchResults = async (): Promise<BatchTaskRunExecutionResult> => {\n // We need to check if the results are already available, but only if any of the items options has an idempotency key\n const hasIdempotencyKey = items.some((item) => item.options?.idempotencyKey);\n\n if (hasIdempotencyKey) {\n const results = await apiClient.getBatchResults(response.batchId);\n\n if (results) {\n return results;\n }\n }\n\n return {\n id: response.batchId,\n items: [],\n };\n };\n\n const existingResults = await getBatchResults();\n\n const incompleteRuns = response.runs.filter(\n (runId) => !existingResults.items.some((item) => item.id === runId)\n );\n\n if (incompleteRuns.length === 0) {\n logger.log(\n `Results reused from previous task runs because of the provided idempotency keys.`\n );\n\n // All runs are already completed\n const runs = await handleBatchTaskRunExecutionResult<TOutput>(existingResults.items);\n\n return {\n id: existingResults.id,\n runs,\n };\n }\n\n const result = await runtime.waitForBatch({\n id: response.batchId,\n runs: incompleteRuns,\n ctx,\n });\n\n // Combine the already completed runs with the newly completed runs, ordered by the original order\n const combinedItems: BatchTaskRunExecutionResult[\"items\"] = [];\n\n for (const runId of response.runs) {\n const existingItem = existingResults.items.find((item) => item.id === runId);\n\n if (existingItem) {\n combinedItems.push(existingItem);\n } else {\n const newItem = result.items.find((item) => item.id === runId);\n\n if (newItem) {\n combinedItems.push(newItem);\n }\n }\n }\n\n const runs = await handleBatchTaskRunExecutionResult<TOutput>(combinedItems);\n\n return {\n id: result.id,\n runs,\n };\n },\n {\n kind: SpanKind.PRODUCER,\n attributes: {\n [SEMATTRS_MESSAGING_OPERATION]: \"publish\",\n [\"messaging.batch.message_count\"]: items.length,\n [\"messaging.client_id\"]: taskContext.worker?.id,\n [SEMATTRS_MESSAGING_DESTINATION]: params.queue?.name ?? params.id,\n [SEMATTRS_MESSAGING_SYSTEM]: \"trigger.dev\",\n [SemanticInternalAttributes.STYLE_ICON]: \"trigger\",\n ...(taskMetadata\n ? accessoryAttributes({\n items: [\n {\n text: `${taskMetadata.exportName}.batchTriggerAndWait()`,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n })\n : {}),\n },\n }\n );\n },\n };\n\n taskCatalog.registerTaskMetadata({\n id: params.id,\n packageVersion: packageJson.version,\n queue: params.queue,\n retry: params.retry ? { ...defaultRetryOptions, ...params.retry } : undefined,\n machine: params.machine,\n fns: {\n run: params.run,\n init: params.init,\n cleanup: params.cleanup,\n middleware: params.middleware,\n handleError: params.handleError,\n onSuccess: params.onSuccess,\n onFailure: params.onFailure,\n onStart: params.onStart,\n },\n });\n\n return task;\n}\n\nasync function handleBatchTaskRunExecutionResult<TOutput>(\n items: Array<TaskRunExecutionResult>\n): Promise<Array<TaskRunResult<TOutput>>> {\n const someObjectStoreOutputs = items.some(\n (item) => item.ok && item.outputType === \"application/store\"\n );\n\n if (!someObjectStoreOutputs) {\n const results = await Promise.all(\n items.map(async (item) => {\n return await handleTaskRunExecutionResult<TOutput>(item);\n })\n );\n\n return results;\n }\n\n return await tracer.startActiveSpan(\n \"store.downloadPayloads\",\n async (span) => {\n const results = await Promise.all(\n items.map(async (item) => {\n return await handleTaskRunExecutionResult<TOutput>(item);\n })\n );\n\n return results;\n },\n {\n kind: SpanKind.INTERNAL,\n [SemanticInternalAttributes.STYLE_ICON]: \"cloud-download\",\n }\n );\n}\n\nasync function handleTaskRunExecutionResult<TOutput>(\n execution: TaskRunExecutionResult\n): Promise<TaskRunResult<TOutput>> {\n if (execution.ok) {\n const outputPacket = { data: execution.output, dataType: execution.outputType };\n const importedPacket = await conditionallyImportPacket(outputPacket, tracer);\n\n return {\n ok: true,\n id: execution.id,\n output: await parsePacket(importedPacket),\n };\n } else {\n return {\n ok: false,\n id: execution.id,\n error: createErrorTaskError(execution.error),\n };\n }\n}\n\nexport function apiClientMissingError() {\n const hasBaseUrl = !!apiClientManager.baseURL;\n const hasAccessToken = !!apiClientManager.accessToken;\n if (!hasBaseUrl && !hasAccessToken) {\n return `You need to set the TRIGGER_API_URL and TRIGGER_SECRET_KEY environment variables.`;\n } else if (!hasBaseUrl) {\n return `You need to set the TRIGGER_API_URL environment variable.`;\n } else if (!hasAccessToken) {\n return `You need to set the TRIGGER_SECRET_KEY environment variable.`;\n }\n\n return `Unknown error`;\n}\n","{\n \"name\": \"@trigger.dev/sdk\",\n \"version\": \"3.0.0-beta.21\",\n \"description\": \"trigger.dev Node.JS SDK\",\n \"license\": \"MIT\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"module\": \"./dist/index.mjs\",\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"files\": [\n \"dist\"\n ],\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.mts\",\n \"default\": \"./dist/index.mjs\"\n },\n \"require\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\"\n },\n \"./v3\": {\n \"import\": {\n \"types\": \"./dist/v3/index.d.mts\",\n \"default\": \"./dist/v3/index.mjs\"\n },\n \"require\": \"./dist/v3/index.js\",\n \"types\": \"./dist/v3/index.d.ts\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"typesVersions\": {\n \"*\": {\n \"v3\": [\n \"./dist/v3/index.d.ts\"\n ]\n }\n },\n \"scripts\": {\n \"clean\": \"rimraf dist\",\n \"build\": \"npm run clean && npm run build:tsup\",\n \"build:tsup\": \"tsup --dts-resolve\",\n \"typecheck\": \"tsc --noEmit\"\n },\n \"dependencies\": {\n \"@opentelemetry/api\": \"^1.8.0\",\n \"@opentelemetry/api-logs\": \"^0.48.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.22.0\",\n \"@trigger.dev/core\": \"workspace:3.0.0-beta.21\",\n \"@trigger.dev/core-backend\": \"workspace:3.0.0-beta.21\",\n \"chalk\": \"^5.2.0\",\n \"cronstrue\": \"^2.21.0\",\n \"debug\": \"^4.3.4\",\n \"evt\": \"^2.4.13\",\n \"get-caller-file\": \"^2.0.5\",\n \"git-remote-origin-url\": \"^4.0.0\",\n \"git-repo-info\": \"^2.1.1\",\n \"slug\": \"^6.0.0\",\n \"terminal-link\": \"^3.0.0\",\n \"ulid\": \"^2.3.0\",\n \"uuid\": \"^9.0.0\",\n \"ws\": \"^8.11.0\",\n \"zod\": \"3.22.3\",\n \"msw\": \"^2.2.1\"\n },\n \"devDependencies\": {\n \"@trigger.dev/tsconfig\": \"workspace:*\",\n \"@trigger.dev/tsup\": \"workspace:*\",\n \"@types/debug\": \"^4.1.7\",\n \"@types/node\": \"18\",\n \"@types/slug\": \"^5.0.3\",\n \"@types/uuid\": \"^9.0.0\",\n \"@types/ws\": \"^8.5.3\",\n \"encoding\": \"^0.1.13\",\n \"msw\": \"^2.2.1\",\n \"rimraf\": \"^3.0.2\",\n \"tsup\": \"^8.0.1\",\n \"typed-emitter\": \"^2.1.0\",\n \"typescript\": \"^5.3.0\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n }\n}","import { TriggerTracer } from \"@trigger.dev/core/v3\";\nimport * as packageJson from \"../../package.json\";\n\nexport const tracer = new TriggerTracer({ name: \"@trigger.dev/sdk\", version: packageJson.version });\n","import { InitOutput } from \"@trigger.dev/core/v3\";\nimport { TaskOptions, Task, createTask } from \"./shared\";\n\n/** Creates a task that can be triggered\n * @param options - Task options\n * @example \n * \n * ```ts\n * import { task } from \"@trigger.dev/sdk/v3\";\n *\n * export const helloWorld = task({\n id: \"hello-world\",\n * run: async (payload: { url: string }) => {\n * return { hello: \"world\" };\n * },\n * });\n *\n * ```\n * \n * @returns A task that can be triggered\n */\nexport function task<TInput = void, TOutput = unknown, TInitOutput extends InitOutput = any>(\n options: TaskOptions<TInput, TOutput, TInitOutput>\n): Task<TInput, TOutput> {\n return createTask<TInput, TOutput, TInitOutput>(options);\n}\n\nexport type { TaskOptions, Task };\n","import { SemanticInternalAttributes, accessoryAttributes, runtime } from \"@trigger.dev/core/v3\";\nimport { tracer } from \"./tracer\";\n\nexport type WaitOptions =\n | {\n seconds: number;\n }\n | {\n minutes: number;\n }\n | {\n hours: number;\n }\n | {\n days: number;\n }\n | {\n weeks: number;\n }\n | {\n months: number;\n }\n | {\n years: number;\n };\n\nexport const wait = {\n for: async (options: WaitOptions) => {\n return tracer.startActiveSpan(\n `wait.for()`,\n async (span) => {\n const start = Date.now();\n const durationInMs = calculateDurationInMs(options);\n\n await runtime.waitForDuration(durationInMs);\n },\n {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"wait\",\n ...accessoryAttributes({\n items: [\n {\n text: nameForWaitOptions(options),\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n }),\n },\n }\n );\n },\n until: async (options: { date: Date; throwIfInThePast?: boolean }) => {\n return tracer.startActiveSpan(\n `wait.until()`,\n async (span) => {\n const start = Date.now();\n\n if (options.throwIfInThePast && options.date < new Date()) {\n throw new Error(\"Date is in the past\");\n }\n\n const durationInMs = options.date.getTime() - start;\n\n await runtime.waitForDuration(durationInMs);\n },\n {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"wait\",\n ...accessoryAttributes({\n items: [\n {\n text: options.date.toISOString(),\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n }),\n },\n }\n );\n },\n};\n\nfunction nameForWaitOptions(options: WaitOptions): string {\n if (\"seconds\" in options) {\n return options.seconds === 1 ? `1 second` : `${options.seconds} seconds`;\n }\n\n if (\"minutes\" in options) {\n return options.minutes === 1 ? `1 minute` : `${options.minutes} minutes`;\n }\n\n if (\"hours\" in options) {\n return options.hours === 1 ? `1 hour` : `${options.hours} hours`;\n }\n\n if (\"days\" in options) {\n return options.days === 1 ? `1 day` : `${options.days} days`;\n }\n\n if (\"weeks\" in options) {\n return options.weeks === 1 ? `1 week` : `${options.weeks} weeks`;\n }\n\n if (\"months\" in options) {\n return options.months === 1 ? `1 month` : `${options.months} months`;\n }\n\n if (\"years\" in options) {\n return options.years === 1 ? `1 year` : `${options.years} years`;\n }\n\n return \"NaN\";\n}\n\nfunction calculateDurationInMs(options: WaitOptions): number {\n if (\"seconds\" in options) {\n return options.seconds * 1000;\n }\n\n if (\"minutes\" in options) {\n return options.minutes * 1000 * 60;\n }\n\n if (\"hours\" in options) {\n return options.hours * 1000 * 60 * 60;\n }\n\n if (\"days\" in options) {\n return options.days * 1000 * 60 * 60 * 24;\n }\n\n if (\"weeks\" in options) {\n return options.weeks * 1000 * 60 * 60 * 24 * 7;\n }\n\n if (\"months\" in options) {\n return options.months * 1000 * 60 * 60 * 24 * 30;\n }\n\n if (\"years\" in options) {\n return options.years * 1000 * 60 * 60 * 24 * 365;\n }\n\n throw new Error(\"Invalid options\");\n}\n\ntype RequestOptions = {\n to: (url: string) => Promise<void>;\n timeout: WaitOptions;\n};\n","import { SemanticInternalAttributes } from \"@trigger.dev/core/v3\";\nimport { tracer } from \"./tracer\";\n\nexport type CacheMetadata = {\n createdTime: number;\n ttl?: number | null;\n};\n\nexport type CacheEntry<Value = unknown> = {\n metadata: CacheMetadata;\n value: Value;\n};\n\nexport type Eventually<Value> = Value | null | undefined | Promise<Value | null | undefined>;\n\nexport type CacheStore<Value = any> = {\n name?: string;\n get: (key: string) => Eventually<CacheEntry<Value>>;\n set: (key: string, value: CacheEntry<Value>) => unknown | Promise<unknown>;\n delete: (key: string) => unknown | Promise<unknown>;\n};\n\nexport type CacheFunction = <Value>(\n cacheKey: string,\n fn: () => Promise<Value> | Value\n) => Promise<Value> | Value;\n\nexport class InMemoryCache<Value = any> {\n private _cache: Map<string, CacheEntry<Value>> = new Map();\n\n get(key: string): Eventually<CacheEntry<Value>> {\n return this._cache.get(key);\n }\n\n set(key: string, value: CacheEntry<Value>): unknown {\n this._cache.set(key, value);\n\n return undefined;\n }\n\n delete(key: string): unknown {\n this._cache.delete(key);\n\n return undefined;\n }\n}\n\n/**\n * Create a cache function that uses the provided store to cache values. Using InMemoryCache is safe because each task run is isolated.\n * @param store\n * @returns\n */\nexport function createCache(store: CacheStore): CacheFunction {\n return function cache<Value>(\n cacheKey: string,\n fn: () => Promise<Value> | Value\n ): Promise<Value> | Value {\n return tracer.startActiveSpan(\"cache\", async (span) => {\n span.setAttribute(\"cache.key\", cacheKey);\n span.setAttribute(SemanticInternalAttributes.STYLE_ICON, \"device-sd-card\");\n\n const cacheEntry = await store.get(cacheKey);\n\n if (cacheEntry) {\n span.updateName(`cache.hit ${cacheKey}`);\n\n return cacheEntry.value;\n }\n\n span.updateName(`cache.miss ${cacheKey}`);\n\n const value = await tracer.startActiveSpan(\n \"cache.getFreshValue\",\n async (span) => {\n return await fn();\n },\n {\n attributes: {\n \"cache.key\": cacheKey,\n [SemanticInternalAttributes.STYLE_ICON]: \"device-sd-card\",\n },\n }\n );\n\n await tracer.startActiveSpan(\n \"cache.set\",\n async (span) => {\n await store.set(cacheKey, {\n value,\n metadata: {\n createdTime: Date.now(),\n },\n });\n },\n {\n attributes: {\n \"cache.key\": cacheKey,\n [SemanticInternalAttributes.STYLE_ICON]: \"device-sd-card\",\n },\n }\n );\n\n return value;\n });\n };\n}\n","import { Attributes, Span, SpanStatusCode, context, trace } from \"@opentelemetry/api\";\nimport {\n SEMATTRS_HTTP_HOST,\n SEMATTRS_HTTP_METHOD,\n SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,\n SEMATTRS_HTTP_SCHEME,\n SEMATTRS_HTTP_STATUS_CODE,\n SEMATTRS_HTTP_URL,\n} from \"@opentelemetry/semantic-conventions\";\nimport {\n FetchRetryByStatusOptions,\n FetchRetryOptions,\n FetchRetryStrategy,\n RetryOptions,\n SemanticInternalAttributes,\n accessoryAttributes,\n calculateNextRetryDelay,\n calculateResetAt,\n defaultRetryOptions,\n eventFilterMatches,\n flattenAttributes,\n runtime,\n} from \"@trigger.dev/core/v3\";\nimport { defaultFetchRetryOptions } from \"@trigger.dev/core/v3\";\nimport type { HttpHandler } from \"msw\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { tracer } from \"./tracer\";\n\nexport type { RetryOptions };\n\nfunction onThrow<T>(\n fn: (options: { attempt: number; maxAttempts: number }) => Promise<T>,\n options: RetryOptions\n): Promise<T> {\n const opts = {\n ...defaultRetryOptions,\n ...options,\n };\n\n return tracer.startActiveSpan(\n `retry.onThrow()`,\n async (span) => {\n let attempt = 1;\n\n while (attempt <= opts.maxAttempts) {\n const innerSpan = tracer.startSpan(\"retry.fn()\", {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"function\",\n ...accessoryAttributes({\n items: [\n {\n text: `${attempt}/${opts.maxAttempts}`,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n }),\n },\n });\n\n const contextWithSpanSet = trace.setSpan(context.active(), innerSpan);\n\n try {\n const result = await context.with(contextWithSpanSet, async () => {\n return fn({ attempt, maxAttempts: opts.maxAttempts });\n });\n\n innerSpan.end();\n\n return result;\n } catch (e) {\n if (e instanceof Error || typeof e === \"string\") {\n innerSpan.recordException(e);\n } else {\n innerSpan.recordException(String(e));\n }\n\n innerSpan.setStatus({ code: SpanStatusCode.ERROR });\n\n const nextRetryDelay = calculateNextRetryDelay(opts, attempt);\n\n if (!nextRetryDelay) {\n innerSpan.end();\n\n throw e;\n }\n\n innerSpan.setAttribute(\n SemanticInternalAttributes.RETRY_AT,\n new Date(Date.now() + nextRetryDelay).toISOString()\n );\n innerSpan.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);\n innerSpan.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);\n innerSpan.end();\n\n await runtime.waitForDuration(nextRetryDelay);\n } finally {\n attempt++;\n }\n }\n\n throw new Error(\"Max attempts reached\");\n },\n {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"arrow-capsule\",\n },\n }\n );\n}\n\nexport interface RetryFetchRequestInit extends RequestInit {\n retry?: FetchRetryOptions;\n timeoutInMs?: number;\n}\n\nconst normalizeUrlFromInput = (input: RequestInfo | URL | string): URL => {\n if (typeof input === \"string\") {\n return new URL(input);\n }\n\n if (input instanceof URL) {\n return input;\n }\n\n return new URL(input.url);\n};\n\nconst normalizeHttpMethod = (input: RequestInfo | URL | string, init?: RequestInit): string => {\n if (typeof input === \"string\" || input instanceof URL) {\n return (init?.method || \"GET\").toUpperCase();\n }\n\n return (input.method ?? init?.method ?? \"GET\").toUpperCase();\n};\n\nconst fetchHttpHandlerStorage = new AsyncLocalStorage<Array<HttpHandler>>();\n\nconst fetchWithInterceptors = async (\n input: RequestInfo | URL,\n init?: RequestInit\n): Promise<Response> => {\n const handlers = fetchHttpHandlerStorage.getStore();\n\n if (handlers) {\n try {\n const { getResponse } = await import(\"msw\");\n\n const request = new Request(input, init);\n\n const response = await getResponse(handlers, request);\n\n if (response) {\n return response;\n }\n } catch (e) {\n // Do nothing\n return fetch(input, init);\n }\n }\n\n return fetch(input, init);\n};\n\nclass FetchErrorWithSpan extends Error {\n constructor(\n public readonly originalError: unknown,\n public readonly span: Span\n ) {\n super(\"Fetch error\");\n }\n}\n\nconst MAX_ATTEMPTS = 10;\n\nasync function retryFetch(\n input: RequestInfo | URL,\n init?: RetryFetchRequestInit | undefined\n): Promise<Response> {\n return tracer.startActiveSpan(\n \"retry.fetch()\",\n async (span) => {\n let attempt = 1;\n\n while (true) {\n try {\n const abortController = new AbortController();\n\n const timeoutId = init?.timeoutInMs\n ? setTimeout(\n () => {\n abortController.abort();\n },\n init?.timeoutInMs\n )\n : undefined;\n\n init?.signal?.addEventListener(\"abort\", () => {\n abortController.abort();\n });\n\n const [response, span] = await doFetchRequest(\n input,\n { ...(init ?? {}), signal: abortController.signal },\n attempt\n );\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n if (response.ok) {\n span.setAttributes(createFetchResponseAttributes(response));\n\n span.end();\n\n return response;\n }\n\n const nextRetry = await calculateRetryDelayForResponse(\n resolveDefaults(init?.retry, \"byStatus\", defaultFetchRetryOptions.byStatus),\n response,\n attempt\n );\n\n if (!nextRetry) {\n span.setAttributes(createFetchResponseAttributes(response));\n\n span.end();\n\n return response;\n }\n\n if (attempt >= MAX_ATTEMPTS) {\n span.setAttributes(createFetchResponseAttributes(response));\n\n span.end();\n\n return response;\n }\n\n if (nextRetry.type === \"delay\") {\n span.setAttribute(\n SemanticInternalAttributes.RETRY_AT,\n new Date(Date.now() + nextRetry.value).toISOString()\n );\n span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);\n span.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetry.value}ms`);\n\n span.end();\n\n await runtime.waitForDuration(nextRetry.value);\n } else {\n const now = Date.now();\n const nextRetryDate = new Date(nextRetry.value);\n const isInFuture = nextRetryDate.getTime() > now;\n\n span.setAttribute(\n SemanticInternalAttributes.RETRY_AT,\n new Date(nextRetry.value).toISOString()\n );\n span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);\n\n if (isInFuture) {\n span.setAttribute(\n SemanticInternalAttributes.RETRY_DELAY,\n `${nextRetry.value - now}ms`\n );\n }\n\n span.end();\n\n await runtime.waitUntil(new Date(nextRetry.value));\n }\n } catch (e) {\n if (e instanceof FetchErrorWithSpan && e.originalError instanceof Error) {\n if (e.originalError.name === \"AbortError\") {\n const nextRetryDelay = calculateNextRetryDelay(\n resolveDefaults(init?.retry, \"timeout\", defaultFetchRetryOptions.timeout),\n attempt\n );\n\n if (!nextRetryDelay) {\n e.span.end();\n throw e;\n }\n\n if (attempt >= MAX_ATTEMPTS) {\n e.span.end();\n throw e;\n }\n\n e.span.setAttribute(\n SemanticInternalAttributes.RETRY_AT,\n new Date(Date.now() + nextRetryDelay).toISOString()\n );\n e.span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);\n e.span.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);\n\n e.span.end();\n\n await runtime.waitForDuration(nextRetryDelay);\n\n continue; // Move to the next attempt\n } else if (\n e.originalError.name === \"TypeError\" &&\n \"cause\" in e.originalError &&\n e.originalError.cause instanceof Error\n ) {\n const nextRetryDelay = calculateNextRetryDelay(\n resolveDefaults(\n init?.retry,\n \"connectionError\",\n defaultFetchRetryOptions.connectionError\n ),\n attempt\n );\n\n if (!nextRetryDelay) {\n e.span.end();\n throw e;\n }\n\n if (attempt >= MAX_ATTEMPTS) {\n e.span.end();\n throw e;\n }\n\n e.span.setAttribute(\n SemanticInternalAttributes.RETRY_AT,\n new Date(Date.now() + nextRetryDelay).toISOString()\n );\n e.span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);\n e.span.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);\n\n e.span.end();\n\n await runtime.waitForDuration(nextRetryDelay);\n\n continue; // Move to the next attempt\n }\n }\n\n if (e instanceof FetchErrorWithSpan) {\n e.span.end();\n }\n\n throw e;\n } finally {\n attempt++;\n }\n }\n },\n {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"arrow-capsule\",\n ...createFetchAttributes(input, init),\n ...createFetchRetryOptionsAttributes(init?.retry),\n },\n }\n );\n}\n\nconst doFetchRequest = async (\n input: RequestInfo | URL | string,\n init?: RequestInit,\n attemptCount: number = 0\n): Promise<[Response, Span]> => {\n const httpMethod = normalizeHttpMethod(input, init);\n\n const span = tracer.startSpan(`HTTP ${httpMethod}`, {\n attributes: {\n [SemanticInternalAttributes.STYLE_ICON]: \"world\",\n ...(attemptCount > 1 ? { [\"http.request.resend_count\"]: attemptCount - 1 } : {}),\n ...createFetchAttributes(input, init),\n },\n });\n\n try {\n const response = await fetchWithInterceptors(input, {\n ...init,\n headers: {\n ...init?.headers,\n \"x-retry-count\": attemptCount.toString(),\n },\n });\n\n span.setAttributes(createFetchResponseAttributes(response));\n\n if (!response.ok) {\n span.recordException(`${response.status}: ${response.statusText}`);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `${response.status}: ${response.statusText}`,\n });\n }\n\n return [response, span];\n } catch (e) {\n if (typeof e === \"string\" || e instanceof Error) {\n span.recordException(e);\n }\n\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.setAttribute(SEMATTRS_HTTP_STATUS_CODE, 0);\n span.setAttribute(\"http.status_text\", \"This operation was aborted.\");\n\n throw new FetchErrorWithSpan(e, span);\n }\n};\n\nconst calculateRetryDelayForResponse = async (\n retry: FetchRetryByStatusOptions | undefined,\n response: Response,\n attemptCount: number\n): Promise<{ type: \"delay\"; value: number } | { type: \"timestamp\"; value: number } | undefined> => {\n if (!retry) {\n return;\n }\n\n const strategy = await getRetryStrategyForResponse(response, retry);\n\n if (!strategy) {\n return;\n }\n\n switch (strategy.strategy) {\n case \"backoff\": {\n const value = calculateNextRetryDelay({ ...defaultRetryOptions, ...strategy }, attemptCount);\n\n if (value) {\n return { type: \"delay\", value };\n }\n\n break;\n }\n case \"headers\": {\n const resetAt = response.headers.get(strategy.resetHeader);\n\n if (typeof resetAt === \"string\") {\n const resetTimestamp = calculateResetAt(\n resetAt,\n strategy.resetFormat ?? \"unix_timestamp_in_ms\"\n );\n\n if (resetTimestamp) {\n return { type: \"timestamp\", value: resetTimestamp };\n }\n }\n\n break;\n }\n }\n};\n\nconst getRetryStrategyForResponse = async (\n response: Response,\n retry: FetchRetryByStatusOptions\n): Promise<FetchRetryStrategy | undefined> => {\n const statusCodes = Object.keys(retry);\n const clonedResponse = response.clone();\n\n for (let i = 0; i < statusCodes.length; i++) {\n const statusRange = statusCodes[i];\n const strategy = retry[statusRange];\n\n if (isStatusCodeInRange(response.status, statusRange)) {\n if (strategy.bodyFilter) {\n const body = safeJsonParse(await clonedResponse.text());\n\n if (!body) {\n continue;\n }\n\n if (eventFilterMatches(body, strategy.bodyFilter)) {\n return strategy;\n } else {\n continue;\n }\n }\n\n return strategy;\n }\n }\n};\n\n/**\n * Checks if a given status code falls within a given range.\n * The range can be a single status code (e.g. \"200\"),\n * a range of status codes (e.g. \"500-599\"),\n * a range of status codes with a wildcard (e.g. \"4xx\" for any 4xx status code),\n * or a list of status codes separated by commas (e.g. \"401,403,404,409-412,5xx\").\n * Returns `true` if the status code falls within the range, and `false` otherwise.\n */\nconst isStatusCodeInRange = (statusCode: number, statusRange: string): boolean => {\n if (statusRange === \"all\") {\n return true;\n }\n\n if (statusRange.includes(\",\")) {\n const statusCodes = statusRange.split(\",\").map((s) => s.trim());\n\n return statusCodes.some((s) => isStatusCodeInRange(statusCode, s));\n }\n\n const [start, end] = statusRange.split(\"-\");\n\n if (end) {\n return statusCode >= parseInt(start, 10) && statusCode <= parseInt(end, 10);\n }\n\n if (start.endsWith(\"xx\")) {\n const prefix = start.slice(0, -2);\n const statusCodePrefix = Math.floor(statusCode / 100).toString();\n return statusCodePrefix === prefix;\n }\n\n const statusCodeString = statusCode.toString();\n const rangePrefix = start.slice(0, -1);\n\n if (start.endsWith(\"x\") && statusCodeString.startsWith(rangePrefix)) {\n return true;\n }\n\n return statusCode === parseInt(start, 10);\n};\n\nconst createAttributesFromHeaders = (headers: Headers): Attributes => {\n const attributes: Attributes = {};\n\n const normalizedHeaderKey = (key: string) => {\n return key.toLowerCase();\n };\n\n headers.forEach((value, key) => {\n attributes[`http.response.header.${normalizedHeaderKey(key)}`] = value;\n });\n\n return attributes;\n};\n\nconst safeJsonParse = (json: string): unknown => {\n try {\n return JSON.parse(json);\n } catch (e) {\n return null;\n }\n};\n\nconst interceptFetch = (...handlers: Array<HttpHandler>) => {\n return {\n run: async <T>(fn: (...args: any[]) => Promise<T>): Promise<T> => {\n const current = fetchHttpHandlerStorage.getStore();\n\n if (current) {\n current.push(...handlers);\n return fn();\n } else {\n return fetchHttpHandlerStorage.run(handlers, fn);\n }\n },\n };\n};\n\n// This function will resolve the defaults of a property within an options object.\n// If the options object is undefined, it will return the defaults for that property (passed in as the 3rd arg).\n// if the options object is defined, and the property exists, then it will return the defaults if the value of the property is undefined or null\nconst resolveDefaults = <\n TObject extends Record<string, unknown>,\n K extends keyof TObject,\n TValue extends TObject[K],\n>(\n obj: TObject | undefined,\n key: K,\n defaults: TValue\n): TValue => {\n if (!obj) {\n return defaults;\n }\n\n if (obj[key] === undefined || obj[key] === null) {\n return defaults;\n }\n\n return obj[key] as TValue;\n};\n\nconst createFetchAttributes = (\n input: RequestInfo | URL,\n init?: RetryFetchRequestInit | undefined\n): Attributes => {\n const url = normalizeUrlFromInput(input);\n const httpMethod = normalizeHttpMethod(input, init);\n\n return {\n [SEMATTRS_HTTP_METHOD]: httpMethod,\n [SEMATTRS_HTTP_URL]: url.href,\n [SEMATTRS_HTTP_HOST]: url.hostname,\n [\"server.host\"]: url.hostname,\n [\"server.port\"]: url.port,\n [SEMATTRS_HTTP_SCHEME]: url.protocol.replace(\":\", \"\"),\n ...accessoryAttributes({\n items: [\n {\n text: url.hostname,\n variant: \"normal\",\n },\n ],\n style: \"codepath\",\n }),\n };\n};\n\nconst createFetchResponseAttributes = (response: Response): Attributes => {\n return {\n [SEMATTRS_HTTP_STATUS_CODE]: response.status,\n \"http.status_text\": response.statusText,\n [SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH]: response.headers.get(\"content-length\") || \"0\",\n ...createAttributesFromHeaders(response.headers),\n };\n};\n\nconst createFetchRetryOptionsAttributes = (retry?: FetchRetryOptions): Attributes => {\n const byStatus = resolveDefaults(retry, \"byStatus\", defaultFetchRetryOptions.byStatus);\n const connectionError = resolveDefaults(\n retry,\n \"connectionError\",\n defaultFetchRetryOptions.connectionError\n );\n const timeout = resolveDefaults(retry, \"timeout\", defaultFetchRetryOptions.timeout);\n\n return {\n ...flattenAttributes(byStatus, \"retry.byStatus\"),\n ...flattenAttributes(connectionError, \"retry.connectionError\"),\n ...flattenAttributes(timeout, \"retry.timeout\"),\n };\n};\n\nexport const retry = {\n onThrow,\n fetch: retryFetch,\n interceptFetch,\n};\n","export * from \"./tasks\";\nexport * from \"./config\";\nexport * from \"./wait\";\nexport * from \"./cache\";\nexport { retry, type RetryOptions } from \"./retry\";\nexport { queue } from \"./shared\";\n\nimport type { Context } from \"./shared\";\nexport type { Context };\n\nexport {\n logger,\n type LogLevel,\n APIError,\n BadRequestError,\n AuthenticationError,\n PermissionDeniedError,\n NotFoundError,\n ConflictError,\n UnprocessableEntityError,\n RateLimitError,\n InternalServerError,\n} from \"@trigger.dev/core/v3\";\n\nexport { runs } from \"./management\";\nexport * as schedules from \"./schedules\";\n","import { CanceledRunResponse, ReplayRunResponse, apiClientManager } from \"@trigger.dev/core/v3\";\nimport { apiClientMissingError } from \"./shared\";\n\nexport const runs = {\n replay: replayRun,\n cancel: cancelRun,\n};\n\nasync function replayRun(runId: string): Promise<ReplayRunResponse> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return await apiClient.replayRun(runId);\n}\n\nasync function cancelRun(runId: string): Promise<CanceledRunResponse> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return await apiClient.cancelRun(runId);\n}\n","import {\n DeletedScheduleObject,\n InitOutput,\n ListSchedulesResult,\n ScheduleObject,\n apiClientManager,\n taskCatalog,\n} from \"@trigger.dev/core/v3\";\nimport { Task, TaskOptions, apiClientMissingError, createTask } from \"../shared\";\nimport * as SchedulesAPI from \"./api\";\n\nexport function task<TOutput, TInitOutput extends InitOutput>(\n params: TaskOptions<SchedulesAPI.ScheduledTaskPayload, TOutput, TInitOutput>\n): Task<SchedulesAPI.ScheduledTaskPayload, TOutput> {\n const task = createTask(params);\n\n taskCatalog.updateTaskMetadata(task.id, {\n triggerSource: \"schedule\",\n });\n\n return task;\n}\n\n/**\n * Creates a new schedule\n * @param options\n * @param options.task - The identifier of the task to be scheduled (Must already exist and be a scheduled task)\n * @param options.cron - The cron expression for the schedule (e.g. `0 0 * * *`)\n * @param options.externalId - An optional external identifier for the schedule\n * @param options.deduplicationKey - An optional deduplication key for the schedule\n * @returns The created schedule\n */\nexport async function create(options: SchedulesAPI.CreateScheduleOptions): Promise<ScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.createSchedule(options);\n}\n\n/**\n * Retrieves a schedule\n * @param scheduleId - The ID of the schedule to retrieve\n * @returns The retrieved schedule\n */\nexport async function retrieve(scheduleId: string): Promise<ScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.retrieveSchedule(scheduleId);\n}\n\n/**\n * Updates a schedule\n * @param scheduleId - The ID of the schedule to update\n * @param options - The updated schedule options\n * @param options.task - The identifier of the task to be scheduled (Must already exist and be a scheduled task)\n * @param options.cron - The cron expression for the schedule (e.g. `0 0 * * *`)\n * @param options.externalId - An optional external identifier for the schedule\n * @returns The updated schedule\n */\nexport async function update(\n scheduleId: string,\n options: SchedulesAPI.UpdateScheduleOptions\n): Promise<ScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.updateSchedule(scheduleId, options);\n}\n\n/**\n * Deletes a schedule\n * @param scheduleId - The ID of the schedule to delete\n */\nexport async function del(scheduleId: string): Promise<DeletedScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.deleteSchedule(scheduleId);\n}\n\n/**\n * Deactivates a schedule\n * @param scheduleId - The ID of the schedule to deactivate\n */\nexport async function deactivate(scheduleId: string): Promise<ScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.deactivateSchedule(scheduleId);\n}\n\n/**\n * Activates a schedule\n * @param scheduleId - The ID of the schedule to activate\n */\nexport async function activate(scheduleId: string): Promise<ScheduleObject> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.activateSchedule(scheduleId);\n}\n\n/**\n * Lists schedules\n * @param options - The list options\n * @param options.page - The page number\n * @param options.perPage - The number of schedules per page\n * @returns The list of schedules\n */\nexport async function list(\n options?: SchedulesAPI.ListScheduleOptions\n): Promise<ListSchedulesResult> {\n const apiClient = apiClientManager.client;\n\n if (!apiClient) {\n throw apiClientMissingError();\n }\n\n return apiClient.listSchedules(options);\n}\n"]}
|
package/dist/v3/index.mjs
CHANGED
|
@@ -17,7 +17,7 @@ var __publicField = (obj, key, value) => {
|
|
|
17
17
|
};
|
|
18
18
|
|
|
19
19
|
// package.json
|
|
20
|
-
var version = "3.0.0-beta.
|
|
20
|
+
var version = "3.0.0-beta.21";
|
|
21
21
|
var tracer = new TriggerTracer({
|
|
22
22
|
name: "@trigger.dev/sdk",
|
|
23
23
|
version
|
|
@@ -292,7 +292,10 @@ function createTask(params) {
|
|
|
292
292
|
init: params.init,
|
|
293
293
|
cleanup: params.cleanup,
|
|
294
294
|
middleware: params.middleware,
|
|
295
|
-
handleError: params.handleError
|
|
295
|
+
handleError: params.handleError,
|
|
296
|
+
onSuccess: params.onSuccess,
|
|
297
|
+
onFailure: params.onFailure,
|
|
298
|
+
onStart: params.onStart
|
|
296
299
|
}
|
|
297
300
|
});
|
|
298
301
|
return task3;
|