@trigger.dev/core 3.0.0-beta.0 → 3.0.0-beta.11

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.
package/dist/v3/index.js CHANGED
@@ -9,6 +9,7 @@ var nodePath = require('path');
9
9
  var apiLogs = require('@opentelemetry/api-logs');
10
10
  var preciseDate = require('@google-cloud/precise-date');
11
11
  var humanizeDuration = require('humanize-duration');
12
+ var promises = require('timers/promises');
12
13
  var util = require('util');
13
14
  var exporterLogsOtlpHttp = require('@opentelemetry/exporter-logs-otlp-http');
14
15
  var exporterTraceOtlpHttp = require('@opentelemetry/exporter-trace-otlp-http');
@@ -17,7 +18,6 @@ var resources = require('@opentelemetry/resources');
17
18
  var sdkLogs = require('@opentelemetry/sdk-logs');
18
19
  var sdkTraceNode = require('@opentelemetry/sdk-trace-node');
19
20
  var semanticConventions = require('@opentelemetry/semantic-conventions');
20
- var superjson = require('superjson');
21
21
 
22
22
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
23
23
 
@@ -225,6 +225,32 @@ var BatchTaskRunExecutionResult = zod.z.object({
225
225
  });
226
226
 
227
227
  // src/v3/schemas/messages.ts
228
+ var EnvironmentType = zod.z.enum([
229
+ "PRODUCTION",
230
+ "STAGING",
231
+ "DEVELOPMENT",
232
+ "PREVIEW"
233
+ ]);
234
+ var MachineCpu = zod.z.union([
235
+ zod.z.literal(0.25),
236
+ zod.z.literal(0.5),
237
+ zod.z.literal(1),
238
+ zod.z.literal(2),
239
+ zod.z.literal(4)
240
+ ]).default(0.5);
241
+ var MachineMemory = zod.z.union([
242
+ zod.z.literal(0.25),
243
+ zod.z.literal(0.5),
244
+ zod.z.literal(1),
245
+ zod.z.literal(2),
246
+ zod.z.literal(4),
247
+ zod.z.literal(8)
248
+ ]).default(1);
249
+ var Machine = zod.z.object({
250
+ version: zod.z.literal("v1").default("v1"),
251
+ cpu: MachineCpu,
252
+ memory: MachineMemory
253
+ });
228
254
  var TaskRunExecutionPayload = zod.z.object({
229
255
  execution: TaskRunExecution,
230
256
  traceContext: zod.z.record(zod.z.unknown()),
@@ -254,11 +280,16 @@ var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
254
280
  }),
255
281
  zod.z.object({
256
282
  type: zod.z.literal("SCHEDULE_ATTEMPT"),
257
- id: zod.z.string(),
258
283
  image: zod.z.string(),
284
+ version: zod.z.string(),
285
+ machine: Machine,
286
+ // identifiers
287
+ id: zod.z.string(),
259
288
  envId: zod.z.string(),
260
- runId: zod.z.string(),
261
- version: zod.z.string()
289
+ envType: EnvironmentType,
290
+ orgId: zod.z.string(),
291
+ projectId: zod.z.string(),
292
+ runId: zod.z.string()
262
293
  })
263
294
  ]);
264
295
  var serverWebsocketMessages = {
@@ -411,7 +442,7 @@ var QueueOptions = zod.z.object({
411
442
  /** An optional property that specifies the maximum number of concurrent run executions.
412
443
  *
413
444
  * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
414
- concurrencyLimit: zod.z.number().int().min(1).max(1e3).optional(),
445
+ concurrencyLimit: zod.z.number().int().min(0).max(1e3).optional(),
415
446
  /** @deprecated This feature is coming soon */
416
447
  rateLimit: RateLimitOptions.optional()
417
448
  });
@@ -420,7 +451,8 @@ var TaskMetadata = zod.z.object({
420
451
  exportName: zod.z.string(),
421
452
  packageVersion: zod.z.string(),
422
453
  queue: QueueOptions.optional(),
423
- retry: RetryOptions.optional()
454
+ retry: RetryOptions.optional(),
455
+ machine: Machine.partial().optional()
424
456
  });
425
457
  var TaskMetadataWithFilePath = TaskMetadata.extend({
426
458
  filePath: zod.z.string()
@@ -437,6 +469,13 @@ var UncaughtExceptionMessage = zod.z.object({
437
469
  "unhandledRejection"
438
470
  ])
439
471
  });
472
+ var TaskMetadataFailedToParseData = zod.z.object({
473
+ version: zod.z.literal("v1").default("v1"),
474
+ tasks: zod.z.unknown(),
475
+ zodIssues: zod.z.custom((v) => {
476
+ return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
477
+ })
478
+ });
440
479
  var childToWorkerMessages = {
441
480
  TASK_RUN_COMPLETED: zod.z.object({
442
481
  version: zod.z.literal("v1").default("v1"),
@@ -447,6 +486,7 @@ var childToWorkerMessages = {
447
486
  version: zod.z.literal("v1").default("v1"),
448
487
  tasks: TaskMetadataWithFilePath.array()
449
488
  }),
489
+ TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
450
490
  TASK_HEARTBEAT: zod.z.object({
451
491
  version: zod.z.literal("v1").default("v1"),
452
492
  id: zod.z.string()
@@ -481,6 +521,9 @@ var ProdChildToWorkerMessages = {
481
521
  tasks: TaskMetadataWithFilePath.array()
482
522
  })
483
523
  },
524
+ TASKS_FAILED_TO_PARSE: {
525
+ message: TaskMetadataFailedToParseData
526
+ },
484
527
  TASK_HEARTBEAT: {
485
528
  message: zod.z.object({
486
529
  version: zod.z.literal("v1").default("v1"),
@@ -564,7 +607,8 @@ var TaskResource = zod.z.object({
564
607
  filePath: zod.z.string(),
565
608
  exportName: zod.z.string(),
566
609
  queue: QueueOptions.optional(),
567
- retry: RetryOptions.optional()
610
+ retry: RetryOptions.optional(),
611
+ machine: Machine.partial().optional()
568
612
  });
569
613
  var BackgroundWorkerMetadata = zod.z.object({
570
614
  packageVersion: zod.z.string(),
@@ -675,6 +719,11 @@ var InitializeDeploymentRequestBody = zod.z.object({
675
719
  contentHash: zod.z.string(),
676
720
  userId: zod.z.string().optional()
677
721
  });
722
+ var DeploymentErrorData = zod.z.object({
723
+ name: zod.z.string(),
724
+ message: zod.z.string(),
725
+ stack: zod.z.string().optional()
726
+ });
678
727
  var GetDeploymentResponseBody = zod.z.object({
679
728
  id: zod.z.string(),
680
729
  status: zod.z.enum([
@@ -690,11 +739,7 @@ var GetDeploymentResponseBody = zod.z.object({
690
739
  shortCode: zod.z.string(),
691
740
  version: zod.z.string(),
692
741
  imageReference: zod.z.string().optional(),
693
- errorData: zod.z.object({
694
- name: zod.z.string(),
695
- message: zod.z.string(),
696
- stack: zod.z.string().optional()
697
- }).optional().nullable(),
742
+ errorData: DeploymentErrorData.optional().nullable(),
698
743
  worker: zod.z.object({
699
744
  id: zod.z.string(),
700
745
  version: zod.z.string(),
@@ -709,6 +754,20 @@ var GetDeploymentResponseBody = zod.z.object({
709
754
  var CreateUploadPayloadUrlResponseBody = zod.z.object({
710
755
  presignedUrl: zod.z.string()
711
756
  });
757
+ var ReplayRunResponse = zod.z.object({
758
+ id: zod.z.string()
759
+ });
760
+ var CanceledRunResponse = zod.z.object({
761
+ message: zod.z.string()
762
+ });
763
+ var PostStartCauses = zod.z.enum([
764
+ "index",
765
+ "create",
766
+ "restore"
767
+ ]);
768
+ var PreStopCauses = zod.z.enum([
769
+ "terminate"
770
+ ]);
712
771
  var RegexSchema = zod.z.custom((val) => {
713
772
  try {
714
773
  return typeof val.test === "function";
@@ -731,11 +790,8 @@ var Config = zod.z.object({
731
790
  dependenciesToBundle: zod.z.array(zod.z.union([
732
791
  zod.z.string(),
733
792
  RegexSchema
734
- ])).optional()
735
- });
736
- var Machine = zod.z.object({
737
- cpu: zod.z.string().default("1").optional(),
738
- memory: zod.z.string().default("500Mi").optional()
793
+ ])).optional(),
794
+ logLevel: zod.z.string().optional()
739
795
  });
740
796
  var WaitReason = zod.z.enum([
741
797
  "WAIT_FOR_DURATION",
@@ -757,6 +813,27 @@ var ProviderToPlatformMessages = {
757
813
  callback: zod.z.object({
758
814
  status: zod.z.literal("ok")
759
815
  })
816
+ },
817
+ WORKER_CRASHED: {
818
+ message: zod.z.object({
819
+ version: zod.z.literal("v1").default("v1"),
820
+ runId: zod.z.string(),
821
+ reason: zod.z.string().optional(),
822
+ exitCode: zod.z.number().optional(),
823
+ message: zod.z.string().optional(),
824
+ logs: zod.z.string().optional()
825
+ })
826
+ },
827
+ INDEXING_FAILED: {
828
+ message: zod.z.object({
829
+ version: zod.z.literal("v1").default("v1"),
830
+ deploymentId: zod.z.string(),
831
+ error: zod.z.object({
832
+ name: zod.z.string(),
833
+ message: zod.z.string(),
834
+ stack: zod.z.string().optional()
835
+ })
836
+ })
760
837
  }
761
838
  };
762
839
  var PlatformToProviderMessages = {
@@ -773,9 +850,14 @@ var PlatformToProviderMessages = {
773
850
  version: zod.z.literal("v1").default("v1"),
774
851
  imageTag: zod.z.string(),
775
852
  shortCode: zod.z.string(),
776
- envId: zod.z.string(),
777
853
  apiKey: zod.z.string(),
778
- apiUrl: zod.z.string()
854
+ apiUrl: zod.z.string(),
855
+ // identifiers
856
+ envId: zod.z.string(),
857
+ envType: EnvironmentType,
858
+ orgId: zod.z.string(),
859
+ projectId: zod.z.string(),
860
+ deploymentId: zod.z.string()
779
861
  }),
780
862
  callback: zod.z.discriminatedUnion("success", [
781
863
  zod.z.object({
@@ -791,25 +873,25 @@ var PlatformToProviderMessages = {
791
873
  })
792
874
  ])
793
875
  },
794
- INVOKE: {
795
- message: zod.z.object({
796
- version: zod.z.literal("v1").default("v1"),
797
- name: zod.z.string(),
798
- machine: Machine
799
- })
800
- },
876
+ // TODO: this should be a shared queue message instead
801
877
  RESTORE: {
802
878
  message: zod.z.object({
803
879
  version: zod.z.literal("v1").default("v1"),
804
- checkpointId: zod.z.string(),
805
- runId: zod.z.string(),
806
880
  type: zod.z.enum([
807
881
  "DOCKER",
808
882
  "KUBERNETES"
809
883
  ]),
810
884
  location: zod.z.string(),
811
885
  reason: zod.z.string().optional(),
812
- imageRef: zod.z.string()
886
+ imageRef: zod.z.string(),
887
+ machine: Machine,
888
+ // identifiers
889
+ checkpointId: zod.z.string(),
890
+ envId: zod.z.string(),
891
+ envType: EnvironmentType,
892
+ orgId: zod.z.string(),
893
+ projectId: zod.z.string(),
894
+ runId: zod.z.string()
813
895
  })
814
896
  },
815
897
  DELETE: {
@@ -1366,7 +1448,11 @@ var SpanMessagingEvent = zod.z.object({
1366
1448
  });
1367
1449
 
1368
1450
  // src/zodfetch.ts
1369
- async function zodfetch(schema, url, requestInit) {
1451
+ async function zodfetch(schema, url, requestInit, options) {
1452
+ return await _doZodFetch(schema, url, requestInit, options);
1453
+ }
1454
+ __name(zodfetch, "zodfetch");
1455
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1370
1456
  try {
1371
1457
  const response = await fetch(url, requestInit);
1372
1458
  if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
@@ -1375,7 +1461,7 @@ async function zodfetch(schema, url, requestInit) {
1375
1461
  error: `404: ${response.statusText}`
1376
1462
  };
1377
1463
  }
1378
- if (response.status >= 400 && response.status < 500) {
1464
+ if (response.status >= 400 && response.status < 500 && response.status !== 429) {
1379
1465
  const body = await response.json();
1380
1466
  if (!body.error) {
1381
1467
  return {
@@ -1388,6 +1474,27 @@ async function zodfetch(schema, url, requestInit) {
1388
1474
  error: body.error
1389
1475
  };
1390
1476
  }
1477
+ if (response.status === 429 || response.status >= 500) {
1478
+ if (!options?.retry) {
1479
+ return {
1480
+ ok: false,
1481
+ error: `Failed to fetch ${url}, got status code ${response.status}`
1482
+ };
1483
+ }
1484
+ const retry = {
1485
+ ...defaultRetryOptions,
1486
+ ...options.retry
1487
+ };
1488
+ if (attempt > retry.maxAttempts) {
1489
+ return {
1490
+ ok: false,
1491
+ error: `Failed to fetch ${url}, got status code ${response.status}`
1492
+ };
1493
+ }
1494
+ const delay = calculateNextRetryDelay(retry, attempt);
1495
+ await new Promise((resolve) => setTimeout(resolve, delay));
1496
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1497
+ }
1391
1498
  if (response.status !== 200) {
1392
1499
  return {
1393
1500
  ok: false,
@@ -1413,13 +1520,28 @@ async function zodfetch(schema, url, requestInit) {
1413
1520
  error: parsedResult.error.message
1414
1521
  };
1415
1522
  } catch (error) {
1523
+ if (options?.retry) {
1524
+ const retry = {
1525
+ ...defaultRetryOptions,
1526
+ ...options.retry
1527
+ };
1528
+ if (attempt > retry.maxAttempts) {
1529
+ return {
1530
+ ok: false,
1531
+ error: error instanceof Error ? error.message : JSON.stringify(error)
1532
+ };
1533
+ }
1534
+ const delay = calculateNextRetryDelay(retry, attempt);
1535
+ await new Promise((resolve) => setTimeout(resolve, delay));
1536
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1537
+ }
1416
1538
  return {
1417
1539
  ok: false,
1418
1540
  error: error instanceof Error ? error.message : JSON.stringify(error)
1419
1541
  };
1420
1542
  }
1421
1543
  }
1422
- __name(zodfetch, "zodfetch");
1544
+ __name(_doZodFetch, "_doZodFetch");
1423
1545
 
1424
1546
  // src/v3/utils/flattenAttributes.ts
1425
1547
  function flattenAttributes(obj, prefix) {
@@ -1705,6 +1827,15 @@ function getEnvVar(name) {
1705
1827
  __name(getEnvVar, "getEnvVar");
1706
1828
 
1707
1829
  // src/v3/apiClient/index.ts
1830
+ var zodFetchOptions = {
1831
+ retry: {
1832
+ maxAttempts: 5,
1833
+ minTimeoutInMs: 1e3,
1834
+ maxTimeoutInMs: 3e4,
1835
+ factor: 2,
1836
+ randomize: false
1837
+ }
1838
+ };
1708
1839
  var _getHeaders, getHeaders_fn;
1709
1840
  var _ApiClient = class _ApiClient {
1710
1841
  constructor(baseUrl, accessToken) {
@@ -1717,26 +1848,38 @@ var _ApiClient = class _ApiClient {
1717
1848
  method: "POST",
1718
1849
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1719
1850
  body: JSON.stringify(body)
1720
- });
1851
+ }, zodFetchOptions);
1721
1852
  }
1722
1853
  batchTriggerTask(taskId, body, options) {
1723
1854
  return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
1724
1855
  method: "POST",
1725
1856
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1726
1857
  body: JSON.stringify(body)
1727
- });
1858
+ }, zodFetchOptions);
1728
1859
  }
1729
1860
  createUploadPayloadUrl(filename) {
1730
1861
  return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1731
1862
  method: "PUT",
1732
1863
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1733
- });
1864
+ }, zodFetchOptions);
1734
1865
  }
1735
1866
  getPayloadUrl(filename) {
1736
1867
  return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1737
1868
  method: "GET",
1738
1869
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1739
- });
1870
+ }, zodFetchOptions);
1871
+ }
1872
+ replayRun(runId) {
1873
+ return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
1874
+ method: "POST",
1875
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1876
+ }, zodFetchOptions);
1877
+ }
1878
+ cancelRun(runId) {
1879
+ return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
1880
+ method: "POST",
1881
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1882
+ }, zodFetchOptions);
1740
1883
  }
1741
1884
  };
1742
1885
  _getHeaders = new WeakSet();
@@ -1786,6 +1929,15 @@ getStore_fn2 = /* @__PURE__ */ __name(function() {
1786
1929
  __name(_ApiClientManager, "ApiClientManager");
1787
1930
  var ApiClientManager = _ApiClientManager;
1788
1931
  var apiClientManager = new ApiClientManager();
1932
+ var _ZodSchemaParsedError = class _ZodSchemaParsedError extends Error {
1933
+ constructor(error, payload) {
1934
+ super(error.message);
1935
+ this.error = error;
1936
+ this.payload = payload;
1937
+ }
1938
+ };
1939
+ __name(_ZodSchemaParsedError, "ZodSchemaParsedError");
1940
+ var ZodSchemaParsedError = _ZodSchemaParsedError;
1789
1941
  var ZodMessageSchema = zod.z.object({
1790
1942
  version: zod.z.literal("v1").default("v1"),
1791
1943
  type: zod.z.string(),
@@ -1882,7 +2034,7 @@ var _ZodMessageSender = class _ZodMessageSender {
1882
2034
  }
1883
2035
  const parsedPayload = schema.safeParse(payload);
1884
2036
  if (!parsedPayload.success) {
1885
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2037
+ throw new ZodSchemaParsedError(parsedPayload.error, payload);
1886
2038
  }
1887
2039
  await __privateGet(this, _sender).call(this, {
1888
2040
  type,
@@ -2051,16 +2203,23 @@ var _ZodSocketConnection = class _ZodSocketConnection {
2051
2203
  __privateAdd(this, _sender2, void 0);
2052
2204
  __privateAdd(this, _handler, void 0);
2053
2205
  __privateAdd(this, _logger, void 0);
2054
- this.socket = socket_ioClient.io(`ws://${opts.host}:${opts.port}/${opts.namespace}`, {
2206
+ const uri = `${opts.secure ? "wss" : "ws"}://${opts.host}:${opts.port ?? (opts.secure ? "443" : "80")}/${opts.namespace}`;
2207
+ const logger2 = new SimpleStructuredLogger(opts.namespace, exports.LogLevel.info);
2208
+ logger2.log("new zod socket", {
2209
+ uri
2210
+ });
2211
+ this.socket = socket_ioClient.io(uri, {
2055
2212
  transports: [
2056
2213
  "websocket"
2057
2214
  ],
2058
2215
  auth: {
2059
2216
  token: opts.authToken
2060
2217
  },
2061
- extraHeaders: opts.extraHeaders
2218
+ extraHeaders: opts.extraHeaders,
2219
+ reconnectionDelay: 500,
2220
+ reconnectionDelayMax: 1e3
2062
2221
  });
2063
- __privateSet(this, _logger, new SimpleStructuredLogger(opts.namespace, exports.LogLevel.info, {
2222
+ __privateSet(this, _logger, logger2.child({
2064
2223
  socketId: this.socket.id
2065
2224
  }));
2066
2225
  __privateSet(this, _handler, new ZodSocketMessageHandler({
@@ -2379,7 +2538,7 @@ var _ZodIpcConnection = class _ZodIpcConnection {
2379
2538
  }
2380
2539
  const parsedPayload = schema.safeParse(payload);
2381
2540
  if (!parsedPayload.success) {
2382
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2541
+ throw new ZodSchemaParsedError(parsedPayload.error, payload);
2383
2542
  }
2384
2543
  await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2385
2544
  type: "EVENT",
@@ -2568,6 +2727,41 @@ function correctStackTraceLine(line, projectDir) {
2568
2727
  return line;
2569
2728
  }
2570
2729
  __name(correctStackTraceLine, "correctStackTraceLine");
2730
+ function groupTaskMetadataIssuesByTask(tasks, issues) {
2731
+ return issues.reduce((acc, issue) => {
2732
+ if (issue.path.length === 0) {
2733
+ return acc;
2734
+ }
2735
+ const taskIndex = issue.path[1];
2736
+ if (typeof taskIndex !== "number") {
2737
+ return acc;
2738
+ }
2739
+ const task = tasks[taskIndex];
2740
+ if (!task) {
2741
+ return acc;
2742
+ }
2743
+ const restOfPath = issue.path.slice(2);
2744
+ const taskId = task.id;
2745
+ const taskName = task.exportName;
2746
+ const filePath = task.filePath;
2747
+ const key = taskIndex;
2748
+ const existing = acc[key] ?? {
2749
+ id: taskId,
2750
+ exportName: taskName,
2751
+ filePath,
2752
+ issues: []
2753
+ };
2754
+ existing.issues.push({
2755
+ message: issue.message,
2756
+ path: restOfPath.length === 0 ? void 0 : restOfPath.join(".")
2757
+ });
2758
+ return {
2759
+ ...acc,
2760
+ [key]: existing
2761
+ };
2762
+ }, {});
2763
+ }
2764
+ __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
2571
2765
 
2572
2766
  // src/v3/utils/platform.ts
2573
2767
  var _globalThis = typeof globalThis === "object" ? globalThis : global;
@@ -2717,27 +2911,58 @@ function iconStringForSeverity(severityNumber) {
2717
2911
  }
2718
2912
  }
2719
2913
  __name(iconStringForSeverity, "iconStringForSeverity");
2720
- function preciseDateOriginNow() {
2721
- return {
2722
- hrtime: process.hrtime(),
2723
- timestamp: new preciseDate.PreciseDate()
2724
- };
2725
- }
2726
- __name(preciseDateOriginNow, "preciseDateOriginNow");
2727
- function calculatePreciseDateHrTime(origin) {
2728
- const elapsedHrTime = process.hrtime(origin.hrtime);
2729
- const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
2730
- const preciseDate$1 = new preciseDate.PreciseDate(origin.timestamp.getFullTime() + elapsedNanoseconds);
2731
- const dateStruct = preciseDate$1.toStruct();
2732
- return [
2733
- dateStruct.seconds,
2734
- dateStruct.nanos
2735
- ];
2736
- }
2737
- __name(calculatePreciseDateHrTime, "calculatePreciseDateHrTime");
2914
+ var _SimpleClock = class _SimpleClock {
2915
+ preciseNow() {
2916
+ const now = new preciseDate.PreciseDate();
2917
+ const nowStruct = now.toStruct();
2918
+ return [
2919
+ nowStruct.seconds,
2920
+ nowStruct.nanos
2921
+ ];
2922
+ }
2923
+ reset() {
2924
+ }
2925
+ };
2926
+ __name(_SimpleClock, "SimpleClock");
2927
+ var SimpleClock = _SimpleClock;
2928
+
2929
+ // src/v3/clock/index.ts
2930
+ var API_NAME2 = "clock";
2931
+ var SIMPLE_CLOCK = new SimpleClock();
2932
+ var _getClock, getClock_fn;
2933
+ var _ClockAPI = class _ClockAPI {
2934
+ constructor() {
2935
+ __privateAdd(this, _getClock);
2936
+ }
2937
+ static getInstance() {
2938
+ if (!this._instance) {
2939
+ this._instance = new _ClockAPI();
2940
+ }
2941
+ return this._instance;
2942
+ }
2943
+ setGlobalClock(clock2) {
2944
+ return registerGlobal(API_NAME2, clock2);
2945
+ }
2946
+ preciseNow() {
2947
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2948
+ }
2949
+ reset() {
2950
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2951
+ }
2952
+ };
2953
+ _getClock = new WeakSet();
2954
+ getClock_fn = /* @__PURE__ */ __name(function() {
2955
+ return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2956
+ }, "#getClock");
2957
+ __name(_ClockAPI, "ClockAPI");
2958
+ var ClockAPI = _ClockAPI;
2959
+
2960
+ // src/v3/clock-api.ts
2961
+ var clock = ClockAPI.getInstance();
2738
2962
 
2739
2963
  // src/v3/logger/taskLogger.ts
2740
2964
  var logLevels = [
2965
+ "none",
2741
2966
  "error",
2742
2967
  "warn",
2743
2968
  "log",
@@ -2753,37 +2978,36 @@ var _OtelTaskLogger = class _OtelTaskLogger {
2753
2978
  this._level = logLevels.indexOf(_config.level);
2754
2979
  }
2755
2980
  debug(message, properties) {
2756
- if (this._level < 4)
2981
+ if (this._level < 5)
2757
2982
  return;
2758
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "debug", apiLogs.SeverityNumber.DEBUG, properties);
2983
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", apiLogs.SeverityNumber.DEBUG, properties);
2759
2984
  }
2760
2985
  log(message, properties) {
2761
- if (this._level < 2)
2986
+ if (this._level < 3)
2762
2987
  return;
2763
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "log", apiLogs.SeverityNumber.INFO, properties);
2988
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", apiLogs.SeverityNumber.INFO, properties);
2764
2989
  }
2765
2990
  info(message, properties) {
2766
- if (this._level < 3)
2991
+ if (this._level < 4)
2767
2992
  return;
2768
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "info", apiLogs.SeverityNumber.INFO, properties);
2993
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", apiLogs.SeverityNumber.INFO, properties);
2769
2994
  }
2770
2995
  warn(message, properties) {
2771
- if (this._level < 1)
2996
+ if (this._level < 2)
2772
2997
  return;
2773
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "warn", apiLogs.SeverityNumber.WARN, properties);
2998
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", apiLogs.SeverityNumber.WARN, properties);
2774
2999
  }
2775
3000
  error(message, properties) {
2776
- if (this._level < 0)
3001
+ if (this._level < 1)
2777
3002
  return;
2778
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "error", apiLogs.SeverityNumber.ERROR, properties);
3003
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", apiLogs.SeverityNumber.ERROR, properties);
2779
3004
  }
2780
3005
  trace(name, fn, options) {
2781
3006
  return this._config.tracer.startActiveSpan(name, fn, options);
2782
3007
  }
2783
3008
  };
2784
3009
  _emitLog = new WeakSet();
2785
- emitLog_fn = /* @__PURE__ */ __name(function(message, severityText, severityNumber, properties) {
2786
- const timestamp = __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this);
3010
+ emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
2787
3011
  let attributes = {
2788
3012
  ...flattenAttributes(properties)
2789
3013
  };
@@ -2801,7 +3025,7 @@ emitLog_fn = /* @__PURE__ */ __name(function(message, severityText, severityNumb
2801
3025
  }, "#emitLog");
2802
3026
  _getTimestampInHrTime = new WeakSet();
2803
3027
  getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
2804
- return calculatePreciseDateHrTime(this._config.preciseDateOrigin);
3028
+ return clock.preciseNow();
2805
3029
  }, "#getTimestampInHrTime");
2806
3030
  __name(_OtelTaskLogger, "OtelTaskLogger");
2807
3031
  var OtelTaskLogger = _OtelTaskLogger;
@@ -2824,7 +3048,7 @@ __name(_NoopTaskLogger, "NoopTaskLogger");
2824
3048
  var NoopTaskLogger = _NoopTaskLogger;
2825
3049
 
2826
3050
  // src/v3/logger/index.ts
2827
- var API_NAME2 = "logger";
3051
+ var API_NAME3 = "logger";
2828
3052
  var NOOP_TASK_LOGGER = new NoopTaskLogger();
2829
3053
  var _getTaskLogger, getTaskLogger_fn;
2830
3054
  var _LoggerAPI = class _LoggerAPI {
@@ -2838,10 +3062,10 @@ var _LoggerAPI = class _LoggerAPI {
2838
3062
  return this._instance;
2839
3063
  }
2840
3064
  disable() {
2841
- unregisterGlobal(API_NAME2);
3065
+ unregisterGlobal(API_NAME3);
2842
3066
  }
2843
3067
  setGlobalTaskLogger(taskLogger) {
2844
- return registerGlobal(API_NAME2, taskLogger);
3068
+ return registerGlobal(API_NAME3, taskLogger);
2845
3069
  }
2846
3070
  debug(message, metadata) {
2847
3071
  __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).debug(message, metadata);
@@ -2864,7 +3088,7 @@ var _LoggerAPI = class _LoggerAPI {
2864
3088
  };
2865
3089
  _getTaskLogger = new WeakSet();
2866
3090
  getTaskLogger_fn = /* @__PURE__ */ __name(function() {
2867
- return getGlobal(API_NAME2) ?? NOOP_TASK_LOGGER;
3091
+ return getGlobal(API_NAME3) ?? NOOP_TASK_LOGGER;
2868
3092
  }, "#getTaskLogger");
2869
3093
  __name(_LoggerAPI, "LoggerAPI");
2870
3094
  var LoggerAPI = _LoggerAPI;
@@ -3079,11 +3303,10 @@ var _DevRuntimeManager = class _DevRuntimeManager {
3079
3303
  };
3080
3304
  __name(_DevRuntimeManager, "DevRuntimeManager");
3081
3305
  var DevRuntimeManager = _DevRuntimeManager;
3082
-
3083
- // src/v3/runtime/prodRuntimeManager.ts
3084
3306
  var _ProdRuntimeManager = class _ProdRuntimeManager {
3085
- constructor(ipc) {
3307
+ constructor(ipc, options = {}) {
3086
3308
  this.ipc = ipc;
3309
+ this.options = options;
3087
3310
  this._taskWaits = /* @__PURE__ */ new Map();
3088
3311
  this._batchWaits = /* @__PURE__ */ new Map();
3089
3312
  this._tasks = /* @__PURE__ */ new Map();
@@ -3099,12 +3322,9 @@ var _ProdRuntimeManager = class _ProdRuntimeManager {
3099
3322
  return this._tasks.get(id);
3100
3323
  }
3101
3324
  async waitForDuration(ms) {
3102
- let timeout;
3103
3325
  const now = Date.now();
3104
- const resolveAfterDuration = new Promise((resolve) => {
3105
- timeout = setTimeout(resolve, ms);
3106
- });
3107
- if (ms < 1e4) {
3326
+ const resolveAfterDuration = promises.setTimeout(ms, "duration");
3327
+ if (ms <= this.waitThresholdInMs) {
3108
3328
  await resolveAfterDuration;
3109
3329
  return;
3110
3330
  }
@@ -3128,13 +3348,13 @@ var _ProdRuntimeManager = class _ProdRuntimeManager {
3128
3348
  resolveAfterDuration
3129
3349
  ]);
3130
3350
  this.ipc.send("CANCEL_CHECKPOINT", {});
3131
- clearTimeout(timeout);
3132
3351
  }
3133
3352
  resumeAfterRestore() {
3134
3353
  if (!this._waitForRestore) {
3135
3354
  return;
3136
3355
  }
3137
- this._waitForRestore.resolve();
3356
+ clock.reset();
3357
+ this._waitForRestore.resolve("restore");
3138
3358
  this._waitForRestore = void 0;
3139
3359
  }
3140
3360
  async waitUntil(date) {
@@ -3189,9 +3409,49 @@ var _ProdRuntimeManager = class _ProdRuntimeManager {
3189
3409
  }
3190
3410
  this._taskWaits.delete(execution.run.id);
3191
3411
  }
3412
+ get waitThresholdInMs() {
3413
+ return this.options.waitThresholdInMs ?? 3e4;
3414
+ }
3192
3415
  };
3193
3416
  __name(_ProdRuntimeManager, "ProdRuntimeManager");
3194
3417
  var ProdRuntimeManager = _ProdRuntimeManager;
3418
+ var _originClockTime, originClockTime_get, _originPreciseDate, originPreciseDate_get;
3419
+ var _PreciseWallClock = class _PreciseWallClock {
3420
+ constructor(options = {}) {
3421
+ __privateAdd(this, _originClockTime);
3422
+ __privateAdd(this, _originPreciseDate);
3423
+ this._origin = {
3424
+ clockTime: options.origin ?? process.hrtime(),
3425
+ preciseDate: options.now ?? new preciseDate.PreciseDate()
3426
+ };
3427
+ }
3428
+ preciseNow() {
3429
+ const elapsedHrTime = process.hrtime(__privateGet(this, _originClockTime, originClockTime_get));
3430
+ const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
3431
+ const preciseDate$1 = new preciseDate.PreciseDate(__privateGet(this, _originPreciseDate, originPreciseDate_get).getFullTime() + elapsedNanoseconds);
3432
+ const dateStruct = preciseDate$1.toStruct();
3433
+ return [
3434
+ dateStruct.seconds,
3435
+ dateStruct.nanos
3436
+ ];
3437
+ }
3438
+ reset() {
3439
+ this._origin = {
3440
+ clockTime: process.hrtime(),
3441
+ preciseDate: new preciseDate.PreciseDate()
3442
+ };
3443
+ }
3444
+ };
3445
+ _originClockTime = new WeakSet();
3446
+ originClockTime_get = /* @__PURE__ */ __name(function() {
3447
+ return this._origin.clockTime;
3448
+ }, "#originClockTime");
3449
+ _originPreciseDate = new WeakSet();
3450
+ originPreciseDate_get = /* @__PURE__ */ __name(function() {
3451
+ return this._origin.preciseDate;
3452
+ }, "#originPreciseDate");
3453
+ __name(_PreciseWallClock, "PreciseWallClock");
3454
+ var PreciseWallClock = _PreciseWallClock;
3195
3455
  var _TriggerTracer = class _TriggerTracer {
3196
3456
  constructor(_config) {
3197
3457
  this._config = _config;
@@ -3220,7 +3480,8 @@ var _TriggerTracer = class _TriggerTracer {
3220
3480
  const attributes = options?.attributes ?? {};
3221
3481
  return this.tracer.startActiveSpan(name, {
3222
3482
  ...options,
3223
- attributes
3483
+ attributes,
3484
+ startTime: clock.preciseNow()
3224
3485
  }, parentContext, async (span) => {
3225
3486
  this.tracer.startSpan(name, {
3226
3487
  ...options,
@@ -3241,7 +3502,7 @@ var _TriggerTracer = class _TriggerTracer {
3241
3502
  });
3242
3503
  throw e;
3243
3504
  } finally {
3244
- span.end();
3505
+ span.end(clock.preciseNow());
3245
3506
  }
3246
3507
  });
3247
3508
  }
@@ -3264,12 +3525,11 @@ __name(_TriggerTracer, "TriggerTracer");
3264
3525
  var TriggerTracer = _TriggerTracer;
3265
3526
  var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
3266
3527
  var _ConsoleInterceptor = class _ConsoleInterceptor {
3267
- constructor(logger2, preciseDateOrigin) {
3528
+ constructor(logger2) {
3268
3529
  __privateAdd(this, _handleLog);
3269
3530
  __privateAdd(this, _getTimestampInHrTime2);
3270
3531
  __privateAdd(this, _getAttributes);
3271
3532
  this.logger = logger2;
3272
- this.preciseDateOrigin = preciseDateOrigin;
3273
3533
  }
3274
3534
  // Intercept the console and send logs to the OpenTelemetry logger
3275
3535
  // during the execution of the callback
@@ -3294,22 +3554,21 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3294
3554
  }
3295
3555
  }
3296
3556
  log(...args) {
3297
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, "Log", ...args);
3557
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
3298
3558
  }
3299
3559
  info(...args) {
3300
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, "Info", ...args);
3560
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
3301
3561
  }
3302
3562
  warn(...args) {
3303
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.WARN, "Warn", ...args);
3563
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
3304
3564
  }
3305
3565
  error(...args) {
3306
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.ERROR, "Error", ...args);
3566
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
3307
3567
  }
3308
3568
  };
3309
3569
  _handleLog = new WeakSet();
3310
- handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, severityText, ...args) {
3570
+ handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
3311
3571
  const body = util__default.default.format(...args);
3312
- const timestamp = __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this);
3313
3572
  const parsed = tryParseJSON(body);
3314
3573
  if (parsed.ok) {
3315
3574
  this.logger.emit({
@@ -3334,7 +3593,7 @@ handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, severityText, ...
3334
3593
  }, "#handleLog");
3335
3594
  _getTimestampInHrTime2 = new WeakSet();
3336
3595
  getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
3337
- return calculatePreciseDateHrTime(this.preciseDateOrigin);
3596
+ return clock.preciseNow();
3338
3597
  }, "#getTimestampInHrTime");
3339
3598
  _getAttributes = new WeakSet();
3340
3599
  getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
@@ -3720,7 +3979,12 @@ var _TracingSDK = class _TracingSDK {
3720
3979
  url: `${config.url}/v1/traces`,
3721
3980
  timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
3722
3981
  });
3723
- traceProvider.addSpanProcessor(new TaskContextSpanProcessor(new sdkTraceNode.SimpleSpanProcessor(spanExporter)));
3982
+ traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkTraceNode.BatchSpanProcessor(spanExporter, {
3983
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
3984
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
3985
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
3986
+ maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
3987
+ }) : new sdkTraceNode.SimpleSpanProcessor(spanExporter)));
3724
3988
  traceProvider.register();
3725
3989
  instrumentation.registerInstrumentations({
3726
3990
  instrumentations: config.instrumentations ?? [],
@@ -3736,7 +4000,12 @@ var _TracingSDK = class _TracingSDK {
3736
4000
  attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
3737
4001
  }
3738
4002
  });
3739
- loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(new sdkLogs.SimpleLogRecordProcessor(logExporter)));
4003
+ loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkLogs.BatchLogRecordProcessor(logExporter, {
4004
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
4005
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
4006
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
4007
+ maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
4008
+ }) : new sdkLogs.SimpleLogRecordProcessor(logExporter)));
3740
4009
  this._logProvider = loggerProvider;
3741
4010
  this._spanExporter = spanExporter;
3742
4011
  this._traceProvider = traceProvider;
@@ -3745,11 +4014,11 @@ var _TracingSDK = class _TracingSDK {
3745
4014
  this.getTracer = traceProvider.getTracer.bind(traceProvider);
3746
4015
  }
3747
4016
  async flush() {
3748
- await this._spanExporter.forceFlush?.();
4017
+ await this._traceProvider.forceFlush();
3749
4018
  await this._logProvider.forceFlush();
3750
4019
  }
3751
4020
  async shutdown() {
3752
- await this._spanExporter.shutdown();
4021
+ await this._traceProvider.shutdown();
3753
4022
  await this._logProvider.shutdown();
3754
4023
  }
3755
4024
  };
@@ -3800,7 +4069,9 @@ function recordSpanException(span, error) {
3800
4069
  });
3801
4070
  }
3802
4071
  __name(recordSpanException, "recordSpanException");
3803
- function parsePacket(value) {
4072
+
4073
+ // src/v3/utils/ioSerialization.ts
4074
+ async function parsePacket(value) {
3804
4075
  if (!value.data) {
3805
4076
  return void 0;
3806
4077
  }
@@ -3808,7 +4079,8 @@ function parsePacket(value) {
3808
4079
  case "application/json":
3809
4080
  return JSON.parse(value.data);
3810
4081
  case "application/super+json":
3811
- return superjson.parse(value.data);
4082
+ const { parse } = await loadSuperJSON();
4083
+ return parse(value.data);
3812
4084
  case "text/plain":
3813
4085
  return value.data;
3814
4086
  case "application/store":
@@ -3818,7 +4090,7 @@ function parsePacket(value) {
3818
4090
  }
3819
4091
  }
3820
4092
  __name(parsePacket, "parsePacket");
3821
- function stringifyIO(value) {
4093
+ async function stringifyIO(value) {
3822
4094
  if (value === void 0) {
3823
4095
  return {
3824
4096
  dataType: "application/json"
@@ -3830,10 +4102,18 @@ function stringifyIO(value) {
3830
4102
  dataType: "text/plain"
3831
4103
  };
3832
4104
  }
3833
- return {
3834
- data: superjson.stringify(value),
3835
- dataType: "application/super+json"
3836
- };
4105
+ try {
4106
+ const { stringify } = await loadSuperJSON();
4107
+ const data = stringify(value);
4108
+ return {
4109
+ data,
4110
+ dataType: "application/super+json"
4111
+ };
4112
+ } catch {
4113
+ return {
4114
+ dataType: "application/json"
4115
+ };
4116
+ }
3837
4117
  }
3838
4118
  __name(stringifyIO, "stringifyIO");
3839
4119
  async function conditionallyExportPacket(packet, pathPrefix, tracer) {
@@ -3935,9 +4215,9 @@ async function importPacket(packet, span) {
3935
4215
  return packet;
3936
4216
  }
3937
4217
  __name(importPacket, "importPacket");
3938
- function createPacketAttributes(packet, dataKey, dataTypeKey) {
4218
+ async function createPacketAttributes(packet, dataKey, dataTypeKey) {
3939
4219
  if (!packet.data) {
3940
- return {};
4220
+ return;
3941
4221
  }
3942
4222
  switch (packet.dataType) {
3943
4223
  case "application/json":
@@ -3946,12 +4226,20 @@ function createPacketAttributes(packet, dataKey, dataTypeKey) {
3946
4226
  [dataTypeKey]: packet.dataType
3947
4227
  };
3948
4228
  case "application/super+json":
3949
- const parsed = superjson.parse(packet.data);
3950
- const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
3951
- return {
3952
- ...flattenAttributes(jsonified, dataKey),
3953
- [dataTypeKey]: "application/json"
3954
- };
4229
+ const { parse } = await loadSuperJSON();
4230
+ if (typeof packet.data === "undefined" || packet.data === null) {
4231
+ return;
4232
+ }
4233
+ try {
4234
+ const parsed = parse(packet.data);
4235
+ const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
4236
+ return {
4237
+ ...flattenAttributes(jsonified, dataKey),
4238
+ [dataTypeKey]: "application/json"
4239
+ };
4240
+ } catch {
4241
+ return;
4242
+ }
3955
4243
  case "application/store":
3956
4244
  return {
3957
4245
  [dataKey]: packet.data,
@@ -3959,15 +4247,15 @@ function createPacketAttributes(packet, dataKey, dataTypeKey) {
3959
4247
  };
3960
4248
  case "text/plain":
3961
4249
  return {
3962
- [SemanticInternalAttributes.OUTPUT]: packet.data,
3963
- [SemanticInternalAttributes.OUTPUT_TYPE]: packet.dataType
4250
+ [dataKey]: packet.data,
4251
+ [dataTypeKey]: packet.dataType
3964
4252
  };
3965
4253
  default:
3966
- return {};
4254
+ return;
3967
4255
  }
3968
4256
  }
3969
4257
  __name(createPacketAttributes, "createPacketAttributes");
3970
- function createPackageAttributesAsJson(data, dataType) {
4258
+ async function createPacketAttributesAsJson(data, dataType) {
3971
4259
  if (typeof data === "string" || typeof data === "number" || typeof data === "boolean" || data === null || data === void 0) {
3972
4260
  return data;
3973
4261
  }
@@ -3975,8 +4263,9 @@ function createPackageAttributesAsJson(data, dataType) {
3975
4263
  case "application/json":
3976
4264
  return imposeAttributeLimits(flattenAttributes(data, void 0));
3977
4265
  case "application/super+json":
3978
- const deserialized = superjson.deserialize(data);
3979
- const jsonify = JSON.parse(JSON.stringify(deserialized, safeReplacer));
4266
+ const { deserialize } = await loadSuperJSON();
4267
+ const deserialized = deserialize(data);
4268
+ const jsonify = safeJsonParse(JSON.stringify(deserialized, safeReplacer));
3980
4269
  return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
3981
4270
  case "application/store":
3982
4271
  return data;
@@ -3984,13 +4273,14 @@ function createPackageAttributesAsJson(data, dataType) {
3984
4273
  return {};
3985
4274
  }
3986
4275
  }
3987
- __name(createPackageAttributesAsJson, "createPackageAttributesAsJson");
3988
- function prettyPrintPacket(rawData, dataType) {
4276
+ __name(createPacketAttributesAsJson, "createPacketAttributesAsJson");
4277
+ async function prettyPrintPacket(rawData, dataType) {
3989
4278
  if (rawData === void 0) {
3990
4279
  return "";
3991
4280
  }
3992
4281
  if (dataType === "application/super+json") {
3993
- return prettyPrintPacket(superjson.deserialize(rawData), "application/json");
4282
+ const { deserialize } = await loadSuperJSON();
4283
+ return await prettyPrintPacket(deserialize(rawData), "application/json");
3994
4284
  }
3995
4285
  if (dataType === "application/json") {
3996
4286
  return JSON.stringify(rawData, safeReplacer, 2);
@@ -4034,6 +4324,18 @@ function getPacketExtension(outputType) {
4034
4324
  }
4035
4325
  }
4036
4326
  __name(getPacketExtension, "getPacketExtension");
4327
+ async function loadSuperJSON() {
4328
+ return await import('superjson');
4329
+ }
4330
+ __name(loadSuperJSON, "loadSuperJSON");
4331
+ function safeJsonParse(value) {
4332
+ try {
4333
+ return JSON.parse(value);
4334
+ } catch {
4335
+ return;
4336
+ }
4337
+ }
4338
+ __name(safeJsonParse, "safeJsonParse");
4037
4339
 
4038
4340
  // src/v3/workers/taskExecutor.ts
4039
4341
  var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
@@ -4073,13 +4375,16 @@ var _TaskExecutor = class _TaskExecutor {
4073
4375
  let initOutput;
4074
4376
  try {
4075
4377
  const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
4076
- parsedPayload = parsePacket(payloadPacket);
4378
+ parsedPayload = await parsePacket(payloadPacket);
4077
4379
  initOutput = await __privateMethod(this, _callTaskInit, callTaskInit_fn).call(this, parsedPayload, ctx);
4078
4380
  const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
4079
4381
  try {
4080
- const stringifiedOutput = stringifyIO(output);
4382
+ const stringifiedOutput = await stringifyIO(output);
4081
4383
  const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
4082
- span.setAttributes(createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE));
4384
+ const attributes = await createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE);
4385
+ if (attributes) {
4386
+ span.setAttributes(attributes);
4387
+ }
4083
4388
  return {
4084
4389
  ok: true,
4085
4390
  id: execution.attempt.id,
@@ -4330,6 +4635,7 @@ exports.BackgroundWorkerServerMessages = BackgroundWorkerServerMessages;
4330
4635
  exports.BatchTaskRunExecutionResult = BatchTaskRunExecutionResult;
4331
4636
  exports.BatchTriggerTaskRequestBody = BatchTriggerTaskRequestBody;
4332
4637
  exports.BatchTriggerTaskResponse = BatchTriggerTaskResponse;
4638
+ exports.CanceledRunResponse = CanceledRunResponse;
4333
4639
  exports.CancellationSpanEvent = CancellationSpanEvent;
4334
4640
  exports.ClientToSharedQueueMessages = ClientToSharedQueueMessages;
4335
4641
  exports.Config = Config;
@@ -4340,7 +4646,10 @@ exports.CreateAuthorizationCodeResponseSchema = CreateAuthorizationCodeResponseS
4340
4646
  exports.CreateBackgroundWorkerRequestBody = CreateBackgroundWorkerRequestBody;
4341
4647
  exports.CreateBackgroundWorkerResponse = CreateBackgroundWorkerResponse;
4342
4648
  exports.CreateUploadPayloadUrlResponseBody = CreateUploadPayloadUrlResponseBody;
4649
+ exports.DeploymentErrorData = DeploymentErrorData;
4343
4650
  exports.DevRuntimeManager = DevRuntimeManager;
4651
+ exports.DurableClock = PreciseWallClock;
4652
+ exports.EnvironmentType = EnvironmentType;
4344
4653
  exports.EventFilter = EventFilter;
4345
4654
  exports.ExceptionEventProperties = ExceptionEventProperties;
4346
4655
  exports.ExceptionSpanEvent = ExceptionSpanEvent;
@@ -4364,6 +4673,8 @@ exports.ImageDetailsMetadata = ImageDetailsMetadata;
4364
4673
  exports.InitializeDeploymentRequestBody = InitializeDeploymentRequestBody;
4365
4674
  exports.InitializeDeploymentResponseBody = InitializeDeploymentResponseBody;
4366
4675
  exports.Machine = Machine;
4676
+ exports.MachineCpu = MachineCpu;
4677
+ exports.MachineMemory = MachineMemory;
4367
4678
  exports.OFFLOAD_IO_PACKET_LENGTH_LIMIT = OFFLOAD_IO_PACKET_LENGTH_LIMIT;
4368
4679
  exports.OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT;
4369
4680
  exports.OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT;
@@ -4378,6 +4689,8 @@ exports.OtherSpanEvent = OtherSpanEvent;
4378
4689
  exports.PRIMARY_VARIANT = PRIMARY_VARIANT;
4379
4690
  exports.PlatformToCoordinatorMessages = PlatformToCoordinatorMessages;
4380
4691
  exports.PlatformToProviderMessages = PlatformToProviderMessages;
4692
+ exports.PostStartCauses = PostStartCauses;
4693
+ exports.PreStopCauses = PreStopCauses;
4381
4694
  exports.ProdChildToWorkerMessages = ProdChildToWorkerMessages;
4382
4695
  exports.ProdRuntimeManager = ProdRuntimeManager;
4383
4696
  exports.ProdTaskRunExecution = ProdTaskRunExecution;
@@ -4388,6 +4701,7 @@ exports.ProdWorkerToCoordinatorMessages = ProdWorkerToCoordinatorMessages;
4388
4701
  exports.ProviderToPlatformMessages = ProviderToPlatformMessages;
4389
4702
  exports.QueueOptions = QueueOptions;
4390
4703
  exports.RateLimitOptions = RateLimitOptions;
4704
+ exports.ReplayRunResponse = ReplayRunResponse;
4391
4705
  exports.RetryOptions = RetryOptions;
4392
4706
  exports.SemanticInternalAttributes = SemanticInternalAttributes;
4393
4707
  exports.SharedQueueToClientMessages = SharedQueueToClientMessages;
@@ -4402,6 +4716,7 @@ exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
4402
4716
  exports.TaskEventStyle = TaskEventStyle;
4403
4717
  exports.TaskExecutor = TaskExecutor;
4404
4718
  exports.TaskMetadata = TaskMetadata;
4719
+ exports.TaskMetadataFailedToParseData = TaskMetadataFailedToParseData;
4405
4720
  exports.TaskMetadataWithFilePath = TaskMetadataWithFilePath;
4406
4721
  exports.TaskResource = TaskResource;
4407
4722
  exports.TaskRun = TaskRun;
@@ -4437,22 +4752,23 @@ exports.ZodMessageHandler = ZodMessageHandler;
4437
4752
  exports.ZodMessageSchema = ZodMessageSchema;
4438
4753
  exports.ZodMessageSender = ZodMessageSender;
4439
4754
  exports.ZodNamespace = ZodNamespace;
4755
+ exports.ZodSchemaParsedError = ZodSchemaParsedError;
4440
4756
  exports.ZodSocketConnection = ZodSocketConnection;
4441
4757
  exports.ZodSocketMessageHandler = ZodSocketMessageHandler;
4442
4758
  exports.ZodSocketMessageSender = ZodSocketMessageSender;
4443
4759
  exports.accessoryAttributes = accessoryAttributes;
4444
4760
  exports.apiClientManager = apiClientManager;
4445
4761
  exports.calculateNextRetryDelay = calculateNextRetryDelay;
4446
- exports.calculatePreciseDateHrTime = calculatePreciseDateHrTime;
4447
4762
  exports.calculateResetAt = calculateResetAt2;
4448
4763
  exports.childToWorkerMessages = childToWorkerMessages;
4449
4764
  exports.clientWebsocketMessages = clientWebsocketMessages;
4765
+ exports.clock = clock;
4450
4766
  exports.conditionallyExportPacket = conditionallyExportPacket;
4451
4767
  exports.conditionallyImportPacket = conditionallyImportPacket;
4452
4768
  exports.correctErrorStackTrace = correctErrorStackTrace;
4453
4769
  exports.createErrorTaskError = createErrorTaskError;
4454
- exports.createPackageAttributesAsJson = createPackageAttributesAsJson;
4455
4770
  exports.createPacketAttributes = createPacketAttributes;
4771
+ exports.createPacketAttributesAsJson = createPacketAttributesAsJson;
4456
4772
  exports.defaultFetchRetryOptions = defaultFetchRetryOptions;
4457
4773
  exports.defaultRetryOptions = defaultRetryOptions;
4458
4774
  exports.detectDependencyVersion = detectDependencyVersion;
@@ -4463,10 +4779,12 @@ exports.formatDurationInDays = formatDurationInDays;
4463
4779
  exports.formatDurationMilliseconds = formatDurationMilliseconds;
4464
4780
  exports.formatDurationNanoseconds = formatDurationNanoseconds;
4465
4781
  exports.getEnvVar = getEnvVar;
4782
+ exports.groupTaskMetadataIssuesByTask = groupTaskMetadataIssuesByTask;
4466
4783
  exports.iconStringForSeverity = iconStringForSeverity;
4467
4784
  exports.imposeAttributeLimits = imposeAttributeLimits;
4468
4785
  exports.isCancellationSpanEvent = isCancellationSpanEvent;
4469
4786
  exports.isExceptionSpanEvent = isExceptionSpanEvent;
4787
+ exports.logLevels = logLevels;
4470
4788
  exports.logger = logger;
4471
4789
  exports.millisecondsToNanoseconds = millisecondsToNanoseconds;
4472
4790
  exports.nanosecondsToMilliseconds = nanosecondsToMilliseconds;
@@ -4476,7 +4794,6 @@ exports.parseBatchTriggerTaskRequestBody = parseBatchTriggerTaskRequestBody;
4476
4794
  exports.parseError = parseError;
4477
4795
  exports.parsePacket = parsePacket;
4478
4796
  exports.parseTriggerTaskRequestBody = parseTriggerTaskRequestBody;
4479
- exports.preciseDateOriginNow = preciseDateOriginNow;
4480
4797
  exports.prettyPrintPacket = prettyPrintPacket;
4481
4798
  exports.primitiveValueOrflattenedAttributes = primitiveValueOrflattenedAttributes;
4482
4799
  exports.recordSpanException = recordSpanException;