@trigger.dev/core 0.0.0-prerelease-20240603154820 → 0.0.0-prerelease-20240723165848

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 (187) hide show
  1. package/dist/api-Pl9fxB8v.d.mts +13879 -0
  2. package/dist/api-sNoooMbT.d.ts +13879 -0
  3. package/dist/{catalog-dRKTgwQ7.d.ts → catalog-H7yFiZ60.d.mts} +52 -52
  4. package/dist/{catalog-XTlJQaMn.d.mts → catalog-h79CG5Wy.d.ts} +52 -52
  5. package/dist/{manager-JkbddlcO.d.mts → common-CLW82lkt.d.mts} +280 -16
  6. package/dist/{manager-JkbddlcO.d.ts → common-CLW82lkt.d.ts} +280 -16
  7. package/dist/{eventFilterMatches-2kHImluE.d.mts → eventFilter-66NaBAMi.d.mts} +1 -3
  8. package/dist/{eventFilterMatches-2kHImluE.d.ts → eventFilter-66NaBAMi.d.ts} +1 -3
  9. package/dist/eventFilterMatches.d.mts +6 -0
  10. package/dist/eventFilterMatches.d.ts +6 -0
  11. package/dist/eventFilterMatches.js +165 -0
  12. package/dist/eventFilterMatches.js.map +1 -0
  13. package/dist/eventFilterMatches.mjs +163 -0
  14. package/dist/eventFilterMatches.mjs.map +1 -0
  15. package/dist/index.d.mts +14 -16716
  16. package/dist/index.d.ts +14 -16716
  17. package/dist/index.js +1 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.mjs +1 -1
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/json-DBPEJQRe.d.mts +16 -0
  22. package/dist/json-DBPEJQRe.d.ts +16 -0
  23. package/dist/manager-KvCabW1a.d.mts +18 -0
  24. package/dist/manager-OBA35PzR.d.ts +18 -0
  25. package/dist/{messages-6_-q72KG.d.mts → messages-JvHJ83wv.d.mts} +2978 -291
  26. package/dist/{messages-6_-q72KG.d.ts → messages-JvHJ83wv.d.ts} +2978 -291
  27. package/dist/replacements.d.mts +22 -0
  28. package/dist/replacements.d.ts +22 -0
  29. package/dist/replacements.js +33 -0
  30. package/dist/replacements.js.map +1 -0
  31. package/dist/replacements.mjs +28 -0
  32. package/dist/replacements.mjs.map +1 -0
  33. package/dist/requestFilter-HNZQEpQb.d.ts +180 -0
  34. package/dist/requestFilter-b5W2_1oP.d.mts +180 -0
  35. package/dist/requestFilterMatches.d.mts +13 -0
  36. package/dist/requestFilterMatches.d.ts +13 -0
  37. package/dist/requestFilterMatches.js +238 -0
  38. package/dist/requestFilterMatches.js.map +1 -0
  39. package/dist/requestFilterMatches.mjs +235 -0
  40. package/dist/requestFilterMatches.mjs.map +1 -0
  41. package/dist/retry.d.mts +10 -0
  42. package/dist/retry.d.ts +10 -0
  43. package/dist/retry.js +100 -0
  44. package/dist/retry.js.map +1 -0
  45. package/dist/retry.mjs +97 -0
  46. package/dist/retry.mjs.map +1 -0
  47. package/dist/schemas/index.d.mts +2611 -0
  48. package/dist/schemas/index.d.ts +2611 -0
  49. package/dist/schemas/index.js +1630 -0
  50. package/dist/schemas/index.js.map +1 -0
  51. package/dist/schemas/index.mjs +1463 -0
  52. package/dist/schemas/index.mjs.map +1 -0
  53. package/dist/{schemas-r4ZP9S-F.d.mts → schemas-C9ssfehv.d.mts} +270 -33
  54. package/dist/{schemas-r4ZP9S-F.d.ts → schemas-C9ssfehv.d.ts} +270 -33
  55. package/dist/taskLogger-CzADe4je.d.ts +33 -0
  56. package/dist/taskLogger-r_AFTX45.d.mts +33 -0
  57. package/dist/tracer-N0p2Fuuv.d.mts +23 -0
  58. package/dist/tracer-N0p2Fuuv.d.ts +23 -0
  59. package/dist/types.d.mts +11 -0
  60. package/dist/types.d.ts +11 -0
  61. package/dist/types.js +4 -0
  62. package/dist/types.js.map +1 -0
  63. package/dist/types.mjs +3 -0
  64. package/dist/types.mjs.map +1 -0
  65. package/dist/utils.d.mts +7 -0
  66. package/dist/utils.d.ts +7 -0
  67. package/dist/utils.js +33 -0
  68. package/dist/utils.js.map +1 -0
  69. package/dist/utils.mjs +30 -0
  70. package/dist/utils.mjs.map +1 -0
  71. package/dist/v3/dev/index.d.mts +2 -1
  72. package/dist/v3/dev/index.d.ts +2 -1
  73. package/dist/v3/dev/index.js.map +1 -1
  74. package/dist/v3/dev/index.mjs.map +1 -1
  75. package/dist/v3/errors.d.mts +39 -0
  76. package/dist/v3/errors.d.ts +39 -0
  77. package/dist/v3/errors.js +204 -0
  78. package/dist/v3/errors.js.map +1 -0
  79. package/dist/v3/errors.mjs +195 -0
  80. package/dist/v3/errors.mjs.map +1 -0
  81. package/dist/v3/index.d.mts +172 -4737
  82. package/dist/v3/index.d.ts +172 -4737
  83. package/dist/v3/index.js +871 -620
  84. package/dist/v3/index.js.map +1 -1
  85. package/dist/v3/index.mjs +856 -620
  86. package/dist/v3/index.mjs.map +1 -1
  87. package/dist/v3/logger-api.d.mts +24 -0
  88. package/dist/v3/logger-api.d.ts +24 -0
  89. package/dist/v3/logger-api.js +118 -0
  90. package/dist/v3/logger-api.js.map +1 -0
  91. package/dist/v3/logger-api.mjs +116 -0
  92. package/dist/v3/logger-api.mjs.map +1 -0
  93. package/dist/v3/otel/index.js +36 -12
  94. package/dist/v3/otel/index.js.map +1 -1
  95. package/dist/v3/otel/index.mjs +36 -12
  96. package/dist/v3/otel/index.mjs.map +1 -1
  97. package/dist/v3/prod/index.d.mts +4 -3
  98. package/dist/v3/prod/index.d.ts +4 -3
  99. package/dist/v3/prod/index.js +7 -131
  100. package/dist/v3/prod/index.js.map +1 -1
  101. package/dist/v3/prod/index.mjs +7 -131
  102. package/dist/v3/prod/index.mjs.map +1 -1
  103. package/dist/v3/schemas/index.d.mts +4807 -0
  104. package/dist/v3/schemas/index.d.ts +4807 -0
  105. package/dist/v3/schemas/index.js +2065 -0
  106. package/dist/v3/schemas/index.js.map +1 -0
  107. package/dist/v3/schemas/index.mjs +1924 -0
  108. package/dist/v3/schemas/index.mjs.map +1 -0
  109. package/dist/v3/semanticInternalAttributes.d.mts +56 -0
  110. package/dist/v3/semanticInternalAttributes.d.ts +56 -0
  111. package/dist/v3/semanticInternalAttributes.js +61 -0
  112. package/dist/v3/semanticInternalAttributes.js.map +1 -0
  113. package/dist/v3/semanticInternalAttributes.mjs +59 -0
  114. package/dist/v3/semanticInternalAttributes.mjs.map +1 -0
  115. package/dist/v3/utils/durations.d.mts +15 -0
  116. package/dist/v3/utils/durations.d.ts +15 -0
  117. package/dist/v3/utils/durations.js +93 -0
  118. package/dist/v3/utils/durations.js.map +1 -0
  119. package/dist/v3/utils/durations.mjs +82 -0
  120. package/dist/v3/utils/durations.mjs.map +1 -0
  121. package/dist/v3/utils/flattenAttributes.d.mts +8 -0
  122. package/dist/v3/utils/flattenAttributes.d.ts +8 -0
  123. package/dist/v3/utils/flattenAttributes.js +131 -0
  124. package/dist/v3/utils/flattenAttributes.js.map +1 -0
  125. package/dist/v3/utils/flattenAttributes.mjs +126 -0
  126. package/dist/v3/utils/flattenAttributes.mjs.map +1 -0
  127. package/dist/v3/utils/ioSerialization.d.mts +21 -0
  128. package/dist/v3/utils/ioSerialization.d.ts +21 -0
  129. package/dist/v3/utils/ioSerialization.js +2403 -0
  130. package/dist/v3/utils/ioSerialization.js.map +1 -0
  131. package/dist/v3/utils/ioSerialization.mjs +2394 -0
  132. package/dist/v3/utils/ioSerialization.mjs.map +1 -0
  133. package/dist/v3/utils/omit.d.mts +3 -0
  134. package/dist/v3/utils/omit.d.ts +3 -0
  135. package/dist/v3/utils/omit.js +20 -0
  136. package/dist/v3/utils/omit.js.map +1 -0
  137. package/dist/v3/utils/omit.mjs +18 -0
  138. package/dist/v3/utils/omit.mjs.map +1 -0
  139. package/dist/v3/utils/retries.d.mts +46 -0
  140. package/dist/v3/utils/retries.d.ts +46 -0
  141. package/dist/v3/utils/retries.js +118 -0
  142. package/dist/v3/utils/retries.js.map +1 -0
  143. package/dist/v3/utils/retries.mjs +113 -0
  144. package/dist/v3/utils/retries.mjs.map +1 -0
  145. package/dist/v3/utils/timers.d.mts +6 -0
  146. package/dist/v3/utils/timers.d.ts +6 -0
  147. package/dist/v3/utils/timers.js +31 -0
  148. package/dist/v3/utils/timers.js.map +1 -0
  149. package/dist/v3/utils/timers.mjs +28 -0
  150. package/dist/v3/utils/timers.mjs.map +1 -0
  151. package/dist/v3/workers/index.d.mts +56 -8
  152. package/dist/v3/workers/index.d.ts +56 -8
  153. package/dist/v3/workers/index.js +755 -279
  154. package/dist/v3/workers/index.js.map +1 -1
  155. package/dist/v3/workers/index.mjs +753 -280
  156. package/dist/v3/workers/index.mjs.map +1 -1
  157. package/dist/v3/zodIpc.js.map +1 -1
  158. package/dist/v3/zodIpc.mjs.map +1 -1
  159. package/dist/v3/zodMessageHandler.d.mts +16 -3
  160. package/dist/v3/zodMessageHandler.d.ts +16 -3
  161. package/dist/v3/zodMessageHandler.js +77 -23
  162. package/dist/v3/zodMessageHandler.js.map +1 -1
  163. package/dist/v3/zodMessageHandler.mjs +77 -23
  164. package/dist/v3/zodMessageHandler.mjs.map +1 -1
  165. package/dist/v3/zodNamespace.js +59 -28
  166. package/dist/v3/zodNamespace.js.map +1 -1
  167. package/dist/v3/zodNamespace.mjs +60 -29
  168. package/dist/v3/zodNamespace.mjs.map +1 -1
  169. package/dist/v3/zodSocket.d.mts +8 -3
  170. package/dist/v3/zodSocket.d.ts +8 -3
  171. package/dist/v3/zodSocket.js +56 -25
  172. package/dist/v3/zodSocket.js.map +1 -1
  173. package/dist/v3/zodSocket.mjs +57 -26
  174. package/dist/v3/zodSocket.mjs.map +1 -1
  175. package/dist/v3/zodfetch.d.mts +15 -58
  176. package/dist/v3/zodfetch.d.ts +15 -58
  177. package/dist/v3/zodfetch.js +246 -156
  178. package/dist/v3/zodfetch.js.map +1 -1
  179. package/dist/v3/zodfetch.mjs +244 -149
  180. package/dist/v3/zodfetch.mjs.map +1 -1
  181. package/dist/versions.d.mts +11 -0
  182. package/dist/versions.d.ts +11 -0
  183. package/dist/versions.js +31 -0
  184. package/dist/versions.js.map +1 -0
  185. package/dist/versions.mjs +27 -0
  186. package/dist/versions.mjs.map +1 -0
  187. package/package.json +154 -10
@@ -9,10 +9,9 @@ import { LoggerProvider, BatchLogRecordProcessor, SimpleLogRecordProcessor } fro
9
9
  import { NodeTracerProvider, BatchSpanProcessor, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node';
10
10
  import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
11
11
  import { fromZodError } from 'zod-validation-error';
12
- import { FormDataEncoder } from 'form-data-encoder';
13
- import { Readable } from 'node:stream';
14
12
  import { PreciseDate } from '@google-cloud/precise-date';
15
13
  import util from 'node:util';
14
+ import { setInterval } from 'node:timers/promises';
16
15
 
17
16
  var __defProp = Object.defineProperty;
18
17
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -71,6 +70,39 @@ var SerializedError = z.object({
71
70
  name: z.string().optional(),
72
71
  stackTrace: z.string().optional()
73
72
  });
73
+ function sanitizeError(error) {
74
+ switch (error.type) {
75
+ case "BUILT_IN_ERROR": {
76
+ return {
77
+ type: "BUILT_IN_ERROR",
78
+ message: error.message?.replace(/\0/g, ""),
79
+ name: error.name?.replace(/\0/g, ""),
80
+ stackTrace: error.stackTrace?.replace(/\0/g, "")
81
+ };
82
+ }
83
+ case "STRING_ERROR": {
84
+ return {
85
+ type: "STRING_ERROR",
86
+ raw: error.raw.replace(/\0/g, "")
87
+ };
88
+ }
89
+ case "CUSTOM_ERROR": {
90
+ return {
91
+ type: "CUSTOM_ERROR",
92
+ raw: error.raw.replace(/\0/g, "")
93
+ };
94
+ }
95
+ case "INTERNAL_ERROR": {
96
+ return {
97
+ type: "INTERNAL_ERROR",
98
+ code: error.code,
99
+ message: error.message?.replace(/\0/g, ""),
100
+ stackTrace: error.stackTrace?.replace(/\0/g, "")
101
+ };
102
+ }
103
+ }
104
+ }
105
+ __name(sanitizeError, "sanitizeError");
74
106
 
75
107
  // src/v3/limits.ts
76
108
  var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
@@ -104,6 +136,10 @@ var SemanticInternalAttributes = {
104
136
  TASK_EXPORT_NAME: "ctx.task.exportName",
105
137
  QUEUE_NAME: "ctx.queue.name",
106
138
  QUEUE_ID: "ctx.queue.id",
139
+ MACHINE_PRESET_NAME: "ctx.machine.name",
140
+ MACHINE_PRESET_CPU: "ctx.machine.cpu",
141
+ MACHINE_PRESET_MEMORY: "ctx.machine.memory",
142
+ MACHINE_PRESET_CENTS_PER_MS: "ctx.machine.centsPerMs",
107
143
  SPAN_PARTIAL: "$span.partial",
108
144
  SPAN_ID: "$span.span_id",
109
145
  OUTPUT: "$output",
@@ -127,7 +163,12 @@ var SemanticInternalAttributes = {
127
163
  RETRY_DELAY: "retry.delay",
128
164
  RETRY_COUNT: "retry.count",
129
165
  LINK_TITLE: "$link.title",
130
- IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
166
+ IDEMPOTENCY_KEY: "ctx.run.idempotencyKey",
167
+ USAGE_DURATION_MS: "$usage.durationMs",
168
+ USAGE_COST_IN_CENTS: "$usage.costInCents",
169
+ RATE_LIMIT_LIMIT: "response.rateLimit.limit",
170
+ RATE_LIMIT_REMAINING: "response.rateLimit.remaining",
171
+ RATE_LIMIT_RESET: "response.rateLimit.reset"
131
172
  };
132
173
 
133
174
  // src/v3/utils/flattenAttributes.ts
@@ -273,7 +314,11 @@ var _TaskContextAPI = class _TaskContextAPI {
273
314
  [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
274
315
  [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
275
316
  [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
276
- [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
317
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey,
318
+ [SemanticInternalAttributes.MACHINE_PRESET_NAME]: this.ctx.machine?.name,
319
+ [SemanticInternalAttributes.MACHINE_PRESET_CPU]: this.ctx.machine?.cpu,
320
+ [SemanticInternalAttributes.MACHINE_PRESET_MEMORY]: this.ctx.machine?.memory,
321
+ [SemanticInternalAttributes.MACHINE_PRESET_CENTS_PER_MS]: this.ctx.machine?.centsPerMs
277
322
  };
278
323
  }
279
324
  return {};
@@ -355,7 +400,7 @@ function getEnvVar(name) {
355
400
  __name(getEnvVar, "getEnvVar");
356
401
 
357
402
  // package.json
358
- var version = "0.0.0-prerelease-20240603154820";
403
+ var version = "0.0.0-prerelease-20240723165848";
359
404
 
360
405
  // src/v3/otel/tracingSDK.ts
361
406
  var _a;
@@ -398,7 +443,7 @@ var _TracingSDK = class _TracingSDK {
398
443
  [SemanticInternalAttributes.CLI_VERSION]: version
399
444
  })).merge(config.resource ?? new Resource({})).merge(new Resource(envResourceAttributes));
400
445
  const traceProvider = new NodeTracerProvider({
401
- forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
446
+ forceFlushTimeoutMillis: config.forceFlushTimeoutMillis,
402
447
  resource: commonResources,
403
448
  spanLimits: {
404
449
  attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
@@ -411,7 +456,7 @@ var _TracingSDK = class _TracingSDK {
411
456
  });
412
457
  const spanExporter = new OTLPTraceExporter({
413
458
  url: `${config.url}/v1/traces`,
414
- timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
459
+ timeoutMillis: config.forceFlushTimeoutMillis
415
460
  });
416
461
  traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new BatchSpanProcessor(spanExporter, {
417
462
  maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
@@ -448,12 +493,16 @@ var _TracingSDK = class _TracingSDK {
448
493
  this.getTracer = traceProvider.getTracer.bind(traceProvider);
449
494
  }
450
495
  async flush() {
451
- await this._traceProvider.forceFlush();
452
- await this._logProvider.forceFlush();
496
+ await Promise.all([
497
+ this._traceProvider.forceFlush(),
498
+ this._logProvider.forceFlush()
499
+ ]);
453
500
  }
454
501
  async shutdown() {
455
- await this._traceProvider.shutdown();
456
- await this._logProvider.shutdown();
502
+ await Promise.all([
503
+ this._traceProvider.shutdown(),
504
+ this._logProvider.shutdown()
505
+ ]);
457
506
  }
458
507
  };
459
508
  __name(_TracingSDK, "TracingSDK");
@@ -492,17 +541,59 @@ __name(setLogLevel, "setLogLevel");
492
541
  // src/v3/otel/index.ts
493
542
  function recordSpanException(span, error) {
494
543
  if (error instanceof Error) {
495
- span.recordException(error);
544
+ span.recordException(sanitizeSpanError(error));
496
545
  } else if (typeof error === "string") {
497
- span.recordException(new Error(error));
546
+ span.recordException(error.replace(/\0/g, ""));
498
547
  } else {
499
- span.recordException(new Error(JSON.stringify(error)));
548
+ span.recordException(JSON.stringify(error).replace(/\0/g, ""));
500
549
  }
501
550
  span.setStatus({
502
551
  code: SpanStatusCode.ERROR
503
552
  });
504
553
  }
505
554
  __name(recordSpanException, "recordSpanException");
555
+ function sanitizeSpanError(error) {
556
+ const sanitizedError = new Error(error.message.replace(/\0/g, ""));
557
+ sanitizedError.name = error.name.replace(/\0/g, "");
558
+ sanitizedError.stack = error.stack?.replace(/\0/g, "");
559
+ return sanitizedError;
560
+ }
561
+ __name(sanitizeSpanError, "sanitizeSpanError");
562
+ var MachineCpu = z.union([
563
+ z.literal(0.25),
564
+ z.literal(0.5),
565
+ z.literal(1),
566
+ z.literal(2),
567
+ z.literal(4)
568
+ ]);
569
+ var MachineMemory = z.union([
570
+ z.literal(0.25),
571
+ z.literal(0.5),
572
+ z.literal(1),
573
+ z.literal(2),
574
+ z.literal(4),
575
+ z.literal(8)
576
+ ]);
577
+ var MachinePresetName = z.enum([
578
+ "micro",
579
+ "small-1x",
580
+ "small-2x",
581
+ "medium-1x",
582
+ "medium-2x",
583
+ "large-1x",
584
+ "large-2x"
585
+ ]);
586
+ var MachineConfig = z.object({
587
+ cpu: MachineCpu.optional(),
588
+ memory: MachineMemory.optional(),
589
+ preset: MachinePresetName.optional()
590
+ });
591
+ var MachinePreset = z.object({
592
+ name: MachinePresetName,
593
+ cpu: z.number(),
594
+ memory: z.number(),
595
+ centsPerMs: z.number()
596
+ });
506
597
  var TaskRunBuiltInError = z.object({
507
598
  type: z.literal("BUILT_IN_ERROR"),
508
599
  name: z.string(),
@@ -548,7 +639,8 @@ var TaskRunInternalError = z.object({
548
639
  "GRACEFUL_EXIT_TIMEOUT",
549
640
  "TASK_RUN_HEARTBEAT_TIMEOUT"
550
641
  ]),
551
- message: z.string().optional()
642
+ message: z.string().optional(),
643
+ stackTrace: z.string().optional()
552
644
  });
553
645
  var TaskRunError = z.discriminatedUnion("type", [
554
646
  TaskRunBuiltInError,
@@ -564,7 +656,12 @@ var TaskRun = z.object({
564
656
  tags: z.array(z.string()),
565
657
  isTest: z.boolean().default(false),
566
658
  createdAt: z.coerce.date(),
567
- idempotencyKey: z.string().optional()
659
+ startedAt: z.coerce.date().default(() => /* @__PURE__ */ new Date()),
660
+ idempotencyKey: z.string().optional(),
661
+ maxAttempts: z.number().optional(),
662
+ durationMs: z.number().default(0),
663
+ costInCents: z.number().default(0),
664
+ baseCostInCents: z.number().default(0)
568
665
  });
569
666
  var TaskRunExecutionTask = z.object({
570
667
  id: z.string(),
@@ -615,7 +712,8 @@ var TaskRunExecution = z.object({
615
712
  environment: TaskRunExecutionEnvironment,
616
713
  organization: TaskRunExecutionOrganization,
617
714
  project: TaskRunExecutionProject,
618
- batch: TaskRunExecutionBatch.optional()
715
+ batch: TaskRunExecutionBatch.optional(),
716
+ machine: MachinePreset.optional()
619
717
  });
620
718
  var TaskRunContext = z.object({
621
719
  task: TaskRunExecutionTask,
@@ -631,25 +729,31 @@ var TaskRunContext = z.object({
631
729
  environment: TaskRunExecutionEnvironment,
632
730
  organization: TaskRunExecutionOrganization,
633
731
  project: TaskRunExecutionProject,
634
- batch: TaskRunExecutionBatch.optional()
732
+ batch: TaskRunExecutionBatch.optional(),
733
+ machine: MachinePreset.optional()
635
734
  });
636
735
  var TaskRunExecutionRetry = z.object({
637
736
  timestamp: z.number(),
638
737
  delay: z.number(),
639
738
  error: z.unknown().optional()
640
739
  });
740
+ var TaskRunExecutionUsage = z.object({
741
+ durationMs: z.number()
742
+ });
641
743
  var TaskRunFailedExecutionResult = z.object({
642
744
  ok: z.literal(false),
643
745
  id: z.string(),
644
746
  error: TaskRunError,
645
747
  retry: TaskRunExecutionRetry.optional(),
646
- skippedRetrying: z.boolean().optional()
748
+ skippedRetrying: z.boolean().optional(),
749
+ usage: TaskRunExecutionUsage.optional()
647
750
  });
648
751
  var TaskRunSuccessfulExecutionResult = z.object({
649
752
  ok: z.literal(true),
650
753
  id: z.string(),
651
754
  output: z.string().optional(),
652
- outputType: z.string()
755
+ outputType: z.string(),
756
+ usage: TaskRunExecutionUsage.optional()
653
757
  });
654
758
  var TaskRunExecutionResult = z.discriminatedUnion("ok", [
655
759
  TaskRunSuccessfulExecutionResult,
@@ -667,26 +771,6 @@ z.enum([
667
771
  "DEVELOPMENT",
668
772
  "PREVIEW"
669
773
  ]);
670
- var MachineCpu = z.union([
671
- z.literal(0.25),
672
- z.literal(0.5),
673
- z.literal(1),
674
- z.literal(2),
675
- z.literal(4)
676
- ]).default(0.5);
677
- var MachineMemory = z.union([
678
- z.literal(0.25),
679
- z.literal(0.5),
680
- z.literal(1),
681
- z.literal(2),
682
- z.literal(4),
683
- z.literal(8)
684
- ]).default(1);
685
- var Machine = z.object({
686
- version: z.literal("v1").default("v1"),
687
- cpu: MachineCpu,
688
- memory: MachineMemory
689
- });
690
774
  z.object({
691
775
  execution: TaskRunExecution,
692
776
  traceContext: z.record(z.unknown()),
@@ -697,6 +781,12 @@ var ProdTaskRunExecution = TaskRunExecution.extend({
697
781
  id: z.string(),
698
782
  contentHash: z.string(),
699
783
  version: z.string()
784
+ }),
785
+ machine: MachinePreset.default({
786
+ name: "small-1x",
787
+ cpu: 1,
788
+ memory: 1,
789
+ centsPerMs: 0
700
790
  })
701
791
  });
702
792
  z.object({
@@ -796,13 +886,18 @@ var QueueOptions = z.object({
796
886
  /** @deprecated This feature is coming soon */
797
887
  rateLimit: RateLimitOptions.optional()
798
888
  });
889
+ var ScheduleMetadata = z.object({
890
+ cron: z.string(),
891
+ timezone: z.string()
892
+ });
799
893
  z.object({
800
894
  id: z.string(),
801
895
  packageVersion: z.string(),
802
896
  queue: QueueOptions.optional(),
803
897
  retry: RetryOptions.optional(),
804
- machine: Machine.partial().optional(),
805
- triggerSource: z.string().optional()
898
+ machine: MachineConfig.optional(),
899
+ triggerSource: z.string().optional(),
900
+ schedule: ScheduleMetadata.optional()
806
901
  });
807
902
  z.object({
808
903
  filePath: z.string(),
@@ -813,8 +908,9 @@ z.object({
813
908
  packageVersion: z.string(),
814
909
  queue: QueueOptions.optional(),
815
910
  retry: RetryOptions.optional(),
816
- machine: Machine.partial().optional(),
911
+ machine: MachineConfig.optional(),
817
912
  triggerSource: z.string().optional(),
913
+ schedule: ScheduleMetadata.optional(),
818
914
  filePath: z.string(),
819
915
  exportName: z.string()
820
916
  });
@@ -851,7 +947,8 @@ z.object({
851
947
  ])).optional(),
852
948
  logLevel: z.string().optional(),
853
949
  enableConsoleLogging: z.boolean().optional(),
854
- postInstall: z.string().optional()
950
+ postInstall: z.string().optional(),
951
+ extraCACerts: z.string().optional()
855
952
  });
856
953
  z.enum([
857
954
  "WAIT_FOR_DURATION",
@@ -860,6 +957,7 @@ z.enum([
860
957
  ]);
861
958
  z.object({
862
959
  runId: z.string(),
960
+ attemptCount: z.number().optional(),
863
961
  messageId: z.string(),
864
962
  isTest: z.boolean(),
865
963
  traceContext: z.record(z.unknown()),
@@ -873,8 +971,9 @@ var TaskResource = z.object({
873
971
  exportName: z.string(),
874
972
  queue: QueueOptions.optional(),
875
973
  retry: RetryOptions.optional(),
876
- machine: Machine.partial().optional(),
877
- triggerSource: z.string().optional()
974
+ machine: MachineConfig.optional(),
975
+ triggerSource: z.string().optional(),
976
+ schedule: ScheduleMetadata.optional()
878
977
  });
879
978
  var BackgroundWorkerMetadata = z.object({
880
979
  packageVersion: z.string(),
@@ -922,6 +1021,22 @@ z.object({
922
1021
  version: z.string(),
923
1022
  contentHash: z.string()
924
1023
  });
1024
+ var RunTag = z.string().max(64, "Tags must be less than 64 characters");
1025
+ var RunTags = z.union([
1026
+ RunTag,
1027
+ z.tuple([
1028
+ RunTag
1029
+ ]),
1030
+ z.tuple([
1031
+ RunTag,
1032
+ RunTag
1033
+ ]),
1034
+ z.tuple([
1035
+ RunTag,
1036
+ RunTag,
1037
+ RunTag
1038
+ ])
1039
+ ]);
925
1040
  var TriggerTaskRequestBody = z.object({
926
1041
  payload: z.any(),
927
1042
  context: z.any(),
@@ -933,7 +1048,11 @@ var TriggerTaskRequestBody = z.object({
933
1048
  concurrencyKey: z.string().optional(),
934
1049
  idempotencyKey: z.string().optional(),
935
1050
  test: z.boolean().optional(),
936
- payloadType: z.string().optional()
1051
+ payloadType: z.string().optional(),
1052
+ delay: z.string().or(z.coerce.date()).optional(),
1053
+ ttl: z.string().or(z.number().nonnegative().int()).optional(),
1054
+ tags: RunTags.optional(),
1055
+ maxAttempts: z.number().int().optional()
937
1056
  }).optional()
938
1057
  });
939
1058
  var TriggerTaskResponse = z.object({
@@ -960,6 +1079,12 @@ z.object({
960
1079
  ])
961
1080
  }))
962
1081
  });
1082
+ z.object({
1083
+ tags: RunTags
1084
+ });
1085
+ z.object({
1086
+ delay: z.string().or(z.coerce.date())
1087
+ });
963
1088
  z.object({
964
1089
  variables: z.record(z.string())
965
1090
  });
@@ -992,7 +1117,8 @@ z.object({
992
1117
  var DeploymentErrorData = z.object({
993
1118
  name: z.string(),
994
1119
  message: z.string(),
995
- stack: z.string().optional()
1120
+ stack: z.string().optional(),
1121
+ stderr: z.string().optional()
996
1122
  });
997
1123
  z.object({
998
1124
  id: z.string(),
@@ -1030,24 +1156,46 @@ var ReplayRunResponse = z.object({
1030
1156
  var CanceledRunResponse = z.object({
1031
1157
  id: z.string()
1032
1158
  });
1159
+ var ScheduleType = z.union([
1160
+ z.literal("DECLARATIVE"),
1161
+ z.literal("IMPERATIVE")
1162
+ ]);
1033
1163
  z.object({
1034
1164
  /** The schedule id associated with this run (you can have many schedules for the same task).
1035
1165
  You can use this to remove the schedule, update it, etc */
1036
1166
  scheduleId: z.string(),
1167
+ /** The type of schedule – `"DECLARATIVE"` or `"IMPERATIVE"`.
1168
+ *
1169
+ * **DECLARATIVE** – defined inline on your `schedules.task` using the `cron` property. They can only be created, updated or deleted by modifying the `cron` property on your task.
1170
+ *
1171
+ * **IMPERATIVE** – created using the `schedules.create` functions or in the dashboard.
1172
+ */
1173
+ type: ScheduleType,
1037
1174
  /** When the task was scheduled to run.
1038
- * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
1175
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task.
1176
+ *
1177
+ * This date is UTC. To output it as a string with a timezone you would do this:
1178
+ * ```ts
1179
+ * const formatted = payload.timestamp.toLocaleString("en-US", {
1180
+ timeZone: payload.timezone,
1181
+ });
1182
+ ``` */
1039
1183
  timestamp: z.date(),
1040
1184
  /** When the task was last run (it has been).
1041
- This can be undefined if it's never been run */
1185
+ This can be undefined if it's never been run. This date is UTC. */
1042
1186
  lastTimestamp: z.date().optional(),
1043
1187
  /** You can optionally provide an external id when creating the schedule.
1044
1188
  Usually you would use a userId or some other unique identifier.
1045
1189
  This defaults to undefined if you didn't provide one. */
1046
1190
  externalId: z.string().optional(),
1191
+ /** The IANA timezone the schedule is set to. The default is UTC.
1192
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1193
+ */
1194
+ timezone: z.string(),
1047
1195
  /** The next 5 dates this task is scheduled to run */
1048
1196
  upcoming: z.array(z.date())
1049
1197
  });
1050
- z.object({
1198
+ var CreateScheduleOptions = z.object({
1051
1199
  /** The id of the task you want to attach to. */
1052
1200
  task: z.string(),
1053
1201
  /** The schedule in CRON format.
@@ -1067,15 +1215,29 @@ z.object({
1067
1215
 
1068
1216
  */
1069
1217
  cron: z.string(),
1070
- /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1218
+ /** You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1071
1219
  *
1072
- * This is useful if you don't want to create duplicate schedules for a user. */
1073
- deduplicationKey: z.string().optional(),
1220
+ * This is required to prevent you from creating duplicate schedules. */
1221
+ deduplicationKey: z.string(),
1074
1222
  /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
1075
1223
  *
1076
1224
  * This allows you to have per-user CRON tasks.
1077
1225
  */
1078
- externalId: z.string().optional()
1226
+ externalId: z.string().optional(),
1227
+ /** Optionally, you can specify a timezone in the IANA format. If unset it will use UTC.
1228
+ * If specified then the CRON will be evaluated in that timezone and will respect daylight savings.
1229
+ *
1230
+ * If you set the CRON to `0 0 * * *` and the timezone to `America/New_York` then the task will run at midnight in New York time, no matter whether it's daylight savings or not.
1231
+ *
1232
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1233
+ *
1234
+ * @example "America/New_York", "Europe/London", "Asia/Tokyo", "Africa/Cairo"
1235
+ *
1236
+ */
1237
+ timezone: z.string().optional()
1238
+ });
1239
+ CreateScheduleOptions.omit({
1240
+ deduplicationKey: true
1079
1241
  });
1080
1242
  var ScheduleGenerator = z.object({
1081
1243
  type: z.literal("CRON"),
@@ -1084,11 +1246,13 @@ var ScheduleGenerator = z.object({
1084
1246
  });
1085
1247
  var ScheduleObject = z.object({
1086
1248
  id: z.string(),
1249
+ type: ScheduleType,
1087
1250
  task: z.string(),
1088
1251
  active: z.boolean(),
1089
1252
  deduplicationKey: z.string().nullish(),
1090
1253
  externalId: z.string().nullish(),
1091
1254
  generator: ScheduleGenerator,
1255
+ timezone: z.string(),
1092
1256
  nextRun: z.coerce.date().nullish(),
1093
1257
  environments: z.array(z.object({
1094
1258
  id: z.string(),
@@ -1111,6 +1275,9 @@ z.object({
1111
1275
  page: z.number().optional(),
1112
1276
  perPage: z.number().optional()
1113
1277
  });
1278
+ z.object({
1279
+ timezones: z.array(z.string())
1280
+ });
1114
1281
  var RunStatus = z.enum([
1115
1282
  /// Task hasn't been deployed yet but is waiting to be executed
1116
1283
  "WAITING_FOR_DEPLOY",
@@ -1133,7 +1300,11 @@ var RunStatus = z.enum([
1133
1300
  /// Task was interrupted during execution, mostly this happens in development environments
1134
1301
  "INTERRUPTED",
1135
1302
  /// Task has failed to complete, due to an error in the system
1136
- "SYSTEM_FAILURE"
1303
+ "SYSTEM_FAILURE",
1304
+ /// Task has been scheduled to run at a specific time
1305
+ "DELAYED",
1306
+ /// Task has expired and won't be executed
1307
+ "EXPIRED"
1137
1308
  ]);
1138
1309
  var AttemptStatus = z.enum([
1139
1310
  "PENDING",
@@ -1170,12 +1341,21 @@ var CommonRunFields = {
1170
1341
  createdAt: z.coerce.date(),
1171
1342
  updatedAt: z.coerce.date(),
1172
1343
  startedAt: z.coerce.date().optional(),
1173
- finishedAt: z.coerce.date().optional()
1344
+ finishedAt: z.coerce.date().optional(),
1345
+ delayedUntil: z.coerce.date().optional(),
1346
+ ttl: z.string().optional(),
1347
+ expiredAt: z.coerce.date().optional(),
1348
+ tags: z.string().array(),
1349
+ costInCents: z.number(),
1350
+ baseCostInCents: z.number(),
1351
+ durationMs: z.number()
1174
1352
  };
1175
1353
  var RetrieveRunResponse = z.object({
1176
1354
  ...CommonRunFields,
1177
1355
  payload: z.any().optional(),
1356
+ payloadPresignedUrl: z.string().optional(),
1178
1357
  output: z.any().optional(),
1358
+ outputPresignedUrl: z.string().optional(),
1179
1359
  schedule: RunScheduleDetails.optional(),
1180
1360
  attempts: z.array(z.object({
1181
1361
  id: z.string(),
@@ -1221,10 +1401,34 @@ var EnvironmentVariable = z.object({
1221
1401
  });
1222
1402
  var EnvironmentVariables = z.array(EnvironmentVariable);
1223
1403
 
1404
+ // src/v3/utils/retries.ts
1405
+ var defaultRetryOptions = {
1406
+ maxAttempts: 3,
1407
+ factor: 2,
1408
+ minTimeoutInMs: 1e3,
1409
+ maxTimeoutInMs: 6e4,
1410
+ randomize: true
1411
+ };
1412
+ function calculateNextRetryDelay(options, attempt) {
1413
+ const opts = {
1414
+ ...defaultRetryOptions,
1415
+ ...options
1416
+ };
1417
+ if (attempt >= opts.maxAttempts) {
1418
+ return;
1419
+ }
1420
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1421
+ const random = randomize ? Math.random() + 1 : 1;
1422
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1423
+ return Math.round(timeout);
1424
+ }
1425
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1426
+
1224
1427
  // src/v3/apiClient/errors.ts
1225
1428
  var _ApiError = class _ApiError extends Error {
1226
1429
  constructor(status, error, message, headers) {
1227
1430
  super(`${_ApiError.makeMessage(status, error, message)}`);
1431
+ this.name = "TriggerApiError";
1228
1432
  this.status = status;
1229
1433
  this.headers = headers;
1230
1434
  const data = error;
@@ -1345,6 +1549,16 @@ var _RateLimitError = class _RateLimitError extends ApiError {
1345
1549
  super(...arguments);
1346
1550
  __publicField(this, "status", 429);
1347
1551
  }
1552
+ get millisecondsUntilReset() {
1553
+ const resetAtUnixEpochMs = (this.headers ?? {})["x-ratelimit-reset"];
1554
+ if (typeof resetAtUnixEpochMs === "string") {
1555
+ const resetAtUnixEpoch = parseInt(resetAtUnixEpochMs, 10);
1556
+ if (isNaN(resetAtUnixEpoch)) {
1557
+ return;
1558
+ }
1559
+ return Math.max(resetAtUnixEpoch - Date.now() + Math.floor(Math.random() * 2e3), 0);
1560
+ }
1561
+ }
1348
1562
  };
1349
1563
  __name(_RateLimitError, "RateLimitError");
1350
1564
  var RateLimitError = _RateLimitError;
@@ -1359,28 +1573,11 @@ function castToError(err) {
1359
1573
  }
1360
1574
  __name(castToError, "castToError");
1361
1575
 
1362
- // src/v3/utils/retries.ts
1363
- var defaultRetryOptions = {
1364
- maxAttempts: 3,
1365
- factor: 2,
1366
- minTimeoutInMs: 1e3,
1367
- maxTimeoutInMs: 6e4,
1368
- randomize: true
1369
- };
1370
- function calculateNextRetryDelay(options, attempt) {
1371
- const opts = {
1372
- ...defaultRetryOptions,
1373
- ...options
1374
- };
1375
- if (attempt >= opts.maxAttempts) {
1376
- return;
1377
- }
1378
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1379
- const random = randomize ? Math.random() + 1 : 1;
1380
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1381
- return Math.round(timeout);
1576
+ // src/v3/utils/styleAttributes.ts
1577
+ function accessoryAttributes(accessory) {
1578
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
1382
1579
  }
1383
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1580
+ __name(accessoryAttributes, "accessoryAttributes");
1384
1581
 
1385
1582
  // src/v3/apiClient/pagination.ts
1386
1583
  var _CursorPage = class _CursorPage {
@@ -1540,47 +1737,47 @@ function zodfetchOffsetLimitPage(schema, url, params, requestInit, options) {
1540
1737
  return new OffsetLimitPagePromise(fetchResult, schema, url, params, requestInit, options);
1541
1738
  }
1542
1739
  __name(zodfetchOffsetLimitPage, "zodfetchOffsetLimitPage");
1543
- function zodupload(schema, url, body, requestInit, options) {
1544
- const finalRequestInit = createMultipartFormRequestInit(body, requestInit);
1545
- return new ApiPromise(_doZodFetch(schema, url, finalRequestInit, options));
1740
+ async function traceZodFetch(params, callback) {
1741
+ if (!params.options?.tracer) {
1742
+ return callback();
1743
+ }
1744
+ const url = new URL(params.url);
1745
+ const method = params.requestInit?.method ?? "GET";
1746
+ const name = params.options.name ?? `${method} ${url.pathname}`;
1747
+ return await params.options.tracer.startActiveSpan(name, async (span) => {
1748
+ return await callback(span);
1749
+ }, {
1750
+ attributes: {
1751
+ [SemanticInternalAttributes.STYLE_ICON]: params.options?.icon ?? "api",
1752
+ ...params.options.attributes
1753
+ }
1754
+ });
1546
1755
  }
1547
- __name(zodupload, "zodupload");
1548
- async function createMultipartFormRequestInit(body, requestInit) {
1549
- const form = await createForm(body);
1550
- const encoder = new FormDataEncoder(form);
1551
- const finalHeaders = {};
1552
- for (const [key, value] of Object.entries(requestInit?.headers || {})) {
1553
- finalHeaders[key] = value;
1554
- }
1555
- for (const [key, value] of Object.entries(encoder.headers)) {
1556
- finalHeaders[key] = value;
1557
- }
1558
- finalHeaders["Content-Length"] = String(encoder.contentLength);
1559
- const finalRequestInit = {
1560
- ...requestInit,
1561
- headers: finalHeaders,
1562
- body: Readable.from(encoder),
1563
- // @ts-expect-error
1564
- duplex: "half"
1565
- };
1566
- return finalRequestInit;
1756
+ __name(traceZodFetch, "traceZodFetch");
1757
+ async function _doZodFetch(schema, url, requestInit, options) {
1758
+ const $requestInit = await requestInit;
1759
+ return traceZodFetch({
1760
+ url,
1761
+ requestInit: $requestInit,
1762
+ options
1763
+ }, async (span) => {
1764
+ const result = await _doZodFetchWithRetries(schema, url, $requestInit, options);
1765
+ if (options?.onResponseBody && span) {
1766
+ options.onResponseBody(result.data, span);
1767
+ }
1768
+ return result;
1769
+ });
1567
1770
  }
1568
- __name(createMultipartFormRequestInit, "createMultipartFormRequestInit");
1569
- var createForm = /* @__PURE__ */ __name(async (body) => {
1570
- const form = new FormData();
1571
- await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
1572
- return form;
1573
- }, "createForm");
1574
- async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1771
+ __name(_doZodFetch, "_doZodFetch");
1772
+ async function _doZodFetchWithRetries(schema, url, requestInit, options, attempt = 1) {
1575
1773
  try {
1576
- const $requestInit = await requestInit;
1577
- const response = await fetch(url, requestInitWithCache($requestInit));
1774
+ const response = await fetch(url, requestInitWithCache(requestInit));
1578
1775
  const responseHeaders = createResponseHeaders(response.headers);
1579
1776
  if (!response.ok) {
1580
1777
  const retryResult = shouldRetry(response, attempt, options?.retry);
1581
1778
  if (retryResult.retry) {
1582
- await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1583
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1779
+ await waitForRetry(url, attempt + 1, retryResult.delay, options, requestInit, response);
1780
+ return await _doZodFetchWithRetries(schema, url, requestInit, options, attempt + 1);
1584
1781
  } else {
1585
1782
  const errText = await response.text().catch((e) => castToError2(e).message);
1586
1783
  const errJSON = safeJsonParse(errText);
@@ -1608,8 +1805,8 @@ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1608
1805
  };
1609
1806
  const delay = calculateNextRetryDelay(retry, attempt);
1610
1807
  if (delay) {
1611
- await new Promise((resolve) => setTimeout(resolve, delay));
1612
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1808
+ await waitForRetry(url, attempt + 1, delay, options, requestInit);
1809
+ return await _doZodFetchWithRetries(schema, url, requestInit, options, attempt + 1);
1613
1810
  }
1614
1811
  }
1615
1812
  throw new ApiConnectionError({
@@ -1617,7 +1814,7 @@ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1617
1814
  });
1618
1815
  }
1619
1816
  }
1620
- __name(_doZodFetch, "_doZodFetch");
1817
+ __name(_doZodFetchWithRetries, "_doZodFetchWithRetries");
1621
1818
  function castToError2(err) {
1622
1819
  if (err instanceof Error)
1623
1820
  return err;
@@ -1654,8 +1851,25 @@ function shouldRetry(response, attempt, retryOptions) {
1654
1851
  return shouldRetryForOptions();
1655
1852
  if (response.status === 409)
1656
1853
  return shouldRetryForOptions();
1657
- if (response.status === 429)
1854
+ if (response.status === 429) {
1855
+ if (attempt >= (typeof retryOptions?.maxAttempts === "number" ? retryOptions?.maxAttempts : 3)) {
1856
+ return {
1857
+ retry: false
1858
+ };
1859
+ }
1860
+ const resetAtUnixEpochMs = response.headers.get("x-ratelimit-reset");
1861
+ if (resetAtUnixEpochMs) {
1862
+ const resetAtUnixEpoch = parseInt(resetAtUnixEpochMs, 10);
1863
+ const delay = resetAtUnixEpoch - Date.now() + Math.floor(Math.random() * 1e3);
1864
+ if (delay > 0) {
1865
+ return {
1866
+ retry: true,
1867
+ delay
1868
+ };
1869
+ }
1870
+ }
1658
1871
  return shouldRetryForOptions();
1872
+ }
1659
1873
  if (response.status >= 500)
1660
1874
  return shouldRetryForOptions();
1661
1875
  return {
@@ -1696,95 +1910,6 @@ function requestInitWithCache(requestInit) {
1696
1910
  }
1697
1911
  }
1698
1912
  __name(requestInitWithCache, "requestInitWithCache");
1699
- var addFormValue = /* @__PURE__ */ __name(async (form, key, value) => {
1700
- if (value === void 0)
1701
- return;
1702
- if (value == null) {
1703
- throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
1704
- }
1705
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1706
- form.append(key, String(value));
1707
- } else if (isUploadable(value) || isBlobLike(value) || value instanceof Buffer || value instanceof ArrayBuffer) {
1708
- const file = await toFile(value);
1709
- form.append(key, file);
1710
- } else if (Array.isArray(value)) {
1711
- await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
1712
- } else if (typeof value === "object") {
1713
- await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
1714
- } else {
1715
- throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
1716
- }
1717
- }, "addFormValue");
1718
- async function toFile(value, name, options) {
1719
- value = await value;
1720
- options ??= isFileLike(value) ? {
1721
- lastModified: value.lastModified,
1722
- type: value.type
1723
- } : {};
1724
- if (isResponseLike(value)) {
1725
- const blob = await value.blob();
1726
- name ||= new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file";
1727
- return new File([
1728
- blob
1729
- ], name, options);
1730
- }
1731
- const bits = await getBytes(value);
1732
- name ||= getName(value) ?? "unknown_file";
1733
- if (!options.type) {
1734
- const type = bits[0]?.type;
1735
- if (typeof type === "string") {
1736
- options = {
1737
- ...options,
1738
- type
1739
- };
1740
- }
1741
- }
1742
- return new File(bits, name, options);
1743
- }
1744
- __name(toFile, "toFile");
1745
- function getName(value) {
1746
- return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream
1747
- getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop();
1748
- }
1749
- __name(getName, "getName");
1750
- var getStringFromMaybeBuffer = /* @__PURE__ */ __name((x) => {
1751
- if (typeof x === "string")
1752
- return x;
1753
- if (typeof Buffer !== "undefined" && x instanceof Buffer)
1754
- return String(x);
1755
- return void 0;
1756
- }, "getStringFromMaybeBuffer");
1757
- async function getBytes(value) {
1758
- let parts = [];
1759
- if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
1760
- value instanceof ArrayBuffer) {
1761
- parts.push(value);
1762
- } else if (isBlobLike(value)) {
1763
- parts.push(await value.arrayBuffer());
1764
- } else if (isAsyncIterableIterator(value)) {
1765
- for await (const chunk of value) {
1766
- parts.push(chunk);
1767
- }
1768
- } else {
1769
- throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);
1770
- }
1771
- return parts;
1772
- }
1773
- __name(getBytes, "getBytes");
1774
- function propsForError(value) {
1775
- const props = Object.getOwnPropertyNames(value);
1776
- return `[${props.map((p) => `"${p}"`).join(", ")}]`;
1777
- }
1778
- __name(propsForError, "propsForError");
1779
- var isAsyncIterableIterator = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterableIterator");
1780
- var isResponseLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", "isResponseLike");
1781
- var isFileLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), "isFileLike");
1782
- 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");
1783
- var isFsReadStream = /* @__PURE__ */ __name((value) => value instanceof Readable, "isFsReadStream");
1784
- var isUploadable = /* @__PURE__ */ __name((value) => {
1785
- return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);
1786
- }, "isUploadable");
1787
- 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");
1788
1913
  var _ApiPromise = class _ApiPromise extends Promise {
1789
1914
  constructor(responsePromise) {
1790
1915
  super((resolve) => {
@@ -1907,9 +2032,32 @@ fetchPage_fn2 = /* @__PURE__ */ __name(function(params1) {
1907
2032
  }, "#fetchPage");
1908
2033
  __name(_OffsetLimitPagePromise, "OffsetLimitPagePromise");
1909
2034
  var OffsetLimitPagePromise = _OffsetLimitPagePromise;
2035
+ async function waitForRetry(url, attempt, delay, options, requestInit, response) {
2036
+ if (options?.tracer) {
2037
+ const method = requestInit?.method ?? "GET";
2038
+ return options.tracer.startActiveSpan(response ? `wait after ${response.status}` : `wait after error`, async (span) => {
2039
+ await new Promise((resolve) => setTimeout(resolve, delay));
2040
+ }, {
2041
+ attributes: {
2042
+ [SemanticInternalAttributes.STYLE_ICON]: "wait",
2043
+ ...accessoryAttributes({
2044
+ items: [
2045
+ {
2046
+ text: `retrying ${options?.name ?? method.toUpperCase()} in ${delay}ms`,
2047
+ variant: "normal"
2048
+ }
2049
+ ],
2050
+ style: "codepath"
2051
+ })
2052
+ }
2053
+ });
2054
+ }
2055
+ await new Promise((resolve) => setTimeout(resolve, delay));
2056
+ }
2057
+ __name(waitForRetry, "waitForRetry");
1910
2058
 
1911
2059
  // src/v3/apiClient/index.ts
1912
- var zodFetchOptions = {
2060
+ var DEFAULT_ZOD_FETCH_OPTIONS = {
1913
2061
  retry: {
1914
2062
  maxAttempts: 3,
1915
2063
  minTimeoutInMs: 1e3,
@@ -1920,17 +2068,18 @@ var zodFetchOptions = {
1920
2068
  };
1921
2069
  var _getHeaders, getHeaders_fn;
1922
2070
  var _ApiClient = class _ApiClient {
1923
- constructor(baseUrl, accessToken) {
2071
+ constructor(baseUrl, accessToken, requestOptions = {}) {
1924
2072
  __privateAdd(this, _getHeaders);
1925
2073
  this.accessToken = accessToken;
1926
2074
  this.baseUrl = baseUrl.replace(/\/$/, "");
2075
+ this.defaultRequestOptions = mergeRequestOptions(DEFAULT_ZOD_FETCH_OPTIONS, requestOptions);
1927
2076
  }
1928
- async getRunResult(runId) {
2077
+ async getRunResult(runId, requestOptions) {
1929
2078
  try {
1930
2079
  return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
1931
2080
  method: "GET",
1932
2081
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1933
- }, zodFetchOptions);
2082
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1934
2083
  } catch (error) {
1935
2084
  if (error instanceof ApiError) {
1936
2085
  if (error.status === 404) {
@@ -1940,47 +2089,47 @@ var _ApiClient = class _ApiClient {
1940
2089
  throw error;
1941
2090
  }
1942
2091
  }
1943
- async getBatchResults(batchId) {
2092
+ async getBatchResults(batchId, requestOptions) {
1944
2093
  return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
1945
2094
  method: "GET",
1946
2095
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1947
- }, zodFetchOptions);
2096
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1948
2097
  }
1949
- triggerTask(taskId, body, options) {
2098
+ triggerTask(taskId, body, options, requestOptions) {
1950
2099
  const encodedTaskId = encodeURIComponent(taskId);
1951
2100
  return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/trigger`, {
1952
2101
  method: "POST",
1953
2102
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1954
2103
  body: JSON.stringify(body)
1955
- }, zodFetchOptions);
2104
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1956
2105
  }
1957
- batchTriggerTask(taskId, body, options) {
2106
+ batchTriggerTask(taskId, body, options, requestOptions) {
1958
2107
  const encodedTaskId = encodeURIComponent(taskId);
1959
2108
  return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/batch`, {
1960
2109
  method: "POST",
1961
2110
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1962
2111
  body: JSON.stringify(body)
1963
- }, zodFetchOptions);
2112
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1964
2113
  }
1965
- createUploadPayloadUrl(filename) {
2114
+ createUploadPayloadUrl(filename, requestOptions) {
1966
2115
  return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1967
2116
  method: "PUT",
1968
2117
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1969
- }, zodFetchOptions);
2118
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1970
2119
  }
1971
- getPayloadUrl(filename) {
2120
+ getPayloadUrl(filename, requestOptions) {
1972
2121
  return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1973
2122
  method: "GET",
1974
2123
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1975
- }, zodFetchOptions);
2124
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1976
2125
  }
1977
- retrieveRun(runId) {
2126
+ retrieveRun(runId, requestOptions) {
1978
2127
  return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v3/runs/${runId}`, {
1979
2128
  method: "GET",
1980
2129
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1981
- }, zodFetchOptions);
2130
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1982
2131
  }
1983
- listRuns(query) {
2132
+ listRuns(query, requestOptions) {
1984
2133
  const searchParams = createSearchQueryForListRuns(query);
1985
2134
  return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/runs`, {
1986
2135
  query: searchParams,
@@ -1990,9 +2139,9 @@ var _ApiClient = class _ApiClient {
1990
2139
  }, {
1991
2140
  method: "GET",
1992
2141
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1993
- }, zodFetchOptions);
2142
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
1994
2143
  }
1995
- listProjectRuns(projectRef, query) {
2144
+ listProjectRuns(projectRef, query, requestOptions) {
1996
2145
  const searchParams = createSearchQueryForListRuns(query);
1997
2146
  if (query?.env) {
1998
2147
  searchParams.append("filter[env]", Array.isArray(query.env) ? query.env.join(",") : query.env);
@@ -2005,28 +2154,44 @@ var _ApiClient = class _ApiClient {
2005
2154
  }, {
2006
2155
  method: "GET",
2007
2156
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2008
- }, zodFetchOptions);
2157
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2009
2158
  }
2010
- replayRun(runId) {
2159
+ replayRun(runId, requestOptions) {
2011
2160
  return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2012
2161
  method: "POST",
2013
2162
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2014
- }, zodFetchOptions);
2163
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2015
2164
  }
2016
- cancelRun(runId) {
2165
+ cancelRun(runId, requestOptions) {
2017
2166
  return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
2018
2167
  method: "POST",
2019
2168
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2020
- }, zodFetchOptions);
2169
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2021
2170
  }
2022
- createSchedule(options) {
2171
+ rescheduleRun(runId, body, requestOptions) {
2172
+ return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/reschedule`, {
2173
+ method: "POST",
2174
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2175
+ body: JSON.stringify(body)
2176
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2177
+ }
2178
+ addTags(runId, body, requestOptions) {
2179
+ return zodfetch(z.object({
2180
+ message: z.string()
2181
+ }), `${this.baseUrl}/api/v1/runs/${runId}/tags`, {
2182
+ method: "POST",
2183
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2184
+ body: JSON.stringify(body)
2185
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2186
+ }
2187
+ createSchedule(options, requestOptions) {
2023
2188
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
2024
2189
  method: "POST",
2025
2190
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2026
2191
  body: JSON.stringify(options)
2027
- });
2192
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2028
2193
  }
2029
- listSchedules(options) {
2194
+ listSchedules(options, requestOptions) {
2030
2195
  const searchParams = new URLSearchParams();
2031
2196
  if (options?.page) {
2032
2197
  searchParams.append("page", options.page.toString());
@@ -2040,84 +2205,77 @@ var _ApiClient = class _ApiClient {
2040
2205
  }, {
2041
2206
  method: "GET",
2042
2207
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2043
- });
2208
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2044
2209
  }
2045
- retrieveSchedule(scheduleId) {
2210
+ retrieveSchedule(scheduleId, requestOptions) {
2046
2211
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2047
2212
  method: "GET",
2048
2213
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2049
- });
2214
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2050
2215
  }
2051
- updateSchedule(scheduleId, options) {
2216
+ updateSchedule(scheduleId, options, requestOptions) {
2052
2217
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2053
2218
  method: "PUT",
2054
2219
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2055
2220
  body: JSON.stringify(options)
2056
- });
2221
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2057
2222
  }
2058
- deactivateSchedule(scheduleId) {
2223
+ deactivateSchedule(scheduleId, requestOptions) {
2059
2224
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
2060
2225
  method: "POST",
2061
2226
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2062
- });
2227
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2063
2228
  }
2064
- activateSchedule(scheduleId) {
2229
+ activateSchedule(scheduleId, requestOptions) {
2065
2230
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
2066
2231
  method: "POST",
2067
2232
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2068
- });
2233
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2069
2234
  }
2070
- deleteSchedule(scheduleId) {
2235
+ deleteSchedule(scheduleId, requestOptions) {
2071
2236
  return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2072
2237
  method: "DELETE",
2073
2238
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2074
- });
2239
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2075
2240
  }
2076
- listEnvVars(projectRef, slug) {
2241
+ listEnvVars(projectRef, slug, requestOptions) {
2077
2242
  return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2078
2243
  method: "GET",
2079
2244
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2080
- });
2245
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2081
2246
  }
2082
- importEnvVars(projectRef, slug, body) {
2083
- if (isRecordLike(body.variables)) {
2084
- return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
2085
- method: "POST",
2086
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2087
- body: JSON.stringify(body)
2088
- });
2089
- } else {
2090
- return zodupload(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, body, {
2091
- method: "POST",
2092
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2093
- });
2094
- }
2247
+ importEnvVars(projectRef, slug, body, requestOptions) {
2248
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
2249
+ method: "POST",
2250
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2251
+ body: JSON.stringify(body)
2252
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2095
2253
  }
2096
- retrieveEnvVar(projectRef, slug, key) {
2254
+ retrieveEnvVar(projectRef, slug, key, requestOptions) {
2097
2255
  return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2098
2256
  method: "GET",
2099
2257
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2100
- });
2258
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2101
2259
  }
2102
- createEnvVar(projectRef, slug, body) {
2260
+ createEnvVar(projectRef, slug, body, requestOptions) {
2103
2261
  return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2104
2262
  method: "POST",
2105
2263
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2106
2264
  body: JSON.stringify(body)
2107
- });
2265
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2108
2266
  }
2109
- updateEnvVar(projectRef, slug, key, body) {
2267
+ updateEnvVar(projectRef, slug, key, body, requestOptions) {
2110
2268
  return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2111
2269
  method: "PUT",
2112
2270
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2113
2271
  body: JSON.stringify(body)
2114
- });
2272
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2115
2273
  }
2116
- deleteEnvVar(projectRef, slug, key) {
2274
+ deleteEnvVar(projectRef, slug, key, requestOptions) {
2117
2275
  return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2118
2276
  method: "DELETE",
2119
2277
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2120
- });
2278
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2121
2279
  }
2122
2280
  };
2123
2281
  _getHeaders = new WeakSet();
@@ -2153,6 +2311,9 @@ function createSearchQueryForListRuns(query) {
2153
2311
  if (query.bulkAction) {
2154
2312
  searchParams.append("filter[bulkAction]", query.bulkAction);
2155
2313
  }
2314
+ if (query.tag) {
2315
+ searchParams.append("filter[tag]", Array.isArray(query.tag) ? query.tag.join(",") : query.tag);
2316
+ }
2156
2317
  if (query.schedule) {
2157
2318
  searchParams.append("filter[schedule]", query.schedule);
2158
2319
  }
@@ -2172,6 +2333,20 @@ function createSearchQueryForListRuns(query) {
2172
2333
  return searchParams;
2173
2334
  }
2174
2335
  __name(createSearchQueryForListRuns, "createSearchQueryForListRuns");
2336
+ function mergeRequestOptions(defaultOptions, options) {
2337
+ if (!options) {
2338
+ return defaultOptions;
2339
+ }
2340
+ return {
2341
+ ...defaultOptions,
2342
+ ...options,
2343
+ retry: {
2344
+ ...defaultOptions.retry,
2345
+ ...options.retry
2346
+ }
2347
+ };
2348
+ }
2349
+ __name(mergeRequestOptions, "mergeRequestOptions");
2175
2350
 
2176
2351
  // src/v3/apiClientManager/index.ts
2177
2352
  var API_NAME2 = "api-client";
@@ -2286,7 +2461,7 @@ async function conditionallyExportPacket(packet, pathPrefix, tracer) {
2286
2461
  return packet;
2287
2462
  }
2288
2463
  __name(conditionallyExportPacket, "conditionallyExportPacket");
2289
- function packetRequiresOffloading(packet) {
2464
+ function packetRequiresOffloading(packet, lengthLimit) {
2290
2465
  if (!packet.data) {
2291
2466
  return {
2292
2467
  needsOffloading: false,
@@ -2295,7 +2470,7 @@ function packetRequiresOffloading(packet) {
2295
2470
  }
2296
2471
  const byteSize = Buffer.byteLength(packet.data, "utf8");
2297
2472
  return {
2298
- needsOffloading: byteSize >= OFFLOAD_IO_PACKET_LENGTH_LIMIT,
2473
+ needsOffloading: byteSize >= (lengthLimit ?? OFFLOAD_IO_PACKET_LENGTH_LIMIT),
2299
2474
  size: byteSize
2300
2475
  };
2301
2476
  }
@@ -2436,12 +2611,6 @@ async function loadSuperJSON() {
2436
2611
  }
2437
2612
  __name(loadSuperJSON, "loadSuperJSON");
2438
2613
 
2439
- // src/v3/utils/styleAttributes.ts
2440
- function accessoryAttributes(accessory) {
2441
- return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
2442
- }
2443
- __name(accessoryAttributes, "accessoryAttributes");
2444
-
2445
2614
  // src/v3/workers/taskExecutor.ts
2446
2615
  var _callRun, callRun_fn, _callInitFunctions, callInitFunctions_fn, _callConfigInit, callConfigInit_fn, _callOnSuccessFunctions, callOnSuccessFunctions_fn, _callOnSuccessFunction, callOnSuccessFunction_fn, _callOnFailureFunctions, callOnFailureFunctions_fn, _callOnFailureFunction, callOnFailureFunction_fn, _callOnStartFunctions, callOnStartFunctions_fn, _callOnStartFunction, callOnStartFunction_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
2447
2616
  var _TaskExecutor = class _TaskExecutor {
@@ -2465,7 +2634,7 @@ var _TaskExecutor = class _TaskExecutor {
2465
2634
  this._importedConfig = options.importedConfig;
2466
2635
  this._handleErrorFn = options.handleErrorFn;
2467
2636
  }
2468
- async execute(execution, worker, traceContext) {
2637
+ async execute(execution, worker, traceContext, usage2) {
2469
2638
  const ctx = TaskRunContext.parse(execution);
2470
2639
  const attemptMessage = `Attempt ${execution.attempt.number}`;
2471
2640
  const originalPacket = {
@@ -2529,7 +2698,7 @@ var _TaskExecutor = class _TaskExecutor {
2529
2698
  return {
2530
2699
  id: execution.run.id,
2531
2700
  ok: false,
2532
- error: handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError),
2701
+ error: sanitizeError(handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError)),
2533
2702
  retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
2534
2703
  skippedRetrying: handleErrorResult.status === "skipped"
2535
2704
  };
@@ -2566,7 +2735,9 @@ var _TaskExecutor = class _TaskExecutor {
2566
2735
  })
2567
2736
  }
2568
2737
  }, this._tracer.extractContext(traceContext));
2569
- return result;
2738
+ return {
2739
+ result
2740
+ };
2570
2741
  }
2571
2742
  };
2572
2743
  _callRun = new WeakSet();
@@ -2578,7 +2749,8 @@ callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
2578
2749
  }
2579
2750
  if (!middlewareFn) {
2580
2751
  return runFn(payload, {
2581
- ctx
2752
+ ctx,
2753
+ init
2582
2754
  });
2583
2755
  }
2584
2756
  return middlewareFn(payload, {
@@ -2715,7 +2887,19 @@ handleError_fn = /* @__PURE__ */ __name(async function(execution, error2, payloa
2715
2887
  status: "noop"
2716
2888
  };
2717
2889
  }
2718
- const delay = calculateNextRetryDelay(retry, execution.attempt.number);
2890
+ if (error2 instanceof Error && error2.name === "AbortTaskRunError") {
2891
+ return {
2892
+ status: "skipped"
2893
+ };
2894
+ }
2895
+ if (execution.run.maxAttempts) {
2896
+ retry.maxAttempts = Math.max(execution.run.maxAttempts, 1);
2897
+ }
2898
+ let delay = calculateNextRetryDelay(retry, execution.attempt.number);
2899
+ if (delay && error2 instanceof Error && error2.name === "TriggerApiError" && error2.status === 429) {
2900
+ const rateLimitError = error2;
2901
+ delay = rateLimitError.millisecondsUntilReset;
2902
+ }
2719
2903
  if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
2720
2904
  return {
2721
2905
  status: "skipped"
@@ -3222,6 +3406,295 @@ var _StandardTaskCatalog = class _StandardTaskCatalog {
3222
3406
  __name(_StandardTaskCatalog, "StandardTaskCatalog");
3223
3407
  var StandardTaskCatalog = _StandardTaskCatalog;
3224
3408
 
3225
- export { ConsoleInterceptor, PreciseWallClock as DurableClock, OtelTaskLogger, StandardTaskCatalog, TaskContextLogProcessor, TaskContextSpanProcessor, TaskExecutor, TracingSDK, getEnvVar, logLevels, recordSpanException };
3409
+ // src/v3/usage/noopUsageManager.ts
3410
+ var _NoopUsageManager = class _NoopUsageManager {
3411
+ disable() {
3412
+ }
3413
+ start() {
3414
+ return {
3415
+ sample: () => ({
3416
+ cpuTime: 0,
3417
+ wallTime: 0
3418
+ })
3419
+ };
3420
+ }
3421
+ stop(measurement) {
3422
+ return measurement.sample();
3423
+ }
3424
+ pauseAsync(cb) {
3425
+ return cb();
3426
+ }
3427
+ sample() {
3428
+ return void 0;
3429
+ }
3430
+ };
3431
+ __name(_NoopUsageManager, "NoopUsageManager");
3432
+ var NoopUsageManager = _NoopUsageManager;
3433
+
3434
+ // src/v3/usage/api.ts
3435
+ var API_NAME4 = "usage";
3436
+ var NOOP_USAGE_MANAGER = new NoopUsageManager();
3437
+ var _getUsageManager, getUsageManager_fn;
3438
+ var _UsageAPI = class _UsageAPI {
3439
+ constructor() {
3440
+ __privateAdd(this, _getUsageManager);
3441
+ }
3442
+ static getInstance() {
3443
+ if (!this._instance) {
3444
+ this._instance = new _UsageAPI();
3445
+ }
3446
+ return this._instance;
3447
+ }
3448
+ setGlobalUsageManager(manager) {
3449
+ return registerGlobal(API_NAME4, manager);
3450
+ }
3451
+ disable() {
3452
+ __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).disable();
3453
+ unregisterGlobal(API_NAME4);
3454
+ }
3455
+ start() {
3456
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).start();
3457
+ }
3458
+ stop(measurement) {
3459
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).stop(measurement);
3460
+ }
3461
+ pauseAsync(cb) {
3462
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).pauseAsync(cb);
3463
+ }
3464
+ sample() {
3465
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).sample();
3466
+ }
3467
+ };
3468
+ _getUsageManager = new WeakSet();
3469
+ getUsageManager_fn = /* @__PURE__ */ __name(function() {
3470
+ return getGlobal(API_NAME4) ?? NOOP_USAGE_MANAGER;
3471
+ }, "#getUsageManager");
3472
+ __name(_UsageAPI, "UsageAPI");
3473
+ var UsageAPI = _UsageAPI;
3474
+
3475
+ // src/v3/usage-api.ts
3476
+ var usage = UsageAPI.getInstance();
3477
+
3478
+ // src/v3/clock/clock.ts
3479
+ function calculateDurationInMs(start, end) {
3480
+ const [startSeconds, startNanoseconds] = start;
3481
+ const [endSeconds, endNanoseconds] = end;
3482
+ const seconds = endSeconds - startSeconds;
3483
+ const nanoseconds = endNanoseconds - startNanoseconds;
3484
+ return Math.floor(seconds * 1e3 + nanoseconds / 1e6);
3485
+ }
3486
+ __name(calculateDurationInMs, "calculateDurationInMs");
3487
+
3488
+ // src/v3/usage/devUsageManager.ts
3489
+ var _a2;
3490
+ var DevUsageMeasurement = (_a2 = class {
3491
+ constructor(id, startedAt = clock.preciseNow()) {
3492
+ this.id = id;
3493
+ this.startedAt = startedAt;
3494
+ this._pauses = /* @__PURE__ */ new Map();
3495
+ }
3496
+ stop() {
3497
+ this._endedAt = clock.preciseNow();
3498
+ }
3499
+ sample() {
3500
+ const endedAt = this._endedAt ?? clock.preciseNow();
3501
+ const wallTime = this.startedAt ? calculateDurationInMs(this.startedAt, endedAt) : 0;
3502
+ if (wallTime === 0) {
3503
+ return {
3504
+ cpuTime: 0,
3505
+ wallTime: 0
3506
+ };
3507
+ }
3508
+ const totalPauses = Array.from(this._pauses.values()).reduce((total, pause) => {
3509
+ return total + calculateDurationInMs(pause.start, pause.end ?? endedAt);
3510
+ }, 0);
3511
+ const cpuTime = wallTime - totalPauses;
3512
+ return {
3513
+ wallTime,
3514
+ cpuTime
3515
+ };
3516
+ }
3517
+ registerPause(pauseId, start, end) {
3518
+ this._pauses.set(pauseId, {
3519
+ start,
3520
+ end
3521
+ });
3522
+ }
3523
+ }, __name(_a2, "DevUsageMeasurement"), _a2);
3524
+ var _DevUsageManager = class _DevUsageManager {
3525
+ constructor() {
3526
+ __publicField(this, "_currentMeasurements", /* @__PURE__ */ new Map());
3527
+ __publicField(this, "_pauses", /* @__PURE__ */ new Map());
3528
+ }
3529
+ disable() {
3530
+ }
3531
+ sample() {
3532
+ return this._firstMeasurement?.sample();
3533
+ }
3534
+ start() {
3535
+ const id = generateRandomString();
3536
+ const measurement = new DevUsageMeasurement(id);
3537
+ if (!this._firstMeasurement) {
3538
+ this._firstMeasurement = measurement;
3539
+ }
3540
+ this._currentMeasurements.set(id, measurement);
3541
+ return measurement;
3542
+ }
3543
+ stop(measurement) {
3544
+ measurement.stop();
3545
+ const sample = measurement.sample();
3546
+ this._currentMeasurements.delete(measurement.id);
3547
+ return sample;
3548
+ }
3549
+ async pauseAsync(cb) {
3550
+ const pauseId = generateRandomString();
3551
+ const pauseStart = clock.preciseNow();
3552
+ try {
3553
+ this._pauses.set(pauseId, {
3554
+ start: pauseStart
3555
+ });
3556
+ for (const measurement of this._currentMeasurements.values()) {
3557
+ measurement.registerPause(pauseId, pauseStart);
3558
+ }
3559
+ return await cb();
3560
+ } finally {
3561
+ const pauseEnd = clock.preciseNow();
3562
+ this._pauses.set(pauseId, {
3563
+ start: pauseStart,
3564
+ end: pauseEnd
3565
+ });
3566
+ for (const measurement of this._currentMeasurements.values()) {
3567
+ measurement.registerPause(pauseId, pauseStart, pauseEnd);
3568
+ }
3569
+ }
3570
+ }
3571
+ };
3572
+ __name(_DevUsageManager, "DevUsageManager");
3573
+ var DevUsageManager = _DevUsageManager;
3574
+ function generateRandomString() {
3575
+ let result = "";
3576
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3577
+ const charactersLength = characters.length;
3578
+ for (var i = 0; i < 16; i++) {
3579
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
3580
+ }
3581
+ return result;
3582
+ }
3583
+ __name(generateRandomString, "generateRandomString");
3584
+
3585
+ // src/v3/usage/usageClient.ts
3586
+ var _UsageClient = class _UsageClient {
3587
+ constructor(url, jwt) {
3588
+ this.url = url;
3589
+ this.jwt = jwt;
3590
+ }
3591
+ async sendUsageEvent(event) {
3592
+ try {
3593
+ const response = await fetch(this.url, {
3594
+ method: "POST",
3595
+ body: JSON.stringify(event),
3596
+ headers: {
3597
+ "content-type": "application/json",
3598
+ "x-trigger-jwt": this.jwt,
3599
+ accept: "application/json",
3600
+ authorization: `Bearer ${apiClientManager.accessToken}`
3601
+ }
3602
+ });
3603
+ if (response.ok) {
3604
+ const renewedJwt = response.headers.get("x-trigger-jwt");
3605
+ if (renewedJwt) {
3606
+ this.jwt = renewedJwt;
3607
+ }
3608
+ }
3609
+ } catch (error) {
3610
+ console.error(`Failed to send usage event: ${error}`);
3611
+ }
3612
+ }
3613
+ };
3614
+ __name(_UsageClient, "UsageClient");
3615
+ var UsageClient = _UsageClient;
3616
+
3617
+ // src/v3/usage/prodUsageManager.ts
3618
+ var _startReportingHeartbeat, startReportingHeartbeat_fn, _reportUsage, reportUsage_fn;
3619
+ var _ProdUsageManager = class _ProdUsageManager {
3620
+ constructor(delegageUsageManager, options) {
3621
+ __privateAdd(this, _startReportingHeartbeat);
3622
+ __privateAdd(this, _reportUsage);
3623
+ this.delegageUsageManager = delegageUsageManager;
3624
+ this.options = options;
3625
+ if (this.options.url && this.options.jwt) {
3626
+ this._usageClient = new UsageClient(this.options.url, this.options.jwt);
3627
+ }
3628
+ }
3629
+ get isReportingEnabled() {
3630
+ return typeof this._usageClient !== "undefined";
3631
+ }
3632
+ disable() {
3633
+ this.delegageUsageManager.disable();
3634
+ this._abortController?.abort();
3635
+ }
3636
+ sample() {
3637
+ return this._measurement?.sample();
3638
+ }
3639
+ start() {
3640
+ if (!this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3641
+ return this.delegageUsageManager.start();
3642
+ }
3643
+ if (!this._measurement) {
3644
+ this._measurement = this.delegageUsageManager.start();
3645
+ __privateMethod(this, _startReportingHeartbeat, startReportingHeartbeat_fn).call(this).catch(console.error);
3646
+ return this._measurement;
3647
+ }
3648
+ return this.delegageUsageManager.start();
3649
+ }
3650
+ stop(measurement) {
3651
+ return this.delegageUsageManager.stop(measurement);
3652
+ }
3653
+ async pauseAsync(cb) {
3654
+ return this.delegageUsageManager.pauseAsync(cb);
3655
+ }
3656
+ async flush() {
3657
+ return await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3658
+ }
3659
+ };
3660
+ _startReportingHeartbeat = new WeakSet();
3661
+ startReportingHeartbeat_fn = /* @__PURE__ */ __name(async function() {
3662
+ if (!this._measurement || !this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3663
+ return;
3664
+ }
3665
+ this._abortController = new AbortController();
3666
+ for await (const _ of setInterval(this.options.heartbeatIntervalMs)) {
3667
+ if (this._abortController.signal.aborted) {
3668
+ break;
3669
+ }
3670
+ await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3671
+ }
3672
+ }, "#startReportingHeartbeat");
3673
+ _reportUsage = new WeakSet();
3674
+ reportUsage_fn = /* @__PURE__ */ __name(async function() {
3675
+ if (!this._measurement) {
3676
+ return;
3677
+ }
3678
+ if (!this.isReportingEnabled) {
3679
+ return;
3680
+ }
3681
+ const client = this._usageClient;
3682
+ if (!client) {
3683
+ return;
3684
+ }
3685
+ const sample = this._measurement.sample();
3686
+ const cpuTimeSinceLastSample = this._lastSample ? sample.cpuTime - this._lastSample.cpuTime : sample.cpuTime;
3687
+ this._lastSample = sample;
3688
+ if (cpuTimeSinceLastSample <= 0) {
3689
+ return;
3690
+ }
3691
+ await client.sendUsageEvent({
3692
+ durationMs: cpuTimeSinceLastSample
3693
+ });
3694
+ }, "#reportUsage");
3695
+ __name(_ProdUsageManager, "ProdUsageManager");
3696
+ var ProdUsageManager = _ProdUsageManager;
3697
+
3698
+ export { ConsoleInterceptor, DevUsageManager, PreciseWallClock as DurableClock, OtelTaskLogger, ProdUsageManager, StandardTaskCatalog, TaskContextLogProcessor, TaskContextSpanProcessor, TaskExecutor, TracingSDK, getEnvVar, logLevels, recordSpanException, usage };
3226
3699
  //# sourceMappingURL=out.js.map
3227
3700
  //# sourceMappingURL=index.mjs.map