@trigger.dev/core 3.0.0-beta.5 → 3.0.0-beta.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/dist/api-Pl9fxB8v.d.mts +13879 -0
  2. package/dist/api-sNoooMbT.d.ts +13879 -0
  3. package/dist/catalog-H7yFiZ60.d.mts +202 -0
  4. package/dist/catalog-h79CG5Wy.d.ts +202 -0
  5. package/dist/common-CLW82lkt.d.mts +1423 -0
  6. package/dist/common-CLW82lkt.d.ts +1423 -0
  7. package/dist/{eventFilterMatches-2kHImluE.d.mts → eventFilter-66NaBAMi.d.mts} +1 -3
  8. package/dist/{eventFilterMatches-2kHImluE.d.ts → eventFilter-66NaBAMi.d.ts} +1 -3
  9. package/dist/eventFilterMatches.d.mts +6 -0
  10. package/dist/eventFilterMatches.d.ts +6 -0
  11. package/dist/eventFilterMatches.js +165 -0
  12. package/dist/eventFilterMatches.js.map +1 -0
  13. package/dist/eventFilterMatches.mjs +163 -0
  14. package/dist/eventFilterMatches.mjs.map +1 -0
  15. package/dist/index.d.mts +14 -16657
  16. package/dist/index.d.ts +14 -16657
  17. package/dist/index.js +8 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.mjs +8 -2
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/json-DBPEJQRe.d.mts +16 -0
  22. package/dist/json-DBPEJQRe.d.ts +16 -0
  23. package/dist/manager-KvCabW1a.d.mts +18 -0
  24. package/dist/manager-OBA35PzR.d.ts +18 -0
  25. package/dist/messages-JvHJ83wv.d.mts +19428 -0
  26. package/dist/messages-JvHJ83wv.d.ts +19428 -0
  27. package/dist/replacements.d.mts +22 -0
  28. package/dist/replacements.d.ts +22 -0
  29. package/dist/replacements.js +33 -0
  30. package/dist/replacements.js.map +1 -0
  31. package/dist/replacements.mjs +28 -0
  32. package/dist/replacements.mjs.map +1 -0
  33. package/dist/requestFilter-HNZQEpQb.d.ts +180 -0
  34. package/dist/requestFilter-b5W2_1oP.d.mts +180 -0
  35. package/dist/requestFilterMatches.d.mts +13 -0
  36. package/dist/requestFilterMatches.d.ts +13 -0
  37. package/dist/requestFilterMatches.js +238 -0
  38. package/dist/requestFilterMatches.js.map +1 -0
  39. package/dist/requestFilterMatches.mjs +235 -0
  40. package/dist/requestFilterMatches.mjs.map +1 -0
  41. package/dist/retry.d.mts +10 -0
  42. package/dist/retry.d.ts +10 -0
  43. package/dist/retry.js +100 -0
  44. package/dist/retry.js.map +1 -0
  45. package/dist/retry.mjs +97 -0
  46. package/dist/retry.mjs.map +1 -0
  47. package/dist/schemas/index.d.mts +2611 -0
  48. package/dist/schemas/index.d.ts +2611 -0
  49. package/dist/schemas/index.js +1630 -0
  50. package/dist/schemas/index.js.map +1 -0
  51. package/dist/schemas/index.mjs +1463 -0
  52. package/dist/schemas/index.mjs.map +1 -0
  53. package/dist/schemas-C9ssfehv.d.mts +2568 -0
  54. package/dist/schemas-C9ssfehv.d.ts +2568 -0
  55. package/dist/taskLogger-CzADe4je.d.ts +33 -0
  56. package/dist/taskLogger-r_AFTX45.d.mts +33 -0
  57. package/dist/tracer-N0p2Fuuv.d.mts +23 -0
  58. package/dist/tracer-N0p2Fuuv.d.ts +23 -0
  59. package/dist/types.d.mts +11 -0
  60. package/dist/types.d.ts +11 -0
  61. package/dist/types.js +4 -0
  62. package/dist/types.js.map +1 -0
  63. package/dist/types.mjs +3 -0
  64. package/dist/types.mjs.map +1 -0
  65. package/dist/utils.d.mts +7 -0
  66. package/dist/utils.d.ts +7 -0
  67. package/dist/utils.js +33 -0
  68. package/dist/utils.js.map +1 -0
  69. package/dist/utils.mjs +30 -0
  70. package/dist/utils.mjs.map +1 -0
  71. package/dist/v3/dev/index.d.mts +29 -0
  72. package/dist/v3/dev/index.d.ts +29 -0
  73. package/dist/v3/dev/index.js +93 -0
  74. package/dist/v3/dev/index.js.map +1 -0
  75. package/dist/v3/dev/index.mjs +91 -0
  76. package/dist/v3/dev/index.mjs.map +1 -0
  77. package/dist/v3/errors.d.mts +39 -0
  78. package/dist/v3/errors.d.ts +39 -0
  79. package/dist/v3/errors.js +204 -0
  80. package/dist/v3/errors.js.map +1 -0
  81. package/dist/v3/errors.mjs +195 -0
  82. package/dist/v3/errors.mjs.map +1 -0
  83. package/dist/v3/index.d.mts +445 -20508
  84. package/dist/v3/index.d.ts +445 -20508
  85. package/dist/v3/index.js +2843 -2884
  86. package/dist/v3/index.js.map +1 -1
  87. package/dist/v3/index.mjs +2785 -2856
  88. package/dist/v3/index.mjs.map +1 -1
  89. package/dist/v3/logger-api.d.mts +24 -0
  90. package/dist/v3/logger-api.d.ts +24 -0
  91. package/dist/v3/logger-api.js +118 -0
  92. package/dist/v3/logger-api.js.map +1 -0
  93. package/dist/v3/logger-api.mjs +116 -0
  94. package/dist/v3/logger-api.mjs.map +1 -0
  95. package/dist/v3/otel/index.js +119 -53
  96. package/dist/v3/otel/index.js.map +1 -1
  97. package/dist/v3/otel/index.mjs +119 -53
  98. package/dist/v3/otel/index.mjs.map +1 -1
  99. package/dist/v3/prod/index.d.mts +46 -0
  100. package/dist/v3/prod/index.d.ts +46 -0
  101. package/dist/v3/prod/index.js +180 -0
  102. package/dist/v3/prod/index.js.map +1 -0
  103. package/dist/v3/prod/index.mjs +178 -0
  104. package/dist/v3/prod/index.mjs.map +1 -0
  105. package/dist/v3/schemas/index.d.mts +4807 -0
  106. package/dist/v3/schemas/index.d.ts +4807 -0
  107. package/dist/v3/schemas/index.js +2054 -0
  108. package/dist/v3/schemas/index.js.map +1 -0
  109. package/dist/v3/schemas/index.mjs +1913 -0
  110. package/dist/v3/schemas/index.mjs.map +1 -0
  111. package/dist/v3/semanticInternalAttributes.d.mts +56 -0
  112. package/dist/v3/semanticInternalAttributes.d.ts +56 -0
  113. package/dist/v3/semanticInternalAttributes.js +61 -0
  114. package/dist/v3/semanticInternalAttributes.js.map +1 -0
  115. package/dist/v3/semanticInternalAttributes.mjs +59 -0
  116. package/dist/v3/semanticInternalAttributes.mjs.map +1 -0
  117. package/dist/v3/utils/durations.d.mts +15 -0
  118. package/dist/v3/utils/durations.d.ts +15 -0
  119. package/dist/v3/utils/durations.js +93 -0
  120. package/dist/v3/utils/durations.js.map +1 -0
  121. package/dist/v3/utils/durations.mjs +82 -0
  122. package/dist/v3/utils/durations.mjs.map +1 -0
  123. package/dist/v3/utils/flattenAttributes.d.mts +8 -0
  124. package/dist/v3/utils/flattenAttributes.d.ts +8 -0
  125. package/dist/v3/utils/flattenAttributes.js +131 -0
  126. package/dist/v3/utils/flattenAttributes.js.map +1 -0
  127. package/dist/v3/utils/flattenAttributes.mjs +126 -0
  128. package/dist/v3/utils/flattenAttributes.mjs.map +1 -0
  129. package/dist/v3/utils/ioSerialization.d.mts +21 -0
  130. package/dist/v3/utils/ioSerialization.d.ts +21 -0
  131. package/dist/v3/utils/ioSerialization.js +2392 -0
  132. package/dist/v3/utils/ioSerialization.js.map +1 -0
  133. package/dist/v3/utils/ioSerialization.mjs +2383 -0
  134. package/dist/v3/utils/ioSerialization.mjs.map +1 -0
  135. package/dist/v3/utils/omit.d.mts +3 -0
  136. package/dist/v3/utils/omit.d.ts +3 -0
  137. package/dist/v3/utils/omit.js +20 -0
  138. package/dist/v3/utils/omit.js.map +1 -0
  139. package/dist/v3/utils/omit.mjs +18 -0
  140. package/dist/v3/utils/omit.mjs.map +1 -0
  141. package/dist/v3/utils/retries.d.mts +46 -0
  142. package/dist/v3/utils/retries.d.ts +46 -0
  143. package/dist/v3/utils/retries.js +118 -0
  144. package/dist/v3/utils/retries.js.map +1 -0
  145. package/dist/v3/utils/retries.mjs +113 -0
  146. package/dist/v3/utils/retries.mjs.map +1 -0
  147. package/dist/v3/utils/structuredLogger.d.mts +31 -0
  148. package/dist/v3/utils/structuredLogger.d.ts +31 -0
  149. package/dist/v3/utils/structuredLogger.js +88 -0
  150. package/dist/v3/utils/structuredLogger.js.map +1 -0
  151. package/dist/v3/utils/structuredLogger.mjs +86 -0
  152. package/dist/v3/utils/structuredLogger.mjs.map +1 -0
  153. package/dist/v3/utils/timers.d.mts +6 -0
  154. package/dist/v3/utils/timers.d.ts +6 -0
  155. package/dist/v3/utils/timers.js +31 -0
  156. package/dist/v3/utils/timers.js.map +1 -0
  157. package/dist/v3/utils/timers.mjs +28 -0
  158. package/dist/v3/utils/timers.mjs.map +1 -0
  159. package/dist/v3/workers/index.d.mts +144 -0
  160. package/dist/v3/workers/index.d.ts +144 -0
  161. package/dist/v3/workers/index.js +3708 -0
  162. package/dist/v3/workers/index.js.map +1 -0
  163. package/dist/v3/workers/index.mjs +3689 -0
  164. package/dist/v3/workers/index.mjs.map +1 -0
  165. package/dist/v3/zodIpc.d.mts +32 -0
  166. package/dist/v3/zodIpc.d.ts +32 -0
  167. package/dist/v3/zodIpc.js +268 -0
  168. package/dist/v3/zodIpc.js.map +1 -0
  169. package/dist/v3/zodIpc.mjs +266 -0
  170. package/dist/v3/zodIpc.mjs.map +1 -0
  171. package/dist/v3/zodMessageHandler.d.mts +82 -0
  172. package/dist/v3/zodMessageHandler.d.ts +82 -0
  173. package/dist/v3/zodMessageHandler.js +222 -0
  174. package/dist/v3/zodMessageHandler.js.map +1 -0
  175. package/dist/v3/zodMessageHandler.mjs +217 -0
  176. package/dist/v3/zodMessageHandler.mjs.map +1 -0
  177. package/dist/v3/zodNamespace.d.mts +3663 -0
  178. package/dist/v3/zodNamespace.d.ts +3663 -0
  179. package/dist/v3/zodNamespace.js +397 -0
  180. package/dist/v3/zodNamespace.js.map +1 -0
  181. package/dist/v3/zodNamespace.mjs +395 -0
  182. package/dist/v3/zodNamespace.mjs.map +1 -0
  183. package/dist/v3/zodSocket.d.mts +93 -0
  184. package/dist/v3/zodSocket.d.ts +93 -0
  185. package/dist/v3/zodSocket.js +350 -0
  186. package/dist/v3/zodSocket.js.map +1 -0
  187. package/dist/v3/zodSocket.mjs +346 -0
  188. package/dist/v3/zodSocket.mjs.map +1 -0
  189. package/dist/v3/zodfetch.d.mts +219 -0
  190. package/dist/v3/zodfetch.d.ts +219 -0
  191. package/dist/v3/zodfetch.js +834 -0
  192. package/dist/v3/zodfetch.js.map +1 -0
  193. package/dist/v3/zodfetch.mjs +811 -0
  194. package/dist/v3/zodfetch.mjs.map +1 -0
  195. package/dist/versions.d.mts +11 -0
  196. package/dist/versions.d.ts +11 -0
  197. package/dist/versions.js +31 -0
  198. package/dist/versions.js.map +1 -0
  199. package/dist/versions.mjs +27 -0
  200. package/dist/versions.mjs.map +1 -0
  201. package/package.json +223 -5
@@ -0,0 +1,2383 @@
1
+ import { propagation, context } from '@opentelemetry/api';
2
+ import { z } from 'zod';
3
+ import { fromZodError } from 'zod-validation-error';
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __publicField = (obj, key, value) => {
9
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
10
+ return value;
11
+ };
12
+ var __accessCheck = (obj, member, msg) => {
13
+ if (!member.has(obj))
14
+ throw TypeError("Cannot " + msg);
15
+ };
16
+ var __privateAdd = (obj, member, value) => {
17
+ if (member.has(obj))
18
+ throw TypeError("Cannot add the same private member more than once");
19
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
20
+ };
21
+ var __privateMethod = (obj, member, method) => {
22
+ __accessCheck(obj, member, "access private method");
23
+ return method;
24
+ };
25
+
26
+ // src/v3/limits.ts
27
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
28
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
29
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
30
+ function imposeAttributeLimits(attributes) {
31
+ const newAttributes = {};
32
+ for (const [key, value] of Object.entries(attributes)) {
33
+ if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
34
+ continue;
35
+ }
36
+ if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
37
+ break;
38
+ }
39
+ newAttributes[key] = value;
40
+ }
41
+ return newAttributes;
42
+ }
43
+ __name(imposeAttributeLimits, "imposeAttributeLimits");
44
+ function calculateAttributeValueLength(value) {
45
+ if (value === void 0 || value === null) {
46
+ return 0;
47
+ }
48
+ if (typeof value === "string") {
49
+ return value.length;
50
+ }
51
+ if (typeof value === "number") {
52
+ return 8;
53
+ }
54
+ if (typeof value === "boolean") {
55
+ return 4;
56
+ }
57
+ if (Array.isArray(value)) {
58
+ return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
59
+ }
60
+ return 0;
61
+ }
62
+ __name(calculateAttributeValueLength, "calculateAttributeValueLength");
63
+
64
+ // src/v3/semanticInternalAttributes.ts
65
+ var SemanticInternalAttributes = {
66
+ ENVIRONMENT_ID: "ctx.environment.id",
67
+ ENVIRONMENT_TYPE: "ctx.environment.type",
68
+ ORGANIZATION_ID: "ctx.organization.id",
69
+ ORGANIZATION_SLUG: "ctx.organization.slug",
70
+ ORGANIZATION_NAME: "ctx.organization.name",
71
+ PROJECT_ID: "ctx.project.id",
72
+ PROJECT_REF: "ctx.project.ref",
73
+ PROJECT_NAME: "ctx.project.title",
74
+ PROJECT_DIR: "project.dir",
75
+ ATTEMPT_ID: "ctx.attempt.id",
76
+ ATTEMPT_NUMBER: "ctx.attempt.number",
77
+ RUN_ID: "ctx.run.id",
78
+ RUN_IS_TEST: "ctx.run.isTest",
79
+ BATCH_ID: "ctx.batch.id",
80
+ TASK_SLUG: "ctx.task.id",
81
+ TASK_PATH: "ctx.task.filePath",
82
+ TASK_EXPORT_NAME: "ctx.task.exportName",
83
+ QUEUE_NAME: "ctx.queue.name",
84
+ QUEUE_ID: "ctx.queue.id",
85
+ MACHINE_PRESET_NAME: "ctx.machine.name",
86
+ MACHINE_PRESET_CPU: "ctx.machine.cpu",
87
+ MACHINE_PRESET_MEMORY: "ctx.machine.memory",
88
+ MACHINE_PRESET_CENTS_PER_MS: "ctx.machine.centsPerMs",
89
+ SPAN_PARTIAL: "$span.partial",
90
+ SPAN_ID: "$span.span_id",
91
+ OUTPUT: "$output",
92
+ OUTPUT_TYPE: "$mime_type_output",
93
+ STYLE: "$style",
94
+ STYLE_ICON: "$style.icon",
95
+ STYLE_VARIANT: "$style.variant",
96
+ STYLE_ACCESSORY: "$style.accessory",
97
+ METADATA: "$metadata",
98
+ TRIGGER: "$trigger",
99
+ PAYLOAD: "$payload",
100
+ PAYLOAD_TYPE: "$mime_type_payload",
101
+ SHOW: "$show",
102
+ SHOW_ACTIONS: "$show.actions",
103
+ WORKER_ID: "worker.id",
104
+ WORKER_VERSION: "worker.version",
105
+ CLI_VERSION: "cli.version",
106
+ SDK_VERSION: "sdk.version",
107
+ SDK_LANGUAGE: "sdk.language",
108
+ RETRY_AT: "retry.at",
109
+ RETRY_DELAY: "retry.delay",
110
+ RETRY_COUNT: "retry.count",
111
+ LINK_TITLE: "$link.title",
112
+ IDEMPOTENCY_KEY: "ctx.run.idempotencyKey",
113
+ USAGE_DURATION_MS: "$usage.durationMs",
114
+ USAGE_COST_IN_CENTS: "$usage.costInCents",
115
+ RATE_LIMIT_LIMIT: "response.rateLimit.limit",
116
+ RATE_LIMIT_REMAINING: "response.rateLimit.remaining",
117
+ RATE_LIMIT_RESET: "response.rateLimit.reset"
118
+ };
119
+
120
+ // src/v3/utils/flattenAttributes.ts
121
+ var NULL_SENTINEL = "$@null((";
122
+ function flattenAttributes(obj, prefix) {
123
+ const result = {};
124
+ if (obj === void 0) {
125
+ return result;
126
+ }
127
+ if (obj === null) {
128
+ result[prefix || ""] = NULL_SENTINEL;
129
+ return result;
130
+ }
131
+ if (typeof obj === "string") {
132
+ result[prefix || ""] = obj;
133
+ return result;
134
+ }
135
+ if (typeof obj === "number") {
136
+ result[prefix || ""] = obj;
137
+ return result;
138
+ }
139
+ if (typeof obj === "boolean") {
140
+ result[prefix || ""] = obj;
141
+ return result;
142
+ }
143
+ for (const [key, value] of Object.entries(obj)) {
144
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${key}]` : key}`;
145
+ if (Array.isArray(value)) {
146
+ for (let i = 0; i < value.length; i++) {
147
+ if (typeof value[i] === "object" && value[i] !== null) {
148
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
149
+ } else {
150
+ if (value[i] === null) {
151
+ result[`${newPrefix}.[${i}]`] = NULL_SENTINEL;
152
+ } else {
153
+ result[`${newPrefix}.[${i}]`] = value[i];
154
+ }
155
+ }
156
+ }
157
+ } else if (isRecord(value)) {
158
+ Object.assign(result, flattenAttributes(value, newPrefix));
159
+ } else {
160
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
161
+ result[newPrefix] = value;
162
+ } else if (value === null) {
163
+ result[newPrefix] = NULL_SENTINEL;
164
+ }
165
+ }
166
+ }
167
+ return result;
168
+ }
169
+ __name(flattenAttributes, "flattenAttributes");
170
+ function isRecord(value) {
171
+ return value !== null && typeof value === "object" && !Array.isArray(value);
172
+ }
173
+ __name(isRecord, "isRecord");
174
+
175
+ // package.json
176
+ var version = "3.0.0-beta.51";
177
+ var MachineCpu = z.union([
178
+ z.literal(0.25),
179
+ z.literal(0.5),
180
+ z.literal(1),
181
+ z.literal(2),
182
+ z.literal(4)
183
+ ]);
184
+ var MachineMemory = z.union([
185
+ z.literal(0.25),
186
+ z.literal(0.5),
187
+ z.literal(1),
188
+ z.literal(2),
189
+ z.literal(4),
190
+ z.literal(8)
191
+ ]);
192
+ var MachinePresetName = z.enum([
193
+ "micro",
194
+ "small-1x",
195
+ "small-2x",
196
+ "medium-1x",
197
+ "medium-2x",
198
+ "large-1x",
199
+ "large-2x"
200
+ ]);
201
+ var MachineConfig = z.object({
202
+ cpu: MachineCpu.optional(),
203
+ memory: MachineMemory.optional(),
204
+ preset: MachinePresetName.optional()
205
+ });
206
+ var MachinePreset = z.object({
207
+ name: MachinePresetName,
208
+ cpu: z.number(),
209
+ memory: z.number(),
210
+ centsPerMs: z.number()
211
+ });
212
+ var TaskRunBuiltInError = z.object({
213
+ type: z.literal("BUILT_IN_ERROR"),
214
+ name: z.string(),
215
+ message: z.string(),
216
+ stackTrace: z.string()
217
+ });
218
+ var TaskRunCustomErrorObject = z.object({
219
+ type: z.literal("CUSTOM_ERROR"),
220
+ raw: z.string()
221
+ });
222
+ var TaskRunStringError = z.object({
223
+ type: z.literal("STRING_ERROR"),
224
+ raw: z.string()
225
+ });
226
+ var TaskRunInternalError = z.object({
227
+ type: z.literal("INTERNAL_ERROR"),
228
+ code: z.enum([
229
+ "COULD_NOT_FIND_EXECUTOR",
230
+ "COULD_NOT_FIND_TASK",
231
+ "CONFIGURED_INCORRECTLY",
232
+ "TASK_ALREADY_RUNNING",
233
+ "TASK_EXECUTION_FAILED",
234
+ "TASK_EXECUTION_ABORTED",
235
+ "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
236
+ "TASK_PROCESS_SIGKILL_TIMEOUT",
237
+ "TASK_RUN_CANCELLED",
238
+ "TASK_OUTPUT_ERROR",
239
+ "HANDLE_ERROR_ERROR",
240
+ "GRACEFUL_EXIT_TIMEOUT",
241
+ "TASK_RUN_HEARTBEAT_TIMEOUT"
242
+ ]),
243
+ message: z.string().optional(),
244
+ stackTrace: z.string().optional()
245
+ });
246
+ var TaskRunError = z.discriminatedUnion("type", [
247
+ TaskRunBuiltInError,
248
+ TaskRunCustomErrorObject,
249
+ TaskRunStringError,
250
+ TaskRunInternalError
251
+ ]);
252
+ var TaskRun = z.object({
253
+ id: z.string(),
254
+ payload: z.string(),
255
+ payloadType: z.string(),
256
+ context: z.any(),
257
+ tags: z.array(z.string()),
258
+ isTest: z.boolean().default(false),
259
+ createdAt: z.coerce.date(),
260
+ startedAt: z.coerce.date().default(() => /* @__PURE__ */ new Date()),
261
+ idempotencyKey: z.string().optional(),
262
+ maxAttempts: z.number().optional(),
263
+ durationMs: z.number().default(0),
264
+ costInCents: z.number().default(0),
265
+ baseCostInCents: z.number().default(0)
266
+ });
267
+ var TaskRunExecutionTask = z.object({
268
+ id: z.string(),
269
+ filePath: z.string(),
270
+ exportName: z.string()
271
+ });
272
+ var TaskRunExecutionAttempt = z.object({
273
+ id: z.string(),
274
+ number: z.number(),
275
+ startedAt: z.coerce.date(),
276
+ backgroundWorkerId: z.string(),
277
+ backgroundWorkerTaskId: z.string(),
278
+ status: z.string()
279
+ });
280
+ var TaskRunExecutionEnvironment = z.object({
281
+ id: z.string(),
282
+ slug: z.string(),
283
+ type: z.enum([
284
+ "PRODUCTION",
285
+ "STAGING",
286
+ "DEVELOPMENT",
287
+ "PREVIEW"
288
+ ])
289
+ });
290
+ var TaskRunExecutionOrganization = z.object({
291
+ id: z.string(),
292
+ slug: z.string(),
293
+ name: z.string()
294
+ });
295
+ var TaskRunExecutionProject = z.object({
296
+ id: z.string(),
297
+ ref: z.string(),
298
+ slug: z.string(),
299
+ name: z.string()
300
+ });
301
+ var TaskRunExecutionQueue = z.object({
302
+ id: z.string(),
303
+ name: z.string()
304
+ });
305
+ var TaskRunExecutionBatch = z.object({
306
+ id: z.string()
307
+ });
308
+ var TaskRunExecution = z.object({
309
+ task: TaskRunExecutionTask,
310
+ attempt: TaskRunExecutionAttempt,
311
+ run: TaskRun,
312
+ queue: TaskRunExecutionQueue,
313
+ environment: TaskRunExecutionEnvironment,
314
+ organization: TaskRunExecutionOrganization,
315
+ project: TaskRunExecutionProject,
316
+ batch: TaskRunExecutionBatch.optional(),
317
+ machine: MachinePreset.optional()
318
+ });
319
+ z.object({
320
+ task: TaskRunExecutionTask,
321
+ attempt: TaskRunExecutionAttempt.omit({
322
+ backgroundWorkerId: true,
323
+ backgroundWorkerTaskId: true
324
+ }),
325
+ run: TaskRun.omit({
326
+ payload: true,
327
+ payloadType: true
328
+ }),
329
+ queue: TaskRunExecutionQueue,
330
+ environment: TaskRunExecutionEnvironment,
331
+ organization: TaskRunExecutionOrganization,
332
+ project: TaskRunExecutionProject,
333
+ batch: TaskRunExecutionBatch.optional(),
334
+ machine: MachinePreset.optional()
335
+ });
336
+ var TaskRunExecutionRetry = z.object({
337
+ timestamp: z.number(),
338
+ delay: z.number(),
339
+ error: z.unknown().optional()
340
+ });
341
+ var TaskRunExecutionUsage = z.object({
342
+ durationMs: z.number()
343
+ });
344
+ var TaskRunFailedExecutionResult = z.object({
345
+ ok: z.literal(false),
346
+ id: z.string(),
347
+ error: TaskRunError,
348
+ retry: TaskRunExecutionRetry.optional(),
349
+ skippedRetrying: z.boolean().optional(),
350
+ usage: TaskRunExecutionUsage.optional()
351
+ });
352
+ var TaskRunSuccessfulExecutionResult = z.object({
353
+ ok: z.literal(true),
354
+ id: z.string(),
355
+ output: z.string().optional(),
356
+ outputType: z.string(),
357
+ usage: TaskRunExecutionUsage.optional()
358
+ });
359
+ var TaskRunExecutionResult = z.discriminatedUnion("ok", [
360
+ TaskRunSuccessfulExecutionResult,
361
+ TaskRunFailedExecutionResult
362
+ ]);
363
+ var BatchTaskRunExecutionResult = z.object({
364
+ id: z.string(),
365
+ items: TaskRunExecutionResult.array()
366
+ });
367
+
368
+ // src/v3/schemas/schemas.ts
369
+ z.enum([
370
+ "PRODUCTION",
371
+ "STAGING",
372
+ "DEVELOPMENT",
373
+ "PREVIEW"
374
+ ]);
375
+ z.object({
376
+ execution: TaskRunExecution,
377
+ traceContext: z.record(z.unknown()),
378
+ environment: z.record(z.string()).optional()
379
+ });
380
+ var ProdTaskRunExecution = TaskRunExecution.extend({
381
+ worker: z.object({
382
+ id: z.string(),
383
+ contentHash: z.string(),
384
+ version: z.string()
385
+ }),
386
+ machine: MachinePreset.default({
387
+ name: "small-1x",
388
+ cpu: 1,
389
+ memory: 1,
390
+ centsPerMs: 0
391
+ })
392
+ });
393
+ z.object({
394
+ execution: ProdTaskRunExecution,
395
+ traceContext: z.record(z.unknown()),
396
+ environment: z.record(z.string()).optional()
397
+ });
398
+ var FixedWindowRateLimit = z.object({
399
+ type: z.literal("fixed-window"),
400
+ limit: z.number(),
401
+ window: z.union([
402
+ z.object({
403
+ seconds: z.number()
404
+ }),
405
+ z.object({
406
+ minutes: z.number()
407
+ }),
408
+ z.object({
409
+ hours: z.number()
410
+ })
411
+ ])
412
+ });
413
+ var SlidingWindowRateLimit = z.object({
414
+ type: z.literal("sliding-window"),
415
+ limit: z.number(),
416
+ window: z.union([
417
+ z.object({
418
+ seconds: z.number()
419
+ }),
420
+ z.object({
421
+ minutes: z.number()
422
+ }),
423
+ z.object({
424
+ hours: z.number()
425
+ })
426
+ ])
427
+ });
428
+ var RateLimitOptions = z.discriminatedUnion("type", [
429
+ FixedWindowRateLimit,
430
+ SlidingWindowRateLimit
431
+ ]);
432
+ var RetryOptions = z.object({
433
+ /** The number of attempts before giving up */
434
+ maxAttempts: z.number().int().optional(),
435
+ /** The exponential factor to use when calculating the next retry time.
436
+ *
437
+ * Each subsequent retry will be calculated as `previousTimeout * factor`
438
+ */
439
+ factor: z.number().optional(),
440
+ /** The minimum time to wait before retrying */
441
+ minTimeoutInMs: z.number().int().optional(),
442
+ /** The maximum time to wait before retrying */
443
+ maxTimeoutInMs: z.number().int().optional(),
444
+ /** Randomize the timeout between retries.
445
+ *
446
+ * This can be useful to prevent the thundering herd problem where all retries happen at the same time.
447
+ */
448
+ randomize: z.boolean().optional()
449
+ });
450
+ var QueueOptions = z.object({
451
+ /** You can define a shared queue and then pass the name in to your task.
452
+ *
453
+ * @example
454
+ *
455
+ * ```ts
456
+ * const myQueue = queue({
457
+ name: "my-queue",
458
+ concurrencyLimit: 1,
459
+ });
460
+
461
+ export const task1 = task({
462
+ id: "task-1",
463
+ queue: {
464
+ name: "my-queue",
465
+ },
466
+ run: async (payload: { message: string }) => {
467
+ // ...
468
+ },
469
+ });
470
+
471
+ export const task2 = task({
472
+ id: "task-2",
473
+ queue: {
474
+ name: "my-queue",
475
+ },
476
+ run: async (payload: { message: string }) => {
477
+ // ...
478
+ },
479
+ });
480
+ * ```
481
+ */
482
+ name: z.string().optional(),
483
+ /** An optional property that specifies the maximum number of concurrent run executions.
484
+ *
485
+ * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
486
+ concurrencyLimit: z.number().int().min(0).max(1e3).optional(),
487
+ /** @deprecated This feature is coming soon */
488
+ rateLimit: RateLimitOptions.optional()
489
+ });
490
+ var ScheduleMetadata = z.object({
491
+ cron: z.string(),
492
+ timezone: z.string()
493
+ });
494
+ z.object({
495
+ id: z.string(),
496
+ packageVersion: z.string(),
497
+ queue: QueueOptions.optional(),
498
+ retry: RetryOptions.optional(),
499
+ machine: MachineConfig.optional(),
500
+ triggerSource: z.string().optional(),
501
+ schedule: ScheduleMetadata.optional()
502
+ });
503
+ z.object({
504
+ filePath: z.string(),
505
+ exportName: z.string()
506
+ });
507
+ z.object({
508
+ id: z.string(),
509
+ packageVersion: z.string(),
510
+ queue: QueueOptions.optional(),
511
+ retry: RetryOptions.optional(),
512
+ machine: MachineConfig.optional(),
513
+ triggerSource: z.string().optional(),
514
+ schedule: ScheduleMetadata.optional(),
515
+ filePath: z.string(),
516
+ exportName: z.string()
517
+ });
518
+ z.enum([
519
+ "index",
520
+ "create",
521
+ "restore"
522
+ ]);
523
+ z.enum([
524
+ "terminate"
525
+ ]);
526
+ var RegexSchema = z.custom((val) => {
527
+ try {
528
+ return typeof val.test === "function";
529
+ } catch {
530
+ return false;
531
+ }
532
+ });
533
+ z.object({
534
+ project: z.string(),
535
+ triggerDirectories: z.string().array().optional(),
536
+ triggerUrl: z.string().optional(),
537
+ projectDir: z.string().optional(),
538
+ tsconfigPath: z.string().optional(),
539
+ retries: z.object({
540
+ enabledInDev: z.boolean().default(true),
541
+ default: RetryOptions.optional()
542
+ }).optional(),
543
+ additionalPackages: z.string().array().optional(),
544
+ additionalFiles: z.string().array().optional(),
545
+ dependenciesToBundle: z.array(z.union([
546
+ z.string(),
547
+ RegexSchema
548
+ ])).optional(),
549
+ logLevel: z.string().optional(),
550
+ enableConsoleLogging: z.boolean().optional(),
551
+ postInstall: z.string().optional(),
552
+ extraCACerts: z.string().optional()
553
+ });
554
+ z.enum([
555
+ "WAIT_FOR_DURATION",
556
+ "WAIT_FOR_TASK",
557
+ "WAIT_FOR_BATCH"
558
+ ]);
559
+ z.object({
560
+ runId: z.string(),
561
+ attemptCount: z.number().optional(),
562
+ messageId: z.string(),
563
+ isTest: z.boolean(),
564
+ traceContext: z.record(z.unknown()),
565
+ environment: z.record(z.string()).optional()
566
+ });
567
+
568
+ // src/v3/schemas/resources.ts
569
+ var TaskResource = z.object({
570
+ id: z.string(),
571
+ filePath: z.string(),
572
+ exportName: z.string(),
573
+ queue: QueueOptions.optional(),
574
+ retry: RetryOptions.optional(),
575
+ machine: MachineConfig.optional(),
576
+ triggerSource: z.string().optional(),
577
+ schedule: ScheduleMetadata.optional()
578
+ });
579
+ var BackgroundWorkerMetadata = z.object({
580
+ packageVersion: z.string(),
581
+ contentHash: z.string(),
582
+ cliPackageVersion: z.string().optional(),
583
+ tasks: z.array(TaskResource)
584
+ });
585
+ z.object({
586
+ contentHash: z.string(),
587
+ imageTag: z.string()
588
+ });
589
+ var SerializedError = z.object({
590
+ message: z.string(),
591
+ name: z.string().optional(),
592
+ stackTrace: z.string().optional()
593
+ });
594
+
595
+ // src/v3/schemas/api.ts
596
+ z.object({
597
+ userId: z.string(),
598
+ email: z.string().email(),
599
+ dashboardUrl: z.string()
600
+ });
601
+ var GetProjectResponseBody = z.object({
602
+ id: z.string(),
603
+ externalRef: z.string(),
604
+ name: z.string(),
605
+ slug: z.string(),
606
+ createdAt: z.coerce.date(),
607
+ organization: z.object({
608
+ id: z.string(),
609
+ title: z.string(),
610
+ slug: z.string(),
611
+ createdAt: z.coerce.date()
612
+ })
613
+ });
614
+ z.array(GetProjectResponseBody);
615
+ z.object({
616
+ apiKey: z.string(),
617
+ name: z.string(),
618
+ apiUrl: z.string()
619
+ });
620
+ z.object({
621
+ localOnly: z.boolean(),
622
+ metadata: BackgroundWorkerMetadata,
623
+ supportsLazyAttempts: z.boolean().optional()
624
+ });
625
+ z.object({
626
+ id: z.string(),
627
+ version: z.string(),
628
+ contentHash: z.string()
629
+ });
630
+ var RunTag = z.string().max(64, "Tags must be less than 64 characters");
631
+ var RunTags = z.union([
632
+ RunTag,
633
+ RunTag.array().max(3, "You can only set a maximum of 3 tags on a run.")
634
+ ]);
635
+ var TriggerTaskRequestBody = z.object({
636
+ payload: z.any(),
637
+ context: z.any(),
638
+ options: z.object({
639
+ dependentAttempt: z.string().optional(),
640
+ dependentBatch: z.string().optional(),
641
+ lockToVersion: z.string().optional(),
642
+ queue: QueueOptions.optional(),
643
+ concurrencyKey: z.string().optional(),
644
+ idempotencyKey: z.string().optional(),
645
+ test: z.boolean().optional(),
646
+ payloadType: z.string().optional(),
647
+ delay: z.string().or(z.coerce.date()).optional(),
648
+ ttl: z.string().or(z.number().nonnegative().int()).optional(),
649
+ tags: RunTags.optional(),
650
+ maxAttempts: z.number().int().optional()
651
+ }).optional()
652
+ });
653
+ var TriggerTaskResponse = z.object({
654
+ id: z.string()
655
+ });
656
+ z.object({
657
+ items: TriggerTaskRequestBody.array(),
658
+ dependentAttempt: z.string().optional()
659
+ });
660
+ var BatchTriggerTaskResponse = z.object({
661
+ batchId: z.string(),
662
+ runs: z.string().array()
663
+ });
664
+ z.object({
665
+ id: z.string(),
666
+ items: z.array(z.object({
667
+ id: z.string(),
668
+ taskRunId: z.string(),
669
+ status: z.enum([
670
+ "PENDING",
671
+ "CANCELED",
672
+ "COMPLETED",
673
+ "FAILED"
674
+ ])
675
+ }))
676
+ });
677
+ z.object({
678
+ tags: RunTags
679
+ });
680
+ z.object({
681
+ delay: z.string().or(z.coerce.date())
682
+ });
683
+ z.object({
684
+ variables: z.record(z.string())
685
+ });
686
+ z.object({
687
+ imageReference: z.string(),
688
+ selfHosted: z.boolean().optional()
689
+ });
690
+ z.object({
691
+ id: z.string(),
692
+ contentHash: z.string()
693
+ });
694
+ var ExternalBuildData = z.object({
695
+ buildId: z.string(),
696
+ buildToken: z.string(),
697
+ projectId: z.string()
698
+ });
699
+ z.object({
700
+ id: z.string(),
701
+ contentHash: z.string(),
702
+ shortCode: z.string(),
703
+ version: z.string(),
704
+ imageTag: z.string(),
705
+ externalBuildData: ExternalBuildData.optional().nullable(),
706
+ registryHost: z.string().optional()
707
+ });
708
+ z.object({
709
+ contentHash: z.string(),
710
+ userId: z.string().optional()
711
+ });
712
+ var DeploymentErrorData = z.object({
713
+ name: z.string(),
714
+ message: z.string(),
715
+ stack: z.string().optional(),
716
+ stderr: z.string().optional()
717
+ });
718
+ z.object({
719
+ id: z.string(),
720
+ status: z.enum([
721
+ "PENDING",
722
+ "BUILDING",
723
+ "DEPLOYING",
724
+ "DEPLOYED",
725
+ "FAILED",
726
+ "CANCELED",
727
+ "TIMED_OUT"
728
+ ]),
729
+ contentHash: z.string(),
730
+ shortCode: z.string(),
731
+ version: z.string(),
732
+ imageReference: z.string().optional(),
733
+ errorData: DeploymentErrorData.optional().nullable(),
734
+ worker: z.object({
735
+ id: z.string(),
736
+ version: z.string(),
737
+ tasks: z.array(z.object({
738
+ id: z.string(),
739
+ slug: z.string(),
740
+ filePath: z.string(),
741
+ exportName: z.string()
742
+ }))
743
+ }).optional()
744
+ });
745
+ var CreateUploadPayloadUrlResponseBody = z.object({
746
+ presignedUrl: z.string()
747
+ });
748
+ var ReplayRunResponse = z.object({
749
+ id: z.string()
750
+ });
751
+ var CanceledRunResponse = z.object({
752
+ id: z.string()
753
+ });
754
+ var ScheduleType = z.union([
755
+ z.literal("DECLARATIVE"),
756
+ z.literal("IMPERATIVE")
757
+ ]);
758
+ z.object({
759
+ /** The schedule id associated with this run (you can have many schedules for the same task).
760
+ You can use this to remove the schedule, update it, etc */
761
+ scheduleId: z.string(),
762
+ /** The type of schedule – `"DECLARATIVE"` or `"IMPERATIVE"`.
763
+ *
764
+ * **DECLARATIVE** – defined inline on your `schedules.task` using the `cron` property. They can only be created, updated or deleted by modifying the `cron` property on your task.
765
+ *
766
+ * **IMPERATIVE** – created using the `schedules.create` functions or in the dashboard.
767
+ */
768
+ type: ScheduleType,
769
+ /** When the task was scheduled to run.
770
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task.
771
+ *
772
+ * This date is UTC. To output it as a string with a timezone you would do this:
773
+ * ```ts
774
+ * const formatted = payload.timestamp.toLocaleString("en-US", {
775
+ timeZone: payload.timezone,
776
+ });
777
+ ``` */
778
+ timestamp: z.date(),
779
+ /** When the task was last run (it has been).
780
+ This can be undefined if it's never been run. This date is UTC. */
781
+ lastTimestamp: z.date().optional(),
782
+ /** You can optionally provide an external id when creating the schedule.
783
+ Usually you would use a userId or some other unique identifier.
784
+ This defaults to undefined if you didn't provide one. */
785
+ externalId: z.string().optional(),
786
+ /** The IANA timezone the schedule is set to. The default is UTC.
787
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
788
+ */
789
+ timezone: z.string(),
790
+ /** The next 5 dates this task is scheduled to run */
791
+ upcoming: z.array(z.date())
792
+ });
793
+ var CreateScheduleOptions = z.object({
794
+ /** The id of the task you want to attach to. */
795
+ task: z.string(),
796
+ /** The schedule in CRON format.
797
+ *
798
+ * ```txt
799
+ * * * * * *
800
+ ┬ ┬ ┬ ┬ ┬
801
+ │ │ │ │ |
802
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
803
+ │ │ │ └───── month (1 - 12)
804
+ │ │ └────────── day of month (1 - 31, L)
805
+ │ └─────────────── hour (0 - 23)
806
+ └──────────────────── minute (0 - 59)
807
+ * ```
808
+
809
+ "L" means the last. In the "day of week" field, 1L means the last Monday of the month. In the day of month field, L means the last day of the month.
810
+
811
+ */
812
+ cron: z.string(),
813
+ /** You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
814
+ *
815
+ * This is required to prevent you from creating duplicate schedules. */
816
+ deduplicationKey: z.string(),
817
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
818
+ *
819
+ * This allows you to have per-user CRON tasks.
820
+ */
821
+ externalId: z.string().optional(),
822
+ /** Optionally, you can specify a timezone in the IANA format. If unset it will use UTC.
823
+ * If specified then the CRON will be evaluated in that timezone and will respect daylight savings.
824
+ *
825
+ * If you set the CRON to `0 0 * * *` and the timezone to `America/New_York` then the task will run at midnight in New York time, no matter whether it's daylight savings or not.
826
+ *
827
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
828
+ *
829
+ * @example "America/New_York", "Europe/London", "Asia/Tokyo", "Africa/Cairo"
830
+ *
831
+ */
832
+ timezone: z.string().optional()
833
+ });
834
+ CreateScheduleOptions.omit({
835
+ deduplicationKey: true
836
+ });
837
+ var ScheduleGenerator = z.object({
838
+ type: z.literal("CRON"),
839
+ expression: z.string(),
840
+ description: z.string()
841
+ });
842
+ var ScheduleObject = z.object({
843
+ id: z.string(),
844
+ type: ScheduleType,
845
+ task: z.string(),
846
+ active: z.boolean(),
847
+ deduplicationKey: z.string().nullish(),
848
+ externalId: z.string().nullish(),
849
+ generator: ScheduleGenerator,
850
+ timezone: z.string(),
851
+ nextRun: z.coerce.date().nullish(),
852
+ environments: z.array(z.object({
853
+ id: z.string(),
854
+ type: z.string(),
855
+ userName: z.string().nullish()
856
+ }))
857
+ });
858
+ var DeletedScheduleObject = z.object({
859
+ id: z.string()
860
+ });
861
+ z.object({
862
+ data: z.array(ScheduleObject),
863
+ pagination: z.object({
864
+ currentPage: z.number(),
865
+ totalPages: z.number(),
866
+ count: z.number()
867
+ })
868
+ });
869
+ z.object({
870
+ page: z.number().optional(),
871
+ perPage: z.number().optional()
872
+ });
873
+ z.object({
874
+ timezones: z.array(z.string())
875
+ });
876
+ var RunStatus = z.enum([
877
+ /// Task hasn't been deployed yet but is waiting to be executed
878
+ "WAITING_FOR_DEPLOY",
879
+ /// Task is waiting to be executed by a worker
880
+ "QUEUED",
881
+ /// Task is currently being executed by a worker
882
+ "EXECUTING",
883
+ /// Task has failed and is waiting to be retried
884
+ "REATTEMPTING",
885
+ /// Task has been paused by the system, and will be resumed by the system
886
+ "FROZEN",
887
+ /// Task has been completed successfully
888
+ "COMPLETED",
889
+ /// Task has been canceled by the user
890
+ "CANCELED",
891
+ /// Task has been completed with errors
892
+ "FAILED",
893
+ /// Task has crashed and won't be retried, most likely the worker ran out of resources, e.g. memory or storage
894
+ "CRASHED",
895
+ /// Task was interrupted during execution, mostly this happens in development environments
896
+ "INTERRUPTED",
897
+ /// Task has failed to complete, due to an error in the system
898
+ "SYSTEM_FAILURE",
899
+ /// Task has been scheduled to run at a specific time
900
+ "DELAYED",
901
+ /// Task has expired and won't be executed
902
+ "EXPIRED"
903
+ ]);
904
+ var AttemptStatus = z.enum([
905
+ "PENDING",
906
+ "EXECUTING",
907
+ "PAUSED",
908
+ "COMPLETED",
909
+ "FAILED",
910
+ "CANCELED"
911
+ ]);
912
+ var RunEnvironmentDetails = z.object({
913
+ id: z.string(),
914
+ name: z.string(),
915
+ user: z.string().optional()
916
+ });
917
+ var RunScheduleDetails = z.object({
918
+ id: z.string(),
919
+ externalId: z.string().optional(),
920
+ deduplicationKey: z.string().optional(),
921
+ generator: ScheduleGenerator
922
+ });
923
+ var CommonRunFields = {
924
+ id: z.string(),
925
+ status: RunStatus,
926
+ taskIdentifier: z.string(),
927
+ idempotencyKey: z.string().optional(),
928
+ version: z.string().optional(),
929
+ isQueued: z.boolean(),
930
+ isExecuting: z.boolean(),
931
+ isCompleted: z.boolean(),
932
+ isSuccess: z.boolean(),
933
+ isFailed: z.boolean(),
934
+ isCancelled: z.boolean(),
935
+ isTest: z.boolean(),
936
+ createdAt: z.coerce.date(),
937
+ updatedAt: z.coerce.date(),
938
+ startedAt: z.coerce.date().optional(),
939
+ finishedAt: z.coerce.date().optional(),
940
+ delayedUntil: z.coerce.date().optional(),
941
+ ttl: z.string().optional(),
942
+ expiredAt: z.coerce.date().optional(),
943
+ tags: z.string().array(),
944
+ costInCents: z.number(),
945
+ baseCostInCents: z.number(),
946
+ durationMs: z.number()
947
+ };
948
+ var RetrieveRunResponse = z.object({
949
+ ...CommonRunFields,
950
+ payload: z.any().optional(),
951
+ payloadPresignedUrl: z.string().optional(),
952
+ output: z.any().optional(),
953
+ outputPresignedUrl: z.string().optional(),
954
+ schedule: RunScheduleDetails.optional(),
955
+ attempts: z.array(z.object({
956
+ id: z.string(),
957
+ status: AttemptStatus,
958
+ createdAt: z.coerce.date(),
959
+ updatedAt: z.coerce.date(),
960
+ startedAt: z.coerce.date().optional(),
961
+ completedAt: z.coerce.date().optional(),
962
+ error: SerializedError.optional()
963
+ }).optional())
964
+ });
965
+ var ListRunResponseItem = z.object({
966
+ ...CommonRunFields,
967
+ env: RunEnvironmentDetails
968
+ });
969
+ z.object({
970
+ data: z.array(ListRunResponseItem),
971
+ pagination: z.object({
972
+ next: z.string().optional(),
973
+ previous: z.string().optional()
974
+ })
975
+ });
976
+ z.object({
977
+ name: z.string(),
978
+ value: z.string()
979
+ });
980
+ z.object({
981
+ value: z.string()
982
+ });
983
+ z.object({
984
+ variables: z.record(z.string()),
985
+ override: z.boolean().optional()
986
+ });
987
+ var EnvironmentVariableResponseBody = z.object({
988
+ success: z.boolean()
989
+ });
990
+ var EnvironmentVariableValue = z.object({
991
+ value: z.string()
992
+ });
993
+ var EnvironmentVariable = z.object({
994
+ name: z.string(),
995
+ value: z.string()
996
+ });
997
+ var EnvironmentVariables = z.array(EnvironmentVariable);
998
+
999
+ // src/v3/utils/platform.ts
1000
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
1001
+
1002
+ // src/v3/utils/globals.ts
1003
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
1004
+ var _global = _globalThis;
1005
+ function registerGlobal(type, instance, allowOverride = false) {
1006
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
1007
+ if (!allowOverride && api[type]) {
1008
+ return false;
1009
+ }
1010
+ api[type] = instance;
1011
+ return true;
1012
+ }
1013
+ __name(registerGlobal, "registerGlobal");
1014
+ function getGlobal(type) {
1015
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
1016
+ }
1017
+ __name(getGlobal, "getGlobal");
1018
+ function unregisterGlobal(type) {
1019
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
1020
+ if (api) {
1021
+ delete api[type];
1022
+ }
1023
+ }
1024
+ __name(unregisterGlobal, "unregisterGlobal");
1025
+
1026
+ // src/v3/taskContext/index.ts
1027
+ var API_NAME = "task-context";
1028
+ var _getTaskContext, getTaskContext_fn;
1029
+ var _TaskContextAPI = class _TaskContextAPI {
1030
+ constructor() {
1031
+ __privateAdd(this, _getTaskContext);
1032
+ }
1033
+ static getInstance() {
1034
+ if (!this._instance) {
1035
+ this._instance = new _TaskContextAPI();
1036
+ }
1037
+ return this._instance;
1038
+ }
1039
+ get isInsideTask() {
1040
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
1041
+ }
1042
+ get ctx() {
1043
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
1044
+ }
1045
+ get worker() {
1046
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
1047
+ }
1048
+ get attributes() {
1049
+ if (this.ctx) {
1050
+ return {
1051
+ ...this.contextAttributes,
1052
+ ...this.workerAttributes
1053
+ };
1054
+ }
1055
+ return {};
1056
+ }
1057
+ get workerAttributes() {
1058
+ if (this.worker) {
1059
+ return {
1060
+ [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
1061
+ [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
1062
+ };
1063
+ }
1064
+ return {};
1065
+ }
1066
+ get contextAttributes() {
1067
+ if (this.ctx) {
1068
+ return {
1069
+ [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
1070
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
1071
+ [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
1072
+ [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
1073
+ [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
1074
+ [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
1075
+ [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
1076
+ [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
1077
+ [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
1078
+ [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
1079
+ [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
1080
+ [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
1081
+ [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
1082
+ [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
1083
+ [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
1084
+ [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
1085
+ [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
1086
+ [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
1087
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey,
1088
+ [SemanticInternalAttributes.MACHINE_PRESET_NAME]: this.ctx.machine?.name,
1089
+ [SemanticInternalAttributes.MACHINE_PRESET_CPU]: this.ctx.machine?.cpu,
1090
+ [SemanticInternalAttributes.MACHINE_PRESET_MEMORY]: this.ctx.machine?.memory,
1091
+ [SemanticInternalAttributes.MACHINE_PRESET_CENTS_PER_MS]: this.ctx.machine?.centsPerMs
1092
+ };
1093
+ }
1094
+ return {};
1095
+ }
1096
+ disable() {
1097
+ unregisterGlobal(API_NAME);
1098
+ }
1099
+ setGlobalTaskContext(taskContext2) {
1100
+ return registerGlobal(API_NAME, taskContext2);
1101
+ }
1102
+ };
1103
+ _getTaskContext = new WeakSet();
1104
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
1105
+ return getGlobal(API_NAME);
1106
+ }, "#getTaskContext");
1107
+ __name(_TaskContextAPI, "TaskContextAPI");
1108
+ var TaskContextAPI = _TaskContextAPI;
1109
+
1110
+ // src/v3/task-context-api.ts
1111
+ var taskContext = TaskContextAPI.getInstance();
1112
+
1113
+ // src/v3/utils/retries.ts
1114
+ var defaultRetryOptions = {
1115
+ maxAttempts: 3,
1116
+ factor: 2,
1117
+ minTimeoutInMs: 1e3,
1118
+ maxTimeoutInMs: 6e4,
1119
+ randomize: true
1120
+ };
1121
+ function calculateNextRetryDelay(options, attempt) {
1122
+ const opts = {
1123
+ ...defaultRetryOptions,
1124
+ ...options
1125
+ };
1126
+ if (attempt >= opts.maxAttempts) {
1127
+ return;
1128
+ }
1129
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1130
+ const random = randomize ? Math.random() + 1 : 1;
1131
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1132
+ return Math.round(timeout);
1133
+ }
1134
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1135
+
1136
+ // src/v3/apiClient/errors.ts
1137
+ var _ApiError = class _ApiError extends Error {
1138
+ constructor(status, error, message, headers) {
1139
+ super(`${_ApiError.makeMessage(status, error, message)}`);
1140
+ this.name = "TriggerApiError";
1141
+ this.status = status;
1142
+ this.headers = headers;
1143
+ const data = error;
1144
+ this.error = data;
1145
+ this.code = data?.["code"];
1146
+ this.param = data?.["param"];
1147
+ this.type = data?.["type"];
1148
+ }
1149
+ static makeMessage(status, error, message) {
1150
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1151
+ if (status && msg) {
1152
+ return `${status} ${msg}`;
1153
+ }
1154
+ if (status) {
1155
+ return `${status} status code (no body)`;
1156
+ }
1157
+ if (msg) {
1158
+ return msg;
1159
+ }
1160
+ return "(no status code or body)";
1161
+ }
1162
+ static generate(status, errorResponse, message, headers) {
1163
+ if (!status) {
1164
+ return new ApiConnectionError({
1165
+ cause: castToError(errorResponse)
1166
+ });
1167
+ }
1168
+ const error = errorResponse?.["error"];
1169
+ if (status === 400) {
1170
+ return new BadRequestError(status, error, message, headers);
1171
+ }
1172
+ if (status === 401) {
1173
+ return new AuthenticationError(status, error, message, headers);
1174
+ }
1175
+ if (status === 403) {
1176
+ return new PermissionDeniedError(status, error, message, headers);
1177
+ }
1178
+ if (status === 404) {
1179
+ return new NotFoundError(status, error, message, headers);
1180
+ }
1181
+ if (status === 409) {
1182
+ return new ConflictError(status, error, message, headers);
1183
+ }
1184
+ if (status === 422) {
1185
+ return new UnprocessableEntityError(status, error, message, headers);
1186
+ }
1187
+ if (status === 429) {
1188
+ return new RateLimitError(status, error, message, headers);
1189
+ }
1190
+ if (status >= 500) {
1191
+ return new InternalServerError(status, error, message, headers);
1192
+ }
1193
+ return new _ApiError(status, error, message, headers);
1194
+ }
1195
+ };
1196
+ __name(_ApiError, "ApiError");
1197
+ var ApiError = _ApiError;
1198
+ var _ApiConnectionError = class _ApiConnectionError extends ApiError {
1199
+ constructor({ message, cause }) {
1200
+ super(void 0, void 0, message || "Connection error.", void 0);
1201
+ __publicField(this, "status");
1202
+ if (cause)
1203
+ this.cause = cause;
1204
+ }
1205
+ };
1206
+ __name(_ApiConnectionError, "ApiConnectionError");
1207
+ var ApiConnectionError = _ApiConnectionError;
1208
+ var _BadRequestError = class _BadRequestError extends ApiError {
1209
+ constructor() {
1210
+ super(...arguments);
1211
+ __publicField(this, "status", 400);
1212
+ }
1213
+ };
1214
+ __name(_BadRequestError, "BadRequestError");
1215
+ var BadRequestError = _BadRequestError;
1216
+ var _AuthenticationError = class _AuthenticationError extends ApiError {
1217
+ constructor() {
1218
+ super(...arguments);
1219
+ __publicField(this, "status", 401);
1220
+ }
1221
+ };
1222
+ __name(_AuthenticationError, "AuthenticationError");
1223
+ var AuthenticationError = _AuthenticationError;
1224
+ var _PermissionDeniedError = class _PermissionDeniedError extends ApiError {
1225
+ constructor() {
1226
+ super(...arguments);
1227
+ __publicField(this, "status", 403);
1228
+ }
1229
+ };
1230
+ __name(_PermissionDeniedError, "PermissionDeniedError");
1231
+ var PermissionDeniedError = _PermissionDeniedError;
1232
+ var _NotFoundError = class _NotFoundError extends ApiError {
1233
+ constructor() {
1234
+ super(...arguments);
1235
+ __publicField(this, "status", 404);
1236
+ }
1237
+ };
1238
+ __name(_NotFoundError, "NotFoundError");
1239
+ var NotFoundError = _NotFoundError;
1240
+ var _ConflictError = class _ConflictError extends ApiError {
1241
+ constructor() {
1242
+ super(...arguments);
1243
+ __publicField(this, "status", 409);
1244
+ }
1245
+ };
1246
+ __name(_ConflictError, "ConflictError");
1247
+ var ConflictError = _ConflictError;
1248
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends ApiError {
1249
+ constructor() {
1250
+ super(...arguments);
1251
+ __publicField(this, "status", 422);
1252
+ }
1253
+ };
1254
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
1255
+ var UnprocessableEntityError = _UnprocessableEntityError;
1256
+ var _RateLimitError = class _RateLimitError extends ApiError {
1257
+ constructor() {
1258
+ super(...arguments);
1259
+ __publicField(this, "status", 429);
1260
+ }
1261
+ get millisecondsUntilReset() {
1262
+ const resetAtUnixEpochMs = (this.headers ?? {})["x-ratelimit-reset"];
1263
+ if (typeof resetAtUnixEpochMs === "string") {
1264
+ const resetAtUnixEpoch = parseInt(resetAtUnixEpochMs, 10);
1265
+ if (isNaN(resetAtUnixEpoch)) {
1266
+ return;
1267
+ }
1268
+ return Math.max(resetAtUnixEpoch - Date.now() + Math.floor(Math.random() * 2e3), 0);
1269
+ }
1270
+ }
1271
+ };
1272
+ __name(_RateLimitError, "RateLimitError");
1273
+ var RateLimitError = _RateLimitError;
1274
+ var _InternalServerError = class _InternalServerError extends ApiError {
1275
+ };
1276
+ __name(_InternalServerError, "InternalServerError");
1277
+ var InternalServerError = _InternalServerError;
1278
+ function castToError(err) {
1279
+ if (err instanceof Error)
1280
+ return err;
1281
+ return new Error(err);
1282
+ }
1283
+ __name(castToError, "castToError");
1284
+
1285
+ // src/v3/utils/styleAttributes.ts
1286
+ function accessoryAttributes(accessory) {
1287
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
1288
+ }
1289
+ __name(accessoryAttributes, "accessoryAttributes");
1290
+
1291
+ // src/v3/apiClient/pagination.ts
1292
+ var _CursorPage = class _CursorPage {
1293
+ constructor(data, pagination, pageFetcher) {
1294
+ this.pageFetcher = pageFetcher;
1295
+ this.data = data;
1296
+ this.pagination = pagination;
1297
+ }
1298
+ getPaginatedItems() {
1299
+ return this.data ?? [];
1300
+ }
1301
+ hasNextPage() {
1302
+ return !!this.pagination.next;
1303
+ }
1304
+ hasPreviousPage() {
1305
+ return !!this.pagination.previous;
1306
+ }
1307
+ getNextPage() {
1308
+ if (!this.pagination.next) {
1309
+ throw new Error("No next page available");
1310
+ }
1311
+ return this.pageFetcher({
1312
+ after: this.pagination.next
1313
+ });
1314
+ }
1315
+ getPreviousPage() {
1316
+ if (!this.pagination.previous) {
1317
+ throw new Error("No previous page available");
1318
+ }
1319
+ return this.pageFetcher({
1320
+ before: this.pagination.previous
1321
+ });
1322
+ }
1323
+ async *iterPages() {
1324
+ let page = this;
1325
+ yield page;
1326
+ while (page.hasNextPage()) {
1327
+ page = await page.getNextPage();
1328
+ yield page;
1329
+ }
1330
+ }
1331
+ async *[Symbol.asyncIterator]() {
1332
+ for await (const page of this.iterPages()) {
1333
+ for (const item of page.getPaginatedItems()) {
1334
+ yield item;
1335
+ }
1336
+ }
1337
+ }
1338
+ };
1339
+ __name(_CursorPage, "CursorPage");
1340
+ var CursorPage = _CursorPage;
1341
+ var _OffsetLimitPage = class _OffsetLimitPage {
1342
+ constructor(data, pagination, pageFetcher) {
1343
+ this.pageFetcher = pageFetcher;
1344
+ this.data = data;
1345
+ this.pagination = pagination;
1346
+ }
1347
+ getPaginatedItems() {
1348
+ return this.data ?? [];
1349
+ }
1350
+ hasNextPage() {
1351
+ return this.pagination.currentPage < this.pagination.totalPages;
1352
+ }
1353
+ hasPreviousPage() {
1354
+ return this.pagination.currentPage > 1;
1355
+ }
1356
+ getNextPage() {
1357
+ if (!this.hasNextPage()) {
1358
+ throw new Error("No next page available");
1359
+ }
1360
+ return this.pageFetcher({
1361
+ page: this.pagination.currentPage + 1
1362
+ });
1363
+ }
1364
+ getPreviousPage() {
1365
+ if (!this.hasPreviousPage()) {
1366
+ throw new Error("No previous page available");
1367
+ }
1368
+ return this.pageFetcher({
1369
+ page: this.pagination.currentPage - 1
1370
+ });
1371
+ }
1372
+ async *iterPages() {
1373
+ let page = this;
1374
+ yield page;
1375
+ while (page.hasNextPage()) {
1376
+ page = await page.getNextPage();
1377
+ yield page;
1378
+ }
1379
+ }
1380
+ async *[Symbol.asyncIterator]() {
1381
+ for await (const page of this.iterPages()) {
1382
+ for (const item of page.getPaginatedItems()) {
1383
+ yield item;
1384
+ }
1385
+ }
1386
+ }
1387
+ };
1388
+ __name(_OffsetLimitPage, "OffsetLimitPage");
1389
+ var OffsetLimitPage = _OffsetLimitPage;
1390
+
1391
+ // src/v3/apiClient/core.ts
1392
+ var defaultRetryOptions2 = {
1393
+ maxAttempts: 3,
1394
+ factor: 2,
1395
+ minTimeoutInMs: 1e3,
1396
+ maxTimeoutInMs: 6e4,
1397
+ randomize: false
1398
+ };
1399
+ function zodfetch(schema, url, requestInit, options) {
1400
+ return new ApiPromise(_doZodFetch(schema, url, requestInit, options));
1401
+ }
1402
+ __name(zodfetch, "zodfetch");
1403
+ function zodfetchCursorPage(schema, url, params, requestInit, options) {
1404
+ const query = new URLSearchParams(params.query);
1405
+ if (params.limit) {
1406
+ query.set("page[size]", String(params.limit));
1407
+ }
1408
+ if (params.after) {
1409
+ query.set("page[after]", params.after);
1410
+ }
1411
+ if (params.before) {
1412
+ query.set("page[before]", params.before);
1413
+ }
1414
+ const cursorPageSchema = z.object({
1415
+ data: z.array(schema),
1416
+ pagination: z.object({
1417
+ next: z.string().optional(),
1418
+ previous: z.string().optional()
1419
+ })
1420
+ });
1421
+ const $url = new URL(url);
1422
+ $url.search = query.toString();
1423
+ const fetchResult = _doZodFetch(cursorPageSchema, $url.href, requestInit, options);
1424
+ return new CursorPagePromise(fetchResult, schema, url, params, requestInit, options);
1425
+ }
1426
+ __name(zodfetchCursorPage, "zodfetchCursorPage");
1427
+ function zodfetchOffsetLimitPage(schema, url, params, requestInit, options) {
1428
+ const query = new URLSearchParams(params.query);
1429
+ if (params.limit) {
1430
+ query.set("perPage", String(params.limit));
1431
+ }
1432
+ if (params.page) {
1433
+ query.set("page", String(params.page));
1434
+ }
1435
+ const offsetLimitPageSchema = z.object({
1436
+ data: z.array(schema),
1437
+ pagination: z.object({
1438
+ currentPage: z.coerce.number(),
1439
+ totalPages: z.coerce.number(),
1440
+ count: z.coerce.number()
1441
+ })
1442
+ });
1443
+ const $url = new URL(url);
1444
+ $url.search = query.toString();
1445
+ const fetchResult = _doZodFetch(offsetLimitPageSchema, $url.href, requestInit, options);
1446
+ return new OffsetLimitPagePromise(fetchResult, schema, url, params, requestInit, options);
1447
+ }
1448
+ __name(zodfetchOffsetLimitPage, "zodfetchOffsetLimitPage");
1449
+ async function traceZodFetch(params, callback) {
1450
+ if (!params.options?.tracer) {
1451
+ return callback();
1452
+ }
1453
+ const url = new URL(params.url);
1454
+ const method = params.requestInit?.method ?? "GET";
1455
+ const name = params.options.name ?? `${method} ${url.pathname}`;
1456
+ return await params.options.tracer.startActiveSpan(name, async (span) => {
1457
+ return await callback(span);
1458
+ }, {
1459
+ attributes: {
1460
+ [SemanticInternalAttributes.STYLE_ICON]: params.options?.icon ?? "api",
1461
+ ...params.options.attributes
1462
+ }
1463
+ });
1464
+ }
1465
+ __name(traceZodFetch, "traceZodFetch");
1466
+ async function _doZodFetch(schema, url, requestInit, options) {
1467
+ const $requestInit = await requestInit;
1468
+ return traceZodFetch({
1469
+ url,
1470
+ requestInit: $requestInit,
1471
+ options
1472
+ }, async (span) => {
1473
+ const result = await _doZodFetchWithRetries(schema, url, $requestInit, options);
1474
+ if (options?.onResponseBody && span) {
1475
+ options.onResponseBody(result.data, span);
1476
+ }
1477
+ return result;
1478
+ });
1479
+ }
1480
+ __name(_doZodFetch, "_doZodFetch");
1481
+ async function _doZodFetchWithRetries(schema, url, requestInit, options, attempt = 1) {
1482
+ try {
1483
+ const response = await fetch(url, requestInitWithCache(requestInit));
1484
+ const responseHeaders = createResponseHeaders(response.headers);
1485
+ if (!response.ok) {
1486
+ const retryResult = shouldRetry(response, attempt, options?.retry);
1487
+ if (retryResult.retry) {
1488
+ await waitForRetry(url, attempt + 1, retryResult.delay, options, requestInit, response);
1489
+ return await _doZodFetchWithRetries(schema, url, requestInit, options, attempt + 1);
1490
+ } else {
1491
+ const errText = await response.text().catch((e) => castToError2(e).message);
1492
+ const errJSON = safeJsonParse(errText);
1493
+ const errMessage = errJSON ? void 0 : errText;
1494
+ throw ApiError.generate(response.status, errJSON, errMessage, responseHeaders);
1495
+ }
1496
+ }
1497
+ const jsonBody = await response.json();
1498
+ const parsedResult = schema.safeParse(jsonBody);
1499
+ if (parsedResult.success) {
1500
+ return {
1501
+ data: parsedResult.data,
1502
+ response
1503
+ };
1504
+ }
1505
+ throw fromZodError(parsedResult.error);
1506
+ } catch (error) {
1507
+ if (error instanceof ApiError) {
1508
+ throw error;
1509
+ }
1510
+ if (options?.retry) {
1511
+ const retry = {
1512
+ ...defaultRetryOptions2,
1513
+ ...options.retry
1514
+ };
1515
+ const delay = calculateNextRetryDelay(retry, attempt);
1516
+ if (delay) {
1517
+ await waitForRetry(url, attempt + 1, delay, options, requestInit);
1518
+ return await _doZodFetchWithRetries(schema, url, requestInit, options, attempt + 1);
1519
+ }
1520
+ }
1521
+ throw new ApiConnectionError({
1522
+ cause: castToError2(error)
1523
+ });
1524
+ }
1525
+ }
1526
+ __name(_doZodFetchWithRetries, "_doZodFetchWithRetries");
1527
+ function castToError2(err) {
1528
+ if (err instanceof Error)
1529
+ return err;
1530
+ return new Error(err);
1531
+ }
1532
+ __name(castToError2, "castToError");
1533
+ function shouldRetry(response, attempt, retryOptions) {
1534
+ function shouldRetryForOptions() {
1535
+ const retry = {
1536
+ ...defaultRetryOptions2,
1537
+ ...retryOptions
1538
+ };
1539
+ const delay = calculateNextRetryDelay(retry, attempt);
1540
+ if (delay) {
1541
+ return {
1542
+ retry: true,
1543
+ delay
1544
+ };
1545
+ } else {
1546
+ return {
1547
+ retry: false
1548
+ };
1549
+ }
1550
+ }
1551
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
1552
+ const shouldRetryHeader = response.headers.get("x-should-retry");
1553
+ if (shouldRetryHeader === "true")
1554
+ return shouldRetryForOptions();
1555
+ if (shouldRetryHeader === "false")
1556
+ return {
1557
+ retry: false
1558
+ };
1559
+ if (response.status === 408)
1560
+ return shouldRetryForOptions();
1561
+ if (response.status === 409)
1562
+ return shouldRetryForOptions();
1563
+ if (response.status === 429) {
1564
+ if (attempt >= (typeof retryOptions?.maxAttempts === "number" ? retryOptions?.maxAttempts : 3)) {
1565
+ return {
1566
+ retry: false
1567
+ };
1568
+ }
1569
+ const resetAtUnixEpochMs = response.headers.get("x-ratelimit-reset");
1570
+ if (resetAtUnixEpochMs) {
1571
+ const resetAtUnixEpoch = parseInt(resetAtUnixEpochMs, 10);
1572
+ const delay = resetAtUnixEpoch - Date.now() + Math.floor(Math.random() * 1e3);
1573
+ if (delay > 0) {
1574
+ return {
1575
+ retry: true,
1576
+ delay
1577
+ };
1578
+ }
1579
+ }
1580
+ return shouldRetryForOptions();
1581
+ }
1582
+ if (response.status >= 500)
1583
+ return shouldRetryForOptions();
1584
+ return {
1585
+ retry: false
1586
+ };
1587
+ }
1588
+ __name(shouldRetry, "shouldRetry");
1589
+ function safeJsonParse(text) {
1590
+ try {
1591
+ return JSON.parse(text);
1592
+ } catch (e) {
1593
+ return void 0;
1594
+ }
1595
+ }
1596
+ __name(safeJsonParse, "safeJsonParse");
1597
+ function createResponseHeaders(headers) {
1598
+ return new Proxy(Object.fromEntries(
1599
+ // @ts-ignore
1600
+ headers.entries()
1601
+ ), {
1602
+ get(target, name) {
1603
+ const key = name.toString();
1604
+ return target[key.toLowerCase()] || target[key];
1605
+ }
1606
+ });
1607
+ }
1608
+ __name(createResponseHeaders, "createResponseHeaders");
1609
+ function requestInitWithCache(requestInit) {
1610
+ try {
1611
+ const withCache = {
1612
+ ...requestInit,
1613
+ cache: "no-cache"
1614
+ };
1615
+ const _ = new Request("http://localhost", withCache);
1616
+ return withCache;
1617
+ } catch (error) {
1618
+ return requestInit ?? {};
1619
+ }
1620
+ }
1621
+ __name(requestInitWithCache, "requestInitWithCache");
1622
+ var _ApiPromise = class _ApiPromise extends Promise {
1623
+ constructor(responsePromise) {
1624
+ super((resolve) => {
1625
+ resolve(null);
1626
+ });
1627
+ this.responsePromise = responsePromise;
1628
+ }
1629
+ /**
1630
+ * Gets the raw `Response` instance instead of parsing the response
1631
+ * data.
1632
+ *
1633
+ * If you want to parse the response body but still get the `Response`
1634
+ * instance, you can use {@link withResponse()}.
1635
+ */
1636
+ asResponse() {
1637
+ return this.responsePromise.then((p) => p.response);
1638
+ }
1639
+ /**
1640
+ * Gets the parsed response data and the raw `Response` instance.
1641
+ *
1642
+ * If you just want to get the raw `Response` instance without parsing it,
1643
+ * you can use {@link asResponse()}.
1644
+ */
1645
+ async withResponse() {
1646
+ const [data, response] = await Promise.all([
1647
+ this.parse(),
1648
+ this.asResponse()
1649
+ ]);
1650
+ return {
1651
+ data,
1652
+ response
1653
+ };
1654
+ }
1655
+ parse() {
1656
+ return this.responsePromise.then((result) => result.data);
1657
+ }
1658
+ then(onfulfilled, onrejected) {
1659
+ return this.parse().then(onfulfilled, onrejected);
1660
+ }
1661
+ catch(onrejected) {
1662
+ return this.parse().catch(onrejected);
1663
+ }
1664
+ finally(onfinally) {
1665
+ return this.parse().finally(onfinally);
1666
+ }
1667
+ };
1668
+ __name(_ApiPromise, "ApiPromise");
1669
+ var ApiPromise = _ApiPromise;
1670
+ var _fetchPage, fetchPage_fn;
1671
+ var _CursorPagePromise = class _CursorPagePromise extends ApiPromise {
1672
+ constructor(result, schema, url, params, requestInit, options) {
1673
+ super(result.then((result2) => ({
1674
+ data: new CursorPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage, fetchPage_fn).bind(this)),
1675
+ response: result2.response
1676
+ })));
1677
+ __privateAdd(this, _fetchPage);
1678
+ this.schema = schema;
1679
+ this.url = url;
1680
+ this.params = params;
1681
+ this.requestInit = requestInit;
1682
+ this.options = options;
1683
+ }
1684
+ /**
1685
+ * Allow auto-paginating iteration on an unawaited list call, eg:
1686
+ *
1687
+ * for await (const item of client.items.list()) {
1688
+ * console.log(item)
1689
+ * }
1690
+ */
1691
+ async *[Symbol.asyncIterator]() {
1692
+ const page = await this;
1693
+ for await (const item of page) {
1694
+ yield item;
1695
+ }
1696
+ }
1697
+ };
1698
+ _fetchPage = new WeakSet();
1699
+ fetchPage_fn = /* @__PURE__ */ __name(function(params) {
1700
+ return zodfetchCursorPage(this.schema, this.url, {
1701
+ ...this.params,
1702
+ ...params
1703
+ }, this.requestInit, this.options);
1704
+ }, "#fetchPage");
1705
+ __name(_CursorPagePromise, "CursorPagePromise");
1706
+ var CursorPagePromise = _CursorPagePromise;
1707
+ var _fetchPage2, fetchPage_fn2;
1708
+ var _OffsetLimitPagePromise = class _OffsetLimitPagePromise extends ApiPromise {
1709
+ constructor(result, schema, url, params, requestInit, options) {
1710
+ super(result.then((result2) => ({
1711
+ data: new OffsetLimitPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage2, fetchPage_fn2).bind(this)),
1712
+ response: result2.response
1713
+ })));
1714
+ __privateAdd(this, _fetchPage2);
1715
+ this.schema = schema;
1716
+ this.url = url;
1717
+ this.params = params;
1718
+ this.requestInit = requestInit;
1719
+ this.options = options;
1720
+ }
1721
+ /**
1722
+ * Allow auto-paginating iteration on an unawaited list call, eg:
1723
+ *
1724
+ * for await (const item of client.items.list()) {
1725
+ * console.log(item)
1726
+ * }
1727
+ */
1728
+ async *[Symbol.asyncIterator]() {
1729
+ const page = await this;
1730
+ for await (const item of page) {
1731
+ yield item;
1732
+ }
1733
+ }
1734
+ };
1735
+ _fetchPage2 = new WeakSet();
1736
+ fetchPage_fn2 = /* @__PURE__ */ __name(function(params1) {
1737
+ return zodfetchOffsetLimitPage(this.schema, this.url, {
1738
+ ...this.params,
1739
+ ...params1
1740
+ }, this.requestInit, this.options);
1741
+ }, "#fetchPage");
1742
+ __name(_OffsetLimitPagePromise, "OffsetLimitPagePromise");
1743
+ var OffsetLimitPagePromise = _OffsetLimitPagePromise;
1744
+ async function waitForRetry(url, attempt, delay, options, requestInit, response) {
1745
+ if (options?.tracer) {
1746
+ const method = requestInit?.method ?? "GET";
1747
+ return options.tracer.startActiveSpan(response ? `wait after ${response.status}` : `wait after error`, async (span) => {
1748
+ await new Promise((resolve) => setTimeout(resolve, delay));
1749
+ }, {
1750
+ attributes: {
1751
+ [SemanticInternalAttributes.STYLE_ICON]: "wait",
1752
+ ...accessoryAttributes({
1753
+ items: [
1754
+ {
1755
+ text: `retrying ${options?.name ?? method.toUpperCase()} in ${delay}ms`,
1756
+ variant: "normal"
1757
+ }
1758
+ ],
1759
+ style: "codepath"
1760
+ })
1761
+ }
1762
+ });
1763
+ }
1764
+ await new Promise((resolve) => setTimeout(resolve, delay));
1765
+ }
1766
+ __name(waitForRetry, "waitForRetry");
1767
+
1768
+ // src/v3/apiClient/index.ts
1769
+ var DEFAULT_ZOD_FETCH_OPTIONS = {
1770
+ retry: {
1771
+ maxAttempts: 3,
1772
+ minTimeoutInMs: 1e3,
1773
+ maxTimeoutInMs: 3e4,
1774
+ factor: 2,
1775
+ randomize: false
1776
+ }
1777
+ };
1778
+ var _getHeaders, getHeaders_fn;
1779
+ var _ApiClient = class _ApiClient {
1780
+ constructor(baseUrl, accessToken, requestOptions = {}) {
1781
+ __privateAdd(this, _getHeaders);
1782
+ this.accessToken = accessToken;
1783
+ this.baseUrl = baseUrl.replace(/\/$/, "");
1784
+ this.defaultRequestOptions = mergeRequestOptions(DEFAULT_ZOD_FETCH_OPTIONS, requestOptions);
1785
+ }
1786
+ async getRunResult(runId, requestOptions) {
1787
+ try {
1788
+ return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
1789
+ method: "GET",
1790
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1791
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1792
+ } catch (error) {
1793
+ if (error instanceof ApiError) {
1794
+ if (error.status === 404) {
1795
+ return void 0;
1796
+ }
1797
+ }
1798
+ throw error;
1799
+ }
1800
+ }
1801
+ async getBatchResults(batchId, requestOptions) {
1802
+ return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
1803
+ method: "GET",
1804
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1805
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1806
+ }
1807
+ triggerTask(taskId, body, options, requestOptions) {
1808
+ const encodedTaskId = encodeURIComponent(taskId);
1809
+ return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/trigger`, {
1810
+ method: "POST",
1811
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1812
+ body: JSON.stringify(body)
1813
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1814
+ }
1815
+ batchTriggerTask(taskId, body, options, requestOptions) {
1816
+ const encodedTaskId = encodeURIComponent(taskId);
1817
+ return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/batch`, {
1818
+ method: "POST",
1819
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1820
+ body: JSON.stringify(body)
1821
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1822
+ }
1823
+ createUploadPayloadUrl(filename, requestOptions) {
1824
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1825
+ method: "PUT",
1826
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1827
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1828
+ }
1829
+ getPayloadUrl(filename, requestOptions) {
1830
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1831
+ method: "GET",
1832
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1833
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1834
+ }
1835
+ retrieveRun(runId, requestOptions) {
1836
+ return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v3/runs/${runId}`, {
1837
+ method: "GET",
1838
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1839
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1840
+ }
1841
+ listRuns(query, requestOptions) {
1842
+ const searchParams = createSearchQueryForListRuns(query);
1843
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/runs`, {
1844
+ query: searchParams,
1845
+ limit: query?.limit,
1846
+ after: query?.after,
1847
+ before: query?.before
1848
+ }, {
1849
+ method: "GET",
1850
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1851
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1852
+ }
1853
+ listProjectRuns(projectRef, query, requestOptions) {
1854
+ const searchParams = createSearchQueryForListRuns(query);
1855
+ if (query?.env) {
1856
+ searchParams.append("filter[env]", Array.isArray(query.env) ? query.env.join(",") : query.env);
1857
+ }
1858
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/projects/${projectRef}/runs`, {
1859
+ query: searchParams,
1860
+ limit: query?.limit,
1861
+ after: query?.after,
1862
+ before: query?.before
1863
+ }, {
1864
+ method: "GET",
1865
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1866
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1867
+ }
1868
+ replayRun(runId, requestOptions) {
1869
+ return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
1870
+ method: "POST",
1871
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1872
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1873
+ }
1874
+ cancelRun(runId, requestOptions) {
1875
+ return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
1876
+ method: "POST",
1877
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1878
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1879
+ }
1880
+ rescheduleRun(runId, body, requestOptions) {
1881
+ return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/reschedule`, {
1882
+ method: "POST",
1883
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1884
+ body: JSON.stringify(body)
1885
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1886
+ }
1887
+ addTags(runId, body, requestOptions) {
1888
+ return zodfetch(z.object({
1889
+ message: z.string()
1890
+ }), `${this.baseUrl}/api/v1/runs/${runId}/tags`, {
1891
+ method: "POST",
1892
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1893
+ body: JSON.stringify(body)
1894
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1895
+ }
1896
+ createSchedule(options, requestOptions) {
1897
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
1898
+ method: "POST",
1899
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1900
+ body: JSON.stringify(options)
1901
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1902
+ }
1903
+ listSchedules(options, requestOptions) {
1904
+ const searchParams = new URLSearchParams();
1905
+ if (options?.page) {
1906
+ searchParams.append("page", options.page.toString());
1907
+ }
1908
+ if (options?.perPage) {
1909
+ searchParams.append("perPage", options.perPage.toString());
1910
+ }
1911
+ return zodfetchOffsetLimitPage(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
1912
+ page: options?.page,
1913
+ limit: options?.perPage
1914
+ }, {
1915
+ method: "GET",
1916
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1917
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1918
+ }
1919
+ retrieveSchedule(scheduleId, requestOptions) {
1920
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
1921
+ method: "GET",
1922
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1923
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1924
+ }
1925
+ updateSchedule(scheduleId, options, requestOptions) {
1926
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
1927
+ method: "PUT",
1928
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1929
+ body: JSON.stringify(options)
1930
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1931
+ }
1932
+ deactivateSchedule(scheduleId, requestOptions) {
1933
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
1934
+ method: "POST",
1935
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1936
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1937
+ }
1938
+ activateSchedule(scheduleId, requestOptions) {
1939
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
1940
+ method: "POST",
1941
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1942
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1943
+ }
1944
+ deleteSchedule(scheduleId, requestOptions) {
1945
+ return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
1946
+ method: "DELETE",
1947
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1948
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1949
+ }
1950
+ listEnvVars(projectRef, slug, requestOptions) {
1951
+ return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
1952
+ method: "GET",
1953
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1954
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1955
+ }
1956
+ importEnvVars(projectRef, slug, body, requestOptions) {
1957
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
1958
+ method: "POST",
1959
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1960
+ body: JSON.stringify(body)
1961
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1962
+ }
1963
+ retrieveEnvVar(projectRef, slug, key, requestOptions) {
1964
+ return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
1965
+ method: "GET",
1966
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1967
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1968
+ }
1969
+ createEnvVar(projectRef, slug, body, requestOptions) {
1970
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
1971
+ method: "POST",
1972
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1973
+ body: JSON.stringify(body)
1974
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1975
+ }
1976
+ updateEnvVar(projectRef, slug, key, body, requestOptions) {
1977
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
1978
+ method: "PUT",
1979
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1980
+ body: JSON.stringify(body)
1981
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1982
+ }
1983
+ deleteEnvVar(projectRef, slug, key, requestOptions) {
1984
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
1985
+ method: "DELETE",
1986
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1987
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1988
+ }
1989
+ };
1990
+ _getHeaders = new WeakSet();
1991
+ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
1992
+ const headers = {
1993
+ "Content-Type": "application/json",
1994
+ Authorization: `Bearer ${this.accessToken}`,
1995
+ "trigger-version": version
1996
+ };
1997
+ if (taskContext.isInsideTask) {
1998
+ headers["x-trigger-worker"] = "true";
1999
+ propagation.inject(context.active(), headers);
2000
+ if (spanParentAsLink) {
2001
+ headers["x-trigger-span-parent-as-link"] = "1";
2002
+ }
2003
+ }
2004
+ return headers;
2005
+ }, "#getHeaders");
2006
+ __name(_ApiClient, "ApiClient");
2007
+ var ApiClient = _ApiClient;
2008
+ function createSearchQueryForListRuns(query) {
2009
+ const searchParams = new URLSearchParams();
2010
+ if (query) {
2011
+ if (query.status) {
2012
+ searchParams.append("filter[status]", Array.isArray(query.status) ? query.status.join(",") : query.status);
2013
+ }
2014
+ if (query.taskIdentifier) {
2015
+ searchParams.append("filter[taskIdentifier]", Array.isArray(query.taskIdentifier) ? query.taskIdentifier.join(",") : query.taskIdentifier);
2016
+ }
2017
+ if (query.version) {
2018
+ searchParams.append("filter[version]", Array.isArray(query.version) ? query.version.join(",") : query.version);
2019
+ }
2020
+ if (query.bulkAction) {
2021
+ searchParams.append("filter[bulkAction]", query.bulkAction);
2022
+ }
2023
+ if (query.tag) {
2024
+ searchParams.append("filter[tag]", Array.isArray(query.tag) ? query.tag.join(",") : query.tag);
2025
+ }
2026
+ if (query.schedule) {
2027
+ searchParams.append("filter[schedule]", query.schedule);
2028
+ }
2029
+ if (typeof query.isTest === "boolean") {
2030
+ searchParams.append("filter[isTest]", String(query.isTest));
2031
+ }
2032
+ if (query.from) {
2033
+ searchParams.append("filter[createdAt][from]", query.from instanceof Date ? query.from.getTime().toString() : query.from.toString());
2034
+ }
2035
+ if (query.to) {
2036
+ searchParams.append("filter[createdAt][to]", query.to instanceof Date ? query.to.getTime().toString() : query.to.toString());
2037
+ }
2038
+ if (query.period) {
2039
+ searchParams.append("filter[createdAt][period]", query.period);
2040
+ }
2041
+ }
2042
+ return searchParams;
2043
+ }
2044
+ __name(createSearchQueryForListRuns, "createSearchQueryForListRuns");
2045
+ function mergeRequestOptions(defaultOptions, options) {
2046
+ if (!options) {
2047
+ return defaultOptions;
2048
+ }
2049
+ return {
2050
+ ...defaultOptions,
2051
+ ...options,
2052
+ retry: {
2053
+ ...defaultOptions.retry,
2054
+ ...options.retry
2055
+ }
2056
+ };
2057
+ }
2058
+ __name(mergeRequestOptions, "mergeRequestOptions");
2059
+
2060
+ // src/v3/utils/getEnv.ts
2061
+ function getEnvVar(name) {
2062
+ if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
2063
+ return process.env[name];
2064
+ }
2065
+ }
2066
+ __name(getEnvVar, "getEnvVar");
2067
+
2068
+ // src/v3/apiClientManager/index.ts
2069
+ var API_NAME2 = "api-client";
2070
+ var _getConfig, getConfig_fn;
2071
+ var _APIClientManagerAPI = class _APIClientManagerAPI {
2072
+ constructor() {
2073
+ __privateAdd(this, _getConfig);
2074
+ }
2075
+ static getInstance() {
2076
+ if (!this._instance) {
2077
+ this._instance = new _APIClientManagerAPI();
2078
+ }
2079
+ return this._instance;
2080
+ }
2081
+ disable() {
2082
+ unregisterGlobal(API_NAME2);
2083
+ }
2084
+ setGlobalAPIClientConfiguration(config) {
2085
+ return registerGlobal(API_NAME2, config);
2086
+ }
2087
+ get baseURL() {
2088
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2089
+ return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
2090
+ }
2091
+ get accessToken() {
2092
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2093
+ return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY") ?? getEnvVar("TRIGGER_ACCESS_TOKEN");
2094
+ }
2095
+ get client() {
2096
+ if (!this.baseURL || !this.accessToken) {
2097
+ return void 0;
2098
+ }
2099
+ return new ApiClient(this.baseURL, this.accessToken);
2100
+ }
2101
+ };
2102
+ _getConfig = new WeakSet();
2103
+ getConfig_fn = /* @__PURE__ */ __name(function() {
2104
+ return getGlobal(API_NAME2);
2105
+ }, "#getConfig");
2106
+ __name(_APIClientManagerAPI, "APIClientManagerAPI");
2107
+ var APIClientManagerAPI = _APIClientManagerAPI;
2108
+
2109
+ // src/v3/apiClientManager-api.ts
2110
+ var apiClientManager = APIClientManagerAPI.getInstance();
2111
+
2112
+ // src/v3/utils/ioSerialization.ts
2113
+ async function parsePacket(value) {
2114
+ if (!value.data) {
2115
+ return void 0;
2116
+ }
2117
+ switch (value.dataType) {
2118
+ case "application/json":
2119
+ return JSON.parse(value.data);
2120
+ case "application/super+json":
2121
+ const { parse } = await loadSuperJSON();
2122
+ return parse(value.data);
2123
+ case "text/plain":
2124
+ return value.data;
2125
+ case "application/store":
2126
+ throw new Error(`Cannot parse an application/store packet (${value.data}). Needs to be imported first.`);
2127
+ default:
2128
+ return value.data;
2129
+ }
2130
+ }
2131
+ __name(parsePacket, "parsePacket");
2132
+ async function stringifyIO(value) {
2133
+ if (value === void 0) {
2134
+ return {
2135
+ dataType: "application/json"
2136
+ };
2137
+ }
2138
+ if (typeof value === "string") {
2139
+ return {
2140
+ data: value,
2141
+ dataType: "text/plain"
2142
+ };
2143
+ }
2144
+ try {
2145
+ const { stringify } = await loadSuperJSON();
2146
+ const data = stringify(value);
2147
+ return {
2148
+ data,
2149
+ dataType: "application/super+json"
2150
+ };
2151
+ } catch {
2152
+ return {
2153
+ data: value,
2154
+ dataType: "application/json"
2155
+ };
2156
+ }
2157
+ }
2158
+ __name(stringifyIO, "stringifyIO");
2159
+ async function conditionallyExportPacket(packet, pathPrefix, tracer) {
2160
+ if (apiClientManager.client) {
2161
+ const { needsOffloading, size } = packetRequiresOffloading(packet);
2162
+ if (needsOffloading) {
2163
+ if (!tracer) {
2164
+ return await exportPacket(packet, pathPrefix);
2165
+ } else {
2166
+ const result = await tracer.startActiveSpan("store.uploadOutput", async (span) => {
2167
+ return await exportPacket(packet, pathPrefix);
2168
+ }, {
2169
+ attributes: {
2170
+ byteLength: size,
2171
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-upload"
2172
+ }
2173
+ });
2174
+ return result ?? packet;
2175
+ }
2176
+ }
2177
+ }
2178
+ return packet;
2179
+ }
2180
+ __name(conditionallyExportPacket, "conditionallyExportPacket");
2181
+ function packetRequiresOffloading(packet, lengthLimit) {
2182
+ if (!packet.data) {
2183
+ return {
2184
+ needsOffloading: false,
2185
+ size: 0
2186
+ };
2187
+ }
2188
+ const byteSize = Buffer.byteLength(packet.data, "utf8");
2189
+ return {
2190
+ needsOffloading: byteSize >= (lengthLimit ?? OFFLOAD_IO_PACKET_LENGTH_LIMIT),
2191
+ size: byteSize
2192
+ };
2193
+ }
2194
+ __name(packetRequiresOffloading, "packetRequiresOffloading");
2195
+ async function exportPacket(packet, pathPrefix) {
2196
+ const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
2197
+ const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
2198
+ const uploadResponse = await fetch(presignedResponse.presignedUrl, {
2199
+ method: "PUT",
2200
+ headers: {
2201
+ "Content-Type": packet.dataType
2202
+ },
2203
+ body: packet.data
2204
+ });
2205
+ if (!uploadResponse.ok) {
2206
+ throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
2207
+ }
2208
+ return {
2209
+ data: filename,
2210
+ dataType: "application/store"
2211
+ };
2212
+ }
2213
+ __name(exportPacket, "exportPacket");
2214
+ async function conditionallyImportPacket(packet, tracer) {
2215
+ if (packet.dataType !== "application/store") {
2216
+ return packet;
2217
+ }
2218
+ if (!tracer) {
2219
+ return await importPacket(packet);
2220
+ } else {
2221
+ const result = await tracer.startActiveSpan("store.downloadPayload", async (span) => {
2222
+ return await importPacket(packet, span);
2223
+ }, {
2224
+ attributes: {
2225
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
2226
+ }
2227
+ });
2228
+ return result ?? packet;
2229
+ }
2230
+ }
2231
+ __name(conditionallyImportPacket, "conditionallyImportPacket");
2232
+ async function importPacket(packet, span) {
2233
+ if (!packet.data) {
2234
+ return packet;
2235
+ }
2236
+ if (!apiClientManager.client) {
2237
+ return packet;
2238
+ }
2239
+ const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
2240
+ const response = await fetch(presignedResponse.presignedUrl);
2241
+ if (!response.ok) {
2242
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
2243
+ }
2244
+ const data = await response.text();
2245
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
2246
+ return {
2247
+ data,
2248
+ dataType: response.headers.get("content-type") ?? "application/json"
2249
+ };
2250
+ }
2251
+ __name(importPacket, "importPacket");
2252
+ async function createPacketAttributes(packet, dataKey, dataTypeKey) {
2253
+ if (!packet.data) {
2254
+ return;
2255
+ }
2256
+ switch (packet.dataType) {
2257
+ case "application/json":
2258
+ return {
2259
+ ...flattenAttributes(packet, dataKey),
2260
+ [dataTypeKey]: packet.dataType
2261
+ };
2262
+ case "application/super+json":
2263
+ const { parse } = await loadSuperJSON();
2264
+ if (typeof packet.data === "undefined" || packet.data === null) {
2265
+ return;
2266
+ }
2267
+ try {
2268
+ const parsed = parse(packet.data);
2269
+ const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
2270
+ const result = {
2271
+ ...flattenAttributes(jsonified, dataKey),
2272
+ [dataTypeKey]: "application/json"
2273
+ };
2274
+ return result;
2275
+ } catch (e) {
2276
+ return;
2277
+ }
2278
+ case "application/store":
2279
+ return {
2280
+ [dataKey]: packet.data,
2281
+ [dataTypeKey]: packet.dataType
2282
+ };
2283
+ case "text/plain":
2284
+ return {
2285
+ [dataKey]: packet.data,
2286
+ [dataTypeKey]: packet.dataType
2287
+ };
2288
+ default:
2289
+ return;
2290
+ }
2291
+ }
2292
+ __name(createPacketAttributes, "createPacketAttributes");
2293
+ async function createPacketAttributesAsJson(data, dataType) {
2294
+ if (typeof data === "string" || typeof data === "number" || typeof data === "boolean" || data === null || data === void 0) {
2295
+ return data;
2296
+ }
2297
+ switch (dataType) {
2298
+ case "application/json":
2299
+ return imposeAttributeLimits(flattenAttributes(data, void 0));
2300
+ case "application/super+json":
2301
+ const { deserialize } = await loadSuperJSON();
2302
+ const deserialized = deserialize(data);
2303
+ const jsonify = safeJsonParse2(JSON.stringify(deserialized, safeReplacer));
2304
+ return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
2305
+ case "application/store":
2306
+ return data;
2307
+ default:
2308
+ return {};
2309
+ }
2310
+ }
2311
+ __name(createPacketAttributesAsJson, "createPacketAttributesAsJson");
2312
+ async function prettyPrintPacket(rawData, dataType) {
2313
+ if (rawData === void 0) {
2314
+ return "";
2315
+ }
2316
+ if (dataType === "application/super+json") {
2317
+ if (typeof rawData === "string") {
2318
+ rawData = safeJsonParse2(rawData);
2319
+ }
2320
+ const { deserialize } = await loadSuperJSON();
2321
+ return await prettyPrintPacket(deserialize(rawData), "application/json");
2322
+ }
2323
+ if (dataType === "application/json") {
2324
+ if (typeof rawData === "string") {
2325
+ rawData = safeJsonParse2(rawData);
2326
+ }
2327
+ return JSON.stringify(rawData, safeReplacer, 2);
2328
+ }
2329
+ if (typeof rawData === "string") {
2330
+ return rawData;
2331
+ }
2332
+ return JSON.stringify(rawData, safeReplacer, 2);
2333
+ }
2334
+ __name(prettyPrintPacket, "prettyPrintPacket");
2335
+ function safeReplacer(key, value) {
2336
+ if (typeof value === "bigint") {
2337
+ return value.toString();
2338
+ }
2339
+ if (value instanceof RegExp) {
2340
+ return value.toString();
2341
+ }
2342
+ if (value instanceof Set) {
2343
+ return Array.from(value);
2344
+ }
2345
+ if (value instanceof Map) {
2346
+ const obj = {};
2347
+ value.forEach((v, k) => {
2348
+ obj[k] = v;
2349
+ });
2350
+ return obj;
2351
+ }
2352
+ return value;
2353
+ }
2354
+ __name(safeReplacer, "safeReplacer");
2355
+ function getPacketExtension(outputType) {
2356
+ switch (outputType) {
2357
+ case "application/json":
2358
+ return "json";
2359
+ case "application/super+json":
2360
+ return "json";
2361
+ case "text/plain":
2362
+ return "txt";
2363
+ default:
2364
+ return "txt";
2365
+ }
2366
+ }
2367
+ __name(getPacketExtension, "getPacketExtension");
2368
+ async function loadSuperJSON() {
2369
+ return await import('superjson');
2370
+ }
2371
+ __name(loadSuperJSON, "loadSuperJSON");
2372
+ function safeJsonParse2(value) {
2373
+ try {
2374
+ return JSON.parse(value);
2375
+ } catch {
2376
+ return;
2377
+ }
2378
+ }
2379
+ __name(safeJsonParse2, "safeJsonParse");
2380
+
2381
+ export { conditionallyExportPacket, conditionallyImportPacket, createPacketAttributes, createPacketAttributesAsJson, packetRequiresOffloading, parsePacket, prettyPrintPacket, stringifyIO };
2382
+ //# sourceMappingURL=out.js.map
2383
+ //# sourceMappingURL=ioSerialization.mjs.map