@trigger.dev/sdk 3.3.17 → 4.0.0-v4-beta.1

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