@trigger.dev/sdk 3.0.0-beta.7 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/dist/commonjs/apiClient.d.ts +737 -0
  2. package/dist/commonjs/apiClient.js +692 -0
  3. package/dist/commonjs/apiClient.js.map +1 -0
  4. package/dist/commonjs/concurrencyLimit.d.ts +10 -0
  5. package/dist/commonjs/concurrencyLimit.js +17 -0
  6. package/dist/commonjs/concurrencyLimit.js.map +1 -0
  7. package/dist/commonjs/errors.d.ts +66 -0
  8. package/dist/commonjs/errors.js +109 -0
  9. package/dist/commonjs/errors.js.map +1 -0
  10. package/dist/commonjs/httpEndpoint.d.ts +87 -0
  11. package/dist/commonjs/httpEndpoint.js +130 -0
  12. package/dist/commonjs/httpEndpoint.js.map +1 -0
  13. package/dist/commonjs/index.d.ts +23 -0
  14. package/dist/commonjs/index.js +55 -0
  15. package/dist/commonjs/index.js.map +1 -0
  16. package/dist/commonjs/integrations.d.ts +11 -0
  17. package/dist/commonjs/integrations.js +3 -0
  18. package/dist/commonjs/integrations.js.map +1 -0
  19. package/dist/commonjs/io.d.ts +453 -0
  20. package/dist/commonjs/io.js +1165 -0
  21. package/dist/commonjs/io.js.map +1 -0
  22. package/dist/commonjs/ioWithIntegrations.d.ts +4 -0
  23. package/dist/commonjs/ioWithIntegrations.js +32 -0
  24. package/dist/commonjs/ioWithIntegrations.js.map +1 -0
  25. package/dist/commonjs/job.d.ts +96 -0
  26. package/dist/commonjs/job.js +210 -0
  27. package/dist/commonjs/job.js.map +1 -0
  28. package/dist/commonjs/package.json +3 -0
  29. package/dist/commonjs/retry.d.ts +20 -0
  30. package/dist/commonjs/retry.js +22 -0
  31. package/dist/commonjs/retry.js.map +1 -0
  32. package/dist/commonjs/runLocalStorage.d.ts +8 -0
  33. package/dist/commonjs/runLocalStorage.js +6 -0
  34. package/dist/commonjs/runLocalStorage.js.map +1 -0
  35. package/dist/commonjs/security.d.ts +18 -0
  36. package/dist/commonjs/security.js +41 -0
  37. package/dist/commonjs/security.js.map +1 -0
  38. package/dist/commonjs/status.d.ts +19 -0
  39. package/dist/commonjs/status.js +38 -0
  40. package/dist/commonjs/status.js.map +1 -0
  41. package/dist/commonjs/store/keyValueStore.d.ts +17 -0
  42. package/dist/commonjs/store/keyValueStore.js +138 -0
  43. package/dist/commonjs/store/keyValueStore.js.map +1 -0
  44. package/dist/commonjs/store/keyValueStoreClient.d.ts +19 -0
  45. package/dist/commonjs/store/keyValueStoreClient.js +65 -0
  46. package/dist/commonjs/store/keyValueStoreClient.js.map +1 -0
  47. package/dist/commonjs/triggerClient.d.ts +300 -0
  48. package/dist/commonjs/triggerClient.js +1366 -0
  49. package/dist/commonjs/triggerClient.js.map +1 -0
  50. package/dist/commonjs/triggers/dynamic.d.ts +56 -0
  51. package/dist/commonjs/triggers/dynamic.js +97 -0
  52. package/dist/commonjs/triggers/dynamic.js.map +1 -0
  53. package/dist/commonjs/triggers/eventTrigger.d.ts +58 -0
  54. package/dist/commonjs/triggers/eventTrigger.js +69 -0
  55. package/dist/commonjs/triggers/eventTrigger.js.map +1 -0
  56. package/dist/commonjs/triggers/externalSource.d.ts +148 -0
  57. package/dist/commonjs/triggers/externalSource.js +106 -0
  58. package/dist/commonjs/triggers/externalSource.js.map +1 -0
  59. package/dist/commonjs/triggers/invokeTrigger.d.ts +39 -0
  60. package/dist/commonjs/triggers/invokeTrigger.js +58 -0
  61. package/dist/commonjs/triggers/invokeTrigger.js.map +1 -0
  62. package/dist/commonjs/triggers/notifications.d.ts +111 -0
  63. package/dist/commonjs/triggers/notifications.js +101 -0
  64. package/dist/commonjs/triggers/notifications.js.map +1 -0
  65. package/dist/commonjs/triggers/scheduled.d.ts +145 -0
  66. package/dist/commonjs/triggers/scheduled.js +208 -0
  67. package/dist/commonjs/triggers/scheduled.js.map +1 -0
  68. package/dist/commonjs/triggers/webhook.d.ts +143 -0
  69. package/dist/commonjs/triggers/webhook.js +133 -0
  70. package/dist/commonjs/triggers/webhook.js.map +1 -0
  71. package/dist/commonjs/typed-emitter.d.ts +37 -0
  72. package/dist/commonjs/typed-emitter.js +3 -0
  73. package/dist/commonjs/typed-emitter.js.map +1 -0
  74. package/dist/commonjs/types.d.ts +204 -0
  75. package/dist/commonjs/types.js +23 -0
  76. package/dist/commonjs/types.js.map +1 -0
  77. package/dist/commonjs/utils/formatSchemaErrors.d.ts +3 -0
  78. package/dist/commonjs/utils/formatSchemaErrors.js +10 -0
  79. package/dist/commonjs/utils/formatSchemaErrors.js.map +1 -0
  80. package/dist/commonjs/utils/typedAsyncLocalStorage.d.ts +6 -0
  81. package/dist/commonjs/utils/typedAsyncLocalStorage.js +18 -0
  82. package/dist/commonjs/utils/typedAsyncLocalStorage.js.map +1 -0
  83. package/dist/commonjs/utils.d.ts +1 -0
  84. package/dist/commonjs/utils.js +11 -0
  85. package/dist/commonjs/utils.js.map +1 -0
  86. package/dist/commonjs/v3/cache.d.ts +28 -0
  87. package/dist/commonjs/v3/cache.js +63 -0
  88. package/dist/commonjs/v3/cache.js.map +1 -0
  89. package/dist/commonjs/v3/config.d.ts +4 -0
  90. package/dist/commonjs/v3/config.js +7 -0
  91. package/dist/commonjs/v3/config.js.map +1 -0
  92. package/dist/commonjs/v3/envvars.d.ts +14 -0
  93. package/dist/commonjs/v3/envvars.js +246 -0
  94. package/dist/commonjs/v3/envvars.js.map +1 -0
  95. package/dist/commonjs/v3/idempotencyKeys.d.ts +49 -0
  96. package/dist/commonjs/v3/idempotencyKeys.js +76 -0
  97. package/dist/commonjs/v3/idempotencyKeys.js.map +1 -0
  98. package/dist/commonjs/v3/index.d.ts +36 -0
  99. package/dist/commonjs/v3/index.js +79 -0
  100. package/dist/commonjs/v3/index.js.map +1 -0
  101. package/dist/commonjs/v3/retry.d.ts +15 -0
  102. package/dist/commonjs/v3/retry.js +411 -0
  103. package/dist/commonjs/v3/retry.js.map +1 -0
  104. package/dist/commonjs/v3/runs.d.ts +345 -0
  105. package/dist/commonjs/v3/runs.js +195 -0
  106. package/dist/commonjs/v3/runs.js.map +1 -0
  107. package/dist/commonjs/v3/schedules/api.d.ts +1 -0
  108. package/dist/commonjs/v3/schedules/api.js +3 -0
  109. package/dist/commonjs/v3/schedules/api.js.map +1 -0
  110. package/dist/commonjs/v3/schedules/index.d.ts +87 -0
  111. package/dist/commonjs/v3/schedules/index.js +250 -0
  112. package/dist/commonjs/v3/schedules/index.js.map +1 -0
  113. package/dist/commonjs/v3/shared.d.ts +443 -0
  114. package/dist/commonjs/v3/shared.js +547 -0
  115. package/dist/commonjs/v3/shared.js.map +1 -0
  116. package/dist/commonjs/v3/tags.d.ts +6 -0
  117. package/dist/commonjs/v3/tags.js +50 -0
  118. package/dist/commonjs/v3/tags.js.map +1 -0
  119. package/dist/commonjs/v3/tasks.d.ts +31 -0
  120. package/dist/commonjs/v3/tasks.js +35 -0
  121. package/dist/commonjs/v3/tasks.js.map +1 -0
  122. package/dist/commonjs/v3/tracer.d.ts +2 -0
  123. package/dist/commonjs/v3/tracer.js +7 -0
  124. package/dist/commonjs/v3/tracer.js.map +1 -0
  125. package/dist/commonjs/v3/usage.d.ts +77 -0
  126. package/dist/commonjs/v3/usage.js +115 -0
  127. package/dist/commonjs/v3/usage.js.map +1 -0
  128. package/dist/commonjs/v3/wait.d.ts +22 -0
  129. package/dist/commonjs/v3/wait.js +99 -0
  130. package/dist/commonjs/v3/wait.js.map +1 -0
  131. package/dist/commonjs/version.d.ts +1 -0
  132. package/dist/commonjs/version.js +5 -0
  133. package/dist/commonjs/version.js.map +1 -0
  134. package/dist/esm/apiClient.d.ts +737 -0
  135. package/dist/esm/apiClient.js +687 -0
  136. package/dist/esm/apiClient.js.map +1 -0
  137. package/dist/esm/concurrencyLimit.d.ts +10 -0
  138. package/dist/esm/concurrencyLimit.js +13 -0
  139. package/dist/esm/concurrencyLimit.js.map +1 -0
  140. package/dist/esm/errors.d.ts +66 -0
  141. package/dist/esm/errors.js +95 -0
  142. package/dist/esm/errors.js.map +1 -0
  143. package/dist/esm/httpEndpoint.d.ts +87 -0
  144. package/dist/esm/httpEndpoint.js +125 -0
  145. package/dist/esm/httpEndpoint.js.map +1 -0
  146. package/dist/esm/index.d.ts +23 -0
  147. package/dist/esm/index.js +35 -0
  148. package/dist/esm/index.js.map +1 -0
  149. package/dist/esm/integrations.d.ts +11 -0
  150. package/dist/esm/integrations.js +2 -0
  151. package/dist/esm/integrations.js.map +1 -0
  152. package/dist/esm/io.d.ts +453 -0
  153. package/dist/esm/io.js +1159 -0
  154. package/dist/esm/io.js.map +1 -0
  155. package/dist/esm/ioWithIntegrations.d.ts +4 -0
  156. package/dist/esm/ioWithIntegrations.js +29 -0
  157. package/dist/esm/ioWithIntegrations.js.map +1 -0
  158. package/dist/esm/job.d.ts +96 -0
  159. package/dist/esm/job.js +206 -0
  160. package/dist/esm/job.js.map +1 -0
  161. package/dist/esm/package.json +3 -0
  162. package/dist/esm/retry.d.ts +20 -0
  163. package/dist/esm/retry.js +19 -0
  164. package/dist/esm/retry.js.map +1 -0
  165. package/dist/esm/runLocalStorage.d.ts +8 -0
  166. package/dist/esm/runLocalStorage.js +3 -0
  167. package/dist/esm/runLocalStorage.js.map +1 -0
  168. package/dist/esm/security.d.ts +18 -0
  169. package/dist/esm/security.js +34 -0
  170. package/dist/esm/security.js.map +1 -0
  171. package/dist/esm/status.d.ts +19 -0
  172. package/dist/esm/status.js +34 -0
  173. package/dist/esm/status.js.map +1 -0
  174. package/dist/esm/store/keyValueStore.d.ts +17 -0
  175. package/dist/esm/store/keyValueStore.js +134 -0
  176. package/dist/esm/store/keyValueStore.js.map +1 -0
  177. package/dist/esm/store/keyValueStoreClient.d.ts +19 -0
  178. package/dist/esm/store/keyValueStoreClient.js +61 -0
  179. package/dist/esm/store/keyValueStoreClient.js.map +1 -0
  180. package/dist/esm/triggerClient.d.ts +300 -0
  181. package/dist/esm/triggerClient.js +1359 -0
  182. package/dist/esm/triggerClient.js.map +1 -0
  183. package/dist/esm/triggers/dynamic.d.ts +56 -0
  184. package/dist/esm/triggers/dynamic.js +93 -0
  185. package/dist/esm/triggers/dynamic.js.map +1 -0
  186. package/dist/esm/triggers/eventTrigger.d.ts +58 -0
  187. package/dist/esm/triggers/eventTrigger.js +64 -0
  188. package/dist/esm/triggers/eventTrigger.js.map +1 -0
  189. package/dist/esm/triggers/externalSource.d.ts +148 -0
  190. package/dist/esm/triggers/externalSource.js +100 -0
  191. package/dist/esm/triggers/externalSource.js.map +1 -0
  192. package/dist/esm/triggers/invokeTrigger.d.ts +39 -0
  193. package/dist/esm/triggers/invokeTrigger.js +53 -0
  194. package/dist/esm/triggers/invokeTrigger.js.map +1 -0
  195. package/dist/esm/triggers/notifications.d.ts +111 -0
  196. package/dist/esm/triggers/notifications.js +94 -0
  197. package/dist/esm/triggers/notifications.js.map +1 -0
  198. package/dist/esm/triggers/scheduled.d.ts +145 -0
  199. package/dist/esm/triggers/scheduled.js +197 -0
  200. package/dist/esm/triggers/scheduled.js.map +1 -0
  201. package/dist/esm/triggers/webhook.d.ts +143 -0
  202. package/dist/esm/triggers/webhook.js +128 -0
  203. package/dist/esm/triggers/webhook.js.map +1 -0
  204. package/dist/esm/typed-emitter.d.ts +37 -0
  205. package/dist/esm/typed-emitter.js +2 -0
  206. package/dist/esm/typed-emitter.js.map +1 -0
  207. package/dist/esm/types.d.ts +204 -0
  208. package/dist/esm/types.js +19 -0
  209. package/dist/esm/types.js.map +1 -0
  210. package/dist/esm/utils/formatSchemaErrors.d.ts +3 -0
  211. package/dist/esm/utils/formatSchemaErrors.js +7 -0
  212. package/dist/esm/utils/formatSchemaErrors.js.map +1 -0
  213. package/dist/esm/utils/typedAsyncLocalStorage.d.ts +6 -0
  214. package/dist/esm/utils/typedAsyncLocalStorage.js +14 -0
  215. package/dist/esm/utils/typedAsyncLocalStorage.js.map +1 -0
  216. package/dist/esm/utils.d.ts +1 -0
  217. package/dist/esm/utils.js +8 -0
  218. package/dist/esm/utils.js.map +1 -0
  219. package/dist/esm/v3/cache.d.ts +28 -0
  220. package/dist/esm/v3/cache.js +58 -0
  221. package/dist/esm/v3/cache.js.map +1 -0
  222. package/dist/esm/v3/config.d.ts +4 -0
  223. package/dist/esm/v3/config.js +4 -0
  224. package/dist/esm/v3/config.js.map +1 -0
  225. package/dist/esm/v3/envvars.d.ts +14 -0
  226. package/dist/esm/v3/envvars.js +238 -0
  227. package/dist/esm/v3/envvars.js.map +1 -0
  228. package/dist/esm/v3/idempotencyKeys.d.ts +49 -0
  229. package/dist/esm/v3/idempotencyKeys.js +72 -0
  230. package/dist/esm/v3/idempotencyKeys.js.map +1 -0
  231. package/dist/esm/v3/index.d.ts +36 -0
  232. package/dist/esm/v3/index.js +35 -0
  233. package/dist/esm/v3/index.js.map +1 -0
  234. package/dist/esm/v3/retry.d.ts +15 -0
  235. package/dist/esm/v3/retry.js +408 -0
  236. package/dist/esm/v3/retry.js.map +1 -0
  237. package/dist/esm/v3/runs.d.ts +345 -0
  238. package/dist/esm/v3/runs.js +192 -0
  239. package/dist/esm/v3/runs.js.map +1 -0
  240. package/dist/esm/v3/schedules/api.d.ts +1 -0
  241. package/dist/esm/v3/schedules/api.js +2 -0
  242. package/dist/esm/v3/schedules/api.js.map +1 -0
  243. package/dist/esm/v3/schedules/index.d.ts +87 -0
  244. package/dist/esm/v3/schedules/index.js +239 -0
  245. package/dist/esm/v3/schedules/index.js.map +1 -0
  246. package/dist/esm/v3/shared.d.ts +443 -0
  247. package/dist/esm/v3/shared.js +534 -0
  248. package/dist/esm/v3/shared.js.map +1 -0
  249. package/dist/esm/v3/tags.d.ts +6 -0
  250. package/dist/esm/v3/tags.js +47 -0
  251. package/dist/esm/v3/tags.js.map +1 -0
  252. package/dist/esm/v3/tasks.d.ts +31 -0
  253. package/dist/esm/v3/tasks.js +31 -0
  254. package/dist/esm/v3/tasks.js.map +1 -0
  255. package/dist/esm/v3/tracer.d.ts +2 -0
  256. package/dist/esm/v3/tracer.js +4 -0
  257. package/dist/esm/v3/tracer.js.map +1 -0
  258. package/dist/esm/v3/usage.d.ts +77 -0
  259. package/dist/esm/v3/usage.js +112 -0
  260. package/dist/esm/v3/usage.js.map +1 -0
  261. package/dist/esm/v3/wait.d.ts +22 -0
  262. package/dist/esm/v3/wait.js +96 -0
  263. package/dist/esm/v3/wait.js.map +1 -0
  264. package/dist/esm/version.d.ts +1 -0
  265. package/dist/esm/version.js +2 -0
  266. package/dist/esm/version.js.map +1 -0
  267. package/package.json +62 -47
  268. package/dist/index.d.mts +0 -2704
  269. package/dist/index.d.ts +0 -2704
  270. package/dist/index.js +0 -4886
  271. package/dist/index.js.map +0 -1
  272. package/dist/index.mjs +0 -4847
  273. package/dist/index.mjs.map +0 -1
  274. package/dist/v3/index.d.mts +0 -261
  275. package/dist/v3/index.d.ts +0 -261
  276. package/dist/v3/index.js +0 -921
  277. package/dist/v3/index.js.map +0 -1
  278. package/dist/v3/index.mjs +0 -911
  279. package/dist/v3/index.mjs.map +0 -1
package/dist/index.js DELETED
@@ -1,4886 +0,0 @@
1
- 'use strict';
2
-
3
- var node_async_hooks = require('node:async_hooks');
4
- var core = require('@trigger.dev/core');
5
- var coreBackend = require('@trigger.dev/core-backend');
6
- var EventEmitter = require('node:events');
7
- var node_process = require('node:process');
8
- var zod = require('zod');
9
- var crypto = require('node:crypto');
10
- var node_buffer = require('node:buffer');
11
- var cronstrue = require('cronstrue');
12
-
13
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
-
15
- var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
16
- var crypto__default = /*#__PURE__*/_interopDefault(crypto);
17
- var cronstrue__default = /*#__PURE__*/_interopDefault(cronstrue);
18
-
19
- var __defProp = Object.defineProperty;
20
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
21
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
22
- var __publicField = (obj, key, value) => {
23
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
24
- return value;
25
- };
26
- var __accessCheck = (obj, member, msg) => {
27
- if (!member.has(obj))
28
- throw TypeError("Cannot " + msg);
29
- };
30
- var __privateGet = (obj, member, getter) => {
31
- __accessCheck(obj, member, "read from private field");
32
- return getter ? getter.call(obj) : member.get(obj);
33
- };
34
- var __privateAdd = (obj, member, value) => {
35
- if (member.has(obj))
36
- throw TypeError("Cannot add the same private member more than once");
37
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
38
- };
39
- var __privateSet = (obj, member, value, setter) => {
40
- __accessCheck(obj, member, "write to private field");
41
- setter ? setter.call(obj, value) : member.set(obj, value);
42
- return value;
43
- };
44
- var __privateMethod = (obj, member, method) => {
45
- __accessCheck(obj, member, "access private method");
46
- return method;
47
- };
48
- var _TypedAsyncLocalStorage = class _TypedAsyncLocalStorage {
49
- constructor() {
50
- this.storage = new node_async_hooks.AsyncLocalStorage();
51
- }
52
- runWith(context, fn) {
53
- return this.storage.run(context, fn);
54
- }
55
- getStore() {
56
- return this.storage.getStore();
57
- }
58
- };
59
- __name(_TypedAsyncLocalStorage, "TypedAsyncLocalStorage");
60
- var TypedAsyncLocalStorage = _TypedAsyncLocalStorage;
61
-
62
- // src/runLocalStorage.ts
63
- var runLocalStorage = new TypedAsyncLocalStorage();
64
-
65
- // src/utils.ts
66
- function slugifyId(input) {
67
- const replaceSpacesWithDash = input.toLowerCase().replace(/\s+/g, "-");
68
- const removeNonUrlSafeChars = replaceSpacesWithDash.replace(/[^a-zA-Z0-9-._~]/g, "");
69
- return removeNonUrlSafeChars;
70
- }
71
- __name(slugifyId, "slugifyId");
72
-
73
- // src/job.ts
74
- var _validate, validate_fn;
75
- var _Job = class _Job {
76
- constructor(options) {
77
- // Make sure the id is valid (must only contain alphanumeric characters and dashes)
78
- // Make sure the version is valid (must be a valid semver version)
79
- __privateAdd(this, _validate);
80
- this.options = options;
81
- __privateMethod(this, _validate, validate_fn).call(this);
82
- }
83
- /**
84
- * Attaches the job to a client. This is called automatically when you define a job using `client.defineJob()`.
85
- */
86
- attachToClient(client) {
87
- client.attach(this);
88
- return this;
89
- }
90
- get id() {
91
- return slugifyId(this.options.id);
92
- }
93
- get enabled() {
94
- return typeof this.options.enabled === "boolean" ? this.options.enabled : true;
95
- }
96
- get name() {
97
- return this.options.name;
98
- }
99
- get trigger() {
100
- return this.options.trigger;
101
- }
102
- get version() {
103
- return this.options.version;
104
- }
105
- get logLevel() {
106
- return this.options.logLevel;
107
- }
108
- get integrations() {
109
- return Object.keys(this.options.integrations ?? {}).reduce((acc, key) => {
110
- const integration = this.options.integrations[key];
111
- acc[key] = {
112
- id: integration.id,
113
- metadata: integration.metadata,
114
- authSource: integration.authSource
115
- };
116
- return acc;
117
- }, {});
118
- }
119
- toJSON() {
120
- const internal = this.options.__internal;
121
- return {
122
- id: this.id,
123
- name: this.name,
124
- version: this.version,
125
- event: this.trigger.event,
126
- trigger: this.trigger.toJSON(),
127
- integrations: this.integrations,
128
- startPosition: "latest",
129
- enabled: this.enabled,
130
- preprocessRuns: this.trigger.preprocessRuns,
131
- internal,
132
- concurrencyLimit: typeof this.options.concurrencyLimit === "number" ? this.options.concurrencyLimit : typeof this.options.concurrencyLimit === "object" ? {
133
- id: this.options.concurrencyLimit.id,
134
- limit: this.options.concurrencyLimit.limit
135
- } : void 0
136
- };
137
- }
138
- async invoke(param1, param2 = void 0, param3 = void 0) {
139
- const triggerClient = this.client;
140
- if (!triggerClient) {
141
- throw new Error("Cannot invoke a job that is not attached to a client. Make sure you attach the job to a client before invoking it.");
142
- }
143
- const runStore = runLocalStorage.getStore();
144
- if (typeof param1 === "string") {
145
- if (!runStore) {
146
- throw new Error("Cannot invoke a job from outside of a run when passing a cacheKey. Make sure you are running the job from within a run or use the invoke method without the cacheKey.");
147
- }
148
- const options = param3 ?? {};
149
- return await runStore.io.runTask(param1, async (task) => {
150
- const result = await triggerClient.invokeJob(this.id, param2, {
151
- idempotencyKey: task.idempotencyKey,
152
- ...options
153
- });
154
- task.outputProperties = [
155
- {
156
- label: "Run",
157
- text: result.id,
158
- url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
159
- }
160
- ];
161
- return result;
162
- }, {
163
- name: `Manually Invoke '${this.name}'`,
164
- params: param2,
165
- properties: [
166
- {
167
- label: "Job",
168
- text: this.id,
169
- url: `/orgs/${runStore.ctx.organization.slug}/projects/${runStore.ctx.project.slug}/jobs/${this.id}`
170
- },
171
- {
172
- label: "Env",
173
- text: runStore.ctx.environment.slug
174
- }
175
- ]
176
- });
177
- }
178
- if (runStore) {
179
- throw new Error("Cannot invoke a job from within a run without a cacheKey.");
180
- }
181
- return await triggerClient.invokeJob(this.id, param1, param2);
182
- }
183
- async invokeAndWaitForCompletion(cacheKey, payload, timeoutInSeconds = 60 * 60, options = {}) {
184
- const triggerClient = this.client;
185
- if (!triggerClient) {
186
- throw new Error("Cannot invoke a job that is not attached to a client. Make sure you attach the job to a client before invoking it.");
187
- }
188
- const runStore = runLocalStorage.getStore();
189
- if (!runStore) {
190
- throw new Error("Cannot invoke a job from outside of a run using invokeAndWaitForCompletion. Make sure you are running the job from within a run or use the invoke method instead.");
191
- }
192
- const { io, ctx } = runStore;
193
- return await io.runTask(cacheKey, async (task) => {
194
- const parsedPayload = this.trigger.event.parseInvokePayload ? this.trigger.event.parseInvokePayload(payload) ? payload : void 0 : payload;
195
- const result = await triggerClient.invokeJob(this.id, parsedPayload, {
196
- idempotencyKey: task.idempotencyKey,
197
- callbackUrl: task.callbackUrl ?? void 0,
198
- ...options
199
- });
200
- task.outputProperties = [
201
- {
202
- label: "Run",
203
- text: result.id,
204
- url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}/runs/${result.id}/trigger`
205
- }
206
- ];
207
- return {};
208
- }, {
209
- name: `Manually Invoke '${this.name}' and wait for completion`,
210
- params: payload,
211
- properties: [
212
- {
213
- label: "Job",
214
- text: this.id,
215
- url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
216
- },
217
- {
218
- label: "Env",
219
- text: ctx.environment.slug
220
- }
221
- ],
222
- callback: {
223
- enabled: true,
224
- timeoutInSeconds
225
- }
226
- });
227
- }
228
- async batchInvokeAndWaitForCompletion(cacheKey, batch) {
229
- const runStore = runLocalStorage.getStore();
230
- if (!runStore) {
231
- throw new Error("Cannot invoke a job from outside of a run using batchInvokeAndWaitForCompletion.");
232
- }
233
- if (batch.length === 0) {
234
- return [];
235
- }
236
- if (batch.length > 25) {
237
- throw new Error(`Cannot batch invoke more than 25 items. You tried to batch invoke ${batch.length} items.`);
238
- }
239
- const { io, ctx } = runStore;
240
- const results = await io.parallel(cacheKey, batch, async (item, index) => {
241
- return await this.invokeAndWaitForCompletion(String(index), item.payload, item.timeoutInSeconds ?? 60 * 60, item.options);
242
- }, {
243
- name: `Batch Invoke '${this.name}'`,
244
- properties: [
245
- {
246
- label: "Job",
247
- text: this.id,
248
- url: `/orgs/${ctx.organization.slug}/projects/${ctx.project.slug}/jobs/${this.id}`
249
- },
250
- {
251
- label: "Env",
252
- text: ctx.environment.slug
253
- }
254
- ]
255
- });
256
- return results;
257
- }
258
- };
259
- _validate = new WeakSet();
260
- validate_fn = /* @__PURE__ */ __name(function() {
261
- if (!this.version.match(/^(\d+)\.(\d+)\.(\d+)$/)) {
262
- throw new Error(`Invalid job version: "${this.version}". Job versions must be valid semver versions.`);
263
- }
264
- }, "#validate");
265
- __name(_Job, "Job");
266
- var Job = _Job;
267
-
268
- // package.json
269
- var version = "3.0.0-beta.7";
270
-
271
- // src/errors.ts
272
- var _ResumeWithTaskError = class _ResumeWithTaskError {
273
- constructor(task) {
274
- this.task = task;
275
- }
276
- };
277
- __name(_ResumeWithTaskError, "ResumeWithTaskError");
278
- var ResumeWithTaskError = _ResumeWithTaskError;
279
- var _ResumeWithParallelTaskError = class _ResumeWithParallelTaskError {
280
- constructor(task, childErrors) {
281
- this.task = task;
282
- this.childErrors = childErrors;
283
- }
284
- };
285
- __name(_ResumeWithParallelTaskError, "ResumeWithParallelTaskError");
286
- var ResumeWithParallelTaskError = _ResumeWithParallelTaskError;
287
- var _RetryWithTaskError = class _RetryWithTaskError {
288
- constructor(cause, task, retryAt) {
289
- this.cause = cause;
290
- this.task = task;
291
- this.retryAt = retryAt;
292
- }
293
- };
294
- __name(_RetryWithTaskError, "RetryWithTaskError");
295
- var RetryWithTaskError = _RetryWithTaskError;
296
- var _CanceledWithTaskError = class _CanceledWithTaskError {
297
- constructor(task) {
298
- this.task = task;
299
- }
300
- };
301
- __name(_CanceledWithTaskError, "CanceledWithTaskError");
302
- var CanceledWithTaskError = _CanceledWithTaskError;
303
- var _YieldExecutionError = class _YieldExecutionError {
304
- constructor(key) {
305
- this.key = key;
306
- }
307
- };
308
- __name(_YieldExecutionError, "YieldExecutionError");
309
- var YieldExecutionError = _YieldExecutionError;
310
- var _AutoYieldExecutionError = class _AutoYieldExecutionError {
311
- constructor(location, timeRemaining, timeElapsed) {
312
- this.location = location;
313
- this.timeRemaining = timeRemaining;
314
- this.timeElapsed = timeElapsed;
315
- }
316
- };
317
- __name(_AutoYieldExecutionError, "AutoYieldExecutionError");
318
- var AutoYieldExecutionError = _AutoYieldExecutionError;
319
- var _AutoYieldWithCompletedTaskExecutionError = class _AutoYieldWithCompletedTaskExecutionError {
320
- constructor(id, properties, data, output) {
321
- this.id = id;
322
- this.properties = properties;
323
- this.data = data;
324
- this.output = output;
325
- }
326
- };
327
- __name(_AutoYieldWithCompletedTaskExecutionError, "AutoYieldWithCompletedTaskExecutionError");
328
- var AutoYieldWithCompletedTaskExecutionError = _AutoYieldWithCompletedTaskExecutionError;
329
- var _ParsedPayloadSchemaError = class _ParsedPayloadSchemaError {
330
- constructor(schemaErrors) {
331
- this.schemaErrors = schemaErrors;
332
- }
333
- };
334
- __name(_ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
335
- var ParsedPayloadSchemaError = _ParsedPayloadSchemaError;
336
- function isTriggerError(err) {
337
- return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError || err instanceof ResumeWithParallelTaskError;
338
- }
339
- __name(isTriggerError, "isTriggerError");
340
- var _ErrorWithTask = class _ErrorWithTask extends Error {
341
- constructor(cause, message) {
342
- super(message);
343
- this.cause = cause;
344
- }
345
- };
346
- __name(_ErrorWithTask, "ErrorWithTask");
347
- var ErrorWithTask = _ErrorWithTask;
348
- var retry = {
349
- standardBackoff: {
350
- limit: 8,
351
- factor: 1.8,
352
- minTimeoutInMs: 500,
353
- maxTimeoutInMs: 3e4,
354
- randomize: true
355
- },
356
- exponentialBackoff: {
357
- limit: 8,
358
- factor: 2,
359
- minTimeoutInMs: 1e3,
360
- maxTimeoutInMs: 3e4,
361
- randomize: true
362
- }
363
- };
364
-
365
- // src/status.ts
366
- var _TriggerStatus = class _TriggerStatus {
367
- constructor(id, io) {
368
- this.id = id;
369
- this.io = io;
370
- }
371
- async update(key, status) {
372
- const properties = [];
373
- if (status.label) {
374
- properties.push({
375
- label: "Label",
376
- text: status.label
377
- });
378
- }
379
- if (status.state) {
380
- properties.push({
381
- label: "State",
382
- text: status.state
383
- });
384
- }
385
- return await this.io.runTask(key, async (task) => {
386
- return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);
387
- }, {
388
- name: status.label ?? `Status update`,
389
- icon: "bell",
390
- params: {
391
- ...status
392
- },
393
- properties
394
- });
395
- }
396
- };
397
- __name(_TriggerStatus, "TriggerStatus");
398
- var TriggerStatus = _TriggerStatus;
399
- var EventSpecificationExampleSchema = zod.z.object({
400
- id: zod.z.string(),
401
- name: zod.z.string(),
402
- icon: zod.z.string().optional(),
403
- payload: zod.z.any()
404
- });
405
- function waitForEventSchema(schema) {
406
- return zod.z.object({
407
- id: zod.z.string(),
408
- name: zod.z.string(),
409
- source: zod.z.string(),
410
- payload: schema,
411
- timestamp: zod.z.coerce.date(),
412
- context: zod.z.any().optional(),
413
- accountId: zod.z.string().optional()
414
- });
415
- }
416
- __name(waitForEventSchema, "waitForEventSchema");
417
-
418
- // src/store/keyValueStore.ts
419
- var _namespacedKey, namespacedKey_fn, _sharedProperties, sharedProperties_fn;
420
- var _KeyValueStore = class _KeyValueStore {
421
- constructor(apiClient, type = null, namespace = "") {
422
- __privateAdd(this, _namespacedKey);
423
- __privateAdd(this, _sharedProperties);
424
- this.apiClient = apiClient;
425
- this.type = type;
426
- this.namespace = namespace;
427
- }
428
- async delete(param1, param2) {
429
- const runStore = runLocalStorage.getStore();
430
- if (!runStore) {
431
- if (typeof param1 !== "string") {
432
- throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
433
- }
434
- return await this.apiClient.store.delete(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
435
- }
436
- const { io } = runStore;
437
- if (!param2) {
438
- throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
439
- }
440
- return await io.runTask(param1, async (task) => {
441
- return await this.apiClient.store.delete(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
442
- }, {
443
- name: "Key-Value Store Delete",
444
- icon: "database-minus",
445
- params: {
446
- key: param2
447
- },
448
- properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
449
- style: {
450
- style: "minimal"
451
- }
452
- });
453
- }
454
- async get(param1, param2) {
455
- const runStore = runLocalStorage.getStore();
456
- if (!runStore) {
457
- if (typeof param1 !== "string") {
458
- throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
459
- }
460
- return await this.apiClient.store.get(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
461
- }
462
- const { io } = runStore;
463
- if (!param2) {
464
- throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
465
- }
466
- return await io.runTask(param1, async (task) => {
467
- return await this.apiClient.store.get(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
468
- }, {
469
- name: "Key-Value Store Get",
470
- icon: "database-export",
471
- params: {
472
- key: param2
473
- },
474
- properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
475
- style: {
476
- style: "minimal"
477
- }
478
- });
479
- }
480
- async has(param1, param2) {
481
- const runStore = runLocalStorage.getStore();
482
- if (!runStore) {
483
- if (typeof param1 !== "string") {
484
- throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
485
- }
486
- return await this.apiClient.store.has(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1));
487
- }
488
- const { io } = runStore;
489
- if (!param2) {
490
- throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
491
- }
492
- return await io.runTask(param1, async (task) => {
493
- return await this.apiClient.store.has(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2));
494
- }, {
495
- name: "Key-Value Store Has",
496
- icon: "database-search",
497
- params: {
498
- key: param2
499
- },
500
- properties: __privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
501
- style: {
502
- style: "minimal"
503
- }
504
- });
505
- }
506
- async set(param1, param2, param3) {
507
- const runStore = runLocalStorage.getStore();
508
- if (!runStore) {
509
- if (typeof param1 !== "string") {
510
- throw new Error("Please use the store without a cacheKey when accessing from outside a run.");
511
- }
512
- return await this.apiClient.store.set(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param1), param2);
513
- }
514
- const { io } = runStore;
515
- if (!param2 || typeof param2 !== "string") {
516
- throw new Error("Please provide a non-empty key when accessing the store from inside a run.");
517
- }
518
- const value = param3;
519
- return await io.runTask(param1, async (task) => {
520
- return await this.apiClient.store.set(__privateMethod(this, _namespacedKey, namespacedKey_fn).call(this, param2), value);
521
- }, {
522
- name: "Key-Value Store Set",
523
- icon: "database-plus",
524
- params: {
525
- key: param2,
526
- value
527
- },
528
- properties: [
529
- ...__privateMethod(this, _sharedProperties, sharedProperties_fn).call(this, param2),
530
- ...typeof value !== "object" || value === null ? [
531
- {
532
- label: "value",
533
- text: String(value) ?? "undefined"
534
- }
535
- ] : []
536
- ],
537
- style: {
538
- style: "minimal"
539
- }
540
- });
541
- }
542
- };
543
- _namespacedKey = new WeakSet();
544
- namespacedKey_fn = /* @__PURE__ */ __name(function(key) {
545
- const parts = [];
546
- if (this.type) {
547
- parts.push(this.type);
548
- }
549
- if (this.namespace) {
550
- parts.push(this.namespace);
551
- }
552
- parts.push(key);
553
- return parts.join(":");
554
- }, "#namespacedKey");
555
- _sharedProperties = new WeakSet();
556
- sharedProperties_fn = /* @__PURE__ */ __name(function(key1) {
557
- return [
558
- {
559
- label: "namespace",
560
- text: this.type ?? "env"
561
- },
562
- {
563
- label: "key",
564
- text: key1
565
- }
566
- ];
567
- }, "#sharedProperties");
568
- __name(_KeyValueStore, "KeyValueStore");
569
- var KeyValueStore = _KeyValueStore;
570
- var _JSONOutputSerializer = class _JSONOutputSerializer {
571
- serialize(value) {
572
- return JSON.stringify(value);
573
- }
574
- deserialize(value) {
575
- return value ? JSON.parse(value) : void 0;
576
- }
577
- };
578
- __name(_JSONOutputSerializer, "JSONOutputSerializer");
579
- var JSONOutputSerializer = _JSONOutputSerializer;
580
- var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
581
- var _IO = class _IO {
582
- constructor(options) {
583
- __privateAdd(this, _addToCachedTasks);
584
- __privateAdd(this, _detectAutoYield);
585
- __privateAdd(this, _forceYield);
586
- __privateAdd(this, _getTimeElapsed);
587
- __privateAdd(this, _getRemainingTimeInMillis);
588
- __publicField(this, "_outputSerializer", new JSONOutputSerializer());
589
- __publicField(this, "_visitedCacheKeys", /* @__PURE__ */ new Set());
590
- /**
591
- * `io.brb()` is an alias of `io.yield()`
592
- */
593
- __publicField(this, "brb", this.yield.bind(this));
594
- this._id = options.id;
595
- this._jobId = options.jobId;
596
- this._apiClient = options.apiClient;
597
- this._triggerClient = options.client;
598
- this._logger = options.logger ?? new coreBackend.Logger("trigger.dev", options.logLevel);
599
- this._cachedTasks = /* @__PURE__ */ new Map();
600
- this._jobLogger = options.jobLogger;
601
- this._jobLogLevel = options.jobLogLevel;
602
- this._timeOrigin = options.timeOrigin;
603
- this._executionTimeout = options.executionTimeout;
604
- this._envStore = new KeyValueStore(options.apiClient);
605
- this._jobStore = new KeyValueStore(options.apiClient, "job", options.jobId);
606
- this._runStore = new KeyValueStore(options.apiClient, "run", options.id);
607
- this._stats = {
608
- initialCachedTasks: 0,
609
- lazyLoadedCachedTasks: 0,
610
- executedTasks: 0,
611
- cachedTaskHits: 0,
612
- cachedTaskMisses: 0,
613
- noopCachedTaskHits: 0,
614
- noopCachedTaskMisses: 0
615
- };
616
- if (options.cachedTasks) {
617
- options.cachedTasks.forEach((task) => {
618
- this._cachedTasks.set(task.idempotencyKey, task);
619
- });
620
- this._stats.initialCachedTasks = options.cachedTasks.length;
621
- }
622
- this._taskStorage = new node_async_hooks.AsyncLocalStorage();
623
- this._context = options.context;
624
- this._yieldedExecutions = options.yieldedExecutions ?? [];
625
- if (options.noopTasksSet) {
626
- this._noopTasksBloomFilter = coreBackend.BloomFilter.deserialize(options.noopTasksSet, coreBackend.BloomFilter.NOOP_TASK_SET_SIZE);
627
- }
628
- this._cachedTasksCursor = options.cachedTasksCursor;
629
- this._serverVersion = options.serverVersion ?? "unversioned";
630
- }
631
- get stats() {
632
- return this._stats;
633
- }
634
- /** @internal */
635
- get runId() {
636
- return this._id;
637
- }
638
- /** @internal */
639
- get triggerClient() {
640
- return this._triggerClient;
641
- }
642
- /** Used to send log messages to the [Run log](https://trigger.dev/docs/documentation/guides/viewing-runs). */
643
- get logger() {
644
- return new IOLogger(async (level, message, data) => {
645
- let logLevel = "info";
646
- if (data instanceof Error) {
647
- data = {
648
- name: data.name,
649
- message: data.message,
650
- stack: data.stack
651
- };
652
- }
653
- if (coreBackend.Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {
654
- await this.runTask([
655
- message,
656
- level
657
- ], async (task) => {
658
- switch (level) {
659
- case "LOG": {
660
- this._jobLogger?.log(message, data);
661
- logLevel = "log";
662
- break;
663
- }
664
- case "DEBUG": {
665
- this._jobLogger?.debug(message, data);
666
- logLevel = "debug";
667
- break;
668
- }
669
- case "INFO": {
670
- this._jobLogger?.info(message, data);
671
- logLevel = "info";
672
- break;
673
- }
674
- case "WARN": {
675
- this._jobLogger?.warn(message, data);
676
- logLevel = "warn";
677
- break;
678
- }
679
- case "ERROR": {
680
- this._jobLogger?.error(message, data);
681
- logLevel = "error";
682
- break;
683
- }
684
- }
685
- }, {
686
- name: "log",
687
- icon: "log",
688
- description: message,
689
- params: data,
690
- properties: [
691
- {
692
- label: "Level",
693
- text: level
694
- }
695
- ],
696
- style: {
697
- style: "minimal",
698
- variant: level.toLowerCase()
699
- },
700
- noop: true
701
- });
702
- }
703
- });
704
- }
705
- /** `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.
706
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
707
- * @param min Sets the lower bound (inclusive). Can't be higher than `max`.
708
- * @param max Sets the upper bound (exclusive). Can't be lower than `min`.
709
- * @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.
710
- */
711
- async random(cacheKey, { min = 0, max = 1, round = false } = {}) {
712
- return await this.runTask(cacheKey, async (task) => {
713
- if (min > max) {
714
- throw new Error(`Lower bound can't be higher than upper bound - min: ${min}, max: ${max}`);
715
- }
716
- if (min === max) {
717
- await this.logger.warn(`Lower and upper bounds are identical. The return value is not random and will always be: ${min}`);
718
- }
719
- const withinBounds = (max - min) * Math.random() + min;
720
- if (!round) {
721
- return withinBounds;
722
- }
723
- if (!Number.isInteger(min) || !Number.isInteger(max)) {
724
- await this.logger.warn("Rounding enabled with floating-point bounds. This may cause unexpected skew and boundary inclusivity.");
725
- }
726
- const rounded = Math.round(withinBounds);
727
- return rounded;
728
- }, {
729
- name: "random",
730
- icon: "dice-5-filled",
731
- params: {
732
- min,
733
- max,
734
- round
735
- },
736
- properties: [
737
- ...min === 0 ? [] : [
738
- {
739
- label: "min",
740
- text: String(min)
741
- }
742
- ],
743
- ...max === 1 ? [] : [
744
- {
745
- label: "max",
746
- text: String(max)
747
- }
748
- ],
749
- ...round === false ? [] : [
750
- {
751
- label: "round",
752
- text: String(round)
753
- }
754
- ]
755
- ],
756
- style: {
757
- style: "minimal"
758
- }
759
- });
760
- }
761
- /** `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.
762
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
763
- * @param seconds The number of seconds to wait. This can be very long, serverless timeouts are not an issue.
764
- */
765
- async wait(cacheKey, seconds) {
766
- return await this.runTask(cacheKey, async (task) => {
767
- }, {
768
- name: "wait",
769
- icon: "clock",
770
- params: {
771
- seconds
772
- },
773
- noop: true,
774
- delayUntil: new Date(Date.now() + seconds * 1e3),
775
- style: {
776
- style: "minimal"
777
- }
778
- });
779
- }
780
- async waitForEvent(cacheKey, event, options) {
781
- const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
782
- return await this.runTask(cacheKey, async (task, io) => {
783
- if (!task.callbackUrl) {
784
- throw new Error("No callbackUrl found on task");
785
- }
786
- await this.triggerClient.createEphemeralEventDispatcher({
787
- url: task.callbackUrl,
788
- name: event.name,
789
- filter: event.filter,
790
- contextFilter: event.contextFilter,
791
- source: event.source,
792
- accountId: event.accountId,
793
- timeoutInSeconds
794
- });
795
- return {};
796
- }, {
797
- name: "Wait for Event",
798
- icon: "custom-event",
799
- params: {
800
- name: event.name,
801
- source: event.source,
802
- filter: event.filter,
803
- contextFilter: event.contextFilter,
804
- accountId: event.accountId
805
- },
806
- callback: {
807
- enabled: true,
808
- timeoutInSeconds
809
- },
810
- properties: [
811
- {
812
- label: "Event",
813
- text: event.name
814
- },
815
- {
816
- label: "Timeout",
817
- text: `${timeoutInSeconds}s`
818
- },
819
- ...event.source ? [
820
- {
821
- label: "Source",
822
- text: event.source
823
- }
824
- ] : [],
825
- ...event.accountId ? [
826
- {
827
- label: "Account ID",
828
- text: event.accountId
829
- }
830
- ] : []
831
- ],
832
- parseOutput: (output) => {
833
- return waitForEventSchema(event.schema ?? zod.z.any()).parse(output);
834
- }
835
- });
836
- }
837
- /** `io.waitForRequest()` allows you to pause the execution of a run until the url provided in the callback is POSTed to.
838
- * 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.
839
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
840
- * @param callback A callback function that will provide the unique URL to POST to.
841
- * @param options Options for the callback.
842
- * @param options.timeoutInSeconds How long to wait for the request to be POSTed to the callback URL before timing out. Defaults to 1hr.
843
- * @returns The POSTed request JSON body.
844
- * @example
845
- * ```ts
846
- const result = await io.waitForRequest<{ message: string }>(
847
- "wait-for-request",
848
- async (url, task) => {
849
- // Save the URL somewhere so you can POST to it later
850
- // Or send it to an external service that will POST to it
851
- },
852
- { timeoutInSeconds: 60 } // wait 60 seconds
853
- );
854
- * ```
855
- */
856
- async waitForRequest(cacheKey, callback, options) {
857
- const timeoutInSeconds = options?.timeoutInSeconds ?? 60 * 60;
858
- return await this.runTask(cacheKey, async (task, io) => {
859
- if (!task.callbackUrl) {
860
- throw new Error("No callbackUrl found on task");
861
- }
862
- task.outputProperties = [
863
- {
864
- label: "Callback URL",
865
- text: task.callbackUrl
866
- }
867
- ];
868
- return callback(task.callbackUrl);
869
- }, {
870
- name: "Wait for Request",
871
- icon: "clock",
872
- callback: {
873
- enabled: true,
874
- timeoutInSeconds: options?.timeoutInSeconds
875
- },
876
- properties: [
877
- {
878
- label: "Timeout",
879
- text: `${timeoutInSeconds}s`
880
- }
881
- ]
882
- });
883
- }
884
- /** `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
885
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
886
- * @param initialStatus The initial status you want this status to have. You can update it during the rub using the returned object.
887
- * @returns a TriggerStatus object that you can call `update()` on, to update the status.
888
- * @example
889
- * ```ts
890
- * client.defineJob(
891
- //...
892
- run: async (payload, io, ctx) => {
893
- const generatingImages = await io.createStatus("generating-images", {
894
- label: "Generating Images",
895
- state: "loading",
896
- data: {
897
- progress: 0.1,
898
- },
899
- });
900
-
901
- //...do stuff
902
-
903
- await generatingImages.update("completed-generation", {
904
- label: "Generated images",
905
- state: "success",
906
- data: {
907
- progress: 1.0,
908
- urls: ["http://..."]
909
- },
910
- });
911
-
912
- //...
913
- });
914
- * ```
915
- */
916
- async createStatus(cacheKey, initialStatus) {
917
- const id = typeof cacheKey === "string" ? cacheKey : cacheKey.join("-");
918
- const status = new TriggerStatus(id, this);
919
- await status.update(cacheKey, initialStatus);
920
- return status;
921
- }
922
- /** `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.
923
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
924
- * @param url The URL to fetch from.
925
- * @param requestInit The options for the request
926
- * @param retry The options for retrying the request if it fails
927
- * An object where the key is a status code pattern and the value is a retrying strategy.
928
- * Supported patterns are:
929
- * - Specific status codes: 429
930
- * - Ranges: 500-599
931
- * - Wildcards: 2xx, 3xx, 4xx, 5xx
932
- */
933
- async backgroundFetch(cacheKey, url, requestInit, options) {
934
- const urlObject = new URL(url);
935
- return await this.runTask(cacheKey, async (task) => {
936
- console.log("task context", task.context);
937
- return task.output;
938
- }, {
939
- name: `fetch ${urlObject.hostname}${urlObject.pathname}`,
940
- params: {
941
- url,
942
- requestInit,
943
- retry: options?.retry,
944
- timeout: options?.timeout
945
- },
946
- operation: "fetch",
947
- icon: "background",
948
- noop: false,
949
- properties: [
950
- {
951
- label: "url",
952
- text: url,
953
- url
954
- },
955
- {
956
- label: "method",
957
- text: requestInit?.method ?? "GET"
958
- },
959
- {
960
- label: "background",
961
- text: "true"
962
- },
963
- ...options?.timeout ? [
964
- {
965
- label: "timeout",
966
- text: `${options.timeout.durationInMs}ms`
967
- }
968
- ] : []
969
- ],
970
- retry: {
971
- limit: 0
972
- }
973
- });
974
- }
975
- /** `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.
976
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
977
- * @param params The options for the background poll
978
- * @param params.url The URL to fetch from.
979
- * @param params.requestInit The options for the request, like headers and method
980
- * @param params.responseFilter An [EventFilter](https://trigger.dev/docs/documentation/guides/event-filter) that allows you to specify when to stop polling.
981
- * @param params.interval The interval in seconds to poll the URL in seconds. Defaults to 10 seconds which is the minimum.
982
- * @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
983
- * @param params.requestTimeout An optional object that allows you to timeout individual fetch requests
984
- * @param params.requestTimeout An optional object that allows you to timeout individual fetch requests
985
- * @param params.requestTimeout.durationInMs The duration in milliseconds to timeout the request
986
- *
987
- * @example
988
- * ```ts
989
- * const result = await io.backgroundPoll<{ id: string; status: string; }>("poll", {
990
- url: `http://localhost:3030/api/v1/runs/${run.id}`,
991
- requestInit: {
992
- headers: {
993
- Accept: "application/json",
994
- Authorization: redactString`Bearer ${process.env["TRIGGER_API_KEY"]!}`,
995
- },
996
- },
997
- interval: 10,
998
- timeout: 600,
999
- responseFilter: {
1000
- status: [200],
1001
- body: {
1002
- status: ["SUCCESS"],
1003
- },
1004
- },
1005
- });
1006
- * ```
1007
- */
1008
- async backgroundPoll(cacheKey, params) {
1009
- const urlObject = new URL(params.url);
1010
- return await this.runTask(cacheKey, async (task) => {
1011
- return task.output;
1012
- }, {
1013
- name: `poll ${urlObject.hostname}${urlObject.pathname}`,
1014
- params,
1015
- operation: "fetch-poll",
1016
- icon: "clock-bolt",
1017
- noop: false,
1018
- properties: [
1019
- {
1020
- label: "url",
1021
- text: params.url
1022
- },
1023
- {
1024
- label: "interval",
1025
- text: `${params.interval}s`
1026
- },
1027
- {
1028
- label: "timeout",
1029
- text: `${params.timeout}s`
1030
- }
1031
- ],
1032
- retry: {
1033
- limit: 0
1034
- }
1035
- });
1036
- }
1037
- /** `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.
1038
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1039
- * @param url The URL to fetch from.
1040
- * @param requestInit The options for the request
1041
- * @param retry The options for retrying the request if it fails
1042
- * An object where the key is a status code pattern and the value is a retrying strategy.
1043
- * Supported patterns are:
1044
- * - Specific status codes: 429
1045
- * - Ranges: 500-599
1046
- * - Wildcards: 2xx, 3xx, 4xx, 5xx
1047
- */
1048
- async backgroundFetchResponse(cacheKey, url, requestInit, options) {
1049
- const urlObject = new URL(url);
1050
- return await this.runTask(cacheKey, async (task) => {
1051
- return task.output;
1052
- }, {
1053
- name: `fetch response ${urlObject.hostname}${urlObject.pathname}`,
1054
- params: {
1055
- url,
1056
- requestInit,
1057
- retry: options?.retry,
1058
- timeout: options?.timeout
1059
- },
1060
- operation: "fetch-response",
1061
- icon: "background",
1062
- noop: false,
1063
- properties: [
1064
- {
1065
- label: "url",
1066
- text: url,
1067
- url
1068
- },
1069
- {
1070
- label: "method",
1071
- text: requestInit?.method ?? "GET"
1072
- },
1073
- {
1074
- label: "background",
1075
- text: "true"
1076
- },
1077
- ...options?.timeout ? [
1078
- {
1079
- label: "timeout",
1080
- text: `${options.timeout.durationInMs}ms`
1081
- }
1082
- ] : []
1083
- ],
1084
- retry: {
1085
- limit: 0
1086
- }
1087
- });
1088
- }
1089
- /** `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).
1090
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1091
- * @param event The event to send. The event name must match the name of the event that your Jobs are listening for.
1092
- * @param options Options for sending the event.
1093
- */
1094
- async sendEvent(cacheKey, event, options) {
1095
- return await this.runTask(cacheKey, async (task) => {
1096
- return await this._triggerClient.sendEvent(event, options);
1097
- }, {
1098
- name: "Send Event",
1099
- params: {
1100
- event,
1101
- options
1102
- },
1103
- icon: "send",
1104
- properties: [
1105
- {
1106
- label: "name",
1107
- text: event.name
1108
- },
1109
- ...event?.id ? [
1110
- {
1111
- label: "ID",
1112
- text: event.id
1113
- }
1114
- ] : [],
1115
- ...sendEventOptionsProperties(options)
1116
- ]
1117
- });
1118
- }
1119
- /** `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).
1120
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1121
- * @param event The events to send. The event names must match the names of the events that your Jobs are listening for.
1122
- * @param options Options for sending the events.
1123
- */
1124
- async sendEvents(cacheKey, events, options) {
1125
- return await this.runTask(cacheKey, async (task) => {
1126
- return await this._triggerClient.sendEvents(events, options);
1127
- }, {
1128
- name: "Send Multiple Events",
1129
- params: {
1130
- events,
1131
- options
1132
- },
1133
- icon: "send",
1134
- properties: [
1135
- {
1136
- label: "Total Events",
1137
- text: String(events.length)
1138
- },
1139
- ...sendEventOptionsProperties(options)
1140
- ]
1141
- });
1142
- }
1143
- async getEvent(cacheKey, id) {
1144
- return await this.runTask(cacheKey, async (task) => {
1145
- return await this._triggerClient.getEvent(id);
1146
- }, {
1147
- name: "getEvent",
1148
- params: {
1149
- id
1150
- },
1151
- properties: [
1152
- {
1153
- label: "id",
1154
- text: id
1155
- }
1156
- ]
1157
- });
1158
- }
1159
- /** `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
1160
- * @param cacheKey
1161
- * @param eventId
1162
- * @returns
1163
- */
1164
- async cancelEvent(cacheKey, eventId) {
1165
- return await this.runTask(cacheKey, async (task) => {
1166
- return await this._triggerClient.cancelEvent(eventId);
1167
- }, {
1168
- name: "cancelEvent",
1169
- params: {
1170
- eventId
1171
- },
1172
- properties: [
1173
- {
1174
- label: "id",
1175
- text: eventId
1176
- }
1177
- ]
1178
- });
1179
- }
1180
- async updateSource(cacheKey, options) {
1181
- return this.runTask(cacheKey, async (task) => {
1182
- return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);
1183
- }, {
1184
- name: "Update Source",
1185
- description: "Update Source",
1186
- properties: [
1187
- {
1188
- label: "key",
1189
- text: options.key
1190
- }
1191
- ],
1192
- params: options,
1193
- redact: {
1194
- paths: [
1195
- "secret"
1196
- ]
1197
- }
1198
- });
1199
- }
1200
- async updateWebhook(cacheKey, options) {
1201
- return this.runTask(cacheKey, async (task) => {
1202
- return await this._apiClient.updateWebhook(options.key, options);
1203
- }, {
1204
- name: "Update Webhook Source",
1205
- icon: "refresh",
1206
- properties: [
1207
- {
1208
- label: "key",
1209
- text: options.key
1210
- }
1211
- ],
1212
- params: options
1213
- });
1214
- }
1215
- /** `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.
1216
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1217
- * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.
1218
- * @param id A unique id for the interval. This is used to identify and unregister the interval later.
1219
- * @param options The options for the interval.
1220
- * @returns A promise that has information about the interval.
1221
- * @deprecated Use `DynamicSchedule.register` instead.
1222
- */
1223
- async registerInterval(cacheKey, dynamicSchedule, id, options) {
1224
- return await this.runTask(cacheKey, async (task) => {
1225
- return dynamicSchedule.register(id, {
1226
- type: "interval",
1227
- options
1228
- });
1229
- }, {
1230
- name: "register-interval",
1231
- properties: [
1232
- {
1233
- label: "schedule",
1234
- text: dynamicSchedule.id
1235
- },
1236
- {
1237
- label: "id",
1238
- text: id
1239
- },
1240
- {
1241
- label: "seconds",
1242
- text: options.seconds.toString()
1243
- }
1244
- ],
1245
- params: options
1246
- });
1247
- }
1248
- /** `io.unregisterInterval()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerInterval()`.
1249
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1250
- * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.
1251
- * @param id A unique id for the interval. This is used to identify and unregister the interval later.
1252
- * @deprecated Use `DynamicSchedule.unregister` instead.
1253
- */
1254
- async unregisterInterval(cacheKey, dynamicSchedule, id) {
1255
- return await this.runTask(cacheKey, async (task) => {
1256
- return dynamicSchedule.unregister(id);
1257
- }, {
1258
- name: "unregister-interval",
1259
- properties: [
1260
- {
1261
- label: "schedule",
1262
- text: dynamicSchedule.id
1263
- },
1264
- {
1265
- label: "id",
1266
- text: id
1267
- }
1268
- ]
1269
- });
1270
- }
1271
- /** `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.
1272
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1273
- * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.
1274
- * @param id A unique id for the schedule. This is used to identify and unregister the schedule later.
1275
- * @param options The options for the CRON schedule.
1276
- * @deprecated Use `DynamicSchedule.register` instead.
1277
- */
1278
- async registerCron(cacheKey, dynamicSchedule, id, options) {
1279
- return await this.runTask(cacheKey, async (task) => {
1280
- return dynamicSchedule.register(id, {
1281
- type: "cron",
1282
- options
1283
- });
1284
- }, {
1285
- name: "register-cron",
1286
- properties: [
1287
- {
1288
- label: "schedule",
1289
- text: dynamicSchedule.id
1290
- },
1291
- {
1292
- label: "id",
1293
- text: id
1294
- },
1295
- {
1296
- label: "cron",
1297
- text: options.cron
1298
- }
1299
- ],
1300
- params: options
1301
- });
1302
- }
1303
- /** `io.unregisterCron()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerCron()`.
1304
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1305
- * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.
1306
- * @param id A unique id for the interval. This is used to identify and unregister the interval later.
1307
- * @deprecated Use `DynamicSchedule.unregister` instead.
1308
- */
1309
- async unregisterCron(cacheKey, dynamicSchedule, id) {
1310
- return await this.runTask(cacheKey, async (task) => {
1311
- return dynamicSchedule.unregister(id);
1312
- }, {
1313
- name: "unregister-cron",
1314
- properties: [
1315
- {
1316
- label: "schedule",
1317
- text: dynamicSchedule.id
1318
- },
1319
- {
1320
- label: "id",
1321
- text: id
1322
- }
1323
- ]
1324
- });
1325
- }
1326
- /** `io.registerTrigger()` allows you to register a [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) with the specified trigger params.
1327
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1328
- * @param trigger The [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) to register.
1329
- * @param id A unique id for the trigger. This is used to identify and unregister the trigger later.
1330
- * @param params The params for the trigger.
1331
- * @deprecated Use `DynamicTrigger.register` instead.
1332
- */
1333
- async registerTrigger(cacheKey, trigger, id, params) {
1334
- return await this.runTask(cacheKey, async (task) => {
1335
- const registration = await this.runTask("register-source", async (subtask1) => {
1336
- return trigger.register(id, params);
1337
- }, {
1338
- name: "register-source"
1339
- });
1340
- return {
1341
- id: registration.id,
1342
- key: registration.source.key
1343
- };
1344
- }, {
1345
- name: "register-trigger",
1346
- properties: [
1347
- {
1348
- label: "trigger",
1349
- text: trigger.id
1350
- },
1351
- {
1352
- label: "id",
1353
- text: id
1354
- }
1355
- ],
1356
- params
1357
- });
1358
- }
1359
- async getAuth(cacheKey, clientId) {
1360
- if (!clientId) {
1361
- return;
1362
- }
1363
- return this.runTask(cacheKey, async (task) => {
1364
- return await this._triggerClient.getAuth(clientId);
1365
- }, {
1366
- name: "get-auth"
1367
- });
1368
- }
1369
- async parallel(cacheKey, items, callback, options) {
1370
- const results = await this.runTask(cacheKey, async (task) => {
1371
- const outcomes = await Promise.allSettled(items.map((item, index) => spaceOut(() => callback(item, index), index, 15)));
1372
- if (outcomes.every((outcome) => outcome.status === "fulfilled")) {
1373
- return outcomes.map((outcome) => outcome.value);
1374
- }
1375
- const nonInternalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && !isTriggerError(outcome.reason)).map((outcome) => outcome);
1376
- if (nonInternalErrors.length > 0) {
1377
- throw nonInternalErrors[0].reason;
1378
- }
1379
- const internalErrors = outcomes.filter((outcome) => outcome.status === "rejected" && isTriggerError(outcome.reason)).map((outcome) => outcome).map((outcome) => outcome.reason);
1380
- throw new ResumeWithParallelTaskError(task, internalErrors);
1381
- }, {
1382
- name: "parallel",
1383
- parallel: true,
1384
- ...options ?? {}
1385
- });
1386
- return results;
1387
- }
1388
- /** `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.
1389
- *
1390
- * @param cacheKey Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.
1391
- * @param callback The callback that will be called when the Task is run. The callback receives the Task and the IO as parameters.
1392
- * @param options The options of how you'd like to run and log the Task.
1393
- * @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.
1394
- * @returns A Promise that resolves with the returned value of the callback.
1395
- */
1396
- async runTask(cacheKey, callback, options, onError) {
1397
- const parentId = this._taskStorage.getStore()?.taskId;
1398
- if (parentId) {
1399
- this._logger.debug("Using parent task", {
1400
- parentId,
1401
- cacheKey,
1402
- options
1403
- });
1404
- }
1405
- const isSubtaskNoop = options?.noop === true && parentId !== void 0;
1406
- if (!isSubtaskNoop) {
1407
- __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "start_task", 500);
1408
- }
1409
- const idempotencyKey = await generateIdempotencyKey([
1410
- this._id,
1411
- parentId ?? "",
1412
- cacheKey
1413
- ].flat());
1414
- if (this._visitedCacheKeys.has(idempotencyKey)) {
1415
- if (typeof cacheKey === "string") {
1416
- throw new Error(`Task with cacheKey "${cacheKey}" has already been executed in this run. Each task must have a unique cacheKey.`);
1417
- } else {
1418
- throw new Error(`Task with cacheKey "${cacheKey.join("-")}" has already been executed in this run. Each task must have a unique cacheKey.`);
1419
- }
1420
- }
1421
- this._visitedCacheKeys.add(idempotencyKey);
1422
- const cachedTask = this._cachedTasks.get(idempotencyKey);
1423
- if (cachedTask && cachedTask.status === "COMPLETED") {
1424
- this._logger.debug("Using completed cached task", {
1425
- idempotencyKey
1426
- });
1427
- this._stats.cachedTaskHits++;
1428
- return options?.parseOutput ? options.parseOutput(cachedTask.output) : cachedTask.output;
1429
- }
1430
- if (options?.noop && this._noopTasksBloomFilter) {
1431
- if (this._noopTasksBloomFilter.test(idempotencyKey)) {
1432
- this._logger.debug("task idempotency key exists in noopTasksBloomFilter", {
1433
- idempotencyKey
1434
- });
1435
- this._stats.noopCachedTaskHits++;
1436
- return {};
1437
- }
1438
- }
1439
- const runOptions = {
1440
- ...options ?? {},
1441
- parseOutput: void 0
1442
- };
1443
- const response = await this._apiClient.runTask(this._id, {
1444
- idempotencyKey,
1445
- displayKey: typeof cacheKey === "string" ? cacheKey : void 0,
1446
- noop: false,
1447
- ...runOptions ?? {},
1448
- parentId
1449
- }, {
1450
- cachedTasksCursor: this._cachedTasksCursor
1451
- });
1452
- const task = response.version === core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1453
- if (task.forceYield) {
1454
- this._logger.debug("Forcing yield after run task", {
1455
- idempotencyKey
1456
- });
1457
- __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_run_task");
1458
- }
1459
- if (response.version === core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {
1460
- this._cachedTasksCursor = response.body.cachedTasks?.cursor;
1461
- for (const cachedTask2 of response.body.cachedTasks?.tasks ?? []) {
1462
- if (!this._cachedTasks.has(cachedTask2.idempotencyKey)) {
1463
- this._cachedTasks.set(cachedTask2.idempotencyKey, cachedTask2);
1464
- this._logger.debug("Injecting lazy loaded task into task cache", {
1465
- idempotencyKey: cachedTask2.idempotencyKey
1466
- });
1467
- this._stats.lazyLoadedCachedTasks++;
1468
- }
1469
- }
1470
- }
1471
- if (task.status === "CANCELED") {
1472
- this._logger.debug("Task canceled", {
1473
- idempotencyKey,
1474
- task
1475
- });
1476
- throw new CanceledWithTaskError(task);
1477
- }
1478
- if (task.status === "COMPLETED") {
1479
- if (task.noop) {
1480
- this._logger.debug("Noop Task completed", {
1481
- idempotencyKey
1482
- });
1483
- this._noopTasksBloomFilter?.add(task.idempotencyKey);
1484
- } else {
1485
- this._logger.debug("Cache miss", {
1486
- idempotencyKey
1487
- });
1488
- this._stats.cachedTaskMisses++;
1489
- __privateMethod(this, _addToCachedTasks, addToCachedTasks_fn).call(this, task);
1490
- }
1491
- return options?.parseOutput ? options.parseOutput(task.output) : task.output;
1492
- }
1493
- if (task.status === "ERRORED") {
1494
- this._logger.debug("Task errored", {
1495
- idempotencyKey,
1496
- task
1497
- });
1498
- throw new ErrorWithTask(task, task.error ?? task?.output ? JSON.stringify(task.output) : "Task errored");
1499
- }
1500
- __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_execute_task", 1500);
1501
- const executeTask = /* @__PURE__ */ __name(async () => {
1502
- try {
1503
- const result = await callback(task, this);
1504
- if (task.status === "WAITING" && task.callbackUrl) {
1505
- this._logger.debug("Waiting for remote callback", {
1506
- idempotencyKey,
1507
- task
1508
- });
1509
- return {};
1510
- }
1511
- const output = this._outputSerializer.serialize(result);
1512
- this._logger.debug("Completing using output", {
1513
- idempotencyKey,
1514
- task
1515
- });
1516
- __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
1517
- const completedTask = await this._apiClient.completeTask(this._id, task.id, {
1518
- output,
1519
- properties: task.outputProperties ?? void 0
1520
- });
1521
- if (completedTask.forceYield) {
1522
- this._logger.debug("Forcing yield after task completed", {
1523
- idempotencyKey
1524
- });
1525
- __privateMethod(this, _forceYield, forceYield_fn).call(this, "after_complete_task");
1526
- }
1527
- this._stats.executedTasks++;
1528
- if (completedTask.status === "CANCELED") {
1529
- throw new CanceledWithTaskError(completedTask);
1530
- }
1531
- __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "after_complete_task", 500);
1532
- const deserializedOutput = this._outputSerializer.deserialize(output);
1533
- return options?.parseOutput ? options.parseOutput(deserializedOutput) : deserializedOutput;
1534
- } catch (error) {
1535
- if (isTriggerError(error)) {
1536
- throw error;
1537
- }
1538
- let skipRetrying = false;
1539
- if (onError) {
1540
- try {
1541
- const onErrorResult = onError(error, task, this);
1542
- if (onErrorResult) {
1543
- if (onErrorResult instanceof Error) {
1544
- error = onErrorResult;
1545
- } else {
1546
- skipRetrying = !!onErrorResult.skipRetrying;
1547
- if (onErrorResult.retryAt && !skipRetrying) {
1548
- const parsedError2 = core.ErrorWithStackSchema.safeParse(onErrorResult.error);
1549
- throw new RetryWithTaskError(parsedError2.success ? parsedError2.data : {
1550
- message: "Unknown error"
1551
- }, task, onErrorResult.retryAt);
1552
- }
1553
- }
1554
- }
1555
- } catch (innerError) {
1556
- if (isTriggerError(innerError)) {
1557
- throw innerError;
1558
- }
1559
- error = innerError;
1560
- }
1561
- }
1562
- if (error instanceof ErrorWithTask) {
1563
- await this._apiClient.failTask(this._id, task.id, {
1564
- error: error.cause.output
1565
- });
1566
- throw error;
1567
- }
1568
- const parsedError = core.ErrorWithStackSchema.safeParse(error);
1569
- if (options?.retry && !skipRetrying) {
1570
- const retryAt = core.calculateRetryAt(options.retry, task.attempts - 1);
1571
- if (retryAt) {
1572
- throw new RetryWithTaskError(parsedError.success ? parsedError.data : {
1573
- message: "Unknown error"
1574
- }, task, retryAt);
1575
- }
1576
- }
1577
- if (parsedError.success) {
1578
- await this._apiClient.failTask(this._id, task.id, {
1579
- error: parsedError.data
1580
- });
1581
- } else {
1582
- const message = typeof error === "string" ? error : JSON.stringify(error);
1583
- await this._apiClient.failTask(this._id, task.id, {
1584
- error: {
1585
- name: "Unknown error",
1586
- message
1587
- }
1588
- });
1589
- }
1590
- throw error;
1591
- }
1592
- }, "executeTask");
1593
- if (task.status === "WAITING") {
1594
- this._logger.debug("Task waiting", {
1595
- idempotencyKey,
1596
- task
1597
- });
1598
- if (task.callbackUrl) {
1599
- await this._taskStorage.run({
1600
- taskId: task.id
1601
- }, executeTask);
1602
- }
1603
- throw new ResumeWithTaskError(task);
1604
- }
1605
- if (task.status === "RUNNING" && typeof task.operation === "string") {
1606
- this._logger.debug("Task running operation", {
1607
- idempotencyKey,
1608
- task
1609
- });
1610
- throw new ResumeWithTaskError(task);
1611
- }
1612
- return this._taskStorage.run({
1613
- taskId: task.id
1614
- }, executeTask);
1615
- }
1616
- /**
1617
- * `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.
1618
- */
1619
- yield(cacheKey) {
1620
- if (!core.supportsFeature("yieldExecution", this._serverVersion)) {
1621
- 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.");
1622
- return;
1623
- }
1624
- if (this._yieldedExecutions.includes(cacheKey)) {
1625
- return;
1626
- }
1627
- throw new YieldExecutionError(cacheKey);
1628
- }
1629
- /** `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).
1630
- * 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.
1631
- * @param tryCallback The code you wish to run
1632
- * @param catchCallback Thhis will be called if the Task fails. The callback receives the error
1633
- * @returns A Promise that resolves with the returned value or the error
1634
- */
1635
- async try(tryCallback, catchCallback) {
1636
- try {
1637
- return await tryCallback();
1638
- } catch (error) {
1639
- if (isTriggerError(error)) {
1640
- throw error;
1641
- }
1642
- return await catchCallback(error);
1643
- }
1644
- }
1645
- get store() {
1646
- return {
1647
- env: this._envStore,
1648
- job: this._jobStore,
1649
- run: this._runStore
1650
- };
1651
- }
1652
- };
1653
- _addToCachedTasks = new WeakSet();
1654
- addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
1655
- this._cachedTasks.set(task.idempotencyKey, task);
1656
- }, "#addToCachedTasks");
1657
- _detectAutoYield = new WeakSet();
1658
- detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task1, output) {
1659
- const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1660
- if (timeRemaining && timeRemaining < threshold) {
1661
- if (task1) {
1662
- throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], {
1663
- location,
1664
- timeRemaining,
1665
- timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1666
- }, output);
1667
- } else {
1668
- throw new AutoYieldExecutionError(location, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1669
- }
1670
- }
1671
- }, "#detectAutoYield");
1672
- _forceYield = new WeakSet();
1673
- forceYield_fn = /* @__PURE__ */ __name(function(location1) {
1674
- const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1675
- if (timeRemaining) {
1676
- throw new AutoYieldExecutionError(location1, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1677
- }
1678
- }, "#forceYield");
1679
- _getTimeElapsed = new WeakSet();
1680
- getTimeElapsed_fn = /* @__PURE__ */ __name(function() {
1681
- return performance.now() - this._timeOrigin;
1682
- }, "#getTimeElapsed");
1683
- _getRemainingTimeInMillis = new WeakSet();
1684
- getRemainingTimeInMillis_fn = /* @__PURE__ */ __name(function() {
1685
- if (this._executionTimeout) {
1686
- return this._executionTimeout - (performance.now() - this._timeOrigin);
1687
- }
1688
- return void 0;
1689
- }, "#getRemainingTimeInMillis");
1690
- __name(_IO, "IO");
1691
- var IO = _IO;
1692
- async function generateIdempotencyKey(keyMaterial) {
1693
- const keys = keyMaterial.map((key2) => {
1694
- if (typeof key2 === "string") {
1695
- return key2;
1696
- }
1697
- return stableStringify(key2);
1698
- });
1699
- const key = keys.join(":");
1700
- const hash = await crypto.webcrypto.subtle.digest("SHA-256", node_buffer.Buffer.from(key));
1701
- return node_buffer.Buffer.from(hash).toString("hex");
1702
- }
1703
- __name(generateIdempotencyKey, "generateIdempotencyKey");
1704
- function stableStringify(obj) {
1705
- function sortKeys(obj2) {
1706
- if (typeof obj2 !== "object" || obj2 === null) {
1707
- return obj2;
1708
- }
1709
- if (Array.isArray(obj2)) {
1710
- return obj2.map(sortKeys);
1711
- }
1712
- const sortedKeys = Object.keys(obj2).sort();
1713
- const sortedObj2 = {};
1714
- for (const key of sortedKeys) {
1715
- sortedObj2[key] = sortKeys(obj2[key]);
1716
- }
1717
- return sortedObj2;
1718
- }
1719
- __name(sortKeys, "sortKeys");
1720
- const sortedObj = sortKeys(obj);
1721
- return JSON.stringify(sortedObj);
1722
- }
1723
- __name(stableStringify, "stableStringify");
1724
- var _IOLogger = class _IOLogger {
1725
- constructor(callback) {
1726
- this.callback = callback;
1727
- }
1728
- /** Log: essential messages */
1729
- log(message, properties) {
1730
- return this.callback("LOG", message, properties);
1731
- }
1732
- /** For debugging: the least important log level */
1733
- debug(message, properties) {
1734
- return this.callback("DEBUG", message, properties);
1735
- }
1736
- /** Info: the second least important log level */
1737
- info(message, properties) {
1738
- return this.callback("INFO", message, properties);
1739
- }
1740
- /** Warnings: the third most important log level */
1741
- warn(message, properties) {
1742
- return this.callback("WARN", message, properties);
1743
- }
1744
- /** Error: The second most important log level */
1745
- error(message, properties) {
1746
- return this.callback("ERROR", message, properties);
1747
- }
1748
- };
1749
- __name(_IOLogger, "IOLogger");
1750
- var IOLogger = _IOLogger;
1751
- async function spaceOut(callback, index, delay) {
1752
- await new Promise((resolve) => setTimeout(resolve, index * delay));
1753
- return await callback();
1754
- }
1755
- __name(spaceOut, "spaceOut");
1756
- function sendEventOptionsProperties(options) {
1757
- return [
1758
- ...options?.accountId ? [
1759
- {
1760
- label: "Account ID",
1761
- text: options.accountId
1762
- }
1763
- ] : [],
1764
- ...options?.deliverAfter ? [
1765
- {
1766
- label: "Deliver After",
1767
- text: `${options.deliverAfter}s`
1768
- }
1769
- ] : [],
1770
- ...options?.deliverAt ? [
1771
- {
1772
- label: "Deliver At",
1773
- text: options.deliverAt.toISOString()
1774
- }
1775
- ] : []
1776
- ];
1777
- }
1778
- __name(sendEventOptionsProperties, "sendEventOptionsProperties");
1779
-
1780
- // src/store/keyValueStoreClient.ts
1781
- var _serializer, _namespacedKey2, namespacedKey_fn2;
1782
- var _KeyValueStoreClient = class _KeyValueStoreClient {
1783
- constructor(queryStore, type = null, namespace = "") {
1784
- __privateAdd(this, _namespacedKey2);
1785
- __privateAdd(this, _serializer, void 0);
1786
- this.queryStore = queryStore;
1787
- this.type = type;
1788
- this.namespace = namespace;
1789
- __privateSet(this, _serializer, new JSONOutputSerializer());
1790
- }
1791
- async delete(key) {
1792
- const result = await this.queryStore("DELETE", {
1793
- key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1794
- });
1795
- if (result.action !== "DELETE") {
1796
- throw new Error(`Unexpected key-value store response: ${result.action}`);
1797
- }
1798
- return result.deleted;
1799
- }
1800
- async get(key) {
1801
- const result = await this.queryStore("GET", {
1802
- key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1803
- });
1804
- if (result.action !== "GET") {
1805
- throw new Error(`Unexpected key-value store response: ${result.action}`);
1806
- }
1807
- return __privateGet(this, _serializer).deserialize(result.value);
1808
- }
1809
- async has(key) {
1810
- const result = await this.queryStore("HAS", {
1811
- key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key)
1812
- });
1813
- if (result.action !== "HAS") {
1814
- throw new Error(`Unexpected key-value store response: ${result.action}`);
1815
- }
1816
- return result.has;
1817
- }
1818
- async set(key, value) {
1819
- const result = await this.queryStore("SET", {
1820
- key: __privateMethod(this, _namespacedKey2, namespacedKey_fn2).call(this, key),
1821
- value: __privateGet(this, _serializer).serialize(value)
1822
- });
1823
- if (result.action !== "SET") {
1824
- throw new Error(`Unexpected key-value store response: ${result.action}`);
1825
- }
1826
- return __privateGet(this, _serializer).deserialize(result.value);
1827
- }
1828
- };
1829
- _serializer = new WeakMap();
1830
- _namespacedKey2 = new WeakSet();
1831
- namespacedKey_fn2 = /* @__PURE__ */ __name(function(key) {
1832
- const parts = [];
1833
- if (this.type) {
1834
- parts.push(this.type);
1835
- }
1836
- if (this.namespace) {
1837
- parts.push(this.namespace);
1838
- }
1839
- parts.push(key);
1840
- return parts.join(":");
1841
- }, "#namespacedKey");
1842
- __name(_KeyValueStoreClient, "KeyValueStoreClient");
1843
- var KeyValueStoreClient = _KeyValueStoreClient;
1844
-
1845
- // src/apiClient.ts
1846
- var _apiUrl, _options, _logger, _storeClient, _queryKeyValueStore, queryKeyValueStore_fn, _apiKey, apiKey_fn;
1847
- var _ApiClient = class _ApiClient {
1848
- constructor(options) {
1849
- __privateAdd(this, _queryKeyValueStore);
1850
- __privateAdd(this, _apiKey);
1851
- __privateAdd(this, _apiUrl, void 0);
1852
- __privateAdd(this, _options, void 0);
1853
- __privateAdd(this, _logger, void 0);
1854
- __privateAdd(this, _storeClient, void 0);
1855
- __privateSet(this, _options, options);
1856
- __privateSet(this, _apiUrl, __privateGet(this, _options).apiUrl ?? node_process.env.TRIGGER_API_URL ?? "https://api.trigger.dev");
1857
- __privateSet(this, _logger, new coreBackend.Logger("trigger.dev", __privateGet(this, _options).logLevel));
1858
- __privateSet(this, _storeClient, new KeyValueStoreClient(__privateMethod(this, _queryKeyValueStore, queryKeyValueStore_fn).bind(this)));
1859
- }
1860
- async registerEndpoint(options) {
1861
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1862
- __privateGet(this, _logger).debug("Registering endpoint", {
1863
- url: options.url,
1864
- name: options.name
1865
- });
1866
- const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
1867
- method: "POST",
1868
- headers: {
1869
- "Content-Type": "application/json",
1870
- Authorization: `Bearer ${apiKey}`
1871
- },
1872
- body: JSON.stringify({
1873
- url: options.url,
1874
- name: options.name
1875
- })
1876
- });
1877
- if (response.status >= 400 && response.status < 500) {
1878
- const body = await response.json();
1879
- throw new Error(body.error);
1880
- }
1881
- if (response.status !== 200) {
1882
- throw new Error(`Failed to register entry point, got status code ${response.status}`);
1883
- }
1884
- return await response.json();
1885
- }
1886
- async runTask(runId, task, options = {}) {
1887
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1888
- __privateGet(this, _logger).debug("Running Task", {
1889
- task
1890
- });
1891
- return await zodfetchWithVersions({
1892
- [core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: core.RunTaskResponseWithCachedTasksBodySchema
1893
- }, core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
1894
- method: "POST",
1895
- headers: {
1896
- "Content-Type": "application/json",
1897
- Authorization: `Bearer ${apiKey}`,
1898
- "Idempotency-Key": task.idempotencyKey,
1899
- "X-Cached-Tasks-Cursor": options.cachedTasksCursor ?? "",
1900
- "Trigger-Version": core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS
1901
- },
1902
- body: JSON.stringify(task)
1903
- });
1904
- }
1905
- async completeTask(runId, id, task) {
1906
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1907
- __privateGet(this, _logger).debug("Complete Task", {
1908
- task
1909
- });
1910
- return await zodfetch(core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/complete`, {
1911
- method: "POST",
1912
- headers: {
1913
- "Content-Type": "application/json",
1914
- Authorization: `Bearer ${apiKey}`,
1915
- "Trigger-Version": core.API_VERSIONS.SERIALIZED_TASK_OUTPUT
1916
- },
1917
- body: JSON.stringify(task)
1918
- });
1919
- }
1920
- async failTask(runId, id, body) {
1921
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1922
- __privateGet(this, _logger).debug("Fail Task", {
1923
- id,
1924
- runId,
1925
- body
1926
- });
1927
- return await zodfetch(core.ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks/${id}/fail`, {
1928
- method: "POST",
1929
- headers: {
1930
- "Content-Type": "application/json",
1931
- Authorization: `Bearer ${apiKey}`
1932
- },
1933
- body: JSON.stringify(body)
1934
- });
1935
- }
1936
- async sendEvent(event, options = {}) {
1937
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1938
- __privateGet(this, _logger).debug("Sending event", {
1939
- event
1940
- });
1941
- return await zodfetch(core.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events`, {
1942
- method: "POST",
1943
- headers: {
1944
- "Content-Type": "application/json",
1945
- Authorization: `Bearer ${apiKey}`
1946
- },
1947
- body: JSON.stringify({
1948
- event,
1949
- options
1950
- })
1951
- });
1952
- }
1953
- async sendEvents(events, options = {}) {
1954
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1955
- __privateGet(this, _logger).debug("Sending multiple events", {
1956
- events
1957
- });
1958
- return await zodfetch(core.ApiEventLogSchema.array(), `${__privateGet(this, _apiUrl)}/api/v1/events/bulk`, {
1959
- method: "POST",
1960
- headers: {
1961
- "Content-Type": "application/json",
1962
- Authorization: `Bearer ${apiKey}`
1963
- },
1964
- body: JSON.stringify({
1965
- events,
1966
- options
1967
- })
1968
- });
1969
- }
1970
- async cancelEvent(eventId) {
1971
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1972
- __privateGet(this, _logger).debug("Cancelling event", {
1973
- eventId
1974
- });
1975
- return await zodfetch(core.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel`, {
1976
- method: "POST",
1977
- headers: {
1978
- "Content-Type": "application/json",
1979
- Authorization: `Bearer ${apiKey}`
1980
- }
1981
- });
1982
- }
1983
- async cancelRunsForEvent(eventId) {
1984
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1985
- __privateGet(this, _logger).debug("Cancelling runs for event", {
1986
- eventId
1987
- });
1988
- return await zodfetch(core.CancelRunsForEventSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel-runs`, {
1989
- method: "POST",
1990
- headers: {
1991
- "Content-Type": "application/json",
1992
- Authorization: `Bearer ${apiKey}`
1993
- }
1994
- });
1995
- }
1996
- async updateStatus(runId, id, status) {
1997
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1998
- __privateGet(this, _logger).debug("Update status", {
1999
- id,
2000
- status
2001
- });
2002
- return await zodfetch(core.JobRunStatusRecordSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/statuses/${id}`, {
2003
- method: "PUT",
2004
- headers: {
2005
- "Content-Type": "application/json",
2006
- Authorization: `Bearer ${apiKey}`
2007
- },
2008
- body: JSON.stringify(status)
2009
- });
2010
- }
2011
- async updateSource(client, key, source) {
2012
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2013
- __privateGet(this, _logger).debug("activating http source", {
2014
- source
2015
- });
2016
- const response = await zodfetch(core.TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v2/${client}/sources/${key}`, {
2017
- method: "PUT",
2018
- headers: {
2019
- "Content-Type": "application/json",
2020
- Authorization: `Bearer ${apiKey}`
2021
- },
2022
- body: JSON.stringify(source)
2023
- });
2024
- return response;
2025
- }
2026
- async updateWebhook(key, webhookData) {
2027
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2028
- __privateGet(this, _logger).debug("activating webhook", {
2029
- webhookData
2030
- });
2031
- const response = await zodfetch(core.TriggerSourceSchema, `${__privateGet(this, _apiUrl)}/api/v1/webhooks/${key}`, {
2032
- method: "PUT",
2033
- headers: {
2034
- "Content-Type": "application/json",
2035
- Authorization: `Bearer ${apiKey}`
2036
- },
2037
- body: JSON.stringify(webhookData)
2038
- });
2039
- return response;
2040
- }
2041
- async registerTrigger(client, id, key, payload, idempotencyKey) {
2042
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2043
- __privateGet(this, _logger).debug("registering trigger", {
2044
- id,
2045
- payload
2046
- });
2047
- const headers = {
2048
- "Content-Type": "application/json",
2049
- Authorization: `Bearer ${apiKey}`
2050
- };
2051
- if (idempotencyKey) {
2052
- headers["Idempotency-Key"] = idempotencyKey;
2053
- }
2054
- const response = await zodfetch(core.RegisterSourceEventSchemaV2, `${__privateGet(this, _apiUrl)}/api/v2/${client}/triggers/${id}/registrations/${key}`, {
2055
- method: "PUT",
2056
- headers,
2057
- body: JSON.stringify(payload)
2058
- });
2059
- return response;
2060
- }
2061
- async registerSchedule(client, id, key, payload) {
2062
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2063
- __privateGet(this, _logger).debug("registering schedule", {
2064
- id,
2065
- payload
2066
- });
2067
- const response = await zodfetch(core.RegisterScheduleResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations`, {
2068
- method: "POST",
2069
- headers: {
2070
- "Content-Type": "application/json",
2071
- Authorization: `Bearer ${apiKey}`
2072
- },
2073
- body: JSON.stringify({
2074
- id: key,
2075
- ...payload
2076
- })
2077
- });
2078
- return response;
2079
- }
2080
- async unregisterSchedule(client, id, key) {
2081
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2082
- __privateGet(this, _logger).debug("unregistering schedule", {
2083
- id
2084
- });
2085
- const response = await zodfetch(zod.z.object({
2086
- ok: zod.z.boolean()
2087
- }), `${__privateGet(this, _apiUrl)}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`, {
2088
- method: "DELETE",
2089
- headers: {
2090
- "Content-Type": "application/json",
2091
- Authorization: `Bearer ${apiKey}`
2092
- }
2093
- });
2094
- return response;
2095
- }
2096
- async getAuth(client, id) {
2097
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2098
- __privateGet(this, _logger).debug("getting auth", {
2099
- id
2100
- });
2101
- const response = await zodfetch(core.ConnectionAuthSchema, `${__privateGet(this, _apiUrl)}/api/v1/${client}/auth/${id}`, {
2102
- method: "GET",
2103
- headers: {
2104
- Accept: "application/json",
2105
- Authorization: `Bearer ${apiKey}`
2106
- }
2107
- }, {
2108
- optional: true
2109
- });
2110
- return response;
2111
- }
2112
- async getEvent(eventId) {
2113
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2114
- __privateGet(this, _logger).debug("Getting Event", {
2115
- eventId
2116
- });
2117
- return await zodfetch(core.GetEventSchema, `${__privateGet(this, _apiUrl)}/api/v2/events/${eventId}`, {
2118
- method: "GET",
2119
- headers: {
2120
- Authorization: `Bearer ${apiKey}`
2121
- }
2122
- });
2123
- }
2124
- async getRun(runId, options) {
2125
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2126
- __privateGet(this, _logger).debug("Getting Run", {
2127
- runId
2128
- });
2129
- return await zodfetch(core.GetRunSchema, core.urlWithSearchParams(`${__privateGet(this, _apiUrl)}/api/v2/runs/${runId}`, options), {
2130
- method: "GET",
2131
- headers: {
2132
- Authorization: `Bearer ${apiKey}`
2133
- }
2134
- });
2135
- }
2136
- async cancelRun(runId) {
2137
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2138
- __privateGet(this, _logger).debug("Cancelling Run", {
2139
- runId
2140
- });
2141
- return await zodfetch(core.GetRunSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/cancel`, {
2142
- method: "POST",
2143
- headers: {
2144
- "Content-Type": "application/json",
2145
- Authorization: `Bearer ${apiKey}`
2146
- }
2147
- });
2148
- }
2149
- async getRunStatuses(runId) {
2150
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2151
- __privateGet(this, _logger).debug("Getting Run statuses", {
2152
- runId
2153
- });
2154
- return await zodfetch(core.GetRunStatusesSchema, `${__privateGet(this, _apiUrl)}/api/v2/runs/${runId}/statuses`, {
2155
- method: "GET",
2156
- headers: {
2157
- Authorization: `Bearer ${apiKey}`
2158
- }
2159
- });
2160
- }
2161
- async getRuns(jobSlug, options) {
2162
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2163
- __privateGet(this, _logger).debug("Getting Runs", {
2164
- jobSlug
2165
- });
2166
- return await zodfetch(core.GetRunsSchema, core.urlWithSearchParams(`${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobSlug}/runs`, options), {
2167
- method: "GET",
2168
- headers: {
2169
- Authorization: `Bearer ${apiKey}`
2170
- }
2171
- });
2172
- }
2173
- async invokeJob(jobId, payload, options = {}) {
2174
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2175
- __privateGet(this, _logger).debug("Invoking Job", {
2176
- jobId
2177
- });
2178
- const body = {
2179
- payload,
2180
- context: options.context ?? {},
2181
- options: {
2182
- accountId: options.accountId,
2183
- callbackUrl: options.callbackUrl
2184
- }
2185
- };
2186
- return await zodfetch(core.InvokeJobResponseSchema, `${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobId}/invoke`, {
2187
- method: "POST",
2188
- headers: {
2189
- "Content-Type": "application/json",
2190
- Authorization: `Bearer ${apiKey}`,
2191
- ...options.idempotencyKey ? {
2192
- "Idempotency-Key": options.idempotencyKey
2193
- } : {}
2194
- },
2195
- body: JSON.stringify(body)
2196
- });
2197
- }
2198
- async cancelRunsForJob(jobId) {
2199
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2200
- __privateGet(this, _logger).debug("Cancelling Runs for Job", {
2201
- jobId
2202
- });
2203
- return await zodfetch(core.CancelRunsForJobSchema, `${__privateGet(this, _apiUrl)}/api/v1/jobs/${jobId}/cancel-runs`, {
2204
- method: "POST",
2205
- headers: {
2206
- "Content-Type": "application/json",
2207
- Authorization: `Bearer ${apiKey}`
2208
- }
2209
- });
2210
- }
2211
- async createEphemeralEventDispatcher(payload) {
2212
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2213
- __privateGet(this, _logger).debug("Creating ephemeral event dispatcher", {
2214
- payload
2215
- });
2216
- const response = await zodfetch(core.EphemeralEventDispatcherResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/event-dispatchers/ephemeral`, {
2217
- method: "POST",
2218
- headers: {
2219
- "Content-Type": "application/json",
2220
- Authorization: `Bearer ${apiKey}`
2221
- },
2222
- body: JSON.stringify(payload)
2223
- });
2224
- return response;
2225
- }
2226
- get store() {
2227
- return __privateGet(this, _storeClient);
2228
- }
2229
- };
2230
- _apiUrl = new WeakMap();
2231
- _options = new WeakMap();
2232
- _logger = new WeakMap();
2233
- _storeClient = new WeakMap();
2234
- _queryKeyValueStore = new WeakSet();
2235
- queryKeyValueStore_fn = /* @__PURE__ */ __name(async function(action, data) {
2236
- const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
2237
- __privateGet(this, _logger).debug("accessing key-value store", {
2238
- action,
2239
- data
2240
- });
2241
- const encodedKey = encodeURIComponent(data.key);
2242
- const STORE_URL = `${__privateGet(this, _apiUrl)}/api/v1/store/${encodedKey}`;
2243
- const authHeader = {
2244
- Authorization: `Bearer ${apiKey}`
2245
- };
2246
- let requestInit;
2247
- switch (action) {
2248
- case "DELETE": {
2249
- requestInit = {
2250
- method: "DELETE",
2251
- headers: authHeader
2252
- };
2253
- break;
2254
- }
2255
- case "GET": {
2256
- requestInit = {
2257
- method: "GET",
2258
- headers: authHeader
2259
- };
2260
- break;
2261
- }
2262
- case "HAS": {
2263
- const headResponse = await fetchHead(STORE_URL, {
2264
- headers: authHeader
2265
- });
2266
- return {
2267
- action: "HAS",
2268
- key: encodedKey,
2269
- has: !!headResponse.ok
2270
- };
2271
- }
2272
- case "SET": {
2273
- const MAX_BODY_BYTE_LENGTH = 256 * 1024;
2274
- if ((data.value?.length ?? 0) > MAX_BODY_BYTE_LENGTH) {
2275
- throw new Error(`Max request body size exceeded: ${MAX_BODY_BYTE_LENGTH} bytes`);
2276
- }
2277
- requestInit = {
2278
- method: "PUT",
2279
- headers: {
2280
- ...authHeader,
2281
- "Content-Type": "text/plain"
2282
- },
2283
- body: data.value
2284
- };
2285
- break;
2286
- }
2287
- default: {
2288
- core.assertExhaustive(action);
2289
- }
2290
- }
2291
- const response = await zodfetch(core.KeyValueStoreResponseBodySchema, STORE_URL, requestInit);
2292
- return response;
2293
- }, "#queryKeyValueStore");
2294
- _apiKey = new WeakSet();
2295
- apiKey_fn = /* @__PURE__ */ __name(async function() {
2296
- const apiKey = getApiKey(__privateGet(this, _options).apiKey);
2297
- if (apiKey.status === "invalid") {
2298
- throw new Error("Invalid API key");
2299
- } else if (apiKey.status === "missing") {
2300
- throw new Error("Missing API key");
2301
- }
2302
- return apiKey.apiKey;
2303
- }, "#apiKey");
2304
- __name(_ApiClient, "ApiClient");
2305
- var ApiClient = _ApiClient;
2306
- function getApiKey(key) {
2307
- const apiKey = key ?? node_process.env.TRIGGER_API_KEY;
2308
- if (!apiKey) {
2309
- return {
2310
- status: "missing"
2311
- };
2312
- }
2313
- const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);
2314
- if (!isValid) {
2315
- return {
2316
- status: "invalid",
2317
- apiKey
2318
- };
2319
- }
2320
- return {
2321
- status: "valid",
2322
- apiKey
2323
- };
2324
- }
2325
- __name(getApiKey, "getApiKey");
2326
- async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount = 0) {
2327
- const response = await fetch(url, requestInitWithCache(requestInit));
2328
- if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2329
- return;
2330
- }
2331
- if (response.status >= 400 && response.status < 500) {
2332
- const body = await response.json();
2333
- throw new Error(body.error);
2334
- }
2335
- if (response.status >= 500 && retryCount < 6) {
2336
- const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2337
- await new Promise((resolve) => setTimeout(resolve, delay));
2338
- return zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount + 1);
2339
- }
2340
- if (response.status !== 200) {
2341
- throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2342
- }
2343
- const jsonBody = await response.json();
2344
- const version2 = response.headers.get("trigger-version");
2345
- if (!version2) {
2346
- return {
2347
- version: "unversioned",
2348
- body: unversionedSchema.parse(jsonBody)
2349
- };
2350
- }
2351
- const versionedSchema = versionedSchemaMap[version2];
2352
- if (!versionedSchema) {
2353
- throw new Error(`Unknown version ${version2}`);
2354
- }
2355
- return {
2356
- version: version2,
2357
- body: versionedSchema.parse(jsonBody)
2358
- };
2359
- }
2360
- __name(zodfetchWithVersions, "zodfetchWithVersions");
2361
- function requestInitWithCache(requestInit) {
2362
- try {
2363
- const withCache = {
2364
- ...requestInit,
2365
- cache: "no-cache"
2366
- };
2367
- const _ = new Request("http://localhost", withCache);
2368
- return withCache;
2369
- } catch (error) {
2370
- return requestInit ?? {};
2371
- }
2372
- }
2373
- __name(requestInitWithCache, "requestInitWithCache");
2374
- async function fetchHead(url, requestInitWithoutMethod, retryCount = 0) {
2375
- const requestInit = {
2376
- ...requestInitWithoutMethod,
2377
- method: "HEAD"
2378
- };
2379
- const response = await fetch(url, requestInitWithCache(requestInit));
2380
- if (response.status >= 500 && retryCount < 6) {
2381
- const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2382
- await new Promise((resolve) => setTimeout(resolve, delay));
2383
- return fetchHead(url, requestInitWithoutMethod, retryCount + 1);
2384
- }
2385
- return response;
2386
- }
2387
- __name(fetchHead, "fetchHead");
2388
- async function zodfetch(schema, url, requestInit, options, retryCount = 0) {
2389
- const response = await fetch(url, requestInitWithCache(requestInit));
2390
- if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2391
- return;
2392
- }
2393
- if (response.status >= 400 && response.status < 500) {
2394
- const body = await response.json();
2395
- throw new Error(body.error);
2396
- }
2397
- if (response.status >= 500 && retryCount < 6) {
2398
- const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2399
- await new Promise((resolve) => setTimeout(resolve, delay));
2400
- return zodfetch(schema, url, requestInit, options, retryCount + 1);
2401
- }
2402
- if (response.status !== 200) {
2403
- throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2404
- }
2405
- const jsonBody = await response.json();
2406
- return schema.parse(jsonBody);
2407
- }
2408
- __name(zodfetch, "zodfetch");
2409
- function exponentialBackoff(retryCount, exponential, minDelay, maxDelay, jitter) {
2410
- const delay = Math.min(Math.pow(exponential, retryCount) * minDelay, maxDelay);
2411
- const jitterValue = Math.random() * jitter;
2412
- return delay + jitterValue;
2413
- }
2414
- __name(exponentialBackoff, "exponentialBackoff");
2415
-
2416
- // src/concurrencyLimit.ts
2417
- var _ConcurrencyLimit = class _ConcurrencyLimit {
2418
- constructor(options) {
2419
- this.options = options;
2420
- }
2421
- get id() {
2422
- return this.options.id;
2423
- }
2424
- get limit() {
2425
- return this.options.limit;
2426
- }
2427
- };
2428
- __name(_ConcurrencyLimit, "ConcurrencyLimit");
2429
- var ConcurrencyLimit = _ConcurrencyLimit;
2430
-
2431
- // src/utils/formatSchemaErrors.ts
2432
- function formatSchemaErrors(errors) {
2433
- return errors.map((error) => {
2434
- const { path, message } = error;
2435
- return {
2436
- path: path.map(String),
2437
- message
2438
- };
2439
- });
2440
- }
2441
- __name(formatSchemaErrors, "formatSchemaErrors");
2442
-
2443
- // src/httpEndpoint.ts
2444
- var _HttpEndpoint = class _HttpEndpoint {
2445
- constructor(options) {
2446
- this.options = options;
2447
- }
2448
- get id() {
2449
- return this.options.id;
2450
- }
2451
- onRequest(options) {
2452
- return new HttpTrigger({
2453
- endpointId: this.id,
2454
- event: this.options.event,
2455
- filter: options?.filter,
2456
- verify: this.options.verify
2457
- });
2458
- }
2459
- // @internal
2460
- async handleRequest(request) {
2461
- if (!this.options.respondWith)
2462
- return;
2463
- return this.options.respondWith.handler(request, () => {
2464
- const clonedRequest = request.clone();
2465
- return this.options.verify(clonedRequest);
2466
- });
2467
- }
2468
- toJSON() {
2469
- return {
2470
- id: this.id,
2471
- icon: this.options.event.icon,
2472
- version: "1",
2473
- enabled: this.options.enabled ?? true,
2474
- event: this.options.event,
2475
- immediateResponseFilter: this.options.respondWith?.filter,
2476
- skipTriggeringRuns: this.options.respondWith?.skipTriggeringRuns,
2477
- source: this.options.event.source
2478
- };
2479
- }
2480
- };
2481
- __name(_HttpEndpoint, "HttpEndpoint");
2482
- var HttpEndpoint = _HttpEndpoint;
2483
- var _a;
2484
- var HttpTrigger = (_a = class {
2485
- constructor(options) {
2486
- this.options = options;
2487
- }
2488
- toJSON() {
2489
- return {
2490
- type: "static",
2491
- title: this.options.endpointId,
2492
- properties: this.options.event.properties,
2493
- rule: {
2494
- event: `httpendpoint.${this.options.endpointId}`,
2495
- payload: this.options.filter ?? {},
2496
- source: this.options.event.source
2497
- },
2498
- link: `http-endpoints/${this.options.endpointId}`,
2499
- help: {
2500
- noRuns: {
2501
- text: "To start triggering runs click here to setup your HTTP Endpoint with the external API service you want to receive webhooks from.",
2502
- link: `http-endpoints/${this.options.endpointId}`
2503
- }
2504
- }
2505
- };
2506
- }
2507
- get event() {
2508
- return this.options.event;
2509
- }
2510
- attachToJob(triggerClient, job) {
2511
- }
2512
- get preprocessRuns() {
2513
- return false;
2514
- }
2515
- async verifyPayload(payload) {
2516
- const clonedRequest = payload.clone();
2517
- return this.options.verify(clonedRequest);
2518
- }
2519
- }, __name(_a, "HttpTrigger"), _a);
2520
- function httpEndpoint(options) {
2521
- const id = slugifyId(options.id);
2522
- return new HttpEndpoint({
2523
- id,
2524
- enabled: options.enabled,
2525
- respondWith: options.respondWith,
2526
- verify: options.verify,
2527
- event: {
2528
- name: id,
2529
- title: options.title ?? "HTTP Trigger",
2530
- source: options.source,
2531
- icon: options.icon ?? "webhook",
2532
- properties: options.properties,
2533
- examples: options.examples ? options.examples : [
2534
- {
2535
- id: "basic-request",
2536
- name: "Basic Request",
2537
- icon: "http-post",
2538
- payload: {
2539
- url: "https://cloud.trigger.dev",
2540
- method: "POST",
2541
- headers: {
2542
- "Content-Type": "application/json"
2543
- },
2544
- rawBody: JSON.stringify({
2545
- foo: "bar"
2546
- })
2547
- }
2548
- }
2549
- ],
2550
- parsePayload: (rawPayload) => {
2551
- const result = core.RequestWithRawBodySchema.safeParse(rawPayload);
2552
- if (!result.success) {
2553
- throw new ParsedPayloadSchemaError(formatSchemaErrors(result.error.issues));
2554
- }
2555
- return new Request(new URL(result.data.url), {
2556
- method: result.data.method,
2557
- headers: result.data.headers,
2558
- body: result.data.rawBody
2559
- });
2560
- }
2561
- }
2562
- });
2563
- }
2564
- __name(httpEndpoint, "httpEndpoint");
2565
-
2566
- // src/ioWithIntegrations.ts
2567
- function createIOWithIntegrations(io, auths, integrations) {
2568
- if (!integrations) {
2569
- return io;
2570
- }
2571
- const connections = Object.entries(integrations).reduce((acc, [connectionKey, integration]) => {
2572
- let auth = auths?.[connectionKey];
2573
- acc[connectionKey] = {
2574
- integration,
2575
- auth
2576
- };
2577
- return acc;
2578
- }, {});
2579
- return new Proxy(io, {
2580
- get(target, prop, receiver) {
2581
- if (prop === "__io") {
2582
- return io;
2583
- }
2584
- if (typeof prop === "string" && prop in connections) {
2585
- const { integration, auth } = connections[prop];
2586
- return integration.cloneForRun(io, prop, auth);
2587
- }
2588
- const value = Reflect.get(target, prop, receiver);
2589
- return typeof value == "function" ? value.bind(target) : value;
2590
- }
2591
- });
2592
- }
2593
- __name(createIOWithIntegrations, "createIOWithIntegrations");
2594
- var _client, _options2;
2595
- var _DynamicTrigger = class _DynamicTrigger {
2596
- /** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime.
2597
- * @param client The `TriggerClient` instance to use for registering the trigger.
2598
- * @param options The options for the dynamic trigger.
2599
- * */
2600
- constructor(client, options) {
2601
- __privateAdd(this, _client, void 0);
2602
- __privateAdd(this, _options2, void 0);
2603
- __privateSet(this, _client, client);
2604
- __privateSet(this, _options2, options);
2605
- this.source = options.source;
2606
- client.attachDynamicTrigger(this);
2607
- }
2608
- toJSON() {
2609
- return {
2610
- type: "dynamic",
2611
- id: __privateGet(this, _options2).id
2612
- };
2613
- }
2614
- get id() {
2615
- return __privateGet(this, _options2).id;
2616
- }
2617
- get event() {
2618
- return __privateGet(this, _options2).event;
2619
- }
2620
- // @internal
2621
- registeredTriggerForParams(params, options = {}) {
2622
- const key = slugifyId(this.source.key(params));
2623
- return {
2624
- rule: {
2625
- event: this.event.name,
2626
- source: this.event.source,
2627
- payload: core.deepMergeFilters(this.source.filter(params), this.event.filter ?? {}, options.filter ?? {})
2628
- },
2629
- source: {
2630
- version: "2",
2631
- key,
2632
- channel: this.source.channel,
2633
- params,
2634
- //todo add other options here
2635
- options: {
2636
- event: typeof this.event.name === "string" ? [
2637
- this.event.name
2638
- ] : this.event.name
2639
- },
2640
- integration: {
2641
- id: this.source.integration.id,
2642
- metadata: this.source.integration.metadata,
2643
- authSource: this.source.integration.authSource
2644
- }
2645
- },
2646
- accountId: options.accountId
2647
- };
2648
- }
2649
- /** Use this method to register a new configuration with the DynamicTrigger.
2650
- * @param key The key for the configuration. This will be used to identify the configuration when it is triggered.
2651
- * @param params The params for the configuration.
2652
- * @param options Options for the configuration.
2653
- * @param options.accountId The accountId to associate with the configuration.
2654
- * @param options.filter The filter to use for the configuration.
2655
- *
2656
- */
2657
- async register(key, params, options = {}) {
2658
- const runStore = runLocalStorage.getStore();
2659
- if (!runStore) {
2660
- return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options));
2661
- }
2662
- const { io } = runStore;
2663
- return await io.runTask([
2664
- key,
2665
- "register"
2666
- ], async (task) => {
2667
- return __privateGet(this, _client).registerTrigger(this.id, key, this.registeredTriggerForParams(params, options), task.idempotencyKey);
2668
- }, {
2669
- name: "Register Dynamic Trigger",
2670
- properties: [
2671
- {
2672
- label: "Dynamic Trigger ID",
2673
- text: this.id
2674
- },
2675
- {
2676
- label: "ID",
2677
- text: key
2678
- }
2679
- ],
2680
- params
2681
- });
2682
- }
2683
- attachToJob(triggerClient, job) {
2684
- triggerClient.attachJobToDynamicTrigger(job, this);
2685
- }
2686
- get preprocessRuns() {
2687
- return true;
2688
- }
2689
- async verifyPayload(payload) {
2690
- return {
2691
- success: true
2692
- };
2693
- }
2694
- };
2695
- _client = new WeakMap();
2696
- _options2 = new WeakMap();
2697
- __name(_DynamicTrigger, "DynamicTrigger");
2698
- var DynamicTrigger = _DynamicTrigger;
2699
- var _options3;
2700
- var _EventTrigger = class _EventTrigger {
2701
- constructor(options) {
2702
- __privateAdd(this, _options3, void 0);
2703
- __privateSet(this, _options3, options);
2704
- }
2705
- toJSON() {
2706
- return {
2707
- type: "static",
2708
- title: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.title,
2709
- rule: {
2710
- event: __privateGet(this, _options3).name ?? __privateGet(this, _options3).event.name,
2711
- source: __privateGet(this, _options3).source ?? "trigger.dev",
2712
- payload: core.deepMergeFilters(__privateGet(this, _options3).filter ?? {}, __privateGet(this, _options3).event.filter ?? {})
2713
- }
2714
- };
2715
- }
2716
- get event() {
2717
- return __privateGet(this, _options3).event;
2718
- }
2719
- attachToJob(triggerClient, job) {
2720
- }
2721
- get preprocessRuns() {
2722
- return false;
2723
- }
2724
- async verifyPayload(payload) {
2725
- if (__privateGet(this, _options3).verify) {
2726
- if (payload instanceof Request) {
2727
- const clonedRequest = payload.clone();
2728
- return __privateGet(this, _options3).verify(clonedRequest);
2729
- }
2730
- }
2731
- return {
2732
- success: true
2733
- };
2734
- }
2735
- };
2736
- _options3 = new WeakMap();
2737
- __name(_EventTrigger, "EventTrigger");
2738
- var EventTrigger = _EventTrigger;
2739
- function eventTrigger(options) {
2740
- return new EventTrigger({
2741
- name: options.name,
2742
- filter: options.filter,
2743
- source: options.source,
2744
- event: {
2745
- name: options.name,
2746
- title: "Event",
2747
- source: options.source ?? "trigger.dev",
2748
- icon: "custom-event",
2749
- examples: options.examples,
2750
- parsePayload: (rawPayload) => {
2751
- if (options.schema) {
2752
- const results = options.schema.safeParse(rawPayload);
2753
- if (!results.success) {
2754
- throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
2755
- }
2756
- return results.data;
2757
- }
2758
- return rawPayload;
2759
- }
2760
- }
2761
- });
2762
- }
2763
- __name(eventTrigger, "eventTrigger");
2764
- var examples = [
2765
- {
2766
- id: "now",
2767
- name: "Now",
2768
- icon: "clock",
2769
- payload: {
2770
- ts: core.currentDate.marker,
2771
- lastTimestamp: core.currentDate.marker
2772
- }
2773
- }
2774
- ];
2775
- var _IntervalTrigger = class _IntervalTrigger {
2776
- constructor(options) {
2777
- this.options = options;
2778
- }
2779
- get event() {
2780
- return {
2781
- name: "trigger.scheduled",
2782
- title: "Schedule",
2783
- source: "trigger.dev",
2784
- icon: "schedule-interval",
2785
- examples,
2786
- parsePayload: core.ScheduledPayloadSchema.parse,
2787
- properties: [
2788
- {
2789
- label: "Interval",
2790
- text: `${this.options.seconds}s`
2791
- }
2792
- ]
2793
- };
2794
- }
2795
- attachToJob(triggerClient, job) {
2796
- }
2797
- get preprocessRuns() {
2798
- return false;
2799
- }
2800
- async verifyPayload(payload) {
2801
- return {
2802
- success: true
2803
- };
2804
- }
2805
- toJSON() {
2806
- return {
2807
- type: "scheduled",
2808
- schedule: {
2809
- type: "interval",
2810
- options: {
2811
- seconds: this.options.seconds
2812
- }
2813
- }
2814
- };
2815
- }
2816
- };
2817
- __name(_IntervalTrigger, "IntervalTrigger");
2818
- var IntervalTrigger = _IntervalTrigger;
2819
- function intervalTrigger(options) {
2820
- return new IntervalTrigger(options);
2821
- }
2822
- __name(intervalTrigger, "intervalTrigger");
2823
- var _CronTrigger = class _CronTrigger {
2824
- constructor(options) {
2825
- this.options = options;
2826
- }
2827
- get event() {
2828
- const humanReadable = cronstrue__default.default.toString(this.options.cron, {
2829
- throwExceptionOnParseError: false
2830
- }).concat(" (UTC)");
2831
- return {
2832
- name: "trigger.scheduled",
2833
- title: "Cron Schedule",
2834
- source: "trigger.dev",
2835
- icon: "schedule-cron",
2836
- examples,
2837
- parsePayload: core.ScheduledPayloadSchema.parse,
2838
- properties: [
2839
- {
2840
- label: "cron",
2841
- text: this.options.cron
2842
- },
2843
- {
2844
- label: "Schedule",
2845
- text: humanReadable
2846
- }
2847
- ]
2848
- };
2849
- }
2850
- attachToJob(triggerClient, job) {
2851
- }
2852
- get preprocessRuns() {
2853
- return false;
2854
- }
2855
- async verifyPayload(payload) {
2856
- return {
2857
- success: true
2858
- };
2859
- }
2860
- toJSON() {
2861
- return {
2862
- type: "scheduled",
2863
- schedule: {
2864
- type: "cron",
2865
- options: {
2866
- cron: this.options.cron
2867
- }
2868
- }
2869
- };
2870
- }
2871
- };
2872
- __name(_CronTrigger, "CronTrigger");
2873
- var CronTrigger = _CronTrigger;
2874
- function cronTrigger(options) {
2875
- return new CronTrigger(options);
2876
- }
2877
- __name(cronTrigger, "cronTrigger");
2878
- var _DynamicSchedule = class _DynamicSchedule {
2879
- /**
2880
- * @param client The `TriggerClient` instance to use for registering the trigger.
2881
- * @param options The options for the schedule.
2882
- */
2883
- constructor(client, options) {
2884
- this.client = client;
2885
- this.options = options;
2886
- client.attachDynamicSchedule(this.options.id);
2887
- }
2888
- get id() {
2889
- return this.options.id;
2890
- }
2891
- get event() {
2892
- return {
2893
- name: "trigger.scheduled",
2894
- title: "Dynamic Schedule",
2895
- source: "trigger.dev",
2896
- icon: "schedule-dynamic",
2897
- examples,
2898
- parsePayload: core.ScheduledPayloadSchema.parse
2899
- };
2900
- }
2901
- async register(key, metadata) {
2902
- const runStore = runLocalStorage.getStore();
2903
- if (!runStore) {
2904
- return this.client.registerSchedule(this.id, key, metadata);
2905
- }
2906
- const { io } = runStore;
2907
- return await io.runTask([
2908
- key,
2909
- "register"
2910
- ], async (task) => {
2911
- return this.client.registerSchedule(this.id, key, metadata);
2912
- }, {
2913
- name: "Register Schedule",
2914
- icon: metadata.type === "cron" ? "schedule-cron" : "schedule-interval",
2915
- properties: [
2916
- {
2917
- label: "Dynamic Schedule",
2918
- text: this.id
2919
- },
2920
- {
2921
- label: "Schedule ID",
2922
- text: key
2923
- }
2924
- ],
2925
- params: metadata
2926
- });
2927
- }
2928
- async unregister(key) {
2929
- const runStore = runLocalStorage.getStore();
2930
- if (!runStore) {
2931
- return this.client.unregisterSchedule(this.id, key);
2932
- }
2933
- const { io } = runStore;
2934
- return await io.runTask([
2935
- key,
2936
- "unregister"
2937
- ], async (task) => {
2938
- return this.client.unregisterSchedule(this.id, key);
2939
- }, {
2940
- name: "Unregister Schedule",
2941
- icon: "schedule",
2942
- properties: [
2943
- {
2944
- label: "Dynamic Schedule",
2945
- text: this.id
2946
- },
2947
- {
2948
- label: "Schedule ID",
2949
- text: key
2950
- }
2951
- ]
2952
- });
2953
- }
2954
- attachToJob(triggerClient, job) {
2955
- triggerClient.attachDynamicScheduleToJob(this.options.id, job);
2956
- }
2957
- get preprocessRuns() {
2958
- return false;
2959
- }
2960
- async verifyPayload(payload) {
2961
- return {
2962
- success: true
2963
- };
2964
- }
2965
- toJSON() {
2966
- return {
2967
- type: "dynamic",
2968
- id: this.options.id
2969
- };
2970
- }
2971
- };
2972
- __name(_DynamicSchedule, "DynamicSchedule");
2973
- var DynamicSchedule = _DynamicSchedule;
2974
-
2975
- // src/triggerClient.ts
2976
- var registerWebhookEvent = /* @__PURE__ */ __name((key) => ({
2977
- name: `${core.REGISTER_WEBHOOK}.${key}`,
2978
- title: "Register Webhook",
2979
- source: "internal",
2980
- icon: "webhook",
2981
- parsePayload: core.RegisterWebhookPayloadSchema.parse
2982
- }), "registerWebhookEvent");
2983
- var registerSourceEvent = {
2984
- name: core.REGISTER_SOURCE_EVENT_V2,
2985
- title: "Register Source",
2986
- source: "internal",
2987
- icon: "register-source",
2988
- parsePayload: core.RegisterSourceEventSchemaV2.parse
2989
- };
2990
- var _options4, _registeredJobs, _registeredSources, _registeredWebhooks, _registeredHttpSourceHandlers, _registeredWebhookSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _registeredHttpEndpoints, _authResolvers, _envStore, _eventEmitter, _client2, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn, _handleHttpEndpointRequestForResponse, handleHttpEndpointRequestForResponse_fn, _handleWebhookRequest, handleWebhookRequest_fn, _resolveConnections, resolveConnections_fn, _resolveConnection, resolveConnection_fn, _buildJobsIndex, buildJobsIndex_fn, _buildJobIndex, buildJobIndex_fn, _buildJobIntegrations, buildJobIntegrations_fn, _buildJobIntegration, buildJobIntegration_fn, _logIOStats, logIOStats_fn, _standardResponseHeaders, standardResponseHeaders_fn, _serializeRunMetadata, serializeRunMetadata_fn, _deliverSuccessfulRunNotification, deliverSuccessfulRunNotification_fn, _deliverFailedRunNotification, deliverFailedRunNotification_fn;
2991
- var _TriggerClient = class _TriggerClient {
2992
- constructor(options) {
2993
- __privateAdd(this, _preprocessRun);
2994
- __privateAdd(this, _executeJob);
2995
- __privateAdd(this, _convertErrorToExecutionResponse);
2996
- __privateAdd(this, _createRunContext);
2997
- __privateAdd(this, _createPreprocessRunContext);
2998
- __privateAdd(this, _handleHttpSourceRequest);
2999
- __privateAdd(this, _handleHttpEndpointRequestForResponse);
3000
- __privateAdd(this, _handleWebhookRequest);
3001
- __privateAdd(this, _resolveConnections);
3002
- __privateAdd(this, _resolveConnection);
3003
- __privateAdd(this, _buildJobsIndex);
3004
- __privateAdd(this, _buildJobIndex);
3005
- __privateAdd(this, _buildJobIntegrations);
3006
- __privateAdd(this, _buildJobIntegration);
3007
- __privateAdd(this, _logIOStats);
3008
- __privateAdd(this, _standardResponseHeaders);
3009
- __privateAdd(this, _serializeRunMetadata);
3010
- __privateAdd(this, _deliverSuccessfulRunNotification);
3011
- __privateAdd(this, _deliverFailedRunNotification);
3012
- __privateAdd(this, _options4, void 0);
3013
- __privateAdd(this, _registeredJobs, {});
3014
- __privateAdd(this, _registeredSources, {});
3015
- __privateAdd(this, _registeredWebhooks, {});
3016
- __privateAdd(this, _registeredHttpSourceHandlers, {});
3017
- __privateAdd(this, _registeredWebhookSourceHandlers, {});
3018
- __privateAdd(this, _registeredDynamicTriggers, {});
3019
- __privateAdd(this, _jobMetadataByDynamicTriggers, {});
3020
- __privateAdd(this, _registeredSchedules, {});
3021
- __privateAdd(this, _registeredHttpEndpoints, {});
3022
- __privateAdd(this, _authResolvers, {});
3023
- __privateAdd(this, _envStore, void 0);
3024
- __privateAdd(this, _eventEmitter, new EventEmitter__default.default());
3025
- __privateAdd(this, _client2, void 0);
3026
- __privateAdd(this, _internalLogger, void 0);
3027
- __publicField(this, "on", __privateGet(this, _eventEmitter).on.bind(__privateGet(this, _eventEmitter)));
3028
- this.id = options.id;
3029
- __privateSet(this, _options4, options);
3030
- __privateSet(this, _client2, new ApiClient(__privateGet(this, _options4)));
3031
- __privateSet(this, _internalLogger, new coreBackend.Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log", [
3032
- "output",
3033
- "noopTasksSet"
3034
- ]));
3035
- __privateSet(this, _envStore, new KeyValueStore(__privateGet(this, _client2)));
3036
- }
3037
- async handleRequest(request, timeOrigin = performance.now()) {
3038
- __privateGet(this, _internalLogger).debug("handling request", {
3039
- url: request.url,
3040
- headers: Object.fromEntries(request.headers.entries()),
3041
- method: request.method
3042
- });
3043
- const apiKey = request.headers.get("x-trigger-api-key");
3044
- const triggerVersion = request.headers.get("x-trigger-version");
3045
- const authorization = this.authorized(apiKey);
3046
- switch (authorization) {
3047
- case "authorized": {
3048
- break;
3049
- }
3050
- case "missing-client": {
3051
- return {
3052
- status: 401,
3053
- body: {
3054
- message: "Unauthorized: client missing apiKey"
3055
- },
3056
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3057
- };
3058
- }
3059
- case "missing-header": {
3060
- return {
3061
- status: 401,
3062
- body: {
3063
- message: "Unauthorized: missing x-trigger-api-key header"
3064
- },
3065
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3066
- };
3067
- }
3068
- case "unauthorized": {
3069
- return {
3070
- status: 401,
3071
- body: {
3072
- message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`
3073
- },
3074
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3075
- };
3076
- }
3077
- }
3078
- if (request.method !== "POST") {
3079
- return {
3080
- status: 405,
3081
- body: {
3082
- message: "Method not allowed (only POST is allowed)"
3083
- },
3084
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3085
- };
3086
- }
3087
- const action = request.headers.get("x-trigger-action");
3088
- if (!action) {
3089
- return {
3090
- status: 400,
3091
- body: {
3092
- message: "Missing x-trigger-action header"
3093
- },
3094
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3095
- };
3096
- }
3097
- switch (action) {
3098
- case "PING": {
3099
- const endpointId = request.headers.get("x-trigger-endpoint-id");
3100
- if (!endpointId) {
3101
- return {
3102
- status: 200,
3103
- body: {
3104
- ok: false,
3105
- error: "Missing endpoint ID"
3106
- },
3107
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3108
- };
3109
- }
3110
- if (this.id !== endpointId) {
3111
- return {
3112
- status: 200,
3113
- body: {
3114
- ok: false,
3115
- error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`
3116
- },
3117
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3118
- };
3119
- }
3120
- return {
3121
- status: 200,
3122
- body: {
3123
- ok: true
3124
- },
3125
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3126
- };
3127
- }
3128
- case "INDEX_ENDPOINT": {
3129
- const body = {
3130
- jobs: __privateMethod(this, _buildJobsIndex, buildJobsIndex_fn).call(this),
3131
- sources: Object.values(__privateGet(this, _registeredSources)),
3132
- webhooks: Object.values(__privateGet(this, _registeredWebhooks)),
3133
- dynamicTriggers: Object.values(__privateGet(this, _registeredDynamicTriggers)).map((trigger) => ({
3134
- id: trigger.id,
3135
- jobs: __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] ?? [],
3136
- registerSourceJob: {
3137
- id: dynamicTriggerRegisterSourceJobId(trigger.id),
3138
- version: trigger.source.version
3139
- }
3140
- })),
3141
- dynamicSchedules: Object.entries(__privateGet(this, _registeredSchedules)).map(([id, jobs]) => ({
3142
- id,
3143
- jobs
3144
- })),
3145
- httpEndpoints: Object.entries(__privateGet(this, _registeredHttpEndpoints)).map(([id, endpoint]) => endpoint.toJSON())
3146
- };
3147
- return {
3148
- status: 200,
3149
- body,
3150
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3151
- };
3152
- }
3153
- case "INITIALIZE_TRIGGER": {
3154
- const json = await request.json();
3155
- const body = core.InitializeTriggerBodySchema.safeParse(json);
3156
- if (!body.success) {
3157
- return {
3158
- status: 400,
3159
- body: {
3160
- message: "Invalid trigger body"
3161
- }
3162
- };
3163
- }
3164
- const dynamicTrigger = __privateGet(this, _registeredDynamicTriggers)[body.data.id];
3165
- if (!dynamicTrigger) {
3166
- return {
3167
- status: 404,
3168
- body: {
3169
- message: "Dynamic trigger not found"
3170
- }
3171
- };
3172
- }
3173
- return {
3174
- status: 200,
3175
- body: dynamicTrigger.registeredTriggerForParams(body.data.params),
3176
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3177
- };
3178
- }
3179
- case "EXECUTE_JOB": {
3180
- const json = await request.json();
3181
- const execution = core.RunJobBodySchema.safeParse(json);
3182
- if (!execution.success) {
3183
- return {
3184
- status: 400,
3185
- body: {
3186
- message: "Invalid execution"
3187
- }
3188
- };
3189
- }
3190
- const job = __privateGet(this, _registeredJobs)[execution.data.job.id];
3191
- if (!job) {
3192
- return {
3193
- status: 404,
3194
- body: {
3195
- message: "Job not found"
3196
- }
3197
- };
3198
- }
3199
- const results = await __privateMethod(this, _executeJob, executeJob_fn).call(this, execution.data, job, timeOrigin, triggerVersion);
3200
- __privateGet(this, _internalLogger).debug("executed job", {
3201
- results,
3202
- job: job.id,
3203
- version: job.version,
3204
- triggerVersion
3205
- });
3206
- const standardHeaders = __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin);
3207
- standardHeaders["x-trigger-run-metadata"] = __privateMethod(this, _serializeRunMetadata, serializeRunMetadata_fn).call(this, job);
3208
- return {
3209
- status: 200,
3210
- body: results,
3211
- headers: standardHeaders
3212
- };
3213
- }
3214
- case "PREPROCESS_RUN": {
3215
- const json = await request.json();
3216
- const body = core.PreprocessRunBodySchema.safeParse(json);
3217
- if (!body.success) {
3218
- return {
3219
- status: 400,
3220
- body: {
3221
- message: "Invalid body"
3222
- }
3223
- };
3224
- }
3225
- const job = __privateGet(this, _registeredJobs)[body.data.job.id];
3226
- if (!job) {
3227
- return {
3228
- status: 404,
3229
- body: {
3230
- message: "Job not found"
3231
- }
3232
- };
3233
- }
3234
- const results = await __privateMethod(this, _preprocessRun, preprocessRun_fn).call(this, body.data, job);
3235
- return {
3236
- status: 200,
3237
- body: {
3238
- abort: results.abort,
3239
- properties: results.properties
3240
- },
3241
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3242
- };
3243
- }
3244
- case "DELIVER_HTTP_SOURCE_REQUEST": {
3245
- const headers = core.HttpSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
3246
- if (!headers.success) {
3247
- return {
3248
- status: 400,
3249
- body: {
3250
- message: "Invalid headers"
3251
- }
3252
- };
3253
- }
3254
- const sourceRequestNeedsBody = headers.data["x-ts-http-method"] !== "GET";
3255
- const sourceRequestInit = {
3256
- method: headers.data["x-ts-http-method"],
3257
- headers: headers.data["x-ts-http-headers"],
3258
- body: sourceRequestNeedsBody ? request.body : void 0
3259
- };
3260
- if (sourceRequestNeedsBody) {
3261
- try {
3262
- sourceRequestInit.duplex = "half";
3263
- } catch (error) {
3264
- }
3265
- }
3266
- const sourceRequest = new Request(headers.data["x-ts-http-url"], sourceRequestInit);
3267
- const key = headers.data["x-ts-key"];
3268
- const dynamicId = headers.data["x-ts-dynamic-id"];
3269
- const secret = headers.data["x-ts-secret"];
3270
- const params = headers.data["x-ts-params"];
3271
- const data = headers.data["x-ts-data"];
3272
- const auth = headers.data["x-ts-auth"];
3273
- const inputMetadata = headers.data["x-ts-metadata"];
3274
- const source = {
3275
- key,
3276
- dynamicId,
3277
- secret,
3278
- params,
3279
- data,
3280
- auth,
3281
- metadata: inputMetadata
3282
- };
3283
- const { response, events, metadata } = await __privateMethod(this, _handleHttpSourceRequest, handleHttpSourceRequest_fn).call(this, source, sourceRequest);
3284
- return {
3285
- status: 200,
3286
- body: {
3287
- events,
3288
- response,
3289
- metadata
3290
- },
3291
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3292
- };
3293
- }
3294
- case "DELIVER_HTTP_ENDPOINT_REQUEST_FOR_RESPONSE": {
3295
- const headers = core.HttpEndpointRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
3296
- if (!headers.success) {
3297
- return {
3298
- status: 400,
3299
- body: {
3300
- message: "Invalid headers"
3301
- }
3302
- };
3303
- }
3304
- const sourceRequestNeedsBody = headers.data["x-ts-http-method"] !== "GET";
3305
- const sourceRequestInit = {
3306
- method: headers.data["x-ts-http-method"],
3307
- headers: headers.data["x-ts-http-headers"],
3308
- body: sourceRequestNeedsBody ? request.body : void 0
3309
- };
3310
- if (sourceRequestNeedsBody) {
3311
- try {
3312
- sourceRequestInit.duplex = "half";
3313
- } catch (error) {
3314
- }
3315
- }
3316
- const sourceRequest = new Request(headers.data["x-ts-http-url"], sourceRequestInit);
3317
- const key = headers.data["x-ts-key"];
3318
- const { response } = await __privateMethod(this, _handleHttpEndpointRequestForResponse, handleHttpEndpointRequestForResponse_fn).call(this, {
3319
- key
3320
- }, sourceRequest);
3321
- return {
3322
- status: 200,
3323
- body: response,
3324
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3325
- };
3326
- }
3327
- case "DELIVER_WEBHOOK_REQUEST": {
3328
- const headers = core.WebhookSourceRequestHeadersSchema.safeParse(Object.fromEntries(request.headers.entries()));
3329
- if (!headers.success) {
3330
- return {
3331
- status: 400,
3332
- body: {
3333
- message: "Invalid headers"
3334
- }
3335
- };
3336
- }
3337
- const sourceRequestNeedsBody = headers.data["x-ts-http-method"] !== "GET";
3338
- const sourceRequestInit = {
3339
- method: headers.data["x-ts-http-method"],
3340
- headers: headers.data["x-ts-http-headers"],
3341
- body: sourceRequestNeedsBody ? request.body : void 0
3342
- };
3343
- if (sourceRequestNeedsBody) {
3344
- try {
3345
- sourceRequestInit.duplex = "half";
3346
- } catch (error2) {
3347
- }
3348
- }
3349
- const webhookRequest = new Request(headers.data["x-ts-http-url"], sourceRequestInit);
3350
- const key = headers.data["x-ts-key"];
3351
- const secret = headers.data["x-ts-secret"];
3352
- const params = headers.data["x-ts-params"];
3353
- const ctx = {
3354
- key,
3355
- secret,
3356
- params
3357
- };
3358
- const { response, verified, error } = await __privateMethod(this, _handleWebhookRequest, handleWebhookRequest_fn).call(this, webhookRequest, ctx);
3359
- return {
3360
- status: 200,
3361
- body: {
3362
- response,
3363
- verified,
3364
- error
3365
- },
3366
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3367
- };
3368
- }
3369
- case "VALIDATE": {
3370
- return {
3371
- status: 200,
3372
- body: {
3373
- ok: true,
3374
- endpointId: this.id
3375
- },
3376
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3377
- };
3378
- }
3379
- case "PROBE_EXECUTION_TIMEOUT": {
3380
- const json = await request.json();
3381
- const timeout = json?.timeout ?? 15 * 60 * 1e3;
3382
- await new Promise((resolve) => setTimeout(resolve, timeout));
3383
- return {
3384
- status: 200,
3385
- body: {
3386
- ok: true
3387
- },
3388
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3389
- };
3390
- }
3391
- case "RUN_NOTIFICATION": {
3392
- const rawJson = await request.json();
3393
- const runNotification = rawJson;
3394
- if (runNotification.ok) {
3395
- await __privateMethod(this, _deliverSuccessfulRunNotification, deliverSuccessfulRunNotification_fn).call(this, runNotification);
3396
- } else {
3397
- await __privateMethod(this, _deliverFailedRunNotification, deliverFailedRunNotification_fn).call(this, runNotification);
3398
- }
3399
- return {
3400
- status: 200,
3401
- body: {
3402
- ok: true
3403
- },
3404
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3405
- };
3406
- }
3407
- }
3408
- return {
3409
- status: 405,
3410
- body: {
3411
- message: "Method not allowed"
3412
- },
3413
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
3414
- };
3415
- }
3416
- defineJob(options) {
3417
- const existingRegisteredJob = __privateGet(this, _registeredJobs)[options.id];
3418
- if (existingRegisteredJob && options.__internal !== true) {
3419
- console.warn(`[@trigger.dev/sdk] Warning: The Job "${existingRegisteredJob.id}" you're attempting to define has already been defined. Please assign a different ID to the job.`);
3420
- }
3421
- const job = new Job(options);
3422
- this.attach(job);
3423
- return job;
3424
- }
3425
- defineAuthResolver(integration, resolver) {
3426
- __privateGet(this, _authResolvers)[integration.id] = resolver;
3427
- return this;
3428
- }
3429
- defineDynamicSchedule(options) {
3430
- return new DynamicSchedule(this, options);
3431
- }
3432
- defineDynamicTrigger(options) {
3433
- return new DynamicTrigger(this, options);
3434
- }
3435
- /**
3436
- * An [HTTP endpoint](https://trigger.dev/docs/documentation/concepts/http-endpoints) allows you to create a [HTTP Trigger](https://trigger.dev/docs/documentation/concepts/triggers/http), which means you can trigger your Jobs from any webhooks.
3437
- * @param options The Endpoint options
3438
- * @returns An HTTP Endpoint, that can be used to create an HTTP Trigger.
3439
- * @link https://trigger.dev/docs/documentation/concepts/http-endpoints
3440
- */
3441
- defineHttpEndpoint(options, suppressWarnings = false) {
3442
- const existingHttpEndpoint = __privateGet(this, _registeredHttpEndpoints)[options.id];
3443
- if (!suppressWarnings && existingHttpEndpoint) {
3444
- console.warn(`[@trigger.dev/sdk] Warning: The HttpEndpoint "${existingHttpEndpoint.id}" you're attempting to define has already been defined. Please assign a different ID to the HttpEndpoint.`);
3445
- }
3446
- const endpoint = httpEndpoint(options);
3447
- __privateGet(this, _registeredHttpEndpoints)[endpoint.id] = endpoint;
3448
- return endpoint;
3449
- }
3450
- defineConcurrencyLimit(options) {
3451
- return new ConcurrencyLimit(options);
3452
- }
3453
- attach(job) {
3454
- __privateGet(this, _registeredJobs)[job.id] = job;
3455
- job.trigger.attachToJob(this, job);
3456
- job.client = this;
3457
- }
3458
- attachDynamicTrigger(trigger) {
3459
- __privateGet(this, _registeredDynamicTriggers)[trigger.id] = trigger;
3460
- this.defineJob({
3461
- id: dynamicTriggerRegisterSourceJobId(trigger.id),
3462
- name: `Register dynamic trigger ${trigger.id}`,
3463
- version: trigger.source.version,
3464
- trigger: new EventTrigger({
3465
- event: registerSourceEvent,
3466
- filter: {
3467
- dynamicTriggerId: [
3468
- trigger.id
3469
- ]
3470
- }
3471
- }),
3472
- integrations: {
3473
- integration: trigger.source.integration
3474
- },
3475
- run: async (event, io, ctx) => {
3476
- const updates = await trigger.source.register(event.source.params, event, io, ctx);
3477
- if (!updates) {
3478
- return;
3479
- }
3480
- return await io.updateSource("update-source", {
3481
- key: event.source.key,
3482
- ...updates
3483
- });
3484
- },
3485
- __internal: true
3486
- });
3487
- }
3488
- attachJobToDynamicTrigger(job, trigger) {
3489
- const jobs = __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] ?? [];
3490
- jobs.push({
3491
- id: job.id,
3492
- version: job.version
3493
- });
3494
- __privateGet(this, _jobMetadataByDynamicTriggers)[trigger.id] = jobs;
3495
- }
3496
- attachSource(options) {
3497
- __privateGet(this, _registeredHttpSourceHandlers)[options.key] = async (s, r) => {
3498
- return await options.source.handle(s, r, __privateGet(this, _internalLogger));
3499
- };
3500
- let registeredSource = __privateGet(this, _registeredSources)[options.key];
3501
- if (!registeredSource) {
3502
- registeredSource = {
3503
- version: "2",
3504
- channel: options.source.channel,
3505
- key: options.key,
3506
- params: options.params,
3507
- options: {},
3508
- integration: {
3509
- id: options.source.integration.id,
3510
- metadata: options.source.integration.metadata,
3511
- authSource: options.source.integration.authSource
3512
- },
3513
- registerSourceJob: {
3514
- id: options.key,
3515
- version: options.source.version
3516
- }
3517
- };
3518
- }
3519
- const newOptions = deepMergeOptions({
3520
- event: typeof options.event.name === "string" ? [
3521
- options.event.name
3522
- ] : options.event.name
3523
- }, options.options ?? {});
3524
- registeredSource.options = deepMergeOptions(registeredSource.options, newOptions);
3525
- __privateGet(this, _registeredSources)[options.key] = registeredSource;
3526
- this.defineJob({
3527
- id: options.key,
3528
- name: options.key,
3529
- version: options.source.version,
3530
- trigger: new EventTrigger({
3531
- event: registerSourceEvent,
3532
- filter: {
3533
- source: {
3534
- key: [
3535
- options.key
3536
- ]
3537
- }
3538
- }
3539
- }),
3540
- integrations: {
3541
- integration: options.source.integration
3542
- },
3543
- run: async (event, io, ctx) => {
3544
- const updates = await options.source.register(options.params, event, io, ctx);
3545
- if (!updates) {
3546
- return;
3547
- }
3548
- return await io.updateSource("update-source", {
3549
- key: options.key,
3550
- ...updates
3551
- });
3552
- },
3553
- __internal: true
3554
- });
3555
- }
3556
- attachDynamicSchedule(key) {
3557
- const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
3558
- __privateGet(this, _registeredSchedules)[key] = jobs;
3559
- }
3560
- attachDynamicScheduleToJob(key, job) {
3561
- const jobs = __privateGet(this, _registeredSchedules)[key] ?? [];
3562
- jobs.push({
3563
- id: job.id,
3564
- version: job.version
3565
- });
3566
- __privateGet(this, _registeredSchedules)[key] = jobs;
3567
- }
3568
- attachWebhook(options) {
3569
- const { source } = options;
3570
- __privateGet(this, _registeredWebhookSourceHandlers)[options.key] = {
3571
- verify: source.verify.bind(source),
3572
- generateEvents: source.generateEvents.bind(source)
3573
- };
3574
- let registeredWebhook = __privateGet(this, _registeredWebhooks)[options.key];
3575
- if (!registeredWebhook) {
3576
- registeredWebhook = {
3577
- key: options.key,
3578
- params: options.params,
3579
- config: options.config,
3580
- integration: {
3581
- id: source.integration.id,
3582
- metadata: source.integration.metadata,
3583
- authSource: source.integration.authSource
3584
- },
3585
- httpEndpoint: {
3586
- id: options.key
3587
- }
3588
- };
3589
- } else {
3590
- registeredWebhook.config = deepMergeOptions(registeredWebhook.config, options.config);
3591
- }
3592
- __privateGet(this, _registeredWebhooks)[options.key] = registeredWebhook;
3593
- this.defineJob({
3594
- id: `webhook.register.${options.key}`,
3595
- name: `webhook.register.${options.key}`,
3596
- version: source.version,
3597
- trigger: new EventTrigger({
3598
- event: registerWebhookEvent(options.key)
3599
- }),
3600
- integrations: {
3601
- integration: source.integration
3602
- },
3603
- run: async (registerPayload, io, ctx) => {
3604
- return await io.try(async () => {
3605
- __privateGet(this, _internalLogger).debug("[webhook.register] Start");
3606
- const crudOptions = {
3607
- io,
3608
- // this is just a more strongly typed payload
3609
- ctx: registerPayload
3610
- };
3611
- if (!registerPayload.active) {
3612
- __privateGet(this, _internalLogger).debug("[webhook.register] Not active, run create");
3613
- await io.try(async () => {
3614
- await source.crud.create(crudOptions);
3615
- }, async (error) => {
3616
- __privateGet(this, _internalLogger).debug("[webhook.register] Error during create, re-trying with delete first", {
3617
- error
3618
- });
3619
- await io.runTask("create-retry", async () => {
3620
- await source.crud.delete(crudOptions);
3621
- await source.crud.create(crudOptions);
3622
- });
3623
- });
3624
- return await io.updateWebhook("update-webhook-success", {
3625
- key: options.key,
3626
- active: true,
3627
- config: registerPayload.config.desired
3628
- });
3629
- }
3630
- __privateGet(this, _internalLogger).debug("[webhook.register] Already active, run update");
3631
- if (source.crud.update) {
3632
- await source.crud.update(crudOptions);
3633
- } else {
3634
- __privateGet(this, _internalLogger).debug("[webhook.register] Run delete and create instead of update");
3635
- await source.crud.delete(crudOptions);
3636
- await source.crud.create(crudOptions);
3637
- }
3638
- return await io.updateWebhook("update-webhook-success", {
3639
- key: options.key,
3640
- active: true,
3641
- config: registerPayload.config.desired
3642
- });
3643
- }, async (error) => {
3644
- __privateGet(this, _internalLogger).debug("[webhook.register] Error", {
3645
- error
3646
- });
3647
- await io.updateWebhook("update-webhook-error", {
3648
- key: options.key,
3649
- active: false
3650
- });
3651
- throw error;
3652
- });
3653
- },
3654
- __internal: true
3655
- });
3656
- }
3657
- async registerTrigger(id, key, options, idempotencyKey) {
3658
- return __privateGet(this, _client2).registerTrigger(this.id, id, key, options, idempotencyKey);
3659
- }
3660
- async getAuth(id) {
3661
- return __privateGet(this, _client2).getAuth(this.id, id);
3662
- }
3663
- /** You can call this function from anywhere in your backend to send an event. The other way to send an event is by using [`io.sendEvent()`](https://trigger.dev/docs/sdk/io/sendevent) from inside a `run()` function.
3664
- * @param event The event to send.
3665
- * @param options Options for sending the event.
3666
- * @returns A promise that resolves to the event details
3667
- */
3668
- async sendEvent(event, options) {
3669
- return __privateGet(this, _client2).sendEvent(event, options);
3670
- }
3671
- /** You can call this function from anywhere in your backend to send multiple events. The other way to send multiple events is by using [`io.sendEvents()`](https://trigger.dev/docs/sdk/io/sendevents) from inside a `run()` function.
3672
- * @param events The events to send.
3673
- * @param options Options for sending the events.
3674
- * @returns A promise that resolves to an array of event details
3675
- */
3676
- async sendEvents(events, options) {
3677
- return __privateGet(this, _client2).sendEvents(events, options);
3678
- }
3679
- async cancelEvent(eventId) {
3680
- return __privateGet(this, _client2).cancelEvent(eventId);
3681
- }
3682
- async cancelRunsForEvent(eventId) {
3683
- return __privateGet(this, _client2).cancelRunsForEvent(eventId);
3684
- }
3685
- async updateStatus(runId, id, status) {
3686
- return __privateGet(this, _client2).updateStatus(runId, id, status);
3687
- }
3688
- async registerSchedule(id, key, schedule) {
3689
- return __privateGet(this, _client2).registerSchedule(this.id, id, key, schedule);
3690
- }
3691
- async unregisterSchedule(id, key) {
3692
- return __privateGet(this, _client2).unregisterSchedule(this.id, id, key);
3693
- }
3694
- async getEvent(eventId) {
3695
- return __privateGet(this, _client2).getEvent(eventId);
3696
- }
3697
- async getRun(runId, options) {
3698
- return __privateGet(this, _client2).getRun(runId, options);
3699
- }
3700
- async cancelRun(runId) {
3701
- return __privateGet(this, _client2).cancelRun(runId);
3702
- }
3703
- async getRuns(jobSlug, options) {
3704
- return __privateGet(this, _client2).getRuns(jobSlug, options);
3705
- }
3706
- async getRunStatuses(runId) {
3707
- return __privateGet(this, _client2).getRunStatuses(runId);
3708
- }
3709
- async invokeJob(jobId, payload, options) {
3710
- return __privateGet(this, _client2).invokeJob(jobId, payload, options);
3711
- }
3712
- async cancelRunsForJob(jobId) {
3713
- return __privateGet(this, _client2).cancelRunsForJob(jobId);
3714
- }
3715
- async createEphemeralEventDispatcher(payload) {
3716
- return __privateGet(this, _client2).createEphemeralEventDispatcher(payload);
3717
- }
3718
- get store() {
3719
- return {
3720
- env: __privateGet(this, _envStore)
3721
- };
3722
- }
3723
- authorized(apiKey) {
3724
- if (typeof apiKey !== "string") {
3725
- return "missing-header";
3726
- }
3727
- const localApiKey = __privateGet(this, _options4).apiKey ?? node_process.env.TRIGGER_API_KEY;
3728
- if (!localApiKey) {
3729
- return "missing-client";
3730
- }
3731
- return apiKey === localApiKey ? "authorized" : "unauthorized";
3732
- }
3733
- apiKey() {
3734
- return __privateGet(this, _options4).apiKey ?? node_process.env.TRIGGER_API_KEY;
3735
- }
3736
- };
3737
- _options4 = new WeakMap();
3738
- _registeredJobs = new WeakMap();
3739
- _registeredSources = new WeakMap();
3740
- _registeredWebhooks = new WeakMap();
3741
- _registeredHttpSourceHandlers = new WeakMap();
3742
- _registeredWebhookSourceHandlers = new WeakMap();
3743
- _registeredDynamicTriggers = new WeakMap();
3744
- _jobMetadataByDynamicTriggers = new WeakMap();
3745
- _registeredSchedules = new WeakMap();
3746
- _registeredHttpEndpoints = new WeakMap();
3747
- _authResolvers = new WeakMap();
3748
- _envStore = new WeakMap();
3749
- _eventEmitter = new WeakMap();
3750
- _client2 = new WeakMap();
3751
- _internalLogger = new WeakMap();
3752
- _preprocessRun = new WeakSet();
3753
- preprocessRun_fn = /* @__PURE__ */ __name(async function(body, job) {
3754
- __privateMethod(this, _createPreprocessRunContext, createPreprocessRunContext_fn).call(this, body);
3755
- const parsedPayload = job.trigger.event.parsePayload(body.event.payload ?? {});
3756
- const properties = job.trigger.event.runProperties?.(parsedPayload) ?? [];
3757
- return {
3758
- abort: false,
3759
- properties
3760
- };
3761
- }, "#preprocessRun");
3762
- _executeJob = new WeakSet();
3763
- executeJob_fn = /* @__PURE__ */ __name(async function(body1, job1, timeOrigin, triggerVersion) {
3764
- __privateGet(this, _internalLogger).debug("executing job", {
3765
- execution: body1,
3766
- job: job1.id,
3767
- version: job1.version,
3768
- triggerVersion
3769
- });
3770
- const context = __privateMethod(this, _createRunContext, createRunContext_fn).call(this, body1);
3771
- const io = new IO({
3772
- id: body1.run.id,
3773
- jobId: job1.id,
3774
- cachedTasks: body1.tasks,
3775
- cachedTasksCursor: body1.cachedTaskCursor,
3776
- yieldedExecutions: body1.yieldedExecutions ?? [],
3777
- noopTasksSet: body1.noopTasksSet,
3778
- apiClient: __privateGet(this, _client2),
3779
- logger: __privateGet(this, _internalLogger),
3780
- client: this,
3781
- context,
3782
- jobLogLevel: job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info",
3783
- jobLogger: __privateGet(this, _options4).ioLogLocalEnabled ? new coreBackend.Logger(job1.id, job1.logLevel ?? __privateGet(this, _options4).logLevel ?? "info") : void 0,
3784
- serverVersion: triggerVersion,
3785
- timeOrigin,
3786
- executionTimeout: body1.runChunkExecutionLimit
3787
- });
3788
- const resolvedConnections = await __privateMethod(this, _resolveConnections, resolveConnections_fn).call(this, context, job1.options.integrations, body1.connections);
3789
- if (!resolvedConnections.ok) {
3790
- return {
3791
- status: "UNRESOLVED_AUTH_ERROR",
3792
- issues: resolvedConnections.issues
3793
- };
3794
- }
3795
- const ioWithConnections = createIOWithIntegrations(io, resolvedConnections.data, job1.options.integrations);
3796
- try {
3797
- const parsedPayload = job1.trigger.event.parsePayload(body1.event.payload ?? {});
3798
- if (!context.run.isTest) {
3799
- const verified = await job1.trigger.verifyPayload(parsedPayload);
3800
- if (!verified.success) {
3801
- return {
3802
- status: "ERROR",
3803
- error: {
3804
- message: `Payload verification failed. ${verified.reason}`
3805
- }
3806
- };
3807
- }
3808
- }
3809
- const output = await runLocalStorage.runWith({
3810
- io,
3811
- ctx: context
3812
- }, () => {
3813
- return job1.options.run(parsedPayload, ioWithConnections, context);
3814
- });
3815
- if (__privateGet(this, _options4).verbose) {
3816
- __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
3817
- }
3818
- return {
3819
- status: "SUCCESS",
3820
- output
3821
- };
3822
- } catch (error) {
3823
- if (__privateGet(this, _options4).verbose) {
3824
- __privateMethod(this, _logIOStats, logIOStats_fn).call(this, io.stats);
3825
- }
3826
- if (error instanceof ResumeWithParallelTaskError) {
3827
- return {
3828
- status: "RESUME_WITH_PARALLEL_TASK",
3829
- task: error.task,
3830
- childErrors: error.childErrors.map((childError) => {
3831
- return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, childError, body1);
3832
- })
3833
- };
3834
- }
3835
- return __privateMethod(this, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn).call(this, error, body1);
3836
- }
3837
- }, "#executeJob");
3838
- _convertErrorToExecutionResponse = new WeakSet();
3839
- convertErrorToExecutionResponse_fn = /* @__PURE__ */ __name(function(error, body2) {
3840
- if (error instanceof AutoYieldExecutionError) {
3841
- return {
3842
- status: "AUTO_YIELD_EXECUTION",
3843
- location: error.location,
3844
- timeRemaining: error.timeRemaining,
3845
- timeElapsed: error.timeElapsed,
3846
- limit: body2.runChunkExecutionLimit
3847
- };
3848
- }
3849
- if (error instanceof AutoYieldWithCompletedTaskExecutionError) {
3850
- return {
3851
- status: "AUTO_YIELD_EXECUTION_WITH_COMPLETED_TASK",
3852
- id: error.id,
3853
- properties: error.properties,
3854
- output: error.output,
3855
- data: {
3856
- ...error.data,
3857
- limit: body2.runChunkExecutionLimit
3858
- }
3859
- };
3860
- }
3861
- if (error instanceof YieldExecutionError) {
3862
- return {
3863
- status: "YIELD_EXECUTION",
3864
- key: error.key
3865
- };
3866
- }
3867
- if (error instanceof ParsedPayloadSchemaError) {
3868
- return {
3869
- status: "INVALID_PAYLOAD",
3870
- errors: error.schemaErrors
3871
- };
3872
- }
3873
- if (error instanceof ResumeWithTaskError) {
3874
- return {
3875
- status: "RESUME_WITH_TASK",
3876
- task: error.task
3877
- };
3878
- }
3879
- if (error instanceof RetryWithTaskError) {
3880
- return {
3881
- status: "RETRY_WITH_TASK",
3882
- task: error.task,
3883
- error: error.cause,
3884
- retryAt: error.retryAt
3885
- };
3886
- }
3887
- if (error instanceof CanceledWithTaskError) {
3888
- return {
3889
- status: "CANCELED",
3890
- task: error.task
3891
- };
3892
- }
3893
- if (error instanceof ErrorWithTask) {
3894
- const errorWithStack2 = core.ErrorWithStackSchema.safeParse(error.cause.output);
3895
- if (errorWithStack2.success) {
3896
- return {
3897
- status: "ERROR",
3898
- error: errorWithStack2.data,
3899
- task: error.cause
3900
- };
3901
- }
3902
- return {
3903
- status: "ERROR",
3904
- error: {
3905
- message: JSON.stringify(error.cause.output)
3906
- },
3907
- task: error.cause
3908
- };
3909
- }
3910
- if (error instanceof RetryWithTaskError) {
3911
- const errorWithStack2 = core.ErrorWithStackSchema.safeParse(error.cause);
3912
- if (errorWithStack2.success) {
3913
- return {
3914
- status: "ERROR",
3915
- error: errorWithStack2.data,
3916
- task: error.task
3917
- };
3918
- }
3919
- return {
3920
- status: "ERROR",
3921
- error: {
3922
- message: "Unknown error"
3923
- },
3924
- task: error.task
3925
- };
3926
- }
3927
- const errorWithStack = core.ErrorWithStackSchema.safeParse(error);
3928
- if (errorWithStack.success) {
3929
- return {
3930
- status: "ERROR",
3931
- error: errorWithStack.data
3932
- };
3933
- }
3934
- const message = typeof error === "string" ? error : JSON.stringify(error);
3935
- return {
3936
- status: "ERROR",
3937
- error: {
3938
- name: "Unknown error",
3939
- message
3940
- }
3941
- };
3942
- }, "#convertErrorToExecutionResponse");
3943
- _createRunContext = new WeakSet();
3944
- createRunContext_fn = /* @__PURE__ */ __name(function(execution) {
3945
- const { event, organization, project, environment, job, run, source } = execution;
3946
- return {
3947
- event: {
3948
- id: event.id,
3949
- name: event.name,
3950
- context: event.context,
3951
- timestamp: event.timestamp
3952
- },
3953
- organization,
3954
- project: project ?? {
3955
- id: "unknown",
3956
- name: "unknown",
3957
- slug: "unknown"
3958
- },
3959
- environment,
3960
- job,
3961
- run,
3962
- account: execution.account,
3963
- source
3964
- };
3965
- }, "#createRunContext");
3966
- _createPreprocessRunContext = new WeakSet();
3967
- createPreprocessRunContext_fn = /* @__PURE__ */ __name(function(body3) {
3968
- const { event, organization, environment, job, run, account } = body3;
3969
- return {
3970
- event: {
3971
- id: event.id,
3972
- name: event.name,
3973
- context: event.context,
3974
- timestamp: event.timestamp
3975
- },
3976
- organization,
3977
- environment,
3978
- job,
3979
- run,
3980
- account
3981
- };
3982
- }, "#createPreprocessRunContext");
3983
- _handleHttpSourceRequest = new WeakSet();
3984
- handleHttpSourceRequest_fn = /* @__PURE__ */ __name(async function(source, sourceRequest) {
3985
- __privateGet(this, _internalLogger).debug("Handling HTTP source request", {
3986
- source
3987
- });
3988
- if (source.dynamicId) {
3989
- const dynamicTrigger = __privateGet(this, _registeredDynamicTriggers)[source.dynamicId];
3990
- if (!dynamicTrigger) {
3991
- __privateGet(this, _internalLogger).debug("No dynamic trigger registered for HTTP source", {
3992
- source
3993
- });
3994
- return {
3995
- response: {
3996
- status: 200,
3997
- body: {
3998
- ok: true
3999
- }
4000
- },
4001
- events: []
4002
- };
4003
- }
4004
- const results2 = await dynamicTrigger.source.handle(source, sourceRequest, __privateGet(this, _internalLogger));
4005
- if (!results2) {
4006
- return {
4007
- events: [],
4008
- response: {
4009
- status: 200,
4010
- body: {
4011
- ok: true
4012
- }
4013
- }
4014
- };
4015
- }
4016
- return {
4017
- events: results2.events,
4018
- response: results2.response ?? {
4019
- status: 200,
4020
- body: {
4021
- ok: true
4022
- }
4023
- },
4024
- metadata: results2.metadata
4025
- };
4026
- }
4027
- const handler = __privateGet(this, _registeredHttpSourceHandlers)[source.key];
4028
- if (!handler) {
4029
- __privateGet(this, _internalLogger).debug("No handler registered for HTTP source", {
4030
- source
4031
- });
4032
- return {
4033
- response: {
4034
- status: 200,
4035
- body: {
4036
- ok: true
4037
- }
4038
- },
4039
- events: []
4040
- };
4041
- }
4042
- const results = await handler(source, sourceRequest);
4043
- if (!results) {
4044
- return {
4045
- events: [],
4046
- response: {
4047
- status: 200,
4048
- body: {
4049
- ok: true
4050
- }
4051
- }
4052
- };
4053
- }
4054
- return {
4055
- events: results.events,
4056
- response: results.response ?? {
4057
- status: 200,
4058
- body: {
4059
- ok: true
4060
- }
4061
- },
4062
- metadata: results.metadata
4063
- };
4064
- }, "#handleHttpSourceRequest");
4065
- _handleHttpEndpointRequestForResponse = new WeakSet();
4066
- handleHttpEndpointRequestForResponse_fn = /* @__PURE__ */ __name(async function(data, sourceRequest1) {
4067
- __privateGet(this, _internalLogger).debug("Handling HTTP Endpoint request for response", {
4068
- data
4069
- });
4070
- const httpEndpoint2 = __privateGet(this, _registeredHttpEndpoints)[data.key];
4071
- if (!httpEndpoint2) {
4072
- __privateGet(this, _internalLogger).debug("No handler registered for HTTP Endpoint", {
4073
- data
4074
- });
4075
- return {
4076
- response: {
4077
- status: 200,
4078
- body: {
4079
- ok: true
4080
- }
4081
- }
4082
- };
4083
- }
4084
- const handledResponse = await httpEndpoint2.handleRequest(sourceRequest1);
4085
- if (!handledResponse) {
4086
- __privateGet(this, _internalLogger).debug("There's no HTTP Endpoint respondWith.handler()", {
4087
- data
4088
- });
4089
- return {
4090
- response: {
4091
- status: 200,
4092
- body: {
4093
- ok: true
4094
- }
4095
- }
4096
- };
4097
- }
4098
- let body;
4099
- try {
4100
- body = await handledResponse.text();
4101
- } catch (error) {
4102
- __privateGet(this, _internalLogger).error(`Error reading httpEndpoint ${httpEndpoint2.id} respondWith.handler Response`, {
4103
- error
4104
- });
4105
- }
4106
- const response = {
4107
- status: handledResponse.status,
4108
- headers: handledResponse.headers ? Object.fromEntries(handledResponse.headers.entries()) : void 0,
4109
- body
4110
- };
4111
- __privateGet(this, _internalLogger).info(`httpEndpoint ${httpEndpoint2.id} respondWith.handler response`, {
4112
- response
4113
- });
4114
- return {
4115
- response
4116
- };
4117
- }, "#handleHttpEndpointRequestForResponse");
4118
- _handleWebhookRequest = new WeakSet();
4119
- handleWebhookRequest_fn = /* @__PURE__ */ __name(async function(request, ctx) {
4120
- __privateGet(this, _internalLogger).debug("Handling webhook request", {
4121
- ctx
4122
- });
4123
- const okResponse = {
4124
- status: 200,
4125
- body: {
4126
- ok: true
4127
- }
4128
- };
4129
- const handlers = __privateGet(this, _registeredWebhookSourceHandlers)[ctx.key];
4130
- if (!handlers) {
4131
- __privateGet(this, _internalLogger).debug("No handler registered for webhook", {
4132
- ctx
4133
- });
4134
- return {
4135
- response: okResponse,
4136
- verified: false
4137
- };
4138
- }
4139
- const { verify, generateEvents } = handlers;
4140
- const verifyResult = await verify(request, this, ctx);
4141
- if (!verifyResult.success) {
4142
- return {
4143
- response: okResponse,
4144
- verified: false,
4145
- error: verifyResult.reason
4146
- };
4147
- }
4148
- await generateEvents(request, this, ctx);
4149
- return {
4150
- response: okResponse,
4151
- verified: true
4152
- };
4153
- }, "#handleWebhookRequest");
4154
- _resolveConnections = new WeakSet();
4155
- resolveConnections_fn = /* @__PURE__ */ __name(async function(ctx1, integrations, connections) {
4156
- if (!integrations) {
4157
- return {
4158
- ok: true,
4159
- data: {}
4160
- };
4161
- }
4162
- const resolvedAuthResults = await Promise.all(Object.keys(integrations).map(async (key) => {
4163
- const integration = integrations[key];
4164
- const auth = (connections ?? {})[key];
4165
- const result = await __privateMethod(this, _resolveConnection, resolveConnection_fn).call(this, ctx1, integration, auth);
4166
- if (result.ok) {
4167
- return {
4168
- ok: true,
4169
- auth: result.auth,
4170
- key
4171
- };
4172
- } else {
4173
- return {
4174
- ok: false,
4175
- error: result.error,
4176
- key
4177
- };
4178
- }
4179
- }));
4180
- const allResolved = resolvedAuthResults.every((result) => result.ok);
4181
- if (allResolved) {
4182
- return {
4183
- ok: true,
4184
- data: resolvedAuthResults.reduce((acc, result) => {
4185
- acc[result.key] = result.auth;
4186
- return acc;
4187
- }, {})
4188
- };
4189
- } else {
4190
- return {
4191
- ok: false,
4192
- issues: resolvedAuthResults.reduce((acc, result) => {
4193
- if (result.ok) {
4194
- return acc;
4195
- }
4196
- const integration = integrations[result.key];
4197
- acc[result.key] = {
4198
- id: integration.id,
4199
- error: result.error
4200
- };
4201
- return acc;
4202
- }, {})
4203
- };
4204
- }
4205
- }, "#resolveConnections");
4206
- _resolveConnection = new WeakSet();
4207
- resolveConnection_fn = /* @__PURE__ */ __name(async function(ctx2, integration, auth) {
4208
- if (auth) {
4209
- return {
4210
- ok: true,
4211
- auth
4212
- };
4213
- }
4214
- const authResolver = __privateGet(this, _authResolvers)[integration.id];
4215
- if (!authResolver) {
4216
- if (integration.authSource === "HOSTED") {
4217
- return {
4218
- ok: false,
4219
- error: `Something went wrong: Integration ${integration.id} is missing auth credentials from Trigger.dev`
4220
- };
4221
- }
4222
- return {
4223
- ok: true,
4224
- auth: void 0
4225
- };
4226
- }
4227
- try {
4228
- const resolvedAuth = await authResolver(ctx2, integration);
4229
- if (!resolvedAuth) {
4230
- return {
4231
- ok: false,
4232
- error: `Auth could not be resolved for ${integration.id}: auth resolver returned null or undefined`
4233
- };
4234
- }
4235
- return {
4236
- ok: true,
4237
- auth: resolvedAuth.type === "apiKey" ? {
4238
- type: "apiKey",
4239
- accessToken: resolvedAuth.token,
4240
- additionalFields: resolvedAuth.additionalFields
4241
- } : {
4242
- type: "oauth2",
4243
- accessToken: resolvedAuth.token,
4244
- additionalFields: resolvedAuth.additionalFields
4245
- }
4246
- };
4247
- } catch (resolverError) {
4248
- if (resolverError instanceof Error) {
4249
- return {
4250
- ok: false,
4251
- error: `Auth could not be resolved for ${integration.id}: auth resolver threw. ${resolverError.name}: ${resolverError.message}`
4252
- };
4253
- } else if (typeof resolverError === "string") {
4254
- return {
4255
- ok: false,
4256
- error: `Auth could not be resolved for ${integration.id}: auth resolver threw an error: ${resolverError}`
4257
- };
4258
- }
4259
- return {
4260
- ok: false,
4261
- error: `Auth could not be resolved for ${integration.id}: auth resolver threw an unknown error: ${JSON.stringify(resolverError)}`
4262
- };
4263
- }
4264
- }, "#resolveConnection");
4265
- _buildJobsIndex = new WeakSet();
4266
- buildJobsIndex_fn = /* @__PURE__ */ __name(function() {
4267
- return Object.values(__privateGet(this, _registeredJobs)).map((job) => __privateMethod(this, _buildJobIndex, buildJobIndex_fn).call(this, job));
4268
- }, "#buildJobsIndex");
4269
- _buildJobIndex = new WeakSet();
4270
- buildJobIndex_fn = /* @__PURE__ */ __name(function(job2) {
4271
- const internal = job2.options.__internal;
4272
- return {
4273
- id: job2.id,
4274
- name: job2.name,
4275
- version: job2.version,
4276
- event: job2.trigger.event,
4277
- trigger: job2.trigger.toJSON(),
4278
- integrations: __privateMethod(this, _buildJobIntegrations, buildJobIntegrations_fn).call(this, job2),
4279
- startPosition: "latest",
4280
- enabled: job2.enabled,
4281
- preprocessRuns: job2.trigger.preprocessRuns,
4282
- internal,
4283
- concurrencyLimit: typeof job2.options.concurrencyLimit === "number" ? job2.options.concurrencyLimit : typeof job2.options.concurrencyLimit === "object" ? {
4284
- id: job2.options.concurrencyLimit.id,
4285
- limit: job2.options.concurrencyLimit.limit
4286
- } : void 0
4287
- };
4288
- }, "#buildJobIndex");
4289
- _buildJobIntegrations = new WeakSet();
4290
- buildJobIntegrations_fn = /* @__PURE__ */ __name(function(job3) {
4291
- return Object.keys(job3.options.integrations ?? {}).reduce((acc, key) => {
4292
- const integration = job3.options.integrations[key];
4293
- acc[key] = __privateMethod(this, _buildJobIntegration, buildJobIntegration_fn).call(this, integration);
4294
- return acc;
4295
- }, {});
4296
- }, "#buildJobIntegrations");
4297
- _buildJobIntegration = new WeakSet();
4298
- buildJobIntegration_fn = /* @__PURE__ */ __name(function(integration1) {
4299
- const authSource = __privateGet(this, _authResolvers)[integration1.id] ? "RESOLVER" : integration1.authSource;
4300
- return {
4301
- id: integration1.id,
4302
- metadata: integration1.metadata,
4303
- authSource
4304
- };
4305
- }, "#buildJobIntegration");
4306
- _logIOStats = new WeakSet();
4307
- logIOStats_fn = /* @__PURE__ */ __name(function(stats) {
4308
- __privateGet(this, _internalLogger).debug("IO stats", {
4309
- stats
4310
- });
4311
- }, "#logIOStats");
4312
- _standardResponseHeaders = new WeakSet();
4313
- standardResponseHeaders_fn = /* @__PURE__ */ __name(function(start) {
4314
- return {
4315
- "Trigger-Version": core.API_VERSIONS.LAZY_LOADED_CACHED_TASKS,
4316
- "Trigger-SDK-Version": version,
4317
- "X-Trigger-Request-Timing": `dur=${performance.now() - start / 1e3}`
4318
- };
4319
- }, "#standardResponseHeaders");
4320
- _serializeRunMetadata = new WeakSet();
4321
- serializeRunMetadata_fn = /* @__PURE__ */ __name(function(job4) {
4322
- const metadata = {};
4323
- if (__privateGet(this, _eventEmitter).listenerCount("runSucceeeded") > 0 || typeof job4.options.onSuccess === "function") {
4324
- metadata["successSubscription"] = true;
4325
- }
4326
- if (__privateGet(this, _eventEmitter).listenerCount("runFailed") > 0 || typeof job4.options.onFailure === "function") {
4327
- metadata["failedSubscription"] = true;
4328
- }
4329
- return JSON.stringify(metadata);
4330
- }, "#serializeRunMetadata");
4331
- _deliverSuccessfulRunNotification = new WeakSet();
4332
- deliverSuccessfulRunNotification_fn = /* @__PURE__ */ __name(async function(notification) {
4333
- __privateGet(this, _internalLogger).debug("delivering successful run notification", {
4334
- notification
4335
- });
4336
- __privateGet(this, _eventEmitter).emit("runSucceeeded", notification);
4337
- const job = __privateGet(this, _registeredJobs)[notification.job.id];
4338
- if (!job) {
4339
- return;
4340
- }
4341
- if (typeof job.options.onSuccess === "function") {
4342
- await job.options.onSuccess(notification);
4343
- }
4344
- }, "#deliverSuccessfulRunNotification");
4345
- _deliverFailedRunNotification = new WeakSet();
4346
- deliverFailedRunNotification_fn = /* @__PURE__ */ __name(async function(notification1) {
4347
- __privateGet(this, _internalLogger).debug("delivering failed run notification", {
4348
- notification: notification1
4349
- });
4350
- __privateGet(this, _eventEmitter).emit("runFailed", notification1);
4351
- const job = __privateGet(this, _registeredJobs)[notification1.job.id];
4352
- if (!job) {
4353
- return;
4354
- }
4355
- if (typeof job.options.onFailure === "function") {
4356
- await job.options.onFailure(notification1);
4357
- }
4358
- }, "#deliverFailedRunNotification");
4359
- __name(_TriggerClient, "TriggerClient");
4360
- var TriggerClient = _TriggerClient;
4361
- function dynamicTriggerRegisterSourceJobId(id) {
4362
- return `register-dynamic-trigger-${id}`;
4363
- }
4364
- __name(dynamicTriggerRegisterSourceJobId, "dynamicTriggerRegisterSourceJobId");
4365
- function deepMergeOptions(obj1, obj2) {
4366
- const mergedOptions = {
4367
- ...obj1
4368
- };
4369
- for (const key in obj2) {
4370
- if (obj2.hasOwnProperty(key)) {
4371
- if (key in mergedOptions) {
4372
- mergedOptions[key] = [
4373
- ...mergedOptions[key],
4374
- ...obj2[key]
4375
- ];
4376
- } else {
4377
- mergedOptions[key] = obj2[key];
4378
- }
4379
- }
4380
- }
4381
- return mergedOptions;
4382
- }
4383
- __name(deepMergeOptions, "deepMergeOptions");
4384
- var _ExternalSource = class _ExternalSource {
4385
- constructor(channel, options) {
4386
- this.options = options;
4387
- this.channel = channel;
4388
- }
4389
- async handle(source, rawEvent, logger) {
4390
- return this.options.handler({
4391
- source: {
4392
- ...source,
4393
- params: source.params
4394
- },
4395
- rawEvent
4396
- }, logger, this.options.integration);
4397
- }
4398
- filter(params, options) {
4399
- return this.options.filter?.(params, options) ?? {};
4400
- }
4401
- properties(params) {
4402
- return this.options.properties?.(params) ?? [];
4403
- }
4404
- async register(params, registerEvent, io, ctx) {
4405
- const { result: event, ommited: source } = omit(registerEvent, "source");
4406
- const { result: sourceWithoutChannel, ommited: channel } = omit(source, "channel");
4407
- const { result: channelWithoutType } = omit(channel, "type");
4408
- const updates = await this.options.register({
4409
- ...event,
4410
- source: {
4411
- ...sourceWithoutChannel,
4412
- ...channelWithoutType
4413
- },
4414
- params
4415
- }, io, ctx);
4416
- return updates;
4417
- }
4418
- key(params) {
4419
- const parts = [
4420
- this.options.id,
4421
- this.channel
4422
- ];
4423
- parts.push(this.options.key(params));
4424
- parts.push(this.integration.id);
4425
- return parts.join("-");
4426
- }
4427
- get integration() {
4428
- return this.options.integration;
4429
- }
4430
- get integrationConfig() {
4431
- return {
4432
- id: this.integration.id,
4433
- metadata: this.integration.metadata
4434
- };
4435
- }
4436
- get id() {
4437
- return this.options.id;
4438
- }
4439
- get version() {
4440
- return this.options.version;
4441
- }
4442
- };
4443
- __name(_ExternalSource, "ExternalSource");
4444
- var ExternalSource = _ExternalSource;
4445
- var _ExternalSourceTrigger = class _ExternalSourceTrigger {
4446
- constructor(options) {
4447
- this.options = options;
4448
- }
4449
- get event() {
4450
- return this.options.event;
4451
- }
4452
- toJSON() {
4453
- return {
4454
- type: "static",
4455
- title: "External Source",
4456
- rule: {
4457
- event: this.event.name,
4458
- payload: core.deepMergeFilters(this.options.source.filter(this.options.params, this.options.options), this.event.filter ?? {}, this.options.params.filter ?? {}),
4459
- source: this.event.source
4460
- },
4461
- properties: this.options.source.properties(this.options.params)
4462
- };
4463
- }
4464
- attachToJob(triggerClient, job) {
4465
- triggerClient.attachSource({
4466
- key: slugifyId(this.options.source.key(this.options.params)),
4467
- source: this.options.source,
4468
- event: this.options.event,
4469
- params: this.options.params,
4470
- options: this.options.options
4471
- });
4472
- }
4473
- get preprocessRuns() {
4474
- return true;
4475
- }
4476
- async verifyPayload(payload) {
4477
- return {
4478
- success: true
4479
- };
4480
- }
4481
- };
4482
- __name(_ExternalSourceTrigger, "ExternalSourceTrigger");
4483
- var ExternalSourceTrigger = _ExternalSourceTrigger;
4484
- function omit(obj, key) {
4485
- const result = {};
4486
- for (const k of Object.keys(obj)) {
4487
- if (k === key)
4488
- continue;
4489
- result[k] = obj[k];
4490
- }
4491
- return {
4492
- result,
4493
- ommited: obj[key]
4494
- };
4495
- }
4496
- __name(omit, "omit");
4497
- function missingConnectionNotification(integrations) {
4498
- return new MissingConnectionNotification({
4499
- integrations
4500
- });
4501
- }
4502
- __name(missingConnectionNotification, "missingConnectionNotification");
4503
- function missingConnectionResolvedNotification(integrations) {
4504
- return new MissingConnectionResolvedNotification({
4505
- integrations
4506
- });
4507
- }
4508
- __name(missingConnectionResolvedNotification, "missingConnectionResolvedNotification");
4509
- var _MissingConnectionNotification = class _MissingConnectionNotification {
4510
- constructor(options) {
4511
- this.options = options;
4512
- }
4513
- get event() {
4514
- return {
4515
- name: core.MISSING_CONNECTION_NOTIFICATION,
4516
- title: "Missing Connection Notification",
4517
- source: "trigger.dev",
4518
- icon: "connection-alert",
4519
- parsePayload: core.MissingConnectionNotificationPayloadSchema.parse,
4520
- properties: [
4521
- {
4522
- label: "Integrations",
4523
- text: this.options.integrations.map((i) => i.id).join(", ")
4524
- }
4525
- ]
4526
- };
4527
- }
4528
- attachToJob(triggerClient, job) {
4529
- }
4530
- get preprocessRuns() {
4531
- return false;
4532
- }
4533
- async verifyPayload(payload) {
4534
- return {
4535
- success: true
4536
- };
4537
- }
4538
- toJSON() {
4539
- return {
4540
- type: "static",
4541
- title: this.event.title,
4542
- rule: {
4543
- event: this.event.name,
4544
- source: "trigger.dev",
4545
- payload: {
4546
- client: {
4547
- id: this.options.integrations.map((i) => i.id)
4548
- }
4549
- }
4550
- }
4551
- };
4552
- }
4553
- };
4554
- __name(_MissingConnectionNotification, "MissingConnectionNotification");
4555
- var MissingConnectionNotification = _MissingConnectionNotification;
4556
- var _MissingConnectionResolvedNotification = class _MissingConnectionResolvedNotification {
4557
- constructor(options) {
4558
- this.options = options;
4559
- }
4560
- get event() {
4561
- return {
4562
- name: core.MISSING_CONNECTION_RESOLVED_NOTIFICATION,
4563
- title: "Missing Connection Resolved Notification",
4564
- source: "trigger.dev",
4565
- icon: "connection-alert",
4566
- parsePayload: core.MissingConnectionResolvedNotificationPayloadSchema.parse,
4567
- properties: [
4568
- {
4569
- label: "Integrations",
4570
- text: this.options.integrations.map((i) => i.id).join(", ")
4571
- }
4572
- ]
4573
- };
4574
- }
4575
- attachToJob(triggerClient, job) {
4576
- }
4577
- get preprocessRuns() {
4578
- return false;
4579
- }
4580
- async verifyPayload(payload) {
4581
- return {
4582
- success: true
4583
- };
4584
- }
4585
- toJSON() {
4586
- return {
4587
- type: "static",
4588
- title: this.event.title,
4589
- rule: {
4590
- event: this.event.name,
4591
- source: "trigger.dev",
4592
- payload: {
4593
- client: {
4594
- id: this.options.integrations.map((i) => i.id)
4595
- }
4596
- }
4597
- }
4598
- };
4599
- }
4600
- };
4601
- __name(_MissingConnectionResolvedNotification, "MissingConnectionResolvedNotification");
4602
- var MissingConnectionResolvedNotification = _MissingConnectionResolvedNotification;
4603
-
4604
- // src/triggers/invokeTrigger.ts
4605
- var _options5;
4606
- var _InvokeTrigger = class _InvokeTrigger {
4607
- constructor(options) {
4608
- __privateAdd(this, _options5, void 0);
4609
- __privateSet(this, _options5, options);
4610
- }
4611
- toJSON() {
4612
- return {
4613
- type: "invoke"
4614
- };
4615
- }
4616
- get event() {
4617
- return {
4618
- name: "invoke",
4619
- title: "Manual Invoke",
4620
- source: "trigger.dev",
4621
- examples: __privateGet(this, _options5).examples ?? [],
4622
- icon: "trigger",
4623
- parsePayload: (rawPayload) => {
4624
- if (__privateGet(this, _options5).schema) {
4625
- const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
4626
- if (!results.success) {
4627
- throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
4628
- }
4629
- return results.data;
4630
- }
4631
- return rawPayload;
4632
- },
4633
- parseInvokePayload: (rawPayload) => {
4634
- if (__privateGet(this, _options5).schema) {
4635
- const results = __privateGet(this, _options5).schema.safeParse(rawPayload);
4636
- if (!results.success) {
4637
- throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));
4638
- }
4639
- return results.data;
4640
- }
4641
- return rawPayload;
4642
- }
4643
- };
4644
- }
4645
- attachToJob(triggerClient, job) {
4646
- }
4647
- get preprocessRuns() {
4648
- return false;
4649
- }
4650
- async verifyPayload() {
4651
- return {
4652
- success: true
4653
- };
4654
- }
4655
- };
4656
- _options5 = new WeakMap();
4657
- __name(_InvokeTrigger, "InvokeTrigger");
4658
- var InvokeTrigger = _InvokeTrigger;
4659
- function invokeTrigger(options) {
4660
- return new InvokeTrigger(options ?? {});
4661
- }
4662
- __name(invokeTrigger, "invokeTrigger");
4663
- var _shortHash, shortHash_fn;
4664
- var _WebhookSource = class _WebhookSource {
4665
- constructor(options) {
4666
- __privateAdd(this, _shortHash);
4667
- this.options = options;
4668
- }
4669
- async generateEvents(request, client, ctx) {
4670
- return this.options.generateEvents({
4671
- request,
4672
- client,
4673
- ctx
4674
- });
4675
- }
4676
- filter(params, config) {
4677
- return this.options.filter?.(params, config) ?? {};
4678
- }
4679
- properties(params) {
4680
- return this.options.properties?.(params) ?? [];
4681
- }
4682
- get crud() {
4683
- return this.options.crud;
4684
- }
4685
- async register(params, registerEvent, io, ctx) {
4686
- if (!this.options.register) {
4687
- return;
4688
- }
4689
- const updates = await this.options.register({
4690
- ...registerEvent,
4691
- params
4692
- }, io, ctx);
4693
- return updates;
4694
- }
4695
- async verify(request, client, ctx) {
4696
- if (this.options.verify) {
4697
- const clonedRequest = request.clone();
4698
- return this.options.verify({
4699
- request: clonedRequest,
4700
- client,
4701
- ctx
4702
- });
4703
- }
4704
- return {
4705
- success: true
4706
- };
4707
- }
4708
- key(params) {
4709
- const parts = [
4710
- "webhook"
4711
- ];
4712
- parts.push(this.options.key(params));
4713
- parts.push(this.integration.id);
4714
- return `${this.options.id}-${__privateMethod(this, _shortHash, shortHash_fn).call(this, parts.join(""))}`;
4715
- }
4716
- get integration() {
4717
- return this.options.integration;
4718
- }
4719
- get integrationConfig() {
4720
- return {
4721
- id: this.integration.id,
4722
- metadata: this.integration.metadata
4723
- };
4724
- }
4725
- get id() {
4726
- return this.options.id;
4727
- }
4728
- get version() {
4729
- return this.options.version;
4730
- }
4731
- };
4732
- _shortHash = new WeakSet();
4733
- shortHash_fn = /* @__PURE__ */ __name(function(str) {
4734
- const hash = crypto.createHash("sha1").update(str).digest("hex");
4735
- return hash.slice(0, 7);
4736
- }, "#shortHash");
4737
- __name(_WebhookSource, "WebhookSource");
4738
- var WebhookSource = _WebhookSource;
4739
- var _WebhookTrigger = class _WebhookTrigger {
4740
- constructor(options) {
4741
- this.options = options;
4742
- }
4743
- get event() {
4744
- return this.options.event;
4745
- }
4746
- get source() {
4747
- return this.options.source;
4748
- }
4749
- get key() {
4750
- return slugifyId(this.options.source.key(this.options.params));
4751
- }
4752
- toJSON() {
4753
- return {
4754
- type: "static",
4755
- title: "Webhook",
4756
- rule: {
4757
- event: this.event.name,
4758
- payload: core.deepMergeFilters(this.options.source.filter(this.options.params, this.options.config), this.event.filter ?? {}),
4759
- source: this.event.source
4760
- },
4761
- properties: this.options.source.properties(this.options.params),
4762
- link: `http-endpoints/${this.key}`
4763
- };
4764
- }
4765
- filter(eventFilter) {
4766
- const { event, ...optionsWithoutEvent } = this.options;
4767
- const { filter, ...eventWithoutFilter } = event;
4768
- return new _WebhookTrigger({
4769
- ...optionsWithoutEvent,
4770
- event: {
4771
- ...eventWithoutFilter,
4772
- filter: core.deepMergeFilters(filter ?? {}, eventFilter)
4773
- }
4774
- });
4775
- }
4776
- attachToJob(triggerClient, job) {
4777
- triggerClient.defineHttpEndpoint({
4778
- id: this.key,
4779
- source: "trigger.dev",
4780
- icon: this.event.icon,
4781
- verify: async () => ({
4782
- success: true
4783
- })
4784
- }, true);
4785
- triggerClient.attachWebhook({
4786
- key: this.key,
4787
- source: this.options.source,
4788
- event: this.options.event,
4789
- params: this.options.params,
4790
- config: this.options.config
4791
- });
4792
- }
4793
- get preprocessRuns() {
4794
- return true;
4795
- }
4796
- async verifyPayload(payload) {
4797
- return {
4798
- success: true
4799
- };
4800
- }
4801
- };
4802
- __name(_WebhookTrigger, "WebhookTrigger");
4803
- var WebhookTrigger = _WebhookTrigger;
4804
- async function verifyRequestSignature({ request, headerName, headerEncoding = "hex", secret, algorithm }) {
4805
- if (!secret) {
4806
- return {
4807
- success: false,
4808
- reason: "Missing secret \u2013 you've probably not set an environment variable."
4809
- };
4810
- }
4811
- const headerValue = request.headers.get(headerName);
4812
- if (!headerValue) {
4813
- return {
4814
- success: false,
4815
- reason: "Missing header"
4816
- };
4817
- }
4818
- switch (algorithm) {
4819
- case "sha256":
4820
- const success = verifyHmacSha256(headerValue, headerEncoding, secret, await request.text());
4821
- if (success) {
4822
- return {
4823
- success
4824
- };
4825
- } else {
4826
- return {
4827
- success: false,
4828
- reason: "Failed sha256 verification"
4829
- };
4830
- }
4831
- default:
4832
- throw new Error(`Unsupported algorithm: ${algorithm}`);
4833
- }
4834
- }
4835
- __name(verifyRequestSignature, "verifyRequestSignature");
4836
- function verifyHmacSha256(headerValue, headerEncoding, secret, body) {
4837
- const bodyDigest = crypto__default.default.createHmac("sha256", secret).update(body).digest(headerEncoding);
4838
- const signature = headerValue?.replace("hmac-sha256=", "").replace("sha256=", "") ?? "";
4839
- return signature === bodyDigest;
4840
- }
4841
- __name(verifyHmacSha256, "verifyHmacSha256");
4842
-
4843
- // src/index.ts
4844
- function redactString(strings, ...interpolations) {
4845
- return {
4846
- __redactedString: true,
4847
- strings: strings.raw,
4848
- interpolations
4849
- };
4850
- }
4851
- __name(redactString, "redactString");
4852
-
4853
- exports.CronTrigger = CronTrigger;
4854
- exports.DynamicSchedule = DynamicSchedule;
4855
- exports.DynamicTrigger = DynamicTrigger;
4856
- exports.EventSpecificationExampleSchema = EventSpecificationExampleSchema;
4857
- exports.EventTrigger = EventTrigger;
4858
- exports.ExternalSource = ExternalSource;
4859
- exports.ExternalSourceTrigger = ExternalSourceTrigger;
4860
- exports.IO = IO;
4861
- exports.IOLogger = IOLogger;
4862
- exports.IntervalTrigger = IntervalTrigger;
4863
- exports.InvokeTrigger = InvokeTrigger;
4864
- exports.JSONOutputSerializer = JSONOutputSerializer;
4865
- exports.Job = Job;
4866
- exports.MissingConnectionNotification = MissingConnectionNotification;
4867
- exports.MissingConnectionResolvedNotification = MissingConnectionResolvedNotification;
4868
- exports.TriggerClient = TriggerClient;
4869
- exports.WebhookSource = WebhookSource;
4870
- exports.WebhookTrigger = WebhookTrigger;
4871
- exports.cronTrigger = cronTrigger;
4872
- exports.eventTrigger = eventTrigger;
4873
- exports.intervalTrigger = intervalTrigger;
4874
- exports.invokeTrigger = invokeTrigger;
4875
- exports.isTriggerError = isTriggerError;
4876
- exports.missingConnectionNotification = missingConnectionNotification;
4877
- exports.missingConnectionResolvedNotification = missingConnectionResolvedNotification;
4878
- exports.omit = omit;
4879
- exports.redactString = redactString;
4880
- exports.retry = retry;
4881
- exports.slugifyId = slugifyId;
4882
- exports.verifyHmacSha256 = verifyHmacSha256;
4883
- exports.verifyRequestSignature = verifyRequestSignature;
4884
- exports.waitForEventSchema = waitForEventSchema;
4885
- //# sourceMappingURL=out.js.map
4886
- //# sourceMappingURL=index.js.map