@trigger.dev/core 3.0.0-beta.48 → 3.0.0-beta.49

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