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

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 +436 -20511
  84. package/dist/v3/index.d.ts +436 -20511
  85. package/dist/v3/index.js +2822 -2890
  86. package/dist/v3/index.js.map +1 -1
  87. package/dist/v3/index.mjs +2767 -2863
  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 +4741 -0
  106. package/dist/v3/schemas/index.d.ts +4741 -0
  107. package/dist/v3/schemas/index.js +2039 -0
  108. package/dist/v3/schemas/index.js.map +1 -0
  109. package/dist/v3/schemas/index.mjs +1900 -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 +2367 -0
  132. package/dist/v3/utils/ioSerialization.js.map +1 -0
  133. package/dist/v3/utils/ioSerialization.mjs +2358 -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 +3683 -0
  162. package/dist/v3/workers/index.js.map +1 -0
  163. package/dist/v3/workers/index.mjs +3664 -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,3683 @@
1
+ 'use strict';
2
+
3
+ var api = require('@opentelemetry/api');
4
+ var zod = require('zod');
5
+ var apiLogs = require('@opentelemetry/api-logs');
6
+ var exporterLogsOtlpHttp = require('@opentelemetry/exporter-logs-otlp-http');
7
+ var exporterTraceOtlpHttp = require('@opentelemetry/exporter-trace-otlp-http');
8
+ var instrumentation = require('@opentelemetry/instrumentation');
9
+ var resources = require('@opentelemetry/resources');
10
+ var sdkLogs = require('@opentelemetry/sdk-logs');
11
+ var sdkTraceNode = require('@opentelemetry/sdk-trace-node');
12
+ var semanticConventions = require('@opentelemetry/semantic-conventions');
13
+ var zodValidationError = require('zod-validation-error');
14
+ var preciseDate = require('@google-cloud/precise-date');
15
+ var util = require('util');
16
+ var promises = require('timers/promises');
17
+
18
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
19
+
20
+ var util__default = /*#__PURE__*/_interopDefault(util);
21
+
22
+ var __defProp = Object.defineProperty;
23
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
24
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
25
+ var __publicField = (obj, key, value) => {
26
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
27
+ return value;
28
+ };
29
+ var __accessCheck = (obj, member, msg) => {
30
+ if (!member.has(obj))
31
+ throw TypeError("Cannot " + msg);
32
+ };
33
+ var __privateGet = (obj, member, getter) => {
34
+ __accessCheck(obj, member, "read from private field");
35
+ return getter ? getter.call(obj) : member.get(obj);
36
+ };
37
+ var __privateAdd = (obj, member, value) => {
38
+ if (member.has(obj))
39
+ throw TypeError("Cannot add the same private member more than once");
40
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
41
+ };
42
+ var __privateMethod = (obj, member, method) => {
43
+ __accessCheck(obj, member, "access private method");
44
+ return method;
45
+ };
46
+ function parseError(error) {
47
+ if (error instanceof Error) {
48
+ return {
49
+ type: "BUILT_IN_ERROR",
50
+ name: error.name,
51
+ message: error.message,
52
+ stackTrace: error.stack ?? ""
53
+ };
54
+ }
55
+ if (typeof error === "string") {
56
+ return {
57
+ type: "STRING_ERROR",
58
+ raw: error
59
+ };
60
+ }
61
+ try {
62
+ return {
63
+ type: "CUSTOM_ERROR",
64
+ raw: JSON.stringify(error)
65
+ };
66
+ } catch (e) {
67
+ return {
68
+ type: "CUSTOM_ERROR",
69
+ raw: String(error)
70
+ };
71
+ }
72
+ }
73
+ __name(parseError, "parseError");
74
+ var SerializedError = zod.z.object({
75
+ message: zod.z.string(),
76
+ name: zod.z.string().optional(),
77
+ stackTrace: zod.z.string().optional()
78
+ });
79
+ function sanitizeError(error) {
80
+ switch (error.type) {
81
+ case "BUILT_IN_ERROR": {
82
+ return {
83
+ type: "BUILT_IN_ERROR",
84
+ message: error.message?.replace(/\0/g, ""),
85
+ name: error.name?.replace(/\0/g, ""),
86
+ stackTrace: error.stackTrace?.replace(/\0/g, "")
87
+ };
88
+ }
89
+ case "STRING_ERROR": {
90
+ return {
91
+ type: "STRING_ERROR",
92
+ raw: error.raw.replace(/\0/g, "")
93
+ };
94
+ }
95
+ case "CUSTOM_ERROR": {
96
+ return {
97
+ type: "CUSTOM_ERROR",
98
+ raw: error.raw.replace(/\0/g, "")
99
+ };
100
+ }
101
+ case "INTERNAL_ERROR": {
102
+ return {
103
+ type: "INTERNAL_ERROR",
104
+ code: error.code,
105
+ message: error.message?.replace(/\0/g, ""),
106
+ stackTrace: error.stackTrace?.replace(/\0/g, "")
107
+ };
108
+ }
109
+ }
110
+ }
111
+ __name(sanitizeError, "sanitizeError");
112
+
113
+ // src/v3/limits.ts
114
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
115
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
116
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
117
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
118
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
119
+ var OTEL_LINK_COUNT_LIMIT = 2;
120
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
121
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
122
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
123
+
124
+ // src/v3/semanticInternalAttributes.ts
125
+ var SemanticInternalAttributes = {
126
+ ENVIRONMENT_ID: "ctx.environment.id",
127
+ ENVIRONMENT_TYPE: "ctx.environment.type",
128
+ ORGANIZATION_ID: "ctx.organization.id",
129
+ ORGANIZATION_SLUG: "ctx.organization.slug",
130
+ ORGANIZATION_NAME: "ctx.organization.name",
131
+ PROJECT_ID: "ctx.project.id",
132
+ PROJECT_REF: "ctx.project.ref",
133
+ PROJECT_NAME: "ctx.project.title",
134
+ PROJECT_DIR: "project.dir",
135
+ ATTEMPT_ID: "ctx.attempt.id",
136
+ ATTEMPT_NUMBER: "ctx.attempt.number",
137
+ RUN_ID: "ctx.run.id",
138
+ RUN_IS_TEST: "ctx.run.isTest",
139
+ BATCH_ID: "ctx.batch.id",
140
+ TASK_SLUG: "ctx.task.id",
141
+ TASK_PATH: "ctx.task.filePath",
142
+ TASK_EXPORT_NAME: "ctx.task.exportName",
143
+ QUEUE_NAME: "ctx.queue.name",
144
+ QUEUE_ID: "ctx.queue.id",
145
+ MACHINE_PRESET_NAME: "ctx.machine.name",
146
+ MACHINE_PRESET_CPU: "ctx.machine.cpu",
147
+ MACHINE_PRESET_MEMORY: "ctx.machine.memory",
148
+ MACHINE_PRESET_CENTS_PER_MS: "ctx.machine.centsPerMs",
149
+ SPAN_PARTIAL: "$span.partial",
150
+ SPAN_ID: "$span.span_id",
151
+ OUTPUT: "$output",
152
+ OUTPUT_TYPE: "$mime_type_output",
153
+ STYLE: "$style",
154
+ STYLE_ICON: "$style.icon",
155
+ STYLE_VARIANT: "$style.variant",
156
+ STYLE_ACCESSORY: "$style.accessory",
157
+ METADATA: "$metadata",
158
+ TRIGGER: "$trigger",
159
+ PAYLOAD: "$payload",
160
+ PAYLOAD_TYPE: "$mime_type_payload",
161
+ SHOW: "$show",
162
+ SHOW_ACTIONS: "$show.actions",
163
+ WORKER_ID: "worker.id",
164
+ WORKER_VERSION: "worker.version",
165
+ CLI_VERSION: "cli.version",
166
+ SDK_VERSION: "sdk.version",
167
+ SDK_LANGUAGE: "sdk.language",
168
+ RETRY_AT: "retry.at",
169
+ RETRY_DELAY: "retry.delay",
170
+ RETRY_COUNT: "retry.count",
171
+ LINK_TITLE: "$link.title",
172
+ IDEMPOTENCY_KEY: "ctx.run.idempotencyKey",
173
+ USAGE_DURATION_MS: "$usage.durationMs",
174
+ USAGE_COST_IN_CENTS: "$usage.costInCents",
175
+ RATE_LIMIT_LIMIT: "response.rateLimit.limit",
176
+ RATE_LIMIT_REMAINING: "response.rateLimit.remaining",
177
+ RATE_LIMIT_RESET: "response.rateLimit.reset"
178
+ };
179
+
180
+ // src/v3/utils/flattenAttributes.ts
181
+ var NULL_SENTINEL = "$@null((";
182
+ function flattenAttributes(obj, prefix) {
183
+ const result = {};
184
+ if (obj === void 0) {
185
+ return result;
186
+ }
187
+ if (obj === null) {
188
+ result[prefix || ""] = NULL_SENTINEL;
189
+ return result;
190
+ }
191
+ if (typeof obj === "string") {
192
+ result[prefix || ""] = obj;
193
+ return result;
194
+ }
195
+ if (typeof obj === "number") {
196
+ result[prefix || ""] = obj;
197
+ return result;
198
+ }
199
+ if (typeof obj === "boolean") {
200
+ result[prefix || ""] = obj;
201
+ return result;
202
+ }
203
+ for (const [key, value] of Object.entries(obj)) {
204
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${key}]` : key}`;
205
+ if (Array.isArray(value)) {
206
+ for (let i = 0; i < value.length; i++) {
207
+ if (typeof value[i] === "object" && value[i] !== null) {
208
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
209
+ } else {
210
+ if (value[i] === null) {
211
+ result[`${newPrefix}.[${i}]`] = NULL_SENTINEL;
212
+ } else {
213
+ result[`${newPrefix}.[${i}]`] = value[i];
214
+ }
215
+ }
216
+ }
217
+ } else if (isRecord(value)) {
218
+ Object.assign(result, flattenAttributes(value, newPrefix));
219
+ } else {
220
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
221
+ result[newPrefix] = value;
222
+ } else if (value === null) {
223
+ result[newPrefix] = NULL_SENTINEL;
224
+ }
225
+ }
226
+ }
227
+ return result;
228
+ }
229
+ __name(flattenAttributes, "flattenAttributes");
230
+ function isRecord(value) {
231
+ return value !== null && typeof value === "object" && !Array.isArray(value);
232
+ }
233
+ __name(isRecord, "isRecord");
234
+
235
+ // src/v3/utils/platform.ts
236
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
237
+
238
+ // src/v3/utils/globals.ts
239
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
240
+ var _global = _globalThis;
241
+ function registerGlobal(type, instance, allowOverride = false) {
242
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
243
+ if (!allowOverride && api[type]) {
244
+ return false;
245
+ }
246
+ api[type] = instance;
247
+ return true;
248
+ }
249
+ __name(registerGlobal, "registerGlobal");
250
+ function getGlobal(type) {
251
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
252
+ }
253
+ __name(getGlobal, "getGlobal");
254
+ function unregisterGlobal(type) {
255
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
256
+ if (api) {
257
+ delete api[type];
258
+ }
259
+ }
260
+ __name(unregisterGlobal, "unregisterGlobal");
261
+
262
+ // src/v3/taskContext/index.ts
263
+ var API_NAME = "task-context";
264
+ var _getTaskContext, getTaskContext_fn;
265
+ var _TaskContextAPI = class _TaskContextAPI {
266
+ constructor() {
267
+ __privateAdd(this, _getTaskContext);
268
+ }
269
+ static getInstance() {
270
+ if (!this._instance) {
271
+ this._instance = new _TaskContextAPI();
272
+ }
273
+ return this._instance;
274
+ }
275
+ get isInsideTask() {
276
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
277
+ }
278
+ get ctx() {
279
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
280
+ }
281
+ get worker() {
282
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
283
+ }
284
+ get attributes() {
285
+ if (this.ctx) {
286
+ return {
287
+ ...this.contextAttributes,
288
+ ...this.workerAttributes
289
+ };
290
+ }
291
+ return {};
292
+ }
293
+ get workerAttributes() {
294
+ if (this.worker) {
295
+ return {
296
+ [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
297
+ [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
298
+ };
299
+ }
300
+ return {};
301
+ }
302
+ get contextAttributes() {
303
+ if (this.ctx) {
304
+ return {
305
+ [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
306
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
307
+ [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
308
+ [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
309
+ [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
310
+ [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
311
+ [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
312
+ [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
313
+ [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
314
+ [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
315
+ [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
316
+ [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
317
+ [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
318
+ [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
319
+ [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
320
+ [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
321
+ [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
322
+ [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
323
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey,
324
+ [SemanticInternalAttributes.MACHINE_PRESET_NAME]: this.ctx.machine?.name,
325
+ [SemanticInternalAttributes.MACHINE_PRESET_CPU]: this.ctx.machine?.cpu,
326
+ [SemanticInternalAttributes.MACHINE_PRESET_MEMORY]: this.ctx.machine?.memory,
327
+ [SemanticInternalAttributes.MACHINE_PRESET_CENTS_PER_MS]: this.ctx.machine?.centsPerMs
328
+ };
329
+ }
330
+ return {};
331
+ }
332
+ disable() {
333
+ unregisterGlobal(API_NAME);
334
+ }
335
+ setGlobalTaskContext(taskContext2) {
336
+ return registerGlobal(API_NAME, taskContext2);
337
+ }
338
+ };
339
+ _getTaskContext = new WeakSet();
340
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
341
+ return getGlobal(API_NAME);
342
+ }, "#getTaskContext");
343
+ __name(_TaskContextAPI, "TaskContextAPI");
344
+ var TaskContextAPI = _TaskContextAPI;
345
+
346
+ // src/v3/task-context-api.ts
347
+ var taskContext = TaskContextAPI.getInstance();
348
+
349
+ // src/v3/taskContext/otelProcessors.ts
350
+ var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
351
+ constructor(innerProcessor) {
352
+ this._innerProcessor = innerProcessor;
353
+ }
354
+ // Called when a span starts
355
+ onStart(span, parentContext) {
356
+ if (taskContext.ctx) {
357
+ span.setAttributes(flattenAttributes({
358
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContext.ctx.attempt.id,
359
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContext.ctx.attempt.number
360
+ }, SemanticInternalAttributes.METADATA));
361
+ }
362
+ this._innerProcessor.onStart(span, parentContext);
363
+ }
364
+ // Delegate the rest of the methods to the wrapped processor
365
+ onEnd(span) {
366
+ this._innerProcessor.onEnd(span);
367
+ }
368
+ shutdown() {
369
+ return this._innerProcessor.shutdown();
370
+ }
371
+ forceFlush() {
372
+ return this._innerProcessor.forceFlush();
373
+ }
374
+ };
375
+ __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
376
+ var TaskContextSpanProcessor = _TaskContextSpanProcessor;
377
+ var _TaskContextLogProcessor = class _TaskContextLogProcessor {
378
+ constructor(innerProcessor) {
379
+ this._innerProcessor = innerProcessor;
380
+ }
381
+ forceFlush() {
382
+ return this._innerProcessor.forceFlush();
383
+ }
384
+ onEmit(logRecord, context2) {
385
+ if (taskContext.ctx) {
386
+ logRecord.setAttributes(flattenAttributes({
387
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContext.ctx.attempt.id,
388
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContext.ctx.attempt.number
389
+ }, SemanticInternalAttributes.METADATA));
390
+ }
391
+ this._innerProcessor.onEmit(logRecord, context2);
392
+ }
393
+ shutdown() {
394
+ return this._innerProcessor.shutdown();
395
+ }
396
+ };
397
+ __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
398
+ var TaskContextLogProcessor = _TaskContextLogProcessor;
399
+
400
+ // src/v3/utils/getEnv.ts
401
+ function getEnvVar(name) {
402
+ if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
403
+ return process.env[name];
404
+ }
405
+ }
406
+ __name(getEnvVar, "getEnvVar");
407
+
408
+ // package.json
409
+ var version = "3.0.0-beta.50";
410
+
411
+ // src/v3/otel/tracingSDK.ts
412
+ var _a;
413
+ var AsyncResourceDetector = (_a = class {
414
+ constructor() {
415
+ __publicField(this, "_resolved", false);
416
+ this._promise = new Promise((resolver) => {
417
+ this._resolver = resolver;
418
+ });
419
+ }
420
+ detect(_config) {
421
+ return new resources.Resource({}, this._promise);
422
+ }
423
+ resolveWithAttributes(attributes) {
424
+ if (!this._resolver) {
425
+ throw new Error("Resolver not available");
426
+ }
427
+ if (this._resolved) {
428
+ return;
429
+ }
430
+ this._resolved = true;
431
+ this._resolver(attributes);
432
+ }
433
+ }, __name(_a, "AsyncResourceDetector"), _a);
434
+ var _TracingSDK = class _TracingSDK {
435
+ constructor(config) {
436
+ this.config = config;
437
+ this.asyncResourceDetector = new AsyncResourceDetector();
438
+ setLogLevel(config.diagLogLevel ?? "none");
439
+ const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
440
+ const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
441
+ const commonResources = resources.detectResourcesSync({
442
+ detectors: [
443
+ this.asyncResourceDetector,
444
+ resources.processDetectorSync
445
+ ]
446
+ }).merge(new resources.Resource({
447
+ [semanticConventions.SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
448
+ [SemanticInternalAttributes.TRIGGER]: true,
449
+ [SemanticInternalAttributes.CLI_VERSION]: version
450
+ })).merge(config.resource ?? new resources.Resource({})).merge(new resources.Resource(envResourceAttributes));
451
+ const traceProvider = new sdkTraceNode.NodeTracerProvider({
452
+ forceFlushTimeoutMillis: config.forceFlushTimeoutMillis,
453
+ resource: commonResources,
454
+ spanLimits: {
455
+ attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
456
+ attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
457
+ eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
458
+ attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
459
+ linkCountLimit: OTEL_LINK_COUNT_LIMIT,
460
+ attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
461
+ }
462
+ });
463
+ const spanExporter = new exporterTraceOtlpHttp.OTLPTraceExporter({
464
+ url: `${config.url}/v1/traces`,
465
+ timeoutMillis: config.forceFlushTimeoutMillis
466
+ });
467
+ traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkTraceNode.BatchSpanProcessor(spanExporter, {
468
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
469
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
470
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
471
+ maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
472
+ }) : new sdkTraceNode.SimpleSpanProcessor(spanExporter)));
473
+ traceProvider.register();
474
+ instrumentation.registerInstrumentations({
475
+ instrumentations: config.instrumentations ?? [],
476
+ tracerProvider: traceProvider
477
+ });
478
+ const logExporter = new exporterLogsOtlpHttp.OTLPLogExporter({
479
+ url: `${config.url}/v1/logs`
480
+ });
481
+ const loggerProvider = new sdkLogs.LoggerProvider({
482
+ resource: commonResources,
483
+ logRecordLimits: {
484
+ attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
485
+ attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
486
+ }
487
+ });
488
+ loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkLogs.BatchLogRecordProcessor(logExporter, {
489
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
490
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
491
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
492
+ maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
493
+ }) : new sdkLogs.SimpleLogRecordProcessor(logExporter)));
494
+ this._logProvider = loggerProvider;
495
+ this._spanExporter = spanExporter;
496
+ this._traceProvider = traceProvider;
497
+ apiLogs.logs.setGlobalLoggerProvider(loggerProvider);
498
+ this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
499
+ this.getTracer = traceProvider.getTracer.bind(traceProvider);
500
+ }
501
+ async flush() {
502
+ await Promise.all([
503
+ this._traceProvider.forceFlush(),
504
+ this._logProvider.forceFlush()
505
+ ]);
506
+ }
507
+ async shutdown() {
508
+ await Promise.all([
509
+ this._traceProvider.shutdown(),
510
+ this._logProvider.shutdown()
511
+ ]);
512
+ }
513
+ };
514
+ __name(_TracingSDK, "TracingSDK");
515
+ var TracingSDK = _TracingSDK;
516
+ function setLogLevel(level) {
517
+ let diagLogLevel;
518
+ switch (level) {
519
+ case "none":
520
+ diagLogLevel = api.DiagLogLevel.NONE;
521
+ break;
522
+ case "error":
523
+ diagLogLevel = api.DiagLogLevel.ERROR;
524
+ break;
525
+ case "warn":
526
+ diagLogLevel = api.DiagLogLevel.WARN;
527
+ break;
528
+ case "info":
529
+ diagLogLevel = api.DiagLogLevel.INFO;
530
+ break;
531
+ case "debug":
532
+ diagLogLevel = api.DiagLogLevel.DEBUG;
533
+ break;
534
+ case "verbose":
535
+ diagLogLevel = api.DiagLogLevel.VERBOSE;
536
+ break;
537
+ case "all":
538
+ diagLogLevel = api.DiagLogLevel.ALL;
539
+ break;
540
+ default:
541
+ diagLogLevel = api.DiagLogLevel.NONE;
542
+ }
543
+ api.diag.setLogger(new api.DiagConsoleLogger(), diagLogLevel);
544
+ }
545
+ __name(setLogLevel, "setLogLevel");
546
+
547
+ // src/v3/otel/index.ts
548
+ function recordSpanException(span, error) {
549
+ if (error instanceof Error) {
550
+ span.recordException(sanitizeSpanError(error));
551
+ } else if (typeof error === "string") {
552
+ span.recordException(error.replace(/\0/g, ""));
553
+ } else {
554
+ span.recordException(JSON.stringify(error).replace(/\0/g, ""));
555
+ }
556
+ span.setStatus({
557
+ code: api.SpanStatusCode.ERROR
558
+ });
559
+ }
560
+ __name(recordSpanException, "recordSpanException");
561
+ function sanitizeSpanError(error) {
562
+ const sanitizedError = new Error(error.message.replace(/\0/g, ""));
563
+ sanitizedError.name = error.name.replace(/\0/g, "");
564
+ sanitizedError.stack = error.stack?.replace(/\0/g, "");
565
+ return sanitizedError;
566
+ }
567
+ __name(sanitizeSpanError, "sanitizeSpanError");
568
+ var MachineCpu = zod.z.union([
569
+ zod.z.literal(0.25),
570
+ zod.z.literal(0.5),
571
+ zod.z.literal(1),
572
+ zod.z.literal(2),
573
+ zod.z.literal(4)
574
+ ]);
575
+ var MachineMemory = zod.z.union([
576
+ zod.z.literal(0.25),
577
+ zod.z.literal(0.5),
578
+ zod.z.literal(1),
579
+ zod.z.literal(2),
580
+ zod.z.literal(4),
581
+ zod.z.literal(8)
582
+ ]);
583
+ var MachinePresetName = zod.z.enum([
584
+ "micro",
585
+ "small-1x",
586
+ "small-2x",
587
+ "medium-1x",
588
+ "medium-2x",
589
+ "large-1x",
590
+ "large-2x"
591
+ ]);
592
+ var MachineConfig = zod.z.object({
593
+ cpu: MachineCpu.optional(),
594
+ memory: MachineMemory.optional(),
595
+ preset: MachinePresetName.optional()
596
+ });
597
+ var MachinePreset = zod.z.object({
598
+ name: MachinePresetName,
599
+ cpu: zod.z.number(),
600
+ memory: zod.z.number(),
601
+ centsPerMs: zod.z.number()
602
+ });
603
+ var TaskRunBuiltInError = zod.z.object({
604
+ type: zod.z.literal("BUILT_IN_ERROR"),
605
+ name: zod.z.string(),
606
+ message: zod.z.string(),
607
+ stackTrace: zod.z.string()
608
+ });
609
+ var TaskRunCustomErrorObject = zod.z.object({
610
+ type: zod.z.literal("CUSTOM_ERROR"),
611
+ raw: zod.z.string()
612
+ });
613
+ var TaskRunStringError = zod.z.object({
614
+ type: zod.z.literal("STRING_ERROR"),
615
+ raw: zod.z.string()
616
+ });
617
+ var TaskRunErrorCodes = {
618
+ COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
619
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
620
+ CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
621
+ TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
622
+ TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
623
+ TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
624
+ TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
625
+ TASK_PROCESS_SIGKILL_TIMEOUT: "TASK_PROCESS_SIGKILL_TIMEOUT",
626
+ TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
627
+ TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
628
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
629
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
630
+ };
631
+ var TaskRunInternalError = zod.z.object({
632
+ type: zod.z.literal("INTERNAL_ERROR"),
633
+ code: zod.z.enum([
634
+ "COULD_NOT_FIND_EXECUTOR",
635
+ "COULD_NOT_FIND_TASK",
636
+ "CONFIGURED_INCORRECTLY",
637
+ "TASK_ALREADY_RUNNING",
638
+ "TASK_EXECUTION_FAILED",
639
+ "TASK_EXECUTION_ABORTED",
640
+ "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
641
+ "TASK_PROCESS_SIGKILL_TIMEOUT",
642
+ "TASK_RUN_CANCELLED",
643
+ "TASK_OUTPUT_ERROR",
644
+ "HANDLE_ERROR_ERROR",
645
+ "GRACEFUL_EXIT_TIMEOUT",
646
+ "TASK_RUN_HEARTBEAT_TIMEOUT"
647
+ ]),
648
+ message: zod.z.string().optional(),
649
+ stackTrace: zod.z.string().optional()
650
+ });
651
+ var TaskRunError = zod.z.discriminatedUnion("type", [
652
+ TaskRunBuiltInError,
653
+ TaskRunCustomErrorObject,
654
+ TaskRunStringError,
655
+ TaskRunInternalError
656
+ ]);
657
+ var TaskRun = zod.z.object({
658
+ id: zod.z.string(),
659
+ payload: zod.z.string(),
660
+ payloadType: zod.z.string(),
661
+ context: zod.z.any(),
662
+ tags: zod.z.array(zod.z.string()),
663
+ isTest: zod.z.boolean().default(false),
664
+ createdAt: zod.z.coerce.date(),
665
+ startedAt: zod.z.coerce.date().default(() => /* @__PURE__ */ new Date()),
666
+ idempotencyKey: zod.z.string().optional(),
667
+ maxAttempts: zod.z.number().optional(),
668
+ durationMs: zod.z.number().default(0),
669
+ costInCents: zod.z.number().default(0),
670
+ baseCostInCents: zod.z.number().default(0)
671
+ });
672
+ var TaskRunExecutionTask = zod.z.object({
673
+ id: zod.z.string(),
674
+ filePath: zod.z.string(),
675
+ exportName: zod.z.string()
676
+ });
677
+ var TaskRunExecutionAttempt = zod.z.object({
678
+ id: zod.z.string(),
679
+ number: zod.z.number(),
680
+ startedAt: zod.z.coerce.date(),
681
+ backgroundWorkerId: zod.z.string(),
682
+ backgroundWorkerTaskId: zod.z.string(),
683
+ status: zod.z.string()
684
+ });
685
+ var TaskRunExecutionEnvironment = zod.z.object({
686
+ id: zod.z.string(),
687
+ slug: zod.z.string(),
688
+ type: zod.z.enum([
689
+ "PRODUCTION",
690
+ "STAGING",
691
+ "DEVELOPMENT",
692
+ "PREVIEW"
693
+ ])
694
+ });
695
+ var TaskRunExecutionOrganization = zod.z.object({
696
+ id: zod.z.string(),
697
+ slug: zod.z.string(),
698
+ name: zod.z.string()
699
+ });
700
+ var TaskRunExecutionProject = zod.z.object({
701
+ id: zod.z.string(),
702
+ ref: zod.z.string(),
703
+ slug: zod.z.string(),
704
+ name: zod.z.string()
705
+ });
706
+ var TaskRunExecutionQueue = zod.z.object({
707
+ id: zod.z.string(),
708
+ name: zod.z.string()
709
+ });
710
+ var TaskRunExecutionBatch = zod.z.object({
711
+ id: zod.z.string()
712
+ });
713
+ var TaskRunExecution = zod.z.object({
714
+ task: TaskRunExecutionTask,
715
+ attempt: TaskRunExecutionAttempt,
716
+ run: TaskRun,
717
+ queue: TaskRunExecutionQueue,
718
+ environment: TaskRunExecutionEnvironment,
719
+ organization: TaskRunExecutionOrganization,
720
+ project: TaskRunExecutionProject,
721
+ batch: TaskRunExecutionBatch.optional(),
722
+ machine: MachinePreset.optional()
723
+ });
724
+ var TaskRunContext = zod.z.object({
725
+ task: TaskRunExecutionTask,
726
+ attempt: TaskRunExecutionAttempt.omit({
727
+ backgroundWorkerId: true,
728
+ backgroundWorkerTaskId: true
729
+ }),
730
+ run: TaskRun.omit({
731
+ payload: true,
732
+ payloadType: true
733
+ }),
734
+ queue: TaskRunExecutionQueue,
735
+ environment: TaskRunExecutionEnvironment,
736
+ organization: TaskRunExecutionOrganization,
737
+ project: TaskRunExecutionProject,
738
+ batch: TaskRunExecutionBatch.optional(),
739
+ machine: MachinePreset.optional()
740
+ });
741
+ var TaskRunExecutionRetry = zod.z.object({
742
+ timestamp: zod.z.number(),
743
+ delay: zod.z.number(),
744
+ error: zod.z.unknown().optional()
745
+ });
746
+ var TaskRunExecutionUsage = zod.z.object({
747
+ durationMs: zod.z.number()
748
+ });
749
+ var TaskRunFailedExecutionResult = zod.z.object({
750
+ ok: zod.z.literal(false),
751
+ id: zod.z.string(),
752
+ error: TaskRunError,
753
+ retry: TaskRunExecutionRetry.optional(),
754
+ skippedRetrying: zod.z.boolean().optional(),
755
+ usage: TaskRunExecutionUsage.optional()
756
+ });
757
+ var TaskRunSuccessfulExecutionResult = zod.z.object({
758
+ ok: zod.z.literal(true),
759
+ id: zod.z.string(),
760
+ output: zod.z.string().optional(),
761
+ outputType: zod.z.string(),
762
+ usage: TaskRunExecutionUsage.optional()
763
+ });
764
+ var TaskRunExecutionResult = zod.z.discriminatedUnion("ok", [
765
+ TaskRunSuccessfulExecutionResult,
766
+ TaskRunFailedExecutionResult
767
+ ]);
768
+ var BatchTaskRunExecutionResult = zod.z.object({
769
+ id: zod.z.string(),
770
+ items: TaskRunExecutionResult.array()
771
+ });
772
+
773
+ // src/v3/schemas/schemas.ts
774
+ zod.z.enum([
775
+ "PRODUCTION",
776
+ "STAGING",
777
+ "DEVELOPMENT",
778
+ "PREVIEW"
779
+ ]);
780
+ zod.z.object({
781
+ execution: TaskRunExecution,
782
+ traceContext: zod.z.record(zod.z.unknown()),
783
+ environment: zod.z.record(zod.z.string()).optional()
784
+ });
785
+ var ProdTaskRunExecution = TaskRunExecution.extend({
786
+ worker: zod.z.object({
787
+ id: zod.z.string(),
788
+ contentHash: zod.z.string(),
789
+ version: zod.z.string()
790
+ }),
791
+ machine: MachinePreset.default({
792
+ name: "small-1x",
793
+ cpu: 1,
794
+ memory: 1,
795
+ centsPerMs: 0
796
+ })
797
+ });
798
+ zod.z.object({
799
+ execution: ProdTaskRunExecution,
800
+ traceContext: zod.z.record(zod.z.unknown()),
801
+ environment: zod.z.record(zod.z.string()).optional()
802
+ });
803
+ var FixedWindowRateLimit = zod.z.object({
804
+ type: zod.z.literal("fixed-window"),
805
+ limit: zod.z.number(),
806
+ window: zod.z.union([
807
+ zod.z.object({
808
+ seconds: zod.z.number()
809
+ }),
810
+ zod.z.object({
811
+ minutes: zod.z.number()
812
+ }),
813
+ zod.z.object({
814
+ hours: zod.z.number()
815
+ })
816
+ ])
817
+ });
818
+ var SlidingWindowRateLimit = zod.z.object({
819
+ type: zod.z.literal("sliding-window"),
820
+ limit: zod.z.number(),
821
+ window: zod.z.union([
822
+ zod.z.object({
823
+ seconds: zod.z.number()
824
+ }),
825
+ zod.z.object({
826
+ minutes: zod.z.number()
827
+ }),
828
+ zod.z.object({
829
+ hours: zod.z.number()
830
+ })
831
+ ])
832
+ });
833
+ var RateLimitOptions = zod.z.discriminatedUnion("type", [
834
+ FixedWindowRateLimit,
835
+ SlidingWindowRateLimit
836
+ ]);
837
+ var RetryOptions = zod.z.object({
838
+ /** The number of attempts before giving up */
839
+ maxAttempts: zod.z.number().int().optional(),
840
+ /** The exponential factor to use when calculating the next retry time.
841
+ *
842
+ * Each subsequent retry will be calculated as `previousTimeout * factor`
843
+ */
844
+ factor: zod.z.number().optional(),
845
+ /** The minimum time to wait before retrying */
846
+ minTimeoutInMs: zod.z.number().int().optional(),
847
+ /** The maximum time to wait before retrying */
848
+ maxTimeoutInMs: zod.z.number().int().optional(),
849
+ /** Randomize the timeout between retries.
850
+ *
851
+ * This can be useful to prevent the thundering herd problem where all retries happen at the same time.
852
+ */
853
+ randomize: zod.z.boolean().optional()
854
+ });
855
+ var QueueOptions = zod.z.object({
856
+ /** You can define a shared queue and then pass the name in to your task.
857
+ *
858
+ * @example
859
+ *
860
+ * ```ts
861
+ * const myQueue = queue({
862
+ name: "my-queue",
863
+ concurrencyLimit: 1,
864
+ });
865
+
866
+ export const task1 = task({
867
+ id: "task-1",
868
+ queue: {
869
+ name: "my-queue",
870
+ },
871
+ run: async (payload: { message: string }) => {
872
+ // ...
873
+ },
874
+ });
875
+
876
+ export const task2 = task({
877
+ id: "task-2",
878
+ queue: {
879
+ name: "my-queue",
880
+ },
881
+ run: async (payload: { message: string }) => {
882
+ // ...
883
+ },
884
+ });
885
+ * ```
886
+ */
887
+ name: zod.z.string().optional(),
888
+ /** An optional property that specifies the maximum number of concurrent run executions.
889
+ *
890
+ * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
891
+ concurrencyLimit: zod.z.number().int().min(0).max(1e3).optional(),
892
+ /** @deprecated This feature is coming soon */
893
+ rateLimit: RateLimitOptions.optional()
894
+ });
895
+ var ScheduleMetadata = zod.z.object({
896
+ cron: zod.z.string(),
897
+ timezone: zod.z.string()
898
+ });
899
+ zod.z.object({
900
+ id: zod.z.string(),
901
+ packageVersion: zod.z.string(),
902
+ queue: QueueOptions.optional(),
903
+ retry: RetryOptions.optional(),
904
+ machine: MachineConfig.optional(),
905
+ triggerSource: zod.z.string().optional(),
906
+ schedule: ScheduleMetadata.optional()
907
+ });
908
+ zod.z.object({
909
+ filePath: zod.z.string(),
910
+ exportName: zod.z.string()
911
+ });
912
+ zod.z.object({
913
+ id: zod.z.string(),
914
+ packageVersion: zod.z.string(),
915
+ queue: QueueOptions.optional(),
916
+ retry: RetryOptions.optional(),
917
+ machine: MachineConfig.optional(),
918
+ triggerSource: zod.z.string().optional(),
919
+ schedule: ScheduleMetadata.optional(),
920
+ filePath: zod.z.string(),
921
+ exportName: zod.z.string()
922
+ });
923
+ zod.z.enum([
924
+ "index",
925
+ "create",
926
+ "restore"
927
+ ]);
928
+ zod.z.enum([
929
+ "terminate"
930
+ ]);
931
+ var RegexSchema = zod.z.custom((val) => {
932
+ try {
933
+ return typeof val.test === "function";
934
+ } catch {
935
+ return false;
936
+ }
937
+ });
938
+ zod.z.object({
939
+ project: zod.z.string(),
940
+ triggerDirectories: zod.z.string().array().optional(),
941
+ triggerUrl: zod.z.string().optional(),
942
+ projectDir: zod.z.string().optional(),
943
+ tsconfigPath: zod.z.string().optional(),
944
+ retries: zod.z.object({
945
+ enabledInDev: zod.z.boolean().default(true),
946
+ default: RetryOptions.optional()
947
+ }).optional(),
948
+ additionalPackages: zod.z.string().array().optional(),
949
+ additionalFiles: zod.z.string().array().optional(),
950
+ dependenciesToBundle: zod.z.array(zod.z.union([
951
+ zod.z.string(),
952
+ RegexSchema
953
+ ])).optional(),
954
+ logLevel: zod.z.string().optional(),
955
+ enableConsoleLogging: zod.z.boolean().optional(),
956
+ postInstall: zod.z.string().optional(),
957
+ extraCACerts: zod.z.string().optional()
958
+ });
959
+ zod.z.enum([
960
+ "WAIT_FOR_DURATION",
961
+ "WAIT_FOR_TASK",
962
+ "WAIT_FOR_BATCH"
963
+ ]);
964
+ zod.z.object({
965
+ runId: zod.z.string(),
966
+ attemptCount: zod.z.number().optional(),
967
+ messageId: zod.z.string(),
968
+ isTest: zod.z.boolean(),
969
+ traceContext: zod.z.record(zod.z.unknown()),
970
+ environment: zod.z.record(zod.z.string()).optional()
971
+ });
972
+
973
+ // src/v3/schemas/resources.ts
974
+ var TaskResource = zod.z.object({
975
+ id: zod.z.string(),
976
+ filePath: zod.z.string(),
977
+ exportName: zod.z.string(),
978
+ queue: QueueOptions.optional(),
979
+ retry: RetryOptions.optional(),
980
+ machine: MachineConfig.optional(),
981
+ triggerSource: zod.z.string().optional(),
982
+ schedule: ScheduleMetadata.optional()
983
+ });
984
+ var BackgroundWorkerMetadata = zod.z.object({
985
+ packageVersion: zod.z.string(),
986
+ contentHash: zod.z.string(),
987
+ cliPackageVersion: zod.z.string().optional(),
988
+ tasks: zod.z.array(TaskResource)
989
+ });
990
+ zod.z.object({
991
+ contentHash: zod.z.string(),
992
+ imageTag: zod.z.string()
993
+ });
994
+
995
+ // src/v3/schemas/api.ts
996
+ zod.z.object({
997
+ userId: zod.z.string(),
998
+ email: zod.z.string().email(),
999
+ dashboardUrl: zod.z.string()
1000
+ });
1001
+ var GetProjectResponseBody = zod.z.object({
1002
+ id: zod.z.string(),
1003
+ externalRef: zod.z.string(),
1004
+ name: zod.z.string(),
1005
+ slug: zod.z.string(),
1006
+ createdAt: zod.z.coerce.date(),
1007
+ organization: zod.z.object({
1008
+ id: zod.z.string(),
1009
+ title: zod.z.string(),
1010
+ slug: zod.z.string(),
1011
+ createdAt: zod.z.coerce.date()
1012
+ })
1013
+ });
1014
+ zod.z.array(GetProjectResponseBody);
1015
+ zod.z.object({
1016
+ apiKey: zod.z.string(),
1017
+ name: zod.z.string(),
1018
+ apiUrl: zod.z.string()
1019
+ });
1020
+ zod.z.object({
1021
+ localOnly: zod.z.boolean(),
1022
+ metadata: BackgroundWorkerMetadata,
1023
+ supportsLazyAttempts: zod.z.boolean().optional()
1024
+ });
1025
+ zod.z.object({
1026
+ id: zod.z.string(),
1027
+ version: zod.z.string(),
1028
+ contentHash: zod.z.string()
1029
+ });
1030
+ var TriggerTaskRequestBody = zod.z.object({
1031
+ payload: zod.z.any(),
1032
+ context: zod.z.any(),
1033
+ options: zod.z.object({
1034
+ dependentAttempt: zod.z.string().optional(),
1035
+ dependentBatch: zod.z.string().optional(),
1036
+ lockToVersion: zod.z.string().optional(),
1037
+ queue: QueueOptions.optional(),
1038
+ concurrencyKey: zod.z.string().optional(),
1039
+ idempotencyKey: zod.z.string().optional(),
1040
+ test: zod.z.boolean().optional(),
1041
+ payloadType: zod.z.string().optional(),
1042
+ delay: zod.z.string().or(zod.z.coerce.date()).optional(),
1043
+ ttl: zod.z.string().or(zod.z.number().nonnegative().int()).optional(),
1044
+ maxAttempts: zod.z.number().int().optional()
1045
+ }).optional()
1046
+ });
1047
+ var TriggerTaskResponse = zod.z.object({
1048
+ id: zod.z.string()
1049
+ });
1050
+ zod.z.object({
1051
+ items: TriggerTaskRequestBody.array(),
1052
+ dependentAttempt: zod.z.string().optional()
1053
+ });
1054
+ var BatchTriggerTaskResponse = zod.z.object({
1055
+ batchId: zod.z.string(),
1056
+ runs: zod.z.string().array()
1057
+ });
1058
+ zod.z.object({
1059
+ id: zod.z.string(),
1060
+ items: zod.z.array(zod.z.object({
1061
+ id: zod.z.string(),
1062
+ taskRunId: zod.z.string(),
1063
+ status: zod.z.enum([
1064
+ "PENDING",
1065
+ "CANCELED",
1066
+ "COMPLETED",
1067
+ "FAILED"
1068
+ ])
1069
+ }))
1070
+ });
1071
+ zod.z.object({
1072
+ delay: zod.z.string().or(zod.z.coerce.date())
1073
+ });
1074
+ zod.z.object({
1075
+ variables: zod.z.record(zod.z.string())
1076
+ });
1077
+ zod.z.object({
1078
+ imageReference: zod.z.string(),
1079
+ selfHosted: zod.z.boolean().optional()
1080
+ });
1081
+ zod.z.object({
1082
+ id: zod.z.string(),
1083
+ contentHash: zod.z.string()
1084
+ });
1085
+ var ExternalBuildData = zod.z.object({
1086
+ buildId: zod.z.string(),
1087
+ buildToken: zod.z.string(),
1088
+ projectId: zod.z.string()
1089
+ });
1090
+ zod.z.object({
1091
+ id: zod.z.string(),
1092
+ contentHash: zod.z.string(),
1093
+ shortCode: zod.z.string(),
1094
+ version: zod.z.string(),
1095
+ imageTag: zod.z.string(),
1096
+ externalBuildData: ExternalBuildData.optional().nullable(),
1097
+ registryHost: zod.z.string().optional()
1098
+ });
1099
+ zod.z.object({
1100
+ contentHash: zod.z.string(),
1101
+ userId: zod.z.string().optional()
1102
+ });
1103
+ var DeploymentErrorData = zod.z.object({
1104
+ name: zod.z.string(),
1105
+ message: zod.z.string(),
1106
+ stack: zod.z.string().optional(),
1107
+ stderr: zod.z.string().optional()
1108
+ });
1109
+ zod.z.object({
1110
+ id: zod.z.string(),
1111
+ status: zod.z.enum([
1112
+ "PENDING",
1113
+ "BUILDING",
1114
+ "DEPLOYING",
1115
+ "DEPLOYED",
1116
+ "FAILED",
1117
+ "CANCELED",
1118
+ "TIMED_OUT"
1119
+ ]),
1120
+ contentHash: zod.z.string(),
1121
+ shortCode: zod.z.string(),
1122
+ version: zod.z.string(),
1123
+ imageReference: zod.z.string().optional(),
1124
+ errorData: DeploymentErrorData.optional().nullable(),
1125
+ worker: zod.z.object({
1126
+ id: zod.z.string(),
1127
+ version: zod.z.string(),
1128
+ tasks: zod.z.array(zod.z.object({
1129
+ id: zod.z.string(),
1130
+ slug: zod.z.string(),
1131
+ filePath: zod.z.string(),
1132
+ exportName: zod.z.string()
1133
+ }))
1134
+ }).optional()
1135
+ });
1136
+ var CreateUploadPayloadUrlResponseBody = zod.z.object({
1137
+ presignedUrl: zod.z.string()
1138
+ });
1139
+ var ReplayRunResponse = zod.z.object({
1140
+ id: zod.z.string()
1141
+ });
1142
+ var CanceledRunResponse = zod.z.object({
1143
+ id: zod.z.string()
1144
+ });
1145
+ var ScheduleType = zod.z.union([
1146
+ zod.z.literal("DECLARATIVE"),
1147
+ zod.z.literal("IMPERATIVE")
1148
+ ]);
1149
+ zod.z.object({
1150
+ /** The schedule id associated with this run (you can have many schedules for the same task).
1151
+ You can use this to remove the schedule, update it, etc */
1152
+ scheduleId: zod.z.string(),
1153
+ /** The type of schedule – `"DECLARATIVE"` or `"IMPERATIVE"`.
1154
+ *
1155
+ * **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.
1156
+ *
1157
+ * **IMPERATIVE** – created using the `schedules.create` functions or in the dashboard.
1158
+ */
1159
+ type: ScheduleType,
1160
+ /** When the task was scheduled to run.
1161
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task.
1162
+ *
1163
+ * This date is UTC. To output it as a string with a timezone you would do this:
1164
+ * ```ts
1165
+ * const formatted = payload.timestamp.toLocaleString("en-US", {
1166
+ timeZone: payload.timezone,
1167
+ });
1168
+ ``` */
1169
+ timestamp: zod.z.date(),
1170
+ /** When the task was last run (it has been).
1171
+ This can be undefined if it's never been run. This date is UTC. */
1172
+ lastTimestamp: zod.z.date().optional(),
1173
+ /** You can optionally provide an external id when creating the schedule.
1174
+ Usually you would use a userId or some other unique identifier.
1175
+ This defaults to undefined if you didn't provide one. */
1176
+ externalId: zod.z.string().optional(),
1177
+ /** The IANA timezone the schedule is set to. The default is UTC.
1178
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1179
+ */
1180
+ timezone: zod.z.string(),
1181
+ /** The next 5 dates this task is scheduled to run */
1182
+ upcoming: zod.z.array(zod.z.date())
1183
+ });
1184
+ var CreateScheduleOptions = zod.z.object({
1185
+ /** The id of the task you want to attach to. */
1186
+ task: zod.z.string(),
1187
+ /** The schedule in CRON format.
1188
+ *
1189
+ * ```txt
1190
+ * * * * * *
1191
+ ┬ ┬ ┬ ┬ ┬
1192
+ │ │ │ │ |
1193
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
1194
+ │ │ │ └───── month (1 - 12)
1195
+ │ │ └────────── day of month (1 - 31, L)
1196
+ │ └─────────────── hour (0 - 23)
1197
+ └──────────────────── minute (0 - 59)
1198
+ * ```
1199
+
1200
+ "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.
1201
+
1202
+ */
1203
+ cron: zod.z.string(),
1204
+ /** You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1205
+ *
1206
+ * This is required to prevent you from creating duplicate schedules. */
1207
+ deduplicationKey: zod.z.string(),
1208
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
1209
+ *
1210
+ * This allows you to have per-user CRON tasks.
1211
+ */
1212
+ externalId: zod.z.string().optional(),
1213
+ /** Optionally, you can specify a timezone in the IANA format. If unset it will use UTC.
1214
+ * If specified then the CRON will be evaluated in that timezone and will respect daylight savings.
1215
+ *
1216
+ * 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.
1217
+ *
1218
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1219
+ *
1220
+ * @example "America/New_York", "Europe/London", "Asia/Tokyo", "Africa/Cairo"
1221
+ *
1222
+ */
1223
+ timezone: zod.z.string().optional()
1224
+ });
1225
+ CreateScheduleOptions.omit({
1226
+ deduplicationKey: true
1227
+ });
1228
+ var ScheduleGenerator = zod.z.object({
1229
+ type: zod.z.literal("CRON"),
1230
+ expression: zod.z.string(),
1231
+ description: zod.z.string()
1232
+ });
1233
+ var ScheduleObject = zod.z.object({
1234
+ id: zod.z.string(),
1235
+ type: ScheduleType,
1236
+ task: zod.z.string(),
1237
+ active: zod.z.boolean(),
1238
+ deduplicationKey: zod.z.string().nullish(),
1239
+ externalId: zod.z.string().nullish(),
1240
+ generator: ScheduleGenerator,
1241
+ timezone: zod.z.string(),
1242
+ nextRun: zod.z.coerce.date().nullish(),
1243
+ environments: zod.z.array(zod.z.object({
1244
+ id: zod.z.string(),
1245
+ type: zod.z.string(),
1246
+ userName: zod.z.string().nullish()
1247
+ }))
1248
+ });
1249
+ var DeletedScheduleObject = zod.z.object({
1250
+ id: zod.z.string()
1251
+ });
1252
+ zod.z.object({
1253
+ data: zod.z.array(ScheduleObject),
1254
+ pagination: zod.z.object({
1255
+ currentPage: zod.z.number(),
1256
+ totalPages: zod.z.number(),
1257
+ count: zod.z.number()
1258
+ })
1259
+ });
1260
+ zod.z.object({
1261
+ page: zod.z.number().optional(),
1262
+ perPage: zod.z.number().optional()
1263
+ });
1264
+ zod.z.object({
1265
+ timezones: zod.z.array(zod.z.string())
1266
+ });
1267
+ var RunStatus = zod.z.enum([
1268
+ /// Task hasn't been deployed yet but is waiting to be executed
1269
+ "WAITING_FOR_DEPLOY",
1270
+ /// Task is waiting to be executed by a worker
1271
+ "QUEUED",
1272
+ /// Task is currently being executed by a worker
1273
+ "EXECUTING",
1274
+ /// Task has failed and is waiting to be retried
1275
+ "REATTEMPTING",
1276
+ /// Task has been paused by the system, and will be resumed by the system
1277
+ "FROZEN",
1278
+ /// Task has been completed successfully
1279
+ "COMPLETED",
1280
+ /// Task has been canceled by the user
1281
+ "CANCELED",
1282
+ /// Task has been completed with errors
1283
+ "FAILED",
1284
+ /// Task has crashed and won't be retried, most likely the worker ran out of resources, e.g. memory or storage
1285
+ "CRASHED",
1286
+ /// Task was interrupted during execution, mostly this happens in development environments
1287
+ "INTERRUPTED",
1288
+ /// Task has failed to complete, due to an error in the system
1289
+ "SYSTEM_FAILURE",
1290
+ /// Task has been scheduled to run at a specific time
1291
+ "DELAYED",
1292
+ /// Task has expired and won't be executed
1293
+ "EXPIRED"
1294
+ ]);
1295
+ var AttemptStatus = zod.z.enum([
1296
+ "PENDING",
1297
+ "EXECUTING",
1298
+ "PAUSED",
1299
+ "COMPLETED",
1300
+ "FAILED",
1301
+ "CANCELED"
1302
+ ]);
1303
+ var RunEnvironmentDetails = zod.z.object({
1304
+ id: zod.z.string(),
1305
+ name: zod.z.string(),
1306
+ user: zod.z.string().optional()
1307
+ });
1308
+ var RunScheduleDetails = zod.z.object({
1309
+ id: zod.z.string(),
1310
+ externalId: zod.z.string().optional(),
1311
+ deduplicationKey: zod.z.string().optional(),
1312
+ generator: ScheduleGenerator
1313
+ });
1314
+ var CommonRunFields = {
1315
+ id: zod.z.string(),
1316
+ status: RunStatus,
1317
+ taskIdentifier: zod.z.string(),
1318
+ idempotencyKey: zod.z.string().optional(),
1319
+ version: zod.z.string().optional(),
1320
+ isQueued: zod.z.boolean(),
1321
+ isExecuting: zod.z.boolean(),
1322
+ isCompleted: zod.z.boolean(),
1323
+ isSuccess: zod.z.boolean(),
1324
+ isFailed: zod.z.boolean(),
1325
+ isCancelled: zod.z.boolean(),
1326
+ isTest: zod.z.boolean(),
1327
+ createdAt: zod.z.coerce.date(),
1328
+ updatedAt: zod.z.coerce.date(),
1329
+ startedAt: zod.z.coerce.date().optional(),
1330
+ finishedAt: zod.z.coerce.date().optional(),
1331
+ delayedUntil: zod.z.coerce.date().optional(),
1332
+ ttl: zod.z.string().optional(),
1333
+ expiredAt: zod.z.coerce.date().optional()
1334
+ };
1335
+ var RetrieveRunResponse = zod.z.object({
1336
+ ...CommonRunFields,
1337
+ payload: zod.z.any().optional(),
1338
+ payloadPresignedUrl: zod.z.string().optional(),
1339
+ output: zod.z.any().optional(),
1340
+ outputPresignedUrl: zod.z.string().optional(),
1341
+ schedule: RunScheduleDetails.optional(),
1342
+ attempts: zod.z.array(zod.z.object({
1343
+ id: zod.z.string(),
1344
+ status: AttemptStatus,
1345
+ createdAt: zod.z.coerce.date(),
1346
+ updatedAt: zod.z.coerce.date(),
1347
+ startedAt: zod.z.coerce.date().optional(),
1348
+ completedAt: zod.z.coerce.date().optional(),
1349
+ error: SerializedError.optional()
1350
+ }).optional())
1351
+ });
1352
+ var ListRunResponseItem = zod.z.object({
1353
+ ...CommonRunFields,
1354
+ env: RunEnvironmentDetails
1355
+ });
1356
+ zod.z.object({
1357
+ data: zod.z.array(ListRunResponseItem),
1358
+ pagination: zod.z.object({
1359
+ next: zod.z.string().optional(),
1360
+ previous: zod.z.string().optional()
1361
+ })
1362
+ });
1363
+ zod.z.object({
1364
+ name: zod.z.string(),
1365
+ value: zod.z.string()
1366
+ });
1367
+ zod.z.object({
1368
+ value: zod.z.string()
1369
+ });
1370
+ zod.z.object({
1371
+ variables: zod.z.record(zod.z.string()),
1372
+ override: zod.z.boolean().optional()
1373
+ });
1374
+ var EnvironmentVariableResponseBody = zod.z.object({
1375
+ success: zod.z.boolean()
1376
+ });
1377
+ var EnvironmentVariableValue = zod.z.object({
1378
+ value: zod.z.string()
1379
+ });
1380
+ var EnvironmentVariable = zod.z.object({
1381
+ name: zod.z.string(),
1382
+ value: zod.z.string()
1383
+ });
1384
+ var EnvironmentVariables = zod.z.array(EnvironmentVariable);
1385
+
1386
+ // src/v3/utils/retries.ts
1387
+ var defaultRetryOptions = {
1388
+ maxAttempts: 3,
1389
+ factor: 2,
1390
+ minTimeoutInMs: 1e3,
1391
+ maxTimeoutInMs: 6e4,
1392
+ randomize: true
1393
+ };
1394
+ function calculateNextRetryDelay(options, attempt) {
1395
+ const opts = {
1396
+ ...defaultRetryOptions,
1397
+ ...options
1398
+ };
1399
+ if (attempt >= opts.maxAttempts) {
1400
+ return;
1401
+ }
1402
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1403
+ const random = randomize ? Math.random() + 1 : 1;
1404
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1405
+ return Math.round(timeout);
1406
+ }
1407
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1408
+
1409
+ // src/v3/apiClient/errors.ts
1410
+ var _ApiError = class _ApiError extends Error {
1411
+ constructor(status, error, message, headers) {
1412
+ super(`${_ApiError.makeMessage(status, error, message)}`);
1413
+ this.name = "TriggerApiError";
1414
+ this.status = status;
1415
+ this.headers = headers;
1416
+ const data = error;
1417
+ this.error = data;
1418
+ this.code = data?.["code"];
1419
+ this.param = data?.["param"];
1420
+ this.type = data?.["type"];
1421
+ }
1422
+ static makeMessage(status, error, message) {
1423
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1424
+ if (status && msg) {
1425
+ return `${status} ${msg}`;
1426
+ }
1427
+ if (status) {
1428
+ return `${status} status code (no body)`;
1429
+ }
1430
+ if (msg) {
1431
+ return msg;
1432
+ }
1433
+ return "(no status code or body)";
1434
+ }
1435
+ static generate(status, errorResponse, message, headers) {
1436
+ if (!status) {
1437
+ return new ApiConnectionError({
1438
+ cause: castToError(errorResponse)
1439
+ });
1440
+ }
1441
+ const error = errorResponse?.["error"];
1442
+ if (status === 400) {
1443
+ return new BadRequestError(status, error, message, headers);
1444
+ }
1445
+ if (status === 401) {
1446
+ return new AuthenticationError(status, error, message, headers);
1447
+ }
1448
+ if (status === 403) {
1449
+ return new PermissionDeniedError(status, error, message, headers);
1450
+ }
1451
+ if (status === 404) {
1452
+ return new NotFoundError(status, error, message, headers);
1453
+ }
1454
+ if (status === 409) {
1455
+ return new ConflictError(status, error, message, headers);
1456
+ }
1457
+ if (status === 422) {
1458
+ return new UnprocessableEntityError(status, error, message, headers);
1459
+ }
1460
+ if (status === 429) {
1461
+ return new RateLimitError(status, error, message, headers);
1462
+ }
1463
+ if (status >= 500) {
1464
+ return new InternalServerError(status, error, message, headers);
1465
+ }
1466
+ return new _ApiError(status, error, message, headers);
1467
+ }
1468
+ };
1469
+ __name(_ApiError, "ApiError");
1470
+ var ApiError = _ApiError;
1471
+ var _ApiConnectionError = class _ApiConnectionError extends ApiError {
1472
+ constructor({ message, cause }) {
1473
+ super(void 0, void 0, message || "Connection error.", void 0);
1474
+ __publicField(this, "status");
1475
+ if (cause)
1476
+ this.cause = cause;
1477
+ }
1478
+ };
1479
+ __name(_ApiConnectionError, "ApiConnectionError");
1480
+ var ApiConnectionError = _ApiConnectionError;
1481
+ var _BadRequestError = class _BadRequestError extends ApiError {
1482
+ constructor() {
1483
+ super(...arguments);
1484
+ __publicField(this, "status", 400);
1485
+ }
1486
+ };
1487
+ __name(_BadRequestError, "BadRequestError");
1488
+ var BadRequestError = _BadRequestError;
1489
+ var _AuthenticationError = class _AuthenticationError extends ApiError {
1490
+ constructor() {
1491
+ super(...arguments);
1492
+ __publicField(this, "status", 401);
1493
+ }
1494
+ };
1495
+ __name(_AuthenticationError, "AuthenticationError");
1496
+ var AuthenticationError = _AuthenticationError;
1497
+ var _PermissionDeniedError = class _PermissionDeniedError extends ApiError {
1498
+ constructor() {
1499
+ super(...arguments);
1500
+ __publicField(this, "status", 403);
1501
+ }
1502
+ };
1503
+ __name(_PermissionDeniedError, "PermissionDeniedError");
1504
+ var PermissionDeniedError = _PermissionDeniedError;
1505
+ var _NotFoundError = class _NotFoundError extends ApiError {
1506
+ constructor() {
1507
+ super(...arguments);
1508
+ __publicField(this, "status", 404);
1509
+ }
1510
+ };
1511
+ __name(_NotFoundError, "NotFoundError");
1512
+ var NotFoundError = _NotFoundError;
1513
+ var _ConflictError = class _ConflictError extends ApiError {
1514
+ constructor() {
1515
+ super(...arguments);
1516
+ __publicField(this, "status", 409);
1517
+ }
1518
+ };
1519
+ __name(_ConflictError, "ConflictError");
1520
+ var ConflictError = _ConflictError;
1521
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends ApiError {
1522
+ constructor() {
1523
+ super(...arguments);
1524
+ __publicField(this, "status", 422);
1525
+ }
1526
+ };
1527
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
1528
+ var UnprocessableEntityError = _UnprocessableEntityError;
1529
+ var _RateLimitError = class _RateLimitError extends ApiError {
1530
+ constructor() {
1531
+ super(...arguments);
1532
+ __publicField(this, "status", 429);
1533
+ }
1534
+ get millisecondsUntilReset() {
1535
+ const resetAtUnixEpochMs = (this.headers ?? {})["x-ratelimit-reset"];
1536
+ if (typeof resetAtUnixEpochMs === "string") {
1537
+ const resetAtUnixEpoch = parseInt(resetAtUnixEpochMs, 10);
1538
+ if (isNaN(resetAtUnixEpoch)) {
1539
+ return;
1540
+ }
1541
+ return Math.max(resetAtUnixEpoch - Date.now() + Math.floor(Math.random() * 2e3), 0);
1542
+ }
1543
+ }
1544
+ };
1545
+ __name(_RateLimitError, "RateLimitError");
1546
+ var RateLimitError = _RateLimitError;
1547
+ var _InternalServerError = class _InternalServerError extends ApiError {
1548
+ };
1549
+ __name(_InternalServerError, "InternalServerError");
1550
+ var InternalServerError = _InternalServerError;
1551
+ function castToError(err) {
1552
+ if (err instanceof Error)
1553
+ return err;
1554
+ return new Error(err);
1555
+ }
1556
+ __name(castToError, "castToError");
1557
+
1558
+ // src/v3/utils/styleAttributes.ts
1559
+ function accessoryAttributes(accessory) {
1560
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
1561
+ }
1562
+ __name(accessoryAttributes, "accessoryAttributes");
1563
+
1564
+ // src/v3/apiClient/pagination.ts
1565
+ var _CursorPage = class _CursorPage {
1566
+ constructor(data, pagination, pageFetcher) {
1567
+ this.pageFetcher = pageFetcher;
1568
+ this.data = data;
1569
+ this.pagination = pagination;
1570
+ }
1571
+ getPaginatedItems() {
1572
+ return this.data ?? [];
1573
+ }
1574
+ hasNextPage() {
1575
+ return !!this.pagination.next;
1576
+ }
1577
+ hasPreviousPage() {
1578
+ return !!this.pagination.previous;
1579
+ }
1580
+ getNextPage() {
1581
+ if (!this.pagination.next) {
1582
+ throw new Error("No next page available");
1583
+ }
1584
+ return this.pageFetcher({
1585
+ after: this.pagination.next
1586
+ });
1587
+ }
1588
+ getPreviousPage() {
1589
+ if (!this.pagination.previous) {
1590
+ throw new Error("No previous page available");
1591
+ }
1592
+ return this.pageFetcher({
1593
+ before: this.pagination.previous
1594
+ });
1595
+ }
1596
+ async *iterPages() {
1597
+ let page = this;
1598
+ yield page;
1599
+ while (page.hasNextPage()) {
1600
+ page = await page.getNextPage();
1601
+ yield page;
1602
+ }
1603
+ }
1604
+ async *[Symbol.asyncIterator]() {
1605
+ for await (const page of this.iterPages()) {
1606
+ for (const item of page.getPaginatedItems()) {
1607
+ yield item;
1608
+ }
1609
+ }
1610
+ }
1611
+ };
1612
+ __name(_CursorPage, "CursorPage");
1613
+ var CursorPage = _CursorPage;
1614
+ var _OffsetLimitPage = class _OffsetLimitPage {
1615
+ constructor(data, pagination, pageFetcher) {
1616
+ this.pageFetcher = pageFetcher;
1617
+ this.data = data;
1618
+ this.pagination = pagination;
1619
+ }
1620
+ getPaginatedItems() {
1621
+ return this.data ?? [];
1622
+ }
1623
+ hasNextPage() {
1624
+ return this.pagination.currentPage < this.pagination.totalPages;
1625
+ }
1626
+ hasPreviousPage() {
1627
+ return this.pagination.currentPage > 1;
1628
+ }
1629
+ getNextPage() {
1630
+ if (!this.hasNextPage()) {
1631
+ throw new Error("No next page available");
1632
+ }
1633
+ return this.pageFetcher({
1634
+ page: this.pagination.currentPage + 1
1635
+ });
1636
+ }
1637
+ getPreviousPage() {
1638
+ if (!this.hasPreviousPage()) {
1639
+ throw new Error("No previous page available");
1640
+ }
1641
+ return this.pageFetcher({
1642
+ page: this.pagination.currentPage - 1
1643
+ });
1644
+ }
1645
+ async *iterPages() {
1646
+ let page = this;
1647
+ yield page;
1648
+ while (page.hasNextPage()) {
1649
+ page = await page.getNextPage();
1650
+ yield page;
1651
+ }
1652
+ }
1653
+ async *[Symbol.asyncIterator]() {
1654
+ for await (const page of this.iterPages()) {
1655
+ for (const item of page.getPaginatedItems()) {
1656
+ yield item;
1657
+ }
1658
+ }
1659
+ }
1660
+ };
1661
+ __name(_OffsetLimitPage, "OffsetLimitPage");
1662
+ var OffsetLimitPage = _OffsetLimitPage;
1663
+
1664
+ // src/v3/apiClient/core.ts
1665
+ var defaultRetryOptions2 = {
1666
+ maxAttempts: 3,
1667
+ factor: 2,
1668
+ minTimeoutInMs: 1e3,
1669
+ maxTimeoutInMs: 6e4,
1670
+ randomize: false
1671
+ };
1672
+ function zodfetch(schema, url, requestInit, options) {
1673
+ return new ApiPromise(_doZodFetch(schema, url, requestInit, options));
1674
+ }
1675
+ __name(zodfetch, "zodfetch");
1676
+ function zodfetchCursorPage(schema, url, params, requestInit, options) {
1677
+ const query = new URLSearchParams(params.query);
1678
+ if (params.limit) {
1679
+ query.set("page[size]", String(params.limit));
1680
+ }
1681
+ if (params.after) {
1682
+ query.set("page[after]", params.after);
1683
+ }
1684
+ if (params.before) {
1685
+ query.set("page[before]", params.before);
1686
+ }
1687
+ const cursorPageSchema = zod.z.object({
1688
+ data: zod.z.array(schema),
1689
+ pagination: zod.z.object({
1690
+ next: zod.z.string().optional(),
1691
+ previous: zod.z.string().optional()
1692
+ })
1693
+ });
1694
+ const $url = new URL(url);
1695
+ $url.search = query.toString();
1696
+ const fetchResult = _doZodFetch(cursorPageSchema, $url.href, requestInit, options);
1697
+ return new CursorPagePromise(fetchResult, schema, url, params, requestInit, options);
1698
+ }
1699
+ __name(zodfetchCursorPage, "zodfetchCursorPage");
1700
+ function zodfetchOffsetLimitPage(schema, url, params, requestInit, options) {
1701
+ const query = new URLSearchParams(params.query);
1702
+ if (params.limit) {
1703
+ query.set("perPage", String(params.limit));
1704
+ }
1705
+ if (params.page) {
1706
+ query.set("page", String(params.page));
1707
+ }
1708
+ const offsetLimitPageSchema = zod.z.object({
1709
+ data: zod.z.array(schema),
1710
+ pagination: zod.z.object({
1711
+ currentPage: zod.z.coerce.number(),
1712
+ totalPages: zod.z.coerce.number(),
1713
+ count: zod.z.coerce.number()
1714
+ })
1715
+ });
1716
+ const $url = new URL(url);
1717
+ $url.search = query.toString();
1718
+ const fetchResult = _doZodFetch(offsetLimitPageSchema, $url.href, requestInit, options);
1719
+ return new OffsetLimitPagePromise(fetchResult, schema, url, params, requestInit, options);
1720
+ }
1721
+ __name(zodfetchOffsetLimitPage, "zodfetchOffsetLimitPage");
1722
+ async function traceZodFetch(params, callback) {
1723
+ if (!params.options?.tracer) {
1724
+ return callback();
1725
+ }
1726
+ const url = new URL(params.url);
1727
+ const method = params.requestInit?.method ?? "GET";
1728
+ const name = params.options.name ?? `${method} ${url.pathname}`;
1729
+ return await params.options.tracer.startActiveSpan(name, async (span) => {
1730
+ return await callback(span);
1731
+ }, {
1732
+ attributes: {
1733
+ [SemanticInternalAttributes.STYLE_ICON]: params.options?.icon ?? "api",
1734
+ ...params.options.attributes
1735
+ }
1736
+ });
1737
+ }
1738
+ __name(traceZodFetch, "traceZodFetch");
1739
+ async function _doZodFetch(schema, url, requestInit, options) {
1740
+ const $requestInit = await requestInit;
1741
+ return traceZodFetch({
1742
+ url,
1743
+ requestInit: $requestInit,
1744
+ options
1745
+ }, async (span) => {
1746
+ const result = await _doZodFetchWithRetries(schema, url, $requestInit, options);
1747
+ if (options?.onResponseBody && span) {
1748
+ options.onResponseBody(result.data, span);
1749
+ }
1750
+ return result;
1751
+ });
1752
+ }
1753
+ __name(_doZodFetch, "_doZodFetch");
1754
+ async function _doZodFetchWithRetries(schema, url, requestInit, options, attempt = 1) {
1755
+ try {
1756
+ const response = await fetch(url, requestInitWithCache(requestInit));
1757
+ const responseHeaders = createResponseHeaders(response.headers);
1758
+ if (!response.ok) {
1759
+ const retryResult = shouldRetry(response, attempt, options?.retry);
1760
+ if (retryResult.retry) {
1761
+ await waitForRetry(url, attempt + 1, retryResult.delay, options, requestInit, response);
1762
+ return await _doZodFetchWithRetries(schema, url, requestInit, options, attempt + 1);
1763
+ } else {
1764
+ const errText = await response.text().catch((e) => castToError2(e).message);
1765
+ const errJSON = safeJsonParse(errText);
1766
+ const errMessage = errJSON ? void 0 : errText;
1767
+ throw ApiError.generate(response.status, errJSON, errMessage, responseHeaders);
1768
+ }
1769
+ }
1770
+ const jsonBody = await response.json();
1771
+ const parsedResult = schema.safeParse(jsonBody);
1772
+ if (parsedResult.success) {
1773
+ return {
1774
+ data: parsedResult.data,
1775
+ response
1776
+ };
1777
+ }
1778
+ throw zodValidationError.fromZodError(parsedResult.error);
1779
+ } catch (error) {
1780
+ if (error instanceof ApiError) {
1781
+ throw error;
1782
+ }
1783
+ if (options?.retry) {
1784
+ const retry = {
1785
+ ...defaultRetryOptions2,
1786
+ ...options.retry
1787
+ };
1788
+ const delay = calculateNextRetryDelay(retry, attempt);
1789
+ if (delay) {
1790
+ await waitForRetry(url, attempt + 1, delay, options, requestInit);
1791
+ return await _doZodFetchWithRetries(schema, url, requestInit, options, attempt + 1);
1792
+ }
1793
+ }
1794
+ throw new ApiConnectionError({
1795
+ cause: castToError2(error)
1796
+ });
1797
+ }
1798
+ }
1799
+ __name(_doZodFetchWithRetries, "_doZodFetchWithRetries");
1800
+ function castToError2(err) {
1801
+ if (err instanceof Error)
1802
+ return err;
1803
+ return new Error(err);
1804
+ }
1805
+ __name(castToError2, "castToError");
1806
+ function shouldRetry(response, attempt, retryOptions) {
1807
+ function shouldRetryForOptions() {
1808
+ const retry = {
1809
+ ...defaultRetryOptions2,
1810
+ ...retryOptions
1811
+ };
1812
+ const delay = calculateNextRetryDelay(retry, attempt);
1813
+ if (delay) {
1814
+ return {
1815
+ retry: true,
1816
+ delay
1817
+ };
1818
+ } else {
1819
+ return {
1820
+ retry: false
1821
+ };
1822
+ }
1823
+ }
1824
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
1825
+ const shouldRetryHeader = response.headers.get("x-should-retry");
1826
+ if (shouldRetryHeader === "true")
1827
+ return shouldRetryForOptions();
1828
+ if (shouldRetryHeader === "false")
1829
+ return {
1830
+ retry: false
1831
+ };
1832
+ if (response.status === 408)
1833
+ return shouldRetryForOptions();
1834
+ if (response.status === 409)
1835
+ return shouldRetryForOptions();
1836
+ if (response.status === 429) {
1837
+ if (attempt >= (typeof retryOptions?.maxAttempts === "number" ? retryOptions?.maxAttempts : 3)) {
1838
+ return {
1839
+ retry: false
1840
+ };
1841
+ }
1842
+ const resetAtUnixEpochMs = response.headers.get("x-ratelimit-reset");
1843
+ if (resetAtUnixEpochMs) {
1844
+ const resetAtUnixEpoch = parseInt(resetAtUnixEpochMs, 10);
1845
+ const delay = resetAtUnixEpoch - Date.now() + Math.floor(Math.random() * 1e3);
1846
+ if (delay > 0) {
1847
+ return {
1848
+ retry: true,
1849
+ delay
1850
+ };
1851
+ }
1852
+ }
1853
+ return shouldRetryForOptions();
1854
+ }
1855
+ if (response.status >= 500)
1856
+ return shouldRetryForOptions();
1857
+ return {
1858
+ retry: false
1859
+ };
1860
+ }
1861
+ __name(shouldRetry, "shouldRetry");
1862
+ function safeJsonParse(text) {
1863
+ try {
1864
+ return JSON.parse(text);
1865
+ } catch (e) {
1866
+ return void 0;
1867
+ }
1868
+ }
1869
+ __name(safeJsonParse, "safeJsonParse");
1870
+ function createResponseHeaders(headers) {
1871
+ return new Proxy(Object.fromEntries(
1872
+ // @ts-ignore
1873
+ headers.entries()
1874
+ ), {
1875
+ get(target, name) {
1876
+ const key = name.toString();
1877
+ return target[key.toLowerCase()] || target[key];
1878
+ }
1879
+ });
1880
+ }
1881
+ __name(createResponseHeaders, "createResponseHeaders");
1882
+ function requestInitWithCache(requestInit) {
1883
+ try {
1884
+ const withCache = {
1885
+ ...requestInit,
1886
+ cache: "no-cache"
1887
+ };
1888
+ const _ = new Request("http://localhost", withCache);
1889
+ return withCache;
1890
+ } catch (error) {
1891
+ return requestInit ?? {};
1892
+ }
1893
+ }
1894
+ __name(requestInitWithCache, "requestInitWithCache");
1895
+ var _ApiPromise = class _ApiPromise extends Promise {
1896
+ constructor(responsePromise) {
1897
+ super((resolve) => {
1898
+ resolve(null);
1899
+ });
1900
+ this.responsePromise = responsePromise;
1901
+ }
1902
+ /**
1903
+ * Gets the raw `Response` instance instead of parsing the response
1904
+ * data.
1905
+ *
1906
+ * If you want to parse the response body but still get the `Response`
1907
+ * instance, you can use {@link withResponse()}.
1908
+ */
1909
+ asResponse() {
1910
+ return this.responsePromise.then((p) => p.response);
1911
+ }
1912
+ /**
1913
+ * Gets the parsed response data and the raw `Response` instance.
1914
+ *
1915
+ * If you just want to get the raw `Response` instance without parsing it,
1916
+ * you can use {@link asResponse()}.
1917
+ */
1918
+ async withResponse() {
1919
+ const [data, response] = await Promise.all([
1920
+ this.parse(),
1921
+ this.asResponse()
1922
+ ]);
1923
+ return {
1924
+ data,
1925
+ response
1926
+ };
1927
+ }
1928
+ parse() {
1929
+ return this.responsePromise.then((result) => result.data);
1930
+ }
1931
+ then(onfulfilled, onrejected) {
1932
+ return this.parse().then(onfulfilled, onrejected);
1933
+ }
1934
+ catch(onrejected) {
1935
+ return this.parse().catch(onrejected);
1936
+ }
1937
+ finally(onfinally) {
1938
+ return this.parse().finally(onfinally);
1939
+ }
1940
+ };
1941
+ __name(_ApiPromise, "ApiPromise");
1942
+ var ApiPromise = _ApiPromise;
1943
+ var _fetchPage, fetchPage_fn;
1944
+ var _CursorPagePromise = class _CursorPagePromise extends ApiPromise {
1945
+ constructor(result, schema, url, params, requestInit, options) {
1946
+ super(result.then((result2) => ({
1947
+ data: new CursorPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage, fetchPage_fn).bind(this)),
1948
+ response: result2.response
1949
+ })));
1950
+ __privateAdd(this, _fetchPage);
1951
+ this.schema = schema;
1952
+ this.url = url;
1953
+ this.params = params;
1954
+ this.requestInit = requestInit;
1955
+ this.options = options;
1956
+ }
1957
+ /**
1958
+ * Allow auto-paginating iteration on an unawaited list call, eg:
1959
+ *
1960
+ * for await (const item of client.items.list()) {
1961
+ * console.log(item)
1962
+ * }
1963
+ */
1964
+ async *[Symbol.asyncIterator]() {
1965
+ const page = await this;
1966
+ for await (const item of page) {
1967
+ yield item;
1968
+ }
1969
+ }
1970
+ };
1971
+ _fetchPage = new WeakSet();
1972
+ fetchPage_fn = /* @__PURE__ */ __name(function(params) {
1973
+ return zodfetchCursorPage(this.schema, this.url, {
1974
+ ...this.params,
1975
+ ...params
1976
+ }, this.requestInit, this.options);
1977
+ }, "#fetchPage");
1978
+ __name(_CursorPagePromise, "CursorPagePromise");
1979
+ var CursorPagePromise = _CursorPagePromise;
1980
+ var _fetchPage2, fetchPage_fn2;
1981
+ var _OffsetLimitPagePromise = class _OffsetLimitPagePromise extends ApiPromise {
1982
+ constructor(result, schema, url, params, requestInit, options) {
1983
+ super(result.then((result2) => ({
1984
+ data: new OffsetLimitPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage2, fetchPage_fn2).bind(this)),
1985
+ response: result2.response
1986
+ })));
1987
+ __privateAdd(this, _fetchPage2);
1988
+ this.schema = schema;
1989
+ this.url = url;
1990
+ this.params = params;
1991
+ this.requestInit = requestInit;
1992
+ this.options = options;
1993
+ }
1994
+ /**
1995
+ * Allow auto-paginating iteration on an unawaited list call, eg:
1996
+ *
1997
+ * for await (const item of client.items.list()) {
1998
+ * console.log(item)
1999
+ * }
2000
+ */
2001
+ async *[Symbol.asyncIterator]() {
2002
+ const page = await this;
2003
+ for await (const item of page) {
2004
+ yield item;
2005
+ }
2006
+ }
2007
+ };
2008
+ _fetchPage2 = new WeakSet();
2009
+ fetchPage_fn2 = /* @__PURE__ */ __name(function(params1) {
2010
+ return zodfetchOffsetLimitPage(this.schema, this.url, {
2011
+ ...this.params,
2012
+ ...params1
2013
+ }, this.requestInit, this.options);
2014
+ }, "#fetchPage");
2015
+ __name(_OffsetLimitPagePromise, "OffsetLimitPagePromise");
2016
+ var OffsetLimitPagePromise = _OffsetLimitPagePromise;
2017
+ async function waitForRetry(url, attempt, delay, options, requestInit, response) {
2018
+ if (options?.tracer) {
2019
+ const method = requestInit?.method ?? "GET";
2020
+ return options.tracer.startActiveSpan(response ? `wait after ${response.status}` : `wait after error`, async (span) => {
2021
+ await new Promise((resolve) => setTimeout(resolve, delay));
2022
+ }, {
2023
+ attributes: {
2024
+ [SemanticInternalAttributes.STYLE_ICON]: "wait",
2025
+ ...accessoryAttributes({
2026
+ items: [
2027
+ {
2028
+ text: `retrying ${options?.name ?? method.toUpperCase()} in ${delay}ms`,
2029
+ variant: "normal"
2030
+ }
2031
+ ],
2032
+ style: "codepath"
2033
+ })
2034
+ }
2035
+ });
2036
+ }
2037
+ await new Promise((resolve) => setTimeout(resolve, delay));
2038
+ }
2039
+ __name(waitForRetry, "waitForRetry");
2040
+
2041
+ // src/v3/apiClient/index.ts
2042
+ var DEFAULT_ZOD_FETCH_OPTIONS = {
2043
+ retry: {
2044
+ maxAttempts: 3,
2045
+ minTimeoutInMs: 1e3,
2046
+ maxTimeoutInMs: 3e4,
2047
+ factor: 2,
2048
+ randomize: false
2049
+ }
2050
+ };
2051
+ var _getHeaders, getHeaders_fn;
2052
+ var _ApiClient = class _ApiClient {
2053
+ constructor(baseUrl, accessToken, requestOptions = {}) {
2054
+ __privateAdd(this, _getHeaders);
2055
+ this.accessToken = accessToken;
2056
+ this.baseUrl = baseUrl.replace(/\/$/, "");
2057
+ this.defaultRequestOptions = mergeRequestOptions(DEFAULT_ZOD_FETCH_OPTIONS, requestOptions);
2058
+ }
2059
+ async getRunResult(runId, requestOptions) {
2060
+ try {
2061
+ return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
2062
+ method: "GET",
2063
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2064
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2065
+ } catch (error) {
2066
+ if (error instanceof ApiError) {
2067
+ if (error.status === 404) {
2068
+ return void 0;
2069
+ }
2070
+ }
2071
+ throw error;
2072
+ }
2073
+ }
2074
+ async getBatchResults(batchId, requestOptions) {
2075
+ return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
2076
+ method: "GET",
2077
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2078
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2079
+ }
2080
+ triggerTask(taskId, body, options, requestOptions) {
2081
+ const encodedTaskId = encodeURIComponent(taskId);
2082
+ return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/trigger`, {
2083
+ method: "POST",
2084
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2085
+ body: JSON.stringify(body)
2086
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2087
+ }
2088
+ batchTriggerTask(taskId, body, options, requestOptions) {
2089
+ const encodedTaskId = encodeURIComponent(taskId);
2090
+ return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/batch`, {
2091
+ method: "POST",
2092
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2093
+ body: JSON.stringify(body)
2094
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2095
+ }
2096
+ createUploadPayloadUrl(filename, requestOptions) {
2097
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2098
+ method: "PUT",
2099
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2100
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2101
+ }
2102
+ getPayloadUrl(filename, requestOptions) {
2103
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2104
+ method: "GET",
2105
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2106
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2107
+ }
2108
+ retrieveRun(runId, requestOptions) {
2109
+ return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v3/runs/${runId}`, {
2110
+ method: "GET",
2111
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2112
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2113
+ }
2114
+ listRuns(query, requestOptions) {
2115
+ const searchParams = createSearchQueryForListRuns(query);
2116
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/runs`, {
2117
+ query: searchParams,
2118
+ limit: query?.limit,
2119
+ after: query?.after,
2120
+ before: query?.before
2121
+ }, {
2122
+ method: "GET",
2123
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2124
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2125
+ }
2126
+ listProjectRuns(projectRef, query, requestOptions) {
2127
+ const searchParams = createSearchQueryForListRuns(query);
2128
+ if (query?.env) {
2129
+ searchParams.append("filter[env]", Array.isArray(query.env) ? query.env.join(",") : query.env);
2130
+ }
2131
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/projects/${projectRef}/runs`, {
2132
+ query: searchParams,
2133
+ limit: query?.limit,
2134
+ after: query?.after,
2135
+ before: query?.before
2136
+ }, {
2137
+ method: "GET",
2138
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2139
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2140
+ }
2141
+ replayRun(runId, requestOptions) {
2142
+ return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2143
+ method: "POST",
2144
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2145
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2146
+ }
2147
+ cancelRun(runId, requestOptions) {
2148
+ return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
2149
+ method: "POST",
2150
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2151
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2152
+ }
2153
+ rescheduleRun(runId, body, requestOptions) {
2154
+ return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/reschedule`, {
2155
+ method: "POST",
2156
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2157
+ body: JSON.stringify(body)
2158
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2159
+ }
2160
+ createSchedule(options, requestOptions) {
2161
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
2162
+ method: "POST",
2163
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2164
+ body: JSON.stringify(options)
2165
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2166
+ }
2167
+ listSchedules(options, requestOptions) {
2168
+ const searchParams = new URLSearchParams();
2169
+ if (options?.page) {
2170
+ searchParams.append("page", options.page.toString());
2171
+ }
2172
+ if (options?.perPage) {
2173
+ searchParams.append("perPage", options.perPage.toString());
2174
+ }
2175
+ return zodfetchOffsetLimitPage(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
2176
+ page: options?.page,
2177
+ limit: options?.perPage
2178
+ }, {
2179
+ method: "GET",
2180
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2181
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2182
+ }
2183
+ retrieveSchedule(scheduleId, requestOptions) {
2184
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2185
+ method: "GET",
2186
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2187
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2188
+ }
2189
+ updateSchedule(scheduleId, options, requestOptions) {
2190
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2191
+ method: "PUT",
2192
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2193
+ body: JSON.stringify(options)
2194
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2195
+ }
2196
+ deactivateSchedule(scheduleId, requestOptions) {
2197
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
2198
+ method: "POST",
2199
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2200
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2201
+ }
2202
+ activateSchedule(scheduleId, requestOptions) {
2203
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
2204
+ method: "POST",
2205
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2206
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2207
+ }
2208
+ deleteSchedule(scheduleId, requestOptions) {
2209
+ return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2210
+ method: "DELETE",
2211
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2212
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2213
+ }
2214
+ listEnvVars(projectRef, slug, requestOptions) {
2215
+ return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2216
+ method: "GET",
2217
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2218
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2219
+ }
2220
+ importEnvVars(projectRef, slug, body, requestOptions) {
2221
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
2222
+ method: "POST",
2223
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2224
+ body: JSON.stringify(body)
2225
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2226
+ }
2227
+ retrieveEnvVar(projectRef, slug, key, requestOptions) {
2228
+ return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2229
+ method: "GET",
2230
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2231
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2232
+ }
2233
+ createEnvVar(projectRef, slug, body, requestOptions) {
2234
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2235
+ method: "POST",
2236
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2237
+ body: JSON.stringify(body)
2238
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2239
+ }
2240
+ updateEnvVar(projectRef, slug, key, body, requestOptions) {
2241
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2242
+ method: "PUT",
2243
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2244
+ body: JSON.stringify(body)
2245
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2246
+ }
2247
+ deleteEnvVar(projectRef, slug, key, requestOptions) {
2248
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2249
+ method: "DELETE",
2250
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2251
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2252
+ }
2253
+ };
2254
+ _getHeaders = new WeakSet();
2255
+ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2256
+ const headers = {
2257
+ "Content-Type": "application/json",
2258
+ Authorization: `Bearer ${this.accessToken}`,
2259
+ "trigger-version": version
2260
+ };
2261
+ if (taskContext.isInsideTask) {
2262
+ headers["x-trigger-worker"] = "true";
2263
+ api.propagation.inject(api.context.active(), headers);
2264
+ if (spanParentAsLink) {
2265
+ headers["x-trigger-span-parent-as-link"] = "1";
2266
+ }
2267
+ }
2268
+ return headers;
2269
+ }, "#getHeaders");
2270
+ __name(_ApiClient, "ApiClient");
2271
+ var ApiClient = _ApiClient;
2272
+ function createSearchQueryForListRuns(query) {
2273
+ const searchParams = new URLSearchParams();
2274
+ if (query) {
2275
+ if (query.status) {
2276
+ searchParams.append("filter[status]", Array.isArray(query.status) ? query.status.join(",") : query.status);
2277
+ }
2278
+ if (query.taskIdentifier) {
2279
+ searchParams.append("filter[taskIdentifier]", Array.isArray(query.taskIdentifier) ? query.taskIdentifier.join(",") : query.taskIdentifier);
2280
+ }
2281
+ if (query.version) {
2282
+ searchParams.append("filter[version]", Array.isArray(query.version) ? query.version.join(",") : query.version);
2283
+ }
2284
+ if (query.bulkAction) {
2285
+ searchParams.append("filter[bulkAction]", query.bulkAction);
2286
+ }
2287
+ if (query.schedule) {
2288
+ searchParams.append("filter[schedule]", query.schedule);
2289
+ }
2290
+ if (typeof query.isTest === "boolean") {
2291
+ searchParams.append("filter[isTest]", String(query.isTest));
2292
+ }
2293
+ if (query.from) {
2294
+ searchParams.append("filter[createdAt][from]", query.from instanceof Date ? query.from.getTime().toString() : query.from.toString());
2295
+ }
2296
+ if (query.to) {
2297
+ searchParams.append("filter[createdAt][to]", query.to instanceof Date ? query.to.getTime().toString() : query.to.toString());
2298
+ }
2299
+ if (query.period) {
2300
+ searchParams.append("filter[createdAt][period]", query.period);
2301
+ }
2302
+ }
2303
+ return searchParams;
2304
+ }
2305
+ __name(createSearchQueryForListRuns, "createSearchQueryForListRuns");
2306
+ function mergeRequestOptions(defaultOptions, options) {
2307
+ if (!options) {
2308
+ return defaultOptions;
2309
+ }
2310
+ return {
2311
+ ...defaultOptions,
2312
+ ...options,
2313
+ retry: {
2314
+ ...defaultOptions.retry,
2315
+ ...options.retry
2316
+ }
2317
+ };
2318
+ }
2319
+ __name(mergeRequestOptions, "mergeRequestOptions");
2320
+
2321
+ // src/v3/apiClientManager/index.ts
2322
+ var API_NAME2 = "api-client";
2323
+ var _getConfig, getConfig_fn;
2324
+ var _APIClientManagerAPI = class _APIClientManagerAPI {
2325
+ constructor() {
2326
+ __privateAdd(this, _getConfig);
2327
+ }
2328
+ static getInstance() {
2329
+ if (!this._instance) {
2330
+ this._instance = new _APIClientManagerAPI();
2331
+ }
2332
+ return this._instance;
2333
+ }
2334
+ disable() {
2335
+ unregisterGlobal(API_NAME2);
2336
+ }
2337
+ setGlobalAPIClientConfiguration(config) {
2338
+ return registerGlobal(API_NAME2, config);
2339
+ }
2340
+ get baseURL() {
2341
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2342
+ return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
2343
+ }
2344
+ get accessToken() {
2345
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2346
+ return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY") ?? getEnvVar("TRIGGER_ACCESS_TOKEN");
2347
+ }
2348
+ get client() {
2349
+ if (!this.baseURL || !this.accessToken) {
2350
+ return void 0;
2351
+ }
2352
+ return new ApiClient(this.baseURL, this.accessToken);
2353
+ }
2354
+ };
2355
+ _getConfig = new WeakSet();
2356
+ getConfig_fn = /* @__PURE__ */ __name(function() {
2357
+ return getGlobal(API_NAME2);
2358
+ }, "#getConfig");
2359
+ __name(_APIClientManagerAPI, "APIClientManagerAPI");
2360
+ var APIClientManagerAPI = _APIClientManagerAPI;
2361
+
2362
+ // src/v3/apiClientManager-api.ts
2363
+ var apiClientManager = APIClientManagerAPI.getInstance();
2364
+
2365
+ // src/v3/utils/ioSerialization.ts
2366
+ async function parsePacket(value) {
2367
+ if (!value.data) {
2368
+ return void 0;
2369
+ }
2370
+ switch (value.dataType) {
2371
+ case "application/json":
2372
+ return JSON.parse(value.data);
2373
+ case "application/super+json":
2374
+ const { parse } = await loadSuperJSON();
2375
+ return parse(value.data);
2376
+ case "text/plain":
2377
+ return value.data;
2378
+ case "application/store":
2379
+ throw new Error(`Cannot parse an application/store packet (${value.data}). Needs to be imported first.`);
2380
+ default:
2381
+ return value.data;
2382
+ }
2383
+ }
2384
+ __name(parsePacket, "parsePacket");
2385
+ async function stringifyIO(value) {
2386
+ if (value === void 0) {
2387
+ return {
2388
+ dataType: "application/json"
2389
+ };
2390
+ }
2391
+ if (typeof value === "string") {
2392
+ return {
2393
+ data: value,
2394
+ dataType: "text/plain"
2395
+ };
2396
+ }
2397
+ try {
2398
+ const { stringify } = await loadSuperJSON();
2399
+ const data = stringify(value);
2400
+ return {
2401
+ data,
2402
+ dataType: "application/super+json"
2403
+ };
2404
+ } catch {
2405
+ return {
2406
+ data: value,
2407
+ dataType: "application/json"
2408
+ };
2409
+ }
2410
+ }
2411
+ __name(stringifyIO, "stringifyIO");
2412
+ async function conditionallyExportPacket(packet, pathPrefix, tracer) {
2413
+ if (apiClientManager.client) {
2414
+ const { needsOffloading, size } = packetRequiresOffloading(packet);
2415
+ if (needsOffloading) {
2416
+ if (!tracer) {
2417
+ return await exportPacket(packet, pathPrefix);
2418
+ } else {
2419
+ const result = await tracer.startActiveSpan("store.uploadOutput", async (span) => {
2420
+ return await exportPacket(packet, pathPrefix);
2421
+ }, {
2422
+ attributes: {
2423
+ byteLength: size,
2424
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-upload"
2425
+ }
2426
+ });
2427
+ return result ?? packet;
2428
+ }
2429
+ }
2430
+ }
2431
+ return packet;
2432
+ }
2433
+ __name(conditionallyExportPacket, "conditionallyExportPacket");
2434
+ function packetRequiresOffloading(packet, lengthLimit) {
2435
+ if (!packet.data) {
2436
+ return {
2437
+ needsOffloading: false,
2438
+ size: 0
2439
+ };
2440
+ }
2441
+ const byteSize = Buffer.byteLength(packet.data, "utf8");
2442
+ return {
2443
+ needsOffloading: byteSize >= (lengthLimit ?? OFFLOAD_IO_PACKET_LENGTH_LIMIT),
2444
+ size: byteSize
2445
+ };
2446
+ }
2447
+ __name(packetRequiresOffloading, "packetRequiresOffloading");
2448
+ async function exportPacket(packet, pathPrefix) {
2449
+ const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
2450
+ const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
2451
+ const uploadResponse = await fetch(presignedResponse.presignedUrl, {
2452
+ method: "PUT",
2453
+ headers: {
2454
+ "Content-Type": packet.dataType
2455
+ },
2456
+ body: packet.data
2457
+ });
2458
+ if (!uploadResponse.ok) {
2459
+ throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
2460
+ }
2461
+ return {
2462
+ data: filename,
2463
+ dataType: "application/store"
2464
+ };
2465
+ }
2466
+ __name(exportPacket, "exportPacket");
2467
+ async function conditionallyImportPacket(packet, tracer) {
2468
+ if (packet.dataType !== "application/store") {
2469
+ return packet;
2470
+ }
2471
+ if (!tracer) {
2472
+ return await importPacket(packet);
2473
+ } else {
2474
+ const result = await tracer.startActiveSpan("store.downloadPayload", async (span) => {
2475
+ return await importPacket(packet, span);
2476
+ }, {
2477
+ attributes: {
2478
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
2479
+ }
2480
+ });
2481
+ return result ?? packet;
2482
+ }
2483
+ }
2484
+ __name(conditionallyImportPacket, "conditionallyImportPacket");
2485
+ async function importPacket(packet, span) {
2486
+ if (!packet.data) {
2487
+ return packet;
2488
+ }
2489
+ if (!apiClientManager.client) {
2490
+ return packet;
2491
+ }
2492
+ const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
2493
+ const response = await fetch(presignedResponse.presignedUrl);
2494
+ if (!response.ok) {
2495
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
2496
+ }
2497
+ const data = await response.text();
2498
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
2499
+ return {
2500
+ data,
2501
+ dataType: response.headers.get("content-type") ?? "application/json"
2502
+ };
2503
+ }
2504
+ __name(importPacket, "importPacket");
2505
+ async function createPacketAttributes(packet, dataKey, dataTypeKey) {
2506
+ if (!packet.data) {
2507
+ return;
2508
+ }
2509
+ switch (packet.dataType) {
2510
+ case "application/json":
2511
+ return {
2512
+ ...flattenAttributes(packet, dataKey),
2513
+ [dataTypeKey]: packet.dataType
2514
+ };
2515
+ case "application/super+json":
2516
+ const { parse } = await loadSuperJSON();
2517
+ if (typeof packet.data === "undefined" || packet.data === null) {
2518
+ return;
2519
+ }
2520
+ try {
2521
+ const parsed = parse(packet.data);
2522
+ const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
2523
+ const result = {
2524
+ ...flattenAttributes(jsonified, dataKey),
2525
+ [dataTypeKey]: "application/json"
2526
+ };
2527
+ return result;
2528
+ } catch (e) {
2529
+ return;
2530
+ }
2531
+ case "application/store":
2532
+ return {
2533
+ [dataKey]: packet.data,
2534
+ [dataTypeKey]: packet.dataType
2535
+ };
2536
+ case "text/plain":
2537
+ return {
2538
+ [dataKey]: packet.data,
2539
+ [dataTypeKey]: packet.dataType
2540
+ };
2541
+ default:
2542
+ return;
2543
+ }
2544
+ }
2545
+ __name(createPacketAttributes, "createPacketAttributes");
2546
+ function safeReplacer(key, value) {
2547
+ if (typeof value === "bigint") {
2548
+ return value.toString();
2549
+ }
2550
+ if (value instanceof RegExp) {
2551
+ return value.toString();
2552
+ }
2553
+ if (value instanceof Set) {
2554
+ return Array.from(value);
2555
+ }
2556
+ if (value instanceof Map) {
2557
+ const obj = {};
2558
+ value.forEach((v, k) => {
2559
+ obj[k] = v;
2560
+ });
2561
+ return obj;
2562
+ }
2563
+ return value;
2564
+ }
2565
+ __name(safeReplacer, "safeReplacer");
2566
+ function getPacketExtension(outputType) {
2567
+ switch (outputType) {
2568
+ case "application/json":
2569
+ return "json";
2570
+ case "application/super+json":
2571
+ return "json";
2572
+ case "text/plain":
2573
+ return "txt";
2574
+ default:
2575
+ return "txt";
2576
+ }
2577
+ }
2578
+ __name(getPacketExtension, "getPacketExtension");
2579
+ async function loadSuperJSON() {
2580
+ return await import('superjson');
2581
+ }
2582
+ __name(loadSuperJSON, "loadSuperJSON");
2583
+
2584
+ // src/v3/workers/taskExecutor.ts
2585
+ var _callRun, callRun_fn, _callInitFunctions, callInitFunctions_fn, _callConfigInit, callConfigInit_fn, _callOnSuccessFunctions, callOnSuccessFunctions_fn, _callOnSuccessFunction, callOnSuccessFunction_fn, _callOnFailureFunctions, callOnFailureFunctions_fn, _callOnFailureFunction, callOnFailureFunction_fn, _callOnStartFunctions, callOnStartFunctions_fn, _callOnStartFunction, callOnStartFunction_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
2586
+ var _TaskExecutor = class _TaskExecutor {
2587
+ constructor(task, options) {
2588
+ __privateAdd(this, _callRun);
2589
+ __privateAdd(this, _callInitFunctions);
2590
+ __privateAdd(this, _callConfigInit);
2591
+ __privateAdd(this, _callOnSuccessFunctions);
2592
+ __privateAdd(this, _callOnSuccessFunction);
2593
+ __privateAdd(this, _callOnFailureFunctions);
2594
+ __privateAdd(this, _callOnFailureFunction);
2595
+ __privateAdd(this, _callOnStartFunctions);
2596
+ __privateAdd(this, _callOnStartFunction);
2597
+ __privateAdd(this, _callTaskCleanup);
2598
+ __privateAdd(this, _handleError);
2599
+ this.task = task;
2600
+ this._tracingSDK = options.tracingSDK;
2601
+ this._tracer = options.tracer;
2602
+ this._consoleInterceptor = options.consoleInterceptor;
2603
+ this._config = options.projectConfig;
2604
+ this._importedConfig = options.importedConfig;
2605
+ this._handleErrorFn = options.handleErrorFn;
2606
+ }
2607
+ async execute(execution, worker, traceContext, usage2) {
2608
+ const ctx = TaskRunContext.parse(execution);
2609
+ const attemptMessage = `Attempt ${execution.attempt.number}`;
2610
+ const originalPacket = {
2611
+ data: execution.run.payload,
2612
+ dataType: execution.run.payloadType
2613
+ };
2614
+ taskContext.setGlobalTaskContext({
2615
+ ctx,
2616
+ worker
2617
+ });
2618
+ this._tracingSDK.asyncResourceDetector.resolveWithAttributes({
2619
+ ...taskContext.attributes,
2620
+ [SemanticInternalAttributes.SDK_VERSION]: this.task.packageVersion,
2621
+ [SemanticInternalAttributes.SDK_LANGUAGE]: "typescript"
2622
+ });
2623
+ const result = await this._tracer.startActiveSpan(attemptMessage, async (span) => {
2624
+ return await this._consoleInterceptor.intercept(console, async () => {
2625
+ let parsedPayload;
2626
+ let initOutput;
2627
+ try {
2628
+ const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
2629
+ parsedPayload = await parsePacket(payloadPacket);
2630
+ if (execution.attempt.number === 1) {
2631
+ await __privateMethod(this, _callOnStartFunctions, callOnStartFunctions_fn).call(this, parsedPayload, ctx);
2632
+ }
2633
+ initOutput = await __privateMethod(this, _callInitFunctions, callInitFunctions_fn).call(this, parsedPayload, ctx);
2634
+ const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
2635
+ await __privateMethod(this, _callOnSuccessFunctions, callOnSuccessFunctions_fn).call(this, parsedPayload, output, ctx, initOutput);
2636
+ try {
2637
+ const stringifiedOutput = await stringifyIO(output);
2638
+ const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
2639
+ const attributes = await createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE);
2640
+ if (attributes) {
2641
+ span.setAttributes(attributes);
2642
+ }
2643
+ return {
2644
+ ok: true,
2645
+ id: execution.run.id,
2646
+ output: finalOutput.data,
2647
+ outputType: finalOutput.dataType
2648
+ };
2649
+ } catch (stringifyError) {
2650
+ recordSpanException(span, stringifyError);
2651
+ return {
2652
+ ok: false,
2653
+ id: execution.run.id,
2654
+ error: {
2655
+ type: "INTERNAL_ERROR",
2656
+ code: TaskRunErrorCodes.TASK_OUTPUT_ERROR,
2657
+ message: stringifyError instanceof Error ? stringifyError.message : typeof stringifyError === "string" ? stringifyError : void 0
2658
+ }
2659
+ };
2660
+ }
2661
+ } catch (runError) {
2662
+ try {
2663
+ const handleErrorResult = await __privateMethod(this, _handleError, handleError_fn).call(this, execution, runError, parsedPayload, ctx);
2664
+ recordSpanException(span, handleErrorResult.error ?? runError);
2665
+ if (handleErrorResult.status !== "retry") {
2666
+ await __privateMethod(this, _callOnFailureFunctions, callOnFailureFunctions_fn).call(this, parsedPayload, handleErrorResult.error ?? runError, ctx, initOutput);
2667
+ }
2668
+ return {
2669
+ id: execution.run.id,
2670
+ ok: false,
2671
+ error: sanitizeError(handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError)),
2672
+ retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
2673
+ skippedRetrying: handleErrorResult.status === "skipped"
2674
+ };
2675
+ } catch (handleErrorError) {
2676
+ recordSpanException(span, handleErrorError);
2677
+ return {
2678
+ ok: false,
2679
+ id: execution.run.id,
2680
+ error: {
2681
+ type: "INTERNAL_ERROR",
2682
+ code: TaskRunErrorCodes.HANDLE_ERROR_ERROR,
2683
+ message: handleErrorError instanceof Error ? handleErrorError.message : typeof handleErrorError === "string" ? handleErrorError : void 0
2684
+ }
2685
+ };
2686
+ }
2687
+ } finally {
2688
+ await __privateMethod(this, _callTaskCleanup, callTaskCleanup_fn).call(this, parsedPayload, ctx, initOutput);
2689
+ }
2690
+ });
2691
+ }, {
2692
+ kind: api.SpanKind.CONSUMER,
2693
+ attributes: {
2694
+ [SemanticInternalAttributes.STYLE_ICON]: "attempt",
2695
+ ...accessoryAttributes({
2696
+ items: [
2697
+ {
2698
+ text: ctx.task.filePath
2699
+ },
2700
+ {
2701
+ text: `${ctx.task.exportName}.run()`
2702
+ }
2703
+ ],
2704
+ style: "codepath"
2705
+ })
2706
+ }
2707
+ }, this._tracer.extractContext(traceContext));
2708
+ return {
2709
+ result
2710
+ };
2711
+ }
2712
+ };
2713
+ _callRun = new WeakSet();
2714
+ callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
2715
+ const runFn = this.task.fns.run;
2716
+ const middlewareFn = this.task.fns.middleware;
2717
+ if (!runFn) {
2718
+ throw new Error("Task does not have a run function");
2719
+ }
2720
+ if (!middlewareFn) {
2721
+ return runFn(payload, {
2722
+ ctx,
2723
+ init
2724
+ });
2725
+ }
2726
+ return middlewareFn(payload, {
2727
+ ctx,
2728
+ next: async () => runFn(payload, {
2729
+ ctx,
2730
+ init
2731
+ })
2732
+ });
2733
+ }, "#callRun");
2734
+ _callInitFunctions = new WeakSet();
2735
+ callInitFunctions_fn = /* @__PURE__ */ __name(async function(payload1, ctx1) {
2736
+ await __privateMethod(this, _callConfigInit, callConfigInit_fn).call(this, payload1, ctx1);
2737
+ const initFn = this.task.fns.init;
2738
+ if (!initFn) {
2739
+ return {};
2740
+ }
2741
+ return this._tracer.startActiveSpan("init", async (span) => {
2742
+ return await initFn(payload1, {
2743
+ ctx: ctx1
2744
+ });
2745
+ }, {
2746
+ attributes: {
2747
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2748
+ }
2749
+ });
2750
+ }, "#callInitFunctions");
2751
+ _callConfigInit = new WeakSet();
2752
+ callConfigInit_fn = /* @__PURE__ */ __name(async function(payload2, ctx2) {
2753
+ const initFn = this._importedConfig?.init;
2754
+ if (!initFn) {
2755
+ return {};
2756
+ }
2757
+ return this._tracer.startActiveSpan("config.init", async (span) => {
2758
+ return await initFn(payload2, {
2759
+ ctx: ctx2
2760
+ });
2761
+ }, {
2762
+ attributes: {
2763
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2764
+ }
2765
+ });
2766
+ }, "#callConfigInit");
2767
+ _callOnSuccessFunctions = new WeakSet();
2768
+ callOnSuccessFunctions_fn = /* @__PURE__ */ __name(async function(payload3, output, ctx3, initOutput) {
2769
+ await __privateMethod(this, _callOnSuccessFunction, callOnSuccessFunction_fn).call(this, this.task.fns.onSuccess, "task.onSuccess", payload3, output, ctx3, initOutput);
2770
+ await __privateMethod(this, _callOnSuccessFunction, callOnSuccessFunction_fn).call(this, this._importedConfig?.onSuccess, "config.onSuccess", payload3, output, ctx3, initOutput);
2771
+ }, "#callOnSuccessFunctions");
2772
+ _callOnSuccessFunction = new WeakSet();
2773
+ callOnSuccessFunction_fn = /* @__PURE__ */ __name(async function(onSuccessFn, name, payload4, output1, ctx4, initOutput1) {
2774
+ if (!onSuccessFn) {
2775
+ return;
2776
+ }
2777
+ try {
2778
+ await this._tracer.startActiveSpan(name, async (span) => {
2779
+ return await onSuccessFn(payload4, output1, {
2780
+ ctx: ctx4,
2781
+ init: initOutput1
2782
+ });
2783
+ }, {
2784
+ attributes: {
2785
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2786
+ }
2787
+ });
2788
+ } catch {
2789
+ }
2790
+ }, "#callOnSuccessFunction");
2791
+ _callOnFailureFunctions = new WeakSet();
2792
+ callOnFailureFunctions_fn = /* @__PURE__ */ __name(async function(payload5, error, ctx5, initOutput2) {
2793
+ await __privateMethod(this, _callOnFailureFunction, callOnFailureFunction_fn).call(this, this.task.fns.onFailure, "task.onFailure", payload5, error, ctx5, initOutput2);
2794
+ await __privateMethod(this, _callOnFailureFunction, callOnFailureFunction_fn).call(this, this._importedConfig?.onFailure, "config.onFailure", payload5, error, ctx5, initOutput2);
2795
+ }, "#callOnFailureFunctions");
2796
+ _callOnFailureFunction = new WeakSet();
2797
+ callOnFailureFunction_fn = /* @__PURE__ */ __name(async function(onFailureFn, name1, payload6, error1, ctx6, initOutput3) {
2798
+ if (!onFailureFn) {
2799
+ return;
2800
+ }
2801
+ try {
2802
+ return await this._tracer.startActiveSpan(name1, async (span) => {
2803
+ return await onFailureFn(payload6, error1, {
2804
+ ctx: ctx6,
2805
+ init: initOutput3
2806
+ });
2807
+ }, {
2808
+ attributes: {
2809
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2810
+ }
2811
+ });
2812
+ } catch (e) {
2813
+ }
2814
+ }, "#callOnFailureFunction");
2815
+ _callOnStartFunctions = new WeakSet();
2816
+ callOnStartFunctions_fn = /* @__PURE__ */ __name(async function(payload7, ctx7) {
2817
+ await __privateMethod(this, _callOnStartFunction, callOnStartFunction_fn).call(this, this._importedConfig?.onStart, "config.onStart", payload7, ctx7, {});
2818
+ await __privateMethod(this, _callOnStartFunction, callOnStartFunction_fn).call(this, this.task.fns.onStart, "task.onStart", payload7, ctx7, {});
2819
+ }, "#callOnStartFunctions");
2820
+ _callOnStartFunction = new WeakSet();
2821
+ callOnStartFunction_fn = /* @__PURE__ */ __name(async function(onStartFn, name2, payload8, ctx8, initOutput4) {
2822
+ if (!onStartFn) {
2823
+ return;
2824
+ }
2825
+ try {
2826
+ await this._tracer.startActiveSpan(name2, async (span) => {
2827
+ return await onStartFn(payload8, {
2828
+ ctx: ctx8
2829
+ });
2830
+ }, {
2831
+ attributes: {
2832
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2833
+ }
2834
+ });
2835
+ } catch {
2836
+ }
2837
+ }, "#callOnStartFunction");
2838
+ _callTaskCleanup = new WeakSet();
2839
+ callTaskCleanup_fn = /* @__PURE__ */ __name(async function(payload9, ctx9, init1) {
2840
+ const cleanupFn = this.task.fns.cleanup;
2841
+ if (!cleanupFn) {
2842
+ return;
2843
+ }
2844
+ return this._tracer.startActiveSpan("cleanup", async (span) => {
2845
+ return await cleanupFn(payload9, {
2846
+ ctx: ctx9,
2847
+ init: init1
2848
+ });
2849
+ });
2850
+ }, "#callTaskCleanup");
2851
+ _handleError = new WeakSet();
2852
+ handleError_fn = /* @__PURE__ */ __name(async function(execution, error2, payload10, ctx10) {
2853
+ const retriesConfig = this._importedConfig?.retries ?? this._config.retries;
2854
+ const retry = this.task.retry ?? retriesConfig?.default;
2855
+ if (!retry) {
2856
+ return {
2857
+ status: "noop"
2858
+ };
2859
+ }
2860
+ if (error2 instanceof Error && error2.name === "AbortTaskRunError") {
2861
+ return {
2862
+ status: "skipped"
2863
+ };
2864
+ }
2865
+ if (execution.run.maxAttempts) {
2866
+ retry.maxAttempts = Math.max(execution.run.maxAttempts, 1);
2867
+ }
2868
+ let delay = calculateNextRetryDelay(retry, execution.attempt.number);
2869
+ if (delay && error2 instanceof Error && error2.name === "TriggerApiError" && error2.status === 429) {
2870
+ const rateLimitError = error2;
2871
+ delay = rateLimitError.millisecondsUntilReset;
2872
+ }
2873
+ if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
2874
+ return {
2875
+ status: "skipped"
2876
+ };
2877
+ }
2878
+ return this._tracer.startActiveSpan("handleError()", async (span) => {
2879
+ const handleErrorResult = this.task.fns.handleError ? await this.task.fns.handleError(payload10, error2, {
2880
+ ctx: ctx10,
2881
+ retry,
2882
+ retryDelayInMs: delay,
2883
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
2884
+ }) : this._importedConfig ? await this._handleErrorFn?.(payload10, error2, {
2885
+ ctx: ctx10,
2886
+ retry,
2887
+ retryDelayInMs: delay,
2888
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
2889
+ }) : void 0;
2890
+ if (!handleErrorResult) {
2891
+ return typeof delay === "undefined" ? {
2892
+ status: "noop"
2893
+ } : {
2894
+ status: "retry",
2895
+ retry: {
2896
+ timestamp: Date.now() + delay,
2897
+ delay
2898
+ }
2899
+ };
2900
+ }
2901
+ if (handleErrorResult.skipRetrying) {
2902
+ return {
2903
+ status: "skipped",
2904
+ error: handleErrorResult.error
2905
+ };
2906
+ }
2907
+ if (typeof handleErrorResult.retryAt !== "undefined") {
2908
+ return {
2909
+ status: "retry",
2910
+ retry: {
2911
+ timestamp: handleErrorResult.retryAt.getTime(),
2912
+ delay: handleErrorResult.retryAt.getTime() - Date.now()
2913
+ },
2914
+ error: handleErrorResult.error
2915
+ };
2916
+ }
2917
+ if (typeof handleErrorResult.retryDelayInMs === "number") {
2918
+ return {
2919
+ status: "retry",
2920
+ retry: {
2921
+ timestamp: Date.now() + handleErrorResult.retryDelayInMs,
2922
+ delay: handleErrorResult.retryDelayInMs
2923
+ },
2924
+ error: handleErrorResult.error
2925
+ };
2926
+ }
2927
+ if (handleErrorResult.retry && typeof handleErrorResult.retry === "object") {
2928
+ const delay2 = calculateNextRetryDelay(handleErrorResult.retry, execution.attempt.number);
2929
+ return typeof delay2 === "undefined" ? {
2930
+ status: "noop",
2931
+ error: handleErrorResult.error
2932
+ } : {
2933
+ status: "retry",
2934
+ retry: {
2935
+ timestamp: Date.now() + delay2,
2936
+ delay: delay2
2937
+ },
2938
+ error: handleErrorResult.error
2939
+ };
2940
+ }
2941
+ return {
2942
+ status: "noop",
2943
+ error: handleErrorResult.error
2944
+ };
2945
+ }, {
2946
+ attributes: {
2947
+ [SemanticInternalAttributes.STYLE_ICON]: "exclamation-circle"
2948
+ }
2949
+ });
2950
+ }, "#handleError");
2951
+ __name(_TaskExecutor, "TaskExecutor");
2952
+ var TaskExecutor = _TaskExecutor;
2953
+ var _originClockTime, originClockTime_get, _originPreciseDate, originPreciseDate_get;
2954
+ var _PreciseWallClock = class _PreciseWallClock {
2955
+ constructor(options = {}) {
2956
+ __privateAdd(this, _originClockTime);
2957
+ __privateAdd(this, _originPreciseDate);
2958
+ this._origin = {
2959
+ clockTime: options.origin ?? process.hrtime(),
2960
+ preciseDate: options.now ?? new preciseDate.PreciseDate()
2961
+ };
2962
+ }
2963
+ preciseNow() {
2964
+ const elapsedHrTime = process.hrtime(__privateGet(this, _originClockTime, originClockTime_get));
2965
+ const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
2966
+ const preciseDate$1 = new preciseDate.PreciseDate(__privateGet(this, _originPreciseDate, originPreciseDate_get).getFullTime() + elapsedNanoseconds);
2967
+ const dateStruct = preciseDate$1.toStruct();
2968
+ return [
2969
+ dateStruct.seconds,
2970
+ dateStruct.nanos
2971
+ ];
2972
+ }
2973
+ reset() {
2974
+ this._origin = {
2975
+ clockTime: process.hrtime(),
2976
+ preciseDate: new preciseDate.PreciseDate()
2977
+ };
2978
+ }
2979
+ };
2980
+ _originClockTime = new WeakSet();
2981
+ originClockTime_get = /* @__PURE__ */ __name(function() {
2982
+ return this._origin.clockTime;
2983
+ }, "#originClockTime");
2984
+ _originPreciseDate = new WeakSet();
2985
+ originPreciseDate_get = /* @__PURE__ */ __name(function() {
2986
+ return this._origin.preciseDate;
2987
+ }, "#originPreciseDate");
2988
+ __name(_PreciseWallClock, "PreciseWallClock");
2989
+ var PreciseWallClock = _PreciseWallClock;
2990
+ function iconStringForSeverity(severityNumber) {
2991
+ switch (severityNumber) {
2992
+ case apiLogs.SeverityNumber.UNSPECIFIED:
2993
+ return void 0;
2994
+ case apiLogs.SeverityNumber.TRACE:
2995
+ case apiLogs.SeverityNumber.TRACE2:
2996
+ case apiLogs.SeverityNumber.TRACE3:
2997
+ case apiLogs.SeverityNumber.TRACE4:
2998
+ return "trace";
2999
+ case apiLogs.SeverityNumber.DEBUG:
3000
+ case apiLogs.SeverityNumber.DEBUG2:
3001
+ case apiLogs.SeverityNumber.DEBUG3:
3002
+ case apiLogs.SeverityNumber.DEBUG4:
3003
+ return "debug";
3004
+ case apiLogs.SeverityNumber.INFO:
3005
+ case apiLogs.SeverityNumber.INFO2:
3006
+ case apiLogs.SeverityNumber.INFO3:
3007
+ case apiLogs.SeverityNumber.INFO4:
3008
+ return "info";
3009
+ case apiLogs.SeverityNumber.WARN:
3010
+ case apiLogs.SeverityNumber.WARN2:
3011
+ case apiLogs.SeverityNumber.WARN3:
3012
+ case apiLogs.SeverityNumber.WARN4:
3013
+ return "warn";
3014
+ case apiLogs.SeverityNumber.ERROR:
3015
+ case apiLogs.SeverityNumber.ERROR2:
3016
+ case apiLogs.SeverityNumber.ERROR3:
3017
+ case apiLogs.SeverityNumber.ERROR4:
3018
+ return "error";
3019
+ case apiLogs.SeverityNumber.FATAL:
3020
+ case apiLogs.SeverityNumber.FATAL2:
3021
+ case apiLogs.SeverityNumber.FATAL3:
3022
+ case apiLogs.SeverityNumber.FATAL4:
3023
+ return "fatal";
3024
+ }
3025
+ }
3026
+ __name(iconStringForSeverity, "iconStringForSeverity");
3027
+ var _SimpleClock = class _SimpleClock {
3028
+ preciseNow() {
3029
+ const now = new preciseDate.PreciseDate();
3030
+ const nowStruct = now.toStruct();
3031
+ return [
3032
+ nowStruct.seconds,
3033
+ nowStruct.nanos
3034
+ ];
3035
+ }
3036
+ reset() {
3037
+ }
3038
+ };
3039
+ __name(_SimpleClock, "SimpleClock");
3040
+ var SimpleClock = _SimpleClock;
3041
+
3042
+ // src/v3/clock/index.ts
3043
+ var API_NAME3 = "clock";
3044
+ var SIMPLE_CLOCK = new SimpleClock();
3045
+ var _getClock, getClock_fn;
3046
+ var _ClockAPI = class _ClockAPI {
3047
+ constructor() {
3048
+ __privateAdd(this, _getClock);
3049
+ }
3050
+ static getInstance() {
3051
+ if (!this._instance) {
3052
+ this._instance = new _ClockAPI();
3053
+ }
3054
+ return this._instance;
3055
+ }
3056
+ setGlobalClock(clock2) {
3057
+ return registerGlobal(API_NAME3, clock2);
3058
+ }
3059
+ preciseNow() {
3060
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
3061
+ }
3062
+ reset() {
3063
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
3064
+ }
3065
+ };
3066
+ _getClock = new WeakSet();
3067
+ getClock_fn = /* @__PURE__ */ __name(function() {
3068
+ return getGlobal(API_NAME3) ?? SIMPLE_CLOCK;
3069
+ }, "#getClock");
3070
+ __name(_ClockAPI, "ClockAPI");
3071
+ var ClockAPI = _ClockAPI;
3072
+
3073
+ // src/v3/clock-api.ts
3074
+ var clock = ClockAPI.getInstance();
3075
+
3076
+ // src/v3/logger/taskLogger.ts
3077
+ var logLevels = [
3078
+ "none",
3079
+ "error",
3080
+ "warn",
3081
+ "info",
3082
+ "debug"
3083
+ ];
3084
+ var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
3085
+ var _OtelTaskLogger = class _OtelTaskLogger {
3086
+ constructor(_config) {
3087
+ __privateAdd(this, _emitLog);
3088
+ __privateAdd(this, _getTimestampInHrTime);
3089
+ this._config = _config;
3090
+ this._level = logLevels.indexOf(_config.level);
3091
+ }
3092
+ debug(message, properties) {
3093
+ if (this._level < 4)
3094
+ return;
3095
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", apiLogs.SeverityNumber.DEBUG, properties);
3096
+ }
3097
+ log(message, properties) {
3098
+ if (this._level < 3)
3099
+ return;
3100
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", apiLogs.SeverityNumber.INFO, properties);
3101
+ }
3102
+ info(message, properties) {
3103
+ if (this._level < 3)
3104
+ return;
3105
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", apiLogs.SeverityNumber.INFO, properties);
3106
+ }
3107
+ warn(message, properties) {
3108
+ if (this._level < 2)
3109
+ return;
3110
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", apiLogs.SeverityNumber.WARN, properties);
3111
+ }
3112
+ error(message, properties) {
3113
+ if (this._level < 1)
3114
+ return;
3115
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", apiLogs.SeverityNumber.ERROR, properties);
3116
+ }
3117
+ trace(name, fn, options) {
3118
+ return this._config.tracer.startActiveSpan(name, fn, options);
3119
+ }
3120
+ };
3121
+ _emitLog = new WeakSet();
3122
+ emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
3123
+ let attributes = {
3124
+ ...flattenAttributes(safeJsonProcess(properties))
3125
+ };
3126
+ const icon = iconStringForSeverity(severityNumber);
3127
+ if (icon !== void 0) {
3128
+ attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
3129
+ }
3130
+ this._config.logger.emit({
3131
+ severityNumber,
3132
+ severityText,
3133
+ body: message,
3134
+ attributes,
3135
+ timestamp
3136
+ });
3137
+ }, "#emitLog");
3138
+ _getTimestampInHrTime = new WeakSet();
3139
+ getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
3140
+ return clock.preciseNow();
3141
+ }, "#getTimestampInHrTime");
3142
+ __name(_OtelTaskLogger, "OtelTaskLogger");
3143
+ var OtelTaskLogger = _OtelTaskLogger;
3144
+ function safeJsonProcess(value) {
3145
+ try {
3146
+ return JSON.parse(JSON.stringify(value, jsonErrorReplacer));
3147
+ } catch {
3148
+ return value;
3149
+ }
3150
+ }
3151
+ __name(safeJsonProcess, "safeJsonProcess");
3152
+ function jsonErrorReplacer(key, value) {
3153
+ if (value instanceof Error) {
3154
+ return {
3155
+ name: value.name,
3156
+ message: value.message,
3157
+ stack: value.stack
3158
+ };
3159
+ }
3160
+ return value;
3161
+ }
3162
+ __name(jsonErrorReplacer, "jsonErrorReplacer");
3163
+ var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
3164
+ var _ConsoleInterceptor = class _ConsoleInterceptor {
3165
+ constructor(logger, sendToStdIO) {
3166
+ __privateAdd(this, _handleLog);
3167
+ __privateAdd(this, _getTimestampInHrTime2);
3168
+ __privateAdd(this, _getAttributes);
3169
+ this.logger = logger;
3170
+ this.sendToStdIO = sendToStdIO;
3171
+ }
3172
+ // Intercept the console and send logs to the OpenTelemetry logger
3173
+ // during the execution of the callback
3174
+ async intercept(console2, callback) {
3175
+ const originalConsole = {
3176
+ log: console2.log,
3177
+ info: console2.info,
3178
+ warn: console2.warn,
3179
+ error: console2.error,
3180
+ debug: console2.debug
3181
+ };
3182
+ console2.log = this.log.bind(this);
3183
+ console2.info = this.info.bind(this);
3184
+ console2.warn = this.warn.bind(this);
3185
+ console2.error = this.error.bind(this);
3186
+ console2.debug = this.debug.bind(this);
3187
+ try {
3188
+ return await callback();
3189
+ } finally {
3190
+ console2.log = originalConsole.log;
3191
+ console2.info = originalConsole.info;
3192
+ console2.warn = originalConsole.warn;
3193
+ console2.error = originalConsole.error;
3194
+ console2.debug = originalConsole.debug;
3195
+ }
3196
+ }
3197
+ debug(...args) {
3198
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
3199
+ }
3200
+ log(...args) {
3201
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
3202
+ }
3203
+ info(...args) {
3204
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
3205
+ }
3206
+ warn(...args) {
3207
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
3208
+ }
3209
+ error(...args) {
3210
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
3211
+ }
3212
+ };
3213
+ _handleLog = new WeakSet();
3214
+ handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
3215
+ const body = util__default.default.format(...args);
3216
+ if (this.sendToStdIO) {
3217
+ if (severityNumber === apiLogs.SeverityNumber.ERROR) {
3218
+ process.stderr.write(body);
3219
+ } else {
3220
+ process.stdout.write(body);
3221
+ }
3222
+ }
3223
+ const parsed = tryParseJSON(body);
3224
+ if (parsed.ok) {
3225
+ this.logger.emit({
3226
+ severityNumber,
3227
+ severityText,
3228
+ body: getLogMessage(parsed.value, severityText),
3229
+ attributes: {
3230
+ ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3231
+ ...flattenAttributes(parsed.value)
3232
+ },
3233
+ timestamp
3234
+ });
3235
+ return;
3236
+ }
3237
+ this.logger.emit({
3238
+ severityNumber,
3239
+ severityText,
3240
+ body,
3241
+ attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3242
+ timestamp
3243
+ });
3244
+ }, "#handleLog");
3245
+ _getTimestampInHrTime2 = new WeakSet();
3246
+ getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
3247
+ return clock.preciseNow();
3248
+ }, "#getTimestampInHrTime");
3249
+ _getAttributes = new WeakSet();
3250
+ getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
3251
+ const icon = iconStringForSeverity(severityNumber1);
3252
+ let result = {};
3253
+ if (icon !== void 0) {
3254
+ result[SemanticInternalAttributes.STYLE_ICON] = icon;
3255
+ }
3256
+ return result;
3257
+ }, "#getAttributes");
3258
+ __name(_ConsoleInterceptor, "ConsoleInterceptor");
3259
+ var ConsoleInterceptor = _ConsoleInterceptor;
3260
+ function getLogMessage(value, fallback) {
3261
+ if (typeof value["message"] === "string") {
3262
+ return value["message"];
3263
+ }
3264
+ if (typeof value["msg"] === "string") {
3265
+ return value["msg"];
3266
+ }
3267
+ if (typeof value["body"] === "string") {
3268
+ return value["body"];
3269
+ }
3270
+ if (typeof value["error"] === "string") {
3271
+ return value["error"];
3272
+ }
3273
+ return fallback;
3274
+ }
3275
+ __name(getLogMessage, "getLogMessage");
3276
+ function tryParseJSON(value) {
3277
+ try {
3278
+ const parsed = JSON.parse(value);
3279
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
3280
+ return {
3281
+ ok: true,
3282
+ value: parsed
3283
+ };
3284
+ }
3285
+ return {
3286
+ ok: false,
3287
+ value
3288
+ };
3289
+ } catch (e) {
3290
+ return {
3291
+ ok: false,
3292
+ value
3293
+ };
3294
+ }
3295
+ }
3296
+ __name(tryParseJSON, "tryParseJSON");
3297
+
3298
+ // src/v3/task-catalog/standardTaskCatalog.ts
3299
+ var _StandardTaskCatalog = class _StandardTaskCatalog {
3300
+ constructor() {
3301
+ __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
3302
+ __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
3303
+ __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
3304
+ }
3305
+ registerTaskMetadata(task) {
3306
+ const { fns, ...metadata } = task;
3307
+ this._taskMetadata.set(task.id, metadata);
3308
+ this._taskFunctions.set(task.id, fns);
3309
+ }
3310
+ updateTaskMetadata(id, updates) {
3311
+ const existingMetadata = this._taskMetadata.get(id);
3312
+ if (existingMetadata) {
3313
+ this._taskMetadata.set(id, {
3314
+ ...existingMetadata,
3315
+ ...updates
3316
+ });
3317
+ }
3318
+ if (updates.fns) {
3319
+ const existingFunctions = this._taskFunctions.get(id);
3320
+ if (existingFunctions) {
3321
+ this._taskFunctions.set(id, {
3322
+ ...existingFunctions,
3323
+ ...updates.fns
3324
+ });
3325
+ }
3326
+ }
3327
+ }
3328
+ registerTaskFileMetadata(id, metadata) {
3329
+ this._taskFileMetadata.set(id, metadata);
3330
+ }
3331
+ // Return all the tasks, without the functions
3332
+ getAllTaskMetadata() {
3333
+ const result = [];
3334
+ for (const [id, metadata] of this._taskMetadata) {
3335
+ const fileMetadata = this._taskFileMetadata.get(id);
3336
+ if (!fileMetadata) {
3337
+ continue;
3338
+ }
3339
+ result.push({
3340
+ ...metadata,
3341
+ ...fileMetadata
3342
+ });
3343
+ }
3344
+ return result;
3345
+ }
3346
+ getTaskMetadata(id) {
3347
+ const metadata = this._taskMetadata.get(id);
3348
+ const fileMetadata = this._taskFileMetadata.get(id);
3349
+ if (!metadata || !fileMetadata) {
3350
+ return void 0;
3351
+ }
3352
+ return {
3353
+ ...metadata,
3354
+ ...fileMetadata
3355
+ };
3356
+ }
3357
+ getTask(id) {
3358
+ const metadata = this._taskMetadata.get(id);
3359
+ const fileMetadata = this._taskFileMetadata.get(id);
3360
+ const fns = this._taskFunctions.get(id);
3361
+ if (!metadata || !fns || !fileMetadata) {
3362
+ return void 0;
3363
+ }
3364
+ return {
3365
+ ...metadata,
3366
+ ...fileMetadata,
3367
+ fns
3368
+ };
3369
+ }
3370
+ taskExists(id) {
3371
+ return this._taskMetadata.has(id);
3372
+ }
3373
+ disable() {
3374
+ }
3375
+ };
3376
+ __name(_StandardTaskCatalog, "StandardTaskCatalog");
3377
+ var StandardTaskCatalog = _StandardTaskCatalog;
3378
+
3379
+ // src/v3/usage/noopUsageManager.ts
3380
+ var _NoopUsageManager = class _NoopUsageManager {
3381
+ disable() {
3382
+ }
3383
+ start() {
3384
+ return {
3385
+ sample: () => ({
3386
+ cpuTime: 0,
3387
+ wallTime: 0
3388
+ })
3389
+ };
3390
+ }
3391
+ stop(measurement) {
3392
+ return measurement.sample();
3393
+ }
3394
+ pauseAsync(cb) {
3395
+ return cb();
3396
+ }
3397
+ sample() {
3398
+ return void 0;
3399
+ }
3400
+ };
3401
+ __name(_NoopUsageManager, "NoopUsageManager");
3402
+ var NoopUsageManager = _NoopUsageManager;
3403
+
3404
+ // src/v3/usage/api.ts
3405
+ var API_NAME4 = "usage";
3406
+ var NOOP_USAGE_MANAGER = new NoopUsageManager();
3407
+ var _getUsageManager, getUsageManager_fn;
3408
+ var _UsageAPI = class _UsageAPI {
3409
+ constructor() {
3410
+ __privateAdd(this, _getUsageManager);
3411
+ }
3412
+ static getInstance() {
3413
+ if (!this._instance) {
3414
+ this._instance = new _UsageAPI();
3415
+ }
3416
+ return this._instance;
3417
+ }
3418
+ setGlobalUsageManager(manager) {
3419
+ return registerGlobal(API_NAME4, manager);
3420
+ }
3421
+ disable() {
3422
+ __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).disable();
3423
+ unregisterGlobal(API_NAME4);
3424
+ }
3425
+ start() {
3426
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).start();
3427
+ }
3428
+ stop(measurement) {
3429
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).stop(measurement);
3430
+ }
3431
+ pauseAsync(cb) {
3432
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).pauseAsync(cb);
3433
+ }
3434
+ sample() {
3435
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).sample();
3436
+ }
3437
+ };
3438
+ _getUsageManager = new WeakSet();
3439
+ getUsageManager_fn = /* @__PURE__ */ __name(function() {
3440
+ return getGlobal(API_NAME4) ?? NOOP_USAGE_MANAGER;
3441
+ }, "#getUsageManager");
3442
+ __name(_UsageAPI, "UsageAPI");
3443
+ var UsageAPI = _UsageAPI;
3444
+
3445
+ // src/v3/usage-api.ts
3446
+ var usage = UsageAPI.getInstance();
3447
+
3448
+ // src/v3/clock/clock.ts
3449
+ function calculateDurationInMs(start, end) {
3450
+ const [startSeconds, startNanoseconds] = start;
3451
+ const [endSeconds, endNanoseconds] = end;
3452
+ const seconds = endSeconds - startSeconds;
3453
+ const nanoseconds = endNanoseconds - startNanoseconds;
3454
+ return Math.floor(seconds * 1e3 + nanoseconds / 1e6);
3455
+ }
3456
+ __name(calculateDurationInMs, "calculateDurationInMs");
3457
+
3458
+ // src/v3/usage/devUsageManager.ts
3459
+ var _a2;
3460
+ var DevUsageMeasurement = (_a2 = class {
3461
+ constructor(id, startedAt = clock.preciseNow()) {
3462
+ this.id = id;
3463
+ this.startedAt = startedAt;
3464
+ this._pauses = /* @__PURE__ */ new Map();
3465
+ }
3466
+ stop() {
3467
+ this._endedAt = clock.preciseNow();
3468
+ }
3469
+ sample() {
3470
+ const endedAt = this._endedAt ?? clock.preciseNow();
3471
+ const wallTime = this.startedAt ? calculateDurationInMs(this.startedAt, endedAt) : 0;
3472
+ if (wallTime === 0) {
3473
+ return {
3474
+ cpuTime: 0,
3475
+ wallTime: 0
3476
+ };
3477
+ }
3478
+ const totalPauses = Array.from(this._pauses.values()).reduce((total, pause) => {
3479
+ return total + calculateDurationInMs(pause.start, pause.end ?? endedAt);
3480
+ }, 0);
3481
+ const cpuTime = wallTime - totalPauses;
3482
+ return {
3483
+ wallTime,
3484
+ cpuTime
3485
+ };
3486
+ }
3487
+ registerPause(pauseId, start, end) {
3488
+ this._pauses.set(pauseId, {
3489
+ start,
3490
+ end
3491
+ });
3492
+ }
3493
+ }, __name(_a2, "DevUsageMeasurement"), _a2);
3494
+ var _DevUsageManager = class _DevUsageManager {
3495
+ constructor() {
3496
+ __publicField(this, "_currentMeasurements", /* @__PURE__ */ new Map());
3497
+ __publicField(this, "_pauses", /* @__PURE__ */ new Map());
3498
+ }
3499
+ disable() {
3500
+ }
3501
+ sample() {
3502
+ return this._firstMeasurement?.sample();
3503
+ }
3504
+ start() {
3505
+ const id = generateRandomString();
3506
+ const measurement = new DevUsageMeasurement(id);
3507
+ if (!this._firstMeasurement) {
3508
+ this._firstMeasurement = measurement;
3509
+ }
3510
+ this._currentMeasurements.set(id, measurement);
3511
+ return measurement;
3512
+ }
3513
+ stop(measurement) {
3514
+ measurement.stop();
3515
+ const sample = measurement.sample();
3516
+ this._currentMeasurements.delete(measurement.id);
3517
+ return sample;
3518
+ }
3519
+ async pauseAsync(cb) {
3520
+ const pauseId = generateRandomString();
3521
+ const pauseStart = clock.preciseNow();
3522
+ try {
3523
+ this._pauses.set(pauseId, {
3524
+ start: pauseStart
3525
+ });
3526
+ for (const measurement of this._currentMeasurements.values()) {
3527
+ measurement.registerPause(pauseId, pauseStart);
3528
+ }
3529
+ return await cb();
3530
+ } finally {
3531
+ const pauseEnd = clock.preciseNow();
3532
+ this._pauses.set(pauseId, {
3533
+ start: pauseStart,
3534
+ end: pauseEnd
3535
+ });
3536
+ for (const measurement of this._currentMeasurements.values()) {
3537
+ measurement.registerPause(pauseId, pauseStart, pauseEnd);
3538
+ }
3539
+ }
3540
+ }
3541
+ };
3542
+ __name(_DevUsageManager, "DevUsageManager");
3543
+ var DevUsageManager = _DevUsageManager;
3544
+ function generateRandomString() {
3545
+ let result = "";
3546
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3547
+ const charactersLength = characters.length;
3548
+ for (var i = 0; i < 16; i++) {
3549
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
3550
+ }
3551
+ return result;
3552
+ }
3553
+ __name(generateRandomString, "generateRandomString");
3554
+
3555
+ // src/v3/usage/usageClient.ts
3556
+ var _UsageClient = class _UsageClient {
3557
+ constructor(url, jwt) {
3558
+ this.url = url;
3559
+ this.jwt = jwt;
3560
+ }
3561
+ async sendUsageEvent(event) {
3562
+ try {
3563
+ const response = await fetch(this.url, {
3564
+ method: "POST",
3565
+ body: JSON.stringify(event),
3566
+ headers: {
3567
+ "content-type": "application/json",
3568
+ "x-trigger-jwt": this.jwt,
3569
+ accept: "application/json",
3570
+ authorization: `Bearer ${apiClientManager.accessToken}`
3571
+ }
3572
+ });
3573
+ if (response.ok) {
3574
+ const renewedJwt = response.headers.get("x-trigger-jwt");
3575
+ if (renewedJwt) {
3576
+ this.jwt = renewedJwt;
3577
+ }
3578
+ }
3579
+ } catch (error) {
3580
+ console.error(`Failed to send usage event: ${error}`);
3581
+ }
3582
+ }
3583
+ };
3584
+ __name(_UsageClient, "UsageClient");
3585
+ var UsageClient = _UsageClient;
3586
+
3587
+ // src/v3/usage/prodUsageManager.ts
3588
+ var _startReportingHeartbeat, startReportingHeartbeat_fn, _reportUsage, reportUsage_fn;
3589
+ var _ProdUsageManager = class _ProdUsageManager {
3590
+ constructor(delegageUsageManager, options) {
3591
+ __privateAdd(this, _startReportingHeartbeat);
3592
+ __privateAdd(this, _reportUsage);
3593
+ this.delegageUsageManager = delegageUsageManager;
3594
+ this.options = options;
3595
+ if (this.options.url && this.options.jwt) {
3596
+ this._usageClient = new UsageClient(this.options.url, this.options.jwt);
3597
+ }
3598
+ }
3599
+ get isReportingEnabled() {
3600
+ return typeof this._usageClient !== "undefined";
3601
+ }
3602
+ disable() {
3603
+ this.delegageUsageManager.disable();
3604
+ this._abortController?.abort();
3605
+ }
3606
+ sample() {
3607
+ return this._measurement?.sample();
3608
+ }
3609
+ start() {
3610
+ if (!this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3611
+ return this.delegageUsageManager.start();
3612
+ }
3613
+ if (!this._measurement) {
3614
+ this._measurement = this.delegageUsageManager.start();
3615
+ __privateMethod(this, _startReportingHeartbeat, startReportingHeartbeat_fn).call(this).catch(console.error);
3616
+ return this._measurement;
3617
+ }
3618
+ return this.delegageUsageManager.start();
3619
+ }
3620
+ stop(measurement) {
3621
+ return this.delegageUsageManager.stop(measurement);
3622
+ }
3623
+ async pauseAsync(cb) {
3624
+ return this.delegageUsageManager.pauseAsync(cb);
3625
+ }
3626
+ async flush() {
3627
+ return await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3628
+ }
3629
+ };
3630
+ _startReportingHeartbeat = new WeakSet();
3631
+ startReportingHeartbeat_fn = /* @__PURE__ */ __name(async function() {
3632
+ if (!this._measurement || !this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3633
+ return;
3634
+ }
3635
+ this._abortController = new AbortController();
3636
+ for await (const _ of promises.setInterval(this.options.heartbeatIntervalMs)) {
3637
+ if (this._abortController.signal.aborted) {
3638
+ break;
3639
+ }
3640
+ await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3641
+ }
3642
+ }, "#startReportingHeartbeat");
3643
+ _reportUsage = new WeakSet();
3644
+ reportUsage_fn = /* @__PURE__ */ __name(async function() {
3645
+ if (!this._measurement) {
3646
+ return;
3647
+ }
3648
+ if (!this.isReportingEnabled) {
3649
+ return;
3650
+ }
3651
+ const client = this._usageClient;
3652
+ if (!client) {
3653
+ return;
3654
+ }
3655
+ const sample = this._measurement.sample();
3656
+ const cpuTimeSinceLastSample = this._lastSample ? sample.cpuTime - this._lastSample.cpuTime : sample.cpuTime;
3657
+ this._lastSample = sample;
3658
+ if (cpuTimeSinceLastSample <= 0) {
3659
+ return;
3660
+ }
3661
+ await client.sendUsageEvent({
3662
+ durationMs: cpuTimeSinceLastSample
3663
+ });
3664
+ }, "#reportUsage");
3665
+ __name(_ProdUsageManager, "ProdUsageManager");
3666
+ var ProdUsageManager = _ProdUsageManager;
3667
+
3668
+ exports.ConsoleInterceptor = ConsoleInterceptor;
3669
+ exports.DevUsageManager = DevUsageManager;
3670
+ exports.DurableClock = PreciseWallClock;
3671
+ exports.OtelTaskLogger = OtelTaskLogger;
3672
+ exports.ProdUsageManager = ProdUsageManager;
3673
+ exports.StandardTaskCatalog = StandardTaskCatalog;
3674
+ exports.TaskContextLogProcessor = TaskContextLogProcessor;
3675
+ exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
3676
+ exports.TaskExecutor = TaskExecutor;
3677
+ exports.TracingSDK = TracingSDK;
3678
+ exports.getEnvVar = getEnvVar;
3679
+ exports.logLevels = logLevels;
3680
+ exports.recordSpanException = recordSpanException;
3681
+ exports.usage = usage;
3682
+ //# sourceMappingURL=out.js.map
3683
+ //# sourceMappingURL=index.js.map