@trigger.dev/core 3.0.0-beta.33 → 3.0.0-beta.35

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 (59) hide show
  1. package/dist/catalog-BUwiuDbt.d.mts +202 -0
  2. package/dist/catalog-eKgqBHUA.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-uPyMRN8k.d.mts} +24 -23
  10. package/dist/{manager-WNMVbgHf.d.ts → manager-uPyMRN8k.d.ts} +24 -23
  11. package/dist/{messages-vq7Bk4Ap.d.mts → messages-l9PdIyKF.d.mts} +4975 -1072
  12. package/dist/{messages-vq7Bk4Ap.d.ts → messages-l9PdIyKF.d.ts} +4975 -1072
  13. package/dist/{catalog-KbyTBoap.d.ts → schemas-b8tRw8dX.d.mts} +21 -186
  14. package/dist/{catalog-ck7x04PV.d.mts → schemas-b8tRw8dX.d.ts} +21 -186
  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 +121 -7
  22. package/dist/v3/index.d.ts +121 -7
  23. package/dist/v3/index.js +735 -352
  24. package/dist/v3/index.js.map +1 -1
  25. package/dist/v3/index.mjs +728 -353
  26. package/dist/v3/index.mjs.map +1 -1
  27. package/dist/v3/otel/index.js +5 -1
  28. package/dist/v3/otel/index.js.map +1 -1
  29. package/dist/v3/otel/index.mjs +5 -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 +204 -9
  40. package/dist/v3/workers/index.js.map +1 -1
  41. package/dist/v3/workers/index.mjs +204 -9
  42. package/dist/v3/workers/index.mjs.map +1 -1
  43. package/dist/v3/zodMessageHandler.d.mts +1 -1
  44. package/dist/v3/zodMessageHandler.d.ts +1 -1
  45. package/dist/v3/zodNamespace.js +16 -6
  46. package/dist/v3/zodNamespace.js.map +1 -1
  47. package/dist/v3/zodNamespace.mjs +17 -7
  48. package/dist/v3/zodNamespace.mjs.map +1 -1
  49. package/dist/v3/zodSocket.js +16 -6
  50. package/dist/v3/zodSocket.js.map +1 -1
  51. package/dist/v3/zodSocket.mjs +17 -7
  52. package/dist/v3/zodSocket.mjs.map +1 -1
  53. package/dist/v3/zodfetch.d.mts +78 -0
  54. package/dist/v3/zodfetch.d.ts +78 -0
  55. package/dist/v3/zodfetch.js +446 -0
  56. package/dist/v3/zodfetch.js.map +1 -0
  57. package/dist/v3/zodfetch.mjs +433 -0
  58. package/dist/v3/zodfetch.mjs.map +1 -0
  59. package/package.json +13 -4
package/dist/v3/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  'use strict';
2
2
 
3
3
  var api = require('@opentelemetry/api');
4
- var zodValidationError = require('zod-validation-error');
5
4
  var zod = require('zod');
5
+ var zodValidationError = require('zod-validation-error');
6
+ var formDataEncoder = require('form-data-encoder');
7
+ var stream = require('stream');
6
8
  var preciseDate = require('@google-cloud/precise-date');
7
9
  var apiLogs = require('@opentelemetry/api-logs');
8
10
  var humanizeDuration = require('humanize-duration');
@@ -32,6 +34,31 @@ var __privateMethod = (obj, member, method) => {
32
34
  return method;
33
35
  };
34
36
 
37
+ // package.json
38
+ var version = "3.0.0-beta.35";
39
+ var dependencies = {
40
+ "@google-cloud/precise-date": "^4.0.0",
41
+ "@opentelemetry/api": "^1.8.0",
42
+ "@opentelemetry/api-logs": "^0.48.0",
43
+ "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
44
+ "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
45
+ "@opentelemetry/instrumentation": "^0.49.1",
46
+ "@opentelemetry/resources": "^1.22.0",
47
+ "@opentelemetry/sdk-logs": "^0.49.1",
48
+ "@opentelemetry/sdk-node": "^0.49.1",
49
+ "@opentelemetry/sdk-trace-base": "^1.22.0",
50
+ "@opentelemetry/sdk-trace-node": "^1.22.0",
51
+ "@opentelemetry/semantic-conventions": "^1.22.0",
52
+ "form-data-encoder": "^4.0.2",
53
+ "humanize-duration": "^3.27.3",
54
+ "socket.io-client": "4.7.4",
55
+ superjson: "^2.2.1",
56
+ ulidx: "^2.2.1",
57
+ zod: "3.22.3",
58
+ "zod-error": "1.5.0",
59
+ "zod-validation-error": "^1.5.0"
60
+ };
61
+
35
62
  // src/v3/apiErrors.ts
36
63
  var _APIError = class _APIError extends Error {
37
64
  constructor(status, error, message, headers) {
@@ -169,286 +196,46 @@ function castToError(err) {
169
196
  return new Error(err);
170
197
  }
171
198
  __name(castToError, "castToError");
172
-
173
- // src/retry.ts
174
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
175
- if (!resets)
176
- return;
177
- switch (format) {
178
- case "iso_8601_duration_openai_variant": {
179
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
180
- }
181
- case "iso_8601": {
182
- return calculateISO8601ResetAt(resets, now);
183
- }
184
- case "unix_timestamp": {
185
- return calculateUnixTimestampResetAt(resets, now);
186
- }
187
- case "unix_timestamp_in_ms": {
188
- return calculateUnixTimestampInMsResetAt(resets, now);
189
- }
190
- }
191
- }
192
- __name(calculateResetAt, "calculateResetAt");
193
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
194
- if (!resets)
195
- return void 0;
196
- const resetAt = parseInt(resets, 10);
197
- if (isNaN(resetAt))
198
- return void 0;
199
- return new Date(resetAt * 1e3);
200
- }
201
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
202
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
203
- if (!resets)
204
- return void 0;
205
- const resetAt = parseInt(resets, 10);
206
- if (isNaN(resetAt))
207
- return void 0;
208
- return new Date(resetAt);
209
- }
210
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
211
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
212
- if (!resets)
213
- return void 0;
214
- const resetAt = new Date(resets);
215
- if (isNaN(resetAt.getTime()))
216
- return void 0;
217
- return resetAt;
218
- }
219
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
220
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
221
- if (!resets)
222
- return void 0;
223
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
224
- const match = resets.match(pattern);
225
- if (!match)
226
- return void 0;
227
- const days = parseInt(match[1], 10) || 0;
228
- const hours = parseInt(match[2], 10) || 0;
229
- const minutes = parseInt(match[3], 10) || 0;
230
- const seconds = parseFloat(match[4]) || 0;
231
- const milliseconds = parseInt(match[5], 10) || 0;
232
- const resetAt = new Date(now);
233
- resetAt.setDate(resetAt.getDate() + days);
234
- resetAt.setHours(resetAt.getHours() + hours);
235
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
236
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
237
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
238
- return resetAt;
239
- }
240
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
241
-
242
- // src/v3/utils/retries.ts
243
- var defaultRetryOptions = {
244
- maxAttempts: 3,
245
- factor: 2,
246
- minTimeoutInMs: 1e3,
247
- maxTimeoutInMs: 6e4,
248
- randomize: true
249
- };
250
- var defaultFetchRetryOptions = {
251
- byStatus: {
252
- "429,408,409,5xx": {
253
- strategy: "backoff",
254
- ...defaultRetryOptions
255
- }
256
- },
257
- connectionError: defaultRetryOptions,
258
- timeout: defaultRetryOptions
259
- };
260
- function calculateNextRetryDelay(options, attempt) {
261
- const opts = {
262
- ...defaultRetryOptions,
263
- ...options
264
- };
265
- if (attempt >= opts.maxAttempts) {
266
- return;
267
- }
268
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
269
- const random = randomize ? Math.random() + 1 : 1;
270
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
271
- return Math.round(timeout);
272
- }
273
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
274
- function calculateResetAt2(resets, format, now = Date.now()) {
275
- const resetAt = calculateResetAt(resets, format, new Date(now));
276
- return resetAt?.getTime();
277
- }
278
- __name(calculateResetAt2, "calculateResetAt");
279
-
280
- // src/v3/zodfetch.ts
281
- var defaultRetryOptions2 = {
282
- maxAttempts: 3,
283
- factor: 2,
284
- minTimeoutInMs: 1e3,
285
- maxTimeoutInMs: 6e4,
286
- randomize: false
287
- };
288
- async function zodfetch(schema, url, requestInit, options) {
289
- return await _doZodFetch(schema, url, requestInit, options);
290
- }
291
- __name(zodfetch, "zodfetch");
292
- async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
293
- try {
294
- const response = await fetch(url, requestInitWithCache(requestInit));
295
- const responseHeaders = createResponseHeaders(response.headers);
296
- if (!response.ok) {
297
- const retryResult = shouldRetry(response, attempt, options?.retry);
298
- if (retryResult.retry) {
299
- await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
300
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
301
- } else {
302
- const errText = await response.text().catch((e) => castToError2(e).message);
303
- const errJSON = safeJsonParse(errText);
304
- const errMessage = errJSON ? void 0 : errText;
305
- throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
306
- }
307
- }
308
- const jsonBody = await response.json();
309
- const parsedResult = schema.safeParse(jsonBody);
310
- if (parsedResult.success) {
311
- return parsedResult.data;
312
- }
313
- throw zodValidationError.fromZodError(parsedResult.error);
314
- } catch (error) {
315
- if (error instanceof APIError) {
316
- throw error;
317
- }
318
- if (options?.retry) {
319
- const retry = {
320
- ...defaultRetryOptions2,
321
- ...options.retry
322
- };
323
- const delay = calculateNextRetryDelay(retry, attempt);
324
- if (delay) {
325
- await new Promise((resolve) => setTimeout(resolve, delay));
326
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
327
- }
328
- }
329
- throw new APIConnectionError({
330
- cause: castToError2(error)
331
- });
332
- }
333
- }
334
- __name(_doZodFetch, "_doZodFetch");
335
- function castToError2(err) {
336
- if (err instanceof Error)
337
- return err;
338
- return new Error(err);
339
- }
340
- __name(castToError2, "castToError");
341
- function shouldRetry(response, attempt, retryOptions) {
342
- function shouldRetryForOptions() {
343
- const retry = {
344
- ...defaultRetryOptions2,
345
- ...retryOptions
346
- };
347
- const delay = calculateNextRetryDelay(retry, attempt);
348
- if (delay) {
349
- return {
350
- retry: true,
351
- delay
352
- };
353
- } else {
354
- return {
355
- retry: false
356
- };
357
- }
358
- }
359
- __name(shouldRetryForOptions, "shouldRetryForOptions");
360
- const shouldRetryHeader = response.headers.get("x-should-retry");
361
- if (shouldRetryHeader === "true")
362
- return shouldRetryForOptions();
363
- if (shouldRetryHeader === "false")
364
- return {
365
- retry: false
366
- };
367
- if (response.status === 408)
368
- return shouldRetryForOptions();
369
- if (response.status === 409)
370
- return shouldRetryForOptions();
371
- if (response.status === 429)
372
- return shouldRetryForOptions();
373
- if (response.status >= 500)
374
- return shouldRetryForOptions();
375
- return {
376
- retry: false
377
- };
378
- }
379
- __name(shouldRetry, "shouldRetry");
380
- function safeJsonParse(text) {
381
- try {
382
- return JSON.parse(text);
383
- } catch (e) {
384
- return void 0;
385
- }
386
- }
387
- __name(safeJsonParse, "safeJsonParse");
388
- function createResponseHeaders(headers) {
389
- return new Proxy(Object.fromEntries(
390
- // @ts-ignore
391
- headers.entries()
392
- ), {
393
- get(target, name) {
394
- const key = name.toString();
395
- return target[key.toLowerCase()] || target[key];
396
- }
397
- });
398
- }
399
- __name(createResponseHeaders, "createResponseHeaders");
400
- function requestInitWithCache(requestInit) {
401
- try {
402
- const withCache = {
403
- ...requestInit,
404
- cache: "no-cache"
405
- };
406
- const _ = new Request("http://localhost", withCache);
407
- return withCache;
408
- } catch (error) {
409
- return requestInit ?? {};
410
- }
411
- }
412
- __name(requestInitWithCache, "requestInitWithCache");
413
- var CreateAuthorizationCodeResponseSchema = zod.z.object({
414
- url: zod.z.string().url(),
415
- authorizationCode: zod.z.string()
416
- });
417
- var GetPersonalAccessTokenRequestSchema = zod.z.object({
418
- authorizationCode: zod.z.string()
419
- });
420
- var GetPersonalAccessTokenResponseSchema = zod.z.object({
421
- token: zod.z.object({
422
- token: zod.z.string(),
423
- obfuscatedToken: zod.z.string()
424
- }).nullable()
425
- });
426
- var TaskRunBuiltInError = zod.z.object({
427
- type: zod.z.literal("BUILT_IN_ERROR"),
428
- name: zod.z.string(),
429
- message: zod.z.string(),
430
- stackTrace: zod.z.string()
431
- });
432
- var TaskRunCustomErrorObject = zod.z.object({
433
- type: zod.z.literal("CUSTOM_ERROR"),
434
- raw: zod.z.string()
435
- });
436
- var TaskRunStringError = zod.z.object({
437
- type: zod.z.literal("STRING_ERROR"),
438
- raw: zod.z.string()
439
- });
440
- var TaskRunErrorCodes = {
441
- COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
442
- COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
443
- CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
444
- TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
445
- TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
446
- TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
447
- TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
448
- TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
449
- TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
450
- HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
451
- GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
199
+ var CreateAuthorizationCodeResponseSchema = zod.z.object({
200
+ url: zod.z.string().url(),
201
+ authorizationCode: zod.z.string()
202
+ });
203
+ var GetPersonalAccessTokenRequestSchema = zod.z.object({
204
+ authorizationCode: zod.z.string()
205
+ });
206
+ var GetPersonalAccessTokenResponseSchema = zod.z.object({
207
+ token: zod.z.object({
208
+ token: zod.z.string(),
209
+ obfuscatedToken: zod.z.string()
210
+ }).nullable()
211
+ });
212
+ var TaskRunBuiltInError = zod.z.object({
213
+ type: zod.z.literal("BUILT_IN_ERROR"),
214
+ name: zod.z.string(),
215
+ message: zod.z.string(),
216
+ stackTrace: zod.z.string()
217
+ });
218
+ var TaskRunCustomErrorObject = zod.z.object({
219
+ type: zod.z.literal("CUSTOM_ERROR"),
220
+ raw: zod.z.string()
221
+ });
222
+ var TaskRunStringError = zod.z.object({
223
+ type: zod.z.literal("STRING_ERROR"),
224
+ raw: zod.z.string()
225
+ });
226
+ var TaskRunErrorCodes = {
227
+ COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
228
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
229
+ CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
230
+ TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
231
+ TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
232
+ TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
233
+ TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
234
+ TASK_PROCESS_SIGKILL_TIMEOUT: "TASK_PROCESS_SIGKILL_TIMEOUT",
235
+ TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
236
+ TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
237
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
238
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
452
239
  };
453
240
  var TaskRunInternalError = zod.z.object({
454
241
  type: zod.z.literal("INTERNAL_ERROR"),
@@ -460,10 +247,12 @@ var TaskRunInternalError = zod.z.object({
460
247
  "TASK_EXECUTION_FAILED",
461
248
  "TASK_EXECUTION_ABORTED",
462
249
  "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
250
+ "TASK_PROCESS_SIGKILL_TIMEOUT",
463
251
  "TASK_RUN_CANCELLED",
464
252
  "TASK_OUTPUT_ERROR",
465
253
  "HANDLE_ERROR_ERROR",
466
- "GRACEFUL_EXIT_TIMEOUT"
254
+ "GRACEFUL_EXIT_TIMEOUT",
255
+ "TASK_RUN_HEARTBEAT_TIMEOUT"
467
256
  ]),
468
257
  message: zod.z.string().optional()
469
258
  });
@@ -766,6 +555,13 @@ var WaitReason = zod.z.enum([
766
555
  "WAIT_FOR_TASK",
767
556
  "WAIT_FOR_BATCH"
768
557
  ]);
558
+ var TaskRunExecutionLazyAttemptPayload = zod.z.object({
559
+ runId: zod.z.string(),
560
+ messageId: zod.z.string(),
561
+ isTest: zod.z.boolean(),
562
+ traceContext: zod.z.record(zod.z.unknown()),
563
+ environment: zod.z.record(zod.z.string()).optional()
564
+ });
769
565
 
770
566
  // src/v3/schemas/resources.ts
771
567
  var TaskResource = zod.z.object({
@@ -815,7 +611,8 @@ var GetProjectEnvResponse = zod.z.object({
815
611
  });
816
612
  var CreateBackgroundWorkerRequestBody = zod.z.object({
817
613
  localOnly: zod.z.boolean(),
818
- metadata: BackgroundWorkerMetadata
614
+ metadata: BackgroundWorkerMetadata,
615
+ supportsLazyAttempts: zod.z.boolean().optional()
819
616
  });
820
617
  var CreateBackgroundWorkerResponse = zod.z.object({
821
618
  id: zod.z.string(),
@@ -1044,6 +841,28 @@ var RetrieveRunResponse = zod.z.object({
1044
841
  completedAt: zod.z.coerce.date().optional()
1045
842
  }).optional())
1046
843
  });
844
+ var CreateEnvironmentVariableRequestBody = zod.z.object({
845
+ name: zod.z.string(),
846
+ value: zod.z.string()
847
+ });
848
+ var UpdateEnvironmentVariableRequestBody = zod.z.object({
849
+ value: zod.z.string()
850
+ });
851
+ var ImportEnvironmentVariablesRequestBody = zod.z.object({
852
+ variables: zod.z.record(zod.z.string()),
853
+ override: zod.z.boolean().optional()
854
+ });
855
+ var EnvironmentVariableResponseBody = zod.z.object({
856
+ success: zod.z.boolean()
857
+ });
858
+ var EnvironmentVariableValue = zod.z.object({
859
+ value: zod.z.string()
860
+ });
861
+ var EnvironmentVariable = zod.z.object({
862
+ name: zod.z.string(),
863
+ value: zod.z.string()
864
+ });
865
+ var EnvironmentVariables = zod.z.array(EnvironmentVariable);
1047
866
  var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
1048
867
  zod.z.object({
1049
868
  type: zod.z.literal("EXECUTE_RUNS"),
@@ -1060,12 +879,16 @@ var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
1060
879
  version: zod.z.string(),
1061
880
  machine: Machine,
1062
881
  // identifiers
1063
- id: zod.z.string(),
882
+ id: zod.z.string().optional(),
1064
883
  envId: zod.z.string(),
1065
884
  envType: EnvironmentType,
1066
885
  orgId: zod.z.string(),
1067
886
  projectId: zod.z.string(),
1068
887
  runId: zod.z.string()
888
+ }),
889
+ zod.z.object({
890
+ type: zod.z.literal("EXECUTE_RUN_LAZY_ATTEMPT"),
891
+ payload: TaskRunExecutionLazyAttemptPayload
1069
892
  })
1070
893
  ]);
1071
894
  var serverWebsocketMessages = {
@@ -1086,10 +909,20 @@ var BackgroundWorkerClientMessages = zod.z.discriminatedUnion("type", [
1086
909
  completion: TaskRunExecutionResult,
1087
910
  execution: TaskRunExecution
1088
911
  }),
912
+ zod.z.object({
913
+ version: zod.z.literal("v1").default("v1"),
914
+ type: zod.z.literal("TASK_RUN_FAILED_TO_RUN"),
915
+ completion: TaskRunFailedExecutionResult
916
+ }),
1089
917
  zod.z.object({
1090
918
  version: zod.z.literal("v1").default("v1"),
1091
919
  type: zod.z.literal("TASK_HEARTBEAT"),
1092
920
  id: zod.z.string()
921
+ }),
922
+ zod.z.object({
923
+ version: zod.z.literal("v1").default("v1"),
924
+ type: zod.z.literal("TASK_RUN_HEARTBEAT"),
925
+ id: zod.z.string()
1093
926
  })
1094
927
  ]);
1095
928
  var BackgroundWorkerProperties = zod.z.object({
@@ -1100,7 +933,8 @@ var BackgroundWorkerProperties = zod.z.object({
1100
933
  var clientWebsocketMessages = {
1101
934
  READY_FOR_TASKS: zod.z.object({
1102
935
  version: zod.z.literal("v1").default("v1"),
1103
- backgroundWorkerId: zod.z.string()
936
+ backgroundWorkerId: zod.z.string(),
937
+ inProgressRuns: zod.z.string().array().optional()
1104
938
  }),
1105
939
  BACKGROUND_WORKER_DEPRECATED: zod.z.object({
1106
940
  version: zod.z.literal("v1").default("v1"),
@@ -1119,11 +953,17 @@ var workerToChildMessages = {
1119
953
  traceContext: zod.z.record(zod.z.unknown()),
1120
954
  metadata: BackgroundWorkerProperties
1121
955
  }),
1122
- TASK_RUN_COMPLETED_NOTIFICATION: zod.z.object({
1123
- version: zod.z.literal("v1").default("v1"),
1124
- completion: TaskRunExecutionResult,
1125
- execution: TaskRunExecution
1126
- }),
956
+ TASK_RUN_COMPLETED_NOTIFICATION: zod.z.discriminatedUnion("version", [
957
+ zod.z.object({
958
+ version: zod.z.literal("v1"),
959
+ completion: TaskRunExecutionResult,
960
+ execution: TaskRunExecution
961
+ }),
962
+ zod.z.object({
963
+ version: zod.z.literal("v2"),
964
+ completion: TaskRunExecutionResult
965
+ })
966
+ ]),
1127
967
  CLEANUP: zod.z.object({
1128
968
  version: zod.z.literal("v1").default("v1"),
1129
969
  flush: zod.z.boolean().default(false),
@@ -1164,6 +1004,10 @@ var childToWorkerMessages = {
1164
1004
  version: zod.z.literal("v1").default("v1"),
1165
1005
  id: zod.z.string()
1166
1006
  }),
1007
+ TASK_RUN_HEARTBEAT: zod.z.object({
1008
+ version: zod.z.literal("v1").default("v1"),
1009
+ id: zod.z.string()
1010
+ }),
1167
1011
  READY_TO_DISPOSE: zod.z.undefined(),
1168
1012
  WAIT_FOR_DURATION: zod.z.object({
1169
1013
  version: zod.z.literal("v1").default("v1"),
@@ -1203,6 +1047,12 @@ var ProdChildToWorkerMessages = {
1203
1047
  id: zod.z.string()
1204
1048
  })
1205
1049
  },
1050
+ TASK_RUN_HEARTBEAT: {
1051
+ message: zod.z.object({
1052
+ version: zod.z.literal("v1").default("v1"),
1053
+ id: zod.z.string()
1054
+ })
1055
+ },
1206
1056
  READY_TO_DISPOSE: {
1207
1057
  message: zod.z.undefined()
1208
1058
  },
@@ -1267,11 +1117,17 @@ var ProdWorkerToChildMessages = {
1267
1117
  })
1268
1118
  },
1269
1119
  TASK_RUN_COMPLETED_NOTIFICATION: {
1270
- message: zod.z.object({
1271
- version: zod.z.literal("v1").default("v1"),
1272
- completion: TaskRunExecutionResult,
1273
- execution: TaskRunExecution
1274
- })
1120
+ message: zod.z.discriminatedUnion("version", [
1121
+ zod.z.object({
1122
+ version: zod.z.literal("v1"),
1123
+ completion: TaskRunExecutionResult,
1124
+ execution: TaskRunExecution
1125
+ }),
1126
+ zod.z.object({
1127
+ version: zod.z.literal("v2"),
1128
+ completion: TaskRunExecutionResult
1129
+ })
1130
+ ])
1275
1131
  },
1276
1132
  CLEANUP: {
1277
1133
  message: zod.z.object({
@@ -1399,6 +1255,17 @@ var PlatformToProviderMessages = {
1399
1255
  })
1400
1256
  }
1401
1257
  };
1258
+ var CreateWorkerMessage = zod.z.object({
1259
+ projectRef: zod.z.string(),
1260
+ envId: zod.z.string(),
1261
+ deploymentId: zod.z.string(),
1262
+ metadata: zod.z.object({
1263
+ cliPackageVersion: zod.z.string().optional(),
1264
+ contentHash: zod.z.string(),
1265
+ packageVersion: zod.z.string(),
1266
+ tasks: TaskResource.array()
1267
+ })
1268
+ });
1402
1269
  var CoordinatorToPlatformMessages = {
1403
1270
  LOG: {
1404
1271
  message: zod.z.object({
@@ -1408,18 +1275,15 @@ var CoordinatorToPlatformMessages = {
1408
1275
  })
1409
1276
  },
1410
1277
  CREATE_WORKER: {
1411
- message: zod.z.object({
1412
- version: zod.z.literal("v1").default("v1"),
1413
- projectRef: zod.z.string(),
1414
- envId: zod.z.string(),
1415
- deploymentId: zod.z.string(),
1416
- metadata: zod.z.object({
1417
- cliPackageVersion: zod.z.string().optional(),
1418
- contentHash: zod.z.string(),
1419
- packageVersion: zod.z.string(),
1420
- tasks: TaskResource.array()
1278
+ message: zod.z.discriminatedUnion("version", [
1279
+ CreateWorkerMessage.extend({
1280
+ version: zod.z.literal("v1")
1281
+ }),
1282
+ CreateWorkerMessage.extend({
1283
+ version: zod.z.literal("v2"),
1284
+ supportsLazyAttempts: zod.z.boolean()
1421
1285
  })
1422
- }),
1286
+ ]),
1423
1287
  callback: zod.z.discriminatedUnion("success", [
1424
1288
  zod.z.object({
1425
1289
  success: zod.z.literal(false)
@@ -1429,6 +1293,23 @@ var CoordinatorToPlatformMessages = {
1429
1293
  })
1430
1294
  ])
1431
1295
  },
1296
+ CREATE_TASK_RUN_ATTEMPT: {
1297
+ message: zod.z.object({
1298
+ version: zod.z.literal("v1").default("v1"),
1299
+ runId: zod.z.string(),
1300
+ envId: zod.z.string()
1301
+ }),
1302
+ callback: zod.z.discriminatedUnion("success", [
1303
+ zod.z.object({
1304
+ success: zod.z.literal(false),
1305
+ reason: zod.z.string().optional()
1306
+ }),
1307
+ zod.z.object({
1308
+ success: zod.z.literal(true),
1309
+ executionPayload: ProdTaskRunExecutionPayload
1310
+ })
1311
+ ])
1312
+ },
1432
1313
  READY_FOR_EXECUTION: {
1433
1314
  message: zod.z.object({
1434
1315
  version: zod.z.literal("v1").default("v1"),
@@ -1445,6 +1326,24 @@ var CoordinatorToPlatformMessages = {
1445
1326
  })
1446
1327
  ])
1447
1328
  },
1329
+ READY_FOR_LAZY_ATTEMPT: {
1330
+ message: zod.z.object({
1331
+ version: zod.z.literal("v1").default("v1"),
1332
+ runId: zod.z.string(),
1333
+ envId: zod.z.string(),
1334
+ totalCompletions: zod.z.number()
1335
+ }),
1336
+ callback: zod.z.discriminatedUnion("success", [
1337
+ zod.z.object({
1338
+ success: zod.z.literal(false),
1339
+ reason: zod.z.string().optional()
1340
+ }),
1341
+ zod.z.object({
1342
+ success: zod.z.literal(true),
1343
+ lazyPayload: TaskRunExecutionLazyAttemptPayload
1344
+ })
1345
+ ])
1346
+ },
1448
1347
  READY_FOR_RESUME: {
1449
1348
  message: zod.z.object({
1450
1349
  version: zod.z.literal("v1").default("v1"),
@@ -1463,12 +1362,24 @@ var CoordinatorToPlatformMessages = {
1463
1362
  }).optional()
1464
1363
  })
1465
1364
  },
1365
+ TASK_RUN_FAILED_TO_RUN: {
1366
+ message: zod.z.object({
1367
+ version: zod.z.literal("v1").default("v1"),
1368
+ completion: TaskRunFailedExecutionResult
1369
+ })
1370
+ },
1466
1371
  TASK_HEARTBEAT: {
1467
1372
  message: zod.z.object({
1468
1373
  version: zod.z.literal("v1").default("v1"),
1469
1374
  attemptFriendlyId: zod.z.string()
1470
1375
  })
1471
1376
  },
1377
+ TASK_RUN_HEARTBEAT: {
1378
+ message: zod.z.object({
1379
+ version: zod.z.literal("v1").default("v1"),
1380
+ runId: zod.z.string()
1381
+ })
1382
+ },
1472
1383
  CHECKPOINT_CREATED: {
1473
1384
  message: zod.z.object({
1474
1385
  version: zod.z.literal("v1").default("v1"),
@@ -1507,6 +1418,17 @@ var CoordinatorToPlatformMessages = {
1507
1418
  stack: zod.z.string().optional()
1508
1419
  })
1509
1420
  })
1421
+ },
1422
+ RUN_CRASHED: {
1423
+ message: zod.z.object({
1424
+ version: zod.z.literal("v1").default("v1"),
1425
+ runId: zod.z.string(),
1426
+ error: zod.z.object({
1427
+ name: zod.z.string(),
1428
+ message: zod.z.string(),
1429
+ stack: zod.z.string().optional()
1430
+ })
1431
+ })
1510
1432
  }
1511
1433
  };
1512
1434
  var PlatformToCoordinatorMessages = {
@@ -1534,6 +1456,13 @@ var PlatformToCoordinatorMessages = {
1534
1456
  attemptFriendlyId: zod.z.string()
1535
1457
  })
1536
1458
  },
1459
+ REQUEST_RUN_CANCELLATION: {
1460
+ message: zod.z.object({
1461
+ version: zod.z.literal("v1").default("v1"),
1462
+ runId: zod.z.string(),
1463
+ delayInMs: zod.z.number().optional()
1464
+ })
1465
+ },
1537
1466
  READY_FOR_RETRY: {
1538
1467
  message: zod.z.object({
1539
1468
  version: zod.z.literal("v1").default("v1"),
@@ -1577,6 +1506,12 @@ var SharedQueueToClientMessages = {
1577
1506
  })
1578
1507
  }
1579
1508
  };
1509
+ var IndexTasksMessage = zod.z.object({
1510
+ version: zod.z.literal("v1"),
1511
+ deploymentId: zod.z.string(),
1512
+ tasks: TaskResource.array(),
1513
+ packageVersion: zod.z.string()
1514
+ });
1580
1515
  var ProdWorkerToCoordinatorMessages = {
1581
1516
  LOG: {
1582
1517
  message: zod.z.object({
@@ -1586,12 +1521,15 @@ var ProdWorkerToCoordinatorMessages = {
1586
1521
  callback: zod.z.void()
1587
1522
  },
1588
1523
  INDEX_TASKS: {
1589
- message: zod.z.object({
1590
- version: zod.z.literal("v1").default("v1"),
1591
- deploymentId: zod.z.string(),
1592
- tasks: TaskResource.array(),
1593
- packageVersion: zod.z.string()
1594
- }),
1524
+ message: zod.z.discriminatedUnion("version", [
1525
+ IndexTasksMessage.extend({
1526
+ version: zod.z.literal("v1")
1527
+ }),
1528
+ IndexTasksMessage.extend({
1529
+ version: zod.z.literal("v2"),
1530
+ supportsLazyAttempts: zod.z.boolean()
1531
+ })
1532
+ ]),
1595
1533
  callback: zod.z.discriminatedUnion("success", [
1596
1534
  zod.z.object({
1597
1535
  success: zod.z.literal(false)
@@ -1608,6 +1546,13 @@ var ProdWorkerToCoordinatorMessages = {
1608
1546
  totalCompletions: zod.z.number()
1609
1547
  })
1610
1548
  },
1549
+ READY_FOR_LAZY_ATTEMPT: {
1550
+ message: zod.z.object({
1551
+ version: zod.z.literal("v1").default("v1"),
1552
+ runId: zod.z.string(),
1553
+ totalCompletions: zod.z.number()
1554
+ })
1555
+ },
1611
1556
  READY_FOR_RESUME: {
1612
1557
  message: zod.z.object({
1613
1558
  version: zod.z.literal("v1").default("v1"),
@@ -1644,6 +1589,12 @@ var ProdWorkerToCoordinatorMessages = {
1644
1589
  attemptFriendlyId: zod.z.string()
1645
1590
  })
1646
1591
  },
1592
+ TASK_RUN_HEARTBEAT: {
1593
+ message: zod.z.object({
1594
+ version: zod.z.literal("v1").default("v1"),
1595
+ runId: zod.z.string()
1596
+ })
1597
+ },
1647
1598
  TASK_RUN_COMPLETED: {
1648
1599
  message: zod.z.object({
1649
1600
  version: zod.z.literal("v1").default("v1"),
@@ -1655,6 +1606,12 @@ var ProdWorkerToCoordinatorMessages = {
1655
1606
  shouldExit: zod.z.boolean()
1656
1607
  })
1657
1608
  },
1609
+ TASK_RUN_FAILED_TO_RUN: {
1610
+ message: zod.z.object({
1611
+ version: zod.z.literal("v1").default("v1"),
1612
+ completion: TaskRunFailedExecutionResult
1613
+ })
1614
+ },
1658
1615
  WAIT_FOR_DURATION: {
1659
1616
  message: zod.z.object({
1660
1617
  version: zod.z.literal("v1").default("v1"),
@@ -1699,21 +1656,47 @@ var ProdWorkerToCoordinatorMessages = {
1699
1656
  stack: zod.z.string().optional()
1700
1657
  })
1701
1658
  })
1702
- }
1703
- };
1704
- var CoordinatorToProdWorkerMessages = {
1705
- RESUME_AFTER_DEPENDENCY: {
1659
+ },
1660
+ CREATE_TASK_RUN_ATTEMPT: {
1706
1661
  message: zod.z.object({
1707
1662
  version: zod.z.literal("v1").default("v1"),
1708
- attemptId: zod.z.string(),
1709
- completions: TaskRunExecutionResult.array(),
1710
- executions: TaskRunExecution.array()
1711
- })
1663
+ runId: zod.z.string()
1664
+ }),
1665
+ callback: zod.z.discriminatedUnion("success", [
1666
+ zod.z.object({
1667
+ success: zod.z.literal(false),
1668
+ reason: zod.z.string().optional()
1669
+ }),
1670
+ zod.z.object({
1671
+ success: zod.z.literal(true),
1672
+ executionPayload: ProdTaskRunExecutionPayload
1673
+ })
1674
+ ])
1712
1675
  },
1713
- RESUME_AFTER_DURATION: {
1676
+ UNRECOVERABLE_ERROR: {
1714
1677
  message: zod.z.object({
1715
1678
  version: zod.z.literal("v1").default("v1"),
1716
- attemptId: zod.z.string()
1679
+ error: zod.z.object({
1680
+ name: zod.z.string(),
1681
+ message: zod.z.string(),
1682
+ stack: zod.z.string().optional()
1683
+ })
1684
+ })
1685
+ }
1686
+ };
1687
+ var CoordinatorToProdWorkerMessages = {
1688
+ RESUME_AFTER_DEPENDENCY: {
1689
+ message: zod.z.object({
1690
+ version: zod.z.literal("v1").default("v1"),
1691
+ attemptId: zod.z.string(),
1692
+ completions: TaskRunExecutionResult.array(),
1693
+ executions: TaskRunExecution.array()
1694
+ })
1695
+ },
1696
+ RESUME_AFTER_DURATION: {
1697
+ message: zod.z.object({
1698
+ version: zod.z.literal("v1").default("v1"),
1699
+ attemptId: zod.z.string()
1717
1700
  })
1718
1701
  },
1719
1702
  EXECUTE_TASK_RUN: {
@@ -1722,6 +1705,12 @@ var CoordinatorToProdWorkerMessages = {
1722
1705
  executionPayload: ProdTaskRunExecutionPayload
1723
1706
  })
1724
1707
  },
1708
+ EXECUTE_TASK_RUN_LAZY_ATTEMPT: {
1709
+ message: zod.z.object({
1710
+ version: zod.z.literal("v1").default("v1"),
1711
+ lazyPayload: TaskRunExecutionLazyAttemptPayload
1712
+ })
1713
+ },
1725
1714
  REQUEST_ATTEMPT_CANCELLATION: {
1726
1715
  message: zod.z.object({
1727
1716
  version: zod.z.literal("v1").default("v1"),
@@ -1729,9 +1718,15 @@ var CoordinatorToProdWorkerMessages = {
1729
1718
  })
1730
1719
  },
1731
1720
  REQUEST_EXIT: {
1732
- message: zod.z.object({
1733
- version: zod.z.literal("v1").default("v1")
1734
- })
1721
+ message: zod.z.discriminatedUnion("version", [
1722
+ zod.z.object({
1723
+ version: zod.z.literal("v1")
1724
+ }),
1725
+ zod.z.object({
1726
+ version: zod.z.literal("v2"),
1727
+ delayInMs: zod.z.number().optional()
1728
+ })
1729
+ ])
1735
1730
  },
1736
1731
  READY_FOR_RETRY: {
1737
1732
  message: zod.z.object({
@@ -2106,29 +2101,359 @@ var TaskContextAPI = _TaskContextAPI;
2106
2101
  // src/v3/task-context-api.ts
2107
2102
  var taskContext = TaskContextAPI.getInstance();
2108
2103
 
2109
- // package.json
2110
- var version = "3.0.0-beta.33";
2111
- var dependencies = {
2112
- "@google-cloud/precise-date": "^4.0.0",
2113
- "@opentelemetry/api": "^1.8.0",
2114
- "@opentelemetry/api-logs": "^0.48.0",
2115
- "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
2116
- "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
2117
- "@opentelemetry/instrumentation": "^0.49.1",
2118
- "@opentelemetry/resources": "^1.22.0",
2119
- "@opentelemetry/sdk-logs": "^0.49.1",
2120
- "@opentelemetry/sdk-node": "^0.49.1",
2121
- "@opentelemetry/sdk-trace-base": "^1.22.0",
2122
- "@opentelemetry/sdk-trace-node": "^1.22.0",
2123
- "@opentelemetry/semantic-conventions": "^1.22.0",
2124
- "humanize-duration": "^3.27.3",
2125
- superjson: "^2.2.1",
2126
- ulidx: "^2.2.1",
2127
- zod: "3.22.3",
2128
- "zod-error": "1.5.0",
2129
- "zod-validation-error": "^1.5.0",
2130
- "socket.io-client": "4.7.4"
2104
+ // src/retry.ts
2105
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
2106
+ if (!resets)
2107
+ return;
2108
+ switch (format) {
2109
+ case "iso_8601_duration_openai_variant": {
2110
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
2111
+ }
2112
+ case "iso_8601": {
2113
+ return calculateISO8601ResetAt(resets, now);
2114
+ }
2115
+ case "unix_timestamp": {
2116
+ return calculateUnixTimestampResetAt(resets, now);
2117
+ }
2118
+ case "unix_timestamp_in_ms": {
2119
+ return calculateUnixTimestampInMsResetAt(resets, now);
2120
+ }
2121
+ }
2122
+ }
2123
+ __name(calculateResetAt, "calculateResetAt");
2124
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
2125
+ if (!resets)
2126
+ return void 0;
2127
+ const resetAt = parseInt(resets, 10);
2128
+ if (isNaN(resetAt))
2129
+ return void 0;
2130
+ return new Date(resetAt * 1e3);
2131
+ }
2132
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
2133
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
2134
+ if (!resets)
2135
+ return void 0;
2136
+ const resetAt = parseInt(resets, 10);
2137
+ if (isNaN(resetAt))
2138
+ return void 0;
2139
+ return new Date(resetAt);
2140
+ }
2141
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
2142
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
2143
+ if (!resets)
2144
+ return void 0;
2145
+ const resetAt = new Date(resets);
2146
+ if (isNaN(resetAt.getTime()))
2147
+ return void 0;
2148
+ return resetAt;
2149
+ }
2150
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
2151
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
2152
+ if (!resets)
2153
+ return void 0;
2154
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
2155
+ const match = resets.match(pattern);
2156
+ if (!match)
2157
+ return void 0;
2158
+ const days = parseInt(match[1], 10) || 0;
2159
+ const hours = parseInt(match[2], 10) || 0;
2160
+ const minutes = parseInt(match[3], 10) || 0;
2161
+ const seconds = parseFloat(match[4]) || 0;
2162
+ const milliseconds = parseInt(match[5], 10) || 0;
2163
+ const resetAt = new Date(now);
2164
+ resetAt.setDate(resetAt.getDate() + days);
2165
+ resetAt.setHours(resetAt.getHours() + hours);
2166
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
2167
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
2168
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
2169
+ return resetAt;
2170
+ }
2171
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
2172
+
2173
+ // src/v3/utils/retries.ts
2174
+ var defaultRetryOptions = {
2175
+ maxAttempts: 3,
2176
+ factor: 2,
2177
+ minTimeoutInMs: 1e3,
2178
+ maxTimeoutInMs: 6e4,
2179
+ randomize: true
2180
+ };
2181
+ var defaultFetchRetryOptions = {
2182
+ byStatus: {
2183
+ "429,408,409,5xx": {
2184
+ strategy: "backoff",
2185
+ ...defaultRetryOptions
2186
+ }
2187
+ },
2188
+ connectionError: defaultRetryOptions,
2189
+ timeout: defaultRetryOptions
2190
+ };
2191
+ function calculateNextRetryDelay(options, attempt) {
2192
+ const opts = {
2193
+ ...defaultRetryOptions,
2194
+ ...options
2195
+ };
2196
+ if (attempt >= opts.maxAttempts) {
2197
+ return;
2198
+ }
2199
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
2200
+ const random = randomize ? Math.random() + 1 : 1;
2201
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
2202
+ return Math.round(timeout);
2203
+ }
2204
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
2205
+ function calculateResetAt2(resets, format, now = Date.now()) {
2206
+ const resetAt = calculateResetAt(resets, format, new Date(now));
2207
+ return resetAt?.getTime();
2208
+ }
2209
+ __name(calculateResetAt2, "calculateResetAt");
2210
+ var defaultRetryOptions2 = {
2211
+ maxAttempts: 3,
2212
+ factor: 2,
2213
+ minTimeoutInMs: 1e3,
2214
+ maxTimeoutInMs: 6e4,
2215
+ randomize: false
2131
2216
  };
2217
+ async function zodfetch(schema, url, requestInit, options) {
2218
+ return await _doZodFetch(schema, url, requestInit, options);
2219
+ }
2220
+ __name(zodfetch, "zodfetch");
2221
+ async function zodupload(schema, url, body, requestInit, options) {
2222
+ const form = await createForm(body);
2223
+ const encoder = new formDataEncoder.FormDataEncoder(form);
2224
+ const finalHeaders = {};
2225
+ for (const [key, value] of Object.entries(requestInit?.headers || {})) {
2226
+ finalHeaders[key] = value;
2227
+ }
2228
+ for (const [key, value] of Object.entries(encoder.headers)) {
2229
+ finalHeaders[key] = value;
2230
+ }
2231
+ finalHeaders["Content-Length"] = String(encoder.contentLength);
2232
+ const finalRequestInit = {
2233
+ ...requestInit,
2234
+ headers: finalHeaders,
2235
+ body: stream.Readable.from(encoder),
2236
+ // @ts-expect-error
2237
+ duplex: "half"
2238
+ };
2239
+ return await _doZodFetch(schema, url, finalRequestInit, options);
2240
+ }
2241
+ __name(zodupload, "zodupload");
2242
+ var createForm = /* @__PURE__ */ __name(async (body) => {
2243
+ const form = new FormData();
2244
+ await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
2245
+ return form;
2246
+ }, "createForm");
2247
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2248
+ try {
2249
+ const response = await fetch(url, requestInitWithCache(requestInit));
2250
+ const responseHeaders = createResponseHeaders(response.headers);
2251
+ if (!response.ok) {
2252
+ const retryResult = shouldRetry(response, attempt, options?.retry);
2253
+ if (retryResult.retry) {
2254
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
2255
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2256
+ } else {
2257
+ const errText = await response.text().catch((e) => castToError2(e).message);
2258
+ const errJSON = safeJsonParse(errText);
2259
+ const errMessage = errJSON ? void 0 : errText;
2260
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
2261
+ }
2262
+ }
2263
+ const jsonBody = await response.json();
2264
+ const parsedResult = schema.safeParse(jsonBody);
2265
+ if (parsedResult.success) {
2266
+ return parsedResult.data;
2267
+ }
2268
+ throw zodValidationError.fromZodError(parsedResult.error);
2269
+ } catch (error) {
2270
+ if (error instanceof APIError) {
2271
+ throw error;
2272
+ }
2273
+ if (options?.retry) {
2274
+ const retry = {
2275
+ ...defaultRetryOptions2,
2276
+ ...options.retry
2277
+ };
2278
+ const delay = calculateNextRetryDelay(retry, attempt);
2279
+ if (delay) {
2280
+ await new Promise((resolve) => setTimeout(resolve, delay));
2281
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2282
+ }
2283
+ }
2284
+ throw new APIConnectionError({
2285
+ cause: castToError2(error)
2286
+ });
2287
+ }
2288
+ }
2289
+ __name(_doZodFetch, "_doZodFetch");
2290
+ function castToError2(err) {
2291
+ if (err instanceof Error)
2292
+ return err;
2293
+ return new Error(err);
2294
+ }
2295
+ __name(castToError2, "castToError");
2296
+ function shouldRetry(response, attempt, retryOptions) {
2297
+ function shouldRetryForOptions() {
2298
+ const retry = {
2299
+ ...defaultRetryOptions2,
2300
+ ...retryOptions
2301
+ };
2302
+ const delay = calculateNextRetryDelay(retry, attempt);
2303
+ if (delay) {
2304
+ return {
2305
+ retry: true,
2306
+ delay
2307
+ };
2308
+ } else {
2309
+ return {
2310
+ retry: false
2311
+ };
2312
+ }
2313
+ }
2314
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
2315
+ const shouldRetryHeader = response.headers.get("x-should-retry");
2316
+ if (shouldRetryHeader === "true")
2317
+ return shouldRetryForOptions();
2318
+ if (shouldRetryHeader === "false")
2319
+ return {
2320
+ retry: false
2321
+ };
2322
+ if (response.status === 408)
2323
+ return shouldRetryForOptions();
2324
+ if (response.status === 409)
2325
+ return shouldRetryForOptions();
2326
+ if (response.status === 429)
2327
+ return shouldRetryForOptions();
2328
+ if (response.status >= 500)
2329
+ return shouldRetryForOptions();
2330
+ return {
2331
+ retry: false
2332
+ };
2333
+ }
2334
+ __name(shouldRetry, "shouldRetry");
2335
+ function safeJsonParse(text) {
2336
+ try {
2337
+ return JSON.parse(text);
2338
+ } catch (e) {
2339
+ return void 0;
2340
+ }
2341
+ }
2342
+ __name(safeJsonParse, "safeJsonParse");
2343
+ function createResponseHeaders(headers) {
2344
+ return new Proxy(Object.fromEntries(
2345
+ // @ts-ignore
2346
+ headers.entries()
2347
+ ), {
2348
+ get(target, name) {
2349
+ const key = name.toString();
2350
+ return target[key.toLowerCase()] || target[key];
2351
+ }
2352
+ });
2353
+ }
2354
+ __name(createResponseHeaders, "createResponseHeaders");
2355
+ function requestInitWithCache(requestInit) {
2356
+ try {
2357
+ const withCache = {
2358
+ ...requestInit,
2359
+ cache: "no-cache"
2360
+ };
2361
+ const _ = new Request("http://localhost", withCache);
2362
+ return withCache;
2363
+ } catch (error) {
2364
+ return requestInit ?? {};
2365
+ }
2366
+ }
2367
+ __name(requestInitWithCache, "requestInitWithCache");
2368
+ var addFormValue = /* @__PURE__ */ __name(async (form, key, value) => {
2369
+ if (value === void 0)
2370
+ return;
2371
+ if (value == null) {
2372
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
2373
+ }
2374
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
2375
+ form.append(key, String(value));
2376
+ } else if (isUploadable(value) || isBlobLike(value) || value instanceof Buffer || value instanceof ArrayBuffer) {
2377
+ const file = await toFile(value);
2378
+ form.append(key, file);
2379
+ } else if (Array.isArray(value)) {
2380
+ await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
2381
+ } else if (typeof value === "object") {
2382
+ await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
2383
+ } else {
2384
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
2385
+ }
2386
+ }, "addFormValue");
2387
+ async function toFile(value, name, options) {
2388
+ value = await value;
2389
+ options ??= isFileLike(value) ? {
2390
+ lastModified: value.lastModified,
2391
+ type: value.type
2392
+ } : {};
2393
+ if (isResponseLike(value)) {
2394
+ const blob = await value.blob();
2395
+ name ||= new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file";
2396
+ return new File([
2397
+ blob
2398
+ ], name, options);
2399
+ }
2400
+ const bits = await getBytes(value);
2401
+ name ||= getName(value) ?? "unknown_file";
2402
+ if (!options.type) {
2403
+ const type = bits[0]?.type;
2404
+ if (typeof type === "string") {
2405
+ options = {
2406
+ ...options,
2407
+ type
2408
+ };
2409
+ }
2410
+ }
2411
+ return new File(bits, name, options);
2412
+ }
2413
+ __name(toFile, "toFile");
2414
+ function getName(value) {
2415
+ return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream
2416
+ getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop();
2417
+ }
2418
+ __name(getName, "getName");
2419
+ var getStringFromMaybeBuffer = /* @__PURE__ */ __name((x) => {
2420
+ if (typeof x === "string")
2421
+ return x;
2422
+ if (typeof Buffer !== "undefined" && x instanceof Buffer)
2423
+ return String(x);
2424
+ return void 0;
2425
+ }, "getStringFromMaybeBuffer");
2426
+ async function getBytes(value) {
2427
+ let parts = [];
2428
+ if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
2429
+ value instanceof ArrayBuffer) {
2430
+ parts.push(value);
2431
+ } else if (isBlobLike(value)) {
2432
+ parts.push(await value.arrayBuffer());
2433
+ } else if (isAsyncIterableIterator(value)) {
2434
+ for await (const chunk of value) {
2435
+ parts.push(chunk);
2436
+ }
2437
+ } else {
2438
+ throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);
2439
+ }
2440
+ return parts;
2441
+ }
2442
+ __name(getBytes, "getBytes");
2443
+ function propsForError(value) {
2444
+ const props = Object.getOwnPropertyNames(value);
2445
+ return `[${props.map((p) => `"${p}"`).join(", ")}]`;
2446
+ }
2447
+ __name(propsForError, "propsForError");
2448
+ var isAsyncIterableIterator = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterableIterator");
2449
+ var isResponseLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", "isResponseLike");
2450
+ var isFileLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), "isFileLike");
2451
+ 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");
2452
+ var isFsReadStream = /* @__PURE__ */ __name((value) => value instanceof stream.Readable, "isFsReadStream");
2453
+ var isUploadable = /* @__PURE__ */ __name((value) => {
2454
+ return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);
2455
+ }, "isUploadable");
2456
+ 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");
2132
2457
 
2133
2458
  // src/v3/apiClient/index.ts
2134
2459
  var zodFetchOptions = {
@@ -2263,6 +2588,52 @@ var _ApiClient = class _ApiClient {
2263
2588
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2264
2589
  });
2265
2590
  }
2591
+ listEnvVars(projectRef, slug) {
2592
+ return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2593
+ method: "GET",
2594
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2595
+ });
2596
+ }
2597
+ importEnvVars(projectRef, slug, body) {
2598
+ if (isRecordLike(body.variables)) {
2599
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
2600
+ method: "POST",
2601
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2602
+ body: JSON.stringify(body)
2603
+ });
2604
+ } else {
2605
+ return zodupload(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, body, {
2606
+ method: "POST",
2607
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2608
+ });
2609
+ }
2610
+ }
2611
+ retrieveEnvVar(projectRef, slug, key) {
2612
+ return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2613
+ method: "GET",
2614
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2615
+ });
2616
+ }
2617
+ createEnvVar(projectRef, slug, body) {
2618
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2619
+ method: "POST",
2620
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2621
+ body: JSON.stringify(body)
2622
+ });
2623
+ }
2624
+ updateEnvVar(projectRef, slug, key, body) {
2625
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2626
+ method: "PUT",
2627
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2628
+ body: JSON.stringify(body)
2629
+ });
2630
+ }
2631
+ deleteEnvVar(projectRef, slug, key) {
2632
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2633
+ method: "DELETE",
2634
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2635
+ });
2636
+ }
2266
2637
  };
2267
2638
  _getHeaders = new WeakSet();
2268
2639
  getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
@@ -2411,7 +2782,7 @@ function correctErrorStackTrace(stackTrace, projectDir, options) {
2411
2782
  const [errorLine, ...traceLines] = stackTrace.split("\n");
2412
2783
  return [
2413
2784
  options?.removeFirstLine ? void 0 : errorLine,
2414
- ...traceLines.map((line) => correctStackTraceLine(line, projectDir))
2785
+ ...traceLines.map((line) => correctStackTraceLine(line, projectDir, options?.isDev))
2415
2786
  ].filter(Boolean).join("\n");
2416
2787
  }
2417
2788
  __name(correctErrorStackTrace, "correctErrorStackTrace");
@@ -2421,14 +2792,18 @@ var LINES_TO_IGNORE = [
2421
2792
  /TaskExecutor/,
2422
2793
  /EXECUTE_TASK_RUN/,
2423
2794
  /@trigger.dev\/core/,
2795
+ /packages\/core\/src\/v3/,
2424
2796
  /safeJsonProcess/,
2425
- /__entryPoint.ts/
2797
+ /__entryPoint.ts/,
2798
+ /ZodIpc/,
2799
+ /startActiveSpan/,
2800
+ /processTicksAndRejections/
2426
2801
  ];
2427
- function correctStackTraceLine(line, projectDir) {
2802
+ function correctStackTraceLine(line, projectDir, isDev) {
2428
2803
  if (LINES_TO_IGNORE.some((regex) => regex.test(line))) {
2429
2804
  return;
2430
2805
  }
2431
- if (projectDir && !line.includes(projectDir)) {
2806
+ if (isDev && projectDir && !line.includes(projectDir)) {
2432
2807
  return;
2433
2808
  }
2434
2809
  return line.trim();
@@ -2809,7 +3184,7 @@ var _APIClientManagerAPI = class _APIClientManagerAPI {
2809
3184
  }
2810
3185
  get accessToken() {
2811
3186
  const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2812
- return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY");
3187
+ return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY") ?? getEnvVar("TRIGGER_ACCESS_TOKEN");
2813
3188
  }
2814
3189
  get client() {
2815
3190
  if (!this.baseURL || !this.accessToken) {
@@ -3524,11 +3899,16 @@ exports.CoordinatorToProdWorkerMessages = CoordinatorToProdWorkerMessages;
3524
3899
  exports.CreateAuthorizationCodeResponseSchema = CreateAuthorizationCodeResponseSchema;
3525
3900
  exports.CreateBackgroundWorkerRequestBody = CreateBackgroundWorkerRequestBody;
3526
3901
  exports.CreateBackgroundWorkerResponse = CreateBackgroundWorkerResponse;
3902
+ exports.CreateEnvironmentVariableRequestBody = CreateEnvironmentVariableRequestBody;
3527
3903
  exports.CreateScheduleOptions = CreateScheduleOptions;
3528
3904
  exports.CreateUploadPayloadUrlResponseBody = CreateUploadPayloadUrlResponseBody;
3529
3905
  exports.DeletedScheduleObject = DeletedScheduleObject;
3530
3906
  exports.DeploymentErrorData = DeploymentErrorData;
3531
3907
  exports.EnvironmentType = EnvironmentType;
3908
+ exports.EnvironmentVariable = EnvironmentVariable;
3909
+ exports.EnvironmentVariableResponseBody = EnvironmentVariableResponseBody;
3910
+ exports.EnvironmentVariableValue = EnvironmentVariableValue;
3911
+ exports.EnvironmentVariables = EnvironmentVariables;
3532
3912
  exports.EventFilter = EventFilter;
3533
3913
  exports.ExceptionEventProperties = ExceptionEventProperties;
3534
3914
  exports.ExceptionSpanEvent = ExceptionSpanEvent;
@@ -3549,6 +3929,7 @@ exports.GetProjectEnvResponse = GetProjectEnvResponse;
3549
3929
  exports.GetProjectResponseBody = GetProjectResponseBody;
3550
3930
  exports.GetProjectsResponseBody = GetProjectsResponseBody;
3551
3931
  exports.ImageDetailsMetadata = ImageDetailsMetadata;
3932
+ exports.ImportEnvironmentVariablesRequestBody = ImportEnvironmentVariablesRequestBody;
3552
3933
  exports.InitializeDeploymentRequestBody = InitializeDeploymentRequestBody;
3553
3934
  exports.InitializeDeploymentResponseBody = InitializeDeploymentResponseBody;
3554
3935
  exports.InternalServerError = InternalServerError;
@@ -3615,6 +3996,7 @@ exports.TaskRunExecution = TaskRunExecution;
3615
3996
  exports.TaskRunExecutionAttempt = TaskRunExecutionAttempt;
3616
3997
  exports.TaskRunExecutionBatch = TaskRunExecutionBatch;
3617
3998
  exports.TaskRunExecutionEnvironment = TaskRunExecutionEnvironment;
3999
+ exports.TaskRunExecutionLazyAttemptPayload = TaskRunExecutionLazyAttemptPayload;
3618
4000
  exports.TaskRunExecutionOrganization = TaskRunExecutionOrganization;
3619
4001
  exports.TaskRunExecutionPayload = TaskRunExecutionPayload;
3620
4002
  exports.TaskRunExecutionProject = TaskRunExecutionProject;
@@ -3631,6 +4013,7 @@ exports.TriggerTaskResponse = TriggerTaskResponse;
3631
4013
  exports.TriggerTracer = TriggerTracer;
3632
4014
  exports.UncaughtExceptionMessage = UncaughtExceptionMessage;
3633
4015
  exports.UnprocessableEntityError = UnprocessableEntityError;
4016
+ exports.UpdateEnvironmentVariableRequestBody = UpdateEnvironmentVariableRequestBody;
3634
4017
  exports.UpdateScheduleOptions = UpdateScheduleOptions;
3635
4018
  exports.WaitReason = WaitReason;
3636
4019
  exports.WhoAmIResponseSchema = WhoAmIResponseSchema;