@trigger.dev/core 0.0.0-v3-prerelease-20240517090458 → 0.0.0-v3-prerelease-20240606120239

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.
Files changed (57) hide show
  1. package/dist/catalog-XTlJQaMn.d.mts +202 -0
  2. package/dist/catalog-dRKTgwQ7.d.ts +202 -0
  3. package/dist/index.d.mts +60 -1
  4. package/dist/index.d.ts +60 -1
  5. package/dist/index.js +7 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +7 -1
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/{manager-WNMVbgHf.d.mts → manager-JkbddlcO.d.mts} +43 -42
  10. package/dist/{manager-WNMVbgHf.d.ts → manager-JkbddlcO.d.ts} +43 -42
  11. package/dist/{messages-vq7Bk4Ap.d.mts → messages-6_-q72KG.d.mts} +5970 -2067
  12. package/dist/{messages-vq7Bk4Ap.d.ts → messages-6_-q72KG.d.ts} +5970 -2067
  13. package/dist/{catalog-KbyTBoap.d.ts → schemas-r4ZP9S-F.d.mts} +22 -187
  14. package/dist/{catalog-ck7x04PV.d.mts → schemas-r4ZP9S-F.d.ts} +22 -187
  15. package/dist/v3/dev/index.d.mts +2 -2
  16. package/dist/v3/dev/index.d.ts +2 -2
  17. package/dist/v3/dev/index.js +4 -4
  18. package/dist/v3/dev/index.js.map +1 -1
  19. package/dist/v3/dev/index.mjs +4 -4
  20. package/dist/v3/dev/index.mjs.map +1 -1
  21. package/dist/v3/index.d.mts +684 -113
  22. package/dist/v3/index.d.ts +684 -113
  23. package/dist/v3/index.js +1501 -698
  24. package/dist/v3/index.js.map +1 -1
  25. package/dist/v3/index.mjs +1484 -697
  26. package/dist/v3/index.mjs.map +1 -1
  27. package/dist/v3/otel/index.js +1 -1
  28. package/dist/v3/otel/index.js.map +1 -1
  29. package/dist/v3/otel/index.mjs +1 -1
  30. package/dist/v3/otel/index.mjs.map +1 -1
  31. package/dist/v3/prod/index.d.mts +3 -3
  32. package/dist/v3/prod/index.d.ts +3 -3
  33. package/dist/v3/prod/index.js +90 -15
  34. package/dist/v3/prod/index.js.map +1 -1
  35. package/dist/v3/prod/index.mjs +90 -15
  36. package/dist/v3/prod/index.mjs.map +1 -1
  37. package/dist/v3/workers/index.d.mts +6 -5
  38. package/dist/v3/workers/index.d.ts +6 -5
  39. package/dist/v3/workers/index.js +658 -52
  40. package/dist/v3/workers/index.js.map +1 -1
  41. package/dist/v3/workers/index.mjs +658 -52
  42. package/dist/v3/workers/index.mjs.map +1 -1
  43. package/dist/v3/zodNamespace.js +16 -6
  44. package/dist/v3/zodNamespace.js.map +1 -1
  45. package/dist/v3/zodNamespace.mjs +17 -7
  46. package/dist/v3/zodNamespace.mjs.map +1 -1
  47. package/dist/v3/zodSocket.js +16 -6
  48. package/dist/v3/zodSocket.js.map +1 -1
  49. package/dist/v3/zodSocket.mjs +17 -7
  50. package/dist/v3/zodSocket.mjs.map +1 -1
  51. package/dist/v3/zodfetch.d.mts +262 -0
  52. package/dist/v3/zodfetch.d.ts +262 -0
  53. package/dist/v3/zodfetch.js +744 -0
  54. package/dist/v3/zodfetch.js.map +1 -0
  55. package/dist/v3/zodfetch.mjs +716 -0
  56. package/dist/v3/zodfetch.mjs.map +1 -0
  57. package/package.json +15 -6
package/dist/v3/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  'use strict';
2
2
 
3
3
  var api = require('@opentelemetry/api');
4
- var zodValidationError = require('zod-validation-error');
5
4
  var zod = require('zod');
5
+ var zodValidationError = require('zod-validation-error');
6
+ var formDataEncoder = require('form-data-encoder');
7
+ var stream = require('stream');
6
8
  var preciseDate = require('@google-cloud/precise-date');
7
9
  var apiLogs = require('@opentelemetry/api-logs');
8
10
  var humanizeDuration = require('humanize-duration');
@@ -32,423 +34,70 @@ var __privateMethod = (obj, member, method) => {
32
34
  return method;
33
35
  };
34
36
 
35
- // src/v3/apiErrors.ts
36
- var _APIError = class _APIError extends Error {
37
- constructor(status, error, message, headers) {
38
- super(`${_APIError.makeMessage(status, error, message)}`);
39
- this.status = status;
40
- this.headers = headers;
41
- const data = error;
42
- this.error = data;
43
- this.code = data?.["code"];
44
- this.param = data?.["param"];
45
- this.type = data?.["type"];
46
- }
47
- static makeMessage(status, error, message) {
48
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
49
- if (status && msg) {
50
- return `${status} ${msg}`;
51
- }
52
- if (status) {
53
- return `${status} status code (no body)`;
54
- }
55
- if (msg) {
56
- return msg;
57
- }
58
- return "(no status code or body)";
59
- }
60
- static generate(status, errorResponse, message, headers) {
61
- if (!status) {
62
- return new APIConnectionError({
63
- cause: castToError(errorResponse)
64
- });
65
- }
66
- const error = errorResponse?.["error"];
67
- if (status === 400) {
68
- return new BadRequestError(status, error, message, headers);
69
- }
70
- if (status === 401) {
71
- return new AuthenticationError(status, error, message, headers);
72
- }
73
- if (status === 403) {
74
- return new PermissionDeniedError(status, error, message, headers);
75
- }
76
- if (status === 404) {
77
- return new NotFoundError(status, error, message, headers);
78
- }
79
- if (status === 409) {
80
- return new ConflictError(status, error, message, headers);
81
- }
82
- if (status === 422) {
83
- return new UnprocessableEntityError(status, error, message, headers);
84
- }
85
- if (status === 429) {
86
- return new RateLimitError(status, error, message, headers);
87
- }
88
- if (status >= 500) {
89
- return new InternalServerError(status, error, message, headers);
90
- }
91
- return new _APIError(status, error, message, headers);
92
- }
93
- };
94
- __name(_APIError, "APIError");
95
- var APIError = _APIError;
96
- var _APIConnectionError = class _APIConnectionError extends APIError {
97
- constructor({ message, cause }) {
98
- super(void 0, void 0, message || "Connection error.", void 0);
99
- __publicField(this, "status");
100
- if (cause)
101
- this.cause = cause;
102
- }
103
- };
104
- __name(_APIConnectionError, "APIConnectionError");
105
- var APIConnectionError = _APIConnectionError;
106
- var _BadRequestError = class _BadRequestError extends APIError {
107
- constructor() {
108
- super(...arguments);
109
- __publicField(this, "status", 400);
110
- }
111
- };
112
- __name(_BadRequestError, "BadRequestError");
113
- var BadRequestError = _BadRequestError;
114
- var _AuthenticationError = class _AuthenticationError extends APIError {
115
- constructor() {
116
- super(...arguments);
117
- __publicField(this, "status", 401);
118
- }
119
- };
120
- __name(_AuthenticationError, "AuthenticationError");
121
- var AuthenticationError = _AuthenticationError;
122
- var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
123
- constructor() {
124
- super(...arguments);
125
- __publicField(this, "status", 403);
126
- }
127
- };
128
- __name(_PermissionDeniedError, "PermissionDeniedError");
129
- var PermissionDeniedError = _PermissionDeniedError;
130
- var _NotFoundError = class _NotFoundError extends APIError {
131
- constructor() {
132
- super(...arguments);
133
- __publicField(this, "status", 404);
134
- }
135
- };
136
- __name(_NotFoundError, "NotFoundError");
137
- var NotFoundError = _NotFoundError;
138
- var _ConflictError = class _ConflictError extends APIError {
139
- constructor() {
140
- super(...arguments);
141
- __publicField(this, "status", 409);
142
- }
143
- };
144
- __name(_ConflictError, "ConflictError");
145
- var ConflictError = _ConflictError;
146
- var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
147
- constructor() {
148
- super(...arguments);
149
- __publicField(this, "status", 422);
150
- }
151
- };
152
- __name(_UnprocessableEntityError, "UnprocessableEntityError");
153
- var UnprocessableEntityError = _UnprocessableEntityError;
154
- var _RateLimitError = class _RateLimitError extends APIError {
155
- constructor() {
156
- super(...arguments);
157
- __publicField(this, "status", 429);
158
- }
159
- };
160
- __name(_RateLimitError, "RateLimitError");
161
- var RateLimitError = _RateLimitError;
162
- var _InternalServerError = class _InternalServerError extends APIError {
37
+ // package.json
38
+ var version = "0.0.0-v3-prerelease-20240606120239";
39
+ var dependencies = {
40
+ "@google-cloud/precise-date": "^4.0.0",
41
+ "@opentelemetry/api": "^1.8.0",
42
+ "@opentelemetry/api-logs": "^0.48.0",
43
+ "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
44
+ "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
45
+ "@opentelemetry/instrumentation": "^0.49.1",
46
+ "@opentelemetry/resources": "^1.22.0",
47
+ "@opentelemetry/sdk-logs": "^0.49.1",
48
+ "@opentelemetry/sdk-node": "^0.49.1",
49
+ "@opentelemetry/sdk-trace-base": "^1.22.0",
50
+ "@opentelemetry/sdk-trace-node": "^1.22.0",
51
+ "@opentelemetry/semantic-conventions": "^1.22.0",
52
+ "form-data-encoder": "^4.0.2",
53
+ "humanize-duration": "^3.27.3",
54
+ "socket.io-client": "4.7.4",
55
+ superjson: "^2.2.1",
56
+ ulidx: "^2.2.1",
57
+ zod: "3.22.3",
58
+ "zod-error": "1.5.0",
59
+ "zod-validation-error": "^1.5.0"
163
60
  };
164
- __name(_InternalServerError, "InternalServerError");
165
- var InternalServerError = _InternalServerError;
166
- function castToError(err) {
167
- if (err instanceof Error)
168
- return err;
169
- return new Error(err);
170
- }
171
- __name(castToError, "castToError");
172
-
173
- // src/retry.ts
174
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
175
- if (!resets)
176
- return;
177
- switch (format) {
178
- case "iso_8601_duration_openai_variant": {
179
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
180
- }
181
- case "iso_8601": {
182
- return calculateISO8601ResetAt(resets, now);
183
- }
184
- case "unix_timestamp": {
185
- return calculateUnixTimestampResetAt(resets, now);
186
- }
187
- case "unix_timestamp_in_ms": {
188
- return calculateUnixTimestampInMsResetAt(resets, now);
189
- }
190
- }
191
- }
192
- __name(calculateResetAt, "calculateResetAt");
193
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
194
- if (!resets)
195
- return void 0;
196
- const resetAt = parseInt(resets, 10);
197
- if (isNaN(resetAt))
198
- return void 0;
199
- return new Date(resetAt * 1e3);
200
- }
201
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
202
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
203
- if (!resets)
204
- return void 0;
205
- const resetAt = parseInt(resets, 10);
206
- if (isNaN(resetAt))
207
- return void 0;
208
- return new Date(resetAt);
209
- }
210
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
211
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
212
- if (!resets)
213
- return void 0;
214
- const resetAt = new Date(resets);
215
- if (isNaN(resetAt.getTime()))
216
- return void 0;
217
- return resetAt;
218
- }
219
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
220
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
221
- if (!resets)
222
- return void 0;
223
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
224
- const match = resets.match(pattern);
225
- if (!match)
226
- return void 0;
227
- const days = parseInt(match[1], 10) || 0;
228
- const hours = parseInt(match[2], 10) || 0;
229
- const minutes = parseInt(match[3], 10) || 0;
230
- const seconds = parseFloat(match[4]) || 0;
231
- const milliseconds = parseInt(match[5], 10) || 0;
232
- const resetAt = new Date(now);
233
- resetAt.setDate(resetAt.getDate() + days);
234
- resetAt.setHours(resetAt.getHours() + hours);
235
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
236
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
237
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
238
- return resetAt;
239
- }
240
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
241
-
242
- // src/v3/utils/retries.ts
243
- var defaultRetryOptions = {
244
- maxAttempts: 3,
245
- factor: 2,
246
- minTimeoutInMs: 1e3,
247
- maxTimeoutInMs: 6e4,
248
- randomize: true
249
- };
250
- var defaultFetchRetryOptions = {
251
- byStatus: {
252
- "429,408,409,5xx": {
253
- strategy: "backoff",
254
- ...defaultRetryOptions
255
- }
256
- },
257
- connectionError: defaultRetryOptions,
258
- timeout: defaultRetryOptions
259
- };
260
- function calculateNextRetryDelay(options, attempt) {
261
- const opts = {
262
- ...defaultRetryOptions,
263
- ...options
264
- };
265
- if (attempt >= opts.maxAttempts) {
266
- return;
267
- }
268
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
269
- const random = randomize ? Math.random() + 1 : 1;
270
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
271
- return Math.round(timeout);
272
- }
273
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
274
- function calculateResetAt2(resets, format, now = Date.now()) {
275
- const resetAt = calculateResetAt(resets, format, new Date(now));
276
- return resetAt?.getTime();
277
- }
278
- __name(calculateResetAt2, "calculateResetAt");
279
-
280
- // src/v3/zodfetch.ts
281
- var defaultRetryOptions2 = {
282
- maxAttempts: 3,
283
- factor: 2,
284
- minTimeoutInMs: 1e3,
285
- maxTimeoutInMs: 6e4,
286
- randomize: false
287
- };
288
- async function zodfetch(schema, url, requestInit, options) {
289
- return await _doZodFetch(schema, url, requestInit, options);
290
- }
291
- __name(zodfetch, "zodfetch");
292
- async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
293
- try {
294
- const response = await fetch(url, requestInitWithCache(requestInit));
295
- const responseHeaders = createResponseHeaders(response.headers);
296
- if (!response.ok) {
297
- const retryResult = shouldRetry(response, attempt, options?.retry);
298
- if (retryResult.retry) {
299
- await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
300
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
301
- } else {
302
- const errText = await response.text().catch((e) => castToError2(e).message);
303
- const errJSON = safeJsonParse(errText);
304
- const errMessage = errJSON ? void 0 : errText;
305
- throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
306
- }
307
- }
308
- const jsonBody = await response.json();
309
- const parsedResult = schema.safeParse(jsonBody);
310
- if (parsedResult.success) {
311
- return parsedResult.data;
312
- }
313
- throw zodValidationError.fromZodError(parsedResult.error);
314
- } catch (error) {
315
- if (error instanceof APIError) {
316
- throw error;
317
- }
318
- if (options?.retry) {
319
- const retry = {
320
- ...defaultRetryOptions2,
321
- ...options.retry
322
- };
323
- const delay = calculateNextRetryDelay(retry, attempt);
324
- if (delay) {
325
- await new Promise((resolve) => setTimeout(resolve, delay));
326
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
327
- }
328
- }
329
- throw new APIConnectionError({
330
- cause: castToError2(error)
331
- });
332
- }
333
- }
334
- __name(_doZodFetch, "_doZodFetch");
335
- function castToError2(err) {
336
- if (err instanceof Error)
337
- return err;
338
- return new Error(err);
339
- }
340
- __name(castToError2, "castToError");
341
- function shouldRetry(response, attempt, retryOptions) {
342
- function shouldRetryForOptions() {
343
- const retry = {
344
- ...defaultRetryOptions2,
345
- ...retryOptions
346
- };
347
- const delay = calculateNextRetryDelay(retry, attempt);
348
- if (delay) {
349
- return {
350
- retry: true,
351
- delay
352
- };
353
- } else {
354
- return {
355
- retry: false
356
- };
357
- }
358
- }
359
- __name(shouldRetryForOptions, "shouldRetryForOptions");
360
- const shouldRetryHeader = response.headers.get("x-should-retry");
361
- if (shouldRetryHeader === "true")
362
- return shouldRetryForOptions();
363
- if (shouldRetryHeader === "false")
364
- return {
365
- retry: false
366
- };
367
- if (response.status === 408)
368
- return shouldRetryForOptions();
369
- if (response.status === 409)
370
- return shouldRetryForOptions();
371
- if (response.status === 429)
372
- return shouldRetryForOptions();
373
- if (response.status >= 500)
374
- return shouldRetryForOptions();
375
- return {
376
- retry: false
377
- };
378
- }
379
- __name(shouldRetry, "shouldRetry");
380
- function safeJsonParse(text) {
381
- try {
382
- return JSON.parse(text);
383
- } catch (e) {
384
- return void 0;
385
- }
386
- }
387
- __name(safeJsonParse, "safeJsonParse");
388
- function createResponseHeaders(headers) {
389
- return new Proxy(Object.fromEntries(
390
- // @ts-ignore
391
- headers.entries()
392
- ), {
393
- get(target, name) {
394
- const key = name.toString();
395
- return target[key.toLowerCase()] || target[key];
396
- }
397
- });
398
- }
399
- __name(createResponseHeaders, "createResponseHeaders");
400
- function requestInitWithCache(requestInit) {
401
- try {
402
- const withCache = {
403
- ...requestInit,
404
- cache: "no-cache"
405
- };
406
- const _ = new Request("http://localhost", withCache);
407
- return withCache;
408
- } catch (error) {
409
- return requestInit ?? {};
410
- }
411
- }
412
- __name(requestInitWithCache, "requestInitWithCache");
413
- var CreateAuthorizationCodeResponseSchema = zod.z.object({
414
- url: zod.z.string().url(),
415
- authorizationCode: zod.z.string()
416
- });
417
- var GetPersonalAccessTokenRequestSchema = zod.z.object({
418
- authorizationCode: zod.z.string()
419
- });
420
- var GetPersonalAccessTokenResponseSchema = zod.z.object({
421
- token: zod.z.object({
422
- token: zod.z.string(),
423
- obfuscatedToken: zod.z.string()
424
- }).nullable()
425
- });
426
- var TaskRunBuiltInError = zod.z.object({
427
- type: zod.z.literal("BUILT_IN_ERROR"),
428
- name: zod.z.string(),
429
- message: zod.z.string(),
430
- stackTrace: zod.z.string()
431
- });
432
- var TaskRunCustomErrorObject = zod.z.object({
433
- type: zod.z.literal("CUSTOM_ERROR"),
434
- raw: zod.z.string()
435
- });
436
- var TaskRunStringError = zod.z.object({
437
- type: zod.z.literal("STRING_ERROR"),
438
- raw: zod.z.string()
439
- });
440
- var TaskRunErrorCodes = {
441
- COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
442
- COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
443
- CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
444
- TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
445
- TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
446
- TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
447
- TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
448
- TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
449
- TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
450
- HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
451
- GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
61
+ var CreateAuthorizationCodeResponseSchema = zod.z.object({
62
+ url: zod.z.string().url(),
63
+ authorizationCode: zod.z.string()
64
+ });
65
+ var GetPersonalAccessTokenRequestSchema = zod.z.object({
66
+ authorizationCode: zod.z.string()
67
+ });
68
+ var GetPersonalAccessTokenResponseSchema = zod.z.object({
69
+ token: zod.z.object({
70
+ token: zod.z.string(),
71
+ obfuscatedToken: zod.z.string()
72
+ }).nullable()
73
+ });
74
+ var TaskRunBuiltInError = zod.z.object({
75
+ type: zod.z.literal("BUILT_IN_ERROR"),
76
+ name: zod.z.string(),
77
+ message: zod.z.string(),
78
+ stackTrace: zod.z.string()
79
+ });
80
+ var TaskRunCustomErrorObject = zod.z.object({
81
+ type: zod.z.literal("CUSTOM_ERROR"),
82
+ raw: zod.z.string()
83
+ });
84
+ var TaskRunStringError = zod.z.object({
85
+ type: zod.z.literal("STRING_ERROR"),
86
+ raw: zod.z.string()
87
+ });
88
+ var TaskRunErrorCodes = {
89
+ COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
90
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
91
+ CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
92
+ TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
93
+ TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
94
+ TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
95
+ TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
96
+ TASK_PROCESS_SIGKILL_TIMEOUT: "TASK_PROCESS_SIGKILL_TIMEOUT",
97
+ TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
98
+ TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
99
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
100
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
452
101
  };
453
102
  var TaskRunInternalError = zod.z.object({
454
103
  type: zod.z.literal("INTERNAL_ERROR"),
@@ -460,10 +109,12 @@ var TaskRunInternalError = zod.z.object({
460
109
  "TASK_EXECUTION_FAILED",
461
110
  "TASK_EXECUTION_ABORTED",
462
111
  "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
112
+ "TASK_PROCESS_SIGKILL_TIMEOUT",
463
113
  "TASK_RUN_CANCELLED",
464
114
  "TASK_OUTPUT_ERROR",
465
115
  "HANDLE_ERROR_ERROR",
466
- "GRACEFUL_EXIT_TIMEOUT"
116
+ "GRACEFUL_EXIT_TIMEOUT",
117
+ "TASK_RUN_HEARTBEAT_TIMEOUT"
467
118
  ]),
468
119
  message: zod.z.string().optional()
469
120
  });
@@ -725,7 +376,16 @@ var TaskFileMetadata = zod.z.object({
725
376
  filePath: zod.z.string(),
726
377
  exportName: zod.z.string()
727
378
  });
728
- var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
379
+ var TaskMetadataWithFilePath = zod.z.object({
380
+ id: zod.z.string(),
381
+ packageVersion: zod.z.string(),
382
+ queue: QueueOptions.optional(),
383
+ retry: RetryOptions.optional(),
384
+ machine: Machine.partial().optional(),
385
+ triggerSource: zod.z.string().optional(),
386
+ filePath: zod.z.string(),
387
+ exportName: zod.z.string()
388
+ });
729
389
  var PostStartCauses = zod.z.enum([
730
390
  "index",
731
391
  "create",
@@ -766,6 +426,13 @@ var WaitReason = zod.z.enum([
766
426
  "WAIT_FOR_TASK",
767
427
  "WAIT_FOR_BATCH"
768
428
  ]);
429
+ var TaskRunExecutionLazyAttemptPayload = zod.z.object({
430
+ runId: zod.z.string(),
431
+ messageId: zod.z.string(),
432
+ isTest: zod.z.boolean(),
433
+ traceContext: zod.z.record(zod.z.unknown()),
434
+ environment: zod.z.record(zod.z.string()).optional()
435
+ });
769
436
 
770
437
  // src/v3/schemas/resources.ts
771
438
  var TaskResource = zod.z.object({
@@ -787,57 +454,204 @@ var ImageDetailsMetadata = zod.z.object({
787
454
  contentHash: zod.z.string(),
788
455
  imageTag: zod.z.string()
789
456
  });
790
-
791
- // src/v3/schemas/api.ts
792
- var WhoAmIResponseSchema = zod.z.object({
793
- userId: zod.z.string(),
794
- email: zod.z.string().email(),
795
- dashboardUrl: zod.z.string()
796
- });
797
- var GetProjectResponseBody = zod.z.object({
798
- id: zod.z.string(),
799
- externalRef: zod.z.string(),
800
- name: zod.z.string(),
801
- slug: zod.z.string(),
802
- createdAt: zod.z.coerce.date(),
803
- organization: zod.z.object({
804
- id: zod.z.string(),
805
- title: zod.z.string(),
806
- slug: zod.z.string(),
807
- createdAt: zod.z.coerce.date()
808
- })
809
- });
810
- var GetProjectsResponseBody = zod.z.array(GetProjectResponseBody);
811
- var GetProjectEnvResponse = zod.z.object({
812
- apiKey: zod.z.string(),
813
- name: zod.z.string(),
814
- apiUrl: zod.z.string()
815
- });
816
- var CreateBackgroundWorkerRequestBody = zod.z.object({
817
- localOnly: zod.z.boolean(),
818
- metadata: BackgroundWorkerMetadata
819
- });
820
- var CreateBackgroundWorkerResponse = zod.z.object({
821
- id: zod.z.string(),
822
- version: zod.z.string(),
823
- contentHash: zod.z.string()
824
- });
825
- var TriggerTaskRequestBody = zod.z.object({
826
- payload: zod.z.any(),
827
- context: zod.z.any(),
828
- options: zod.z.object({
829
- dependentAttempt: zod.z.string().optional(),
830
- dependentBatch: zod.z.string().optional(),
831
- lockToVersion: zod.z.string().optional(),
832
- queue: QueueOptions.optional(),
833
- concurrencyKey: zod.z.string().optional(),
834
- idempotencyKey: zod.z.string().optional(),
835
- test: zod.z.boolean().optional(),
836
- payloadType: zod.z.string().optional()
837
- }).optional()
838
- });
839
- var TriggerTaskResponse = zod.z.object({
840
- id: zod.z.string()
457
+ function parseError(error) {
458
+ if (error instanceof Error) {
459
+ return {
460
+ type: "BUILT_IN_ERROR",
461
+ name: error.name,
462
+ message: error.message,
463
+ stackTrace: error.stack ?? ""
464
+ };
465
+ }
466
+ if (typeof error === "string") {
467
+ return {
468
+ type: "STRING_ERROR",
469
+ raw: error
470
+ };
471
+ }
472
+ try {
473
+ return {
474
+ type: "CUSTOM_ERROR",
475
+ raw: JSON.stringify(error)
476
+ };
477
+ } catch (e) {
478
+ return {
479
+ type: "CUSTOM_ERROR",
480
+ raw: String(error)
481
+ };
482
+ }
483
+ }
484
+ __name(parseError, "parseError");
485
+ function createErrorTaskError(error) {
486
+ switch (error.type) {
487
+ case "BUILT_IN_ERROR": {
488
+ const e = new Error(error.message);
489
+ e.name = error.name;
490
+ e.stack = error.stackTrace;
491
+ return e;
492
+ }
493
+ case "STRING_ERROR": {
494
+ return error.raw;
495
+ }
496
+ case "CUSTOM_ERROR": {
497
+ return JSON.parse(error.raw);
498
+ }
499
+ case "INTERNAL_ERROR": {
500
+ return new Error(`trigger.dev internal error (${error.code})`);
501
+ }
502
+ }
503
+ }
504
+ __name(createErrorTaskError, "createErrorTaskError");
505
+ var SerializedError = zod.z.object({
506
+ message: zod.z.string(),
507
+ name: zod.z.string().optional(),
508
+ stackTrace: zod.z.string().optional()
509
+ });
510
+ function createJsonErrorObject(error) {
511
+ switch (error.type) {
512
+ case "BUILT_IN_ERROR": {
513
+ return {
514
+ name: error.name,
515
+ message: error.message,
516
+ stackTrace: error.stackTrace
517
+ };
518
+ }
519
+ case "STRING_ERROR": {
520
+ return {
521
+ message: error.raw
522
+ };
523
+ }
524
+ case "CUSTOM_ERROR": {
525
+ return {
526
+ message: error.raw
527
+ };
528
+ }
529
+ case "INTERNAL_ERROR": {
530
+ return {
531
+ message: `trigger.dev internal error (${error.code})`
532
+ };
533
+ }
534
+ }
535
+ }
536
+ __name(createJsonErrorObject, "createJsonErrorObject");
537
+ function correctErrorStackTrace(stackTrace, projectDir, options) {
538
+ const [errorLine, ...traceLines] = stackTrace.split("\n");
539
+ return [
540
+ options?.removeFirstLine ? void 0 : errorLine,
541
+ ...traceLines.map((line) => correctStackTraceLine(line, projectDir, options?.isDev))
542
+ ].filter(Boolean).join("\n");
543
+ }
544
+ __name(correctErrorStackTrace, "correctErrorStackTrace");
545
+ var LINES_TO_IGNORE = [
546
+ /ConsoleInterceptor/,
547
+ /TriggerTracer/,
548
+ /TaskExecutor/,
549
+ /EXECUTE_TASK_RUN/,
550
+ /@trigger.dev\/core/,
551
+ /packages\/core\/src\/v3/,
552
+ /safeJsonProcess/,
553
+ /__entryPoint.ts/,
554
+ /ZodIpc/,
555
+ /startActiveSpan/,
556
+ /processTicksAndRejections/
557
+ ];
558
+ function correctStackTraceLine(line, projectDir, isDev) {
559
+ if (LINES_TO_IGNORE.some((regex) => regex.test(line))) {
560
+ return;
561
+ }
562
+ if (isDev && projectDir && !line.includes(projectDir)) {
563
+ return;
564
+ }
565
+ return line.trim();
566
+ }
567
+ __name(correctStackTraceLine, "correctStackTraceLine");
568
+ function groupTaskMetadataIssuesByTask(tasks, issues) {
569
+ return issues.reduce((acc, issue) => {
570
+ if (issue.path.length === 0) {
571
+ return acc;
572
+ }
573
+ const taskIndex = issue.path[1];
574
+ if (typeof taskIndex !== "number") {
575
+ return acc;
576
+ }
577
+ const task = tasks[taskIndex];
578
+ if (!task) {
579
+ return acc;
580
+ }
581
+ const restOfPath = issue.path.slice(2);
582
+ const taskId = task.id;
583
+ const taskName = task.exportName;
584
+ const filePath = task.filePath;
585
+ const key = taskIndex;
586
+ const existing = acc[key] ?? {
587
+ id: taskId,
588
+ exportName: taskName,
589
+ filePath,
590
+ issues: []
591
+ };
592
+ existing.issues.push({
593
+ message: issue.message,
594
+ path: restOfPath.length === 0 ? void 0 : restOfPath.join(".")
595
+ });
596
+ return {
597
+ ...acc,
598
+ [key]: existing
599
+ };
600
+ }, {});
601
+ }
602
+ __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
603
+
604
+ // src/v3/schemas/api.ts
605
+ var WhoAmIResponseSchema = zod.z.object({
606
+ userId: zod.z.string(),
607
+ email: zod.z.string().email(),
608
+ dashboardUrl: zod.z.string()
609
+ });
610
+ var GetProjectResponseBody = zod.z.object({
611
+ id: zod.z.string(),
612
+ externalRef: zod.z.string(),
613
+ name: zod.z.string(),
614
+ slug: zod.z.string(),
615
+ createdAt: zod.z.coerce.date(),
616
+ organization: zod.z.object({
617
+ id: zod.z.string(),
618
+ title: zod.z.string(),
619
+ slug: zod.z.string(),
620
+ createdAt: zod.z.coerce.date()
621
+ })
622
+ });
623
+ var GetProjectsResponseBody = zod.z.array(GetProjectResponseBody);
624
+ var GetProjectEnvResponse = zod.z.object({
625
+ apiKey: zod.z.string(),
626
+ name: zod.z.string(),
627
+ apiUrl: zod.z.string()
628
+ });
629
+ var CreateBackgroundWorkerRequestBody = zod.z.object({
630
+ localOnly: zod.z.boolean(),
631
+ metadata: BackgroundWorkerMetadata,
632
+ supportsLazyAttempts: zod.z.boolean().optional()
633
+ });
634
+ var CreateBackgroundWorkerResponse = zod.z.object({
635
+ id: zod.z.string(),
636
+ version: zod.z.string(),
637
+ contentHash: zod.z.string()
638
+ });
639
+ var TriggerTaskRequestBody = zod.z.object({
640
+ payload: zod.z.any(),
641
+ context: zod.z.any(),
642
+ options: zod.z.object({
643
+ dependentAttempt: zod.z.string().optional(),
644
+ dependentBatch: zod.z.string().optional(),
645
+ lockToVersion: zod.z.string().optional(),
646
+ queue: QueueOptions.optional(),
647
+ concurrencyKey: zod.z.string().optional(),
648
+ idempotencyKey: zod.z.string().optional(),
649
+ test: zod.z.boolean().optional(),
650
+ payloadType: zod.z.string().optional()
651
+ }).optional()
652
+ });
653
+ var TriggerTaskResponse = zod.z.object({
654
+ id: zod.z.string()
841
655
  });
842
656
  var BatchTriggerTaskRequestBody = zod.z.object({
843
657
  items: TriggerTaskRequestBody.array(),
@@ -928,7 +742,7 @@ var ReplayRunResponse = zod.z.object({
928
742
  id: zod.z.string()
929
743
  });
930
744
  var CanceledRunResponse = zod.z.object({
931
- message: zod.z.string()
745
+ id: zod.z.string()
932
746
  });
933
747
  var ScheduledTaskPayload = zod.z.object({
934
748
  /** The schedule id associated with this run (you can have many schedules for the same task).
@@ -978,17 +792,18 @@ var CreateScheduleOptions = zod.z.object({
978
792
  externalId: zod.z.string().optional()
979
793
  });
980
794
  var UpdateScheduleOptions = CreateScheduleOptions;
795
+ var ScheduleGenerator = zod.z.object({
796
+ type: zod.z.literal("CRON"),
797
+ expression: zod.z.string(),
798
+ description: zod.z.string()
799
+ });
981
800
  var ScheduleObject = zod.z.object({
982
801
  id: zod.z.string(),
983
802
  task: zod.z.string(),
984
803
  active: zod.z.boolean(),
985
804
  deduplicationKey: zod.z.string().nullish(),
986
805
  externalId: zod.z.string().nullish(),
987
- generator: zod.z.object({
988
- type: zod.z.literal("CRON"),
989
- expression: zod.z.string(),
990
- description: zod.z.string()
991
- }),
806
+ generator: ScheduleGenerator,
992
807
  nextRun: zod.z.coerce.date().nullish(),
993
808
  environments: zod.z.array(zod.z.object({
994
809
  id: zod.z.string(),
@@ -1012,12 +827,28 @@ var ListScheduleOptions = zod.z.object({
1012
827
  perPage: zod.z.number().optional()
1013
828
  });
1014
829
  var RunStatus = zod.z.enum([
1015
- "PENDING",
830
+ /// Task hasn't been deployed yet but is waiting to be executed
831
+ "WAITING_FOR_DEPLOY",
832
+ /// Task is waiting to be executed by a worker
833
+ "QUEUED",
834
+ /// Task is currently being executed by a worker
1016
835
  "EXECUTING",
1017
- "PAUSED",
836
+ /// Task has failed and is waiting to be retried
837
+ "REATTEMPTING",
838
+ /// Task has been paused by the system, and will be resumed by the system
839
+ "FROZEN",
840
+ /// Task has been completed successfully
1018
841
  "COMPLETED",
842
+ /// Task has been canceled by the user
843
+ "CANCELED",
844
+ /// Task has been completed with errors
1019
845
  "FAILED",
1020
- "CANCELED"
846
+ /// Task has crashed and won't be retried, most likely the worker ran out of resources, e.g. memory or storage
847
+ "CRASHED",
848
+ /// Task was interrupted during execution, mostly this happens in development environments
849
+ "INTERRUPTED",
850
+ /// Task has failed to complete, due to an error in the system
851
+ "SYSTEM_FAILURE"
1021
852
  ]);
1022
853
  var AttemptStatus = zod.z.enum([
1023
854
  "PENDING",
@@ -1027,23 +858,83 @@ var AttemptStatus = zod.z.enum([
1027
858
  "FAILED",
1028
859
  "CANCELED"
1029
860
  ]);
1030
- var RetrieveRunResponse = zod.z.object({
861
+ var RunEnvironmentDetails = zod.z.object({
862
+ id: zod.z.string(),
863
+ name: zod.z.string(),
864
+ user: zod.z.string().optional()
865
+ });
866
+ var RunScheduleDetails = zod.z.object({
867
+ id: zod.z.string(),
868
+ externalId: zod.z.string().optional(),
869
+ deduplicationKey: zod.z.string().optional(),
870
+ generator: ScheduleGenerator
871
+ });
872
+ var CommonRunFields = {
1031
873
  id: zod.z.string(),
1032
874
  status: RunStatus,
1033
875
  taskIdentifier: zod.z.string(),
1034
876
  idempotencyKey: zod.z.string().optional(),
1035
877
  version: zod.z.string().optional(),
878
+ isQueued: zod.z.boolean(),
879
+ isExecuting: zod.z.boolean(),
880
+ isCompleted: zod.z.boolean(),
881
+ isSuccess: zod.z.boolean(),
882
+ isFailed: zod.z.boolean(),
883
+ isCancelled: zod.z.boolean(),
884
+ isTest: zod.z.boolean(),
1036
885
  createdAt: zod.z.coerce.date(),
1037
886
  updatedAt: zod.z.coerce.date(),
887
+ startedAt: zod.z.coerce.date().optional(),
888
+ finishedAt: zod.z.coerce.date().optional()
889
+ };
890
+ var RetrieveRunResponse = zod.z.object({
891
+ ...CommonRunFields,
892
+ payload: zod.z.any().optional(),
893
+ output: zod.z.any().optional(),
894
+ schedule: RunScheduleDetails.optional(),
1038
895
  attempts: zod.z.array(zod.z.object({
1039
896
  id: zod.z.string(),
1040
897
  status: AttemptStatus,
1041
898
  createdAt: zod.z.coerce.date(),
1042
899
  updatedAt: zod.z.coerce.date(),
1043
900
  startedAt: zod.z.coerce.date().optional(),
1044
- completedAt: zod.z.coerce.date().optional()
901
+ completedAt: zod.z.coerce.date().optional(),
902
+ error: SerializedError.optional()
1045
903
  }).optional())
1046
904
  });
905
+ var ListRunResponseItem = zod.z.object({
906
+ ...CommonRunFields,
907
+ env: RunEnvironmentDetails
908
+ });
909
+ var ListRunResponse = zod.z.object({
910
+ data: zod.z.array(ListRunResponseItem),
911
+ pagination: zod.z.object({
912
+ next: zod.z.string().optional(),
913
+ previous: zod.z.string().optional()
914
+ })
915
+ });
916
+ var CreateEnvironmentVariableRequestBody = zod.z.object({
917
+ name: zod.z.string(),
918
+ value: zod.z.string()
919
+ });
920
+ var UpdateEnvironmentVariableRequestBody = zod.z.object({
921
+ value: zod.z.string()
922
+ });
923
+ var ImportEnvironmentVariablesRequestBody = zod.z.object({
924
+ variables: zod.z.record(zod.z.string()),
925
+ override: zod.z.boolean().optional()
926
+ });
927
+ var EnvironmentVariableResponseBody = zod.z.object({
928
+ success: zod.z.boolean()
929
+ });
930
+ var EnvironmentVariableValue = zod.z.object({
931
+ value: zod.z.string()
932
+ });
933
+ var EnvironmentVariable = zod.z.object({
934
+ name: zod.z.string(),
935
+ value: zod.z.string()
936
+ });
937
+ var EnvironmentVariables = zod.z.array(EnvironmentVariable);
1047
938
  var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
1048
939
  zod.z.object({
1049
940
  type: zod.z.literal("EXECUTE_RUNS"),
@@ -1060,12 +951,16 @@ var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
1060
951
  version: zod.z.string(),
1061
952
  machine: Machine,
1062
953
  // identifiers
1063
- id: zod.z.string(),
954
+ id: zod.z.string().optional(),
1064
955
  envId: zod.z.string(),
1065
956
  envType: EnvironmentType,
1066
957
  orgId: zod.z.string(),
1067
958
  projectId: zod.z.string(),
1068
959
  runId: zod.z.string()
960
+ }),
961
+ zod.z.object({
962
+ type: zod.z.literal("EXECUTE_RUN_LAZY_ATTEMPT"),
963
+ payload: TaskRunExecutionLazyAttemptPayload
1069
964
  })
1070
965
  ]);
1071
966
  var serverWebsocketMessages = {
@@ -1086,10 +981,20 @@ var BackgroundWorkerClientMessages = zod.z.discriminatedUnion("type", [
1086
981
  completion: TaskRunExecutionResult,
1087
982
  execution: TaskRunExecution
1088
983
  }),
984
+ zod.z.object({
985
+ version: zod.z.literal("v1").default("v1"),
986
+ type: zod.z.literal("TASK_RUN_FAILED_TO_RUN"),
987
+ completion: TaskRunFailedExecutionResult
988
+ }),
1089
989
  zod.z.object({
1090
990
  version: zod.z.literal("v1").default("v1"),
1091
991
  type: zod.z.literal("TASK_HEARTBEAT"),
1092
992
  id: zod.z.string()
993
+ }),
994
+ zod.z.object({
995
+ version: zod.z.literal("v1").default("v1"),
996
+ type: zod.z.literal("TASK_RUN_HEARTBEAT"),
997
+ id: zod.z.string()
1093
998
  })
1094
999
  ]);
1095
1000
  var BackgroundWorkerProperties = zod.z.object({
@@ -1100,7 +1005,8 @@ var BackgroundWorkerProperties = zod.z.object({
1100
1005
  var clientWebsocketMessages = {
1101
1006
  READY_FOR_TASKS: zod.z.object({
1102
1007
  version: zod.z.literal("v1").default("v1"),
1103
- backgroundWorkerId: zod.z.string()
1008
+ backgroundWorkerId: zod.z.string(),
1009
+ inProgressRuns: zod.z.string().array().optional()
1104
1010
  }),
1105
1011
  BACKGROUND_WORKER_DEPRECATED: zod.z.object({
1106
1012
  version: zod.z.literal("v1").default("v1"),
@@ -1119,11 +1025,17 @@ var workerToChildMessages = {
1119
1025
  traceContext: zod.z.record(zod.z.unknown()),
1120
1026
  metadata: BackgroundWorkerProperties
1121
1027
  }),
1122
- TASK_RUN_COMPLETED_NOTIFICATION: zod.z.object({
1123
- version: zod.z.literal("v1").default("v1"),
1124
- completion: TaskRunExecutionResult,
1125
- execution: TaskRunExecution
1126
- }),
1028
+ TASK_RUN_COMPLETED_NOTIFICATION: zod.z.discriminatedUnion("version", [
1029
+ zod.z.object({
1030
+ version: zod.z.literal("v1"),
1031
+ completion: TaskRunExecutionResult,
1032
+ execution: TaskRunExecution
1033
+ }),
1034
+ zod.z.object({
1035
+ version: zod.z.literal("v2"),
1036
+ completion: TaskRunExecutionResult
1037
+ })
1038
+ ]),
1127
1039
  CLEANUP: zod.z.object({
1128
1040
  version: zod.z.literal("v1").default("v1"),
1129
1041
  flush: zod.z.boolean().default(false),
@@ -1164,6 +1076,10 @@ var childToWorkerMessages = {
1164
1076
  version: zod.z.literal("v1").default("v1"),
1165
1077
  id: zod.z.string()
1166
1078
  }),
1079
+ TASK_RUN_HEARTBEAT: zod.z.object({
1080
+ version: zod.z.literal("v1").default("v1"),
1081
+ id: zod.z.string()
1082
+ }),
1167
1083
  READY_TO_DISPOSE: zod.z.undefined(),
1168
1084
  WAIT_FOR_DURATION: zod.z.object({
1169
1085
  version: zod.z.literal("v1").default("v1"),
@@ -1203,6 +1119,12 @@ var ProdChildToWorkerMessages = {
1203
1119
  id: zod.z.string()
1204
1120
  })
1205
1121
  },
1122
+ TASK_RUN_HEARTBEAT: {
1123
+ message: zod.z.object({
1124
+ version: zod.z.literal("v1").default("v1"),
1125
+ id: zod.z.string()
1126
+ })
1127
+ },
1206
1128
  READY_TO_DISPOSE: {
1207
1129
  message: zod.z.undefined()
1208
1130
  },
@@ -1267,13 +1189,19 @@ var ProdWorkerToChildMessages = {
1267
1189
  })
1268
1190
  },
1269
1191
  TASK_RUN_COMPLETED_NOTIFICATION: {
1270
- message: zod.z.object({
1271
- version: zod.z.literal("v1").default("v1"),
1272
- completion: TaskRunExecutionResult,
1273
- execution: TaskRunExecution
1274
- })
1275
- },
1276
- CLEANUP: {
1192
+ message: zod.z.discriminatedUnion("version", [
1193
+ zod.z.object({
1194
+ version: zod.z.literal("v1"),
1195
+ completion: TaskRunExecutionResult,
1196
+ execution: TaskRunExecution
1197
+ }),
1198
+ zod.z.object({
1199
+ version: zod.z.literal("v2"),
1200
+ completion: TaskRunExecutionResult
1201
+ })
1202
+ ])
1203
+ },
1204
+ CLEANUP: {
1277
1205
  message: zod.z.object({
1278
1206
  version: zod.z.literal("v1").default("v1"),
1279
1207
  flush: zod.z.boolean().default(false),
@@ -1399,6 +1327,17 @@ var PlatformToProviderMessages = {
1399
1327
  })
1400
1328
  }
1401
1329
  };
1330
+ var CreateWorkerMessage = zod.z.object({
1331
+ projectRef: zod.z.string(),
1332
+ envId: zod.z.string(),
1333
+ deploymentId: zod.z.string(),
1334
+ metadata: zod.z.object({
1335
+ cliPackageVersion: zod.z.string().optional(),
1336
+ contentHash: zod.z.string(),
1337
+ packageVersion: zod.z.string(),
1338
+ tasks: TaskResource.array()
1339
+ })
1340
+ });
1402
1341
  var CoordinatorToPlatformMessages = {
1403
1342
  LOG: {
1404
1343
  message: zod.z.object({
@@ -1408,18 +1347,15 @@ var CoordinatorToPlatformMessages = {
1408
1347
  })
1409
1348
  },
1410
1349
  CREATE_WORKER: {
1411
- message: zod.z.object({
1412
- version: zod.z.literal("v1").default("v1"),
1413
- projectRef: zod.z.string(),
1414
- envId: zod.z.string(),
1415
- deploymentId: zod.z.string(),
1416
- metadata: zod.z.object({
1417
- cliPackageVersion: zod.z.string().optional(),
1418
- contentHash: zod.z.string(),
1419
- packageVersion: zod.z.string(),
1420
- tasks: TaskResource.array()
1350
+ message: zod.z.discriminatedUnion("version", [
1351
+ CreateWorkerMessage.extend({
1352
+ version: zod.z.literal("v1")
1353
+ }),
1354
+ CreateWorkerMessage.extend({
1355
+ version: zod.z.literal("v2"),
1356
+ supportsLazyAttempts: zod.z.boolean()
1421
1357
  })
1422
- }),
1358
+ ]),
1423
1359
  callback: zod.z.discriminatedUnion("success", [
1424
1360
  zod.z.object({
1425
1361
  success: zod.z.literal(false)
@@ -1429,6 +1365,23 @@ var CoordinatorToPlatformMessages = {
1429
1365
  })
1430
1366
  ])
1431
1367
  },
1368
+ CREATE_TASK_RUN_ATTEMPT: {
1369
+ message: zod.z.object({
1370
+ version: zod.z.literal("v1").default("v1"),
1371
+ runId: zod.z.string(),
1372
+ envId: zod.z.string()
1373
+ }),
1374
+ callback: zod.z.discriminatedUnion("success", [
1375
+ zod.z.object({
1376
+ success: zod.z.literal(false),
1377
+ reason: zod.z.string().optional()
1378
+ }),
1379
+ zod.z.object({
1380
+ success: zod.z.literal(true),
1381
+ executionPayload: ProdTaskRunExecutionPayload
1382
+ })
1383
+ ])
1384
+ },
1432
1385
  READY_FOR_EXECUTION: {
1433
1386
  message: zod.z.object({
1434
1387
  version: zod.z.literal("v1").default("v1"),
@@ -1445,6 +1398,24 @@ var CoordinatorToPlatformMessages = {
1445
1398
  })
1446
1399
  ])
1447
1400
  },
1401
+ READY_FOR_LAZY_ATTEMPT: {
1402
+ message: zod.z.object({
1403
+ version: zod.z.literal("v1").default("v1"),
1404
+ runId: zod.z.string(),
1405
+ envId: zod.z.string(),
1406
+ totalCompletions: zod.z.number()
1407
+ }),
1408
+ callback: zod.z.discriminatedUnion("success", [
1409
+ zod.z.object({
1410
+ success: zod.z.literal(false),
1411
+ reason: zod.z.string().optional()
1412
+ }),
1413
+ zod.z.object({
1414
+ success: zod.z.literal(true),
1415
+ lazyPayload: TaskRunExecutionLazyAttemptPayload
1416
+ })
1417
+ ])
1418
+ },
1448
1419
  READY_FOR_RESUME: {
1449
1420
  message: zod.z.object({
1450
1421
  version: zod.z.literal("v1").default("v1"),
@@ -1463,12 +1434,24 @@ var CoordinatorToPlatformMessages = {
1463
1434
  }).optional()
1464
1435
  })
1465
1436
  },
1437
+ TASK_RUN_FAILED_TO_RUN: {
1438
+ message: zod.z.object({
1439
+ version: zod.z.literal("v1").default("v1"),
1440
+ completion: TaskRunFailedExecutionResult
1441
+ })
1442
+ },
1466
1443
  TASK_HEARTBEAT: {
1467
1444
  message: zod.z.object({
1468
1445
  version: zod.z.literal("v1").default("v1"),
1469
1446
  attemptFriendlyId: zod.z.string()
1470
1447
  })
1471
1448
  },
1449
+ TASK_RUN_HEARTBEAT: {
1450
+ message: zod.z.object({
1451
+ version: zod.z.literal("v1").default("v1"),
1452
+ runId: zod.z.string()
1453
+ })
1454
+ },
1472
1455
  CHECKPOINT_CREATED: {
1473
1456
  message: zod.z.object({
1474
1457
  version: zod.z.literal("v1").default("v1"),
@@ -1507,6 +1490,17 @@ var CoordinatorToPlatformMessages = {
1507
1490
  stack: zod.z.string().optional()
1508
1491
  })
1509
1492
  })
1493
+ },
1494
+ RUN_CRASHED: {
1495
+ message: zod.z.object({
1496
+ version: zod.z.literal("v1").default("v1"),
1497
+ runId: zod.z.string(),
1498
+ error: zod.z.object({
1499
+ name: zod.z.string(),
1500
+ message: zod.z.string(),
1501
+ stack: zod.z.string().optional()
1502
+ })
1503
+ })
1510
1504
  }
1511
1505
  };
1512
1506
  var PlatformToCoordinatorMessages = {
@@ -1534,6 +1528,13 @@ var PlatformToCoordinatorMessages = {
1534
1528
  attemptFriendlyId: zod.z.string()
1535
1529
  })
1536
1530
  },
1531
+ REQUEST_RUN_CANCELLATION: {
1532
+ message: zod.z.object({
1533
+ version: zod.z.literal("v1").default("v1"),
1534
+ runId: zod.z.string(),
1535
+ delayInMs: zod.z.number().optional()
1536
+ })
1537
+ },
1537
1538
  READY_FOR_RETRY: {
1538
1539
  message: zod.z.object({
1539
1540
  version: zod.z.literal("v1").default("v1"),
@@ -1577,6 +1578,12 @@ var SharedQueueToClientMessages = {
1577
1578
  })
1578
1579
  }
1579
1580
  };
1581
+ var IndexTasksMessage = zod.z.object({
1582
+ version: zod.z.literal("v1"),
1583
+ deploymentId: zod.z.string(),
1584
+ tasks: TaskResource.array(),
1585
+ packageVersion: zod.z.string()
1586
+ });
1580
1587
  var ProdWorkerToCoordinatorMessages = {
1581
1588
  LOG: {
1582
1589
  message: zod.z.object({
@@ -1586,12 +1593,15 @@ var ProdWorkerToCoordinatorMessages = {
1586
1593
  callback: zod.z.void()
1587
1594
  },
1588
1595
  INDEX_TASKS: {
1589
- message: zod.z.object({
1590
- version: zod.z.literal("v1").default("v1"),
1591
- deploymentId: zod.z.string(),
1592
- tasks: TaskResource.array(),
1593
- packageVersion: zod.z.string()
1594
- }),
1596
+ message: zod.z.discriminatedUnion("version", [
1597
+ IndexTasksMessage.extend({
1598
+ version: zod.z.literal("v1")
1599
+ }),
1600
+ IndexTasksMessage.extend({
1601
+ version: zod.z.literal("v2"),
1602
+ supportsLazyAttempts: zod.z.boolean()
1603
+ })
1604
+ ]),
1595
1605
  callback: zod.z.discriminatedUnion("success", [
1596
1606
  zod.z.object({
1597
1607
  success: zod.z.literal(false)
@@ -1608,6 +1618,13 @@ var ProdWorkerToCoordinatorMessages = {
1608
1618
  totalCompletions: zod.z.number()
1609
1619
  })
1610
1620
  },
1621
+ READY_FOR_LAZY_ATTEMPT: {
1622
+ message: zod.z.object({
1623
+ version: zod.z.literal("v1").default("v1"),
1624
+ runId: zod.z.string(),
1625
+ totalCompletions: zod.z.number()
1626
+ })
1627
+ },
1611
1628
  READY_FOR_RESUME: {
1612
1629
  message: zod.z.object({
1613
1630
  version: zod.z.literal("v1").default("v1"),
@@ -1644,6 +1661,12 @@ var ProdWorkerToCoordinatorMessages = {
1644
1661
  attemptFriendlyId: zod.z.string()
1645
1662
  })
1646
1663
  },
1664
+ TASK_RUN_HEARTBEAT: {
1665
+ message: zod.z.object({
1666
+ version: zod.z.literal("v1").default("v1"),
1667
+ runId: zod.z.string()
1668
+ })
1669
+ },
1647
1670
  TASK_RUN_COMPLETED: {
1648
1671
  message: zod.z.object({
1649
1672
  version: zod.z.literal("v1").default("v1"),
@@ -1655,6 +1678,12 @@ var ProdWorkerToCoordinatorMessages = {
1655
1678
  shouldExit: zod.z.boolean()
1656
1679
  })
1657
1680
  },
1681
+ TASK_RUN_FAILED_TO_RUN: {
1682
+ message: zod.z.object({
1683
+ version: zod.z.literal("v1").default("v1"),
1684
+ completion: TaskRunFailedExecutionResult
1685
+ })
1686
+ },
1658
1687
  WAIT_FOR_DURATION: {
1659
1688
  message: zod.z.object({
1660
1689
  version: zod.z.literal("v1").default("v1"),
@@ -1699,6 +1728,32 @@ var ProdWorkerToCoordinatorMessages = {
1699
1728
  stack: zod.z.string().optional()
1700
1729
  })
1701
1730
  })
1731
+ },
1732
+ CREATE_TASK_RUN_ATTEMPT: {
1733
+ message: zod.z.object({
1734
+ version: zod.z.literal("v1").default("v1"),
1735
+ runId: zod.z.string()
1736
+ }),
1737
+ callback: zod.z.discriminatedUnion("success", [
1738
+ zod.z.object({
1739
+ success: zod.z.literal(false),
1740
+ reason: zod.z.string().optional()
1741
+ }),
1742
+ zod.z.object({
1743
+ success: zod.z.literal(true),
1744
+ executionPayload: ProdTaskRunExecutionPayload
1745
+ })
1746
+ ])
1747
+ },
1748
+ UNRECOVERABLE_ERROR: {
1749
+ message: zod.z.object({
1750
+ version: zod.z.literal("v1").default("v1"),
1751
+ error: zod.z.object({
1752
+ name: zod.z.string(),
1753
+ message: zod.z.string(),
1754
+ stack: zod.z.string().optional()
1755
+ })
1756
+ })
1702
1757
  }
1703
1758
  };
1704
1759
  var CoordinatorToProdWorkerMessages = {
@@ -1722,6 +1777,12 @@ var CoordinatorToProdWorkerMessages = {
1722
1777
  executionPayload: ProdTaskRunExecutionPayload
1723
1778
  })
1724
1779
  },
1780
+ EXECUTE_TASK_RUN_LAZY_ATTEMPT: {
1781
+ message: zod.z.object({
1782
+ version: zod.z.literal("v1").default("v1"),
1783
+ lazyPayload: TaskRunExecutionLazyAttemptPayload
1784
+ })
1785
+ },
1725
1786
  REQUEST_ATTEMPT_CANCELLATION: {
1726
1787
  message: zod.z.object({
1727
1788
  version: zod.z.literal("v1").default("v1"),
@@ -1729,9 +1790,15 @@ var CoordinatorToProdWorkerMessages = {
1729
1790
  })
1730
1791
  },
1731
1792
  REQUEST_EXIT: {
1732
- message: zod.z.object({
1733
- version: zod.z.literal("v1").default("v1")
1734
- })
1793
+ message: zod.z.discriminatedUnion("version", [
1794
+ zod.z.object({
1795
+ version: zod.z.literal("v1")
1796
+ }),
1797
+ zod.z.object({
1798
+ version: zod.z.literal("v2"),
1799
+ delayInMs: zod.z.number().optional()
1800
+ })
1801
+ ])
1735
1802
  },
1736
1803
  READY_FOR_RETRY: {
1737
1804
  message: zod.z.object({
@@ -2087,48 +2154,795 @@ var _TaskContextAPI = class _TaskContextAPI {
2087
2154
  [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
2088
2155
  };
2089
2156
  }
2090
- return {};
2157
+ return {};
2158
+ }
2159
+ disable() {
2160
+ unregisterGlobal(API_NAME);
2161
+ }
2162
+ setGlobalTaskContext(taskContext2) {
2163
+ return registerGlobal(API_NAME, taskContext2);
2164
+ }
2165
+ };
2166
+ _getTaskContext = new WeakSet();
2167
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
2168
+ return getGlobal(API_NAME);
2169
+ }, "#getTaskContext");
2170
+ __name(_TaskContextAPI, "TaskContextAPI");
2171
+ var TaskContextAPI = _TaskContextAPI;
2172
+
2173
+ // src/v3/task-context-api.ts
2174
+ var taskContext = TaskContextAPI.getInstance();
2175
+
2176
+ // src/v3/apiClient/errors.ts
2177
+ var _ApiError = class _ApiError extends Error {
2178
+ constructor(status, error, message, headers) {
2179
+ super(`${_ApiError.makeMessage(status, error, message)}`);
2180
+ this.status = status;
2181
+ this.headers = headers;
2182
+ const data = error;
2183
+ this.error = data;
2184
+ this.code = data?.["code"];
2185
+ this.param = data?.["param"];
2186
+ this.type = data?.["type"];
2187
+ }
2188
+ static makeMessage(status, error, message) {
2189
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
2190
+ if (status && msg) {
2191
+ return `${status} ${msg}`;
2192
+ }
2193
+ if (status) {
2194
+ return `${status} status code (no body)`;
2195
+ }
2196
+ if (msg) {
2197
+ return msg;
2198
+ }
2199
+ return "(no status code or body)";
2200
+ }
2201
+ static generate(status, errorResponse, message, headers) {
2202
+ if (!status) {
2203
+ return new ApiConnectionError({
2204
+ cause: castToError(errorResponse)
2205
+ });
2206
+ }
2207
+ const error = errorResponse?.["error"];
2208
+ if (status === 400) {
2209
+ return new BadRequestError(status, error, message, headers);
2210
+ }
2211
+ if (status === 401) {
2212
+ return new AuthenticationError(status, error, message, headers);
2213
+ }
2214
+ if (status === 403) {
2215
+ return new PermissionDeniedError(status, error, message, headers);
2216
+ }
2217
+ if (status === 404) {
2218
+ return new NotFoundError(status, error, message, headers);
2219
+ }
2220
+ if (status === 409) {
2221
+ return new ConflictError(status, error, message, headers);
2222
+ }
2223
+ if (status === 422) {
2224
+ return new UnprocessableEntityError(status, error, message, headers);
2225
+ }
2226
+ if (status === 429) {
2227
+ return new RateLimitError(status, error, message, headers);
2228
+ }
2229
+ if (status >= 500) {
2230
+ return new InternalServerError(status, error, message, headers);
2231
+ }
2232
+ return new _ApiError(status, error, message, headers);
2233
+ }
2234
+ };
2235
+ __name(_ApiError, "ApiError");
2236
+ var ApiError = _ApiError;
2237
+ var _ApiConnectionError = class _ApiConnectionError extends ApiError {
2238
+ constructor({ message, cause }) {
2239
+ super(void 0, void 0, message || "Connection error.", void 0);
2240
+ __publicField(this, "status");
2241
+ if (cause)
2242
+ this.cause = cause;
2243
+ }
2244
+ };
2245
+ __name(_ApiConnectionError, "ApiConnectionError");
2246
+ var ApiConnectionError = _ApiConnectionError;
2247
+ var _BadRequestError = class _BadRequestError extends ApiError {
2248
+ constructor() {
2249
+ super(...arguments);
2250
+ __publicField(this, "status", 400);
2251
+ }
2252
+ };
2253
+ __name(_BadRequestError, "BadRequestError");
2254
+ var BadRequestError = _BadRequestError;
2255
+ var _AuthenticationError = class _AuthenticationError extends ApiError {
2256
+ constructor() {
2257
+ super(...arguments);
2258
+ __publicField(this, "status", 401);
2259
+ }
2260
+ };
2261
+ __name(_AuthenticationError, "AuthenticationError");
2262
+ var AuthenticationError = _AuthenticationError;
2263
+ var _PermissionDeniedError = class _PermissionDeniedError extends ApiError {
2264
+ constructor() {
2265
+ super(...arguments);
2266
+ __publicField(this, "status", 403);
2267
+ }
2268
+ };
2269
+ __name(_PermissionDeniedError, "PermissionDeniedError");
2270
+ var PermissionDeniedError = _PermissionDeniedError;
2271
+ var _NotFoundError = class _NotFoundError extends ApiError {
2272
+ constructor() {
2273
+ super(...arguments);
2274
+ __publicField(this, "status", 404);
2275
+ }
2276
+ };
2277
+ __name(_NotFoundError, "NotFoundError");
2278
+ var NotFoundError = _NotFoundError;
2279
+ var _ConflictError = class _ConflictError extends ApiError {
2280
+ constructor() {
2281
+ super(...arguments);
2282
+ __publicField(this, "status", 409);
2283
+ }
2284
+ };
2285
+ __name(_ConflictError, "ConflictError");
2286
+ var ConflictError = _ConflictError;
2287
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends ApiError {
2288
+ constructor() {
2289
+ super(...arguments);
2290
+ __publicField(this, "status", 422);
2291
+ }
2292
+ };
2293
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
2294
+ var UnprocessableEntityError = _UnprocessableEntityError;
2295
+ var _RateLimitError = class _RateLimitError extends ApiError {
2296
+ constructor() {
2297
+ super(...arguments);
2298
+ __publicField(this, "status", 429);
2299
+ }
2300
+ };
2301
+ __name(_RateLimitError, "RateLimitError");
2302
+ var RateLimitError = _RateLimitError;
2303
+ var _InternalServerError = class _InternalServerError extends ApiError {
2304
+ };
2305
+ __name(_InternalServerError, "InternalServerError");
2306
+ var InternalServerError = _InternalServerError;
2307
+ function castToError(err) {
2308
+ if (err instanceof Error)
2309
+ return err;
2310
+ return new Error(err);
2311
+ }
2312
+ __name(castToError, "castToError");
2313
+
2314
+ // src/retry.ts
2315
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
2316
+ if (!resets)
2317
+ return;
2318
+ switch (format) {
2319
+ case "iso_8601_duration_openai_variant": {
2320
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
2321
+ }
2322
+ case "iso_8601": {
2323
+ return calculateISO8601ResetAt(resets, now);
2324
+ }
2325
+ case "unix_timestamp": {
2326
+ return calculateUnixTimestampResetAt(resets, now);
2327
+ }
2328
+ case "unix_timestamp_in_ms": {
2329
+ return calculateUnixTimestampInMsResetAt(resets, now);
2330
+ }
2331
+ }
2332
+ }
2333
+ __name(calculateResetAt, "calculateResetAt");
2334
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
2335
+ if (!resets)
2336
+ return void 0;
2337
+ const resetAt = parseInt(resets, 10);
2338
+ if (isNaN(resetAt))
2339
+ return void 0;
2340
+ return new Date(resetAt * 1e3);
2341
+ }
2342
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
2343
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
2344
+ if (!resets)
2345
+ return void 0;
2346
+ const resetAt = parseInt(resets, 10);
2347
+ if (isNaN(resetAt))
2348
+ return void 0;
2349
+ return new Date(resetAt);
2350
+ }
2351
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
2352
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
2353
+ if (!resets)
2354
+ return void 0;
2355
+ const resetAt = new Date(resets);
2356
+ if (isNaN(resetAt.getTime()))
2357
+ return void 0;
2358
+ return resetAt;
2359
+ }
2360
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
2361
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
2362
+ if (!resets)
2363
+ return void 0;
2364
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
2365
+ const match = resets.match(pattern);
2366
+ if (!match)
2367
+ return void 0;
2368
+ const days = parseInt(match[1], 10) || 0;
2369
+ const hours = parseInt(match[2], 10) || 0;
2370
+ const minutes = parseInt(match[3], 10) || 0;
2371
+ const seconds = parseFloat(match[4]) || 0;
2372
+ const milliseconds = parseInt(match[5], 10) || 0;
2373
+ const resetAt = new Date(now);
2374
+ resetAt.setDate(resetAt.getDate() + days);
2375
+ resetAt.setHours(resetAt.getHours() + hours);
2376
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
2377
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
2378
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
2379
+ return resetAt;
2380
+ }
2381
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
2382
+
2383
+ // src/v3/utils/retries.ts
2384
+ var defaultRetryOptions = {
2385
+ maxAttempts: 3,
2386
+ factor: 2,
2387
+ minTimeoutInMs: 1e3,
2388
+ maxTimeoutInMs: 6e4,
2389
+ randomize: true
2390
+ };
2391
+ var defaultFetchRetryOptions = {
2392
+ byStatus: {
2393
+ "429,408,409,5xx": {
2394
+ strategy: "backoff",
2395
+ ...defaultRetryOptions
2396
+ }
2397
+ },
2398
+ connectionError: defaultRetryOptions,
2399
+ timeout: defaultRetryOptions
2400
+ };
2401
+ function calculateNextRetryDelay(options, attempt) {
2402
+ const opts = {
2403
+ ...defaultRetryOptions,
2404
+ ...options
2405
+ };
2406
+ if (attempt >= opts.maxAttempts) {
2407
+ return;
2408
+ }
2409
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
2410
+ const random = randomize ? Math.random() + 1 : 1;
2411
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
2412
+ return Math.round(timeout);
2413
+ }
2414
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
2415
+ function calculateResetAt2(resets, format, now = Date.now()) {
2416
+ const resetAt = calculateResetAt(resets, format, new Date(now));
2417
+ return resetAt?.getTime();
2418
+ }
2419
+ __name(calculateResetAt2, "calculateResetAt");
2420
+
2421
+ // src/v3/apiClient/pagination.ts
2422
+ var _CursorPage = class _CursorPage {
2423
+ constructor(data, pagination, pageFetcher) {
2424
+ this.pageFetcher = pageFetcher;
2425
+ this.data = data;
2426
+ this.pagination = pagination;
2427
+ }
2428
+ getPaginatedItems() {
2429
+ return this.data ?? [];
2430
+ }
2431
+ hasNextPage() {
2432
+ return !!this.pagination.next;
2433
+ }
2434
+ hasPreviousPage() {
2435
+ return !!this.pagination.previous;
2436
+ }
2437
+ getNextPage() {
2438
+ if (!this.pagination.next) {
2439
+ throw new Error("No next page available");
2440
+ }
2441
+ return this.pageFetcher({
2442
+ after: this.pagination.next
2443
+ });
2444
+ }
2445
+ getPreviousPage() {
2446
+ if (!this.pagination.previous) {
2447
+ throw new Error("No previous page available");
2448
+ }
2449
+ return this.pageFetcher({
2450
+ before: this.pagination.previous
2451
+ });
2452
+ }
2453
+ async *iterPages() {
2454
+ let page = this;
2455
+ yield page;
2456
+ while (page.hasNextPage()) {
2457
+ page = await page.getNextPage();
2458
+ yield page;
2459
+ }
2460
+ }
2461
+ async *[Symbol.asyncIterator]() {
2462
+ for await (const page of this.iterPages()) {
2463
+ for (const item of page.getPaginatedItems()) {
2464
+ yield item;
2465
+ }
2466
+ }
2467
+ }
2468
+ };
2469
+ __name(_CursorPage, "CursorPage");
2470
+ var CursorPage = _CursorPage;
2471
+ var _OffsetLimitPage = class _OffsetLimitPage {
2472
+ constructor(data, pagination, pageFetcher) {
2473
+ this.pageFetcher = pageFetcher;
2474
+ this.data = data;
2475
+ this.pagination = pagination;
2476
+ }
2477
+ getPaginatedItems() {
2478
+ return this.data ?? [];
2479
+ }
2480
+ hasNextPage() {
2481
+ return this.pagination.currentPage < this.pagination.totalPages;
2482
+ }
2483
+ hasPreviousPage() {
2484
+ return this.pagination.currentPage > 1;
2485
+ }
2486
+ getNextPage() {
2487
+ if (!this.hasNextPage()) {
2488
+ throw new Error("No next page available");
2489
+ }
2490
+ return this.pageFetcher({
2491
+ page: this.pagination.currentPage + 1
2492
+ });
2493
+ }
2494
+ getPreviousPage() {
2495
+ if (!this.hasPreviousPage()) {
2496
+ throw new Error("No previous page available");
2497
+ }
2498
+ return this.pageFetcher({
2499
+ page: this.pagination.currentPage - 1
2500
+ });
2501
+ }
2502
+ async *iterPages() {
2503
+ let page = this;
2504
+ yield page;
2505
+ while (page.hasNextPage()) {
2506
+ page = await page.getNextPage();
2507
+ yield page;
2508
+ }
2509
+ }
2510
+ async *[Symbol.asyncIterator]() {
2511
+ for await (const page of this.iterPages()) {
2512
+ for (const item of page.getPaginatedItems()) {
2513
+ yield item;
2514
+ }
2515
+ }
2516
+ }
2517
+ };
2518
+ __name(_OffsetLimitPage, "OffsetLimitPage");
2519
+ var OffsetLimitPage = _OffsetLimitPage;
2520
+
2521
+ // src/v3/apiClient/core.ts
2522
+ var defaultRetryOptions2 = {
2523
+ maxAttempts: 3,
2524
+ factor: 2,
2525
+ minTimeoutInMs: 1e3,
2526
+ maxTimeoutInMs: 6e4,
2527
+ randomize: false
2528
+ };
2529
+ function zodfetch(schema, url, requestInit, options) {
2530
+ return new ApiPromise(_doZodFetch(schema, url, requestInit, options));
2531
+ }
2532
+ __name(zodfetch, "zodfetch");
2533
+ function zodfetchCursorPage(schema, url, params, requestInit, options) {
2534
+ const query = new URLSearchParams(params.query);
2535
+ if (params.limit) {
2536
+ query.set("page[size]", String(params.limit));
2537
+ }
2538
+ if (params.after) {
2539
+ query.set("page[after]", params.after);
2540
+ }
2541
+ if (params.before) {
2542
+ query.set("page[before]", params.before);
2543
+ }
2544
+ const cursorPageSchema = zod.z.object({
2545
+ data: zod.z.array(schema),
2546
+ pagination: zod.z.object({
2547
+ next: zod.z.string().optional(),
2548
+ previous: zod.z.string().optional()
2549
+ })
2550
+ });
2551
+ const $url = new URL(url);
2552
+ $url.search = query.toString();
2553
+ const fetchResult = _doZodFetch(cursorPageSchema, $url.href, requestInit, options);
2554
+ return new CursorPagePromise(fetchResult, schema, url, params, requestInit, options);
2555
+ }
2556
+ __name(zodfetchCursorPage, "zodfetchCursorPage");
2557
+ function zodfetchOffsetLimitPage(schema, url, params, requestInit, options) {
2558
+ const query = new URLSearchParams(params.query);
2559
+ if (params.limit) {
2560
+ query.set("perPage", String(params.limit));
2561
+ }
2562
+ if (params.page) {
2563
+ query.set("page", String(params.page));
2564
+ }
2565
+ const offsetLimitPageSchema = zod.z.object({
2566
+ data: zod.z.array(schema),
2567
+ pagination: zod.z.object({
2568
+ currentPage: zod.z.coerce.number(),
2569
+ totalPages: zod.z.coerce.number(),
2570
+ count: zod.z.coerce.number()
2571
+ })
2572
+ });
2573
+ const $url = new URL(url);
2574
+ $url.search = query.toString();
2575
+ const fetchResult = _doZodFetch(offsetLimitPageSchema, $url.href, requestInit, options);
2576
+ return new OffsetLimitPagePromise(fetchResult, schema, url, params, requestInit, options);
2577
+ }
2578
+ __name(zodfetchOffsetLimitPage, "zodfetchOffsetLimitPage");
2579
+ function zodupload(schema, url, body, requestInit, options) {
2580
+ const finalRequestInit = createMultipartFormRequestInit(body, requestInit);
2581
+ return new ApiPromise(_doZodFetch(schema, url, finalRequestInit, options));
2582
+ }
2583
+ __name(zodupload, "zodupload");
2584
+ async function createMultipartFormRequestInit(body, requestInit) {
2585
+ const form = await createForm(body);
2586
+ const encoder = new formDataEncoder.FormDataEncoder(form);
2587
+ const finalHeaders = {};
2588
+ for (const [key, value] of Object.entries(requestInit?.headers || {})) {
2589
+ finalHeaders[key] = value;
2590
+ }
2591
+ for (const [key, value] of Object.entries(encoder.headers)) {
2592
+ finalHeaders[key] = value;
2593
+ }
2594
+ finalHeaders["Content-Length"] = String(encoder.contentLength);
2595
+ const finalRequestInit = {
2596
+ ...requestInit,
2597
+ headers: finalHeaders,
2598
+ body: stream.Readable.from(encoder),
2599
+ // @ts-expect-error
2600
+ duplex: "half"
2601
+ };
2602
+ return finalRequestInit;
2603
+ }
2604
+ __name(createMultipartFormRequestInit, "createMultipartFormRequestInit");
2605
+ var createForm = /* @__PURE__ */ __name(async (body) => {
2606
+ const form = new FormData();
2607
+ await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
2608
+ return form;
2609
+ }, "createForm");
2610
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2611
+ try {
2612
+ const $requestInit = await requestInit;
2613
+ const response = await fetch(url, requestInitWithCache($requestInit));
2614
+ const responseHeaders = createResponseHeaders(response.headers);
2615
+ if (!response.ok) {
2616
+ const retryResult = shouldRetry(response, attempt, options?.retry);
2617
+ if (retryResult.retry) {
2618
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
2619
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2620
+ } else {
2621
+ const errText = await response.text().catch((e) => castToError2(e).message);
2622
+ const errJSON = safeJsonParse(errText);
2623
+ const errMessage = errJSON ? void 0 : errText;
2624
+ throw ApiError.generate(response.status, errJSON, errMessage, responseHeaders);
2625
+ }
2626
+ }
2627
+ const jsonBody = await response.json();
2628
+ const parsedResult = schema.safeParse(jsonBody);
2629
+ if (parsedResult.success) {
2630
+ return {
2631
+ data: parsedResult.data,
2632
+ response
2633
+ };
2634
+ }
2635
+ throw zodValidationError.fromZodError(parsedResult.error);
2636
+ } catch (error) {
2637
+ if (error instanceof ApiError) {
2638
+ throw error;
2639
+ }
2640
+ if (options?.retry) {
2641
+ const retry = {
2642
+ ...defaultRetryOptions2,
2643
+ ...options.retry
2644
+ };
2645
+ const delay = calculateNextRetryDelay(retry, attempt);
2646
+ if (delay) {
2647
+ await new Promise((resolve) => setTimeout(resolve, delay));
2648
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2649
+ }
2650
+ }
2651
+ throw new ApiConnectionError({
2652
+ cause: castToError2(error)
2653
+ });
2654
+ }
2655
+ }
2656
+ __name(_doZodFetch, "_doZodFetch");
2657
+ function castToError2(err) {
2658
+ if (err instanceof Error)
2659
+ return err;
2660
+ return new Error(err);
2661
+ }
2662
+ __name(castToError2, "castToError");
2663
+ function shouldRetry(response, attempt, retryOptions) {
2664
+ function shouldRetryForOptions() {
2665
+ const retry = {
2666
+ ...defaultRetryOptions2,
2667
+ ...retryOptions
2668
+ };
2669
+ const delay = calculateNextRetryDelay(retry, attempt);
2670
+ if (delay) {
2671
+ return {
2672
+ retry: true,
2673
+ delay
2674
+ };
2675
+ } else {
2676
+ return {
2677
+ retry: false
2678
+ };
2679
+ }
2680
+ }
2681
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
2682
+ const shouldRetryHeader = response.headers.get("x-should-retry");
2683
+ if (shouldRetryHeader === "true")
2684
+ return shouldRetryForOptions();
2685
+ if (shouldRetryHeader === "false")
2686
+ return {
2687
+ retry: false
2688
+ };
2689
+ if (response.status === 408)
2690
+ return shouldRetryForOptions();
2691
+ if (response.status === 409)
2692
+ return shouldRetryForOptions();
2693
+ if (response.status === 429)
2694
+ return shouldRetryForOptions();
2695
+ if (response.status >= 500)
2696
+ return shouldRetryForOptions();
2697
+ return {
2698
+ retry: false
2699
+ };
2700
+ }
2701
+ __name(shouldRetry, "shouldRetry");
2702
+ function safeJsonParse(text) {
2703
+ try {
2704
+ return JSON.parse(text);
2705
+ } catch (e) {
2706
+ return void 0;
2707
+ }
2708
+ }
2709
+ __name(safeJsonParse, "safeJsonParse");
2710
+ function createResponseHeaders(headers) {
2711
+ return new Proxy(Object.fromEntries(
2712
+ // @ts-ignore
2713
+ headers.entries()
2714
+ ), {
2715
+ get(target, name) {
2716
+ const key = name.toString();
2717
+ return target[key.toLowerCase()] || target[key];
2718
+ }
2719
+ });
2720
+ }
2721
+ __name(createResponseHeaders, "createResponseHeaders");
2722
+ function requestInitWithCache(requestInit) {
2723
+ try {
2724
+ const withCache = {
2725
+ ...requestInit,
2726
+ cache: "no-cache"
2727
+ };
2728
+ const _ = new Request("http://localhost", withCache);
2729
+ return withCache;
2730
+ } catch (error) {
2731
+ return requestInit ?? {};
2732
+ }
2733
+ }
2734
+ __name(requestInitWithCache, "requestInitWithCache");
2735
+ var addFormValue = /* @__PURE__ */ __name(async (form, key, value) => {
2736
+ if (value === void 0)
2737
+ return;
2738
+ if (value == null) {
2739
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
2740
+ }
2741
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
2742
+ form.append(key, String(value));
2743
+ } else if (isUploadable(value) || isBlobLike(value) || value instanceof Buffer || value instanceof ArrayBuffer) {
2744
+ const file = await toFile(value);
2745
+ form.append(key, file);
2746
+ } else if (Array.isArray(value)) {
2747
+ await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
2748
+ } else if (typeof value === "object") {
2749
+ await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
2750
+ } else {
2751
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
2752
+ }
2753
+ }, "addFormValue");
2754
+ async function toFile(value, name, options) {
2755
+ value = await value;
2756
+ options ??= isFileLike(value) ? {
2757
+ lastModified: value.lastModified,
2758
+ type: value.type
2759
+ } : {};
2760
+ if (isResponseLike(value)) {
2761
+ const blob = await value.blob();
2762
+ name ||= new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file";
2763
+ return new File([
2764
+ blob
2765
+ ], name, options);
2766
+ }
2767
+ const bits = await getBytes(value);
2768
+ name ||= getName(value) ?? "unknown_file";
2769
+ if (!options.type) {
2770
+ const type = bits[0]?.type;
2771
+ if (typeof type === "string") {
2772
+ options = {
2773
+ ...options,
2774
+ type
2775
+ };
2776
+ }
2091
2777
  }
2092
- disable() {
2093
- unregisterGlobal(API_NAME);
2778
+ return new File(bits, name, options);
2779
+ }
2780
+ __name(toFile, "toFile");
2781
+ function getName(value) {
2782
+ return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream
2783
+ getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop();
2784
+ }
2785
+ __name(getName, "getName");
2786
+ var getStringFromMaybeBuffer = /* @__PURE__ */ __name((x) => {
2787
+ if (typeof x === "string")
2788
+ return x;
2789
+ if (typeof Buffer !== "undefined" && x instanceof Buffer)
2790
+ return String(x);
2791
+ return void 0;
2792
+ }, "getStringFromMaybeBuffer");
2793
+ async function getBytes(value) {
2794
+ let parts = [];
2795
+ if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
2796
+ value instanceof ArrayBuffer) {
2797
+ parts.push(value);
2798
+ } else if (isBlobLike(value)) {
2799
+ parts.push(await value.arrayBuffer());
2800
+ } else if (isAsyncIterableIterator(value)) {
2801
+ for await (const chunk of value) {
2802
+ parts.push(chunk);
2803
+ }
2804
+ } else {
2805
+ throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);
2094
2806
  }
2095
- setGlobalTaskContext(taskContext2) {
2096
- return registerGlobal(API_NAME, taskContext2);
2807
+ return parts;
2808
+ }
2809
+ __name(getBytes, "getBytes");
2810
+ function propsForError(value) {
2811
+ const props = Object.getOwnPropertyNames(value);
2812
+ return `[${props.map((p) => `"${p}"`).join(", ")}]`;
2813
+ }
2814
+ __name(propsForError, "propsForError");
2815
+ var isAsyncIterableIterator = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterableIterator");
2816
+ var isResponseLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", "isResponseLike");
2817
+ var isFileLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), "isFileLike");
2818
+ var isBlobLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", "isBlobLike");
2819
+ var isFsReadStream = /* @__PURE__ */ __name((value) => value instanceof stream.Readable, "isFsReadStream");
2820
+ var isUploadable = /* @__PURE__ */ __name((value) => {
2821
+ return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);
2822
+ }, "isUploadable");
2823
+ var isRecordLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => typeof key === "string" && typeof value[key] === "string"), "isRecordLike");
2824
+ var _ApiPromise = class _ApiPromise extends Promise {
2825
+ constructor(responsePromise) {
2826
+ super((resolve) => {
2827
+ resolve(null);
2828
+ });
2829
+ this.responsePromise = responsePromise;
2830
+ }
2831
+ /**
2832
+ * Gets the raw `Response` instance instead of parsing the response
2833
+ * data.
2834
+ *
2835
+ * If you want to parse the response body but still get the `Response`
2836
+ * instance, you can use {@link withResponse()}.
2837
+ */
2838
+ asResponse() {
2839
+ return this.responsePromise.then((p) => p.response);
2840
+ }
2841
+ /**
2842
+ * Gets the parsed response data and the raw `Response` instance.
2843
+ *
2844
+ * If you just want to get the raw `Response` instance without parsing it,
2845
+ * you can use {@link asResponse()}.
2846
+ */
2847
+ async withResponse() {
2848
+ const [data, response] = await Promise.all([
2849
+ this.parse(),
2850
+ this.asResponse()
2851
+ ]);
2852
+ return {
2853
+ data,
2854
+ response
2855
+ };
2856
+ }
2857
+ parse() {
2858
+ return this.responsePromise.then((result) => result.data);
2859
+ }
2860
+ then(onfulfilled, onrejected) {
2861
+ return this.parse().then(onfulfilled, onrejected);
2862
+ }
2863
+ catch(onrejected) {
2864
+ return this.parse().catch(onrejected);
2865
+ }
2866
+ finally(onfinally) {
2867
+ return this.parse().finally(onfinally);
2097
2868
  }
2098
2869
  };
2099
- _getTaskContext = new WeakSet();
2100
- getTaskContext_fn = /* @__PURE__ */ __name(function() {
2101
- return getGlobal(API_NAME);
2102
- }, "#getTaskContext");
2103
- __name(_TaskContextAPI, "TaskContextAPI");
2104
- var TaskContextAPI = _TaskContextAPI;
2105
-
2106
- // src/v3/task-context-api.ts
2107
- var taskContext = TaskContextAPI.getInstance();
2108
-
2109
- // package.json
2110
- var version = "0.0.0-v3-prerelease-20240517090458";
2111
- var dependencies = {
2112
- "@google-cloud/precise-date": "^4.0.0",
2113
- "@opentelemetry/api": "^1.8.0",
2114
- "@opentelemetry/api-logs": "^0.48.0",
2115
- "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
2116
- "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
2117
- "@opentelemetry/instrumentation": "^0.49.1",
2118
- "@opentelemetry/resources": "^1.22.0",
2119
- "@opentelemetry/sdk-logs": "^0.49.1",
2120
- "@opentelemetry/sdk-node": "^0.49.1",
2121
- "@opentelemetry/sdk-trace-base": "^1.22.0",
2122
- "@opentelemetry/sdk-trace-node": "^1.22.0",
2123
- "@opentelemetry/semantic-conventions": "^1.22.0",
2124
- "humanize-duration": "^3.27.3",
2125
- superjson: "^2.2.1",
2126
- ulidx: "^2.2.1",
2127
- zod: "3.22.3",
2128
- "zod-error": "1.5.0",
2129
- "zod-validation-error": "^1.5.0",
2130
- "socket.io-client": "4.7.4"
2870
+ __name(_ApiPromise, "ApiPromise");
2871
+ var ApiPromise = _ApiPromise;
2872
+ var _fetchPage, fetchPage_fn;
2873
+ var _CursorPagePromise = class _CursorPagePromise extends ApiPromise {
2874
+ constructor(result, schema, url, params, requestInit, options) {
2875
+ super(result.then((result2) => ({
2876
+ data: new CursorPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage, fetchPage_fn).bind(this)),
2877
+ response: result2.response
2878
+ })));
2879
+ __privateAdd(this, _fetchPage);
2880
+ this.schema = schema;
2881
+ this.url = url;
2882
+ this.params = params;
2883
+ this.requestInit = requestInit;
2884
+ this.options = options;
2885
+ }
2886
+ /**
2887
+ * Allow auto-paginating iteration on an unawaited list call, eg:
2888
+ *
2889
+ * for await (const item of client.items.list()) {
2890
+ * console.log(item)
2891
+ * }
2892
+ */
2893
+ async *[Symbol.asyncIterator]() {
2894
+ const page = await this;
2895
+ for await (const item of page) {
2896
+ yield item;
2897
+ }
2898
+ }
2131
2899
  };
2900
+ _fetchPage = new WeakSet();
2901
+ fetchPage_fn = /* @__PURE__ */ __name(function(params) {
2902
+ return zodfetchCursorPage(this.schema, this.url, {
2903
+ ...this.params,
2904
+ ...params
2905
+ }, this.requestInit, this.options);
2906
+ }, "#fetchPage");
2907
+ __name(_CursorPagePromise, "CursorPagePromise");
2908
+ var CursorPagePromise = _CursorPagePromise;
2909
+ var _fetchPage2, fetchPage_fn2;
2910
+ var _OffsetLimitPagePromise = class _OffsetLimitPagePromise extends ApiPromise {
2911
+ constructor(result, schema, url, params, requestInit, options) {
2912
+ super(result.then((result2) => ({
2913
+ data: new OffsetLimitPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage2, fetchPage_fn2).bind(this)),
2914
+ response: result2.response
2915
+ })));
2916
+ __privateAdd(this, _fetchPage2);
2917
+ this.schema = schema;
2918
+ this.url = url;
2919
+ this.params = params;
2920
+ this.requestInit = requestInit;
2921
+ this.options = options;
2922
+ }
2923
+ /**
2924
+ * Allow auto-paginating iteration on an unawaited list call, eg:
2925
+ *
2926
+ * for await (const item of client.items.list()) {
2927
+ * console.log(item)
2928
+ * }
2929
+ */
2930
+ async *[Symbol.asyncIterator]() {
2931
+ const page = await this;
2932
+ for await (const item of page) {
2933
+ yield item;
2934
+ }
2935
+ }
2936
+ };
2937
+ _fetchPage2 = new WeakSet();
2938
+ fetchPage_fn2 = /* @__PURE__ */ __name(function(params1) {
2939
+ return zodfetchOffsetLimitPage(this.schema, this.url, {
2940
+ ...this.params,
2941
+ ...params1
2942
+ }, this.requestInit, this.options);
2943
+ }, "#fetchPage");
2944
+ __name(_OffsetLimitPagePromise, "OffsetLimitPagePromise");
2945
+ var OffsetLimitPagePromise = _OffsetLimitPagePromise;
2132
2946
 
2133
2947
  // src/v3/apiClient/index.ts
2134
2948
  var zodFetchOptions = {
@@ -2154,7 +2968,7 @@ var _ApiClient = class _ApiClient {
2154
2968
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2155
2969
  }, zodFetchOptions);
2156
2970
  } catch (error) {
2157
- if (error instanceof APIError) {
2971
+ if (error instanceof ApiError) {
2158
2972
  if (error.status === 404) {
2159
2973
  return void 0;
2160
2974
  }
@@ -2169,14 +2983,16 @@ var _ApiClient = class _ApiClient {
2169
2983
  }, zodFetchOptions);
2170
2984
  }
2171
2985
  triggerTask(taskId, body, options) {
2172
- return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
2986
+ const encodedTaskId = encodeURIComponent(taskId);
2987
+ return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/trigger`, {
2173
2988
  method: "POST",
2174
2989
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2175
2990
  body: JSON.stringify(body)
2176
2991
  }, zodFetchOptions);
2177
2992
  }
2178
2993
  batchTriggerTask(taskId, body, options) {
2179
- return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
2994
+ const encodedTaskId = encodeURIComponent(taskId);
2995
+ return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/batch`, {
2180
2996
  method: "POST",
2181
2997
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2182
2998
  body: JSON.stringify(body)
@@ -2200,6 +3016,33 @@ var _ApiClient = class _ApiClient {
2200
3016
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2201
3017
  }, zodFetchOptions);
2202
3018
  }
3019
+ listRuns(query) {
3020
+ const searchParams = createSearchQueryForListRuns(query);
3021
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/runs`, {
3022
+ query: searchParams,
3023
+ limit: query?.limit,
3024
+ after: query?.after,
3025
+ before: query?.before
3026
+ }, {
3027
+ method: "GET",
3028
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3029
+ }, zodFetchOptions);
3030
+ }
3031
+ listProjectRuns(projectRef, query) {
3032
+ const searchParams = createSearchQueryForListRuns(query);
3033
+ if (query?.env) {
3034
+ searchParams.append("filter[env]", Array.isArray(query.env) ? query.env.join(",") : query.env);
3035
+ }
3036
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/projects/${projectRef}/runs`, {
3037
+ query: searchParams,
3038
+ limit: query?.limit,
3039
+ after: query?.after,
3040
+ before: query?.before
3041
+ }, {
3042
+ method: "GET",
3043
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3044
+ }, zodFetchOptions);
3045
+ }
2203
3046
  replayRun(runId) {
2204
3047
  return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2205
3048
  method: "POST",
@@ -2227,7 +3070,10 @@ var _ApiClient = class _ApiClient {
2227
3070
  if (options?.perPage) {
2228
3071
  searchParams.append("perPage", options.perPage.toString());
2229
3072
  }
2230
- return zodfetch(ListSchedulesResult, `${this.baseUrl}/api/v1/schedules${searchParams.size > 0 ? `?${searchParams}` : ""}`, {
3073
+ return zodfetchOffsetLimitPage(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
3074
+ page: options?.page,
3075
+ limit: options?.perPage
3076
+ }, {
2231
3077
  method: "GET",
2232
3078
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2233
3079
  });
@@ -2263,6 +3109,52 @@ var _ApiClient = class _ApiClient {
2263
3109
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2264
3110
  });
2265
3111
  }
3112
+ listEnvVars(projectRef, slug) {
3113
+ return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
3114
+ method: "GET",
3115
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3116
+ });
3117
+ }
3118
+ importEnvVars(projectRef, slug, body) {
3119
+ if (isRecordLike(body.variables)) {
3120
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
3121
+ method: "POST",
3122
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3123
+ body: JSON.stringify(body)
3124
+ });
3125
+ } else {
3126
+ return zodupload(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, body, {
3127
+ method: "POST",
3128
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3129
+ });
3130
+ }
3131
+ }
3132
+ retrieveEnvVar(projectRef, slug, key) {
3133
+ return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3134
+ method: "GET",
3135
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3136
+ });
3137
+ }
3138
+ createEnvVar(projectRef, slug, body) {
3139
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
3140
+ method: "POST",
3141
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3142
+ body: JSON.stringify(body)
3143
+ });
3144
+ }
3145
+ updateEnvVar(projectRef, slug, key, body) {
3146
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3147
+ method: "PUT",
3148
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3149
+ body: JSON.stringify(body)
3150
+ });
3151
+ }
3152
+ deleteEnvVar(projectRef, slug, key) {
3153
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3154
+ method: "DELETE",
3155
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3156
+ });
3157
+ }
2266
3158
  };
2267
3159
  _getHeaders = new WeakSet();
2268
3160
  getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
@@ -2282,6 +3174,40 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2282
3174
  }, "#getHeaders");
2283
3175
  __name(_ApiClient, "ApiClient");
2284
3176
  var ApiClient = _ApiClient;
3177
+ function createSearchQueryForListRuns(query) {
3178
+ const searchParams = new URLSearchParams();
3179
+ if (query) {
3180
+ if (query.status) {
3181
+ searchParams.append("filter[status]", Array.isArray(query.status) ? query.status.join(",") : query.status);
3182
+ }
3183
+ if (query.taskIdentifier) {
3184
+ searchParams.append("filter[taskIdentifier]", Array.isArray(query.taskIdentifier) ? query.taskIdentifier.join(",") : query.taskIdentifier);
3185
+ }
3186
+ if (query.version) {
3187
+ searchParams.append("filter[version]", Array.isArray(query.version) ? query.version.join(",") : query.version);
3188
+ }
3189
+ if (query.bulkAction) {
3190
+ searchParams.append("filter[bulkAction]", query.bulkAction);
3191
+ }
3192
+ if (query.schedule) {
3193
+ searchParams.append("filter[schedule]", query.schedule);
3194
+ }
3195
+ if (typeof query.isTest === "boolean") {
3196
+ searchParams.append("filter[isTest]", String(query.isTest));
3197
+ }
3198
+ if (query.from) {
3199
+ searchParams.append("filter[createdAt][from]", query.from instanceof Date ? query.from.getTime().toString() : query.from.toString());
3200
+ }
3201
+ if (query.to) {
3202
+ searchParams.append("filter[createdAt][to]", query.to instanceof Date ? query.to.getTime().toString() : query.to.toString());
3203
+ }
3204
+ if (query.period) {
3205
+ searchParams.append("filter[createdAt][period]", query.period);
3206
+ }
3207
+ }
3208
+ return searchParams;
3209
+ }
3210
+ __name(createSearchQueryForListRuns, "createSearchQueryForListRuns");
2285
3211
  var _SimpleClock = class _SimpleClock {
2286
3212
  preciseNow() {
2287
3213
  const now = new preciseDate.PreciseDate();
@@ -2331,145 +3257,6 @@ var ClockAPI = _ClockAPI;
2331
3257
  // src/v3/clock-api.ts
2332
3258
  var clock = ClockAPI.getInstance();
2333
3259
 
2334
- // src/v3/errors.ts
2335
- function parseError(error) {
2336
- if (error instanceof Error) {
2337
- return {
2338
- type: "BUILT_IN_ERROR",
2339
- name: error.name,
2340
- message: error.message,
2341
- stackTrace: error.stack ?? ""
2342
- };
2343
- }
2344
- if (typeof error === "string") {
2345
- return {
2346
- type: "STRING_ERROR",
2347
- raw: error
2348
- };
2349
- }
2350
- try {
2351
- return {
2352
- type: "CUSTOM_ERROR",
2353
- raw: JSON.stringify(error)
2354
- };
2355
- } catch (e) {
2356
- return {
2357
- type: "CUSTOM_ERROR",
2358
- raw: String(error)
2359
- };
2360
- }
2361
- }
2362
- __name(parseError, "parseError");
2363
- function createErrorTaskError(error) {
2364
- switch (error.type) {
2365
- case "BUILT_IN_ERROR": {
2366
- const e = new Error(error.message);
2367
- e.name = error.name;
2368
- e.stack = error.stackTrace;
2369
- return e;
2370
- }
2371
- case "STRING_ERROR": {
2372
- return error.raw;
2373
- }
2374
- case "CUSTOM_ERROR": {
2375
- return JSON.parse(error.raw);
2376
- }
2377
- case "INTERNAL_ERROR": {
2378
- return new Error(`trigger.dev internal error (${error.code})`);
2379
- }
2380
- }
2381
- }
2382
- __name(createErrorTaskError, "createErrorTaskError");
2383
- function createJsonErrorObject(error) {
2384
- switch (error.type) {
2385
- case "BUILT_IN_ERROR": {
2386
- return {
2387
- name: error.name,
2388
- message: error.message,
2389
- stackTrace: error.stackTrace
2390
- };
2391
- }
2392
- case "STRING_ERROR": {
2393
- return {
2394
- message: error.raw
2395
- };
2396
- }
2397
- case "CUSTOM_ERROR": {
2398
- return {
2399
- message: error.raw
2400
- };
2401
- }
2402
- case "INTERNAL_ERROR": {
2403
- return {
2404
- message: `trigger.dev internal error (${error.code})`
2405
- };
2406
- }
2407
- }
2408
- }
2409
- __name(createJsonErrorObject, "createJsonErrorObject");
2410
- function correctErrorStackTrace(stackTrace, projectDir, options) {
2411
- const [errorLine, ...traceLines] = stackTrace.split("\n");
2412
- return [
2413
- options?.removeFirstLine ? void 0 : errorLine,
2414
- ...traceLines.map((line) => correctStackTraceLine(line, projectDir))
2415
- ].filter(Boolean).join("\n");
2416
- }
2417
- __name(correctErrorStackTrace, "correctErrorStackTrace");
2418
- var LINES_TO_IGNORE = [
2419
- /ConsoleInterceptor/,
2420
- /TriggerTracer/,
2421
- /TaskExecutor/,
2422
- /EXECUTE_TASK_RUN/,
2423
- /@trigger.dev\/core/,
2424
- /safeJsonProcess/,
2425
- /__entryPoint.ts/
2426
- ];
2427
- function correctStackTraceLine(line, projectDir) {
2428
- if (LINES_TO_IGNORE.some((regex) => regex.test(line))) {
2429
- return;
2430
- }
2431
- if (projectDir && !line.includes(projectDir)) {
2432
- return;
2433
- }
2434
- return line.trim();
2435
- }
2436
- __name(correctStackTraceLine, "correctStackTraceLine");
2437
- function groupTaskMetadataIssuesByTask(tasks, issues) {
2438
- return issues.reduce((acc, issue) => {
2439
- if (issue.path.length === 0) {
2440
- return acc;
2441
- }
2442
- const taskIndex = issue.path[1];
2443
- if (typeof taskIndex !== "number") {
2444
- return acc;
2445
- }
2446
- const task = tasks[taskIndex];
2447
- if (!task) {
2448
- return acc;
2449
- }
2450
- const restOfPath = issue.path.slice(2);
2451
- const taskId = task.id;
2452
- const taskName = task.exportName;
2453
- const filePath = task.filePath;
2454
- const key = taskIndex;
2455
- const existing = acc[key] ?? {
2456
- id: taskId,
2457
- exportName: taskName,
2458
- filePath,
2459
- issues: []
2460
- };
2461
- existing.issues.push({
2462
- message: issue.message,
2463
- path: restOfPath.length === 0 ? void 0 : restOfPath.join(".")
2464
- });
2465
- return {
2466
- ...acc,
2467
- [key]: existing
2468
- };
2469
- }, {});
2470
- }
2471
- __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
2472
-
2473
3260
  // src/v3/limits.ts
2474
3261
  var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2475
3262
  var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
@@ -2809,7 +3596,7 @@ var _APIClientManagerAPI = class _APIClientManagerAPI {
2809
3596
  }
2810
3597
  get accessToken() {
2811
3598
  const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2812
- return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY");
3599
+ return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY") ?? getEnvVar("TRIGGER_ACCESS_TOKEN");
2813
3600
  }
2814
3601
  get client() {
2815
3602
  if (!this.baseURL || !this.accessToken) {
@@ -3501,9 +4288,9 @@ function safeJsonParse2(value) {
3501
4288
  }
3502
4289
  __name(safeJsonParse2, "safeJsonParse");
3503
4290
 
3504
- exports.APIConnectionError = APIConnectionError;
3505
- exports.APIError = APIError;
3506
4291
  exports.ApiClient = ApiClient;
4292
+ exports.ApiConnectionError = ApiConnectionError;
4293
+ exports.ApiError = ApiError;
3507
4294
  exports.AttemptStatus = AttemptStatus;
3508
4295
  exports.AuthenticationError = AuthenticationError;
3509
4296
  exports.BackgroundWorkerClientMessages = BackgroundWorkerClientMessages;
@@ -3524,11 +4311,17 @@ exports.CoordinatorToProdWorkerMessages = CoordinatorToProdWorkerMessages;
3524
4311
  exports.CreateAuthorizationCodeResponseSchema = CreateAuthorizationCodeResponseSchema;
3525
4312
  exports.CreateBackgroundWorkerRequestBody = CreateBackgroundWorkerRequestBody;
3526
4313
  exports.CreateBackgroundWorkerResponse = CreateBackgroundWorkerResponse;
4314
+ exports.CreateEnvironmentVariableRequestBody = CreateEnvironmentVariableRequestBody;
3527
4315
  exports.CreateScheduleOptions = CreateScheduleOptions;
3528
4316
  exports.CreateUploadPayloadUrlResponseBody = CreateUploadPayloadUrlResponseBody;
4317
+ exports.CursorPage = CursorPage;
3529
4318
  exports.DeletedScheduleObject = DeletedScheduleObject;
3530
4319
  exports.DeploymentErrorData = DeploymentErrorData;
3531
4320
  exports.EnvironmentType = EnvironmentType;
4321
+ exports.EnvironmentVariable = EnvironmentVariable;
4322
+ exports.EnvironmentVariableResponseBody = EnvironmentVariableResponseBody;
4323
+ exports.EnvironmentVariableValue = EnvironmentVariableValue;
4324
+ exports.EnvironmentVariables = EnvironmentVariables;
3532
4325
  exports.EventFilter = EventFilter;
3533
4326
  exports.ExceptionEventProperties = ExceptionEventProperties;
3534
4327
  exports.ExceptionSpanEvent = ExceptionSpanEvent;
@@ -3549,9 +4342,12 @@ exports.GetProjectEnvResponse = GetProjectEnvResponse;
3549
4342
  exports.GetProjectResponseBody = GetProjectResponseBody;
3550
4343
  exports.GetProjectsResponseBody = GetProjectsResponseBody;
3551
4344
  exports.ImageDetailsMetadata = ImageDetailsMetadata;
4345
+ exports.ImportEnvironmentVariablesRequestBody = ImportEnvironmentVariablesRequestBody;
3552
4346
  exports.InitializeDeploymentRequestBody = InitializeDeploymentRequestBody;
3553
4347
  exports.InitializeDeploymentResponseBody = InitializeDeploymentResponseBody;
3554
4348
  exports.InternalServerError = InternalServerError;
4349
+ exports.ListRunResponse = ListRunResponse;
4350
+ exports.ListRunResponseItem = ListRunResponseItem;
3555
4351
  exports.ListScheduleOptions = ListScheduleOptions;
3556
4352
  exports.ListSchedulesResult = ListSchedulesResult;
3557
4353
  exports.Machine = Machine;
@@ -3568,6 +4364,7 @@ exports.OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_
3568
4364
  exports.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT;
3569
4365
  exports.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT;
3570
4366
  exports.OTEL_SPAN_EVENT_COUNT_LIMIT = OTEL_SPAN_EVENT_COUNT_LIMIT;
4367
+ exports.OffsetLimitPage = OffsetLimitPage;
3571
4368
  exports.OtherSpanEvent = OtherSpanEvent;
3572
4369
  exports.PRIMARY_VARIANT = PRIMARY_VARIANT;
3573
4370
  exports.PermissionDeniedError = PermissionDeniedError;
@@ -3588,10 +4385,14 @@ exports.RateLimitOptions = RateLimitOptions;
3588
4385
  exports.ReplayRunResponse = ReplayRunResponse;
3589
4386
  exports.RetrieveRunResponse = RetrieveRunResponse;
3590
4387
  exports.RetryOptions = RetryOptions;
4388
+ exports.RunEnvironmentDetails = RunEnvironmentDetails;
4389
+ exports.RunScheduleDetails = RunScheduleDetails;
3591
4390
  exports.RunStatus = RunStatus;
4391
+ exports.ScheduleGenerator = ScheduleGenerator;
3592
4392
  exports.ScheduleObject = ScheduleObject;
3593
4393
  exports.ScheduledTaskPayload = ScheduledTaskPayload;
3594
4394
  exports.SemanticInternalAttributes = SemanticInternalAttributes;
4395
+ exports.SerializedError = SerializedError;
3595
4396
  exports.SharedQueueToClientMessages = SharedQueueToClientMessages;
3596
4397
  exports.SlidingWindowRateLimit = SlidingWindowRateLimit;
3597
4398
  exports.SpanEvent = SpanEvent;
@@ -3615,6 +4416,7 @@ exports.TaskRunExecution = TaskRunExecution;
3615
4416
  exports.TaskRunExecutionAttempt = TaskRunExecutionAttempt;
3616
4417
  exports.TaskRunExecutionBatch = TaskRunExecutionBatch;
3617
4418
  exports.TaskRunExecutionEnvironment = TaskRunExecutionEnvironment;
4419
+ exports.TaskRunExecutionLazyAttemptPayload = TaskRunExecutionLazyAttemptPayload;
3618
4420
  exports.TaskRunExecutionOrganization = TaskRunExecutionOrganization;
3619
4421
  exports.TaskRunExecutionPayload = TaskRunExecutionPayload;
3620
4422
  exports.TaskRunExecutionProject = TaskRunExecutionProject;
@@ -3631,6 +4433,7 @@ exports.TriggerTaskResponse = TriggerTaskResponse;
3631
4433
  exports.TriggerTracer = TriggerTracer;
3632
4434
  exports.UncaughtExceptionMessage = UncaughtExceptionMessage;
3633
4435
  exports.UnprocessableEntityError = UnprocessableEntityError;
4436
+ exports.UpdateEnvironmentVariableRequestBody = UpdateEnvironmentVariableRequestBody;
3634
4437
  exports.UpdateScheduleOptions = UpdateScheduleOptions;
3635
4438
  exports.WaitReason = WaitReason;
3636
4439
  exports.WhoAmIResponseSchema = WhoAmIResponseSchema;