@trigger.dev/core 0.0.0-v3-prerelease-20240517090458 → 0.0.0-v3-prerelease-20240606120239

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 (57) hide show
  1. package/dist/catalog-XTlJQaMn.d.mts +202 -0
  2. package/dist/catalog-dRKTgwQ7.d.ts +202 -0
  3. package/dist/index.d.mts +60 -1
  4. package/dist/index.d.ts +60 -1
  5. package/dist/index.js +7 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +7 -1
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/{manager-WNMVbgHf.d.mts → manager-JkbddlcO.d.mts} +43 -42
  10. package/dist/{manager-WNMVbgHf.d.ts → manager-JkbddlcO.d.ts} +43 -42
  11. package/dist/{messages-vq7Bk4Ap.d.mts → messages-6_-q72KG.d.mts} +5970 -2067
  12. package/dist/{messages-vq7Bk4Ap.d.ts → messages-6_-q72KG.d.ts} +5970 -2067
  13. package/dist/{catalog-KbyTBoap.d.ts → schemas-r4ZP9S-F.d.mts} +22 -187
  14. package/dist/{catalog-ck7x04PV.d.mts → schemas-r4ZP9S-F.d.ts} +22 -187
  15. package/dist/v3/dev/index.d.mts +2 -2
  16. package/dist/v3/dev/index.d.ts +2 -2
  17. package/dist/v3/dev/index.js +4 -4
  18. package/dist/v3/dev/index.js.map +1 -1
  19. package/dist/v3/dev/index.mjs +4 -4
  20. package/dist/v3/dev/index.mjs.map +1 -1
  21. package/dist/v3/index.d.mts +684 -113
  22. package/dist/v3/index.d.ts +684 -113
  23. package/dist/v3/index.js +1501 -698
  24. package/dist/v3/index.js.map +1 -1
  25. package/dist/v3/index.mjs +1484 -697
  26. package/dist/v3/index.mjs.map +1 -1
  27. package/dist/v3/otel/index.js +1 -1
  28. package/dist/v3/otel/index.js.map +1 -1
  29. package/dist/v3/otel/index.mjs +1 -1
  30. package/dist/v3/otel/index.mjs.map +1 -1
  31. package/dist/v3/prod/index.d.mts +3 -3
  32. package/dist/v3/prod/index.d.ts +3 -3
  33. package/dist/v3/prod/index.js +90 -15
  34. package/dist/v3/prod/index.js.map +1 -1
  35. package/dist/v3/prod/index.mjs +90 -15
  36. package/dist/v3/prod/index.mjs.map +1 -1
  37. package/dist/v3/workers/index.d.mts +6 -5
  38. package/dist/v3/workers/index.d.ts +6 -5
  39. package/dist/v3/workers/index.js +658 -52
  40. package/dist/v3/workers/index.js.map +1 -1
  41. package/dist/v3/workers/index.mjs +658 -52
  42. package/dist/v3/workers/index.mjs.map +1 -1
  43. package/dist/v3/zodNamespace.js +16 -6
  44. package/dist/v3/zodNamespace.js.map +1 -1
  45. package/dist/v3/zodNamespace.mjs +17 -7
  46. package/dist/v3/zodNamespace.mjs.map +1 -1
  47. package/dist/v3/zodSocket.js +16 -6
  48. package/dist/v3/zodSocket.js.map +1 -1
  49. package/dist/v3/zodSocket.mjs +17 -7
  50. package/dist/v3/zodSocket.mjs.map +1 -1
  51. package/dist/v3/zodfetch.d.mts +262 -0
  52. package/dist/v3/zodfetch.d.ts +262 -0
  53. package/dist/v3/zodfetch.js +744 -0
  54. package/dist/v3/zodfetch.js.map +1 -0
  55. package/dist/v3/zodfetch.mjs +716 -0
  56. package/dist/v3/zodfetch.mjs.map +1 -0
  57. package/package.json +15 -6
package/dist/v3/index.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  import { propagation, context, trace, SpanStatusCode } from '@opentelemetry/api';
2
- import { fromZodError } from 'zod-validation-error';
3
2
  import { z } from 'zod';
3
+ import { fromZodError } from 'zod-validation-error';
4
+ import { FormDataEncoder } from 'form-data-encoder';
5
+ import { Readable } from 'node:stream';
4
6
  import { PreciseDate } from '@google-cloud/precise-date';
5
7
  import { logs } from '@opentelemetry/api-logs';
6
8
  import humanizeDuration from 'humanize-duration';
@@ -26,423 +28,70 @@ var __privateMethod = (obj, member, method) => {
26
28
  return method;
27
29
  };
28
30
 
29
- // src/v3/apiErrors.ts
30
- var _APIError = class _APIError extends Error {
31
- constructor(status, error, message, headers) {
32
- super(`${_APIError.makeMessage(status, error, message)}`);
33
- this.status = status;
34
- this.headers = headers;
35
- const data = error;
36
- this.error = data;
37
- this.code = data?.["code"];
38
- this.param = data?.["param"];
39
- this.type = data?.["type"];
40
- }
41
- static makeMessage(status, error, message) {
42
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
43
- if (status && msg) {
44
- return `${status} ${msg}`;
45
- }
46
- if (status) {
47
- return `${status} status code (no body)`;
48
- }
49
- if (msg) {
50
- return msg;
51
- }
52
- return "(no status code or body)";
53
- }
54
- static generate(status, errorResponse, message, headers) {
55
- if (!status) {
56
- return new APIConnectionError({
57
- cause: castToError(errorResponse)
58
- });
59
- }
60
- const error = errorResponse?.["error"];
61
- if (status === 400) {
62
- return new BadRequestError(status, error, message, headers);
63
- }
64
- if (status === 401) {
65
- return new AuthenticationError(status, error, message, headers);
66
- }
67
- if (status === 403) {
68
- return new PermissionDeniedError(status, error, message, headers);
69
- }
70
- if (status === 404) {
71
- return new NotFoundError(status, error, message, headers);
72
- }
73
- if (status === 409) {
74
- return new ConflictError(status, error, message, headers);
75
- }
76
- if (status === 422) {
77
- return new UnprocessableEntityError(status, error, message, headers);
78
- }
79
- if (status === 429) {
80
- return new RateLimitError(status, error, message, headers);
81
- }
82
- if (status >= 500) {
83
- return new InternalServerError(status, error, message, headers);
84
- }
85
- return new _APIError(status, error, message, headers);
86
- }
87
- };
88
- __name(_APIError, "APIError");
89
- var APIError = _APIError;
90
- var _APIConnectionError = class _APIConnectionError extends APIError {
91
- constructor({ message, cause }) {
92
- super(void 0, void 0, message || "Connection error.", void 0);
93
- __publicField(this, "status");
94
- if (cause)
95
- this.cause = cause;
96
- }
97
- };
98
- __name(_APIConnectionError, "APIConnectionError");
99
- var APIConnectionError = _APIConnectionError;
100
- var _BadRequestError = class _BadRequestError extends APIError {
101
- constructor() {
102
- super(...arguments);
103
- __publicField(this, "status", 400);
104
- }
105
- };
106
- __name(_BadRequestError, "BadRequestError");
107
- var BadRequestError = _BadRequestError;
108
- var _AuthenticationError = class _AuthenticationError extends APIError {
109
- constructor() {
110
- super(...arguments);
111
- __publicField(this, "status", 401);
112
- }
113
- };
114
- __name(_AuthenticationError, "AuthenticationError");
115
- var AuthenticationError = _AuthenticationError;
116
- var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
117
- constructor() {
118
- super(...arguments);
119
- __publicField(this, "status", 403);
120
- }
121
- };
122
- __name(_PermissionDeniedError, "PermissionDeniedError");
123
- var PermissionDeniedError = _PermissionDeniedError;
124
- var _NotFoundError = class _NotFoundError extends APIError {
125
- constructor() {
126
- super(...arguments);
127
- __publicField(this, "status", 404);
128
- }
129
- };
130
- __name(_NotFoundError, "NotFoundError");
131
- var NotFoundError = _NotFoundError;
132
- var _ConflictError = class _ConflictError extends APIError {
133
- constructor() {
134
- super(...arguments);
135
- __publicField(this, "status", 409);
136
- }
137
- };
138
- __name(_ConflictError, "ConflictError");
139
- var ConflictError = _ConflictError;
140
- var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
141
- constructor() {
142
- super(...arguments);
143
- __publicField(this, "status", 422);
144
- }
145
- };
146
- __name(_UnprocessableEntityError, "UnprocessableEntityError");
147
- var UnprocessableEntityError = _UnprocessableEntityError;
148
- var _RateLimitError = class _RateLimitError extends APIError {
149
- constructor() {
150
- super(...arguments);
151
- __publicField(this, "status", 429);
152
- }
153
- };
154
- __name(_RateLimitError, "RateLimitError");
155
- var RateLimitError = _RateLimitError;
156
- var _InternalServerError = class _InternalServerError extends APIError {
31
+ // package.json
32
+ var version = "0.0.0-v3-prerelease-20240606120239";
33
+ var dependencies = {
34
+ "@google-cloud/precise-date": "^4.0.0",
35
+ "@opentelemetry/api": "^1.8.0",
36
+ "@opentelemetry/api-logs": "^0.48.0",
37
+ "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
38
+ "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
39
+ "@opentelemetry/instrumentation": "^0.49.1",
40
+ "@opentelemetry/resources": "^1.22.0",
41
+ "@opentelemetry/sdk-logs": "^0.49.1",
42
+ "@opentelemetry/sdk-node": "^0.49.1",
43
+ "@opentelemetry/sdk-trace-base": "^1.22.0",
44
+ "@opentelemetry/sdk-trace-node": "^1.22.0",
45
+ "@opentelemetry/semantic-conventions": "^1.22.0",
46
+ "form-data-encoder": "^4.0.2",
47
+ "humanize-duration": "^3.27.3",
48
+ "socket.io-client": "4.7.4",
49
+ superjson: "^2.2.1",
50
+ ulidx: "^2.2.1",
51
+ zod: "3.22.3",
52
+ "zod-error": "1.5.0",
53
+ "zod-validation-error": "^1.5.0"
157
54
  };
158
- __name(_InternalServerError, "InternalServerError");
159
- var InternalServerError = _InternalServerError;
160
- function castToError(err) {
161
- if (err instanceof Error)
162
- return err;
163
- return new Error(err);
164
- }
165
- __name(castToError, "castToError");
166
-
167
- // src/retry.ts
168
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
169
- if (!resets)
170
- return;
171
- switch (format) {
172
- case "iso_8601_duration_openai_variant": {
173
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
174
- }
175
- case "iso_8601": {
176
- return calculateISO8601ResetAt(resets, now);
177
- }
178
- case "unix_timestamp": {
179
- return calculateUnixTimestampResetAt(resets, now);
180
- }
181
- case "unix_timestamp_in_ms": {
182
- return calculateUnixTimestampInMsResetAt(resets, now);
183
- }
184
- }
185
- }
186
- __name(calculateResetAt, "calculateResetAt");
187
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
188
- if (!resets)
189
- return void 0;
190
- const resetAt = parseInt(resets, 10);
191
- if (isNaN(resetAt))
192
- return void 0;
193
- return new Date(resetAt * 1e3);
194
- }
195
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
196
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
197
- if (!resets)
198
- return void 0;
199
- const resetAt = parseInt(resets, 10);
200
- if (isNaN(resetAt))
201
- return void 0;
202
- return new Date(resetAt);
203
- }
204
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
205
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
206
- if (!resets)
207
- return void 0;
208
- const resetAt = new Date(resets);
209
- if (isNaN(resetAt.getTime()))
210
- return void 0;
211
- return resetAt;
212
- }
213
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
214
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
215
- if (!resets)
216
- return void 0;
217
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
218
- const match = resets.match(pattern);
219
- if (!match)
220
- return void 0;
221
- const days = parseInt(match[1], 10) || 0;
222
- const hours = parseInt(match[2], 10) || 0;
223
- const minutes = parseInt(match[3], 10) || 0;
224
- const seconds = parseFloat(match[4]) || 0;
225
- const milliseconds = parseInt(match[5], 10) || 0;
226
- const resetAt = new Date(now);
227
- resetAt.setDate(resetAt.getDate() + days);
228
- resetAt.setHours(resetAt.getHours() + hours);
229
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
230
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
231
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
232
- return resetAt;
233
- }
234
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
235
-
236
- // src/v3/utils/retries.ts
237
- var defaultRetryOptions = {
238
- maxAttempts: 3,
239
- factor: 2,
240
- minTimeoutInMs: 1e3,
241
- maxTimeoutInMs: 6e4,
242
- randomize: true
243
- };
244
- var defaultFetchRetryOptions = {
245
- byStatus: {
246
- "429,408,409,5xx": {
247
- strategy: "backoff",
248
- ...defaultRetryOptions
249
- }
250
- },
251
- connectionError: defaultRetryOptions,
252
- timeout: defaultRetryOptions
253
- };
254
- function calculateNextRetryDelay(options, attempt) {
255
- const opts = {
256
- ...defaultRetryOptions,
257
- ...options
258
- };
259
- if (attempt >= opts.maxAttempts) {
260
- return;
261
- }
262
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
263
- const random = randomize ? Math.random() + 1 : 1;
264
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
265
- return Math.round(timeout);
266
- }
267
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
268
- function calculateResetAt2(resets, format, now = Date.now()) {
269
- const resetAt = calculateResetAt(resets, format, new Date(now));
270
- return resetAt?.getTime();
271
- }
272
- __name(calculateResetAt2, "calculateResetAt");
273
-
274
- // src/v3/zodfetch.ts
275
- var defaultRetryOptions2 = {
276
- maxAttempts: 3,
277
- factor: 2,
278
- minTimeoutInMs: 1e3,
279
- maxTimeoutInMs: 6e4,
280
- randomize: false
281
- };
282
- async function zodfetch(schema, url, requestInit, options) {
283
- return await _doZodFetch(schema, url, requestInit, options);
284
- }
285
- __name(zodfetch, "zodfetch");
286
- async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
287
- try {
288
- const response = await fetch(url, requestInitWithCache(requestInit));
289
- const responseHeaders = createResponseHeaders(response.headers);
290
- if (!response.ok) {
291
- const retryResult = shouldRetry(response, attempt, options?.retry);
292
- if (retryResult.retry) {
293
- await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
294
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
295
- } else {
296
- const errText = await response.text().catch((e) => castToError2(e).message);
297
- const errJSON = safeJsonParse(errText);
298
- const errMessage = errJSON ? void 0 : errText;
299
- throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
300
- }
301
- }
302
- const jsonBody = await response.json();
303
- const parsedResult = schema.safeParse(jsonBody);
304
- if (parsedResult.success) {
305
- return parsedResult.data;
306
- }
307
- throw fromZodError(parsedResult.error);
308
- } catch (error) {
309
- if (error instanceof APIError) {
310
- throw error;
311
- }
312
- if (options?.retry) {
313
- const retry = {
314
- ...defaultRetryOptions2,
315
- ...options.retry
316
- };
317
- const delay = calculateNextRetryDelay(retry, attempt);
318
- if (delay) {
319
- await new Promise((resolve) => setTimeout(resolve, delay));
320
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
321
- }
322
- }
323
- throw new APIConnectionError({
324
- cause: castToError2(error)
325
- });
326
- }
327
- }
328
- __name(_doZodFetch, "_doZodFetch");
329
- function castToError2(err) {
330
- if (err instanceof Error)
331
- return err;
332
- return new Error(err);
333
- }
334
- __name(castToError2, "castToError");
335
- function shouldRetry(response, attempt, retryOptions) {
336
- function shouldRetryForOptions() {
337
- const retry = {
338
- ...defaultRetryOptions2,
339
- ...retryOptions
340
- };
341
- const delay = calculateNextRetryDelay(retry, attempt);
342
- if (delay) {
343
- return {
344
- retry: true,
345
- delay
346
- };
347
- } else {
348
- return {
349
- retry: false
350
- };
351
- }
352
- }
353
- __name(shouldRetryForOptions, "shouldRetryForOptions");
354
- const shouldRetryHeader = response.headers.get("x-should-retry");
355
- if (shouldRetryHeader === "true")
356
- return shouldRetryForOptions();
357
- if (shouldRetryHeader === "false")
358
- return {
359
- retry: false
360
- };
361
- if (response.status === 408)
362
- return shouldRetryForOptions();
363
- if (response.status === 409)
364
- return shouldRetryForOptions();
365
- if (response.status === 429)
366
- return shouldRetryForOptions();
367
- if (response.status >= 500)
368
- return shouldRetryForOptions();
369
- return {
370
- retry: false
371
- };
372
- }
373
- __name(shouldRetry, "shouldRetry");
374
- function safeJsonParse(text) {
375
- try {
376
- return JSON.parse(text);
377
- } catch (e) {
378
- return void 0;
379
- }
380
- }
381
- __name(safeJsonParse, "safeJsonParse");
382
- function createResponseHeaders(headers) {
383
- return new Proxy(Object.fromEntries(
384
- // @ts-ignore
385
- headers.entries()
386
- ), {
387
- get(target, name) {
388
- const key = name.toString();
389
- return target[key.toLowerCase()] || target[key];
390
- }
391
- });
392
- }
393
- __name(createResponseHeaders, "createResponseHeaders");
394
- function requestInitWithCache(requestInit) {
395
- try {
396
- const withCache = {
397
- ...requestInit,
398
- cache: "no-cache"
399
- };
400
- const _ = new Request("http://localhost", withCache);
401
- return withCache;
402
- } catch (error) {
403
- return requestInit ?? {};
404
- }
405
- }
406
- __name(requestInitWithCache, "requestInitWithCache");
407
- var CreateAuthorizationCodeResponseSchema = z.object({
408
- url: z.string().url(),
409
- authorizationCode: z.string()
410
- });
411
- var GetPersonalAccessTokenRequestSchema = z.object({
412
- authorizationCode: z.string()
413
- });
414
- var GetPersonalAccessTokenResponseSchema = z.object({
415
- token: z.object({
416
- token: z.string(),
417
- obfuscatedToken: z.string()
418
- }).nullable()
419
- });
420
- var TaskRunBuiltInError = z.object({
421
- type: z.literal("BUILT_IN_ERROR"),
422
- name: z.string(),
423
- message: z.string(),
424
- stackTrace: z.string()
425
- });
426
- var TaskRunCustomErrorObject = z.object({
427
- type: z.literal("CUSTOM_ERROR"),
428
- raw: z.string()
429
- });
430
- var TaskRunStringError = z.object({
431
- type: z.literal("STRING_ERROR"),
432
- raw: z.string()
433
- });
434
- var TaskRunErrorCodes = {
435
- COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
436
- COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
437
- CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
438
- TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
439
- TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
440
- TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
441
- TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
442
- TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
443
- TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
444
- HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
445
- GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
55
+ var CreateAuthorizationCodeResponseSchema = z.object({
56
+ url: z.string().url(),
57
+ authorizationCode: z.string()
58
+ });
59
+ var GetPersonalAccessTokenRequestSchema = z.object({
60
+ authorizationCode: z.string()
61
+ });
62
+ var GetPersonalAccessTokenResponseSchema = z.object({
63
+ token: z.object({
64
+ token: z.string(),
65
+ obfuscatedToken: z.string()
66
+ }).nullable()
67
+ });
68
+ var TaskRunBuiltInError = z.object({
69
+ type: z.literal("BUILT_IN_ERROR"),
70
+ name: z.string(),
71
+ message: z.string(),
72
+ stackTrace: z.string()
73
+ });
74
+ var TaskRunCustomErrorObject = z.object({
75
+ type: z.literal("CUSTOM_ERROR"),
76
+ raw: z.string()
77
+ });
78
+ var TaskRunStringError = z.object({
79
+ type: z.literal("STRING_ERROR"),
80
+ raw: z.string()
81
+ });
82
+ var TaskRunErrorCodes = {
83
+ COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
84
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
85
+ CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
86
+ TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
87
+ TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
88
+ TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
89
+ TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
90
+ TASK_PROCESS_SIGKILL_TIMEOUT: "TASK_PROCESS_SIGKILL_TIMEOUT",
91
+ TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
92
+ TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
93
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
94
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
446
95
  };
447
96
  var TaskRunInternalError = z.object({
448
97
  type: z.literal("INTERNAL_ERROR"),
@@ -454,10 +103,12 @@ var TaskRunInternalError = z.object({
454
103
  "TASK_EXECUTION_FAILED",
455
104
  "TASK_EXECUTION_ABORTED",
456
105
  "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
106
+ "TASK_PROCESS_SIGKILL_TIMEOUT",
457
107
  "TASK_RUN_CANCELLED",
458
108
  "TASK_OUTPUT_ERROR",
459
109
  "HANDLE_ERROR_ERROR",
460
- "GRACEFUL_EXIT_TIMEOUT"
110
+ "GRACEFUL_EXIT_TIMEOUT",
111
+ "TASK_RUN_HEARTBEAT_TIMEOUT"
461
112
  ]),
462
113
  message: z.string().optional()
463
114
  });
@@ -719,7 +370,16 @@ var TaskFileMetadata = z.object({
719
370
  filePath: z.string(),
720
371
  exportName: z.string()
721
372
  });
722
- var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
373
+ var TaskMetadataWithFilePath = z.object({
374
+ id: z.string(),
375
+ packageVersion: z.string(),
376
+ queue: QueueOptions.optional(),
377
+ retry: RetryOptions.optional(),
378
+ machine: Machine.partial().optional(),
379
+ triggerSource: z.string().optional(),
380
+ filePath: z.string(),
381
+ exportName: z.string()
382
+ });
723
383
  var PostStartCauses = z.enum([
724
384
  "index",
725
385
  "create",
@@ -760,6 +420,13 @@ var WaitReason = z.enum([
760
420
  "WAIT_FOR_TASK",
761
421
  "WAIT_FOR_BATCH"
762
422
  ]);
423
+ var TaskRunExecutionLazyAttemptPayload = z.object({
424
+ runId: z.string(),
425
+ messageId: z.string(),
426
+ isTest: z.boolean(),
427
+ traceContext: z.record(z.unknown()),
428
+ environment: z.record(z.string()).optional()
429
+ });
763
430
 
764
431
  // src/v3/schemas/resources.ts
765
432
  var TaskResource = z.object({
@@ -781,57 +448,204 @@ var ImageDetailsMetadata = z.object({
781
448
  contentHash: z.string(),
782
449
  imageTag: z.string()
783
450
  });
784
-
785
- // src/v3/schemas/api.ts
786
- var WhoAmIResponseSchema = z.object({
787
- userId: z.string(),
788
- email: z.string().email(),
789
- dashboardUrl: z.string()
790
- });
791
- var GetProjectResponseBody = z.object({
792
- id: z.string(),
793
- externalRef: z.string(),
794
- name: z.string(),
795
- slug: z.string(),
796
- createdAt: z.coerce.date(),
797
- organization: z.object({
798
- id: z.string(),
799
- title: z.string(),
800
- slug: z.string(),
801
- createdAt: z.coerce.date()
802
- })
803
- });
804
- var GetProjectsResponseBody = z.array(GetProjectResponseBody);
805
- var GetProjectEnvResponse = z.object({
806
- apiKey: z.string(),
807
- name: z.string(),
808
- apiUrl: z.string()
809
- });
810
- var CreateBackgroundWorkerRequestBody = z.object({
811
- localOnly: z.boolean(),
812
- metadata: BackgroundWorkerMetadata
813
- });
814
- var CreateBackgroundWorkerResponse = z.object({
815
- id: z.string(),
816
- version: z.string(),
817
- contentHash: z.string()
818
- });
819
- var TriggerTaskRequestBody = z.object({
820
- payload: z.any(),
821
- context: z.any(),
822
- options: z.object({
823
- dependentAttempt: z.string().optional(),
824
- dependentBatch: z.string().optional(),
825
- lockToVersion: z.string().optional(),
826
- queue: QueueOptions.optional(),
827
- concurrencyKey: z.string().optional(),
828
- idempotencyKey: z.string().optional(),
829
- test: z.boolean().optional(),
830
- payloadType: z.string().optional()
831
- }).optional()
832
- });
833
- var TriggerTaskResponse = z.object({
834
- id: z.string()
451
+ function parseError(error) {
452
+ if (error instanceof Error) {
453
+ return {
454
+ type: "BUILT_IN_ERROR",
455
+ name: error.name,
456
+ message: error.message,
457
+ stackTrace: error.stack ?? ""
458
+ };
459
+ }
460
+ if (typeof error === "string") {
461
+ return {
462
+ type: "STRING_ERROR",
463
+ raw: error
464
+ };
465
+ }
466
+ try {
467
+ return {
468
+ type: "CUSTOM_ERROR",
469
+ raw: JSON.stringify(error)
470
+ };
471
+ } catch (e) {
472
+ return {
473
+ type: "CUSTOM_ERROR",
474
+ raw: String(error)
475
+ };
476
+ }
477
+ }
478
+ __name(parseError, "parseError");
479
+ function createErrorTaskError(error) {
480
+ switch (error.type) {
481
+ case "BUILT_IN_ERROR": {
482
+ const e = new Error(error.message);
483
+ e.name = error.name;
484
+ e.stack = error.stackTrace;
485
+ return e;
486
+ }
487
+ case "STRING_ERROR": {
488
+ return error.raw;
489
+ }
490
+ case "CUSTOM_ERROR": {
491
+ return JSON.parse(error.raw);
492
+ }
493
+ case "INTERNAL_ERROR": {
494
+ return new Error(`trigger.dev internal error (${error.code})`);
495
+ }
496
+ }
497
+ }
498
+ __name(createErrorTaskError, "createErrorTaskError");
499
+ var SerializedError = z.object({
500
+ message: z.string(),
501
+ name: z.string().optional(),
502
+ stackTrace: z.string().optional()
503
+ });
504
+ function createJsonErrorObject(error) {
505
+ switch (error.type) {
506
+ case "BUILT_IN_ERROR": {
507
+ return {
508
+ name: error.name,
509
+ message: error.message,
510
+ stackTrace: error.stackTrace
511
+ };
512
+ }
513
+ case "STRING_ERROR": {
514
+ return {
515
+ message: error.raw
516
+ };
517
+ }
518
+ case "CUSTOM_ERROR": {
519
+ return {
520
+ message: error.raw
521
+ };
522
+ }
523
+ case "INTERNAL_ERROR": {
524
+ return {
525
+ message: `trigger.dev internal error (${error.code})`
526
+ };
527
+ }
528
+ }
529
+ }
530
+ __name(createJsonErrorObject, "createJsonErrorObject");
531
+ function correctErrorStackTrace(stackTrace, projectDir, options) {
532
+ const [errorLine, ...traceLines] = stackTrace.split("\n");
533
+ return [
534
+ options?.removeFirstLine ? void 0 : errorLine,
535
+ ...traceLines.map((line) => correctStackTraceLine(line, projectDir, options?.isDev))
536
+ ].filter(Boolean).join("\n");
537
+ }
538
+ __name(correctErrorStackTrace, "correctErrorStackTrace");
539
+ var LINES_TO_IGNORE = [
540
+ /ConsoleInterceptor/,
541
+ /TriggerTracer/,
542
+ /TaskExecutor/,
543
+ /EXECUTE_TASK_RUN/,
544
+ /@trigger.dev\/core/,
545
+ /packages\/core\/src\/v3/,
546
+ /safeJsonProcess/,
547
+ /__entryPoint.ts/,
548
+ /ZodIpc/,
549
+ /startActiveSpan/,
550
+ /processTicksAndRejections/
551
+ ];
552
+ function correctStackTraceLine(line, projectDir, isDev) {
553
+ if (LINES_TO_IGNORE.some((regex) => regex.test(line))) {
554
+ return;
555
+ }
556
+ if (isDev && projectDir && !line.includes(projectDir)) {
557
+ return;
558
+ }
559
+ return line.trim();
560
+ }
561
+ __name(correctStackTraceLine, "correctStackTraceLine");
562
+ function groupTaskMetadataIssuesByTask(tasks, issues) {
563
+ return issues.reduce((acc, issue) => {
564
+ if (issue.path.length === 0) {
565
+ return acc;
566
+ }
567
+ const taskIndex = issue.path[1];
568
+ if (typeof taskIndex !== "number") {
569
+ return acc;
570
+ }
571
+ const task = tasks[taskIndex];
572
+ if (!task) {
573
+ return acc;
574
+ }
575
+ const restOfPath = issue.path.slice(2);
576
+ const taskId = task.id;
577
+ const taskName = task.exportName;
578
+ const filePath = task.filePath;
579
+ const key = taskIndex;
580
+ const existing = acc[key] ?? {
581
+ id: taskId,
582
+ exportName: taskName,
583
+ filePath,
584
+ issues: []
585
+ };
586
+ existing.issues.push({
587
+ message: issue.message,
588
+ path: restOfPath.length === 0 ? void 0 : restOfPath.join(".")
589
+ });
590
+ return {
591
+ ...acc,
592
+ [key]: existing
593
+ };
594
+ }, {});
595
+ }
596
+ __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
597
+
598
+ // src/v3/schemas/api.ts
599
+ var WhoAmIResponseSchema = z.object({
600
+ userId: z.string(),
601
+ email: z.string().email(),
602
+ dashboardUrl: z.string()
603
+ });
604
+ var GetProjectResponseBody = z.object({
605
+ id: z.string(),
606
+ externalRef: z.string(),
607
+ name: z.string(),
608
+ slug: z.string(),
609
+ createdAt: z.coerce.date(),
610
+ organization: z.object({
611
+ id: z.string(),
612
+ title: z.string(),
613
+ slug: z.string(),
614
+ createdAt: z.coerce.date()
615
+ })
616
+ });
617
+ var GetProjectsResponseBody = z.array(GetProjectResponseBody);
618
+ var GetProjectEnvResponse = z.object({
619
+ apiKey: z.string(),
620
+ name: z.string(),
621
+ apiUrl: z.string()
622
+ });
623
+ var CreateBackgroundWorkerRequestBody = z.object({
624
+ localOnly: z.boolean(),
625
+ metadata: BackgroundWorkerMetadata,
626
+ supportsLazyAttempts: z.boolean().optional()
627
+ });
628
+ var CreateBackgroundWorkerResponse = z.object({
629
+ id: z.string(),
630
+ version: z.string(),
631
+ contentHash: z.string()
632
+ });
633
+ var TriggerTaskRequestBody = z.object({
634
+ payload: z.any(),
635
+ context: z.any(),
636
+ options: z.object({
637
+ dependentAttempt: z.string().optional(),
638
+ dependentBatch: z.string().optional(),
639
+ lockToVersion: z.string().optional(),
640
+ queue: QueueOptions.optional(),
641
+ concurrencyKey: z.string().optional(),
642
+ idempotencyKey: z.string().optional(),
643
+ test: z.boolean().optional(),
644
+ payloadType: z.string().optional()
645
+ }).optional()
646
+ });
647
+ var TriggerTaskResponse = z.object({
648
+ id: z.string()
835
649
  });
836
650
  var BatchTriggerTaskRequestBody = z.object({
837
651
  items: TriggerTaskRequestBody.array(),
@@ -922,7 +736,7 @@ var ReplayRunResponse = z.object({
922
736
  id: z.string()
923
737
  });
924
738
  var CanceledRunResponse = z.object({
925
- message: z.string()
739
+ id: z.string()
926
740
  });
927
741
  var ScheduledTaskPayload = z.object({
928
742
  /** The schedule id associated with this run (you can have many schedules for the same task).
@@ -972,17 +786,18 @@ var CreateScheduleOptions = z.object({
972
786
  externalId: z.string().optional()
973
787
  });
974
788
  var UpdateScheduleOptions = CreateScheduleOptions;
789
+ var ScheduleGenerator = z.object({
790
+ type: z.literal("CRON"),
791
+ expression: z.string(),
792
+ description: z.string()
793
+ });
975
794
  var ScheduleObject = z.object({
976
795
  id: z.string(),
977
796
  task: z.string(),
978
797
  active: z.boolean(),
979
798
  deduplicationKey: z.string().nullish(),
980
799
  externalId: z.string().nullish(),
981
- generator: z.object({
982
- type: z.literal("CRON"),
983
- expression: z.string(),
984
- description: z.string()
985
- }),
800
+ generator: ScheduleGenerator,
986
801
  nextRun: z.coerce.date().nullish(),
987
802
  environments: z.array(z.object({
988
803
  id: z.string(),
@@ -1006,12 +821,28 @@ var ListScheduleOptions = z.object({
1006
821
  perPage: z.number().optional()
1007
822
  });
1008
823
  var RunStatus = z.enum([
1009
- "PENDING",
824
+ /// Task hasn't been deployed yet but is waiting to be executed
825
+ "WAITING_FOR_DEPLOY",
826
+ /// Task is waiting to be executed by a worker
827
+ "QUEUED",
828
+ /// Task is currently being executed by a worker
1010
829
  "EXECUTING",
1011
- "PAUSED",
830
+ /// Task has failed and is waiting to be retried
831
+ "REATTEMPTING",
832
+ /// Task has been paused by the system, and will be resumed by the system
833
+ "FROZEN",
834
+ /// Task has been completed successfully
1012
835
  "COMPLETED",
836
+ /// Task has been canceled by the user
837
+ "CANCELED",
838
+ /// Task has been completed with errors
1013
839
  "FAILED",
1014
- "CANCELED"
840
+ /// Task has crashed and won't be retried, most likely the worker ran out of resources, e.g. memory or storage
841
+ "CRASHED",
842
+ /// Task was interrupted during execution, mostly this happens in development environments
843
+ "INTERRUPTED",
844
+ /// Task has failed to complete, due to an error in the system
845
+ "SYSTEM_FAILURE"
1015
846
  ]);
1016
847
  var AttemptStatus = z.enum([
1017
848
  "PENDING",
@@ -1021,23 +852,83 @@ var AttemptStatus = z.enum([
1021
852
  "FAILED",
1022
853
  "CANCELED"
1023
854
  ]);
1024
- var RetrieveRunResponse = z.object({
855
+ var RunEnvironmentDetails = z.object({
856
+ id: z.string(),
857
+ name: z.string(),
858
+ user: z.string().optional()
859
+ });
860
+ var RunScheduleDetails = z.object({
861
+ id: z.string(),
862
+ externalId: z.string().optional(),
863
+ deduplicationKey: z.string().optional(),
864
+ generator: ScheduleGenerator
865
+ });
866
+ var CommonRunFields = {
1025
867
  id: z.string(),
1026
868
  status: RunStatus,
1027
869
  taskIdentifier: z.string(),
1028
870
  idempotencyKey: z.string().optional(),
1029
871
  version: z.string().optional(),
872
+ isQueued: z.boolean(),
873
+ isExecuting: z.boolean(),
874
+ isCompleted: z.boolean(),
875
+ isSuccess: z.boolean(),
876
+ isFailed: z.boolean(),
877
+ isCancelled: z.boolean(),
878
+ isTest: z.boolean(),
1030
879
  createdAt: z.coerce.date(),
1031
880
  updatedAt: z.coerce.date(),
881
+ startedAt: z.coerce.date().optional(),
882
+ finishedAt: z.coerce.date().optional()
883
+ };
884
+ var RetrieveRunResponse = z.object({
885
+ ...CommonRunFields,
886
+ payload: z.any().optional(),
887
+ output: z.any().optional(),
888
+ schedule: RunScheduleDetails.optional(),
1032
889
  attempts: z.array(z.object({
1033
890
  id: z.string(),
1034
891
  status: AttemptStatus,
1035
892
  createdAt: z.coerce.date(),
1036
893
  updatedAt: z.coerce.date(),
1037
894
  startedAt: z.coerce.date().optional(),
1038
- completedAt: z.coerce.date().optional()
895
+ completedAt: z.coerce.date().optional(),
896
+ error: SerializedError.optional()
1039
897
  }).optional())
1040
898
  });
899
+ var ListRunResponseItem = z.object({
900
+ ...CommonRunFields,
901
+ env: RunEnvironmentDetails
902
+ });
903
+ var ListRunResponse = z.object({
904
+ data: z.array(ListRunResponseItem),
905
+ pagination: z.object({
906
+ next: z.string().optional(),
907
+ previous: z.string().optional()
908
+ })
909
+ });
910
+ var CreateEnvironmentVariableRequestBody = z.object({
911
+ name: z.string(),
912
+ value: z.string()
913
+ });
914
+ var UpdateEnvironmentVariableRequestBody = z.object({
915
+ value: z.string()
916
+ });
917
+ var ImportEnvironmentVariablesRequestBody = z.object({
918
+ variables: z.record(z.string()),
919
+ override: z.boolean().optional()
920
+ });
921
+ var EnvironmentVariableResponseBody = z.object({
922
+ success: z.boolean()
923
+ });
924
+ var EnvironmentVariableValue = z.object({
925
+ value: z.string()
926
+ });
927
+ var EnvironmentVariable = z.object({
928
+ name: z.string(),
929
+ value: z.string()
930
+ });
931
+ var EnvironmentVariables = z.array(EnvironmentVariable);
1041
932
  var BackgroundWorkerServerMessages = z.discriminatedUnion("type", [
1042
933
  z.object({
1043
934
  type: z.literal("EXECUTE_RUNS"),
@@ -1054,12 +945,16 @@ var BackgroundWorkerServerMessages = z.discriminatedUnion("type", [
1054
945
  version: z.string(),
1055
946
  machine: Machine,
1056
947
  // identifiers
1057
- id: z.string(),
948
+ id: z.string().optional(),
1058
949
  envId: z.string(),
1059
950
  envType: EnvironmentType,
1060
951
  orgId: z.string(),
1061
952
  projectId: z.string(),
1062
953
  runId: z.string()
954
+ }),
955
+ z.object({
956
+ type: z.literal("EXECUTE_RUN_LAZY_ATTEMPT"),
957
+ payload: TaskRunExecutionLazyAttemptPayload
1063
958
  })
1064
959
  ]);
1065
960
  var serverWebsocketMessages = {
@@ -1080,10 +975,20 @@ var BackgroundWorkerClientMessages = z.discriminatedUnion("type", [
1080
975
  completion: TaskRunExecutionResult,
1081
976
  execution: TaskRunExecution
1082
977
  }),
978
+ z.object({
979
+ version: z.literal("v1").default("v1"),
980
+ type: z.literal("TASK_RUN_FAILED_TO_RUN"),
981
+ completion: TaskRunFailedExecutionResult
982
+ }),
1083
983
  z.object({
1084
984
  version: z.literal("v1").default("v1"),
1085
985
  type: z.literal("TASK_HEARTBEAT"),
1086
986
  id: z.string()
987
+ }),
988
+ z.object({
989
+ version: z.literal("v1").default("v1"),
990
+ type: z.literal("TASK_RUN_HEARTBEAT"),
991
+ id: z.string()
1087
992
  })
1088
993
  ]);
1089
994
  var BackgroundWorkerProperties = z.object({
@@ -1094,7 +999,8 @@ var BackgroundWorkerProperties = z.object({
1094
999
  var clientWebsocketMessages = {
1095
1000
  READY_FOR_TASKS: z.object({
1096
1001
  version: z.literal("v1").default("v1"),
1097
- backgroundWorkerId: z.string()
1002
+ backgroundWorkerId: z.string(),
1003
+ inProgressRuns: z.string().array().optional()
1098
1004
  }),
1099
1005
  BACKGROUND_WORKER_DEPRECATED: z.object({
1100
1006
  version: z.literal("v1").default("v1"),
@@ -1113,11 +1019,17 @@ var workerToChildMessages = {
1113
1019
  traceContext: z.record(z.unknown()),
1114
1020
  metadata: BackgroundWorkerProperties
1115
1021
  }),
1116
- TASK_RUN_COMPLETED_NOTIFICATION: z.object({
1117
- version: z.literal("v1").default("v1"),
1118
- completion: TaskRunExecutionResult,
1119
- execution: TaskRunExecution
1120
- }),
1022
+ TASK_RUN_COMPLETED_NOTIFICATION: z.discriminatedUnion("version", [
1023
+ z.object({
1024
+ version: z.literal("v1"),
1025
+ completion: TaskRunExecutionResult,
1026
+ execution: TaskRunExecution
1027
+ }),
1028
+ z.object({
1029
+ version: z.literal("v2"),
1030
+ completion: TaskRunExecutionResult
1031
+ })
1032
+ ]),
1121
1033
  CLEANUP: z.object({
1122
1034
  version: z.literal("v1").default("v1"),
1123
1035
  flush: z.boolean().default(false),
@@ -1158,6 +1070,10 @@ var childToWorkerMessages = {
1158
1070
  version: z.literal("v1").default("v1"),
1159
1071
  id: z.string()
1160
1072
  }),
1073
+ TASK_RUN_HEARTBEAT: z.object({
1074
+ version: z.literal("v1").default("v1"),
1075
+ id: z.string()
1076
+ }),
1161
1077
  READY_TO_DISPOSE: z.undefined(),
1162
1078
  WAIT_FOR_DURATION: z.object({
1163
1079
  version: z.literal("v1").default("v1"),
@@ -1197,6 +1113,12 @@ var ProdChildToWorkerMessages = {
1197
1113
  id: z.string()
1198
1114
  })
1199
1115
  },
1116
+ TASK_RUN_HEARTBEAT: {
1117
+ message: z.object({
1118
+ version: z.literal("v1").default("v1"),
1119
+ id: z.string()
1120
+ })
1121
+ },
1200
1122
  READY_TO_DISPOSE: {
1201
1123
  message: z.undefined()
1202
1124
  },
@@ -1261,13 +1183,19 @@ var ProdWorkerToChildMessages = {
1261
1183
  })
1262
1184
  },
1263
1185
  TASK_RUN_COMPLETED_NOTIFICATION: {
1264
- message: z.object({
1265
- version: z.literal("v1").default("v1"),
1266
- completion: TaskRunExecutionResult,
1267
- execution: TaskRunExecution
1268
- })
1269
- },
1270
- CLEANUP: {
1186
+ message: z.discriminatedUnion("version", [
1187
+ z.object({
1188
+ version: z.literal("v1"),
1189
+ completion: TaskRunExecutionResult,
1190
+ execution: TaskRunExecution
1191
+ }),
1192
+ z.object({
1193
+ version: z.literal("v2"),
1194
+ completion: TaskRunExecutionResult
1195
+ })
1196
+ ])
1197
+ },
1198
+ CLEANUP: {
1271
1199
  message: z.object({
1272
1200
  version: z.literal("v1").default("v1"),
1273
1201
  flush: z.boolean().default(false),
@@ -1393,6 +1321,17 @@ var PlatformToProviderMessages = {
1393
1321
  })
1394
1322
  }
1395
1323
  };
1324
+ var CreateWorkerMessage = z.object({
1325
+ projectRef: z.string(),
1326
+ envId: z.string(),
1327
+ deploymentId: z.string(),
1328
+ metadata: z.object({
1329
+ cliPackageVersion: z.string().optional(),
1330
+ contentHash: z.string(),
1331
+ packageVersion: z.string(),
1332
+ tasks: TaskResource.array()
1333
+ })
1334
+ });
1396
1335
  var CoordinatorToPlatformMessages = {
1397
1336
  LOG: {
1398
1337
  message: z.object({
@@ -1402,18 +1341,15 @@ var CoordinatorToPlatformMessages = {
1402
1341
  })
1403
1342
  },
1404
1343
  CREATE_WORKER: {
1405
- message: z.object({
1406
- version: z.literal("v1").default("v1"),
1407
- projectRef: z.string(),
1408
- envId: z.string(),
1409
- deploymentId: z.string(),
1410
- metadata: z.object({
1411
- cliPackageVersion: z.string().optional(),
1412
- contentHash: z.string(),
1413
- packageVersion: z.string(),
1414
- tasks: TaskResource.array()
1344
+ message: z.discriminatedUnion("version", [
1345
+ CreateWorkerMessage.extend({
1346
+ version: z.literal("v1")
1347
+ }),
1348
+ CreateWorkerMessage.extend({
1349
+ version: z.literal("v2"),
1350
+ supportsLazyAttempts: z.boolean()
1415
1351
  })
1416
- }),
1352
+ ]),
1417
1353
  callback: z.discriminatedUnion("success", [
1418
1354
  z.object({
1419
1355
  success: z.literal(false)
@@ -1423,6 +1359,23 @@ var CoordinatorToPlatformMessages = {
1423
1359
  })
1424
1360
  ])
1425
1361
  },
1362
+ CREATE_TASK_RUN_ATTEMPT: {
1363
+ message: z.object({
1364
+ version: z.literal("v1").default("v1"),
1365
+ runId: z.string(),
1366
+ envId: z.string()
1367
+ }),
1368
+ callback: z.discriminatedUnion("success", [
1369
+ z.object({
1370
+ success: z.literal(false),
1371
+ reason: z.string().optional()
1372
+ }),
1373
+ z.object({
1374
+ success: z.literal(true),
1375
+ executionPayload: ProdTaskRunExecutionPayload
1376
+ })
1377
+ ])
1378
+ },
1426
1379
  READY_FOR_EXECUTION: {
1427
1380
  message: z.object({
1428
1381
  version: z.literal("v1").default("v1"),
@@ -1439,6 +1392,24 @@ var CoordinatorToPlatformMessages = {
1439
1392
  })
1440
1393
  ])
1441
1394
  },
1395
+ READY_FOR_LAZY_ATTEMPT: {
1396
+ message: z.object({
1397
+ version: z.literal("v1").default("v1"),
1398
+ runId: z.string(),
1399
+ envId: z.string(),
1400
+ totalCompletions: z.number()
1401
+ }),
1402
+ callback: z.discriminatedUnion("success", [
1403
+ z.object({
1404
+ success: z.literal(false),
1405
+ reason: z.string().optional()
1406
+ }),
1407
+ z.object({
1408
+ success: z.literal(true),
1409
+ lazyPayload: TaskRunExecutionLazyAttemptPayload
1410
+ })
1411
+ ])
1412
+ },
1442
1413
  READY_FOR_RESUME: {
1443
1414
  message: z.object({
1444
1415
  version: z.literal("v1").default("v1"),
@@ -1457,12 +1428,24 @@ var CoordinatorToPlatformMessages = {
1457
1428
  }).optional()
1458
1429
  })
1459
1430
  },
1431
+ TASK_RUN_FAILED_TO_RUN: {
1432
+ message: z.object({
1433
+ version: z.literal("v1").default("v1"),
1434
+ completion: TaskRunFailedExecutionResult
1435
+ })
1436
+ },
1460
1437
  TASK_HEARTBEAT: {
1461
1438
  message: z.object({
1462
1439
  version: z.literal("v1").default("v1"),
1463
1440
  attemptFriendlyId: z.string()
1464
1441
  })
1465
1442
  },
1443
+ TASK_RUN_HEARTBEAT: {
1444
+ message: z.object({
1445
+ version: z.literal("v1").default("v1"),
1446
+ runId: z.string()
1447
+ })
1448
+ },
1466
1449
  CHECKPOINT_CREATED: {
1467
1450
  message: z.object({
1468
1451
  version: z.literal("v1").default("v1"),
@@ -1501,6 +1484,17 @@ var CoordinatorToPlatformMessages = {
1501
1484
  stack: z.string().optional()
1502
1485
  })
1503
1486
  })
1487
+ },
1488
+ RUN_CRASHED: {
1489
+ message: z.object({
1490
+ version: z.literal("v1").default("v1"),
1491
+ runId: z.string(),
1492
+ error: z.object({
1493
+ name: z.string(),
1494
+ message: z.string(),
1495
+ stack: z.string().optional()
1496
+ })
1497
+ })
1504
1498
  }
1505
1499
  };
1506
1500
  var PlatformToCoordinatorMessages = {
@@ -1528,6 +1522,13 @@ var PlatformToCoordinatorMessages = {
1528
1522
  attemptFriendlyId: z.string()
1529
1523
  })
1530
1524
  },
1525
+ REQUEST_RUN_CANCELLATION: {
1526
+ message: z.object({
1527
+ version: z.literal("v1").default("v1"),
1528
+ runId: z.string(),
1529
+ delayInMs: z.number().optional()
1530
+ })
1531
+ },
1531
1532
  READY_FOR_RETRY: {
1532
1533
  message: z.object({
1533
1534
  version: z.literal("v1").default("v1"),
@@ -1571,6 +1572,12 @@ var SharedQueueToClientMessages = {
1571
1572
  })
1572
1573
  }
1573
1574
  };
1575
+ var IndexTasksMessage = z.object({
1576
+ version: z.literal("v1"),
1577
+ deploymentId: z.string(),
1578
+ tasks: TaskResource.array(),
1579
+ packageVersion: z.string()
1580
+ });
1574
1581
  var ProdWorkerToCoordinatorMessages = {
1575
1582
  LOG: {
1576
1583
  message: z.object({
@@ -1580,12 +1587,15 @@ var ProdWorkerToCoordinatorMessages = {
1580
1587
  callback: z.void()
1581
1588
  },
1582
1589
  INDEX_TASKS: {
1583
- message: z.object({
1584
- version: z.literal("v1").default("v1"),
1585
- deploymentId: z.string(),
1586
- tasks: TaskResource.array(),
1587
- packageVersion: z.string()
1588
- }),
1590
+ message: z.discriminatedUnion("version", [
1591
+ IndexTasksMessage.extend({
1592
+ version: z.literal("v1")
1593
+ }),
1594
+ IndexTasksMessage.extend({
1595
+ version: z.literal("v2"),
1596
+ supportsLazyAttempts: z.boolean()
1597
+ })
1598
+ ]),
1589
1599
  callback: z.discriminatedUnion("success", [
1590
1600
  z.object({
1591
1601
  success: z.literal(false)
@@ -1602,6 +1612,13 @@ var ProdWorkerToCoordinatorMessages = {
1602
1612
  totalCompletions: z.number()
1603
1613
  })
1604
1614
  },
1615
+ READY_FOR_LAZY_ATTEMPT: {
1616
+ message: z.object({
1617
+ version: z.literal("v1").default("v1"),
1618
+ runId: z.string(),
1619
+ totalCompletions: z.number()
1620
+ })
1621
+ },
1605
1622
  READY_FOR_RESUME: {
1606
1623
  message: z.object({
1607
1624
  version: z.literal("v1").default("v1"),
@@ -1638,6 +1655,12 @@ var ProdWorkerToCoordinatorMessages = {
1638
1655
  attemptFriendlyId: z.string()
1639
1656
  })
1640
1657
  },
1658
+ TASK_RUN_HEARTBEAT: {
1659
+ message: z.object({
1660
+ version: z.literal("v1").default("v1"),
1661
+ runId: z.string()
1662
+ })
1663
+ },
1641
1664
  TASK_RUN_COMPLETED: {
1642
1665
  message: z.object({
1643
1666
  version: z.literal("v1").default("v1"),
@@ -1649,6 +1672,12 @@ var ProdWorkerToCoordinatorMessages = {
1649
1672
  shouldExit: z.boolean()
1650
1673
  })
1651
1674
  },
1675
+ TASK_RUN_FAILED_TO_RUN: {
1676
+ message: z.object({
1677
+ version: z.literal("v1").default("v1"),
1678
+ completion: TaskRunFailedExecutionResult
1679
+ })
1680
+ },
1652
1681
  WAIT_FOR_DURATION: {
1653
1682
  message: z.object({
1654
1683
  version: z.literal("v1").default("v1"),
@@ -1693,6 +1722,32 @@ var ProdWorkerToCoordinatorMessages = {
1693
1722
  stack: z.string().optional()
1694
1723
  })
1695
1724
  })
1725
+ },
1726
+ CREATE_TASK_RUN_ATTEMPT: {
1727
+ message: z.object({
1728
+ version: z.literal("v1").default("v1"),
1729
+ runId: z.string()
1730
+ }),
1731
+ callback: z.discriminatedUnion("success", [
1732
+ z.object({
1733
+ success: z.literal(false),
1734
+ reason: z.string().optional()
1735
+ }),
1736
+ z.object({
1737
+ success: z.literal(true),
1738
+ executionPayload: ProdTaskRunExecutionPayload
1739
+ })
1740
+ ])
1741
+ },
1742
+ UNRECOVERABLE_ERROR: {
1743
+ message: z.object({
1744
+ version: z.literal("v1").default("v1"),
1745
+ error: z.object({
1746
+ name: z.string(),
1747
+ message: z.string(),
1748
+ stack: z.string().optional()
1749
+ })
1750
+ })
1696
1751
  }
1697
1752
  };
1698
1753
  var CoordinatorToProdWorkerMessages = {
@@ -1716,6 +1771,12 @@ var CoordinatorToProdWorkerMessages = {
1716
1771
  executionPayload: ProdTaskRunExecutionPayload
1717
1772
  })
1718
1773
  },
1774
+ EXECUTE_TASK_RUN_LAZY_ATTEMPT: {
1775
+ message: z.object({
1776
+ version: z.literal("v1").default("v1"),
1777
+ lazyPayload: TaskRunExecutionLazyAttemptPayload
1778
+ })
1779
+ },
1719
1780
  REQUEST_ATTEMPT_CANCELLATION: {
1720
1781
  message: z.object({
1721
1782
  version: z.literal("v1").default("v1"),
@@ -1723,9 +1784,15 @@ var CoordinatorToProdWorkerMessages = {
1723
1784
  })
1724
1785
  },
1725
1786
  REQUEST_EXIT: {
1726
- message: z.object({
1727
- version: z.literal("v1").default("v1")
1728
- })
1787
+ message: z.discriminatedUnion("version", [
1788
+ z.object({
1789
+ version: z.literal("v1")
1790
+ }),
1791
+ z.object({
1792
+ version: z.literal("v2"),
1793
+ delayInMs: z.number().optional()
1794
+ })
1795
+ ])
1729
1796
  },
1730
1797
  READY_FOR_RETRY: {
1731
1798
  message: z.object({
@@ -2081,48 +2148,795 @@ var _TaskContextAPI = class _TaskContextAPI {
2081
2148
  [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
2082
2149
  };
2083
2150
  }
2084
- return {};
2151
+ return {};
2152
+ }
2153
+ disable() {
2154
+ unregisterGlobal(API_NAME);
2155
+ }
2156
+ setGlobalTaskContext(taskContext2) {
2157
+ return registerGlobal(API_NAME, taskContext2);
2158
+ }
2159
+ };
2160
+ _getTaskContext = new WeakSet();
2161
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
2162
+ return getGlobal(API_NAME);
2163
+ }, "#getTaskContext");
2164
+ __name(_TaskContextAPI, "TaskContextAPI");
2165
+ var TaskContextAPI = _TaskContextAPI;
2166
+
2167
+ // src/v3/task-context-api.ts
2168
+ var taskContext = TaskContextAPI.getInstance();
2169
+
2170
+ // src/v3/apiClient/errors.ts
2171
+ var _ApiError = class _ApiError extends Error {
2172
+ constructor(status, error, message, headers) {
2173
+ super(`${_ApiError.makeMessage(status, error, message)}`);
2174
+ this.status = status;
2175
+ this.headers = headers;
2176
+ const data = error;
2177
+ this.error = data;
2178
+ this.code = data?.["code"];
2179
+ this.param = data?.["param"];
2180
+ this.type = data?.["type"];
2181
+ }
2182
+ static makeMessage(status, error, message) {
2183
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
2184
+ if (status && msg) {
2185
+ return `${status} ${msg}`;
2186
+ }
2187
+ if (status) {
2188
+ return `${status} status code (no body)`;
2189
+ }
2190
+ if (msg) {
2191
+ return msg;
2192
+ }
2193
+ return "(no status code or body)";
2194
+ }
2195
+ static generate(status, errorResponse, message, headers) {
2196
+ if (!status) {
2197
+ return new ApiConnectionError({
2198
+ cause: castToError(errorResponse)
2199
+ });
2200
+ }
2201
+ const error = errorResponse?.["error"];
2202
+ if (status === 400) {
2203
+ return new BadRequestError(status, error, message, headers);
2204
+ }
2205
+ if (status === 401) {
2206
+ return new AuthenticationError(status, error, message, headers);
2207
+ }
2208
+ if (status === 403) {
2209
+ return new PermissionDeniedError(status, error, message, headers);
2210
+ }
2211
+ if (status === 404) {
2212
+ return new NotFoundError(status, error, message, headers);
2213
+ }
2214
+ if (status === 409) {
2215
+ return new ConflictError(status, error, message, headers);
2216
+ }
2217
+ if (status === 422) {
2218
+ return new UnprocessableEntityError(status, error, message, headers);
2219
+ }
2220
+ if (status === 429) {
2221
+ return new RateLimitError(status, error, message, headers);
2222
+ }
2223
+ if (status >= 500) {
2224
+ return new InternalServerError(status, error, message, headers);
2225
+ }
2226
+ return new _ApiError(status, error, message, headers);
2227
+ }
2228
+ };
2229
+ __name(_ApiError, "ApiError");
2230
+ var ApiError = _ApiError;
2231
+ var _ApiConnectionError = class _ApiConnectionError extends ApiError {
2232
+ constructor({ message, cause }) {
2233
+ super(void 0, void 0, message || "Connection error.", void 0);
2234
+ __publicField(this, "status");
2235
+ if (cause)
2236
+ this.cause = cause;
2237
+ }
2238
+ };
2239
+ __name(_ApiConnectionError, "ApiConnectionError");
2240
+ var ApiConnectionError = _ApiConnectionError;
2241
+ var _BadRequestError = class _BadRequestError extends ApiError {
2242
+ constructor() {
2243
+ super(...arguments);
2244
+ __publicField(this, "status", 400);
2245
+ }
2246
+ };
2247
+ __name(_BadRequestError, "BadRequestError");
2248
+ var BadRequestError = _BadRequestError;
2249
+ var _AuthenticationError = class _AuthenticationError extends ApiError {
2250
+ constructor() {
2251
+ super(...arguments);
2252
+ __publicField(this, "status", 401);
2253
+ }
2254
+ };
2255
+ __name(_AuthenticationError, "AuthenticationError");
2256
+ var AuthenticationError = _AuthenticationError;
2257
+ var _PermissionDeniedError = class _PermissionDeniedError extends ApiError {
2258
+ constructor() {
2259
+ super(...arguments);
2260
+ __publicField(this, "status", 403);
2261
+ }
2262
+ };
2263
+ __name(_PermissionDeniedError, "PermissionDeniedError");
2264
+ var PermissionDeniedError = _PermissionDeniedError;
2265
+ var _NotFoundError = class _NotFoundError extends ApiError {
2266
+ constructor() {
2267
+ super(...arguments);
2268
+ __publicField(this, "status", 404);
2269
+ }
2270
+ };
2271
+ __name(_NotFoundError, "NotFoundError");
2272
+ var NotFoundError = _NotFoundError;
2273
+ var _ConflictError = class _ConflictError extends ApiError {
2274
+ constructor() {
2275
+ super(...arguments);
2276
+ __publicField(this, "status", 409);
2277
+ }
2278
+ };
2279
+ __name(_ConflictError, "ConflictError");
2280
+ var ConflictError = _ConflictError;
2281
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends ApiError {
2282
+ constructor() {
2283
+ super(...arguments);
2284
+ __publicField(this, "status", 422);
2285
+ }
2286
+ };
2287
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
2288
+ var UnprocessableEntityError = _UnprocessableEntityError;
2289
+ var _RateLimitError = class _RateLimitError extends ApiError {
2290
+ constructor() {
2291
+ super(...arguments);
2292
+ __publicField(this, "status", 429);
2293
+ }
2294
+ };
2295
+ __name(_RateLimitError, "RateLimitError");
2296
+ var RateLimitError = _RateLimitError;
2297
+ var _InternalServerError = class _InternalServerError extends ApiError {
2298
+ };
2299
+ __name(_InternalServerError, "InternalServerError");
2300
+ var InternalServerError = _InternalServerError;
2301
+ function castToError(err) {
2302
+ if (err instanceof Error)
2303
+ return err;
2304
+ return new Error(err);
2305
+ }
2306
+ __name(castToError, "castToError");
2307
+
2308
+ // src/retry.ts
2309
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
2310
+ if (!resets)
2311
+ return;
2312
+ switch (format) {
2313
+ case "iso_8601_duration_openai_variant": {
2314
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
2315
+ }
2316
+ case "iso_8601": {
2317
+ return calculateISO8601ResetAt(resets, now);
2318
+ }
2319
+ case "unix_timestamp": {
2320
+ return calculateUnixTimestampResetAt(resets, now);
2321
+ }
2322
+ case "unix_timestamp_in_ms": {
2323
+ return calculateUnixTimestampInMsResetAt(resets, now);
2324
+ }
2325
+ }
2326
+ }
2327
+ __name(calculateResetAt, "calculateResetAt");
2328
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
2329
+ if (!resets)
2330
+ return void 0;
2331
+ const resetAt = parseInt(resets, 10);
2332
+ if (isNaN(resetAt))
2333
+ return void 0;
2334
+ return new Date(resetAt * 1e3);
2335
+ }
2336
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
2337
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
2338
+ if (!resets)
2339
+ return void 0;
2340
+ const resetAt = parseInt(resets, 10);
2341
+ if (isNaN(resetAt))
2342
+ return void 0;
2343
+ return new Date(resetAt);
2344
+ }
2345
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
2346
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
2347
+ if (!resets)
2348
+ return void 0;
2349
+ const resetAt = new Date(resets);
2350
+ if (isNaN(resetAt.getTime()))
2351
+ return void 0;
2352
+ return resetAt;
2353
+ }
2354
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
2355
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
2356
+ if (!resets)
2357
+ return void 0;
2358
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
2359
+ const match = resets.match(pattern);
2360
+ if (!match)
2361
+ return void 0;
2362
+ const days = parseInt(match[1], 10) || 0;
2363
+ const hours = parseInt(match[2], 10) || 0;
2364
+ const minutes = parseInt(match[3], 10) || 0;
2365
+ const seconds = parseFloat(match[4]) || 0;
2366
+ const milliseconds = parseInt(match[5], 10) || 0;
2367
+ const resetAt = new Date(now);
2368
+ resetAt.setDate(resetAt.getDate() + days);
2369
+ resetAt.setHours(resetAt.getHours() + hours);
2370
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
2371
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
2372
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
2373
+ return resetAt;
2374
+ }
2375
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
2376
+
2377
+ // src/v3/utils/retries.ts
2378
+ var defaultRetryOptions = {
2379
+ maxAttempts: 3,
2380
+ factor: 2,
2381
+ minTimeoutInMs: 1e3,
2382
+ maxTimeoutInMs: 6e4,
2383
+ randomize: true
2384
+ };
2385
+ var defaultFetchRetryOptions = {
2386
+ byStatus: {
2387
+ "429,408,409,5xx": {
2388
+ strategy: "backoff",
2389
+ ...defaultRetryOptions
2390
+ }
2391
+ },
2392
+ connectionError: defaultRetryOptions,
2393
+ timeout: defaultRetryOptions
2394
+ };
2395
+ function calculateNextRetryDelay(options, attempt) {
2396
+ const opts = {
2397
+ ...defaultRetryOptions,
2398
+ ...options
2399
+ };
2400
+ if (attempt >= opts.maxAttempts) {
2401
+ return;
2402
+ }
2403
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
2404
+ const random = randomize ? Math.random() + 1 : 1;
2405
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
2406
+ return Math.round(timeout);
2407
+ }
2408
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
2409
+ function calculateResetAt2(resets, format, now = Date.now()) {
2410
+ const resetAt = calculateResetAt(resets, format, new Date(now));
2411
+ return resetAt?.getTime();
2412
+ }
2413
+ __name(calculateResetAt2, "calculateResetAt");
2414
+
2415
+ // src/v3/apiClient/pagination.ts
2416
+ var _CursorPage = class _CursorPage {
2417
+ constructor(data, pagination, pageFetcher) {
2418
+ this.pageFetcher = pageFetcher;
2419
+ this.data = data;
2420
+ this.pagination = pagination;
2421
+ }
2422
+ getPaginatedItems() {
2423
+ return this.data ?? [];
2424
+ }
2425
+ hasNextPage() {
2426
+ return !!this.pagination.next;
2427
+ }
2428
+ hasPreviousPage() {
2429
+ return !!this.pagination.previous;
2430
+ }
2431
+ getNextPage() {
2432
+ if (!this.pagination.next) {
2433
+ throw new Error("No next page available");
2434
+ }
2435
+ return this.pageFetcher({
2436
+ after: this.pagination.next
2437
+ });
2438
+ }
2439
+ getPreviousPage() {
2440
+ if (!this.pagination.previous) {
2441
+ throw new Error("No previous page available");
2442
+ }
2443
+ return this.pageFetcher({
2444
+ before: this.pagination.previous
2445
+ });
2446
+ }
2447
+ async *iterPages() {
2448
+ let page = this;
2449
+ yield page;
2450
+ while (page.hasNextPage()) {
2451
+ page = await page.getNextPage();
2452
+ yield page;
2453
+ }
2454
+ }
2455
+ async *[Symbol.asyncIterator]() {
2456
+ for await (const page of this.iterPages()) {
2457
+ for (const item of page.getPaginatedItems()) {
2458
+ yield item;
2459
+ }
2460
+ }
2461
+ }
2462
+ };
2463
+ __name(_CursorPage, "CursorPage");
2464
+ var CursorPage = _CursorPage;
2465
+ var _OffsetLimitPage = class _OffsetLimitPage {
2466
+ constructor(data, pagination, pageFetcher) {
2467
+ this.pageFetcher = pageFetcher;
2468
+ this.data = data;
2469
+ this.pagination = pagination;
2470
+ }
2471
+ getPaginatedItems() {
2472
+ return this.data ?? [];
2473
+ }
2474
+ hasNextPage() {
2475
+ return this.pagination.currentPage < this.pagination.totalPages;
2476
+ }
2477
+ hasPreviousPage() {
2478
+ return this.pagination.currentPage > 1;
2479
+ }
2480
+ getNextPage() {
2481
+ if (!this.hasNextPage()) {
2482
+ throw new Error("No next page available");
2483
+ }
2484
+ return this.pageFetcher({
2485
+ page: this.pagination.currentPage + 1
2486
+ });
2487
+ }
2488
+ getPreviousPage() {
2489
+ if (!this.hasPreviousPage()) {
2490
+ throw new Error("No previous page available");
2491
+ }
2492
+ return this.pageFetcher({
2493
+ page: this.pagination.currentPage - 1
2494
+ });
2495
+ }
2496
+ async *iterPages() {
2497
+ let page = this;
2498
+ yield page;
2499
+ while (page.hasNextPage()) {
2500
+ page = await page.getNextPage();
2501
+ yield page;
2502
+ }
2503
+ }
2504
+ async *[Symbol.asyncIterator]() {
2505
+ for await (const page of this.iterPages()) {
2506
+ for (const item of page.getPaginatedItems()) {
2507
+ yield item;
2508
+ }
2509
+ }
2510
+ }
2511
+ };
2512
+ __name(_OffsetLimitPage, "OffsetLimitPage");
2513
+ var OffsetLimitPage = _OffsetLimitPage;
2514
+
2515
+ // src/v3/apiClient/core.ts
2516
+ var defaultRetryOptions2 = {
2517
+ maxAttempts: 3,
2518
+ factor: 2,
2519
+ minTimeoutInMs: 1e3,
2520
+ maxTimeoutInMs: 6e4,
2521
+ randomize: false
2522
+ };
2523
+ function zodfetch(schema, url, requestInit, options) {
2524
+ return new ApiPromise(_doZodFetch(schema, url, requestInit, options));
2525
+ }
2526
+ __name(zodfetch, "zodfetch");
2527
+ function zodfetchCursorPage(schema, url, params, requestInit, options) {
2528
+ const query = new URLSearchParams(params.query);
2529
+ if (params.limit) {
2530
+ query.set("page[size]", String(params.limit));
2531
+ }
2532
+ if (params.after) {
2533
+ query.set("page[after]", params.after);
2534
+ }
2535
+ if (params.before) {
2536
+ query.set("page[before]", params.before);
2537
+ }
2538
+ const cursorPageSchema = z.object({
2539
+ data: z.array(schema),
2540
+ pagination: z.object({
2541
+ next: z.string().optional(),
2542
+ previous: z.string().optional()
2543
+ })
2544
+ });
2545
+ const $url = new URL(url);
2546
+ $url.search = query.toString();
2547
+ const fetchResult = _doZodFetch(cursorPageSchema, $url.href, requestInit, options);
2548
+ return new CursorPagePromise(fetchResult, schema, url, params, requestInit, options);
2549
+ }
2550
+ __name(zodfetchCursorPage, "zodfetchCursorPage");
2551
+ function zodfetchOffsetLimitPage(schema, url, params, requestInit, options) {
2552
+ const query = new URLSearchParams(params.query);
2553
+ if (params.limit) {
2554
+ query.set("perPage", String(params.limit));
2555
+ }
2556
+ if (params.page) {
2557
+ query.set("page", String(params.page));
2558
+ }
2559
+ const offsetLimitPageSchema = z.object({
2560
+ data: z.array(schema),
2561
+ pagination: z.object({
2562
+ currentPage: z.coerce.number(),
2563
+ totalPages: z.coerce.number(),
2564
+ count: z.coerce.number()
2565
+ })
2566
+ });
2567
+ const $url = new URL(url);
2568
+ $url.search = query.toString();
2569
+ const fetchResult = _doZodFetch(offsetLimitPageSchema, $url.href, requestInit, options);
2570
+ return new OffsetLimitPagePromise(fetchResult, schema, url, params, requestInit, options);
2571
+ }
2572
+ __name(zodfetchOffsetLimitPage, "zodfetchOffsetLimitPage");
2573
+ function zodupload(schema, url, body, requestInit, options) {
2574
+ const finalRequestInit = createMultipartFormRequestInit(body, requestInit);
2575
+ return new ApiPromise(_doZodFetch(schema, url, finalRequestInit, options));
2576
+ }
2577
+ __name(zodupload, "zodupload");
2578
+ async function createMultipartFormRequestInit(body, requestInit) {
2579
+ const form = await createForm(body);
2580
+ const encoder = new FormDataEncoder(form);
2581
+ const finalHeaders = {};
2582
+ for (const [key, value] of Object.entries(requestInit?.headers || {})) {
2583
+ finalHeaders[key] = value;
2584
+ }
2585
+ for (const [key, value] of Object.entries(encoder.headers)) {
2586
+ finalHeaders[key] = value;
2587
+ }
2588
+ finalHeaders["Content-Length"] = String(encoder.contentLength);
2589
+ const finalRequestInit = {
2590
+ ...requestInit,
2591
+ headers: finalHeaders,
2592
+ body: Readable.from(encoder),
2593
+ // @ts-expect-error
2594
+ duplex: "half"
2595
+ };
2596
+ return finalRequestInit;
2597
+ }
2598
+ __name(createMultipartFormRequestInit, "createMultipartFormRequestInit");
2599
+ var createForm = /* @__PURE__ */ __name(async (body) => {
2600
+ const form = new FormData();
2601
+ await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
2602
+ return form;
2603
+ }, "createForm");
2604
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2605
+ try {
2606
+ const $requestInit = await requestInit;
2607
+ const response = await fetch(url, requestInitWithCache($requestInit));
2608
+ const responseHeaders = createResponseHeaders(response.headers);
2609
+ if (!response.ok) {
2610
+ const retryResult = shouldRetry(response, attempt, options?.retry);
2611
+ if (retryResult.retry) {
2612
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
2613
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2614
+ } else {
2615
+ const errText = await response.text().catch((e) => castToError2(e).message);
2616
+ const errJSON = safeJsonParse(errText);
2617
+ const errMessage = errJSON ? void 0 : errText;
2618
+ throw ApiError.generate(response.status, errJSON, errMessage, responseHeaders);
2619
+ }
2620
+ }
2621
+ const jsonBody = await response.json();
2622
+ const parsedResult = schema.safeParse(jsonBody);
2623
+ if (parsedResult.success) {
2624
+ return {
2625
+ data: parsedResult.data,
2626
+ response
2627
+ };
2628
+ }
2629
+ throw fromZodError(parsedResult.error);
2630
+ } catch (error) {
2631
+ if (error instanceof ApiError) {
2632
+ throw error;
2633
+ }
2634
+ if (options?.retry) {
2635
+ const retry = {
2636
+ ...defaultRetryOptions2,
2637
+ ...options.retry
2638
+ };
2639
+ const delay = calculateNextRetryDelay(retry, attempt);
2640
+ if (delay) {
2641
+ await new Promise((resolve) => setTimeout(resolve, delay));
2642
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2643
+ }
2644
+ }
2645
+ throw new ApiConnectionError({
2646
+ cause: castToError2(error)
2647
+ });
2648
+ }
2649
+ }
2650
+ __name(_doZodFetch, "_doZodFetch");
2651
+ function castToError2(err) {
2652
+ if (err instanceof Error)
2653
+ return err;
2654
+ return new Error(err);
2655
+ }
2656
+ __name(castToError2, "castToError");
2657
+ function shouldRetry(response, attempt, retryOptions) {
2658
+ function shouldRetryForOptions() {
2659
+ const retry = {
2660
+ ...defaultRetryOptions2,
2661
+ ...retryOptions
2662
+ };
2663
+ const delay = calculateNextRetryDelay(retry, attempt);
2664
+ if (delay) {
2665
+ return {
2666
+ retry: true,
2667
+ delay
2668
+ };
2669
+ } else {
2670
+ return {
2671
+ retry: false
2672
+ };
2673
+ }
2674
+ }
2675
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
2676
+ const shouldRetryHeader = response.headers.get("x-should-retry");
2677
+ if (shouldRetryHeader === "true")
2678
+ return shouldRetryForOptions();
2679
+ if (shouldRetryHeader === "false")
2680
+ return {
2681
+ retry: false
2682
+ };
2683
+ if (response.status === 408)
2684
+ return shouldRetryForOptions();
2685
+ if (response.status === 409)
2686
+ return shouldRetryForOptions();
2687
+ if (response.status === 429)
2688
+ return shouldRetryForOptions();
2689
+ if (response.status >= 500)
2690
+ return shouldRetryForOptions();
2691
+ return {
2692
+ retry: false
2693
+ };
2694
+ }
2695
+ __name(shouldRetry, "shouldRetry");
2696
+ function safeJsonParse(text) {
2697
+ try {
2698
+ return JSON.parse(text);
2699
+ } catch (e) {
2700
+ return void 0;
2701
+ }
2702
+ }
2703
+ __name(safeJsonParse, "safeJsonParse");
2704
+ function createResponseHeaders(headers) {
2705
+ return new Proxy(Object.fromEntries(
2706
+ // @ts-ignore
2707
+ headers.entries()
2708
+ ), {
2709
+ get(target, name) {
2710
+ const key = name.toString();
2711
+ return target[key.toLowerCase()] || target[key];
2712
+ }
2713
+ });
2714
+ }
2715
+ __name(createResponseHeaders, "createResponseHeaders");
2716
+ function requestInitWithCache(requestInit) {
2717
+ try {
2718
+ const withCache = {
2719
+ ...requestInit,
2720
+ cache: "no-cache"
2721
+ };
2722
+ const _ = new Request("http://localhost", withCache);
2723
+ return withCache;
2724
+ } catch (error) {
2725
+ return requestInit ?? {};
2726
+ }
2727
+ }
2728
+ __name(requestInitWithCache, "requestInitWithCache");
2729
+ var addFormValue = /* @__PURE__ */ __name(async (form, key, value) => {
2730
+ if (value === void 0)
2731
+ return;
2732
+ if (value == null) {
2733
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
2734
+ }
2735
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
2736
+ form.append(key, String(value));
2737
+ } else if (isUploadable(value) || isBlobLike(value) || value instanceof Buffer || value instanceof ArrayBuffer) {
2738
+ const file = await toFile(value);
2739
+ form.append(key, file);
2740
+ } else if (Array.isArray(value)) {
2741
+ await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
2742
+ } else if (typeof value === "object") {
2743
+ await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
2744
+ } else {
2745
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
2746
+ }
2747
+ }, "addFormValue");
2748
+ async function toFile(value, name, options) {
2749
+ value = await value;
2750
+ options ??= isFileLike(value) ? {
2751
+ lastModified: value.lastModified,
2752
+ type: value.type
2753
+ } : {};
2754
+ if (isResponseLike(value)) {
2755
+ const blob = await value.blob();
2756
+ name ||= new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file";
2757
+ return new File([
2758
+ blob
2759
+ ], name, options);
2760
+ }
2761
+ const bits = await getBytes(value);
2762
+ name ||= getName(value) ?? "unknown_file";
2763
+ if (!options.type) {
2764
+ const type = bits[0]?.type;
2765
+ if (typeof type === "string") {
2766
+ options = {
2767
+ ...options,
2768
+ type
2769
+ };
2770
+ }
2085
2771
  }
2086
- disable() {
2087
- unregisterGlobal(API_NAME);
2772
+ return new File(bits, name, options);
2773
+ }
2774
+ __name(toFile, "toFile");
2775
+ function getName(value) {
2776
+ return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream
2777
+ getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop();
2778
+ }
2779
+ __name(getName, "getName");
2780
+ var getStringFromMaybeBuffer = /* @__PURE__ */ __name((x) => {
2781
+ if (typeof x === "string")
2782
+ return x;
2783
+ if (typeof Buffer !== "undefined" && x instanceof Buffer)
2784
+ return String(x);
2785
+ return void 0;
2786
+ }, "getStringFromMaybeBuffer");
2787
+ async function getBytes(value) {
2788
+ let parts = [];
2789
+ if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
2790
+ value instanceof ArrayBuffer) {
2791
+ parts.push(value);
2792
+ } else if (isBlobLike(value)) {
2793
+ parts.push(await value.arrayBuffer());
2794
+ } else if (isAsyncIterableIterator(value)) {
2795
+ for await (const chunk of value) {
2796
+ parts.push(chunk);
2797
+ }
2798
+ } else {
2799
+ throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);
2088
2800
  }
2089
- setGlobalTaskContext(taskContext2) {
2090
- return registerGlobal(API_NAME, taskContext2);
2801
+ return parts;
2802
+ }
2803
+ __name(getBytes, "getBytes");
2804
+ function propsForError(value) {
2805
+ const props = Object.getOwnPropertyNames(value);
2806
+ return `[${props.map((p) => `"${p}"`).join(", ")}]`;
2807
+ }
2808
+ __name(propsForError, "propsForError");
2809
+ var isAsyncIterableIterator = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterableIterator");
2810
+ var isResponseLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", "isResponseLike");
2811
+ var isFileLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), "isFileLike");
2812
+ var isBlobLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", "isBlobLike");
2813
+ var isFsReadStream = /* @__PURE__ */ __name((value) => value instanceof Readable, "isFsReadStream");
2814
+ var isUploadable = /* @__PURE__ */ __name((value) => {
2815
+ return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);
2816
+ }, "isUploadable");
2817
+ var isRecordLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => typeof key === "string" && typeof value[key] === "string"), "isRecordLike");
2818
+ var _ApiPromise = class _ApiPromise extends Promise {
2819
+ constructor(responsePromise) {
2820
+ super((resolve) => {
2821
+ resolve(null);
2822
+ });
2823
+ this.responsePromise = responsePromise;
2824
+ }
2825
+ /**
2826
+ * Gets the raw `Response` instance instead of parsing the response
2827
+ * data.
2828
+ *
2829
+ * If you want to parse the response body but still get the `Response`
2830
+ * instance, you can use {@link withResponse()}.
2831
+ */
2832
+ asResponse() {
2833
+ return this.responsePromise.then((p) => p.response);
2834
+ }
2835
+ /**
2836
+ * Gets the parsed response data and the raw `Response` instance.
2837
+ *
2838
+ * If you just want to get the raw `Response` instance without parsing it,
2839
+ * you can use {@link asResponse()}.
2840
+ */
2841
+ async withResponse() {
2842
+ const [data, response] = await Promise.all([
2843
+ this.parse(),
2844
+ this.asResponse()
2845
+ ]);
2846
+ return {
2847
+ data,
2848
+ response
2849
+ };
2850
+ }
2851
+ parse() {
2852
+ return this.responsePromise.then((result) => result.data);
2853
+ }
2854
+ then(onfulfilled, onrejected) {
2855
+ return this.parse().then(onfulfilled, onrejected);
2856
+ }
2857
+ catch(onrejected) {
2858
+ return this.parse().catch(onrejected);
2859
+ }
2860
+ finally(onfinally) {
2861
+ return this.parse().finally(onfinally);
2091
2862
  }
2092
2863
  };
2093
- _getTaskContext = new WeakSet();
2094
- getTaskContext_fn = /* @__PURE__ */ __name(function() {
2095
- return getGlobal(API_NAME);
2096
- }, "#getTaskContext");
2097
- __name(_TaskContextAPI, "TaskContextAPI");
2098
- var TaskContextAPI = _TaskContextAPI;
2099
-
2100
- // src/v3/task-context-api.ts
2101
- var taskContext = TaskContextAPI.getInstance();
2102
-
2103
- // package.json
2104
- var version = "0.0.0-v3-prerelease-20240517090458";
2105
- var dependencies = {
2106
- "@google-cloud/precise-date": "^4.0.0",
2107
- "@opentelemetry/api": "^1.8.0",
2108
- "@opentelemetry/api-logs": "^0.48.0",
2109
- "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
2110
- "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
2111
- "@opentelemetry/instrumentation": "^0.49.1",
2112
- "@opentelemetry/resources": "^1.22.0",
2113
- "@opentelemetry/sdk-logs": "^0.49.1",
2114
- "@opentelemetry/sdk-node": "^0.49.1",
2115
- "@opentelemetry/sdk-trace-base": "^1.22.0",
2116
- "@opentelemetry/sdk-trace-node": "^1.22.0",
2117
- "@opentelemetry/semantic-conventions": "^1.22.0",
2118
- "humanize-duration": "^3.27.3",
2119
- superjson: "^2.2.1",
2120
- ulidx: "^2.2.1",
2121
- zod: "3.22.3",
2122
- "zod-error": "1.5.0",
2123
- "zod-validation-error": "^1.5.0",
2124
- "socket.io-client": "4.7.4"
2864
+ __name(_ApiPromise, "ApiPromise");
2865
+ var ApiPromise = _ApiPromise;
2866
+ var _fetchPage, fetchPage_fn;
2867
+ var _CursorPagePromise = class _CursorPagePromise extends ApiPromise {
2868
+ constructor(result, schema, url, params, requestInit, options) {
2869
+ super(result.then((result2) => ({
2870
+ data: new CursorPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage, fetchPage_fn).bind(this)),
2871
+ response: result2.response
2872
+ })));
2873
+ __privateAdd(this, _fetchPage);
2874
+ this.schema = schema;
2875
+ this.url = url;
2876
+ this.params = params;
2877
+ this.requestInit = requestInit;
2878
+ this.options = options;
2879
+ }
2880
+ /**
2881
+ * Allow auto-paginating iteration on an unawaited list call, eg:
2882
+ *
2883
+ * for await (const item of client.items.list()) {
2884
+ * console.log(item)
2885
+ * }
2886
+ */
2887
+ async *[Symbol.asyncIterator]() {
2888
+ const page = await this;
2889
+ for await (const item of page) {
2890
+ yield item;
2891
+ }
2892
+ }
2125
2893
  };
2894
+ _fetchPage = new WeakSet();
2895
+ fetchPage_fn = /* @__PURE__ */ __name(function(params) {
2896
+ return zodfetchCursorPage(this.schema, this.url, {
2897
+ ...this.params,
2898
+ ...params
2899
+ }, this.requestInit, this.options);
2900
+ }, "#fetchPage");
2901
+ __name(_CursorPagePromise, "CursorPagePromise");
2902
+ var CursorPagePromise = _CursorPagePromise;
2903
+ var _fetchPage2, fetchPage_fn2;
2904
+ var _OffsetLimitPagePromise = class _OffsetLimitPagePromise extends ApiPromise {
2905
+ constructor(result, schema, url, params, requestInit, options) {
2906
+ super(result.then((result2) => ({
2907
+ data: new OffsetLimitPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage2, fetchPage_fn2).bind(this)),
2908
+ response: result2.response
2909
+ })));
2910
+ __privateAdd(this, _fetchPage2);
2911
+ this.schema = schema;
2912
+ this.url = url;
2913
+ this.params = params;
2914
+ this.requestInit = requestInit;
2915
+ this.options = options;
2916
+ }
2917
+ /**
2918
+ * Allow auto-paginating iteration on an unawaited list call, eg:
2919
+ *
2920
+ * for await (const item of client.items.list()) {
2921
+ * console.log(item)
2922
+ * }
2923
+ */
2924
+ async *[Symbol.asyncIterator]() {
2925
+ const page = await this;
2926
+ for await (const item of page) {
2927
+ yield item;
2928
+ }
2929
+ }
2930
+ };
2931
+ _fetchPage2 = new WeakSet();
2932
+ fetchPage_fn2 = /* @__PURE__ */ __name(function(params1) {
2933
+ return zodfetchOffsetLimitPage(this.schema, this.url, {
2934
+ ...this.params,
2935
+ ...params1
2936
+ }, this.requestInit, this.options);
2937
+ }, "#fetchPage");
2938
+ __name(_OffsetLimitPagePromise, "OffsetLimitPagePromise");
2939
+ var OffsetLimitPagePromise = _OffsetLimitPagePromise;
2126
2940
 
2127
2941
  // src/v3/apiClient/index.ts
2128
2942
  var zodFetchOptions = {
@@ -2148,7 +2962,7 @@ var _ApiClient = class _ApiClient {
2148
2962
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2149
2963
  }, zodFetchOptions);
2150
2964
  } catch (error) {
2151
- if (error instanceof APIError) {
2965
+ if (error instanceof ApiError) {
2152
2966
  if (error.status === 404) {
2153
2967
  return void 0;
2154
2968
  }
@@ -2163,14 +2977,16 @@ var _ApiClient = class _ApiClient {
2163
2977
  }, zodFetchOptions);
2164
2978
  }
2165
2979
  triggerTask(taskId, body, options) {
2166
- return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
2980
+ const encodedTaskId = encodeURIComponent(taskId);
2981
+ return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/trigger`, {
2167
2982
  method: "POST",
2168
2983
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2169
2984
  body: JSON.stringify(body)
2170
2985
  }, zodFetchOptions);
2171
2986
  }
2172
2987
  batchTriggerTask(taskId, body, options) {
2173
- return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
2988
+ const encodedTaskId = encodeURIComponent(taskId);
2989
+ return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/batch`, {
2174
2990
  method: "POST",
2175
2991
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2176
2992
  body: JSON.stringify(body)
@@ -2194,6 +3010,33 @@ var _ApiClient = class _ApiClient {
2194
3010
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2195
3011
  }, zodFetchOptions);
2196
3012
  }
3013
+ listRuns(query) {
3014
+ const searchParams = createSearchQueryForListRuns(query);
3015
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/runs`, {
3016
+ query: searchParams,
3017
+ limit: query?.limit,
3018
+ after: query?.after,
3019
+ before: query?.before
3020
+ }, {
3021
+ method: "GET",
3022
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3023
+ }, zodFetchOptions);
3024
+ }
3025
+ listProjectRuns(projectRef, query) {
3026
+ const searchParams = createSearchQueryForListRuns(query);
3027
+ if (query?.env) {
3028
+ searchParams.append("filter[env]", Array.isArray(query.env) ? query.env.join(",") : query.env);
3029
+ }
3030
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/projects/${projectRef}/runs`, {
3031
+ query: searchParams,
3032
+ limit: query?.limit,
3033
+ after: query?.after,
3034
+ before: query?.before
3035
+ }, {
3036
+ method: "GET",
3037
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3038
+ }, zodFetchOptions);
3039
+ }
2197
3040
  replayRun(runId) {
2198
3041
  return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2199
3042
  method: "POST",
@@ -2221,7 +3064,10 @@ var _ApiClient = class _ApiClient {
2221
3064
  if (options?.perPage) {
2222
3065
  searchParams.append("perPage", options.perPage.toString());
2223
3066
  }
2224
- return zodfetch(ListSchedulesResult, `${this.baseUrl}/api/v1/schedules${searchParams.size > 0 ? `?${searchParams}` : ""}`, {
3067
+ return zodfetchOffsetLimitPage(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
3068
+ page: options?.page,
3069
+ limit: options?.perPage
3070
+ }, {
2225
3071
  method: "GET",
2226
3072
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2227
3073
  });
@@ -2257,6 +3103,52 @@ var _ApiClient = class _ApiClient {
2257
3103
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2258
3104
  });
2259
3105
  }
3106
+ listEnvVars(projectRef, slug) {
3107
+ return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
3108
+ method: "GET",
3109
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3110
+ });
3111
+ }
3112
+ importEnvVars(projectRef, slug, body) {
3113
+ if (isRecordLike(body.variables)) {
3114
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
3115
+ method: "POST",
3116
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3117
+ body: JSON.stringify(body)
3118
+ });
3119
+ } else {
3120
+ return zodupload(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, body, {
3121
+ method: "POST",
3122
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3123
+ });
3124
+ }
3125
+ }
3126
+ retrieveEnvVar(projectRef, slug, key) {
3127
+ return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3128
+ method: "GET",
3129
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3130
+ });
3131
+ }
3132
+ createEnvVar(projectRef, slug, body) {
3133
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
3134
+ method: "POST",
3135
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3136
+ body: JSON.stringify(body)
3137
+ });
3138
+ }
3139
+ updateEnvVar(projectRef, slug, key, body) {
3140
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3141
+ method: "PUT",
3142
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3143
+ body: JSON.stringify(body)
3144
+ });
3145
+ }
3146
+ deleteEnvVar(projectRef, slug, key) {
3147
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3148
+ method: "DELETE",
3149
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3150
+ });
3151
+ }
2260
3152
  };
2261
3153
  _getHeaders = new WeakSet();
2262
3154
  getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
@@ -2276,6 +3168,40 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2276
3168
  }, "#getHeaders");
2277
3169
  __name(_ApiClient, "ApiClient");
2278
3170
  var ApiClient = _ApiClient;
3171
+ function createSearchQueryForListRuns(query) {
3172
+ const searchParams = new URLSearchParams();
3173
+ if (query) {
3174
+ if (query.status) {
3175
+ searchParams.append("filter[status]", Array.isArray(query.status) ? query.status.join(",") : query.status);
3176
+ }
3177
+ if (query.taskIdentifier) {
3178
+ searchParams.append("filter[taskIdentifier]", Array.isArray(query.taskIdentifier) ? query.taskIdentifier.join(",") : query.taskIdentifier);
3179
+ }
3180
+ if (query.version) {
3181
+ searchParams.append("filter[version]", Array.isArray(query.version) ? query.version.join(",") : query.version);
3182
+ }
3183
+ if (query.bulkAction) {
3184
+ searchParams.append("filter[bulkAction]", query.bulkAction);
3185
+ }
3186
+ if (query.schedule) {
3187
+ searchParams.append("filter[schedule]", query.schedule);
3188
+ }
3189
+ if (typeof query.isTest === "boolean") {
3190
+ searchParams.append("filter[isTest]", String(query.isTest));
3191
+ }
3192
+ if (query.from) {
3193
+ searchParams.append("filter[createdAt][from]", query.from instanceof Date ? query.from.getTime().toString() : query.from.toString());
3194
+ }
3195
+ if (query.to) {
3196
+ searchParams.append("filter[createdAt][to]", query.to instanceof Date ? query.to.getTime().toString() : query.to.toString());
3197
+ }
3198
+ if (query.period) {
3199
+ searchParams.append("filter[createdAt][period]", query.period);
3200
+ }
3201
+ }
3202
+ return searchParams;
3203
+ }
3204
+ __name(createSearchQueryForListRuns, "createSearchQueryForListRuns");
2279
3205
  var _SimpleClock = class _SimpleClock {
2280
3206
  preciseNow() {
2281
3207
  const now = new PreciseDate();
@@ -2325,145 +3251,6 @@ var ClockAPI = _ClockAPI;
2325
3251
  // src/v3/clock-api.ts
2326
3252
  var clock = ClockAPI.getInstance();
2327
3253
 
2328
- // src/v3/errors.ts
2329
- function parseError(error) {
2330
- if (error instanceof Error) {
2331
- return {
2332
- type: "BUILT_IN_ERROR",
2333
- name: error.name,
2334
- message: error.message,
2335
- stackTrace: error.stack ?? ""
2336
- };
2337
- }
2338
- if (typeof error === "string") {
2339
- return {
2340
- type: "STRING_ERROR",
2341
- raw: error
2342
- };
2343
- }
2344
- try {
2345
- return {
2346
- type: "CUSTOM_ERROR",
2347
- raw: JSON.stringify(error)
2348
- };
2349
- } catch (e) {
2350
- return {
2351
- type: "CUSTOM_ERROR",
2352
- raw: String(error)
2353
- };
2354
- }
2355
- }
2356
- __name(parseError, "parseError");
2357
- function createErrorTaskError(error) {
2358
- switch (error.type) {
2359
- case "BUILT_IN_ERROR": {
2360
- const e = new Error(error.message);
2361
- e.name = error.name;
2362
- e.stack = error.stackTrace;
2363
- return e;
2364
- }
2365
- case "STRING_ERROR": {
2366
- return error.raw;
2367
- }
2368
- case "CUSTOM_ERROR": {
2369
- return JSON.parse(error.raw);
2370
- }
2371
- case "INTERNAL_ERROR": {
2372
- return new Error(`trigger.dev internal error (${error.code})`);
2373
- }
2374
- }
2375
- }
2376
- __name(createErrorTaskError, "createErrorTaskError");
2377
- function createJsonErrorObject(error) {
2378
- switch (error.type) {
2379
- case "BUILT_IN_ERROR": {
2380
- return {
2381
- name: error.name,
2382
- message: error.message,
2383
- stackTrace: error.stackTrace
2384
- };
2385
- }
2386
- case "STRING_ERROR": {
2387
- return {
2388
- message: error.raw
2389
- };
2390
- }
2391
- case "CUSTOM_ERROR": {
2392
- return {
2393
- message: error.raw
2394
- };
2395
- }
2396
- case "INTERNAL_ERROR": {
2397
- return {
2398
- message: `trigger.dev internal error (${error.code})`
2399
- };
2400
- }
2401
- }
2402
- }
2403
- __name(createJsonErrorObject, "createJsonErrorObject");
2404
- function correctErrorStackTrace(stackTrace, projectDir, options) {
2405
- const [errorLine, ...traceLines] = stackTrace.split("\n");
2406
- return [
2407
- options?.removeFirstLine ? void 0 : errorLine,
2408
- ...traceLines.map((line) => correctStackTraceLine(line, projectDir))
2409
- ].filter(Boolean).join("\n");
2410
- }
2411
- __name(correctErrorStackTrace, "correctErrorStackTrace");
2412
- var LINES_TO_IGNORE = [
2413
- /ConsoleInterceptor/,
2414
- /TriggerTracer/,
2415
- /TaskExecutor/,
2416
- /EXECUTE_TASK_RUN/,
2417
- /@trigger.dev\/core/,
2418
- /safeJsonProcess/,
2419
- /__entryPoint.ts/
2420
- ];
2421
- function correctStackTraceLine(line, projectDir) {
2422
- if (LINES_TO_IGNORE.some((regex) => regex.test(line))) {
2423
- return;
2424
- }
2425
- if (projectDir && !line.includes(projectDir)) {
2426
- return;
2427
- }
2428
- return line.trim();
2429
- }
2430
- __name(correctStackTraceLine, "correctStackTraceLine");
2431
- function groupTaskMetadataIssuesByTask(tasks, issues) {
2432
- return issues.reduce((acc, issue) => {
2433
- if (issue.path.length === 0) {
2434
- return acc;
2435
- }
2436
- const taskIndex = issue.path[1];
2437
- if (typeof taskIndex !== "number") {
2438
- return acc;
2439
- }
2440
- const task = tasks[taskIndex];
2441
- if (!task) {
2442
- return acc;
2443
- }
2444
- const restOfPath = issue.path.slice(2);
2445
- const taskId = task.id;
2446
- const taskName = task.exportName;
2447
- const filePath = task.filePath;
2448
- const key = taskIndex;
2449
- const existing = acc[key] ?? {
2450
- id: taskId,
2451
- exportName: taskName,
2452
- filePath,
2453
- issues: []
2454
- };
2455
- existing.issues.push({
2456
- message: issue.message,
2457
- path: restOfPath.length === 0 ? void 0 : restOfPath.join(".")
2458
- });
2459
- return {
2460
- ...acc,
2461
- [key]: existing
2462
- };
2463
- }, {});
2464
- }
2465
- __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
2466
-
2467
3254
  // src/v3/limits.ts
2468
3255
  var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2469
3256
  var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
@@ -2803,7 +3590,7 @@ var _APIClientManagerAPI = class _APIClientManagerAPI {
2803
3590
  }
2804
3591
  get accessToken() {
2805
3592
  const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2806
- return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY");
3593
+ return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY") ?? getEnvVar("TRIGGER_ACCESS_TOKEN");
2807
3594
  }
2808
3595
  get client() {
2809
3596
  if (!this.baseURL || !this.accessToken) {
@@ -3495,6 +4282,6 @@ function safeJsonParse2(value) {
3495
4282
  }
3496
4283
  __name(safeJsonParse2, "safeJsonParse");
3497
4284
 
3498
- export { APIConnectionError, APIError, ApiClient, AttemptStatus, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, DeletedScheduleObject, DeploymentErrorData, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListScheduleOptions, ListSchedulesResult, Machine, MachineCpu, MachineMemory, NULL_SENTINEL, NotFoundError, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetrieveRunResponse, RetryOptions, RunStatus, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SharedQueueToClientMessages, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskEventStyle, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createJsonErrorObject, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, groupTaskMetadataIssuesByTask, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseError, parsePacket, prettyPrintPacket, primitiveValueOrflattenedAttributes, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContext, unflattenAttributes, workerToChildMessages };
4285
+ export { ApiClient, ApiConnectionError, ApiError, AttemptStatus, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateEnvironmentVariableRequestBody, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, CursorPage, DeletedScheduleObject, DeploymentErrorData, EnvironmentType, EnvironmentVariable, EnvironmentVariableResponseBody, EnvironmentVariableValue, EnvironmentVariables, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, ImportEnvironmentVariablesRequestBody, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListRunResponse, ListRunResponseItem, ListScheduleOptions, ListSchedulesResult, Machine, MachineCpu, MachineMemory, NULL_SENTINEL, NotFoundError, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OffsetLimitPage, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetrieveRunResponse, RetryOptions, RunEnvironmentDetails, RunScheduleDetails, RunStatus, ScheduleGenerator, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SerializedError, SharedQueueToClientMessages, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskEventStyle, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionLazyAttemptPayload, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateEnvironmentVariableRequestBody, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createJsonErrorObject, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, groupTaskMetadataIssuesByTask, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseError, parsePacket, prettyPrintPacket, primitiveValueOrflattenedAttributes, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContext, unflattenAttributes, workerToChildMessages };
3499
4286
  //# sourceMappingURL=out.js.map
3500
4287
  //# sourceMappingURL=index.mjs.map