@trigger.dev/core 3.0.0-beta.37 → 3.0.0-beta.39

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 (35) hide show
  1. package/dist/{catalog-XTlJQaMn.d.mts → catalog-EP9DGAGm.d.ts} +43 -3
  2. package/dist/{catalog-dRKTgwQ7.d.ts → catalog-Gjy5NtAB.d.mts} +43 -3
  3. package/dist/{manager-JkbddlcO.d.mts → manager-S98VaLUy.d.mts} +244 -1
  4. package/dist/{manager-JkbddlcO.d.ts → manager-S98VaLUy.d.ts} +244 -1
  5. package/dist/{messages-9lty-Du5.d.mts → messages--WkQvA2l.d.mts} +2370 -141
  6. package/dist/{messages-9lty-Du5.d.ts → messages--WkQvA2l.d.ts} +2370 -141
  7. package/dist/{schemas-r4ZP9S-F.d.mts → schemas-Sb0sJcEt.d.mts} +199 -33
  8. package/dist/{schemas-r4ZP9S-F.d.ts → schemas-Sb0sJcEt.d.ts} +199 -33
  9. package/dist/v3/dev/index.d.mts +1 -1
  10. package/dist/v3/dev/index.d.ts +1 -1
  11. package/dist/v3/index.d.mts +129 -55
  12. package/dist/v3/index.d.ts +129 -55
  13. package/dist/v3/index.js +208 -57
  14. package/dist/v3/index.js.map +1 -1
  15. package/dist/v3/index.mjs +203 -57
  16. package/dist/v3/index.mjs.map +1 -1
  17. package/dist/v3/otel/index.js +15 -5
  18. package/dist/v3/otel/index.js.map +1 -1
  19. package/dist/v3/otel/index.mjs +15 -5
  20. package/dist/v3/otel/index.mjs.map +1 -1
  21. package/dist/v3/prod/index.d.mts +2 -2
  22. package/dist/v3/prod/index.d.ts +2 -2
  23. package/dist/v3/prod/index.js.map +1 -1
  24. package/dist/v3/prod/index.mjs.map +1 -1
  25. package/dist/v3/workers/index.d.mts +54 -8
  26. package/dist/v3/workers/index.d.ts +54 -8
  27. package/dist/v3/workers/index.js +408 -42
  28. package/dist/v3/workers/index.js.map +1 -1
  29. package/dist/v3/workers/index.mjs +406 -43
  30. package/dist/v3/workers/index.mjs.map +1 -1
  31. package/dist/v3/zodIpc.js.map +1 -1
  32. package/dist/v3/zodIpc.mjs.map +1 -1
  33. package/dist/v3/zodfetch.d.mts +1 -1
  34. package/dist/v3/zodfetch.d.ts +1 -1
  35. package/package.json +1 -1
@@ -13,6 +13,7 @@ import { FormDataEncoder } from 'form-data-encoder';
13
13
  import { Readable } from 'node:stream';
14
14
  import { PreciseDate } from '@google-cloud/precise-date';
15
15
  import util from 'node:util';
16
+ import { setInterval } from 'node:timers/promises';
16
17
 
17
18
  var __defProp = Object.defineProperty;
18
19
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -104,6 +105,10 @@ var SemanticInternalAttributes = {
104
105
  TASK_EXPORT_NAME: "ctx.task.exportName",
105
106
  QUEUE_NAME: "ctx.queue.name",
106
107
  QUEUE_ID: "ctx.queue.id",
108
+ MACHINE_PRESET_NAME: "ctx.machine.name",
109
+ MACHINE_PRESET_CPU: "ctx.machine.cpu",
110
+ MACHINE_PRESET_MEMORY: "ctx.machine.memory",
111
+ MACHINE_PRESET_CENTS_PER_MS: "ctx.machine.centsPerMs",
107
112
  SPAN_PARTIAL: "$span.partial",
108
113
  SPAN_ID: "$span.span_id",
109
114
  OUTPUT: "$output",
@@ -127,7 +132,9 @@ var SemanticInternalAttributes = {
127
132
  RETRY_DELAY: "retry.delay",
128
133
  RETRY_COUNT: "retry.count",
129
134
  LINK_TITLE: "$link.title",
130
- IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
135
+ IDEMPOTENCY_KEY: "ctx.run.idempotencyKey",
136
+ USAGE_DURATION_MS: "$usage.durationMs",
137
+ USAGE_COST_IN_CENTS: "$usage.costInCents"
131
138
  };
132
139
 
133
140
  // src/v3/utils/flattenAttributes.ts
@@ -273,7 +280,11 @@ var _TaskContextAPI = class _TaskContextAPI {
273
280
  [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
274
281
  [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
275
282
  [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
276
- [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
283
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey,
284
+ [SemanticInternalAttributes.MACHINE_PRESET_NAME]: this.ctx.machine?.name,
285
+ [SemanticInternalAttributes.MACHINE_PRESET_CPU]: this.ctx.machine?.cpu,
286
+ [SemanticInternalAttributes.MACHINE_PRESET_MEMORY]: this.ctx.machine?.memory,
287
+ [SemanticInternalAttributes.MACHINE_PRESET_CENTS_PER_MS]: this.ctx.machine?.centsPerMs
277
288
  };
278
289
  }
279
290
  return {};
@@ -355,7 +366,7 @@ function getEnvVar(name) {
355
366
  __name(getEnvVar, "getEnvVar");
356
367
 
357
368
  // package.json
358
- var version = "3.0.0-beta.37";
369
+ var version = "3.0.0-beta.39";
359
370
 
360
371
  // src/v3/otel/tracingSDK.ts
361
372
  var _a;
@@ -398,7 +409,7 @@ var _TracingSDK = class _TracingSDK {
398
409
  [SemanticInternalAttributes.CLI_VERSION]: version
399
410
  })).merge(config.resource ?? new Resource({})).merge(new Resource(envResourceAttributes));
400
411
  const traceProvider = new NodeTracerProvider({
401
- forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
412
+ forceFlushTimeoutMillis: config.forceFlushTimeoutMillis,
402
413
  resource: commonResources,
403
414
  spanLimits: {
404
415
  attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
@@ -411,7 +422,7 @@ var _TracingSDK = class _TracingSDK {
411
422
  });
412
423
  const spanExporter = new OTLPTraceExporter({
413
424
  url: `${config.url}/v1/traces`,
414
- timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
425
+ timeoutMillis: config.forceFlushTimeoutMillis
415
426
  });
416
427
  traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new BatchSpanProcessor(spanExporter, {
417
428
  maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
@@ -503,6 +514,41 @@ function recordSpanException(span, error) {
503
514
  });
504
515
  }
505
516
  __name(recordSpanException, "recordSpanException");
517
+ var MachineCpu = z.union([
518
+ z.literal(0.25),
519
+ z.literal(0.5),
520
+ z.literal(1),
521
+ z.literal(2),
522
+ z.literal(4)
523
+ ]);
524
+ var MachineMemory = z.union([
525
+ z.literal(0.25),
526
+ z.literal(0.5),
527
+ z.literal(1),
528
+ z.literal(2),
529
+ z.literal(4),
530
+ z.literal(8)
531
+ ]);
532
+ var MachinePresetName = z.enum([
533
+ "micro",
534
+ "small-1x",
535
+ "small-2x",
536
+ "medium-1x",
537
+ "medium-2x",
538
+ "large-1x",
539
+ "large-2x"
540
+ ]);
541
+ var MachineConfig = z.object({
542
+ cpu: MachineCpu.optional(),
543
+ memory: MachineMemory.optional(),
544
+ preset: MachinePresetName.optional()
545
+ });
546
+ var MachinePreset = z.object({
547
+ name: MachinePresetName,
548
+ cpu: z.number(),
549
+ memory: z.number(),
550
+ centsPerMs: z.number()
551
+ });
506
552
  var TaskRunBuiltInError = z.object({
507
553
  type: z.literal("BUILT_IN_ERROR"),
508
554
  name: z.string(),
@@ -564,7 +610,11 @@ var TaskRun = z.object({
564
610
  tags: z.array(z.string()),
565
611
  isTest: z.boolean().default(false),
566
612
  createdAt: z.coerce.date(),
567
- idempotencyKey: z.string().optional()
613
+ startedAt: z.coerce.date().default(() => /* @__PURE__ */ new Date()),
614
+ idempotencyKey: z.string().optional(),
615
+ durationMs: z.number().default(0),
616
+ costInCents: z.number().default(0),
617
+ baseCostInCents: z.number().default(0)
568
618
  });
569
619
  var TaskRunExecutionTask = z.object({
570
620
  id: z.string(),
@@ -615,7 +665,8 @@ var TaskRunExecution = z.object({
615
665
  environment: TaskRunExecutionEnvironment,
616
666
  organization: TaskRunExecutionOrganization,
617
667
  project: TaskRunExecutionProject,
618
- batch: TaskRunExecutionBatch.optional()
668
+ batch: TaskRunExecutionBatch.optional(),
669
+ machine: MachinePreset.optional()
619
670
  });
620
671
  var TaskRunContext = z.object({
621
672
  task: TaskRunExecutionTask,
@@ -631,25 +682,31 @@ var TaskRunContext = z.object({
631
682
  environment: TaskRunExecutionEnvironment,
632
683
  organization: TaskRunExecutionOrganization,
633
684
  project: TaskRunExecutionProject,
634
- batch: TaskRunExecutionBatch.optional()
685
+ batch: TaskRunExecutionBatch.optional(),
686
+ machine: MachinePreset.optional()
635
687
  });
636
688
  var TaskRunExecutionRetry = z.object({
637
689
  timestamp: z.number(),
638
690
  delay: z.number(),
639
691
  error: z.unknown().optional()
640
692
  });
693
+ var TaskRunExecutionUsage = z.object({
694
+ durationMs: z.number()
695
+ });
641
696
  var TaskRunFailedExecutionResult = z.object({
642
697
  ok: z.literal(false),
643
698
  id: z.string(),
644
699
  error: TaskRunError,
645
700
  retry: TaskRunExecutionRetry.optional(),
646
- skippedRetrying: z.boolean().optional()
701
+ skippedRetrying: z.boolean().optional(),
702
+ usage: TaskRunExecutionUsage.optional()
647
703
  });
648
704
  var TaskRunSuccessfulExecutionResult = z.object({
649
705
  ok: z.literal(true),
650
706
  id: z.string(),
651
707
  output: z.string().optional(),
652
- outputType: z.string()
708
+ outputType: z.string(),
709
+ usage: TaskRunExecutionUsage.optional()
653
710
  });
654
711
  var TaskRunExecutionResult = z.discriminatedUnion("ok", [
655
712
  TaskRunSuccessfulExecutionResult,
@@ -667,26 +724,6 @@ z.enum([
667
724
  "DEVELOPMENT",
668
725
  "PREVIEW"
669
726
  ]);
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
727
  z.object({
691
728
  execution: TaskRunExecution,
692
729
  traceContext: z.record(z.unknown()),
@@ -697,6 +734,12 @@ var ProdTaskRunExecution = TaskRunExecution.extend({
697
734
  id: z.string(),
698
735
  contentHash: z.string(),
699
736
  version: z.string()
737
+ }),
738
+ machine: MachinePreset.default({
739
+ name: "small-1x",
740
+ cpu: 1,
741
+ memory: 1,
742
+ centsPerMs: 0
700
743
  })
701
744
  });
702
745
  z.object({
@@ -801,7 +844,7 @@ z.object({
801
844
  packageVersion: z.string(),
802
845
  queue: QueueOptions.optional(),
803
846
  retry: RetryOptions.optional(),
804
- machine: Machine.partial().optional(),
847
+ machine: MachineConfig.optional(),
805
848
  triggerSource: z.string().optional()
806
849
  });
807
850
  z.object({
@@ -813,7 +856,7 @@ z.object({
813
856
  packageVersion: z.string(),
814
857
  queue: QueueOptions.optional(),
815
858
  retry: RetryOptions.optional(),
816
- machine: Machine.partial().optional(),
859
+ machine: MachineConfig.optional(),
817
860
  triggerSource: z.string().optional(),
818
861
  filePath: z.string(),
819
862
  exportName: z.string()
@@ -873,7 +916,7 @@ var TaskResource = z.object({
873
916
  exportName: z.string(),
874
917
  queue: QueueOptions.optional(),
875
918
  retry: RetryOptions.optional(),
876
- machine: Machine.partial().optional(),
919
+ machine: MachineConfig.optional(),
877
920
  triggerSource: z.string().optional()
878
921
  });
879
922
  var BackgroundWorkerMetadata = z.object({
@@ -1036,19 +1079,30 @@ z.object({
1036
1079
  You can use this to remove the schedule, update it, etc */
1037
1080
  scheduleId: z.string(),
1038
1081
  /** When the task was scheduled to run.
1039
- * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
1082
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task.
1083
+ *
1084
+ * This date is UTC. To output it as a string with a timezone you would do this:
1085
+ * ```ts
1086
+ * const formatted = payload.timestamp.toLocaleString("en-US", {
1087
+ timeZone: payload.timezone,
1088
+ });
1089
+ ``` */
1040
1090
  timestamp: z.date(),
1041
1091
  /** When the task was last run (it has been).
1042
- This can be undefined if it's never been run */
1092
+ This can be undefined if it's never been run. This date is UTC. */
1043
1093
  lastTimestamp: z.date().optional(),
1044
1094
  /** You can optionally provide an external id when creating the schedule.
1045
1095
  Usually you would use a userId or some other unique identifier.
1046
1096
  This defaults to undefined if you didn't provide one. */
1047
1097
  externalId: z.string().optional(),
1098
+ /** The IANA timezone the schedule is set to. The default is UTC.
1099
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1100
+ */
1101
+ timezone: z.string(),
1048
1102
  /** The next 5 dates this task is scheduled to run */
1049
1103
  upcoming: z.array(z.date())
1050
1104
  });
1051
- z.object({
1105
+ var CreateScheduleOptions = z.object({
1052
1106
  /** The id of the task you want to attach to. */
1053
1107
  task: z.string(),
1054
1108
  /** The schedule in CRON format.
@@ -1068,15 +1122,29 @@ z.object({
1068
1122
 
1069
1123
  */
1070
1124
  cron: z.string(),
1071
- /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1125
+ /** You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1072
1126
  *
1073
- * This is useful if you don't want to create duplicate schedules for a user. */
1074
- deduplicationKey: z.string().optional(),
1127
+ * This is required to prevent you from creating duplicate schedules. */
1128
+ deduplicationKey: z.string(),
1075
1129
  /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
1076
1130
  *
1077
1131
  * This allows you to have per-user CRON tasks.
1078
1132
  */
1079
- externalId: z.string().optional()
1133
+ externalId: z.string().optional(),
1134
+ /** Optionally, you can specify a timezone in the IANA format. If unset it will use UTC.
1135
+ * If specified then the CRON will be evaluated in that timezone and will respect daylight savings.
1136
+ *
1137
+ * 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.
1138
+ *
1139
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1140
+ *
1141
+ * @example "America/New_York", "Europe/London", "Asia/Tokyo", "Africa/Cairo"
1142
+ *
1143
+ */
1144
+ timezone: z.string().optional()
1145
+ });
1146
+ CreateScheduleOptions.omit({
1147
+ deduplicationKey: true
1080
1148
  });
1081
1149
  var ScheduleGenerator = z.object({
1082
1150
  type: z.literal("CRON"),
@@ -1090,6 +1158,7 @@ var ScheduleObject = z.object({
1090
1158
  deduplicationKey: z.string().nullish(),
1091
1159
  externalId: z.string().nullish(),
1092
1160
  generator: ScheduleGenerator,
1161
+ timezone: z.string(),
1093
1162
  nextRun: z.coerce.date().nullish(),
1094
1163
  environments: z.array(z.object({
1095
1164
  id: z.string(),
@@ -1112,6 +1181,9 @@ z.object({
1112
1181
  page: z.number().optional(),
1113
1182
  perPage: z.number().optional()
1114
1183
  });
1184
+ z.object({
1185
+ timezones: z.array(z.string())
1186
+ });
1115
1187
  var RunStatus = z.enum([
1116
1188
  /// Task hasn't been deployed yet but is waiting to be executed
1117
1189
  "WAITING_FOR_DEPLOY",
@@ -2466,7 +2538,7 @@ var _TaskExecutor = class _TaskExecutor {
2466
2538
  this._importedConfig = options.importedConfig;
2467
2539
  this._handleErrorFn = options.handleErrorFn;
2468
2540
  }
2469
- async execute(execution, worker, traceContext) {
2541
+ async execute(execution, worker, traceContext, usage2) {
2470
2542
  const ctx = TaskRunContext.parse(execution);
2471
2543
  const attemptMessage = `Attempt ${execution.attempt.number}`;
2472
2544
  const originalPacket = {
@@ -2567,7 +2639,9 @@ var _TaskExecutor = class _TaskExecutor {
2567
2639
  })
2568
2640
  }
2569
2641
  }, this._tracer.extractContext(traceContext));
2570
- return result;
2642
+ return {
2643
+ result
2644
+ };
2571
2645
  }
2572
2646
  };
2573
2647
  _callRun = new WeakSet();
@@ -3223,6 +3297,295 @@ var _StandardTaskCatalog = class _StandardTaskCatalog {
3223
3297
  __name(_StandardTaskCatalog, "StandardTaskCatalog");
3224
3298
  var StandardTaskCatalog = _StandardTaskCatalog;
3225
3299
 
3226
- export { ConsoleInterceptor, PreciseWallClock as DurableClock, OtelTaskLogger, StandardTaskCatalog, TaskContextLogProcessor, TaskContextSpanProcessor, TaskExecutor, TracingSDK, getEnvVar, logLevels, recordSpanException };
3300
+ // src/v3/usage/noopUsageManager.ts
3301
+ var _NoopUsageManager = class _NoopUsageManager {
3302
+ disable() {
3303
+ }
3304
+ start() {
3305
+ return {
3306
+ sample: () => ({
3307
+ cpuTime: 0,
3308
+ wallTime: 0
3309
+ })
3310
+ };
3311
+ }
3312
+ stop(measurement) {
3313
+ return measurement.sample();
3314
+ }
3315
+ pauseAsync(cb) {
3316
+ return cb();
3317
+ }
3318
+ sample() {
3319
+ return void 0;
3320
+ }
3321
+ };
3322
+ __name(_NoopUsageManager, "NoopUsageManager");
3323
+ var NoopUsageManager = _NoopUsageManager;
3324
+
3325
+ // src/v3/usage/api.ts
3326
+ var API_NAME4 = "usage";
3327
+ var NOOP_USAGE_MANAGER = new NoopUsageManager();
3328
+ var _getUsageManager, getUsageManager_fn;
3329
+ var _UsageAPI = class _UsageAPI {
3330
+ constructor() {
3331
+ __privateAdd(this, _getUsageManager);
3332
+ }
3333
+ static getInstance() {
3334
+ if (!this._instance) {
3335
+ this._instance = new _UsageAPI();
3336
+ }
3337
+ return this._instance;
3338
+ }
3339
+ setGlobalUsageManager(manager) {
3340
+ return registerGlobal(API_NAME4, manager);
3341
+ }
3342
+ disable() {
3343
+ __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).disable();
3344
+ unregisterGlobal(API_NAME4);
3345
+ }
3346
+ start() {
3347
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).start();
3348
+ }
3349
+ stop(measurement) {
3350
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).stop(measurement);
3351
+ }
3352
+ pauseAsync(cb) {
3353
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).pauseAsync(cb);
3354
+ }
3355
+ sample() {
3356
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).sample();
3357
+ }
3358
+ };
3359
+ _getUsageManager = new WeakSet();
3360
+ getUsageManager_fn = /* @__PURE__ */ __name(function() {
3361
+ return getGlobal(API_NAME4) ?? NOOP_USAGE_MANAGER;
3362
+ }, "#getUsageManager");
3363
+ __name(_UsageAPI, "UsageAPI");
3364
+ var UsageAPI = _UsageAPI;
3365
+
3366
+ // src/v3/usage-api.ts
3367
+ var usage = UsageAPI.getInstance();
3368
+
3369
+ // src/v3/clock/clock.ts
3370
+ function calculateDurationInMs(start, end) {
3371
+ const [startSeconds, startNanoseconds] = start;
3372
+ const [endSeconds, endNanoseconds] = end;
3373
+ const seconds = endSeconds - startSeconds;
3374
+ const nanoseconds = endNanoseconds - startNanoseconds;
3375
+ return Math.floor(seconds * 1e3 + nanoseconds / 1e6);
3376
+ }
3377
+ __name(calculateDurationInMs, "calculateDurationInMs");
3378
+
3379
+ // src/v3/usage/devUsageManager.ts
3380
+ var _a2;
3381
+ var DevUsageMeasurement = (_a2 = class {
3382
+ constructor(id, startedAt = clock.preciseNow()) {
3383
+ this.id = id;
3384
+ this.startedAt = startedAt;
3385
+ this._pauses = /* @__PURE__ */ new Map();
3386
+ }
3387
+ stop() {
3388
+ this._endedAt = clock.preciseNow();
3389
+ }
3390
+ sample() {
3391
+ const endedAt = this._endedAt ?? clock.preciseNow();
3392
+ const wallTime = this.startedAt ? calculateDurationInMs(this.startedAt, endedAt) : 0;
3393
+ if (wallTime === 0) {
3394
+ return {
3395
+ cpuTime: 0,
3396
+ wallTime: 0
3397
+ };
3398
+ }
3399
+ const totalPauses = Array.from(this._pauses.values()).reduce((total, pause) => {
3400
+ return total + calculateDurationInMs(pause.start, pause.end ?? endedAt);
3401
+ }, 0);
3402
+ const cpuTime = wallTime - totalPauses;
3403
+ return {
3404
+ wallTime,
3405
+ cpuTime
3406
+ };
3407
+ }
3408
+ registerPause(pauseId, start, end) {
3409
+ this._pauses.set(pauseId, {
3410
+ start,
3411
+ end
3412
+ });
3413
+ }
3414
+ }, __name(_a2, "DevUsageMeasurement"), _a2);
3415
+ var _DevUsageManager = class _DevUsageManager {
3416
+ constructor() {
3417
+ __publicField(this, "_currentMeasurements", /* @__PURE__ */ new Map());
3418
+ __publicField(this, "_pauses", /* @__PURE__ */ new Map());
3419
+ }
3420
+ disable() {
3421
+ }
3422
+ sample() {
3423
+ return this._firstMeasurement?.sample();
3424
+ }
3425
+ start() {
3426
+ const id = generateRandomString();
3427
+ const measurement = new DevUsageMeasurement(id);
3428
+ if (!this._firstMeasurement) {
3429
+ this._firstMeasurement = measurement;
3430
+ }
3431
+ this._currentMeasurements.set(id, measurement);
3432
+ return measurement;
3433
+ }
3434
+ stop(measurement) {
3435
+ measurement.stop();
3436
+ const sample = measurement.sample();
3437
+ this._currentMeasurements.delete(measurement.id);
3438
+ return sample;
3439
+ }
3440
+ async pauseAsync(cb) {
3441
+ const pauseId = generateRandomString();
3442
+ const pauseStart = clock.preciseNow();
3443
+ try {
3444
+ this._pauses.set(pauseId, {
3445
+ start: pauseStart
3446
+ });
3447
+ for (const measurement of this._currentMeasurements.values()) {
3448
+ measurement.registerPause(pauseId, pauseStart);
3449
+ }
3450
+ return await cb();
3451
+ } finally {
3452
+ const pauseEnd = clock.preciseNow();
3453
+ this._pauses.set(pauseId, {
3454
+ start: pauseStart,
3455
+ end: pauseEnd
3456
+ });
3457
+ for (const measurement of this._currentMeasurements.values()) {
3458
+ measurement.registerPause(pauseId, pauseStart, pauseEnd);
3459
+ }
3460
+ }
3461
+ }
3462
+ };
3463
+ __name(_DevUsageManager, "DevUsageManager");
3464
+ var DevUsageManager = _DevUsageManager;
3465
+ function generateRandomString() {
3466
+ let result = "";
3467
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3468
+ const charactersLength = characters.length;
3469
+ for (var i = 0; i < 16; i++) {
3470
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
3471
+ }
3472
+ return result;
3473
+ }
3474
+ __name(generateRandomString, "generateRandomString");
3475
+
3476
+ // src/v3/usage/usageClient.ts
3477
+ var _UsageClient = class _UsageClient {
3478
+ constructor(url, jwt) {
3479
+ this.url = url;
3480
+ this.jwt = jwt;
3481
+ }
3482
+ async sendUsageEvent(event) {
3483
+ try {
3484
+ const response = await fetch(this.url, {
3485
+ method: "POST",
3486
+ body: JSON.stringify(event),
3487
+ headers: {
3488
+ "content-type": "application/json",
3489
+ "x-trigger-jwt": this.jwt,
3490
+ accept: "application/json",
3491
+ authorization: `Bearer ${apiClientManager.accessToken}`
3492
+ }
3493
+ });
3494
+ if (response.ok) {
3495
+ const renewedJwt = response.headers.get("x-trigger-jwt");
3496
+ if (renewedJwt) {
3497
+ this.jwt = renewedJwt;
3498
+ }
3499
+ }
3500
+ } catch (error) {
3501
+ console.error(`Failed to send usage event: ${error}`);
3502
+ }
3503
+ }
3504
+ };
3505
+ __name(_UsageClient, "UsageClient");
3506
+ var UsageClient = _UsageClient;
3507
+
3508
+ // src/v3/usage/prodUsageManager.ts
3509
+ var _startReportingHeartbeat, startReportingHeartbeat_fn, _reportUsage, reportUsage_fn;
3510
+ var _ProdUsageManager = class _ProdUsageManager {
3511
+ constructor(delegageUsageManager, options) {
3512
+ __privateAdd(this, _startReportingHeartbeat);
3513
+ __privateAdd(this, _reportUsage);
3514
+ this.delegageUsageManager = delegageUsageManager;
3515
+ this.options = options;
3516
+ if (this.options.url && this.options.jwt) {
3517
+ this._usageClient = new UsageClient(this.options.url, this.options.jwt);
3518
+ }
3519
+ }
3520
+ get isReportingEnabled() {
3521
+ return typeof this._usageClient !== "undefined";
3522
+ }
3523
+ disable() {
3524
+ this.delegageUsageManager.disable();
3525
+ this._abortController?.abort();
3526
+ }
3527
+ sample() {
3528
+ return this._measurement?.sample();
3529
+ }
3530
+ start() {
3531
+ if (!this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3532
+ return this.delegageUsageManager.start();
3533
+ }
3534
+ if (!this._measurement) {
3535
+ this._measurement = this.delegageUsageManager.start();
3536
+ __privateMethod(this, _startReportingHeartbeat, startReportingHeartbeat_fn).call(this).catch(console.error);
3537
+ return this._measurement;
3538
+ }
3539
+ return this.delegageUsageManager.start();
3540
+ }
3541
+ stop(measurement) {
3542
+ return this.delegageUsageManager.stop(measurement);
3543
+ }
3544
+ async pauseAsync(cb) {
3545
+ return this.delegageUsageManager.pauseAsync(cb);
3546
+ }
3547
+ async flush() {
3548
+ return await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3549
+ }
3550
+ };
3551
+ _startReportingHeartbeat = new WeakSet();
3552
+ startReportingHeartbeat_fn = /* @__PURE__ */ __name(async function() {
3553
+ if (!this._measurement || !this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3554
+ return;
3555
+ }
3556
+ this._abortController = new AbortController();
3557
+ for await (const _ of setInterval(this.options.heartbeatIntervalMs)) {
3558
+ if (this._abortController.signal.aborted) {
3559
+ break;
3560
+ }
3561
+ await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3562
+ }
3563
+ }, "#startReportingHeartbeat");
3564
+ _reportUsage = new WeakSet();
3565
+ reportUsage_fn = /* @__PURE__ */ __name(async function() {
3566
+ if (!this._measurement) {
3567
+ return;
3568
+ }
3569
+ if (!this.isReportingEnabled) {
3570
+ return;
3571
+ }
3572
+ const client = this._usageClient;
3573
+ if (!client) {
3574
+ return;
3575
+ }
3576
+ const sample = this._measurement.sample();
3577
+ const cpuTimeSinceLastSample = this._lastSample ? sample.cpuTime - this._lastSample.cpuTime : sample.cpuTime;
3578
+ this._lastSample = sample;
3579
+ if (cpuTimeSinceLastSample <= 0) {
3580
+ return;
3581
+ }
3582
+ await client.sendUsageEvent({
3583
+ durationMs: cpuTimeSinceLastSample
3584
+ });
3585
+ }, "#reportUsage");
3586
+ __name(_ProdUsageManager, "ProdUsageManager");
3587
+ var ProdUsageManager = _ProdUsageManager;
3588
+
3589
+ export { ConsoleInterceptor, DevUsageManager, PreciseWallClock as DurableClock, OtelTaskLogger, ProdUsageManager, StandardTaskCatalog, TaskContextLogProcessor, TaskContextSpanProcessor, TaskExecutor, TracingSDK, getEnvVar, logLevels, recordSpanException, usage };
3227
3590
  //# sourceMappingURL=out.js.map
3228
3591
  //# sourceMappingURL=index.mjs.map