@trigger.dev/sdk 2.0.0-next.5 → 2.0.0-next.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +433 -153
- package/dist/index.js +106 -55
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/job.ts","../../internal/src/logger.ts","../../internal/src/schemas/api.ts","../../internal/src/schemas/errors.ts","../../internal/src/schemas/eventFilter.ts","../../internal/src/schemas/integrations.ts","../../internal/src/schemas/json.ts","../../internal/src/schemas/properties.ts","../../internal/src/schemas/schedules.ts","../../internal/src/schemas/tasks.ts","../../internal/src/schemas/triggers.ts","../../internal/src/schemas/notifications.ts","../../internal/src/schemas/fetch.ts","../../internal/src/utils.ts","../../internal/src/retry.ts","../../internal/src/replacements.ts","../src/apiClient.ts","../src/errors.ts","../src/io.ts","../src/ioWithIntegrations.ts","../src/triggers/eventTrigger.ts","../src/triggerClient.ts","../src/integrations.ts","../src/triggers/externalSource.ts","../src/triggers/dynamic.ts","../src/triggers/scheduled.ts","../src/triggers/notifications.ts"],"sourcesContent":["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 \"./io\";\nexport * from \"./types\";\n\nimport { ServerTask } from \"@trigger.dev/internal\";\nimport { RedactString } from \"./types\";\nexport { isTriggerError } from \"./errors\";\n\nexport type { NormalizedRequest, EventFilter } from \"@trigger.dev/internal\";\n\nexport type Task = ServerTask;\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 ctx.fetch(\"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","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(\n /[^a-zA-Z0-9-._~]/g,\n \"\"\n );\n\n return removeNonUrlSafeChars;\n}\n","import {\n IntegrationConfig,\n JobMetadata,\n LogLevel,\n QueueOptions,\n} from \"@trigger.dev/internal\";\nimport {\n IOWithIntegrations,\n IntegrationClient,\n TriggerIntegration,\n} from \"./integrations\";\nimport { TriggerClient } from \"./triggerClient\";\nimport type {\n EventSpecification,\n Trigger,\n TriggerContext,\n TriggerEventType,\n} from \"./types\";\nimport { slugifyId } from \"./utils\";\n\nexport type JobOptions<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<\n string,\n TriggerIntegration<IntegrationClient<any, any>>\n > = {}\n> = {\n id: string;\n name: string;\n version: string;\n trigger: TTrigger;\n logLevel?: LogLevel;\n integrations?: TIntegrations;\n queue?: QueueOptions | string;\n startPosition?: \"initial\" | \"latest\";\n enabled?: boolean;\n\n run: (\n event: TriggerEventType<TTrigger>,\n io: IOWithIntegrations<TIntegrations>,\n ctx: TriggerContext\n ) => Promise<any>;\n};\n\nexport class Job<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<\n string,\n TriggerIntegration<IntegrationClient<any, any>>\n > = {}\n> {\n readonly options: JobOptions<TTrigger, TIntegrations>;\n\n client: TriggerClient;\n\n constructor(\n client: TriggerClient,\n options: JobOptions<TTrigger, TIntegrations>\n ) {\n this.client = client;\n this.options = options;\n this.#validate();\n\n client.attach(this);\n }\n\n get id() {\n return slugifyId(this.options.id);\n }\n\n get enabled() {\n return typeof this.options.enabled === \"boolean\"\n ? this.options.enabled\n : 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 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.client.usesLocalAuth ? \"LOCAL\" : \"HOSTED\",\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 queue: this.options.queue,\n startPosition: this.options.startPosition ?? \"latest\",\n enabled:\n typeof this.options.enabled === \"boolean\" ? this.options.enabled : true,\n preprocessRuns: this.trigger.preprocessRuns,\n internal,\n };\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","// Create a logger class that uses the debug package internally\n\nexport type LogLevel = \"log\" | \"error\" | \"warn\" | \"info\" | \"debug\";\n\nconst logLevels: Array<LogLevel> = [\"log\", \"error\", \"warn\", \"info\", \"debug\"];\n\nexport class Logger {\n #name: string;\n readonly #level: number;\n #filteredKeys: string[] = [];\n #jsonReplacer?: (key: string, value: unknown) => unknown;\n\n constructor(\n name: string,\n level: LogLevel = \"info\",\n filteredKeys: string[] = [],\n jsonReplacer?: (key: string, value: unknown) => unknown\n ) {\n this.#name = name;\n this.#level = logLevels.indexOf(\n (process.env.TRIGGER_LOG_LEVEL ?? level) as LogLevel\n );\n this.#filteredKeys = filteredKeys;\n this.#jsonReplacer = jsonReplacer;\n }\n\n // Return a new Logger instance with the same name and a new log level\n // but filter out the keys from the log messages (at any level)\n filter(...keys: string[]) {\n return new Logger(\n this.#name,\n logLevels[this.#level],\n keys,\n this.#jsonReplacer\n );\n }\n\n log(...args: any[]) {\n if (this.#level < 0) return;\n\n console.log(`[${formattedDateTime()}] [${this.#name}] `, ...args);\n }\n\n error(...args: any[]) {\n if (this.#level < 1) return;\n\n console.error(`[${formattedDateTime()}] [${this.#name}] `, ...args);\n }\n\n warn(...args: any[]) {\n if (this.#level < 2) return;\n\n console.warn(`[${formattedDateTime()}] [${this.#name}] `, ...args);\n }\n\n info(...args: any[]) {\n if (this.#level < 3) return;\n\n console.info(`[${formattedDateTime()}] [${this.#name}] `, ...args);\n }\n\n debug(message: string, ...args: Array<Record<string, unknown> | undefined>) {\n if (this.#level < 4) return;\n\n const structuredLog = {\n timestamp: new Date(),\n name: this.#name,\n message,\n args: structureArgs(\n safeJsonClone(args) as Record<string, unknown>[],\n this.#filteredKeys\n ),\n };\n\n console.debug(\n JSON.stringify(structuredLog, createReplacer(this.#jsonReplacer))\n );\n }\n}\n\nfunction createReplacer(replacer?: (key: string, value: unknown) => unknown) {\n return (key: string, value: unknown) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n if (replacer) {\n return replacer(key, value);\n }\n\n return value;\n };\n}\n\n// Replacer function for JSON.stringify that converts BigInts to strings\nfunction bigIntReplacer(_key: string, value: unknown) {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return value;\n}\n\nfunction safeJsonClone(obj: unknown) {\n try {\n return JSON.parse(JSON.stringify(obj, bigIntReplacer));\n } catch (e) {\n return obj;\n }\n}\n\nfunction formattedDateTime() {\n const date = new Date();\n\n const hours = date.getHours();\n const minutes = date.getMinutes();\n const seconds = date.getSeconds();\n const milliseconds = date.getMilliseconds();\n\n // Make sure the time is always 2 digits\n const formattedHours = hours < 10 ? `0${hours}` : hours;\n const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes;\n const formattedSeconds = seconds < 10 ? `0${seconds}` : seconds;\n const formattedMilliseconds =\n milliseconds < 10\n ? `00${milliseconds}`\n : milliseconds < 100\n ? `0${milliseconds}`\n : milliseconds;\n\n return `${formattedHours}:${formattedMinutes}:${formattedSeconds}.${formattedMilliseconds}`;\n}\n\n// If args is has a single item that is an object, return that object\nfunction structureArgs(\n args: Array<Record<string, unknown>>,\n filteredKeys: string[] = []\n) {\n if (args.length === 0) {\n return;\n }\n\n if (args.length === 1 && typeof args[0] === \"object\") {\n return filterKeys(\n JSON.parse(JSON.stringify(args[0], bigIntReplacer)),\n filteredKeys\n );\n }\n\n return args;\n}\n\n// Recursively filter out keys from an object, including nested objects, and arrays\nfunction filterKeys(obj: unknown, keys: string[]): any {\n if (typeof obj !== \"object\" || obj === null) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => filterKeys(item, keys));\n }\n\n const filteredObj: any = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (keys.includes(key)) {\n continue;\n }\n\n filteredObj[key] = filterKeys(value, keys);\n }\n\n return filteredObj;\n}\n","import { ulid } from \"ulid\";\nimport { z } from \"zod\";\nimport { ErrorWithStackSchema } from \"./errors\";\nimport { EventRuleSchema } from \"./eventFilter\";\nimport { ConnectionAuthSchema, IntegrationConfigSchema } from \"./integrations\";\nimport { DeserializedJsonSchema, SerializableJsonSchema } from \"./json\";\nimport { DisplayPropertySchema, StyleSchema } from \"./properties\";\nimport {\n CronMetadataSchema,\n IntervalMetadataSchema,\n RegisterDynamicSchedulePayloadSchema,\n ScheduleMetadataSchema,\n} from \"./schedules\";\nimport { CachedTaskSchema, ServerTaskSchema, TaskSchema } from \"./tasks\";\nimport { EventSpecificationSchema, TriggerMetadataSchema } from \"./triggers\";\n\nexport const UpdateTriggerSourceBodySchema = z.object({\n registeredEvents: z.array(z.string()),\n secret: z.string().optional(),\n data: SerializableJsonSchema.optional(),\n});\n\nexport type UpdateTriggerSourceBody = z.infer<\n typeof UpdateTriggerSourceBodySchema\n>;\n\nexport const HttpEventSourceSchema = UpdateTriggerSourceBodySchema.extend({\n id: z.string(),\n active: z.boolean(),\n url: z.string().url(),\n});\n\nexport const RegisterHTTPTriggerSourceBodySchema = z.object({\n type: z.literal(\"HTTP\"),\n url: z.string().url(),\n});\n\nexport const RegisterSMTPTriggerSourceBodySchema = z.object({\n type: z.literal(\"SMTP\"),\n});\n\nexport const RegisterSQSTriggerSourceBodySchema = z.object({\n type: z.literal(\"SQS\"),\n});\n\nexport const RegisterSourceChannelBodySchema = z.discriminatedUnion(\"type\", [\n RegisterHTTPTriggerSourceBodySchema,\n RegisterSMTPTriggerSourceBodySchema,\n RegisterSQSTriggerSourceBodySchema,\n]);\n\nexport const REGISTER_SOURCE_EVENT = \"dev.trigger.source.register\";\n\nexport const RegisterTriggerSourceSchema = z.object({\n key: z.string(),\n params: z.any(),\n active: z.boolean(),\n secret: z.string(),\n data: DeserializedJsonSchema.optional(),\n channel: RegisterSourceChannelBodySchema,\n clientId: z.string().optional(),\n});\n\nexport type RegisterTriggerSource = z.infer<typeof RegisterTriggerSourceSchema>;\n\nexport const RegisterSourceEventSchema = z.object({\n id: z.string(),\n source: RegisterTriggerSourceSchema,\n events: z.array(z.string()),\n missingEvents: z.array(z.string()),\n orphanedEvents: z.array(z.string()),\n dynamicTriggerId: z.string().optional(),\n});\n\nexport type RegisterSourceEvent = z.infer<typeof RegisterSourceEventSchema>;\n\nexport const TriggerSourceSchema = z.object({\n id: z.string(),\n key: z.string(),\n});\n\nexport const HandleTriggerSourceSchema = z.object({\n key: z.string(),\n secret: z.string(),\n data: z.any(),\n params: z.any(),\n});\n\nexport type HandleTriggerSource = z.infer<typeof HandleTriggerSourceSchema>;\n\nexport type TriggerSource = z.infer<typeof TriggerSourceSchema>;\n\nexport const HttpSourceRequestSchema = z.object({\n url: z.string().url(),\n method: z.string(),\n headers: z.record(z.string()),\n rawBody: z.instanceof(Buffer).optional().nullable(),\n});\n\nexport type HttpSourceRequest = z.infer<typeof HttpSourceRequestSchema>;\n\nexport const HttpSourceRequestHeadersSchema = z.object({\n \"x-ts-key\": z.string(),\n \"x-ts-dynamic-id\": z.string().optional(),\n \"x-ts-secret\": z.string(),\n \"x-ts-data\": z.string().transform((s) => JSON.parse(s)),\n \"x-ts-params\": z.string().transform((s) => JSON.parse(s)),\n \"x-ts-http-url\": z.string(),\n \"x-ts-http-method\": z.string(),\n \"x-ts-http-headers\": z\n .string()\n .transform((s) => z.record(z.string()).parse(JSON.parse(s))),\n});\n\nexport type HttpSourceRequestHeaders = z.output<\n typeof HttpSourceRequestHeadersSchema\n>;\n\nexport const PongSuccessResponseSchema = z.object({\n ok: z.literal(true),\n});\n\nexport const PongErrorResponseSchema = z.object({\n ok: z.literal(false),\n error: z.string(),\n});\n\nexport const PongResponseSchema = z.discriminatedUnion(\"ok\", [\n PongSuccessResponseSchema,\n PongErrorResponseSchema,\n]);\n\nexport type PongResponse = z.infer<typeof PongResponseSchema>;\n\nexport const QueueOptionsSchema = z.object({\n name: z.string(),\n maxConcurrent: z.number().optional(),\n});\n\nexport type QueueOptions = z.infer<typeof QueueOptionsSchema>;\n\nexport const JobMetadataSchema = z.object({\n id: z.string(),\n name: z.string(),\n version: z.string(),\n event: EventSpecificationSchema,\n trigger: TriggerMetadataSchema,\n integrations: z.record(IntegrationConfigSchema),\n internal: z.boolean().default(false),\n queue: z.union([QueueOptionsSchema, z.string()]).optional(),\n startPosition: z.enum([\"initial\", \"latest\"]),\n enabled: z.boolean(),\n preprocessRuns: z.boolean(),\n});\n\nexport type JobMetadata = z.infer<typeof JobMetadataSchema>;\n\nexport const SourceMetadataSchema = z.object({\n channel: z.enum([\"HTTP\", \"SQS\", \"SMTP\"]),\n integration: IntegrationConfigSchema,\n key: z.string(),\n params: z.any(),\n events: z.array(z.string()),\n});\n\nexport type SourceMetadata = z.infer<typeof SourceMetadataSchema>;\n\nexport const DynamicTriggerEndpointMetadataSchema = z.object({\n id: z.string(),\n jobs: z.array(JobMetadataSchema.pick({ id: true, version: true })),\n});\n\nexport type DynamicTriggerEndpointMetadata = z.infer<\n typeof DynamicTriggerEndpointMetadataSchema\n>;\n\nexport const IndexEndpointResponseSchema = z.object({\n jobs: z.array(JobMetadataSchema),\n sources: z.array(SourceMetadataSchema),\n dynamicTriggers: z.array(DynamicTriggerEndpointMetadataSchema),\n dynamicSchedules: z.array(RegisterDynamicSchedulePayloadSchema),\n});\n\nexport type IndexEndpointResponse = z.infer<typeof IndexEndpointResponseSchema>;\n\nexport const RawEventSchema = z.object({\n id: z.string().default(() => ulid()),\n name: z.string(),\n source: z.string().optional(),\n payload: z.any(),\n context: z.any().optional(),\n timestamp: z.string().datetime().optional(),\n});\n\nexport type RawEvent = z.infer<typeof RawEventSchema>;\nexport type SendEvent = z.input<typeof RawEventSchema>;\n\nexport const ApiEventLogSchema = z.object({\n id: z.string(),\n name: z.string(),\n payload: DeserializedJsonSchema,\n context: DeserializedJsonSchema.optional().nullable(),\n timestamp: z.coerce.date(),\n deliverAt: z.coerce.date().optional().nullable(),\n deliveredAt: z.coerce.date().optional().nullable(),\n});\n\nexport type ApiEventLog = z.infer<typeof ApiEventLogSchema>;\n\nexport const SendEventOptionsSchema = z.object({\n deliverAt: z.string().datetime().optional(),\n deliverAfter: z.number().int().optional(),\n accountId: z.string().optional(),\n});\n\nexport const SendEventBodySchema = z.object({\n event: RawEventSchema,\n options: SendEventOptionsSchema.optional(),\n});\n\nexport type SendEventBody = z.infer<typeof SendEventBodySchema>;\nexport type SendEventOptions = z.infer<typeof SendEventOptionsSchema>;\n\nexport const DeliverEventResponseSchema = z.object({\n deliveredAt: z.string().datetime(),\n});\n\nexport type DeliverEventResponse = z.infer<typeof DeliverEventResponseSchema>;\n\nexport const RuntimeEnvironmentTypeSchema = z.enum([\n \"PRODUCTION\",\n \"STAGING\",\n \"DEVELOPMENT\",\n \"PREVIEW\",\n]);\n\nexport type RuntimeEnvironmentType = z.infer<\n typeof RuntimeEnvironmentTypeSchema\n>;\n\nexport const RunSourceContextSchema = z.object({\n id: z.string(),\n metadata: z.any(),\n});\n\nexport const RunJobBodySchema = z.object({\n event: ApiEventLogSchema,\n job: z.object({\n id: z.string(),\n version: z.string(),\n }),\n run: z.object({\n id: z.string(),\n isTest: z.boolean(),\n startedAt: z.coerce.date(),\n }),\n environment: z.object({\n id: z.string(),\n slug: z.string(),\n type: RuntimeEnvironmentTypeSchema,\n }),\n organization: z.object({\n id: z.string(),\n title: z.string(),\n slug: z.string(),\n }),\n account: z\n .object({\n id: z.string(),\n metadata: z.any(),\n })\n .optional(),\n source: RunSourceContextSchema.optional(),\n tasks: z.array(CachedTaskSchema).optional(),\n connections: z.record(ConnectionAuthSchema).optional(),\n});\n\nexport type RunJobBody = z.infer<typeof RunJobBodySchema>;\n\nexport const RunJobErrorSchema = z.object({\n status: z.literal(\"ERROR\"),\n error: ErrorWithStackSchema,\n task: TaskSchema.optional(),\n});\n\nexport type RunJobError = z.infer<typeof RunJobErrorSchema>;\n\nexport const RunJobResumeWithTaskSchema = z.object({\n status: z.literal(\"RESUME_WITH_TASK\"),\n task: TaskSchema,\n});\n\nexport type RunJobResumeWithTask = z.infer<typeof RunJobResumeWithTaskSchema>;\n\nexport const RunJobRetryWithTaskSchema = z.object({\n status: z.literal(\"RETRY_WITH_TASK\"),\n task: TaskSchema,\n error: ErrorWithStackSchema,\n retryAt: z.coerce.date(),\n});\n\nexport type RunJobRetryWithTask = z.infer<typeof RunJobRetryWithTaskSchema>;\n\nexport const RunJobSuccessSchema = z.object({\n status: z.literal(\"SUCCESS\"),\n output: DeserializedJsonSchema.optional(),\n});\n\nexport type RunJobSuccess = z.infer<typeof RunJobSuccessSchema>;\n\nexport const RunJobResponseSchema = z.discriminatedUnion(\"status\", [\n RunJobErrorSchema,\n RunJobResumeWithTaskSchema,\n RunJobRetryWithTaskSchema,\n RunJobSuccessSchema,\n]);\n\nexport type RunJobResponse = z.infer<typeof RunJobResponseSchema>;\n\nexport const PreprocessRunBodySchema = z.object({\n event: ApiEventLogSchema,\n job: z.object({\n id: z.string(),\n version: z.string(),\n }),\n run: z.object({\n id: z.string(),\n isTest: z.boolean(),\n }),\n environment: z.object({\n id: z.string(),\n slug: z.string(),\n type: RuntimeEnvironmentTypeSchema,\n }),\n organization: z.object({\n id: z.string(),\n title: z.string(),\n slug: z.string(),\n }),\n account: z\n .object({\n id: z.string(),\n metadata: z.any(),\n })\n .optional(),\n});\n\nexport type PreprocessRunBody = z.infer<typeof PreprocessRunBodySchema>;\n\nexport const PreprocessRunResponseSchema = z.object({\n abort: z.boolean(),\n properties: z.array(DisplayPropertySchema).optional(),\n});\n\nexport type PreprocessRunResponse = z.infer<typeof PreprocessRunResponseSchema>;\n\nexport const CreateRunBodySchema = z.object({\n client: z.string(),\n job: JobMetadataSchema,\n event: ApiEventLogSchema,\n properties: z.array(DisplayPropertySchema).optional(),\n});\n\nexport type CreateRunBody = z.infer<typeof CreateRunBodySchema>;\n\nconst CreateRunResponseOkSchema = z.object({\n ok: z.literal(true),\n data: z.object({\n id: z.string(),\n }),\n});\n\nconst CreateRunResponseErrorSchema = z.object({\n ok: z.literal(false),\n error: z.string(),\n});\n\nexport const CreateRunResponseBodySchema = z.discriminatedUnion(\"ok\", [\n CreateRunResponseOkSchema,\n CreateRunResponseErrorSchema,\n]);\n\nexport type CreateRunResponseBody = z.infer<typeof CreateRunResponseBodySchema>;\n\nexport const RedactStringSchema = z.object({\n __redactedString: z.literal(true),\n strings: z.array(z.string()),\n interpolations: z.array(z.string()),\n});\n\nexport type RedactString = z.infer<typeof RedactStringSchema>;\n\nexport const LogMessageSchema = z.object({\n level: z.enum([\"DEBUG\", \"INFO\", \"WARN\", \"ERROR\"]),\n message: z.string(),\n data: SerializableJsonSchema.optional(),\n});\n\nexport type LogMessage = z.infer<typeof LogMessageSchema>;\n\nexport type ClientTask = z.infer<typeof TaskSchema>;\nexport type CachedTask = z.infer<typeof CachedTaskSchema>;\n\nexport const RedactSchema = z.object({\n paths: z.array(z.string()),\n});\n\nexport const RetryOptionsSchema = z.object({\n limit: z.number().optional(),\n factor: z.number().optional(),\n minTimeoutInMs: z.number().optional(),\n maxTimeoutInMs: z.number().optional(),\n randomize: z.boolean().optional(),\n});\n\nexport type RetryOptions = z.infer<typeof RetryOptionsSchema>;\n\nexport const RunTaskOptionsSchema = z.object({\n name: z.string(),\n icon: z.string().optional(),\n displayKey: z.string().optional(),\n noop: z.boolean().default(false),\n operation: z.enum([\"fetch\"]).optional(),\n delayUntil: z.coerce.date().optional(),\n description: z.string().optional(),\n properties: z.array(DisplayPropertySchema).optional(),\n params: z.any(),\n trigger: TriggerMetadataSchema.optional(),\n redact: RedactSchema.optional(),\n connectionKey: z.string().optional(),\n style: StyleSchema.optional(),\n retry: RetryOptionsSchema.optional(),\n});\n\nexport type RunTaskOptions = z.input<typeof RunTaskOptionsSchema>;\n\nexport const RunTaskBodyInputSchema = RunTaskOptionsSchema.extend({\n idempotencyKey: z.string(),\n parentId: z.string().optional(),\n});\n\nexport type RunTaskBodyInput = z.infer<typeof RunTaskBodyInputSchema>;\n\nexport const RunTaskBodyOutputSchema = RunTaskBodyInputSchema.extend({\n params: DeserializedJsonSchema.optional().nullable(),\n});\n\nexport type RunTaskBodyOutput = z.infer<typeof RunTaskBodyOutputSchema>;\n\nexport const CompleteTaskBodyInputSchema = RunTaskBodyInputSchema.pick({\n properties: true,\n description: true,\n params: true,\n}).extend({\n output: SerializableJsonSchema.optional().transform((v) =>\n v ? DeserializedJsonSchema.parse(JSON.parse(JSON.stringify(v))) : {}\n ),\n});\n\nexport type CompleteTaskBodyInput = z.input<typeof CompleteTaskBodyInputSchema>;\nexport type CompleteTaskBodyOutput = z.infer<\n typeof CompleteTaskBodyInputSchema\n>;\n\nexport const FailTaskBodyInputSchema = z.object({\n error: ErrorWithStackSchema,\n});\n\nexport type FailTaskBodyInput = z.infer<typeof FailTaskBodyInputSchema>;\n\nexport const NormalizedRequestSchema = z.object({\n headers: z.record(z.string()),\n method: z.string(),\n query: z.record(z.string()),\n url: z.string(),\n body: z.any(),\n});\n\nexport type NormalizedRequest = z.infer<typeof NormalizedRequestSchema>;\n\nexport const NormalizedResponseSchema = z.object({\n status: z.number(),\n body: z.any(),\n headers: z.record(z.string()).optional(),\n});\n\nexport type NormalizedResponse = z.infer<typeof NormalizedResponseSchema>;\n\nexport const HttpSourceResponseSchema = z.object({\n response: NormalizedResponseSchema,\n events: z.array(RawEventSchema),\n});\n\nexport const RegisterTriggerBodySchema = z.object({\n rule: EventRuleSchema,\n source: SourceMetadataSchema,\n});\n\nexport type RegisterTriggerBody = z.infer<typeof RegisterTriggerBodySchema>;\n\nexport const InitializeTriggerBodySchema = z.object({\n id: z.string(),\n params: z.any(),\n accountId: z.string().optional(),\n metadata: z.any().optional()\n});\n\nexport type InitializeTriggerBody = z.infer<typeof InitializeTriggerBodySchema>;\n\nconst RegisterCommonScheduleBodySchema = z.object({\n id: z.string(),\n metadata: z.any(),\n accountId: z.string().optional(),\n});\n\nexport const RegisterIntervalScheduleBodySchema =\n RegisterCommonScheduleBodySchema.merge(IntervalMetadataSchema);\n\nexport type RegisterIntervalScheduleBody = z.infer<\n typeof RegisterIntervalScheduleBodySchema\n>;\n\nexport const InitializeCronScheduleBodySchema =\n RegisterCommonScheduleBodySchema.merge(CronMetadataSchema);\n\nexport type RegisterCronScheduleBody = z.infer<\n typeof InitializeCronScheduleBodySchema\n>;\n\nexport const RegisterScheduleBodySchema = z.discriminatedUnion(\"type\", [\n RegisterIntervalScheduleBodySchema,\n InitializeCronScheduleBodySchema,\n]);\n\nexport type RegisterScheduleBody = z.infer<typeof RegisterScheduleBodySchema>;\n\nexport const RegisterScheduleResponseBodySchema = z.object({\n id: z.string(),\n schedule: ScheduleMetadataSchema,\n metadata: z.any(),\n active: z.boolean(),\n});\n\nexport type RegisterScheduleResponseBody = z.infer<\n typeof RegisterScheduleResponseBodySchema\n>;\n\nexport const CreateExternalConnectionBodySchema = z.object({\n accessToken: z.string(),\n type: z.enum([\"oauth2\"]),\n scopes: z.array(z.string()).optional(),\n metadata: z.any(),\n});\n\nexport type CreateExternalConnectionBody = z.infer<\n typeof CreateExternalConnectionBodySchema\n>;\n","import { z } from \"zod\";\n\nexport const ErrorWithStackSchema = z.object({\n message: z.string(),\n name: z.string().optional(),\n stack: z.string().optional(),\n});\n\nexport type ErrorWithStack = z.infer<typeof ErrorWithStackSchema>;\n","import { z } from \"zod\";\n\nconst EventMatcherSchema = z.union([\n z.array(z.string()),\n z.array(z.number()),\n z.array(z.boolean()),\n]);\ntype EventMatcher = z.infer<typeof EventMatcherSchema>;\n\nexport type EventFilter = { [key: string]: EventMatcher | EventFilter };\n\nexport const EventFilterSchema: z.ZodType<EventFilter> = z.lazy(() =>\n z.record(z.union([EventMatcherSchema, EventFilterSchema]))\n);\n\nexport const EventRuleSchema = z.object({\n event: z.string(),\n source: z.string(),\n payload: EventFilterSchema.optional(),\n context: EventFilterSchema.optional(),\n});\n\nexport type EventRule = z.infer<typeof EventRuleSchema>;\n","import { z } from \"zod\";\n\nexport const ConnectionAuthSchema = z.object({\n type: z.enum([\"oauth2\"]),\n accessToken: z.string(),\n scopes: z.array(z.string()).optional(),\n additionalFields: z.record(z.string()).optional(),\n});\n\nexport type ConnectionAuth = z.infer<typeof ConnectionAuthSchema>;\n\nexport const IntegrationMetadataSchema = z.object({\n id: z.string(),\n name: z.string(),\n instructions: z.string().optional(),\n});\n\nexport type IntegrationMetadata = z.infer<typeof IntegrationMetadataSchema>;\n\nexport const IntegrationConfigSchema = z.object({\n id: z.string(),\n metadata: IntegrationMetadataSchema,\n authSource: z.enum([\"HOSTED\", \"LOCAL\"]),\n});\n\nexport type IntegrationConfig = z.infer<typeof IntegrationConfigSchema>;\n","import { z } from \"zod\";\n\nconst LiteralSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);\ntype Literal = z.infer<typeof LiteralSchema>;\n\nexport type DeserializedJson =\n | Literal\n | { [key: string]: DeserializedJson }\n | DeserializedJson[];\n\nexport const DeserializedJsonSchema: z.ZodType<DeserializedJson> = z.lazy(() =>\n z.union([\n LiteralSchema,\n z.array(DeserializedJsonSchema),\n z.record(DeserializedJsonSchema),\n ])\n);\n\nconst SerializableSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.date(),\n z.undefined(),\n z.symbol(),\n]);\ntype Serializable = z.infer<typeof SerializableSchema>;\n\nexport type SerializableJson =\n | Serializable\n | { [key: string]: SerializableJson }\n | SerializableJson[];\n\nexport const SerializableJsonSchema: z.ZodType<SerializableJson> = z.lazy(() =>\n z.union([\n SerializableSchema,\n z.array(SerializableJsonSchema),\n z.record(SerializableJsonSchema),\n ])\n);\n","import { z } from \"zod\";\n\nexport const DisplayPropertySchema = z.object({\n label: z.string(),\n text: z.string(),\n url: z.string().optional(),\n});\n\nexport const DisplayPropertiesSchema = z.array(DisplayPropertySchema);\n\nexport type DisplayProperty = z.infer<typeof DisplayPropertySchema>;\n\nexport const StyleSchema = z.object({\n style: z.enum([\"normal\", \"minimal\"]),\n variant: z.string().optional(),\n});\n\nexport type Style = z.infer<typeof StyleSchema>;\nexport type StyleName = Style[\"style\"];\n","import { z } from \"zod\";\n\nexport const SCHEDULED_EVENT = \"dev.trigger.scheduled\";\n\nexport const ScheduledPayloadSchema = z.object({\n ts: z.coerce.date(),\n lastTimestamp: z.coerce.date().optional(),\n});\n\nexport type ScheduledPayload = z.infer<typeof ScheduledPayloadSchema>;\n\nexport const IntervalOptionsSchema = z.object({\n seconds: z.number().int().positive().min(60).max(86400),\n});\n\nexport type IntervalOptions = z.infer<typeof IntervalOptionsSchema>;\n\nexport const CronOptionsSchema = z.object({\n cron: z.string(),\n});\n\nexport type CronOptions = z.infer<typeof CronOptionsSchema>;\n\nexport const CronMetadataSchema = z.object({\n type: z.literal(\"cron\"),\n options: CronOptionsSchema,\n metadata: z.any(),\n});\n\nexport type CronMetadata = z.infer<typeof CronMetadataSchema>;\n\nexport const IntervalMetadataSchema = z.object({\n type: z.literal(\"interval\"),\n options: IntervalOptionsSchema,\n metadata: z.any(),\n});\n\nexport type IntervalMetadata = z.infer<typeof IntervalMetadataSchema>;\n\nexport const ScheduleMetadataSchema = z.discriminatedUnion(\"type\", [\n IntervalMetadataSchema,\n CronMetadataSchema,\n]);\n\nexport type ScheduleMetadata = z.infer<typeof ScheduleMetadataSchema>;\n\nexport const RegisterDynamicSchedulePayloadSchema = z.object({\n id: z.string(),\n jobs: z.array(\n z.object({\n id: z.string(),\n version: z.string(),\n })\n ),\n});\n\nexport type RegisterDynamicSchedulePayload = z.infer<\n typeof RegisterDynamicSchedulePayloadSchema\n>;\n","import { z } from \"zod\";\nimport { DisplayPropertySchema, StyleSchema } from \"./properties\";\nimport { DeserializedJsonSchema } from \"./json\";\n\nexport const TaskStatusSchema = z.enum([\n \"PENDING\",\n \"WAITING\",\n \"RUNNING\",\n \"COMPLETED\",\n \"ERRORED\",\n]);\n\nexport type TaskStatus = z.infer<typeof TaskStatusSchema>;\n\nexport const TaskSchema = z.object({\n id: z.string(),\n name: z.string(),\n icon: z.string().optional().nullable(),\n noop: z.boolean(),\n startedAt: z.coerce.date().optional().nullable(),\n completedAt: z.coerce.date().optional().nullable(),\n delayUntil: z.coerce.date().optional().nullable(),\n status: TaskStatusSchema,\n description: z.string().optional().nullable(),\n properties: z.array(DisplayPropertySchema).optional().nullable(),\n params: DeserializedJsonSchema.optional().nullable(),\n output: DeserializedJsonSchema.optional().nullable(),\n error: z.string().optional().nullable(),\n parentId: z.string().optional().nullable(),\n style: StyleSchema.optional().nullable(),\n operation: z.string().optional().nullable(),\n});\n\nexport const ServerTaskSchema = TaskSchema.extend({\n idempotencyKey: z.string(),\n attempts: z.number(),\n});\n\nexport type ServerTask = z.infer<typeof ServerTaskSchema>;\n\nexport const CachedTaskSchema = z.object({\n id: z.string(),\n idempotencyKey: z.string(),\n status: TaskStatusSchema,\n noop: z.boolean().default(false),\n output: DeserializedJsonSchema.optional().nullable(),\n parentId: z.string().optional().nullable(),\n});\n","import { z } from \"zod\";\nimport { EventFilterSchema, EventRuleSchema } from \"./eventFilter\";\nimport { DisplayPropertySchema } from \"./properties\";\nimport { ScheduleMetadataSchema } from \"./schedules\";\n\nexport const EventExampleSchema = z.object({\n id: z.string(),\n icon: z.string().optional(),\n name: z.string(),\n payload: z.any(),\n});\n\nexport type EventExample = z.infer<typeof EventExampleSchema>;\n\nexport const EventSpecificationSchema = z.object({\n name: z.string(),\n title: z.string(),\n source: z.string(),\n icon: z.string(),\n filter: EventFilterSchema.optional(),\n properties: z.array(DisplayPropertySchema).optional(),\n schema: z.any().optional(),\n examples: z.array(EventExampleSchema).optional(),\n});\n\nexport const DynamicTriggerMetadataSchema = z.object({\n type: z.literal(\"dynamic\"),\n id: z.string(),\n});\n\nexport const StaticTriggerMetadataSchema = z.object({\n type: z.literal(\"static\"),\n title: z.string(),\n properties: z.array(DisplayPropertySchema).optional(),\n rule: EventRuleSchema,\n});\n\nexport const ScheduledTriggerMetadataSchema = z.object({\n type: z.literal(\"scheduled\"),\n schedule: ScheduleMetadataSchema,\n});\n\nexport const TriggerMetadataSchema = z.discriminatedUnion(\"type\", [\n DynamicTriggerMetadataSchema,\n StaticTriggerMetadataSchema,\n ScheduledTriggerMetadataSchema,\n]);\n\nexport type TriggerMetadata = z.infer<typeof TriggerMetadataSchema>;\n","import { z } from \"zod\";\n\nexport const MISSING_CONNECTION_NOTIFICATION =\n \"dev.trigger.notifications.missingConnection\";\n\nexport const MISSING_CONNECTION_RESOLVED_NOTIFICATION =\n \"dev.trigger.notifications.missingConnectionResolved\";\n\nexport const CommonMissingConnectionNotificationPayloadSchema = z.object({\n id: z.string(),\n client: z.object({\n id: z.string(),\n title: z.string(),\n scopes: z.array(z.string()),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n }),\n authorizationUrl: z.string(),\n});\n\nexport const MissingDeveloperConnectionNotificationPayloadSchema =\n CommonMissingConnectionNotificationPayloadSchema.extend({\n type: z.literal(\"DEVELOPER\"),\n });\n\nexport const MissingExternalConnectionNotificationPayloadSchema =\n CommonMissingConnectionNotificationPayloadSchema.extend({\n type: z.literal(\"EXTERNAL\"),\n account: z.object({\n id: z.string(),\n metadata: z.any(),\n }),\n });\n\nexport const MissingConnectionNotificationPayloadSchema = z.discriminatedUnion(\n \"type\",\n [\n MissingDeveloperConnectionNotificationPayloadSchema,\n MissingExternalConnectionNotificationPayloadSchema,\n ]\n);\n\nexport type MissingConnectionNotificationPayload = z.infer<\n typeof MissingConnectionNotificationPayloadSchema\n>;\n\nexport const CommonMissingConnectionNotificationResolvedPayloadSchema =\n z.object({\n id: z.string(),\n client: z.object({\n id: z.string(),\n title: z.string(),\n scopes: z.array(z.string()),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n integrationIdentifier: z.string(),\n integrationAuthMethod: z.string(),\n }),\n expiresAt: z.coerce.date(),\n });\n\nexport const MissingDeveloperConnectionResolvedNotificationPayloadSchema =\n CommonMissingConnectionNotificationResolvedPayloadSchema.extend({\n type: z.literal(\"DEVELOPER\"),\n });\n\nexport const MissingExternalConnectionResolvedNotificationPayloadSchema =\n CommonMissingConnectionNotificationResolvedPayloadSchema.extend({\n type: z.literal(\"EXTERNAL\"),\n account: z.object({\n id: z.string(),\n metadata: z.any(),\n }),\n });\n\nexport const MissingConnectionResolvedNotificationPayloadSchema =\n z.discriminatedUnion(\"type\", [\n MissingDeveloperConnectionResolvedNotificationPayloadSchema,\n MissingExternalConnectionResolvedNotificationPayloadSchema,\n ]);\n\nexport type MissingConnectionResolvedNotificationPayload = z.infer<\n typeof MissingConnectionResolvedNotificationPayloadSchema\n>;\n","import { z } from \"zod\";\nimport { RedactStringSchema, RetryOptionsSchema } from \"./api\";\n\nexport const FetchRetryHeadersStrategySchema = z.object({\n strategy: z.literal(\"headers\"),\n limitHeader: z.string(),\n remainingHeader: z.string(),\n resetHeader: z.string(),\n});\n\nexport type FetchRetryHeadersStrategy = z.infer<\n typeof FetchRetryHeadersStrategySchema\n>;\n\nexport const FetchRetryBackoffStrategySchema = RetryOptionsSchema.extend({\n strategy: z.literal(\"backoff\"),\n});\n\nexport type FetchRetryBackoffStrategy = z.infer<\n typeof FetchRetryBackoffStrategySchema\n>;\n\nexport const FetchRetryStrategySchema = z.discriminatedUnion(\"strategy\", [\n FetchRetryHeadersStrategySchema,\n FetchRetryBackoffStrategySchema,\n]);\n\nexport type FetchRetryStrategy = z.infer<typeof FetchRetryStrategySchema>;\n\nexport const FetchRequestInitSchema = z.object({\n method: z.string().optional(),\n headers: z.record(z.union([z.string(), RedactStringSchema])).optional(),\n body: z.union([z.string(), z.instanceof(ArrayBuffer)]).optional(),\n});\n\nexport type FetchRequestInit = z.infer<typeof FetchRequestInitSchema>;\n\nexport const FetchRetryOptionsSchema = z.record(FetchRetryStrategySchema);\n\nexport type FetchRetryOptions = z.infer<typeof FetchRetryOptionsSchema>;\n\nexport const FetchOperationSchema = z.object({\n url: z.string(),\n requestInit: FetchRequestInitSchema.optional(),\n retry: z.record(FetchRetryStrategySchema).optional(),\n});\n\nexport type FetchOperation = z.infer<typeof FetchOperationSchema>;\n","// EventFilter is typed as type EventFilter = { [key: string]: EventFilter | string[] | number[] | boolean[] }\n\nimport { EventFilter } from \"./schemas\";\n\n// This function should take two EventFilters and return a new EventFilter that is the result of merging the two.\nexport function deepMergeFilters(\n filter: EventFilter,\n other: EventFilter\n): EventFilter {\n const result: EventFilter = { ...filter };\n\n for (const key in other) {\n if (other.hasOwnProperty(key)) {\n const otherValue = other[key];\n\n if (\n typeof otherValue === \"object\" &&\n !Array.isArray(otherValue) &&\n otherValue !== null\n ) {\n const filterValue = filter[key];\n\n if (\n filterValue &&\n typeof filterValue === \"object\" &&\n !Array.isArray(filterValue)\n ) {\n result[key] = deepMergeFilters(filterValue, otherValue);\n } else {\n result[key] = { ...other[key] };\n }\n } else {\n result[key] = other[key];\n }\n }\n }\n\n return result;\n}\n","import { RetryOptions } from \"./schemas\";\n\nconst DEFAULT_RETRY_OPTIONS = {\n limit: 5,\n factor: 1.8,\n minTimeoutInMs: 1000,\n maxTimeoutInMs: 60000,\n randomize: true,\n} satisfies RetryOptions;\n\nexport function calculateRetryAt(\n retryOptions: RetryOptions,\n attempts: number\n): Date | undefined {\n const options = {\n ...DEFAULT_RETRY_OPTIONS,\n ...retryOptions,\n };\n\n const retryCount = attempts + 1;\n\n if (retryCount >= options.limit) {\n return;\n }\n\n const random = options.randomize ? Math.random() + 1 : 1;\n\n let timeoutInMs = Math.round(\n random *\n Math.max(options.minTimeoutInMs, 1) *\n Math.pow(options.factor, Math.max(attempts - 1, 0))\n );\n\n timeoutInMs = Math.min(timeoutInMs, options.maxTimeoutInMs);\n\n return new Date(Date.now() + timeoutInMs);\n}\n","import { DeserializedJson, DeserializedJsonSchema } from \"./schemas\";\n\nexport interface ExampleReplacement {\n marker: string;\n replace(input: ExampleInputData): DeserializedJson;\n}\n\ntype ExampleInputData = {\n match: {\n key: string;\n value: string;\n };\n data: {\n now: Date;\n };\n};\n\nexport const currentDate: ExampleReplacement = {\n marker: \"__CURRENT_DATE__\",\n replace({ data: { now } }: ExampleInputData) {\n return now.toISOString();\n },\n};\n\nexport const currentTimestampMilliseconds: ExampleReplacement = {\n marker: \"__CURRENT_TIMESTAMP_MS__\",\n replace({ data: { now } }: ExampleInputData) {\n return now.getTime();\n },\n};\n\nexport const currentTimestampSeconds: ExampleReplacement = {\n marker: \"__CURRENT_TIMESTAMP_S__\",\n replace({ data: { now } }: ExampleInputData) {\n return now.getTime() / 1000;\n },\n};\n\nexport const replacements: ExampleReplacement[] = [\n currentDate,\n currentTimestampMilliseconds,\n currentTimestampSeconds,\n];\n","import {\n ApiEventLog,\n ApiEventLogSchema,\n CompleteTaskBodyInput,\n ConnectionAuthSchema,\n CreateRunBody,\n CreateRunResponseBodySchema,\n FailTaskBodyInput,\n LogLevel,\n Logger,\n RegisterScheduleResponseBodySchema,\n RegisterSourceEvent,\n RegisterSourceEventSchema,\n RegisterTriggerBody,\n RunTaskBodyInput,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n ServerTaskSchema,\n TriggerSource,\n TriggerSourceSchema,\n UpdateTriggerSourceBody,\n} from \"@trigger.dev/internal\";\nimport { z } from \"zod\";\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\n constructor(options: ApiClientOptions) {\n this.#options = options;\n\n this.#apiUrl =\n this.#options.apiUrl ??\n process.env.TRIGGER_API_URL ??\n \"https://api.trigger.dev\";\n this.#logger = new Logger(\"trigger.dev\", this.#options.logLevel);\n }\n\n async registerEndpoint(options: {\n url: string;\n name: string;\n }): 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(\n `Failed to register entry point, got status code ${response.status}`\n );\n }\n\n return await response.json();\n }\n\n async createRun(params: CreateRunBody) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Creating run\", {\n params,\n });\n\n return await zodfetch(\n CreateRunResponseBodySchema,\n `${this.#apiUrl}/api/v1/runs`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(params),\n }\n );\n }\n\n async runTask(runId: string, task: RunTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Running Task\", {\n task,\n });\n\n return await zodfetch(\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 },\n body: JSON.stringify(task),\n }\n );\n }\n\n async completeTask(runId: string, id: string, task: CompleteTaskBodyInput) {\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 },\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 updateSource(\n client: string,\n key: string,\n source: UpdateTriggerSourceBody\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/v1/${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 registerTrigger(\n client: string,\n id: string,\n key: string,\n payload: RegisterTriggerBody\n ): Promise<RegisterSourceEvent> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering trigger\", {\n id,\n payload,\n });\n\n const response = await zodfetch(\n RegisterSourceEventSchema,\n `${this.#apiUrl}/api/v1/${client}/triggers/${id}/registrations/${key}`,\n {\n method: \"PUT\",\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 async registerSchedule(\n client: string,\n id: string,\n key: string,\n payload: ScheduleMetadata\n ) {\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 `${\n this.#apiUrl\n }/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(\n key\n )}`,\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 #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 ?? process.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\nasync function zodfetch<\n TResponseBody extends any,\n TOptional extends boolean = false\n>(\n schema: z.Schema<TResponseBody>,\n url: string,\n requestInit?: RequestInit,\n options?: {\n errorMessage?: string;\n optional?: TOptional;\n }\n): Promise<TOptional extends true ? TResponseBody | undefined : TResponseBody> {\n const response = await fetch(url, 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 !== 200) {\n throw new Error(\n options?.errorMessage ??\n `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","import { ErrorWithStack, ServerTask } from \"@trigger.dev/internal\";\n\nexport class ResumeWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\nexport class RetryWithTaskError {\n constructor(\n public cause: ErrorWithStack,\n public task: ServerTask,\n public retryAt: Date\n ) {}\n}\n\nexport function isTriggerError(\n err: unknown\n): err is ResumeWithTaskError | RetryWithTaskError {\n return (\n err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError\n );\n}\n","import {\n CachedTask,\n ConnectionAuth,\n CronOptions,\n ErrorWithStackSchema,\n FetchRequestInit,\n FetchRetryOptions,\n IntervalOptions,\n LogLevel,\n Logger,\n RunTaskOptions,\n SendEvent,\n SendEventOptions,\n SerializableJson,\n ServerTask,\n UpdateTriggerSourceBody,\n} from \"@trigger.dev/internal\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { webcrypto } from \"node:crypto\";\nimport { ApiClient } from \"./apiClient\";\nimport {\n ResumeWithTaskError,\n RetryWithTaskError,\n isTriggerError,\n} from \"./errors\";\nimport { createIOWithIntegrations } from \"./ioWithIntegrations\";\nimport { calculateRetryAt } from \"./retry\";\nimport { TriggerClient } from \"./triggerClient\";\nimport { DynamicTrigger } from \"./triggers/dynamic\";\nimport {\n ExternalSource,\n ExternalSourceParams,\n} from \"./triggers/externalSource\";\nimport { DynamicSchedule } from \"./triggers/scheduled\";\nimport { EventSpecification, TaskLogger, TriggerContext } from \"./types\";\n\nexport type IOTask = ServerTask;\n\nexport type IOOptions = {\n id: string;\n apiClient: ApiClient;\n client: TriggerClient;\n context: TriggerContext;\n logger?: Logger;\n logLevel?: LogLevel;\n cachedTasks?: Array<CachedTask>;\n};\n\nexport class IO {\n private _id: string;\n private _apiClient: ApiClient;\n private _triggerClient: TriggerClient;\n private _logger: Logger;\n private _cachedTasks: Map<string, CachedTask>;\n private _taskStorage: AsyncLocalStorage<{ taskId: string }>;\n private _context: TriggerContext;\n\n constructor(options: IOOptions) {\n this._id = options.id;\n this._apiClient = options.apiClient;\n this._triggerClient = options.client;\n this._logger =\n options.logger ?? new Logger(\"trigger.dev\", options.logLevel);\n this._cachedTasks = new Map();\n\n if (options.cachedTasks) {\n options.cachedTasks.forEach((task) => {\n this._cachedTasks.set(task.id, task);\n });\n }\n\n this._taskStorage = new AsyncLocalStorage();\n this._context = options.context;\n }\n\n get logger() {\n return new IOLogger(async (level, message, data) => {\n switch (level) {\n case \"DEBUG\": {\n this._logger.debug(message, data);\n break;\n }\n case \"INFO\": {\n this._logger.info(message, data);\n break;\n }\n case \"WARN\": {\n this._logger.warn(message, data);\n break;\n }\n case \"ERROR\": {\n this._logger.error(message, data);\n break;\n }\n }\n\n await this.runTask(\n [message, level],\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 async (task) => {}\n );\n });\n }\n\n async wait(key: string | any[], seconds: number) {\n return await this.runTask(\n key,\n {\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 async (task) => {}\n );\n }\n\n async backgroundFetch<TResponseData>(\n key: string | any[],\n url: string,\n requestInit?: FetchRequestInit,\n retry?: FetchRetryOptions\n ): Promise<TResponseData> {\n const urlObject = new URL(url);\n\n return (await this.runTask(\n key,\n {\n name: `fetch ${urlObject.hostname}${urlObject.pathname}`,\n params: { url, requestInit, retry },\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 ],\n },\n async (task) => {\n return task.output;\n }\n )) as TResponseData;\n }\n\n async sendEvent(\n key: string | any[],\n event: SendEvent,\n options?: SendEventOptions\n ) {\n return await this.runTask(\n key,\n {\n name: \"sendEvent\",\n params: { event, options },\n },\n async (task) => {\n return await this._triggerClient.sendEvent(event, options);\n }\n );\n }\n\n async updateSource(\n key: string | any[],\n options: { key: string } & UpdateTriggerSourceBody\n ) {\n return this.runTask(\n key,\n {\n name: \"Update Source\",\n description: `Update Source ${options.key}`,\n properties: [\n {\n label: \"key\",\n text: options.key,\n },\n ],\n redact: {\n paths: [\"secret\"],\n },\n },\n async (task) => {\n return await this._apiClient.updateSource(\n this._triggerClient.id,\n options.key,\n options\n );\n }\n );\n }\n\n async registerInterval(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: IntervalOptions\n ) {\n return await this.runTask(\n key,\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 async (task) => {\n return dynamicSchedule.register(id, {\n type: \"interval\",\n options,\n });\n }\n );\n }\n\n async unregisterInterval(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string\n ) {\n return await this.runTask(\n key,\n {\n name: \"unregister-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n },\n async (task) => {\n return dynamicSchedule.unregister(id);\n }\n );\n }\n\n async registerCron(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: CronOptions\n ) {\n return await this.runTask(\n key,\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 async (task) => {\n return dynamicSchedule.register(id, {\n type: \"cron\",\n options,\n });\n }\n );\n }\n\n async unregisterCron(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string\n ) {\n return await this.runTask(\n key,\n {\n name: \"unregister-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n },\n async (task) => {\n return dynamicSchedule.unregister(id);\n }\n );\n }\n\n async registerTrigger<\n TTrigger extends DynamicTrigger<\n EventSpecification<any>,\n ExternalSource<any, any, any>\n >\n >(\n key: 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 key,\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 async (task) => {\n const registration = await this.runTask(\n \"register-source\",\n {\n name: \"register-source\",\n },\n async (subtask1) => {\n return trigger.register(id, params);\n }\n );\n\n const connection = await this.getAuth(\n \"get-auth\",\n registration.source.clientId\n );\n\n const io = createIOWithIntegrations(\n // @ts-ignore\n this,\n {\n integration: connection,\n },\n {\n integration: trigger.source.integration,\n }\n );\n\n const updates = await trigger.source.register(\n params,\n registration,\n io,\n this._context\n );\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await this.updateSource(\"update-source\", {\n key: registration.source.key,\n ...updates,\n });\n }\n );\n }\n\n async getAuth(\n key: string | any[],\n clientId?: string\n ): Promise<ConnectionAuth | undefined> {\n if (!clientId) {\n return;\n }\n\n return this.runTask(key, { name: \"get-auth\" }, async (task) => {\n return await this._triggerClient.getAuth(clientId);\n });\n }\n\n async runTask<TResult extends SerializableJson | void = void>(\n key: string | any[],\n options: RunTaskOptions,\n callback: (task: IOTask, io: IO) => Promise<TResult>,\n onError?: (\n error: unknown,\n task: IOTask,\n io: IO\n ) => { retryAt: Date; error?: Error; jitter?: number } | undefined | void\n ): Promise<TResult> {\n const parentId = this._taskStorage.getStore()?.taskId;\n\n if (parentId) {\n this._logger.debug(\"Using parent task\", {\n parentId,\n key,\n options,\n });\n }\n\n const idempotencyKey = await generateIdempotencyKey(\n [this._id, parentId ?? \"\", key].flat()\n );\n\n const cachedTask = this._cachedTasks.get(idempotencyKey);\n\n if (cachedTask) {\n this._logger.debug(\"Using cached task\", {\n idempotencyKey,\n cachedTask,\n });\n\n return cachedTask.output as TResult;\n }\n\n const task = await this._apiClient.runTask(this._id, {\n idempotencyKey,\n displayKey: typeof key === \"string\" ? key : undefined,\n noop: false,\n ...options,\n parentId,\n });\n\n if (task.status === \"COMPLETED\") {\n this._logger.debug(\"Using task output\", {\n idempotencyKey,\n task,\n });\n\n this.#addToCachedTasks(task);\n\n return task.output as TResult;\n }\n\n if (task.status === \"ERRORED\") {\n this._logger.debug(\"Task errored\", {\n idempotencyKey,\n task,\n });\n\n throw new Error(task.error ?? \"Task errored\");\n }\n\n if (task.status === \"WAITING\") {\n this._logger.debug(\"Task waiting\", {\n idempotencyKey,\n task,\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 const executeTask = async () => {\n try {\n const result = await callback(task, this);\n\n this._logger.debug(\"Completing using output\", {\n idempotencyKey,\n task,\n });\n\n await this._apiClient.completeTask(this._id, task.id, {\n output: result ?? undefined,\n });\n\n return result;\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n if (onError) {\n const onErrorResult = onError(error, task, this);\n\n if (onErrorResult) {\n const parsedError = ErrorWithStackSchema.safeParse(\n onErrorResult.error\n );\n\n throw new RetryWithTaskError(\n parsedError.success\n ? parsedError.data\n : { message: \"Unknown error\" },\n task,\n onErrorResult.retryAt\n );\n }\n }\n\n const parsedError = ErrorWithStackSchema.safeParse(error);\n\n if (options.retry) {\n const retryAt = calculateRetryAt(options.retry, task.attempts - 1);\n\n if (retryAt) {\n throw new RetryWithTaskError(\n parsedError.success\n ? parsedError.data\n : { 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 await this._apiClient.failTask(this._id, task.id, {\n error: { message: JSON.stringify(error), name: \"Unknown Error\" },\n });\n }\n\n throw error;\n }\n };\n\n return this._taskStorage.run({ taskId: task.id }, executeTask);\n }\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 #addToCachedTasks(task: ServerTask) {\n this._cachedTasks.set(task.idempotencyKey, task);\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\",\n message: string,\n properties?: Record<string, any>\n) => Promise<void>;\n\nexport class IOLogger implements TaskLogger {\n constructor(private callback: CallbackFunction) {}\n\n debug(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"DEBUG\", message, properties);\n }\n info(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"INFO\", message, properties);\n }\n warn(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"WARN\", message, properties);\n }\n error(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"ERROR\", message, properties);\n }\n}\n","import { ConnectionAuth } from \"@trigger.dev/internal\";\nimport {\n AuthenticatedTask,\n IOWithIntegrations,\n IntegrationClient,\n TriggerIntegration,\n} from \"./integrations\";\nimport { IO } from \"./io\";\n\nexport function createIOWithIntegrations<\n TIntegrations extends Record<\n string,\n TriggerIntegration<IntegrationClient<any, any>>\n >\n>(\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 const client = integration.client.usesLocalAuth\n ? integration.client.client\n : auth\n ? integration.client.clientFactory?.(auth)\n : undefined;\n\n if (!client) {\n return acc;\n }\n\n auth = integration.client.usesLocalAuth ? integration.client.auth : auth;\n\n const ioConnection = {\n client,\n } as any;\n\n if (integration.client.tasks) {\n const tasks: Record<\n string,\n AuthenticatedTask<any, any, any, any>\n > = integration.client.tasks;\n\n Object.keys(tasks).forEach((taskName) => {\n const authenticatedTask = tasks[taskName];\n\n ioConnection[taskName] = async (\n key: string | string[],\n params: any\n ) => {\n const options = authenticatedTask.init(params);\n options.connectionKey = connectionKey;\n\n return await io.runTask(\n key,\n options,\n async (ioTask) => {\n return authenticatedTask.run(params, client, ioTask, io, auth);\n },\n authenticatedTask.onError\n );\n };\n });\n }\n\n acc[connectionKey] = ioConnection;\n\n return acc;\n },\n {} as any\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 (prop in connections) {\n return connections[prop];\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 EventFilter,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/internal\";\nimport { z } from \"zod\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\n\ntype EventTriggerOptions<TEventSpecification extends EventSpecification<any>> =\n {\n event: TEventSpecification;\n name?: string;\n source?: string;\n filter?: EventFilter;\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(\n this.#options.filter ?? {},\n this.#options.event.filter ?? {}\n ),\n },\n };\n }\n\n get event() {\n return this.#options.event;\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<TEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n}\n\ntype TriggerOptions<TEvent> = {\n name: string;\n schema?: z.Schema<TEvent>;\n source?: string;\n filter?: EventFilter;\n};\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 event: {\n name: options.name,\n title: \"Event\",\n source: options.source ?? \"trigger.dev\",\n icon: \"custom-event\",\n parsePayload: (rawPayload: any) => {\n if (options.schema) {\n return options.schema.parse(rawPayload);\n }\n\n return rawPayload as any;\n },\n },\n });\n}\n","import {\n ErrorWithStackSchema,\n HandleTriggerSource,\n HttpSourceRequestHeadersSchema,\n IndexEndpointResponse,\n InitializeTriggerBodySchema,\n LogLevel,\n Logger,\n NormalizedResponse,\n PreprocessRunBody,\n PreprocessRunBodySchema,\n REGISTER_SOURCE_EVENT,\n RegisterSourceEvent,\n RegisterSourceEventSchema,\n RegisterTriggerBody,\n RunJobBody,\n RunJobBodySchema,\n RunJobResponse,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n SourceMetadata,\n} from \"@trigger.dev/internal\";\nimport { ApiClient } from \"./apiClient\";\nimport { ResumeWithTaskError, RetryWithTaskError } from \"./errors\";\nimport { IO } from \"./io\";\nimport { createIOWithIntegrations } from \"./ioWithIntegrations\";\nimport { Job } from \"./job\";\nimport { DynamicTrigger } from \"./triggers/dynamic\";\nimport { EventTrigger } from \"./triggers/eventTrigger\";\nimport { ExternalSource } from \"./triggers/externalSource\";\nimport type {\n EventSpecification,\n Trigger,\n TriggerContext,\n TriggerPreprocessContext,\n} from \"./types\";\n\nconst registerSourceEvent: EventSpecification<RegisterSourceEvent> = {\n name: REGISTER_SOURCE_EVENT,\n title: \"Register Source\",\n source: \"internal\",\n icon: \"register-source\",\n parsePayload: RegisterSourceEventSchema.parse,\n};\n\nexport type TriggerClientOptions = {\n id: string;\n apiKey?: string;\n apiUrl?: string;\n logLevel?: LogLevel;\n};\n\nexport class TriggerClient {\n #options: TriggerClientOptions;\n #registeredJobs: Record<string, Job<Trigger<EventSpecification<any>>, any>> =\n {};\n #registeredSources: Record<string, SourceMetadata> = {};\n #registeredHttpSourceHandlers: Record<\n string,\n (\n source: HandleTriggerSource,\n request: Request\n ) => Promise<{\n events: Array<SendEvent>;\n response?: NormalizedResponse;\n } | void>\n > = {};\n #registeredDynamicTriggers: Record<\n string,\n DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>\n > = {};\n #jobMetadataByDynamicTriggers: Record<\n string,\n Array<{ id: string; version: string }>\n > = {};\n #registeredSchedules: Record<string, Array<{ id: string; version: string }>> =\n {};\n\n #client: ApiClient;\n #logger: Logger;\n id: string;\n\n constructor(options: TriggerClientOptions) {\n this.id = options.id;\n this.#options = options;\n this.#client = new ApiClient(this.#options);\n this.#logger = new Logger(\"trigger.dev\", this.#options.logLevel);\n }\n\n async handleRequest(request: Request): Promise<NormalizedResponse> {\n this.#logger.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\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 };\n }\n case \"missing-header\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: missing x-trigger-api-key header\",\n },\n };\n }\n case \"unauthorized\": {\n return {\n status: 401,\n body: {\n message: `Forbidden: client apiKey mismatch: Expected ${\n this.#options.apiKey\n }, got ${apiKey}`,\n },\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 };\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 };\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 message: \"Missing endpoint ID\",\n },\n };\n }\n\n if (this.id !== endpointId) {\n return {\n status: 200,\n body: {\n ok: false,\n message: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`,\n },\n };\n }\n\n return {\n status: 200,\n body: {\n ok: true,\n },\n };\n }\n case \"INDEX_ENDPOINT\": {\n // if the x-trigger-job-id header is set, we return the job with that id\n const jobId = request.headers.get(\"x-trigger-job-id\");\n\n if (jobId) {\n const job = this.#registeredJobs[jobId];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n return {\n status: 200,\n body: job.toJSON(),\n };\n }\n\n const body: IndexEndpointResponse = {\n jobs: Object.values(this.#registeredJobs).map((job) => job.toJSON()),\n sources: Object.values(this.#registeredSources),\n dynamicTriggers: Object.values(this.#registeredDynamicTriggers).map(\n (trigger) => ({\n id: trigger.id,\n jobs: this.#jobMetadataByDynamicTriggers[trigger.id] ?? [],\n })\n ),\n dynamicSchedules: Object.entries(this.#registeredSchedules).map(\n ([id, jobs]) => ({\n id,\n jobs,\n })\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 };\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 };\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);\n\n return {\n status: 200,\n body: results,\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 };\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 sourceRequest = new Request(headers.data[\"x-ts-http-url\"], {\n method: headers.data[\"x-ts-http-method\"],\n headers: headers.data[\"x-ts-http-headers\"],\n body:\n headers.data[\"x-ts-http-method\"] !== \"GET\"\n ? request.body\n : undefined,\n });\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\n const source = {\n key,\n dynamicId,\n secret,\n params,\n data,\n };\n\n const { response, events } = await this.#handleHttpSourceRequest(\n source,\n sourceRequest\n );\n\n return {\n status: 200,\n body: {\n events,\n response,\n },\n };\n }\n }\n\n return {\n status: 405,\n body: {\n message: \"Method not allowed\",\n },\n };\n }\n\n attach(job: Job<Trigger<any>, any>): void {\n if (!job.enabled) {\n return;\n }\n\n this.#registeredJobs[job.id] = job;\n\n job.trigger.attachToJob(this, job);\n }\n\n attachDynamicTrigger(trigger: DynamicTrigger<any, any>): void {\n this.#registeredDynamicTriggers[trigger.id] = trigger;\n\n new Job(this, {\n id: `register-dynamic-trigger-${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(\n event.source.params,\n event,\n io,\n ctx\n );\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 // @ts-ignore\n __internal: true,\n });\n }\n\n attachJobToDynamicTrigger(\n job: Job<Trigger<any>, any>,\n trigger: DynamicTrigger<any, any>\n ): 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 }): void {\n this.#registeredHttpSourceHandlers[options.key] = async (s, r) => {\n return await options.source.handle(s, r, this.#logger);\n };\n\n let registeredSource = this.#registeredSources[options.key];\n\n if (!registeredSource) {\n registeredSource = {\n channel: options.source.channel,\n key: options.key,\n params: options.params,\n events: [],\n integration: {\n id: options.source.integration.id,\n metadata: options.source.integration.metadata,\n authSource: options.source.integration.client.usesLocalAuth\n ? \"LOCAL\"\n : \"HOSTED\",\n },\n };\n }\n\n registeredSource.events = Array.from(\n new Set([...registeredSource.events, options.event.name])\n );\n\n this.#registeredSources[options.key] = registeredSource;\n\n new Job(this, {\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 queue: {\n name: options.key,\n maxConcurrent: 1,\n },\n startPosition: \"initial\",\n run: async (event, io, ctx) => {\n const updates = await options.source.register(\n options.params,\n event,\n io,\n ctx\n );\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 // @ts-ignore\n __internal: true,\n });\n }\n\n attachDynamicSchedule(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 async registerTrigger(id: string, key: string, options: RegisterTriggerBody) {\n return this.#client.registerTrigger(this.id, id, key, options);\n }\n\n async getAuth(id: string) {\n return this.#client.getAuth(this.id, id);\n }\n\n async sendEvent(event: SendEvent, options?: SendEventOptions) {\n return this.#client.sendEvent(event, options);\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 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 ?? process.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 ?? process.env.TRIGGER_API_KEY;\n }\n\n async #preprocessRun(\n body: PreprocessRunBody,\n job: Job<Trigger<EventSpecification<any>>, any>\n ) {\n const context = this.#createPreprocessRunContext(body);\n\n const parsedPayload = job.trigger.event.parsePayload(\n body.event.payload ?? {}\n );\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>, any>\n ): Promise<RunJobResponse> {\n this.#logger.debug(\"executing job\", { execution: body, job: job.toJSON() });\n\n const context = this.#createRunContext(body);\n\n const io = new IO({\n id: body.run.id,\n cachedTasks: body.tasks,\n apiClient: this.#client,\n logger: this.#logger,\n client: this,\n context,\n });\n\n const ioWithConnections = createIOWithIntegrations(\n io,\n body.connections,\n job.options.integrations\n );\n\n try {\n const output = await job.options.run(\n job.trigger.event.parsePayload(body.event.payload ?? {}),\n ioWithConnections,\n context\n );\n\n return { status: \"SUCCESS\", output };\n } catch (error) {\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 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 return {\n status: \"ERROR\",\n error: { message: \"Unknown error\" },\n };\n }\n }\n\n #createRunContext(execution: RunJobBody): TriggerContext {\n const { event, organization, 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 environment,\n job,\n run,\n account: execution.account,\n source,\n };\n }\n\n #createPreprocessRunContext(\n body: PreprocessRunBody\n ): 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 },\n sourceRequest: Request\n ): Promise<{ response: NormalizedResponse; events: SendEvent[] }> {\n this.#logger.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.#logger.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.#logger\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 };\n }\n\n const handler = this.#registeredHttpSourceHandlers[source.key];\n\n if (!handler) {\n this.#logger.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 };\n }\n}\n","import {\n ConnectionAuth,\n IntegrationMetadata,\n RunTaskOptions,\n ServerTask,\n} from \"@trigger.dev/internal\";\nimport { IO } from \"./io\";\n\nexport type ClientFactory<TClient> = (auth: ConnectionAuth) => TClient;\n\nexport interface TriggerIntegration<\n TIntegrationClient extends IntegrationClient<any, any> = IntegrationClient<\n any,\n any\n >\n> {\n client: TIntegrationClient;\n id: string;\n metadata: IntegrationMetadata;\n}\n\nexport type IntegrationClient<\n TClient,\n TTasks extends Record<string, AuthenticatedTask<TClient, any, any, any>>\n> =\n | {\n usesLocalAuth: true;\n client: TClient;\n tasks?: TTasks;\n auth: any;\n }\n | {\n usesLocalAuth: false;\n clientFactory: ClientFactory<TClient>;\n tasks?: TTasks;\n };\n\nexport type AuthenticatedTask<\n TClient,\n TParams,\n TResult,\n TAuth = ConnectionAuth\n> = {\n run: (\n params: TParams,\n client: TClient,\n task: ServerTask,\n io: IO,\n auth: TAuth\n ) => Promise<TResult>;\n init: (params: TParams) => RunTaskOptions;\n onError?: (\n error: unknown,\n task: ServerTask\n ) => { retryAt: Date; error?: Error } | undefined | void;\n};\n\nexport function authenticatedTask<TClient, TParams, TResult>(options: {\n run: (\n params: TParams,\n client: TClient,\n task: ServerTask,\n io: IO\n ) => Promise<TResult>;\n init: (params: TParams) => RunTaskOptions;\n}): AuthenticatedTask<TClient, TParams, TResult> {\n return options;\n}\n\ntype ExtractRunFunction<T> = T extends AuthenticatedTask<\n any,\n infer TParams,\n infer TResult,\n infer TAuth\n>\n ? (key: string, params: TParams) => Promise<TResult>\n : never;\n\ntype ExtractTasks<\n TTasks extends Record<string, AuthenticatedTask<any, any, any, any>>\n> = {\n [key in keyof TTasks]: ExtractRunFunction<TTasks[key]>;\n};\n\ntype ExtractIntegrationClientClient<\n TIntegrationClient extends IntegrationClient<any, any>\n> = TIntegrationClient extends {\n usesLocalAuth: true;\n client: infer TClient;\n}\n ? { client: TClient }\n : TIntegrationClient extends {\n usesLocalAuth: false;\n clientFactory: ClientFactory<infer TClient>;\n }\n ? { client: TClient }\n : never;\n\ntype ExtractIntegrationClient<\n TIntegrationClient extends IntegrationClient<any, any>\n> = ExtractIntegrationClientClient<TIntegrationClient> &\n ExtractTasks<TIntegrationClient[\"tasks\"]>;\n\ntype ExtractIntegrations<\n TIntegrations extends Record<\n string,\n TriggerIntegration<IntegrationClient<any, any>>\n >\n> = {\n [key in keyof TIntegrations]: ExtractIntegrationClient<\n TIntegrations[key][\"client\"]\n >;\n};\n\nexport type IOWithIntegrations<\n TIntegrations extends Record<\n string,\n TriggerIntegration<IntegrationClient<any, any>>\n >\n> = IO & ExtractIntegrations<TIntegrations>;\n","import { z } from \"zod\";\n\nimport {\n DisplayProperty,\n EventFilter,\n HandleTriggerSource,\n Logger,\n NormalizedResponse,\n RegisterSourceEvent,\n SendEvent,\n TriggerMetadata,\n UpdateTriggerSourceBody,\n deepMergeFilters,\n} from \"@trigger.dev/internal\";\nimport {\n IOWithIntegrations,\n IntegrationClient,\n TriggerIntegration,\n} from \"../integrations\";\nimport { IO } from \"../io\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport type { EventSpecification, 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 RegisterFunctionEvent<\n TChannel extends ChannelNames,\n TParams extends any\n> = {\n events: Array<string>;\n missingEvents: Array<string>;\n orphanedEvents: Array<string>;\n source: {\n active: boolean;\n data?: any;\n secret: string;\n } & ExternalSourceChannelMap[TChannel][\"register\"];\n params: TParams;\n};\n\ntype RegisterFunction<\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any,\n TChannel extends ChannelNames\n> = (\n event: RegisterFunctionEvent<TChannel, TParams>,\n io: IOWithIntegrations<{ integration: TIntegration }>,\n ctx: TriggerContext\n) => Promise<UpdateTriggerSourceBody | undefined>;\n\nexport type HandlerEvent<\n TChannel extends ChannelNames,\n TParams extends any = any\n> = {\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"];\n source: HandleTriggerSource & { params: TParams };\n};\n\ntype HandlerFunction<TChannel extends ChannelNames, TParams extends any> = (\n event: HandlerEvent<TChannel, TParams>,\n logger: Logger\n) => Promise<{ events: SendEvent[]; response?: NormalizedResponse } | void>;\n\ntype KeyFunction<TParams extends any> = (params: TParams) => string;\ntype FilterFunction<TParams extends any> = (params: TParams) => EventFilter;\n\ntype ExternalSourceOptions<\n TChannel extends ChannelNames,\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any\n> = {\n id: string;\n version: string;\n schema: z.Schema<TParams>;\n integration: TIntegration;\n register: RegisterFunction<TIntegration, TParams, TChannel>;\n filter: FilterFunction<TParams>;\n handler: HandlerFunction<TChannel, TParams>;\n key: KeyFunction<TParams>;\n properties?: (params: TParams) => DisplayProperty[];\n};\n\nexport class ExternalSource<\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any,\n TChannel extends ChannelNames = ChannelNames\n> {\n channel: TChannel;\n\n constructor(\n channel: TChannel,\n private options: ExternalSourceOptions<TChannel, TIntegration, TParams>\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 );\n }\n\n filter(params: TParams): EventFilter {\n return this.options.filter(params);\n }\n\n properties(params: TParams): DisplayProperty[] {\n return this.options.properties?.(params) ?? [];\n }\n\n async register(\n params: TParams,\n registerEvent: RegisterSourceEvent,\n io: IO,\n ctx: TriggerContext\n ) {\n const { result: event, ommited: source } = omit(registerEvent, \"source\");\n const { result: sourceWithoutChannel, ommited: channel } = omit(\n source,\n \"channel\"\n );\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<\n TExternalSource extends ExternalSource<any, any, any>\n> = TExternalSource extends ExternalSource<any, infer TParams, any>\n ? TParams\n : never;\n\nexport type ExternalSourceTriggerOptions<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>\n> = {\n event: TEventSpecification;\n source: TEventSource;\n params: ExternalSourceParams<TEventSource>;\n};\n\nexport class ExternalSourceTrigger<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>\n> implements Trigger<TEventSpecification>\n{\n constructor(\n private options: ExternalSourceTriggerOptions<\n TEventSpecification,\n TEventSource\n >\n ) {}\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),\n this.event.filter ?? {}\n ),\n source: this.event.source,\n },\n properties: this.options.source.properties(this.options.params),\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<TEventSpecification>, any>\n ) {\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 });\n }\n\n get preprocessRuns() {\n return true;\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 RegisterSourceEvent,\n RegisterTriggerBody,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/internal\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport { slugifyId } from \"../utils\";\nimport { ExternalSource, ExternalSourceParams } from \"./externalSource\";\n\nexport type DynamicTriggerOptions<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>\n> = {\n id: string;\n event: TEventSpec;\n source: TExternalSource;\n};\n\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 constructor(\n client: TriggerClient,\n options: DynamicTriggerOptions<TEventSpec, TExternalSource>\n ) {\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 registeredTriggerForParams(\n params: ExternalSourceParams<TExternalSource>\n ): RegisterTriggerBody {\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 ),\n },\n source: {\n key: slugifyId(this.source.key(params)),\n channel: this.source.channel,\n params,\n events: [this.event.name],\n integration: {\n id: this.source.integration.id,\n metadata: this.source.integration.metadata,\n authSource: this.source.integration.client.usesLocalAuth\n ? \"LOCAL\"\n : \"HOSTED\",\n },\n },\n };\n }\n\n async register(\n key: string,\n params: ExternalSourceParams<TExternalSource>\n ): Promise<RegisterSourceEvent> {\n return this.#client.registerTrigger(\n this.id,\n key,\n this.registeredTriggerForParams(params)\n );\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<TEventSpec>, any>\n ): void {\n triggerClient.attachJobToDynamicTrigger(job, this);\n }\n\n get preprocessRuns() {\n return true;\n }\n}\n","import {\n CronOptions,\n EventExample,\n IntervalOptions,\n ScheduleMetadata,\n ScheduledPayload,\n ScheduledPayloadSchema,\n TriggerMetadata,\n currentDate,\n} from \"@trigger.dev/internal\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\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 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\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 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: \"Expression\",\n text: this.options.cron,\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 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\nexport function cronTrigger(options: CronOptions) {\n return new CronTrigger(options);\n}\n\nexport type DynamicIntervalOptions = { id: string };\n\nexport class DynamicSchedule implements Trigger<ScheduledEventSpecification> {\n constructor(\n private client: TriggerClient,\n private options: DynamicIntervalOptions\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 return this.client.registerSchedule(this.id, key, metadata);\n }\n\n async unregister(key: string) {\n return this.client.unregisterSchedule(this.id, key);\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {\n triggerClient.attachDynamicSchedule(this.options.id, job);\n }\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.options.id,\n };\n }\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/internal\";\nimport { TriggerIntegration } from \"../integrations\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\n\nexport function missingConnectionNotification(\n integrations: Array<TriggerIntegration>\n) {\n return new MissingConnectionNotification({ integrations });\n}\n\nexport function missingConnectionResolvedNotification(\n integrations: Array<TriggerIntegration>\n) {\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 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 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAO,SAASA,UAAUC,OAAuB;AAE/C,QAAMC,wBAAwBD,MAAME,YAAW,EAAGC,QAAQ,QAAQ,GAAA;AAGlE,QAAMC,wBAAwBH,sBAAsBE,QAClD,qBACA,EAAA;AAGF,SAAOC;AACT;AAXgBL;;;ACkBhB;AA0BO,IAAMM,MAAN,MAAMA;EAWXC,YACEC,QACAC,SACA;AAqEF;AApEE,SAAKD,SAASA;AACd,SAAKC,UAAUA;AACf,0BAAK,wBAAL;AAEAD,WAAOE,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O,KAAKH,MAAMG;MAClBmB,MAAM;QACJtB,OAAO,KAAKA,MAAMC;QAClBG,QAAQ;QACRmB,SAAS;UACPC,QAAQ;YACNV,IAAI,KAAKf,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE;UAC/C;QACF;MACF;IACF;EACF;AACF;AA7CanB;AAkDN,IAAME,wCAAN,MAAMA;EAGXC,YAAoBC,SAA+C;mBAA/CA;EAAgD;EAEpE,IAAIC,QAAQ;AACV,WAAO;MACLC,MAAMwB;MACNtB,OAAO;MACPC,QAAQ;MACRC,MAAM;MACNC,cAAcoB,mDAAmDlB;MACjEC,YAAY;QACV;UACEC,OAAO;UACPC,MAAM,KAAKZ,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE,EAAEC,KAAK,IAAA;QACxD;;IAEJ;EACF;EAEAC,YACEC,eACAC,KACM;EAAC;EAET,IAAIC,iBAAiB;AACnB,WAAO;EACT;EAEAC,SAA0B;AACxB,WAAO;MACLC,MAAM;MACNlB,OAAO,KAAKH,MAAMG;MAClBmB,MAAM;QACJtB,OAAO,KAAKA,MAAMC;QAClBG,QAAQ;QACRmB,SAAS;UACPC,QAAQ;YACNV,IAAI,KAAKf,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE;UAC/C;QACF;MACF;IACF;EACF;AACF;AA7CajB;;;A5BrDN,SAAS8B,aACdC,YACGC,gBACW;AACd,SAAO;IACLC,kBAAkB;IAClBF,SAASA,QAAQG;IACjBF;EACF;AACF;AATgBF;","names":["slugifyId","input","replaceSpacesWithDash","toLowerCase","replace","removeNonUrlSafeChars","Job","constructor","client","options","attach","id","slugifyId","enabled","name","trigger","version","integrations","Object","keys","reduce","acc","key","integration","metadata","authSource","usesLocalAuth","toJSON","internal","__internal","event","queue","startPosition","preprocessRuns","match","Error","logLevels","Logger","constructor","name","level","filteredKeys","jsonReplacer","indexOf","process","env","TRIGGER_LOG_LEVEL","filter","keys","log","args","console","formattedDateTime","error","warn","info","debug","message","structuredLog","timestamp","Date","structureArgs","safeJsonClone","JSON","stringify","createReplacer","replacer","key","value","toString","bigIntReplacer","_key","obj","parse","e","date","hours","getHours","minutes","getMinutes","seconds","getSeconds","milliseconds","getMilliseconds","formattedHours","formattedMinutes","formattedSeconds","formattedMilliseconds","length","filterKeys","Array","isArray","map","item","filteredObj","Object","entries","includes","import_zod","ErrorWithStackSchema","z","object","message","string","name","optional","stack","import_zod","EventMatcherSchema","z","union","array","string","number","boolean","EventFilterSchema","lazy","record","EventRuleSchema","object","event","source","payload","optional","context","import_zod","ConnectionAuthSchema","z","object","type","enum","accessToken","string","scopes","array","optional","additionalFields","record","IntegrationMetadataSchema","id","name","instructions","IntegrationConfigSchema","metadata","authSource","import_zod","LiteralSchema","z","union","string","number","boolean","null","DeserializedJsonSchema","lazy","array","record","SerializableSchema","date","undefined","symbol","SerializableJsonSchema","import_zod","DisplayPropertySchema","z","object","label","string","text","url","optional","DisplayPropertiesSchema","array","StyleSchema","style","enum","variant","import_zod","ScheduledPayloadSchema","z","object","ts","coerce","date","lastTimestamp","optional","IntervalOptionsSchema","seconds","number","int","positive","min","max","CronOptionsSchema","cron","string","CronMetadataSchema","type","literal","options","metadata","any","IntervalMetadataSchema","ScheduleMetadataSchema","discriminatedUnion","RegisterDynamicSchedulePayloadSchema","id","jobs","array","version","import_zod","TaskStatusSchema","z","enum","TaskSchema","object","id","string","name","icon","optional","nullable","noop","boolean","startedAt","coerce","date","completedAt","delayUntil","status","description","properties","array","DisplayPropertySchema","params","DeserializedJsonSchema","output","error","parentId","style","StyleSchema","operation","ServerTaskSchema","extend","idempotencyKey","attempts","number","CachedTaskSchema","default","import_zod","EventExampleSchema","z","object","id","string","icon","optional","name","payload","any","EventSpecificationSchema","title","source","filter","EventFilterSchema","properties","array","DisplayPropertySchema","schema","examples","DynamicTriggerMetadataSchema","type","literal","StaticTriggerMetadataSchema","rule","EventRuleSchema","ScheduledTriggerMetadataSchema","schedule","ScheduleMetadataSchema","TriggerMetadataSchema","discriminatedUnion","UpdateTriggerSourceBodySchema","z","object","registeredEvents","array","string","secret","optional","data","SerializableJsonSchema","HttpEventSourceSchema","extend","id","active","boolean","url","RegisterHTTPTriggerSourceBodySchema","type","literal","RegisterSMTPTriggerSourceBodySchema","RegisterSQSTriggerSourceBodySchema","RegisterSourceChannelBodySchema","discriminatedUnion","REGISTER_SOURCE_EVENT","RegisterTriggerSourceSchema","key","params","any","DeserializedJsonSchema","channel","clientId","RegisterSourceEventSchema","source","events","missingEvents","orphanedEvents","dynamicTriggerId","TriggerSourceSchema","HandleTriggerSourceSchema","HttpSourceRequestSchema","method","headers","record","rawBody","instanceof","Buffer","nullable","HttpSourceRequestHeadersSchema","transform","s","JSON","parse","PongSuccessResponseSchema","ok","PongErrorResponseSchema","error","PongResponseSchema","QueueOptionsSchema","name","maxConcurrent","number","JobMetadataSchema","version","event","EventSpecificationSchema","trigger","TriggerMetadataSchema","integrations","IntegrationConfigSchema","internal","default","queue","union","startPosition","enum","enabled","preprocessRuns","SourceMetadataSchema","integration","DynamicTriggerEndpointMetadataSchema","jobs","pick","IndexEndpointResponseSchema","sources","dynamicTriggers","dynamicSchedules","RegisterDynamicSchedulePayloadSchema","RawEventSchema","ulid","payload","context","timestamp","datetime","ApiEventLogSchema","coerce","date","deliverAt","deliveredAt","SendEventOptionsSchema","deliverAfter","int","accountId","SendEventBodySchema","options","DeliverEventResponseSchema","RuntimeEnvironmentTypeSchema","RunSourceContextSchema","metadata","RunJobBodySchema","job","run","isTest","startedAt","environment","slug","organization","title","account","tasks","CachedTaskSchema","connections","ConnectionAuthSchema","RunJobErrorSchema","status","ErrorWithStackSchema","task","TaskSchema","RunJobResumeWithTaskSchema","RunJobRetryWithTaskSchema","retryAt","RunJobSuccessSchema","output","RunJobResponseSchema","PreprocessRunBodySchema","PreprocessRunResponseSchema","abort","properties","DisplayPropertySchema","CreateRunBodySchema","client","CreateRunResponseOkSchema","CreateRunResponseErrorSchema","CreateRunResponseBodySchema","RedactStringSchema","__redactedString","strings","interpolations","LogMessageSchema","level","message","RedactSchema","paths","RetryOptionsSchema","limit","factor","minTimeoutInMs","maxTimeoutInMs","randomize","RunTaskOptionsSchema","icon","displayKey","noop","operation","delayUntil","description","redact","connectionKey","style","StyleSchema","retry","RunTaskBodyInputSchema","idempotencyKey","parentId","RunTaskBodyOutputSchema","CompleteTaskBodyInputSchema","v","stringify","FailTaskBodyInputSchema","NormalizedRequestSchema","query","body","NormalizedResponseSchema","HttpSourceResponseSchema","response","RegisterTriggerBodySchema","rule","EventRuleSchema","InitializeTriggerBodySchema","RegisterCommonScheduleBodySchema","RegisterIntervalScheduleBodySchema","merge","IntervalMetadataSchema","InitializeCronScheduleBodySchema","CronMetadataSchema","RegisterScheduleBodySchema","RegisterScheduleResponseBodySchema","schedule","ScheduleMetadataSchema","CreateExternalConnectionBodySchema","accessToken","scopes","import_zod","MISSING_CONNECTION_NOTIFICATION","MISSING_CONNECTION_RESOLVED_NOTIFICATION","CommonMissingConnectionNotificationPayloadSchema","z","object","id","string","client","title","scopes","array","createdAt","coerce","date","updatedAt","authorizationUrl","MissingDeveloperConnectionNotificationPayloadSchema","extend","type","literal","MissingExternalConnectionNotificationPayloadSchema","account","metadata","any","MissingConnectionNotificationPayloadSchema","discriminatedUnion","CommonMissingConnectionNotificationResolvedPayloadSchema","integrationIdentifier","integrationAuthMethod","expiresAt","MissingDeveloperConnectionResolvedNotificationPayloadSchema","MissingExternalConnectionResolvedNotificationPayloadSchema","MissingConnectionResolvedNotificationPayloadSchema","import_zod","FetchRetryHeadersStrategySchema","z","object","strategy","literal","limitHeader","string","remainingHeader","resetHeader","FetchRetryBackoffStrategySchema","RetryOptionsSchema","extend","FetchRetryStrategySchema","discriminatedUnion","FetchRequestInitSchema","method","optional","headers","record","union","RedactStringSchema","body","instanceof","ArrayBuffer","FetchRetryOptionsSchema","FetchOperationSchema","url","requestInit","retry","deepMergeFilters","filter","other","result","key","hasOwnProperty","otherValue","Array","isArray","filterValue","DEFAULT_RETRY_OPTIONS","limit","factor","minTimeoutInMs","maxTimeoutInMs","randomize","calculateRetryAt","retryOptions","attempts","options","retryCount","random","Math","timeoutInMs","round","max","pow","min","Date","now","currentDate","marker","replace","data","now","toISOString","import_zod","ApiClient","constructor","options","apiUrl","process","env","TRIGGER_API_URL","Logger","logLevel","registerEndpoint","apiKey","debug","url","name","response","fetch","method","headers","Authorization","body","JSON","stringify","status","json","Error","error","createRun","params","zodfetch","CreateRunResponseBodySchema","runTask","runId","task","ServerTaskSchema","idempotencyKey","completeTask","id","failTask","sendEvent","event","ApiEventLogSchema","updateSource","client","key","source","TriggerSourceSchema","registerTrigger","payload","RegisterSourceEventSchema","registerSchedule","RegisterScheduleResponseBodySchema","unregisterSchedule","z","object","ok","boolean","encodeURIComponent","getAuth","ConnectionAuthSchema","Accept","optional","getApiKey","TRIGGER_API_KEY","isValid","match","schema","requestInit","errorMessage","jsonBody","parse","ResumeWithTaskError","constructor","task","RetryWithTaskError","cause","retryAt","isTriggerError","err","createIOWithIntegrations","io","auths","integrations","connections","Object","entries","reduce","acc","connectionKey","integration","auth","client","usesLocalAuth","clientFactory","undefined","ioConnection","tasks","keys","forEach","taskName","authenticatedTask","key","params","options","init","runTask","ioTask","run","onError","Proxy","get","target","prop","receiver","value","Reflect","bind","IO","constructor","options","_id","id","_apiClient","apiClient","_triggerClient","client","_logger","logger","Logger","logLevel","_cachedTasks","Map","cachedTasks","forEach","task","set","_taskStorage","AsyncLocalStorage","_context","context","IOLogger","level","message","data","debug","info","warn","error","runTask","name","icon","description","params","properties","label","text","style","variant","toLowerCase","noop","wait","key","seconds","delayUntil","Date","now","backgroundFetch","url","requestInit","retry","urlObject","URL","hostname","pathname","operation","method","output","sendEvent","event","updateSource","redact","paths","registerInterval","dynamicSchedule","toString","register","type","unregisterInterval","unregister","registerCron","cron","unregisterCron","registerTrigger","trigger","registration","subtask1","connection","getAuth","source","clientId","io","createIOWithIntegrations","integration","updates","callback","onError","parentId","getStore","taskId","idempotencyKey","generateIdempotencyKey","flat","cachedTask","get","displayKey","undefined","status","Error","ResumeWithTaskError","executeTask","result","completeTask","isTriggerError","onErrorResult","parsedError","ErrorWithStackSchema","safeParse","RetryWithTaskError","success","retryAt","calculateRetryAt","attempts","failTask","JSON","stringify","run","try","tryCallback","catchCallback","keyMaterial","keys","map","stableStringify","join","hash","webcrypto","subtle","digest","Buffer","from","obj","sortKeys","Array","isArray","sortedKeys","Object","sort","sortedObj","_options","EventTrigger","constructor","options","toJSON","type","title","name","event","rule","source","payload","deepMergeFilters","filter","attachToJob","triggerClient","job","preprocessRuns","eventTrigger","icon","parsePayload","rawPayload","schema","parse","registerSourceEvent","name","REGISTER_SOURCE_EVENT","title","source","icon","parsePayload","RegisterSourceEventSchema","parse","_options","_logger","TriggerClient","constructor","options","id","ApiClient","Logger","logLevel","handleRequest","request","debug","url","headers","Object","fromEntries","entries","method","apiKey","get","authorization","authorized","status","body","message","action","endpointId","ok","jobId","job","toJSON","jobs","values","map","sources","dynamicTriggers","trigger","dynamicSchedules","json","InitializeTriggerBodySchema","safeParse","success","dynamicTrigger","data","registeredTriggerForParams","params","execution","RunJobBodySchema","results","PreprocessRunBodySchema","abort","properties","HttpSourceRequestHeadersSchema","sourceRequest","Request","undefined","key","dynamicId","secret","response","events","attach","enabled","attachToJob","attachDynamicTrigger","Job","version","EventTrigger","event","filter","dynamicTriggerId","integrations","integration","run","io","ctx","updates","register","updateSource","__internal","attachJobToDynamicTrigger","push","attachSource","s","r","handle","registeredSource","channel","metadata","authSource","client","usesLocalAuth","Array","from","Set","queue","maxConcurrent","startPosition","attachDynamicSchedule","registerTrigger","getAuth","sendEvent","registerSchedule","schedule","unregisterSchedule","localApiKey","process","env","TRIGGER_API_KEY","context","parsedPayload","payload","runProperties","IO","cachedTasks","tasks","apiClient","logger","ioWithConnections","createIOWithIntegrations","connections","output","error","ResumeWithTaskError","task","RetryWithTaskError","cause","retryAt","errorWithStack","ErrorWithStackSchema","organization","environment","timestamp","account","handler","authenticatedTask","options","ExternalSource","constructor","channel","options","handle","source","rawEvent","logger","handler","params","filter","properties","register","registerEvent","io","ctx","result","event","ommited","omit","sourceWithoutChannel","channelWithoutType","updates","key","parts","id","push","integration","join","integrationConfig","metadata","version","ExternalSourceTrigger","toJSON","type","title","rule","name","payload","deepMergeFilters","attachToJob","triggerClient","job","attachSource","slugifyId","preprocessRuns","obj","k","Object","keys","_client","_options","DynamicTrigger","constructor","client","options","source","attachDynamicTrigger","toJSON","type","id","event","registeredTriggerForParams","params","rule","name","payload","deepMergeFilters","filter","key","slugifyId","channel","events","integration","metadata","authSource","usesLocalAuth","register","registerTrigger","attachToJob","triggerClient","job","attachJobToDynamicTrigger","preprocessRuns","examples","id","name","icon","payload","ts","currentDate","marker","lastTimestamp","IntervalTrigger","constructor","options","event","title","source","parsePayload","ScheduledPayloadSchema","parse","properties","label","text","seconds","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","schedule","intervalTrigger","CronTrigger","cron","cronTrigger","DynamicSchedule","client","register","key","metadata","registerSchedule","unregister","unregisterSchedule","attachDynamicSchedule","missingConnectionNotification","integrations","MissingConnectionNotification","missingConnectionResolvedNotification","MissingConnectionResolvedNotification","constructor","options","event","name","MISSING_CONNECTION_NOTIFICATION","title","source","icon","parsePayload","MissingConnectionNotificationPayloadSchema","parse","properties","label","text","map","i","id","join","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","rule","payload","client","MISSING_CONNECTION_RESOLVED_NOTIFICATION","MissingConnectionResolvedNotificationPayloadSchema","redactString","strings","interpolations","__redactedString","raw"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/job.ts","../../internal/src/logger.ts","../../internal/src/schemas/api.ts","../../internal/src/schemas/errors.ts","../../internal/src/schemas/eventFilter.ts","../../internal/src/schemas/integrations.ts","../../internal/src/schemas/json.ts","../../internal/src/schemas/properties.ts","../../internal/src/schemas/schedules.ts","../../internal/src/schemas/tasks.ts","../../internal/src/schemas/triggers.ts","../../internal/src/schemas/notifications.ts","../../internal/src/schemas/fetch.ts","../../internal/src/utils.ts","../../internal/src/retry.ts","../../internal/src/replacements.ts","../src/apiClient.ts","../src/errors.ts","../src/io.ts","../src/ioWithIntegrations.ts","../src/triggers/eventTrigger.ts","../src/triggerClient.ts","../src/integrations.ts","../src/triggers/externalSource.ts","../src/triggers/dynamic.ts","../src/triggers/scheduled.ts","../src/triggers/notifications.ts"],"sourcesContent":["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 \"./io\";\nexport * from \"./types\";\n\nimport { ServerTask } from \"@trigger.dev/internal\";\nimport { RedactString } from \"./types\";\nexport { isTriggerError } from \"./errors\";\n\nexport type { NormalizedRequest, EventFilter } from \"@trigger.dev/internal\";\n\nexport type Task = ServerTask;\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 ctx.fetch(\"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","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(\n /[^a-zA-Z0-9-._~]/g,\n \"\"\n );\n\n return removeNonUrlSafeChars;\n}\n","import {\n IntegrationConfig,\n JobMetadata,\n LogLevel,\n QueueOptions,\n} from \"@trigger.dev/internal\";\nimport {\n IOWithIntegrations,\n IntegrationClient,\n TriggerIntegration,\n} from \"./integrations\";\nimport { TriggerClient } from \"./triggerClient\";\nimport type {\n EventSpecification,\n Logger,\n Trigger,\n TriggerContext,\n TriggerEventType,\n} from \"./types\";\nimport { slugifyId } from \"./utils\";\n\nexport type JobOptions<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<\n string,\n TriggerIntegration<IntegrationClient<any, any>>\n > = {}\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 new Job(client, {\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 /** The `queue` property is used to specify a custom queue. If you use an Object and specify the `maxConcurrent` option, you can control how many simulataneous runs can happen. */\n queue?: QueueOptions | string;\n startPosition?: \"initial\" | \"latest\";\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<any>;\n};\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<\n string,\n TriggerIntegration<IntegrationClient<any, any>>\n > = {}\n> {\n readonly options: JobOptions<TTrigger, TIntegrations>;\n\n client: TriggerClient;\n\n constructor(\n /** An instance of [TriggerClient](/sdk/triggerclient) that is used to send events\n to the Trigger API. */\n client: TriggerClient,\n options: JobOptions<TTrigger, TIntegrations>\n ) {\n this.client = client;\n this.options = options;\n this.#validate();\n\n client.attach(this);\n }\n\n get id() {\n return slugifyId(this.options.id);\n }\n\n get enabled() {\n return typeof this.options.enabled === \"boolean\"\n ? this.options.enabled\n : 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 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.client.usesLocalAuth ? \"LOCAL\" : \"HOSTED\",\n };\n\n return acc;\n },\n {}\n );\n }\n\n get logLevel() {\n return this.options.logLevel;\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 queue: this.options.queue,\n startPosition: this.options.startPosition ?? \"latest\",\n enabled:\n typeof this.options.enabled === \"boolean\" ? this.options.enabled : true,\n preprocessRuns: this.trigger.preprocessRuns,\n internal,\n };\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","// Create a logger class that uses the debug package internally\n\n/**\n * Represents different log levels.\n * - `\"log\"`: Only essential messages.\n * - `\"error\"`: Errors and essential messages.\n * - `\"warn\"`: Warnings, Errors and essential messages.\n * - `\"info\"`: Info, Warnings, Errors and essential messages.\n * - `\"debug\"`: Everything.\n */\nexport type LogLevel = \"log\" | \"error\" | \"warn\" | \"info\" | \"debug\";\n\nconst logLevels: Array<LogLevel> = [\"log\", \"error\", \"warn\", \"info\", \"debug\"];\n\nexport class Logger {\n #name: string;\n readonly #level: number;\n #filteredKeys: string[] = [];\n #jsonReplacer?: (key: string, value: unknown) => unknown;\n\n constructor(\n name: string,\n level: LogLevel = \"info\",\n filteredKeys: string[] = [],\n jsonReplacer?: (key: string, value: unknown) => unknown\n ) {\n this.#name = name;\n this.#level = logLevels.indexOf(\n (process.env.TRIGGER_LOG_LEVEL ?? level) as LogLevel\n );\n this.#filteredKeys = filteredKeys;\n this.#jsonReplacer = jsonReplacer;\n }\n\n // Return a new Logger instance with the same name and a new log level\n // but filter out the keys from the log messages (at any level)\n filter(...keys: string[]) {\n return new Logger(\n this.#name,\n logLevels[this.#level],\n keys,\n this.#jsonReplacer\n );\n }\n\n static satisfiesLogLevel(logLevel: LogLevel, setLevel: LogLevel) {\n return logLevels.indexOf(logLevel) <= logLevels.indexOf(setLevel);\n }\n\n log(...args: any[]) {\n if (this.#level < 0) return;\n\n console.log(`[${formattedDateTime()}] [${this.#name}] `, ...args);\n }\n\n error(...args: any[]) {\n if (this.#level < 1) return;\n\n console.error(`[${formattedDateTime()}] [${this.#name}] `, ...args);\n }\n\n warn(...args: any[]) {\n if (this.#level < 2) return;\n\n console.warn(`[${formattedDateTime()}] [${this.#name}] `, ...args);\n }\n\n info(...args: any[]) {\n if (this.#level < 3) return;\n\n console.info(`[${formattedDateTime()}] [${this.#name}] `, ...args);\n }\n\n debug(message: string, ...args: Array<Record<string, unknown> | undefined>) {\n if (this.#level < 4) return;\n\n const structuredLog = {\n timestamp: new Date(),\n name: this.#name,\n message,\n args: structureArgs(\n safeJsonClone(args) as Record<string, unknown>[],\n this.#filteredKeys\n ),\n };\n\n console.debug(\n JSON.stringify(structuredLog, createReplacer(this.#jsonReplacer))\n );\n }\n}\n\nfunction createReplacer(replacer?: (key: string, value: unknown) => unknown) {\n return (key: string, value: unknown) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n if (replacer) {\n return replacer(key, value);\n }\n\n return value;\n };\n}\n\n// Replacer function for JSON.stringify that converts BigInts to strings\nfunction bigIntReplacer(_key: string, value: unknown) {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return value;\n}\n\nfunction safeJsonClone(obj: unknown) {\n try {\n return JSON.parse(JSON.stringify(obj, bigIntReplacer));\n } catch (e) {\n return obj;\n }\n}\n\nfunction formattedDateTime() {\n const date = new Date();\n\n const hours = date.getHours();\n const minutes = date.getMinutes();\n const seconds = date.getSeconds();\n const milliseconds = date.getMilliseconds();\n\n // Make sure the time is always 2 digits\n const formattedHours = hours < 10 ? `0${hours}` : hours;\n const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes;\n const formattedSeconds = seconds < 10 ? `0${seconds}` : seconds;\n const formattedMilliseconds =\n milliseconds < 10\n ? `00${milliseconds}`\n : milliseconds < 100\n ? `0${milliseconds}`\n : milliseconds;\n\n return `${formattedHours}:${formattedMinutes}:${formattedSeconds}.${formattedMilliseconds}`;\n}\n\n// If args is has a single item that is an object, return that object\nfunction structureArgs(\n args: Array<Record<string, unknown>>,\n filteredKeys: string[] = []\n) {\n if (args.length === 0) {\n return;\n }\n\n if (args.length === 1 && typeof args[0] === \"object\") {\n return filterKeys(\n JSON.parse(JSON.stringify(args[0], bigIntReplacer)),\n filteredKeys\n );\n }\n\n return args;\n}\n\n// Recursively filter out keys from an object, including nested objects, and arrays\nfunction filterKeys(obj: unknown, keys: string[]): any {\n if (typeof obj !== \"object\" || obj === null) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => filterKeys(item, keys));\n }\n\n const filteredObj: any = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (keys.includes(key)) {\n continue;\n }\n\n filteredObj[key] = filterKeys(value, keys);\n }\n\n return filteredObj;\n}\n","import { ulid } from \"ulid\";\nimport { z } from \"zod\";\nimport { ErrorWithStackSchema } from \"./errors\";\nimport { EventRuleSchema } from \"./eventFilter\";\nimport { ConnectionAuthSchema, IntegrationConfigSchema } from \"./integrations\";\nimport { DeserializedJsonSchema, SerializableJsonSchema } from \"./json\";\nimport { DisplayPropertySchema, StyleSchema } from \"./properties\";\nimport {\n CronMetadataSchema,\n IntervalMetadataSchema,\n RegisterDynamicSchedulePayloadSchema,\n ScheduleMetadataSchema,\n} from \"./schedules\";\nimport { CachedTaskSchema, ServerTaskSchema, TaskSchema } from \"./tasks\";\nimport { EventSpecificationSchema, TriggerMetadataSchema } from \"./triggers\";\n\nexport const UpdateTriggerSourceBodySchema = z.object({\n registeredEvents: z.array(z.string()),\n secret: z.string().optional(),\n data: SerializableJsonSchema.optional(),\n});\n\nexport type UpdateTriggerSourceBody = z.infer<\n typeof UpdateTriggerSourceBodySchema\n>;\n\nexport const HttpEventSourceSchema = UpdateTriggerSourceBodySchema.extend({\n id: z.string(),\n active: z.boolean(),\n url: z.string().url(),\n});\n\nexport const RegisterHTTPTriggerSourceBodySchema = z.object({\n type: z.literal(\"HTTP\"),\n url: z.string().url(),\n});\n\nexport const RegisterSMTPTriggerSourceBodySchema = z.object({\n type: z.literal(\"SMTP\"),\n});\n\nexport const RegisterSQSTriggerSourceBodySchema = z.object({\n type: z.literal(\"SQS\"),\n});\n\nexport const RegisterSourceChannelBodySchema = z.discriminatedUnion(\"type\", [\n RegisterHTTPTriggerSourceBodySchema,\n RegisterSMTPTriggerSourceBodySchema,\n RegisterSQSTriggerSourceBodySchema,\n]);\n\nexport const REGISTER_SOURCE_EVENT = \"dev.trigger.source.register\";\n\nexport const RegisterTriggerSourceSchema = z.object({\n key: z.string(),\n params: z.any(),\n active: z.boolean(),\n secret: z.string(),\n data: DeserializedJsonSchema.optional(),\n channel: RegisterSourceChannelBodySchema,\n clientId: z.string().optional(),\n});\n\nexport type RegisterTriggerSource = z.infer<typeof RegisterTriggerSourceSchema>;\n\nexport const RegisterSourceEventSchema = z.object({\n id: z.string(),\n source: RegisterTriggerSourceSchema,\n events: z.array(z.string()),\n missingEvents: z.array(z.string()),\n orphanedEvents: z.array(z.string()),\n dynamicTriggerId: z.string().optional(),\n});\n\nexport type RegisterSourceEvent = z.infer<typeof RegisterSourceEventSchema>;\n\nexport const TriggerSourceSchema = z.object({\n id: z.string(),\n key: z.string(),\n});\n\nexport const HandleTriggerSourceSchema = z.object({\n key: z.string(),\n secret: z.string(),\n data: z.any(),\n params: z.any(),\n});\n\nexport type HandleTriggerSource = z.infer<typeof HandleTriggerSourceSchema>;\n\nexport type TriggerSource = z.infer<typeof TriggerSourceSchema>;\n\nexport const HttpSourceRequestSchema = z.object({\n url: z.string().url(),\n method: z.string(),\n headers: z.record(z.string()),\n rawBody: z.instanceof(Buffer).optional().nullable(),\n});\n\nexport type HttpSourceRequest = z.infer<typeof HttpSourceRequestSchema>;\n\nexport const HttpSourceRequestHeadersSchema = z.object({\n \"x-ts-key\": z.string(),\n \"x-ts-dynamic-id\": z.string().optional(),\n \"x-ts-secret\": z.string(),\n \"x-ts-data\": z.string().transform((s) => JSON.parse(s)),\n \"x-ts-params\": z.string().transform((s) => JSON.parse(s)),\n \"x-ts-http-url\": z.string(),\n \"x-ts-http-method\": z.string(),\n \"x-ts-http-headers\": z\n .string()\n .transform((s) => z.record(z.string()).parse(JSON.parse(s))),\n});\n\nexport type HttpSourceRequestHeaders = z.output<\n typeof HttpSourceRequestHeadersSchema\n>;\n\nexport const PongSuccessResponseSchema = z.object({\n ok: z.literal(true),\n});\n\nexport const PongErrorResponseSchema = z.object({\n ok: z.literal(false),\n error: z.string(),\n});\n\nexport const PongResponseSchema = z.discriminatedUnion(\"ok\", [\n PongSuccessResponseSchema,\n PongErrorResponseSchema,\n]);\n\nexport type PongResponse = z.infer<typeof PongResponseSchema>;\n\nexport const QueueOptionsSchema = z.object({\n name: z.string(),\n maxConcurrent: z.number().optional(),\n});\n\nexport type QueueOptions = z.infer<typeof QueueOptionsSchema>;\n\nexport const JobMetadataSchema = z.object({\n id: z.string(),\n name: z.string(),\n version: z.string(),\n event: EventSpecificationSchema,\n trigger: TriggerMetadataSchema,\n integrations: z.record(IntegrationConfigSchema),\n internal: z.boolean().default(false),\n queue: z.union([QueueOptionsSchema, z.string()]).optional(),\n startPosition: z.enum([\"initial\", \"latest\"]),\n enabled: z.boolean(),\n preprocessRuns: z.boolean(),\n});\n\nexport type JobMetadata = z.infer<typeof JobMetadataSchema>;\n\nexport const SourceMetadataSchema = z.object({\n channel: z.enum([\"HTTP\", \"SQS\", \"SMTP\"]),\n integration: IntegrationConfigSchema,\n key: z.string(),\n params: z.any(),\n events: z.array(z.string()),\n});\n\nexport type SourceMetadata = z.infer<typeof SourceMetadataSchema>;\n\nexport const DynamicTriggerEndpointMetadataSchema = z.object({\n id: z.string(),\n jobs: z.array(JobMetadataSchema.pick({ id: true, version: true })),\n});\n\nexport type DynamicTriggerEndpointMetadata = z.infer<\n typeof DynamicTriggerEndpointMetadataSchema\n>;\n\nexport const IndexEndpointResponseSchema = z.object({\n jobs: z.array(JobMetadataSchema),\n sources: z.array(SourceMetadataSchema),\n dynamicTriggers: z.array(DynamicTriggerEndpointMetadataSchema),\n dynamicSchedules: z.array(RegisterDynamicSchedulePayloadSchema),\n});\n\nexport type IndexEndpointResponse = z.infer<typeof IndexEndpointResponseSchema>;\n\nexport const RawEventSchema = z.object({\n /** The `name` property must exactly match any subscriptions you want to\n trigger. */\n name: z.string(),\n /** The `payload` property will be sent to any matching Jobs and will appear\n as the `payload` param of the `run()` function. You can leave this\n parameter out if you just want to trigger a Job without any input data. */\n payload: z.any(),\n /** The optional `context` property will be sent to any matching Jobs and will\n be passed through as the `context.event.context` param of the `run()`\n function. This is optional but can be useful if you want to pass through\n some additional context to the Job. */\n context: z.any().optional(),\n /** The `id` property uniquely identify this particular event. If unset it\n will be set automatically using `ulid`. */\n id: z.string().default(() => ulid()),\n /** This is optional, it defaults to the current timestamp. Usually you would\n only set this if you have a timestamp that you wish to pass through, e.g.\n you receive a timestamp from a service and you want the same timestamp to\n be used in your Job. */\n timestamp: z.coerce.date().optional(),\n /** This is optional, it defaults to \"trigger.dev\". It can be useful to set\n this as you can filter events using this in the `eventTrigger()`. */\n source: z.string().optional(),\n});\n\nexport type RawEvent = z.infer<typeof RawEventSchema>;\n\n/** The event you wish to send to Trigger a Job */\nexport type SendEvent = z.input<typeof RawEventSchema>;\n\n/** The event that was sent */\nexport const ApiEventLogSchema = z.object({\n /** The `id` of the event that was sent.\n */\n id: z.string(),\n /** The `name` of the event that was sent. */\n name: z.string(),\n /** The `payload` of the event that was sent */\n payload: DeserializedJsonSchema,\n /** The `context` of the event that was sent. Is `undefined` if no context was\n set when sending the event. */\n context: DeserializedJsonSchema.optional().nullable(),\n /** The `timestamp` of the event that was sent */\n timestamp: z.coerce.date(),\n /** The timestamp when the event will be delivered to any matching Jobs. Is\n `undefined` if `deliverAt` or `deliverAfter` wasn't set when sending the\n event. */\n deliverAt: z.coerce.date().optional().nullable(),\n /** The timestamp when the event was delivered. Is `undefined` if `deliverAt`\n or `deliverAfter` were set when sending the event. */\n deliveredAt: z.coerce.date().optional().nullable(),\n});\n\nexport type ApiEventLog = z.infer<typeof ApiEventLogSchema>;\n\n/** Options to control the delivery of the event */\nexport const SendEventOptionsSchema = z.object({\n /** An optional Date when you want the event to trigger Jobs. The event will\n be sent to the platform immediately but won't be acted upon until the\n specified time. */\n deliverAt: z.coerce.date().optional(),\n /** An optional number of seconds you want to wait for the event to trigger\n any relevant Jobs. The event will be sent to the platform immediately but\n won't be delivered until after the elapsed number of seconds. */\n deliverAfter: z.number().int().optional(),\n /** This optional param will be used by Trigger.dev Connect, which\n is coming soon. */\n accountId: z.string().optional(),\n});\n\nexport const SendEventBodySchema = z.object({\n event: RawEventSchema,\n options: SendEventOptionsSchema.optional(),\n});\n\nexport type SendEventBody = z.infer<typeof SendEventBodySchema>;\nexport type SendEventOptions = z.infer<typeof SendEventOptionsSchema>;\n\nexport const DeliverEventResponseSchema = z.object({\n deliveredAt: z.string().datetime(),\n});\n\nexport type DeliverEventResponse = z.infer<typeof DeliverEventResponseSchema>;\n\nexport const RuntimeEnvironmentTypeSchema = z.enum([\n \"PRODUCTION\",\n \"STAGING\",\n \"DEVELOPMENT\",\n \"PREVIEW\",\n]);\n\nexport type RuntimeEnvironmentType = z.infer<\n typeof RuntimeEnvironmentTypeSchema\n>;\n\nexport const RunSourceContextSchema = z.object({\n id: z.string(),\n metadata: z.any(),\n});\n\nexport const RunJobBodySchema = z.object({\n event: ApiEventLogSchema,\n job: z.object({\n id: z.string(),\n version: z.string(),\n }),\n run: z.object({\n id: z.string(),\n isTest: z.boolean(),\n startedAt: z.coerce.date(),\n }),\n environment: z.object({\n id: z.string(),\n slug: z.string(),\n type: RuntimeEnvironmentTypeSchema,\n }),\n organization: z.object({\n id: z.string(),\n title: z.string(),\n slug: z.string(),\n }),\n account: z\n .object({\n id: z.string(),\n metadata: z.any(),\n })\n .optional(),\n source: RunSourceContextSchema.optional(),\n tasks: z.array(CachedTaskSchema).optional(),\n connections: z.record(ConnectionAuthSchema).optional(),\n});\n\nexport type RunJobBody = z.infer<typeof RunJobBodySchema>;\n\nexport const RunJobErrorSchema = z.object({\n status: z.literal(\"ERROR\"),\n error: ErrorWithStackSchema,\n task: TaskSchema.optional(),\n});\n\nexport type RunJobError = z.infer<typeof RunJobErrorSchema>;\n\nexport const RunJobResumeWithTaskSchema = z.object({\n status: z.literal(\"RESUME_WITH_TASK\"),\n task: TaskSchema,\n});\n\nexport type RunJobResumeWithTask = z.infer<typeof RunJobResumeWithTaskSchema>;\n\nexport const RunJobRetryWithTaskSchema = z.object({\n status: z.literal(\"RETRY_WITH_TASK\"),\n task: TaskSchema,\n error: ErrorWithStackSchema,\n retryAt: z.coerce.date(),\n});\n\nexport type RunJobRetryWithTask = z.infer<typeof RunJobRetryWithTaskSchema>;\n\nexport const RunJobSuccessSchema = z.object({\n status: z.literal(\"SUCCESS\"),\n output: DeserializedJsonSchema.optional(),\n});\n\nexport type RunJobSuccess = z.infer<typeof RunJobSuccessSchema>;\n\nexport const RunJobResponseSchema = z.discriminatedUnion(\"status\", [\n RunJobErrorSchema,\n RunJobResumeWithTaskSchema,\n RunJobRetryWithTaskSchema,\n RunJobSuccessSchema,\n]);\n\nexport type RunJobResponse = z.infer<typeof RunJobResponseSchema>;\n\nexport const PreprocessRunBodySchema = z.object({\n event: ApiEventLogSchema,\n job: z.object({\n id: z.string(),\n version: z.string(),\n }),\n run: z.object({\n id: z.string(),\n isTest: z.boolean(),\n }),\n environment: z.object({\n id: z.string(),\n slug: z.string(),\n type: RuntimeEnvironmentTypeSchema,\n }),\n organization: z.object({\n id: z.string(),\n title: z.string(),\n slug: z.string(),\n }),\n account: z\n .object({\n id: z.string(),\n metadata: z.any(),\n })\n .optional(),\n});\n\nexport type PreprocessRunBody = z.infer<typeof PreprocessRunBodySchema>;\n\nexport const PreprocessRunResponseSchema = z.object({\n abort: z.boolean(),\n properties: z.array(DisplayPropertySchema).optional(),\n});\n\nexport type PreprocessRunResponse = z.infer<typeof PreprocessRunResponseSchema>;\n\nexport const CreateRunBodySchema = z.object({\n client: z.string(),\n job: JobMetadataSchema,\n event: ApiEventLogSchema,\n properties: z.array(DisplayPropertySchema).optional(),\n});\n\nexport type CreateRunBody = z.infer<typeof CreateRunBodySchema>;\n\nconst CreateRunResponseOkSchema = z.object({\n ok: z.literal(true),\n data: z.object({\n id: z.string(),\n }),\n});\n\nconst CreateRunResponseErrorSchema = z.object({\n ok: z.literal(false),\n error: z.string(),\n});\n\nexport const CreateRunResponseBodySchema = z.discriminatedUnion(\"ok\", [\n CreateRunResponseOkSchema,\n CreateRunResponseErrorSchema,\n]);\n\nexport type CreateRunResponseBody = z.infer<typeof CreateRunResponseBodySchema>;\n\nexport const RedactStringSchema = z.object({\n __redactedString: z.literal(true),\n strings: z.array(z.string()),\n interpolations: z.array(z.string()),\n});\n\nexport type RedactString = z.infer<typeof RedactStringSchema>;\n\nexport const LogMessageSchema = z.object({\n level: z.enum([\"DEBUG\", \"INFO\", \"WARN\", \"ERROR\"]),\n message: z.string(),\n data: SerializableJsonSchema.optional(),\n});\n\nexport type LogMessage = z.infer<typeof LogMessageSchema>;\n\nexport type ClientTask = z.infer<typeof TaskSchema>;\nexport type CachedTask = z.infer<typeof CachedTaskSchema>;\n\nexport const RedactSchema = z.object({\n paths: z.array(z.string()),\n});\n\nexport const RetryOptionsSchema = z.object({\n /** The maximum number of times to retry the request. */\n limit: z.number().optional(),\n /** The exponential factor to use when calculating the next retry time. */\n factor: z.number().optional(),\n /** The minimum amount of time to wait before retrying the request. */\n minTimeoutInMs: z.number().optional(),\n /** The maximum amount of time to wait before retrying the request. */\n maxTimeoutInMs: z.number().optional(),\n /** Whether to randomize the retry time. */\n randomize: z.boolean().optional(),\n});\n\nexport type RetryOptions = z.infer<typeof RetryOptionsSchema>;\n\nexport const RunTaskOptionsSchema = z.object({\n /** The name of the Task is required. This is displayed on the Task in the logs. */\n name: z.string(),\n /** The Task will wait and only start at the specified Date */\n delayUntil: z.coerce.date().optional(),\n /** Retry options */\n retry: RetryOptionsSchema.optional(),\n /** The icon for the Task, it will appear in the logs.\n * You can use the name of a company in lowercase, e.g. \"github\".\n * Or any icon name that [Font Awesome](https://fontawesome.com/icons) supports. */\n icon: z.string().optional(),\n /** The key for the Task that you want to appear in the logs */\n displayKey: z.string().optional(),\n /** A description of the Task */\n description: z.string().optional(),\n /** Properties that are displayed in the logs */\n properties: z.array(DisplayPropertySchema).optional(),\n /** The input params to the Task, will be displayed in the logs */\n params: z.any(),\n /** The style of the log entry. */\n style: StyleSchema.optional(),\n /** Allows you to link the Integration connection in the logs. This is handled automatically in integrations. */\n connectionKey: z.string().optional(),\n /** An operation you want to perform on the Trigger.dev platform, current only \"fetch\" is supported. If you wish to `fetch` use [`io.backgroundFetch()`](https://trigger.dev/docs/sdk/io/backgroundfetch) instead. */\n operation: z.enum([\"fetch\"]).optional(),\n /** A No Operation means that the code won't be executed. This is used internally to implement features like [io.wait()](https://trigger.dev/docs/sdk/io/wait). */\n noop: z.boolean().default(false),\n redact: RedactSchema.optional(),\n trigger: TriggerMetadataSchema.optional(),\n});\n\nexport type RunTaskOptions = z.input<typeof RunTaskOptionsSchema>;\n\nexport const RunTaskBodyInputSchema = RunTaskOptionsSchema.extend({\n idempotencyKey: z.string(),\n parentId: z.string().optional(),\n});\n\nexport type RunTaskBodyInput = z.infer<typeof RunTaskBodyInputSchema>;\n\nexport const RunTaskBodyOutputSchema = RunTaskBodyInputSchema.extend({\n params: DeserializedJsonSchema.optional().nullable(),\n});\n\nexport type RunTaskBodyOutput = z.infer<typeof RunTaskBodyOutputSchema>;\n\nexport const CompleteTaskBodyInputSchema = RunTaskBodyInputSchema.pick({\n properties: true,\n description: true,\n params: true,\n}).extend({\n output: SerializableJsonSchema.optional().transform((v) =>\n v ? DeserializedJsonSchema.parse(JSON.parse(JSON.stringify(v))) : {}\n ),\n});\n\nexport type CompleteTaskBodyInput = z.input<typeof CompleteTaskBodyInputSchema>;\nexport type CompleteTaskBodyOutput = z.infer<\n typeof CompleteTaskBodyInputSchema\n>;\n\nexport const FailTaskBodyInputSchema = z.object({\n error: ErrorWithStackSchema,\n});\n\nexport type FailTaskBodyInput = z.infer<typeof FailTaskBodyInputSchema>;\n\nexport const NormalizedRequestSchema = z.object({\n headers: z.record(z.string()),\n method: z.string(),\n query: z.record(z.string()),\n url: z.string(),\n body: z.any(),\n});\n\nexport type NormalizedRequest = z.infer<typeof NormalizedRequestSchema>;\n\nexport const NormalizedResponseSchema = z.object({\n status: z.number(),\n body: z.any(),\n headers: z.record(z.string()).optional(),\n});\n\nexport type NormalizedResponse = z.infer<typeof NormalizedResponseSchema>;\n\nexport const HttpSourceResponseSchema = z.object({\n response: NormalizedResponseSchema,\n events: z.array(RawEventSchema),\n});\n\nexport const RegisterTriggerBodySchema = z.object({\n rule: EventRuleSchema,\n source: SourceMetadataSchema,\n});\n\nexport type RegisterTriggerBody = z.infer<typeof RegisterTriggerBodySchema>;\n\nexport const InitializeTriggerBodySchema = z.object({\n id: z.string(),\n params: z.any(),\n accountId: z.string().optional(),\n metadata: z.any().optional(),\n});\n\nexport type InitializeTriggerBody = z.infer<typeof InitializeTriggerBodySchema>;\n\nconst RegisterCommonScheduleBodySchema = z.object({\n /** A unique id for the schedule. This is used to identify and unregister the schedule later. */\n id: z.string(),\n /** Any additional metadata about the schedule. */\n metadata: z.any(),\n /** This will be used by the Trigger.dev Connect feature, which is coming soon. */\n accountId: z.string().optional(),\n});\n\nexport const RegisterIntervalScheduleBodySchema =\n RegisterCommonScheduleBodySchema.merge(IntervalMetadataSchema);\n\nexport type RegisterIntervalScheduleBody = z.infer<\n typeof RegisterIntervalScheduleBodySchema\n>;\n\nexport const InitializeCronScheduleBodySchema =\n RegisterCommonScheduleBodySchema.merge(CronMetadataSchema);\n\nexport type RegisterCronScheduleBody = z.infer<\n typeof InitializeCronScheduleBodySchema\n>;\n\nexport const RegisterScheduleBodySchema = z.discriminatedUnion(\"type\", [\n RegisterIntervalScheduleBodySchema,\n InitializeCronScheduleBodySchema,\n]);\n\nexport type RegisterScheduleBody = z.infer<typeof RegisterScheduleBodySchema>;\n\nexport const RegisterScheduleResponseBodySchema = z.object({\n id: z.string(),\n schedule: ScheduleMetadataSchema,\n metadata: z.any(),\n active: z.boolean(),\n});\n\nexport type RegisterScheduleResponseBody = z.infer<\n typeof RegisterScheduleResponseBodySchema\n>;\n\nexport const CreateExternalConnectionBodySchema = z.object({\n accessToken: z.string(),\n type: z.enum([\"oauth2\"]),\n scopes: z.array(z.string()).optional(),\n metadata: z.any(),\n});\n\nexport type CreateExternalConnectionBody = z.infer<\n typeof CreateExternalConnectionBodySchema\n>;\n","import { z } from \"zod\";\n\nexport const ErrorWithStackSchema = z.object({\n message: z.string(),\n name: z.string().optional(),\n stack: z.string().optional(),\n});\n\nexport type ErrorWithStack = z.infer<typeof ErrorWithStackSchema>;\n","import { z } from \"zod\";\n\nconst EventMatcherSchema = z.union([\n z.array(z.string()),\n z.array(z.number()),\n z.array(z.boolean()),\n]);\ntype EventMatcher = z.infer<typeof EventMatcherSchema>;\n\nexport type EventFilter = { [key: string]: EventMatcher | EventFilter };\n\nexport const EventFilterSchema: z.ZodType<EventFilter> = z.lazy(() =>\n z.record(z.union([EventMatcherSchema, EventFilterSchema]))\n);\n\nexport const EventRuleSchema = z.object({\n event: z.string(),\n source: z.string(),\n payload: EventFilterSchema.optional(),\n context: EventFilterSchema.optional(),\n});\n\nexport type EventRule = z.infer<typeof EventRuleSchema>;\n","import { z } from \"zod\";\n\nexport const ConnectionAuthSchema = z.object({\n type: z.enum([\"oauth2\"]),\n accessToken: z.string(),\n scopes: z.array(z.string()).optional(),\n additionalFields: z.record(z.string()).optional(),\n});\n\nexport type ConnectionAuth = z.infer<typeof ConnectionAuthSchema>;\n\nexport const IntegrationMetadataSchema = z.object({\n id: z.string(),\n name: z.string(),\n instructions: z.string().optional(),\n});\n\nexport type IntegrationMetadata = z.infer<typeof IntegrationMetadataSchema>;\n\nexport const IntegrationConfigSchema = z.object({\n id: z.string(),\n metadata: IntegrationMetadataSchema,\n authSource: z.enum([\"HOSTED\", \"LOCAL\"]),\n});\n\nexport type IntegrationConfig = z.infer<typeof IntegrationConfigSchema>;\n","import { z } from \"zod\";\n\nconst LiteralSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);\ntype Literal = z.infer<typeof LiteralSchema>;\n\nexport type DeserializedJson =\n | Literal\n | { [key: string]: DeserializedJson }\n | DeserializedJson[];\n\nexport const DeserializedJsonSchema: z.ZodType<DeserializedJson> = z.lazy(() =>\n z.union([\n LiteralSchema,\n z.array(DeserializedJsonSchema),\n z.record(DeserializedJsonSchema),\n ])\n);\n\nconst SerializableSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.date(),\n z.undefined(),\n z.symbol(),\n]);\ntype Serializable = z.infer<typeof SerializableSchema>;\n\nexport type SerializableJson =\n | Serializable\n | { [key: string]: SerializableJson }\n | SerializableJson[];\n\nexport const SerializableJsonSchema: z.ZodType<SerializableJson> = z.lazy(() =>\n z.union([\n SerializableSchema,\n z.array(SerializableJsonSchema),\n z.record(SerializableJsonSchema),\n ])\n);\n","import { z } from \"zod\";\n\n/** A property that is displayed in the logs */\nexport const DisplayPropertySchema = z.object({\n /** The label for the property */\n label: z.string(),\n /** The value of the property */\n text: z.string(),\n /** The URL to link to when the property is clicked */\n url: z.string().optional(),\n});\n\nexport const DisplayPropertiesSchema = z.array(DisplayPropertySchema);\n\nexport type DisplayProperty = z.infer<typeof DisplayPropertySchema>;\n\nexport const StyleSchema = z.object({\n /** The style, `normal` or `minimal` */\n style: z.enum([\"normal\", \"minimal\"]),\n /** A variant of the style. */\n variant: z.string().optional(),\n});\n\nexport type Style = z.infer<typeof StyleSchema>;\nexport type StyleName = Style[\"style\"];\n","import { z } from \"zod\";\n\nexport const SCHEDULED_EVENT = \"dev.trigger.scheduled\";\n\nexport const ScheduledPayloadSchema = z.object({\n ts: z.coerce.date(),\n lastTimestamp: z.coerce.date().optional(),\n});\n\nexport type ScheduledPayload = z.infer<typeof ScheduledPayloadSchema>;\n\nexport const IntervalOptionsSchema = z.object({\n /** The number of seconds for the interval. Min = 60, Max = 86400 (1 day) */\n seconds: z.number().int().positive().min(60).max(86400),\n});\n\n/** Interval options */\nexport type IntervalOptions = z.infer<typeof IntervalOptionsSchema>;\n\nexport const CronOptionsSchema = z.object({\n /** A CRON expression that defines the schedule. A useful tool when writing CRON\n expressions is [crontab guru](https://crontab.guru). Note that the timezone\n used is UTC. */\n cron: z.string(),\n});\n\nexport type CronOptions = z.infer<typeof CronOptionsSchema>;\n\nexport const CronMetadataSchema = z.object({\n type: z.literal(\"cron\"),\n options: CronOptionsSchema,\n metadata: z.any(),\n});\n\nexport type CronMetadata = z.infer<typeof CronMetadataSchema>;\n\nexport const IntervalMetadataSchema = z.object({\n /** An interval reoccurs at the specified number of seconds */\n type: z.literal(\"interval\"),\n /** An object containing options about the interval. */\n options: IntervalOptionsSchema,\n /** Any additional metadata about the schedule. */\n metadata: z.any(),\n});\n\nexport type IntervalMetadata = z.infer<typeof IntervalMetadataSchema>;\n\nexport const ScheduleMetadataSchema = z.discriminatedUnion(\"type\", [\n IntervalMetadataSchema,\n CronMetadataSchema,\n]);\n\nexport type ScheduleMetadata = z.infer<typeof ScheduleMetadataSchema>;\n\nexport const RegisterDynamicSchedulePayloadSchema = z.object({\n id: z.string(),\n jobs: z.array(\n z.object({\n id: z.string(),\n version: z.string(),\n })\n ),\n});\n\nexport type RegisterDynamicSchedulePayload = z.infer<\n typeof RegisterDynamicSchedulePayloadSchema\n>;\n","import { z } from \"zod\";\nimport { DisplayPropertySchema, StyleSchema } from \"./properties\";\nimport { DeserializedJsonSchema } from \"./json\";\n\nexport const TaskStatusSchema = z.enum([\n \"PENDING\",\n \"WAITING\",\n \"RUNNING\",\n \"COMPLETED\",\n \"ERRORED\",\n]);\n\nexport type TaskStatus = z.infer<typeof TaskStatusSchema>;\n\nexport const TaskSchema = z.object({\n id: z.string(),\n name: z.string(),\n icon: z.string().optional().nullable(),\n noop: z.boolean(),\n startedAt: z.coerce.date().optional().nullable(),\n completedAt: z.coerce.date().optional().nullable(),\n delayUntil: z.coerce.date().optional().nullable(),\n status: TaskStatusSchema,\n description: z.string().optional().nullable(),\n properties: z.array(DisplayPropertySchema).optional().nullable(),\n params: DeserializedJsonSchema.optional().nullable(),\n output: DeserializedJsonSchema.optional().nullable(),\n error: z.string().optional().nullable(),\n parentId: z.string().optional().nullable(),\n style: StyleSchema.optional().nullable(),\n operation: z.string().optional().nullable(),\n});\n\nexport const ServerTaskSchema = TaskSchema.extend({\n idempotencyKey: z.string(),\n attempts: z.number(),\n});\n\nexport type ServerTask = z.infer<typeof ServerTaskSchema>;\n\nexport const CachedTaskSchema = z.object({\n id: z.string(),\n idempotencyKey: z.string(),\n status: TaskStatusSchema,\n noop: z.boolean().default(false),\n output: DeserializedJsonSchema.optional().nullable(),\n parentId: z.string().optional().nullable(),\n});\n","import { z } from \"zod\";\nimport { EventFilterSchema, EventRuleSchema } from \"./eventFilter\";\nimport { DisplayPropertySchema } from \"./properties\";\nimport { ScheduleMetadataSchema } from \"./schedules\";\n\nexport const EventExampleSchema = z.object({\n id: z.string(),\n icon: z.string().optional(),\n name: z.string(),\n payload: z.any(),\n});\n\nexport type EventExample = z.infer<typeof EventExampleSchema>;\n\nexport const EventSpecificationSchema = z.object({\n name: z.string(),\n title: z.string(),\n source: z.string(),\n icon: z.string(),\n filter: EventFilterSchema.optional(),\n properties: z.array(DisplayPropertySchema).optional(),\n schema: z.any().optional(),\n examples: z.array(EventExampleSchema).optional(),\n});\n\nexport const DynamicTriggerMetadataSchema = z.object({\n type: z.literal(\"dynamic\"),\n id: z.string(),\n});\n\nexport const StaticTriggerMetadataSchema = z.object({\n type: z.literal(\"static\"),\n title: z.string(),\n properties: z.array(DisplayPropertySchema).optional(),\n rule: EventRuleSchema,\n});\n\nexport const ScheduledTriggerMetadataSchema = z.object({\n type: z.literal(\"scheduled\"),\n schedule: ScheduleMetadataSchema,\n});\n\nexport const TriggerMetadataSchema = z.discriminatedUnion(\"type\", [\n DynamicTriggerMetadataSchema,\n StaticTriggerMetadataSchema,\n ScheduledTriggerMetadataSchema,\n]);\n\nexport type TriggerMetadata = z.infer<typeof TriggerMetadataSchema>;\n","import { z } from \"zod\";\n\nexport const MISSING_CONNECTION_NOTIFICATION =\n \"dev.trigger.notifications.missingConnection\";\n\nexport const MISSING_CONNECTION_RESOLVED_NOTIFICATION =\n \"dev.trigger.notifications.missingConnectionResolved\";\n\nexport const CommonMissingConnectionNotificationPayloadSchema = z.object({\n id: z.string(),\n client: z.object({\n id: z.string(),\n title: z.string(),\n scopes: z.array(z.string()),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n }),\n authorizationUrl: z.string(),\n});\n\nexport const MissingDeveloperConnectionNotificationPayloadSchema =\n CommonMissingConnectionNotificationPayloadSchema.extend({\n type: z.literal(\"DEVELOPER\"),\n });\n\nexport const MissingExternalConnectionNotificationPayloadSchema =\n CommonMissingConnectionNotificationPayloadSchema.extend({\n type: z.literal(\"EXTERNAL\"),\n account: z.object({\n id: z.string(),\n metadata: z.any(),\n }),\n });\n\nexport const MissingConnectionNotificationPayloadSchema = z.discriminatedUnion(\n \"type\",\n [\n MissingDeveloperConnectionNotificationPayloadSchema,\n MissingExternalConnectionNotificationPayloadSchema,\n ]\n);\n\nexport type MissingConnectionNotificationPayload = z.infer<\n typeof MissingConnectionNotificationPayloadSchema\n>;\n\nexport const CommonMissingConnectionNotificationResolvedPayloadSchema =\n z.object({\n id: z.string(),\n client: z.object({\n id: z.string(),\n title: z.string(),\n scopes: z.array(z.string()),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n integrationIdentifier: z.string(),\n integrationAuthMethod: z.string(),\n }),\n expiresAt: z.coerce.date(),\n });\n\nexport const MissingDeveloperConnectionResolvedNotificationPayloadSchema =\n CommonMissingConnectionNotificationResolvedPayloadSchema.extend({\n type: z.literal(\"DEVELOPER\"),\n });\n\nexport const MissingExternalConnectionResolvedNotificationPayloadSchema =\n CommonMissingConnectionNotificationResolvedPayloadSchema.extend({\n type: z.literal(\"EXTERNAL\"),\n account: z.object({\n id: z.string(),\n metadata: z.any(),\n }),\n });\n\nexport const MissingConnectionResolvedNotificationPayloadSchema =\n z.discriminatedUnion(\"type\", [\n MissingDeveloperConnectionResolvedNotificationPayloadSchema,\n MissingExternalConnectionResolvedNotificationPayloadSchema,\n ]);\n\nexport type MissingConnectionResolvedNotificationPayload = z.infer<\n typeof MissingConnectionResolvedNotificationPayloadSchema\n>;\n","import { z } from \"zod\";\nimport { RedactStringSchema, RetryOptionsSchema } from \"./api\";\n\nexport const FetchRetryHeadersStrategySchema = z.object({\n /** The `headers` strategy retries the request using info from the response headers. */\n strategy: z.literal(\"headers\"),\n /** The header to use to determine the maximum number of times to retry the request. */\n limitHeader: z.string(),\n /** The header to use to determine the number of remaining retries. */\n remainingHeader: z.string(),\n /** The header to use to determine the time when the number of remaining retries will be reset. */\n resetHeader: z.string(),\n});\n\nexport type FetchRetryHeadersStrategy = z.infer<\n typeof FetchRetryHeadersStrategySchema\n>;\n\n/** The `backoff` strategy retries the request with an exponential backoff. */\nexport const FetchRetryBackoffStrategySchema = RetryOptionsSchema.extend({\n /** The `backoff` strategy retries the request with an exponential backoff. */\n strategy: z.literal(\"backoff\"),\n});\n\n/** The `backoff` strategy retries the request with an exponential backoff. */\nexport type FetchRetryBackoffStrategy = z.infer<\n typeof FetchRetryBackoffStrategySchema\n>;\n\nexport const FetchRetryStrategySchema = z.discriminatedUnion(\"strategy\", [\n FetchRetryHeadersStrategySchema,\n FetchRetryBackoffStrategySchema,\n]);\n\nexport type FetchRetryStrategy = z.infer<typeof FetchRetryStrategySchema>;\n\n/** The options for a fetch request */\nexport const FetchRequestInitSchema = z.object({\n /** The HTTP method to use for the request. */\n method: z.string().optional(),\n /** Any headers to send with the request. Note that you can use [redactString](https://trigger.dev/docs/sdk/redactString) to prevent sensitive information from being stored (e.g. in the logs), like API keys and tokens. */\n headers: z.record(z.union([z.string(), RedactStringSchema])).optional(),\n /** The body of the request. */\n body: z.union([z.string(), z.instanceof(ArrayBuffer)]).optional(),\n});\n\n/** The options for a fetch request */\nexport type FetchRequestInit = z.infer<typeof FetchRequestInitSchema>;\n\nexport const FetchRetryOptionsSchema = z.record(FetchRetryStrategySchema);\n\n/** An object where the key is a status code pattern and the value is a retrying strategy. Supported patterns are:\n - Specific status codes: 429\n - Ranges: 500-599\n - Wildcards: 2xx, 3xx, 4xx, 5xx \n */\nexport type FetchRetryOptions = z.infer<typeof FetchRetryOptionsSchema>;\n\nexport const FetchOperationSchema = z.object({\n url: z.string(),\n requestInit: FetchRequestInitSchema.optional(),\n retry: z.record(FetchRetryStrategySchema).optional(),\n});\n\nexport type FetchOperation = z.infer<typeof FetchOperationSchema>;\n","// EventFilter is typed as type EventFilter = { [key: string]: EventFilter | string[] | number[] | boolean[] }\n\nimport { EventFilter } from \"./schemas\";\n\n// This function should take two EventFilters and return a new EventFilter that is the result of merging the two.\nexport function deepMergeFilters(\n filter: EventFilter,\n other: EventFilter\n): EventFilter {\n const result: EventFilter = { ...filter };\n\n for (const key in other) {\n if (other.hasOwnProperty(key)) {\n const otherValue = other[key];\n\n if (\n typeof otherValue === \"object\" &&\n !Array.isArray(otherValue) &&\n otherValue !== null\n ) {\n const filterValue = filter[key];\n\n if (\n filterValue &&\n typeof filterValue === \"object\" &&\n !Array.isArray(filterValue)\n ) {\n result[key] = deepMergeFilters(filterValue, otherValue);\n } else {\n result[key] = { ...other[key] };\n }\n } else {\n result[key] = other[key];\n }\n }\n }\n\n return result;\n}\n","import { RetryOptions } from \"./schemas\";\n\nconst DEFAULT_RETRY_OPTIONS = {\n limit: 5,\n factor: 1.8,\n minTimeoutInMs: 1000,\n maxTimeoutInMs: 60000,\n randomize: true,\n} satisfies RetryOptions;\n\nexport function calculateRetryAt(\n retryOptions: RetryOptions,\n attempts: number\n): Date | undefined {\n const options = {\n ...DEFAULT_RETRY_OPTIONS,\n ...retryOptions,\n };\n\n const retryCount = attempts + 1;\n\n if (retryCount >= options.limit) {\n return;\n }\n\n const random = options.randomize ? Math.random() + 1 : 1;\n\n let timeoutInMs = Math.round(\n random *\n Math.max(options.minTimeoutInMs, 1) *\n Math.pow(options.factor, Math.max(attempts - 1, 0))\n );\n\n timeoutInMs = Math.min(timeoutInMs, options.maxTimeoutInMs);\n\n return new Date(Date.now() + timeoutInMs);\n}\n","import { DeserializedJson } from \"./schemas\";\n\nexport interface ExampleReplacement {\n marker: string;\n replace(input: ExampleInputData): DeserializedJson;\n}\n\ntype ExampleInputData = {\n match: {\n key: string;\n value: string;\n };\n data: {\n now: Date;\n };\n};\n\nexport const currentDate: ExampleReplacement = {\n marker: \"__CURRENT_DATE__\",\n replace({ data: { now } }: ExampleInputData) {\n return now.toISOString();\n },\n};\n\nexport const currentTimestampMilliseconds: ExampleReplacement = {\n marker: \"__CURRENT_TIMESTAMP_MS__\",\n replace({ data: { now } }: ExampleInputData) {\n return now.getTime();\n },\n};\n\nexport const currentTimestampSeconds: ExampleReplacement = {\n marker: \"__CURRENT_TIMESTAMP_S__\",\n replace({ data: { now } }: ExampleInputData) {\n return now.getTime() / 1000;\n },\n};\n\nexport const replacements: ExampleReplacement[] = [\n currentDate,\n currentTimestampMilliseconds,\n currentTimestampSeconds,\n];\n","import {\n ApiEventLog,\n ApiEventLogSchema,\n CompleteTaskBodyInput,\n ConnectionAuthSchema,\n CreateRunBody,\n CreateRunResponseBodySchema,\n FailTaskBodyInput,\n LogLevel,\n Logger,\n RegisterScheduleResponseBodySchema,\n RegisterSourceEvent,\n RegisterSourceEventSchema,\n RegisterTriggerBody,\n RunTaskBodyInput,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n ServerTaskSchema,\n TriggerSource,\n TriggerSourceSchema,\n UpdateTriggerSourceBody,\n} from \"@trigger.dev/internal\";\nimport { z } from \"zod\";\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\n constructor(options: ApiClientOptions) {\n this.#options = options;\n\n this.#apiUrl =\n this.#options.apiUrl ??\n process.env.TRIGGER_API_URL ??\n \"https://api.trigger.dev\";\n this.#logger = new Logger(\"trigger.dev\", this.#options.logLevel);\n }\n\n async registerEndpoint(options: {\n url: string;\n name: string;\n }): 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(\n `Failed to register entry point, got status code ${response.status}`\n );\n }\n\n return await response.json();\n }\n\n async createRun(params: CreateRunBody) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Creating run\", {\n params,\n });\n\n return await zodfetch(\n CreateRunResponseBodySchema,\n `${this.#apiUrl}/api/v1/runs`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(params),\n }\n );\n }\n\n async runTask(runId: string, task: RunTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Running Task\", {\n task,\n });\n\n return await zodfetch(\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 },\n body: JSON.stringify(task),\n }\n );\n }\n\n async completeTask(runId: string, id: string, task: CompleteTaskBodyInput) {\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 },\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 updateSource(\n client: string,\n key: string,\n source: UpdateTriggerSourceBody\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/v1/${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 registerTrigger(\n client: string,\n id: string,\n key: string,\n payload: RegisterTriggerBody\n ): Promise<RegisterSourceEvent> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering trigger\", {\n id,\n payload,\n });\n\n const response = await zodfetch(\n RegisterSourceEventSchema,\n `${this.#apiUrl}/api/v1/${client}/triggers/${id}/registrations/${key}`,\n {\n method: \"PUT\",\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 async registerSchedule(\n client: string,\n id: string,\n key: string,\n payload: ScheduleMetadata\n ) {\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 `${\n this.#apiUrl\n }/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(\n key\n )}`,\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 #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 ?? process.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\nasync function zodfetch<\n TResponseBody extends any,\n TOptional extends boolean = false\n>(\n schema: z.Schema<TResponseBody>,\n url: string,\n requestInit?: RequestInit,\n options?: {\n errorMessage?: string;\n optional?: TOptional;\n }\n): Promise<TOptional extends true ? TResponseBody | undefined : TResponseBody> {\n const response = await fetch(url, 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 !== 200) {\n throw new Error(\n options?.errorMessage ??\n `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","import { ErrorWithStack, ServerTask } from \"@trigger.dev/internal\";\n\nexport class ResumeWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\nexport class RetryWithTaskError {\n constructor(\n public cause: ErrorWithStack,\n public task: ServerTask,\n public retryAt: Date\n ) {}\n}\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(\n err: unknown\n): err is ResumeWithTaskError | RetryWithTaskError {\n return (\n err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError\n );\n}\n","import {\n CachedTask,\n ConnectionAuth,\n CronOptions,\n ErrorWithStackSchema,\n FetchRequestInit,\n FetchRetryOptions,\n IntervalOptions,\n LogLevel,\n Logger,\n RunTaskOptions,\n SendEvent,\n SendEventOptions,\n SerializableJson,\n ServerTask,\n UpdateTriggerSourceBody,\n} from \"@trigger.dev/internal\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { webcrypto } from \"node:crypto\";\nimport { ApiClient } from \"./apiClient\";\nimport {\n ResumeWithTaskError,\n RetryWithTaskError,\n isTriggerError,\n} from \"./errors\";\nimport { createIOWithIntegrations } from \"./ioWithIntegrations\";\nimport { calculateRetryAt } from \"./retry\";\nimport { TriggerClient } from \"./triggerClient\";\nimport { DynamicTrigger } from \"./triggers/dynamic\";\nimport {\n ExternalSource,\n ExternalSourceParams,\n} from \"./triggers/externalSource\";\nimport { DynamicSchedule } from \"./triggers/scheduled\";\nimport { EventSpecification, TaskLogger, TriggerContext } from \"./types\";\n\nexport type IOTask = ServerTask;\n\nexport type IOOptions = {\n id: string;\n apiClient: ApiClient;\n client: TriggerClient;\n context: TriggerContext;\n logger?: Logger;\n logLevel?: LogLevel;\n jobLogger?: Logger;\n jobLogLevel: LogLevel;\n cachedTasks?: Array<CachedTask>;\n};\n\nexport class IO {\n private _id: 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 _context: TriggerContext;\n\n constructor(options: IOOptions) {\n this._id = options.id;\n this._apiClient = options.apiClient;\n this._triggerClient = options.client;\n this._logger =\n options.logger ?? new Logger(\"trigger.dev\", options.logLevel);\n this._cachedTasks = new Map();\n this._jobLogger = options.jobLogger;\n this._jobLogLevel = options.jobLogLevel;\n\n if (options.cachedTasks) {\n options.cachedTasks.forEach((task) => {\n this._cachedTasks.set(task.id, task);\n });\n }\n\n this._taskStorage = new AsyncLocalStorage();\n this._context = options.context;\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 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 if (Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {\n await this.runTask(\n [message, level],\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 async (task) => {}\n );\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 key 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(key: string | any[], seconds: number) {\n return await this.runTask(\n key,\n {\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 async (task) => {}\n );\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 key 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 key: string | any[],\n url: string,\n requestInit?: FetchRequestInit,\n retry?: FetchRetryOptions\n ): Promise<TResponseData> {\n const urlObject = new URL(url);\n\n return (await this.runTask(\n key,\n {\n name: `fetch ${urlObject.hostname}${urlObject.pathname}`,\n params: { url, requestInit, retry },\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 ],\n },\n async (task) => {\n return task.output;\n }\n )) as TResponseData;\n }\n\n /** `io.sendEvent()` allows you to send an event from inside a Job run. The sent even will trigger any Jobs that are listening for that event (based on the name).\n * @param key 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(\n key: string | any[],\n event: SendEvent,\n options?: SendEventOptions\n ) {\n return await this.runTask(\n key,\n {\n name: \"sendEvent\",\n params: { event, options },\n properties: [\n {\n label: \"name\",\n text: event.name,\n },\n ...(event?.id ? [{ label: \"ID\", text: event.id }] : []),\n ],\n },\n async (task) => {\n return await this._triggerClient.sendEvent(event, options);\n }\n );\n }\n\n async updateSource(\n key: string | any[],\n options: { key: string } & UpdateTriggerSourceBody\n ) {\n return this.runTask(\n key,\n {\n name: \"Update Source\",\n description: `Update Source ${options.key}`,\n properties: [\n {\n label: \"key\",\n text: options.key,\n },\n ],\n redact: {\n paths: [\"secret\"],\n },\n },\n async (task) => {\n return await this._apiClient.updateSource(\n this._triggerClient.id,\n options.key,\n options\n );\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 key 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 */\n async registerInterval(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: IntervalOptions\n ) {\n return await this.runTask(\n key,\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 async (task) => {\n return dynamicSchedule.register(id, {\n type: \"interval\",\n options,\n });\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 key 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 */\n async unregisterInterval(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string\n ) {\n return await this.runTask(\n key,\n {\n name: \"unregister-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n },\n async (task) => {\n return dynamicSchedule.unregister(id);\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 key 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 */\n async registerCron(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: CronOptions\n ) {\n return await this.runTask(\n key,\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 async (task) => {\n return dynamicSchedule.register(id, {\n type: \"cron\",\n options,\n });\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 key 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 */\n async unregisterCron(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string\n ) {\n return await this.runTask(\n key,\n {\n name: \"unregister-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n },\n async (task) => {\n return dynamicSchedule.unregister(id);\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 key 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 */\n async registerTrigger<\n TTrigger extends DynamicTrigger<\n EventSpecification<any>,\n ExternalSource<any, any, any>\n >\n >(\n key: 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 key,\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 async (task) => {\n const registration = await this.runTask(\n \"register-source\",\n {\n name: \"register-source\",\n },\n async (subtask1) => {\n return trigger.register(id, params);\n }\n );\n\n const connection = await this.getAuth(\n \"get-auth\",\n registration.source.clientId\n );\n\n const io = createIOWithIntegrations(\n // @ts-ignore\n this,\n {\n integration: connection,\n },\n {\n integration: trigger.source.integration,\n }\n );\n\n const updates = await trigger.source.register(\n params,\n registration,\n io,\n this._context\n );\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await this.updateSource(\"update-source\", {\n key: registration.source.key,\n ...updates,\n });\n }\n );\n }\n\n async getAuth(\n key: string | any[],\n clientId?: string\n ): Promise<ConnectionAuth | undefined> {\n if (!clientId) {\n return;\n }\n\n return this.runTask(key, { name: \"get-auth\" }, async (task) => {\n return await this._triggerClient.getAuth(clientId);\n });\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 key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param options The options of how you'd like to run and log the Task. Name is required.\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 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<TResult extends SerializableJson | void = void>(\n key: string | any[],\n options: RunTaskOptions,\n callback: (task: IOTask, io: IO) => Promise<TResult>,\n onError?: (\n error: unknown,\n task: IOTask,\n io: IO\n ) => { retryAt: Date; error?: Error; jitter?: number } | undefined | void\n ): Promise<TResult> {\n const parentId = this._taskStorage.getStore()?.taskId;\n\n if (parentId) {\n this._logger.debug(\"Using parent task\", {\n parentId,\n key,\n options,\n });\n }\n\n const idempotencyKey = await generateIdempotencyKey(\n [this._id, parentId ?? \"\", key].flat()\n );\n\n const cachedTask = this._cachedTasks.get(idempotencyKey);\n\n if (cachedTask) {\n this._logger.debug(\"Using cached task\", {\n idempotencyKey,\n cachedTask,\n });\n\n return cachedTask.output as TResult;\n }\n\n const task = await this._apiClient.runTask(this._id, {\n idempotencyKey,\n displayKey: typeof key === \"string\" ? key : undefined,\n noop: false,\n ...options,\n parentId,\n });\n\n if (task.status === \"COMPLETED\") {\n this._logger.debug(\"Using task output\", {\n idempotencyKey,\n task,\n });\n\n this.#addToCachedTasks(task);\n\n return task.output as TResult;\n }\n\n if (task.status === \"ERRORED\") {\n this._logger.debug(\"Task errored\", {\n idempotencyKey,\n task,\n });\n\n throw new Error(task.error ?? \"Task errored\");\n }\n\n if (task.status === \"WAITING\") {\n this._logger.debug(\"Task waiting\", {\n idempotencyKey,\n task,\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 const executeTask = async () => {\n try {\n const result = await callback(task, this);\n\n this._logger.debug(\"Completing using output\", {\n idempotencyKey,\n task,\n });\n\n await this._apiClient.completeTask(this._id, task.id, {\n output: result ?? undefined,\n });\n\n return result;\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n if (onError) {\n const onErrorResult = onError(error, task, this);\n\n if (onErrorResult) {\n const parsedError = ErrorWithStackSchema.safeParse(\n onErrorResult.error\n );\n\n throw new RetryWithTaskError(\n parsedError.success\n ? parsedError.data\n : { message: \"Unknown error\" },\n task,\n onErrorResult.retryAt\n );\n }\n }\n\n const parsedError = ErrorWithStackSchema.safeParse(error);\n\n if (options.retry) {\n const retryAt = calculateRetryAt(options.retry, task.attempts - 1);\n\n if (retryAt) {\n throw new RetryWithTaskError(\n parsedError.success\n ? parsedError.data\n : { 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 await this._apiClient.failTask(this._id, task.id, {\n error: { message: JSON.stringify(error), name: \"Unknown Error\" },\n });\n }\n\n throw error;\n }\n };\n\n return this._taskStorage.run({ taskId: task.id }, executeTask);\n }\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()](/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 #addToCachedTasks(task: ServerTask) {\n this._cachedTasks.set(task.idempotencyKey, task);\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","import { ConnectionAuth } from \"@trigger.dev/internal\";\nimport {\n AuthenticatedTask,\n IOWithIntegrations,\n IntegrationClient,\n TriggerIntegration,\n} from \"./integrations\";\nimport { IO } from \"./io\";\n\nexport function createIOWithIntegrations<\n TIntegrations extends Record<\n string,\n TriggerIntegration<IntegrationClient<any, any>>\n >\n>(\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 const client = integration.client.usesLocalAuth\n ? integration.client.client\n : auth\n ? integration.client.clientFactory?.(auth)\n : undefined;\n\n if (!client) {\n return acc;\n }\n\n auth = integration.client.usesLocalAuth ? integration.client.auth : auth;\n\n const ioConnection = {\n client,\n } as any;\n\n if (integration.client.tasks) {\n const tasks: Record<\n string,\n AuthenticatedTask<any, any, any, any>\n > = integration.client.tasks;\n\n Object.keys(tasks).forEach((taskName) => {\n const authenticatedTask = tasks[taskName];\n\n ioConnection[taskName] = async (\n key: string | string[],\n params: any\n ) => {\n const options = authenticatedTask.init(params);\n options.connectionKey = connectionKey;\n\n return await io.runTask(\n key,\n options,\n async (ioTask) => {\n return authenticatedTask.run(params, client, ioTask, io, auth);\n },\n authenticatedTask.onError\n );\n };\n });\n }\n\n acc[connectionKey] = ioConnection;\n\n return acc;\n },\n {} as any\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 (prop in connections) {\n return connections[prop];\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 EventFilter,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/internal\";\nimport { z } from \"zod\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\n\ntype EventTriggerOptions<TEventSpecification extends EventSpecification<any>> =\n {\n event: TEventSpecification;\n name?: string;\n source?: string;\n filter?: EventFilter;\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(\n this.#options.filter ?? {},\n this.#options.event.filter ?? {}\n ),\n },\n };\n }\n\n get event() {\n return this.#options.event;\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<TEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n}\n\ntype TriggerOptions<TEvent> = {\n name: string;\n schema?: z.Schema<TEvent>;\n source?: string;\n filter?: EventFilter;\n};\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 event: {\n name: options.name,\n title: \"Event\",\n source: options.source ?? \"trigger.dev\",\n icon: \"custom-event\",\n parsePayload: (rawPayload: any) => {\n if (options.schema) {\n return options.schema.parse(rawPayload);\n }\n\n return rawPayload as any;\n },\n },\n });\n}\n","import {\n ErrorWithStackSchema,\n HandleTriggerSource,\n HttpSourceRequestHeadersSchema,\n IndexEndpointResponse,\n InitializeTriggerBodySchema,\n LogLevel,\n Logger,\n NormalizedResponse,\n PreprocessRunBody,\n PreprocessRunBodySchema,\n Prettify,\n REGISTER_SOURCE_EVENT,\n RegisterSourceEvent,\n RegisterSourceEventSchema,\n RegisterTriggerBody,\n RunJobBody,\n RunJobBodySchema,\n RunJobResponse,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n SourceMetadata,\n} from \"@trigger.dev/internal\";\nimport { ApiClient } from \"./apiClient\";\nimport { ResumeWithTaskError, RetryWithTaskError } from \"./errors\";\nimport { IO } from \"./io\";\nimport { createIOWithIntegrations } from \"./ioWithIntegrations\";\nimport { Job } from \"./job\";\nimport { DynamicTrigger } from \"./triggers/dynamic\";\nimport { EventTrigger } from \"./triggers/eventTrigger\";\nimport { ExternalSource } from \"./triggers/externalSource\";\nimport type {\n EventSpecification,\n Trigger,\n TriggerContext,\n TriggerPreprocessContext,\n} from \"./types\";\n\nconst registerSourceEvent: EventSpecification<RegisterSourceEvent> = {\n name: REGISTER_SOURCE_EVENT,\n title: \"Register Source\",\n source: \"internal\",\n icon: \"register-source\",\n parsePayload: RegisterSourceEventSchema.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\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 {};\n #registeredSources: Record<string, SourceMetadata> = {};\n #registeredHttpSourceHandlers: Record<\n string,\n (\n source: HandleTriggerSource,\n request: Request\n ) => Promise<{\n events: Array<SendEvent>;\n response?: NormalizedResponse;\n } | void>\n > = {};\n #registeredDynamicTriggers: Record<\n string,\n DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>\n > = {};\n #jobMetadataByDynamicTriggers: Record<\n string,\n Array<{ id: string; version: string }>\n > = {};\n #registeredSchedules: Record<string, Array<{ id: string; version: string }>> =\n {};\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(\n \"trigger.dev\",\n this.#options.verbose ? \"debug\" : \"log\"\n );\n }\n\n async handleRequest(request: Request): 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\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 };\n }\n case \"missing-header\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: missing x-trigger-api-key header\",\n },\n };\n }\n case \"unauthorized\": {\n return {\n status: 401,\n body: {\n message: `Forbidden: client apiKey mismatch: Expected ${\n this.#options.apiKey\n }, got ${apiKey}`,\n },\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 };\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 };\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 };\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 };\n }\n\n return {\n status: 200,\n body: {\n ok: true,\n },\n };\n }\n case \"INDEX_ENDPOINT\": {\n // if the x-trigger-job-id header is set, we return the job with that id\n const jobId = request.headers.get(\"x-trigger-job-id\");\n\n if (jobId) {\n const job = this.#registeredJobs[jobId];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n return {\n status: 200,\n body: job.toJSON(),\n };\n }\n\n const body: IndexEndpointResponse = {\n jobs: Object.values(this.#registeredJobs).map((job) => job.toJSON()),\n sources: Object.values(this.#registeredSources),\n dynamicTriggers: Object.values(this.#registeredDynamicTriggers).map(\n (trigger) => ({\n id: trigger.id,\n jobs: this.#jobMetadataByDynamicTriggers[trigger.id] ?? [],\n })\n ),\n dynamicSchedules: Object.entries(this.#registeredSchedules).map(\n ([id, jobs]) => ({\n id,\n jobs,\n })\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 };\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 };\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);\n\n return {\n status: 200,\n body: results,\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 };\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 sourceRequest = new Request(headers.data[\"x-ts-http-url\"], {\n method: headers.data[\"x-ts-http-method\"],\n headers: headers.data[\"x-ts-http-headers\"],\n body:\n headers.data[\"x-ts-http-method\"] !== \"GET\"\n ? request.body\n : undefined,\n });\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\n const source = {\n key,\n dynamicId,\n secret,\n params,\n data,\n };\n\n const { response, events } = await this.#handleHttpSourceRequest(\n source,\n sourceRequest\n );\n\n return {\n status: 200,\n body: {\n events,\n response,\n },\n };\n }\n }\n\n return {\n status: 405,\n body: {\n message: \"Method not allowed\",\n },\n };\n }\n\n attach(job: Job<Trigger<any>, any>): void {\n if (!job.enabled) {\n return;\n }\n\n this.#registeredJobs[job.id] = job;\n\n job.trigger.attachToJob(this, job);\n }\n\n attachDynamicTrigger(trigger: DynamicTrigger<any, any>): void {\n this.#registeredDynamicTriggers[trigger.id] = trigger;\n\n new Job(this, {\n id: `register-dynamic-trigger-${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(\n event.source.params,\n event,\n io,\n ctx\n );\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 // @ts-ignore\n __internal: true,\n });\n }\n\n attachJobToDynamicTrigger(\n job: Job<Trigger<any>, any>,\n trigger: DynamicTrigger<any, any>\n ): 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 }): 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 channel: options.source.channel,\n key: options.key,\n params: options.params,\n events: [],\n integration: {\n id: options.source.integration.id,\n metadata: options.source.integration.metadata,\n authSource: options.source.integration.client.usesLocalAuth\n ? \"LOCAL\"\n : \"HOSTED\",\n },\n };\n }\n\n registeredSource.events = Array.from(\n new Set([...registeredSource.events, options.event.name])\n );\n\n this.#registeredSources[options.key] = registeredSource;\n\n new Job(this, {\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 queue: {\n name: options.key,\n maxConcurrent: 1,\n },\n startPosition: \"initial\",\n run: async (event, io, ctx) => {\n const updates = await options.source.register(\n options.params,\n event,\n io,\n ctx\n );\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 // @ts-ignore\n __internal: true,\n });\n }\n\n attachDynamicSchedule(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 async registerTrigger(id: string, key: string, options: RegisterTriggerBody) {\n return this.#client.registerTrigger(this.id, id, key, options);\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 code 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 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 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 ?? process.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 ?? process.env.TRIGGER_API_KEY;\n }\n\n async #preprocessRun(\n body: PreprocessRunBody,\n job: Job<Trigger<EventSpecification<any>>, any>\n ) {\n const context = this.#createPreprocessRunContext(body);\n\n const parsedPayload = job.trigger.event.parsePayload(\n body.event.payload ?? {}\n );\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>, any>\n ): Promise<RunJobResponse> {\n this.#internalLogger.debug(\"executing job\", {\n execution: body,\n job: job.toJSON(),\n });\n\n const context = this.#createRunContext(body);\n\n const io = new IO({\n id: body.run.id,\n cachedTasks: body.tasks,\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 });\n\n const ioWithConnections = createIOWithIntegrations(\n io,\n body.connections,\n job.options.integrations\n );\n\n try {\n const output = await job.options.run(\n job.trigger.event.parsePayload(body.event.payload ?? {}),\n ioWithConnections,\n context\n );\n\n return { status: \"SUCCESS\", output };\n } catch (error) {\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 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 return {\n status: \"ERROR\",\n error: { message: \"Unknown error\" },\n };\n }\n }\n\n #createRunContext(execution: RunJobBody): TriggerContext {\n const { event, organization, 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 environment,\n job,\n run,\n account: execution.account,\n source,\n };\n }\n\n #createPreprocessRunContext(\n body: PreprocessRunBody\n ): 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 },\n sourceRequest: Request\n ): Promise<{ response: NormalizedResponse; events: SendEvent[] }> {\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(\n \"No dynamic trigger registered for HTTP source\",\n {\n source,\n }\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 };\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 };\n }\n}\n","import {\n ConnectionAuth,\n IntegrationMetadata,\n RunTaskOptions,\n ServerTask,\n} from \"@trigger.dev/internal\";\nimport { IO } from \"./io\";\n\nexport type ClientFactory<TClient> = (auth: ConnectionAuth) => TClient;\n\nexport interface TriggerIntegration<\n TIntegrationClient extends IntegrationClient<any, any> = IntegrationClient<\n any,\n any\n >\n> {\n client: TIntegrationClient;\n id: string;\n metadata: IntegrationMetadata;\n}\n\nexport type IntegrationClient<\n TClient,\n TTasks extends Record<string, AuthenticatedTask<TClient, any, any, any>>\n> =\n | {\n usesLocalAuth: true;\n client: TClient;\n tasks?: TTasks;\n auth: any;\n }\n | {\n usesLocalAuth: false;\n clientFactory: ClientFactory<TClient>;\n tasks?: TTasks;\n };\n\nexport type AuthenticatedTask<\n TClient,\n TParams,\n TResult,\n TAuth = ConnectionAuth\n> = {\n run: (\n params: TParams,\n client: TClient,\n task: ServerTask,\n io: IO,\n auth: TAuth\n ) => Promise<TResult>;\n init: (params: TParams) => RunTaskOptions;\n onError?: (\n error: unknown,\n task: ServerTask\n ) => { retryAt: Date; error?: Error } | undefined | void;\n};\n\nexport function authenticatedTask<TClient, TParams, TResult>(options: {\n run: (\n params: TParams,\n client: TClient,\n task: ServerTask,\n io: IO\n ) => Promise<TResult>;\n init: (params: TParams) => RunTaskOptions;\n}): AuthenticatedTask<TClient, TParams, TResult> {\n return options;\n}\n\ntype ExtractRunFunction<T> = T extends AuthenticatedTask<\n any,\n infer TParams,\n infer TResult,\n infer TAuth\n>\n ? (key: string, params: TParams) => Promise<TResult>\n : never;\n\ntype ExtractTasks<\n TTasks extends Record<string, AuthenticatedTask<any, any, any, any>>\n> = {\n [key in keyof TTasks]: ExtractRunFunction<TTasks[key]>;\n};\n\ntype ExtractIntegrationClientClient<\n TIntegrationClient extends IntegrationClient<any, any>\n> = TIntegrationClient extends {\n usesLocalAuth: true;\n client: infer TClient;\n}\n ? { client: TClient }\n : TIntegrationClient extends {\n usesLocalAuth: false;\n clientFactory: ClientFactory<infer TClient>;\n }\n ? { client: TClient }\n : never;\n\ntype ExtractIntegrationClient<\n TIntegrationClient extends IntegrationClient<any, any>\n> = ExtractIntegrationClientClient<TIntegrationClient> &\n ExtractTasks<TIntegrationClient[\"tasks\"]>;\n\ntype ExtractIntegrations<\n TIntegrations extends Record<\n string,\n TriggerIntegration<IntegrationClient<any, any>>\n >\n> = {\n [key in keyof TIntegrations]: ExtractIntegrationClient<\n TIntegrations[key][\"client\"]\n >;\n};\n\nexport type IOWithIntegrations<\n TIntegrations extends Record<\n string,\n TriggerIntegration<IntegrationClient<any, any>>\n >\n> = IO & ExtractIntegrations<TIntegrations>;\n","import { z } from \"zod\";\n\nimport {\n DisplayProperty,\n EventFilter,\n HandleTriggerSource,\n Logger,\n NormalizedResponse,\n RegisterSourceEvent,\n SendEvent,\n TriggerMetadata,\n UpdateTriggerSourceBody,\n deepMergeFilters,\n} from \"@trigger.dev/internal\";\nimport {\n IOWithIntegrations,\n IntegrationClient,\n TriggerIntegration,\n} from \"../integrations\";\nimport { IO } from \"../io\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport type { EventSpecification, 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 RegisterFunctionEvent<\n TChannel extends ChannelNames,\n TParams extends any\n> = {\n events: Array<string>;\n missingEvents: Array<string>;\n orphanedEvents: Array<string>;\n source: {\n active: boolean;\n data?: any;\n secret: string;\n } & ExternalSourceChannelMap[TChannel][\"register\"];\n params: TParams;\n};\n\ntype RegisterFunction<\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any,\n TChannel extends ChannelNames\n> = (\n event: RegisterFunctionEvent<TChannel, TParams>,\n io: IOWithIntegrations<{ integration: TIntegration }>,\n ctx: TriggerContext\n) => Promise<UpdateTriggerSourceBody | undefined>;\n\nexport type HandlerEvent<\n TChannel extends ChannelNames,\n TParams extends any = any\n> = {\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"];\n source: HandleTriggerSource & { params: TParams };\n};\n\ntype HandlerFunction<TChannel extends ChannelNames, TParams extends any> = (\n event: HandlerEvent<TChannel, TParams>,\n logger: Logger\n) => Promise<{ events: SendEvent[]; response?: NormalizedResponse } | void>;\n\ntype KeyFunction<TParams extends any> = (params: TParams) => string;\ntype FilterFunction<TParams extends any> = (params: TParams) => EventFilter;\n\ntype ExternalSourceOptions<\n TChannel extends ChannelNames,\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any\n> = {\n id: string;\n version: string;\n schema: z.Schema<TParams>;\n integration: TIntegration;\n register: RegisterFunction<TIntegration, TParams, TChannel>;\n filter: FilterFunction<TParams>;\n handler: HandlerFunction<TChannel, TParams>;\n key: KeyFunction<TParams>;\n properties?: (params: TParams) => DisplayProperty[];\n};\n\nexport class ExternalSource<\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any,\n TChannel extends ChannelNames = ChannelNames\n> {\n channel: TChannel;\n\n constructor(\n channel: TChannel,\n private options: ExternalSourceOptions<TChannel, TIntegration, TParams>\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 );\n }\n\n filter(params: TParams): EventFilter {\n return this.options.filter(params);\n }\n\n properties(params: TParams): DisplayProperty[] {\n return this.options.properties?.(params) ?? [];\n }\n\n async register(\n params: TParams,\n registerEvent: RegisterSourceEvent,\n io: IO,\n ctx: TriggerContext\n ) {\n const { result: event, ommited: source } = omit(registerEvent, \"source\");\n const { result: sourceWithoutChannel, ommited: channel } = omit(\n source,\n \"channel\"\n );\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<\n TExternalSource extends ExternalSource<any, any, any>\n> = TExternalSource extends ExternalSource<any, infer TParams, any>\n ? TParams\n : never;\n\nexport type ExternalSourceTriggerOptions<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>\n> = {\n event: TEventSpecification;\n source: TEventSource;\n params: ExternalSourceParams<TEventSource>;\n};\n\nexport class ExternalSourceTrigger<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>\n> implements Trigger<TEventSpecification>\n{\n constructor(\n private options: ExternalSourceTriggerOptions<\n TEventSpecification,\n TEventSource\n >\n ) {}\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),\n this.event.filter ?? {}\n ),\n source: this.event.source,\n },\n properties: this.options.source.properties(this.options.params),\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<TEventSpecification>, any>\n ) {\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 });\n }\n\n get preprocessRuns() {\n return true;\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 RegisterSourceEvent,\n RegisterTriggerBody,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/internal\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport { slugifyId } from \"../utils\";\nimport { ExternalSource, ExternalSourceParams } from \"./externalSource\";\n\nexport type DynamicTriggerOptions<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>\n> = {\n id: string;\n event: TEventSpec;\n source: TExternalSource;\n};\n\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 constructor(\n client: TriggerClient,\n options: DynamicTriggerOptions<TEventSpec, TExternalSource>\n ) {\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 registeredTriggerForParams(\n params: ExternalSourceParams<TExternalSource>\n ): RegisterTriggerBody {\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 ),\n },\n source: {\n key: slugifyId(this.source.key(params)),\n channel: this.source.channel,\n params,\n events: [this.event.name],\n integration: {\n id: this.source.integration.id,\n metadata: this.source.integration.metadata,\n authSource: this.source.integration.client.usesLocalAuth\n ? \"LOCAL\"\n : \"HOSTED\",\n },\n },\n };\n }\n\n async register(\n key: string,\n params: ExternalSourceParams<TExternalSource>\n ): Promise<RegisterSourceEvent> {\n return this.#client.registerTrigger(\n this.id,\n key,\n this.registeredTriggerForParams(params)\n );\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<TEventSpec>, any>\n ): void {\n triggerClient.attachJobToDynamicTrigger(job, this);\n }\n\n get preprocessRuns() {\n return true;\n }\n}\n","import {\n CronOptions,\n IntervalOptions,\n ScheduleMetadata,\n ScheduledPayload,\n ScheduledPayloadSchema,\n TriggerMetadata,\n currentDate,\n} from \"@trigger.dev/internal\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport cronstrue from \"cronstrue\";\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 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\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 const humanReadable = cronstrue.toString(this.options.cron, {\n throwExceptionOnParseError: false,\n });\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 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\nexport function cronTrigger(options: CronOptions) {\n return new CronTrigger(options);\n}\n\nexport type DynamicIntervalOptions = { id: string };\n\nexport class DynamicSchedule implements Trigger<ScheduledEventSpecification> {\n constructor(\n private client: TriggerClient,\n private options: DynamicIntervalOptions\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 return this.client.registerSchedule(this.id, key, metadata);\n }\n\n async unregister(key: string) {\n return this.client.unregisterSchedule(this.id, key);\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {\n triggerClient.attachDynamicSchedule(this.options.id, job);\n }\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.options.id,\n };\n }\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/internal\";\nimport { TriggerIntegration } from \"../integrations\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\n\nexport function missingConnectionNotification(\n integrations: Array<TriggerIntegration>\n) {\n return new MissingConnectionNotification({ integrations });\n}\n\nexport function missingConnectionResolvedNotification(\n integrations: Array<TriggerIntegration>\n) {\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 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 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAO,SAASA,UAAUC,OAAuB;AAE/C,QAAMC,wBAAwBD,MAAME,YAAW,EAAGC,QAAQ,QAAQ,GAAA;AAGlE,QAAMC,wBAAwBH,sBAAsBE,QAClD,qBACA,EAAA;AAGF,SAAOC;AACT;AAXgBL;;;ACmBhB;AA8DO,IAAMM,MAAN,MAAMA;EAWXC,YAGEC,QACAC,SACA;AAyEF;AAxEE,SAAKD,SAASA;AACd,SAAKC,UAAUA;AACf,0BAAK,wBAAL;AAEAD,WAAOE,OAAO,IAAI;EACpB;EAEA,IAAIC,KAAK;AACP,WAAOC,UAAU,KAAKH,QAAQE,EAAE;EAClC;EAEA,IAAIE,UAAU;AACZ,WAAO,OAAO,KAAKJ,QAAQI,YAAY,YACnC,KAAKJ,QAAQI,UACb;EACN;EAEA,IAAIC,OAAO;AACT,WAAO,KAAKL,QAAQK;EACtB;EAEA,IAAIC,UAAU;AACZ,WAAO,KAAKN,QAAQM;EACtB;EAEA,IAAIC,UAAU;AACZ,WAAO,KAAKP,QAAQO;EACtB;EAEA,IAAIC,eAAkD;AACpD,WAAOC,OAAOC,KAAK,KAAKV,QAAQQ,gBAAgB,CAAC,CAAA,EAAGG,OAClD,CAACC,KAAwCC,QAAQ;AAC/C,YAAMC,cAAc,KAAKd,QAAQQ,aAAcK;AAE/CD,UAAIC,OAAO;QACTX,IAAIY,YAAYZ;QAChBa,UAAUD,YAAYC;QACtBC,YAAYF,YAAYf,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akB,IAAI,CAACC,MAAMA,EAAEC,EAAE;UAC/C;QACF;MACF;IACF;EACF;AACF;AA7CajB;;;A5BrDN,SAAS8B,aACdC,YACGC,gBACW;AACd,SAAO;IACLC,kBAAkB;IAClBF,SAASA,QAAQG;IACjBF;EACF;AACF;AATgBF;","names":["slugifyId","input","replaceSpacesWithDash","toLowerCase","replace","removeNonUrlSafeChars","Job","constructor","client","options","attach","id","slugifyId","enabled","name","trigger","version","integrations","Object","keys","reduce","acc","key","integration","metadata","authSource","usesLocalAuth","logLevel","toJSON","internal","__internal","event","queue","startPosition","preprocessRuns","match","Error","logLevels","Logger","constructor","name","level","filteredKeys","jsonReplacer","indexOf","process","env","TRIGGER_LOG_LEVEL","filter","keys","satisfiesLogLevel","logLevel","setLevel","log","args","console","formattedDateTime","error","warn","info","debug","message","structuredLog","timestamp","Date","structureArgs","safeJsonClone","JSON","stringify","createReplacer","replacer","key","value","toString","bigIntReplacer","_key","obj","parse","e","date","hours","getHours","minutes","getMinutes","seconds","getSeconds","milliseconds","getMilliseconds","formattedHours","formattedMinutes","formattedSeconds","formattedMilliseconds","length","filterKeys","Array","isArray","map","item","filteredObj","Object","entries","includes","import_zod","ErrorWithStackSchema","z","object","message","string","name","optional","stack","import_zod","EventMatcherSchema","z","union","array","string","number","boolean","EventFilterSchema","lazy","record","EventRuleSchema","object","event","source","payload","optional","context","import_zod","ConnectionAuthSchema","z","object","type","enum","accessToken","string","scopes","array","optional","additionalFields","record","IntegrationMetadataSchema","id","name","instructions","IntegrationConfigSchema","metadata","authSource","import_zod","LiteralSchema","z","union","string","number","boolean","null","DeserializedJsonSchema","lazy","array","record","SerializableSchema","date","undefined","symbol","SerializableJsonSchema","import_zod","DisplayPropertySchema","z","object","label","string","text","url","optional","DisplayPropertiesSchema","array","StyleSchema","style","enum","variant","import_zod","ScheduledPayloadSchema","z","object","ts","coerce","date","lastTimestamp","optional","IntervalOptionsSchema","seconds","number","int","positive","min","max","CronOptionsSchema","cron","string","CronMetadataSchema","type","literal","options","metadata","any","IntervalMetadataSchema","ScheduleMetadataSchema","discriminatedUnion","RegisterDynamicSchedulePayloadSchema","id","jobs","array","version","import_zod","TaskStatusSchema","z","enum","TaskSchema","object","id","string","name","icon","optional","nullable","noop","boolean","startedAt","coerce","date","completedAt","delayUntil","status","description","properties","array","DisplayPropertySchema","params","DeserializedJsonSchema","output","error","parentId","style","StyleSchema","operation","ServerTaskSchema","extend","idempotencyKey","attempts","number","CachedTaskSchema","default","import_zod","EventExampleSchema","z","object","id","string","icon","optional","name","payload","any","EventSpecificationSchema","title","source","filter","EventFilterSchema","properties","array","DisplayPropertySchema","schema","examples","DynamicTriggerMetadataSchema","type","literal","StaticTriggerMetadataSchema","rule","EventRuleSchema","ScheduledTriggerMetadataSchema","schedule","ScheduleMetadataSchema","TriggerMetadataSchema","discriminatedUnion","UpdateTriggerSourceBodySchema","z","object","registeredEvents","array","string","secret","optional","data","SerializableJsonSchema","HttpEventSourceSchema","extend","id","active","boolean","url","RegisterHTTPTriggerSourceBodySchema","type","literal","RegisterSMTPTriggerSourceBodySchema","RegisterSQSTriggerSourceBodySchema","RegisterSourceChannelBodySchema","discriminatedUnion","REGISTER_SOURCE_EVENT","RegisterTriggerSourceSchema","key","params","any","DeserializedJsonSchema","channel","clientId","RegisterSourceEventSchema","source","events","missingEvents","orphanedEvents","dynamicTriggerId","TriggerSourceSchema","HandleTriggerSourceSchema","HttpSourceRequestSchema","method","headers","record","rawBody","instanceof","Buffer","nullable","HttpSourceRequestHeadersSchema","transform","s","JSON","parse","PongSuccessResponseSchema","ok","PongErrorResponseSchema","error","PongResponseSchema","QueueOptionsSchema","name","maxConcurrent","number","JobMetadataSchema","version","event","EventSpecificationSchema","trigger","TriggerMetadataSchema","integrations","IntegrationConfigSchema","internal","default","queue","union","startPosition","enum","enabled","preprocessRuns","SourceMetadataSchema","integration","DynamicTriggerEndpointMetadataSchema","jobs","pick","IndexEndpointResponseSchema","sources","dynamicTriggers","dynamicSchedules","RegisterDynamicSchedulePayloadSchema","RawEventSchema","payload","context","ulid","timestamp","coerce","date","ApiEventLogSchema","deliverAt","deliveredAt","SendEventOptionsSchema","deliverAfter","int","accountId","SendEventBodySchema","options","DeliverEventResponseSchema","datetime","RuntimeEnvironmentTypeSchema","RunSourceContextSchema","metadata","RunJobBodySchema","job","run","isTest","startedAt","environment","slug","organization","title","account","tasks","CachedTaskSchema","connections","ConnectionAuthSchema","RunJobErrorSchema","status","ErrorWithStackSchema","task","TaskSchema","RunJobResumeWithTaskSchema","RunJobRetryWithTaskSchema","retryAt","RunJobSuccessSchema","output","RunJobResponseSchema","PreprocessRunBodySchema","PreprocessRunResponseSchema","abort","properties","DisplayPropertySchema","CreateRunBodySchema","client","CreateRunResponseOkSchema","CreateRunResponseErrorSchema","CreateRunResponseBodySchema","RedactStringSchema","__redactedString","strings","interpolations","LogMessageSchema","level","message","RedactSchema","paths","RetryOptionsSchema","limit","factor","minTimeoutInMs","maxTimeoutInMs","randomize","RunTaskOptionsSchema","delayUntil","retry","icon","displayKey","description","style","StyleSchema","connectionKey","operation","noop","redact","RunTaskBodyInputSchema","idempotencyKey","parentId","RunTaskBodyOutputSchema","CompleteTaskBodyInputSchema","v","stringify","FailTaskBodyInputSchema","NormalizedRequestSchema","query","body","NormalizedResponseSchema","HttpSourceResponseSchema","response","RegisterTriggerBodySchema","rule","EventRuleSchema","InitializeTriggerBodySchema","RegisterCommonScheduleBodySchema","RegisterIntervalScheduleBodySchema","merge","IntervalMetadataSchema","InitializeCronScheduleBodySchema","CronMetadataSchema","RegisterScheduleBodySchema","RegisterScheduleResponseBodySchema","schedule","ScheduleMetadataSchema","CreateExternalConnectionBodySchema","accessToken","scopes","import_zod","MISSING_CONNECTION_NOTIFICATION","MISSING_CONNECTION_RESOLVED_NOTIFICATION","CommonMissingConnectionNotificationPayloadSchema","z","object","id","string","client","title","scopes","array","createdAt","coerce","date","updatedAt","authorizationUrl","MissingDeveloperConnectionNotificationPayloadSchema","extend","type","literal","MissingExternalConnectionNotificationPayloadSchema","account","metadata","any","MissingConnectionNotificationPayloadSchema","discriminatedUnion","CommonMissingConnectionNotificationResolvedPayloadSchema","integrationIdentifier","integrationAuthMethod","expiresAt","MissingDeveloperConnectionResolvedNotificationPayloadSchema","MissingExternalConnectionResolvedNotificationPayloadSchema","MissingConnectionResolvedNotificationPayloadSchema","import_zod","FetchRetryHeadersStrategySchema","z","object","strategy","literal","limitHeader","string","remainingHeader","resetHeader","FetchRetryBackoffStrategySchema","RetryOptionsSchema","extend","FetchRetryStrategySchema","discriminatedUnion","FetchRequestInitSchema","method","optional","headers","record","union","RedactStringSchema","body","instanceof","ArrayBuffer","FetchRetryOptionsSchema","FetchOperationSchema","url","requestInit","retry","deepMergeFilters","filter","other","result","key","hasOwnProperty","otherValue","Array","isArray","filterValue","DEFAULT_RETRY_OPTIONS","limit","factor","minTimeoutInMs","maxTimeoutInMs","randomize","calculateRetryAt","retryOptions","attempts","options","retryCount","random","Math","timeoutInMs","round","max","pow","min","Date","now","currentDate","marker","replace","data","now","toISOString","import_zod","ApiClient","constructor","options","apiUrl","process","env","TRIGGER_API_URL","Logger","logLevel","registerEndpoint","apiKey","debug","url","name","response","fetch","method","headers","Authorization","body","JSON","stringify","status","json","Error","error","createRun","params","zodfetch","CreateRunResponseBodySchema","runTask","runId","task","ServerTaskSchema","idempotencyKey","completeTask","id","failTask","sendEvent","event","ApiEventLogSchema","updateSource","client","key","source","TriggerSourceSchema","registerTrigger","payload","RegisterSourceEventSchema","registerSchedule","RegisterScheduleResponseBodySchema","unregisterSchedule","z","object","ok","boolean","encodeURIComponent","getAuth","ConnectionAuthSchema","Accept","optional","getApiKey","TRIGGER_API_KEY","isValid","match","schema","requestInit","errorMessage","jsonBody","parse","ResumeWithTaskError","constructor","task","RetryWithTaskError","cause","retryAt","isTriggerError","err","createIOWithIntegrations","io","auths","integrations","connections","Object","entries","reduce","acc","connectionKey","integration","auth","client","usesLocalAuth","clientFactory","undefined","ioConnection","tasks","keys","forEach","taskName","authenticatedTask","key","params","options","init","runTask","ioTask","run","onError","Proxy","get","target","prop","receiver","value","Reflect","bind","IO","constructor","options","_id","id","_apiClient","apiClient","_triggerClient","client","_logger","logger","Logger","logLevel","_cachedTasks","Map","_jobLogger","jobLogger","_jobLogLevel","jobLogLevel","cachedTasks","forEach","task","set","_taskStorage","AsyncLocalStorage","_context","context","IOLogger","level","message","data","log","debug","info","warn","error","satisfiesLogLevel","runTask","name","icon","description","params","properties","label","text","style","variant","toLowerCase","noop","wait","key","seconds","delayUntil","Date","now","backgroundFetch","url","requestInit","retry","urlObject","URL","hostname","pathname","operation","method","output","sendEvent","event","updateSource","redact","paths","registerInterval","dynamicSchedule","toString","register","type","unregisterInterval","unregister","registerCron","cron","unregisterCron","registerTrigger","trigger","registration","subtask1","connection","getAuth","source","clientId","io","createIOWithIntegrations","integration","updates","callback","onError","parentId","getStore","taskId","idempotencyKey","generateIdempotencyKey","flat","cachedTask","get","displayKey","undefined","status","Error","ResumeWithTaskError","executeTask","result","completeTask","isTriggerError","onErrorResult","parsedError","ErrorWithStackSchema","safeParse","RetryWithTaskError","success","retryAt","calculateRetryAt","attempts","failTask","JSON","stringify","run","try","tryCallback","catchCallback","keyMaterial","keys","map","stableStringify","join","hash","webcrypto","subtle","digest","Buffer","from","obj","sortKeys","Array","isArray","sortedKeys","Object","sort","sortedObj","_options","EventTrigger","constructor","options","toJSON","type","title","name","event","rule","source","payload","deepMergeFilters","filter","attachToJob","triggerClient","job","preprocessRuns","eventTrigger","icon","parsePayload","rawPayload","schema","parse","registerSourceEvent","name","REGISTER_SOURCE_EVENT","title","source","icon","parsePayload","RegisterSourceEventSchema","parse","_options","TriggerClient","constructor","options","id","ApiClient","Logger","verbose","handleRequest","request","debug","url","headers","Object","fromEntries","entries","method","apiKey","get","authorization","authorized","status","body","message","action","endpointId","ok","error","jobId","job","toJSON","jobs","values","map","sources","dynamicTriggers","trigger","dynamicSchedules","json","InitializeTriggerBodySchema","safeParse","success","dynamicTrigger","data","registeredTriggerForParams","params","execution","RunJobBodySchema","results","PreprocessRunBodySchema","abort","properties","HttpSourceRequestHeadersSchema","sourceRequest","Request","undefined","key","dynamicId","secret","response","events","attach","enabled","attachToJob","attachDynamicTrigger","Job","version","EventTrigger","event","filter","dynamicTriggerId","integrations","integration","run","io","ctx","updates","register","updateSource","__internal","attachJobToDynamicTrigger","push","attachSource","s","r","handle","registeredSource","channel","metadata","authSource","client","usesLocalAuth","Array","from","Set","queue","maxConcurrent","startPosition","attachDynamicSchedule","registerTrigger","getAuth","sendEvent","registerSchedule","schedule","unregisterSchedule","localApiKey","process","env","TRIGGER_API_KEY","context","parsedPayload","payload","runProperties","IO","cachedTasks","tasks","apiClient","logger","jobLogLevel","logLevel","jobLogger","ioLogLocalEnabled","ioWithConnections","createIOWithIntegrations","connections","output","ResumeWithTaskError","task","RetryWithTaskError","cause","retryAt","errorWithStack","ErrorWithStackSchema","organization","environment","timestamp","account","handler","authenticatedTask","options","ExternalSource","constructor","channel","options","handle","source","rawEvent","logger","handler","params","filter","properties","register","registerEvent","io","ctx","result","event","ommited","omit","sourceWithoutChannel","channelWithoutType","updates","key","parts","id","push","integration","join","integrationConfig","metadata","version","ExternalSourceTrigger","toJSON","type","title","rule","name","payload","deepMergeFilters","attachToJob","triggerClient","job","attachSource","slugifyId","preprocessRuns","obj","k","Object","keys","_client","_options","DynamicTrigger","constructor","client","options","source","attachDynamicTrigger","toJSON","type","id","event","registeredTriggerForParams","params","rule","name","payload","deepMergeFilters","filter","key","slugifyId","channel","events","integration","metadata","authSource","usesLocalAuth","register","registerTrigger","attachToJob","triggerClient","job","attachJobToDynamicTrigger","preprocessRuns","examples","id","name","icon","payload","ts","currentDate","marker","lastTimestamp","IntervalTrigger","constructor","options","event","title","source","parsePayload","ScheduledPayloadSchema","parse","properties","label","text","seconds","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","schedule","intervalTrigger","CronTrigger","humanReadable","cronstrue","toString","cron","throwExceptionOnParseError","cronTrigger","DynamicSchedule","client","register","key","metadata","registerSchedule","unregister","unregisterSchedule","attachDynamicSchedule","missingConnectionNotification","integrations","MissingConnectionNotification","missingConnectionResolvedNotification","MissingConnectionResolvedNotification","constructor","options","event","name","MISSING_CONNECTION_NOTIFICATION","title","source","icon","parsePayload","MissingConnectionNotificationPayloadSchema","parse","properties","label","text","map","i","id","join","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","rule","payload","client","MISSING_CONNECTION_RESOLVED_NOTIFICATION","MissingConnectionResolvedNotificationPayloadSchema","redactString","strings","interpolations","__redactedString","raw"]}
|