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

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 (37) hide show
  1. package/dist/{catalog-dRKTgwQ7.d.ts → catalog-Tdea4K0I.d.mts} +43 -3
  2. package/dist/{catalog-XTlJQaMn.d.mts → catalog-yeAHwmSe.d.ts} +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-BD0yXLtn.d.mts} +2370 -141
  6. package/dist/{messages-9lty-Du5.d.ts → messages-BD0yXLtn.d.ts} +2370 -141
  7. package/dist/{schemas-r4ZP9S-F.d.mts → schemas-XNxZYXOy.d.mts} +199 -33
  8. package/dist/{schemas-r4ZP9S-F.d.ts → schemas-XNxZYXOy.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 +117 -52
  12. package/dist/v3/index.d.ts +117 -52
  13. package/dist/v3/index.js +204 -58
  14. package/dist/v3/index.js.map +1 -1
  15. package/dist/v3/index.mjs +199 -58
  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 +404 -43
  28. package/dist/v3/workers/index.js.map +1 -1
  29. package/dist/v3/workers/index.mjs +402 -44
  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/zodMessageHandler.d.mts +1 -1
  34. package/dist/v3/zodMessageHandler.d.ts +1 -1
  35. package/dist/v3/zodfetch.d.mts +1 -1
  36. package/dist/v3/zodfetch.d.ts +1 -1
  37. 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.38";
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,7 +734,8 @@ var ProdTaskRunExecution = TaskRunExecution.extend({
697
734
  id: z.string(),
698
735
  contentHash: z.string(),
699
736
  version: z.string()
700
- })
737
+ }),
738
+ machine: MachinePreset
701
739
  });
702
740
  z.object({
703
741
  execution: ProdTaskRunExecution,
@@ -801,7 +839,7 @@ z.object({
801
839
  packageVersion: z.string(),
802
840
  queue: QueueOptions.optional(),
803
841
  retry: RetryOptions.optional(),
804
- machine: Machine.partial().optional(),
842
+ machine: MachineConfig.optional(),
805
843
  triggerSource: z.string().optional()
806
844
  });
807
845
  z.object({
@@ -813,7 +851,7 @@ z.object({
813
851
  packageVersion: z.string(),
814
852
  queue: QueueOptions.optional(),
815
853
  retry: RetryOptions.optional(),
816
- machine: Machine.partial().optional(),
854
+ machine: MachineConfig.optional(),
817
855
  triggerSource: z.string().optional(),
818
856
  filePath: z.string(),
819
857
  exportName: z.string()
@@ -873,7 +911,7 @@ var TaskResource = z.object({
873
911
  exportName: z.string(),
874
912
  queue: QueueOptions.optional(),
875
913
  retry: RetryOptions.optional(),
876
- machine: Machine.partial().optional(),
914
+ machine: MachineConfig.optional(),
877
915
  triggerSource: z.string().optional()
878
916
  });
879
917
  var BackgroundWorkerMetadata = z.object({
@@ -1036,19 +1074,30 @@ z.object({
1036
1074
  You can use this to remove the schedule, update it, etc */
1037
1075
  scheduleId: z.string(),
1038
1076
  /** 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. */
1077
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task.
1078
+ *
1079
+ * This date is UTC. To output it as a string with a timezone you would do this:
1080
+ * ```ts
1081
+ * const formatted = payload.timestamp.toLocaleString("en-US", {
1082
+ timeZone: payload.timezone,
1083
+ });
1084
+ ``` */
1040
1085
  timestamp: z.date(),
1041
1086
  /** When the task was last run (it has been).
1042
- This can be undefined if it's never been run */
1087
+ This can be undefined if it's never been run. This date is UTC. */
1043
1088
  lastTimestamp: z.date().optional(),
1044
1089
  /** You can optionally provide an external id when creating the schedule.
1045
1090
  Usually you would use a userId or some other unique identifier.
1046
1091
  This defaults to undefined if you didn't provide one. */
1047
1092
  externalId: z.string().optional(),
1093
+ /** The IANA timezone the schedule is set to. The default is UTC.
1094
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1095
+ */
1096
+ timezone: z.string(),
1048
1097
  /** The next 5 dates this task is scheduled to run */
1049
1098
  upcoming: z.array(z.date())
1050
1099
  });
1051
- z.object({
1100
+ var CreateScheduleOptions = z.object({
1052
1101
  /** The id of the task you want to attach to. */
1053
1102
  task: z.string(),
1054
1103
  /** The schedule in CRON format.
@@ -1068,15 +1117,29 @@ z.object({
1068
1117
 
1069
1118
  */
1070
1119
  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.
1120
+ /** You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1072
1121
  *
1073
- * This is useful if you don't want to create duplicate schedules for a user. */
1074
- deduplicationKey: z.string().optional(),
1122
+ * This is required to prevent you from creating duplicate schedules. */
1123
+ deduplicationKey: z.string(),
1075
1124
  /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
1076
1125
  *
1077
1126
  * This allows you to have per-user CRON tasks.
1078
1127
  */
1079
- externalId: z.string().optional()
1128
+ externalId: z.string().optional(),
1129
+ /** Optionally, you can specify a timezone in the IANA format. If unset it will use UTC.
1130
+ * If specified then the CRON will be evaluated in that timezone and will respect daylight savings.
1131
+ *
1132
+ * 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.
1133
+ *
1134
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1135
+ *
1136
+ * @example "America/New_York", "Europe/London", "Asia/Tokyo", "Africa/Cairo"
1137
+ *
1138
+ */
1139
+ timezone: z.string().optional()
1140
+ });
1141
+ CreateScheduleOptions.omit({
1142
+ deduplicationKey: true
1080
1143
  });
1081
1144
  var ScheduleGenerator = z.object({
1082
1145
  type: z.literal("CRON"),
@@ -1090,6 +1153,7 @@ var ScheduleObject = z.object({
1090
1153
  deduplicationKey: z.string().nullish(),
1091
1154
  externalId: z.string().nullish(),
1092
1155
  generator: ScheduleGenerator,
1156
+ timezone: z.string(),
1093
1157
  nextRun: z.coerce.date().nullish(),
1094
1158
  environments: z.array(z.object({
1095
1159
  id: z.string(),
@@ -1112,6 +1176,9 @@ z.object({
1112
1176
  page: z.number().optional(),
1113
1177
  perPage: z.number().optional()
1114
1178
  });
1179
+ z.object({
1180
+ timezones: z.array(z.string())
1181
+ });
1115
1182
  var RunStatus = z.enum([
1116
1183
  /// Task hasn't been deployed yet but is waiting to be executed
1117
1184
  "WAITING_FOR_DEPLOY",
@@ -2466,7 +2533,7 @@ var _TaskExecutor = class _TaskExecutor {
2466
2533
  this._importedConfig = options.importedConfig;
2467
2534
  this._handleErrorFn = options.handleErrorFn;
2468
2535
  }
2469
- async execute(execution, worker, traceContext) {
2536
+ async execute(execution, worker, traceContext, usage2) {
2470
2537
  const ctx = TaskRunContext.parse(execution);
2471
2538
  const attemptMessage = `Attempt ${execution.attempt.number}`;
2472
2539
  const originalPacket = {
@@ -2567,7 +2634,9 @@ var _TaskExecutor = class _TaskExecutor {
2567
2634
  })
2568
2635
  }
2569
2636
  }, this._tracer.extractContext(traceContext));
2570
- return result;
2637
+ return {
2638
+ result
2639
+ };
2571
2640
  }
2572
2641
  };
2573
2642
  _callRun = new WeakSet();
@@ -3223,6 +3292,295 @@ var _StandardTaskCatalog = class _StandardTaskCatalog {
3223
3292
  __name(_StandardTaskCatalog, "StandardTaskCatalog");
3224
3293
  var StandardTaskCatalog = _StandardTaskCatalog;
3225
3294
 
3226
- export { ConsoleInterceptor, PreciseWallClock as DurableClock, OtelTaskLogger, StandardTaskCatalog, TaskContextLogProcessor, TaskContextSpanProcessor, TaskExecutor, TracingSDK, getEnvVar, logLevels, recordSpanException };
3295
+ // src/v3/usage/noopUsageManager.ts
3296
+ var _NoopUsageManager = class _NoopUsageManager {
3297
+ disable() {
3298
+ }
3299
+ start() {
3300
+ return {
3301
+ sample: () => ({
3302
+ cpuTime: 0,
3303
+ wallTime: 0
3304
+ })
3305
+ };
3306
+ }
3307
+ stop(measurement) {
3308
+ return measurement.sample();
3309
+ }
3310
+ pauseAsync(cb) {
3311
+ return cb();
3312
+ }
3313
+ sample() {
3314
+ return void 0;
3315
+ }
3316
+ };
3317
+ __name(_NoopUsageManager, "NoopUsageManager");
3318
+ var NoopUsageManager = _NoopUsageManager;
3319
+
3320
+ // src/v3/usage/api.ts
3321
+ var API_NAME4 = "usage";
3322
+ var NOOP_USAGE_MANAGER = new NoopUsageManager();
3323
+ var _getUsageManager, getUsageManager_fn;
3324
+ var _UsageAPI = class _UsageAPI {
3325
+ constructor() {
3326
+ __privateAdd(this, _getUsageManager);
3327
+ }
3328
+ static getInstance() {
3329
+ if (!this._instance) {
3330
+ this._instance = new _UsageAPI();
3331
+ }
3332
+ return this._instance;
3333
+ }
3334
+ setGlobalUsageManager(manager) {
3335
+ return registerGlobal(API_NAME4, manager);
3336
+ }
3337
+ disable() {
3338
+ __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).disable();
3339
+ unregisterGlobal(API_NAME4);
3340
+ }
3341
+ start() {
3342
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).start();
3343
+ }
3344
+ stop(measurement) {
3345
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).stop(measurement);
3346
+ }
3347
+ pauseAsync(cb) {
3348
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).pauseAsync(cb);
3349
+ }
3350
+ sample() {
3351
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).sample();
3352
+ }
3353
+ };
3354
+ _getUsageManager = new WeakSet();
3355
+ getUsageManager_fn = /* @__PURE__ */ __name(function() {
3356
+ return getGlobal(API_NAME4) ?? NOOP_USAGE_MANAGER;
3357
+ }, "#getUsageManager");
3358
+ __name(_UsageAPI, "UsageAPI");
3359
+ var UsageAPI = _UsageAPI;
3360
+
3361
+ // src/v3/usage-api.ts
3362
+ var usage = UsageAPI.getInstance();
3363
+
3364
+ // src/v3/clock/clock.ts
3365
+ function calculateDurationInMs(start, end) {
3366
+ const [startSeconds, startNanoseconds] = start;
3367
+ const [endSeconds, endNanoseconds] = end;
3368
+ const seconds = endSeconds - startSeconds;
3369
+ const nanoseconds = endNanoseconds - startNanoseconds;
3370
+ return Math.floor(seconds * 1e3 + nanoseconds / 1e6);
3371
+ }
3372
+ __name(calculateDurationInMs, "calculateDurationInMs");
3373
+
3374
+ // src/v3/usage/devUsageManager.ts
3375
+ var _a2;
3376
+ var DevUsageMeasurement = (_a2 = class {
3377
+ constructor(id, startedAt = clock.preciseNow()) {
3378
+ this.id = id;
3379
+ this.startedAt = startedAt;
3380
+ this._pauses = /* @__PURE__ */ new Map();
3381
+ }
3382
+ stop() {
3383
+ this._endedAt = clock.preciseNow();
3384
+ }
3385
+ sample() {
3386
+ const endedAt = this._endedAt ?? clock.preciseNow();
3387
+ const wallTime = this.startedAt ? calculateDurationInMs(this.startedAt, endedAt) : 0;
3388
+ if (wallTime === 0) {
3389
+ return {
3390
+ cpuTime: 0,
3391
+ wallTime: 0
3392
+ };
3393
+ }
3394
+ const totalPauses = Array.from(this._pauses.values()).reduce((total, pause) => {
3395
+ return total + calculateDurationInMs(pause.start, pause.end ?? endedAt);
3396
+ }, 0);
3397
+ const cpuTime = wallTime - totalPauses;
3398
+ return {
3399
+ wallTime,
3400
+ cpuTime
3401
+ };
3402
+ }
3403
+ registerPause(pauseId, start, end) {
3404
+ this._pauses.set(pauseId, {
3405
+ start,
3406
+ end
3407
+ });
3408
+ }
3409
+ }, __name(_a2, "DevUsageMeasurement"), _a2);
3410
+ var _DevUsageManager = class _DevUsageManager {
3411
+ constructor() {
3412
+ __publicField(this, "_currentMeasurements", /* @__PURE__ */ new Map());
3413
+ __publicField(this, "_pauses", /* @__PURE__ */ new Map());
3414
+ }
3415
+ disable() {
3416
+ }
3417
+ sample() {
3418
+ return this._firstMeasurement?.sample();
3419
+ }
3420
+ start() {
3421
+ const id = generateRandomString();
3422
+ const measurement = new DevUsageMeasurement(id);
3423
+ if (!this._firstMeasurement) {
3424
+ this._firstMeasurement = measurement;
3425
+ }
3426
+ this._currentMeasurements.set(id, measurement);
3427
+ return measurement;
3428
+ }
3429
+ stop(measurement) {
3430
+ measurement.stop();
3431
+ const sample = measurement.sample();
3432
+ this._currentMeasurements.delete(measurement.id);
3433
+ return sample;
3434
+ }
3435
+ async pauseAsync(cb) {
3436
+ const pauseId = generateRandomString();
3437
+ const pauseStart = clock.preciseNow();
3438
+ try {
3439
+ this._pauses.set(pauseId, {
3440
+ start: pauseStart
3441
+ });
3442
+ for (const measurement of this._currentMeasurements.values()) {
3443
+ measurement.registerPause(pauseId, pauseStart);
3444
+ }
3445
+ return await cb();
3446
+ } finally {
3447
+ const pauseEnd = clock.preciseNow();
3448
+ this._pauses.set(pauseId, {
3449
+ start: pauseStart,
3450
+ end: pauseEnd
3451
+ });
3452
+ for (const measurement of this._currentMeasurements.values()) {
3453
+ measurement.registerPause(pauseId, pauseStart, pauseEnd);
3454
+ }
3455
+ }
3456
+ }
3457
+ };
3458
+ __name(_DevUsageManager, "DevUsageManager");
3459
+ var DevUsageManager = _DevUsageManager;
3460
+ function generateRandomString() {
3461
+ let result = "";
3462
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3463
+ const charactersLength = characters.length;
3464
+ for (var i = 0; i < 16; i++) {
3465
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
3466
+ }
3467
+ return result;
3468
+ }
3469
+ __name(generateRandomString, "generateRandomString");
3470
+
3471
+ // src/v3/usage/usageClient.ts
3472
+ var _UsageClient = class _UsageClient {
3473
+ constructor(url, jwt) {
3474
+ this.url = url;
3475
+ this.jwt = jwt;
3476
+ }
3477
+ async sendUsageEvent(event) {
3478
+ try {
3479
+ const response = await fetch(this.url, {
3480
+ method: "POST",
3481
+ body: JSON.stringify(event),
3482
+ headers: {
3483
+ "content-type": "application/json",
3484
+ "x-trigger-jwt": this.jwt,
3485
+ accept: "application/json",
3486
+ authorization: `Bearer ${apiClientManager.accessToken}`
3487
+ }
3488
+ });
3489
+ if (response.ok) {
3490
+ const renewedJwt = response.headers.get("x-trigger-jwt");
3491
+ if (renewedJwt) {
3492
+ this.jwt = renewedJwt;
3493
+ }
3494
+ }
3495
+ } catch (error) {
3496
+ console.error(`Failed to send usage event: ${error}`);
3497
+ }
3498
+ }
3499
+ };
3500
+ __name(_UsageClient, "UsageClient");
3501
+ var UsageClient = _UsageClient;
3502
+
3503
+ // src/v3/usage/prodUsageManager.ts
3504
+ var _startReportingHeartbeat, startReportingHeartbeat_fn, _reportUsage, reportUsage_fn;
3505
+ var _ProdUsageManager = class _ProdUsageManager {
3506
+ constructor(delegageUsageManager, options) {
3507
+ __privateAdd(this, _startReportingHeartbeat);
3508
+ __privateAdd(this, _reportUsage);
3509
+ this.delegageUsageManager = delegageUsageManager;
3510
+ this.options = options;
3511
+ if (this.options.url && this.options.jwt) {
3512
+ this._usageClient = new UsageClient(this.options.url, this.options.jwt);
3513
+ }
3514
+ }
3515
+ get isReportingEnabled() {
3516
+ return typeof this._usageClient !== "undefined";
3517
+ }
3518
+ disable() {
3519
+ this.delegageUsageManager.disable();
3520
+ this._abortController?.abort();
3521
+ }
3522
+ sample() {
3523
+ return this._measurement?.sample();
3524
+ }
3525
+ start() {
3526
+ if (!this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3527
+ return this.delegageUsageManager.start();
3528
+ }
3529
+ if (!this._measurement) {
3530
+ this._measurement = this.delegageUsageManager.start();
3531
+ __privateMethod(this, _startReportingHeartbeat, startReportingHeartbeat_fn).call(this).catch(console.error);
3532
+ return this._measurement;
3533
+ }
3534
+ return this.delegageUsageManager.start();
3535
+ }
3536
+ stop(measurement) {
3537
+ return this.delegageUsageManager.stop(measurement);
3538
+ }
3539
+ async pauseAsync(cb) {
3540
+ return this.delegageUsageManager.pauseAsync(cb);
3541
+ }
3542
+ async flush() {
3543
+ return await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3544
+ }
3545
+ };
3546
+ _startReportingHeartbeat = new WeakSet();
3547
+ startReportingHeartbeat_fn = /* @__PURE__ */ __name(async function() {
3548
+ if (!this._measurement || !this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3549
+ return;
3550
+ }
3551
+ this._abortController = new AbortController();
3552
+ for await (const _ of setInterval(this.options.heartbeatIntervalMs)) {
3553
+ if (this._abortController.signal.aborted) {
3554
+ break;
3555
+ }
3556
+ await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3557
+ }
3558
+ }, "#startReportingHeartbeat");
3559
+ _reportUsage = new WeakSet();
3560
+ reportUsage_fn = /* @__PURE__ */ __name(async function() {
3561
+ if (!this._measurement) {
3562
+ return;
3563
+ }
3564
+ if (!this.isReportingEnabled) {
3565
+ return;
3566
+ }
3567
+ const client = this._usageClient;
3568
+ if (!client) {
3569
+ return;
3570
+ }
3571
+ const sample = this._measurement.sample();
3572
+ const cpuTimeSinceLastSample = this._lastSample ? sample.cpuTime - this._lastSample.cpuTime : sample.cpuTime;
3573
+ this._lastSample = sample;
3574
+ if (cpuTimeSinceLastSample <= 0) {
3575
+ return;
3576
+ }
3577
+ await client.sendUsageEvent({
3578
+ durationMs: cpuTimeSinceLastSample
3579
+ });
3580
+ }, "#reportUsage");
3581
+ __name(_ProdUsageManager, "ProdUsageManager");
3582
+ var ProdUsageManager = _ProdUsageManager;
3583
+
3584
+ export { ConsoleInterceptor, DevUsageManager, PreciseWallClock as DurableClock, OtelTaskLogger, ProdUsageManager, StandardTaskCatalog, TaskContextLogProcessor, TaskContextSpanProcessor, TaskExecutor, TracingSDK, getEnvVar, logLevels, recordSpanException, usage };
3227
3585
  //# sourceMappingURL=out.js.map
3228
3586
  //# sourceMappingURL=index.mjs.map