@trigger.dev/sdk 3.0.0-beta.7 → 3.0.0
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/commonjs/apiClient.d.ts +737 -0
- package/dist/commonjs/apiClient.js +692 -0
- package/dist/commonjs/apiClient.js.map +1 -0
- package/dist/commonjs/concurrencyLimit.d.ts +10 -0
- package/dist/commonjs/concurrencyLimit.js +17 -0
- package/dist/commonjs/concurrencyLimit.js.map +1 -0
- package/dist/commonjs/errors.d.ts +66 -0
- package/dist/commonjs/errors.js +109 -0
- package/dist/commonjs/errors.js.map +1 -0
- package/dist/commonjs/httpEndpoint.d.ts +87 -0
- package/dist/commonjs/httpEndpoint.js +130 -0
- package/dist/commonjs/httpEndpoint.js.map +1 -0
- package/dist/commonjs/index.d.ts +23 -0
- package/dist/commonjs/index.js +55 -0
- package/dist/commonjs/index.js.map +1 -0
- package/dist/commonjs/integrations.d.ts +11 -0
- package/dist/commonjs/integrations.js +3 -0
- package/dist/commonjs/integrations.js.map +1 -0
- package/dist/commonjs/io.d.ts +453 -0
- package/dist/commonjs/io.js +1165 -0
- package/dist/commonjs/io.js.map +1 -0
- package/dist/commonjs/ioWithIntegrations.d.ts +4 -0
- package/dist/commonjs/ioWithIntegrations.js +32 -0
- package/dist/commonjs/ioWithIntegrations.js.map +1 -0
- package/dist/commonjs/job.d.ts +96 -0
- package/dist/commonjs/job.js +210 -0
- package/dist/commonjs/job.js.map +1 -0
- package/dist/commonjs/package.json +3 -0
- package/dist/commonjs/retry.d.ts +20 -0
- package/dist/commonjs/retry.js +22 -0
- package/dist/commonjs/retry.js.map +1 -0
- package/dist/commonjs/runLocalStorage.d.ts +8 -0
- package/dist/commonjs/runLocalStorage.js +6 -0
- package/dist/commonjs/runLocalStorage.js.map +1 -0
- package/dist/commonjs/security.d.ts +18 -0
- package/dist/commonjs/security.js +41 -0
- package/dist/commonjs/security.js.map +1 -0
- package/dist/commonjs/status.d.ts +19 -0
- package/dist/commonjs/status.js +38 -0
- package/dist/commonjs/status.js.map +1 -0
- package/dist/commonjs/store/keyValueStore.d.ts +17 -0
- package/dist/commonjs/store/keyValueStore.js +138 -0
- package/dist/commonjs/store/keyValueStore.js.map +1 -0
- package/dist/commonjs/store/keyValueStoreClient.d.ts +19 -0
- package/dist/commonjs/store/keyValueStoreClient.js +65 -0
- package/dist/commonjs/store/keyValueStoreClient.js.map +1 -0
- package/dist/commonjs/triggerClient.d.ts +300 -0
- package/dist/commonjs/triggerClient.js +1366 -0
- package/dist/commonjs/triggerClient.js.map +1 -0
- package/dist/commonjs/triggers/dynamic.d.ts +56 -0
- package/dist/commonjs/triggers/dynamic.js +97 -0
- package/dist/commonjs/triggers/dynamic.js.map +1 -0
- package/dist/commonjs/triggers/eventTrigger.d.ts +58 -0
- package/dist/commonjs/triggers/eventTrigger.js +69 -0
- package/dist/commonjs/triggers/eventTrigger.js.map +1 -0
- package/dist/commonjs/triggers/externalSource.d.ts +148 -0
- package/dist/commonjs/triggers/externalSource.js +106 -0
- package/dist/commonjs/triggers/externalSource.js.map +1 -0
- package/dist/commonjs/triggers/invokeTrigger.d.ts +39 -0
- package/dist/commonjs/triggers/invokeTrigger.js +58 -0
- package/dist/commonjs/triggers/invokeTrigger.js.map +1 -0
- package/dist/commonjs/triggers/notifications.d.ts +111 -0
- package/dist/commonjs/triggers/notifications.js +101 -0
- package/dist/commonjs/triggers/notifications.js.map +1 -0
- package/dist/commonjs/triggers/scheduled.d.ts +145 -0
- package/dist/commonjs/triggers/scheduled.js +208 -0
- package/dist/commonjs/triggers/scheduled.js.map +1 -0
- package/dist/commonjs/triggers/webhook.d.ts +143 -0
- package/dist/commonjs/triggers/webhook.js +133 -0
- package/dist/commonjs/triggers/webhook.js.map +1 -0
- package/dist/commonjs/typed-emitter.d.ts +37 -0
- package/dist/commonjs/typed-emitter.js +3 -0
- package/dist/commonjs/typed-emitter.js.map +1 -0
- package/dist/commonjs/types.d.ts +204 -0
- package/dist/commonjs/types.js +23 -0
- package/dist/commonjs/types.js.map +1 -0
- package/dist/commonjs/utils/formatSchemaErrors.d.ts +3 -0
- package/dist/commonjs/utils/formatSchemaErrors.js +10 -0
- package/dist/commonjs/utils/formatSchemaErrors.js.map +1 -0
- package/dist/commonjs/utils/typedAsyncLocalStorage.d.ts +6 -0
- package/dist/commonjs/utils/typedAsyncLocalStorage.js +18 -0
- package/dist/commonjs/utils/typedAsyncLocalStorage.js.map +1 -0
- package/dist/commonjs/utils.d.ts +1 -0
- package/dist/commonjs/utils.js +11 -0
- package/dist/commonjs/utils.js.map +1 -0
- package/dist/commonjs/v3/cache.d.ts +28 -0
- package/dist/commonjs/v3/cache.js +63 -0
- package/dist/commonjs/v3/cache.js.map +1 -0
- package/dist/commonjs/v3/config.d.ts +4 -0
- package/dist/commonjs/v3/config.js +7 -0
- package/dist/commonjs/v3/config.js.map +1 -0
- package/dist/commonjs/v3/envvars.d.ts +14 -0
- package/dist/commonjs/v3/envvars.js +246 -0
- package/dist/commonjs/v3/envvars.js.map +1 -0
- package/dist/commonjs/v3/idempotencyKeys.d.ts +49 -0
- package/dist/commonjs/v3/idempotencyKeys.js +76 -0
- package/dist/commonjs/v3/idempotencyKeys.js.map +1 -0
- package/dist/commonjs/v3/index.d.ts +36 -0
- package/dist/commonjs/v3/index.js +79 -0
- package/dist/commonjs/v3/index.js.map +1 -0
- package/dist/commonjs/v3/retry.d.ts +15 -0
- package/dist/commonjs/v3/retry.js +411 -0
- package/dist/commonjs/v3/retry.js.map +1 -0
- package/dist/commonjs/v3/runs.d.ts +345 -0
- package/dist/commonjs/v3/runs.js +195 -0
- package/dist/commonjs/v3/runs.js.map +1 -0
- package/dist/commonjs/v3/schedules/api.d.ts +1 -0
- package/dist/commonjs/v3/schedules/api.js +3 -0
- package/dist/commonjs/v3/schedules/api.js.map +1 -0
- package/dist/commonjs/v3/schedules/index.d.ts +87 -0
- package/dist/commonjs/v3/schedules/index.js +250 -0
- package/dist/commonjs/v3/schedules/index.js.map +1 -0
- package/dist/commonjs/v3/shared.d.ts +443 -0
- package/dist/commonjs/v3/shared.js +547 -0
- package/dist/commonjs/v3/shared.js.map +1 -0
- package/dist/commonjs/v3/tags.d.ts +6 -0
- package/dist/commonjs/v3/tags.js +50 -0
- package/dist/commonjs/v3/tags.js.map +1 -0
- package/dist/commonjs/v3/tasks.d.ts +31 -0
- package/dist/commonjs/v3/tasks.js +35 -0
- package/dist/commonjs/v3/tasks.js.map +1 -0
- package/dist/commonjs/v3/tracer.d.ts +2 -0
- package/dist/commonjs/v3/tracer.js +7 -0
- package/dist/commonjs/v3/tracer.js.map +1 -0
- package/dist/commonjs/v3/usage.d.ts +77 -0
- package/dist/commonjs/v3/usage.js +115 -0
- package/dist/commonjs/v3/usage.js.map +1 -0
- package/dist/commonjs/v3/wait.d.ts +22 -0
- package/dist/commonjs/v3/wait.js +99 -0
- package/dist/commonjs/v3/wait.js.map +1 -0
- package/dist/commonjs/version.d.ts +1 -0
- package/dist/commonjs/version.js +5 -0
- package/dist/commonjs/version.js.map +1 -0
- package/dist/esm/apiClient.d.ts +737 -0
- package/dist/esm/apiClient.js +687 -0
- package/dist/esm/apiClient.js.map +1 -0
- package/dist/esm/concurrencyLimit.d.ts +10 -0
- package/dist/esm/concurrencyLimit.js +13 -0
- package/dist/esm/concurrencyLimit.js.map +1 -0
- package/dist/esm/errors.d.ts +66 -0
- package/dist/esm/errors.js +95 -0
- package/dist/esm/errors.js.map +1 -0
- package/dist/esm/httpEndpoint.d.ts +87 -0
- package/dist/esm/httpEndpoint.js +125 -0
- package/dist/esm/httpEndpoint.js.map +1 -0
- package/dist/esm/index.d.ts +23 -0
- package/dist/esm/index.js +35 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/integrations.d.ts +11 -0
- package/dist/esm/integrations.js +2 -0
- package/dist/esm/integrations.js.map +1 -0
- package/dist/esm/io.d.ts +453 -0
- package/dist/esm/io.js +1159 -0
- package/dist/esm/io.js.map +1 -0
- package/dist/esm/ioWithIntegrations.d.ts +4 -0
- package/dist/esm/ioWithIntegrations.js +29 -0
- package/dist/esm/ioWithIntegrations.js.map +1 -0
- package/dist/esm/job.d.ts +96 -0
- package/dist/esm/job.js +206 -0
- package/dist/esm/job.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/retry.d.ts +20 -0
- package/dist/esm/retry.js +19 -0
- package/dist/esm/retry.js.map +1 -0
- package/dist/esm/runLocalStorage.d.ts +8 -0
- package/dist/esm/runLocalStorage.js +3 -0
- package/dist/esm/runLocalStorage.js.map +1 -0
- package/dist/esm/security.d.ts +18 -0
- package/dist/esm/security.js +34 -0
- package/dist/esm/security.js.map +1 -0
- package/dist/esm/status.d.ts +19 -0
- package/dist/esm/status.js +34 -0
- package/dist/esm/status.js.map +1 -0
- package/dist/esm/store/keyValueStore.d.ts +17 -0
- package/dist/esm/store/keyValueStore.js +134 -0
- package/dist/esm/store/keyValueStore.js.map +1 -0
- package/dist/esm/store/keyValueStoreClient.d.ts +19 -0
- package/dist/esm/store/keyValueStoreClient.js +61 -0
- package/dist/esm/store/keyValueStoreClient.js.map +1 -0
- package/dist/esm/triggerClient.d.ts +300 -0
- package/dist/esm/triggerClient.js +1359 -0
- package/dist/esm/triggerClient.js.map +1 -0
- package/dist/esm/triggers/dynamic.d.ts +56 -0
- package/dist/esm/triggers/dynamic.js +93 -0
- package/dist/esm/triggers/dynamic.js.map +1 -0
- package/dist/esm/triggers/eventTrigger.d.ts +58 -0
- package/dist/esm/triggers/eventTrigger.js +64 -0
- package/dist/esm/triggers/eventTrigger.js.map +1 -0
- package/dist/esm/triggers/externalSource.d.ts +148 -0
- package/dist/esm/triggers/externalSource.js +100 -0
- package/dist/esm/triggers/externalSource.js.map +1 -0
- package/dist/esm/triggers/invokeTrigger.d.ts +39 -0
- package/dist/esm/triggers/invokeTrigger.js +53 -0
- package/dist/esm/triggers/invokeTrigger.js.map +1 -0
- package/dist/esm/triggers/notifications.d.ts +111 -0
- package/dist/esm/triggers/notifications.js +94 -0
- package/dist/esm/triggers/notifications.js.map +1 -0
- package/dist/esm/triggers/scheduled.d.ts +145 -0
- package/dist/esm/triggers/scheduled.js +197 -0
- package/dist/esm/triggers/scheduled.js.map +1 -0
- package/dist/esm/triggers/webhook.d.ts +143 -0
- package/dist/esm/triggers/webhook.js +128 -0
- package/dist/esm/triggers/webhook.js.map +1 -0
- package/dist/esm/typed-emitter.d.ts +37 -0
- package/dist/esm/typed-emitter.js +2 -0
- package/dist/esm/typed-emitter.js.map +1 -0
- package/dist/esm/types.d.ts +204 -0
- package/dist/esm/types.js +19 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/utils/formatSchemaErrors.d.ts +3 -0
- package/dist/esm/utils/formatSchemaErrors.js +7 -0
- package/dist/esm/utils/formatSchemaErrors.js.map +1 -0
- package/dist/esm/utils/typedAsyncLocalStorage.d.ts +6 -0
- package/dist/esm/utils/typedAsyncLocalStorage.js +14 -0
- package/dist/esm/utils/typedAsyncLocalStorage.js.map +1 -0
- package/dist/esm/utils.d.ts +1 -0
- package/dist/esm/utils.js +8 -0
- package/dist/esm/utils.js.map +1 -0
- package/dist/esm/v3/cache.d.ts +28 -0
- package/dist/esm/v3/cache.js +58 -0
- package/dist/esm/v3/cache.js.map +1 -0
- package/dist/esm/v3/config.d.ts +4 -0
- package/dist/esm/v3/config.js +4 -0
- package/dist/esm/v3/config.js.map +1 -0
- package/dist/esm/v3/envvars.d.ts +14 -0
- package/dist/esm/v3/envvars.js +238 -0
- package/dist/esm/v3/envvars.js.map +1 -0
- package/dist/esm/v3/idempotencyKeys.d.ts +49 -0
- package/dist/esm/v3/idempotencyKeys.js +72 -0
- package/dist/esm/v3/idempotencyKeys.js.map +1 -0
- package/dist/esm/v3/index.d.ts +36 -0
- package/dist/esm/v3/index.js +35 -0
- package/dist/esm/v3/index.js.map +1 -0
- package/dist/esm/v3/retry.d.ts +15 -0
- package/dist/esm/v3/retry.js +408 -0
- package/dist/esm/v3/retry.js.map +1 -0
- package/dist/esm/v3/runs.d.ts +345 -0
- package/dist/esm/v3/runs.js +192 -0
- package/dist/esm/v3/runs.js.map +1 -0
- package/dist/esm/v3/schedules/api.d.ts +1 -0
- package/dist/esm/v3/schedules/api.js +2 -0
- package/dist/esm/v3/schedules/api.js.map +1 -0
- package/dist/esm/v3/schedules/index.d.ts +87 -0
- package/dist/esm/v3/schedules/index.js +239 -0
- package/dist/esm/v3/schedules/index.js.map +1 -0
- package/dist/esm/v3/shared.d.ts +443 -0
- package/dist/esm/v3/shared.js +534 -0
- package/dist/esm/v3/shared.js.map +1 -0
- package/dist/esm/v3/tags.d.ts +6 -0
- package/dist/esm/v3/tags.js +47 -0
- package/dist/esm/v3/tags.js.map +1 -0
- package/dist/esm/v3/tasks.d.ts +31 -0
- package/dist/esm/v3/tasks.js +31 -0
- package/dist/esm/v3/tasks.js.map +1 -0
- package/dist/esm/v3/tracer.d.ts +2 -0
- package/dist/esm/v3/tracer.js +4 -0
- package/dist/esm/v3/tracer.js.map +1 -0
- package/dist/esm/v3/usage.d.ts +77 -0
- package/dist/esm/v3/usage.js +112 -0
- package/dist/esm/v3/usage.js.map +1 -0
- package/dist/esm/v3/wait.d.ts +22 -0
- package/dist/esm/v3/wait.js +96 -0
- package/dist/esm/v3/wait.js.map +1 -0
- package/dist/esm/version.d.ts +1 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/version.js.map +1 -0
- package/package.json +62 -47
- package/dist/index.d.mts +0 -2704
- package/dist/index.d.ts +0 -2704
- package/dist/index.js +0 -4886
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -4847
- package/dist/index.mjs.map +0 -1
- package/dist/v3/index.d.mts +0 -261
- package/dist/v3/index.d.ts +0 -261
- package/dist/v3/index.js +0 -921
- package/dist/v3/index.js.map +0 -1
- package/dist/v3/index.mjs +0 -911
- package/dist/v3/index.mjs.map +0 -1
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/typedAsyncLocalStorage.ts","../src/runLocalStorage.ts","../src/utils.ts","../src/job.ts","../src/triggerClient.ts","../package.json","../src/apiClient.ts","../src/io.ts","../src/errors.ts","../src/retry.ts","../src/status.ts","../src/types.ts","../src/store/keyValueStore.ts","../src/store/keyValueStoreClient.ts","../src/concurrencyLimit.ts","../src/httpEndpoint.ts","../src/utils/formatSchemaErrors.ts","../src/ioWithIntegrations.ts","../src/triggers/dynamic.ts","../src/triggers/eventTrigger.ts","../src/triggers/scheduled.ts","../src/triggers/externalSource.ts","../src/triggers/notifications.ts","../src/triggers/invokeTrigger.ts","../src/triggers/webhook.ts","../src/security.ts","../src/index.ts"],"names":["AsyncLocalStorage","TypedAsyncLocalStorage","constructor","storage","runWith","context","fn","run","getStore","runLocalStorage","slugifyId","input","replaceSpacesWithDash","toLowerCase","replace","removeNonUrlSafeChars","Job","options","attachToClient","client","attach","id","enabled","name","trigger","version","logLevel","integrations","Object","keys","reduce","acc","key","integration","metadata","authSource","toJSON","internal","__internal","event","startPosition","preprocessRuns","concurrencyLimit","limit","undefined","invoke","param1","param2","param3","triggerClient","Error","runStore","io","runTask","task","result","invokeJob","idempotencyKey","outputProperties","label","text","url","ctx","organization","slug","project","params","properties","environment","invokeAndWaitForCompletion","cacheKey","payload","timeoutInSeconds","parsedPayload","parseInvokePayload","callbackUrl","callback","batchInvokeAndWaitForCompletion","batch","length","results","parallel","item","index","String","match","API_VERSIONS","ErrorWithStackSchema","HttpEndpointRequestHeadersSchema","HttpSourceRequestHeadersSchema","InitializeTriggerBodySchema","PreprocessRunBodySchema","REGISTER_SOURCE_EVENT_V2","REGISTER_WEBHOOK","RegisterSourceEventSchemaV2","RegisterWebhookPayloadSchema","RequestWithRawBodySchema","RunJobBodySchema","WebhookSourceRequestHeadersSchema","Logger","EventEmitter","env","ApiEventLogSchema","CancelRunsForEventSchema","CancelRunsForJobSchema","ConnectionAuthSchema","EphemeralEventDispatcherResponseBodySchema","GetEventSchema","GetRunSchema","GetRunStatusesSchema","GetRunsSchema","InvokeJobResponseSchema","JobRunStatusRecordSchema","KeyValueStoreResponseBodySchema","RegisterScheduleResponseBodySchema","RunTaskResponseWithCachedTasksBodySchema","ServerTaskSchema","TriggerSourceSchema","assertExhaustive","urlWithSearchParams","z","supportsFeature","BloomFilter","webcrypto","ResumeWithTaskError","ResumeWithParallelTaskError","childErrors","RetryWithTaskError","cause","retryAt","CanceledWithTaskError","YieldExecutionError","AutoYieldExecutionError","location","timeRemaining","timeElapsed","AutoYieldWithCompletedTaskExecutionError","data","output","ParsedPayloadSchemaError","schemaErrors","isTriggerError","err","ErrorWithTask","message","calculateRetryAt","retry","standardBackoff","factor","minTimeoutInMs","maxTimeoutInMs","randomize","exponentialBackoff","TriggerStatus","update","status","push","state","updateStatus","runId","icon","EventSpecificationExampleSchema","object","string","optional","any","waitForEventSchema","schema","source","timestamp","coerce","date","accountId","KeyValueStore","apiClient","type","namespace","delete","store","style","get","has","set","value","parts","join","Buffer","JSONOutputSerializer","serialize","JSON","stringify","deserialize","parse","IO","_outputSerializer","_visitedCacheKeys","Set","brb","yield","bind","_id","_jobId","jobId","_apiClient","_triggerClient","_logger","logger","_cachedTasks","Map","_jobLogger","jobLogger","_jobLogLevel","jobLogLevel","_timeOrigin","timeOrigin","_executionTimeout","executionTimeout","_envStore","_jobStore","_runStore","_stats","initialCachedTasks","lazyLoadedCachedTasks","executedTasks","cachedTaskHits","cachedTaskMisses","noopCachedTaskHits","noopCachedTaskMisses","cachedTasks","forEach","_taskStorage","_context","_yieldedExecutions","yieldedExecutions","noopTasksSet","_noopTasksBloomFilter","NOOP_TASK_SET_SIZE","_cachedTasksCursor","cachedTasksCursor","_serverVersion","serverVersion","stats","IOLogger","level","stack","satisfiesLogLevel","log","debug","info","warn","error","description","variant","noop","random","min","max","round","withinBounds","Math","Number","isInteger","rounded","wait","seconds","delayUntil","Date","now","waitForEvent","createEphemeralEventDispatcher","filter","contextFilter","parseOutput","waitForRequest","createStatus","initialStatus","backgroundFetch","requestInit","urlObject","URL","console","hostname","pathname","timeout","operation","method","durationInMs","backgroundPoll","interval","backgroundFetchResponse","sendEvent","sendEventOptionsProperties","sendEvents","events","getEvent","cancelEvent","eventId","updateSource","redact","paths","updateWebhook","registerInterval","dynamicSchedule","register","toString","unregisterInterval","unregister","registerCron","cron","unregisterCron","registerTrigger","registration","subtask1","getAuth","clientId","items","outcomes","Promise","allSettled","map","spaceOut","every","outcome","nonInternalErrors","reason","internalErrors","onError","parentId","taskId","isSubtaskNoop","generateIdempotencyKey","flat","add","cachedTask","test","runOptions","response","displayKey","LAZY_LOADED_CACHED_TASKS","body","forceYield","cursor","tasks","executeTask","completedTask","completeTask","deserializedOutput","skipRetrying","onErrorResult","parsedError","safeParse","success","innerError","failTask","attempts","includes","try","tryCallback","catchCallback","job","threshold","performance","keyMaterial","stableStringify","hash","subtle","digest","from","obj","sortKeys","Array","isArray","sortedKeys","sort","sortedObj","delay","resolve","setTimeout","deliverAfter","deliverAt","toISOString","_namespacedKey","namespacedKey_fn","KeyValueStoreClient","queryStore","action","deleted","ApiClient","apiUrl","TRIGGER_API_URL","registerEndpoint","apiKey","fetch","headers","Authorization","json","zodfetchWithVersions","zodfetch","SERIALIZED_TASK_OUTPUT","array","cancelRunsForEvent","webhookData","registerSchedule","unregisterSchedule","ok","boolean","encodeURIComponent","Accept","getRun","cancelRun","getRunStatuses","getRuns","jobSlug","cancelRunsForJob","encodedKey","STORE_URL","authHeader","headResponse","fetchHead","MAX_BODY_BYTE_LENGTH","getApiKey","TRIGGER_API_KEY","isValid","versionedSchemaMap","unversionedSchema","retryCount","requestInitWithCache","errorMessage","jsonBody","versionedSchema","withCache","cache","_","Request","requestInitWithoutMethod","exponential","minDelay","maxDelay","jitter","pow","jitterValue","ConcurrencyLimit","formatSchemaErrors","errors","path","HttpEndpoint","onRequest","HttpTrigger","endpointId","verify","handleRequest","request","respondWith","handler","clonedRequest","clone","immediateResponseFilter","skipTriggeringRuns","title","rule","link","help","noRuns","attachToJob","verifyPayload","httpEndpoint","examples","rawBody","foo","parsePayload","rawPayload","issues","createIOWithIntegrations","auths","connections","entries","connectionKey","auth","Proxy","target","prop","receiver","cloneForRun","Reflect","deepMergeFilters","_options","DynamicTrigger","attachDynamicTrigger","registeredTriggerForParams","channel","attachJobToDynamicTrigger","EventTrigger","eventTrigger","ScheduledPayloadSchema","currentDate","cronstrue","ts","marker","lastTimestamp","IntervalTrigger","schedule","intervalTrigger","CronTrigger","humanReadable","throwExceptionOnParseError","concat","cronTrigger","DynamicSchedule","attachDynamicSchedule","attachDynamicScheduleToJob","registerWebhookEvent","registerSourceEvent","_client","TriggerClient","on","verbose","fromEntries","triggerVersion","authorization","authorized","jobs","sources","values","webhooks","dynamicTriggers","registerSourceJob","dynamicTriggerRegisterSourceJobId","dynamicSchedules","httpEndpoints","endpoint","dynamicTrigger","execution","standardHeaders","abort","sourceRequestNeedsBody","sourceRequestInit","duplex","sourceRequest","dynamicId","secret","inputMetadata","webhookRequest","verified","rawJson","runNotification","defineJob","existingRegisteredJob","defineAuthResolver","resolver","defineDynamicSchedule","defineDynamicTrigger","defineHttpEndpoint","suppressWarnings","existingHttpEndpoint","defineConcurrencyLimit","dynamicTriggerId","updates","attachSource","s","r","handle","registeredSource","newOptions","deepMergeOptions","attachWebhook","generateEvents","registeredWebhook","config","registerPayload","crudOptions","active","crud","create","desired","localApiKey","runProperties","cachedTaskCursor","ioLogLocalEnabled","runChunkExecutionLimit","resolvedConnections","ioWithConnections","isTest","childError","errorWithStack","account","handledResponse","okResponse","handlers","verifyResult","resolvedAuthResults","all","allResolved","authResolver","resolvedAuth","accessToken","token","additionalFields","resolverError","start","listenerCount","onSuccess","onFailure","notification","emit","obj1","obj2","mergedOptions","hasOwnProperty","ExternalSource","rawEvent","registerEvent","ommited","omit","sourceWithoutChannel","channelWithoutType","integrationConfig","ExternalSourceTrigger","k","MISSING_CONNECTION_NOTIFICATION","MISSING_CONNECTION_RESOLVED_NOTIFICATION","MissingConnectionNotificationPayloadSchema","MissingConnectionResolvedNotificationPayloadSchema","missingConnectionNotification","MissingConnectionNotification","missingConnectionResolvedNotification","MissingConnectionResolvedNotification","i","InvokeTrigger","invokeTrigger","createHash","WebhookSource","str","slice","WebhookTrigger","eventFilter","optionsWithoutEvent","eventWithoutFilter","crypto","verifyRequestSignature","headerName","headerEncoding","algorithm","headerValue","verifyHmacSha256","bodyDigest","createHmac","signature","redactString","strings","interpolations","__redactedString","raw"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,yBAAyB;AAE3B,IAAMC,0BAAN,MAAMA,wBAAAA;EAGXC,cAAc;AACZ,SAAKC,UAAU,IAAIH,kBAAAA;EACrB;EAEAI,QAAoDC,SAAYC,IAA+B;AAC7F,WAAO,KAAKH,QAAQI,IAAIF,SAASC,EAAAA;EACnC;EAEAE,WAA0B;AACxB,WAAO,KAAKL,QAAQK,SAAQ;EAC9B;AACF;AAdaP;AAAN,IAAMA,yBAAN;;;ACOA,IAAMQ,kBAAkB,IAAIR,uBAAAA;;;ACT5B,SAASS,UAAUC,OAAuB;AAE/C,QAAMC,wBAAwBD,MAAME,YAAW,EAAGC,QAAQ,QAAQ,GAAA;AAGlE,QAAMC,wBAAwBH,sBAAsBE,QAAQ,qBAAqB,EAAA;AAEjF,SAAOC;AACT;AARgBL;;;ACYhB;AA6FO,IAAMM,OAAN,MAAMA,KAAAA;EASXd,YAAYe,SAAuD;AA+RnE;;;AA9RE,SAAKA,UAAUA;AACf,0BAAK,wBAAL;EACF;;;;EAKAC,eAAeC,QAAuB;AACpCA,WAAOC,OAAO,IAAI;AAClB,WAAO;EACT;EAEA,IAAIC,KAAK;AACP,WAAOX,UAAU,KAAKO,QAAQI,EAAE;EAClC;EAEA,IAAIC,UAAU;AACZ,WAAO,OAAO,KAAKL,QAAQK,YAAY,YAAY,KAAKL,QAAQK,UAAU;EAC5E;EAEA,IAAIC,OAAO;AACT,WAAO,KAAKN,QAAQM;EACtB;EAEA,IAAIC,UAA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A0B+kB,SAAAA,EAAW;EACzD;AACF;AA9CsBH;AAgDf,SAASK,iBACdD,aACAF,gBACArG,QACAxM,MACS;AACT,QAAMiT,aAAaP,OAAOQ,WAAW,UAAU1G,MAAAA,EAAQjY,OAAOyL,IAAAA,EAAM2B,OAAOkR,cAAAA;AAC3E,QAAMM,YAAYJ,aAAapnB,QAAQ,gBAAgB,EAAA,EAAIA,QAAQ,WAAW,EAAA,KAAO;AAErF,SAAOwnB,cAAcF;AACvB;AAVgBD;;;ACfT,SAASI,aACdC,YACGC,gBACW;AACd,SAAO;IACLC,kBAAkB;IAClBF,SAASA,QAAQG;IACjBF;EACF;AACF;AATgBF","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport class TypedAsyncLocalStorage<T> {\n private storage: AsyncLocalStorage<T>;\n\n constructor() {\n this.storage = new AsyncLocalStorage<T>();\n }\n\n runWith<R extends (...args: any[]) => Promise<any>>(context: T, fn: R): Promise<ReturnType<R>> {\n return this.storage.run(context, fn);\n }\n\n getStore(): T | undefined {\n return this.storage.getStore();\n }\n}\n","import { IO } from \"./io\";\nimport { TriggerContext } from \"./types\";\nimport { TypedAsyncLocalStorage } from \"./utils/typedAsyncLocalStorage\";\n\nexport type RunStore = {\n io: IO;\n ctx: TriggerContext;\n};\n\nexport const runLocalStorage = new TypedAsyncLocalStorage<RunStore>();\n","export function slugifyId(input: string): string {\n // Replace any number of spaces with a single dash\n const replaceSpacesWithDash = input.toLowerCase().replace(/\\s+/g, \"-\");\n\n // Remove any non-URL-safe characters\n const removeNonUrlSafeChars = replaceSpacesWithDash.replace(/[^a-zA-Z0-9-._~]/g, \"\");\n\n return removeNonUrlSafeChars;\n}\n","import {\n FailedRunNotification,\n IntegrationConfig,\n InvokeOptions,\n JobMetadata,\n Prettify,\n RunNotification,\n SuccessfulRunNotification,\n} from \"@trigger.dev/core\";\nimport { LogLevel } from \"@trigger.dev/core-backend\";\nimport { ConcurrencyLimit } from \"./concurrencyLimit\";\nimport { IOWithIntegrations, TriggerIntegration } from \"./integrations\";\nimport { runLocalStorage } from \"./runLocalStorage\";\nimport { TriggerClient } from \"./triggerClient\";\nimport type {\n EventSpecification,\n Trigger,\n TriggerContext,\n TriggerEventType,\n TriggerInvokeType,\n} from \"./types\";\nimport { slugifyId } from \"./utils\";\n\nexport type JobOptions<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration> = {},\n TOutput extends any = any,\n> = {\n /** The `id` property is used to uniquely identify the Job. Only change this if you want to create a new Job. */\n id: string;\n /** The `name` of the Job that you want to appear in the dashboard and logs. You can change this without creating a new Job. */\n name: string;\n /** The `version` property is used to version your Job. A new version will be created if you change this property. We recommend using [semantic versioning](https://www.baeldung.com/cs/semantic-versioning), e.g. `1.0.3`. */\n version: string;\n /** The `trigger` property is used to define when the Job should run. There are currently the following Trigger types:\n - [cronTrigger](https://trigger.dev/docs/sdk/crontrigger)\n - [intervalTrigger](https://trigger.dev/docs/sdk/intervaltrigger)\n - [eventTrigger](https://trigger.dev/docs/sdk/eventtrigger)\n - [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger)\n - [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule)\n - integration Triggers, like webhooks. See the [integrations](https://trigger.dev/docs/integrations) page for more information. */\n trigger: TTrigger;\n /** The `logLevel` property is an optional property that specifies the level of\n logging for the Job. The level is inherited from the client if you omit this property. */\n logLevel?: LogLevel;\n /** Imports the specified integrations into the Job. The integrations will be available on the `io` object in the `run()` function with the same name as the key. For example:\n ```ts\n client.defineJob({\n //... other options\n integrations: {\n slack,\n gh: github,\n },\n run: async (payload, io, ctx) => {\n //slack is available on io.slack\n io.slack.postMessage(...);\n //github is available on io.gh\n io.gh.addIssueLabels(...);\n }\n });\n ``` */\n integrations?: TIntegrations;\n\n /**\n * The `concurrencyLimit` property is used to limit the number of concurrent run executions of a job.\n * Can be a number which represents the limit or a `ConcurrencyLimit` instance which can be used to\n * group together multiple jobs to share the same concurrency limit.\n *\n * If undefined the job will be limited only by the server's global concurrency limit, or if you are using the\n * Trigger.dev Cloud service, the concurrency limit of your plan.\n */\n concurrencyLimit?: number | ConcurrencyLimit;\n /** The `enabled` property is used to enable or disable the Job. If you disable a Job, it will not run. */\n enabled?: boolean;\n /** This function gets called automatically when a Run is Triggered.\n * This is where you put the code you want to run for a Job. You can use normal code in here and you can also use Tasks. You can return a value from this function and it will be sent back to the Trigger API.\n * @param payload The payload of the event\n * @param io An object that contains the integrations that you specified in the `integrations` property and other useful functions like delays and running Tasks.\n * @param context An object that contains information about the Organization, Job, Run and more.\n */\n run: (\n payload: TriggerEventType<TTrigger>,\n io: IOWithIntegrations<TIntegrations>,\n context: TriggerContext\n ) => Promise<TOutput>;\n\n onSuccess?: (\n notification: SuccessfulRunNotification<TOutput, TriggerEventType<TTrigger>>\n ) => void;\n\n onFailure?: (notification: FailedRunNotification<TriggerEventType<TTrigger>>) => void;\n\n // @internal\n __internal?: boolean;\n};\n\nexport type JobPayload<TJob> = TJob extends Job<Trigger<EventSpecification<infer TEvent>>, any>\n ? TEvent\n : never;\n\nexport type JobIO<TJob> = TJob extends Job<any, infer TIntegrations>\n ? IOWithIntegrations<TIntegrations>\n : never;\n\n/** A [Job](https://trigger.dev/docs/documentation/concepts/jobs) is used to define the [Trigger](https://trigger.dev/docs/documentation/concepts/triggers), metadata, and what happens when it runs. */\nexport class Job<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration> = {},\n TOutput extends any = any,\n> {\n readonly options: JobOptions<TTrigger, TIntegrations, TOutput>;\n\n client?: TriggerClient;\n\n constructor(options: JobOptions<TTrigger, TIntegrations, TOutput>) {\n this.options = options;\n this.#validate();\n }\n\n /**\n * Attaches the job to a client. This is called automatically when you define a job using `client.defineJob()`.\n */\n attachToClient(client: TriggerClient) {\n client.attach(this);\n return this;\n }\n\n get id() {\n return slugifyId(this.options.id);\n }\n\n get enabled() {\n return typeof this.options.enabled === \"boolean\" ? this.options.enabled : true;\n }\n\n get name() {\n return this.options.name;\n }\n\n get trigger() {\n return this.options.trigger;\n }\n\n get version() {\n return this.options.version;\n }\n\n get logLevel() {\n return this.options.logLevel;\n }\n\n get integrations(): Record<string, IntegrationConfig> {\n return Object.keys(this.options.integrations ?? {}).reduce(\n (acc: Record<string, IntegrationConfig>, key) => {\n const integration = this.options.integrations![key];\n\n acc[key] = {\n id: integration.id,\n metadata: integration.metadata,\n authSource: integration.authSource,\n };\n\n return acc;\n },\n {}\n );\n }\n\n toJSON(): JobMetadata {\n // @ts-ignore\n const internal = this.options.__internal as JobMetadata[\"internal\"];\n\n return {\n id: this.id,\n name: this.name,\n version: this.version,\n event: this.trigger.event,\n trigger: this.trigger.toJSON(),\n integrations: this.integrations,\n startPosition: \"latest\", // this is deprecated, leaving this for now to make sure newer clients work with older servers\n enabled: this.enabled,\n preprocessRuns: this.trigger.preprocessRuns,\n internal,\n concurrencyLimit:\n typeof this.options.concurrencyLimit === \"number\"\n ? this.options.concurrencyLimit\n : typeof this.options.concurrencyLimit === \"object\"\n ? { id: this.options.concurrencyLimit.id, limit: this.options.concurrencyLimit.limit }\n : undefined,\n };\n }\n\n async invoke(\n cacheKey: string,\n payload: TriggerInvokeType<TTrigger>,\n options?: InvokeOptions\n ): Promise<{ id: string }>;\n async invoke(\n payload: TriggerInvokeType<TTrigger>,\n options?: InvokeOptions\n ): Promise<{ id: string }>;\n async invoke(\n param1: string | TriggerInvokeType<TTrigger>,\n param2: TriggerInvokeType<TTrigger> | InvokeOptions | undefined = undefined,\n param3: InvokeOptions | undefined = undefined\n ): Promise<{ id: string }> {\n const triggerClient = this.client;\n\n if (!triggerClient) {\n throw new Error(\n \"Cannot invoke a job that is not attached to a client. Make sure you attach the job to a client before invoking it.\"\n );\n }\n\n const runStore = runLocalStorage.getStore();\n\n if (typeof param1 === \"string\") {\n if (!runStore) {\n throw new Error(\n \"Cannot invoke a job from outside of a run when passing a cacheKey. Make sure you are running the job from within a run or use the invoke method without the cacheKey.\"\n );\n }\n\n const options = param3 ?? {};\n\n return await runStore.io.runTask(\n param1,\n async (task) => {\n const result = await triggerClient.invokeJob(this.id, param2, {\n idempotencyKey: task.idempotencyKey,\n ...options,\n });\n\n task.outputProperties = [\n {\n label: \"Run\",\n text: result.id,\n url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`,\n },\n ];\n\n return result;\n },\n {\n name: `Manually Invoke '${this.name}'`,\n params: param2,\n properties: [\n {\n label: \"Job\",\n text: this.id,\n url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}`,\n },\n {\n label: \"Env\",\n text: runStore.ctx.environment.slug,\n },\n ],\n }\n );\n }\n\n if (runStore) {\n throw new Error(\"Cannot invoke a job from within a run without a cacheKey.\");\n }\n\n return await triggerClient.invokeJob(this.id, param1, param2);\n }\n\n async invokeAndWaitForCompletion(\n cacheKey: string | string[],\n payload: TriggerInvokeType<TTrigger>,\n timeoutInSeconds: number = 60 * 60, // 1 hour\n options: Prettify<Pick<InvokeOptions, \"accountId\" | \"context\">> = {}\n ): Promise<RunNotification<TOutput>> {\n const triggerClient = this.client;\n\n if (!triggerClient) {\n throw new Error(\n \"Cannot invoke a job that is not attached to a client. Make sure you attach the job to a client before invoking it.\"\n );\n }\n\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n throw new Error(\n \"Cannot invoke a job from outside of a run using invokeAndWaitForCompletion. Make sure you are running the job from within a run or use the invoke method instead.\"\n );\n }\n\n const { io, ctx } = runStore;\n\n return (await io.runTask(\n cacheKey,\n async (task) => {\n const parsedPayload = this.trigger.event.parseInvokePayload\n ? this.trigger.event.parseInvokePayload(payload)\n ? payload\n : undefined\n : payload;\n\n const result = await triggerClient.invokeJob(this.id, parsedPayload, {\n idempotencyKey: task.idempotencyKey,\n callbackUrl: task.callbackUrl ?? undefined,\n ...options,\n });\n\n task.outputProperties = [\n {\n label: \"Run\",\n text: result.id,\n url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`,\n },\n ];\n\n return {}; // we don't want to return anything here, we just want to wait for the callback\n },\n {\n name: `Manually Invoke '${this.name}' and wait for completion`,\n params: payload,\n properties: [\n {\n label: \"Job\",\n text: this.id,\n url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`,\n },\n {\n label: \"Env\",\n text: ctx.environment.slug,\n },\n ],\n callback: {\n enabled: true,\n timeoutInSeconds,\n },\n }\n )) as RunNotification<TOutput>;\n }\n\n async batchInvokeAndWaitForCompletion(\n cacheKey: string | string[],\n batch: Array<{\n payload: TriggerInvokeType<TTrigger>;\n timeoutInSeconds?: number;\n options?: Prettify<Pick<InvokeOptions, \"accountId\" | \"context\">>;\n }>\n ): Promise<Array<RunNotification<TOutput>>> {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n throw new Error(\n \"Cannot invoke a job from outside of a run using batchInvokeAndWaitForCompletion.\"\n );\n }\n\n // If there are no items in the batch, return an empty array\n if (batch.length === 0) {\n return [];\n }\n\n // If there are too many items in the batch, throw an error\n if (batch.length > 25) {\n throw new Error(\n `Cannot batch invoke more than 25 items. You tried to batch invoke ${batch.length} items.`\n );\n }\n\n const { io, ctx } = runStore;\n\n const results = await io.parallel(\n cacheKey,\n batch,\n async (item, index) => {\n return (await this.invokeAndWaitForCompletion(\n String(index),\n item.payload,\n item.timeoutInSeconds ?? 60 * 60,\n item.options\n )) as RunNotification<{}>;\n },\n {\n name: `Batch Invoke '${this.name}'`,\n properties: [\n {\n label: \"Job\",\n text: this.id,\n url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`,\n },\n {\n label: \"Env\",\n text: ctx.environment.slug,\n },\n ],\n }\n );\n\n return results as Array<RunNotification<TOutput>>;\n }\n\n // Make sure the id is valid (must only contain alphanumeric characters and dashes)\n // Make sure the version is valid (must be a valid semver version)\n #validate() {\n if (!this.version.match(/^(\\d+)\\.(\\d+)\\.(\\d+)$/)) {\n throw new Error(\n `Invalid job version: \"${this.version}\". Job versions must be valid semver versions.`\n );\n }\n }\n}\n","import {\n API_VERSIONS,\n ConnectionAuth,\n DELIVER_WEBHOOK_REQUEST,\n DeserializedJson,\n EphemeralEventDispatcherRequestBody,\n ErrorWithStackSchema,\n FailedRunNotification,\n GetRunOptionsWithTaskDetails,\n GetRunsOptions,\n HandleTriggerSource,\n HttpEndpointRequestHeadersSchema,\n HttpSourceRequestHeadersSchema,\n HttpSourceResponseMetadata,\n IndexEndpointResponse,\n InitializeTriggerBodySchema,\n IntegrationConfig,\n InvokeOptions,\n JobMetadata,\n NormalizedResponse,\n PreprocessRunBody,\n PreprocessRunBodySchema,\n Prettify,\n REGISTER_SOURCE_EVENT_V2,\n REGISTER_WEBHOOK,\n RegisterSourceEventSchemaV2,\n RegisterSourceEventV2,\n RegisterTriggerBodyV2,\n RegisterWebhookPayload,\n RegisterWebhookPayloadSchema,\n RequestWithRawBodySchema,\n RunJobBody,\n RunJobBodySchema,\n RunJobErrorResponse,\n RunJobResponse,\n RunNotification,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n SourceMetadataV2,\n StatusUpdate,\n SuccessfulRunNotification,\n WebhookDeliveryResponse,\n WebhookMetadata,\n WebhookSourceRequestHeadersSchema,\n} from \"@trigger.dev/core\";\nimport { LogLevel, Logger } from \"@trigger.dev/core-backend\";\nimport EventEmitter from \"node:events\";\nimport { env } from \"node:process\";\nimport * as packageJson from \"../package.json\";\nimport { ApiClient } from \"./apiClient\";\nimport { ConcurrencyLimit, ConcurrencyLimitOptions } from \"./concurrencyLimit\";\nimport {\n AutoYieldExecutionError,\n AutoYieldWithCompletedTaskExecutionError,\n CanceledWithTaskError,\n ErrorWithTask,\n ParsedPayloadSchemaError,\n ResumeWithParallelTaskError,\n ResumeWithTaskError,\n RetryWithTaskError,\n YieldExecutionError,\n} from \"./errors\";\nimport { EndpointOptions, HttpEndpoint, httpEndpoint } from \"./httpEndpoint\";\nimport { TriggerIntegration } from \"./integrations\";\nimport { IO, IOStats } from \"./io\";\nimport { createIOWithIntegrations } from \"./ioWithIntegrations\";\nimport { Job, JobOptions } from \"./job\";\nimport { runLocalStorage } from \"./runLocalStorage\";\nimport { KeyValueStore } from \"./store/keyValueStore\";\nimport { DynamicTrigger, DynamicTriggerOptions } from \"./triggers/dynamic\";\nimport { EventTrigger } from \"./triggers/eventTrigger\";\nimport { ExternalSource } from \"./triggers/externalSource\";\nimport { DynamicIntervalOptions, DynamicSchedule } from \"./triggers/scheduled\";\nimport { WebhookDeliveryContext, WebhookSource } from \"./triggers/webhook\";\nimport {\n type EventSpecification,\n type NotificationsEventEmitter,\n type Trigger,\n type TriggerContext,\n type TriggerPreprocessContext,\n type VerifyResult,\n} from \"./types\";\nimport { formatSchemaErrors } from \"./utils/formatSchemaErrors\";\n\nconst parseRequestPayload = (rawPayload: any) => {\n const result = RequestWithRawBodySchema.safeParse(rawPayload);\n\n if (!result.success) {\n throw new ParsedPayloadSchemaError(formatSchemaErrors(result.error.issues));\n }\n\n return new Request(new URL(result.data.url), {\n method: result.data.method,\n headers: result.data.headers,\n body: result.data.rawBody,\n });\n};\n\nconst registerWebhookEvent = (key: string): EventSpecification<RegisterWebhookPayload> => ({\n name: `${REGISTER_WEBHOOK}.${key}`,\n title: \"Register Webhook\",\n source: \"internal\",\n icon: \"webhook\",\n parsePayload: RegisterWebhookPayloadSchema.parse,\n});\n\nconst registerSourceEvent: EventSpecification<RegisterSourceEventV2> = {\n name: REGISTER_SOURCE_EVENT_V2,\n title: \"Register Source\",\n source: \"internal\",\n icon: \"register-source\",\n parsePayload: RegisterSourceEventSchemaV2.parse,\n};\n\nexport type TriggerClientOptions = {\n /** The `id` property is used to uniquely identify the client.\n */\n id: string;\n /** The `apiKey` property is the API Key for your Trigger.dev environment. We\n recommend using an environment variable to store your API Key. */\n apiKey?: string;\n /** The `apiUrl` property is an optional property that specifies the API URL. You\n only need to specify this if you are not using Trigger.dev Cloud and are\n running your own Trigger.dev instance. */\n apiUrl?: string;\n /** The `logLevel` property is an optional property that specifies the level of\n logging for the TriggerClient. The level is inherited by all Jobs that use this Client, unless they also specify a `logLevel`. */\n logLevel?: LogLevel;\n /** Very verbose log messages, defaults to false. */\n verbose?: boolean;\n /** Default is unset and off. If set to true it will log to the server's console as well as the Trigger.dev platform */\n ioLogLocalEnabled?: boolean;\n};\n\nexport type AuthResolverResult = {\n type: \"apiKey\" | \"oauth\";\n token: string;\n additionalFields?: Record<string, string>;\n};\n\nexport type TriggerAuthResolver = (\n ctx: TriggerContext,\n integration: TriggerIntegration\n) => Promise<AuthResolverResult | void | undefined>;\n\ntype WebhookVerifyFunction = (\n request: Request,\n client: TriggerClient,\n ctx: WebhookDeliveryContext\n) => Promise<VerifyResult>;\n\ntype WebhookEventGeneratorFunction = (\n request: Request,\n client: TriggerClient,\n ctx: WebhookDeliveryContext\n) => Promise<void>;\n\n/** A [TriggerClient](https://trigger.dev/docs/documentation/concepts/client-adaptors) is used to connect to a specific [Project](https://trigger.dev/docs/documentation/concepts/projects) by using an [API Key](https://trigger.dev/docs/documentation/concepts/environments-apikeys). */\nexport class TriggerClient {\n #options: TriggerClientOptions;\n #registeredJobs: Record<string, Job<Trigger<EventSpecification<any>>, any>> = {};\n #registeredSources: Record<string, SourceMetadataV2> = {};\n #registeredWebhooks: Record<string, WebhookMetadata> = {};\n #registeredHttpSourceHandlers: Record<\n string,\n (\n source: HandleTriggerSource,\n request: Request\n ) => Promise<{\n events: Array<SendEvent>;\n response?: NormalizedResponse;\n metadata?: HttpSourceResponseMetadata;\n } | void>\n > = {};\n #registeredWebhookSourceHandlers: Record<\n string,\n {\n verify: WebhookVerifyFunction;\n generateEvents: WebhookEventGeneratorFunction;\n }\n > = {};\n #registeredDynamicTriggers: Record<\n string,\n DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>\n > = {};\n #jobMetadataByDynamicTriggers: Record<string, Array<{ id: string; version: string }>> = {};\n #registeredSchedules: Record<string, Array<{ id: string; version: string }>> = {};\n #registeredHttpEndpoints: Record<string, HttpEndpoint<EventSpecification<any>>> = {};\n #authResolvers: Record<string, TriggerAuthResolver> = {};\n #envStore: KeyValueStore;\n #eventEmitter: NotificationsEventEmitter = new EventEmitter() as NotificationsEventEmitter;\n\n #client: ApiClient;\n #internalLogger: Logger;\n id: string;\n\n constructor(options: Prettify<TriggerClientOptions>) {\n this.id = options.id;\n this.#options = options;\n this.#client = new ApiClient(this.#options);\n this.#internalLogger = new Logger(\"trigger.dev\", this.#options.verbose ? \"debug\" : \"log\", [\n \"output\",\n \"noopTasksSet\",\n ]);\n this.#envStore = new KeyValueStore(this.#client);\n }\n\n on = this.#eventEmitter.on.bind(this.#eventEmitter);\n\n async handleRequest(\n request: Request,\n timeOrigin: number = performance.now()\n ): Promise<NormalizedResponse> {\n this.#internalLogger.debug(\"handling request\", {\n url: request.url,\n headers: Object.fromEntries(request.headers.entries()),\n method: request.method,\n });\n\n const apiKey = request.headers.get(\"x-trigger-api-key\");\n const triggerVersion = request.headers.get(\"x-trigger-version\");\n\n const authorization = this.authorized(apiKey);\n\n switch (authorization) {\n case \"authorized\": {\n break;\n }\n case \"missing-client\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: client missing apiKey\",\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n case \"missing-header\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: missing x-trigger-api-key header\",\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n case \"unauthorized\": {\n return {\n status: 401,\n body: {\n message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`,\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n }\n\n if (request.method !== \"POST\") {\n return {\n status: 405,\n body: {\n message: \"Method not allowed (only POST is allowed)\",\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n\n const action = request.headers.get(\"x-trigger-action\");\n\n if (!action) {\n return {\n status: 400,\n body: {\n message: \"Missing x-trigger-action header\",\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n\n switch (action) {\n case \"PING\": {\n const endpointId = request.headers.get(\"x-trigger-endpoint-id\");\n\n if (!endpointId) {\n return {\n status: 200,\n body: {\n ok: false,\n error: \"Missing endpoint ID\",\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n\n if (this.id !== endpointId) {\n return {\n status: 200,\n body: {\n ok: false,\n error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`,\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n\n return {\n status: 200,\n body: {\n ok: true,\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n case \"INDEX_ENDPOINT\": {\n const body: IndexEndpointResponse = {\n jobs: this.#buildJobsIndex(),\n sources: Object.values(this.#registeredSources),\n webhooks: Object.values(this.#registeredWebhooks),\n dynamicTriggers: Object.values(this.#registeredDynamicTriggers).map((trigger) => ({\n id: trigger.id,\n jobs: this.#jobMetadataByDynamicTriggers[trigger.id] ?? [],\n registerSourceJob: {\n id: dynamicTriggerRegisterSourceJobId(trigger.id),\n version: trigger.source.version,\n },\n })),\n dynamicSchedules: Object.entries(this.#registeredSchedules).map(([id, jobs]) => ({\n id,\n jobs,\n })),\n httpEndpoints: Object.entries(this.#registeredHttpEndpoints).map(([id, endpoint]) =>\n endpoint.toJSON()\n ),\n };\n\n // if the x-trigger-job-id header is not set, we return all jobs\n return {\n status: 200,\n body,\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n case \"INITIALIZE_TRIGGER\": {\n const json = await request.json();\n const body = InitializeTriggerBodySchema.safeParse(json);\n\n if (!body.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid trigger body\",\n },\n };\n }\n\n const dynamicTrigger = this.#registeredDynamicTriggers[body.data.id];\n\n if (!dynamicTrigger) {\n return {\n status: 404,\n body: {\n message: \"Dynamic trigger not found\",\n },\n };\n }\n\n return {\n status: 200,\n body: dynamicTrigger.registeredTriggerForParams(body.data.params),\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n case \"EXECUTE_JOB\": {\n const json = await request.json();\n const execution = RunJobBodySchema.safeParse(json);\n\n if (!execution.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid execution\",\n },\n };\n }\n\n const job = this.#registeredJobs[execution.data.job.id];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n const results = await this.#executeJob(execution.data, job, timeOrigin, triggerVersion);\n\n this.#internalLogger.debug(\"executed job\", {\n results,\n job: job.id,\n version: job.version,\n triggerVersion,\n });\n\n const standardHeaders = this.#standardResponseHeaders(timeOrigin);\n\n standardHeaders[\"x-trigger-run-metadata\"] = this.#serializeRunMetadata(job);\n\n return {\n status: 200,\n body: results,\n headers: standardHeaders,\n };\n }\n case \"PREPROCESS_RUN\": {\n const json = await request.json();\n const body = PreprocessRunBodySchema.safeParse(json);\n\n if (!body.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid body\",\n },\n };\n }\n\n const job = this.#registeredJobs[body.data.job.id];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n const results = await this.#preprocessRun(body.data, job);\n\n return {\n status: 200,\n body: {\n abort: results.abort,\n properties: results.properties,\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n case \"DELIVER_HTTP_SOURCE_REQUEST\": {\n const headers = HttpSourceRequestHeadersSchema.safeParse(\n Object.fromEntries(request.headers.entries())\n );\n\n if (!headers.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid headers\",\n },\n };\n }\n\n const sourceRequestNeedsBody = headers.data[\"x-ts-http-method\"] !== \"GET\";\n\n const sourceRequestInit: RequestInit = {\n method: headers.data[\"x-ts-http-method\"],\n headers: headers.data[\"x-ts-http-headers\"],\n body: sourceRequestNeedsBody ? request.body : undefined,\n };\n\n if (sourceRequestNeedsBody) {\n try {\n // @ts-ignore\n sourceRequestInit.duplex = \"half\";\n } catch (error) {\n // ignore\n }\n }\n\n const sourceRequest = new Request(headers.data[\"x-ts-http-url\"], sourceRequestInit);\n\n const key = headers.data[\"x-ts-key\"];\n const dynamicId = headers.data[\"x-ts-dynamic-id\"];\n const secret = headers.data[\"x-ts-secret\"];\n const params = headers.data[\"x-ts-params\"];\n const data = headers.data[\"x-ts-data\"];\n const auth = headers.data[\"x-ts-auth\"];\n const inputMetadata = headers.data[\"x-ts-metadata\"];\n\n const source = {\n key,\n dynamicId,\n secret,\n params,\n data,\n auth,\n metadata: inputMetadata,\n };\n\n const { response, events, metadata } = await this.#handleHttpSourceRequest(\n source,\n sourceRequest\n );\n\n return {\n status: 200,\n body: {\n events,\n response,\n metadata,\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n case \"DELIVER_HTTP_ENDPOINT_REQUEST_FOR_RESPONSE\": {\n const headers = HttpEndpointRequestHeadersSchema.safeParse(\n Object.fromEntries(request.headers.entries())\n );\n\n if (!headers.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid headers\",\n },\n };\n }\n\n const sourceRequestNeedsBody = headers.data[\"x-ts-http-method\"] !== \"GET\";\n\n const sourceRequestInit: RequestInit = {\n method: headers.data[\"x-ts-http-method\"],\n headers: headers.data[\"x-ts-http-headers\"],\n body: sourceRequestNeedsBody ? request.body : undefined,\n };\n\n if (sourceRequestNeedsBody) {\n try {\n // @ts-ignore\n sourceRequestInit.duplex = \"half\";\n } catch (error) {\n // ignore\n }\n }\n\n const sourceRequest = new Request(headers.data[\"x-ts-http-url\"], sourceRequestInit);\n\n const key = headers.data[\"x-ts-key\"];\n\n const { response } = await this.#handleHttpEndpointRequestForResponse(\n {\n key,\n },\n sourceRequest\n );\n\n return {\n status: 200,\n body: response,\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n case \"DELIVER_WEBHOOK_REQUEST\": {\n const headers = WebhookSourceRequestHeadersSchema.safeParse(\n Object.fromEntries(request.headers.entries())\n );\n\n if (!headers.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid headers\",\n },\n };\n }\n\n const sourceRequestNeedsBody = headers.data[\"x-ts-http-method\"] !== \"GET\";\n\n const sourceRequestInit: RequestInit = {\n method: headers.data[\"x-ts-http-method\"],\n headers: headers.data[\"x-ts-http-headers\"],\n body: sourceRequestNeedsBody ? request.body : undefined,\n };\n\n if (sourceRequestNeedsBody) {\n try {\n // @ts-ignore\n sourceRequestInit.duplex = \"half\";\n } catch (error) {\n // ignore\n }\n }\n\n const webhookRequest = new Request(headers.data[\"x-ts-http-url\"], sourceRequestInit);\n\n const key = headers.data[\"x-ts-key\"];\n const secret = headers.data[\"x-ts-secret\"];\n const params = headers.data[\"x-ts-params\"];\n\n const ctx = {\n key,\n secret,\n params,\n };\n\n const { response, verified, error } = await this.#handleWebhookRequest(webhookRequest, ctx);\n\n return {\n status: 200,\n body: {\n response,\n verified,\n error,\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n case \"VALIDATE\": {\n return {\n status: 200,\n body: {\n ok: true,\n endpointId: this.id,\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n case \"PROBE_EXECUTION_TIMEOUT\": {\n const json = await request.json();\n // Keep this request open for max 15 minutes so the server can detect when the function execution limit is exceeded\n const timeout = json?.timeout ?? 15 * 60 * 1000;\n\n await new Promise((resolve) => setTimeout(resolve, timeout));\n\n return {\n status: 200,\n body: {\n ok: true,\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n case \"RUN_NOTIFICATION\": {\n const rawJson = await request.json();\n const runNotification = rawJson as RunNotification<any>;\n\n if (runNotification.ok) {\n await this.#deliverSuccessfulRunNotification(runNotification);\n } else {\n await this.#deliverFailedRunNotification(runNotification);\n }\n\n return {\n status: 200,\n body: {\n ok: true,\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n }\n\n return {\n status: 405,\n body: {\n message: \"Method not allowed\",\n },\n headers: this.#standardResponseHeaders(timeOrigin),\n };\n }\n\n defineJob<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration> = {},\n TOutput extends any = any,\n >(options: JobOptions<TTrigger, TIntegrations, TOutput>) {\n const existingRegisteredJob = this.#registeredJobs[options.id];\n\n if (existingRegisteredJob && options.__internal !== true) {\n console.warn(\n `[@trigger.dev/sdk] Warning: The Job \"${existingRegisteredJob.id}\" you're attempting to define has already been defined. Please assign a different ID to the job.`\n );\n }\n\n const job = new Job<TTrigger, TIntegrations, TOutput>(options);\n\n this.attach(job);\n\n return job;\n }\n\n defineAuthResolver(\n integration: TriggerIntegration,\n resolver: TriggerAuthResolver\n ): TriggerClient {\n this.#authResolvers[integration.id] = resolver;\n\n return this;\n }\n\n defineDynamicSchedule(options: DynamicIntervalOptions): DynamicSchedule {\n return new DynamicSchedule(this, options);\n }\n\n defineDynamicTrigger<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n >(\n options: DynamicTriggerOptions<TEventSpec, TExternalSource>\n ): DynamicTrigger<TEventSpec, TExternalSource> {\n return new DynamicTrigger(this, options);\n }\n\n /**\n * An [HTTP endpoint](https://trigger.dev/docs/documentation/concepts/http-endpoints) allows you to create a [HTTP Trigger](https://trigger.dev/docs/documentation/concepts/triggers/http), which means you can trigger your Jobs from any webhooks.\n * @param options The Endpoint options\n * @returns An HTTP Endpoint, that can be used to create an HTTP Trigger.\n * @link https://trigger.dev/docs/documentation/concepts/http-endpoints\n */\n defineHttpEndpoint(options: EndpointOptions, suppressWarnings = false) {\n const existingHttpEndpoint = this.#registeredHttpEndpoints[options.id];\n if (!suppressWarnings && existingHttpEndpoint) {\n console.warn(\n `[@trigger.dev/sdk] Warning: The HttpEndpoint \"${existingHttpEndpoint.id}\" you're attempting to define has already been defined. Please assign a different ID to the HttpEndpoint.`\n );\n }\n\n const endpoint = httpEndpoint(options);\n this.#registeredHttpEndpoints[endpoint.id] = endpoint;\n return endpoint;\n }\n\n defineConcurrencyLimit(options: ConcurrencyLimitOptions) {\n return new ConcurrencyLimit(options);\n }\n\n attach(job: Job<Trigger<any>, any>): void {\n this.#registeredJobs[job.id] = job;\n job.trigger.attachToJob(this, job);\n job.client = this;\n }\n\n attachDynamicTrigger(trigger: DynamicTrigger<any, any>): void {\n this.#registeredDynamicTriggers[trigger.id] = trigger;\n\n this.defineJob({\n id: dynamicTriggerRegisterSourceJobId(trigger.id),\n name: `Register dynamic trigger ${trigger.id}`,\n version: trigger.source.version,\n trigger: new EventTrigger({\n event: registerSourceEvent,\n filter: { dynamicTriggerId: [trigger.id] },\n }),\n integrations: {\n integration: trigger.source.integration,\n },\n run: async (event, io, ctx) => {\n const updates = await trigger.source.register(event.source.params, event, io, ctx);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await io.updateSource(\"update-source\", {\n key: event.source.key,\n ...updates,\n });\n },\n __internal: true,\n });\n }\n\n attachJobToDynamicTrigger(job: Job<Trigger<any>, any>, trigger: DynamicTrigger<any, any>): void {\n const jobs = this.#jobMetadataByDynamicTriggers[trigger.id] ?? [];\n\n jobs.push({ id: job.id, version: job.version });\n\n this.#jobMetadataByDynamicTriggers[trigger.id] = jobs;\n }\n\n attachSource(options: {\n key: string;\n source: ExternalSource<any, any>;\n event: EventSpecification<any>;\n params: any;\n options?: Record<string, string[]>;\n }): void {\n this.#registeredHttpSourceHandlers[options.key] = async (s, r) => {\n return await options.source.handle(s, r, this.#internalLogger);\n };\n\n let registeredSource = this.#registeredSources[options.key];\n\n if (!registeredSource) {\n registeredSource = {\n version: \"2\",\n channel: options.source.channel,\n key: options.key,\n params: options.params,\n options: {},\n integration: {\n id: options.source.integration.id,\n metadata: options.source.integration.metadata,\n authSource: options.source.integration.authSource,\n },\n registerSourceJob: {\n id: options.key,\n version: options.source.version,\n },\n };\n }\n\n //combined the previous source options with this one, making sure to include event\n const newOptions = deepMergeOptions(\n {\n event: typeof options.event.name === \"string\" ? [options.event.name] : options.event.name,\n },\n options.options ?? {}\n );\n registeredSource.options = deepMergeOptions(registeredSource.options, newOptions);\n\n this.#registeredSources[options.key] = registeredSource;\n\n this.defineJob({\n id: options.key,\n name: options.key,\n version: options.source.version,\n trigger: new EventTrigger({\n event: registerSourceEvent,\n filter: { source: { key: [options.key] } },\n }),\n integrations: {\n integration: options.source.integration,\n },\n run: async (event, io, ctx) => {\n const updates = await options.source.register(options.params, event, io, ctx);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await io.updateSource(\"update-source\", {\n key: options.key,\n ...updates,\n });\n },\n __internal: true,\n });\n }\n\n attachDynamicSchedule(key: string): void {\n const jobs = this.#registeredSchedules[key] ?? [];\n\n this.#registeredSchedules[key] = jobs;\n }\n\n attachDynamicScheduleToJob(key: string, job: Job<Trigger<any>, any>): void {\n const jobs = this.#registeredSchedules[key] ?? [];\n\n jobs.push({ id: job.id, version: job.version });\n\n this.#registeredSchedules[key] = jobs;\n }\n\n attachWebhook<\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TConfig extends Record<string, string[]>,\n >(options: {\n key: string;\n source: WebhookSource<TIntegration, TParams, TConfig>;\n event: EventSpecification<any>;\n params: any;\n config: TConfig;\n }): void {\n const { source } = options;\n\n this.#registeredWebhookSourceHandlers[options.key] = {\n verify: source.verify.bind(source),\n generateEvents: source.generateEvents.bind(source),\n };\n\n let registeredWebhook = this.#registeredWebhooks[options.key];\n\n if (!registeredWebhook) {\n registeredWebhook = {\n key: options.key,\n params: options.params,\n config: options.config,\n integration: {\n id: source.integration.id,\n metadata: source.integration.metadata,\n authSource: source.integration.authSource,\n },\n httpEndpoint: {\n id: options.key,\n },\n };\n } else {\n registeredWebhook.config = deepMergeOptions(registeredWebhook.config, options.config);\n }\n\n this.#registeredWebhooks[options.key] = registeredWebhook;\n\n this.defineJob({\n id: `webhook.register.${options.key}`,\n name: `webhook.register.${options.key}`,\n version: source.version,\n trigger: new EventTrigger({\n event: registerWebhookEvent(options.key),\n }),\n integrations: {\n integration: source.integration,\n },\n run: async (registerPayload, io, ctx) => {\n return await io.try(\n async () => {\n this.#internalLogger.debug(\"[webhook.register] Start\");\n\n const crudOptions = {\n io,\n // this is just a more strongly typed payload\n ctx: registerPayload as Parameters<(typeof source)[\"crud\"][\"create\"]>[0][\"ctx\"],\n };\n\n if (!registerPayload.active) {\n this.#internalLogger.debug(\"[webhook.register] Not active, run create\");\n\n await io.try(\n async () => {\n await source.crud.create(crudOptions);\n },\n async (error) => {\n this.#internalLogger.debug(\n \"[webhook.register] Error during create, re-trying with delete first\",\n { error }\n );\n\n await io.runTask(\"create-retry\", async () => {\n await source.crud.delete(crudOptions);\n await source.crud.create(crudOptions);\n });\n }\n );\n\n return await io.updateWebhook(\"update-webhook-success\", {\n key: options.key,\n active: true,\n config: registerPayload.config.desired,\n });\n }\n\n this.#internalLogger.debug(\"[webhook.register] Already active, run update\");\n\n if (source.crud.update) {\n await source.crud.update(crudOptions);\n } else {\n this.#internalLogger.debug(\n \"[webhook.register] Run delete and create instead of update\"\n );\n\n await source.crud.delete(crudOptions);\n await source.crud.create(crudOptions);\n }\n\n return await io.updateWebhook(\"update-webhook-success\", {\n key: options.key,\n active: true,\n config: registerPayload.config.desired,\n });\n },\n async (error) => {\n this.#internalLogger.debug(\"[webhook.register] Error\", { error });\n\n await io.updateWebhook(\"update-webhook-error\", {\n key: options.key,\n active: false,\n });\n\n throw error;\n }\n );\n },\n __internal: true,\n });\n }\n\n async registerTrigger(\n id: string,\n key: string,\n options: RegisterTriggerBodyV2,\n idempotencyKey?: string\n ) {\n return this.#client.registerTrigger(this.id, id, key, options, idempotencyKey);\n }\n\n async getAuth(id: string) {\n return this.#client.getAuth(this.id, id);\n }\n\n /** You can call this function from anywhere in your backend to send an event. The other way to send an event is by using [`io.sendEvent()`](https://trigger.dev/docs/sdk/io/sendevent) from inside a `run()` function.\n * @param event The event to send.\n * @param options Options for sending the event.\n * @returns A promise that resolves to the event details\n */\n async sendEvent(event: SendEvent, options?: SendEventOptions) {\n return this.#client.sendEvent(event, options);\n }\n\n /** You can call this function from anywhere in your backend to send multiple events. The other way to send multiple events is by using [`io.sendEvents()`](https://trigger.dev/docs/sdk/io/sendevents) from inside a `run()` function.\n * @param events The events to send.\n * @param options Options for sending the events.\n * @returns A promise that resolves to an array of event details\n */\n async sendEvents(events: SendEvent[], options?: SendEventOptions) {\n return this.#client.sendEvents(events, options);\n }\n\n async cancelEvent(eventId: string) {\n return this.#client.cancelEvent(eventId);\n }\n\n async cancelRunsForEvent(eventId: string) {\n return this.#client.cancelRunsForEvent(eventId);\n }\n\n async updateStatus(runId: string, id: string, status: StatusUpdate) {\n return this.#client.updateStatus(runId, id, status);\n }\n\n async registerSchedule(id: string, key: string, schedule: ScheduleMetadata) {\n return this.#client.registerSchedule(this.id, id, key, schedule);\n }\n\n async unregisterSchedule(id: string, key: string) {\n return this.#client.unregisterSchedule(this.id, id, key);\n }\n\n async getEvent(eventId: string) {\n return this.#client.getEvent(eventId);\n }\n\n async getRun(runId: string, options?: GetRunOptionsWithTaskDetails) {\n return this.#client.getRun(runId, options);\n }\n\n async cancelRun(runId: string) {\n return this.#client.cancelRun(runId);\n }\n\n async getRuns(jobSlug: string, options?: GetRunsOptions) {\n return this.#client.getRuns(jobSlug, options);\n }\n\n async getRunStatuses(runId: string) {\n return this.#client.getRunStatuses(runId);\n }\n\n async invokeJob(jobId: string, payload: any, options?: InvokeOptions) {\n return this.#client.invokeJob(jobId, payload, options);\n }\n\n async cancelRunsForJob(jobId: string) {\n return this.#client.cancelRunsForJob(jobId);\n }\n\n async createEphemeralEventDispatcher(payload: EphemeralEventDispatcherRequestBody) {\n return this.#client.createEphemeralEventDispatcher(payload);\n }\n\n get store() {\n return {\n env: this.#envStore,\n };\n }\n\n authorized(\n apiKey?: string | null\n ): \"authorized\" | \"unauthorized\" | \"missing-client\" | \"missing-header\" {\n if (typeof apiKey !== \"string\") {\n return \"missing-header\";\n }\n\n const localApiKey = this.#options.apiKey ?? env.TRIGGER_API_KEY;\n\n if (!localApiKey) {\n return \"missing-client\";\n }\n\n return apiKey === localApiKey ? \"authorized\" : \"unauthorized\";\n }\n\n apiKey() {\n return this.#options.apiKey ?? env.TRIGGER_API_KEY;\n }\n\n async #preprocessRun(body: PreprocessRunBody, job: Job<Trigger<EventSpecification<any>>, any>) {\n const context = this.#createPreprocessRunContext(body);\n\n const parsedPayload = job.trigger.event.parsePayload(body.event.payload ?? {});\n\n const properties = job.trigger.event.runProperties?.(parsedPayload) ?? [];\n\n return {\n abort: false,\n properties,\n };\n }\n\n async #executeJob(\n body: RunJobBody,\n job: Job<Trigger<any>, Record<string, TriggerIntegration>>,\n timeOrigin: number,\n triggerVersion: string | null\n ): Promise<RunJobResponse> {\n this.#internalLogger.debug(\"executing job\", {\n execution: body,\n job: job.id,\n version: job.version,\n triggerVersion,\n });\n\n const context = this.#createRunContext(body);\n\n const io = new IO({\n id: body.run.id,\n jobId: job.id,\n cachedTasks: body.tasks,\n cachedTasksCursor: body.cachedTaskCursor,\n yieldedExecutions: body.yieldedExecutions ?? [],\n noopTasksSet: body.noopTasksSet,\n apiClient: this.#client,\n logger: this.#internalLogger,\n client: this,\n context,\n jobLogLevel: job.logLevel ?? this.#options.logLevel ?? \"info\",\n jobLogger: this.#options.ioLogLocalEnabled\n ? new Logger(job.id, job.logLevel ?? this.#options.logLevel ?? \"info\")\n : undefined,\n serverVersion: triggerVersion,\n timeOrigin,\n executionTimeout: body.runChunkExecutionLimit,\n });\n\n const resolvedConnections = await this.#resolveConnections(\n context,\n job.options.integrations,\n body.connections\n );\n\n if (!resolvedConnections.ok) {\n return {\n status: \"UNRESOLVED_AUTH_ERROR\",\n issues: resolvedConnections.issues,\n };\n }\n\n const ioWithConnections = createIOWithIntegrations(\n io,\n resolvedConnections.data,\n job.options.integrations\n );\n\n try {\n const parsedPayload = job.trigger.event.parsePayload(body.event.payload ?? {});\n\n if (!context.run.isTest) {\n const verified = await job.trigger.verifyPayload(parsedPayload);\n if (!verified.success) {\n return {\n status: \"ERROR\",\n error: { message: `Payload verification failed. ${verified.reason}` },\n };\n }\n }\n\n const output = await runLocalStorage.runWith({ io, ctx: context }, () => {\n return job.options.run(parsedPayload, ioWithConnections, context);\n });\n\n if (this.#options.verbose) {\n this.#logIOStats(io.stats);\n }\n\n return { status: \"SUCCESS\", output };\n } catch (error) {\n if (this.#options.verbose) {\n this.#logIOStats(io.stats);\n }\n\n if (error instanceof ResumeWithParallelTaskError) {\n return {\n status: \"RESUME_WITH_PARALLEL_TASK\",\n task: error.task,\n childErrors: error.childErrors.map((childError) => {\n return this.#convertErrorToExecutionResponse(childError, body);\n }),\n };\n }\n\n return this.#convertErrorToExecutionResponse(error, body);\n }\n }\n\n #convertErrorToExecutionResponse(error: any, body: RunJobBody): RunJobErrorResponse {\n if (error instanceof AutoYieldExecutionError) {\n return {\n status: \"AUTO_YIELD_EXECUTION\",\n location: error.location,\n timeRemaining: error.timeRemaining,\n timeElapsed: error.timeElapsed,\n limit: body.runChunkExecutionLimit,\n };\n }\n\n if (error instanceof AutoYieldWithCompletedTaskExecutionError) {\n return {\n status: \"AUTO_YIELD_EXECUTION_WITH_COMPLETED_TASK\",\n id: error.id,\n properties: error.properties,\n output: error.output,\n data: {\n ...error.data,\n limit: body.runChunkExecutionLimit,\n },\n };\n }\n\n if (error instanceof YieldExecutionError) {\n return { status: \"YIELD_EXECUTION\", key: error.key };\n }\n\n if (error instanceof ParsedPayloadSchemaError) {\n return { status: \"INVALID_PAYLOAD\", errors: error.schemaErrors };\n }\n\n if (error instanceof ResumeWithTaskError) {\n return { status: \"RESUME_WITH_TASK\", task: error.task };\n }\n\n if (error instanceof RetryWithTaskError) {\n return {\n status: \"RETRY_WITH_TASK\",\n task: error.task,\n error: error.cause,\n retryAt: error.retryAt,\n };\n }\n\n if (error instanceof CanceledWithTaskError) {\n return {\n status: \"CANCELED\",\n task: error.task,\n };\n }\n\n if (error instanceof ErrorWithTask) {\n const errorWithStack = ErrorWithStackSchema.safeParse(error.cause.output);\n\n if (errorWithStack.success) {\n return {\n status: \"ERROR\",\n error: errorWithStack.data,\n task: error.cause,\n };\n }\n\n return {\n status: \"ERROR\",\n error: { message: JSON.stringify(error.cause.output) },\n task: error.cause,\n };\n }\n\n if (error instanceof RetryWithTaskError) {\n const errorWithStack = ErrorWithStackSchema.safeParse(error.cause);\n\n if (errorWithStack.success) {\n return {\n status: \"ERROR\",\n error: errorWithStack.data,\n task: error.task,\n };\n }\n\n return {\n status: \"ERROR\",\n error: { message: \"Unknown error\" },\n task: error.task,\n };\n }\n\n const errorWithStack = ErrorWithStackSchema.safeParse(error);\n\n if (errorWithStack.success) {\n return { status: \"ERROR\", error: errorWithStack.data };\n }\n\n const message = typeof error === \"string\" ? error : JSON.stringify(error);\n\n return {\n status: \"ERROR\",\n error: { name: \"Unknown error\", message },\n };\n }\n\n #createRunContext(execution: RunJobBody): TriggerContext {\n const { event, organization, project, environment, job, run, source } = execution;\n\n return {\n event: {\n id: event.id,\n name: event.name,\n context: event.context,\n timestamp: event.timestamp,\n },\n organization,\n project: project ?? { id: \"unknown\", name: \"unknown\", slug: \"unknown\" }, // backwards compat with old servers\n environment,\n job,\n run,\n account: execution.account,\n source,\n };\n }\n\n #createPreprocessRunContext(body: PreprocessRunBody): TriggerPreprocessContext {\n const { event, organization, environment, job, run, account } = body;\n\n return {\n event: {\n id: event.id,\n name: event.name,\n context: event.context,\n timestamp: event.timestamp,\n },\n organization,\n environment,\n job,\n run,\n account,\n };\n }\n\n async #handleHttpSourceRequest(\n source: {\n key: string;\n dynamicId?: string;\n secret: string;\n data: any;\n params: any;\n auth?: ConnectionAuth;\n metadata?: DeserializedJson;\n },\n sourceRequest: Request\n ): Promise<{\n response: NormalizedResponse;\n events: SendEvent[];\n metadata?: HttpSourceResponseMetadata;\n }> {\n this.#internalLogger.debug(\"Handling HTTP source request\", {\n source,\n });\n\n if (source.dynamicId) {\n const dynamicTrigger = this.#registeredDynamicTriggers[source.dynamicId];\n\n if (!dynamicTrigger) {\n this.#internalLogger.debug(\"No dynamic trigger registered for HTTP source\", {\n source,\n });\n\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n events: [],\n };\n }\n\n const results = await dynamicTrigger.source.handle(\n source,\n sourceRequest,\n this.#internalLogger\n );\n\n if (!results) {\n return {\n events: [],\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n return {\n events: results.events,\n response: results.response ?? {\n status: 200,\n body: {\n ok: true,\n },\n },\n metadata: results.metadata,\n };\n }\n\n const handler = this.#registeredHttpSourceHandlers[source.key];\n\n if (!handler) {\n this.#internalLogger.debug(\"No handler registered for HTTP source\", {\n source,\n });\n\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n events: [],\n };\n }\n\n const results = await handler(source, sourceRequest);\n\n if (!results) {\n return {\n events: [],\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n return {\n events: results.events,\n response: results.response ?? {\n status: 200,\n body: {\n ok: true,\n },\n },\n metadata: results.metadata,\n };\n }\n\n async #handleHttpEndpointRequestForResponse(\n data: {\n key: string;\n },\n sourceRequest: Request\n ): Promise<{\n response: NormalizedResponse;\n }> {\n this.#internalLogger.debug(\"Handling HTTP Endpoint request for response\", {\n data,\n });\n\n const httpEndpoint = this.#registeredHttpEndpoints[data.key];\n if (!httpEndpoint) {\n this.#internalLogger.debug(\"No handler registered for HTTP Endpoint\", {\n data,\n });\n\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n const handledResponse = await httpEndpoint.handleRequest(sourceRequest);\n\n if (!handledResponse) {\n this.#internalLogger.debug(\"There's no HTTP Endpoint respondWith.handler()\", {\n data,\n });\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n let body: string | undefined;\n try {\n body = await handledResponse.text();\n } catch (error) {\n this.#internalLogger.error(\n `Error reading httpEndpoint ${httpEndpoint.id} respondWith.handler Response`,\n {\n error,\n }\n );\n }\n\n const response = {\n status: handledResponse.status,\n headers: handledResponse.headers\n ? Object.fromEntries(handledResponse.headers.entries())\n : undefined,\n body,\n };\n\n this.#internalLogger.info(`httpEndpoint ${httpEndpoint.id} respondWith.handler response`, {\n response,\n });\n\n return {\n response,\n };\n }\n\n async #handleWebhookRequest(\n request: Request,\n ctx: WebhookDeliveryContext\n ): Promise<WebhookDeliveryResponse> {\n this.#internalLogger.debug(\"Handling webhook request\", {\n ctx,\n });\n\n const okResponse = {\n status: 200,\n body: {\n ok: true,\n },\n };\n\n const handlers = this.#registeredWebhookSourceHandlers[ctx.key];\n\n if (!handlers) {\n this.#internalLogger.debug(\"No handler registered for webhook\", {\n ctx,\n });\n\n return {\n response: okResponse,\n verified: false,\n };\n }\n\n const { verify, generateEvents } = handlers;\n\n const verifyResult = await verify(request, this, ctx);\n\n if (!verifyResult.success) {\n return {\n response: okResponse,\n verified: false,\n error: verifyResult.reason,\n };\n }\n\n await generateEvents(request, this, ctx);\n\n return {\n response: okResponse,\n verified: true,\n };\n }\n\n async #resolveConnections(\n ctx: TriggerContext,\n integrations?: Record<string, TriggerIntegration>,\n connections?: Record<string, ConnectionAuth>\n ): Promise<\n | { ok: true; data: Record<string, ConnectionAuth> }\n | { ok: false; issues: Record<string, { id: string; error: string }> }\n > {\n if (!integrations) {\n return { ok: true, data: {} };\n }\n\n const resolvedAuthResults = await Promise.all(\n Object.keys(integrations).map(async (key) => {\n const integration = integrations[key];\n const auth = (connections ?? {})[key];\n\n const result = await this.#resolveConnection(ctx, integration, auth);\n\n if (result.ok) {\n return {\n ok: true as const,\n auth: result.auth,\n key,\n };\n } else {\n return {\n ok: false as const,\n error: result.error,\n key,\n };\n }\n })\n );\n\n const allResolved = resolvedAuthResults.every((result) => result.ok);\n\n if (allResolved) {\n return {\n ok: true,\n data: resolvedAuthResults.reduce((acc: Record<string, ConnectionAuth>, result) => {\n acc[result.key] = result.auth!;\n\n return acc;\n }, {}),\n };\n } else {\n return {\n ok: false,\n issues: resolvedAuthResults.reduce(\n (acc: Record<string, { id: string; error: string }>, result) => {\n if (result.ok) {\n return acc;\n }\n\n const integration = integrations[result.key];\n\n acc[result.key] = { id: integration.id, error: result.error };\n\n return acc;\n },\n {}\n ),\n };\n }\n }\n\n async #resolveConnection(\n ctx: TriggerContext,\n integration: TriggerIntegration,\n auth?: ConnectionAuth\n ): Promise<{ ok: true; auth: ConnectionAuth | undefined } | { ok: false; error: string }> {\n if (auth) {\n return { ok: true, auth };\n }\n\n const authResolver = this.#authResolvers[integration.id];\n\n if (!authResolver) {\n if (integration.authSource === \"HOSTED\") {\n return {\n ok: false,\n error: `Something went wrong: Integration ${integration.id} is missing auth credentials from Trigger.dev`,\n };\n }\n\n return {\n ok: true,\n auth: undefined,\n };\n }\n\n try {\n const resolvedAuth = await authResolver(ctx, integration);\n\n if (!resolvedAuth) {\n return {\n ok: false,\n error: `Auth could not be resolved for ${integration.id}: auth resolver returned null or undefined`,\n };\n }\n\n return {\n ok: true,\n auth:\n resolvedAuth.type === \"apiKey\"\n ? {\n type: \"apiKey\",\n accessToken: resolvedAuth.token,\n additionalFields: resolvedAuth.additionalFields,\n }\n : {\n type: \"oauth2\",\n accessToken: resolvedAuth.token,\n additionalFields: resolvedAuth.additionalFields,\n },\n };\n } catch (resolverError) {\n if (resolverError instanceof Error) {\n return {\n ok: false,\n error: `Auth could not be resolved for ${integration.id}: auth resolver threw. ${resolverError.name}: ${resolverError.message}`,\n };\n } else if (typeof resolverError === \"string\") {\n return {\n ok: false,\n error: `Auth could not be resolved for ${integration.id}: auth resolver threw an error: ${resolverError}`,\n };\n }\n\n return {\n ok: false,\n error: `Auth could not be resolved for ${\n integration.id\n }: auth resolver threw an unknown error: ${JSON.stringify(resolverError)}`,\n };\n }\n }\n\n #buildJobsIndex(): IndexEndpointResponse[\"jobs\"] {\n return Object.values(this.#registeredJobs).map((job) => this.#buildJobIndex(job));\n }\n\n #buildJobIndex(job: Job<Trigger<any>, any>): IndexEndpointResponse[\"jobs\"][number] {\n const internal = job.options.__internal as JobMetadata[\"internal\"];\n\n return {\n id: job.id,\n name: job.name,\n version: job.version,\n event: job.trigger.event,\n trigger: job.trigger.toJSON(),\n integrations: this.#buildJobIntegrations(job),\n startPosition: \"latest\", // job is deprecated, leaving job for now to make sure newer clients work with older servers\n enabled: job.enabled,\n preprocessRuns: job.trigger.preprocessRuns,\n internal,\n concurrencyLimit:\n typeof job.options.concurrencyLimit === \"number\"\n ? job.options.concurrencyLimit\n : typeof job.options.concurrencyLimit === \"object\"\n ? { id: job.options.concurrencyLimit.id, limit: job.options.concurrencyLimit.limit }\n : undefined,\n };\n }\n\n #buildJobIntegrations(\n job: Job<Trigger<any>, Record<string, TriggerIntegration>>\n ): IndexEndpointResponse[\"jobs\"][number][\"integrations\"] {\n return Object.keys(job.options.integrations ?? {}).reduce(\n (acc: Record<string, IntegrationConfig>, key) => {\n const integration = job.options.integrations![key];\n\n acc[key] = this.#buildJobIntegration(integration);\n\n return acc;\n },\n {}\n );\n }\n\n #buildJobIntegration(\n integration: TriggerIntegration\n ): IndexEndpointResponse[\"jobs\"][number][\"integrations\"][string] {\n const authSource = this.#authResolvers[integration.id] ? \"RESOLVER\" : integration.authSource;\n\n return {\n id: integration.id,\n metadata: integration.metadata,\n authSource,\n };\n }\n\n #logIOStats(stats: IOStats) {\n this.#internalLogger.debug(\"IO stats\", {\n stats,\n });\n }\n\n #standardResponseHeaders(start: number): Record<string, string> {\n return {\n \"Trigger-Version\": API_VERSIONS.LAZY_LOADED_CACHED_TASKS,\n \"Trigger-SDK-Version\": packageJson.version,\n \"X-Trigger-Request-Timing\": `dur=${performance.now() - start / 1000.0}`,\n };\n }\n\n #serializeRunMetadata(job: Job<Trigger<EventSpecification<any>>, any>) {\n const metadata: Record<string, any> = {};\n\n if (\n this.#eventEmitter.listenerCount(\"runSucceeeded\") > 0 ||\n typeof job.options.onSuccess === \"function\"\n ) {\n metadata[\"successSubscription\"] = true;\n }\n\n if (\n this.#eventEmitter.listenerCount(\"runFailed\") > 0 ||\n typeof job.options.onFailure === \"function\"\n ) {\n metadata[\"failedSubscription\"] = true;\n }\n\n return JSON.stringify(metadata);\n }\n\n async #deliverSuccessfulRunNotification(notification: SuccessfulRunNotification<any>) {\n this.#internalLogger.debug(\"delivering successful run notification\", {\n notification,\n });\n\n this.#eventEmitter.emit(\"runSucceeeded\", notification);\n\n const job = this.#registeredJobs[notification.job.id];\n\n if (!job) {\n return;\n }\n\n if (typeof job.options.onSuccess === \"function\") {\n await job.options.onSuccess(notification);\n }\n }\n\n async #deliverFailedRunNotification(notification: FailedRunNotification) {\n this.#internalLogger.debug(\"delivering failed run notification\", {\n notification,\n });\n\n this.#eventEmitter.emit(\"runFailed\", notification);\n\n const job = this.#registeredJobs[notification.job.id];\n\n if (!job) {\n return;\n }\n\n if (typeof job.options.onFailure === \"function\") {\n await job.options.onFailure(notification);\n }\n }\n}\n\nfunction dynamicTriggerRegisterSourceJobId(id: string) {\n return `register-dynamic-trigger-${id}`;\n}\n\ntype Options = Record<string, string[]>;\n\nfunction deepMergeOptions(obj1: Options, obj2: Options): Options {\n const mergedOptions: Options = { ...obj1 };\n\n for (const key in obj2) {\n if (obj2.hasOwnProperty(key)) {\n if (key in mergedOptions) {\n mergedOptions[key] = [...mergedOptions[key], ...obj2[key]];\n } else {\n mergedOptions[key] = obj2[key];\n }\n }\n }\n\n return mergedOptions;\n}\n","{\n \"name\": \"@trigger.dev/sdk\",\n \"version\": \"3.0.0-beta.7\",\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.7\",\n \"@trigger.dev/core-backend\": \"workspace:^3.0.0-beta.7\",\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 },\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 \"peerDependencies\": {\n \"msw\": \"^2.2.1\"\n },\n \"peerDependenciesMeta\": {\n \"msw\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n }\n}","import {\n API_VERSIONS,\n ApiEventLog,\n ApiEventLogSchema,\n CancelRunsForEventSchema,\n CancelRunsForJobSchema,\n CompleteTaskBodyV2Input,\n ConnectionAuthSchema,\n EphemeralEventDispatcherRequestBody,\n EphemeralEventDispatcherResponseBodySchema,\n FailTaskBodyInput,\n GetEventSchema,\n GetRunOptionsWithTaskDetails,\n GetRunSchema,\n GetRunStatusesSchema,\n GetRunsOptions,\n GetRunsSchema,\n InvokeJobRequestBody,\n InvokeJobResponseSchema,\n InvokeOptions,\n JobRunStatusRecordSchema,\n KeyValueStoreResponseBody,\n KeyValueStoreResponseBodySchema,\n RegisterScheduleResponseBodySchema,\n RegisterSourceEventSchemaV2,\n RegisterSourceEventV2,\n RegisterTriggerBodyV2,\n RunTaskBodyInput,\n RunTaskResponseWithCachedTasksBodySchema,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n ServerTaskSchema,\n StatusUpdate,\n TriggerSource,\n TriggerSourceSchema,\n UpdateTriggerSourceBodyV2,\n UpdateWebhookBody,\n assertExhaustive,\n urlWithSearchParams,\n} from \"@trigger.dev/core\";\nimport { LogLevel, Logger } from \"@trigger.dev/core-backend\";\nimport { env } from \"node:process\";\n\nimport { z } from \"zod\";\nimport { KeyValueStoreClient } from \"./store/keyValueStoreClient\";\n\nexport type ApiClientOptions = {\n apiKey?: string;\n apiUrl?: string;\n logLevel?: LogLevel;\n};\n\nexport type EndpointRecord = {\n id: string;\n name: string;\n url: string;\n};\n\nexport type HttpSourceRecord = {\n id: string;\n key: string;\n managed: boolean;\n url: string;\n status: \"PENDING\" | \"ACTIVE\" | \"INACTIVE\";\n secret?: string;\n data?: any;\n};\n\nexport type RunRecord = {\n id: string;\n jobId: string;\n callbackUrl: string;\n event: ApiEventLog;\n};\n\nexport class ApiClient {\n #apiUrl: string;\n #options: ApiClientOptions;\n #logger: Logger;\n #storeClient: KeyValueStoreClient;\n\n constructor(options: ApiClientOptions) {\n this.#options = options;\n\n this.#apiUrl = this.#options.apiUrl ?? env.TRIGGER_API_URL ?? \"https://api.trigger.dev\";\n this.#logger = new Logger(\"trigger.dev\", this.#options.logLevel);\n\n this.#storeClient = new KeyValueStoreClient(this.#queryKeyValueStore.bind(this));\n }\n\n async registerEndpoint(options: { url: string; name: string }): Promise<EndpointRecord> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Registering endpoint\", {\n url: options.url,\n name: options.name,\n });\n\n const response = await fetch(`${this.#apiUrl}/api/v1/endpoints`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n url: options.url,\n name: options.name,\n }),\n });\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status !== 200) {\n throw new Error(`Failed to register entry point, got status code ${response.status}`);\n }\n\n return await response.json();\n }\n\n async runTask(\n runId: string,\n task: RunTaskBodyInput,\n options: { cachedTasksCursor?: string } = {}\n ) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Running Task\", {\n task,\n });\n\n return await zodfetchWithVersions(\n {\n [API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: RunTaskResponseWithCachedTasksBodySchema,\n },\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n \"Idempotency-Key\": task.idempotencyKey,\n \"X-Cached-Tasks-Cursor\": options.cachedTasksCursor ?? \"\",\n \"Trigger-Version\": API_VERSIONS.LAZY_LOADED_CACHED_TASKS,\n },\n body: JSON.stringify(task),\n }\n );\n }\n\n async completeTask(runId: string, id: string, task: CompleteTaskBodyV2Input) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Complete Task\", {\n task,\n });\n\n return await zodfetch(\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks/${id}/complete`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n \"Trigger-Version\": API_VERSIONS.SERIALIZED_TASK_OUTPUT,\n },\n body: JSON.stringify(task),\n }\n );\n }\n\n async failTask(runId: string, id: string, body: FailTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Fail Task\", {\n id,\n runId,\n body,\n });\n\n return await zodfetch(\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks/${id}/fail`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n }\n );\n }\n\n async sendEvent(event: SendEvent, options: SendEventOptions = {}) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Sending event\", {\n event,\n });\n\n return await zodfetch(ApiEventLogSchema, `${this.#apiUrl}/api/v1/events`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ event, options }),\n });\n }\n\n async sendEvents(events: SendEvent[], options: SendEventOptions = {}) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Sending multiple events\", {\n events,\n });\n\n return await zodfetch(ApiEventLogSchema.array(), `${this.#apiUrl}/api/v1/events/bulk`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ events, options }),\n });\n }\n\n async cancelEvent(eventId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Cancelling event\", {\n eventId,\n });\n\n return await zodfetch(ApiEventLogSchema, `${this.#apiUrl}/api/v1/events/${eventId}/cancel`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async cancelRunsForEvent(eventId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Cancelling runs for event\", {\n eventId,\n });\n\n return await zodfetch(\n CancelRunsForEventSchema,\n `${this.#apiUrl}/api/v1/events/${eventId}/cancel-runs`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async updateStatus(runId: string, id: string, status: StatusUpdate) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Update status\", {\n id,\n status,\n });\n\n return await zodfetch(\n JobRunStatusRecordSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/statuses/${id}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(status),\n }\n );\n }\n\n async updateSource(\n client: string,\n key: string,\n source: UpdateTriggerSourceBodyV2\n ): Promise<TriggerSource> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"activating http source\", {\n source,\n });\n\n const response = await zodfetch(\n TriggerSourceSchema,\n `${this.#apiUrl}/api/v2/${client}/sources/${key}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(source),\n }\n );\n\n return response;\n }\n\n async updateWebhook(key: string, webhookData: UpdateWebhookBody): Promise<TriggerSource> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"activating webhook\", {\n webhookData,\n });\n\n const response = await zodfetch(TriggerSourceSchema, `${this.#apiUrl}/api/v1/webhooks/${key}`, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(webhookData),\n });\n\n return response;\n }\n\n async registerTrigger(\n client: string,\n id: string,\n key: string,\n payload: RegisterTriggerBodyV2,\n idempotencyKey?: string\n ): Promise<RegisterSourceEventV2> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering trigger\", {\n id,\n payload,\n });\n\n const headers: HeadersInit = {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n };\n\n if (idempotencyKey) {\n headers[\"Idempotency-Key\"] = idempotencyKey;\n }\n\n const response = await zodfetch(\n RegisterSourceEventSchemaV2,\n `${this.#apiUrl}/api/v2/${client}/triggers/${id}/registrations/${key}`,\n {\n method: \"PUT\",\n headers: headers,\n body: JSON.stringify(payload),\n }\n );\n\n return response;\n }\n\n async registerSchedule(client: string, id: string, key: string, payload: ScheduleMetadata) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering schedule\", {\n id,\n payload,\n });\n\n const response = await zodfetch(\n RegisterScheduleResponseBodySchema,\n `${this.#apiUrl}/api/v1/${client}/schedules/${id}/registrations`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ id: key, ...payload }),\n }\n );\n\n return response;\n }\n\n async unregisterSchedule(client: string, id: string, key: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"unregistering schedule\", {\n id,\n });\n\n const response = await zodfetch(\n z.object({ ok: z.boolean() }),\n `${this.#apiUrl}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`,\n {\n method: \"DELETE\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n\n return response;\n }\n\n async getAuth(client: string, id: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"getting auth\", {\n id,\n });\n\n const response = await zodfetch(\n ConnectionAuthSchema,\n `${this.#apiUrl}/api/v1/${client}/auth/${id}`,\n {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n },\n {\n optional: true,\n }\n );\n\n return response;\n }\n\n async getEvent(eventId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Event\", {\n eventId,\n });\n\n return await zodfetch(GetEventSchema, `${this.#apiUrl}/api/v2/events/${eventId}`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async getRun(runId: string, options?: GetRunOptionsWithTaskDetails) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Run\", {\n runId,\n });\n\n return await zodfetch(\n GetRunSchema,\n urlWithSearchParams(`${this.#apiUrl}/api/v2/runs/${runId}`, options),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async cancelRun(runId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Cancelling Run\", {\n runId,\n });\n\n return await zodfetch(GetRunSchema, `${this.#apiUrl}/api/v1/runs/${runId}/cancel`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async getRunStatuses(runId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Run statuses\", {\n runId,\n });\n\n return await zodfetch(GetRunStatusesSchema, `${this.#apiUrl}/api/v2/runs/${runId}/statuses`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async getRuns(jobSlug: string, options?: GetRunsOptions) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Runs\", {\n jobSlug,\n });\n\n return await zodfetch(\n GetRunsSchema,\n urlWithSearchParams(`${this.#apiUrl}/api/v1/jobs/${jobSlug}/runs`, options),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async invokeJob(jobId: string, payload: any, options: InvokeOptions = {}) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Invoking Job\", {\n jobId,\n });\n\n const body: InvokeJobRequestBody = {\n payload,\n context: options.context ?? {},\n options: {\n accountId: options.accountId,\n callbackUrl: options.callbackUrl,\n },\n };\n\n return await zodfetch(InvokeJobResponseSchema, `${this.#apiUrl}/api/v1/jobs/${jobId}/invoke`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n ...(options.idempotencyKey ? { \"Idempotency-Key\": options.idempotencyKey } : {}),\n },\n body: JSON.stringify(body),\n });\n }\n\n async cancelRunsForJob(jobId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Cancelling Runs for Job\", {\n jobId,\n });\n\n return await zodfetch(\n CancelRunsForJobSchema,\n `${this.#apiUrl}/api/v1/jobs/${jobId}/cancel-runs`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async createEphemeralEventDispatcher(payload: EphemeralEventDispatcherRequestBody) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Creating ephemeral event dispatcher\", {\n payload,\n });\n\n const response = await zodfetch(\n EphemeralEventDispatcherResponseBodySchema,\n `${this.#apiUrl}/api/v1/event-dispatchers/ephemeral`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n }\n );\n\n return response;\n }\n\n get store() {\n return this.#storeClient;\n }\n\n async #queryKeyValueStore(\n action: KeyValueStoreResponseBody[\"action\"],\n data: {\n key: string;\n value?: string;\n }\n ): Promise<KeyValueStoreResponseBody> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"accessing key-value store\", {\n action,\n data,\n });\n\n const encodedKey = encodeURIComponent(data.key);\n\n const STORE_URL = `${this.#apiUrl}/api/v1/store/${encodedKey}`;\n\n const authHeader: HeadersInit = {\n Authorization: `Bearer ${apiKey}`,\n };\n\n let requestInit: RequestInit | undefined;\n\n switch (action) {\n case \"DELETE\": {\n requestInit = {\n method: \"DELETE\",\n headers: authHeader,\n };\n\n break;\n }\n case \"GET\": {\n requestInit = {\n method: \"GET\",\n headers: authHeader,\n };\n\n break;\n }\n case \"HAS\": {\n const headResponse = await fetchHead(STORE_URL, {\n headers: authHeader,\n });\n\n return {\n action: \"HAS\",\n key: encodedKey,\n has: !!headResponse.ok,\n };\n }\n case \"SET\": {\n const MAX_BODY_BYTE_LENGTH = 256 * 1024;\n\n if ((data.value?.length ?? 0) > MAX_BODY_BYTE_LENGTH) {\n throw new Error(`Max request body size exceeded: ${MAX_BODY_BYTE_LENGTH} bytes`);\n }\n\n requestInit = {\n method: \"PUT\",\n headers: {\n ...authHeader,\n \"Content-Type\": \"text/plain\",\n },\n body: data.value,\n };\n\n break;\n }\n default: {\n assertExhaustive(action);\n }\n }\n\n const response = await zodfetch(KeyValueStoreResponseBodySchema, STORE_URL, requestInit);\n\n return response;\n }\n\n async #apiKey() {\n const apiKey = getApiKey(this.#options.apiKey);\n\n if (apiKey.status === \"invalid\") {\n throw new Error(\"Invalid API key\");\n\n // const chalk = (await import(\"chalk\")).default;\n // const terminalLink = (await import(\"terminal-link\")).default;\n\n // throw new Error(\n // `${chalk.red(\"Trigger.dev error\")}: Invalid API key (\"${chalk.italic(\n // apiKey.apiKey\n // )}\"), please set the TRIGGER_API_KEY environment variable or pass the apiKey option to a valid value. ${terminalLink(\n // \"Get your API key here\",\n // \"https://app.trigger.dev\",\n // {\n // fallback(text, url) {\n // return `${text} 👉 ${url}`;\n // },\n // }\n // )}`\n // );\n } else if (apiKey.status === \"missing\") {\n throw new Error(\"Missing API key\");\n // const chalk = (await import(\"chalk\")).default;\n // const terminalLink = (await import(\"terminal-link\")).default;\n\n // throw new Error(\n // `${chalk.red(\n // \"Trigger.dev error\"\n // )}: Missing an API key, please set the TRIGGER_API_KEY environment variable or pass the apiKey option to the Trigger constructor. ${terminalLink(\n // \"Get your API key here\",\n // \"https://app.trigger.dev\",\n // {\n // fallback(text, url) {\n // return `${text} 👉 ${url}`;\n // },\n // }\n // )}`\n // );\n }\n\n return apiKey.apiKey;\n }\n}\n\nfunction getApiKey(key?: string) {\n const apiKey = key ?? env.TRIGGER_API_KEY;\n\n if (!apiKey) {\n return { status: \"missing\" as const };\n }\n\n // Validate the api_key format (should be tr_{env}_XXXXX)\n const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);\n\n if (!isValid) {\n return { status: \"invalid\" as const, apiKey };\n }\n\n return { status: \"valid\" as const, apiKey };\n}\n\ntype VersionedResponseBodyMap = {\n [key: string]: z.ZodTypeAny;\n};\n\n// The resulting type should be a discriminating union\n// For example, if the TVersions param is { \"2023_09_29\": z.string() } and the TUnversioned param is z.number(), the resulting type should be:\n// type VersionedResponseBody = { version: \"2023_09_29\"; body: string } | { version: \"unversioned\"; body: number }\ntype VersionedResponseBody<\n TVersions extends VersionedResponseBodyMap,\n TUnversioned extends z.ZodTypeAny,\n> =\n | {\n [TVersion in keyof TVersions]: {\n version: TVersion;\n body: z.infer<TVersions[TVersion]>;\n };\n }[keyof TVersions]\n | {\n version: \"unversioned\";\n body: z.infer<TUnversioned>;\n };\n\nasync function zodfetchWithVersions<\n TVersionedResponseBodyMap extends VersionedResponseBodyMap,\n TUnversionedResponseBodySchema extends z.ZodTypeAny,\n TOptional extends boolean = false,\n>(\n versionedSchemaMap: TVersionedResponseBodyMap,\n unversionedSchema: TUnversionedResponseBodySchema,\n url: string,\n requestInit?: RequestInit,\n options?: {\n errorMessage?: string;\n optional?: TOptional;\n },\n retryCount = 0\n): Promise<\n TOptional extends true\n ? VersionedResponseBody<TVersionedResponseBodyMap, TUnversionedResponseBodySchema> | undefined\n : VersionedResponseBody<TVersionedResponseBodyMap, TUnversionedResponseBodySchema>\n> {\n const response = await fetch(url, requestInitWithCache(requestInit));\n\n if (\n (!requestInit || requestInit.method === \"GET\") &&\n response.status === 404 &&\n options?.optional\n ) {\n // @ts-ignore\n return;\n }\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status >= 500 && retryCount < 6) {\n // retry with exponential backoff and jitter\n const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n\n return zodfetchWithVersions(\n versionedSchemaMap,\n unversionedSchema,\n url,\n requestInit,\n options,\n retryCount + 1\n );\n }\n\n if (response.status !== 200) {\n throw new Error(\n options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`\n );\n }\n\n const jsonBody = await response.json();\n\n const version = response.headers.get(\"trigger-version\");\n\n if (!version) {\n return {\n version: \"unversioned\",\n body: unversionedSchema.parse(jsonBody),\n };\n }\n\n const versionedSchema = versionedSchemaMap[version];\n\n if (!versionedSchema) {\n throw new Error(`Unknown version ${version}`);\n }\n\n return {\n version,\n body: versionedSchema.parse(jsonBody),\n };\n}\n\nfunction requestInitWithCache(requestInit?: RequestInit): RequestInit {\n try {\n const withCache: RequestInit = {\n ...requestInit,\n cache: \"no-cache\",\n };\n\n const _ = new Request(\"http://localhost\", withCache);\n\n return withCache;\n } catch (error) {\n return requestInit ?? {};\n }\n}\n\nasync function fetchHead(\n url: string,\n requestInitWithoutMethod?: Omit<RequestInit, \"method\">,\n retryCount = 0\n): Promise<Response> {\n const requestInit: RequestInit = {\n ...requestInitWithoutMethod,\n method: \"HEAD\",\n };\n const response = await fetch(url, requestInitWithCache(requestInit));\n\n if (response.status >= 500 && retryCount < 6) {\n // retry with exponential backoff and jitter\n const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n\n return fetchHead(url, requestInitWithoutMethod, retryCount + 1);\n }\n\n return response;\n}\n\nasync function zodfetch<TResponseSchema extends z.ZodTypeAny, TOptional extends boolean = false>(\n schema: TResponseSchema,\n url: string,\n requestInit?: RequestInit,\n options?: {\n errorMessage?: string;\n optional?: TOptional;\n },\n retryCount = 0\n): Promise<\n TOptional extends true ? z.infer<TResponseSchema> | undefined : z.infer<TResponseSchema>\n> {\n const response = await fetch(url, requestInitWithCache(requestInit));\n\n if (\n (!requestInit || requestInit.method === \"GET\") &&\n response.status === 404 &&\n options?.optional\n ) {\n // @ts-ignore\n return;\n }\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status >= 500 && retryCount < 6) {\n // retry with exponential backoff and jitter\n const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n\n return zodfetch(schema, url, requestInit, options, retryCount + 1);\n }\n\n if (response.status !== 200) {\n throw new Error(\n options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`\n );\n }\n\n const jsonBody = await response.json();\n\n return schema.parse(jsonBody);\n}\n\nfunction exponentialBackoff(\n retryCount: number,\n exponential: number,\n minDelay: number,\n maxDelay: number,\n jitter: number\n): number {\n // Calculate the delay using the exponential backoff formula\n const delay = Math.min(Math.pow(exponential, retryCount) * minDelay, maxDelay);\n\n // Calculate the jitter\n const jitterValue = Math.random() * jitter;\n\n // Return the calculated delay with jitter\n return delay + jitterValue;\n}\n","import {\n API_VERSIONS,\n CachedTask,\n ConnectionAuth,\n CronOptions,\n ErrorWithStackSchema,\n EventFilter,\n FetchPollOperation,\n FetchRequestInit,\n FetchRetryOptions,\n FetchTimeoutOptions,\n InitialStatusUpdate,\n IntervalOptions,\n RunTaskOptions,\n SendEvent,\n SendEventOptions,\n ServerTask,\n UpdateTriggerSourceBodyV2,\n UpdateWebhookBody,\n supportsFeature,\n} from \"@trigger.dev/core\";\nimport { LogLevel, Logger } from \"@trigger.dev/core-backend\";\nimport { BloomFilter } from \"@trigger.dev/core-backend\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { webcrypto } from \"node:crypto\";\nimport { ApiClient } from \"./apiClient\";\nimport {\n AutoYieldExecutionError,\n AutoYieldWithCompletedTaskExecutionError,\n CanceledWithTaskError,\n ErrorWithTask,\n ResumeWithParallelTaskError,\n ResumeWithTaskError,\n RetryWithTaskError,\n TriggerInternalError,\n YieldExecutionError,\n isTriggerError,\n} from \"./errors\";\nimport { IntegrationTaskKey } from \"./integrations\";\nimport { calculateRetryAt } from \"./retry\";\nimport { TriggerStatus } from \"./status\";\nimport { TriggerClient } from \"./triggerClient\";\nimport { DynamicTrigger } from \"./triggers/dynamic\";\nimport { ExternalSource, ExternalSourceParams } from \"./triggers/externalSource\";\nimport { DynamicSchedule } from \"./triggers/scheduled\";\nimport {\n EventSpecification,\n TaskLogger,\n TriggerContext,\n WaitForEventResult,\n waitForEventSchema,\n} from \"./types\";\nimport { z } from \"zod\";\nimport { KeyValueStore } from \"./store/keyValueStore\";\nimport { Buffer } from \"node:buffer\";\n\nexport type IOTask = ServerTask;\n\nexport type IOOptions = {\n id: string;\n jobId: string;\n apiClient: ApiClient;\n client: TriggerClient;\n context: TriggerContext;\n timeOrigin: number;\n logger?: Logger;\n logLevel?: LogLevel;\n jobLogger?: Logger;\n jobLogLevel: LogLevel;\n cachedTasks?: Array<CachedTask>;\n cachedTasksCursor?: string;\n yieldedExecutions?: Array<string>;\n noopTasksSet?: string;\n serverVersion?: string | null;\n executionTimeout?: number;\n};\n\ntype JsonPrimitive = string | number | boolean | null | undefined | Date | symbol;\ntype JsonArray = Json[];\ntype JsonRecord<T> = { [Property in keyof T]: Json };\nexport type Json<T = any> = JsonPrimitive | JsonArray | JsonRecord<T>;\n\nexport type RunTaskErrorCallback = (\n error: unknown,\n task: IOTask,\n io: IO\n) =>\n | { retryAt?: Date; error?: Error; jitter?: number; skipRetrying?: boolean }\n | Error\n | undefined\n | void;\n\nexport type IOStats = {\n initialCachedTasks: number;\n lazyLoadedCachedTasks: number;\n executedTasks: number;\n cachedTaskHits: number;\n cachedTaskMisses: number;\n noopCachedTaskHits: number;\n noopCachedTaskMisses: number;\n};\n\nexport interface OutputSerializer {\n serialize(value: any): string;\n deserialize<T>(value: string): T;\n}\n\nexport class JSONOutputSerializer implements OutputSerializer {\n serialize(value: any): string {\n return JSON.stringify(value);\n }\n\n deserialize(value?: string): any {\n return value ? JSON.parse(value) : undefined;\n }\n}\n\nexport type BackgroundFetchResponse<T> = {\n status: number;\n data: T;\n headers: Record<string, string>;\n};\n\nexport class IO {\n private _id: string;\n private _jobId: string;\n private _apiClient: ApiClient;\n private _triggerClient: TriggerClient;\n private _logger: Logger;\n private _jobLogger?: Logger;\n private _jobLogLevel: LogLevel;\n private _cachedTasks: Map<string, CachedTask>;\n private _taskStorage: AsyncLocalStorage<{ taskId: string }>;\n private _cachedTasksCursor?: string;\n private _context: TriggerContext;\n private _yieldedExecutions: Array<string>;\n private _noopTasksBloomFilter: BloomFilter | undefined;\n private _stats: IOStats;\n private _serverVersion: string;\n private _timeOrigin: number;\n private _executionTimeout?: number;\n private _outputSerializer: OutputSerializer = new JSONOutputSerializer();\n private _visitedCacheKeys: Set<string> = new Set();\n\n private _envStore: KeyValueStore;\n private _jobStore: KeyValueStore;\n private _runStore: KeyValueStore;\n\n get stats() {\n return this._stats;\n }\n\n constructor(options: IOOptions) {\n this._id = options.id;\n this._jobId = options.jobId;\n this._apiClient = options.apiClient;\n this._triggerClient = options.client;\n this._logger = options.logger ?? new Logger(\"trigger.dev\", options.logLevel);\n this._cachedTasks = new Map();\n this._jobLogger = options.jobLogger;\n this._jobLogLevel = options.jobLogLevel;\n this._timeOrigin = options.timeOrigin;\n this._executionTimeout = options.executionTimeout;\n\n this._envStore = new KeyValueStore(options.apiClient);\n this._jobStore = new KeyValueStore(options.apiClient, \"job\", options.jobId);\n this._runStore = new KeyValueStore(options.apiClient, \"run\", options.id);\n\n this._stats = {\n initialCachedTasks: 0,\n lazyLoadedCachedTasks: 0,\n executedTasks: 0,\n cachedTaskHits: 0,\n cachedTaskMisses: 0,\n noopCachedTaskHits: 0,\n noopCachedTaskMisses: 0,\n };\n\n if (options.cachedTasks) {\n options.cachedTasks.forEach((task) => {\n this._cachedTasks.set(task.idempotencyKey, task);\n });\n\n this._stats.initialCachedTasks = options.cachedTasks.length;\n }\n\n this._taskStorage = new AsyncLocalStorage();\n this._context = options.context;\n this._yieldedExecutions = options.yieldedExecutions ?? [];\n\n if (options.noopTasksSet) {\n this._noopTasksBloomFilter = BloomFilter.deserialize(\n options.noopTasksSet,\n BloomFilter.NOOP_TASK_SET_SIZE\n );\n }\n\n this._cachedTasksCursor = options.cachedTasksCursor;\n this._serverVersion = options.serverVersion ?? \"unversioned\";\n }\n\n /** @internal */\n get runId() {\n return this._id;\n }\n\n /** @internal */\n get triggerClient() {\n return this._triggerClient;\n }\n\n /** Used to send log messages to the [Run log](https://trigger.dev/docs/documentation/guides/viewing-runs). */\n get logger() {\n return new IOLogger(async (level, message, data) => {\n let logLevel: LogLevel = \"info\";\n\n if (data instanceof Error) {\n data = {\n name: data.name,\n message: data.message,\n stack: data.stack,\n };\n }\n\n if (Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {\n await this.runTask(\n [message, level],\n async (task) => {\n switch (level) {\n case \"LOG\": {\n this._jobLogger?.log(message, data);\n logLevel = \"log\";\n break;\n }\n case \"DEBUG\": {\n this._jobLogger?.debug(message, data);\n logLevel = \"debug\";\n break;\n }\n case \"INFO\": {\n this._jobLogger?.info(message, data);\n logLevel = \"info\";\n break;\n }\n case \"WARN\": {\n this._jobLogger?.warn(message, data);\n logLevel = \"warn\";\n break;\n }\n case \"ERROR\": {\n this._jobLogger?.error(message, data);\n logLevel = \"error\";\n break;\n }\n }\n },\n {\n name: \"log\",\n icon: \"log\",\n description: message,\n params: data,\n properties: [{ label: \"Level\", text: level }],\n style: { style: \"minimal\", variant: level.toLowerCase() },\n noop: true,\n }\n );\n }\n });\n }\n\n /** `io.random()` is identical to `Math.random()` when called without options but ensures your random numbers are not regenerated on resume or retry. It will return a pseudo-random floating-point number between optional `min` (default: 0, inclusive) and `max` (default: 1, exclusive). Can optionally `round` to the nearest integer.\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param min Sets the lower bound (inclusive). Can't be higher than `max`.\n * @param max Sets the upper bound (exclusive). Can't be lower than `min`.\n * @param round Controls rounding to the nearest integer. Any `max` integer will become inclusive when enabled. Rounding with floating-point bounds may cause unexpected skew and boundary inclusivity.\n */\n async random(\n cacheKey: string | any[],\n {\n min = 0,\n max = 1,\n round = false,\n }: {\n min?: number;\n max?: number;\n round?: boolean;\n } = {}\n ) {\n return await this.runTask(\n cacheKey,\n async (task) => {\n if (min > max) {\n throw new Error(\n `Lower bound can't be higher than upper bound - min: ${min}, max: ${max}`\n );\n }\n\n if (min === max) {\n await this.logger.warn(\n `Lower and upper bounds are identical. The return value is not random and will always be: ${min}`\n );\n }\n\n const withinBounds = (max - min) * Math.random() + min;\n\n if (!round) {\n return withinBounds;\n }\n\n if (!Number.isInteger(min) || !Number.isInteger(max)) {\n await this.logger.warn(\n \"Rounding enabled with floating-point bounds. This may cause unexpected skew and boundary inclusivity.\"\n );\n }\n\n const rounded = Math.round(withinBounds);\n\n return rounded;\n },\n {\n name: \"random\",\n icon: \"dice-5-filled\",\n params: { min, max, round },\n properties: [\n ...(min === 0\n ? []\n : [\n {\n label: \"min\",\n text: String(min),\n },\n ]),\n ...(max === 1\n ? []\n : [\n {\n label: \"max\",\n text: String(max),\n },\n ]),\n ...(round === false\n ? []\n : [\n {\n label: \"round\",\n text: String(round),\n },\n ]),\n ],\n style: { style: \"minimal\" },\n }\n );\n }\n\n /** `io.wait()` waits for the specified amount of time before continuing the Job. Delays work even if you're on a serverless platform with timeouts, or if your server goes down. They utilize [resumability](https://trigger.dev/docs/documentation/concepts/resumability) to ensure that the Run can be resumed after the delay.\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param seconds The number of seconds to wait. This can be very long, serverless timeouts are not an issue.\n */\n async wait(cacheKey: string | any[], seconds: number) {\n return await this.runTask(cacheKey, async (task) => {}, {\n name: \"wait\",\n icon: \"clock\",\n params: { seconds },\n noop: true,\n delayUntil: new Date(Date.now() + seconds * 1000),\n style: { style: \"minimal\" },\n });\n }\n\n async waitForEvent<T extends z.ZodTypeAny = z.ZodTypeAny>(\n cacheKey: string | any[],\n event: {\n name: string;\n schema?: T;\n filter?: EventFilter;\n source?: string;\n contextFilter?: EventFilter;\n accountId?: string;\n },\n options?: { timeoutInSeconds?: number }\n ): Promise<WaitForEventResult<z.output<T>>> {\n const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;\n\n return (await this.runTask(\n cacheKey,\n async (task, io) => {\n if (!task.callbackUrl) {\n throw new Error(\"No callbackUrl found on task\");\n }\n\n await this.triggerClient.createEphemeralEventDispatcher({\n url: task.callbackUrl,\n name: event.name,\n filter: event.filter,\n contextFilter: event.contextFilter,\n source: event.source,\n accountId: event.accountId,\n timeoutInSeconds,\n });\n\n return {} as Promise<{}>;\n },\n {\n name: \"Wait for Event\",\n icon: \"custom-event\",\n params: {\n name: event.name,\n source: event.source,\n filter: event.filter,\n contextFilter: event.contextFilter,\n accountId: event.accountId,\n },\n callback: {\n enabled: true,\n timeoutInSeconds,\n },\n properties: [\n {\n label: \"Event\",\n text: event.name,\n },\n {\n label: \"Timeout\",\n text: `${timeoutInSeconds}s`,\n },\n ...(event.source ? [{ label: \"Source\", text: event.source }] : []),\n ...(event.accountId ? [{ label: \"Account ID\", text: event.accountId }] : []),\n ],\n parseOutput: (output) => {\n return waitForEventSchema(event.schema ?? z.any()).parse(output);\n },\n }\n )) as WaitForEventResult<z.output<T>>;\n }\n\n /** `io.waitForRequest()` allows you to pause the execution of a run until the url provided in the callback is POSTed to.\n * This is useful for integrating with external services that require a callback URL to be provided, or if you want to be able to wait until an action is performed somewhere else in your system.\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param callback A callback function that will provide the unique URL to POST to.\n * @param options Options for the callback.\n * @param options.timeoutInSeconds How long to wait for the request to be POSTed to the callback URL before timing out. Defaults to 1hr.\n * @returns The POSTed request JSON body.\n * @example\n * ```ts\n const result = await io.waitForRequest<{ message: string }>(\n \"wait-for-request\",\n async (url, task) => {\n // Save the URL somewhere so you can POST to it later\n // Or send it to an external service that will POST to it\n },\n { timeoutInSeconds: 60 } // wait 60 seconds\n );\n * ```\n */\n async waitForRequest<T extends Json<T> | unknown = unknown>(\n cacheKey: string | any[],\n callback: (url: string) => Promise<unknown>,\n options?: { timeoutInSeconds?: number }\n ): Promise<T> {\n const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;\n\n return (await this.runTask(\n cacheKey,\n async (task, io) => {\n if (!task.callbackUrl) {\n throw new Error(\"No callbackUrl found on task\");\n }\n\n task.outputProperties = [\n {\n label: \"Callback URL\",\n text: task.callbackUrl,\n },\n ];\n\n return callback(task.callbackUrl) as Promise<{}>;\n },\n {\n name: \"Wait for Request\",\n icon: \"clock\",\n callback: {\n enabled: true,\n timeoutInSeconds: options?.timeoutInSeconds,\n },\n properties: [\n {\n label: \"Timeout\",\n text: `${timeoutInSeconds}s`,\n },\n ],\n }\n )) as T;\n }\n\n /** `io.createStatus()` allows you to set a status with associated data during the Run. Statuses can be used by your UI using the react package \n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param initialStatus The initial status you want this status to have. You can update it during the rub using the returned object.\n * @returns a TriggerStatus object that you can call `update()` on, to update the status.\n * @example \n * ```ts\n * client.defineJob(\n //...\n run: async (payload, io, ctx) => {\n const generatingImages = await io.createStatus(\"generating-images\", {\n label: \"Generating Images\",\n state: \"loading\",\n data: {\n progress: 0.1,\n },\n });\n\n //...do stuff\n\n await generatingImages.update(\"completed-generation\", {\n label: \"Generated images\",\n state: \"success\",\n data: {\n progress: 1.0,\n urls: [\"http://...\"]\n },\n });\n\n //...\n });\n * ```\n */\n async createStatus(\n cacheKey: IntegrationTaskKey,\n initialStatus: InitialStatusUpdate\n ): Promise<TriggerStatus> {\n const id = typeof cacheKey === \"string\" ? cacheKey : cacheKey.join(\"-\");\n const status = new TriggerStatus(id, this);\n await status.update(cacheKey, initialStatus);\n return status;\n }\n\n /** `io.backgroundFetch()` fetches data from a URL that can take longer that the serverless timeout. The actual `fetch` request is performed on the Trigger.dev platform, and the response is sent back to you.\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param url The URL to fetch from.\n * @param requestInit The options for the request\n * @param retry The options for retrying the request if it fails\n * An object where the key is a status code pattern and the value is a retrying strategy.\n * Supported patterns are:\n * - Specific status codes: 429\n * - Ranges: 500-599\n * - Wildcards: 2xx, 3xx, 4xx, 5xx\n */\n async backgroundFetch<TResponseData>(\n cacheKey: string | any[],\n url: string,\n requestInit?: FetchRequestInit,\n options?: {\n retry?: FetchRetryOptions;\n timeout?: FetchTimeoutOptions;\n }\n ): Promise<TResponseData> {\n const urlObject = new URL(url);\n\n return (await this.runTask(\n cacheKey,\n async (task) => {\n console.log(\"task context\", task.context);\n\n return task.output;\n },\n {\n name: `fetch ${urlObject.hostname}${urlObject.pathname}`,\n params: { url, requestInit, retry: options?.retry, timeout: options?.timeout },\n operation: \"fetch\",\n icon: \"background\",\n noop: false,\n properties: [\n {\n label: \"url\",\n text: url,\n url,\n },\n {\n label: \"method\",\n text: requestInit?.method ?? \"GET\",\n },\n {\n label: \"background\",\n text: \"true\",\n },\n ...(options?.timeout\n ? [{ label: \"timeout\", text: `${options.timeout.durationInMs}ms` }]\n : []),\n ],\n retry: {\n limit: 0,\n },\n }\n )) as TResponseData;\n }\n\n /** `io.backgroundPoll()` will fetch data from a URL on an interval. The actual `fetch` requests are performed on the Trigger.dev server, so you don't have to worry about serverless function timeouts.\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param params The options for the background poll\n * @param params.url The URL to fetch from.\n * @param params.requestInit The options for the request, like headers and method\n * @param params.responseFilter An [EventFilter](https://trigger.dev/docs/documentation/guides/event-filter) that allows you to specify when to stop polling.\n * @param params.interval The interval in seconds to poll the URL in seconds. Defaults to 10 seconds which is the minimum.\n * @param params.timeout The timeout in seconds for each request in seconds. Defaults to 10 minutes. Minimum is 60 seconds and max is 1 hour\n * @param params.requestTimeout An optional object that allows you to timeout individual fetch requests\n * @param params.requestTimeout An optional object that allows you to timeout individual fetch requests\n * @param params.requestTimeout.durationInMs The duration in milliseconds to timeout the request\n * \n * @example\n * ```ts\n * const result = await io.backgroundPoll<{ id: string; status: string; }>(\"poll\", {\n url: `http://localhost:3030/api/v1/runs/${run.id}`,\n requestInit: {\n headers: {\n Accept: \"application/json\",\n Authorization: redactString`Bearer ${process.env[\"TRIGGER_API_KEY\"]!}`,\n },\n },\n interval: 10,\n timeout: 600,\n responseFilter: {\n status: [200],\n body: {\n status: [\"SUCCESS\"],\n },\n },\n });\n * ```\n */\n async backgroundPoll<TResponseData>(\n cacheKey: string | any[],\n params: FetchPollOperation\n ): Promise<TResponseData> {\n const urlObject = new URL(params.url);\n\n return (await this.runTask(\n cacheKey,\n async (task) => {\n return task.output;\n },\n {\n name: `poll ${urlObject.hostname}${urlObject.pathname}`,\n params,\n operation: \"fetch-poll\",\n icon: \"clock-bolt\",\n noop: false,\n properties: [\n {\n label: \"url\",\n text: params.url,\n },\n {\n label: \"interval\",\n text: `${params.interval}s`,\n },\n {\n label: \"timeout\",\n text: `${params.timeout}s`,\n },\n ],\n retry: {\n limit: 0,\n },\n }\n )) as TResponseData;\n }\n\n /** `io.backgroundFetchResponse()` fetches data from a URL that can take longer that the serverless timeout. The actual `fetch` request is performed on the Trigger.dev platform, and the response is sent back to you.\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param url The URL to fetch from.\n * @param requestInit The options for the request\n * @param retry The options for retrying the request if it fails\n * An object where the key is a status code pattern and the value is a retrying strategy.\n * Supported patterns are:\n * - Specific status codes: 429\n * - Ranges: 500-599\n * - Wildcards: 2xx, 3xx, 4xx, 5xx\n */\n async backgroundFetchResponse<TResponseData>(\n cacheKey: string | any[],\n url: string,\n requestInit?: FetchRequestInit,\n options?: {\n retry?: FetchRetryOptions;\n timeout?: FetchTimeoutOptions;\n }\n ): Promise<BackgroundFetchResponse<TResponseData>> {\n const urlObject = new URL(url);\n\n return (await this.runTask(\n cacheKey,\n async (task) => {\n return task.output;\n },\n {\n name: `fetch response ${urlObject.hostname}${urlObject.pathname}`,\n params: { url, requestInit, retry: options?.retry, timeout: options?.timeout },\n operation: \"fetch-response\",\n icon: \"background\",\n noop: false,\n properties: [\n {\n label: \"url\",\n text: url,\n url,\n },\n {\n label: \"method\",\n text: requestInit?.method ?? \"GET\",\n },\n {\n label: \"background\",\n text: \"true\",\n },\n ...(options?.timeout\n ? [{ label: \"timeout\", text: `${options.timeout.durationInMs}ms` }]\n : []),\n ],\n retry: {\n limit: 0,\n },\n }\n )) as BackgroundFetchResponse<TResponseData>;\n }\n\n /** `io.sendEvent()` allows you to send an event from inside a Job run. The sent event will trigger any Jobs that are listening for that event (based on the name).\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param event The event to send. The event name must match the name of the event that your Jobs are listening for.\n * @param options Options for sending the event.\n */\n async sendEvent(cacheKey: string | any[], event: SendEvent, options?: SendEventOptions) {\n return await this.runTask(\n cacheKey,\n async (task) => {\n return await this._triggerClient.sendEvent(event, options);\n },\n {\n name: \"Send Event\",\n params: { event, options },\n icon: \"send\",\n properties: [\n {\n label: \"name\",\n text: event.name,\n },\n ...(event?.id ? [{ label: \"ID\", text: event.id }] : []),\n ...sendEventOptionsProperties(options),\n ],\n }\n );\n }\n\n /** `io.sendEvents()` allows you to send multiple events from inside a Job run. The sent events will trigger any Jobs that are listening for those events (based on the name).\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param event The events to send. The event names must match the names of the events that your Jobs are listening for.\n * @param options Options for sending the events.\n */\n async sendEvents(cacheKey: string | any[], events: SendEvent[], options?: SendEventOptions) {\n return await this.runTask(\n cacheKey,\n async (task) => {\n return await this._triggerClient.sendEvents(events, options);\n },\n {\n name: \"Send Multiple Events\",\n params: { events, options },\n icon: \"send\",\n properties: [\n {\n label: \"Total Events\",\n text: String(events.length),\n },\n ...sendEventOptionsProperties(options),\n ],\n }\n );\n }\n\n async getEvent(cacheKey: string | any[], id: string) {\n return await this.runTask(\n cacheKey,\n async (task) => {\n return await this._triggerClient.getEvent(id);\n },\n {\n name: \"getEvent\",\n params: { id },\n properties: [\n {\n label: \"id\",\n text: id,\n },\n ],\n }\n );\n }\n\n /** `io.cancelEvent()` allows you to cancel an event that was previously sent with `io.sendEvent()`. This will prevent any Jobs from running that are listening for that event if the event was sent with a delay\n * @param cacheKey\n * @param eventId\n * @returns\n */\n async cancelEvent(cacheKey: string | any[], eventId: string) {\n return await this.runTask(\n cacheKey,\n async (task) => {\n return await this._triggerClient.cancelEvent(eventId);\n },\n {\n name: \"cancelEvent\",\n params: {\n eventId,\n },\n properties: [\n {\n label: \"id\",\n text: eventId,\n },\n ],\n }\n );\n }\n\n async updateSource(\n cacheKey: string | any[],\n options: { key: string } & UpdateTriggerSourceBodyV2\n ) {\n return this.runTask(\n cacheKey,\n async (task) => {\n return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);\n },\n {\n name: \"Update Source\",\n description: \"Update Source\",\n properties: [\n {\n label: \"key\",\n text: options.key,\n },\n ],\n params: options,\n redact: {\n paths: [\"secret\"],\n },\n }\n );\n }\n\n async updateWebhook(cacheKey: string | any[], options: { key: string } & UpdateWebhookBody) {\n return this.runTask(\n cacheKey,\n async (task) => {\n return await this._apiClient.updateWebhook(options.key, options);\n },\n {\n name: \"Update Webhook Source\",\n icon: \"refresh\",\n properties: [\n {\n label: \"key\",\n text: options.key,\n },\n ],\n params: options,\n }\n );\n }\n\n /** `io.registerInterval()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular interval.\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n * @param options The options for the interval.\n * @returns A promise that has information about the interval.\n * @deprecated Use `DynamicSchedule.register` instead.\n */\n async registerInterval(\n cacheKey: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: IntervalOptions\n ) {\n return await this.runTask(\n cacheKey,\n async (task) => {\n return dynamicSchedule.register(id, {\n type: \"interval\",\n options,\n });\n },\n {\n name: \"register-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n { label: \"seconds\", text: options.seconds.toString() },\n ],\n params: options,\n }\n );\n }\n\n /** `io.unregisterInterval()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerInterval()`.\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n * @deprecated Use `DynamicSchedule.unregister` instead.\n */\n async unregisterInterval(cacheKey: string | any[], dynamicSchedule: DynamicSchedule, id: string) {\n return await this.runTask(\n cacheKey,\n async (task) => {\n return dynamicSchedule.unregister(id);\n },\n {\n name: \"unregister-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n }\n );\n }\n\n /** `io.registerCron()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular CRON schedule.\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.\n * @param id A unique id for the schedule. This is used to identify and unregister the schedule later.\n * @param options The options for the CRON schedule.\n * @deprecated Use `DynamicSchedule.register` instead.\n */\n async registerCron(\n cacheKey: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: CronOptions\n ) {\n return await this.runTask(\n cacheKey,\n async (task) => {\n return dynamicSchedule.register(id, {\n type: \"cron\",\n options,\n });\n },\n {\n name: \"register-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n { label: \"cron\", text: options.cron },\n ],\n params: options,\n }\n );\n }\n\n /** `io.unregisterCron()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerCron()`.\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n * @deprecated Use `DynamicSchedule.unregister` instead.\n */\n async unregisterCron(cacheKey: string | any[], dynamicSchedule: DynamicSchedule, id: string) {\n return await this.runTask(\n cacheKey,\n async (task) => {\n return dynamicSchedule.unregister(id);\n },\n {\n name: \"unregister-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n }\n );\n }\n\n /** `io.registerTrigger()` allows you to register a [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) with the specified trigger params.\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param trigger The [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) to register.\n * @param id A unique id for the trigger. This is used to identify and unregister the trigger later.\n * @param params The params for the trigger.\n * @deprecated Use `DynamicTrigger.register` instead.\n */\n async registerTrigger<\n TTrigger extends DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>,\n >(\n cacheKey: string | any[],\n trigger: TTrigger,\n id: string,\n params: ExternalSourceParams<TTrigger[\"source\"]>\n ): Promise<{ id: string; key: string } | undefined> {\n return await this.runTask(\n cacheKey,\n async (task) => {\n const registration = await this.runTask(\n \"register-source\",\n async (subtask1) => {\n return trigger.register(id, params);\n },\n {\n name: \"register-source\",\n }\n );\n\n return {\n id: registration.id,\n key: registration.source.key,\n };\n },\n {\n name: \"register-trigger\",\n properties: [\n { label: \"trigger\", text: trigger.id },\n { label: \"id\", text: id },\n ],\n params: params as any,\n }\n );\n }\n\n async getAuth(cacheKey: string | any[], clientId?: string): Promise<ConnectionAuth | undefined> {\n if (!clientId) {\n return;\n }\n\n return this.runTask(\n cacheKey,\n async (task) => {\n return await this._triggerClient.getAuth(clientId);\n },\n { name: \"get-auth\" }\n );\n }\n\n async parallel<T extends Json<T> | void, TItem>(\n cacheKey: string | any[],\n items: Array<TItem>,\n callback: (item: TItem, index: number) => Promise<T>,\n options?: Pick<RunTaskOptions, \"name\" | \"properties\">\n ): Promise<Array<T>> {\n const results = await this.runTask(\n cacheKey,\n async (task) => {\n const outcomes = await Promise.allSettled(\n items.map((item, index) => spaceOut(() => callback(item, index), index, 15))\n );\n\n // If all the outcomes are fulfilled, return the values\n if (outcomes.every((outcome) => outcome.status === \"fulfilled\")) {\n return outcomes.map(\n (outcome) => (outcome as PromiseFulfilledResult<T>).value\n ) as Array<{}>;\n }\n\n // If they any of the errors are non internal errors, throw the first one\n const nonInternalErrors = outcomes\n .filter((outcome) => outcome.status === \"rejected\" && !isTriggerError(outcome.reason))\n .map((outcome) => outcome as PromiseRejectedResult);\n\n if (nonInternalErrors.length > 0) {\n throw nonInternalErrors[0].reason;\n }\n\n // gather all the internal errors\n const internalErrors = outcomes\n .filter((outcome) => outcome.status === \"rejected\" && isTriggerError(outcome.reason))\n .map((outcome) => outcome as PromiseRejectedResult)\n .map((outcome) => outcome.reason as TriggerInternalError);\n\n throw new ResumeWithParallelTaskError(task, internalErrors);\n },\n {\n name: \"parallel\",\n parallel: true,\n ...(options ?? {}),\n }\n );\n\n return results as unknown as Array<T>;\n }\n\n /** `io.runTask()` allows you to run a [Task](https://trigger.dev/docs/documentation/concepts/tasks) from inside a Job run. A Task is a resumable unit of a Run that can be retried, resumed and is logged. [Integrations](https://trigger.dev/docs/integrations) use Tasks internally to perform their actions.\n *\n * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param callback The callback that will be called when the Task is run. The callback receives the Task and the IO as parameters.\n * @param options The options of how you'd like to run and log the Task.\n * @param onError The callback that will be called when the Task fails. The callback receives the error, the Task and the IO as parameters. If you wish to retry then return an object with a `retryAt` property.\n * @returns A Promise that resolves with the returned value of the callback.\n */\n async runTask<T extends Json<T> | void>(\n cacheKey: string | any[],\n callback: (task: ServerTask, io: IO) => Promise<T>,\n options?: RunTaskOptions & { parseOutput?: (output: unknown) => T },\n onError?: RunTaskErrorCallback\n ): Promise<T> {\n const parentId = this._taskStorage.getStore()?.taskId;\n\n if (parentId) {\n this._logger.debug(\"Using parent task\", {\n parentId,\n cacheKey,\n options,\n });\n }\n\n //don't auto-yield if it's a no-op and a subtask (e.g. a log inside a task)\n const isSubtaskNoop = options?.noop === true && parentId !== undefined;\n if (!isSubtaskNoop) {\n this.#detectAutoYield(\"start_task\", 500);\n }\n\n const idempotencyKey = await generateIdempotencyKey(\n [this._id, parentId ?? \"\", cacheKey].flat()\n );\n\n if (this._visitedCacheKeys.has(idempotencyKey)) {\n if (typeof cacheKey === \"string\") {\n throw new Error(\n `Task with cacheKey \"${cacheKey}\" has already been executed in this run. Each task must have a unique cacheKey.`\n );\n } else {\n throw new Error(\n `Task with cacheKey \"${cacheKey.join(\n \"-\"\n )}\" has already been executed in this run. Each task must have a unique cacheKey.`\n );\n }\n }\n\n this._visitedCacheKeys.add(idempotencyKey);\n\n const cachedTask = this._cachedTasks.get(idempotencyKey);\n\n if (cachedTask && cachedTask.status === \"COMPLETED\") {\n this._logger.debug(\"Using completed cached task\", {\n idempotencyKey,\n });\n\n this._stats.cachedTaskHits++;\n\n return options?.parseOutput\n ? options.parseOutput(cachedTask.output)\n : (cachedTask.output as T);\n }\n\n if (options?.noop && this._noopTasksBloomFilter) {\n if (this._noopTasksBloomFilter.test(idempotencyKey)) {\n this._logger.debug(\"task idempotency key exists in noopTasksBloomFilter\", {\n idempotencyKey,\n });\n\n this._stats.noopCachedTaskHits++;\n\n return {} as T;\n }\n }\n\n const runOptions = { ...(options ?? {}), parseOutput: undefined };\n\n const response = await this._apiClient.runTask(\n this._id,\n {\n idempotencyKey,\n displayKey: typeof cacheKey === \"string\" ? cacheKey : undefined,\n noop: false,\n ...(runOptions ?? {}),\n parentId,\n },\n {\n cachedTasksCursor: this._cachedTasksCursor,\n }\n );\n\n const task =\n response.version === API_VERSIONS.LAZY_LOADED_CACHED_TASKS\n ? response.body.task\n : response.body;\n\n if (task.forceYield) {\n this._logger.debug(\"Forcing yield after run task\", {\n idempotencyKey,\n });\n\n this.#forceYield(\"after_run_task\");\n }\n\n if (response.version === API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {\n this._cachedTasksCursor = response.body.cachedTasks?.cursor;\n\n for (const cachedTask of response.body.cachedTasks?.tasks ?? []) {\n if (!this._cachedTasks.has(cachedTask.idempotencyKey)) {\n this._cachedTasks.set(cachedTask.idempotencyKey, cachedTask);\n\n this._logger.debug(\"Injecting lazy loaded task into task cache\", {\n idempotencyKey: cachedTask.idempotencyKey,\n });\n\n this._stats.lazyLoadedCachedTasks++;\n }\n }\n }\n\n if (task.status === \"CANCELED\") {\n this._logger.debug(\"Task canceled\", {\n idempotencyKey,\n task,\n });\n\n throw new CanceledWithTaskError(task);\n }\n\n if (task.status === \"COMPLETED\") {\n if (task.noop) {\n this._logger.debug(\"Noop Task completed\", {\n idempotencyKey,\n });\n\n this._noopTasksBloomFilter?.add(task.idempotencyKey);\n } else {\n this._logger.debug(\"Cache miss\", {\n idempotencyKey,\n });\n\n this._stats.cachedTaskMisses++;\n this.#addToCachedTasks(task);\n }\n\n return options?.parseOutput ? options.parseOutput(task.output) : (task.output as T);\n }\n\n if (task.status === \"ERRORED\") {\n this._logger.debug(\"Task errored\", {\n idempotencyKey,\n task,\n });\n\n throw new ErrorWithTask(\n task,\n task.error ?? task?.output ? JSON.stringify(task.output) : \"Task errored\"\n );\n }\n\n this.#detectAutoYield(\"before_execute_task\", 1500);\n\n const executeTask = async () => {\n try {\n const result = await callback(task, this);\n\n if (task.status === \"WAITING\" && task.callbackUrl) {\n this._logger.debug(\"Waiting for remote callback\", {\n idempotencyKey,\n task,\n });\n return {} as T;\n }\n\n const output = this._outputSerializer.serialize(result);\n\n this._logger.debug(\"Completing using output\", {\n idempotencyKey,\n task,\n });\n\n this.#detectAutoYield(\"before_complete_task\", 500, task, output);\n\n const completedTask = await this._apiClient.completeTask(this._id, task.id, {\n output,\n properties: task.outputProperties ?? undefined,\n });\n\n if (completedTask.forceYield) {\n this._logger.debug(\"Forcing yield after task completed\", {\n idempotencyKey,\n });\n\n this.#forceYield(\"after_complete_task\");\n }\n\n this._stats.executedTasks++;\n\n if (completedTask.status === \"CANCELED\") {\n throw new CanceledWithTaskError(completedTask);\n }\n\n this.#detectAutoYield(\"after_complete_task\", 500);\n\n const deserializedOutput = this._outputSerializer.deserialize<T>(output);\n\n return options?.parseOutput ? options.parseOutput(deserializedOutput) : deserializedOutput;\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n let skipRetrying = false;\n\n if (onError) {\n try {\n const onErrorResult = onError(error, task, this);\n\n if (onErrorResult) {\n if (onErrorResult instanceof Error) {\n error = onErrorResult;\n } else {\n skipRetrying = !!onErrorResult.skipRetrying;\n\n if (onErrorResult.retryAt && !skipRetrying) {\n const parsedError = ErrorWithStackSchema.safeParse(onErrorResult.error);\n\n throw new RetryWithTaskError(\n parsedError.success ? parsedError.data : { message: \"Unknown error\" },\n task,\n onErrorResult.retryAt\n );\n }\n }\n }\n } catch (innerError) {\n if (isTriggerError(innerError)) {\n throw innerError;\n }\n\n error = innerError;\n }\n }\n\n if (error instanceof ErrorWithTask) {\n // This means a subtask errored, so we need to update the parent task and not retry it\n await this._apiClient.failTask(this._id, task.id, {\n error: error.cause.output as any,\n });\n\n throw error;\n }\n\n const parsedError = ErrorWithStackSchema.safeParse(error);\n\n if (options?.retry && !skipRetrying) {\n const retryAt = calculateRetryAt(options.retry, task.attempts - 1);\n\n if (retryAt) {\n throw new RetryWithTaskError(\n parsedError.success ? parsedError.data : { message: \"Unknown error\" },\n task,\n retryAt\n );\n }\n }\n\n if (parsedError.success) {\n await this._apiClient.failTask(this._id, task.id, {\n error: parsedError.data,\n });\n } else {\n const message = typeof error === \"string\" ? error : JSON.stringify(error);\n await this._apiClient.failTask(this._id, task.id, {\n error: { name: \"Unknown error\", message },\n });\n }\n\n throw error;\n }\n };\n\n if (task.status === \"WAITING\") {\n this._logger.debug(\"Task waiting\", {\n idempotencyKey,\n task,\n });\n\n if (task.callbackUrl) {\n await this._taskStorage.run({ taskId: task.id }, executeTask);\n }\n\n throw new ResumeWithTaskError(task);\n }\n\n if (task.status === \"RUNNING\" && typeof task.operation === \"string\") {\n this._logger.debug(\"Task running operation\", {\n idempotencyKey,\n task,\n });\n\n throw new ResumeWithTaskError(task);\n }\n\n return this._taskStorage.run({ taskId: task.id }, executeTask);\n }\n\n /**\n * `io.yield()` allows you to yield execution of the current run and resume it in a new function execution. Similar to `io.wait()` but does not create a task and resumes execution immediately.\n */\n yield(cacheKey: string) {\n if (!supportsFeature(\"yieldExecution\", this._serverVersion)) {\n console.warn(\n \"[trigger.dev] io.yield() is not support by the version of the Trigger.dev server you are using, you will need to upgrade your self-hosted Trigger.dev instance.\"\n );\n\n return;\n }\n\n if (this._yieldedExecutions.includes(cacheKey)) {\n return;\n }\n\n throw new YieldExecutionError(cacheKey);\n }\n\n /**\n * `io.brb()` is an alias of `io.yield()`\n */\n brb = this.yield.bind(this);\n\n /** `io.try()` allows you to run Tasks and catch any errors that are thrown, it's similar to a normal `try/catch` block but works with [io.runTask()](https://trigger.dev/docs/sdk/io/runtask).\n * A regular `try/catch` block on its own won't work as expected with Tasks. Internally `runTask()` throws some special errors to control flow execution. This is necessary to deal with resumability, serverless timeouts, and retrying Tasks.\n * @param tryCallback The code you wish to run\n * @param catchCallback Thhis will be called if the Task fails. The callback receives the error\n * @returns A Promise that resolves with the returned value or the error\n */\n async try<TResult, TCatchResult>(\n tryCallback: () => Promise<TResult>,\n catchCallback: (error: unknown) => Promise<TCatchResult>\n ): Promise<TResult | TCatchResult> {\n try {\n return await tryCallback();\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n return await catchCallback(error);\n }\n }\n\n get store() {\n return {\n env: this._envStore,\n job: this._jobStore,\n run: this._runStore,\n };\n }\n\n #addToCachedTasks(task: ServerTask) {\n this._cachedTasks.set(task.idempotencyKey, task);\n }\n\n #detectAutoYield(location: string, threshold: number = 1500, task?: ServerTask, output?: string) {\n const timeRemaining = this.#getRemainingTimeInMillis();\n\n if (timeRemaining && timeRemaining < threshold) {\n if (task) {\n throw new AutoYieldWithCompletedTaskExecutionError(\n task.id,\n task.outputProperties ?? [],\n {\n location,\n timeRemaining,\n timeElapsed: this.#getTimeElapsed(),\n },\n output\n );\n } else {\n throw new AutoYieldExecutionError(location, timeRemaining, this.#getTimeElapsed());\n }\n }\n }\n\n #forceYield(location: string) {\n const timeRemaining = this.#getRemainingTimeInMillis();\n\n if (timeRemaining) {\n throw new AutoYieldExecutionError(location, timeRemaining, this.#getTimeElapsed());\n }\n }\n\n #getTimeElapsed() {\n return performance.now() - this._timeOrigin;\n }\n\n #getRemainingTimeInMillis() {\n if (this._executionTimeout) {\n return this._executionTimeout - (performance.now() - this._timeOrigin);\n }\n\n return undefined;\n }\n}\n\n// Generate a stable idempotency key for the key material, using a stable json stringification\nasync function generateIdempotencyKey(keyMaterial: any[]) {\n const keys = keyMaterial.map((key) => {\n if (typeof key === \"string\") {\n return key;\n }\n\n return stableStringify(key);\n });\n\n const key = keys.join(\":\");\n\n const hash = await webcrypto.subtle.digest(\"SHA-256\", Buffer.from(key));\n\n return Buffer.from(hash).toString(\"hex\");\n}\n\nfunction stableStringify(obj: any): string {\n function sortKeys(obj: any): any {\n if (typeof obj !== \"object\" || obj === null) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortKeys);\n }\n\n const sortedKeys = Object.keys(obj).sort();\n const sortedObj: { [key: string]: any } = {};\n\n for (const key of sortedKeys) {\n sortedObj[key] = sortKeys(obj[key]);\n }\n\n return sortedObj;\n }\n\n const sortedObj = sortKeys(obj);\n return JSON.stringify(sortedObj);\n}\n\ntype CallbackFunction = (\n level: \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"LOG\",\n message: string,\n properties?: Record<string, any>\n) => Promise<void>;\n\nexport class IOLogger implements TaskLogger {\n constructor(private callback: CallbackFunction) {}\n\n /** Log: essential messages */\n log(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"LOG\", message, properties);\n }\n\n /** For debugging: the least important log level */\n debug(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"DEBUG\", message, properties);\n }\n\n /** Info: the second least important log level */\n info(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"INFO\", message, properties);\n }\n\n /** Warnings: the third most important log level */\n warn(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"WARN\", message, properties);\n }\n\n /** Error: The second most important log level */\n error(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"ERROR\", message, properties);\n }\n}\n\n// Space out the execution of the callback by a delay of index * delay\nasync function spaceOut<T>(callback: () => Promise<T>, index: number, delay: number): Promise<T> {\n await new Promise((resolve) => setTimeout(resolve, index * delay));\n\n return await callback();\n}\n\nfunction sendEventOptionsProperties(options?: SendEventOptions) {\n return [\n ...(options?.accountId ? [{ label: \"Account ID\", text: options.accountId }] : []),\n ...(options?.deliverAfter\n ? [{ label: \"Deliver After\", text: `${options.deliverAfter}s` }]\n : []),\n ...(options?.deliverAt ? [{ label: \"Deliver At\", text: options.deliverAt.toISOString() }] : []),\n ];\n}\n","import { DisplayProperty } from \"@trigger.dev/core\";\nimport { ErrorWithStack, SchemaError, ServerTask } from \"@trigger.dev/core\";\n\nexport class ResumeWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\nexport class ResumeWithParallelTaskError {\n constructor(\n public task: ServerTask,\n public childErrors: Array<TriggerInternalError>\n ) {}\n}\n\nexport class RetryWithTaskError {\n constructor(\n public cause: ErrorWithStack,\n public task: ServerTask,\n public retryAt: Date\n ) {}\n}\n\nexport class CanceledWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\nexport class YieldExecutionError {\n constructor(public key: string) {}\n}\n\nexport class AutoYieldExecutionError {\n constructor(\n public location: string,\n public timeRemaining: number,\n public timeElapsed: number\n ) {}\n}\n\nexport class AutoYieldWithCompletedTaskExecutionError {\n constructor(\n public id: string,\n public properties: DisplayProperty[] | undefined,\n public data: { location: string; timeRemaining: number; timeElapsed: number },\n public output?: string\n ) {}\n}\n\nexport class ParsedPayloadSchemaError {\n constructor(public schemaErrors: SchemaError[]) {}\n}\n\nexport type TriggerInternalError =\n | ResumeWithTaskError\n | RetryWithTaskError\n | CanceledWithTaskError\n | YieldExecutionError\n | AutoYieldExecutionError\n | AutoYieldWithCompletedTaskExecutionError\n | ResumeWithParallelTaskError;\n\n/** Use this function if you're using a `try/catch` block to catch errors.\n * It checks if a thrown error is a special internal error that you should ignore.\n * If this returns `true` then you must rethrow the error: `throw err;`\n * @param err The error to check\n * @returns `true` if the error is a Trigger Error, `false` otherwise.\n */\nexport function isTriggerError(err: unknown): err is TriggerInternalError {\n return (\n err instanceof ResumeWithTaskError ||\n err instanceof RetryWithTaskError ||\n err instanceof CanceledWithTaskError ||\n err instanceof YieldExecutionError ||\n err instanceof AutoYieldExecutionError ||\n err instanceof AutoYieldWithCompletedTaskExecutionError ||\n err instanceof ResumeWithParallelTaskError\n );\n}\n\n// This error isn't an internal error but it can be used by the user to figure out which task caused the error\nexport class ErrorWithTask extends Error {\n constructor(\n public cause: ServerTask,\n message: string\n ) {\n super(message);\n }\n}\n","import type { RetryOptions } from \"@trigger.dev/core\";\nimport { calculateRetryAt } from \"@trigger.dev/core\";\n\nexport { calculateRetryAt };\nexport type { RetryOptions };\n\nexport const retry = {\n standardBackoff: {\n limit: 8,\n factor: 1.8,\n minTimeoutInMs: 500,\n maxTimeoutInMs: 30000,\n randomize: true,\n },\n exponentialBackoff: {\n limit: 8,\n factor: 2,\n minTimeoutInMs: 1000,\n maxTimeoutInMs: 30000,\n randomize: true,\n },\n} as const satisfies Record<string, RetryOptions>;\n","import { DisplayProperty, StatusUpdate } from \"@trigger.dev/core\";\nimport { IntegrationTaskKey } from \"./integrations\";\nimport { IO } from \"./io\";\n\nexport class TriggerStatus {\n constructor(\n private id: string,\n private io: IO\n ) {}\n\n async update(key: IntegrationTaskKey, status: StatusUpdate) {\n const properties: DisplayProperty[] = [];\n\n if (status.label) {\n properties.push({\n label: \"Label\",\n text: status.label,\n });\n }\n\n if (status.state) {\n properties.push({\n label: \"State\",\n text: status.state,\n });\n }\n\n return await this.io.runTask(\n key,\n async (task) => {\n return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);\n },\n {\n name: status.label ?? `Status update`,\n icon: \"bell\",\n params: {\n ...status,\n },\n properties,\n }\n );\n }\n}\n","import type {\n DisplayProperty,\n EventFilter,\n FailedRunNotification,\n OverridableRunTaskOptions,\n Prettify,\n RedactString,\n RegisteredOptionsDiff,\n RunTaskOptions,\n RuntimeEnvironmentType,\n SourceEventOption,\n SuccessfulRunNotification,\n TriggerMetadata,\n} from \"@trigger.dev/core\";\nimport { Logger } from \"@trigger.dev/core-backend\";\nimport type TypedEmitter from \"typed-emitter\";\nimport { z } from \"zod\";\nimport { Job } from \"./job\";\nimport { TriggerClient } from \"./triggerClient\";\n\nexport type {\n DisplayProperty,\n Logger,\n OverridableRunTaskOptions,\n Prettify,\n RedactString,\n RegisteredOptionsDiff,\n RunTaskOptions,\n SourceEventOption,\n};\n\nexport interface TriggerContext {\n /** Job metadata */\n job: { id: string; version: string };\n /** Environment metadata */\n environment: { slug: string; id: string; type: RuntimeEnvironmentType };\n /** Organization metadata */\n organization: { slug: string; id: string; title: string };\n /** Project metadata */\n project: { slug: string; id: string; name: string };\n /** Run metadata */\n run: { id: string; isTest: boolean; startedAt: Date; isRetry: boolean };\n /** Event metadata */\n event: { id: string; name: string; context: any; timestamp: Date };\n /** Source metadata */\n source?: { id: string; metadata?: any };\n /** Account metadata */\n account?: { id: string; metadata?: any };\n}\n\nexport interface TriggerPreprocessContext {\n job: { id: string; version: string };\n environment: { slug: string; id: string; type: RuntimeEnvironmentType };\n organization: { slug: string; id: string; title: string };\n run: { id: string; isTest: boolean };\n event: { id: string; name: string; context: any; timestamp: Date };\n account?: { id: string; metadata?: any };\n}\n\nexport interface TaskLogger {\n debug(message: string, properties?: Record<string, any>): Promise<void>;\n info(message: string, properties?: Record<string, any>): Promise<void>;\n warn(message: string, properties?: Record<string, any>): Promise<void>;\n error(message: string, properties?: Record<string, any>): Promise<void>;\n}\n\nexport type PreprocessResults = {\n abort: boolean;\n properties: DisplayProperty[];\n};\n\nexport type TriggerEventType<TTrigger extends Trigger<any>> = TTrigger extends Trigger<\n infer TEventSpec\n>\n ? ReturnType<TEventSpec[\"parsePayload\"]>\n : never;\n\nexport type TriggerInvokeType<TTrigger extends Trigger<any>> = TTrigger extends Trigger<\n EventSpecification<any, infer TInvoke>\n>\n ? TInvoke\n : any;\n\nexport type VerifyResult =\n | {\n success: true;\n }\n | {\n success: false;\n reason?: string;\n };\n\nexport interface Trigger<TEventSpec extends EventSpecification<any>> {\n event: TEventSpec;\n toJSON(): TriggerMetadata;\n // Attach this trigger to the job and the trigger client\n // Gives different triggers the ability to do things like register internal jobs\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpec>, any>): void;\n\n preprocessRuns: boolean;\n\n verifyPayload: (payload: ReturnType<TEventSpec[\"parsePayload\"]>) => Promise<VerifyResult>;\n}\n\nexport type TriggerPayload<TTrigger> = TTrigger extends Trigger<EventSpecification<infer TEvent>>\n ? TEvent\n : never;\n\nexport const EventSpecificationExampleSchema = z.object({\n id: z.string(),\n name: z.string(),\n icon: z.string().optional(),\n payload: z.any(),\n});\n\nexport type EventSpecificationExample = z.infer<typeof EventSpecificationExampleSchema>;\n\nexport type TypedEventSpecificationExample<TEvent> = {\n id: string;\n name: string;\n icon?: string;\n payload: TEvent;\n};\n\nexport interface EventSpecification<TEvent extends any, TInvoke extends any = TEvent> {\n name: string | string[];\n title: string;\n source: string;\n icon: string;\n properties?: DisplayProperty[];\n schema?: any;\n examples?: Array<EventSpecificationExample>;\n filter?: EventFilter;\n parsePayload: (payload: unknown) => TEvent;\n parseInvokePayload?: (payload: unknown) => TInvoke;\n runProperties?: (payload: TEvent) => DisplayProperty[];\n}\n\nexport type EventTypeFromSpecification<TEventSpec extends EventSpecification<any>> =\n TEventSpec extends EventSpecification<infer TEvent> ? TEvent : never;\n\nexport type SchemaParserIssue = { path: PropertyKey[]; message: string };\n\nexport type SchemaParserResult<T> =\n | {\n success: true;\n data: T;\n }\n | { success: false; error: { issues: SchemaParserIssue[] } };\n\nexport type SchemaParser<T extends unknown = unknown> = {\n safeParse: (a: unknown) => SchemaParserResult<T>;\n};\n\nexport type WaitForEventResult<TEvent> = {\n id: string;\n name: string;\n source: string;\n payload: TEvent;\n timestamp: Date;\n context?: any;\n accountId?: string;\n};\n\nexport function waitForEventSchema(schema: z.ZodTypeAny) {\n return z.object({\n id: z.string(),\n name: z.string(),\n source: z.string(),\n payload: schema,\n timestamp: z.coerce.date(),\n context: z.any().optional(),\n accountId: z.string().optional(),\n });\n}\n\nexport type NotificationEvents = {\n runSucceeeded: (notification: SuccessfulRunNotification<any>) => void;\n runFailed: (notification: FailedRunNotification) => void;\n};\n\nexport type NotificationsEventEmitter = TypedEmitter<NotificationEvents>;\n","import { ApiClient } from \"../apiClient\";\nimport { Json } from \"../io\";\nimport { runLocalStorage } from \"../runLocalStorage\";\n\nexport class KeyValueStore {\n constructor(\n private apiClient: ApiClient,\n private type: string | null = null,\n private namespace: string = \"\"\n ) {}\n\n #namespacedKey(key: string) {\n const parts = [];\n\n if (this.type) {\n parts.push(this.type);\n }\n\n if (this.namespace) {\n parts.push(this.namespace);\n }\n\n parts.push(key);\n\n return parts.join(\":\");\n }\n\n #sharedProperties(key: string) {\n return [\n {\n label: \"namespace\",\n text: this.type ?? \"env\",\n },\n {\n label: \"key\",\n text: key,\n },\n ];\n }\n\n async delete(cacheKey: string | any[], key: string): Promise<boolean>;\n async delete(key: string): Promise<boolean>;\n async delete(param1: string | any[], param2?: string): Promise<boolean> {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n if (typeof param1 !== \"string\") {\n throw new Error(\n \"Please use the store without a cacheKey when accessing from outside a run.\"\n );\n }\n\n return await this.apiClient.store.delete(this.#namespacedKey(param1));\n }\n\n const { io } = runStore;\n\n if (!param2) {\n throw new Error(\"Please provide a non-empty key when accessing the store from inside a run.\");\n }\n\n return await io.runTask(\n param1,\n async (task) => {\n return await this.apiClient.store.delete(this.#namespacedKey(param2));\n },\n {\n name: \"Key-Value Store Delete\",\n icon: \"database-minus\",\n params: { key: param2 },\n properties: this.#sharedProperties(param2),\n style: { style: \"minimal\" },\n }\n );\n }\n\n async get<T extends Json<T> = any>(cacheKey: string | any[], key: string): Promise<T | undefined>;\n async get<T extends Json<T> = any>(key: string): Promise<T | undefined>;\n async get<T extends Json<T> = any>(\n param1: string | any[],\n param2?: string\n ): Promise<T | undefined> {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n if (typeof param1 !== \"string\") {\n throw new Error(\n \"Please use the store without a cacheKey when accessing from outside a run.\"\n );\n }\n\n return await this.apiClient.store.get(this.#namespacedKey(param1));\n }\n\n const { io } = runStore;\n\n if (!param2) {\n throw new Error(\"Please provide a non-empty key when accessing the store from inside a run.\");\n }\n\n return await io.runTask(\n param1,\n async (task) => {\n return await this.apiClient.store.get(this.#namespacedKey(param2));\n },\n {\n name: \"Key-Value Store Get\",\n icon: \"database-export\",\n params: { key: param2 },\n properties: this.#sharedProperties(param2),\n style: { style: \"minimal\" },\n }\n );\n }\n\n async has(cacheKey: string | any[], key: string): Promise<boolean>;\n async has(key: string): Promise<boolean>;\n async has(param1: string | any[], param2?: string): Promise<boolean> {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n if (typeof param1 !== \"string\") {\n throw new Error(\n \"Please use the store without a cacheKey when accessing from outside a run.\"\n );\n }\n\n return await this.apiClient.store.has(this.#namespacedKey(param1));\n }\n\n const { io } = runStore;\n\n if (!param2) {\n throw new Error(\"Please provide a non-empty key when accessing the store from inside a run.\");\n }\n\n return await io.runTask(\n param1,\n async (task) => {\n return await this.apiClient.store.has(this.#namespacedKey(param2));\n },\n {\n name: \"Key-Value Store Has\",\n icon: \"database-search\",\n params: { key: param2 },\n properties: this.#sharedProperties(param2),\n style: { style: \"minimal\" },\n }\n );\n }\n\n async set<T extends Json<T>>(cacheKey: string | any[], key: string, value: T): Promise<T>;\n async set<T extends Json<T>>(key: string, value: T): Promise<T>;\n async set<T extends Json<T>>(param1: string | any[], param2: string | T, param3?: T): Promise<T> {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n if (typeof param1 !== \"string\") {\n throw new Error(\n \"Please use the store without a cacheKey when accessing from outside a run.\"\n );\n }\n\n return await this.apiClient.store.set(this.#namespacedKey(param1), param2 as T);\n }\n\n const { io } = runStore;\n\n if (!param2 || typeof param2 !== \"string\") {\n throw new Error(\"Please provide a non-empty key when accessing the store from inside a run.\");\n }\n\n const value = param3 as T;\n\n return await io.runTask(\n param1,\n async (task) => {\n return await this.apiClient.store.set(this.#namespacedKey(param2), value);\n },\n {\n name: \"Key-Value Store Set\",\n icon: \"database-plus\",\n params: { key: param2, value },\n properties: [\n ...this.#sharedProperties(param2),\n ...(typeof value !== \"object\" || value === null\n ? [\n {\n label: \"value\",\n text: String(value) ?? \"undefined\",\n },\n ]\n : []),\n ],\n style: { style: \"minimal\" },\n }\n );\n }\n}\n","import { AsyncMap } from \"@trigger.dev/core\";\nimport { KeyValueStoreResponseBody } from \"@trigger.dev/core\";\nimport { JSONOutputSerializer, Json } from \"../io\";\n\ntype QueryKeyValueStoreFunction = (\n action: \"DELETE\" | \"GET\" | \"HAS\" | \"SET\",\n data: {\n key: string;\n value?: string;\n }\n) => Promise<KeyValueStoreResponseBody>;\n\nexport class KeyValueStoreClient implements AsyncMap {\n #serializer = new JSONOutputSerializer();\n\n constructor(\n private queryStore: QueryKeyValueStoreFunction,\n private type: string | null = null,\n private namespace: string = \"\"\n ) {}\n\n #namespacedKey(key: string) {\n const parts = [];\n\n if (this.type) {\n parts.push(this.type);\n }\n\n if (this.namespace) {\n parts.push(this.namespace);\n }\n\n parts.push(key);\n\n return parts.join(\":\");\n }\n\n async delete(key: string): Promise<boolean> {\n const result = await this.queryStore(\"DELETE\", {\n key: this.#namespacedKey(key),\n });\n\n if (result.action !== \"DELETE\") {\n throw new Error(`Unexpected key-value store response: ${result.action}`);\n }\n\n return result.deleted;\n }\n\n async get<T extends Json<T>>(key: string): Promise<T | undefined> {\n const result = await this.queryStore(\"GET\", {\n key: this.#namespacedKey(key),\n });\n\n if (result.action !== \"GET\") {\n throw new Error(`Unexpected key-value store response: ${result.action}`);\n }\n\n return this.#serializer.deserialize(result.value);\n }\n\n async has(key: string): Promise<boolean> {\n const result = await this.queryStore(\"HAS\", {\n key: this.#namespacedKey(key),\n });\n\n if (result.action !== \"HAS\") {\n throw new Error(`Unexpected key-value store response: ${result.action}`);\n }\n\n return result.has;\n }\n\n async set<T extends Json<T>>(key: string, value: T): Promise<T> {\n const result = await this.queryStore(\"SET\", {\n key: this.#namespacedKey(key),\n value: this.#serializer.serialize(value),\n });\n\n if (result.action !== \"SET\") {\n throw new Error(`Unexpected key-value store response: ${result.action}`);\n }\n\n return this.#serializer.deserialize(result.value);\n }\n}\n","export type ConcurrencyLimitOptions = {\n id: string;\n limit: number;\n};\n\nexport class ConcurrencyLimit {\n constructor(private options: ConcurrencyLimitOptions) {}\n\n get id() {\n return this.options.id;\n }\n\n get limit() {\n return this.options.limit;\n }\n}\n","import {\n DisplayProperty,\n EventFilter,\n HttpEndpointMetadata,\n RequestFilter,\n RequestWithRawBodySchema,\n TriggerMetadata,\n} from \"@trigger.dev/core\";\nimport { ParsedPayloadSchemaError } from \"./errors\";\nimport { Job } from \"./job\";\nimport { TriggerClient } from \"./triggerClient\";\nimport { EventSpecification, EventSpecificationExample, Trigger, VerifyResult } from \"./types\";\nimport { formatSchemaErrors } from \"./utils/formatSchemaErrors\";\nimport { slugifyId } from \"./utils\";\n\ntype HttpEndpointOptions<TEventSpecification extends EventSpecification<any>> = {\n id: string;\n enabled?: boolean;\n event: TEventSpecification;\n respondWith?: RespondWith;\n verify: VerifyCallback;\n};\n\nexport type RequestOptions = {\n filter?: RequestFilter;\n};\n\nexport class HttpEndpoint<TEventSpecification extends EventSpecification<any>> {\n constructor(private readonly options: HttpEndpointOptions<TEventSpecification>) {}\n\n get id() {\n return this.options.id;\n }\n\n onRequest(options?: RequestOptions): HttpTrigger<EventSpecification<Request>> {\n return new HttpTrigger({\n endpointId: this.id,\n event: this.options.event,\n filter: options?.filter,\n verify: this.options.verify,\n });\n }\n\n // @internal\n async handleRequest(request: Request): Promise<Response | undefined> {\n if (!this.options.respondWith) return;\n return this.options.respondWith.handler(request, () => {\n const clonedRequest = request.clone();\n return this.options.verify(clonedRequest);\n });\n }\n\n toJSON(): HttpEndpointMetadata {\n return {\n id: this.id,\n icon: this.options.event.icon,\n version: \"1\",\n enabled: this.options.enabled ?? true,\n event: this.options.event,\n immediateResponseFilter: this.options.respondWith?.filter,\n skipTriggeringRuns: this.options.respondWith?.skipTriggeringRuns,\n source: this.options.event.source,\n };\n }\n}\n\ntype TriggerOptions<TEventSpecification extends EventSpecification<any>> = {\n endpointId: string;\n event: TEventSpecification;\n filter?: EventFilter;\n verify: VerifyCallback;\n};\n\nclass HttpTrigger<TEventSpecification extends EventSpecification<any>>\n implements Trigger<TEventSpecification>\n{\n constructor(private readonly options: TriggerOptions<TEventSpecification>) {}\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.options.endpointId,\n properties: this.options.event.properties,\n rule: {\n event: `httpendpoint.${this.options.endpointId}`,\n payload: this.options.filter ?? {},\n source: this.options.event.source,\n },\n link: `http-endpoints/${this.options.endpointId}`,\n help: {\n noRuns: {\n text: \"To start triggering runs click here to setup your HTTP Endpoint with the external API service you want to receive webhooks from.\",\n link: `http-endpoints/${this.options.endpointId}`,\n },\n },\n };\n }\n\n get event() {\n return this.options.event;\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n async verifyPayload(payload: Request) {\n const clonedRequest = payload.clone();\n return this.options.verify(clonedRequest);\n }\n}\n\ntype RespondWith = {\n /** Only Requests that match this filter will cause the `handler` function to run.\n * For example, you can use this to only respond to `GET` Requests. */\n filter?: RequestFilter;\n /** If you set this to `true`, the Request that comes in won't go on to Trigger any Runs.\n * This is useful if you want to Respond to the Request, but don't want to Trigger any Runs. */\n skipTriggeringRuns?: boolean;\n /** This is a function that's called when a Request comes in.\n * It's passed the Request object, and expects you to return a Response object. */\n handler: (request: Request, verify: () => Promise<VerifyResult>) => Promise<Response>;\n};\n\nexport type VerifyCallback = (request: Request) => Promise<VerifyResult>;\n\nexport type EndpointOptions = {\n /** Used to uniquely identify the HTTP Endpoint inside your Project. */\n id: string;\n enabled?: boolean;\n /** Usually you would use the domain name of the service, e.g. `cal.com`. */\n source: string;\n /** An optional title, displayed in the dashboard. */\n title?: string;\n /** An optional icon name that's displayed in the dashboard.\n * Lots of company names are supported, e.g. `github`, `twilio`.\n * You can also reference the name of any [Tabler icon](https://tabler-icons.io/), e.g. `brand-google-maps`, `brand-twitch`. */\n icon?: string;\n /** Used to provide example payloads that are accepted by the job.\n * This will be available in the dashboard and can be used to trigger test runs. */\n examples?: EventSpecificationExample[];\n /** Properties that are displayed in the dashboard. */\n properties?: DisplayProperty[];\n /** This optional object allows you to immediately Respond to a Request. This is useful for some APIs where they do a `GET` Request when the webhook is first setup and expect a specific Response.\n\n Only use this if you really need to Respond to the Request that comes in. Most of the time you don't. */\n respondWith?: RespondWith;\n /** This is compulsory, and is used to verify that the received webhook is authentic.\n * It's a function that expects you to return a result object like:\n \n In 90% of cases, you'll want to use the `verifyRequestSignature` helper function we provide.\n\n @example\n ```ts\n //if it's valid\n return { success: true }\n //if it's invalid, reason is optional\n return { success: false, reason: \"No header\" }\n ```\n\n */\n verify: VerifyCallback;\n};\n\nexport function httpEndpoint(options: EndpointOptions): HttpEndpoint<EventSpecification<Request>> {\n const id = slugifyId(options.id);\n\n return new HttpEndpoint({\n id,\n enabled: options.enabled,\n respondWith: options.respondWith,\n verify: options.verify,\n event: {\n name: id,\n title: options.title ?? \"HTTP Trigger\",\n source: options.source,\n icon: options.icon ?? \"webhook\",\n properties: options.properties,\n examples: options.examples\n ? options.examples\n : [\n {\n id: \"basic-request\",\n name: \"Basic Request\",\n icon: \"http-post\",\n payload: {\n url: \"https://cloud.trigger.dev\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n rawBody: JSON.stringify({\n foo: \"bar\",\n }),\n },\n },\n ],\n parsePayload: (rawPayload: any) => {\n const result = RequestWithRawBodySchema.safeParse(rawPayload);\n\n if (!result.success) {\n throw new ParsedPayloadSchemaError(formatSchemaErrors(result.error.issues));\n }\n\n return new Request(new URL(result.data.url), {\n method: result.data.method,\n headers: result.data.headers,\n body: result.data.rawBody,\n });\n },\n },\n });\n}\n","import type { SchemaError } from \"@trigger.dev/core\";\nimport { SchemaParserIssue } from \"../types\";\n\nexport function formatSchemaErrors(errors: SchemaParserIssue[]): SchemaError[] {\n return errors.map((error) => {\n const { path, message } = error;\n return { path: path.map(String), message };\n });\n}\n","import { ConnectionAuth } from \"@trigger.dev/core\";\nimport { IOWithIntegrations, TriggerIntegration } from \"./integrations\";\nimport { IO } from \"./io\";\n\nexport function createIOWithIntegrations<TIntegrations extends Record<string, TriggerIntegration>>(\n io: IO,\n auths?: Record<string, ConnectionAuth | undefined>,\n integrations?: TIntegrations\n): IOWithIntegrations<TIntegrations> {\n if (!integrations) {\n return io as IOWithIntegrations<TIntegrations>;\n }\n\n const connections = Object.entries(integrations).reduce(\n (acc, [connectionKey, integration]) => {\n let auth = auths?.[connectionKey];\n\n acc[connectionKey] = {\n integration,\n auth,\n };\n\n return acc;\n },\n {} as Record<\n string,\n {\n integration: TriggerIntegration;\n auth?: ConnectionAuth;\n }\n >\n );\n\n return new Proxy(io, {\n get(target, prop, receiver) {\n // We can return the original io back if the prop is __io\n if (prop === \"__io\") {\n return io;\n }\n\n if (typeof prop === \"string\" && prop in connections) {\n const { integration, auth } = connections[prop];\n return integration.cloneForRun(io, prop, auth);\n }\n\n const value = Reflect.get(target, prop, receiver);\n return typeof value == \"function\" ? value.bind(target) : value;\n },\n }) as IOWithIntegrations<TIntegrations>;\n}\n","import {\n RegisterSourceEventV2,\n RegisterTriggerBodyV2,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport { slugifyId } from \"../utils\";\nimport { ExternalSource, ExternalSourceParams } from \"./externalSource\";\nimport { runLocalStorage } from \"../runLocalStorage\";\nimport { EventFilter } from \"@trigger.dev/core\";\n\n/** Options for a DynamicTrigger */\nexport type DynamicTriggerOptions<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n> = {\n /** Used to uniquely identify a DynamicTrigger */\n id: string;\n /** An event from an [Integration](https://trigger.dev/docs/integrations) package that you want to attach to the DynamicTrigger. The event types will come through to the payload in your Job's run. */\n event: TEventSpec;\n /** An external source fron an [Integration](https://trigger.dev/docs/integrations) package\n * @example \n * ```ts\n * import { events } from \"@trigger.dev/github\";\n * \n * const dynamicOnIssueOpened = client.defineDynamicTrigger({\n id: \"github-issue-opened\",\n event: events.onIssueOpened,\n source: github.sources.repo,\n });\n * ```\n */\n source: TExternalSource;\n};\n\n/** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime. */\nexport class DynamicTrigger<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n> implements Trigger<TEventSpec>\n{\n #client: TriggerClient;\n #options: DynamicTriggerOptions<TEventSpec, TExternalSource>;\n source: TExternalSource;\n\n /** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime.\n * @param client The `TriggerClient` instance to use for registering the trigger.\n * @param options The options for the dynamic trigger.\n * */\n constructor(client: TriggerClient, options: DynamicTriggerOptions<TEventSpec, TExternalSource>) {\n this.#client = client;\n this.#options = options;\n this.source = options.source;\n\n client.attachDynamicTrigger(this);\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.#options.id,\n };\n }\n\n get id() {\n return this.#options.id;\n }\n\n get event() {\n return this.#options.event;\n }\n\n // @internal\n registeredTriggerForParams(\n params: ExternalSourceParams<TExternalSource>,\n options: { accountId?: string; filter?: EventFilter } = {}\n ): RegisterTriggerBodyV2 {\n const key = slugifyId(this.source.key(params));\n\n return {\n rule: {\n event: this.event.name,\n source: this.event.source,\n payload: deepMergeFilters(\n this.source.filter(params),\n this.event.filter ?? {},\n options.filter ?? {}\n ),\n },\n source: {\n version: \"2\",\n key,\n channel: this.source.channel,\n params,\n //todo add other options here\n options: {\n event: typeof this.event.name === \"string\" ? [this.event.name] : this.event.name,\n },\n integration: {\n id: this.source.integration.id,\n metadata: this.source.integration.metadata,\n authSource: this.source.integration.authSource,\n },\n },\n accountId: options.accountId,\n };\n }\n\n /** Use this method to register a new configuration with the DynamicTrigger.\n * @param key The key for the configuration. This will be used to identify the configuration when it is triggered.\n * @param params The params for the configuration.\n * @param options Options for the configuration.\n * @param options.accountId The accountId to associate with the configuration.\n * @param options.filter The filter to use for the configuration.\n *\n */\n async register(\n key: string,\n params: ExternalSourceParams<TExternalSource>,\n options: { accountId?: string; filter?: EventFilter } = {}\n ): Promise<RegisterSourceEventV2> {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n return this.#client.registerTrigger(\n this.id,\n key,\n this.registeredTriggerForParams(params, options)\n );\n }\n\n const { io } = runStore;\n\n return await io.runTask(\n [key, \"register\"],\n async (task) => {\n return this.#client.registerTrigger(\n this.id,\n key,\n this.registeredTriggerForParams(params, options),\n task.idempotencyKey\n );\n },\n {\n name: \"Register Dynamic Trigger\",\n properties: [\n { label: \"Dynamic Trigger ID\", text: this.id },\n { label: \"ID\", text: key },\n ],\n params: params as any,\n }\n );\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpec>, any>): void {\n triggerClient.attachJobToDynamicTrigger(job, this);\n }\n\n get preprocessRuns() {\n return true;\n }\n\n async verifyPayload(payload: ReturnType<TEventSpec[\"parsePayload\"]>) {\n return { success: true as const };\n }\n}\n","import { EventFilter, TriggerMetadata, deepMergeFilters } from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport {\n EventSpecification,\n EventSpecificationExample,\n EventTypeFromSpecification,\n SchemaParser,\n Trigger,\n} from \"../types\";\nimport { formatSchemaErrors } from \"../utils/formatSchemaErrors\";\nimport { ParsedPayloadSchemaError } from \"../errors\";\nimport { VerifyCallback } from \"../httpEndpoint\";\n\ntype EventTriggerOptions<TEventSpecification extends EventSpecification<any>> = {\n event: TEventSpecification;\n name?: string | string[];\n source?: string;\n filter?: EventFilter;\n verify?: EventTypeFromSpecification<TEventSpecification> extends Request ? VerifyCallback : never;\n};\n\nexport class EventTrigger<TEventSpecification extends EventSpecification<any>>\n implements Trigger<TEventSpecification>\n{\n #options: EventTriggerOptions<TEventSpecification>;\n\n constructor(options: EventTriggerOptions<TEventSpecification>) {\n this.#options = options;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.#options.name ?? this.#options.event.title,\n rule: {\n event: this.#options.name ?? this.#options.event.name,\n source: this.#options.source ?? \"trigger.dev\",\n payload: deepMergeFilters(this.#options.filter ?? {}, this.#options.event.filter ?? {}),\n },\n };\n }\n\n get event() {\n return this.#options.event;\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n async verifyPayload(payload: ReturnType<TEventSpecification[\"parsePayload\"]>) {\n if (this.#options.verify) {\n if ((payload as any) instanceof Request) {\n const clonedRequest = (payload as Request).clone();\n return this.#options.verify(clonedRequest);\n }\n }\n\n return { success: true as const };\n }\n}\n\n/** Configuration options for an EventTrigger */\ntype TriggerOptions<TEvent> = {\n /** The name of the event you are subscribing to. Must be an exact match (case sensitive). To trigger on multiple possible events, pass in an array of event names */\n name: string | string[];\n /** A [Zod](https://trigger.dev/docs/documentation/guides/zod) schema that defines the shape of the event payload.\n * The default is `z.any()` which is `any`.\n * */\n schema?: SchemaParser<TEvent>;\n /** You can use this to filter events based on the source. */\n source?: string;\n /** Used to filter which events trigger the Job\n * @example\n * filter:\n * ```ts\n * {\n * name: [\"John\", \"Jane\"],\n * age: [18, 21]\n * }\n * ```\n *\n * This filter would match against an event with the following data:\n * ```json\n * {\n * \"name\": \"Jane\",\n * \"age\": 18,\n * \"location\": \"San Francisco\"\n * }\n * ```\n */\n filter?: EventFilter;\n\n examples?: EventSpecificationExample[];\n};\n\n/** `eventTrigger()` is set as a [Job's trigger](https://trigger.dev/docs/sdk/job) to subscribe to an event a Job from [a sent event](https://trigger.dev/docs/sdk/triggerclient/instancemethods/sendevent)\n * @param options options for the EventTrigger\n */\nexport function eventTrigger<TEvent extends any = any>(\n options: TriggerOptions<TEvent>\n): Trigger<EventSpecification<TEvent>> {\n return new EventTrigger({\n name: options.name,\n filter: options.filter,\n source: options.source,\n event: {\n name: options.name,\n title: \"Event\",\n source: options.source ?? \"trigger.dev\",\n icon: \"custom-event\",\n examples: options.examples,\n parsePayload: (rawPayload: any) => {\n if (options.schema) {\n const results = options.schema.safeParse(rawPayload);\n\n if (!results.success) {\n throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));\n }\n\n return results.data;\n }\n\n return rawPayload as any;\n },\n },\n });\n}\n","import {\n CronOptions,\n IntervalOptions,\n ScheduleMetadata,\n ScheduledPayload,\n ScheduledPayloadSchema,\n TriggerMetadata,\n currentDate,\n} from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport cronstrue from \"cronstrue\";\nimport { runLocalStorage } from \"../runLocalStorage\";\n\ntype ScheduledEventSpecification = EventSpecification<ScheduledPayload>;\n\nconst examples = [\n {\n id: \"now\",\n name: \"Now\",\n icon: \"clock\",\n payload: {\n ts: currentDate.marker,\n lastTimestamp: currentDate.marker,\n },\n },\n];\n\nexport class IntervalTrigger implements Trigger<ScheduledEventSpecification> {\n constructor(private options: IntervalOptions) {}\n\n get event() {\n return {\n name: \"trigger.scheduled\",\n title: \"Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-interval\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n properties: [\n {\n label: \"Interval\",\n text: `${this.options.seconds}s`,\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n async verifyPayload(payload: ReturnType<ScheduledEventSpecification[\"parsePayload\"]>) {\n return { success: true as const };\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"scheduled\",\n schedule: {\n type: \"interval\",\n options: {\n seconds: this.options.seconds,\n },\n },\n };\n }\n}\n\n/** `intervalTrigger()` is set as a [Job's trigger](/sdk/job) to trigger a Job at a recurring interval.\n * @param options An object containing options about the interval.\n */\nexport function intervalTrigger(options: IntervalOptions) {\n return new IntervalTrigger(options);\n}\n\nexport class CronTrigger implements Trigger<ScheduledEventSpecification> {\n constructor(private options: CronOptions) {}\n\n get event() {\n /**\n * We need to concat `(UTC)` string at the end of the human readable string to avoid confusion \n * with execution time/last run of a job in the UI dashboard which is displayed in local time.\n */\n const humanReadable = cronstrue.toString(this.options.cron, {\n throwExceptionOnParseError: false,\n }).concat(\" (UTC)\");\n\n return {\n name: \"trigger.scheduled\",\n title: \"Cron Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-cron\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n properties: [\n {\n label: \"cron\",\n text: this.options.cron,\n },\n {\n label: \"Schedule\",\n text: humanReadable,\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n async verifyPayload(payload: ReturnType<ScheduledEventSpecification[\"parsePayload\"]>) {\n return { success: true as const };\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"scheduled\",\n schedule: {\n type: \"cron\",\n options: {\n cron: this.options.cron,\n },\n },\n };\n }\n}\n\n/** `cronTrigger()` is set as a [Job's trigger](https://trigger.dev/docs/sdk/job) to trigger a Job on a recurring schedule using a CRON expression.\n * @param options An object containing options about the CRON schedule.\n */\nexport function cronTrigger(options: CronOptions) {\n return new CronTrigger(options);\n}\n\n/** DynamicSchedule options\n * @param id Used to uniquely identify a DynamicSchedule\n */\nexport type DynamicIntervalOptions = { id: string };\n\n/** DynamicSchedule` allows you to define a scheduled trigger that can be configured dynamically at runtime. */\nexport class DynamicSchedule implements Trigger<ScheduledEventSpecification> {\n /**\n * @param client The `TriggerClient` instance to use for registering the trigger.\n * @param options The options for the schedule.\n */\n constructor(\n private client: TriggerClient,\n private options: DynamicIntervalOptions\n ) {\n client.attachDynamicSchedule(this.options.id);\n }\n\n get id() {\n return this.options.id;\n }\n\n get event() {\n return {\n name: \"trigger.scheduled\",\n title: \"Dynamic Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-dynamic\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n };\n }\n\n async register(key: string, metadata: ScheduleMetadata) {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n return this.client.registerSchedule(this.id, key, metadata);\n }\n\n const { io } = runStore;\n\n return await io.runTask(\n [key, \"register\"],\n async (task) => {\n return this.client.registerSchedule(this.id, key, metadata);\n },\n {\n name: \"Register Schedule\",\n icon: metadata.type === \"cron\" ? \"schedule-cron\" : \"schedule-interval\",\n properties: [\n { label: \"Dynamic Schedule\", text: this.id },\n { label: \"Schedule ID\", text: key },\n ],\n params: metadata,\n }\n );\n }\n\n async unregister(key: string) {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n return this.client.unregisterSchedule(this.id, key);\n }\n\n const { io } = runStore;\n\n return await io.runTask(\n [key, \"unregister\"],\n async (task) => {\n return this.client.unregisterSchedule(this.id, key);\n },\n {\n name: \"Unregister Schedule\",\n icon: \"schedule\",\n properties: [\n { label: \"Dynamic Schedule\", text: this.id },\n { label: \"Schedule ID\", text: key },\n ],\n }\n );\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {\n triggerClient.attachDynamicScheduleToJob(this.options.id, job);\n }\n\n get preprocessRuns() {\n return false;\n }\n\n async verifyPayload(payload: ReturnType<ScheduledEventSpecification[\"parsePayload\"]>) {\n return { success: true as const };\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.options.id,\n };\n }\n}\n","import {\n ConnectionAuth,\n DisplayProperty,\n EventFilter,\n HandleTriggerSource,\n HttpSourceResponseMetadata,\n NormalizedResponse,\n Prettify,\n RegisterTriggerSource,\n SendEvent,\n SerializableJson,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/core\";\nimport { Logger } from \"@trigger.dev/core-backend\";\nimport type { Buffer } from \"buffer\";\nimport { IOWithIntegrations, TriggerIntegration } from \"../integrations\";\nimport { IO } from \"../io\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport type { EventSpecification, SchemaParser, Trigger, TriggerContext } from \"../types\";\nimport { slugifyId } from \"../utils\";\n\nexport type HttpSourceEvent = {\n url: string;\n method: string;\n headers: Record<string, string>;\n rawBody?: Buffer | null;\n};\n\ntype SmtpSourceEvent = {\n from: string;\n to: string;\n subject: string;\n body: string;\n};\n\ntype SqsSourceEvent = {\n body: string;\n};\n\ntype ExternalSourceChannelMap = {\n HTTP: {\n event: Request;\n register: {\n url: string;\n };\n };\n SMTP: {\n event: SmtpSourceEvent;\n register: {};\n };\n SQS: {\n event: SqsSourceEvent;\n register: {};\n };\n};\n\ntype ChannelNames = keyof ExternalSourceChannelMap;\n\ntype TriggerOptionDiff = {\n desired: string[];\n missing: string[];\n orphaned: string[];\n};\n\ntype TriggerOptionDiffs<TTriggerOptionDefinitions extends Record<string, string[]> = any> =\n TriggerOptionsRecordWithEvent<TriggerOptionDiff, TTriggerOptionDefinitions>;\n\ntype TriggerOptionsRecordWithEvent<\n TValue,\n TTriggerOptionDefinitions extends Record<string, string[]>,\n> = {\n event: TValue;\n} & TriggerOptionRecord<TValue, TTriggerOptionDefinitions>;\n\nexport type TriggerOptionRecord<\n TValue,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n [K in keyof TTriggerOptionDefinitions]: TValue;\n};\n\ntype RegisterFunctionEvent<\n TChannel extends ChannelNames,\n TParams extends any,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n options: TriggerOptionDiffs<TTriggerOptionDefinitions>;\n source: {\n active: boolean;\n data?: any;\n secret: string;\n } & ExternalSourceChannelMap[TChannel][\"register\"];\n params: TParams;\n};\n\ntype RegisterSourceEvent<TTriggerOptionDefinitions extends Record<string, string[]> = any> = {\n id: string;\n source: RegisterTriggerSource;\n dynamicTriggerId?: string;\n options: TriggerOptionDiffs<TTriggerOptionDefinitions>;\n};\n\ntype RegisterFunctionOutput<TTriggerOptionDefinitions extends Record<string, string[]> = any> = {\n secret?: string;\n data?: SerializableJson;\n options: TriggerOptionsRecordWithEvent<string[], TTriggerOptionDefinitions>;\n};\n\ntype RegisterFunction<\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TChannel extends ChannelNames,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = (\n event: RegisterFunctionEvent<TChannel, TParams, TTriggerOptionDefinitions>,\n io: IOWithIntegrations<{ integration: TIntegration }>,\n ctx: TriggerContext\n) => Promise<RegisterFunctionOutput<TTriggerOptionDefinitions> | undefined>;\n\nexport type HandlerEvent<TChannel extends ChannelNames, TParams extends any = any> = {\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"];\n source: Prettify<Omit<HandleTriggerSource, \"params\"> & { params: TParams }>;\n};\n\ntype HandlerFunction<\n TChannel extends ChannelNames,\n TParams extends any,\n TTriggerIntegration extends TriggerIntegration,\n> = (\n event: HandlerEvent<TChannel, TParams>,\n logger: Logger,\n integration: TTriggerIntegration,\n auth?: ConnectionAuth\n) => Promise<{\n events: SendEvent[];\n response?: NormalizedResponse;\n metadata?: HttpSourceResponseMetadata;\n} | void>;\n\ntype KeyFunction<TParams extends any> = (params: TParams) => string;\ntype FilterFunction<\n TParams extends any,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = (params: TParams, options?: TTriggerOptionDefinitions) => EventFilter;\n\ntype ExternalSourceOptions<\n TChannel extends ChannelNames,\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n id: string;\n version: string;\n schema: SchemaParser<TParams>;\n optionSchema?: SchemaParser<TTriggerOptionDefinitions>;\n integration: TIntegration;\n register: RegisterFunction<TIntegration, TParams, TChannel, TTriggerOptionDefinitions>;\n filter?: FilterFunction<TParams, TTriggerOptionDefinitions>;\n handler: HandlerFunction<TChannel, TParams, TIntegration>;\n key: KeyFunction<TParams>;\n properties?: (params: TParams) => DisplayProperty[];\n};\n\nexport class ExternalSource<\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TChannel extends ChannelNames = ChannelNames,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> {\n channel: TChannel;\n\n constructor(\n channel: TChannel,\n private options: ExternalSourceOptions<\n TChannel,\n TIntegration,\n TParams,\n TTriggerOptionDefinitions\n >\n ) {\n this.channel = channel;\n }\n\n async handle(\n source: HandleTriggerSource,\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"],\n logger: Logger\n ) {\n return this.options.handler(\n {\n source: { ...source, params: source.params as TParams },\n rawEvent,\n },\n logger,\n this.options.integration\n );\n }\n\n filter(params: TParams, options?: TTriggerOptionDefinitions): EventFilter {\n return this.options.filter?.(params, options) ?? {};\n }\n\n properties(params: TParams): DisplayProperty[] {\n return this.options.properties?.(params) ?? [];\n }\n\n async register(\n params: TParams,\n registerEvent: RegisterSourceEvent<TTriggerOptionDefinitions>,\n io: IO,\n ctx: TriggerContext\n ) {\n const { result: event, ommited: source } = omit(registerEvent, \"source\");\n const { result: sourceWithoutChannel, ommited: channel } = omit(source, \"channel\");\n const { result: channelWithoutType } = omit(channel, \"type\");\n\n const updates = await this.options.register(\n {\n ...event,\n source: { ...sourceWithoutChannel, ...channelWithoutType },\n params,\n },\n io as IOWithIntegrations<{ integration: TIntegration }>,\n ctx\n );\n\n return updates;\n }\n\n key(params: TParams): string {\n const parts = [this.options.id, this.channel];\n\n parts.push(this.options.key(params));\n parts.push(this.integration.id);\n\n return parts.join(\"-\");\n }\n\n get integration() {\n return this.options.integration;\n }\n\n get integrationConfig() {\n return {\n id: this.integration.id,\n metadata: this.integration.metadata,\n };\n }\n\n get id() {\n return this.options.id;\n }\n\n get version() {\n return this.options.version;\n }\n}\n\nexport type ExternalSourceParams<TExternalSource extends ExternalSource<any, any, any>> =\n TExternalSource extends ExternalSource<any, infer TParams, any> ? TParams : never;\n\nexport type ExternalSourceTriggerOptions<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n event: TEventSpecification;\n source: TEventSource;\n params: ExternalSourceParams<TEventSource>;\n options: TriggerOptionRecord<string[], TTriggerOptionDefinitions>;\n};\n\nexport class ExternalSourceTrigger<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>,\n> implements Trigger<TEventSpecification>\n{\n constructor(private options: ExternalSourceTriggerOptions<TEventSpecification, TEventSource>) {}\n\n get event() {\n return this.options.event;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: \"External Source\",\n rule: {\n event: this.event.name,\n payload: deepMergeFilters(\n this.options.source.filter(this.options.params, this.options.options),\n this.event.filter ?? {},\n this.options.params.filter ?? {}\n ),\n source: this.event.source,\n },\n properties: this.options.source.properties(this.options.params),\n };\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>) {\n triggerClient.attachSource({\n key: slugifyId(this.options.source.key(this.options.params)),\n source: this.options.source,\n event: this.options.event,\n params: this.options.params,\n options: this.options.options,\n });\n }\n\n get preprocessRuns() {\n return true;\n }\n\n async verifyPayload(payload: ReturnType<TEventSpecification[\"parsePayload\"]>) {\n return { success: true as const };\n }\n}\n\nexport function omit<T extends Record<string, unknown>, K extends keyof T>(\n obj: T,\n key: K\n): { result: Omit<T, K>; ommited: T[K] } {\n const result: any = {};\n\n for (const k of Object.keys(obj)) {\n if (k === key) continue;\n\n result[k] = obj[k];\n }\n\n return { result, ommited: obj[key] };\n}\n","import {\n MISSING_CONNECTION_NOTIFICATION,\n MISSING_CONNECTION_RESOLVED_NOTIFICATION,\n MissingConnectionNotificationPayload,\n MissingConnectionNotificationPayloadSchema,\n MissingConnectionResolvedNotificationPayload,\n MissingConnectionResolvedNotificationPayloadSchema,\n TriggerMetadata,\n} from \"@trigger.dev/core\";\nimport { TriggerIntegration } from \"../integrations\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\n\nexport function missingConnectionNotification(integrations: Array<TriggerIntegration>) {\n return new MissingConnectionNotification({ integrations });\n}\n\nexport function missingConnectionResolvedNotification(integrations: Array<TriggerIntegration>) {\n return new MissingConnectionResolvedNotification({ integrations });\n}\n\ntype MissingConnectionNotificationSpecification =\n EventSpecification<MissingConnectionNotificationPayload>;\n\ntype MissingConnectionNotificationOptions = {\n integrations: Array<TriggerIntegration>;\n};\n\nexport class MissingConnectionNotification\n implements Trigger<MissingConnectionNotificationSpecification>\n{\n constructor(private options: MissingConnectionNotificationOptions) {}\n\n get event() {\n return {\n name: MISSING_CONNECTION_NOTIFICATION,\n title: \"Missing Connection Notification\",\n source: \"trigger.dev\",\n icon: \"connection-alert\",\n parsePayload: MissingConnectionNotificationPayloadSchema.parse,\n properties: [\n {\n label: \"Integrations\",\n text: this.options.integrations.map((i) => i.id).join(\", \"),\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<MissingConnectionNotificationSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n async verifyPayload(\n payload: ReturnType<MissingConnectionNotificationSpecification[\"parsePayload\"]>\n ) {\n return { success: true as const };\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.event.title,\n rule: {\n event: this.event.name,\n source: \"trigger.dev\",\n payload: {\n client: {\n id: this.options.integrations.map((i) => i.id),\n },\n },\n },\n };\n }\n}\n\ntype MissingConnectionResolvedNotificationSpecification =\n EventSpecification<MissingConnectionResolvedNotificationPayload>;\n\nexport class MissingConnectionResolvedNotification\n implements Trigger<MissingConnectionResolvedNotificationSpecification>\n{\n constructor(private options: MissingConnectionNotificationOptions) {}\n\n get event() {\n return {\n name: MISSING_CONNECTION_RESOLVED_NOTIFICATION,\n title: \"Missing Connection Resolved Notification\",\n source: \"trigger.dev\",\n icon: \"connection-alert\",\n parsePayload: MissingConnectionResolvedNotificationPayloadSchema.parse,\n properties: [\n {\n label: \"Integrations\",\n text: this.options.integrations.map((i) => i.id).join(\", \"),\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<MissingConnectionResolvedNotificationSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n async verifyPayload(\n payload: ReturnType<MissingConnectionResolvedNotificationSpecification[\"parsePayload\"]>\n ) {\n return { success: true as const };\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.event.title,\n rule: {\n event: this.event.name,\n source: \"trigger.dev\",\n payload: {\n client: {\n id: this.options.integrations.map((i) => i.id),\n },\n },\n },\n };\n }\n}\n","import { TriggerMetadata } from \"@trigger.dev/core\";\nimport { ParsedPayloadSchemaError } from \"../errors\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport {\n EventSpecification,\n EventSpecificationExample,\n SchemaParser,\n Trigger,\n VerifyResult,\n} from \"../types\";\nimport { formatSchemaErrors } from \"../utils/formatSchemaErrors\";\nimport { TypeOf, ZodType, z } from \"zod\";\n\n/** Configuration options for an InvokeTrigger */\ntype InvokeTriggerOptions<TSchema extends ZodType = z.ZodTypeAny> = {\n /** A [Zod](https://trigger.dev/docs/documentation/guides/zod) schema that defines the shape of the event payload.\n * The default is `z.any()` which is `any`.\n * */\n schema?: TSchema;\n examples?: EventSpecificationExample[];\n};\n\nexport class InvokeTrigger<TSchema extends ZodType = z.ZodTypeAny>\n implements Trigger<EventSpecification<TypeOf<TSchema>, z.input<TSchema>>>\n{\n #options: InvokeTriggerOptions<TSchema>;\n\n constructor(options: InvokeTriggerOptions<TSchema>) {\n this.#options = options;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"invoke\",\n };\n }\n\n get event() {\n return {\n name: \"invoke\",\n title: \"Manual Invoke\",\n source: \"trigger.dev\",\n examples: this.#options.examples ?? [],\n icon: \"trigger\",\n parsePayload: (rawPayload: unknown) => {\n if (this.#options.schema) {\n const results = this.#options.schema.safeParse(rawPayload);\n\n if (!results.success) {\n throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));\n }\n\n return results.data;\n }\n\n return rawPayload as any;\n },\n parseInvokePayload: (rawPayload: unknown) => {\n if (this.#options.schema) {\n const results = this.#options.schema.safeParse(rawPayload);\n\n if (!results.success) {\n throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));\n }\n\n return results.data;\n }\n\n return rawPayload as any;\n },\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<EventSpecification<ZodType<TSchema>>>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n async verifyPayload() {\n return { success: true as const };\n }\n}\n\nexport function invokeTrigger<TSchema extends ZodType = z.ZodTypeAny>(\n options?: InvokeTriggerOptions<TSchema>\n): Trigger<EventSpecification<TypeOf<TSchema>, z.input<TSchema>>> {\n return new InvokeTrigger(options ?? {});\n}\n","import {\n DisplayProperty,\n EventFilter,\n HandleTriggerSource,\n RegisterWebhookSource,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/core\";\nimport { IOWithIntegrations, TriggerIntegration } from \"../integrations\";\nimport { IO } from \"../io\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport type {\n EventSpecification,\n SchemaParser,\n Trigger,\n TriggerContext,\n VerifyResult,\n} from \"../types\";\nimport { slugifyId } from \"../utils\";\nimport { SerializableJson } from \"@trigger.dev/core\";\nimport { Prettify } from \"@trigger.dev/core\";\nimport { createHash } from \"node:crypto\";\n\ntype WebhookCRUDContext<TParams extends any, TConfig extends Record<string, string[]>> = {\n active: boolean;\n params: TParams;\n config: {\n current: Partial<TConfig>;\n desired: TConfig;\n };\n url: string;\n secret: string;\n};\n\ntype WebhookCRUDFunction<\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TConfig extends Record<string, string[]>,\n> = (options: {\n io: IOWithIntegrations<{ integration: TIntegration }>;\n ctx: WebhookCRUDContext<TParams, TConfig>;\n}) => Promise<any>;\n\ninterface WebhookCRUD<\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TConfig extends Record<string, string[]>,\n> {\n create: WebhookCRUDFunction<TIntegration, TParams, TConfig>;\n read?: WebhookCRUDFunction<TIntegration, TParams, TConfig>; // currently unused\n update?: WebhookCRUDFunction<TIntegration, TParams, TConfig>;\n delete: WebhookCRUDFunction<TIntegration, TParams, TConfig>;\n}\n\nexport type WebhookConfig<TConfigKeys extends string> = {\n [K in TConfigKeys]: string[];\n};\n\ntype RegisterFunctionEvent<TParams extends any, TConfig extends Record<string, string[]>> = {\n source: {\n active: boolean;\n data?: any;\n secret: string;\n url: string;\n };\n params: TParams;\n config: TConfig;\n};\n\ntype WebhookRegisterEvent<TConfig extends Record<string, string[]>> = {\n id: string;\n source: RegisterWebhookSource;\n dynamicTriggerId?: string;\n config: TConfig;\n};\n\ntype RegisterFunctionOutput<TConfig extends Record<string, string[]>> = {\n secret?: string;\n data?: SerializableJson;\n config: TConfig;\n};\n\ntype RegisterFunction<\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TConfig extends Record<string, string[]>,\n> = (\n event: RegisterFunctionEvent<TParams, TConfig>,\n io: IOWithIntegrations<{ integration: TIntegration }>,\n ctx: TriggerContext\n) => Promise<RegisterFunctionOutput<TConfig> | undefined>;\n\nexport type WebhookHandlerEvent<TParams extends any = any> = {\n rawEvent: Request;\n source: Prettify<Omit<HandleTriggerSource, \"params\"> & { params: TParams }>;\n};\n\ntype WebhookHandlerContext<TParams extends any, TConfig extends Record<string, string[]>> = {\n params: TParams;\n config: TConfig;\n secret: string;\n};\n\nexport type WebhookDeliveryContext = {\n key: string;\n secret: string;\n params: any;\n};\n\ntype EventGenerator<\n TParams extends any,\n TConfig extends Record<string, string[]>,\n TIntegration extends TriggerIntegration,\n> = (options: {\n request: Request;\n client: TriggerClient;\n ctx: WebhookDeliveryContext;\n}) => Promise<any>;\n\ntype KeyFunction<TParams extends any> = (params: TParams) => string;\n\ntype FilterFunction<TParams extends any, TConfig extends Record<string, string[]>> = (\n params: TParams,\n config?: TConfig\n) => EventFilter;\n\ntype WebhookOptions<\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TConfig extends Record<string, string[]>,\n> = {\n id: string;\n version: string;\n integration: TIntegration;\n schemas: {\n params: SchemaParser<TParams>;\n config?: SchemaParser<TConfig>;\n };\n key: KeyFunction<TParams>;\n crud: WebhookCRUD<TIntegration, TParams, TConfig>;\n filter?: FilterFunction<TParams, TConfig>;\n register?: RegisterFunction<TIntegration, TParams, TConfig>;\n verify?: (options: {\n request: Request;\n client: TriggerClient;\n ctx: WebhookDeliveryContext;\n }) => Promise<VerifyResult>;\n generateEvents: EventGenerator<TParams, TConfig, TIntegration>;\n properties?: (params: TParams) => DisplayProperty[];\n};\n\nexport class WebhookSource<\n TIntegration extends TriggerIntegration,\n TParams extends any = any,\n TConfig extends Record<string, string[]> = Record<string, string[]>,\n> {\n constructor(private options: WebhookOptions<TIntegration, TParams, TConfig>) {}\n\n async generateEvents(request: Request, client: TriggerClient, ctx: WebhookDeliveryContext) {\n return this.options.generateEvents({\n request,\n client,\n ctx,\n });\n }\n\n filter(params: TParams, config?: TConfig): EventFilter {\n return this.options.filter?.(params, config) ?? {};\n }\n\n properties(params: TParams): DisplayProperty[] {\n return this.options.properties?.(params) ?? [];\n }\n\n get crud() {\n return this.options.crud;\n }\n\n async register(\n params: TParams,\n registerEvent: WebhookRegisterEvent<TConfig>,\n io: IO,\n ctx: TriggerContext\n ) {\n if (!this.options.register) {\n return;\n }\n\n const updates = await this.options.register(\n {\n ...registerEvent,\n params,\n },\n io as IOWithIntegrations<{ integration: TIntegration }>,\n ctx\n );\n\n return updates;\n }\n\n async verify(\n request: Request,\n client: TriggerClient,\n ctx: WebhookDeliveryContext\n ): Promise<VerifyResult> {\n if (this.options.verify) {\n const clonedRequest = request.clone();\n return this.options.verify({ request: clonedRequest, client, ctx });\n }\n\n return { success: true as const };\n }\n\n #shortHash(str: string) {\n const hash = createHash(\"sha1\").update(str).digest(\"hex\");\n return hash.slice(0, 7);\n }\n\n key(params: TParams): string {\n const parts = [\"webhook\"];\n\n parts.push(this.options.key(params));\n parts.push(this.integration.id);\n\n return `${this.options.id}-${this.#shortHash(parts.join(\"\"))}`;\n }\n\n get integration() {\n return this.options.integration;\n }\n\n get integrationConfig() {\n return {\n id: this.integration.id,\n metadata: this.integration.metadata,\n };\n }\n\n get id() {\n return this.options.id;\n }\n\n get version() {\n return this.options.version;\n }\n}\n\nexport type GetWebhookParams<TWebhook extends WebhookSource<any, any, any>> =\n TWebhook extends WebhookSource<any, infer TParams, any> ? TParams : never;\n\nexport type GetWebhookConfig<TWebhook extends WebhookSource<any, any, any>> =\n TWebhook extends WebhookSource<any, any, infer TConfig> ? TConfig : never;\n\nexport type WebhookTriggerOptions<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends WebhookSource<any, any, any>,\n TConfig extends Record<string, string[]> = Record<string, string[]>,\n> = {\n event: TEventSpecification;\n source: TEventSource;\n params: GetWebhookParams<TEventSource>;\n config: TConfig;\n};\n\nexport class WebhookTrigger<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends WebhookSource<any, any, any>,\n> implements Trigger<TEventSpecification>\n{\n constructor(private options: WebhookTriggerOptions<TEventSpecification, TEventSource>) {}\n\n get event() {\n return this.options.event;\n }\n\n get source() {\n return this.options.source;\n }\n\n get key() {\n return slugifyId(this.options.source.key(this.options.params));\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: \"Webhook\",\n rule: {\n event: this.event.name,\n payload: deepMergeFilters(\n this.options.source.filter(this.options.params, this.options.config),\n this.event.filter ?? {}\n ),\n source: this.event.source,\n },\n properties: this.options.source.properties(this.options.params),\n link: `http-endpoints/${this.key}`,\n };\n }\n\n filter(eventFilter: EventFilter) {\n const { event, ...optionsWithoutEvent } = this.options;\n const { filter, ...eventWithoutFilter } = event;\n\n return new WebhookTrigger({\n ...optionsWithoutEvent,\n event: {\n ...eventWithoutFilter,\n filter: deepMergeFilters(filter ?? {}, eventFilter),\n },\n });\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>) {\n triggerClient.defineHttpEndpoint(\n {\n id: this.key,\n source: \"trigger.dev\",\n icon: this.event.icon,\n verify: async () => ({ success: true }),\n },\n true\n );\n\n triggerClient.attachWebhook({\n key: this.key,\n source: this.options.source,\n event: this.options.event,\n params: this.options.params,\n config: this.options.config,\n });\n }\n\n get preprocessRuns() {\n return true;\n }\n\n async verifyPayload(payload: ReturnType<TEventSpecification[\"parsePayload\"]>) {\n return { success: true as const };\n }\n}\n","import crypto from \"node:crypto\";\nimport type { BinaryToTextEncoding, BinaryLike, KeyObject } from \"crypto\";\nimport { VerifyResult } from \"./types\";\n\n/** Easily verify webhook payloads when they're using common signing methods. */\nexport async function verifyRequestSignature({\n request,\n headerName,\n headerEncoding = \"hex\",\n secret,\n algorithm,\n}: {\n /** The web request that you want to verify. */\n request: Request;\n /** The name of the header that contains the signature. E.g. `X-Cal-Signature-256`. */\n headerName: string;\n /** The header encoding. Defaults to `hex`. */\n headerEncoding?: BinaryToTextEncoding;\n /** The secret that you use to hash the payload. For HttpEndpoints this will usually originally\n come from the Trigger.dev dashboard and should be stored in an environment variable. */\n secret: BinaryLike | KeyObject;\n /** The hashing algorithm that was used to create the signature. Currently only `sha256` is\n supported. */\n algorithm: \"sha256\";\n}): Promise<VerifyResult> {\n if (!secret) {\n return {\n success: false,\n reason: \"Missing secret – you've probably not set an environment variable.\",\n };\n }\n\n const headerValue = request.headers.get(headerName);\n if (!headerValue) {\n return { success: false, reason: \"Missing header\" };\n }\n\n switch (algorithm) {\n case \"sha256\":\n const success = verifyHmacSha256(headerValue, headerEncoding, secret, await request.text());\n\n if (success) {\n return {\n success,\n };\n } else {\n return { success: false, reason: \"Failed sha256 verification\" };\n }\n default:\n throw new Error(`Unsupported algorithm: ${algorithm}`);\n }\n}\n\nexport function verifyHmacSha256(\n headerValue: string,\n headerEncoding: BinaryToTextEncoding,\n secret: BinaryLike | KeyObject,\n body: string\n): boolean {\n const bodyDigest = crypto.createHmac(\"sha256\", secret).update(body).digest(headerEncoding);\n const signature = headerValue?.replace(\"hmac-sha256=\", \"\").replace(\"sha256=\", \"\") ?? \"\";\n\n return signature === bodyDigest;\n}\n","export * from \"./job\";\nexport * from \"./triggerClient\";\nexport * from \"./integrations\";\nexport * from \"./triggers/eventTrigger\";\nexport * from \"./triggers/externalSource\";\nexport * from \"./triggers/dynamic\";\nexport * from \"./triggers/scheduled\";\nexport * from \"./triggers/notifications\";\nexport * from \"./triggers/invokeTrigger\";\nexport * from \"./triggers/webhook\";\nexport * from \"./io\";\nexport * from \"./types\";\nexport * from \"./utils\";\nexport * from \"./security\";\n\nimport { ServerTask } from \"@trigger.dev/core\";\nimport { RedactString } from \"./types\";\nexport { isTriggerError } from \"./errors\";\nexport { retry } from \"./retry\";\n\nexport type { NormalizedRequest, EventFilter } from \"@trigger.dev/core\";\n\nexport type Task = ServerTask;\n\nimport { ApiEventLog } from \"@trigger.dev/core\";\nexport type SentEvent = ApiEventLog;\n\n/*\n * This function is used to create a redacted string that can be used in the headers of a fetch request.\n * It is used to prevent the string from being logged in trigger.dev.\n * You can use it like this:\n *\n * await io.backgroundFetch<SomeResponseType>(\"https://example.com\", {\n * headers: {\n * Authorization: redactString`Bearer ${ACCESS_TOKEN}`,\n * },\n * })\n */\nexport function redactString(\n strings: TemplateStringsArray,\n ...interpolations: string[]\n): RedactString {\n return {\n __redactedString: true,\n strings: strings.raw as string[],\n interpolations,\n };\n}\n"]}
|