@trigger.dev/sdk 0.0.0-canary-20231129101350 → 0.0.0-cli-e2e-20240910161832

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