@trigger.dev/core 3.0.0-beta.11 → 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.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var zod = require('zod');
4
4
  var api = require('@opentelemetry/api');
5
+ var zodValidationError = require('zod-validation-error');
5
6
  var async_hooks = require('async_hooks');
6
7
  var socket_ioClient = require('socket.io-client');
7
8
  var crypto = require('crypto');
@@ -91,6 +92,7 @@ var TaskRunStringError = zod.z.object({
91
92
  });
92
93
  var TaskRunErrorCodes = {
93
94
  COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
95
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
94
96
  CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
95
97
  TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
96
98
  TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
@@ -104,6 +106,7 @@ var TaskRunInternalError = zod.z.object({
104
106
  type: zod.z.literal("INTERNAL_ERROR"),
105
107
  code: zod.z.enum([
106
108
  "COULD_NOT_FIND_EXECUTOR",
109
+ "COULD_NOT_FIND_TASK",
107
110
  "CONFIGURED_INCORRECTLY",
108
111
  "TASK_ALREADY_RUNNING",
109
112
  "TASK_EXECUTION_FAILED",
@@ -448,15 +451,17 @@ var QueueOptions = zod.z.object({
448
451
  });
449
452
  var TaskMetadata = zod.z.object({
450
453
  id: zod.z.string(),
451
- exportName: zod.z.string(),
452
454
  packageVersion: zod.z.string(),
453
455
  queue: QueueOptions.optional(),
454
456
  retry: RetryOptions.optional(),
455
- machine: Machine.partial().optional()
457
+ machine: Machine.partial().optional(),
458
+ triggerSource: zod.z.string().optional()
456
459
  });
457
- var TaskMetadataWithFilePath = TaskMetadata.extend({
458
- filePath: zod.z.string()
460
+ var TaskFileMetadata = zod.z.object({
461
+ filePath: zod.z.string(),
462
+ exportName: zod.z.string()
459
463
  });
464
+ var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
460
465
  var UncaughtExceptionMessage = zod.z.object({
461
466
  version: zod.z.literal("v1").default("v1"),
462
467
  error: zod.z.object({
@@ -608,7 +613,8 @@ var TaskResource = zod.z.object({
608
613
  exportName: zod.z.string(),
609
614
  queue: QueueOptions.optional(),
610
615
  retry: RetryOptions.optional(),
611
- machine: Machine.partial().optional()
616
+ machine: Machine.partial().optional(),
617
+ triggerSource: zod.z.string().optional()
612
618
  });
613
619
  var BackgroundWorkerMetadata = zod.z.object({
614
620
  packageVersion: zod.z.string(),
@@ -664,7 +670,9 @@ var TriggerTaskRequestBody = zod.z.object({
664
670
  lockToVersion: zod.z.string().optional(),
665
671
  queue: QueueOptions.optional(),
666
672
  concurrencyKey: zod.z.string().optional(),
667
- test: zod.z.boolean().optional()
673
+ idempotencyKey: zod.z.string().optional(),
674
+ test: zod.z.boolean().optional(),
675
+ payloadType: zod.z.string().optional()
668
676
  }).optional()
669
677
  });
670
678
  var TriggerTaskResponse = zod.z.object({
@@ -760,6 +768,87 @@ var ReplayRunResponse = zod.z.object({
760
768
  var CanceledRunResponse = zod.z.object({
761
769
  message: zod.z.string()
762
770
  });
771
+ var ScheduledTaskPayload = zod.z.object({
772
+ /** The schedule id associated with this run (you can have many schedules for the same task).
773
+ You can use this to remove the schedule, update it, etc */
774
+ scheduleId: zod.z.string(),
775
+ /** When the task was scheduled to run.
776
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
777
+ timestamp: zod.z.date(),
778
+ /** When the task was last run (it has been).
779
+ This can be undefined if it's never been run */
780
+ lastTimestamp: zod.z.date().optional(),
781
+ /** You can optionally provide an external id when creating the schedule.
782
+ Usually you would use a userId or some other unique identifier.
783
+ This defaults to undefined if you didn't provide one. */
784
+ externalId: zod.z.string().optional(),
785
+ /** The next 5 dates this task is scheduled to run */
786
+ upcoming: zod.z.array(zod.z.date())
787
+ });
788
+ var CreateScheduleOptions = zod.z.object({
789
+ /** The id of the task you want to attach to. */
790
+ task: zod.z.string(),
791
+ /** The schedule in CRON format.
792
+ *
793
+ * ```txt
794
+ * * * * * *
795
+ ┬ ┬ ┬ ┬ ┬
796
+ │ │ │ │ |
797
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
798
+ │ │ │ └───── month (1 - 12)
799
+ │ │ └────────── day of month (1 - 31, L)
800
+ │ └─────────────── hour (0 - 23)
801
+ └──────────────────── minute (0 - 59)
802
+ * ```
803
+
804
+ "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.
805
+
806
+ */
807
+ cron: zod.z.string(),
808
+ /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
809
+ *
810
+ * This is useful if you don't want to create duplicate schedules for a user. */
811
+ deduplicationKey: zod.z.string().optional(),
812
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
813
+ *
814
+ * This allows you to have per-user CRON tasks.
815
+ */
816
+ externalId: zod.z.string().optional()
817
+ });
818
+ var UpdateScheduleOptions = CreateScheduleOptions;
819
+ var ScheduleObject = zod.z.object({
820
+ id: zod.z.string(),
821
+ task: zod.z.string(),
822
+ active: zod.z.boolean(),
823
+ deduplicationKey: zod.z.string().nullish(),
824
+ externalId: zod.z.string().nullish(),
825
+ generator: zod.z.object({
826
+ type: zod.z.literal("CRON"),
827
+ expression: zod.z.string(),
828
+ description: zod.z.string()
829
+ }),
830
+ nextRun: zod.z.coerce.date().nullish(),
831
+ environments: zod.z.array(zod.z.object({
832
+ id: zod.z.string(),
833
+ type: zod.z.string(),
834
+ userName: zod.z.string().nullish()
835
+ }))
836
+ });
837
+ var DeletedScheduleObject = zod.z.object({
838
+ id: zod.z.string()
839
+ });
840
+ var ListSchedulesResult = zod.z.object({
841
+ data: zod.z.array(ScheduleObject),
842
+ pagination: zod.z.object({
843
+ currentPage: zod.z.number(),
844
+ totalPages: zod.z.number(),
845
+ count: zod.z.number()
846
+ })
847
+ });
848
+ var ListScheduleOptions = zod.z.object({
849
+ page: zod.z.number().optional(),
850
+ perPage: zod.z.number().optional()
851
+ });
763
852
  var PostStartCauses = zod.z.enum([
764
853
  "index",
765
854
  "create",
@@ -791,7 +880,8 @@ var Config = zod.z.object({
791
880
  zod.z.string(),
792
881
  RegexSchema
793
882
  ])).optional(),
794
- logLevel: zod.z.string().optional()
883
+ logLevel: zod.z.string().optional(),
884
+ enableConsoleLogging: zod.z.boolean().optional()
795
885
  });
796
886
  var WaitReason = zod.z.enum([
797
887
  "WAIT_FOR_DURATION",
@@ -1447,101 +1537,384 @@ var SpanMessagingEvent = zod.z.object({
1447
1537
  destination: zod.z.string().optional()
1448
1538
  });
1449
1539
 
1450
- // src/zodfetch.ts
1540
+ // src/v3/apiErrors.ts
1541
+ var _APIError = class _APIError extends Error {
1542
+ constructor(status, error, message, headers) {
1543
+ super(`${_APIError.makeMessage(status, error, message)}`);
1544
+ this.status = status;
1545
+ this.headers = headers;
1546
+ const data = error;
1547
+ this.error = data;
1548
+ this.code = data?.["code"];
1549
+ this.param = data?.["param"];
1550
+ this.type = data?.["type"];
1551
+ }
1552
+ static makeMessage(status, error, message) {
1553
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1554
+ if (status && msg) {
1555
+ return `${status} ${msg}`;
1556
+ }
1557
+ if (status) {
1558
+ return `${status} status code (no body)`;
1559
+ }
1560
+ if (msg) {
1561
+ return msg;
1562
+ }
1563
+ return "(no status code or body)";
1564
+ }
1565
+ static generate(status, errorResponse, message, headers) {
1566
+ if (!status) {
1567
+ return new APIConnectionError({
1568
+ cause: castToError(errorResponse)
1569
+ });
1570
+ }
1571
+ const error = errorResponse?.["error"];
1572
+ if (status === 400) {
1573
+ return new BadRequestError(status, error, message, headers);
1574
+ }
1575
+ if (status === 401) {
1576
+ return new AuthenticationError(status, error, message, headers);
1577
+ }
1578
+ if (status === 403) {
1579
+ return new PermissionDeniedError(status, error, message, headers);
1580
+ }
1581
+ if (status === 404) {
1582
+ return new NotFoundError(status, error, message, headers);
1583
+ }
1584
+ if (status === 409) {
1585
+ return new ConflictError(status, error, message, headers);
1586
+ }
1587
+ if (status === 422) {
1588
+ return new UnprocessableEntityError(status, error, message, headers);
1589
+ }
1590
+ if (status === 429) {
1591
+ return new RateLimitError(status, error, message, headers);
1592
+ }
1593
+ if (status >= 500) {
1594
+ return new InternalServerError(status, error, message, headers);
1595
+ }
1596
+ return new _APIError(status, error, message, headers);
1597
+ }
1598
+ };
1599
+ __name(_APIError, "APIError");
1600
+ var APIError = _APIError;
1601
+ var _APIConnectionError = class _APIConnectionError extends APIError {
1602
+ constructor({ message, cause }) {
1603
+ super(void 0, void 0, message || "Connection error.", void 0);
1604
+ __publicField(this, "status");
1605
+ if (cause)
1606
+ this.cause = cause;
1607
+ }
1608
+ };
1609
+ __name(_APIConnectionError, "APIConnectionError");
1610
+ var APIConnectionError = _APIConnectionError;
1611
+ var _BadRequestError = class _BadRequestError extends APIError {
1612
+ constructor() {
1613
+ super(...arguments);
1614
+ __publicField(this, "status", 400);
1615
+ }
1616
+ };
1617
+ __name(_BadRequestError, "BadRequestError");
1618
+ var BadRequestError = _BadRequestError;
1619
+ var _AuthenticationError = class _AuthenticationError extends APIError {
1620
+ constructor() {
1621
+ super(...arguments);
1622
+ __publicField(this, "status", 401);
1623
+ }
1624
+ };
1625
+ __name(_AuthenticationError, "AuthenticationError");
1626
+ var AuthenticationError = _AuthenticationError;
1627
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1628
+ constructor() {
1629
+ super(...arguments);
1630
+ __publicField(this, "status", 403);
1631
+ }
1632
+ };
1633
+ __name(_PermissionDeniedError, "PermissionDeniedError");
1634
+ var PermissionDeniedError = _PermissionDeniedError;
1635
+ var _NotFoundError = class _NotFoundError extends APIError {
1636
+ constructor() {
1637
+ super(...arguments);
1638
+ __publicField(this, "status", 404);
1639
+ }
1640
+ };
1641
+ __name(_NotFoundError, "NotFoundError");
1642
+ var NotFoundError = _NotFoundError;
1643
+ var _ConflictError = class _ConflictError extends APIError {
1644
+ constructor() {
1645
+ super(...arguments);
1646
+ __publicField(this, "status", 409);
1647
+ }
1648
+ };
1649
+ __name(_ConflictError, "ConflictError");
1650
+ var ConflictError = _ConflictError;
1651
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1652
+ constructor() {
1653
+ super(...arguments);
1654
+ __publicField(this, "status", 422);
1655
+ }
1656
+ };
1657
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
1658
+ var UnprocessableEntityError = _UnprocessableEntityError;
1659
+ var _RateLimitError = class _RateLimitError extends APIError {
1660
+ constructor() {
1661
+ super(...arguments);
1662
+ __publicField(this, "status", 429);
1663
+ }
1664
+ };
1665
+ __name(_RateLimitError, "RateLimitError");
1666
+ var RateLimitError = _RateLimitError;
1667
+ var _InternalServerError = class _InternalServerError extends APIError {
1668
+ };
1669
+ __name(_InternalServerError, "InternalServerError");
1670
+ var InternalServerError = _InternalServerError;
1671
+ function castToError(err) {
1672
+ if (err instanceof Error)
1673
+ return err;
1674
+ return new Error(err);
1675
+ }
1676
+ __name(castToError, "castToError");
1677
+
1678
+ // src/retry.ts
1679
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
1680
+ if (!resets)
1681
+ return;
1682
+ switch (format) {
1683
+ case "iso_8601_duration_openai_variant": {
1684
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
1685
+ }
1686
+ case "iso_8601": {
1687
+ return calculateISO8601ResetAt(resets, now);
1688
+ }
1689
+ case "unix_timestamp": {
1690
+ return calculateUnixTimestampResetAt(resets, now);
1691
+ }
1692
+ case "unix_timestamp_in_ms": {
1693
+ return calculateUnixTimestampInMsResetAt(resets, now);
1694
+ }
1695
+ }
1696
+ }
1697
+ __name(calculateResetAt, "calculateResetAt");
1698
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
1699
+ if (!resets)
1700
+ return void 0;
1701
+ const resetAt = parseInt(resets, 10);
1702
+ if (isNaN(resetAt))
1703
+ return void 0;
1704
+ return new Date(resetAt * 1e3);
1705
+ }
1706
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
1707
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
1708
+ if (!resets)
1709
+ return void 0;
1710
+ const resetAt = parseInt(resets, 10);
1711
+ if (isNaN(resetAt))
1712
+ return void 0;
1713
+ return new Date(resetAt);
1714
+ }
1715
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
1716
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
1717
+ if (!resets)
1718
+ return void 0;
1719
+ const resetAt = new Date(resets);
1720
+ if (isNaN(resetAt.getTime()))
1721
+ return void 0;
1722
+ return resetAt;
1723
+ }
1724
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
1725
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
1726
+ if (!resets)
1727
+ return void 0;
1728
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
1729
+ const match = resets.match(pattern);
1730
+ if (!match)
1731
+ return void 0;
1732
+ const days = parseInt(match[1], 10) || 0;
1733
+ const hours = parseInt(match[2], 10) || 0;
1734
+ const minutes = parseInt(match[3], 10) || 0;
1735
+ const seconds = parseFloat(match[4]) || 0;
1736
+ const milliseconds = parseInt(match[5], 10) || 0;
1737
+ const resetAt = new Date(now);
1738
+ resetAt.setDate(resetAt.getDate() + days);
1739
+ resetAt.setHours(resetAt.getHours() + hours);
1740
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
1741
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
1742
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
1743
+ return resetAt;
1744
+ }
1745
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
1746
+
1747
+ // src/v3/utils/retries.ts
1748
+ var defaultRetryOptions = {
1749
+ maxAttempts: 3,
1750
+ factor: 2,
1751
+ minTimeoutInMs: 1e3,
1752
+ maxTimeoutInMs: 6e4,
1753
+ randomize: true
1754
+ };
1755
+ var defaultFetchRetryOptions = {
1756
+ byStatus: {
1757
+ "429,408,409,5xx": {
1758
+ strategy: "backoff",
1759
+ ...defaultRetryOptions
1760
+ }
1761
+ },
1762
+ connectionError: defaultRetryOptions,
1763
+ timeout: defaultRetryOptions
1764
+ };
1765
+ function calculateNextRetryDelay(options, attempt) {
1766
+ const opts = {
1767
+ ...defaultRetryOptions,
1768
+ ...options
1769
+ };
1770
+ if (attempt >= opts.maxAttempts) {
1771
+ return;
1772
+ }
1773
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1774
+ const random = randomize ? Math.random() + 1 : 1;
1775
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1776
+ return Math.round(timeout);
1777
+ }
1778
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1779
+ function calculateResetAt2(resets, format, now = Date.now()) {
1780
+ const resetAt = calculateResetAt(resets, format, new Date(now));
1781
+ return resetAt?.getTime();
1782
+ }
1783
+ __name(calculateResetAt2, "calculateResetAt");
1784
+
1785
+ // src/v3/zodfetch.ts
1786
+ var defaultRetryOptions2 = {
1787
+ maxAttempts: 3,
1788
+ factor: 2,
1789
+ minTimeoutInMs: 1e3,
1790
+ maxTimeoutInMs: 6e4,
1791
+ randomize: false
1792
+ };
1451
1793
  async function zodfetch(schema, url, requestInit, options) {
1452
1794
  return await _doZodFetch(schema, url, requestInit, options);
1453
1795
  }
1454
1796
  __name(zodfetch, "zodfetch");
1455
1797
  async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1456
1798
  try {
1457
- const response = await fetch(url, requestInit);
1458
- if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
1459
- return {
1460
- ok: false,
1461
- error: `404: ${response.statusText}`
1462
- };
1463
- }
1464
- if (response.status >= 400 && response.status < 500 && response.status !== 429) {
1465
- const body = await response.json();
1466
- if (!body.error) {
1467
- return {
1468
- ok: false,
1469
- error: "Something went wrong"
1470
- };
1799
+ const response = await fetch(url, requestInitWithCache(requestInit));
1800
+ const responseHeaders = createResponseHeaders(response.headers);
1801
+ if (!response.ok) {
1802
+ const retryResult = shouldRetry(response, attempt, options?.retry);
1803
+ if (retryResult.retry) {
1804
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1805
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1806
+ } else {
1807
+ const errText = await response.text().catch((e) => castToError2(e).message);
1808
+ const errJSON = safeJsonParse(errText);
1809
+ const errMessage = errJSON ? void 0 : errText;
1810
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
1471
1811
  }
1472
- return {
1473
- ok: false,
1474
- error: body.error
1475
- };
1476
1812
  }
1477
- if (response.status === 429 || response.status >= 500) {
1478
- if (!options?.retry) {
1479
- return {
1480
- ok: false,
1481
- error: `Failed to fetch ${url}, got status code ${response.status}`
1482
- };
1483
- }
1813
+ const jsonBody = await response.json();
1814
+ const parsedResult = schema.safeParse(jsonBody);
1815
+ if (parsedResult.success) {
1816
+ return parsedResult.data;
1817
+ }
1818
+ throw zodValidationError.fromZodError(parsedResult.error);
1819
+ } catch (error) {
1820
+ if (error instanceof APIError) {
1821
+ throw error;
1822
+ }
1823
+ if (options?.retry) {
1484
1824
  const retry = {
1485
- ...defaultRetryOptions,
1825
+ ...defaultRetryOptions2,
1486
1826
  ...options.retry
1487
1827
  };
1488
- if (attempt > retry.maxAttempts) {
1489
- return {
1490
- ok: false,
1491
- error: `Failed to fetch ${url}, got status code ${response.status}`
1492
- };
1493
- }
1494
1828
  const delay = calculateNextRetryDelay(retry, attempt);
1495
- await new Promise((resolve) => setTimeout(resolve, delay));
1496
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1497
- }
1498
- if (response.status !== 200) {
1499
- return {
1500
- ok: false,
1501
- error: `Failed to fetch ${url}, got status code ${response.status}`
1502
- };
1829
+ if (delay) {
1830
+ await new Promise((resolve) => setTimeout(resolve, delay));
1831
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1832
+ }
1503
1833
  }
1504
- const jsonBody = await response.json();
1505
- const parsedResult = schema.safeParse(jsonBody);
1506
- if (parsedResult.success) {
1834
+ throw new APIConnectionError({
1835
+ cause: castToError2(error)
1836
+ });
1837
+ }
1838
+ }
1839
+ __name(_doZodFetch, "_doZodFetch");
1840
+ function castToError2(err) {
1841
+ if (err instanceof Error)
1842
+ return err;
1843
+ return new Error(err);
1844
+ }
1845
+ __name(castToError2, "castToError");
1846
+ function shouldRetry(response, attempt, retryOptions) {
1847
+ function shouldRetryForOptions() {
1848
+ const retry = {
1849
+ ...defaultRetryOptions2,
1850
+ ...retryOptions
1851
+ };
1852
+ const delay = calculateNextRetryDelay(retry, attempt);
1853
+ if (delay) {
1507
1854
  return {
1508
- ok: true,
1509
- data: parsedResult.data
1855
+ retry: true,
1856
+ delay
1510
1857
  };
1511
- }
1512
- if ("error" in jsonBody) {
1858
+ } else {
1513
1859
  return {
1514
- ok: false,
1515
- error: typeof jsonBody.error === "string" ? jsonBody.error : JSON.stringify(jsonBody.error)
1860
+ retry: false
1516
1861
  };
1517
1862
  }
1863
+ }
1864
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
1865
+ const shouldRetryHeader = response.headers.get("x-should-retry");
1866
+ if (shouldRetryHeader === "true")
1867
+ return shouldRetryForOptions();
1868
+ if (shouldRetryHeader === "false")
1518
1869
  return {
1519
- ok: false,
1520
- error: parsedResult.error.message
1870
+ retry: false
1521
1871
  };
1522
- } catch (error) {
1523
- if (options?.retry) {
1524
- const retry = {
1525
- ...defaultRetryOptions,
1526
- ...options.retry
1527
- };
1528
- if (attempt > retry.maxAttempts) {
1529
- return {
1530
- ok: false,
1531
- error: error instanceof Error ? error.message : JSON.stringify(error)
1532
- };
1533
- }
1534
- const delay = calculateNextRetryDelay(retry, attempt);
1535
- await new Promise((resolve) => setTimeout(resolve, delay));
1536
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1872
+ if (response.status === 408)
1873
+ return shouldRetryForOptions();
1874
+ if (response.status === 409)
1875
+ return shouldRetryForOptions();
1876
+ if (response.status === 429)
1877
+ return shouldRetryForOptions();
1878
+ if (response.status >= 500)
1879
+ return shouldRetryForOptions();
1880
+ return {
1881
+ retry: false
1882
+ };
1883
+ }
1884
+ __name(shouldRetry, "shouldRetry");
1885
+ function safeJsonParse(text) {
1886
+ try {
1887
+ return JSON.parse(text);
1888
+ } catch (e) {
1889
+ return void 0;
1890
+ }
1891
+ }
1892
+ __name(safeJsonParse, "safeJsonParse");
1893
+ function createResponseHeaders(headers) {
1894
+ return new Proxy(Object.fromEntries(
1895
+ // @ts-ignore
1896
+ headers.entries()
1897
+ ), {
1898
+ get(target, name) {
1899
+ const key = name.toString();
1900
+ return target[key.toLowerCase()] || target[key];
1537
1901
  }
1538
- return {
1539
- ok: false,
1540
- error: error instanceof Error ? error.message : JSON.stringify(error)
1902
+ });
1903
+ }
1904
+ __name(createResponseHeaders, "createResponseHeaders");
1905
+ function requestInitWithCache(requestInit) {
1906
+ try {
1907
+ const withCache = {
1908
+ ...requestInit,
1909
+ cache: "no-cache"
1541
1910
  };
1911
+ const _ = new Request("http://localhost", withCache);
1912
+ return withCache;
1913
+ } catch (error) {
1914
+ return requestInit ?? {};
1542
1915
  }
1543
1916
  }
1544
- __name(_doZodFetch, "_doZodFetch");
1917
+ __name(requestInitWithCache, "requestInitWithCache");
1545
1918
 
1546
1919
  // src/v3/utils/flattenAttributes.ts
1547
1920
  function flattenAttributes(obj, prefix) {
@@ -1693,7 +2066,8 @@ var SemanticInternalAttributes = {
1693
2066
  SDK_LANGUAGE: "sdk.language",
1694
2067
  RETRY_AT: "retry.at",
1695
2068
  RETRY_DELAY: "retry.delay",
1696
- RETRY_COUNT: "retry.count"
2069
+ RETRY_COUNT: "retry.count",
2070
+ LINK_TITLE: "$link.title"
1697
2071
  };
1698
2072
 
1699
2073
  // src/v3/tasks/taskContextManager.ts
@@ -1829,7 +2203,7 @@ __name(getEnvVar, "getEnvVar");
1829
2203
  // src/v3/apiClient/index.ts
1830
2204
  var zodFetchOptions = {
1831
2205
  retry: {
1832
- maxAttempts: 5,
2206
+ maxAttempts: 3,
1833
2207
  minTimeoutInMs: 1e3,
1834
2208
  maxTimeoutInMs: 3e4,
1835
2209
  factor: 2,
@@ -1881,6 +2255,57 @@ var _ApiClient = class _ApiClient {
1881
2255
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1882
2256
  }, zodFetchOptions);
1883
2257
  }
2258
+ createSchedule(options) {
2259
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
2260
+ method: "POST",
2261
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2262
+ body: JSON.stringify(options)
2263
+ });
2264
+ }
2265
+ listSchedules(options) {
2266
+ const searchParams = new URLSearchParams();
2267
+ if (options?.page) {
2268
+ searchParams.append("page", options.page.toString());
2269
+ }
2270
+ if (options?.perPage) {
2271
+ searchParams.append("perPage", options.perPage.toString());
2272
+ }
2273
+ return zodfetch(ListSchedulesResult, `${this.baseUrl}/api/v1/schedules${searchParams.size > 0 ? `?${searchParams}` : ""}`, {
2274
+ method: "GET",
2275
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2276
+ });
2277
+ }
2278
+ retrieveSchedule(scheduleId) {
2279
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2280
+ method: "GET",
2281
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2282
+ });
2283
+ }
2284
+ updateSchedule(scheduleId, options) {
2285
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2286
+ method: "PUT",
2287
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2288
+ body: JSON.stringify(options)
2289
+ });
2290
+ }
2291
+ deactivateSchedule(scheduleId) {
2292
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
2293
+ method: "POST",
2294
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2295
+ });
2296
+ }
2297
+ activateSchedule(scheduleId) {
2298
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
2299
+ method: "POST",
2300
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2301
+ });
2302
+ }
2303
+ deleteSchedule(scheduleId) {
2304
+ return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2305
+ method: "DELETE",
2306
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2307
+ });
2308
+ }
1884
2309
  };
1885
2310
  _getHeaders = new WeakSet();
1886
2311
  getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
@@ -2794,11 +3219,6 @@ __name(unregisterGlobal, "unregisterGlobal");
2794
3219
  var _NoopRuntimeManager = class _NoopRuntimeManager {
2795
3220
  disable() {
2796
3221
  }
2797
- registerTasks() {
2798
- }
2799
- getTaskMetadata(id) {
2800
- return void 0;
2801
- }
2802
3222
  waitForDuration(ms) {
2803
3223
  return Promise.resolve();
2804
3224
  }
@@ -2858,12 +3278,6 @@ var _RuntimeAPI = class _RuntimeAPI {
2858
3278
  __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2859
3279
  unregisterGlobal(API_NAME);
2860
3280
  }
2861
- registerTasks(tasks) {
2862
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).registerTasks(tasks);
2863
- }
2864
- getTaskMetadata(id) {
2865
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).getTaskMetadata(id);
2866
- }
2867
3281
  };
2868
3282
  _getRuntimeManager = new WeakSet();
2869
3283
  getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
@@ -3009,7 +3423,7 @@ var _OtelTaskLogger = class _OtelTaskLogger {
3009
3423
  _emitLog = new WeakSet();
3010
3424
  emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
3011
3425
  let attributes = {
3012
- ...flattenAttributes(properties)
3426
+ ...flattenAttributes(safeJsonProcess(properties))
3013
3427
  };
3014
3428
  const icon = iconStringForSeverity(severityNumber);
3015
3429
  if (icon !== void 0) {
@@ -3046,6 +3460,14 @@ var _NoopTaskLogger = class _NoopTaskLogger {
3046
3460
  };
3047
3461
  __name(_NoopTaskLogger, "NoopTaskLogger");
3048
3462
  var NoopTaskLogger = _NoopTaskLogger;
3463
+ function safeJsonProcess(value) {
3464
+ try {
3465
+ return JSON.parse(JSON.stringify(value));
3466
+ } catch {
3467
+ return value;
3468
+ }
3469
+ }
3470
+ __name(safeJsonProcess, "safeJsonProcess");
3049
3471
 
3050
3472
  // src/v3/logger/index.ts
3051
3473
  var API_NAME3 = "logger";
@@ -3096,6 +3518,78 @@ var LoggerAPI = _LoggerAPI;
3096
3518
  // src/v3/logger-api.ts
3097
3519
  var logger = LoggerAPI.getInstance();
3098
3520
 
3521
+ // src/v3/task-catalog/noopTaskCatalog.ts
3522
+ var _NoopTaskCatalog = class _NoopTaskCatalog {
3523
+ registerTaskMetadata(task) {
3524
+ }
3525
+ registerTaskFileMetadata(id, metadata) {
3526
+ }
3527
+ updateTaskMetadata(id, updates) {
3528
+ }
3529
+ getAllTaskMetadata() {
3530
+ return [];
3531
+ }
3532
+ getTaskMetadata(id) {
3533
+ return void 0;
3534
+ }
3535
+ getTask(id) {
3536
+ return void 0;
3537
+ }
3538
+ disable() {
3539
+ }
3540
+ };
3541
+ __name(_NoopTaskCatalog, "NoopTaskCatalog");
3542
+ var NoopTaskCatalog = _NoopTaskCatalog;
3543
+
3544
+ // src/v3/task-catalog/index.ts
3545
+ var API_NAME4 = "task-catalog";
3546
+ var NOOP_TASK_CATALOG = new NoopTaskCatalog();
3547
+ var _getCatalog, getCatalog_fn;
3548
+ var _TaskCatalogAPI = class _TaskCatalogAPI {
3549
+ constructor() {
3550
+ __privateAdd(this, _getCatalog);
3551
+ }
3552
+ static getInstance() {
3553
+ if (!this._instance) {
3554
+ this._instance = new _TaskCatalogAPI();
3555
+ }
3556
+ return this._instance;
3557
+ }
3558
+ setGlobalTaskCatalog(taskCatalog2) {
3559
+ return registerGlobal(API_NAME4, taskCatalog2);
3560
+ }
3561
+ disable() {
3562
+ unregisterGlobal(API_NAME4);
3563
+ }
3564
+ registerTaskMetadata(task) {
3565
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskMetadata(task);
3566
+ }
3567
+ updateTaskMetadata(id, updates) {
3568
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).updateTaskMetadata(id, updates);
3569
+ }
3570
+ registerTaskFileMetadata(id, metadata) {
3571
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskFileMetadata(id, metadata);
3572
+ }
3573
+ getAllTaskMetadata() {
3574
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getAllTaskMetadata();
3575
+ }
3576
+ getTaskMetadata(id) {
3577
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTaskMetadata(id);
3578
+ }
3579
+ getTask(id) {
3580
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTask(id);
3581
+ }
3582
+ };
3583
+ _getCatalog = new WeakSet();
3584
+ getCatalog_fn = /* @__PURE__ */ __name(function() {
3585
+ return getGlobal(API_NAME4) ?? NOOP_TASK_CATALOG;
3586
+ }, "#getCatalog");
3587
+ __name(_TaskCatalogAPI, "TaskCatalogAPI");
3588
+ var TaskCatalogAPI = _TaskCatalogAPI;
3589
+
3590
+ // src/v3/task-catalog-api.ts
3591
+ var taskCatalog = TaskCatalogAPI.getInstance();
3592
+
3099
3593
  // src/v3/limits.ts
3100
3594
  var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
3101
3595
  var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
@@ -3219,19 +3713,10 @@ var _DevRuntimeManager = class _DevRuntimeManager {
3219
3713
  constructor() {
3220
3714
  __publicField(this, "_taskWaits", /* @__PURE__ */ new Map());
3221
3715
  __publicField(this, "_batchWaits", /* @__PURE__ */ new Map());
3222
- __publicField(this, "_tasks", /* @__PURE__ */ new Map());
3223
3716
  __publicField(this, "_pendingCompletionNotifications", /* @__PURE__ */ new Map());
3224
3717
  }
3225
3718
  disable() {
3226
3719
  }
3227
- registerTasks(tasks) {
3228
- for (const task of tasks) {
3229
- this._tasks.set(task.id, task);
3230
- }
3231
- }
3232
- getTaskMetadata(id) {
3233
- return this._tasks.get(id);
3234
- }
3235
3720
  async waitForDuration(ms) {
3236
3721
  return new Promise((resolve) => {
3237
3722
  setTimeout(resolve, ms);
@@ -3309,18 +3794,9 @@ var _ProdRuntimeManager = class _ProdRuntimeManager {
3309
3794
  this.options = options;
3310
3795
  this._taskWaits = /* @__PURE__ */ new Map();
3311
3796
  this._batchWaits = /* @__PURE__ */ new Map();
3312
- this._tasks = /* @__PURE__ */ new Map();
3313
3797
  }
3314
3798
  disable() {
3315
3799
  }
3316
- registerTasks(tasks) {
3317
- for (const task of tasks) {
3318
- this._tasks.set(task.id, task);
3319
- }
3320
- }
3321
- getTaskMetadata(id) {
3322
- return this._tasks.get(id);
3323
- }
3324
3800
  async waitForDuration(ms) {
3325
3801
  const now = Date.now();
3326
3802
  const resolveAfterDuration = promises.setTimeout(ms, "duration");
@@ -3525,11 +4001,12 @@ __name(_TriggerTracer, "TriggerTracer");
3525
4001
  var TriggerTracer = _TriggerTracer;
3526
4002
  var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
3527
4003
  var _ConsoleInterceptor = class _ConsoleInterceptor {
3528
- constructor(logger2) {
4004
+ constructor(logger2, sendToStdIO) {
3529
4005
  __privateAdd(this, _handleLog);
3530
4006
  __privateAdd(this, _getTimestampInHrTime2);
3531
4007
  __privateAdd(this, _getAttributes);
3532
4008
  this.logger = logger2;
4009
+ this.sendToStdIO = sendToStdIO;
3533
4010
  }
3534
4011
  // Intercept the console and send logs to the OpenTelemetry logger
3535
4012
  // during the execution of the callback
@@ -3538,12 +4015,14 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3538
4015
  log: console2.log,
3539
4016
  info: console2.info,
3540
4017
  warn: console2.warn,
3541
- error: console2.error
4018
+ error: console2.error,
4019
+ debug: console2.debug
3542
4020
  };
3543
4021
  console2.log = this.log.bind(this);
3544
4022
  console2.info = this.info.bind(this);
3545
4023
  console2.warn = this.warn.bind(this);
3546
4024
  console2.error = this.error.bind(this);
4025
+ console2.debug = this.debug.bind(this);
3547
4026
  try {
3548
4027
  return await callback();
3549
4028
  } finally {
@@ -3551,8 +4030,12 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3551
4030
  console2.info = originalConsole.info;
3552
4031
  console2.warn = originalConsole.warn;
3553
4032
  console2.error = originalConsole.error;
4033
+ console2.debug = originalConsole.debug;
3554
4034
  }
3555
4035
  }
4036
+ debug(...args) {
4037
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
4038
+ }
3556
4039
  log(...args) {
3557
4040
  __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
3558
4041
  }
@@ -3569,6 +4052,13 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3569
4052
  _handleLog = new WeakSet();
3570
4053
  handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
3571
4054
  const body = util__default.default.format(...args);
4055
+ if (this.sendToStdIO) {
4056
+ if (severityNumber === apiLogs.SeverityNumber.ERROR) {
4057
+ process.stderr.write(body);
4058
+ } else {
4059
+ process.stdout.write(body);
4060
+ }
4061
+ }
3572
4062
  const parsed = tryParseJSON(body);
3573
4063
  if (parsed.ok) {
3574
4064
  this.logger.emit({
@@ -3644,113 +4134,6 @@ function tryParseJSON(value) {
3644
4134
  }
3645
4135
  __name(tryParseJSON, "tryParseJSON");
3646
4136
 
3647
- // src/retry.ts
3648
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
3649
- if (!resets)
3650
- return;
3651
- switch (format) {
3652
- case "iso_8601_duration_openai_variant": {
3653
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
3654
- }
3655
- case "iso_8601": {
3656
- return calculateISO8601ResetAt(resets, now);
3657
- }
3658
- case "unix_timestamp": {
3659
- return calculateUnixTimestampResetAt(resets, now);
3660
- }
3661
- case "unix_timestamp_in_ms": {
3662
- return calculateUnixTimestampInMsResetAt(resets, now);
3663
- }
3664
- }
3665
- }
3666
- __name(calculateResetAt, "calculateResetAt");
3667
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
3668
- if (!resets)
3669
- return void 0;
3670
- const resetAt = parseInt(resets, 10);
3671
- if (isNaN(resetAt))
3672
- return void 0;
3673
- return new Date(resetAt * 1e3);
3674
- }
3675
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
3676
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
3677
- if (!resets)
3678
- return void 0;
3679
- const resetAt = parseInt(resets, 10);
3680
- if (isNaN(resetAt))
3681
- return void 0;
3682
- return new Date(resetAt);
3683
- }
3684
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
3685
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
3686
- if (!resets)
3687
- return void 0;
3688
- const resetAt = new Date(resets);
3689
- if (isNaN(resetAt.getTime()))
3690
- return void 0;
3691
- return resetAt;
3692
- }
3693
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
3694
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
3695
- if (!resets)
3696
- return void 0;
3697
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
3698
- const match = resets.match(pattern);
3699
- if (!match)
3700
- return void 0;
3701
- const days = parseInt(match[1], 10) || 0;
3702
- const hours = parseInt(match[2], 10) || 0;
3703
- const minutes = parseInt(match[3], 10) || 0;
3704
- const seconds = parseFloat(match[4]) || 0;
3705
- const milliseconds = parseInt(match[5], 10) || 0;
3706
- const resetAt = new Date(now);
3707
- resetAt.setDate(resetAt.getDate() + days);
3708
- resetAt.setHours(resetAt.getHours() + hours);
3709
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
3710
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
3711
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
3712
- return resetAt;
3713
- }
3714
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
3715
-
3716
- // src/v3/utils/retries.ts
3717
- var defaultRetryOptions = {
3718
- maxAttempts: 3,
3719
- factor: 2,
3720
- minTimeoutInMs: 1e3,
3721
- maxTimeoutInMs: 6e4,
3722
- randomize: true
3723
- };
3724
- var defaultFetchRetryOptions = {
3725
- byStatus: {
3726
- "429,408,409,5xx": {
3727
- strategy: "backoff",
3728
- ...defaultRetryOptions
3729
- }
3730
- },
3731
- connectionError: defaultRetryOptions,
3732
- timeout: defaultRetryOptions
3733
- };
3734
- function calculateNextRetryDelay(options, attempt) {
3735
- const opts = {
3736
- ...defaultRetryOptions,
3737
- ...options
3738
- };
3739
- if (attempt >= opts.maxAttempts) {
3740
- return;
3741
- }
3742
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
3743
- const random = randomize ? Math.random() + 1 : 1;
3744
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
3745
- return Math.round(timeout);
3746
- }
3747
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
3748
- function calculateResetAt2(resets, format, now = Date.now()) {
3749
- const resetAt = calculateResetAt(resets, format, new Date(now));
3750
- return resetAt?.getTime();
3751
- }
3752
- __name(calculateResetAt2, "calculateResetAt");
3753
-
3754
4137
  // src/v3/utils/styleAttributes.ts
3755
4138
  function accessoryAttributes(accessory) {
3756
4139
  return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
@@ -4111,6 +4494,7 @@ async function stringifyIO(value) {
4111
4494
  };
4112
4495
  } catch {
4113
4496
  return {
4497
+ data: value,
4114
4498
  dataType: "application/json"
4115
4499
  };
4116
4500
  }
@@ -4155,23 +4539,20 @@ __name(packetRequiresOffloading, "packetRequiresOffloading");
4155
4539
  async function exportPacket(packet, pathPrefix) {
4156
4540
  const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
4157
4541
  const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
4158
- if (presignedResponse.ok) {
4159
- const uploadResponse = await fetch(presignedResponse.data.presignedUrl, {
4160
- method: "PUT",
4161
- headers: {
4162
- "Content-Type": packet.dataType
4163
- },
4164
- body: packet.data
4165
- });
4166
- if (!uploadResponse.ok) {
4167
- throw new Error(`Failed to upload output to ${presignedResponse.data.presignedUrl}: ${uploadResponse.statusText}`);
4168
- }
4169
- return {
4170
- data: filename,
4171
- dataType: "application/store"
4172
- };
4542
+ const uploadResponse = await fetch(presignedResponse.presignedUrl, {
4543
+ method: "PUT",
4544
+ headers: {
4545
+ "Content-Type": packet.dataType
4546
+ },
4547
+ body: packet.data
4548
+ });
4549
+ if (!uploadResponse.ok) {
4550
+ throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
4173
4551
  }
4174
- return packet;
4552
+ return {
4553
+ data: filename,
4554
+ dataType: "application/store"
4555
+ };
4175
4556
  }
4176
4557
  __name(exportPacket, "exportPacket");
4177
4558
  async function conditionallyImportPacket(packet, tracer) {
@@ -4200,19 +4581,16 @@ async function importPacket(packet, span) {
4200
4581
  return packet;
4201
4582
  }
4202
4583
  const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
4203
- if (presignedResponse.ok) {
4204
- const response = await fetch(presignedResponse.data.presignedUrl);
4205
- if (!response.ok) {
4206
- throw new Error(`Failed to import packet ${presignedResponse.data.presignedUrl}: ${response.statusText}`);
4207
- }
4208
- const data = await response.text();
4209
- span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4210
- return {
4211
- data,
4212
- dataType: response.headers.get("content-type") ?? "application/json"
4213
- };
4584
+ const response = await fetch(presignedResponse.presignedUrl);
4585
+ if (!response.ok) {
4586
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
4214
4587
  }
4215
- return packet;
4588
+ const data = await response.text();
4589
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4590
+ return {
4591
+ data,
4592
+ dataType: response.headers.get("content-type") ?? "application/json"
4593
+ };
4216
4594
  }
4217
4595
  __name(importPacket, "importPacket");
4218
4596
  async function createPacketAttributes(packet, dataKey, dataTypeKey) {
@@ -4265,7 +4643,7 @@ async function createPacketAttributesAsJson(data, dataType) {
4265
4643
  case "application/super+json":
4266
4644
  const { deserialize } = await loadSuperJSON();
4267
4645
  const deserialized = deserialize(data);
4268
- const jsonify = safeJsonParse(JSON.stringify(deserialized, safeReplacer));
4646
+ const jsonify = safeJsonParse2(JSON.stringify(deserialized, safeReplacer));
4269
4647
  return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
4270
4648
  case "application/store":
4271
4649
  return data;
@@ -4279,10 +4657,16 @@ async function prettyPrintPacket(rawData, dataType) {
4279
4657
  return "";
4280
4658
  }
4281
4659
  if (dataType === "application/super+json") {
4660
+ if (typeof rawData === "string") {
4661
+ rawData = safeJsonParse2(rawData);
4662
+ }
4282
4663
  const { deserialize } = await loadSuperJSON();
4283
4664
  return await prettyPrintPacket(deserialize(rawData), "application/json");
4284
4665
  }
4285
4666
  if (dataType === "application/json") {
4667
+ if (typeof rawData === "string") {
4668
+ rawData = safeJsonParse2(rawData);
4669
+ }
4286
4670
  return JSON.stringify(rawData, safeReplacer, 2);
4287
4671
  }
4288
4672
  if (typeof rawData === "string") {
@@ -4328,14 +4712,14 @@ async function loadSuperJSON() {
4328
4712
  return await import('superjson');
4329
4713
  }
4330
4714
  __name(loadSuperJSON, "loadSuperJSON");
4331
- function safeJsonParse(value) {
4715
+ function safeJsonParse2(value) {
4332
4716
  try {
4333
4717
  return JSON.parse(value);
4334
4718
  } catch {
4335
4719
  return;
4336
4720
  }
4337
4721
  }
4338
- __name(safeJsonParse, "safeJsonParse");
4722
+ __name(safeJsonParse2, "safeJsonParse");
4339
4723
 
4340
4724
  // src/v3/workers/taskExecutor.ts
4341
4725
  var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
@@ -4607,7 +4991,8 @@ var dependencies = {
4607
4991
  superjson: "^2.2.1",
4608
4992
  ulidx: "^2.2.1",
4609
4993
  zod: "3.22.3",
4610
- "zod-error": "1.5.0"
4994
+ "zod-error": "1.5.0",
4995
+ "zod-validation-error": "^1.5.0"
4611
4996
  };
4612
4997
 
4613
4998
  // src/v3/utils/detectDependencyVersion.ts
@@ -4616,6 +5001,84 @@ function detectDependencyVersion(dependency) {
4616
5001
  }
4617
5002
  __name(detectDependencyVersion, "detectDependencyVersion");
4618
5003
 
5004
+ // src/v3/task-catalog/standardTaskCatalog.ts
5005
+ var _StandardTaskCatalog = class _StandardTaskCatalog {
5006
+ constructor() {
5007
+ __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
5008
+ __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
5009
+ __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
5010
+ }
5011
+ registerTaskMetadata(task) {
5012
+ const { fns, ...metadata } = task;
5013
+ this._taskMetadata.set(task.id, metadata);
5014
+ this._taskFunctions.set(task.id, fns);
5015
+ }
5016
+ updateTaskMetadata(id, updates) {
5017
+ const existingMetadata = this._taskMetadata.get(id);
5018
+ if (existingMetadata) {
5019
+ this._taskMetadata.set(id, {
5020
+ ...existingMetadata,
5021
+ ...updates
5022
+ });
5023
+ }
5024
+ if (updates.fns) {
5025
+ const existingFunctions = this._taskFunctions.get(id);
5026
+ if (existingFunctions) {
5027
+ this._taskFunctions.set(id, {
5028
+ ...existingFunctions,
5029
+ ...updates.fns
5030
+ });
5031
+ }
5032
+ }
5033
+ }
5034
+ registerTaskFileMetadata(id, metadata) {
5035
+ this._taskFileMetadata.set(id, metadata);
5036
+ }
5037
+ // Return all the tasks, without the functions
5038
+ getAllTaskMetadata() {
5039
+ const result = [];
5040
+ for (const [id, metadata] of this._taskMetadata) {
5041
+ const fileMetadata = this._taskFileMetadata.get(id);
5042
+ if (!fileMetadata) {
5043
+ continue;
5044
+ }
5045
+ result.push({
5046
+ ...metadata,
5047
+ ...fileMetadata
5048
+ });
5049
+ }
5050
+ return result;
5051
+ }
5052
+ getTaskMetadata(id) {
5053
+ const metadata = this._taskMetadata.get(id);
5054
+ const fileMetadata = this._taskFileMetadata.get(id);
5055
+ if (!metadata || !fileMetadata) {
5056
+ return void 0;
5057
+ }
5058
+ return {
5059
+ ...metadata,
5060
+ ...fileMetadata
5061
+ };
5062
+ }
5063
+ getTask(id) {
5064
+ const metadata = this._taskMetadata.get(id);
5065
+ const fileMetadata = this._taskFileMetadata.get(id);
5066
+ const fns = this._taskFunctions.get(id);
5067
+ if (!metadata || !fns || !fileMetadata) {
5068
+ return void 0;
5069
+ }
5070
+ return {
5071
+ ...metadata,
5072
+ ...fileMetadata,
5073
+ fns
5074
+ };
5075
+ }
5076
+ disable() {
5077
+ }
5078
+ };
5079
+ __name(_StandardTaskCatalog, "StandardTaskCatalog");
5080
+ var StandardTaskCatalog = _StandardTaskCatalog;
5081
+
4619
5082
  // src/v3/index.ts
4620
5083
  function parseTriggerTaskRequestBody(body) {
4621
5084
  return TriggerTaskRequestBody.safeParse(body);
@@ -4626,12 +5089,16 @@ function parseBatchTriggerTaskRequestBody(body) {
4626
5089
  }
4627
5090
  __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
4628
5091
 
5092
+ exports.APIConnectionError = APIConnectionError;
5093
+ exports.APIError = APIError;
4629
5094
  exports.ApiClient = ApiClient;
4630
5095
  exports.ApiClientManager = ApiClientManager;
5096
+ exports.AuthenticationError = AuthenticationError;
4631
5097
  exports.BackgroundWorkerClientMessages = BackgroundWorkerClientMessages;
4632
5098
  exports.BackgroundWorkerMetadata = BackgroundWorkerMetadata;
4633
5099
  exports.BackgroundWorkerProperties = BackgroundWorkerProperties;
4634
5100
  exports.BackgroundWorkerServerMessages = BackgroundWorkerServerMessages;
5101
+ exports.BadRequestError = BadRequestError;
4635
5102
  exports.BatchTaskRunExecutionResult = BatchTaskRunExecutionResult;
4636
5103
  exports.BatchTriggerTaskRequestBody = BatchTriggerTaskRequestBody;
4637
5104
  exports.BatchTriggerTaskResponse = BatchTriggerTaskResponse;
@@ -4639,13 +5106,16 @@ exports.CanceledRunResponse = CanceledRunResponse;
4639
5106
  exports.CancellationSpanEvent = CancellationSpanEvent;
4640
5107
  exports.ClientToSharedQueueMessages = ClientToSharedQueueMessages;
4641
5108
  exports.Config = Config;
5109
+ exports.ConflictError = ConflictError;
4642
5110
  exports.ConsoleInterceptor = ConsoleInterceptor;
4643
5111
  exports.CoordinatorToPlatformMessages = CoordinatorToPlatformMessages;
4644
5112
  exports.CoordinatorToProdWorkerMessages = CoordinatorToProdWorkerMessages;
4645
5113
  exports.CreateAuthorizationCodeResponseSchema = CreateAuthorizationCodeResponseSchema;
4646
5114
  exports.CreateBackgroundWorkerRequestBody = CreateBackgroundWorkerRequestBody;
4647
5115
  exports.CreateBackgroundWorkerResponse = CreateBackgroundWorkerResponse;
5116
+ exports.CreateScheduleOptions = CreateScheduleOptions;
4648
5117
  exports.CreateUploadPayloadUrlResponseBody = CreateUploadPayloadUrlResponseBody;
5118
+ exports.DeletedScheduleObject = DeletedScheduleObject;
4649
5119
  exports.DeploymentErrorData = DeploymentErrorData;
4650
5120
  exports.DevRuntimeManager = DevRuntimeManager;
4651
5121
  exports.DurableClock = PreciseWallClock;
@@ -4672,9 +5142,13 @@ exports.GetProjectsResponseBody = GetProjectsResponseBody;
4672
5142
  exports.ImageDetailsMetadata = ImageDetailsMetadata;
4673
5143
  exports.InitializeDeploymentRequestBody = InitializeDeploymentRequestBody;
4674
5144
  exports.InitializeDeploymentResponseBody = InitializeDeploymentResponseBody;
5145
+ exports.InternalServerError = InternalServerError;
5146
+ exports.ListScheduleOptions = ListScheduleOptions;
5147
+ exports.ListSchedulesResult = ListSchedulesResult;
4675
5148
  exports.Machine = Machine;
4676
5149
  exports.MachineCpu = MachineCpu;
4677
5150
  exports.MachineMemory = MachineMemory;
5151
+ exports.NotFoundError = NotFoundError;
4678
5152
  exports.OFFLOAD_IO_PACKET_LENGTH_LIMIT = OFFLOAD_IO_PACKET_LENGTH_LIMIT;
4679
5153
  exports.OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT;
4680
5154
  exports.OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT;
@@ -4687,6 +5161,7 @@ exports.OTEL_SPAN_EVENT_COUNT_LIMIT = OTEL_SPAN_EVENT_COUNT_LIMIT;
4687
5161
  exports.OtelTaskLogger = OtelTaskLogger;
4688
5162
  exports.OtherSpanEvent = OtherSpanEvent;
4689
5163
  exports.PRIMARY_VARIANT = PRIMARY_VARIANT;
5164
+ exports.PermissionDeniedError = PermissionDeniedError;
4690
5165
  exports.PlatformToCoordinatorMessages = PlatformToCoordinatorMessages;
4691
5166
  exports.PlatformToProviderMessages = PlatformToProviderMessages;
4692
5167
  exports.PostStartCauses = PostStartCauses;
@@ -4700,9 +5175,12 @@ exports.ProdWorkerToChildMessages = ProdWorkerToChildMessages;
4700
5175
  exports.ProdWorkerToCoordinatorMessages = ProdWorkerToCoordinatorMessages;
4701
5176
  exports.ProviderToPlatformMessages = ProviderToPlatformMessages;
4702
5177
  exports.QueueOptions = QueueOptions;
5178
+ exports.RateLimitError = RateLimitError;
4703
5179
  exports.RateLimitOptions = RateLimitOptions;
4704
5180
  exports.ReplayRunResponse = ReplayRunResponse;
4705
5181
  exports.RetryOptions = RetryOptions;
5182
+ exports.ScheduleObject = ScheduleObject;
5183
+ exports.ScheduledTaskPayload = ScheduledTaskPayload;
4706
5184
  exports.SemanticInternalAttributes = SemanticInternalAttributes;
4707
5185
  exports.SharedQueueToClientMessages = SharedQueueToClientMessages;
4708
5186
  exports.SimpleStructuredLogger = SimpleStructuredLogger;
@@ -4710,11 +5188,13 @@ exports.SlidingWindowRateLimit = SlidingWindowRateLimit;
4710
5188
  exports.SpanEvent = SpanEvent;
4711
5189
  exports.SpanEvents = SpanEvents;
4712
5190
  exports.SpanMessagingEvent = SpanMessagingEvent;
5191
+ exports.StandardTaskCatalog = StandardTaskCatalog;
4713
5192
  exports.StartDeploymentIndexingRequestBody = StartDeploymentIndexingRequestBody;
4714
5193
  exports.StartDeploymentIndexingResponseBody = StartDeploymentIndexingResponseBody;
4715
5194
  exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
4716
5195
  exports.TaskEventStyle = TaskEventStyle;
4717
5196
  exports.TaskExecutor = TaskExecutor;
5197
+ exports.TaskFileMetadata = TaskFileMetadata;
4718
5198
  exports.TaskMetadata = TaskMetadata;
4719
5199
  exports.TaskMetadataFailedToParseData = TaskMetadataFailedToParseData;
4720
5200
  exports.TaskMetadataWithFilePath = TaskMetadataWithFilePath;
@@ -4745,6 +5225,8 @@ exports.TriggerTaskRequestBody = TriggerTaskRequestBody;
4745
5225
  exports.TriggerTaskResponse = TriggerTaskResponse;
4746
5226
  exports.TriggerTracer = TriggerTracer;
4747
5227
  exports.UncaughtExceptionMessage = UncaughtExceptionMessage;
5228
+ exports.UnprocessableEntityError = UnprocessableEntityError;
5229
+ exports.UpdateScheduleOptions = UpdateScheduleOptions;
4748
5230
  exports.WaitReason = WaitReason;
4749
5231
  exports.WhoAmIResponseSchema = WhoAmIResponseSchema;
4750
5232
  exports.ZodIpcConnection = ZodIpcConnection;
@@ -4801,6 +5283,7 @@ exports.runtime = runtime;
4801
5283
  exports.serverWebsocketMessages = serverWebsocketMessages;
4802
5284
  exports.stringPatternMatchers = stringPatternMatchers;
4803
5285
  exports.stringifyIO = stringifyIO;
5286
+ exports.taskCatalog = taskCatalog;
4804
5287
  exports.taskContextManager = taskContextManager;
4805
5288
  exports.unflattenAttributes = unflattenAttributes;
4806
5289
  exports.workerToChildMessages = workerToChildMessages;