@trigger.dev/sdk 2.0.10 → 2.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -201
- package/dist/index.d.ts +63 -10
- package/dist/index.js +49 -18
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/LICENSE
CHANGED
|
@@ -1,201 +1,21 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
-
exercising permissions granted by this License.
|
|
25
|
-
|
|
26
|
-
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
-
including but not limited to software source code, documentation
|
|
28
|
-
source, and configuration files.
|
|
29
|
-
|
|
30
|
-
"Object" form shall mean any form resulting from mechanical
|
|
31
|
-
transformation or translation of a Source form, including but
|
|
32
|
-
not limited to compiled object code, generated documentation,
|
|
33
|
-
and conversions to other media types.
|
|
34
|
-
|
|
35
|
-
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
-
Object form, made available under the License, as indicated by a
|
|
37
|
-
copyright notice that is included in or attached to the work
|
|
38
|
-
(an example is provided in the Appendix below).
|
|
39
|
-
|
|
40
|
-
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
-
form, that is based on (or derived from) the Work and for which the
|
|
42
|
-
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
-
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
-
of this License, Derivative Works shall not include works that remain
|
|
45
|
-
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
-
the Work and Derivative Works thereof.
|
|
47
|
-
|
|
48
|
-
"Contribution" shall mean any work of authorship, including
|
|
49
|
-
the original version of the Work and any modifications or additions
|
|
50
|
-
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
-
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
-
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
-
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
-
means any form of electronic, verbal, or written communication sent
|
|
55
|
-
to the Licensor or its representatives, including but not limited to
|
|
56
|
-
communication on electronic mailing lists, source code control systems,
|
|
57
|
-
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
-
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
-
excluding communication that is conspicuously marked or otherwise
|
|
60
|
-
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
-
|
|
62
|
-
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
-
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
-
subsequently incorporated within the Work.
|
|
65
|
-
|
|
66
|
-
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
-
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
-
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
-
Work and such Derivative Works in Source or Object form.
|
|
72
|
-
|
|
73
|
-
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
-
(except as stated in this section) patent license to make, have made,
|
|
77
|
-
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
-
where such license applies only to those patent claims licensable
|
|
79
|
-
by such Contributor that are necessarily infringed by their
|
|
80
|
-
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
-
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
-
institute patent litigation against any entity (including a
|
|
83
|
-
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
-
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
-
or contributory patent infringement, then any patent licenses
|
|
86
|
-
granted to You under this License for that Work shall terminate
|
|
87
|
-
as of the date such litigation is filed.
|
|
88
|
-
|
|
89
|
-
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
-
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
-
modifications, and in Source or Object form, provided that You
|
|
92
|
-
meet the following conditions:
|
|
93
|
-
|
|
94
|
-
(a) You must give any other recipients of the Work or
|
|
95
|
-
Derivative Works a copy of this License; and
|
|
96
|
-
|
|
97
|
-
(b) You must cause any modified files to carry prominent notices
|
|
98
|
-
stating that You changed the files; and
|
|
99
|
-
|
|
100
|
-
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
-
that You distribute, all copyright, patent, trademark, and
|
|
102
|
-
attribution notices from the Source form of the Work,
|
|
103
|
-
excluding those notices that do not pertain to any part of
|
|
104
|
-
the Derivative Works; and
|
|
105
|
-
|
|
106
|
-
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
-
distribution, then any Derivative Works that You distribute must
|
|
108
|
-
include a readable copy of the attribution notices contained
|
|
109
|
-
within such NOTICE file, excluding those notices that do not
|
|
110
|
-
pertain to any part of the Derivative Works, in at least one
|
|
111
|
-
of the following places: within a NOTICE text file distributed
|
|
112
|
-
as part of the Derivative Works; within the Source form or
|
|
113
|
-
documentation, if provided along with the Derivative Works; or,
|
|
114
|
-
within a display generated by the Derivative Works, if and
|
|
115
|
-
wherever such third-party notices normally appear. The contents
|
|
116
|
-
of the NOTICE file are for informational purposes only and
|
|
117
|
-
do not modify the License. You may add Your own attribution
|
|
118
|
-
notices within Derivative Works that You distribute, alongside
|
|
119
|
-
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
-
that such additional attribution notices cannot be construed
|
|
121
|
-
as modifying the License.
|
|
122
|
-
|
|
123
|
-
You may add Your own copyright statement to Your modifications and
|
|
124
|
-
may provide additional or different license terms and conditions
|
|
125
|
-
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
-
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
-
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
-
the conditions stated in this License.
|
|
129
|
-
|
|
130
|
-
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
-
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
-
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
-
this License, without any additional terms or conditions.
|
|
134
|
-
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
-
the terms of any separate license agreement you may have executed
|
|
136
|
-
with Licensor regarding such Contributions.
|
|
137
|
-
|
|
138
|
-
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
-
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
-
except as required for reasonable and customary use in describing the
|
|
141
|
-
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
-
|
|
143
|
-
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
-
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
-
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
-
implied, including, without limitation, any warranties or conditions
|
|
148
|
-
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
-
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
-
appropriateness of using or redistributing the Work and assume any
|
|
151
|
-
risks associated with Your exercise of permissions under this License.
|
|
152
|
-
|
|
153
|
-
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
-
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
-
unless required by applicable law (such as deliberate and grossly
|
|
156
|
-
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
-
liable to You for damages, including any direct, indirect, special,
|
|
158
|
-
incidental, or consequential damages of any character arising as a
|
|
159
|
-
result of this License or out of the use or inability to use the
|
|
160
|
-
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
-
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
-
other commercial damages or losses), even if such Contributor
|
|
163
|
-
has been advised of the possibility of such damages.
|
|
164
|
-
|
|
165
|
-
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
-
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
-
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
-
or other liability obligations and/or rights consistent with this
|
|
169
|
-
License. However, in accepting such obligations, You may act only
|
|
170
|
-
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
-
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
-
defend, and hold each Contributor harmless for any liability
|
|
173
|
-
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
-
of your accepting any such warranty or additional liability.
|
|
175
|
-
|
|
176
|
-
END OF TERMS AND CONDITIONS
|
|
177
|
-
|
|
178
|
-
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
-
|
|
180
|
-
To apply the Apache License to your work, attach the following
|
|
181
|
-
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
-
replaced with your own identifying information. (Don't include
|
|
183
|
-
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
-
comment syntax for the file format. We also recommend that a
|
|
185
|
-
file or class name and description of purpose be included on the
|
|
186
|
-
same "printed page" as the copyright notice for easier
|
|
187
|
-
identification within third-party archives.
|
|
188
|
-
|
|
189
|
-
Copyright [yyyy] [name of copyright owner]
|
|
190
|
-
|
|
191
|
-
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
-
you may not use this file except in compliance with the License.
|
|
193
|
-
You may obtain a copy of the License at
|
|
194
|
-
|
|
195
|
-
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
-
|
|
197
|
-
Unless required by applicable law or agreed to in writing, software
|
|
198
|
-
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
-
See the License for the specific language governing permissions and
|
|
201
|
-
limitations under the License.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Trigger.dev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _trigger_dev_core from '@trigger.dev/core';
|
|
2
|
-
import {
|
|
2
|
+
import { RunTaskBodyInput, CompleteTaskBodyInput, FailTaskBodyInput, SendEvent, SendEventOptions, UpdateTriggerSourceBody, TriggerSource, RegisterTriggerBody, RegisterSourceEvent, ScheduleMetadata, GetRunOptionsWithTaskDetails, GetRunsOptions, LogLevel, RuntimeEnvironmentType, DisplayProperty, TriggerMetadata, EventFilter, HandleTriggerSource, Logger, NormalizedResponse, Prettify, IntervalOptions, CronOptions, ScheduledPayload, ServerTask, CachedTask, FetchRequestInit, FetchRetryOptions, ConnectionAuth, SerializableJson, RunTaskOptions, IntegrationMetadata, QueueOptions, IntegrationConfig, JobMetadata, MissingConnectionNotificationPayload, MissingConnectionResolvedNotificationPayload, ErrorWithStack, ApiEventLog, RedactString } from '@trigger.dev/core';
|
|
3
3
|
export { EventFilter, Logger, NormalizedRequest, RedactString } from '@trigger.dev/core';
|
|
4
4
|
import * as zod from 'zod';
|
|
5
5
|
import { z } from 'zod';
|
|
@@ -21,15 +21,6 @@ declare class ApiClient {
|
|
|
21
21
|
url: string;
|
|
22
22
|
name: string;
|
|
23
23
|
}): Promise<EndpointRecord>;
|
|
24
|
-
createRun(params: CreateRunBody): Promise<{
|
|
25
|
-
data: {
|
|
26
|
-
id: string;
|
|
27
|
-
};
|
|
28
|
-
ok: true;
|
|
29
|
-
} | {
|
|
30
|
-
error: string;
|
|
31
|
-
ok: false;
|
|
32
|
-
}>;
|
|
33
24
|
runTask(runId: string, task: RunTaskBodyInput): Promise<{
|
|
34
25
|
id: string;
|
|
35
26
|
name: string;
|
|
@@ -138,6 +129,21 @@ declare class ApiClient {
|
|
|
138
129
|
context?: _trigger_dev_core.DeserializedJson | undefined;
|
|
139
130
|
deliverAt?: Date | null | undefined;
|
|
140
131
|
deliveredAt?: Date | null | undefined;
|
|
132
|
+
cancelledAt?: Date | null | undefined;
|
|
133
|
+
}>;
|
|
134
|
+
cancelEvent(eventId: string): Promise<{
|
|
135
|
+
id: string;
|
|
136
|
+
name: string;
|
|
137
|
+
payload: ((string | number | boolean | {
|
|
138
|
+
[key: string]: _trigger_dev_core.DeserializedJson;
|
|
139
|
+
} | _trigger_dev_core.DeserializedJson[]) & (string | number | boolean | {
|
|
140
|
+
[key: string]: _trigger_dev_core.DeserializedJson;
|
|
141
|
+
} | _trigger_dev_core.DeserializedJson[] | undefined)) | null;
|
|
142
|
+
timestamp: Date;
|
|
143
|
+
context?: _trigger_dev_core.DeserializedJson | undefined;
|
|
144
|
+
deliverAt?: Date | null | undefined;
|
|
145
|
+
deliveredAt?: Date | null | undefined;
|
|
146
|
+
cancelledAt?: Date | null | undefined;
|
|
141
147
|
}>;
|
|
142
148
|
updateSource(client: string, key: string, source: UpdateTriggerSourceBody): Promise<TriggerSource>;
|
|
143
149
|
registerTrigger(client: string, id: string, key: string, payload: RegisterTriggerBody): Promise<RegisterSourceEvent>;
|
|
@@ -565,6 +571,21 @@ declare class TriggerClient {
|
|
|
565
571
|
context?: _trigger_dev_core.DeserializedJson | undefined;
|
|
566
572
|
deliverAt?: Date | null | undefined;
|
|
567
573
|
deliveredAt?: Date | null | undefined;
|
|
574
|
+
cancelledAt?: Date | null | undefined;
|
|
575
|
+
}>;
|
|
576
|
+
cancelEvent(eventId: string): Promise<{
|
|
577
|
+
id: string;
|
|
578
|
+
name: string;
|
|
579
|
+
payload: ((string | number | boolean | {
|
|
580
|
+
[key: string]: _trigger_dev_core.DeserializedJson;
|
|
581
|
+
} | _trigger_dev_core.DeserializedJson[]) & (string | number | boolean | {
|
|
582
|
+
[key: string]: _trigger_dev_core.DeserializedJson;
|
|
583
|
+
} | _trigger_dev_core.DeserializedJson[] | undefined)) | null;
|
|
584
|
+
timestamp: Date;
|
|
585
|
+
context?: _trigger_dev_core.DeserializedJson | undefined;
|
|
586
|
+
deliverAt?: Date | null | undefined;
|
|
587
|
+
deliveredAt?: Date | null | undefined;
|
|
588
|
+
cancelledAt?: Date | null | undefined;
|
|
568
589
|
}>;
|
|
569
590
|
registerSchedule(id: string, key: string, schedule: ScheduleMetadata): Promise<{
|
|
570
591
|
id: string;
|
|
@@ -814,6 +835,38 @@ declare class IO {
|
|
|
814
835
|
context?: _trigger_dev_core.DeserializedJson | undefined;
|
|
815
836
|
deliverAt?: Date | null | undefined;
|
|
816
837
|
deliveredAt?: Date | null | undefined;
|
|
838
|
+
cancelledAt?: Date | null | undefined;
|
|
839
|
+
}>;
|
|
840
|
+
getEvent(key: string | any[], id: string): Promise<{
|
|
841
|
+
id: string;
|
|
842
|
+
name: string;
|
|
843
|
+
createdAt: Date;
|
|
844
|
+
updatedAt: Date;
|
|
845
|
+
runs: {
|
|
846
|
+
id: string;
|
|
847
|
+
status: "PENDING" | "CANCELED" | "SUCCESS" | "QUEUED" | "WAITING_ON_CONNECTIONS" | "PREPROCESSING" | "STARTED" | "FAILURE" | "TIMED_OUT" | "ABORTED";
|
|
848
|
+
startedAt?: Date | null | undefined;
|
|
849
|
+
completedAt?: Date | null | undefined;
|
|
850
|
+
}[];
|
|
851
|
+
}>;
|
|
852
|
+
/** `io.cancelEvent()` allows you to cancel an event that was previously sent with `io.sendEvent()`. This will prevent any Jobs from running that are listening for that event if the event was sent with a delay
|
|
853
|
+
* @param key
|
|
854
|
+
* @param eventId
|
|
855
|
+
* @returns
|
|
856
|
+
*/
|
|
857
|
+
cancelEvent(key: string | any[], eventId: string): Promise<{
|
|
858
|
+
id: string;
|
|
859
|
+
name: string;
|
|
860
|
+
payload: ((string | number | boolean | {
|
|
861
|
+
[key: string]: _trigger_dev_core.DeserializedJson;
|
|
862
|
+
} | _trigger_dev_core.DeserializedJson[]) & (string | number | boolean | {
|
|
863
|
+
[key: string]: _trigger_dev_core.DeserializedJson;
|
|
864
|
+
} | _trigger_dev_core.DeserializedJson[] | undefined)) | null;
|
|
865
|
+
timestamp: Date;
|
|
866
|
+
context?: _trigger_dev_core.DeserializedJson | undefined;
|
|
867
|
+
deliverAt?: Date | null | undefined;
|
|
868
|
+
deliveredAt?: Date | null | undefined;
|
|
869
|
+
cancelledAt?: Date | null | undefined;
|
|
817
870
|
}>;
|
|
818
871
|
updateSource(key: string | any[], options: {
|
|
819
872
|
key: string;
|
package/dist/index.js
CHANGED
|
@@ -131,7 +131,7 @@ var Job = class {
|
|
|
131
131
|
trigger: this.trigger.toJSON(),
|
|
132
132
|
integrations: this.integrations,
|
|
133
133
|
startPosition: "latest",
|
|
134
|
-
enabled:
|
|
134
|
+
enabled: this.enabled,
|
|
135
135
|
preprocessRuns: this.trigger.preprocessRuns,
|
|
136
136
|
internal
|
|
137
137
|
};
|
|
@@ -189,20 +189,6 @@ var ApiClient = class {
|
|
|
189
189
|
}
|
|
190
190
|
return await response.json();
|
|
191
191
|
}
|
|
192
|
-
async createRun(params) {
|
|
193
|
-
const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
|
|
194
|
-
__privateGet(this, _logger).debug("Creating run", {
|
|
195
|
-
params
|
|
196
|
-
});
|
|
197
|
-
return await zodfetch(import_core.CreateRunResponseBodySchema, `${__privateGet(this, _apiUrl)}/api/v1/runs`, {
|
|
198
|
-
method: "POST",
|
|
199
|
-
headers: {
|
|
200
|
-
"Content-Type": "application/json",
|
|
201
|
-
Authorization: `Bearer ${apiKey}`
|
|
202
|
-
},
|
|
203
|
-
body: JSON.stringify(params)
|
|
204
|
-
});
|
|
205
|
-
}
|
|
206
192
|
async runTask(runId, task) {
|
|
207
193
|
const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
|
|
208
194
|
__privateGet(this, _logger).debug("Running Task", {
|
|
@@ -265,6 +251,19 @@ var ApiClient = class {
|
|
|
265
251
|
})
|
|
266
252
|
});
|
|
267
253
|
}
|
|
254
|
+
async cancelEvent(eventId) {
|
|
255
|
+
const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
|
|
256
|
+
__privateGet(this, _logger).debug("Cancelling event", {
|
|
257
|
+
eventId
|
|
258
|
+
});
|
|
259
|
+
return await zodfetch(import_core.ApiEventLogSchema, `${__privateGet(this, _apiUrl)}/api/v1/events/${eventId}/cancel`, {
|
|
260
|
+
method: "POST",
|
|
261
|
+
headers: {
|
|
262
|
+
"Content-Type": "application/json",
|
|
263
|
+
Authorization: `Bearer ${apiKey}`
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
268
267
|
async updateSource(client, key, source) {
|
|
269
268
|
const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
|
|
270
269
|
__privateGet(this, _logger).debug("activating http source", {
|
|
@@ -675,6 +674,38 @@ var IO = class {
|
|
|
675
674
|
return await this._triggerClient.sendEvent(event, options);
|
|
676
675
|
});
|
|
677
676
|
}
|
|
677
|
+
async getEvent(key, id) {
|
|
678
|
+
return await this.runTask(key, {
|
|
679
|
+
name: "getEvent",
|
|
680
|
+
params: {
|
|
681
|
+
id
|
|
682
|
+
},
|
|
683
|
+
properties: [
|
|
684
|
+
{
|
|
685
|
+
label: "id",
|
|
686
|
+
text: id
|
|
687
|
+
}
|
|
688
|
+
]
|
|
689
|
+
}, async (task) => {
|
|
690
|
+
return await this._triggerClient.getEvent(id);
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
async cancelEvent(key, eventId) {
|
|
694
|
+
return await this.runTask(key, {
|
|
695
|
+
name: "cancelEvent",
|
|
696
|
+
params: {
|
|
697
|
+
eventId
|
|
698
|
+
},
|
|
699
|
+
properties: [
|
|
700
|
+
{
|
|
701
|
+
label: "id",
|
|
702
|
+
text: eventId
|
|
703
|
+
}
|
|
704
|
+
]
|
|
705
|
+
}, async (task) => {
|
|
706
|
+
return await this._triggerClient.cancelEvent(eventId);
|
|
707
|
+
});
|
|
708
|
+
}
|
|
678
709
|
async updateSource(key, options) {
|
|
679
710
|
return this.runTask(key, {
|
|
680
711
|
name: "Update Source",
|
|
@@ -1375,9 +1406,6 @@ var TriggerClient = class {
|
|
|
1375
1406
|
};
|
|
1376
1407
|
}
|
|
1377
1408
|
attach(job) {
|
|
1378
|
-
if (!job.enabled) {
|
|
1379
|
-
return;
|
|
1380
|
-
}
|
|
1381
1409
|
__privateGet(this, _registeredJobs)[job.id] = job;
|
|
1382
1410
|
job.trigger.attachToJob(this, job);
|
|
1383
1411
|
}
|
|
@@ -1495,6 +1523,9 @@ var TriggerClient = class {
|
|
|
1495
1523
|
async sendEvent(event, options) {
|
|
1496
1524
|
return __privateGet(this, _client).sendEvent(event, options);
|
|
1497
1525
|
}
|
|
1526
|
+
async cancelEvent(eventId) {
|
|
1527
|
+
return __privateGet(this, _client).cancelEvent(eventId);
|
|
1528
|
+
}
|
|
1498
1529
|
async registerSchedule(id, key, schedule) {
|
|
1499
1530
|
return __privateGet(this, _client).registerSchedule(this.id, id, key, schedule);
|
|
1500
1531
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/job.ts","../src/triggerClient.ts","../src/apiClient.ts","../src/errors.ts","../src/io.ts","../src/ioWithIntegrations.ts","../src/retry.ts","../src/triggers/eventTrigger.ts","../src/integrations.ts","../src/triggers/externalSource.ts","../src/triggers/dynamic.ts","../src/triggers/scheduled.ts","../src/triggers/notifications.ts"],"sourcesContent":["export * from \"./job\";\nexport * from \"./triggerClient\";\nexport * from \"./integrations\";\nexport * from \"./triggers/eventTrigger\";\nexport * from \"./triggers/externalSource\";\nexport * from \"./triggers/dynamic\";\nexport * from \"./triggers/scheduled\";\nexport * from \"./triggers/notifications\";\nexport * from \"./io\";\nexport * from \"./types\";\n\nimport { ServerTask } from \"@trigger.dev/core\";\nimport { RedactString } from \"./types\";\nexport { isTriggerError } from \"./errors\";\n\nexport type { NormalizedRequest, EventFilter } from \"@trigger.dev/core\";\n\nexport type Task = ServerTask;\n\nimport { ApiEventLog } from \"@trigger.dev/core\";\nexport type SentEvent = ApiEventLog;\n\n/*\n * This function is used to create a redacted string that can be used in the headers of a fetch request.\n * It is used to prevent the string from being logged in trigger.dev.\n * You can use it like this:\n *\n * await io.backgroundFetch<SomeResponseType>(\"https://example.com\", {\n * headers: {\n * Authorization: redactString`Bearer ${ACCESS_TOKEN}`,\n * },\n * })\n */\nexport function redactString(\n strings: TemplateStringsArray,\n ...interpolations: string[]\n): RedactString {\n return {\n __redactedString: true,\n strings: strings.raw as string[],\n interpolations,\n };\n}\n","export function slugifyId(input: string): string {\n // Replace any number of spaces with a single dash\n const replaceSpacesWithDash = input.toLowerCase().replace(/\\s+/g, \"-\");\n\n // Remove any non-URL-safe characters\n const removeNonUrlSafeChars = replaceSpacesWithDash.replace(/[^a-zA-Z0-9-._~]/g, \"\");\n\n return removeNonUrlSafeChars;\n}\n","import { IntegrationConfig, JobMetadata, LogLevel, QueueOptions } from \"@trigger.dev/core\";\nimport { IOWithIntegrations, IntegrationClient, TriggerIntegration } from \"./integrations\";\nimport { TriggerClient } from \"./triggerClient\";\nimport type { EventSpecification, Trigger, TriggerContext, TriggerEventType } from \"./types\";\nimport { slugifyId } from \"./utils\";\n\nexport type JobOptions<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>> = {},\n> = {\n /** The `id` property is used to uniquely identify the Job. Only change this if you want to create a new Job. */\n id: string;\n /** The `name` of the Job that you want to appear in the dashboard and logs. You can change this without creating a new Job. */\n name: string;\n /** The `version` property is used to version your Job. A new version will be created if you change this property. We recommend using [semantic versioning](https://www.baeldung.com/cs/semantic-versioning), e.g. `1.0.3`. */\n version: string;\n /** The `trigger` property is used to define when the Job should run. There are currently the following Trigger types:\n - [cronTrigger](https://trigger.dev/docs/sdk/crontrigger)\n - [intervalTrigger](https://trigger.dev/docs/sdk/intervaltrigger)\n - [eventTrigger](https://trigger.dev/docs/sdk/eventtrigger)\n - [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger)\n - [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule)\n - integration Triggers, like webhooks. See the [integrations](https://trigger.dev/docs/integrations) page for more information. */\n trigger: TTrigger;\n /** The `logLevel` property is an optional property that specifies the level of\n logging for the Job. The level is inherited from the client if you omit this property. */\n logLevel?: LogLevel;\n /** Imports the specified integrations into the Job. The integrations will be available on the `io` object in the `run()` function with the same name as the key. For example:\n ```ts\n client.defineJob({\n //... other options\n integrations: {\n slack,\n gh: github,\n },\n run: async (payload, io, ctx) => {\n //slack is available on io.slack\n io.slack.postMessage(...);\n //github is available on io.gh\n io.gh.addIssueLabels(...);\n }\n });\n ``` */\n integrations?: TIntegrations;\n /** @deprecated This property is deprecated and no longer effects the execution of the Job\n * */\n queue?: QueueOptions | string;\n /** The `enabled` property is used to enable or disable the Job. If you disable a Job, it will not run. */\n enabled?: boolean;\n /** This function gets called automatically when a Run is Triggered.\n * This is where you put the code you want to run for a Job. You can use normal code in here and you can also use Tasks. You can return a value from this function and it will be sent back to the Trigger API.\n * @param payload The payload of the event\n * @param io An object that contains the integrations that you specified in the `integrations` property and other useful functions like delays and running Tasks.\n * @param context An object that contains information about the Organization, Job, Run and more.\n */\n run: (\n payload: TriggerEventType<TTrigger>,\n io: IOWithIntegrations<TIntegrations>,\n context: TriggerContext\n ) => Promise<any>;\n};\n\nexport type JobPayload<TJob> = TJob extends Job<Trigger<EventSpecification<infer TEvent>>, any>\n ? TEvent\n : never;\n\nexport type JobIO<TJob> = TJob extends Job<any, infer TIntegrations>\n ? IOWithIntegrations<TIntegrations>\n : never;\n\n/** A [Job](https://trigger.dev/docs/documentation/concepts/jobs) is used to define the [Trigger](https://trigger.dev/docs/documentation/concepts/triggers), metadata, and what happens when it runs. */\nexport class Job<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>> = {},\n> {\n readonly options: JobOptions<TTrigger, TIntegrations>;\n\n client: TriggerClient;\n\n constructor(\n /** An instance of [TriggerClient](/sdk/triggerclient) that is used to send events\n to the Trigger API. */\n client: TriggerClient,\n options: JobOptions<TTrigger, TIntegrations>\n ) {\n this.client = client;\n this.options = options;\n this.#validate();\n\n client.attach(this);\n }\n\n get id() {\n return slugifyId(this.options.id);\n }\n\n get enabled() {\n return typeof this.options.enabled === \"boolean\" ? this.options.enabled : true;\n }\n\n get name() {\n return this.options.name;\n }\n\n get trigger() {\n return this.options.trigger;\n }\n\n get version() {\n return this.options.version;\n }\n\n get integrations(): Record<string, IntegrationConfig> {\n return Object.keys(this.options.integrations ?? {}).reduce(\n (acc: Record<string, IntegrationConfig>, key) => {\n const integration = this.options.integrations![key];\n\n acc[key] = {\n id: integration.id,\n metadata: integration.metadata,\n authSource: integration.client.usesLocalAuth ? \"LOCAL\" : \"HOSTED\",\n };\n\n return acc;\n },\n {}\n );\n }\n\n get logLevel() {\n return this.options.logLevel;\n }\n\n toJSON(): JobMetadata {\n // @ts-ignore\n const internal = this.options.__internal as JobMetadata[\"internal\"];\n\n return {\n id: this.id,\n name: this.name,\n version: this.version,\n event: this.trigger.event,\n trigger: this.trigger.toJSON(),\n integrations: this.integrations,\n startPosition: \"latest\", // this is deprecated, leaving this for now to make sure newer clients work with older servers\n enabled: typeof this.options.enabled === \"boolean\" ? this.options.enabled : true,\n preprocessRuns: this.trigger.preprocessRuns,\n internal,\n };\n }\n\n // Make sure the id is valid (must only contain alphanumeric characters and dashes)\n // Make sure the version is valid (must be a valid semver version)\n #validate() {\n if (!this.version.match(/^(\\d+)\\.(\\d+)\\.(\\d+)$/)) {\n throw new Error(\n `Invalid job version: \"${this.version}\". Job versions must be valid semver versions.`\n );\n }\n }\n}\n","import {\n ErrorWithStackSchema,\n GetRunOptionsWithTaskDetails,\n GetRunsOptions,\n HandleTriggerSource,\n HttpSourceRequestHeadersSchema,\n IndexEndpointResponse,\n InitializeTriggerBodySchema,\n LogLevel,\n Logger,\n NormalizedResponse,\n PreprocessRunBody,\n PreprocessRunBodySchema,\n Prettify,\n REGISTER_SOURCE_EVENT,\n RegisterSourceEvent,\n RegisterSourceEventSchema,\n RegisterTriggerBody,\n RunJobBody,\n RunJobBodySchema,\n RunJobResponse,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n SourceMetadata,\n} from \"@trigger.dev/core\";\nimport { ApiClient } from \"./apiClient\";\nimport { CanceledWithTaskError, ResumeWithTaskError, RetryWithTaskError } from \"./errors\";\nimport { IntegrationClient, TriggerIntegration } from \"./integrations\";\nimport { IO } from \"./io\";\nimport { createIOWithIntegrations } from \"./ioWithIntegrations\";\nimport { Job, JobOptions } from \"./job\";\nimport { DynamicTrigger } from \"./triggers/dynamic\";\nimport { EventTrigger } from \"./triggers/eventTrigger\";\nimport { ExternalSource } from \"./triggers/externalSource\";\nimport type {\n EventSpecification,\n Trigger,\n TriggerContext,\n TriggerPreprocessContext,\n} from \"./types\";\n\nconst registerSourceEvent: EventSpecification<RegisterSourceEvent> = {\n name: REGISTER_SOURCE_EVENT,\n title: \"Register Source\",\n source: \"internal\",\n icon: \"register-source\",\n parsePayload: RegisterSourceEventSchema.parse,\n};\n\nexport type TriggerClientOptions = {\n /** The `id` property is used to uniquely identify the client.\n */\n id: string;\n /** The `apiKey` property is the API Key for your Trigger.dev environment. We\n recommend using an environment variable to store your API Key. */\n apiKey?: string;\n /** The `apiUrl` property is an optional property that specifies the API URL. You\n only need to specify this if you are not using Trigger.dev Cloud and are\n running your own Trigger.dev instance. */\n apiUrl?: string;\n /** The `logLevel` property is an optional property that specifies the level of\n logging for the TriggerClient. The level is inherited by all Jobs that use this Client, unless they also specify a `logLevel`. */\n logLevel?: LogLevel;\n /** Very verbose log messages, defaults to false. */\n verbose?: boolean;\n /** Default is unset and off. If set to true it will log to the server's console as well as the Trigger.dev platform */\n ioLogLocalEnabled?: boolean;\n};\n\n/** A [TriggerClient](https://trigger.dev/docs/documentation/concepts/client-adaptors) is used to connect to a specific [Project](https://trigger.dev/docs/documentation/concepts/projects) by using an [API Key](https://trigger.dev/docs/documentation/concepts/environments-apikeys). */\nexport class TriggerClient {\n #options: TriggerClientOptions;\n #registeredJobs: Record<string, Job<Trigger<EventSpecification<any>>, any>> = {};\n #registeredSources: Record<string, SourceMetadata> = {};\n #registeredHttpSourceHandlers: Record<\n string,\n (\n source: HandleTriggerSource,\n request: Request\n ) => Promise<{\n events: Array<SendEvent>;\n response?: NormalizedResponse;\n } | void>\n > = {};\n #registeredDynamicTriggers: Record<\n string,\n DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>\n > = {};\n #jobMetadataByDynamicTriggers: Record<string, Array<{ id: string; version: string }>> = {};\n #registeredSchedules: Record<string, Array<{ id: string; version: string }>> = {};\n\n #client: ApiClient;\n #internalLogger: Logger;\n id: string;\n\n constructor(options: Prettify<TriggerClientOptions>) {\n this.id = options.id;\n this.#options = options;\n this.#client = new ApiClient(this.#options);\n this.#internalLogger = new Logger(\"trigger.dev\", this.#options.verbose ? \"debug\" : \"log\");\n }\n\n async handleRequest(request: Request): Promise<NormalizedResponse> {\n this.#internalLogger.debug(\"handling request\", {\n url: request.url,\n headers: Object.fromEntries(request.headers.entries()),\n method: request.method,\n });\n\n const apiKey = request.headers.get(\"x-trigger-api-key\");\n\n const authorization = this.authorized(apiKey);\n\n switch (authorization) {\n case \"authorized\": {\n break;\n }\n case \"missing-client\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: client missing apiKey\",\n },\n };\n }\n case \"missing-header\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: missing x-trigger-api-key header\",\n },\n };\n }\n case \"unauthorized\": {\n return {\n status: 401,\n body: {\n message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`,\n },\n };\n }\n }\n\n if (request.method !== \"POST\") {\n return {\n status: 405,\n body: {\n message: \"Method not allowed (only POST is allowed)\",\n },\n };\n }\n\n const action = request.headers.get(\"x-trigger-action\");\n\n if (!action) {\n return {\n status: 400,\n body: {\n message: \"Missing x-trigger-action header\",\n },\n };\n }\n\n switch (action) {\n case \"PING\": {\n const endpointId = request.headers.get(\"x-trigger-endpoint-id\");\n\n if (!endpointId) {\n return {\n status: 200,\n body: {\n ok: false,\n error: \"Missing endpoint ID\",\n },\n };\n }\n\n if (this.id !== endpointId) {\n return {\n status: 200,\n body: {\n ok: false,\n error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`,\n },\n };\n }\n\n return {\n status: 200,\n body: {\n ok: true,\n },\n };\n }\n case \"INDEX_ENDPOINT\": {\n // if the x-trigger-job-id header is set, we return the job with that id\n const jobId = request.headers.get(\"x-trigger-job-id\");\n\n if (jobId) {\n const job = this.#registeredJobs[jobId];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n return {\n status: 200,\n body: job.toJSON(),\n };\n }\n\n const body: IndexEndpointResponse = {\n jobs: Object.values(this.#registeredJobs).map((job) => job.toJSON()),\n sources: Object.values(this.#registeredSources),\n dynamicTriggers: Object.values(this.#registeredDynamicTriggers).map((trigger) => ({\n id: trigger.id,\n jobs: this.#jobMetadataByDynamicTriggers[trigger.id] ?? [],\n registerSourceJob: {\n id: dynamicTriggerRegisterSourceJobId(trigger.id),\n version: trigger.source.version,\n },\n })),\n dynamicSchedules: Object.entries(this.#registeredSchedules).map(([id, jobs]) => ({\n id,\n jobs,\n })),\n };\n\n // if the x-trigger-job-id header is not set, we return all jobs\n return {\n status: 200,\n body,\n };\n }\n case \"INITIALIZE_TRIGGER\": {\n const json = await request.json();\n const body = InitializeTriggerBodySchema.safeParse(json);\n\n if (!body.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid trigger body\",\n },\n };\n }\n\n const dynamicTrigger = this.#registeredDynamicTriggers[body.data.id];\n\n if (!dynamicTrigger) {\n return {\n status: 404,\n body: {\n message: \"Dynamic trigger not found\",\n },\n };\n }\n\n return {\n status: 200,\n body: dynamicTrigger.registeredTriggerForParams(body.data.params),\n };\n }\n case \"EXECUTE_JOB\": {\n const json = await request.json();\n const execution = RunJobBodySchema.safeParse(json);\n\n if (!execution.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid execution\",\n },\n };\n }\n\n const job = this.#registeredJobs[execution.data.job.id];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n const results = await this.#executeJob(execution.data, job);\n\n return {\n status: 200,\n body: results,\n };\n }\n case \"PREPROCESS_RUN\": {\n const json = await request.json();\n const body = PreprocessRunBodySchema.safeParse(json);\n\n if (!body.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid body\",\n },\n };\n }\n\n const job = this.#registeredJobs[body.data.job.id];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n const results = await this.#preprocessRun(body.data, job);\n\n return {\n status: 200,\n body: {\n abort: results.abort,\n properties: results.properties,\n },\n };\n }\n case \"DELIVER_HTTP_SOURCE_REQUEST\": {\n const headers = HttpSourceRequestHeadersSchema.safeParse(\n Object.fromEntries(request.headers.entries())\n );\n\n if (!headers.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid headers\",\n },\n };\n }\n\n const sourceRequestNeedsBody = headers.data[\"x-ts-http-method\"] !== \"GET\";\n\n const sourceRequestInit: RequestInit = {\n method: headers.data[\"x-ts-http-method\"],\n headers: headers.data[\"x-ts-http-headers\"],\n body: sourceRequestNeedsBody ? request.body : undefined,\n };\n\n if (sourceRequestNeedsBody) {\n try {\n // @ts-ignore\n sourceRequestInit.duplex = \"half\";\n } catch (error) {\n // ignore\n }\n }\n\n const sourceRequest = new Request(headers.data[\"x-ts-http-url\"], sourceRequestInit);\n\n const key = headers.data[\"x-ts-key\"];\n const dynamicId = headers.data[\"x-ts-dynamic-id\"];\n const secret = headers.data[\"x-ts-secret\"];\n const params = headers.data[\"x-ts-params\"];\n const data = headers.data[\"x-ts-data\"];\n\n const source = {\n key,\n dynamicId,\n secret,\n params,\n data,\n };\n\n const { response, events } = await this.#handleHttpSourceRequest(source, sourceRequest);\n\n return {\n status: 200,\n body: {\n events,\n response,\n },\n };\n }\n case \"VALIDATE\": {\n return {\n status: 200,\n body: {\n ok: true,\n endpointId: this.id,\n },\n };\n }\n }\n\n return {\n status: 405,\n body: {\n message: \"Method not allowed\",\n },\n };\n }\n\n attach(job: Job<Trigger<any>, any>): void {\n if (!job.enabled) {\n return;\n }\n\n this.#registeredJobs[job.id] = job;\n\n job.trigger.attachToJob(this, job);\n }\n\n attachDynamicTrigger(trigger: DynamicTrigger<any, any>): void {\n this.#registeredDynamicTriggers[trigger.id] = trigger;\n\n new Job(this, {\n id: dynamicTriggerRegisterSourceJobId(trigger.id),\n name: `Register dynamic trigger ${trigger.id}`,\n version: trigger.source.version,\n trigger: new EventTrigger({\n event: registerSourceEvent,\n filter: { dynamicTriggerId: [trigger.id] },\n }),\n integrations: {\n integration: trigger.source.integration,\n },\n run: async (event, io, ctx) => {\n const updates = await trigger.source.register(event.source.params, event, io, ctx);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await io.updateSource(\"update-source\", {\n key: event.source.key,\n ...updates,\n });\n },\n // @ts-ignore\n __internal: true,\n });\n }\n\n attachJobToDynamicTrigger(job: Job<Trigger<any>, any>, trigger: DynamicTrigger<any, any>): void {\n const jobs = this.#jobMetadataByDynamicTriggers[trigger.id] ?? [];\n\n jobs.push({ id: job.id, version: job.version });\n\n this.#jobMetadataByDynamicTriggers[trigger.id] = jobs;\n }\n\n attachSource(options: {\n key: string;\n source: ExternalSource<any, any>;\n event: EventSpecification<any>;\n params: any;\n }): void {\n this.#registeredHttpSourceHandlers[options.key] = async (s, r) => {\n return await options.source.handle(s, r, this.#internalLogger);\n };\n\n let registeredSource = this.#registeredSources[options.key];\n\n if (!registeredSource) {\n registeredSource = {\n channel: options.source.channel,\n key: options.key,\n params: options.params,\n events: [],\n integration: {\n id: options.source.integration.id,\n metadata: options.source.integration.metadata,\n authSource: options.source.integration.client.usesLocalAuth ? \"LOCAL\" : \"HOSTED\",\n },\n registerSourceJob: {\n id: options.key,\n version: options.source.version,\n },\n };\n }\n\n registeredSource.events = Array.from(\n new Set([\n ...registeredSource.events,\n ...(typeof options.event.name === \"string\" ? [options.event.name] : options.event.name),\n ])\n );\n\n this.#registeredSources[options.key] = registeredSource;\n\n new Job(this, {\n id: options.key,\n name: options.key,\n version: options.source.version,\n trigger: new EventTrigger({\n event: registerSourceEvent,\n filter: { source: { key: [options.key] } },\n }),\n integrations: {\n integration: options.source.integration,\n },\n run: async (event, io, ctx) => {\n const updates = await options.source.register(options.params, event, io, ctx);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await io.updateSource(\"update-source\", {\n key: options.key,\n ...updates,\n });\n },\n // @ts-ignore\n __internal: true,\n });\n }\n\n attachDynamicSchedule(key: string, job: Job<Trigger<any>, any>): void {\n const jobs = this.#registeredSchedules[key] ?? [];\n\n jobs.push({ id: job.id, version: job.version });\n\n this.#registeredSchedules[key] = jobs;\n }\n\n async registerTrigger(id: string, key: string, options: RegisterTriggerBody) {\n return this.#client.registerTrigger(this.id, id, key, options);\n }\n\n async getAuth(id: string) {\n return this.#client.getAuth(this.id, id);\n }\n\n /** You can call this function from anywhere in your code to send an event. The other way to send an event is by using [`io.sendEvent()`](https://trigger.dev/docs/sdk/io/sendevent) from inside a `run()` function.\n * @param event The event to send.\n * @param options Options for sending the event.\n * @returns A promise that resolves to the event details\n */\n async sendEvent(event: SendEvent, options?: SendEventOptions) {\n return this.#client.sendEvent(event, options);\n }\n\n async registerSchedule(id: string, key: string, schedule: ScheduleMetadata) {\n return this.#client.registerSchedule(this.id, id, key, schedule);\n }\n\n async unregisterSchedule(id: string, key: string) {\n return this.#client.unregisterSchedule(this.id, id, key);\n }\n\n async getEvent(eventId: string) {\n return this.#client.getEvent(eventId);\n }\n\n async getRun(runId: string, options?: GetRunOptionsWithTaskDetails) {\n return this.#client.getRun(runId, options);\n }\n\n async getRuns(jobSlug: string, options?: GetRunsOptions) {\n return this.#client.getRuns(jobSlug, options);\n }\n\n authorized(\n apiKey?: string | null\n ): \"authorized\" | \"unauthorized\" | \"missing-client\" | \"missing-header\" {\n if (typeof apiKey !== \"string\") {\n return \"missing-header\";\n }\n\n const localApiKey = this.#options.apiKey ?? process.env.TRIGGER_API_KEY;\n\n if (!localApiKey) {\n return \"missing-client\";\n }\n\n return apiKey === localApiKey ? \"authorized\" : \"unauthorized\";\n }\n\n apiKey() {\n return this.#options.apiKey ?? process.env.TRIGGER_API_KEY;\n }\n\n async #preprocessRun(body: PreprocessRunBody, job: Job<Trigger<EventSpecification<any>>, any>) {\n const context = this.#createPreprocessRunContext(body);\n\n const parsedPayload = job.trigger.event.parsePayload(body.event.payload ?? {});\n\n const properties = job.trigger.event.runProperties?.(parsedPayload) ?? [];\n\n return {\n abort: false,\n properties,\n };\n }\n\n async #executeJob(body: RunJobBody, job: Job<Trigger<any>, any>): Promise<RunJobResponse> {\n this.#internalLogger.debug(\"executing job\", {\n execution: body,\n job: job.toJSON(),\n });\n\n const context = this.#createRunContext(body);\n\n const io = new IO({\n id: body.run.id,\n cachedTasks: body.tasks,\n apiClient: this.#client,\n logger: this.#internalLogger,\n client: this,\n context,\n jobLogLevel: job.logLevel ?? this.#options.logLevel ?? \"info\",\n jobLogger: this.#options.ioLogLocalEnabled\n ? new Logger(job.id, job.logLevel ?? this.#options.logLevel ?? \"info\")\n : undefined,\n });\n\n const ioWithConnections = createIOWithIntegrations(\n io,\n body.connections,\n job.options.integrations\n );\n\n try {\n const output = await job.options.run(\n job.trigger.event.parsePayload(body.event.payload ?? {}),\n ioWithConnections,\n context\n );\n\n return { status: \"SUCCESS\", output };\n } catch (error) {\n if (error instanceof ResumeWithTaskError) {\n return { status: \"RESUME_WITH_TASK\", task: error.task };\n }\n\n if (error instanceof RetryWithTaskError) {\n return {\n status: \"RETRY_WITH_TASK\",\n task: error.task,\n error: error.cause,\n retryAt: error.retryAt,\n };\n }\n\n if (error instanceof CanceledWithTaskError) {\n return {\n status: \"CANCELED\",\n task: error.task,\n };\n }\n\n if (error instanceof RetryWithTaskError) {\n const errorWithStack = ErrorWithStackSchema.safeParse(error.cause);\n\n if (errorWithStack.success) {\n return {\n status: \"ERROR\",\n error: errorWithStack.data,\n task: error.task,\n };\n }\n\n return {\n status: \"ERROR\",\n error: { message: \"Unknown error\" },\n task: error.task,\n };\n }\n\n const errorWithStack = ErrorWithStackSchema.safeParse(error);\n\n if (errorWithStack.success) {\n return { status: \"ERROR\", error: errorWithStack.data };\n }\n\n return {\n status: \"ERROR\",\n error: { message: \"Unknown error\" },\n };\n }\n }\n\n #createRunContext(execution: RunJobBody): TriggerContext {\n const { event, organization, environment, job, run, source } = execution;\n\n return {\n event: {\n id: event.id,\n name: event.name,\n context: event.context,\n timestamp: event.timestamp,\n },\n organization,\n environment,\n job,\n run,\n account: execution.account,\n source,\n };\n }\n\n #createPreprocessRunContext(body: PreprocessRunBody): TriggerPreprocessContext {\n const { event, organization, environment, job, run, account } = body;\n\n return {\n event: {\n id: event.id,\n name: event.name,\n context: event.context,\n timestamp: event.timestamp,\n },\n organization,\n environment,\n job,\n run,\n account,\n };\n }\n\n async #handleHttpSourceRequest(\n source: {\n key: string;\n dynamicId?: string;\n secret: string;\n data: any;\n params: any;\n },\n sourceRequest: Request\n ): Promise<{ response: NormalizedResponse; events: SendEvent[] }> {\n this.#internalLogger.debug(\"Handling HTTP source request\", {\n source,\n });\n\n if (source.dynamicId) {\n const dynamicTrigger = this.#registeredDynamicTriggers[source.dynamicId];\n\n if (!dynamicTrigger) {\n this.#internalLogger.debug(\"No dynamic trigger registered for HTTP source\", {\n source,\n });\n\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n events: [],\n };\n }\n\n const results = await dynamicTrigger.source.handle(\n source,\n sourceRequest,\n this.#internalLogger\n );\n\n if (!results) {\n return {\n events: [],\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n return {\n events: results.events,\n response: results.response ?? {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n const handler = this.#registeredHttpSourceHandlers[source.key];\n\n if (!handler) {\n this.#internalLogger.debug(\"No handler registered for HTTP source\", {\n source,\n });\n\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n events: [],\n };\n }\n\n const results = await handler(source, sourceRequest);\n\n if (!results) {\n return {\n events: [],\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n return {\n events: results.events,\n response: results.response ?? {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n defineJob<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>> = {},\n >(options: JobOptions<TTrigger, TIntegrations>) {\n return new Job<TTrigger, TIntegrations>(this, options);\n }\n}\n\nfunction dynamicTriggerRegisterSourceJobId(id: string) {\n return `register-dynamic-trigger-${id}`;\n}\n","import {\n ApiEventLog,\n ApiEventLogSchema,\n CompleteTaskBodyInput,\n ConnectionAuthSchema,\n CreateRunBody,\n CreateRunResponseBodySchema,\n FailTaskBodyInput,\n GetEventSchema,\n GetRunOptionsWithTaskDetails,\n GetRunSchema,\n GetRunsOptions,\n GetRunsSchema,\n LogLevel,\n Logger,\n RegisterScheduleResponseBodySchema,\n RegisterSourceEvent,\n RegisterSourceEventSchema,\n RegisterTriggerBody,\n RunTaskBodyInput,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n ServerTaskSchema,\n TriggerSource,\n TriggerSourceSchema,\n UpdateTriggerSourceBody,\n urlWithSearchParams,\n} from \"@trigger.dev/core\";\n\nimport fetch, { type RequestInit } from \"node-fetch\";\nimport { z } from \"zod\";\n\nexport type ApiClientOptions = {\n apiKey?: string;\n apiUrl?: string;\n logLevel?: LogLevel;\n};\n\nexport type EndpointRecord = {\n id: string;\n name: string;\n url: string;\n};\n\nexport type HttpSourceRecord = {\n id: string;\n key: string;\n managed: boolean;\n url: string;\n status: \"PENDING\" | \"ACTIVE\" | \"INACTIVE\";\n secret?: string;\n data?: any;\n};\n\nexport type RunRecord = {\n id: string;\n jobId: string;\n callbackUrl: string;\n event: ApiEventLog;\n};\n\nexport class ApiClient {\n #apiUrl: string;\n #options: ApiClientOptions;\n #logger: Logger;\n\n constructor(options: ApiClientOptions) {\n this.#options = options;\n\n this.#apiUrl = this.#options.apiUrl ?? process.env.TRIGGER_API_URL ?? \"https://api.trigger.dev\";\n this.#logger = new Logger(\"trigger.dev\", this.#options.logLevel);\n }\n\n async registerEndpoint(options: { url: string; name: string }): Promise<EndpointRecord> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Registering endpoint\", {\n url: options.url,\n name: options.name,\n });\n\n const response = await fetch(`${this.#apiUrl}/api/v1/endpoints`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n url: options.url,\n name: options.name,\n }),\n });\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status !== 200) {\n throw new Error(`Failed to register entry point, got status code ${response.status}`);\n }\n\n return await response.json();\n }\n\n async createRun(params: CreateRunBody) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Creating run\", {\n params,\n });\n\n return await zodfetch(CreateRunResponseBodySchema, `${this.#apiUrl}/api/v1/runs`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(params),\n });\n }\n\n async runTask(runId: string, task: RunTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Running Task\", {\n task,\n });\n\n return await zodfetch(ServerTaskSchema, `${this.#apiUrl}/api/v1/runs/${runId}/tasks`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n \"Idempotency-Key\": task.idempotencyKey,\n },\n body: JSON.stringify(task),\n });\n }\n\n async completeTask(runId: string, id: string, task: CompleteTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Complete Task\", {\n task,\n });\n\n return await zodfetch(\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks/${id}/complete`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(task),\n }\n );\n }\n\n async failTask(runId: string, id: string, body: FailTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Fail Task\", {\n id,\n runId,\n body,\n });\n\n return await zodfetch(\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks/${id}/fail`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n }\n );\n }\n\n async sendEvent(event: SendEvent, options: SendEventOptions = {}) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Sending event\", {\n event,\n });\n\n return await zodfetch(ApiEventLogSchema, `${this.#apiUrl}/api/v1/events`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ event, options }),\n });\n }\n\n async updateSource(\n client: string,\n key: string,\n source: UpdateTriggerSourceBody\n ): Promise<TriggerSource> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"activating http source\", {\n source,\n });\n\n const response = await zodfetch(\n TriggerSourceSchema,\n `${this.#apiUrl}/api/v1/${client}/sources/${key}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(source),\n }\n );\n\n return response;\n }\n\n async registerTrigger(\n client: string,\n id: string,\n key: string,\n payload: RegisterTriggerBody\n ): Promise<RegisterSourceEvent> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering trigger\", {\n id,\n payload,\n });\n\n const response = await zodfetch(\n RegisterSourceEventSchema,\n `${this.#apiUrl}/api/v1/${client}/triggers/${id}/registrations/${key}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n }\n );\n\n return response;\n }\n\n async registerSchedule(client: string, id: string, key: string, payload: ScheduleMetadata) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering schedule\", {\n id,\n payload,\n });\n\n const response = await zodfetch(\n RegisterScheduleResponseBodySchema,\n `${this.#apiUrl}/api/v1/${client}/schedules/${id}/registrations`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ id: key, ...payload }),\n }\n );\n\n return response;\n }\n\n async unregisterSchedule(client: string, id: string, key: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"unregistering schedule\", {\n id,\n });\n\n const response = await zodfetch(\n z.object({ ok: z.boolean() }),\n `${this.#apiUrl}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`,\n {\n method: \"DELETE\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n\n return response;\n }\n\n async getAuth(client: string, id: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"getting auth\", {\n id,\n });\n\n const response = await zodfetch(\n ConnectionAuthSchema,\n `${this.#apiUrl}/api/v1/${client}/auth/${id}`,\n {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n },\n {\n optional: true,\n }\n );\n\n return response;\n }\n\n async getEvent(eventId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Event\", {\n eventId,\n });\n\n return await zodfetch(GetEventSchema, `${this.#apiUrl}/api/v1/events/${eventId}`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async getRun(runId: string, options?: GetRunOptionsWithTaskDetails) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Run\", {\n runId,\n });\n\n return await zodfetch(\n GetRunSchema,\n urlWithSearchParams(`${this.#apiUrl}/api/v1/runs/${runId}`, options),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async getRuns(jobSlug: string, options?: GetRunsOptions) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Runs\", {\n jobSlug,\n });\n\n return await zodfetch(\n GetRunsSchema,\n urlWithSearchParams(`${this.#apiUrl}/api/v1/jobs/${jobSlug}/runs`, options),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async #apiKey() {\n const apiKey = getApiKey(this.#options.apiKey);\n\n if (apiKey.status === \"invalid\") {\n throw new Error(\"Invalid API key\");\n\n // const chalk = (await import(\"chalk\")).default;\n // const terminalLink = (await import(\"terminal-link\")).default;\n\n // throw new Error(\n // `${chalk.red(\"Trigger.dev error\")}: Invalid API key (\"${chalk.italic(\n // apiKey.apiKey\n // )}\"), please set the TRIGGER_API_KEY environment variable or pass the apiKey option to a valid value. ${terminalLink(\n // \"Get your API key here\",\n // \"https://app.trigger.dev\",\n // {\n // fallback(text, url) {\n // return `${text} 👉 ${url}`;\n // },\n // }\n // )}`\n // );\n } else if (apiKey.status === \"missing\") {\n throw new Error(\"Missing API key\");\n // const chalk = (await import(\"chalk\")).default;\n // const terminalLink = (await import(\"terminal-link\")).default;\n\n // throw new Error(\n // `${chalk.red(\n // \"Trigger.dev error\"\n // )}: Missing an API key, please set the TRIGGER_API_KEY environment variable or pass the apiKey option to the Trigger constructor. ${terminalLink(\n // \"Get your API key here\",\n // \"https://app.trigger.dev\",\n // {\n // fallback(text, url) {\n // return `${text} 👉 ${url}`;\n // },\n // }\n // )}`\n // );\n }\n\n return apiKey.apiKey;\n }\n}\n\nfunction getApiKey(key?: string) {\n const apiKey = key ?? process.env.TRIGGER_API_KEY;\n\n if (!apiKey) {\n return { status: \"missing\" as const };\n }\n\n // Validate the api_key format (should be tr_{env}_XXXXX)\n const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);\n\n if (!isValid) {\n return { status: \"invalid\" as const, apiKey };\n }\n\n return { status: \"valid\" as const, apiKey };\n}\n\nasync function zodfetch<TResponseBody extends any, TOptional extends boolean = false>(\n schema: z.Schema<TResponseBody>,\n url: string,\n requestInit?: RequestInit,\n options?: {\n errorMessage?: string;\n optional?: TOptional;\n }\n): Promise<TOptional extends true ? TResponseBody | undefined : TResponseBody> {\n const response = await fetch(url, requestInit);\n\n if (\n (!requestInit || requestInit.method === \"GET\") &&\n response.status === 404 &&\n options?.optional\n ) {\n // @ts-ignore\n return;\n }\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status !== 200) {\n throw new Error(\n options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`\n );\n }\n\n const jsonBody = await response.json();\n\n return schema.parse(jsonBody);\n}\n","import { ErrorWithStack, ServerTask } from \"@trigger.dev/core\";\n\nexport class ResumeWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\nexport class RetryWithTaskError {\n constructor(\n public cause: ErrorWithStack,\n public task: ServerTask,\n public retryAt: Date\n ) {}\n}\n\nexport class CanceledWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\n/** Use this function if you're using a `try/catch` block to catch errors.\n * It checks if a thrown error is a special internal error that you should ignore.\n * If this returns `true` then you must rethrow the error: `throw err;`\n * @param err The error to check\n * @returns `true` if the error is a Trigger Error, `false` otherwise.\n */\nexport function isTriggerError(\n err: unknown\n): err is ResumeWithTaskError | RetryWithTaskError | CanceledWithTaskError {\n return (\n err instanceof ResumeWithTaskError ||\n err instanceof RetryWithTaskError ||\n err instanceof CanceledWithTaskError\n );\n}\n","import {\n CachedTask,\n ConnectionAuth,\n CronOptions,\n ErrorWithStackSchema,\n FetchRequestInit,\n FetchRetryOptions,\n IntervalOptions,\n LogLevel,\n Logger,\n RunTaskOptions,\n SendEvent,\n SendEventOptions,\n SerializableJson,\n SerializableJsonSchema,\n ServerTask,\n UpdateTriggerSourceBody,\n} from \"@trigger.dev/core\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { webcrypto } from \"node:crypto\";\nimport { ApiClient } from \"./apiClient\";\nimport {\n CanceledWithTaskError,\n ResumeWithTaskError,\n RetryWithTaskError,\n isTriggerError,\n} from \"./errors\";\nimport { createIOWithIntegrations } from \"./ioWithIntegrations\";\nimport { calculateRetryAt } from \"./retry\";\nimport { TriggerClient } from \"./triggerClient\";\nimport { DynamicTrigger } from \"./triggers/dynamic\";\nimport { ExternalSource, ExternalSourceParams } from \"./triggers/externalSource\";\nimport { DynamicSchedule } from \"./triggers/scheduled\";\nimport { EventSpecification, TaskLogger, TriggerContext } from \"./types\";\n\nexport type IOTask = ServerTask;\n\nexport type IOOptions = {\n id: string;\n apiClient: ApiClient;\n client: TriggerClient;\n context: TriggerContext;\n logger?: Logger;\n logLevel?: LogLevel;\n jobLogger?: Logger;\n jobLogLevel: LogLevel;\n cachedTasks?: Array<CachedTask>;\n};\n\nexport class IO {\n private _id: string;\n private _apiClient: ApiClient;\n private _triggerClient: TriggerClient;\n private _logger: Logger;\n private _jobLogger?: Logger;\n private _jobLogLevel: LogLevel;\n private _cachedTasks: Map<string, CachedTask>;\n private _taskStorage: AsyncLocalStorage<{ taskId: string }>;\n private _context: TriggerContext;\n\n constructor(options: IOOptions) {\n this._id = options.id;\n this._apiClient = options.apiClient;\n this._triggerClient = options.client;\n this._logger = options.logger ?? new Logger(\"trigger.dev\", options.logLevel);\n this._cachedTasks = new Map();\n this._jobLogger = options.jobLogger;\n this._jobLogLevel = options.jobLogLevel;\n\n if (options.cachedTasks) {\n options.cachedTasks.forEach((task) => {\n this._cachedTasks.set(task.idempotencyKey, task);\n });\n }\n\n this._taskStorage = new AsyncLocalStorage();\n this._context = options.context;\n }\n\n /** Used to send log messages to the [Run log](https://trigger.dev/docs/documentation/guides/viewing-runs). */\n get logger() {\n return new IOLogger(async (level, message, data) => {\n let logLevel: LogLevel = \"info\";\n\n switch (level) {\n case \"LOG\": {\n this._jobLogger?.log(message, data);\n logLevel = \"log\";\n break;\n }\n case \"DEBUG\": {\n this._jobLogger?.debug(message, data);\n logLevel = \"debug\";\n break;\n }\n case \"INFO\": {\n this._jobLogger?.info(message, data);\n logLevel = \"info\";\n break;\n }\n case \"WARN\": {\n this._jobLogger?.warn(message, data);\n logLevel = \"warn\";\n break;\n }\n case \"ERROR\": {\n this._jobLogger?.error(message, data);\n logLevel = \"error\";\n break;\n }\n }\n\n if (Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {\n await this.runTask(\n [message, level],\n {\n name: \"log\",\n icon: \"log\",\n description: message,\n params: data,\n properties: [{ label: \"Level\", text: level }],\n style: { style: \"minimal\", variant: level.toLowerCase() },\n noop: true,\n },\n async (task) => {}\n );\n }\n });\n }\n\n /** `io.wait()` waits for the specified amount of time before continuing the Job. Delays work even if you're on a serverless platform with timeouts, or if your server goes down. They utilize [resumability](https://trigger.dev/docs/documentation/concepts/resumability) to ensure that the Run can be resumed after the delay.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param seconds The number of seconds to wait. This can be very long, serverless timeouts are not an issue.\n */\n async wait(key: string | any[], seconds: number) {\n return await this.runTask(\n key,\n {\n name: \"wait\",\n icon: \"clock\",\n params: { seconds },\n noop: true,\n delayUntil: new Date(Date.now() + seconds * 1000),\n style: { style: \"minimal\" },\n },\n async (task) => {}\n );\n }\n\n /** `io.backgroundFetch()` fetches data from a URL that can take longer that the serverless timeout. The actual `fetch` request is performed on the Trigger.dev platform, and the response is sent back to you.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param url The URL to fetch from.\n * @param requestInit The options for the request\n * @param retry The options for retrying the request if it fails\n * An object where the key is a status code pattern and the value is a retrying strategy.\n * Supported patterns are:\n * - Specific status codes: 429\n * - Ranges: 500-599\n * - Wildcards: 2xx, 3xx, 4xx, 5xx\n */\n async backgroundFetch<TResponseData>(\n key: string | any[],\n url: string,\n requestInit?: FetchRequestInit,\n retry?: FetchRetryOptions\n ): Promise<TResponseData> {\n const urlObject = new URL(url);\n\n return (await this.runTask(\n key,\n {\n name: `fetch ${urlObject.hostname}${urlObject.pathname}`,\n params: { url, requestInit, retry },\n operation: \"fetch\",\n icon: \"background\",\n noop: false,\n properties: [\n {\n label: \"url\",\n text: url,\n url,\n },\n {\n label: \"method\",\n text: requestInit?.method ?? \"GET\",\n },\n {\n label: \"background\",\n text: \"true\",\n },\n ],\n },\n async (task) => {\n return task.output;\n }\n )) as TResponseData;\n }\n\n /** `io.sendEvent()` allows you to send an event from inside a Job run. The sent even will trigger any Jobs that are listening for that event (based on the name).\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param event The event to send. The event name must match the name of the event that your Jobs are listening for.\n * @param options Options for sending the event.\n */\n async sendEvent(key: string | any[], event: SendEvent, options?: SendEventOptions) {\n return await this.runTask(\n key,\n {\n name: \"sendEvent\",\n params: { event, options },\n properties: [\n {\n label: \"name\",\n text: event.name,\n },\n ...(event?.id ? [{ label: \"ID\", text: event.id }] : []),\n ],\n },\n async (task) => {\n return await this._triggerClient.sendEvent(event, options);\n }\n );\n }\n\n async updateSource(key: string | any[], options: { key: string } & UpdateTriggerSourceBody) {\n return this.runTask(\n key,\n {\n name: \"Update Source\",\n description: \"Update Source\",\n properties: [\n {\n label: \"key\",\n text: options.key,\n },\n ],\n params: options,\n redact: {\n paths: [\"secret\"],\n },\n },\n async (task) => {\n return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);\n }\n );\n }\n\n /** `io.registerInterval()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular interval.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n * @param options The options for the interval.\n * @returns A promise that has information about the interval.\n */\n async registerInterval(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: IntervalOptions\n ) {\n return await this.runTask(\n key,\n {\n name: \"register-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n { label: \"seconds\", text: options.seconds.toString() },\n ],\n params: options,\n },\n async (task) => {\n return dynamicSchedule.register(id, {\n type: \"interval\",\n options,\n });\n }\n );\n }\n\n /** `io.unregisterInterval()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerInterval()`.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n */\n async unregisterInterval(key: string | any[], dynamicSchedule: DynamicSchedule, id: string) {\n return await this.runTask(\n key,\n {\n name: \"unregister-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n },\n async (task) => {\n return dynamicSchedule.unregister(id);\n }\n );\n }\n\n /** `io.registerCron()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular CRON schedule.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.\n * @param id A unique id for the schedule. This is used to identify and unregister the schedule later.\n * @param options The options for the CRON schedule.\n */\n async registerCron(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: CronOptions\n ) {\n return await this.runTask(\n key,\n {\n name: \"register-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n { label: \"cron\", text: options.cron },\n ],\n params: options,\n },\n async (task) => {\n return dynamicSchedule.register(id, {\n type: \"cron\",\n options,\n });\n }\n );\n }\n\n /** `io.unregisterCron()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerCron()`.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n */\n async unregisterCron(key: string | any[], dynamicSchedule: DynamicSchedule, id: string) {\n return await this.runTask(\n key,\n {\n name: \"unregister-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n },\n async (task) => {\n return dynamicSchedule.unregister(id);\n }\n );\n }\n\n /** `io.registerTrigger()` allows you to register a [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) with the specified trigger params.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param trigger The [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) to register.\n * @param id A unique id for the trigger. This is used to identify and unregister the trigger later.\n * @param params The params for the trigger.\n */\n async registerTrigger<\n TTrigger extends DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>,\n >(\n key: string | any[],\n trigger: TTrigger,\n id: string,\n params: ExternalSourceParams<TTrigger[\"source\"]>\n ): Promise<{ id: string; key: string } | undefined> {\n return await this.runTask(\n key,\n {\n name: \"register-trigger\",\n properties: [\n { label: \"trigger\", text: trigger.id },\n { label: \"id\", text: id },\n ],\n params: params as any,\n },\n async (task) => {\n const registration = await this.runTask(\n \"register-source\",\n {\n name: \"register-source\",\n },\n async (subtask1) => {\n return trigger.register(id, params);\n }\n );\n\n const connection = await this.getAuth(\"get-auth\", registration.source.clientId);\n\n const io = createIOWithIntegrations(\n // @ts-ignore\n this,\n {\n integration: connection,\n },\n {\n integration: trigger.source.integration,\n }\n );\n\n const updates = await trigger.source.register(params, registration, io, this._context);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await this.updateSource(\"update-source\", {\n key: registration.source.key,\n ...updates,\n });\n }\n );\n }\n\n async getAuth(key: string | any[], clientId?: string): Promise<ConnectionAuth | undefined> {\n if (!clientId) {\n return;\n }\n\n return this.runTask(key, { name: \"get-auth\" }, async (task) => {\n return await this._triggerClient.getAuth(clientId);\n });\n }\n\n /** `io.runTask()` allows you to run a [Task](https://trigger.dev/docs/documentation/concepts/tasks) from inside a Job run. A Task is a resumable unit of a Run that can be retried, resumed and is logged. [Integrations](https://trigger.dev/docs/integrations) use Tasks internally to perform their actions.\n *\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param options The options of how you'd like to run and log the Task. Name is required.\n * @param callback The callback that will be called when the Task is run. The callback receives the Task and the IO as parameters.\n= * @param onError The callback that will be called when the Task fails. The callback receives the error, the Task and the IO as parameters. If you wish to retry then return an object with a `retryAt` property.\n * @returns A Promise that resolves with the returned value of the callback.\n */\n async runTask<TResult extends SerializableJson | void = void, TCallbackResult extends unknown = TResult>(\n key: string | any[],\n options: RunTaskOptions,\n callback: (task: IOTask, io: IO) => Promise<TCallbackResult | TResult>,\n onError?: (\n error: unknown,\n task: IOTask,\n io: IO\n ) => { retryAt: Date; error?: Error; jitter?: number } | Error | undefined | void\n ): Promise<TResult> {\n const parentId = this._taskStorage.getStore()?.taskId;\n\n if (parentId) {\n this._logger.debug(\"Using parent task\", {\n parentId,\n key,\n options,\n });\n }\n\n const idempotencyKey = await generateIdempotencyKey([this._id, parentId ?? \"\", key].flat());\n\n const cachedTask = this._cachedTasks.get(idempotencyKey);\n\n if (cachedTask) {\n this._logger.debug(\"Using cached task\", {\n idempotencyKey,\n cachedTask,\n });\n\n return cachedTask.output as TResult;\n }\n\n const task = await this._apiClient.runTask(this._id, {\n idempotencyKey,\n displayKey: typeof key === \"string\" ? key : undefined,\n noop: false,\n ...options,\n parentId,\n });\n\n if (task.status === \"CANCELED\") {\n this._logger.debug(\"Task canceled\", {\n idempotencyKey,\n task,\n });\n\n throw new CanceledWithTaskError(task);\n }\n\n if (task.status === \"COMPLETED\") {\n this._logger.debug(\"Using task output\", {\n idempotencyKey,\n task,\n });\n\n this.#addToCachedTasks(task);\n\n return task.output as TResult;\n }\n\n if (task.status === \"ERRORED\") {\n this._logger.debug(\"Task errored\", {\n idempotencyKey,\n task,\n });\n\n throw new Error(task.error ?? \"Task errored\");\n }\n\n if (task.status === \"WAITING\") {\n this._logger.debug(\"Task waiting\", {\n idempotencyKey,\n task,\n });\n\n throw new ResumeWithTaskError(task);\n }\n\n if (task.status === \"RUNNING\" && typeof task.operation === \"string\") {\n this._logger.debug(\"Task running operation\", {\n idempotencyKey,\n task,\n });\n\n throw new ResumeWithTaskError(task);\n }\n\n const executeTask = async () => {\n try {\n const result = await callback(task, this);\n\n const output = SerializableJsonSchema.parse(result) as TResult;\n \n this._logger.debug(\"Completing using output\", {\n idempotencyKey,\n task,\n });\n\n const completedTask = await this._apiClient.completeTask(this._id, task.id, {\n output: output ?? undefined,\n properties: task.outputProperties ?? undefined,\n });\n\n if (completedTask.status === \"CANCELED\") {\n throw new CanceledWithTaskError(completedTask);\n }\n\n return output;\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n if (onError) {\n try {\n const onErrorResult = onError(error, task, this);\n\n if (onErrorResult) {\n if (onErrorResult instanceof Error) {\n error = onErrorResult;\n } else {\n const parsedError = ErrorWithStackSchema.safeParse(onErrorResult.error);\n\n throw new RetryWithTaskError(\n parsedError.success ? parsedError.data : { message: \"Unknown error\" },\n task,\n onErrorResult.retryAt\n );\n }\n }\n } catch (innerError) {\n if (isTriggerError(innerError)) {\n throw innerError;\n }\n\n error = innerError;\n }\n }\n\n const parsedError = ErrorWithStackSchema.safeParse(error);\n\n if (options.retry) {\n const retryAt = calculateRetryAt(options.retry, task.attempts - 1);\n\n if (retryAt) {\n throw new RetryWithTaskError(\n parsedError.success ? parsedError.data : { message: \"Unknown error\" },\n task,\n retryAt\n );\n }\n }\n\n if (parsedError.success) {\n await this._apiClient.failTask(this._id, task.id, {\n error: parsedError.data,\n });\n } else {\n await this._apiClient.failTask(this._id, task.id, {\n error: { message: JSON.stringify(error), name: \"Unknown Error\" },\n });\n }\n\n throw error;\n }\n };\n\n return this._taskStorage.run({ taskId: task.id }, executeTask);\n }\n\n /** `io.try()` allows you to run Tasks and catch any errors that are thrown, it's similar to a normal `try/catch` block but works with [io.runTask()](/sdk/io/runtask).\n * A regular `try/catch` block on its own won't work as expected with Tasks. Internally `runTask()` throws some special errors to control flow execution. This is necessary to deal with resumability, serverless timeouts, and retrying Tasks.\n * @param tryCallback The code you wish to run\n * @param catchCallback Thhis will be called if the Task fails. The callback receives the error\n * @returns A Promise that resolves with the returned value or the error\n */\n async try<TResult, TCatchResult>(\n tryCallback: () => Promise<TResult>,\n catchCallback: (error: unknown) => Promise<TCatchResult>\n ): Promise<TResult | TCatchResult> {\n try {\n return await tryCallback();\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n return await catchCallback(error);\n }\n }\n\n #addToCachedTasks(task: ServerTask) {\n this._cachedTasks.set(task.idempotencyKey, task);\n }\n}\n\n// Generate a stable idempotency key for the key material, using a stable json stringification\nasync function generateIdempotencyKey(keyMaterial: any[]) {\n const keys = keyMaterial.map((key) => {\n if (typeof key === \"string\") {\n return key;\n }\n\n return stableStringify(key);\n });\n\n const key = keys.join(\":\");\n\n const hash = await webcrypto.subtle.digest(\"SHA-256\", Buffer.from(key));\n\n return Buffer.from(hash).toString(\"hex\");\n}\n\nfunction stableStringify(obj: any): string {\n function sortKeys(obj: any): any {\n if (typeof obj !== \"object\" || obj === null) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortKeys);\n }\n\n const sortedKeys = Object.keys(obj).sort();\n const sortedObj: { [key: string]: any } = {};\n\n for (const key of sortedKeys) {\n sortedObj[key] = sortKeys(obj[key]);\n }\n\n return sortedObj;\n }\n\n const sortedObj = sortKeys(obj);\n return JSON.stringify(sortedObj);\n}\n\ntype CallbackFunction = (\n level: \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"LOG\",\n message: string,\n properties?: Record<string, any>\n) => Promise<void>;\n\nexport class IOLogger implements TaskLogger {\n constructor(private callback: CallbackFunction) {}\n\n /** Log: essential messages */\n log(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"LOG\", message, properties);\n }\n\n /** For debugging: the least important log level */\n debug(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"DEBUG\", message, properties);\n }\n\n /** Info: the second least important log level */\n info(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"INFO\", message, properties);\n }\n\n /** Warnings: the third most important log level */\n warn(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"WARN\", message, properties);\n }\n\n /** Error: The second most important log level */\n error(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"ERROR\", message, properties);\n }\n}\n","import { ConnectionAuth, RunTaskOptions } from \"@trigger.dev/core\";\nimport {\n AuthenticatedTask,\n IOWithIntegrations,\n IntegrationClient,\n TriggerIntegration,\n} from \"./integrations\";\nimport { IO } from \"./io\";\n\nexport function createIOWithIntegrations<\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>>,\n>(\n io: IO,\n auths?: Record<string, ConnectionAuth | undefined>,\n integrations?: TIntegrations\n): IOWithIntegrations<TIntegrations> {\n if (!integrations) {\n return io as IOWithIntegrations<TIntegrations>;\n }\n\n const connections = Object.entries(integrations).reduce((acc, [connectionKey, integration]) => {\n let auth = auths?.[connectionKey];\n\n const client = integration.client.usesLocalAuth\n ? integration.client.client\n : auth\n ? integration.client.clientFactory?.(auth)\n : undefined;\n\n if (!client) {\n return acc;\n }\n\n auth = integration.client.usesLocalAuth ? integration.client.auth : auth;\n\n const ioConnection = {\n client,\n } as any;\n\n ioConnection.runTask = async (\n key: string | any[],\n callback: (client: any, task: any, io: IO) => Promise<any>,\n options?: RunTaskOptions\n ) => {\n return await io.runTask(\n key,\n {\n name: \"Task\",\n icon: integration.metadata.id,\n retry: {\n limit: 10,\n minTimeoutInMs: 1000,\n maxTimeoutInMs: 30000,\n factor: 2,\n randomize: true,\n },\n ...options,\n },\n async (ioTask) => {\n return await callback(client, ioTask, io);\n }\n );\n };\n\n if (integration.client.tasks) {\n const tasks: Record<string, AuthenticatedTask<any, any, any, any>> = integration.client.tasks;\n\n Object.keys(tasks).forEach((taskName) => {\n const authenticatedTask = tasks[taskName];\n\n ioConnection[taskName] = async (key: string | string[], params: any) => {\n const options = authenticatedTask.init(params);\n options.connectionKey = connectionKey;\n\n return await io.runTask(\n key,\n options,\n async (ioTask) => {\n return authenticatedTask.run(params, client, ioTask, io, auth);\n },\n authenticatedTask.onError\n );\n };\n });\n }\n\n acc[connectionKey] = ioConnection;\n\n return acc;\n }, {} as any);\n\n return new Proxy(io, {\n get(target, prop, receiver) {\n // We can return the original io back if the prop is __io\n if (prop === \"__io\") {\n return io;\n }\n\n if (prop in connections) {\n return connections[prop];\n }\n\n const value = Reflect.get(target, prop, receiver);\n return typeof value == \"function\" ? value.bind(target) : value;\n },\n }) as IOWithIntegrations<TIntegrations>;\n}\n","import type { RetryOptions } from \"@trigger.dev/core\";\nimport { calculateRetryAt } from \"@trigger.dev/core\";\n\nexport { calculateRetryAt };\nexport type { RetryOptions };\n","import { EventFilter, TriggerMetadata, deepMergeFilters } from \"@trigger.dev/core\";\nimport { z } from \"zod\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, EventSpecificationExample, Trigger } from \"../types\";\n\ntype EventTriggerOptions<TEventSpecification extends EventSpecification<any>> = {\n event: TEventSpecification;\n name?: string | string[];\n source?: string;\n filter?: EventFilter;\n};\n\nexport class EventTrigger<TEventSpecification extends EventSpecification<any>>\n implements Trigger<TEventSpecification>\n{\n #options: EventTriggerOptions<TEventSpecification>;\n\n constructor(options: EventTriggerOptions<TEventSpecification>) {\n this.#options = options;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.#options.name ?? this.#options.event.title,\n rule: {\n event: this.#options.name ?? this.#options.event.name,\n source: this.#options.source ?? \"trigger.dev\",\n payload: deepMergeFilters(this.#options.filter ?? {}, this.#options.event.filter ?? {}),\n },\n };\n }\n\n get event() {\n return this.#options.event;\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>): void {}\n\n get preprocessRuns() {\n return false;\n }\n}\n\n/** Configuration options for an EventTrigger */\ntype TriggerOptions<TEvent> = {\n /** The name of the event you are subscribing to. Must be an exact match (case sensitive). To trigger on multiple possible events, pass in an array of event names */\n name: string | string[];\n /** A [Zod](https://trigger.dev/docs/documentation/guides/zod) schema that defines the shape of the event payload.\n * The default is `z.any()` which is `any`.\n * */\n schema?: z.Schema<TEvent>;\n /** You can use this to filter events based on the source. */\n source?: string;\n /** Used to filter which events trigger the Job\n * @example\n * filter:\n * ```ts\n * {\n * name: [\"John\", \"Jane\"],\n * age: [18, 21]\n * }\n * ```\n *\n * This filter would match against an event with the following data:\n * ```json\n * {\n * \"name\": \"Jane\",\n * \"age\": 18,\n * \"location\": \"San Francisco\"\n * }\n * ```\n */\n filter?: EventFilter;\n\n examples?: EventSpecificationExample[];\n};\n\n/** `eventTrigger()` is set as a [Job's trigger](https://trigger.dev/docs/sdk/job) to subscribe to an event a Job from [a sent event](https://trigger.dev/docs/sdk/triggerclient/instancemethods/sendevent)\n * @param options options for the EventTrigger\n */\nexport function eventTrigger<TEvent extends any = any>(\n options: TriggerOptions<TEvent>\n): Trigger<EventSpecification<TEvent>> {\n return new EventTrigger({\n name: options.name,\n filter: options.filter,\n event: {\n name: options.name,\n title: \"Event\",\n source: options.source ?? \"trigger.dev\",\n icon: \"custom-event\",\n examples: options.examples,\n parsePayload: (rawPayload: any) => {\n if (options.schema) {\n return options.schema.parse(rawPayload);\n }\n\n return rawPayload as any;\n },\n },\n });\n}\n","import { ConnectionAuth, IntegrationMetadata, RunTaskOptions, ServerTask } from \"@trigger.dev/core\";\nimport { IO, IOTask } from \"./io\";\n\ntype IntegrationRunTaskFunction<TClient> = <TResult>(\n key: string | any[],\n callback: (client: TClient, task: IOTask, io: IO) => Promise<TResult>,\n options?: RunTaskOptions\n) => Promise<TResult>;\n\nexport type ClientFactory<TClient> = (auth: ConnectionAuth) => TClient;\n\nexport interface TriggerIntegration<\n TIntegrationClient extends IntegrationClient<any, any> = IntegrationClient<any, any>,\n> {\n client: TIntegrationClient;\n id: string;\n metadata: IntegrationMetadata;\n}\n\nexport type IntegrationClient<\n TClient,\n TTasks extends Record<string, AuthenticatedTask<TClient, any, any, any>>,\n> =\n | {\n usesLocalAuth: true;\n client: TClient;\n tasks?: TTasks;\n auth: any;\n }\n | {\n usesLocalAuth: false;\n clientFactory: ClientFactory<TClient>;\n tasks?: TTasks;\n };\n\nexport type AuthenticatedTask<TClient, TParams, TResult, TAuth = ConnectionAuth> = {\n run: (\n params: TParams,\n client: TClient,\n task: ServerTask,\n io: IO,\n auth: TAuth\n ) => Promise<TResult>;\n init: (params: TParams) => RunTaskOptions;\n onError?: (\n error: unknown,\n task: ServerTask\n ) => { retryAt: Date; error?: Error } | Error | undefined | void;\n};\n\nexport function authenticatedTask<TClient, TParams, TResult>(options: {\n run: (params: TParams, client: TClient, task: ServerTask, io: IO) => Promise<TResult>;\n init: (params: TParams) => RunTaskOptions;\n}): AuthenticatedTask<TClient, TParams, TResult> {\n return options;\n}\n\ntype ExtractRunFunction<T> = T extends AuthenticatedTask<\n any,\n infer TParams,\n infer TResult,\n infer TAuth\n>\n ? (key: string, params: TParams) => Promise<TResult>\n : never;\n\ntype ExtractTasks<TTasks extends Record<string, AuthenticatedTask<any, any, any, any>>> = {\n [key in keyof TTasks]: ExtractRunFunction<TTasks[key]>;\n};\n\ntype ExtractIntegrationClientClient<TIntegrationClient extends IntegrationClient<any, any>> =\n TIntegrationClient extends {\n usesLocalAuth: true;\n client: infer TClient;\n }\n ? {\n client: TClient;\n runTask: IntegrationRunTaskFunction<TClient>;\n }\n : TIntegrationClient extends {\n usesLocalAuth: false;\n clientFactory: ClientFactory<infer TClient>;\n }\n ? {\n client: TClient;\n runTask: IntegrationRunTaskFunction<TClient>;\n }\n : never;\n\ntype ExtractIntegrationClient<TIntegrationClient extends IntegrationClient<any, any>> =\n ExtractIntegrationClientClient<TIntegrationClient> & ExtractTasks<TIntegrationClient[\"tasks\"]>;\n\nexport type IntegrationIO<TIntegration extends TriggerIntegration<IntegrationClient<any, any>>> =\n ExtractIntegrationClient<TIntegration[\"client\"]>;\n\ntype ExtractIntegrations<\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>>,\n> = {\n [key in keyof TIntegrations]: ExtractIntegrationClient<TIntegrations[key][\"client\"]>;\n};\n\nexport type IOWithIntegrations<\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>>,\n> = IO & ExtractIntegrations<TIntegrations>;\n","import { z } from \"zod\";\n\nimport {\n DisplayProperty,\n EventFilter,\n HandleTriggerSource,\n Logger,\n NormalizedResponse,\n RegisterSourceEvent,\n SendEvent,\n TriggerMetadata,\n UpdateTriggerSourceBody,\n deepMergeFilters,\n} from \"@trigger.dev/core\";\nimport { IOWithIntegrations, IntegrationClient, TriggerIntegration } from \"../integrations\";\nimport { IO } from \"../io\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport type { EventSpecification, Trigger, TriggerContext } from \"../types\";\nimport { slugifyId } from \"../utils\";\n\nexport type HttpSourceEvent = {\n url: string;\n method: string;\n headers: Record<string, string>;\n rawBody?: Buffer | null;\n};\n\ntype SmtpSourceEvent = {\n from: string;\n to: string;\n subject: string;\n body: string;\n};\n\ntype SqsSourceEvent = {\n body: string;\n};\n\ntype ExternalSourceChannelMap = {\n HTTP: {\n event: Request;\n register: {\n url: string;\n };\n };\n SMTP: {\n event: SmtpSourceEvent;\n register: {};\n };\n SQS: {\n event: SqsSourceEvent;\n register: {};\n };\n};\n\ntype ChannelNames = keyof ExternalSourceChannelMap;\n\ntype RegisterFunctionEvent<TChannel extends ChannelNames, TParams extends any> = {\n events: Array<string>;\n missingEvents: Array<string>;\n orphanedEvents: Array<string>;\n source: {\n active: boolean;\n data?: any;\n secret: string;\n } & ExternalSourceChannelMap[TChannel][\"register\"];\n params: TParams;\n};\n\ntype RegisterFunction<\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any,\n TChannel extends ChannelNames,\n> = (\n event: RegisterFunctionEvent<TChannel, TParams>,\n io: IOWithIntegrations<{ integration: TIntegration }>,\n ctx: TriggerContext\n) => Promise<UpdateTriggerSourceBody | undefined>;\n\nexport type HandlerEvent<TChannel extends ChannelNames, TParams extends any = any> = {\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"];\n source: HandleTriggerSource & { params: TParams };\n};\n\ntype HandlerFunction<TChannel extends ChannelNames, TParams extends any> = (\n event: HandlerEvent<TChannel, TParams>,\n logger: Logger\n) => Promise<{ events: SendEvent[]; response?: NormalizedResponse } | void>;\n\ntype KeyFunction<TParams extends any> = (params: TParams) => string;\ntype FilterFunction<TParams extends any> = (params: TParams) => EventFilter;\n\ntype ExternalSourceOptions<\n TChannel extends ChannelNames,\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any,\n> = {\n id: string;\n version: string;\n schema: z.Schema<TParams>;\n integration: TIntegration;\n register: RegisterFunction<TIntegration, TParams, TChannel>;\n filter?: FilterFunction<TParams>;\n handler: HandlerFunction<TChannel, TParams>;\n key: KeyFunction<TParams>;\n properties?: (params: TParams) => DisplayProperty[];\n};\n\nexport class ExternalSource<\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any,\n TChannel extends ChannelNames = ChannelNames,\n> {\n channel: TChannel;\n\n constructor(\n channel: TChannel,\n private options: ExternalSourceOptions<TChannel, TIntegration, TParams>\n ) {\n this.channel = channel;\n }\n\n async handle(\n source: HandleTriggerSource,\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"],\n logger: Logger\n ) {\n return this.options.handler(\n {\n source: { ...source, params: source.params as TParams },\n rawEvent,\n },\n logger\n );\n }\n\n filter(params: TParams): EventFilter {\n return this.options.filter?.(params) ?? {};\n }\n\n properties(params: TParams): DisplayProperty[] {\n return this.options.properties?.(params) ?? [];\n }\n\n async register(params: TParams, registerEvent: RegisterSourceEvent, io: IO, ctx: TriggerContext) {\n const { result: event, ommited: source } = omit(registerEvent, \"source\");\n const { result: sourceWithoutChannel, ommited: channel } = omit(source, \"channel\");\n const { result: channelWithoutType } = omit(channel, \"type\");\n\n const updates = await this.options.register(\n {\n ...event,\n source: { ...sourceWithoutChannel, ...channelWithoutType },\n params,\n },\n io as IOWithIntegrations<{ integration: TIntegration }>,\n ctx\n );\n\n return updates;\n }\n\n key(params: TParams): string {\n const parts = [this.options.id, this.channel];\n\n parts.push(this.options.key(params));\n parts.push(this.integration.id);\n\n return parts.join(\"-\");\n }\n\n get integration() {\n return this.options.integration;\n }\n\n get integrationConfig() {\n return {\n id: this.integration.id,\n metadata: this.integration.metadata,\n };\n }\n\n get id() {\n return this.options.id;\n }\n\n get version() {\n return this.options.version;\n }\n}\n\nexport type ExternalSourceParams<TExternalSource extends ExternalSource<any, any, any>> =\n TExternalSource extends ExternalSource<any, infer TParams, any>\n ? TParams & { filter?: EventFilter }\n : never;\n\nexport type ExternalSourceTriggerOptions<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>,\n> = {\n event: TEventSpecification;\n source: TEventSource;\n params: ExternalSourceParams<TEventSource>;\n};\n\nexport class ExternalSourceTrigger<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>,\n> implements Trigger<TEventSpecification>\n{\n constructor(private options: ExternalSourceTriggerOptions<TEventSpecification, TEventSource>) {}\n\n get event() {\n return this.options.event;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: \"External Source\",\n rule: {\n event: this.event.name,\n payload: deepMergeFilters(\n this.options.source.filter(this.options.params),\n this.event.filter ?? {},\n this.options.params.filter ?? {}\n ),\n source: this.event.source,\n },\n properties: this.options.source.properties(this.options.params),\n };\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>) {\n triggerClient.attachSource({\n key: slugifyId(this.options.source.key(this.options.params)),\n source: this.options.source,\n event: this.options.event,\n params: this.options.params,\n });\n }\n\n get preprocessRuns() {\n return true;\n }\n}\n\nexport function omit<T extends Record<string, unknown>, K extends keyof T>(\n obj: T,\n key: K\n): { result: Omit<T, K>; ommited: T[K] } {\n const result: any = {};\n\n for (const k of Object.keys(obj)) {\n if (k === key) continue;\n\n result[k] = obj[k];\n }\n\n return { result, ommited: obj[key] };\n}\n","import {\n RegisterSourceEvent,\n RegisterTriggerBody,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport { slugifyId } from \"../utils\";\nimport { ExternalSource, ExternalSourceParams } from \"./externalSource\";\n\n/** Options for a DynamicTrigger */\nexport type DynamicTriggerOptions<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n> = {\n /** Used to uniquely identify a DynamicTrigger */\n id: string;\n /** An event from an [Integration](https://trigger.dev/docs/integrations) package that you want to attach to the DynamicTrigger. The event types will come through to the payload in your Job's run. */\n event: TEventSpec;\n /** An external source fron an [Integration](https://trigger.dev/docs/integrations) package\n * @example \n * ```ts\n * import { events } from \"@trigger.dev/github\";\n * \n * const dynamicOnIssueOpened = new DynamicTrigger(client, {\n id: \"github-issue-opened\",\n event: events.onIssueOpened,\n source: github.sources.repo,\n });\n * ```\n */\n source: TExternalSource;\n};\n\n/** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime. */\nexport class DynamicTrigger<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n> implements Trigger<TEventSpec>\n{\n #client: TriggerClient;\n #options: DynamicTriggerOptions<TEventSpec, TExternalSource>;\n source: TExternalSource;\n\n /** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime.\n * @param client The `TriggerClient` instance to use for registering the trigger.\n * @param options The options for the dynamic trigger.\n * */\n constructor(client: TriggerClient, options: DynamicTriggerOptions<TEventSpec, TExternalSource>) {\n this.#client = client;\n this.#options = options;\n this.source = options.source;\n\n client.attachDynamicTrigger(this);\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.#options.id,\n };\n }\n\n get id() {\n return this.#options.id;\n }\n\n get event() {\n return this.#options.event;\n }\n\n registeredTriggerForParams(params: ExternalSourceParams<TExternalSource>): RegisterTriggerBody {\n const key = slugifyId(this.source.key(params));\n\n return {\n rule: {\n event: this.event.name,\n source: this.event.source,\n payload: deepMergeFilters(this.source.filter(params), this.event.filter ?? {}),\n },\n source: {\n key,\n channel: this.source.channel,\n params,\n events: typeof this.event.name === \"string\" ? [this.event.name] : this.event.name,\n integration: {\n id: this.source.integration.id,\n metadata: this.source.integration.metadata,\n authSource: this.source.integration.client.usesLocalAuth ? \"LOCAL\" : \"HOSTED\",\n },\n },\n };\n }\n\n /** Use this method to register a new configuration with the DynamicTrigger.\n * @param key The key for the configuration. This will be used to identify the configuration when it is triggered.\n * @param params The params for the configuration.\n */\n async register(\n key: string,\n params: ExternalSourceParams<TExternalSource>\n ): Promise<RegisterSourceEvent> {\n return this.#client.registerTrigger(this.id, key, this.registeredTriggerForParams(params));\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpec>, any>): void {\n triggerClient.attachJobToDynamicTrigger(job, this);\n }\n\n get preprocessRuns() {\n return true;\n }\n}\n","import {\n CronOptions,\n IntervalOptions,\n ScheduleMetadata,\n ScheduledPayload,\n ScheduledPayloadSchema,\n TriggerMetadata,\n currentDate,\n} from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport cronstrue from \"cronstrue\";\n\ntype ScheduledEventSpecification = EventSpecification<ScheduledPayload>;\n\nconst examples = [\n {\n id: \"now\",\n name: \"Now\",\n icon: \"clock\",\n payload: {\n ts: currentDate.marker,\n lastTimestamp: currentDate.marker,\n },\n },\n];\n\nexport class IntervalTrigger implements Trigger<ScheduledEventSpecification> {\n constructor(private options: IntervalOptions) {}\n\n get event() {\n return {\n name: \"trigger.scheduled\",\n title: \"Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-interval\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n properties: [\n {\n label: \"Interval\",\n text: `${this.options.seconds}s`,\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"scheduled\",\n schedule: {\n type: \"interval\",\n options: {\n seconds: this.options.seconds,\n },\n },\n };\n }\n}\n\n/** `intervalTrigger()` is set as a [Job's trigger](/sdk/job) to trigger a Job at a recurring interval.\n * @param options An object containing options about the interval.\n */\nexport function intervalTrigger(options: IntervalOptions) {\n return new IntervalTrigger(options);\n}\n\nexport class CronTrigger implements Trigger<ScheduledEventSpecification> {\n constructor(private options: CronOptions) {}\n\n get event() {\n const humanReadable = cronstrue.toString(this.options.cron, {\n throwExceptionOnParseError: false,\n });\n\n return {\n name: \"trigger.scheduled\",\n title: \"Cron Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-cron\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n properties: [\n {\n label: \"cron\",\n text: this.options.cron,\n },\n {\n label: \"Schedule\",\n text: humanReadable,\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"scheduled\",\n schedule: {\n type: \"cron\",\n options: {\n cron: this.options.cron,\n },\n },\n };\n }\n}\n\n/** `cronTrigger()` is set as a [Job's trigger](https://trigger.dev/docs/sdk/job) to trigger a Job on a recurring schedule using a CRON expression.\n * @param options An object containing options about the CRON schedule.\n */\nexport function cronTrigger(options: CronOptions) {\n return new CronTrigger(options);\n}\n\n/** DynamicSchedule options\n * @param id Used to uniquely identify a DynamicSchedule\n */\nexport type DynamicIntervalOptions = { id: string };\n\n/** DynamicSchedule` allows you to define a scheduled trigger that can be configured dynamically at runtime. */\nexport class DynamicSchedule implements Trigger<ScheduledEventSpecification> {\n /**\n * @param client The `TriggerClient` instance to use for registering the trigger.\n * @param options The options for the schedule.\n */\n constructor(\n private client: TriggerClient,\n private options: DynamicIntervalOptions\n ) {}\n\n get id() {\n return this.options.id;\n }\n\n get event() {\n return {\n name: \"trigger.scheduled\",\n title: \"Dynamic Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-dynamic\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n };\n }\n\n async register(key: string, metadata: ScheduleMetadata) {\n return this.client.registerSchedule(this.id, key, metadata);\n }\n\n async unregister(key: string) {\n return this.client.unregisterSchedule(this.id, key);\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {\n triggerClient.attachDynamicSchedule(this.options.id, job);\n }\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.options.id,\n };\n }\n}\n","import {\n MISSING_CONNECTION_NOTIFICATION,\n MISSING_CONNECTION_RESOLVED_NOTIFICATION,\n MissingConnectionNotificationPayload,\n MissingConnectionNotificationPayloadSchema,\n MissingConnectionResolvedNotificationPayload,\n MissingConnectionResolvedNotificationPayloadSchema,\n TriggerMetadata,\n} from \"@trigger.dev/core\";\nimport { TriggerIntegration } from \"../integrations\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\n\nexport function missingConnectionNotification(integrations: Array<TriggerIntegration>) {\n return new MissingConnectionNotification({ integrations });\n}\n\nexport function missingConnectionResolvedNotification(integrations: Array<TriggerIntegration>) {\n return new MissingConnectionResolvedNotification({ integrations });\n}\n\ntype MissingConnectionNotificationSpecification =\n EventSpecification<MissingConnectionNotificationPayload>;\n\ntype MissingConnectionNotificationOptions = {\n integrations: Array<TriggerIntegration>;\n};\n\nexport class MissingConnectionNotification\n implements Trigger<MissingConnectionNotificationSpecification>\n{\n constructor(private options: MissingConnectionNotificationOptions) {}\n\n get event() {\n return {\n name: MISSING_CONNECTION_NOTIFICATION,\n title: \"Missing Connection Notification\",\n source: \"trigger.dev\",\n icon: \"connection-alert\",\n parsePayload: MissingConnectionNotificationPayloadSchema.parse,\n properties: [\n {\n label: \"Integrations\",\n text: this.options.integrations.map((i) => i.id).join(\", \"),\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<MissingConnectionNotificationSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.event.title,\n rule: {\n event: this.event.name,\n source: \"trigger.dev\",\n payload: {\n client: {\n id: this.options.integrations.map((i) => i.id),\n },\n },\n },\n };\n }\n}\n\ntype MissingConnectionResolvedNotificationSpecification =\n EventSpecification<MissingConnectionResolvedNotificationPayload>;\n\nexport class MissingConnectionResolvedNotification\n implements Trigger<MissingConnectionResolvedNotificationSpecification>\n{\n constructor(private options: MissingConnectionNotificationOptions) {}\n\n get event() {\n return {\n name: MISSING_CONNECTION_RESOLVED_NOTIFICATION,\n title: \"Missing Connection Resolved Notification\",\n source: \"trigger.dev\",\n icon: \"connection-alert\",\n parsePayload: MissingConnectionResolvedNotificationPayloadSchema.parse,\n properties: [\n {\n label: \"Integrations\",\n text: this.options.integrations.map((i) => i.id).join(\", \"),\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<MissingConnectionResolvedNotificationSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.event.title,\n rule: {\n event: this.event.name,\n source: \"trigger.dev\",\n payload: {\n client: {\n id: this.options.integrations.map((i) => i.id),\n },\n },\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAO,SAASA,UAAUC,OAAuB;AAE/C,QAAMC,wBAAwBD,MAAME,YAAW,EAAGC,QAAQ,QAAQ,GAAA;AAGlE,QAAMC,wBAAwBH,sBAAsBE,QAAQ,qBAAqB,EAAA;AAEjF,SAAOC;AACT;AARgBL;;;ACIhB;AAmEO,IAAMM,MAAN,MAAMA;EAQXC,YAGEC,QACAC,SACA;AAqEF;AApEE,SAAKD,SAASA;AACd,SAAKC,UAAUA;AACf,0BAAK,wBAAL;AAEAD,WAAOE,OAAO,IAAI;EACpB;EAEA,IAAIC,KAAK;AACP,WAAOC,UAAU,KAAKH,QAAQE,EAAE;EAClC;EAEA,IAAIE,UAAU;AACZ,WAAO,OAAO,KAAKJ,QAAQI,YAAY,YAAY,KAAKJ,QAAQI,UAAU;EAC5E;EAEA,IAAIC,OAAO;AACT,WAAO,KAAKL,QAAQK;EACtB;EAEA,IAAIC,UAAU;AACZ,WAAO,KAAKN,QAAQM;EACtB;EAEA,IAAIC,UAAU;AACZ,WAAO,KAAKP,QAAQO;EACtB;EAEA,IAAIC,eAAkD;AACpD,WAAOC,OAAOC,KAAK,KAAKV,QAAQQ,gBAAgB,CAAC,CAAA,EAAGG,OAClD,CAACC,KAAwCC,QAAQ;AAC/C,YAAMC,cAAc,KAAKd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F;EAEAC,YACEC,eACAC,KACM;EAAC;EAET,IAAIC,iBAAiB;AACnB,WAAO;EACT;EAEAC,SAA0B;AACxB,WAAO;MACLC,MAAM;MACNlB,OAAO,KAAKH,MAAMG;MAClBmB,MAAM;QACJtB,OAAO,KAAKA,MAAMC;QAClBG,QAAQ;QACRmB,SAAS;UACPC,QAAQ;YACNV,IAAI,KAAKf,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE;UAC/C;QACF;MACF;IACF;EACF;AACF;AA7CanB;AAkDN,IAAME,wCAAN,MAAMA;EAGXC,YAAoBC,SAA+C;mBAA/CA;EAAgD;EAEpE,IAAIC,QAAQ;AACV,WAAO;MACLC,MAAMwB;MACNtB,OAAO;MACPC,QAAQ;MACRC,MAAM;MACNC,cAAcoB,gEAAmDlB;MACjEC,YAAY;QACV;UACEC,OAAO;UACPC,MAAM,KAAKZ,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE,EAAEC,KAAK,IAAA;QACxD;;IAEJ;EACF;EAEAC,YACEC,eACAC,KACM;EAAC;EAET,IAAIC,iBAAiB;AACnB,WAAO;EACT;EAEAC,SAA0B;AACxB,WAAO;MACLC,MAAM;MACNlB,OAAO,KAAKH,MAAMG;MAClBmB,MAAM;QACJtB,OAAO,KAAKA,MAAMC;QAClBG,QAAQ;QACRmB,SAAS;UACPC,QAAQ;YACNV,IAAI,KAAKf,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE;UAC/C;QACF;MACF;IACF;EACF;AACF;AA7CajB;;;Ad9CN,SAAS8B,aACdC,YACGC,gBACW;AACd,SAAO;IACLC,kBAAkB;IAClBF,SAASA,QAAQG;IACjBF;EACF;AACF;AATgBF;","names":["slugifyId","input","replaceSpacesWithDash","toLowerCase","replace","removeNonUrlSafeChars","Job","constructor","client","options","attach","id","slugifyId","enabled","name","trigger","version","integrations","Object","keys","reduce","acc","key","integration","metadata","authSource","usesLocalAuth","logLevel","toJSON","internal","__internal","event","startPosition","preprocessRuns","match","Error","import_core","ApiClient","constructor","options","apiUrl","process","env","TRIGGER_API_URL","Logger","logLevel","registerEndpoint","apiKey","debug","url","name","response","fetch","method","headers","Authorization","body","JSON","stringify","status","json","Error","error","createRun","params","zodfetch","CreateRunResponseBodySchema","runTask","runId","task","ServerTaskSchema","idempotencyKey","completeTask","id","failTask","sendEvent","event","ApiEventLogSchema","updateSource","client","key","source","TriggerSourceSchema","registerTrigger","payload","RegisterSourceEventSchema","registerSchedule","RegisterScheduleResponseBodySchema","unregisterSchedule","z","object","ok","boolean","encodeURIComponent","getAuth","ConnectionAuthSchema","Accept","optional","getEvent","eventId","GetEventSchema","getRun","GetRunSchema","urlWithSearchParams","getRuns","jobSlug","GetRunsSchema","getApiKey","TRIGGER_API_KEY","isValid","match","schema","requestInit","errorMessage","jsonBody","parse","ResumeWithTaskError","constructor","task","RetryWithTaskError","cause","retryAt","CanceledWithTaskError","isTriggerError","err","import_core","createIOWithIntegrations","io","auths","integrations","connections","Object","entries","reduce","acc","connectionKey","integration","auth","client","usesLocalAuth","clientFactory","undefined","ioConnection","runTask","key","callback","options","name","icon","metadata","id","retry","limit","minTimeoutInMs","maxTimeoutInMs","factor","randomize","ioTask","tasks","keys","forEach","taskName","authenticatedTask","params","init","run","onError","Proxy","get","target","prop","receiver","value","Reflect","bind","import_core","IO","constructor","options","_id","id","_apiClient","apiClient","_triggerClient","client","_logger","logger","Logger","logLevel","_cachedTasks","Map","_jobLogger","jobLogger","_jobLogLevel","jobLogLevel","cachedTasks","forEach","task","set","idempotencyKey","_taskStorage","AsyncLocalStorage","_context","context","IOLogger","level","message","data","log","debug","info","warn","error","satisfiesLogLevel","runTask","name","icon","description","params","properties","label","text","style","variant","toLowerCase","noop","wait","key","seconds","delayUntil","Date","now","backgroundFetch","url","requestInit","retry","urlObject","URL","hostname","pathname","operation","method","output","sendEvent","event","updateSource","redact","paths","registerInterval","dynamicSchedule","toString","register","type","unregisterInterval","unregister","registerCron","cron","unregisterCron","registerTrigger","trigger","registration","subtask1","connection","getAuth","source","clientId","io","createIOWithIntegrations","integration","updates","callback","onError","parentId","getStore","taskId","generateIdempotencyKey","flat","cachedTask","get","displayKey","undefined","status","CanceledWithTaskError","Error","ResumeWithTaskError","executeTask","result","SerializableJsonSchema","parse","completedTask","completeTask","outputProperties","isTriggerError","onErrorResult","parsedError","ErrorWithStackSchema","safeParse","RetryWithTaskError","success","retryAt","innerError","calculateRetryAt","attempts","failTask","JSON","stringify","run","try","tryCallback","catchCallback","keyMaterial","keys","map","stableStringify","join","hash","webcrypto","subtle","digest","Buffer","from","obj","sortKeys","Array","isArray","sortedKeys","Object","sort","sortedObj","import_core","_options","EventTrigger","constructor","options","toJSON","type","title","name","event","rule","source","payload","deepMergeFilters","filter","attachToJob","triggerClient","job","preprocessRuns","eventTrigger","icon","examples","parsePayload","rawPayload","schema","parse","registerSourceEvent","name","REGISTER_SOURCE_EVENT","title","source","icon","parsePayload","RegisterSourceEventSchema","parse","_options","TriggerClient","constructor","options","id","ApiClient","Logger","verbose","handleRequest","request","debug","url","headers","Object","fromEntries","entries","method","apiKey","get","authorization","authorized","status","body","message","action","endpointId","ok","error","jobId","job","toJSON","jobs","values","map","sources","dynamicTriggers","trigger","registerSourceJob","dynamicTriggerRegisterSourceJobId","version","dynamicSchedules","json","InitializeTriggerBodySchema","safeParse","success","dynamicTrigger","data","registeredTriggerForParams","params","execution","RunJobBodySchema","results","PreprocessRunBodySchema","abort","properties","HttpSourceRequestHeadersSchema","sourceRequestNeedsBody","sourceRequestInit","undefined","duplex","sourceRequest","Request","key","dynamicId","secret","response","events","attach","enabled","attachToJob","attachDynamicTrigger","Job","EventTrigger","event","filter","dynamicTriggerId","integrations","integration","run","io","ctx","updates","register","updateSource","__internal","attachJobToDynamicTrigger","push","attachSource","s","r","handle","registeredSource","channel","metadata","authSource","client","usesLocalAuth","Array","from","Set","attachDynamicSchedule","registerTrigger","getAuth","sendEvent","registerSchedule","schedule","unregisterSchedule","getEvent","eventId","getRun","runId","getRuns","jobSlug","localApiKey","process","env","TRIGGER_API_KEY","defineJob","context","parsedPayload","payload","runProperties","IO","cachedTasks","tasks","apiClient","logger","jobLogLevel","logLevel","jobLogger","ioLogLocalEnabled","ioWithConnections","createIOWithIntegrations","connections","output","ResumeWithTaskError","task","RetryWithTaskError","cause","retryAt","CanceledWithTaskError","errorWithStack","ErrorWithStackSchema","organization","environment","timestamp","account","handler","authenticatedTask","options","import_core","ExternalSource","constructor","channel","options","handle","source","rawEvent","logger","handler","params","filter","properties","register","registerEvent","io","ctx","result","event","ommited","omit","sourceWithoutChannel","channelWithoutType","updates","key","parts","id","push","integration","join","integrationConfig","metadata","version","ExternalSourceTrigger","toJSON","type","title","rule","name","payload","deepMergeFilters","attachToJob","triggerClient","job","attachSource","slugifyId","preprocessRuns","obj","k","Object","keys","import_core","_client","_options","DynamicTrigger","constructor","client","options","source","attachDynamicTrigger","toJSON","type","id","event","registeredTriggerForParams","params","key","slugifyId","rule","name","payload","deepMergeFilters","filter","channel","events","integration","metadata","authSource","usesLocalAuth","register","registerTrigger","attachToJob","triggerClient","job","attachJobToDynamicTrigger","preprocessRuns","import_core","examples","id","name","icon","payload","ts","currentDate","marker","lastTimestamp","IntervalTrigger","constructor","options","event","title","source","parsePayload","ScheduledPayloadSchema","parse","properties","label","text","seconds","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","schedule","intervalTrigger","CronTrigger","humanReadable","cronstrue","toString","cron","throwExceptionOnParseError","cronTrigger","DynamicSchedule","client","register","key","metadata","registerSchedule","unregister","unregisterSchedule","attachDynamicSchedule","import_core","missingConnectionNotification","integrations","MissingConnectionNotification","missingConnectionResolvedNotification","MissingConnectionResolvedNotification","constructor","options","event","name","MISSING_CONNECTION_NOTIFICATION","title","source","icon","parsePayload","MissingConnectionNotificationPayloadSchema","parse","properties","label","text","map","i","id","join","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","rule","payload","client","MISSING_CONNECTION_RESOLVED_NOTIFICATION","MissingConnectionResolvedNotificationPayloadSchema","redactString","strings","interpolations","__redactedString","raw"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/job.ts","../src/triggerClient.ts","../src/apiClient.ts","../src/errors.ts","../src/io.ts","../src/ioWithIntegrations.ts","../src/retry.ts","../src/triggers/eventTrigger.ts","../src/integrations.ts","../src/triggers/externalSource.ts","../src/triggers/dynamic.ts","../src/triggers/scheduled.ts","../src/triggers/notifications.ts"],"sourcesContent":["export * from \"./job\";\nexport * from \"./triggerClient\";\nexport * from \"./integrations\";\nexport * from \"./triggers/eventTrigger\";\nexport * from \"./triggers/externalSource\";\nexport * from \"./triggers/dynamic\";\nexport * from \"./triggers/scheduled\";\nexport * from \"./triggers/notifications\";\nexport * from \"./io\";\nexport * from \"./types\";\n\nimport { ServerTask } from \"@trigger.dev/core\";\nimport { RedactString } from \"./types\";\nexport { isTriggerError } from \"./errors\";\n\nexport type { NormalizedRequest, EventFilter } from \"@trigger.dev/core\";\n\nexport type Task = ServerTask;\n\nimport { ApiEventLog } from \"@trigger.dev/core\";\nexport type SentEvent = ApiEventLog;\n\n/*\n * This function is used to create a redacted string that can be used in the headers of a fetch request.\n * It is used to prevent the string from being logged in trigger.dev.\n * You can use it like this:\n *\n * await io.backgroundFetch<SomeResponseType>(\"https://example.com\", {\n * headers: {\n * Authorization: redactString`Bearer ${ACCESS_TOKEN}`,\n * },\n * })\n */\nexport function redactString(\n strings: TemplateStringsArray,\n ...interpolations: string[]\n): RedactString {\n return {\n __redactedString: true,\n strings: strings.raw as string[],\n interpolations,\n };\n}\n","export function slugifyId(input: string): string {\n // Replace any number of spaces with a single dash\n const replaceSpacesWithDash = input.toLowerCase().replace(/\\s+/g, \"-\");\n\n // Remove any non-URL-safe characters\n const removeNonUrlSafeChars = replaceSpacesWithDash.replace(/[^a-zA-Z0-9-._~]/g, \"\");\n\n return removeNonUrlSafeChars;\n}\n","import { IntegrationConfig, JobMetadata, LogLevel, QueueOptions } from \"@trigger.dev/core\";\nimport { IOWithIntegrations, IntegrationClient, TriggerIntegration } from \"./integrations\";\nimport { TriggerClient } from \"./triggerClient\";\nimport type { EventSpecification, Trigger, TriggerContext, TriggerEventType } from \"./types\";\nimport { slugifyId } from \"./utils\";\n\nexport type JobOptions<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>> = {},\n> = {\n /** The `id` property is used to uniquely identify the Job. Only change this if you want to create a new Job. */\n id: string;\n /** The `name` of the Job that you want to appear in the dashboard and logs. You can change this without creating a new Job. */\n name: string;\n /** The `version` property is used to version your Job. A new version will be created if you change this property. We recommend using [semantic versioning](https://www.baeldung.com/cs/semantic-versioning), e.g. `1.0.3`. */\n version: string;\n /** The `trigger` property is used to define when the Job should run. There are currently the following Trigger types:\n - [cronTrigger](https://trigger.dev/docs/sdk/crontrigger)\n - [intervalTrigger](https://trigger.dev/docs/sdk/intervaltrigger)\n - [eventTrigger](https://trigger.dev/docs/sdk/eventtrigger)\n - [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger)\n - [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule)\n - integration Triggers, like webhooks. See the [integrations](https://trigger.dev/docs/integrations) page for more information. */\n trigger: TTrigger;\n /** The `logLevel` property is an optional property that specifies the level of\n logging for the Job. The level is inherited from the client if you omit this property. */\n logLevel?: LogLevel;\n /** Imports the specified integrations into the Job. The integrations will be available on the `io` object in the `run()` function with the same name as the key. For example:\n ```ts\n client.defineJob({\n //... other options\n integrations: {\n slack,\n gh: github,\n },\n run: async (payload, io, ctx) => {\n //slack is available on io.slack\n io.slack.postMessage(...);\n //github is available on io.gh\n io.gh.addIssueLabels(...);\n }\n });\n ``` */\n integrations?: TIntegrations;\n /** @deprecated This property is deprecated and no longer effects the execution of the Job\n * */\n queue?: QueueOptions | string;\n /** The `enabled` property is used to enable or disable the Job. If you disable a Job, it will not run. */\n enabled?: boolean;\n /** This function gets called automatically when a Run is Triggered.\n * This is where you put the code you want to run for a Job. You can use normal code in here and you can also use Tasks. You can return a value from this function and it will be sent back to the Trigger API.\n * @param payload The payload of the event\n * @param io An object that contains the integrations that you specified in the `integrations` property and other useful functions like delays and running Tasks.\n * @param context An object that contains information about the Organization, Job, Run and more.\n */\n run: (\n payload: TriggerEventType<TTrigger>,\n io: IOWithIntegrations<TIntegrations>,\n context: TriggerContext\n ) => Promise<any>;\n};\n\nexport type JobPayload<TJob> = TJob extends Job<Trigger<EventSpecification<infer TEvent>>, any>\n ? TEvent\n : never;\n\nexport type JobIO<TJob> = TJob extends Job<any, infer TIntegrations>\n ? IOWithIntegrations<TIntegrations>\n : never;\n\n/** A [Job](https://trigger.dev/docs/documentation/concepts/jobs) is used to define the [Trigger](https://trigger.dev/docs/documentation/concepts/triggers), metadata, and what happens when it runs. */\nexport class Job<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>> = {},\n> {\n readonly options: JobOptions<TTrigger, TIntegrations>;\n\n client: TriggerClient;\n\n constructor(\n /** An instance of [TriggerClient](/sdk/triggerclient) that is used to send events\n to the Trigger API. */\n client: TriggerClient,\n options: JobOptions<TTrigger, TIntegrations>\n ) {\n this.client = client;\n this.options = options;\n this.#validate();\n\n client.attach(this);\n }\n\n get id() {\n return slugifyId(this.options.id);\n }\n\n get enabled() {\n return typeof this.options.enabled === \"boolean\" ? this.options.enabled : true;\n }\n\n get name() {\n return this.options.name;\n }\n\n get trigger() {\n return this.options.trigger;\n }\n\n get version() {\n return this.options.version;\n }\n\n get integrations(): Record<string, IntegrationConfig> {\n return Object.keys(this.options.integrations ?? {}).reduce(\n (acc: Record<string, IntegrationConfig>, key) => {\n const integration = this.options.integrations![key];\n\n acc[key] = {\n id: integration.id,\n metadata: integration.metadata,\n authSource: integration.client.usesLocalAuth ? \"LOCAL\" : \"HOSTED\",\n };\n\n return acc;\n },\n {}\n );\n }\n\n get logLevel() {\n return this.options.logLevel;\n }\n\n toJSON(): JobMetadata {\n // @ts-ignore\n const internal = this.options.__internal as JobMetadata[\"internal\"];\n\n return {\n id: this.id,\n name: this.name,\n version: this.version,\n event: this.trigger.event,\n trigger: this.trigger.toJSON(),\n integrations: this.integrations,\n startPosition: \"latest\", // this is deprecated, leaving this for now to make sure newer clients work with older servers\n enabled: this.enabled,\n preprocessRuns: this.trigger.preprocessRuns,\n internal,\n };\n }\n\n // Make sure the id is valid (must only contain alphanumeric characters and dashes)\n // Make sure the version is valid (must be a valid semver version)\n #validate() {\n if (!this.version.match(/^(\\d+)\\.(\\d+)\\.(\\d+)$/)) {\n throw new Error(\n `Invalid job version: \"${this.version}\". Job versions must be valid semver versions.`\n );\n }\n }\n}\n","import {\n ErrorWithStackSchema,\n GetRunOptionsWithTaskDetails,\n GetRunsOptions,\n HandleTriggerSource,\n HttpSourceRequestHeadersSchema,\n IndexEndpointResponse,\n InitializeTriggerBodySchema,\n LogLevel,\n Logger,\n NormalizedResponse,\n PreprocessRunBody,\n PreprocessRunBodySchema,\n Prettify,\n REGISTER_SOURCE_EVENT,\n RegisterSourceEvent,\n RegisterSourceEventSchema,\n RegisterTriggerBody,\n RunJobBody,\n RunJobBodySchema,\n RunJobResponse,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n SourceMetadata,\n} from \"@trigger.dev/core\";\nimport { ApiClient } from \"./apiClient\";\nimport { CanceledWithTaskError, ResumeWithTaskError, RetryWithTaskError } from \"./errors\";\nimport { IntegrationClient, TriggerIntegration } from \"./integrations\";\nimport { IO } from \"./io\";\nimport { createIOWithIntegrations } from \"./ioWithIntegrations\";\nimport { Job, JobOptions } from \"./job\";\nimport { DynamicTrigger } from \"./triggers/dynamic\";\nimport { EventTrigger } from \"./triggers/eventTrigger\";\nimport { ExternalSource } from \"./triggers/externalSource\";\nimport type {\n EventSpecification,\n Trigger,\n TriggerContext,\n TriggerPreprocessContext,\n} from \"./types\";\n\nconst registerSourceEvent: EventSpecification<RegisterSourceEvent> = {\n name: REGISTER_SOURCE_EVENT,\n title: \"Register Source\",\n source: \"internal\",\n icon: \"register-source\",\n parsePayload: RegisterSourceEventSchema.parse,\n};\n\nexport type TriggerClientOptions = {\n /** The `id` property is used to uniquely identify the client.\n */\n id: string;\n /** The `apiKey` property is the API Key for your Trigger.dev environment. We\n recommend using an environment variable to store your API Key. */\n apiKey?: string;\n /** The `apiUrl` property is an optional property that specifies the API URL. You\n only need to specify this if you are not using Trigger.dev Cloud and are\n running your own Trigger.dev instance. */\n apiUrl?: string;\n /** The `logLevel` property is an optional property that specifies the level of\n logging for the TriggerClient. The level is inherited by all Jobs that use this Client, unless they also specify a `logLevel`. */\n logLevel?: LogLevel;\n /** Very verbose log messages, defaults to false. */\n verbose?: boolean;\n /** Default is unset and off. If set to true it will log to the server's console as well as the Trigger.dev platform */\n ioLogLocalEnabled?: boolean;\n};\n\n/** A [TriggerClient](https://trigger.dev/docs/documentation/concepts/client-adaptors) is used to connect to a specific [Project](https://trigger.dev/docs/documentation/concepts/projects) by using an [API Key](https://trigger.dev/docs/documentation/concepts/environments-apikeys). */\nexport class TriggerClient {\n #options: TriggerClientOptions;\n #registeredJobs: Record<string, Job<Trigger<EventSpecification<any>>, any>> = {};\n #registeredSources: Record<string, SourceMetadata> = {};\n #registeredHttpSourceHandlers: Record<\n string,\n (\n source: HandleTriggerSource,\n request: Request\n ) => Promise<{\n events: Array<SendEvent>;\n response?: NormalizedResponse;\n } | void>\n > = {};\n #registeredDynamicTriggers: Record<\n string,\n DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>\n > = {};\n #jobMetadataByDynamicTriggers: Record<string, Array<{ id: string; version: string }>> = {};\n #registeredSchedules: Record<string, Array<{ id: string; version: string }>> = {};\n\n #client: ApiClient;\n #internalLogger: Logger;\n id: string;\n\n constructor(options: Prettify<TriggerClientOptions>) {\n this.id = options.id;\n this.#options = options;\n this.#client = new ApiClient(this.#options);\n this.#internalLogger = new Logger(\"trigger.dev\", this.#options.verbose ? \"debug\" : \"log\");\n }\n\n async handleRequest(request: Request): Promise<NormalizedResponse> {\n this.#internalLogger.debug(\"handling request\", {\n url: request.url,\n headers: Object.fromEntries(request.headers.entries()),\n method: request.method,\n });\n\n const apiKey = request.headers.get(\"x-trigger-api-key\");\n\n const authorization = this.authorized(apiKey);\n\n switch (authorization) {\n case \"authorized\": {\n break;\n }\n case \"missing-client\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: client missing apiKey\",\n },\n };\n }\n case \"missing-header\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: missing x-trigger-api-key header\",\n },\n };\n }\n case \"unauthorized\": {\n return {\n status: 401,\n body: {\n message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`,\n },\n };\n }\n }\n\n if (request.method !== \"POST\") {\n return {\n status: 405,\n body: {\n message: \"Method not allowed (only POST is allowed)\",\n },\n };\n }\n\n const action = request.headers.get(\"x-trigger-action\");\n\n if (!action) {\n return {\n status: 400,\n body: {\n message: \"Missing x-trigger-action header\",\n },\n };\n }\n\n switch (action) {\n case \"PING\": {\n const endpointId = request.headers.get(\"x-trigger-endpoint-id\");\n\n if (!endpointId) {\n return {\n status: 200,\n body: {\n ok: false,\n error: \"Missing endpoint ID\",\n },\n };\n }\n\n if (this.id !== endpointId) {\n return {\n status: 200,\n body: {\n ok: false,\n error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`,\n },\n };\n }\n\n return {\n status: 200,\n body: {\n ok: true,\n },\n };\n }\n case \"INDEX_ENDPOINT\": {\n // if the x-trigger-job-id header is set, we return the job with that id\n const jobId = request.headers.get(\"x-trigger-job-id\");\n\n if (jobId) {\n const job = this.#registeredJobs[jobId];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n return {\n status: 200,\n body: job.toJSON(),\n };\n }\n\n const body: IndexEndpointResponse = {\n jobs: Object.values(this.#registeredJobs).map((job) => job.toJSON()),\n sources: Object.values(this.#registeredSources),\n dynamicTriggers: Object.values(this.#registeredDynamicTriggers).map((trigger) => ({\n id: trigger.id,\n jobs: this.#jobMetadataByDynamicTriggers[trigger.id] ?? [],\n registerSourceJob: {\n id: dynamicTriggerRegisterSourceJobId(trigger.id),\n version: trigger.source.version,\n },\n })),\n dynamicSchedules: Object.entries(this.#registeredSchedules).map(([id, jobs]) => ({\n id,\n jobs,\n })),\n };\n\n // if the x-trigger-job-id header is not set, we return all jobs\n return {\n status: 200,\n body,\n };\n }\n case \"INITIALIZE_TRIGGER\": {\n const json = await request.json();\n const body = InitializeTriggerBodySchema.safeParse(json);\n\n if (!body.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid trigger body\",\n },\n };\n }\n\n const dynamicTrigger = this.#registeredDynamicTriggers[body.data.id];\n\n if (!dynamicTrigger) {\n return {\n status: 404,\n body: {\n message: \"Dynamic trigger not found\",\n },\n };\n }\n\n return {\n status: 200,\n body: dynamicTrigger.registeredTriggerForParams(body.data.params),\n };\n }\n case \"EXECUTE_JOB\": {\n const json = await request.json();\n const execution = RunJobBodySchema.safeParse(json);\n\n if (!execution.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid execution\",\n },\n };\n }\n\n const job = this.#registeredJobs[execution.data.job.id];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n const results = await this.#executeJob(execution.data, job);\n\n return {\n status: 200,\n body: results,\n };\n }\n case \"PREPROCESS_RUN\": {\n const json = await request.json();\n const body = PreprocessRunBodySchema.safeParse(json);\n\n if (!body.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid body\",\n },\n };\n }\n\n const job = this.#registeredJobs[body.data.job.id];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n const results = await this.#preprocessRun(body.data, job);\n\n return {\n status: 200,\n body: {\n abort: results.abort,\n properties: results.properties,\n },\n };\n }\n case \"DELIVER_HTTP_SOURCE_REQUEST\": {\n const headers = HttpSourceRequestHeadersSchema.safeParse(\n Object.fromEntries(request.headers.entries())\n );\n\n if (!headers.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid headers\",\n },\n };\n }\n\n const sourceRequestNeedsBody = headers.data[\"x-ts-http-method\"] !== \"GET\";\n\n const sourceRequestInit: RequestInit = {\n method: headers.data[\"x-ts-http-method\"],\n headers: headers.data[\"x-ts-http-headers\"],\n body: sourceRequestNeedsBody ? request.body : undefined,\n };\n\n if (sourceRequestNeedsBody) {\n try {\n // @ts-ignore\n sourceRequestInit.duplex = \"half\";\n } catch (error) {\n // ignore\n }\n }\n\n const sourceRequest = new Request(headers.data[\"x-ts-http-url\"], sourceRequestInit);\n\n const key = headers.data[\"x-ts-key\"];\n const dynamicId = headers.data[\"x-ts-dynamic-id\"];\n const secret = headers.data[\"x-ts-secret\"];\n const params = headers.data[\"x-ts-params\"];\n const data = headers.data[\"x-ts-data\"];\n\n const source = {\n key,\n dynamicId,\n secret,\n params,\n data,\n };\n\n const { response, events } = await this.#handleHttpSourceRequest(source, sourceRequest);\n\n return {\n status: 200,\n body: {\n events,\n response,\n },\n };\n }\n case \"VALIDATE\": {\n return {\n status: 200,\n body: {\n ok: true,\n endpointId: this.id,\n },\n };\n }\n }\n\n return {\n status: 405,\n body: {\n message: \"Method not allowed\",\n },\n };\n }\n\n attach(job: Job<Trigger<any>, any>): void {\n this.#registeredJobs[job.id] = job;\n\n job.trigger.attachToJob(this, job);\n }\n\n attachDynamicTrigger(trigger: DynamicTrigger<any, any>): void {\n this.#registeredDynamicTriggers[trigger.id] = trigger;\n\n new Job(this, {\n id: dynamicTriggerRegisterSourceJobId(trigger.id),\n name: `Register dynamic trigger ${trigger.id}`,\n version: trigger.source.version,\n trigger: new EventTrigger({\n event: registerSourceEvent,\n filter: { dynamicTriggerId: [trigger.id] },\n }),\n integrations: {\n integration: trigger.source.integration,\n },\n run: async (event, io, ctx) => {\n const updates = await trigger.source.register(event.source.params, event, io, ctx);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await io.updateSource(\"update-source\", {\n key: event.source.key,\n ...updates,\n });\n },\n // @ts-ignore\n __internal: true,\n });\n }\n\n attachJobToDynamicTrigger(job: Job<Trigger<any>, any>, trigger: DynamicTrigger<any, any>): void {\n const jobs = this.#jobMetadataByDynamicTriggers[trigger.id] ?? [];\n\n jobs.push({ id: job.id, version: job.version });\n\n this.#jobMetadataByDynamicTriggers[trigger.id] = jobs;\n }\n\n attachSource(options: {\n key: string;\n source: ExternalSource<any, any>;\n event: EventSpecification<any>;\n params: any;\n }): void {\n this.#registeredHttpSourceHandlers[options.key] = async (s, r) => {\n return await options.source.handle(s, r, this.#internalLogger);\n };\n\n let registeredSource = this.#registeredSources[options.key];\n\n if (!registeredSource) {\n registeredSource = {\n channel: options.source.channel,\n key: options.key,\n params: options.params,\n events: [],\n integration: {\n id: options.source.integration.id,\n metadata: options.source.integration.metadata,\n authSource: options.source.integration.client.usesLocalAuth ? \"LOCAL\" : \"HOSTED\",\n },\n registerSourceJob: {\n id: options.key,\n version: options.source.version,\n },\n };\n }\n\n registeredSource.events = Array.from(\n new Set([\n ...registeredSource.events,\n ...(typeof options.event.name === \"string\" ? [options.event.name] : options.event.name),\n ])\n );\n\n this.#registeredSources[options.key] = registeredSource;\n\n new Job(this, {\n id: options.key,\n name: options.key,\n version: options.source.version,\n trigger: new EventTrigger({\n event: registerSourceEvent,\n filter: { source: { key: [options.key] } },\n }),\n integrations: {\n integration: options.source.integration,\n },\n run: async (event, io, ctx) => {\n const updates = await options.source.register(options.params, event, io, ctx);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await io.updateSource(\"update-source\", {\n key: options.key,\n ...updates,\n });\n },\n // @ts-ignore\n __internal: true,\n });\n }\n\n attachDynamicSchedule(key: string, job: Job<Trigger<any>, any>): void {\n const jobs = this.#registeredSchedules[key] ?? [];\n\n jobs.push({ id: job.id, version: job.version });\n\n this.#registeredSchedules[key] = jobs;\n }\n\n async registerTrigger(id: string, key: string, options: RegisterTriggerBody) {\n return this.#client.registerTrigger(this.id, id, key, options);\n }\n\n async getAuth(id: string) {\n return this.#client.getAuth(this.id, id);\n }\n\n /** You can call this function from anywhere in your code to send an event. The other way to send an event is by using [`io.sendEvent()`](https://trigger.dev/docs/sdk/io/sendevent) from inside a `run()` function.\n * @param event The event to send.\n * @param options Options for sending the event.\n * @returns A promise that resolves to the event details\n */\n async sendEvent(event: SendEvent, options?: SendEventOptions) {\n return this.#client.sendEvent(event, options);\n }\n\n async cancelEvent(eventId: string) {\n return this.#client.cancelEvent(eventId);\n }\n\n async registerSchedule(id: string, key: string, schedule: ScheduleMetadata) {\n return this.#client.registerSchedule(this.id, id, key, schedule);\n }\n\n async unregisterSchedule(id: string, key: string) {\n return this.#client.unregisterSchedule(this.id, id, key);\n }\n\n async getEvent(eventId: string) {\n return this.#client.getEvent(eventId);\n }\n\n async getRun(runId: string, options?: GetRunOptionsWithTaskDetails) {\n return this.#client.getRun(runId, options);\n }\n\n async getRuns(jobSlug: string, options?: GetRunsOptions) {\n return this.#client.getRuns(jobSlug, options);\n }\n\n authorized(\n apiKey?: string | null\n ): \"authorized\" | \"unauthorized\" | \"missing-client\" | \"missing-header\" {\n if (typeof apiKey !== \"string\") {\n return \"missing-header\";\n }\n\n const localApiKey = this.#options.apiKey ?? process.env.TRIGGER_API_KEY;\n\n if (!localApiKey) {\n return \"missing-client\";\n }\n\n return apiKey === localApiKey ? \"authorized\" : \"unauthorized\";\n }\n\n apiKey() {\n return this.#options.apiKey ?? process.env.TRIGGER_API_KEY;\n }\n\n async #preprocessRun(body: PreprocessRunBody, job: Job<Trigger<EventSpecification<any>>, any>) {\n const context = this.#createPreprocessRunContext(body);\n\n const parsedPayload = job.trigger.event.parsePayload(body.event.payload ?? {});\n\n const properties = job.trigger.event.runProperties?.(parsedPayload) ?? [];\n\n return {\n abort: false,\n properties,\n };\n }\n\n async #executeJob(body: RunJobBody, job: Job<Trigger<any>, any>): Promise<RunJobResponse> {\n this.#internalLogger.debug(\"executing job\", {\n execution: body,\n job: job.toJSON(),\n });\n\n const context = this.#createRunContext(body);\n\n const io = new IO({\n id: body.run.id,\n cachedTasks: body.tasks,\n apiClient: this.#client,\n logger: this.#internalLogger,\n client: this,\n context,\n jobLogLevel: job.logLevel ?? this.#options.logLevel ?? \"info\",\n jobLogger: this.#options.ioLogLocalEnabled\n ? new Logger(job.id, job.logLevel ?? this.#options.logLevel ?? \"info\")\n : undefined,\n });\n\n const ioWithConnections = createIOWithIntegrations(\n io,\n body.connections,\n job.options.integrations\n );\n\n try {\n const output = await job.options.run(\n job.trigger.event.parsePayload(body.event.payload ?? {}),\n ioWithConnections,\n context\n );\n\n return { status: \"SUCCESS\", output };\n } catch (error) {\n if (error instanceof ResumeWithTaskError) {\n return { status: \"RESUME_WITH_TASK\", task: error.task };\n }\n\n if (error instanceof RetryWithTaskError) {\n return {\n status: \"RETRY_WITH_TASK\",\n task: error.task,\n error: error.cause,\n retryAt: error.retryAt,\n };\n }\n\n if (error instanceof CanceledWithTaskError) {\n return {\n status: \"CANCELED\",\n task: error.task,\n };\n }\n\n if (error instanceof RetryWithTaskError) {\n const errorWithStack = ErrorWithStackSchema.safeParse(error.cause);\n\n if (errorWithStack.success) {\n return {\n status: \"ERROR\",\n error: errorWithStack.data,\n task: error.task,\n };\n }\n\n return {\n status: \"ERROR\",\n error: { message: \"Unknown error\" },\n task: error.task,\n };\n }\n\n const errorWithStack = ErrorWithStackSchema.safeParse(error);\n\n if (errorWithStack.success) {\n return { status: \"ERROR\", error: errorWithStack.data };\n }\n\n return {\n status: \"ERROR\",\n error: { message: \"Unknown error\" },\n };\n }\n }\n\n #createRunContext(execution: RunJobBody): TriggerContext {\n const { event, organization, environment, job, run, source } = execution;\n\n return {\n event: {\n id: event.id,\n name: event.name,\n context: event.context,\n timestamp: event.timestamp,\n },\n organization,\n environment,\n job,\n run,\n account: execution.account,\n source,\n };\n }\n\n #createPreprocessRunContext(body: PreprocessRunBody): TriggerPreprocessContext {\n const { event, organization, environment, job, run, account } = body;\n\n return {\n event: {\n id: event.id,\n name: event.name,\n context: event.context,\n timestamp: event.timestamp,\n },\n organization,\n environment,\n job,\n run,\n account,\n };\n }\n\n async #handleHttpSourceRequest(\n source: {\n key: string;\n dynamicId?: string;\n secret: string;\n data: any;\n params: any;\n },\n sourceRequest: Request\n ): Promise<{ response: NormalizedResponse; events: SendEvent[] }> {\n this.#internalLogger.debug(\"Handling HTTP source request\", {\n source,\n });\n\n if (source.dynamicId) {\n const dynamicTrigger = this.#registeredDynamicTriggers[source.dynamicId];\n\n if (!dynamicTrigger) {\n this.#internalLogger.debug(\"No dynamic trigger registered for HTTP source\", {\n source,\n });\n\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n events: [],\n };\n }\n\n const results = await dynamicTrigger.source.handle(\n source,\n sourceRequest,\n this.#internalLogger\n );\n\n if (!results) {\n return {\n events: [],\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n return {\n events: results.events,\n response: results.response ?? {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n const handler = this.#registeredHttpSourceHandlers[source.key];\n\n if (!handler) {\n this.#internalLogger.debug(\"No handler registered for HTTP source\", {\n source,\n });\n\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n events: [],\n };\n }\n\n const results = await handler(source, sourceRequest);\n\n if (!results) {\n return {\n events: [],\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n return {\n events: results.events,\n response: results.response ?? {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n defineJob<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>> = {},\n >(options: JobOptions<TTrigger, TIntegrations>) {\n return new Job<TTrigger, TIntegrations>(this, options);\n }\n}\n\nfunction dynamicTriggerRegisterSourceJobId(id: string) {\n return `register-dynamic-trigger-${id}`;\n}\n","import {\n ApiEventLog,\n ApiEventLogSchema,\n CompleteTaskBodyInput,\n ConnectionAuthSchema,\n FailTaskBodyInput,\n GetEventSchema,\n GetRunOptionsWithTaskDetails,\n GetRunSchema,\n GetRunsOptions,\n GetRunsSchema,\n LogLevel,\n Logger,\n RegisterScheduleResponseBodySchema,\n RegisterSourceEvent,\n RegisterSourceEventSchema,\n RegisterTriggerBody,\n RunTaskBodyInput,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n ServerTaskSchema,\n TriggerSource,\n TriggerSourceSchema,\n UpdateTriggerSourceBody,\n urlWithSearchParams,\n} from \"@trigger.dev/core\";\n\nimport fetch, { type RequestInit } from \"node-fetch\";\nimport { z } from \"zod\";\n\nexport type ApiClientOptions = {\n apiKey?: string;\n apiUrl?: string;\n logLevel?: LogLevel;\n};\n\nexport type EndpointRecord = {\n id: string;\n name: string;\n url: string;\n};\n\nexport type HttpSourceRecord = {\n id: string;\n key: string;\n managed: boolean;\n url: string;\n status: \"PENDING\" | \"ACTIVE\" | \"INACTIVE\";\n secret?: string;\n data?: any;\n};\n\nexport type RunRecord = {\n id: string;\n jobId: string;\n callbackUrl: string;\n event: ApiEventLog;\n};\n\nexport class ApiClient {\n #apiUrl: string;\n #options: ApiClientOptions;\n #logger: Logger;\n\n constructor(options: ApiClientOptions) {\n this.#options = options;\n\n this.#apiUrl = this.#options.apiUrl ?? process.env.TRIGGER_API_URL ?? \"https://api.trigger.dev\";\n this.#logger = new Logger(\"trigger.dev\", this.#options.logLevel);\n }\n\n async registerEndpoint(options: { url: string; name: string }): Promise<EndpointRecord> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Registering endpoint\", {\n url: options.url,\n name: options.name,\n });\n\n const response = await fetch(`${this.#apiUrl}/api/v1/endpoints`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n url: options.url,\n name: options.name,\n }),\n });\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status !== 200) {\n throw new Error(`Failed to register entry point, got status code ${response.status}`);\n }\n\n return await response.json();\n }\n\n async runTask(runId: string, task: RunTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Running Task\", {\n task,\n });\n\n return await zodfetch(ServerTaskSchema, `${this.#apiUrl}/api/v1/runs/${runId}/tasks`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n \"Idempotency-Key\": task.idempotencyKey,\n },\n body: JSON.stringify(task),\n });\n }\n\n async completeTask(runId: string, id: string, task: CompleteTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Complete Task\", {\n task,\n });\n\n return await zodfetch(\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks/${id}/complete`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(task),\n }\n );\n }\n\n async failTask(runId: string, id: string, body: FailTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Fail Task\", {\n id,\n runId,\n body,\n });\n\n return await zodfetch(\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks/${id}/fail`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n }\n );\n }\n\n async sendEvent(event: SendEvent, options: SendEventOptions = {}) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Sending event\", {\n event,\n });\n\n return await zodfetch(ApiEventLogSchema, `${this.#apiUrl}/api/v1/events`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ event, options }),\n });\n }\n\n async cancelEvent(eventId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Cancelling event\", {\n eventId,\n });\n\n return await zodfetch(ApiEventLogSchema, `${this.#apiUrl}/api/v1/events/${eventId}/cancel`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async updateSource(\n client: string,\n key: string,\n source: UpdateTriggerSourceBody\n ): Promise<TriggerSource> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"activating http source\", {\n source,\n });\n\n const response = await zodfetch(\n TriggerSourceSchema,\n `${this.#apiUrl}/api/v1/${client}/sources/${key}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(source),\n }\n );\n\n return response;\n }\n\n async registerTrigger(\n client: string,\n id: string,\n key: string,\n payload: RegisterTriggerBody\n ): Promise<RegisterSourceEvent> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering trigger\", {\n id,\n payload,\n });\n\n const response = await zodfetch(\n RegisterSourceEventSchema,\n `${this.#apiUrl}/api/v1/${client}/triggers/${id}/registrations/${key}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n }\n );\n\n return response;\n }\n\n async registerSchedule(client: string, id: string, key: string, payload: ScheduleMetadata) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering schedule\", {\n id,\n payload,\n });\n\n const response = await zodfetch(\n RegisterScheduleResponseBodySchema,\n `${this.#apiUrl}/api/v1/${client}/schedules/${id}/registrations`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ id: key, ...payload }),\n }\n );\n\n return response;\n }\n\n async unregisterSchedule(client: string, id: string, key: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"unregistering schedule\", {\n id,\n });\n\n const response = await zodfetch(\n z.object({ ok: z.boolean() }),\n `${this.#apiUrl}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`,\n {\n method: \"DELETE\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n\n return response;\n }\n\n async getAuth(client: string, id: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"getting auth\", {\n id,\n });\n\n const response = await zodfetch(\n ConnectionAuthSchema,\n `${this.#apiUrl}/api/v1/${client}/auth/${id}`,\n {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n },\n {\n optional: true,\n }\n );\n\n return response;\n }\n\n async getEvent(eventId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Event\", {\n eventId,\n });\n\n return await zodfetch(GetEventSchema, `${this.#apiUrl}/api/v1/events/${eventId}`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async getRun(runId: string, options?: GetRunOptionsWithTaskDetails) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Run\", {\n runId,\n });\n\n return await zodfetch(\n GetRunSchema,\n urlWithSearchParams(`${this.#apiUrl}/api/v1/runs/${runId}`, options),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async getRuns(jobSlug: string, options?: GetRunsOptions) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Runs\", {\n jobSlug,\n });\n\n return await zodfetch(\n GetRunsSchema,\n urlWithSearchParams(`${this.#apiUrl}/api/v1/jobs/${jobSlug}/runs`, options),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async #apiKey() {\n const apiKey = getApiKey(this.#options.apiKey);\n\n if (apiKey.status === \"invalid\") {\n throw new Error(\"Invalid API key\");\n\n // const chalk = (await import(\"chalk\")).default;\n // const terminalLink = (await import(\"terminal-link\")).default;\n\n // throw new Error(\n // `${chalk.red(\"Trigger.dev error\")}: Invalid API key (\"${chalk.italic(\n // apiKey.apiKey\n // )}\"), please set the TRIGGER_API_KEY environment variable or pass the apiKey option to a valid value. ${terminalLink(\n // \"Get your API key here\",\n // \"https://app.trigger.dev\",\n // {\n // fallback(text, url) {\n // return `${text} 👉 ${url}`;\n // },\n // }\n // )}`\n // );\n } else if (apiKey.status === \"missing\") {\n throw new Error(\"Missing API key\");\n // const chalk = (await import(\"chalk\")).default;\n // const terminalLink = (await import(\"terminal-link\")).default;\n\n // throw new Error(\n // `${chalk.red(\n // \"Trigger.dev error\"\n // )}: Missing an API key, please set the TRIGGER_API_KEY environment variable or pass the apiKey option to the Trigger constructor. ${terminalLink(\n // \"Get your API key here\",\n // \"https://app.trigger.dev\",\n // {\n // fallback(text, url) {\n // return `${text} 👉 ${url}`;\n // },\n // }\n // )}`\n // );\n }\n\n return apiKey.apiKey;\n }\n}\n\nfunction getApiKey(key?: string) {\n const apiKey = key ?? process.env.TRIGGER_API_KEY;\n\n if (!apiKey) {\n return { status: \"missing\" as const };\n }\n\n // Validate the api_key format (should be tr_{env}_XXXXX)\n const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);\n\n if (!isValid) {\n return { status: \"invalid\" as const, apiKey };\n }\n\n return { status: \"valid\" as const, apiKey };\n}\n\nasync function zodfetch<TResponseBody extends any, TOptional extends boolean = false>(\n schema: z.Schema<TResponseBody>,\n url: string,\n requestInit?: RequestInit,\n options?: {\n errorMessage?: string;\n optional?: TOptional;\n }\n): Promise<TOptional extends true ? TResponseBody | undefined : TResponseBody> {\n const response = await fetch(url, requestInit);\n\n if (\n (!requestInit || requestInit.method === \"GET\") &&\n response.status === 404 &&\n options?.optional\n ) {\n // @ts-ignore\n return;\n }\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status !== 200) {\n throw new Error(\n options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`\n );\n }\n\n const jsonBody = await response.json();\n\n return schema.parse(jsonBody);\n}\n","import { ErrorWithStack, ServerTask } from \"@trigger.dev/core\";\n\nexport class ResumeWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\nexport class RetryWithTaskError {\n constructor(\n public cause: ErrorWithStack,\n public task: ServerTask,\n public retryAt: Date\n ) {}\n}\n\nexport class CanceledWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\n/** Use this function if you're using a `try/catch` block to catch errors.\n * It checks if a thrown error is a special internal error that you should ignore.\n * If this returns `true` then you must rethrow the error: `throw err;`\n * @param err The error to check\n * @returns `true` if the error is a Trigger Error, `false` otherwise.\n */\nexport function isTriggerError(\n err: unknown\n): err is ResumeWithTaskError | RetryWithTaskError | CanceledWithTaskError {\n return (\n err instanceof ResumeWithTaskError ||\n err instanceof RetryWithTaskError ||\n err instanceof CanceledWithTaskError\n );\n}\n","import {\n CachedTask,\n ConnectionAuth,\n CronOptions,\n ErrorWithStackSchema,\n FetchRequestInit,\n FetchRetryOptions,\n IntervalOptions,\n LogLevel,\n Logger,\n RunTaskOptions,\n SendEvent,\n SendEventOptions,\n SerializableJson,\n SerializableJsonSchema,\n ServerTask,\n UpdateTriggerSourceBody,\n} from \"@trigger.dev/core\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { webcrypto } from \"node:crypto\";\nimport { ApiClient } from \"./apiClient\";\nimport {\n CanceledWithTaskError,\n ResumeWithTaskError,\n RetryWithTaskError,\n isTriggerError,\n} from \"./errors\";\nimport { createIOWithIntegrations } from \"./ioWithIntegrations\";\nimport { calculateRetryAt } from \"./retry\";\nimport { TriggerClient } from \"./triggerClient\";\nimport { DynamicTrigger } from \"./triggers/dynamic\";\nimport { ExternalSource, ExternalSourceParams } from \"./triggers/externalSource\";\nimport { DynamicSchedule } from \"./triggers/scheduled\";\nimport { EventSpecification, TaskLogger, TriggerContext } from \"./types\";\n\nexport type IOTask = ServerTask;\n\nexport type IOOptions = {\n id: string;\n apiClient: ApiClient;\n client: TriggerClient;\n context: TriggerContext;\n logger?: Logger;\n logLevel?: LogLevel;\n jobLogger?: Logger;\n jobLogLevel: LogLevel;\n cachedTasks?: Array<CachedTask>;\n};\n\nexport class IO {\n private _id: string;\n private _apiClient: ApiClient;\n private _triggerClient: TriggerClient;\n private _logger: Logger;\n private _jobLogger?: Logger;\n private _jobLogLevel: LogLevel;\n private _cachedTasks: Map<string, CachedTask>;\n private _taskStorage: AsyncLocalStorage<{ taskId: string }>;\n private _context: TriggerContext;\n\n constructor(options: IOOptions) {\n this._id = options.id;\n this._apiClient = options.apiClient;\n this._triggerClient = options.client;\n this._logger = options.logger ?? new Logger(\"trigger.dev\", options.logLevel);\n this._cachedTasks = new Map();\n this._jobLogger = options.jobLogger;\n this._jobLogLevel = options.jobLogLevel;\n\n if (options.cachedTasks) {\n options.cachedTasks.forEach((task) => {\n this._cachedTasks.set(task.idempotencyKey, task);\n });\n }\n\n this._taskStorage = new AsyncLocalStorage();\n this._context = options.context;\n }\n\n /** Used to send log messages to the [Run log](https://trigger.dev/docs/documentation/guides/viewing-runs). */\n get logger() {\n return new IOLogger(async (level, message, data) => {\n let logLevel: LogLevel = \"info\";\n\n switch (level) {\n case \"LOG\": {\n this._jobLogger?.log(message, data);\n logLevel = \"log\";\n break;\n }\n case \"DEBUG\": {\n this._jobLogger?.debug(message, data);\n logLevel = \"debug\";\n break;\n }\n case \"INFO\": {\n this._jobLogger?.info(message, data);\n logLevel = \"info\";\n break;\n }\n case \"WARN\": {\n this._jobLogger?.warn(message, data);\n logLevel = \"warn\";\n break;\n }\n case \"ERROR\": {\n this._jobLogger?.error(message, data);\n logLevel = \"error\";\n break;\n }\n }\n\n if (Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {\n await this.runTask(\n [message, level],\n {\n name: \"log\",\n icon: \"log\",\n description: message,\n params: data,\n properties: [{ label: \"Level\", text: level }],\n style: { style: \"minimal\", variant: level.toLowerCase() },\n noop: true,\n },\n async (task) => {}\n );\n }\n });\n }\n\n /** `io.wait()` waits for the specified amount of time before continuing the Job. Delays work even if you're on a serverless platform with timeouts, or if your server goes down. They utilize [resumability](https://trigger.dev/docs/documentation/concepts/resumability) to ensure that the Run can be resumed after the delay.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param seconds The number of seconds to wait. This can be very long, serverless timeouts are not an issue.\n */\n async wait(key: string | any[], seconds: number) {\n return await this.runTask(\n key,\n {\n name: \"wait\",\n icon: \"clock\",\n params: { seconds },\n noop: true,\n delayUntil: new Date(Date.now() + seconds * 1000),\n style: { style: \"minimal\" },\n },\n async (task) => {}\n );\n }\n\n /** `io.backgroundFetch()` fetches data from a URL that can take longer that the serverless timeout. The actual `fetch` request is performed on the Trigger.dev platform, and the response is sent back to you.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param url The URL to fetch from.\n * @param requestInit The options for the request\n * @param retry The options for retrying the request if it fails\n * An object where the key is a status code pattern and the value is a retrying strategy.\n * Supported patterns are:\n * - Specific status codes: 429\n * - Ranges: 500-599\n * - Wildcards: 2xx, 3xx, 4xx, 5xx\n */\n async backgroundFetch<TResponseData>(\n key: string | any[],\n url: string,\n requestInit?: FetchRequestInit,\n retry?: FetchRetryOptions\n ): Promise<TResponseData> {\n const urlObject = new URL(url);\n\n return (await this.runTask(\n key,\n {\n name: `fetch ${urlObject.hostname}${urlObject.pathname}`,\n params: { url, requestInit, retry },\n operation: \"fetch\",\n icon: \"background\",\n noop: false,\n properties: [\n {\n label: \"url\",\n text: url,\n url,\n },\n {\n label: \"method\",\n text: requestInit?.method ?? \"GET\",\n },\n {\n label: \"background\",\n text: \"true\",\n },\n ],\n },\n async (task) => {\n return task.output;\n }\n )) as TResponseData;\n }\n\n /** `io.sendEvent()` allows you to send an event from inside a Job run. The sent even will trigger any Jobs that are listening for that event (based on the name).\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param event The event to send. The event name must match the name of the event that your Jobs are listening for.\n * @param options Options for sending the event.\n */\n async sendEvent(key: string | any[], event: SendEvent, options?: SendEventOptions) {\n return await this.runTask(\n key,\n {\n name: \"sendEvent\",\n params: { event, options },\n properties: [\n {\n label: \"name\",\n text: event.name,\n },\n ...(event?.id ? [{ label: \"ID\", text: event.id }] : []),\n ],\n },\n async (task) => {\n return await this._triggerClient.sendEvent(event, options);\n }\n );\n }\n\n async getEvent(key: string | any[], id: string) {\n return await this.runTask(\n key,\n {\n name: \"getEvent\",\n params: { id },\n properties: [\n {\n label: \"id\",\n text: id,\n },\n ],\n },\n async (task) => {\n return await this._triggerClient.getEvent(id);\n }\n );\n }\n\n /** `io.cancelEvent()` allows you to cancel an event that was previously sent with `io.sendEvent()`. This will prevent any Jobs from running that are listening for that event if the event was sent with a delay\n * @param key\n * @param eventId\n * @returns\n */\n async cancelEvent(key: string | any[], eventId: string) {\n return await this.runTask(\n key,\n {\n name: \"cancelEvent\",\n params: {\n eventId,\n },\n properties: [\n {\n label: \"id\",\n text: eventId,\n },\n ],\n },\n async (task) => {\n return await this._triggerClient.cancelEvent(eventId);\n }\n );\n }\n\n async updateSource(key: string | any[], options: { key: string } & UpdateTriggerSourceBody) {\n return this.runTask(\n key,\n {\n name: \"Update Source\",\n description: \"Update Source\",\n properties: [\n {\n label: \"key\",\n text: options.key,\n },\n ],\n params: options,\n redact: {\n paths: [\"secret\"],\n },\n },\n async (task) => {\n return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);\n }\n );\n }\n\n /** `io.registerInterval()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular interval.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n * @param options The options for the interval.\n * @returns A promise that has information about the interval.\n */\n async registerInterval(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: IntervalOptions\n ) {\n return await this.runTask(\n key,\n {\n name: \"register-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n { label: \"seconds\", text: options.seconds.toString() },\n ],\n params: options,\n },\n async (task) => {\n return dynamicSchedule.register(id, {\n type: \"interval\",\n options,\n });\n }\n );\n }\n\n /** `io.unregisterInterval()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerInterval()`.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n */\n async unregisterInterval(key: string | any[], dynamicSchedule: DynamicSchedule, id: string) {\n return await this.runTask(\n key,\n {\n name: \"unregister-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n },\n async (task) => {\n return dynamicSchedule.unregister(id);\n }\n );\n }\n\n /** `io.registerCron()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular CRON schedule.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.\n * @param id A unique id for the schedule. This is used to identify and unregister the schedule later.\n * @param options The options for the CRON schedule.\n */\n async registerCron(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: CronOptions\n ) {\n return await this.runTask(\n key,\n {\n name: \"register-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n { label: \"cron\", text: options.cron },\n ],\n params: options,\n },\n async (task) => {\n return dynamicSchedule.register(id, {\n type: \"cron\",\n options,\n });\n }\n );\n }\n\n /** `io.unregisterCron()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerCron()`.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n */\n async unregisterCron(key: string | any[], dynamicSchedule: DynamicSchedule, id: string) {\n return await this.runTask(\n key,\n {\n name: \"unregister-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n },\n async (task) => {\n return dynamicSchedule.unregister(id);\n }\n );\n }\n\n /** `io.registerTrigger()` allows you to register a [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) with the specified trigger params.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param trigger The [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) to register.\n * @param id A unique id for the trigger. This is used to identify and unregister the trigger later.\n * @param params The params for the trigger.\n */\n async registerTrigger<\n TTrigger extends DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>,\n >(\n key: string | any[],\n trigger: TTrigger,\n id: string,\n params: ExternalSourceParams<TTrigger[\"source\"]>\n ): Promise<{ id: string; key: string } | undefined> {\n return await this.runTask(\n key,\n {\n name: \"register-trigger\",\n properties: [\n { label: \"trigger\", text: trigger.id },\n { label: \"id\", text: id },\n ],\n params: params as any,\n },\n async (task) => {\n const registration = await this.runTask(\n \"register-source\",\n {\n name: \"register-source\",\n },\n async (subtask1) => {\n return trigger.register(id, params);\n }\n );\n\n const connection = await this.getAuth(\"get-auth\", registration.source.clientId);\n\n const io = createIOWithIntegrations(\n // @ts-ignore\n this,\n {\n integration: connection,\n },\n {\n integration: trigger.source.integration,\n }\n );\n\n const updates = await trigger.source.register(params, registration, io, this._context);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await this.updateSource(\"update-source\", {\n key: registration.source.key,\n ...updates,\n });\n }\n );\n }\n\n async getAuth(key: string | any[], clientId?: string): Promise<ConnectionAuth | undefined> {\n if (!clientId) {\n return;\n }\n\n return this.runTask(key, { name: \"get-auth\" }, async (task) => {\n return await this._triggerClient.getAuth(clientId);\n });\n }\n\n /** `io.runTask()` allows you to run a [Task](https://trigger.dev/docs/documentation/concepts/tasks) from inside a Job run. A Task is a resumable unit of a Run that can be retried, resumed and is logged. [Integrations](https://trigger.dev/docs/integrations) use Tasks internally to perform their actions.\n *\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param options The options of how you'd like to run and log the Task. Name is required.\n * @param callback The callback that will be called when the Task is run. The callback receives the Task and the IO as parameters.\n= * @param onError The callback that will be called when the Task fails. The callback receives the error, the Task and the IO as parameters. If you wish to retry then return an object with a `retryAt` property.\n * @returns A Promise that resolves with the returned value of the callback.\n */\n async runTask<\n TResult extends SerializableJson | void = void,\n TCallbackResult extends unknown = TResult,\n >(\n key: string | any[],\n options: RunTaskOptions,\n callback: (task: IOTask, io: IO) => Promise<TCallbackResult | TResult>,\n onError?: (\n error: unknown,\n task: IOTask,\n io: IO\n ) => { retryAt: Date; error?: Error; jitter?: number } | Error | undefined | void\n ): Promise<TResult> {\n const parentId = this._taskStorage.getStore()?.taskId;\n\n if (parentId) {\n this._logger.debug(\"Using parent task\", {\n parentId,\n key,\n options,\n });\n }\n\n const idempotencyKey = await generateIdempotencyKey([this._id, parentId ?? \"\", key].flat());\n\n const cachedTask = this._cachedTasks.get(idempotencyKey);\n\n if (cachedTask) {\n this._logger.debug(\"Using cached task\", {\n idempotencyKey,\n cachedTask,\n });\n\n return cachedTask.output as TResult;\n }\n\n const task = await this._apiClient.runTask(this._id, {\n idempotencyKey,\n displayKey: typeof key === \"string\" ? key : undefined,\n noop: false,\n ...options,\n parentId,\n });\n\n if (task.status === \"CANCELED\") {\n this._logger.debug(\"Task canceled\", {\n idempotencyKey,\n task,\n });\n\n throw new CanceledWithTaskError(task);\n }\n\n if (task.status === \"COMPLETED\") {\n this._logger.debug(\"Using task output\", {\n idempotencyKey,\n task,\n });\n\n this.#addToCachedTasks(task);\n\n return task.output as TResult;\n }\n\n if (task.status === \"ERRORED\") {\n this._logger.debug(\"Task errored\", {\n idempotencyKey,\n task,\n });\n\n throw new Error(task.error ?? \"Task errored\");\n }\n\n if (task.status === \"WAITING\") {\n this._logger.debug(\"Task waiting\", {\n idempotencyKey,\n task,\n });\n\n throw new ResumeWithTaskError(task);\n }\n\n if (task.status === \"RUNNING\" && typeof task.operation === \"string\") {\n this._logger.debug(\"Task running operation\", {\n idempotencyKey,\n task,\n });\n\n throw new ResumeWithTaskError(task);\n }\n\n const executeTask = async () => {\n try {\n const result = await callback(task, this);\n\n const output = SerializableJsonSchema.parse(result) as TResult;\n\n this._logger.debug(\"Completing using output\", {\n idempotencyKey,\n task,\n });\n\n const completedTask = await this._apiClient.completeTask(this._id, task.id, {\n output: output ?? undefined,\n properties: task.outputProperties ?? undefined,\n });\n\n if (completedTask.status === \"CANCELED\") {\n throw new CanceledWithTaskError(completedTask);\n }\n\n return output;\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n if (onError) {\n try {\n const onErrorResult = onError(error, task, this);\n\n if (onErrorResult) {\n if (onErrorResult instanceof Error) {\n error = onErrorResult;\n } else {\n const parsedError = ErrorWithStackSchema.safeParse(onErrorResult.error);\n\n throw new RetryWithTaskError(\n parsedError.success ? parsedError.data : { message: \"Unknown error\" },\n task,\n onErrorResult.retryAt\n );\n }\n }\n } catch (innerError) {\n if (isTriggerError(innerError)) {\n throw innerError;\n }\n\n error = innerError;\n }\n }\n\n const parsedError = ErrorWithStackSchema.safeParse(error);\n\n if (options.retry) {\n const retryAt = calculateRetryAt(options.retry, task.attempts - 1);\n\n if (retryAt) {\n throw new RetryWithTaskError(\n parsedError.success ? parsedError.data : { message: \"Unknown error\" },\n task,\n retryAt\n );\n }\n }\n\n if (parsedError.success) {\n await this._apiClient.failTask(this._id, task.id, {\n error: parsedError.data,\n });\n } else {\n await this._apiClient.failTask(this._id, task.id, {\n error: { message: JSON.stringify(error), name: \"Unknown Error\" },\n });\n }\n\n throw error;\n }\n };\n\n return this._taskStorage.run({ taskId: task.id }, executeTask);\n }\n\n /** `io.try()` allows you to run Tasks and catch any errors that are thrown, it's similar to a normal `try/catch` block but works with [io.runTask()](/sdk/io/runtask).\n * A regular `try/catch` block on its own won't work as expected with Tasks. Internally `runTask()` throws some special errors to control flow execution. This is necessary to deal with resumability, serverless timeouts, and retrying Tasks.\n * @param tryCallback The code you wish to run\n * @param catchCallback Thhis will be called if the Task fails. The callback receives the error\n * @returns A Promise that resolves with the returned value or the error\n */\n async try<TResult, TCatchResult>(\n tryCallback: () => Promise<TResult>,\n catchCallback: (error: unknown) => Promise<TCatchResult>\n ): Promise<TResult | TCatchResult> {\n try {\n return await tryCallback();\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n return await catchCallback(error);\n }\n }\n\n #addToCachedTasks(task: ServerTask) {\n this._cachedTasks.set(task.idempotencyKey, task);\n }\n}\n\n// Generate a stable idempotency key for the key material, using a stable json stringification\nasync function generateIdempotencyKey(keyMaterial: any[]) {\n const keys = keyMaterial.map((key) => {\n if (typeof key === \"string\") {\n return key;\n }\n\n return stableStringify(key);\n });\n\n const key = keys.join(\":\");\n\n const hash = await webcrypto.subtle.digest(\"SHA-256\", Buffer.from(key));\n\n return Buffer.from(hash).toString(\"hex\");\n}\n\nfunction stableStringify(obj: any): string {\n function sortKeys(obj: any): any {\n if (typeof obj !== \"object\" || obj === null) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortKeys);\n }\n\n const sortedKeys = Object.keys(obj).sort();\n const sortedObj: { [key: string]: any } = {};\n\n for (const key of sortedKeys) {\n sortedObj[key] = sortKeys(obj[key]);\n }\n\n return sortedObj;\n }\n\n const sortedObj = sortKeys(obj);\n return JSON.stringify(sortedObj);\n}\n\ntype CallbackFunction = (\n level: \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"LOG\",\n message: string,\n properties?: Record<string, any>\n) => Promise<void>;\n\nexport class IOLogger implements TaskLogger {\n constructor(private callback: CallbackFunction) {}\n\n /** Log: essential messages */\n log(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"LOG\", message, properties);\n }\n\n /** For debugging: the least important log level */\n debug(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"DEBUG\", message, properties);\n }\n\n /** Info: the second least important log level */\n info(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"INFO\", message, properties);\n }\n\n /** Warnings: the third most important log level */\n warn(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"WARN\", message, properties);\n }\n\n /** Error: The second most important log level */\n error(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"ERROR\", message, properties);\n }\n}\n","import { ConnectionAuth, RunTaskOptions } from \"@trigger.dev/core\";\nimport {\n AuthenticatedTask,\n IOWithIntegrations,\n IntegrationClient,\n TriggerIntegration,\n} from \"./integrations\";\nimport { IO } from \"./io\";\n\nexport function createIOWithIntegrations<\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>>,\n>(\n io: IO,\n auths?: Record<string, ConnectionAuth | undefined>,\n integrations?: TIntegrations\n): IOWithIntegrations<TIntegrations> {\n if (!integrations) {\n return io as IOWithIntegrations<TIntegrations>;\n }\n\n const connections = Object.entries(integrations).reduce((acc, [connectionKey, integration]) => {\n let auth = auths?.[connectionKey];\n\n const client = integration.client.usesLocalAuth\n ? integration.client.client\n : auth\n ? integration.client.clientFactory?.(auth)\n : undefined;\n\n if (!client) {\n return acc;\n }\n\n auth = integration.client.usesLocalAuth ? integration.client.auth : auth;\n\n const ioConnection = {\n client,\n } as any;\n\n ioConnection.runTask = async (\n key: string | any[],\n callback: (client: any, task: any, io: IO) => Promise<any>,\n options?: RunTaskOptions\n ) => {\n return await io.runTask(\n key,\n {\n name: \"Task\",\n icon: integration.metadata.id,\n retry: {\n limit: 10,\n minTimeoutInMs: 1000,\n maxTimeoutInMs: 30000,\n factor: 2,\n randomize: true,\n },\n ...options,\n },\n async (ioTask) => {\n return await callback(client, ioTask, io);\n }\n );\n };\n\n if (integration.client.tasks) {\n const tasks: Record<string, AuthenticatedTask<any, any, any, any>> = integration.client.tasks;\n\n Object.keys(tasks).forEach((taskName) => {\n const authenticatedTask = tasks[taskName];\n\n ioConnection[taskName] = async (key: string | string[], params: any) => {\n const options = authenticatedTask.init(params);\n options.connectionKey = connectionKey;\n\n return await io.runTask(\n key,\n options,\n async (ioTask) => {\n return authenticatedTask.run(params, client, ioTask, io, auth);\n },\n authenticatedTask.onError\n );\n };\n });\n }\n\n acc[connectionKey] = ioConnection;\n\n return acc;\n }, {} as any);\n\n return new Proxy(io, {\n get(target, prop, receiver) {\n // We can return the original io back if the prop is __io\n if (prop === \"__io\") {\n return io;\n }\n\n if (prop in connections) {\n return connections[prop];\n }\n\n const value = Reflect.get(target, prop, receiver);\n return typeof value == \"function\" ? value.bind(target) : value;\n },\n }) as IOWithIntegrations<TIntegrations>;\n}\n","import type { RetryOptions } from \"@trigger.dev/core\";\nimport { calculateRetryAt } from \"@trigger.dev/core\";\n\nexport { calculateRetryAt };\nexport type { RetryOptions };\n","import { EventFilter, TriggerMetadata, deepMergeFilters } from \"@trigger.dev/core\";\nimport { z } from \"zod\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, EventSpecificationExample, Trigger } from \"../types\";\n\ntype EventTriggerOptions<TEventSpecification extends EventSpecification<any>> = {\n event: TEventSpecification;\n name?: string | string[];\n source?: string;\n filter?: EventFilter;\n};\n\nexport class EventTrigger<TEventSpecification extends EventSpecification<any>>\n implements Trigger<TEventSpecification>\n{\n #options: EventTriggerOptions<TEventSpecification>;\n\n constructor(options: EventTriggerOptions<TEventSpecification>) {\n this.#options = options;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.#options.name ?? this.#options.event.title,\n rule: {\n event: this.#options.name ?? this.#options.event.name,\n source: this.#options.source ?? \"trigger.dev\",\n payload: deepMergeFilters(this.#options.filter ?? {}, this.#options.event.filter ?? {}),\n },\n };\n }\n\n get event() {\n return this.#options.event;\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>): void {}\n\n get preprocessRuns() {\n return false;\n }\n}\n\n/** Configuration options for an EventTrigger */\ntype TriggerOptions<TEvent> = {\n /** The name of the event you are subscribing to. Must be an exact match (case sensitive). To trigger on multiple possible events, pass in an array of event names */\n name: string | string[];\n /** A [Zod](https://trigger.dev/docs/documentation/guides/zod) schema that defines the shape of the event payload.\n * The default is `z.any()` which is `any`.\n * */\n schema?: z.Schema<TEvent>;\n /** You can use this to filter events based on the source. */\n source?: string;\n /** Used to filter which events trigger the Job\n * @example\n * filter:\n * ```ts\n * {\n * name: [\"John\", \"Jane\"],\n * age: [18, 21]\n * }\n * ```\n *\n * This filter would match against an event with the following data:\n * ```json\n * {\n * \"name\": \"Jane\",\n * \"age\": 18,\n * \"location\": \"San Francisco\"\n * }\n * ```\n */\n filter?: EventFilter;\n\n examples?: EventSpecificationExample[];\n};\n\n/** `eventTrigger()` is set as a [Job's trigger](https://trigger.dev/docs/sdk/job) to subscribe to an event a Job from [a sent event](https://trigger.dev/docs/sdk/triggerclient/instancemethods/sendevent)\n * @param options options for the EventTrigger\n */\nexport function eventTrigger<TEvent extends any = any>(\n options: TriggerOptions<TEvent>\n): Trigger<EventSpecification<TEvent>> {\n return new EventTrigger({\n name: options.name,\n filter: options.filter,\n event: {\n name: options.name,\n title: \"Event\",\n source: options.source ?? \"trigger.dev\",\n icon: \"custom-event\",\n examples: options.examples,\n parsePayload: (rawPayload: any) => {\n if (options.schema) {\n return options.schema.parse(rawPayload);\n }\n\n return rawPayload as any;\n },\n },\n });\n}\n","import { ConnectionAuth, IntegrationMetadata, RunTaskOptions, ServerTask } from \"@trigger.dev/core\";\nimport { IO, IOTask } from \"./io\";\n\ntype IntegrationRunTaskFunction<TClient> = <TResult>(\n key: string | any[],\n callback: (client: TClient, task: IOTask, io: IO) => Promise<TResult>,\n options?: RunTaskOptions\n) => Promise<TResult>;\n\nexport type ClientFactory<TClient> = (auth: ConnectionAuth) => TClient;\n\nexport interface TriggerIntegration<\n TIntegrationClient extends IntegrationClient<any, any> = IntegrationClient<any, any>,\n> {\n client: TIntegrationClient;\n id: string;\n metadata: IntegrationMetadata;\n}\n\nexport type IntegrationClient<\n TClient,\n TTasks extends Record<string, AuthenticatedTask<TClient, any, any, any>>,\n> =\n | {\n usesLocalAuth: true;\n client: TClient;\n tasks?: TTasks;\n auth: any;\n }\n | {\n usesLocalAuth: false;\n clientFactory: ClientFactory<TClient>;\n tasks?: TTasks;\n };\n\nexport type AuthenticatedTask<TClient, TParams, TResult, TAuth = ConnectionAuth> = {\n run: (\n params: TParams,\n client: TClient,\n task: ServerTask,\n io: IO,\n auth: TAuth\n ) => Promise<TResult>;\n init: (params: TParams) => RunTaskOptions;\n onError?: (\n error: unknown,\n task: ServerTask\n ) => { retryAt: Date; error?: Error } | Error | undefined | void;\n};\n\nexport function authenticatedTask<TClient, TParams, TResult>(options: {\n run: (params: TParams, client: TClient, task: ServerTask, io: IO) => Promise<TResult>;\n init: (params: TParams) => RunTaskOptions;\n}): AuthenticatedTask<TClient, TParams, TResult> {\n return options;\n}\n\ntype ExtractRunFunction<T> = T extends AuthenticatedTask<\n any,\n infer TParams,\n infer TResult,\n infer TAuth\n>\n ? (key: string, params: TParams) => Promise<TResult>\n : never;\n\ntype ExtractTasks<TTasks extends Record<string, AuthenticatedTask<any, any, any, any>>> = {\n [key in keyof TTasks]: ExtractRunFunction<TTasks[key]>;\n};\n\ntype ExtractIntegrationClientClient<TIntegrationClient extends IntegrationClient<any, any>> =\n TIntegrationClient extends {\n usesLocalAuth: true;\n client: infer TClient;\n }\n ? {\n client: TClient;\n runTask: IntegrationRunTaskFunction<TClient>;\n }\n : TIntegrationClient extends {\n usesLocalAuth: false;\n clientFactory: ClientFactory<infer TClient>;\n }\n ? {\n client: TClient;\n runTask: IntegrationRunTaskFunction<TClient>;\n }\n : never;\n\ntype ExtractIntegrationClient<TIntegrationClient extends IntegrationClient<any, any>> =\n ExtractIntegrationClientClient<TIntegrationClient> & ExtractTasks<TIntegrationClient[\"tasks\"]>;\n\nexport type IntegrationIO<TIntegration extends TriggerIntegration<IntegrationClient<any, any>>> =\n ExtractIntegrationClient<TIntegration[\"client\"]>;\n\ntype ExtractIntegrations<\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>>,\n> = {\n [key in keyof TIntegrations]: ExtractIntegrationClient<TIntegrations[key][\"client\"]>;\n};\n\nexport type IOWithIntegrations<\n TIntegrations extends Record<string, TriggerIntegration<IntegrationClient<any, any>>>,\n> = IO & ExtractIntegrations<TIntegrations>;\n","import { z } from \"zod\";\n\nimport {\n DisplayProperty,\n EventFilter,\n HandleTriggerSource,\n Logger,\n NormalizedResponse,\n RegisterSourceEvent,\n SendEvent,\n TriggerMetadata,\n UpdateTriggerSourceBody,\n deepMergeFilters,\n} from \"@trigger.dev/core\";\nimport { IOWithIntegrations, IntegrationClient, TriggerIntegration } from \"../integrations\";\nimport { IO } from \"../io\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport type { EventSpecification, Trigger, TriggerContext } from \"../types\";\nimport { slugifyId } from \"../utils\";\n\nexport type HttpSourceEvent = {\n url: string;\n method: string;\n headers: Record<string, string>;\n rawBody?: Buffer | null;\n};\n\ntype SmtpSourceEvent = {\n from: string;\n to: string;\n subject: string;\n body: string;\n};\n\ntype SqsSourceEvent = {\n body: string;\n};\n\ntype ExternalSourceChannelMap = {\n HTTP: {\n event: Request;\n register: {\n url: string;\n };\n };\n SMTP: {\n event: SmtpSourceEvent;\n register: {};\n };\n SQS: {\n event: SqsSourceEvent;\n register: {};\n };\n};\n\ntype ChannelNames = keyof ExternalSourceChannelMap;\n\ntype RegisterFunctionEvent<TChannel extends ChannelNames, TParams extends any> = {\n events: Array<string>;\n missingEvents: Array<string>;\n orphanedEvents: Array<string>;\n source: {\n active: boolean;\n data?: any;\n secret: string;\n } & ExternalSourceChannelMap[TChannel][\"register\"];\n params: TParams;\n};\n\ntype RegisterFunction<\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any,\n TChannel extends ChannelNames,\n> = (\n event: RegisterFunctionEvent<TChannel, TParams>,\n io: IOWithIntegrations<{ integration: TIntegration }>,\n ctx: TriggerContext\n) => Promise<UpdateTriggerSourceBody | undefined>;\n\nexport type HandlerEvent<TChannel extends ChannelNames, TParams extends any = any> = {\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"];\n source: HandleTriggerSource & { params: TParams };\n};\n\ntype HandlerFunction<TChannel extends ChannelNames, TParams extends any> = (\n event: HandlerEvent<TChannel, TParams>,\n logger: Logger\n) => Promise<{ events: SendEvent[]; response?: NormalizedResponse } | void>;\n\ntype KeyFunction<TParams extends any> = (params: TParams) => string;\ntype FilterFunction<TParams extends any> = (params: TParams) => EventFilter;\n\ntype ExternalSourceOptions<\n TChannel extends ChannelNames,\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any,\n> = {\n id: string;\n version: string;\n schema: z.Schema<TParams>;\n integration: TIntegration;\n register: RegisterFunction<TIntegration, TParams, TChannel>;\n filter?: FilterFunction<TParams>;\n handler: HandlerFunction<TChannel, TParams>;\n key: KeyFunction<TParams>;\n properties?: (params: TParams) => DisplayProperty[];\n};\n\nexport class ExternalSource<\n TIntegration extends TriggerIntegration<IntegrationClient<any, any>>,\n TParams extends any,\n TChannel extends ChannelNames = ChannelNames,\n> {\n channel: TChannel;\n\n constructor(\n channel: TChannel,\n private options: ExternalSourceOptions<TChannel, TIntegration, TParams>\n ) {\n this.channel = channel;\n }\n\n async handle(\n source: HandleTriggerSource,\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"],\n logger: Logger\n ) {\n return this.options.handler(\n {\n source: { ...source, params: source.params as TParams },\n rawEvent,\n },\n logger\n );\n }\n\n filter(params: TParams): EventFilter {\n return this.options.filter?.(params) ?? {};\n }\n\n properties(params: TParams): DisplayProperty[] {\n return this.options.properties?.(params) ?? [];\n }\n\n async register(params: TParams, registerEvent: RegisterSourceEvent, io: IO, ctx: TriggerContext) {\n const { result: event, ommited: source } = omit(registerEvent, \"source\");\n const { result: sourceWithoutChannel, ommited: channel } = omit(source, \"channel\");\n const { result: channelWithoutType } = omit(channel, \"type\");\n\n const updates = await this.options.register(\n {\n ...event,\n source: { ...sourceWithoutChannel, ...channelWithoutType },\n params,\n },\n io as IOWithIntegrations<{ integration: TIntegration }>,\n ctx\n );\n\n return updates;\n }\n\n key(params: TParams): string {\n const parts = [this.options.id, this.channel];\n\n parts.push(this.options.key(params));\n parts.push(this.integration.id);\n\n return parts.join(\"-\");\n }\n\n get integration() {\n return this.options.integration;\n }\n\n get integrationConfig() {\n return {\n id: this.integration.id,\n metadata: this.integration.metadata,\n };\n }\n\n get id() {\n return this.options.id;\n }\n\n get version() {\n return this.options.version;\n }\n}\n\nexport type ExternalSourceParams<TExternalSource extends ExternalSource<any, any, any>> =\n TExternalSource extends ExternalSource<any, infer TParams, any>\n ? TParams & { filter?: EventFilter }\n : never;\n\nexport type ExternalSourceTriggerOptions<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>,\n> = {\n event: TEventSpecification;\n source: TEventSource;\n params: ExternalSourceParams<TEventSource>;\n};\n\nexport class ExternalSourceTrigger<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>,\n> implements Trigger<TEventSpecification>\n{\n constructor(private options: ExternalSourceTriggerOptions<TEventSpecification, TEventSource>) {}\n\n get event() {\n return this.options.event;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: \"External Source\",\n rule: {\n event: this.event.name,\n payload: deepMergeFilters(\n this.options.source.filter(this.options.params),\n this.event.filter ?? {},\n this.options.params.filter ?? {}\n ),\n source: this.event.source,\n },\n properties: this.options.source.properties(this.options.params),\n };\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>) {\n triggerClient.attachSource({\n key: slugifyId(this.options.source.key(this.options.params)),\n source: this.options.source,\n event: this.options.event,\n params: this.options.params,\n });\n }\n\n get preprocessRuns() {\n return true;\n }\n}\n\nexport function omit<T extends Record<string, unknown>, K extends keyof T>(\n obj: T,\n key: K\n): { result: Omit<T, K>; ommited: T[K] } {\n const result: any = {};\n\n for (const k of Object.keys(obj)) {\n if (k === key) continue;\n\n result[k] = obj[k];\n }\n\n return { result, ommited: obj[key] };\n}\n","import {\n RegisterSourceEvent,\n RegisterTriggerBody,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport { slugifyId } from \"../utils\";\nimport { ExternalSource, ExternalSourceParams } from \"./externalSource\";\n\n/** Options for a DynamicTrigger */\nexport type DynamicTriggerOptions<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n> = {\n /** Used to uniquely identify a DynamicTrigger */\n id: string;\n /** An event from an [Integration](https://trigger.dev/docs/integrations) package that you want to attach to the DynamicTrigger. The event types will come through to the payload in your Job's run. */\n event: TEventSpec;\n /** An external source fron an [Integration](https://trigger.dev/docs/integrations) package\n * @example \n * ```ts\n * import { events } from \"@trigger.dev/github\";\n * \n * const dynamicOnIssueOpened = new DynamicTrigger(client, {\n id: \"github-issue-opened\",\n event: events.onIssueOpened,\n source: github.sources.repo,\n });\n * ```\n */\n source: TExternalSource;\n};\n\n/** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime. */\nexport class DynamicTrigger<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n> implements Trigger<TEventSpec>\n{\n #client: TriggerClient;\n #options: DynamicTriggerOptions<TEventSpec, TExternalSource>;\n source: TExternalSource;\n\n /** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime.\n * @param client The `TriggerClient` instance to use for registering the trigger.\n * @param options The options for the dynamic trigger.\n * */\n constructor(client: TriggerClient, options: DynamicTriggerOptions<TEventSpec, TExternalSource>) {\n this.#client = client;\n this.#options = options;\n this.source = options.source;\n\n client.attachDynamicTrigger(this);\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.#options.id,\n };\n }\n\n get id() {\n return this.#options.id;\n }\n\n get event() {\n return this.#options.event;\n }\n\n registeredTriggerForParams(params: ExternalSourceParams<TExternalSource>): RegisterTriggerBody {\n const key = slugifyId(this.source.key(params));\n\n return {\n rule: {\n event: this.event.name,\n source: this.event.source,\n payload: deepMergeFilters(this.source.filter(params), this.event.filter ?? {}),\n },\n source: {\n key,\n channel: this.source.channel,\n params,\n events: typeof this.event.name === \"string\" ? [this.event.name] : this.event.name,\n integration: {\n id: this.source.integration.id,\n metadata: this.source.integration.metadata,\n authSource: this.source.integration.client.usesLocalAuth ? \"LOCAL\" : \"HOSTED\",\n },\n },\n };\n }\n\n /** Use this method to register a new configuration with the DynamicTrigger.\n * @param key The key for the configuration. This will be used to identify the configuration when it is triggered.\n * @param params The params for the configuration.\n */\n async register(\n key: string,\n params: ExternalSourceParams<TExternalSource>\n ): Promise<RegisterSourceEvent> {\n return this.#client.registerTrigger(this.id, key, this.registeredTriggerForParams(params));\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpec>, any>): void {\n triggerClient.attachJobToDynamicTrigger(job, this);\n }\n\n get preprocessRuns() {\n return true;\n }\n}\n","import {\n CronOptions,\n IntervalOptions,\n ScheduleMetadata,\n ScheduledPayload,\n ScheduledPayloadSchema,\n TriggerMetadata,\n currentDate,\n} from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport cronstrue from \"cronstrue\";\n\ntype ScheduledEventSpecification = EventSpecification<ScheduledPayload>;\n\nconst examples = [\n {\n id: \"now\",\n name: \"Now\",\n icon: \"clock\",\n payload: {\n ts: currentDate.marker,\n lastTimestamp: currentDate.marker,\n },\n },\n];\n\nexport class IntervalTrigger implements Trigger<ScheduledEventSpecification> {\n constructor(private options: IntervalOptions) {}\n\n get event() {\n return {\n name: \"trigger.scheduled\",\n title: \"Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-interval\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n properties: [\n {\n label: \"Interval\",\n text: `${this.options.seconds}s`,\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"scheduled\",\n schedule: {\n type: \"interval\",\n options: {\n seconds: this.options.seconds,\n },\n },\n };\n }\n}\n\n/** `intervalTrigger()` is set as a [Job's trigger](/sdk/job) to trigger a Job at a recurring interval.\n * @param options An object containing options about the interval.\n */\nexport function intervalTrigger(options: IntervalOptions) {\n return new IntervalTrigger(options);\n}\n\nexport class CronTrigger implements Trigger<ScheduledEventSpecification> {\n constructor(private options: CronOptions) {}\n\n get event() {\n const humanReadable = cronstrue.toString(this.options.cron, {\n throwExceptionOnParseError: false,\n });\n\n return {\n name: \"trigger.scheduled\",\n title: \"Cron Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-cron\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n properties: [\n {\n label: \"cron\",\n text: this.options.cron,\n },\n {\n label: \"Schedule\",\n text: humanReadable,\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"scheduled\",\n schedule: {\n type: \"cron\",\n options: {\n cron: this.options.cron,\n },\n },\n };\n }\n}\n\n/** `cronTrigger()` is set as a [Job's trigger](https://trigger.dev/docs/sdk/job) to trigger a Job on a recurring schedule using a CRON expression.\n * @param options An object containing options about the CRON schedule.\n */\nexport function cronTrigger(options: CronOptions) {\n return new CronTrigger(options);\n}\n\n/** DynamicSchedule options\n * @param id Used to uniquely identify a DynamicSchedule\n */\nexport type DynamicIntervalOptions = { id: string };\n\n/** DynamicSchedule` allows you to define a scheduled trigger that can be configured dynamically at runtime. */\nexport class DynamicSchedule implements Trigger<ScheduledEventSpecification> {\n /**\n * @param client The `TriggerClient` instance to use for registering the trigger.\n * @param options The options for the schedule.\n */\n constructor(\n private client: TriggerClient,\n private options: DynamicIntervalOptions\n ) {}\n\n get id() {\n return this.options.id;\n }\n\n get event() {\n return {\n name: \"trigger.scheduled\",\n title: \"Dynamic Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-dynamic\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n };\n }\n\n async register(key: string, metadata: ScheduleMetadata) {\n return this.client.registerSchedule(this.id, key, metadata);\n }\n\n async unregister(key: string) {\n return this.client.unregisterSchedule(this.id, key);\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {\n triggerClient.attachDynamicSchedule(this.options.id, job);\n }\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.options.id,\n };\n }\n}\n","import {\n MISSING_CONNECTION_NOTIFICATION,\n MISSING_CONNECTION_RESOLVED_NOTIFICATION,\n MissingConnectionNotificationPayload,\n MissingConnectionNotificationPayloadSchema,\n MissingConnectionResolvedNotificationPayload,\n MissingConnectionResolvedNotificationPayloadSchema,\n TriggerMetadata,\n} from \"@trigger.dev/core\";\nimport { TriggerIntegration } from \"../integrations\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\n\nexport function missingConnectionNotification(integrations: Array<TriggerIntegration>) {\n return new MissingConnectionNotification({ integrations });\n}\n\nexport function missingConnectionResolvedNotification(integrations: Array<TriggerIntegration>) {\n return new MissingConnectionResolvedNotification({ integrations });\n}\n\ntype MissingConnectionNotificationSpecification =\n EventSpecification<MissingConnectionNotificationPayload>;\n\ntype MissingConnectionNotificationOptions = {\n integrations: Array<TriggerIntegration>;\n};\n\nexport class MissingConnectionNotification\n implements Trigger<MissingConnectionNotificationSpecification>\n{\n constructor(private options: MissingConnectionNotificationOptions) {}\n\n get event() {\n return {\n name: MISSING_CONNECTION_NOTIFICATION,\n title: \"Missing Connection Notification\",\n source: \"trigger.dev\",\n icon: \"connection-alert\",\n parsePayload: MissingConnectionNotificationPayloadSchema.parse,\n properties: [\n {\n label: \"Integrations\",\n text: this.options.integrations.map((i) => i.id).join(\", \"),\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<MissingConnectionNotificationSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.event.title,\n rule: {\n event: this.event.name,\n source: \"trigger.dev\",\n payload: {\n client: {\n id: this.options.integrations.map((i) => i.id),\n },\n },\n },\n };\n }\n}\n\ntype MissingConnectionResolvedNotificationSpecification =\n EventSpecification<MissingConnectionResolvedNotificationPayload>;\n\nexport class MissingConnectionResolvedNotification\n implements Trigger<MissingConnectionResolvedNotificationSpecification>\n{\n constructor(private options: MissingConnectionNotificationOptions) {}\n\n get event() {\n return {\n name: MISSING_CONNECTION_RESOLVED_NOTIFICATION,\n title: \"Missing Connection Resolved Notification\",\n source: \"trigger.dev\",\n icon: \"connection-alert\",\n parsePayload: MissingConnectionResolvedNotificationPayloadSchema.parse,\n properties: [\n {\n label: \"Integrations\",\n text: this.options.integrations.map((i) => i.id).join(\", \"),\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<MissingConnectionResolvedNotificationSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.event.title,\n rule: {\n event: this.event.name,\n source: \"trigger.dev\",\n payload: {\n client: {\n id: this.options.integrations.map((i) => i.id),\n },\n },\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAO,SAASA,UAAUC,OAAuB;AAE/C,QAAMC,wBAAwBD,MAAME,YAAW,EAAGC,QAAQ,QAAQ,GAAA;AAGlE,QAAMC,wBAAwBH,sBAAsBE,QAAQ,qBAAqB,EAAA;AAEjF,SAAOC;AACT;AARgBL;;;ACIhB;AAmEO,IAAMM,MAAN,MAAMA;EAQXC,YAGEC,QACAC,SACA;AAqEF;AApEE,SAAKD,SAASA;AACd,SAAKC,UAAUA;AACf,0BAAK,wBAAL;AAEAD,WAAOE,OAAO,IAAI;EACpB;EAEA,IAAIC,KAAK;AACP,WAAOC,UAAU,KAAKH,QAAQE,EAAE;EAClC;EAEA,IAAIE,UAAU;AACZ,WAAO,OAAO,KAAKJ,QAAQI,YAAY,YAAY,KAAKJ,QAAQI,UAAU;EAC5E;EAEA,IAAIC,OAAO;AACT,WAAO,KAAKL,QAAQK;EACtB;EAEA,IAAIC,UAAU;AACZ,WAAO,KAAKN,QAAQM;EACtB;EAEA,IAAIC,UAAU;AACZ,WAAO,KAAKP,QAAQO;EACtB;EAEA,IAAIC,eAAkD;AACpD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,YACEC,eACAC,KACM;EAAC;EAET,IAAIC,iBAAiB;AACnB,WAAO;EACT;EAEAC,SAA0B;AACxB,WAAO;MACLC,MAAM;MACNlB,OAAO,KAAKH,MAAMG;MAClBmB,MAAM;QACJtB,OAAO,KAAKA,MAAMC;QAClBG,QAAQ;QACRmB,SAAS;UACPC,QAAQ;YACNV,IAAI,KAAKf,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE;UAC/C;QACF;MACF;IACF;EACF;AACF;AA7CajB;;;Ad9CN,SAAS8B,aACdC,YACGC,gBACW;AACd,SAAO;IACLC,kBAAkB;IAClBF,SAASA,QAAQG;IACjBF;EACF;AACF;AATgBF;","names":["slugifyId","input","replaceSpacesWithDash","toLowerCase","replace","removeNonUrlSafeChars","Job","constructor","client","options","attach","id","slugifyId","enabled","name","trigger","version","integrations","Object","keys","reduce","acc","key","integration","metadata","authSource","usesLocalAuth","logLevel","toJSON","internal","__internal","event","startPosition","preprocessRuns","match","Error","import_core","ApiClient","constructor","options","apiUrl","process","env","TRIGGER_API_URL","Logger","logLevel","registerEndpoint","apiKey","debug","url","name","response","fetch","method","headers","Authorization","body","JSON","stringify","status","json","Error","error","runTask","runId","task","zodfetch","ServerTaskSchema","idempotencyKey","completeTask","id","failTask","sendEvent","event","ApiEventLogSchema","cancelEvent","eventId","updateSource","client","key","source","TriggerSourceSchema","registerTrigger","payload","RegisterSourceEventSchema","registerSchedule","RegisterScheduleResponseBodySchema","unregisterSchedule","z","object","ok","boolean","encodeURIComponent","getAuth","ConnectionAuthSchema","Accept","optional","getEvent","GetEventSchema","getRun","GetRunSchema","urlWithSearchParams","getRuns","jobSlug","GetRunsSchema","getApiKey","TRIGGER_API_KEY","isValid","match","schema","requestInit","errorMessage","jsonBody","parse","ResumeWithTaskError","constructor","task","RetryWithTaskError","cause","retryAt","CanceledWithTaskError","isTriggerError","err","import_core","createIOWithIntegrations","io","auths","integrations","connections","Object","entries","reduce","acc","connectionKey","integration","auth","client","usesLocalAuth","clientFactory","undefined","ioConnection","runTask","key","callback","options","name","icon","metadata","id","retry","limit","minTimeoutInMs","maxTimeoutInMs","factor","randomize","ioTask","tasks","keys","forEach","taskName","authenticatedTask","params","init","run","onError","Proxy","get","target","prop","receiver","value","Reflect","bind","import_core","IO","constructor","options","_id","id","_apiClient","apiClient","_triggerClient","client","_logger","logger","Logger","logLevel","_cachedTasks","Map","_jobLogger","jobLogger","_jobLogLevel","jobLogLevel","cachedTasks","forEach","task","set","idempotencyKey","_taskStorage","AsyncLocalStorage","_context","context","IOLogger","level","message","data","log","debug","info","warn","error","satisfiesLogLevel","runTask","name","icon","description","params","properties","label","text","style","variant","toLowerCase","noop","wait","key","seconds","delayUntil","Date","now","backgroundFetch","url","requestInit","retry","urlObject","URL","hostname","pathname","operation","method","output","sendEvent","event","getEvent","cancelEvent","eventId","updateSource","redact","paths","registerInterval","dynamicSchedule","toString","register","type","unregisterInterval","unregister","registerCron","cron","unregisterCron","registerTrigger","trigger","registration","subtask1","connection","getAuth","source","clientId","io","createIOWithIntegrations","integration","updates","callback","onError","parentId","getStore","taskId","generateIdempotencyKey","flat","cachedTask","get","displayKey","undefined","status","CanceledWithTaskError","Error","ResumeWithTaskError","executeTask","result","SerializableJsonSchema","parse","completedTask","completeTask","outputProperties","isTriggerError","onErrorResult","parsedError","ErrorWithStackSchema","safeParse","RetryWithTaskError","success","retryAt","innerError","calculateRetryAt","attempts","failTask","JSON","stringify","run","try","tryCallback","catchCallback","keyMaterial","keys","map","stableStringify","join","hash","webcrypto","subtle","digest","Buffer","from","obj","sortKeys","Array","isArray","sortedKeys","Object","sort","sortedObj","import_core","_options","EventTrigger","constructor","options","toJSON","type","title","name","event","rule","source","payload","deepMergeFilters","filter","attachToJob","triggerClient","job","preprocessRuns","eventTrigger","icon","examples","parsePayload","rawPayload","schema","parse","registerSourceEvent","name","REGISTER_SOURCE_EVENT","title","source","icon","parsePayload","RegisterSourceEventSchema","parse","_options","TriggerClient","constructor","options","id","ApiClient","Logger","verbose","handleRequest","request","debug","url","headers","Object","fromEntries","entries","method","apiKey","get","authorization","authorized","status","body","message","action","endpointId","ok","error","jobId","job","toJSON","jobs","values","map","sources","dynamicTriggers","trigger","registerSourceJob","dynamicTriggerRegisterSourceJobId","version","dynamicSchedules","json","InitializeTriggerBodySchema","safeParse","success","dynamicTrigger","data","registeredTriggerForParams","params","execution","RunJobBodySchema","results","PreprocessRunBodySchema","abort","properties","HttpSourceRequestHeadersSchema","sourceRequestNeedsBody","sourceRequestInit","undefined","duplex","sourceRequest","Request","key","dynamicId","secret","response","events","attach","attachToJob","attachDynamicTrigger","Job","EventTrigger","event","filter","dynamicTriggerId","integrations","integration","run","io","ctx","updates","register","updateSource","__internal","attachJobToDynamicTrigger","push","attachSource","s","r","handle","registeredSource","channel","metadata","authSource","client","usesLocalAuth","Array","from","Set","attachDynamicSchedule","registerTrigger","getAuth","sendEvent","cancelEvent","eventId","registerSchedule","schedule","unregisterSchedule","getEvent","getRun","runId","getRuns","jobSlug","localApiKey","process","env","TRIGGER_API_KEY","defineJob","context","parsedPayload","payload","runProperties","IO","cachedTasks","tasks","apiClient","logger","jobLogLevel","logLevel","jobLogger","ioLogLocalEnabled","ioWithConnections","createIOWithIntegrations","connections","output","ResumeWithTaskError","task","RetryWithTaskError","cause","retryAt","CanceledWithTaskError","errorWithStack","ErrorWithStackSchema","organization","environment","timestamp","account","handler","authenticatedTask","options","import_core","ExternalSource","constructor","channel","options","handle","source","rawEvent","logger","handler","params","filter","properties","register","registerEvent","io","ctx","result","event","ommited","omit","sourceWithoutChannel","channelWithoutType","updates","key","parts","id","push","integration","join","integrationConfig","metadata","version","ExternalSourceTrigger","toJSON","type","title","rule","name","payload","deepMergeFilters","attachToJob","triggerClient","job","attachSource","slugifyId","preprocessRuns","obj","k","Object","keys","import_core","_client","_options","DynamicTrigger","constructor","client","options","source","attachDynamicTrigger","toJSON","type","id","event","registeredTriggerForParams","params","key","slugifyId","rule","name","payload","deepMergeFilters","filter","channel","events","integration","metadata","authSource","usesLocalAuth","register","registerTrigger","attachToJob","triggerClient","job","attachJobToDynamicTrigger","preprocessRuns","import_core","examples","id","name","icon","payload","ts","currentDate","marker","lastTimestamp","IntervalTrigger","constructor","options","event","title","source","parsePayload","ScheduledPayloadSchema","parse","properties","label","text","seconds","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","schedule","intervalTrigger","CronTrigger","humanReadable","cronstrue","toString","cron","throwExceptionOnParseError","cronTrigger","DynamicSchedule","client","register","key","metadata","registerSchedule","unregister","unregisterSchedule","attachDynamicSchedule","import_core","missingConnectionNotification","integrations","MissingConnectionNotification","missingConnectionResolvedNotification","MissingConnectionResolvedNotification","constructor","options","event","name","MISSING_CONNECTION_NOTIFICATION","title","source","icon","parsePayload","MissingConnectionNotificationPayloadSchema","parse","properties","label","text","map","i","id","join","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","rule","payload","client","MISSING_CONNECTION_RESOLVED_NOTIFICATION","MissingConnectionResolvedNotificationPayloadSchema","redactString","strings","interpolations","__redactedString","raw"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trigger.dev/sdk",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.12",
|
|
4
4
|
"description": "trigger.dev Node.JS SDK",
|
|
5
|
+
"license": "MIT",
|
|
5
6
|
"main": "./dist/index.js",
|
|
6
7
|
"types": "./dist/index.d.ts",
|
|
7
8
|
"publishConfig": {
|
|
@@ -18,7 +19,7 @@
|
|
|
18
19
|
"./package.json": "./package.json"
|
|
19
20
|
},
|
|
20
21
|
"dependencies": {
|
|
21
|
-
"@trigger.dev/core": "^2.0.
|
|
22
|
+
"@trigger.dev/core": "^2.0.12",
|
|
22
23
|
"chalk": "^5.2.0",
|
|
23
24
|
"cronstrue": "^2.21.0",
|
|
24
25
|
"debug": "^4.3.4",
|