@trigger.dev/core 3.0.0-beta.12 → 3.0.0-beta.13

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.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { SpanStatusCode, trace, propagation, context, DiagLogLevel, diag, DiagConsoleLogger, SpanKind } from '@opentelemetry/api';
3
+ import { fromZodError } from 'zod-validation-error';
3
4
  import { AsyncLocalStorage } from 'node:async_hooks';
4
5
  import { io } from 'socket.io-client';
5
6
  import { randomUUID } from 'crypto';
@@ -83,6 +84,7 @@ var TaskRunStringError = z.object({
83
84
  });
84
85
  var TaskRunErrorCodes = {
85
86
  COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
87
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
86
88
  CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
87
89
  TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
88
90
  TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
@@ -96,6 +98,7 @@ var TaskRunInternalError = z.object({
96
98
  type: z.literal("INTERNAL_ERROR"),
97
99
  code: z.enum([
98
100
  "COULD_NOT_FIND_EXECUTOR",
101
+ "COULD_NOT_FIND_TASK",
99
102
  "CONFIGURED_INCORRECTLY",
100
103
  "TASK_ALREADY_RUNNING",
101
104
  "TASK_EXECUTION_FAILED",
@@ -440,15 +443,17 @@ var QueueOptions = z.object({
440
443
  });
441
444
  var TaskMetadata = z.object({
442
445
  id: z.string(),
443
- exportName: z.string(),
444
446
  packageVersion: z.string(),
445
447
  queue: QueueOptions.optional(),
446
448
  retry: RetryOptions.optional(),
447
- machine: Machine.partial().optional()
449
+ machine: Machine.partial().optional(),
450
+ triggerSource: z.string().optional()
448
451
  });
449
- var TaskMetadataWithFilePath = TaskMetadata.extend({
450
- filePath: z.string()
452
+ var TaskFileMetadata = z.object({
453
+ filePath: z.string(),
454
+ exportName: z.string()
451
455
  });
456
+ var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
452
457
  var UncaughtExceptionMessage = z.object({
453
458
  version: z.literal("v1").default("v1"),
454
459
  error: z.object({
@@ -600,7 +605,8 @@ var TaskResource = z.object({
600
605
  exportName: z.string(),
601
606
  queue: QueueOptions.optional(),
602
607
  retry: RetryOptions.optional(),
603
- machine: Machine.partial().optional()
608
+ machine: Machine.partial().optional(),
609
+ triggerSource: z.string().optional()
604
610
  });
605
611
  var BackgroundWorkerMetadata = z.object({
606
612
  packageVersion: z.string(),
@@ -656,7 +662,9 @@ var TriggerTaskRequestBody = z.object({
656
662
  lockToVersion: z.string().optional(),
657
663
  queue: QueueOptions.optional(),
658
664
  concurrencyKey: z.string().optional(),
659
- test: z.boolean().optional()
665
+ idempotencyKey: z.string().optional(),
666
+ test: z.boolean().optional(),
667
+ payloadType: z.string().optional()
660
668
  }).optional()
661
669
  });
662
670
  var TriggerTaskResponse = z.object({
@@ -752,6 +760,87 @@ var ReplayRunResponse = z.object({
752
760
  var CanceledRunResponse = z.object({
753
761
  message: z.string()
754
762
  });
763
+ var ScheduledTaskPayload = z.object({
764
+ /** The schedule id associated with this run (you can have many schedules for the same task).
765
+ You can use this to remove the schedule, update it, etc */
766
+ scheduleId: z.string(),
767
+ /** When the task was scheduled to run.
768
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
769
+ timestamp: z.date(),
770
+ /** When the task was last run (it has been).
771
+ This can be undefined if it's never been run */
772
+ lastTimestamp: z.date().optional(),
773
+ /** You can optionally provide an external id when creating the schedule.
774
+ Usually you would use a userId or some other unique identifier.
775
+ This defaults to undefined if you didn't provide one. */
776
+ externalId: z.string().optional(),
777
+ /** The next 5 dates this task is scheduled to run */
778
+ upcoming: z.array(z.date())
779
+ });
780
+ var CreateScheduleOptions = z.object({
781
+ /** The id of the task you want to attach to. */
782
+ task: z.string(),
783
+ /** The schedule in CRON format.
784
+ *
785
+ * ```txt
786
+ * * * * * *
787
+ ┬ ┬ ┬ ┬ ┬
788
+ │ │ │ │ |
789
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
790
+ │ │ │ └───── month (1 - 12)
791
+ │ │ └────────── day of month (1 - 31, L)
792
+ │ └─────────────── hour (0 - 23)
793
+ └──────────────────── minute (0 - 59)
794
+ * ```
795
+
796
+ "L" means the last. In the "day of week" field, 1L means the last Monday of the month. In the day of month field, L means the last day of the month.
797
+
798
+ */
799
+ cron: z.string(),
800
+ /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
801
+ *
802
+ * This is useful if you don't want to create duplicate schedules for a user. */
803
+ deduplicationKey: z.string().optional(),
804
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
805
+ *
806
+ * This allows you to have per-user CRON tasks.
807
+ */
808
+ externalId: z.string().optional()
809
+ });
810
+ var UpdateScheduleOptions = CreateScheduleOptions;
811
+ var ScheduleObject = z.object({
812
+ id: z.string(),
813
+ task: z.string(),
814
+ active: z.boolean(),
815
+ deduplicationKey: z.string().nullish(),
816
+ externalId: z.string().nullish(),
817
+ generator: z.object({
818
+ type: z.literal("CRON"),
819
+ expression: z.string(),
820
+ description: z.string()
821
+ }),
822
+ nextRun: z.coerce.date().nullish(),
823
+ environments: z.array(z.object({
824
+ id: z.string(),
825
+ type: z.string(),
826
+ userName: z.string().nullish()
827
+ }))
828
+ });
829
+ var DeletedScheduleObject = z.object({
830
+ id: z.string()
831
+ });
832
+ var ListSchedulesResult = z.object({
833
+ data: z.array(ScheduleObject),
834
+ pagination: z.object({
835
+ currentPage: z.number(),
836
+ totalPages: z.number(),
837
+ count: z.number()
838
+ })
839
+ });
840
+ var ListScheduleOptions = z.object({
841
+ page: z.number().optional(),
842
+ perPage: z.number().optional()
843
+ });
755
844
  var PostStartCauses = z.enum([
756
845
  "index",
757
846
  "create",
@@ -783,7 +872,8 @@ var Config = z.object({
783
872
  z.string(),
784
873
  RegexSchema
785
874
  ])).optional(),
786
- logLevel: z.string().optional()
875
+ logLevel: z.string().optional(),
876
+ enableConsoleLogging: z.boolean().optional()
787
877
  });
788
878
  var WaitReason = z.enum([
789
879
  "WAIT_FOR_DURATION",
@@ -1439,101 +1529,384 @@ var SpanMessagingEvent = z.object({
1439
1529
  destination: z.string().optional()
1440
1530
  });
1441
1531
 
1442
- // src/zodfetch.ts
1532
+ // src/v3/apiErrors.ts
1533
+ var _APIError = class _APIError extends Error {
1534
+ constructor(status, error, message, headers) {
1535
+ super(`${_APIError.makeMessage(status, error, message)}`);
1536
+ this.status = status;
1537
+ this.headers = headers;
1538
+ const data = error;
1539
+ this.error = data;
1540
+ this.code = data?.["code"];
1541
+ this.param = data?.["param"];
1542
+ this.type = data?.["type"];
1543
+ }
1544
+ static makeMessage(status, error, message) {
1545
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1546
+ if (status && msg) {
1547
+ return `${status} ${msg}`;
1548
+ }
1549
+ if (status) {
1550
+ return `${status} status code (no body)`;
1551
+ }
1552
+ if (msg) {
1553
+ return msg;
1554
+ }
1555
+ return "(no status code or body)";
1556
+ }
1557
+ static generate(status, errorResponse, message, headers) {
1558
+ if (!status) {
1559
+ return new APIConnectionError({
1560
+ cause: castToError(errorResponse)
1561
+ });
1562
+ }
1563
+ const error = errorResponse?.["error"];
1564
+ if (status === 400) {
1565
+ return new BadRequestError(status, error, message, headers);
1566
+ }
1567
+ if (status === 401) {
1568
+ return new AuthenticationError(status, error, message, headers);
1569
+ }
1570
+ if (status === 403) {
1571
+ return new PermissionDeniedError(status, error, message, headers);
1572
+ }
1573
+ if (status === 404) {
1574
+ return new NotFoundError(status, error, message, headers);
1575
+ }
1576
+ if (status === 409) {
1577
+ return new ConflictError(status, error, message, headers);
1578
+ }
1579
+ if (status === 422) {
1580
+ return new UnprocessableEntityError(status, error, message, headers);
1581
+ }
1582
+ if (status === 429) {
1583
+ return new RateLimitError(status, error, message, headers);
1584
+ }
1585
+ if (status >= 500) {
1586
+ return new InternalServerError(status, error, message, headers);
1587
+ }
1588
+ return new _APIError(status, error, message, headers);
1589
+ }
1590
+ };
1591
+ __name(_APIError, "APIError");
1592
+ var APIError = _APIError;
1593
+ var _APIConnectionError = class _APIConnectionError extends APIError {
1594
+ constructor({ message, cause }) {
1595
+ super(void 0, void 0, message || "Connection error.", void 0);
1596
+ __publicField(this, "status");
1597
+ if (cause)
1598
+ this.cause = cause;
1599
+ }
1600
+ };
1601
+ __name(_APIConnectionError, "APIConnectionError");
1602
+ var APIConnectionError = _APIConnectionError;
1603
+ var _BadRequestError = class _BadRequestError extends APIError {
1604
+ constructor() {
1605
+ super(...arguments);
1606
+ __publicField(this, "status", 400);
1607
+ }
1608
+ };
1609
+ __name(_BadRequestError, "BadRequestError");
1610
+ var BadRequestError = _BadRequestError;
1611
+ var _AuthenticationError = class _AuthenticationError extends APIError {
1612
+ constructor() {
1613
+ super(...arguments);
1614
+ __publicField(this, "status", 401);
1615
+ }
1616
+ };
1617
+ __name(_AuthenticationError, "AuthenticationError");
1618
+ var AuthenticationError = _AuthenticationError;
1619
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1620
+ constructor() {
1621
+ super(...arguments);
1622
+ __publicField(this, "status", 403);
1623
+ }
1624
+ };
1625
+ __name(_PermissionDeniedError, "PermissionDeniedError");
1626
+ var PermissionDeniedError = _PermissionDeniedError;
1627
+ var _NotFoundError = class _NotFoundError extends APIError {
1628
+ constructor() {
1629
+ super(...arguments);
1630
+ __publicField(this, "status", 404);
1631
+ }
1632
+ };
1633
+ __name(_NotFoundError, "NotFoundError");
1634
+ var NotFoundError = _NotFoundError;
1635
+ var _ConflictError = class _ConflictError extends APIError {
1636
+ constructor() {
1637
+ super(...arguments);
1638
+ __publicField(this, "status", 409);
1639
+ }
1640
+ };
1641
+ __name(_ConflictError, "ConflictError");
1642
+ var ConflictError = _ConflictError;
1643
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1644
+ constructor() {
1645
+ super(...arguments);
1646
+ __publicField(this, "status", 422);
1647
+ }
1648
+ };
1649
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
1650
+ var UnprocessableEntityError = _UnprocessableEntityError;
1651
+ var _RateLimitError = class _RateLimitError extends APIError {
1652
+ constructor() {
1653
+ super(...arguments);
1654
+ __publicField(this, "status", 429);
1655
+ }
1656
+ };
1657
+ __name(_RateLimitError, "RateLimitError");
1658
+ var RateLimitError = _RateLimitError;
1659
+ var _InternalServerError = class _InternalServerError extends APIError {
1660
+ };
1661
+ __name(_InternalServerError, "InternalServerError");
1662
+ var InternalServerError = _InternalServerError;
1663
+ function castToError(err) {
1664
+ if (err instanceof Error)
1665
+ return err;
1666
+ return new Error(err);
1667
+ }
1668
+ __name(castToError, "castToError");
1669
+
1670
+ // src/retry.ts
1671
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
1672
+ if (!resets)
1673
+ return;
1674
+ switch (format) {
1675
+ case "iso_8601_duration_openai_variant": {
1676
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
1677
+ }
1678
+ case "iso_8601": {
1679
+ return calculateISO8601ResetAt(resets, now);
1680
+ }
1681
+ case "unix_timestamp": {
1682
+ return calculateUnixTimestampResetAt(resets, now);
1683
+ }
1684
+ case "unix_timestamp_in_ms": {
1685
+ return calculateUnixTimestampInMsResetAt(resets, now);
1686
+ }
1687
+ }
1688
+ }
1689
+ __name(calculateResetAt, "calculateResetAt");
1690
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
1691
+ if (!resets)
1692
+ return void 0;
1693
+ const resetAt = parseInt(resets, 10);
1694
+ if (isNaN(resetAt))
1695
+ return void 0;
1696
+ return new Date(resetAt * 1e3);
1697
+ }
1698
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
1699
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
1700
+ if (!resets)
1701
+ return void 0;
1702
+ const resetAt = parseInt(resets, 10);
1703
+ if (isNaN(resetAt))
1704
+ return void 0;
1705
+ return new Date(resetAt);
1706
+ }
1707
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
1708
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
1709
+ if (!resets)
1710
+ return void 0;
1711
+ const resetAt = new Date(resets);
1712
+ if (isNaN(resetAt.getTime()))
1713
+ return void 0;
1714
+ return resetAt;
1715
+ }
1716
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
1717
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
1718
+ if (!resets)
1719
+ return void 0;
1720
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
1721
+ const match = resets.match(pattern);
1722
+ if (!match)
1723
+ return void 0;
1724
+ const days = parseInt(match[1], 10) || 0;
1725
+ const hours = parseInt(match[2], 10) || 0;
1726
+ const minutes = parseInt(match[3], 10) || 0;
1727
+ const seconds = parseFloat(match[4]) || 0;
1728
+ const milliseconds = parseInt(match[5], 10) || 0;
1729
+ const resetAt = new Date(now);
1730
+ resetAt.setDate(resetAt.getDate() + days);
1731
+ resetAt.setHours(resetAt.getHours() + hours);
1732
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
1733
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
1734
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
1735
+ return resetAt;
1736
+ }
1737
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
1738
+
1739
+ // src/v3/utils/retries.ts
1740
+ var defaultRetryOptions = {
1741
+ maxAttempts: 3,
1742
+ factor: 2,
1743
+ minTimeoutInMs: 1e3,
1744
+ maxTimeoutInMs: 6e4,
1745
+ randomize: true
1746
+ };
1747
+ var defaultFetchRetryOptions = {
1748
+ byStatus: {
1749
+ "429,408,409,5xx": {
1750
+ strategy: "backoff",
1751
+ ...defaultRetryOptions
1752
+ }
1753
+ },
1754
+ connectionError: defaultRetryOptions,
1755
+ timeout: defaultRetryOptions
1756
+ };
1757
+ function calculateNextRetryDelay(options, attempt) {
1758
+ const opts = {
1759
+ ...defaultRetryOptions,
1760
+ ...options
1761
+ };
1762
+ if (attempt >= opts.maxAttempts) {
1763
+ return;
1764
+ }
1765
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1766
+ const random = randomize ? Math.random() + 1 : 1;
1767
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1768
+ return Math.round(timeout);
1769
+ }
1770
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1771
+ function calculateResetAt2(resets, format, now = Date.now()) {
1772
+ const resetAt = calculateResetAt(resets, format, new Date(now));
1773
+ return resetAt?.getTime();
1774
+ }
1775
+ __name(calculateResetAt2, "calculateResetAt");
1776
+
1777
+ // src/v3/zodfetch.ts
1778
+ var defaultRetryOptions2 = {
1779
+ maxAttempts: 3,
1780
+ factor: 2,
1781
+ minTimeoutInMs: 1e3,
1782
+ maxTimeoutInMs: 6e4,
1783
+ randomize: false
1784
+ };
1443
1785
  async function zodfetch(schema, url, requestInit, options) {
1444
1786
  return await _doZodFetch(schema, url, requestInit, options);
1445
1787
  }
1446
1788
  __name(zodfetch, "zodfetch");
1447
1789
  async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1448
1790
  try {
1449
- const response = await fetch(url, requestInit);
1450
- if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
1451
- return {
1452
- ok: false,
1453
- error: `404: ${response.statusText}`
1454
- };
1455
- }
1456
- if (response.status >= 400 && response.status < 500 && response.status !== 429) {
1457
- const body = await response.json();
1458
- if (!body.error) {
1459
- return {
1460
- ok: false,
1461
- error: "Something went wrong"
1462
- };
1791
+ const response = await fetch(url, requestInitWithCache(requestInit));
1792
+ const responseHeaders = createResponseHeaders(response.headers);
1793
+ if (!response.ok) {
1794
+ const retryResult = shouldRetry(response, attempt, options?.retry);
1795
+ if (retryResult.retry) {
1796
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1797
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1798
+ } else {
1799
+ const errText = await response.text().catch((e) => castToError2(e).message);
1800
+ const errJSON = safeJsonParse(errText);
1801
+ const errMessage = errJSON ? void 0 : errText;
1802
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
1463
1803
  }
1464
- return {
1465
- ok: false,
1466
- error: body.error
1467
- };
1468
1804
  }
1469
- if (response.status === 429 || response.status >= 500) {
1470
- if (!options?.retry) {
1471
- return {
1472
- ok: false,
1473
- error: `Failed to fetch ${url}, got status code ${response.status}`
1474
- };
1475
- }
1805
+ const jsonBody = await response.json();
1806
+ const parsedResult = schema.safeParse(jsonBody);
1807
+ if (parsedResult.success) {
1808
+ return parsedResult.data;
1809
+ }
1810
+ throw fromZodError(parsedResult.error);
1811
+ } catch (error) {
1812
+ if (error instanceof APIError) {
1813
+ throw error;
1814
+ }
1815
+ if (options?.retry) {
1476
1816
  const retry = {
1477
- ...defaultRetryOptions,
1817
+ ...defaultRetryOptions2,
1478
1818
  ...options.retry
1479
1819
  };
1480
- if (attempt > retry.maxAttempts) {
1481
- return {
1482
- ok: false,
1483
- error: `Failed to fetch ${url}, got status code ${response.status}`
1484
- };
1485
- }
1486
1820
  const delay = calculateNextRetryDelay(retry, attempt);
1487
- await new Promise((resolve) => setTimeout(resolve, delay));
1488
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1489
- }
1490
- if (response.status !== 200) {
1491
- return {
1492
- ok: false,
1493
- error: `Failed to fetch ${url}, got status code ${response.status}`
1494
- };
1821
+ if (delay) {
1822
+ await new Promise((resolve) => setTimeout(resolve, delay));
1823
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1824
+ }
1495
1825
  }
1496
- const jsonBody = await response.json();
1497
- const parsedResult = schema.safeParse(jsonBody);
1498
- if (parsedResult.success) {
1826
+ throw new APIConnectionError({
1827
+ cause: castToError2(error)
1828
+ });
1829
+ }
1830
+ }
1831
+ __name(_doZodFetch, "_doZodFetch");
1832
+ function castToError2(err) {
1833
+ if (err instanceof Error)
1834
+ return err;
1835
+ return new Error(err);
1836
+ }
1837
+ __name(castToError2, "castToError");
1838
+ function shouldRetry(response, attempt, retryOptions) {
1839
+ function shouldRetryForOptions() {
1840
+ const retry = {
1841
+ ...defaultRetryOptions2,
1842
+ ...retryOptions
1843
+ };
1844
+ const delay = calculateNextRetryDelay(retry, attempt);
1845
+ if (delay) {
1499
1846
  return {
1500
- ok: true,
1501
- data: parsedResult.data
1847
+ retry: true,
1848
+ delay
1502
1849
  };
1503
- }
1504
- if ("error" in jsonBody) {
1850
+ } else {
1505
1851
  return {
1506
- ok: false,
1507
- error: typeof jsonBody.error === "string" ? jsonBody.error : JSON.stringify(jsonBody.error)
1852
+ retry: false
1508
1853
  };
1509
1854
  }
1855
+ }
1856
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
1857
+ const shouldRetryHeader = response.headers.get("x-should-retry");
1858
+ if (shouldRetryHeader === "true")
1859
+ return shouldRetryForOptions();
1860
+ if (shouldRetryHeader === "false")
1510
1861
  return {
1511
- ok: false,
1512
- error: parsedResult.error.message
1862
+ retry: false
1513
1863
  };
1514
- } catch (error) {
1515
- if (options?.retry) {
1516
- const retry = {
1517
- ...defaultRetryOptions,
1518
- ...options.retry
1519
- };
1520
- if (attempt > retry.maxAttempts) {
1521
- return {
1522
- ok: false,
1523
- error: error instanceof Error ? error.message : JSON.stringify(error)
1524
- };
1525
- }
1526
- const delay = calculateNextRetryDelay(retry, attempt);
1527
- await new Promise((resolve) => setTimeout(resolve, delay));
1528
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1864
+ if (response.status === 408)
1865
+ return shouldRetryForOptions();
1866
+ if (response.status === 409)
1867
+ return shouldRetryForOptions();
1868
+ if (response.status === 429)
1869
+ return shouldRetryForOptions();
1870
+ if (response.status >= 500)
1871
+ return shouldRetryForOptions();
1872
+ return {
1873
+ retry: false
1874
+ };
1875
+ }
1876
+ __name(shouldRetry, "shouldRetry");
1877
+ function safeJsonParse(text) {
1878
+ try {
1879
+ return JSON.parse(text);
1880
+ } catch (e) {
1881
+ return void 0;
1882
+ }
1883
+ }
1884
+ __name(safeJsonParse, "safeJsonParse");
1885
+ function createResponseHeaders(headers) {
1886
+ return new Proxy(Object.fromEntries(
1887
+ // @ts-ignore
1888
+ headers.entries()
1889
+ ), {
1890
+ get(target, name) {
1891
+ const key = name.toString();
1892
+ return target[key.toLowerCase()] || target[key];
1529
1893
  }
1530
- return {
1531
- ok: false,
1532
- error: error instanceof Error ? error.message : JSON.stringify(error)
1894
+ });
1895
+ }
1896
+ __name(createResponseHeaders, "createResponseHeaders");
1897
+ function requestInitWithCache(requestInit) {
1898
+ try {
1899
+ const withCache = {
1900
+ ...requestInit,
1901
+ cache: "no-cache"
1533
1902
  };
1903
+ const _ = new Request("http://localhost", withCache);
1904
+ return withCache;
1905
+ } catch (error) {
1906
+ return requestInit ?? {};
1534
1907
  }
1535
1908
  }
1536
- __name(_doZodFetch, "_doZodFetch");
1909
+ __name(requestInitWithCache, "requestInitWithCache");
1537
1910
 
1538
1911
  // src/v3/utils/flattenAttributes.ts
1539
1912
  function flattenAttributes(obj, prefix) {
@@ -1685,7 +2058,8 @@ var SemanticInternalAttributes = {
1685
2058
  SDK_LANGUAGE: "sdk.language",
1686
2059
  RETRY_AT: "retry.at",
1687
2060
  RETRY_DELAY: "retry.delay",
1688
- RETRY_COUNT: "retry.count"
2061
+ RETRY_COUNT: "retry.count",
2062
+ LINK_TITLE: "$link.title"
1689
2063
  };
1690
2064
 
1691
2065
  // src/v3/tasks/taskContextManager.ts
@@ -1821,7 +2195,7 @@ __name(getEnvVar, "getEnvVar");
1821
2195
  // src/v3/apiClient/index.ts
1822
2196
  var zodFetchOptions = {
1823
2197
  retry: {
1824
- maxAttempts: 5,
2198
+ maxAttempts: 3,
1825
2199
  minTimeoutInMs: 1e3,
1826
2200
  maxTimeoutInMs: 3e4,
1827
2201
  factor: 2,
@@ -1873,6 +2247,57 @@ var _ApiClient = class _ApiClient {
1873
2247
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1874
2248
  }, zodFetchOptions);
1875
2249
  }
2250
+ createSchedule(options) {
2251
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
2252
+ method: "POST",
2253
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2254
+ body: JSON.stringify(options)
2255
+ });
2256
+ }
2257
+ listSchedules(options) {
2258
+ const searchParams = new URLSearchParams();
2259
+ if (options?.page) {
2260
+ searchParams.append("page", options.page.toString());
2261
+ }
2262
+ if (options?.perPage) {
2263
+ searchParams.append("perPage", options.perPage.toString());
2264
+ }
2265
+ return zodfetch(ListSchedulesResult, `${this.baseUrl}/api/v1/schedules${searchParams.size > 0 ? `?${searchParams}` : ""}`, {
2266
+ method: "GET",
2267
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2268
+ });
2269
+ }
2270
+ retrieveSchedule(scheduleId) {
2271
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2272
+ method: "GET",
2273
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2274
+ });
2275
+ }
2276
+ updateSchedule(scheduleId, options) {
2277
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2278
+ method: "PUT",
2279
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2280
+ body: JSON.stringify(options)
2281
+ });
2282
+ }
2283
+ deactivateSchedule(scheduleId) {
2284
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
2285
+ method: "POST",
2286
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2287
+ });
2288
+ }
2289
+ activateSchedule(scheduleId) {
2290
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
2291
+ method: "POST",
2292
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2293
+ });
2294
+ }
2295
+ deleteSchedule(scheduleId) {
2296
+ return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2297
+ method: "DELETE",
2298
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2299
+ });
2300
+ }
1876
2301
  };
1877
2302
  _getHeaders = new WeakSet();
1878
2303
  getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
@@ -2786,11 +3211,6 @@ __name(unregisterGlobal, "unregisterGlobal");
2786
3211
  var _NoopRuntimeManager = class _NoopRuntimeManager {
2787
3212
  disable() {
2788
3213
  }
2789
- registerTasks() {
2790
- }
2791
- getTaskMetadata(id) {
2792
- return void 0;
2793
- }
2794
3214
  waitForDuration(ms) {
2795
3215
  return Promise.resolve();
2796
3216
  }
@@ -2850,12 +3270,6 @@ var _RuntimeAPI = class _RuntimeAPI {
2850
3270
  __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2851
3271
  unregisterGlobal(API_NAME);
2852
3272
  }
2853
- registerTasks(tasks) {
2854
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).registerTasks(tasks);
2855
- }
2856
- getTaskMetadata(id) {
2857
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).getTaskMetadata(id);
2858
- }
2859
3273
  };
2860
3274
  _getRuntimeManager = new WeakSet();
2861
3275
  getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
@@ -3001,7 +3415,7 @@ var _OtelTaskLogger = class _OtelTaskLogger {
3001
3415
  _emitLog = new WeakSet();
3002
3416
  emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
3003
3417
  let attributes = {
3004
- ...flattenAttributes(properties)
3418
+ ...flattenAttributes(safeJsonProcess(properties))
3005
3419
  };
3006
3420
  const icon = iconStringForSeverity(severityNumber);
3007
3421
  if (icon !== void 0) {
@@ -3038,6 +3452,14 @@ var _NoopTaskLogger = class _NoopTaskLogger {
3038
3452
  };
3039
3453
  __name(_NoopTaskLogger, "NoopTaskLogger");
3040
3454
  var NoopTaskLogger = _NoopTaskLogger;
3455
+ function safeJsonProcess(value) {
3456
+ try {
3457
+ return JSON.parse(JSON.stringify(value));
3458
+ } catch {
3459
+ return value;
3460
+ }
3461
+ }
3462
+ __name(safeJsonProcess, "safeJsonProcess");
3041
3463
 
3042
3464
  // src/v3/logger/index.ts
3043
3465
  var API_NAME3 = "logger";
@@ -3088,6 +3510,78 @@ var LoggerAPI = _LoggerAPI;
3088
3510
  // src/v3/logger-api.ts
3089
3511
  var logger = LoggerAPI.getInstance();
3090
3512
 
3513
+ // src/v3/task-catalog/noopTaskCatalog.ts
3514
+ var _NoopTaskCatalog = class _NoopTaskCatalog {
3515
+ registerTaskMetadata(task) {
3516
+ }
3517
+ registerTaskFileMetadata(id, metadata) {
3518
+ }
3519
+ updateTaskMetadata(id, updates) {
3520
+ }
3521
+ getAllTaskMetadata() {
3522
+ return [];
3523
+ }
3524
+ getTaskMetadata(id) {
3525
+ return void 0;
3526
+ }
3527
+ getTask(id) {
3528
+ return void 0;
3529
+ }
3530
+ disable() {
3531
+ }
3532
+ };
3533
+ __name(_NoopTaskCatalog, "NoopTaskCatalog");
3534
+ var NoopTaskCatalog = _NoopTaskCatalog;
3535
+
3536
+ // src/v3/task-catalog/index.ts
3537
+ var API_NAME4 = "task-catalog";
3538
+ var NOOP_TASK_CATALOG = new NoopTaskCatalog();
3539
+ var _getCatalog, getCatalog_fn;
3540
+ var _TaskCatalogAPI = class _TaskCatalogAPI {
3541
+ constructor() {
3542
+ __privateAdd(this, _getCatalog);
3543
+ }
3544
+ static getInstance() {
3545
+ if (!this._instance) {
3546
+ this._instance = new _TaskCatalogAPI();
3547
+ }
3548
+ return this._instance;
3549
+ }
3550
+ setGlobalTaskCatalog(taskCatalog2) {
3551
+ return registerGlobal(API_NAME4, taskCatalog2);
3552
+ }
3553
+ disable() {
3554
+ unregisterGlobal(API_NAME4);
3555
+ }
3556
+ registerTaskMetadata(task) {
3557
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskMetadata(task);
3558
+ }
3559
+ updateTaskMetadata(id, updates) {
3560
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).updateTaskMetadata(id, updates);
3561
+ }
3562
+ registerTaskFileMetadata(id, metadata) {
3563
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskFileMetadata(id, metadata);
3564
+ }
3565
+ getAllTaskMetadata() {
3566
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getAllTaskMetadata();
3567
+ }
3568
+ getTaskMetadata(id) {
3569
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTaskMetadata(id);
3570
+ }
3571
+ getTask(id) {
3572
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTask(id);
3573
+ }
3574
+ };
3575
+ _getCatalog = new WeakSet();
3576
+ getCatalog_fn = /* @__PURE__ */ __name(function() {
3577
+ return getGlobal(API_NAME4) ?? NOOP_TASK_CATALOG;
3578
+ }, "#getCatalog");
3579
+ __name(_TaskCatalogAPI, "TaskCatalogAPI");
3580
+ var TaskCatalogAPI = _TaskCatalogAPI;
3581
+
3582
+ // src/v3/task-catalog-api.ts
3583
+ var taskCatalog = TaskCatalogAPI.getInstance();
3584
+
3091
3585
  // src/v3/limits.ts
3092
3586
  var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
3093
3587
  var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
@@ -3211,19 +3705,10 @@ var _DevRuntimeManager = class _DevRuntimeManager {
3211
3705
  constructor() {
3212
3706
  __publicField(this, "_taskWaits", /* @__PURE__ */ new Map());
3213
3707
  __publicField(this, "_batchWaits", /* @__PURE__ */ new Map());
3214
- __publicField(this, "_tasks", /* @__PURE__ */ new Map());
3215
3708
  __publicField(this, "_pendingCompletionNotifications", /* @__PURE__ */ new Map());
3216
3709
  }
3217
3710
  disable() {
3218
3711
  }
3219
- registerTasks(tasks) {
3220
- for (const task of tasks) {
3221
- this._tasks.set(task.id, task);
3222
- }
3223
- }
3224
- getTaskMetadata(id) {
3225
- return this._tasks.get(id);
3226
- }
3227
3712
  async waitForDuration(ms) {
3228
3713
  return new Promise((resolve) => {
3229
3714
  setTimeout(resolve, ms);
@@ -3301,18 +3786,9 @@ var _ProdRuntimeManager = class _ProdRuntimeManager {
3301
3786
  this.options = options;
3302
3787
  this._taskWaits = /* @__PURE__ */ new Map();
3303
3788
  this._batchWaits = /* @__PURE__ */ new Map();
3304
- this._tasks = /* @__PURE__ */ new Map();
3305
3789
  }
3306
3790
  disable() {
3307
3791
  }
3308
- registerTasks(tasks) {
3309
- for (const task of tasks) {
3310
- this._tasks.set(task.id, task);
3311
- }
3312
- }
3313
- getTaskMetadata(id) {
3314
- return this._tasks.get(id);
3315
- }
3316
3792
  async waitForDuration(ms) {
3317
3793
  const now = Date.now();
3318
3794
  const resolveAfterDuration = setTimeout$1(ms, "duration");
@@ -3517,11 +3993,12 @@ __name(_TriggerTracer, "TriggerTracer");
3517
3993
  var TriggerTracer = _TriggerTracer;
3518
3994
  var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
3519
3995
  var _ConsoleInterceptor = class _ConsoleInterceptor {
3520
- constructor(logger2) {
3996
+ constructor(logger2, sendToStdIO) {
3521
3997
  __privateAdd(this, _handleLog);
3522
3998
  __privateAdd(this, _getTimestampInHrTime2);
3523
3999
  __privateAdd(this, _getAttributes);
3524
4000
  this.logger = logger2;
4001
+ this.sendToStdIO = sendToStdIO;
3525
4002
  }
3526
4003
  // Intercept the console and send logs to the OpenTelemetry logger
3527
4004
  // during the execution of the callback
@@ -3530,12 +4007,14 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3530
4007
  log: console2.log,
3531
4008
  info: console2.info,
3532
4009
  warn: console2.warn,
3533
- error: console2.error
4010
+ error: console2.error,
4011
+ debug: console2.debug
3534
4012
  };
3535
4013
  console2.log = this.log.bind(this);
3536
4014
  console2.info = this.info.bind(this);
3537
4015
  console2.warn = this.warn.bind(this);
3538
4016
  console2.error = this.error.bind(this);
4017
+ console2.debug = this.debug.bind(this);
3539
4018
  try {
3540
4019
  return await callback();
3541
4020
  } finally {
@@ -3543,8 +4022,12 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3543
4022
  console2.info = originalConsole.info;
3544
4023
  console2.warn = originalConsole.warn;
3545
4024
  console2.error = originalConsole.error;
4025
+ console2.debug = originalConsole.debug;
3546
4026
  }
3547
4027
  }
4028
+ debug(...args) {
4029
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
4030
+ }
3548
4031
  log(...args) {
3549
4032
  __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
3550
4033
  }
@@ -3561,6 +4044,13 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3561
4044
  _handleLog = new WeakSet();
3562
4045
  handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
3563
4046
  const body = util.format(...args);
4047
+ if (this.sendToStdIO) {
4048
+ if (severityNumber === SeverityNumber.ERROR) {
4049
+ process.stderr.write(body);
4050
+ } else {
4051
+ process.stdout.write(body);
4052
+ }
4053
+ }
3564
4054
  const parsed = tryParseJSON(body);
3565
4055
  if (parsed.ok) {
3566
4056
  this.logger.emit({
@@ -3636,113 +4126,6 @@ function tryParseJSON(value) {
3636
4126
  }
3637
4127
  __name(tryParseJSON, "tryParseJSON");
3638
4128
 
3639
- // src/retry.ts
3640
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
3641
- if (!resets)
3642
- return;
3643
- switch (format) {
3644
- case "iso_8601_duration_openai_variant": {
3645
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
3646
- }
3647
- case "iso_8601": {
3648
- return calculateISO8601ResetAt(resets, now);
3649
- }
3650
- case "unix_timestamp": {
3651
- return calculateUnixTimestampResetAt(resets, now);
3652
- }
3653
- case "unix_timestamp_in_ms": {
3654
- return calculateUnixTimestampInMsResetAt(resets, now);
3655
- }
3656
- }
3657
- }
3658
- __name(calculateResetAt, "calculateResetAt");
3659
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
3660
- if (!resets)
3661
- return void 0;
3662
- const resetAt = parseInt(resets, 10);
3663
- if (isNaN(resetAt))
3664
- return void 0;
3665
- return new Date(resetAt * 1e3);
3666
- }
3667
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
3668
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
3669
- if (!resets)
3670
- return void 0;
3671
- const resetAt = parseInt(resets, 10);
3672
- if (isNaN(resetAt))
3673
- return void 0;
3674
- return new Date(resetAt);
3675
- }
3676
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
3677
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
3678
- if (!resets)
3679
- return void 0;
3680
- const resetAt = new Date(resets);
3681
- if (isNaN(resetAt.getTime()))
3682
- return void 0;
3683
- return resetAt;
3684
- }
3685
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
3686
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
3687
- if (!resets)
3688
- return void 0;
3689
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
3690
- const match = resets.match(pattern);
3691
- if (!match)
3692
- return void 0;
3693
- const days = parseInt(match[1], 10) || 0;
3694
- const hours = parseInt(match[2], 10) || 0;
3695
- const minutes = parseInt(match[3], 10) || 0;
3696
- const seconds = parseFloat(match[4]) || 0;
3697
- const milliseconds = parseInt(match[5], 10) || 0;
3698
- const resetAt = new Date(now);
3699
- resetAt.setDate(resetAt.getDate() + days);
3700
- resetAt.setHours(resetAt.getHours() + hours);
3701
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
3702
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
3703
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
3704
- return resetAt;
3705
- }
3706
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
3707
-
3708
- // src/v3/utils/retries.ts
3709
- var defaultRetryOptions = {
3710
- maxAttempts: 3,
3711
- factor: 2,
3712
- minTimeoutInMs: 1e3,
3713
- maxTimeoutInMs: 6e4,
3714
- randomize: true
3715
- };
3716
- var defaultFetchRetryOptions = {
3717
- byStatus: {
3718
- "429,408,409,5xx": {
3719
- strategy: "backoff",
3720
- ...defaultRetryOptions
3721
- }
3722
- },
3723
- connectionError: defaultRetryOptions,
3724
- timeout: defaultRetryOptions
3725
- };
3726
- function calculateNextRetryDelay(options, attempt) {
3727
- const opts = {
3728
- ...defaultRetryOptions,
3729
- ...options
3730
- };
3731
- if (attempt >= opts.maxAttempts) {
3732
- return;
3733
- }
3734
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
3735
- const random = randomize ? Math.random() + 1 : 1;
3736
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
3737
- return Math.round(timeout);
3738
- }
3739
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
3740
- function calculateResetAt2(resets, format, now = Date.now()) {
3741
- const resetAt = calculateResetAt(resets, format, new Date(now));
3742
- return resetAt?.getTime();
3743
- }
3744
- __name(calculateResetAt2, "calculateResetAt");
3745
-
3746
4129
  // src/v3/utils/styleAttributes.ts
3747
4130
  function accessoryAttributes(accessory) {
3748
4131
  return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
@@ -4103,6 +4486,7 @@ async function stringifyIO(value) {
4103
4486
  };
4104
4487
  } catch {
4105
4488
  return {
4489
+ data: value,
4106
4490
  dataType: "application/json"
4107
4491
  };
4108
4492
  }
@@ -4147,23 +4531,20 @@ __name(packetRequiresOffloading, "packetRequiresOffloading");
4147
4531
  async function exportPacket(packet, pathPrefix) {
4148
4532
  const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
4149
4533
  const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
4150
- if (presignedResponse.ok) {
4151
- const uploadResponse = await fetch(presignedResponse.data.presignedUrl, {
4152
- method: "PUT",
4153
- headers: {
4154
- "Content-Type": packet.dataType
4155
- },
4156
- body: packet.data
4157
- });
4158
- if (!uploadResponse.ok) {
4159
- throw new Error(`Failed to upload output to ${presignedResponse.data.presignedUrl}: ${uploadResponse.statusText}`);
4160
- }
4161
- return {
4162
- data: filename,
4163
- dataType: "application/store"
4164
- };
4534
+ const uploadResponse = await fetch(presignedResponse.presignedUrl, {
4535
+ method: "PUT",
4536
+ headers: {
4537
+ "Content-Type": packet.dataType
4538
+ },
4539
+ body: packet.data
4540
+ });
4541
+ if (!uploadResponse.ok) {
4542
+ throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
4165
4543
  }
4166
- return packet;
4544
+ return {
4545
+ data: filename,
4546
+ dataType: "application/store"
4547
+ };
4167
4548
  }
4168
4549
  __name(exportPacket, "exportPacket");
4169
4550
  async function conditionallyImportPacket(packet, tracer) {
@@ -4192,19 +4573,16 @@ async function importPacket(packet, span) {
4192
4573
  return packet;
4193
4574
  }
4194
4575
  const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
4195
- if (presignedResponse.ok) {
4196
- const response = await fetch(presignedResponse.data.presignedUrl);
4197
- if (!response.ok) {
4198
- throw new Error(`Failed to import packet ${presignedResponse.data.presignedUrl}: ${response.statusText}`);
4199
- }
4200
- const data = await response.text();
4201
- span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4202
- return {
4203
- data,
4204
- dataType: response.headers.get("content-type") ?? "application/json"
4205
- };
4576
+ const response = await fetch(presignedResponse.presignedUrl);
4577
+ if (!response.ok) {
4578
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
4206
4579
  }
4207
- return packet;
4580
+ const data = await response.text();
4581
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4582
+ return {
4583
+ data,
4584
+ dataType: response.headers.get("content-type") ?? "application/json"
4585
+ };
4208
4586
  }
4209
4587
  __name(importPacket, "importPacket");
4210
4588
  async function createPacketAttributes(packet, dataKey, dataTypeKey) {
@@ -4257,7 +4635,7 @@ async function createPacketAttributesAsJson(data, dataType) {
4257
4635
  case "application/super+json":
4258
4636
  const { deserialize } = await loadSuperJSON();
4259
4637
  const deserialized = deserialize(data);
4260
- const jsonify = safeJsonParse(JSON.stringify(deserialized, safeReplacer));
4638
+ const jsonify = safeJsonParse2(JSON.stringify(deserialized, safeReplacer));
4261
4639
  return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
4262
4640
  case "application/store":
4263
4641
  return data;
@@ -4271,10 +4649,16 @@ async function prettyPrintPacket(rawData, dataType) {
4271
4649
  return "";
4272
4650
  }
4273
4651
  if (dataType === "application/super+json") {
4652
+ if (typeof rawData === "string") {
4653
+ rawData = safeJsonParse2(rawData);
4654
+ }
4274
4655
  const { deserialize } = await loadSuperJSON();
4275
4656
  return await prettyPrintPacket(deserialize(rawData), "application/json");
4276
4657
  }
4277
4658
  if (dataType === "application/json") {
4659
+ if (typeof rawData === "string") {
4660
+ rawData = safeJsonParse2(rawData);
4661
+ }
4278
4662
  return JSON.stringify(rawData, safeReplacer, 2);
4279
4663
  }
4280
4664
  if (typeof rawData === "string") {
@@ -4320,14 +4704,14 @@ async function loadSuperJSON() {
4320
4704
  return await import('superjson');
4321
4705
  }
4322
4706
  __name(loadSuperJSON, "loadSuperJSON");
4323
- function safeJsonParse(value) {
4707
+ function safeJsonParse2(value) {
4324
4708
  try {
4325
4709
  return JSON.parse(value);
4326
4710
  } catch {
4327
4711
  return;
4328
4712
  }
4329
4713
  }
4330
- __name(safeJsonParse, "safeJsonParse");
4714
+ __name(safeJsonParse2, "safeJsonParse");
4331
4715
 
4332
4716
  // src/v3/workers/taskExecutor.ts
4333
4717
  var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
@@ -4599,7 +4983,8 @@ var dependencies = {
4599
4983
  superjson: "^2.2.1",
4600
4984
  ulidx: "^2.2.1",
4601
4985
  zod: "3.22.3",
4602
- "zod-error": "1.5.0"
4986
+ "zod-error": "1.5.0",
4987
+ "zod-validation-error": "^1.5.0"
4603
4988
  };
4604
4989
 
4605
4990
  // src/v3/utils/detectDependencyVersion.ts
@@ -4608,6 +4993,84 @@ function detectDependencyVersion(dependency) {
4608
4993
  }
4609
4994
  __name(detectDependencyVersion, "detectDependencyVersion");
4610
4995
 
4996
+ // src/v3/task-catalog/standardTaskCatalog.ts
4997
+ var _StandardTaskCatalog = class _StandardTaskCatalog {
4998
+ constructor() {
4999
+ __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
5000
+ __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
5001
+ __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
5002
+ }
5003
+ registerTaskMetadata(task) {
5004
+ const { fns, ...metadata } = task;
5005
+ this._taskMetadata.set(task.id, metadata);
5006
+ this._taskFunctions.set(task.id, fns);
5007
+ }
5008
+ updateTaskMetadata(id, updates) {
5009
+ const existingMetadata = this._taskMetadata.get(id);
5010
+ if (existingMetadata) {
5011
+ this._taskMetadata.set(id, {
5012
+ ...existingMetadata,
5013
+ ...updates
5014
+ });
5015
+ }
5016
+ if (updates.fns) {
5017
+ const existingFunctions = this._taskFunctions.get(id);
5018
+ if (existingFunctions) {
5019
+ this._taskFunctions.set(id, {
5020
+ ...existingFunctions,
5021
+ ...updates.fns
5022
+ });
5023
+ }
5024
+ }
5025
+ }
5026
+ registerTaskFileMetadata(id, metadata) {
5027
+ this._taskFileMetadata.set(id, metadata);
5028
+ }
5029
+ // Return all the tasks, without the functions
5030
+ getAllTaskMetadata() {
5031
+ const result = [];
5032
+ for (const [id, metadata] of this._taskMetadata) {
5033
+ const fileMetadata = this._taskFileMetadata.get(id);
5034
+ if (!fileMetadata) {
5035
+ continue;
5036
+ }
5037
+ result.push({
5038
+ ...metadata,
5039
+ ...fileMetadata
5040
+ });
5041
+ }
5042
+ return result;
5043
+ }
5044
+ getTaskMetadata(id) {
5045
+ const metadata = this._taskMetadata.get(id);
5046
+ const fileMetadata = this._taskFileMetadata.get(id);
5047
+ if (!metadata || !fileMetadata) {
5048
+ return void 0;
5049
+ }
5050
+ return {
5051
+ ...metadata,
5052
+ ...fileMetadata
5053
+ };
5054
+ }
5055
+ getTask(id) {
5056
+ const metadata = this._taskMetadata.get(id);
5057
+ const fileMetadata = this._taskFileMetadata.get(id);
5058
+ const fns = this._taskFunctions.get(id);
5059
+ if (!metadata || !fns || !fileMetadata) {
5060
+ return void 0;
5061
+ }
5062
+ return {
5063
+ ...metadata,
5064
+ ...fileMetadata,
5065
+ fns
5066
+ };
5067
+ }
5068
+ disable() {
5069
+ }
5070
+ };
5071
+ __name(_StandardTaskCatalog, "StandardTaskCatalog");
5072
+ var StandardTaskCatalog = _StandardTaskCatalog;
5073
+
4611
5074
  // src/v3/index.ts
4612
5075
  function parseTriggerTaskRequestBody(body) {
4613
5076
  return TriggerTaskRequestBody.safeParse(body);
@@ -4618,6 +5081,6 @@ function parseBatchTriggerTaskRequestBody(body) {
4618
5081
  }
4619
5082
  __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
4620
5083
 
4621
- export { ApiClient, ApiClientManager, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConsoleInterceptor, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateUploadPayloadUrlResponseBody, DeploymentErrorData, DevRuntimeManager, PreciseWallClock as DurableClock, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, LogLevel, Machine, MachineCpu, MachineMemory, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtelTaskLogger, OtherSpanEvent, PRIMARY_VARIANT, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdRuntimeManager, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitOptions, ReplayRunResponse, RetryOptions, SemanticInternalAttributes, SharedQueueToClientMessages, SimpleStructuredLogger, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskContextSpanProcessor, TaskEventStyle, TaskExecutor, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TracingSDK, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, WaitReason, WhoAmIResponseSchema, ZodIpcConnection, ZodMessageHandler, ZodMessageSchema, ZodMessageSender, ZodNamespace, ZodSchemaParsedError, ZodSocketConnection, ZodSocketMessageHandler, ZodSocketMessageSender, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, getEnvVar, groupTaskMetadataIssuesByTask, iconStringForSeverity, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logLevels, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseBatchTriggerTaskRequestBody, parseError, parsePacket, parseTriggerTaskRequestBody, prettyPrintPacket, primitiveValueOrflattenedAttributes, recordSpanException, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskContextManager, unflattenAttributes, workerToChildMessages };
5084
+ export { APIConnectionError, APIError, ApiClient, ApiClientManager, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, ConsoleInterceptor, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, DeletedScheduleObject, DeploymentErrorData, DevRuntimeManager, PreciseWallClock as DurableClock, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListScheduleOptions, ListSchedulesResult, LogLevel, Machine, MachineCpu, MachineMemory, NotFoundError, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtelTaskLogger, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdRuntimeManager, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetryOptions, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SharedQueueToClientMessages, SimpleStructuredLogger, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StandardTaskCatalog, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskContextSpanProcessor, TaskEventStyle, TaskExecutor, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TracingSDK, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, ZodIpcConnection, ZodMessageHandler, ZodMessageSchema, ZodMessageSender, ZodNamespace, ZodSchemaParsedError, ZodSocketConnection, ZodSocketMessageHandler, ZodSocketMessageSender, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, getEnvVar, groupTaskMetadataIssuesByTask, iconStringForSeverity, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logLevels, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseBatchTriggerTaskRequestBody, parseError, parsePacket, parseTriggerTaskRequestBody, prettyPrintPacket, primitiveValueOrflattenedAttributes, recordSpanException, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContextManager, unflattenAttributes, workerToChildMessages };
4622
5085
  //# sourceMappingURL=out.js.map
4623
5086
  //# sourceMappingURL=index.mjs.map