@trigger.dev/sdk 3.3.16 → 4.0.0-v4-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/dist/commonjs/v3/ai.d.ts +23 -0
  2. package/dist/commonjs/v3/ai.js +50 -0
  3. package/dist/commonjs/v3/ai.js.map +1 -0
  4. package/dist/commonjs/v3/auth.d.ts +4 -3
  5. package/dist/commonjs/v3/auth.js.map +1 -1
  6. package/dist/commonjs/v3/hooks.d.ts +22 -0
  7. package/dist/commonjs/v3/hooks.js +65 -0
  8. package/dist/commonjs/v3/hooks.js.map +1 -0
  9. package/dist/commonjs/v3/index.d.ts +3 -1
  10. package/dist/commonjs/v3/index.js +4 -1
  11. package/dist/commonjs/v3/index.js.map +1 -1
  12. package/dist/commonjs/v3/locals.d.ts +3 -0
  13. package/dist/commonjs/v3/locals.js +6 -0
  14. package/dist/commonjs/v3/locals.js.map +1 -0
  15. package/dist/commonjs/v3/queues.d.ts +61 -0
  16. package/dist/commonjs/v3/queues.js +137 -0
  17. package/dist/commonjs/v3/queues.js.map +1 -0
  18. package/dist/commonjs/v3/retry.js +10 -7
  19. package/dist/commonjs/v3/retry.js.map +1 -1
  20. package/dist/commonjs/v3/runs.d.ts +40 -40
  21. package/dist/commonjs/v3/schedules/index.js +1 -1
  22. package/dist/commonjs/v3/schedules/index.js.map +1 -1
  23. package/dist/commonjs/v3/shared.d.ts +7 -6
  24. package/dist/commonjs/v3/shared.js +192 -176
  25. package/dist/commonjs/v3/shared.js.map +1 -1
  26. package/dist/commonjs/v3/tasks.d.ts +12 -0
  27. package/dist/commonjs/v3/tasks.js +11 -0
  28. package/dist/commonjs/v3/tasks.js.map +1 -1
  29. package/dist/commonjs/v3/wait.d.ts +208 -3
  30. package/dist/commonjs/v3/wait.js +407 -7
  31. package/dist/commonjs/v3/wait.js.map +1 -1
  32. package/dist/commonjs/version.js +1 -1
  33. package/dist/esm/v3/ai.d.ts +23 -0
  34. package/dist/esm/v3/ai.js +47 -0
  35. package/dist/esm/v3/ai.js.map +1 -0
  36. package/dist/esm/v3/auth.d.ts +4 -3
  37. package/dist/esm/v3/auth.js.map +1 -1
  38. package/dist/esm/v3/hooks.d.ts +22 -0
  39. package/dist/esm/v3/hooks.js +54 -0
  40. package/dist/esm/v3/hooks.js.map +1 -0
  41. package/dist/esm/v3/index.d.ts +3 -1
  42. package/dist/esm/v3/index.js +3 -1
  43. package/dist/esm/v3/index.js.map +1 -1
  44. package/dist/esm/v3/locals.d.ts +3 -0
  45. package/dist/esm/v3/locals.js +3 -0
  46. package/dist/esm/v3/locals.js.map +1 -0
  47. package/dist/esm/v3/queues.d.ts +61 -0
  48. package/dist/esm/v3/queues.js +131 -0
  49. package/dist/esm/v3/queues.js.map +1 -0
  50. package/dist/esm/v3/retry.js +11 -8
  51. package/dist/esm/v3/retry.js.map +1 -1
  52. package/dist/esm/v3/runs.d.ts +39 -39
  53. package/dist/esm/v3/schedules/index.js +2 -2
  54. package/dist/esm/v3/schedules/index.js.map +1 -1
  55. package/dist/esm/v3/shared.d.ts +7 -6
  56. package/dist/esm/v3/shared.js +193 -177
  57. package/dist/esm/v3/shared.js.map +1 -1
  58. package/dist/esm/v3/tasks.d.ts +12 -0
  59. package/dist/esm/v3/tasks.js +11 -0
  60. package/dist/esm/v3/tasks.js.map +1 -1
  61. package/dist/esm/v3/wait.d.ts +208 -3
  62. package/dist/esm/v3/wait.js +406 -7
  63. package/dist/esm/v3/wait.js.map +1 -1
  64. package/dist/esm/version.js +1 -1
  65. package/package.json +36 -17
  66. package/dist/commonjs/apiClient.d.ts +0 -727
  67. package/dist/commonjs/apiClient.js +0 -692
  68. package/dist/commonjs/apiClient.js.map +0 -1
  69. package/dist/commonjs/concurrencyLimit.d.ts +0 -10
  70. package/dist/commonjs/concurrencyLimit.js +0 -17
  71. package/dist/commonjs/concurrencyLimit.js.map +0 -1
  72. package/dist/commonjs/errors.d.ts +0 -66
  73. package/dist/commonjs/errors.js +0 -109
  74. package/dist/commonjs/errors.js.map +0 -1
  75. package/dist/commonjs/httpEndpoint.d.ts +0 -87
  76. package/dist/commonjs/httpEndpoint.js +0 -130
  77. package/dist/commonjs/httpEndpoint.js.map +0 -1
  78. package/dist/commonjs/index.d.ts +0 -23
  79. package/dist/commonjs/index.js +0 -55
  80. package/dist/commonjs/index.js.map +0 -1
  81. package/dist/commonjs/integrations.d.ts +0 -11
  82. package/dist/commonjs/integrations.js +0 -3
  83. package/dist/commonjs/integrations.js.map +0 -1
  84. package/dist/commonjs/io.d.ts +0 -441
  85. package/dist/commonjs/io.js +0 -1165
  86. package/dist/commonjs/io.js.map +0 -1
  87. package/dist/commonjs/ioWithIntegrations.d.ts +0 -4
  88. package/dist/commonjs/ioWithIntegrations.js +0 -32
  89. package/dist/commonjs/ioWithIntegrations.js.map +0 -1
  90. package/dist/commonjs/job.d.ts +0 -96
  91. package/dist/commonjs/job.js +0 -210
  92. package/dist/commonjs/job.js.map +0 -1
  93. package/dist/commonjs/retry.d.ts +0 -20
  94. package/dist/commonjs/retry.js +0 -22
  95. package/dist/commonjs/retry.js.map +0 -1
  96. package/dist/commonjs/runLocalStorage.d.ts +0 -8
  97. package/dist/commonjs/runLocalStorage.js +0 -6
  98. package/dist/commonjs/runLocalStorage.js.map +0 -1
  99. package/dist/commonjs/security.d.ts +0 -18
  100. package/dist/commonjs/security.js +0 -41
  101. package/dist/commonjs/security.js.map +0 -1
  102. package/dist/commonjs/status.d.ts +0 -19
  103. package/dist/commonjs/status.js +0 -38
  104. package/dist/commonjs/status.js.map +0 -1
  105. package/dist/commonjs/store/keyValueStore.d.ts +0 -17
  106. package/dist/commonjs/store/keyValueStore.js +0 -138
  107. package/dist/commonjs/store/keyValueStore.js.map +0 -1
  108. package/dist/commonjs/store/keyValueStoreClient.d.ts +0 -19
  109. package/dist/commonjs/store/keyValueStoreClient.js +0 -65
  110. package/dist/commonjs/store/keyValueStoreClient.js.map +0 -1
  111. package/dist/commonjs/triggerClient.d.ts +0 -290
  112. package/dist/commonjs/triggerClient.js +0 -1366
  113. package/dist/commonjs/triggerClient.js.map +0 -1
  114. package/dist/commonjs/triggers/dynamic.d.ts +0 -56
  115. package/dist/commonjs/triggers/dynamic.js +0 -97
  116. package/dist/commonjs/triggers/dynamic.js.map +0 -1
  117. package/dist/commonjs/triggers/eventTrigger.d.ts +0 -58
  118. package/dist/commonjs/triggers/eventTrigger.js +0 -69
  119. package/dist/commonjs/triggers/eventTrigger.js.map +0 -1
  120. package/dist/commonjs/triggers/externalSource.d.ts +0 -148
  121. package/dist/commonjs/triggers/externalSource.js +0 -106
  122. package/dist/commonjs/triggers/externalSource.js.map +0 -1
  123. package/dist/commonjs/triggers/invokeTrigger.d.ts +0 -39
  124. package/dist/commonjs/triggers/invokeTrigger.js +0 -58
  125. package/dist/commonjs/triggers/invokeTrigger.js.map +0 -1
  126. package/dist/commonjs/triggers/notifications.d.ts +0 -111
  127. package/dist/commonjs/triggers/notifications.js +0 -101
  128. package/dist/commonjs/triggers/notifications.js.map +0 -1
  129. package/dist/commonjs/triggers/scheduled.d.ts +0 -145
  130. package/dist/commonjs/triggers/scheduled.js +0 -208
  131. package/dist/commonjs/triggers/scheduled.js.map +0 -1
  132. package/dist/commonjs/triggers/webhook.d.ts +0 -143
  133. package/dist/commonjs/triggers/webhook.js +0 -133
  134. package/dist/commonjs/triggers/webhook.js.map +0 -1
  135. package/dist/commonjs/typed-emitter.d.ts +0 -37
  136. package/dist/commonjs/typed-emitter.js +0 -3
  137. package/dist/commonjs/typed-emitter.js.map +0 -1
  138. package/dist/commonjs/types.d.ts +0 -204
  139. package/dist/commonjs/types.js +0 -23
  140. package/dist/commonjs/types.js.map +0 -1
  141. package/dist/commonjs/utils/formatSchemaErrors.d.ts +0 -3
  142. package/dist/commonjs/utils/formatSchemaErrors.js +0 -10
  143. package/dist/commonjs/utils/formatSchemaErrors.js.map +0 -1
  144. package/dist/commonjs/utils/typedAsyncLocalStorage.d.ts +0 -6
  145. package/dist/commonjs/utils/typedAsyncLocalStorage.js +0 -18
  146. package/dist/commonjs/utils/typedAsyncLocalStorage.js.map +0 -1
  147. package/dist/commonjs/utils.d.ts +0 -1
  148. package/dist/commonjs/utils.js +0 -11
  149. package/dist/commonjs/utils.js.map +0 -1
  150. package/dist/esm/apiClient.d.ts +0 -727
  151. package/dist/esm/apiClient.js +0 -687
  152. package/dist/esm/apiClient.js.map +0 -1
  153. package/dist/esm/concurrencyLimit.d.ts +0 -10
  154. package/dist/esm/concurrencyLimit.js +0 -13
  155. package/dist/esm/concurrencyLimit.js.map +0 -1
  156. package/dist/esm/errors.d.ts +0 -66
  157. package/dist/esm/errors.js +0 -95
  158. package/dist/esm/errors.js.map +0 -1
  159. package/dist/esm/httpEndpoint.d.ts +0 -87
  160. package/dist/esm/httpEndpoint.js +0 -125
  161. package/dist/esm/httpEndpoint.js.map +0 -1
  162. package/dist/esm/index.d.ts +0 -23
  163. package/dist/esm/index.js +0 -35
  164. package/dist/esm/index.js.map +0 -1
  165. package/dist/esm/integrations.d.ts +0 -11
  166. package/dist/esm/integrations.js +0 -2
  167. package/dist/esm/integrations.js.map +0 -1
  168. package/dist/esm/io.d.ts +0 -441
  169. package/dist/esm/io.js +0 -1159
  170. package/dist/esm/io.js.map +0 -1
  171. package/dist/esm/ioWithIntegrations.d.ts +0 -4
  172. package/dist/esm/ioWithIntegrations.js +0 -29
  173. package/dist/esm/ioWithIntegrations.js.map +0 -1
  174. package/dist/esm/job.d.ts +0 -96
  175. package/dist/esm/job.js +0 -206
  176. package/dist/esm/job.js.map +0 -1
  177. package/dist/esm/retry.d.ts +0 -20
  178. package/dist/esm/retry.js +0 -19
  179. package/dist/esm/retry.js.map +0 -1
  180. package/dist/esm/runLocalStorage.d.ts +0 -8
  181. package/dist/esm/runLocalStorage.js +0 -3
  182. package/dist/esm/runLocalStorage.js.map +0 -1
  183. package/dist/esm/security.d.ts +0 -18
  184. package/dist/esm/security.js +0 -34
  185. package/dist/esm/security.js.map +0 -1
  186. package/dist/esm/status.d.ts +0 -19
  187. package/dist/esm/status.js +0 -34
  188. package/dist/esm/status.js.map +0 -1
  189. package/dist/esm/store/keyValueStore.d.ts +0 -17
  190. package/dist/esm/store/keyValueStore.js +0 -134
  191. package/dist/esm/store/keyValueStore.js.map +0 -1
  192. package/dist/esm/store/keyValueStoreClient.d.ts +0 -19
  193. package/dist/esm/store/keyValueStoreClient.js +0 -61
  194. package/dist/esm/store/keyValueStoreClient.js.map +0 -1
  195. package/dist/esm/triggerClient.d.ts +0 -288
  196. package/dist/esm/triggerClient.js +0 -1359
  197. package/dist/esm/triggerClient.js.map +0 -1
  198. package/dist/esm/triggers/dynamic.d.ts +0 -56
  199. package/dist/esm/triggers/dynamic.js +0 -93
  200. package/dist/esm/triggers/dynamic.js.map +0 -1
  201. package/dist/esm/triggers/eventTrigger.d.ts +0 -58
  202. package/dist/esm/triggers/eventTrigger.js +0 -64
  203. package/dist/esm/triggers/eventTrigger.js.map +0 -1
  204. package/dist/esm/triggers/externalSource.d.ts +0 -148
  205. package/dist/esm/triggers/externalSource.js +0 -100
  206. package/dist/esm/triggers/externalSource.js.map +0 -1
  207. package/dist/esm/triggers/invokeTrigger.d.ts +0 -39
  208. package/dist/esm/triggers/invokeTrigger.js +0 -53
  209. package/dist/esm/triggers/invokeTrigger.js.map +0 -1
  210. package/dist/esm/triggers/notifications.d.ts +0 -111
  211. package/dist/esm/triggers/notifications.js +0 -94
  212. package/dist/esm/triggers/notifications.js.map +0 -1
  213. package/dist/esm/triggers/scheduled.d.ts +0 -145
  214. package/dist/esm/triggers/scheduled.js +0 -197
  215. package/dist/esm/triggers/scheduled.js.map +0 -1
  216. package/dist/esm/triggers/webhook.d.ts +0 -143
  217. package/dist/esm/triggers/webhook.js +0 -128
  218. package/dist/esm/triggers/webhook.js.map +0 -1
  219. package/dist/esm/typed-emitter.d.ts +0 -37
  220. package/dist/esm/typed-emitter.js +0 -2
  221. package/dist/esm/typed-emitter.js.map +0 -1
  222. package/dist/esm/types.d.ts +0 -204
  223. package/dist/esm/types.js +0 -19
  224. package/dist/esm/types.js.map +0 -1
  225. package/dist/esm/utils/formatSchemaErrors.d.ts +0 -3
  226. package/dist/esm/utils/formatSchemaErrors.js +0 -7
  227. package/dist/esm/utils/formatSchemaErrors.js.map +0 -1
  228. package/dist/esm/utils/typedAsyncLocalStorage.d.ts +0 -6
  229. package/dist/esm/utils/typedAsyncLocalStorage.js +0 -14
  230. package/dist/esm/utils/typedAsyncLocalStorage.js.map +0 -1
  231. package/dist/esm/utils.d.ts +0 -1
  232. package/dist/esm/utils.js +0 -8
  233. package/dist/esm/utils.js.map +0 -1
package/dist/esm/io.js DELETED
@@ -1,1159 +0,0 @@
1
- import { API_VERSIONS, ErrorWithStackSchema, supportsFeature, } from "@trigger.dev/core";
2
- import { Logger } from "@trigger.dev/core/logger";
3
- import { BloomFilter } from "@trigger.dev/core/bloom";
4
- import { AsyncLocalStorage } from "node:async_hooks";
5
- import { webcrypto } from "node:crypto";
6
- import { AutoYieldExecutionError, AutoYieldRateLimitError, AutoYieldWithCompletedTaskExecutionError, CanceledWithTaskError, ErrorWithTask, ResumeWithParallelTaskError, ResumeWithTaskError, RetryWithTaskError, YieldExecutionError, isTriggerError, } from "./errors.js";
7
- import { calculateRetryAt } from "./retry.js";
8
- import { TriggerStatus } from "./status.js";
9
- import { waitForEventSchema, } from "./types.js";
10
- import { z } from "zod";
11
- import { KeyValueStore } from "./store/keyValueStore.js";
12
- import { Buffer } from "node:buffer";
13
- export class JSONOutputSerializer {
14
- serialize(value) {
15
- return JSON.stringify(value);
16
- }
17
- deserialize(value) {
18
- return value ? JSON.parse(value) : undefined;
19
- }
20
- }
21
- export class IO {
22
- _id;
23
- _jobId;
24
- _apiClient;
25
- _triggerClient;
26
- _logger;
27
- _jobLogger;
28
- _jobLogLevel;
29
- _cachedTasks;
30
- _taskStorage;
31
- _cachedTasksCursor;
32
- _context;
33
- _yieldedExecutions;
34
- _noopTasksBloomFilter;
35
- _stats;
36
- _serverVersion;
37
- _timeOrigin;
38
- _executionTimeout;
39
- _outputSerializer = new JSONOutputSerializer();
40
- _visitedCacheKeys = new Set();
41
- _envStore;
42
- _jobStore;
43
- _runStore;
44
- get stats() {
45
- return this._stats;
46
- }
47
- constructor(options) {
48
- this._id = options.id;
49
- this._jobId = options.jobId;
50
- this._apiClient = options.apiClient;
51
- this._triggerClient = options.client;
52
- this._logger = options.logger ?? new Logger("trigger.dev", options.logLevel);
53
- this._cachedTasks = new Map();
54
- this._jobLogger = options.jobLogger;
55
- this._jobLogLevel = options.jobLogLevel;
56
- this._timeOrigin = options.timeOrigin;
57
- this._executionTimeout = options.executionTimeout;
58
- this._envStore = new KeyValueStore(options.apiClient);
59
- this._jobStore = new KeyValueStore(options.apiClient, "job", options.jobId);
60
- this._runStore = new KeyValueStore(options.apiClient, "run", options.id);
61
- this._stats = {
62
- initialCachedTasks: 0,
63
- lazyLoadedCachedTasks: 0,
64
- executedTasks: 0,
65
- cachedTaskHits: 0,
66
- cachedTaskMisses: 0,
67
- noopCachedTaskHits: 0,
68
- noopCachedTaskMisses: 0,
69
- };
70
- if (options.cachedTasks) {
71
- options.cachedTasks.forEach((task) => {
72
- this._cachedTasks.set(task.idempotencyKey, task);
73
- });
74
- this._stats.initialCachedTasks = options.cachedTasks.length;
75
- }
76
- this._taskStorage = new AsyncLocalStorage();
77
- this._context = options.context;
78
- this._yieldedExecutions = options.yieldedExecutions ?? [];
79
- if (options.noopTasksSet) {
80
- this._noopTasksBloomFilter = BloomFilter.deserialize(options.noopTasksSet, BloomFilter.NOOP_TASK_SET_SIZE);
81
- }
82
- this._cachedTasksCursor = options.cachedTasksCursor;
83
- this._serverVersion = options.serverVersion ?? "unversioned";
84
- }
85
- /** @internal */
86
- get runId() {
87
- return this._id;
88
- }
89
- /** @internal */
90
- get triggerClient() {
91
- return this._triggerClient;
92
- }
93
- /** Used to send log messages to the [Run log](https://trigger.dev/docs/documentation/guides/viewing-runs). */
94
- get logger() {
95
- return new IOLogger(async (level, message, data) => {
96
- let logLevel = "info";
97
- if (data instanceof Error) {
98
- data = {
99
- name: data.name,
100
- message: data.message,
101
- stack: data.stack,
102
- };
103
- }
104
- if (Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
105
- await this.runTask([message, level], async (task) => {
106
- switch (level) {
107
- case "LOG": {
108
- this._jobLogger?.log(message, data);
109
- logLevel = "log";
110
- break;
111
- }
112
- case "DEBUG": {
113
- this._jobLogger?.debug(message, data);
114
- logLevel = "debug";
115
- break;
116
- }
117
- case "INFO": {
118
- this._jobLogger?.info(message, data);
119
- logLevel = "info";
120
- break;
121
- }
122
- case "WARN": {
123
- this._jobLogger?.warn(message, data);
124
- logLevel = "warn";
125
- break;
126
- }
127
- case "ERROR": {
128
- this._jobLogger?.error(message, data);
129
- logLevel = "error";
130
- break;
131
- }
132
- }
133
- }, {
134
- name: "log",
135
- icon: "log",
136
- description: message,
137
- params: data,
138
- properties: [{ label: "Level", text: level }],
139
- style: { style: "minimal", variant: level.toLowerCase() },
140
- noop: true,
141
- });
142
- }
143
- });
144
- }
145
- /** `io.random()` is identical to `Math.random()` when called without options but ensures your random numbers are not regenerated on resume or retry. It will return a pseudo-random floating-point number between optional `min` (default: 0, inclusive) and `max` (default: 1, exclusive). Can optionally `round` to the nearest integer.
146
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
147
- * @param min Sets the lower bound (inclusive). Can't be higher than `max`.
148
- * @param max Sets the upper bound (exclusive). Can't be lower than `min`.
149
- * @param round Controls rounding to the nearest integer. Any `max` integer will become inclusive when enabled. Rounding with floating-point bounds may cause unexpected skew and boundary inclusivity.
150
- */
151
- async random(cacheKey, { min = 0, max = 1, round = false, } = {}) {
152
- return await this.runTask(cacheKey, async (task) => {
153
- if (min > max) {
154
- throw new Error(`Lower bound can't be higher than upper bound - min: ${min}, max: ${max}`);
155
- }
156
- if (min === max) {
157
- await this.logger.warn(`Lower and upper bounds are identical. The return value is not random and will always be: ${min}`);
158
- }
159
- const withinBounds = (max - min) * Math.random() + min;
160
- if (!round) {
161
- return withinBounds;
162
- }
163
- if (!Number.isInteger(min) || !Number.isInteger(max)) {
164
- await this.logger.warn("Rounding enabled with floating-point bounds. This may cause unexpected skew and boundary inclusivity.");
165
- }
166
- const rounded = Math.round(withinBounds);
167
- return rounded;
168
- }, {
169
- name: "random",
170
- icon: "dice-5-filled",
171
- params: { min, max, round },
172
- properties: [
173
- ...(min === 0
174
- ? []
175
- : [
176
- {
177
- label: "min",
178
- text: String(min),
179
- },
180
- ]),
181
- ...(max === 1
182
- ? []
183
- : [
184
- {
185
- label: "max",
186
- text: String(max),
187
- },
188
- ]),
189
- ...(round === false
190
- ? []
191
- : [
192
- {
193
- label: "round",
194
- text: String(round),
195
- },
196
- ]),
197
- ],
198
- style: { style: "minimal" },
199
- });
200
- }
201
- /** `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.
202
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
203
- * @param seconds The number of seconds to wait. This can be very long, serverless timeouts are not an issue.
204
- */
205
- async wait(cacheKey, seconds) {
206
- return await this.runTask(cacheKey, async (task) => { }, {
207
- name: "wait",
208
- icon: "clock",
209
- params: { seconds },
210
- noop: true,
211
- delayUntil: new Date(Date.now() + seconds * 1000),
212
- style: { style: "minimal" },
213
- });
214
- }
215
- async waitForEvent(cacheKey, event, options) {
216
- const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
217
- return (await this.runTask(cacheKey, async (task, io) => {
218
- if (!task.callbackUrl) {
219
- throw new Error("No callbackUrl found on task");
220
- }
221
- await this.triggerClient.createEphemeralEventDispatcher({
222
- url: task.callbackUrl,
223
- name: event.name,
224
- filter: event.filter,
225
- contextFilter: event.contextFilter,
226
- source: event.source,
227
- accountId: event.accountId,
228
- timeoutInSeconds,
229
- });
230
- return {};
231
- }, {
232
- name: "Wait for Event",
233
- icon: "custom-event",
234
- params: {
235
- name: event.name,
236
- source: event.source,
237
- filter: event.filter,
238
- contextFilter: event.contextFilter,
239
- accountId: event.accountId,
240
- },
241
- callback: {
242
- enabled: true,
243
- timeoutInSeconds,
244
- },
245
- properties: [
246
- {
247
- label: "Event",
248
- text: event.name,
249
- },
250
- {
251
- label: "Timeout",
252
- text: `${timeoutInSeconds}s`,
253
- },
254
- ...(event.source ? [{ label: "Source", text: event.source }] : []),
255
- ...(event.accountId ? [{ label: "Account ID", text: event.accountId }] : []),
256
- ],
257
- parseOutput: (output) => {
258
- return waitForEventSchema(event.schema ?? z.any()).parse(output);
259
- },
260
- }));
261
- }
262
- /** `io.waitForRequest()` allows you to pause the execution of a run until the url provided in the callback is POSTed to.
263
- * This is useful for integrating with external services that require a callback URL to be provided, or if you want to be able to wait until an action is performed somewhere else in your system.
264
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
265
- * @param callback A callback function that will provide the unique URL to POST to.
266
- * @param options Options for the callback.
267
- * @param options.timeoutInSeconds How long to wait for the request to be POSTed to the callback URL before timing out. Defaults to 1hr.
268
- * @returns The POSTed request JSON body.
269
- * @example
270
- * ```ts
271
- const result = await io.waitForRequest<{ message: string }>(
272
- "wait-for-request",
273
- async (url, task) => {
274
- // Save the URL somewhere so you can POST to it later
275
- // Or send it to an external service that will POST to it
276
- },
277
- { timeoutInSeconds: 60 } // wait 60 seconds
278
- );
279
- * ```
280
- */
281
- async waitForRequest(cacheKey, callback, options) {
282
- const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
283
- return (await this.runTask(cacheKey, async (task, io) => {
284
- if (!task.callbackUrl) {
285
- throw new Error("No callbackUrl found on task");
286
- }
287
- task.outputProperties = [
288
- {
289
- label: "Callback URL",
290
- text: task.callbackUrl,
291
- },
292
- ];
293
- return callback(task.callbackUrl);
294
- }, {
295
- name: "Wait for Request",
296
- icon: "clock",
297
- callback: {
298
- enabled: true,
299
- timeoutInSeconds: options?.timeoutInSeconds,
300
- },
301
- properties: [
302
- {
303
- label: "Timeout",
304
- text: `${timeoutInSeconds}s`,
305
- },
306
- ],
307
- }));
308
- }
309
- /** `io.createStatus()` allows you to set a status with associated data during the Run. Statuses can be used by your UI using the react package
310
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
311
- * @param initialStatus The initial status you want this status to have. You can update it during the rub using the returned object.
312
- * @returns a TriggerStatus object that you can call `update()` on, to update the status.
313
- * @example
314
- * ```ts
315
- * client.defineJob(
316
- //...
317
- run: async (payload, io, ctx) => {
318
- const generatingImages = await io.createStatus("generating-images", {
319
- label: "Generating Images",
320
- state: "loading",
321
- data: {
322
- progress: 0.1,
323
- },
324
- });
325
-
326
- //...do stuff
327
-
328
- await generatingImages.update("completed-generation", {
329
- label: "Generated images",
330
- state: "success",
331
- data: {
332
- progress: 1.0,
333
- urls: ["http://..."]
334
- },
335
- });
336
-
337
- //...
338
- });
339
- * ```
340
- */
341
- async createStatus(cacheKey, initialStatus) {
342
- const id = typeof cacheKey === "string" ? cacheKey : cacheKey.join("-");
343
- const status = new TriggerStatus(id, this);
344
- await status.update(cacheKey, initialStatus);
345
- return status;
346
- }
347
- /** `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.
348
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
349
- * @param url The URL to fetch from.
350
- * @param requestInit The options for the request
351
- * @param retry The options for retrying the request if it fails
352
- * An object where the key is a status code pattern and the value is a retrying strategy.
353
- * Supported patterns are:
354
- * - Specific status codes: 429
355
- * - Ranges: 500-599
356
- * - Wildcards: 2xx, 3xx, 4xx, 5xx
357
- */
358
- async backgroundFetch(cacheKey, url, requestInit, options) {
359
- const urlObject = new URL(url);
360
- return (await this.runTask(cacheKey, async (task) => {
361
- console.log("task context", task.context);
362
- return task.output;
363
- }, {
364
- name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
365
- params: { url, requestInit, retry: options?.retry, timeout: options?.timeout },
366
- operation: "fetch",
367
- icon: "background",
368
- noop: false,
369
- properties: [
370
- {
371
- label: "url",
372
- text: url,
373
- url,
374
- },
375
- {
376
- label: "method",
377
- text: requestInit?.method ?? "GET",
378
- },
379
- {
380
- label: "background",
381
- text: "true",
382
- },
383
- ...(options?.timeout
384
- ? [{ label: "timeout", text: `${options.timeout.durationInMs}ms` }]
385
- : []),
386
- ],
387
- retry: {
388
- limit: 0,
389
- },
390
- }));
391
- }
392
- /** `io.backgroundPoll()` will fetch data from a URL on an interval. The actual `fetch` requests are performed on the Trigger.dev server, so you don't have to worry about serverless function timeouts.
393
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
394
- * @param params The options for the background poll
395
- * @param params.url The URL to fetch from.
396
- * @param params.requestInit The options for the request, like headers and method
397
- * @param params.responseFilter An [EventFilter](https://trigger.dev/docs/documentation/guides/event-filter) that allows you to specify when to stop polling.
398
- * @param params.interval The interval in seconds to poll the URL in seconds. Defaults to 10 seconds which is the minimum.
399
- * @param params.timeout The timeout in seconds for each request in seconds. Defaults to 10 minutes. Minimum is 60 seconds and max is 1 hour
400
- * @param params.requestTimeout An optional object that allows you to timeout individual fetch requests
401
- * @param params.requestTimeout An optional object that allows you to timeout individual fetch requests
402
- * @param params.requestTimeout.durationInMs The duration in milliseconds to timeout the request
403
- *
404
- * @example
405
- * ```ts
406
- * const result = await io.backgroundPoll<{ id: string; status: string; }>("poll", {
407
- url: `http://localhost:3030/api/v1/runs/${run.id}`,
408
- requestInit: {
409
- headers: {
410
- Accept: "application/json",
411
- Authorization: redactString`Bearer ${process.env["TRIGGER_API_KEY"]!}`,
412
- },
413
- },
414
- interval: 10,
415
- timeout: 600,
416
- responseFilter: {
417
- status: [200],
418
- body: {
419
- status: ["SUCCESS"],
420
- },
421
- },
422
- });
423
- * ```
424
- */
425
- async backgroundPoll(cacheKey, params) {
426
- const urlObject = new URL(params.url);
427
- return (await this.runTask(cacheKey, async (task) => {
428
- return task.output;
429
- }, {
430
- name: `poll ${urlObject.hostname}${urlObject.pathname}`,
431
- params,
432
- operation: "fetch-poll",
433
- icon: "clock-bolt",
434
- noop: false,
435
- properties: [
436
- {
437
- label: "url",
438
- text: params.url,
439
- },
440
- {
441
- label: "interval",
442
- text: `${params.interval}s`,
443
- },
444
- {
445
- label: "timeout",
446
- text: `${params.timeout}s`,
447
- },
448
- ],
449
- retry: {
450
- limit: 0,
451
- },
452
- }));
453
- }
454
- /** `io.backgroundFetchResponse()` fetches data from a URL that can take longer that the serverless timeout. The actual `fetch` request is performed on the Trigger.dev platform, and the response is sent back to you.
455
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
456
- * @param url The URL to fetch from.
457
- * @param requestInit The options for the request
458
- * @param retry The options for retrying the request if it fails
459
- * An object where the key is a status code pattern and the value is a retrying strategy.
460
- * Supported patterns are:
461
- * - Specific status codes: 429
462
- * - Ranges: 500-599
463
- * - Wildcards: 2xx, 3xx, 4xx, 5xx
464
- */
465
- async backgroundFetchResponse(cacheKey, url, requestInit, options) {
466
- const urlObject = new URL(url);
467
- return (await this.runTask(cacheKey, async (task) => {
468
- return task.output;
469
- }, {
470
- name: `fetch response ${urlObject.hostname}${urlObject.pathname}`,
471
- params: { url, requestInit, retry: options?.retry, timeout: options?.timeout },
472
- operation: "fetch-response",
473
- icon: "background",
474
- noop: false,
475
- properties: [
476
- {
477
- label: "url",
478
- text: url,
479
- url,
480
- },
481
- {
482
- label: "method",
483
- text: requestInit?.method ?? "GET",
484
- },
485
- {
486
- label: "background",
487
- text: "true",
488
- },
489
- ...(options?.timeout
490
- ? [{ label: "timeout", text: `${options.timeout.durationInMs}ms` }]
491
- : []),
492
- ],
493
- retry: {
494
- limit: 0,
495
- },
496
- }));
497
- }
498
- /** `io.sendEvent()` allows you to send an event from inside a Job run. The sent event will trigger any Jobs that are listening for that event (based on the name).
499
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
500
- * @param event The event to send. The event name must match the name of the event that your Jobs are listening for.
501
- * @param options Options for sending the event.
502
- */
503
- async sendEvent(cacheKey, event, options) {
504
- return await this.runTask(cacheKey, async (task) => {
505
- return await this._triggerClient.sendEvent(event, options);
506
- }, {
507
- name: "Send Event",
508
- params: { event, options },
509
- icon: "send",
510
- properties: [
511
- {
512
- label: "name",
513
- text: event.name,
514
- },
515
- ...(event?.id ? [{ label: "ID", text: event.id }] : []),
516
- ...sendEventOptionsProperties(options),
517
- ],
518
- });
519
- }
520
- /** `io.sendEvents()` allows you to send multiple events from inside a Job run. The sent events will trigger any Jobs that are listening for those events (based on the name).
521
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
522
- * @param event The events to send. The event names must match the names of the events that your Jobs are listening for.
523
- * @param options Options for sending the events.
524
- */
525
- async sendEvents(cacheKey, events, options) {
526
- return await this.runTask(cacheKey, async (task) => {
527
- return await this._triggerClient.sendEvents(events, options);
528
- }, {
529
- name: "Send Multiple Events",
530
- params: { events, options },
531
- icon: "send",
532
- properties: [
533
- {
534
- label: "Total Events",
535
- text: String(events.length),
536
- },
537
- ...sendEventOptionsProperties(options),
538
- ],
539
- });
540
- }
541
- async getEvent(cacheKey, id) {
542
- return await this.runTask(cacheKey, async (task) => {
543
- return await this._triggerClient.getEvent(id);
544
- }, {
545
- name: "getEvent",
546
- params: { id },
547
- properties: [
548
- {
549
- label: "id",
550
- text: id,
551
- },
552
- ],
553
- });
554
- }
555
- /** `io.cancelEvent()` allows you to cancel an event that was previously sent with `io.sendEvent()`. This will prevent any Jobs from running that are listening for that event if the event was sent with a delay
556
- * @param cacheKey
557
- * @param eventId
558
- * @returns
559
- */
560
- async cancelEvent(cacheKey, eventId) {
561
- return await this.runTask(cacheKey, async (task) => {
562
- return await this._triggerClient.cancelEvent(eventId);
563
- }, {
564
- name: "cancelEvent",
565
- params: {
566
- eventId,
567
- },
568
- properties: [
569
- {
570
- label: "id",
571
- text: eventId,
572
- },
573
- ],
574
- });
575
- }
576
- async updateSource(cacheKey, options) {
577
- return this.runTask(cacheKey, async (task) => {
578
- return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
579
- }, {
580
- name: "Update Source",
581
- description: "Update Source",
582
- properties: [
583
- {
584
- label: "key",
585
- text: options.key,
586
- },
587
- ],
588
- params: options,
589
- redact: {
590
- paths: ["secret"],
591
- },
592
- });
593
- }
594
- async updateWebhook(cacheKey, options) {
595
- return this.runTask(cacheKey, async (task) => {
596
- return await this._apiClient.updateWebhook(options.key, options);
597
- }, {
598
- name: "Update Webhook Source",
599
- icon: "refresh",
600
- properties: [
601
- {
602
- label: "key",
603
- text: options.key,
604
- },
605
- ],
606
- params: options,
607
- });
608
- }
609
- /** `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.
610
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
611
- * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.
612
- * @param id A unique id for the interval. This is used to identify and unregister the interval later.
613
- * @param options The options for the interval.
614
- * @returns A promise that has information about the interval.
615
- * @deprecated Use `DynamicSchedule.register` instead.
616
- */
617
- async registerInterval(cacheKey, dynamicSchedule, id, options) {
618
- return await this.runTask(cacheKey, async (task) => {
619
- return dynamicSchedule.register(id, {
620
- type: "interval",
621
- options,
622
- });
623
- }, {
624
- name: "register-interval",
625
- properties: [
626
- { label: "schedule", text: dynamicSchedule.id },
627
- { label: "id", text: id },
628
- { label: "seconds", text: options.seconds.toString() },
629
- ],
630
- params: options,
631
- });
632
- }
633
- /** `io.unregisterInterval()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerInterval()`.
634
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
635
- * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.
636
- * @param id A unique id for the interval. This is used to identify and unregister the interval later.
637
- * @deprecated Use `DynamicSchedule.unregister` instead.
638
- */
639
- async unregisterInterval(cacheKey, dynamicSchedule, id) {
640
- return await this.runTask(cacheKey, async (task) => {
641
- return dynamicSchedule.unregister(id);
642
- }, {
643
- name: "unregister-interval",
644
- properties: [
645
- { label: "schedule", text: dynamicSchedule.id },
646
- { label: "id", text: id },
647
- ],
648
- });
649
- }
650
- /** `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.
651
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
652
- * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.
653
- * @param id A unique id for the schedule. This is used to identify and unregister the schedule later.
654
- * @param options The options for the CRON schedule.
655
- * @deprecated Use `DynamicSchedule.register` instead.
656
- */
657
- async registerCron(cacheKey, dynamicSchedule, id, options) {
658
- return await this.runTask(cacheKey, async (task) => {
659
- return dynamicSchedule.register(id, {
660
- type: "cron",
661
- options,
662
- });
663
- }, {
664
- name: "register-cron",
665
- properties: [
666
- { label: "schedule", text: dynamicSchedule.id },
667
- { label: "id", text: id },
668
- { label: "cron", text: options.cron },
669
- ],
670
- params: options,
671
- });
672
- }
673
- /** `io.unregisterCron()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerCron()`.
674
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
675
- * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.
676
- * @param id A unique id for the interval. This is used to identify and unregister the interval later.
677
- * @deprecated Use `DynamicSchedule.unregister` instead.
678
- */
679
- async unregisterCron(cacheKey, dynamicSchedule, id) {
680
- return await this.runTask(cacheKey, async (task) => {
681
- return dynamicSchedule.unregister(id);
682
- }, {
683
- name: "unregister-cron",
684
- properties: [
685
- { label: "schedule", text: dynamicSchedule.id },
686
- { label: "id", text: id },
687
- ],
688
- });
689
- }
690
- /** `io.registerTrigger()` allows you to register a [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) with the specified trigger params.
691
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
692
- * @param trigger The [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) to register.
693
- * @param id A unique id for the trigger. This is used to identify and unregister the trigger later.
694
- * @param params The params for the trigger.
695
- * @deprecated Use `DynamicTrigger.register` instead.
696
- */
697
- async registerTrigger(cacheKey, trigger, id, params) {
698
- return await this.runTask(cacheKey, async (task) => {
699
- const registration = await this.runTask("register-source", async (subtask1) => {
700
- return trigger.register(id, params);
701
- }, {
702
- name: "register-source",
703
- });
704
- return {
705
- id: registration.id,
706
- key: registration.source.key,
707
- };
708
- }, {
709
- name: "register-trigger",
710
- properties: [
711
- { label: "trigger", text: trigger.id },
712
- { label: "id", text: id },
713
- ],
714
- params: params,
715
- });
716
- }
717
- async getAuth(cacheKey, clientId) {
718
- if (!clientId) {
719
- return;
720
- }
721
- return this.runTask(cacheKey, async (task) => {
722
- return await this._triggerClient.getAuth(clientId);
723
- }, { name: "get-auth" });
724
- }
725
- async parallel(cacheKey, items, callback, options) {
726
- const results = await this.runTask(cacheKey, async (task) => {
727
- const outcomes = await Promise.allSettled(items.map((item, index) => spaceOut(() => callback(item, index), index, 15)));
728
- // If all the outcomes are fulfilled, return the values
729
- if (outcomes.every((outcome) => outcome.status === "fulfilled")) {
730
- return outcomes.map((outcome) => outcome.value);
731
- }
732
- // If they any of the errors are non internal errors, throw the first one
733
- const nonInternalErrors = outcomes
734
- .filter((outcome) => outcome.status === "rejected" && !isTriggerError(outcome.reason))
735
- .map((outcome) => outcome);
736
- if (nonInternalErrors.length > 0) {
737
- // @ts-expect-error
738
- throw nonInternalErrors[0].reason;
739
- }
740
- // gather all the internal errors
741
- const internalErrors = outcomes
742
- .filter((outcome) => outcome.status === "rejected" && isTriggerError(outcome.reason))
743
- .map((outcome) => outcome)
744
- .map((outcome) => outcome.reason);
745
- throw new ResumeWithParallelTaskError(task, internalErrors);
746
- }, {
747
- name: "parallel",
748
- parallel: true,
749
- ...(options ?? {}),
750
- });
751
- return results;
752
- }
753
- /** `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.
754
- *
755
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
756
- * @param callback The callback that will be called when the Task is run. The callback receives the Task and the IO as parameters.
757
- * @param options The options of how you'd like to run and log the Task.
758
- * @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.
759
- * @returns A Promise that resolves with the returned value of the callback.
760
- */
761
- async runTask(cacheKey, callback, options, onError) {
762
- const parentId = this._taskStorage.getStore()?.taskId;
763
- if (parentId) {
764
- this._logger.debug("Using parent task", {
765
- parentId,
766
- cacheKey,
767
- options,
768
- });
769
- }
770
- //don't auto-yield if it's a no-op and a subtask (e.g. a log inside a task)
771
- const isSubtaskNoop = options?.noop === true && parentId !== undefined;
772
- if (!isSubtaskNoop) {
773
- this.#detectAutoYield("start_task", 500);
774
- }
775
- const idempotencyKey = await generateIdempotencyKey([this._id, parentId ?? "", cacheKey].flat());
776
- if (this._visitedCacheKeys.has(idempotencyKey)) {
777
- if (typeof cacheKey === "string") {
778
- throw new Error(`Task with cacheKey "${cacheKey}" has already been executed in this run. Each task must have a unique cacheKey.`);
779
- }
780
- else {
781
- throw new Error(`Task with cacheKey "${cacheKey.join("-")}" has already been executed in this run. Each task must have a unique cacheKey.`);
782
- }
783
- }
784
- this._visitedCacheKeys.add(idempotencyKey);
785
- const cachedTask = this._cachedTasks.get(idempotencyKey);
786
- if (cachedTask && cachedTask.status === "COMPLETED") {
787
- this._logger.debug("Using completed cached task", {
788
- idempotencyKey,
789
- });
790
- this._stats.cachedTaskHits++;
791
- return options?.parseOutput
792
- ? options.parseOutput(cachedTask.output)
793
- : cachedTask.output;
794
- }
795
- if (options?.noop && this._noopTasksBloomFilter) {
796
- if (this._noopTasksBloomFilter.test(idempotencyKey)) {
797
- this._logger.debug("task idempotency key exists in noopTasksBloomFilter", {
798
- idempotencyKey,
799
- });
800
- this._stats.noopCachedTaskHits++;
801
- return {};
802
- }
803
- }
804
- const runOptions = { ...(options ?? {}), parseOutput: undefined };
805
- const response = await this.#doRunTask({
806
- idempotencyKey,
807
- displayKey: typeof cacheKey === "string" ? cacheKey : undefined,
808
- noop: false,
809
- ...(runOptions ?? {}),
810
- parentId,
811
- });
812
- if (!response) {
813
- this.#forceYield("failed_task_run");
814
- throw new Error("Failed to run task"); // this shouldn't actually happen, because forceYield will throw
815
- }
816
- const task = response.version === API_VERSIONS.LAZY_LOADED_CACHED_TASKS
817
- ? response.body.task
818
- : response.body;
819
- if (task.forceYield) {
820
- this._logger.debug("Forcing yield after run task", {
821
- idempotencyKey,
822
- });
823
- this.#forceYield("after_run_task");
824
- }
825
- if (response.version === API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
826
- this._cachedTasksCursor = response.body.cachedTasks?.cursor;
827
- for (const cachedTask of response.body.cachedTasks?.tasks ?? []) {
828
- if (!this._cachedTasks.has(cachedTask.idempotencyKey)) {
829
- this._cachedTasks.set(cachedTask.idempotencyKey, cachedTask);
830
- this._logger.debug("Injecting lazy loaded task into task cache", {
831
- idempotencyKey: cachedTask.idempotencyKey,
832
- });
833
- this._stats.lazyLoadedCachedTasks++;
834
- }
835
- }
836
- }
837
- if (task.status === "CANCELED") {
838
- this._logger.debug("Task canceled", {
839
- idempotencyKey,
840
- task,
841
- });
842
- throw new CanceledWithTaskError(task);
843
- }
844
- if (task.status === "COMPLETED") {
845
- if (task.noop) {
846
- this._logger.debug("Noop Task completed", {
847
- idempotencyKey,
848
- });
849
- this._noopTasksBloomFilter?.add(task.idempotencyKey);
850
- }
851
- else {
852
- this._logger.debug("Cache miss", {
853
- idempotencyKey,
854
- });
855
- this._stats.cachedTaskMisses++;
856
- this.#addToCachedTasks(task);
857
- }
858
- return options?.parseOutput ? options.parseOutput(task.output) : task.output;
859
- }
860
- if (task.status === "ERRORED") {
861
- this._logger.debug("Task errored", {
862
- idempotencyKey,
863
- task,
864
- });
865
- throw new ErrorWithTask(task, task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
866
- }
867
- this.#detectAutoYield("before_execute_task", 1500);
868
- const executeTask = async () => {
869
- try {
870
- const result = await callback(task, this);
871
- if (task.status === "WAITING" && task.callbackUrl) {
872
- this._logger.debug("Waiting for remote callback", {
873
- idempotencyKey,
874
- task,
875
- });
876
- return {};
877
- }
878
- const output = this._outputSerializer.serialize(result);
879
- this._logger.debug("Completing using output", {
880
- idempotencyKey,
881
- task,
882
- });
883
- this.#detectAutoYield("before_complete_task", 500, task, output);
884
- const completedTask = await this.#doCompleteTask(task.id, {
885
- output,
886
- properties: task.outputProperties ?? undefined,
887
- });
888
- if (!completedTask) {
889
- this.#forceYield("before_complete_task", task, output);
890
- throw new Error("Failed to complete task"); // this shouldn't actually happen, because forceYield will throw
891
- }
892
- if (completedTask.forceYield) {
893
- this._logger.debug("Forcing yield after task completed", {
894
- idempotencyKey,
895
- });
896
- this.#forceYield("after_complete_task");
897
- }
898
- this._stats.executedTasks++;
899
- if (completedTask.status === "CANCELED") {
900
- throw new CanceledWithTaskError(completedTask);
901
- }
902
- this.#detectAutoYield("after_complete_task", 500);
903
- const deserializedOutput = this._outputSerializer.deserialize(output);
904
- return options?.parseOutput ? options.parseOutput(deserializedOutput) : deserializedOutput;
905
- }
906
- catch (error) {
907
- if (isTriggerError(error)) {
908
- throw error;
909
- }
910
- let skipRetrying = false;
911
- if (onError) {
912
- try {
913
- const onErrorResult = onError(error, task, this);
914
- if (onErrorResult) {
915
- if (onErrorResult instanceof Error) {
916
- error = onErrorResult;
917
- }
918
- else {
919
- skipRetrying = !!onErrorResult.skipRetrying;
920
- if (onErrorResult.retryAt && !skipRetrying) {
921
- const parsedError = ErrorWithStackSchema.safeParse(onErrorResult.error);
922
- throw new RetryWithTaskError(parsedError.success ? parsedError.data : { message: "Unknown error" }, task, onErrorResult.retryAt);
923
- }
924
- }
925
- }
926
- }
927
- catch (innerError) {
928
- if (isTriggerError(innerError)) {
929
- throw innerError;
930
- }
931
- error = innerError;
932
- }
933
- }
934
- if (error instanceof ErrorWithTask) {
935
- // This means a subtask errored, so we need to update the parent task and not retry it
936
- await this._apiClient.failTask(this._id, task.id, {
937
- error: error.cause.output,
938
- });
939
- throw error;
940
- }
941
- const parsedError = ErrorWithStackSchema.safeParse(error);
942
- if (options?.retry && !skipRetrying) {
943
- const retryAt = calculateRetryAt(options.retry, task.attempts - 1);
944
- if (retryAt) {
945
- throw new RetryWithTaskError(parsedError.success ? parsedError.data : { message: "Unknown error" }, task, retryAt);
946
- }
947
- }
948
- if (parsedError.success) {
949
- await this._apiClient.failTask(this._id, task.id, {
950
- error: parsedError.data,
951
- });
952
- }
953
- else {
954
- const message = typeof error === "string" ? error : JSON.stringify(error);
955
- await this._apiClient.failTask(this._id, task.id, {
956
- error: { name: "Unknown error", message },
957
- });
958
- }
959
- throw error;
960
- }
961
- };
962
- if (task.status === "WAITING") {
963
- this._logger.debug("Task waiting", {
964
- idempotencyKey,
965
- task,
966
- });
967
- if (task.callbackUrl) {
968
- await this._taskStorage.run({ taskId: task.id }, executeTask);
969
- }
970
- throw new ResumeWithTaskError(task);
971
- }
972
- if (task.status === "RUNNING" && typeof task.operation === "string") {
973
- this._logger.debug("Task running operation", {
974
- idempotencyKey,
975
- task,
976
- });
977
- throw new ResumeWithTaskError(task);
978
- }
979
- return this._taskStorage.run({ taskId: task.id }, executeTask);
980
- }
981
- /**
982
- * `io.yield()` allows you to yield execution of the current run and resume it in a new function execution. Similar to `io.wait()` but does not create a task and resumes execution immediately.
983
- */
984
- yield(cacheKey) {
985
- if (!supportsFeature("yieldExecution", this._serverVersion)) {
986
- console.warn("[trigger.dev] io.yield() is not support by the version of the Trigger.dev server you are using, you will need to upgrade your self-hosted Trigger.dev instance.");
987
- return;
988
- }
989
- if (this._yieldedExecutions.includes(cacheKey)) {
990
- return;
991
- }
992
- throw new YieldExecutionError(cacheKey);
993
- }
994
- /**
995
- * `io.brb()` is an alias of `io.yield()`
996
- */
997
- brb = this.yield.bind(this);
998
- /** `io.try()` allows you to run Tasks and catch any errors that are thrown, it's similar to a normal `try/catch` block but works with [io.runTask()](https://trigger.dev/docs/sdk/io/runtask).
999
- * 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.
1000
- * @param tryCallback The code you wish to run
1001
- * @param catchCallback Thhis will be called if the Task fails. The callback receives the error
1002
- * @returns A Promise that resolves with the returned value or the error
1003
- */
1004
- async try(tryCallback, catchCallback) {
1005
- try {
1006
- return await tryCallback();
1007
- }
1008
- catch (error) {
1009
- if (isTriggerError(error)) {
1010
- throw error;
1011
- }
1012
- return await catchCallback(error);
1013
- }
1014
- }
1015
- get store() {
1016
- return {
1017
- env: this._envStore,
1018
- job: this._jobStore,
1019
- run: this._runStore,
1020
- };
1021
- }
1022
- #addToCachedTasks(task) {
1023
- this._cachedTasks.set(task.idempotencyKey, task);
1024
- }
1025
- async #doRunTask(task) {
1026
- try {
1027
- return await this._apiClient.runTask(this._id, task, {
1028
- cachedTasksCursor: this._cachedTasksCursor,
1029
- });
1030
- }
1031
- catch (error) {
1032
- if (error instanceof AutoYieldRateLimitError) {
1033
- this._logger.debug("AutoYieldRateLimitError", {
1034
- error,
1035
- });
1036
- throw error;
1037
- }
1038
- return;
1039
- }
1040
- }
1041
- async #doCompleteTask(id, task) {
1042
- try {
1043
- return await this._apiClient.completeTask(this._id, id, task);
1044
- }
1045
- catch (error) {
1046
- return;
1047
- }
1048
- }
1049
- #detectAutoYield(location, threshold = 1500, task, output) {
1050
- const timeRemaining = this.#getRemainingTimeInMillis();
1051
- if (timeRemaining && timeRemaining < threshold) {
1052
- if (task) {
1053
- throw new AutoYieldWithCompletedTaskExecutionError(task.id, task.outputProperties ?? [], {
1054
- location,
1055
- timeRemaining,
1056
- timeElapsed: this.#getTimeElapsed(),
1057
- }, output);
1058
- }
1059
- else {
1060
- throw new AutoYieldExecutionError(location, timeRemaining, this.#getTimeElapsed());
1061
- }
1062
- }
1063
- }
1064
- #forceYield(location, task, output) {
1065
- const timeRemaining = this.#getRemainingTimeInMillis();
1066
- if (timeRemaining) {
1067
- if (task) {
1068
- throw new AutoYieldWithCompletedTaskExecutionError(task.id, task.outputProperties ?? [], {
1069
- location,
1070
- timeRemaining,
1071
- timeElapsed: this.#getTimeElapsed(),
1072
- }, output);
1073
- }
1074
- else {
1075
- throw new AutoYieldExecutionError(location, timeRemaining, this.#getTimeElapsed());
1076
- }
1077
- }
1078
- }
1079
- #getTimeElapsed() {
1080
- return performance.now() - this._timeOrigin;
1081
- }
1082
- #getRemainingTimeInMillis() {
1083
- if (this._executionTimeout) {
1084
- return this._executionTimeout - (performance.now() - this._timeOrigin);
1085
- }
1086
- return undefined;
1087
- }
1088
- }
1089
- // Generate a stable idempotency key for the key material, using a stable json stringification
1090
- async function generateIdempotencyKey(keyMaterial) {
1091
- const keys = keyMaterial.map((key) => {
1092
- if (typeof key === "string") {
1093
- return key;
1094
- }
1095
- return stableStringify(key);
1096
- });
1097
- const key = keys.join(":");
1098
- const hash = await webcrypto.subtle.digest("SHA-256", Buffer.from(key));
1099
- return Buffer.from(hash).toString("hex");
1100
- }
1101
- function stableStringify(obj) {
1102
- function sortKeys(obj) {
1103
- if (typeof obj !== "object" || obj === null) {
1104
- return obj;
1105
- }
1106
- if (Array.isArray(obj)) {
1107
- return obj.map(sortKeys);
1108
- }
1109
- const sortedKeys = Object.keys(obj).sort();
1110
- const sortedObj = {};
1111
- for (const key of sortedKeys) {
1112
- sortedObj[key] = sortKeys(obj[key]);
1113
- }
1114
- return sortedObj;
1115
- }
1116
- const sortedObj = sortKeys(obj);
1117
- return JSON.stringify(sortedObj);
1118
- }
1119
- export class IOLogger {
1120
- callback;
1121
- constructor(callback) {
1122
- this.callback = callback;
1123
- }
1124
- /** Log: essential messages */
1125
- log(message, properties) {
1126
- return this.callback("LOG", message, properties);
1127
- }
1128
- /** For debugging: the least important log level */
1129
- debug(message, properties) {
1130
- return this.callback("DEBUG", message, properties);
1131
- }
1132
- /** Info: the second least important log level */
1133
- info(message, properties) {
1134
- return this.callback("INFO", message, properties);
1135
- }
1136
- /** Warnings: the third most important log level */
1137
- warn(message, properties) {
1138
- return this.callback("WARN", message, properties);
1139
- }
1140
- /** Error: The second most important log level */
1141
- error(message, properties) {
1142
- return this.callback("ERROR", message, properties);
1143
- }
1144
- }
1145
- // Space out the execution of the callback by a delay of index * delay
1146
- async function spaceOut(callback, index, delay) {
1147
- await new Promise((resolve) => setTimeout(resolve, index * delay));
1148
- return await callback();
1149
- }
1150
- function sendEventOptionsProperties(options) {
1151
- return [
1152
- ...(options?.accountId ? [{ label: "Account ID", text: options.accountId }] : []),
1153
- ...(options?.deliverAfter
1154
- ? [{ label: "Deliver After", text: `${options.deliverAfter}s` }]
1155
- : []),
1156
- ...(options?.deliverAt ? [{ label: "Deliver At", text: options.deliverAt.toISOString() }] : []),
1157
- ];
1158
- }
1159
- //# sourceMappingURL=io.js.map