@trigger.dev/sdk 3.0.0-beta.5 → 3.0.0-beta.50

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/index.mjs CHANGED
@@ -258,7 +258,7 @@ __name(_Job, "Job");
258
258
  var Job = _Job;
259
259
 
260
260
  // package.json
261
- var version = "3.0.0-beta.5";
261
+ var version = "3.0.0-beta.50";
262
262
 
263
263
  // src/errors.ts
264
264
  var _ResumeWithTaskError = class _ResumeWithTaskError {
@@ -318,6 +318,13 @@ var _AutoYieldWithCompletedTaskExecutionError = class _AutoYieldWithCompletedTas
318
318
  };
319
319
  __name(_AutoYieldWithCompletedTaskExecutionError, "AutoYieldWithCompletedTaskExecutionError");
320
320
  var AutoYieldWithCompletedTaskExecutionError = _AutoYieldWithCompletedTaskExecutionError;
321
+ var _AutoYieldRateLimitError = class _AutoYieldRateLimitError {
322
+ constructor(resetAtTimestamp) {
323
+ this.resetAtTimestamp = resetAtTimestamp;
324
+ }
325
+ };
326
+ __name(_AutoYieldRateLimitError, "AutoYieldRateLimitError");
327
+ var AutoYieldRateLimitError = _AutoYieldRateLimitError;
321
328
  var _ParsedPayloadSchemaError = class _ParsedPayloadSchemaError {
322
329
  constructor(schemaErrors) {
323
330
  this.schemaErrors = schemaErrors;
@@ -326,7 +333,7 @@ var _ParsedPayloadSchemaError = class _ParsedPayloadSchemaError {
326
333
  __name(_ParsedPayloadSchemaError, "ParsedPayloadSchemaError");
327
334
  var ParsedPayloadSchemaError = _ParsedPayloadSchemaError;
328
335
  function isTriggerError(err) {
329
- return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError || err instanceof ResumeWithParallelTaskError;
336
+ return err instanceof ResumeWithTaskError || err instanceof RetryWithTaskError || err instanceof CanceledWithTaskError || err instanceof YieldExecutionError || err instanceof AutoYieldExecutionError || err instanceof AutoYieldWithCompletedTaskExecutionError || err instanceof AutoYieldRateLimitError || err instanceof ResumeWithParallelTaskError;
330
337
  }
331
338
  __name(isTriggerError, "isTriggerError");
332
339
  var _ErrorWithTask = class _ErrorWithTask extends Error {
@@ -569,10 +576,12 @@ var _JSONOutputSerializer = class _JSONOutputSerializer {
569
576
  };
570
577
  __name(_JSONOutputSerializer, "JSONOutputSerializer");
571
578
  var JSONOutputSerializer = _JSONOutputSerializer;
572
- var _addToCachedTasks, addToCachedTasks_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
579
+ var _addToCachedTasks, addToCachedTasks_fn, _doRunTask, doRunTask_fn, _doCompleteTask, doCompleteTask_fn, _detectAutoYield, detectAutoYield_fn, _forceYield, forceYield_fn, _getTimeElapsed, getTimeElapsed_fn, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn;
573
580
  var _IO = class _IO {
574
581
  constructor(options) {
575
582
  __privateAdd(this, _addToCachedTasks);
583
+ __privateAdd(this, _doRunTask);
584
+ __privateAdd(this, _doCompleteTask);
576
585
  __privateAdd(this, _detectAutoYield);
577
586
  __privateAdd(this, _forceYield);
578
587
  __privateAdd(this, _getTimeElapsed);
@@ -1432,15 +1441,17 @@ var _IO = class _IO {
1432
1441
  ...options ?? {},
1433
1442
  parseOutput: void 0
1434
1443
  };
1435
- const response = await this._apiClient.runTask(this._id, {
1444
+ const response = await __privateMethod(this, _doRunTask, doRunTask_fn).call(this, {
1436
1445
  idempotencyKey,
1437
1446
  displayKey: typeof cacheKey === "string" ? cacheKey : void 0,
1438
1447
  noop: false,
1439
1448
  ...runOptions ?? {},
1440
1449
  parentId
1441
- }, {
1442
- cachedTasksCursor: this._cachedTasksCursor
1443
1450
  });
1451
+ if (!response) {
1452
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "failed_task_run");
1453
+ throw new Error("Failed to run task");
1454
+ }
1444
1455
  const task = response.version === API_VERSIONS.LAZY_LOADED_CACHED_TASKS ? response.body.task : response.body;
1445
1456
  if (task.forceYield) {
1446
1457
  this._logger.debug("Forcing yield after run task", {
@@ -1506,10 +1517,14 @@ var _IO = class _IO {
1506
1517
  task
1507
1518
  });
1508
1519
  __privateMethod(this, _detectAutoYield, detectAutoYield_fn).call(this, "before_complete_task", 500, task, output);
1509
- const completedTask = await this._apiClient.completeTask(this._id, task.id, {
1520
+ const completedTask = await __privateMethod(this, _doCompleteTask, doCompleteTask_fn).call(this, task.id, {
1510
1521
  output,
1511
1522
  properties: task.outputProperties ?? void 0
1512
1523
  });
1524
+ if (!completedTask) {
1525
+ __privateMethod(this, _forceYield, forceYield_fn).call(this, "before_complete_task", task, output);
1526
+ throw new Error("Failed to complete task");
1527
+ }
1513
1528
  if (completedTask.forceYield) {
1514
1529
  this._logger.debug("Forcing yield after task completed", {
1515
1530
  idempotencyKey
@@ -1646,12 +1661,36 @@ _addToCachedTasks = new WeakSet();
1646
1661
  addToCachedTasks_fn = /* @__PURE__ */ __name(function(task) {
1647
1662
  this._cachedTasks.set(task.idempotencyKey, task);
1648
1663
  }, "#addToCachedTasks");
1664
+ _doRunTask = new WeakSet();
1665
+ doRunTask_fn = /* @__PURE__ */ __name(async function(task1) {
1666
+ try {
1667
+ return await this._apiClient.runTask(this._id, task1, {
1668
+ cachedTasksCursor: this._cachedTasksCursor
1669
+ });
1670
+ } catch (error) {
1671
+ if (error instanceof AutoYieldRateLimitError) {
1672
+ this._logger.debug("AutoYieldRateLimitError", {
1673
+ error
1674
+ });
1675
+ throw error;
1676
+ }
1677
+ return;
1678
+ }
1679
+ }, "#doRunTask");
1680
+ _doCompleteTask = new WeakSet();
1681
+ doCompleteTask_fn = /* @__PURE__ */ __name(async function(id, task2) {
1682
+ try {
1683
+ return await this._apiClient.completeTask(this._id, id, task2);
1684
+ } catch (error) {
1685
+ return;
1686
+ }
1687
+ }, "#doCompleteTask");
1649
1688
  _detectAutoYield = new WeakSet();
1650
- detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task1, output) {
1689
+ detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500, task3, output) {
1651
1690
  const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1652
1691
  if (timeRemaining && timeRemaining < threshold) {
1653
- if (task1) {
1654
- throw new AutoYieldWithCompletedTaskExecutionError(task1.id, task1.outputProperties ?? [], {
1692
+ if (task3) {
1693
+ throw new AutoYieldWithCompletedTaskExecutionError(task3.id, task3.outputProperties ?? [], {
1655
1694
  location,
1656
1695
  timeRemaining,
1657
1696
  timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
@@ -1662,10 +1701,18 @@ detectAutoYield_fn = /* @__PURE__ */ __name(function(location, threshold = 1500,
1662
1701
  }
1663
1702
  }, "#detectAutoYield");
1664
1703
  _forceYield = new WeakSet();
1665
- forceYield_fn = /* @__PURE__ */ __name(function(location1) {
1704
+ forceYield_fn = /* @__PURE__ */ __name(function(location1, task4, output1) {
1666
1705
  const timeRemaining = __privateMethod(this, _getRemainingTimeInMillis, getRemainingTimeInMillis_fn).call(this);
1667
1706
  if (timeRemaining) {
1668
- throw new AutoYieldExecutionError(location1, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1707
+ if (task4) {
1708
+ throw new AutoYieldWithCompletedTaskExecutionError(task4.id, task4.outputProperties ?? [], {
1709
+ location: location1,
1710
+ timeRemaining,
1711
+ timeElapsed: __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this)
1712
+ }, output1);
1713
+ } else {
1714
+ throw new AutoYieldExecutionError(location1, timeRemaining, __privateMethod(this, _getTimeElapsed, getTimeElapsed_fn).call(this));
1715
+ }
1669
1716
  }
1670
1717
  }, "#forceYield");
1671
1718
  _getTimeElapsed = new WeakSet();
@@ -1835,6 +1882,18 @@ __name(_KeyValueStoreClient, "KeyValueStoreClient");
1835
1882
  var KeyValueStoreClient = _KeyValueStoreClient;
1836
1883
 
1837
1884
  // src/apiClient.ts
1885
+ var _UnknownVersionError = class _UnknownVersionError extends Error {
1886
+ constructor(version2) {
1887
+ super(`Unknown version ${version2}`);
1888
+ }
1889
+ };
1890
+ __name(_UnknownVersionError, "UnknownVersionError");
1891
+ var UnknownVersionError = _UnknownVersionError;
1892
+ var MAX_RETRIES = 8;
1893
+ var EXPONENT_FACTOR = 2;
1894
+ var MIN_DELAY_IN_MS = 80;
1895
+ var MAX_DELAY_IN_MS = 2e3;
1896
+ var JITTER_IN_MS = 50;
1838
1897
  var _apiUrl, _options, _logger, _storeClient, _queryKeyValueStore, queryKeyValueStore_fn, _apiKey, apiKey_fn;
1839
1898
  var _ApiClient = class _ApiClient {
1840
1899
  constructor(options) {
@@ -1877,10 +1936,8 @@ var _ApiClient = class _ApiClient {
1877
1936
  }
1878
1937
  async runTask(runId, task, options = {}) {
1879
1938
  const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
1880
- __privateGet(this, _logger).debug("Running Task", {
1881
- task
1882
- });
1883
- return await zodfetchWithVersions({
1939
+ __privateGet(this, _logger).debug(`[ApiClient] runTask ${task.displayKey}`);
1940
+ return await zodfetchWithVersions(__privateGet(this, _logger), {
1884
1941
  [API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: RunTaskResponseWithCachedTasksBodySchema
1885
1942
  }, ServerTaskSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/tasks`, {
1886
1943
  method: "POST",
@@ -2315,39 +2372,91 @@ function getApiKey(key) {
2315
2372
  };
2316
2373
  }
2317
2374
  __name(getApiKey, "getApiKey");
2318
- async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount = 0) {
2319
- const response = await fetch(url, requestInitWithCache(requestInit));
2320
- if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2321
- return;
2322
- }
2323
- if (response.status >= 400 && response.status < 500) {
2324
- const body = await response.json();
2325
- throw new Error(body.error);
2326
- }
2327
- if (response.status >= 500 && retryCount < 6) {
2328
- const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2329
- await new Promise((resolve) => setTimeout(resolve, delay));
2330
- return zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount + 1);
2331
- }
2332
- if (response.status !== 200) {
2333
- throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2334
- }
2335
- const jsonBody = await response.json();
2336
- const version2 = response.headers.get("trigger-version");
2337
- if (!version2) {
2375
+ async function zodfetchWithVersions(logger, versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount = 0) {
2376
+ try {
2377
+ const fullRequestInit = requestInitWithCache(requestInit);
2378
+ const response = await fetch(url, fullRequestInit);
2379
+ logger.debug(`[ApiClient] zodfetchWithVersions ${url} (attempt ${retryCount + 1})`, {
2380
+ url,
2381
+ retryCount,
2382
+ requestHeaders: fullRequestInit?.headers,
2383
+ responseHeaders: Object.fromEntries(response.headers.entries())
2384
+ });
2385
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2386
+ return;
2387
+ }
2388
+ if (response.status === 429) {
2389
+ const retryAfter = response.headers.get("x-ratelimit-reset");
2390
+ if (retryAfter) {
2391
+ throw new AutoYieldRateLimitError(parseInt(retryAfter));
2392
+ }
2393
+ }
2394
+ if (response.status >= 400 && response.status < 500) {
2395
+ const rawBody = await safeResponseText(response);
2396
+ const body = safeJsonParse(rawBody);
2397
+ logger.error(`[ApiClient] zodfetchWithVersions failed with ${response.status}`, {
2398
+ url,
2399
+ retryCount,
2400
+ requestHeaders: fullRequestInit?.headers,
2401
+ responseHeaders: Object.fromEntries(response.headers.entries()),
2402
+ status: response.status,
2403
+ rawBody
2404
+ });
2405
+ if (body && body.error) {
2406
+ throw new Error(body.error);
2407
+ } else {
2408
+ throw new Error(rawBody);
2409
+ }
2410
+ }
2411
+ if (response.status >= 500 && retryCount < MAX_RETRIES) {
2412
+ const delay = exponentialBackoff(retryCount + 1);
2413
+ await new Promise((resolve) => setTimeout(resolve, delay));
2414
+ return zodfetchWithVersions(logger, versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount + 1);
2415
+ }
2416
+ if (response.status !== 200) {
2417
+ const rawBody = await safeResponseText(response);
2418
+ logger.error(`[ApiClient] zodfetchWithVersions failed with ${response.status}`, {
2419
+ url,
2420
+ retryCount,
2421
+ requestHeaders: fullRequestInit?.headers,
2422
+ responseHeaders: Object.fromEntries(response.headers.entries()),
2423
+ status: response.status,
2424
+ rawBody
2425
+ });
2426
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2427
+ }
2428
+ const jsonBody = await response.json();
2429
+ const version2 = response.headers.get("trigger-version");
2430
+ if (!version2) {
2431
+ return {
2432
+ version: "unversioned",
2433
+ body: unversionedSchema.parse(jsonBody)
2434
+ };
2435
+ }
2436
+ const versionedSchema = versionedSchemaMap[version2];
2437
+ if (!versionedSchema) {
2438
+ throw new UnknownVersionError(version2);
2439
+ }
2338
2440
  return {
2339
- version: "unversioned",
2340
- body: unversionedSchema.parse(jsonBody)
2441
+ version: version2,
2442
+ body: versionedSchema.parse(jsonBody)
2341
2443
  };
2444
+ } catch (error) {
2445
+ if (error instanceof UnknownVersionError || error instanceof AutoYieldRateLimitError) {
2446
+ throw error;
2447
+ }
2448
+ logger.error(`[ApiClient] zodfetchWithVersions failed with a connection error`, {
2449
+ url,
2450
+ retryCount,
2451
+ error
2452
+ });
2453
+ if (retryCount < MAX_RETRIES) {
2454
+ const delay = exponentialBackoff(retryCount + 1);
2455
+ await new Promise((resolve) => setTimeout(resolve, delay));
2456
+ return zodfetchWithVersions(logger, versionedSchemaMap, unversionedSchema, url, requestInit, options, retryCount + 1);
2457
+ }
2458
+ throw error;
2342
2459
  }
2343
- const versionedSchema = versionedSchemaMap[version2];
2344
- if (!versionedSchema) {
2345
- throw new Error(`Unknown version ${version2}`);
2346
- }
2347
- return {
2348
- version: version2,
2349
- body: versionedSchema.parse(jsonBody)
2350
- };
2351
2460
  }
2352
2461
  __name(zodfetchWithVersions, "zodfetchWithVersions");
2353
2462
  function requestInitWithCache(requestInit) {
@@ -2369,8 +2478,8 @@ async function fetchHead(url, requestInitWithoutMethod, retryCount = 0) {
2369
2478
  method: "HEAD"
2370
2479
  };
2371
2480
  const response = await fetch(url, requestInitWithCache(requestInit));
2372
- if (response.status >= 500 && retryCount < 6) {
2373
- const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2481
+ if (response.status >= 500 && retryCount < MAX_RETRIES) {
2482
+ const delay = exponentialBackoff(retryCount + 1);
2374
2483
  await new Promise((resolve) => setTimeout(resolve, delay));
2375
2484
  return fetchHead(url, requestInitWithoutMethod, retryCount + 1);
2376
2485
  }
@@ -2378,32 +2487,66 @@ async function fetchHead(url, requestInitWithoutMethod, retryCount = 0) {
2378
2487
  }
2379
2488
  __name(fetchHead, "fetchHead");
2380
2489
  async function zodfetch(schema, url, requestInit, options, retryCount = 0) {
2381
- const response = await fetch(url, requestInitWithCache(requestInit));
2382
- if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2383
- return;
2384
- }
2385
- if (response.status >= 400 && response.status < 500) {
2386
- const body = await response.json();
2387
- throw new Error(body.error);
2388
- }
2389
- if (response.status >= 500 && retryCount < 6) {
2390
- const delay = exponentialBackoff(retryCount + 1, 2, 50, 1150, 50);
2391
- await new Promise((resolve) => setTimeout(resolve, delay));
2392
- return zodfetch(schema, url, requestInit, options, retryCount + 1);
2393
- }
2394
- if (response.status !== 200) {
2395
- throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2490
+ try {
2491
+ const response = await fetch(url, requestInitWithCache(requestInit));
2492
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
2493
+ return;
2494
+ }
2495
+ if (response.status === 429) {
2496
+ const retryAfter = response.headers.get("x-ratelimit-reset");
2497
+ if (retryAfter) {
2498
+ throw new AutoYieldRateLimitError(parseInt(retryAfter));
2499
+ }
2500
+ }
2501
+ if (response.status >= 400 && response.status < 500) {
2502
+ const body = await response.json();
2503
+ throw new Error(body.error);
2504
+ }
2505
+ if (response.status >= 500 && retryCount < MAX_RETRIES) {
2506
+ const delay = exponentialBackoff(retryCount + 1);
2507
+ await new Promise((resolve) => setTimeout(resolve, delay));
2508
+ return zodfetch(schema, url, requestInit, options, retryCount + 1);
2509
+ }
2510
+ if (response.status !== 200) {
2511
+ throw new Error(options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`);
2512
+ }
2513
+ const jsonBody = await response.json();
2514
+ return schema.parse(jsonBody);
2515
+ } catch (error) {
2516
+ if (error instanceof AutoYieldRateLimitError) {
2517
+ throw error;
2518
+ }
2519
+ if (retryCount < MAX_RETRIES) {
2520
+ const delay = exponentialBackoff(retryCount + 1);
2521
+ await new Promise((resolve) => setTimeout(resolve, delay));
2522
+ return zodfetch(schema, url, requestInit, options, retryCount + 1);
2523
+ }
2524
+ throw error;
2396
2525
  }
2397
- const jsonBody = await response.json();
2398
- return schema.parse(jsonBody);
2399
2526
  }
2400
2527
  __name(zodfetch, "zodfetch");
2401
- function exponentialBackoff(retryCount, exponential, minDelay, maxDelay, jitter) {
2402
- const delay = Math.min(Math.pow(exponential, retryCount) * minDelay, maxDelay);
2403
- const jitterValue = Math.random() * jitter;
2528
+ function exponentialBackoff(retryCount) {
2529
+ const delay = Math.min(Math.pow(EXPONENT_FACTOR, retryCount) * MIN_DELAY_IN_MS, MAX_DELAY_IN_MS);
2530
+ const jitterValue = Math.random() * JITTER_IN_MS;
2404
2531
  return delay + jitterValue;
2405
2532
  }
2406
2533
  __name(exponentialBackoff, "exponentialBackoff");
2534
+ function safeJsonParse(rawBody) {
2535
+ try {
2536
+ return JSON.parse(rawBody);
2537
+ } catch (error) {
2538
+ return;
2539
+ }
2540
+ }
2541
+ __name(safeJsonParse, "safeJsonParse");
2542
+ async function safeResponseText(response) {
2543
+ try {
2544
+ return await response.text();
2545
+ } catch (error) {
2546
+ return "";
2547
+ }
2548
+ }
2549
+ __name(safeResponseText, "safeResponseText");
2407
2550
 
2408
2551
  // src/concurrencyLimit.ts
2409
2552
  var _ConcurrencyLimit = class _ConcurrencyLimit {
@@ -3019,11 +3162,14 @@ var _TriggerClient = class _TriggerClient {
3019
3162
  __publicField(this, "on", __privateGet(this, _eventEmitter).on.bind(__privateGet(this, _eventEmitter)));
3020
3163
  this.id = options.id;
3021
3164
  __privateSet(this, _options4, options);
3022
- __privateSet(this, _client2, new ApiClient(__privateGet(this, _options4)));
3023
3165
  __privateSet(this, _internalLogger, new Logger("trigger.dev", __privateGet(this, _options4).verbose ? "debug" : "log", [
3024
3166
  "output",
3025
3167
  "noopTasksSet"
3026
3168
  ]));
3169
+ __privateSet(this, _client2, new ApiClient({
3170
+ logLevel: __privateGet(this, _options4).verbose ? "debug" : "log",
3171
+ ...__privateGet(this, _options4)
3172
+ }));
3027
3173
  __privateSet(this, _envStore, new KeyValueStore(__privateGet(this, _client2)));
3028
3174
  }
3029
3175
  async handleRequest(request, timeOrigin = performance.now()) {
@@ -3850,6 +3996,12 @@ convertErrorToExecutionResponse_fn = /* @__PURE__ */ __name(function(error, body
3850
3996
  }
3851
3997
  };
3852
3998
  }
3999
+ if (error instanceof AutoYieldRateLimitError) {
4000
+ return {
4001
+ status: "AUTO_YIELD_RATE_LIMIT",
4002
+ reset: error.resetAtTimestamp
4003
+ };
4004
+ }
3853
4005
  if (error instanceof YieldExecutionError) {
3854
4006
  return {
3855
4007
  status: "YIELD_EXECUTION",