@trigger.dev/core 0.0.0-v3-schedules-beta-20240417103105 → 0.0.0-v3-schedules-beta-20240417141912

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';
@@ -760,16 +761,50 @@ var CanceledRunResponse = z.object({
760
761
  message: z.string()
761
762
  });
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 */
763
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. */
764
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 */
765
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. */
766
776
  externalId: z.string().optional(),
777
+ /** The next 5 dates this task is scheduled to run */
767
778
  upcoming: z.array(z.date())
768
779
  });
769
780
  var CreateScheduleOptions = z.object({
781
+ /** The id of the task you want to attach to. */
770
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
+ */
771
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. */
772
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
+ */
773
808
  externalId: z.string().optional()
774
809
  });
775
810
  var UpdateScheduleOptions = CreateScheduleOptions;
@@ -777,18 +812,18 @@ var ScheduleObject = z.object({
777
812
  id: z.string(),
778
813
  task: z.string(),
779
814
  active: z.boolean(),
780
- deduplicationKey: z.string().optional(),
781
- externalId: z.string().optional(),
815
+ deduplicationKey: z.string().nullish(),
816
+ externalId: z.string().nullish(),
782
817
  generator: z.object({
783
818
  type: z.literal("CRON"),
784
819
  expression: z.string(),
785
820
  description: z.string()
786
821
  }),
787
- nextRun: z.coerce.date().optional(),
822
+ nextRun: z.coerce.date().nullish(),
788
823
  environments: z.array(z.object({
789
824
  id: z.string(),
790
825
  type: z.string(),
791
- userName: z.string().optional()
826
+ userName: z.string().nullish()
792
827
  }))
793
828
  });
794
829
  var DeletedScheduleObject = z.object({
@@ -1494,101 +1529,384 @@ var SpanMessagingEvent = z.object({
1494
1529
  destination: z.string().optional()
1495
1530
  });
1496
1531
 
1497
- // 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
+ };
1498
1785
  async function zodfetch(schema, url, requestInit, options) {
1499
1786
  return await _doZodFetch(schema, url, requestInit, options);
1500
1787
  }
1501
1788
  __name(zodfetch, "zodfetch");
1502
1789
  async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1503
1790
  try {
1504
- const response = await fetch(url, requestInit);
1505
- if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
1506
- return {
1507
- ok: false,
1508
- error: `404: ${response.statusText}`
1509
- };
1510
- }
1511
- if (response.status >= 400 && response.status < 500 && response.status !== 429) {
1512
- const body = await response.json();
1513
- if (!body.error) {
1514
- return {
1515
- ok: false,
1516
- error: "Something went wrong"
1517
- };
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);
1518
1803
  }
1519
- return {
1520
- ok: false,
1521
- error: body.error
1522
- };
1523
1804
  }
1524
- if (response.status === 429 || response.status >= 500) {
1525
- if (!options?.retry) {
1526
- return {
1527
- ok: false,
1528
- error: `Failed to fetch ${url}, got status code ${response.status}`
1529
- };
1530
- }
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) {
1531
1816
  const retry = {
1532
- ...defaultRetryOptions,
1817
+ ...defaultRetryOptions2,
1533
1818
  ...options.retry
1534
1819
  };
1535
- if (attempt > retry.maxAttempts) {
1536
- return {
1537
- ok: false,
1538
- error: `Failed to fetch ${url}, got status code ${response.status}`
1539
- };
1540
- }
1541
1820
  const delay = calculateNextRetryDelay(retry, attempt);
1542
- await new Promise((resolve) => setTimeout(resolve, delay));
1543
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1544
- }
1545
- if (response.status !== 200) {
1546
- return {
1547
- ok: false,
1548
- error: `Failed to fetch ${url}, got status code ${response.status}`
1549
- };
1821
+ if (delay) {
1822
+ await new Promise((resolve) => setTimeout(resolve, delay));
1823
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1824
+ }
1550
1825
  }
1551
- const jsonBody = await response.json();
1552
- const parsedResult = schema.safeParse(jsonBody);
1553
- 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) {
1554
1846
  return {
1555
- ok: true,
1556
- data: parsedResult.data
1847
+ retry: true,
1848
+ delay
1557
1849
  };
1558
- }
1559
- if ("error" in jsonBody) {
1850
+ } else {
1560
1851
  return {
1561
- ok: false,
1562
- error: typeof jsonBody.error === "string" ? jsonBody.error : JSON.stringify(jsonBody.error)
1852
+ retry: false
1563
1853
  };
1564
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")
1565
1861
  return {
1566
- ok: false,
1567
- error: parsedResult.error.message
1862
+ retry: false
1568
1863
  };
1569
- } catch (error) {
1570
- if (options?.retry) {
1571
- const retry = {
1572
- ...defaultRetryOptions,
1573
- ...options.retry
1574
- };
1575
- if (attempt > retry.maxAttempts) {
1576
- return {
1577
- ok: false,
1578
- error: error instanceof Error ? error.message : JSON.stringify(error)
1579
- };
1580
- }
1581
- const delay = calculateNextRetryDelay(retry, attempt);
1582
- await new Promise((resolve) => setTimeout(resolve, delay));
1583
- 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];
1584
1893
  }
1585
- return {
1586
- ok: false,
1587
- 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"
1588
1902
  };
1903
+ const _ = new Request("http://localhost", withCache);
1904
+ return withCache;
1905
+ } catch (error) {
1906
+ return requestInit ?? {};
1589
1907
  }
1590
1908
  }
1591
- __name(_doZodFetch, "_doZodFetch");
1909
+ __name(requestInitWithCache, "requestInitWithCache");
1592
1910
 
1593
1911
  // src/v3/utils/flattenAttributes.ts
1594
1912
  function flattenAttributes(obj, prefix) {
@@ -1877,7 +2195,7 @@ __name(getEnvVar, "getEnvVar");
1877
2195
  // src/v3/apiClient/index.ts
1878
2196
  var zodFetchOptions = {
1879
2197
  retry: {
1880
- maxAttempts: 5,
2198
+ maxAttempts: 3,
1881
2199
  minTimeoutInMs: 1e3,
1882
2200
  maxTimeoutInMs: 3e4,
1883
2201
  factor: 2,
@@ -3808,113 +4126,6 @@ function tryParseJSON(value) {
3808
4126
  }
3809
4127
  __name(tryParseJSON, "tryParseJSON");
3810
4128
 
3811
- // src/retry.ts
3812
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
3813
- if (!resets)
3814
- return;
3815
- switch (format) {
3816
- case "iso_8601_duration_openai_variant": {
3817
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
3818
- }
3819
- case "iso_8601": {
3820
- return calculateISO8601ResetAt(resets, now);
3821
- }
3822
- case "unix_timestamp": {
3823
- return calculateUnixTimestampResetAt(resets, now);
3824
- }
3825
- case "unix_timestamp_in_ms": {
3826
- return calculateUnixTimestampInMsResetAt(resets, now);
3827
- }
3828
- }
3829
- }
3830
- __name(calculateResetAt, "calculateResetAt");
3831
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
3832
- if (!resets)
3833
- return void 0;
3834
- const resetAt = parseInt(resets, 10);
3835
- if (isNaN(resetAt))
3836
- return void 0;
3837
- return new Date(resetAt * 1e3);
3838
- }
3839
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
3840
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
3841
- if (!resets)
3842
- return void 0;
3843
- const resetAt = parseInt(resets, 10);
3844
- if (isNaN(resetAt))
3845
- return void 0;
3846
- return new Date(resetAt);
3847
- }
3848
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
3849
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
3850
- if (!resets)
3851
- return void 0;
3852
- const resetAt = new Date(resets);
3853
- if (isNaN(resetAt.getTime()))
3854
- return void 0;
3855
- return resetAt;
3856
- }
3857
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
3858
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
3859
- if (!resets)
3860
- return void 0;
3861
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
3862
- const match = resets.match(pattern);
3863
- if (!match)
3864
- return void 0;
3865
- const days = parseInt(match[1], 10) || 0;
3866
- const hours = parseInt(match[2], 10) || 0;
3867
- const minutes = parseInt(match[3], 10) || 0;
3868
- const seconds = parseFloat(match[4]) || 0;
3869
- const milliseconds = parseInt(match[5], 10) || 0;
3870
- const resetAt = new Date(now);
3871
- resetAt.setDate(resetAt.getDate() + days);
3872
- resetAt.setHours(resetAt.getHours() + hours);
3873
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
3874
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
3875
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
3876
- return resetAt;
3877
- }
3878
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
3879
-
3880
- // src/v3/utils/retries.ts
3881
- var defaultRetryOptions = {
3882
- maxAttempts: 3,
3883
- factor: 2,
3884
- minTimeoutInMs: 1e3,
3885
- maxTimeoutInMs: 6e4,
3886
- randomize: true
3887
- };
3888
- var defaultFetchRetryOptions = {
3889
- byStatus: {
3890
- "429,408,409,5xx": {
3891
- strategy: "backoff",
3892
- ...defaultRetryOptions
3893
- }
3894
- },
3895
- connectionError: defaultRetryOptions,
3896
- timeout: defaultRetryOptions
3897
- };
3898
- function calculateNextRetryDelay(options, attempt) {
3899
- const opts = {
3900
- ...defaultRetryOptions,
3901
- ...options
3902
- };
3903
- if (attempt >= opts.maxAttempts) {
3904
- return;
3905
- }
3906
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
3907
- const random = randomize ? Math.random() + 1 : 1;
3908
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
3909
- return Math.round(timeout);
3910
- }
3911
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
3912
- function calculateResetAt2(resets, format, now = Date.now()) {
3913
- const resetAt = calculateResetAt(resets, format, new Date(now));
3914
- return resetAt?.getTime();
3915
- }
3916
- __name(calculateResetAt2, "calculateResetAt");
3917
-
3918
4129
  // src/v3/utils/styleAttributes.ts
3919
4130
  function accessoryAttributes(accessory) {
3920
4131
  return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
@@ -4320,23 +4531,20 @@ __name(packetRequiresOffloading, "packetRequiresOffloading");
4320
4531
  async function exportPacket(packet, pathPrefix) {
4321
4532
  const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
4322
4533
  const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
4323
- if (presignedResponse.ok) {
4324
- const uploadResponse = await fetch(presignedResponse.data.presignedUrl, {
4325
- method: "PUT",
4326
- headers: {
4327
- "Content-Type": packet.dataType
4328
- },
4329
- body: packet.data
4330
- });
4331
- if (!uploadResponse.ok) {
4332
- throw new Error(`Failed to upload output to ${presignedResponse.data.presignedUrl}: ${uploadResponse.statusText}`);
4333
- }
4334
- return {
4335
- data: filename,
4336
- dataType: "application/store"
4337
- };
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}`);
4338
4543
  }
4339
- return packet;
4544
+ return {
4545
+ data: filename,
4546
+ dataType: "application/store"
4547
+ };
4340
4548
  }
4341
4549
  __name(exportPacket, "exportPacket");
4342
4550
  async function conditionallyImportPacket(packet, tracer) {
@@ -4365,19 +4573,16 @@ async function importPacket(packet, span) {
4365
4573
  return packet;
4366
4574
  }
4367
4575
  const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
4368
- if (presignedResponse.ok) {
4369
- const response = await fetch(presignedResponse.data.presignedUrl);
4370
- if (!response.ok) {
4371
- throw new Error(`Failed to import packet ${presignedResponse.data.presignedUrl}: ${response.statusText}`);
4372
- }
4373
- const data = await response.text();
4374
- span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4375
- return {
4376
- data,
4377
- dataType: response.headers.get("content-type") ?? "application/json"
4378
- };
4576
+ const response = await fetch(presignedResponse.presignedUrl);
4577
+ if (!response.ok) {
4578
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
4379
4579
  }
4380
- 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
+ };
4381
4586
  }
4382
4587
  __name(importPacket, "importPacket");
4383
4588
  async function createPacketAttributes(packet, dataKey, dataTypeKey) {
@@ -4430,7 +4635,7 @@ async function createPacketAttributesAsJson(data, dataType) {
4430
4635
  case "application/super+json":
4431
4636
  const { deserialize } = await loadSuperJSON();
4432
4637
  const deserialized = deserialize(data);
4433
- const jsonify = safeJsonParse(JSON.stringify(deserialized, safeReplacer));
4638
+ const jsonify = safeJsonParse2(JSON.stringify(deserialized, safeReplacer));
4434
4639
  return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
4435
4640
  case "application/store":
4436
4641
  return data;
@@ -4445,14 +4650,14 @@ async function prettyPrintPacket(rawData, dataType) {
4445
4650
  }
4446
4651
  if (dataType === "application/super+json") {
4447
4652
  if (typeof rawData === "string") {
4448
- rawData = safeJsonParse(rawData);
4653
+ rawData = safeJsonParse2(rawData);
4449
4654
  }
4450
4655
  const { deserialize } = await loadSuperJSON();
4451
4656
  return await prettyPrintPacket(deserialize(rawData), "application/json");
4452
4657
  }
4453
4658
  if (dataType === "application/json") {
4454
4659
  if (typeof rawData === "string") {
4455
- rawData = safeJsonParse(rawData);
4660
+ rawData = safeJsonParse2(rawData);
4456
4661
  }
4457
4662
  return JSON.stringify(rawData, safeReplacer, 2);
4458
4663
  }
@@ -4499,14 +4704,14 @@ async function loadSuperJSON() {
4499
4704
  return await import('superjson');
4500
4705
  }
4501
4706
  __name(loadSuperJSON, "loadSuperJSON");
4502
- function safeJsonParse(value) {
4707
+ function safeJsonParse2(value) {
4503
4708
  try {
4504
4709
  return JSON.parse(value);
4505
4710
  } catch {
4506
4711
  return;
4507
4712
  }
4508
4713
  }
4509
- __name(safeJsonParse, "safeJsonParse");
4714
+ __name(safeJsonParse2, "safeJsonParse");
4510
4715
 
4511
4716
  // src/v3/workers/taskExecutor.ts
4512
4717
  var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
@@ -4778,7 +4983,8 @@ var dependencies = {
4778
4983
  superjson: "^2.2.1",
4779
4984
  ulidx: "^2.2.1",
4780
4985
  zod: "3.22.3",
4781
- "zod-error": "1.5.0"
4986
+ "zod-error": "1.5.0",
4987
+ "zod-validation-error": "^1.5.0"
4782
4988
  };
4783
4989
 
4784
4990
  // src/v3/utils/detectDependencyVersion.ts
@@ -4875,6 +5081,6 @@ function parseBatchTriggerTaskRequestBody(body) {
4875
5081
  }
4876
5082
  __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
4877
5083
 
4878
- export { ApiClient, ApiClientManager, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, 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, ListScheduleOptions, ListSchedulesResult, 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, 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, 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 };
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 };
4879
5085
  //# sourceMappingURL=out.js.map
4880
5086
  //# sourceMappingURL=index.mjs.map