@trigger.dev/core 0.0.0-v3-trigger-dirs-20240423091017 → 0.0.0-v3-trigger-dirs-20240423123825

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 (33) hide show
  1. package/dist/{consoleInterceptor-pKvaiAI6.d.ts → catalog-e2OUDZEa.d.mts} +52 -84
  2. package/dist/{consoleInterceptor-tCKb2R0l.d.mts → catalog-ndN7py2b.d.ts} +52 -84
  3. package/dist/{messages-oFuHKbi4.d.mts → messages-AriaDDm0.d.mts} +48 -48
  4. package/dist/{messages-oFuHKbi4.d.ts → messages-AriaDDm0.d.ts} +48 -48
  5. package/dist/v3/dev/index.d.mts +1 -1
  6. package/dist/v3/dev/index.d.ts +1 -1
  7. package/dist/v3/index.d.mts +99 -313
  8. package/dist/v3/index.d.ts +99 -313
  9. package/dist/v3/index.js +2045 -2595
  10. package/dist/v3/index.js.map +1 -1
  11. package/dist/v3/index.mjs +2065 -2603
  12. package/dist/v3/index.mjs.map +1 -1
  13. package/dist/v3/otel/index.d.mts +34 -6
  14. package/dist/v3/otel/index.d.ts +34 -6
  15. package/dist/v3/otel/index.js +62 -38
  16. package/dist/v3/otel/index.js.map +1 -1
  17. package/dist/v3/otel/index.mjs +62 -38
  18. package/dist/v3/otel/index.mjs.map +1 -1
  19. package/dist/v3/prod/index.d.mts +2 -2
  20. package/dist/v3/prod/index.d.ts +2 -2
  21. package/dist/v3/prod/index.js.map +1 -1
  22. package/dist/v3/prod/index.mjs.map +1 -1
  23. package/dist/v3/workers/index.d.mts +57 -12
  24. package/dist/v3/workers/index.d.ts +57 -12
  25. package/dist/v3/workers/index.js +728 -124
  26. package/dist/v3/workers/index.js.map +1 -1
  27. package/dist/v3/workers/index.mjs +718 -125
  28. package/dist/v3/workers/index.mjs.map +1 -1
  29. package/package.json +1 -1
  30. package/dist/tracingSDK-XMTLzw35.d.mts +0 -35
  31. package/dist/tracingSDK-XMTLzw35.d.ts +0 -35
  32. package/dist/{manager-KhqZOMNe.d.mts → manager-M9GLDnhJ.d.mts} +18 -18
  33. package/dist/{manager-KhqZOMNe.d.ts → manager-M9GLDnhJ.d.ts} +18 -18
package/dist/v3/index.js CHANGED
@@ -1,27 +1,18 @@
1
1
  'use strict';
2
2
 
3
- var zod = require('zod');
4
3
  var api = require('@opentelemetry/api');
5
4
  var zodValidationError = require('zod-validation-error');
5
+ var zod = require('zod');
6
6
  var async_hooks = require('async_hooks');
7
+ var preciseDate = require('@google-cloud/precise-date');
7
8
  var nodePath = require('path');
8
9
  var apiLogs = require('@opentelemetry/api-logs');
9
- var preciseDate = require('@google-cloud/precise-date');
10
10
  var humanizeDuration = require('humanize-duration');
11
- var util = require('util');
12
- var exporterLogsOtlpHttp = require('@opentelemetry/exporter-logs-otlp-http');
13
- var exporterTraceOtlpHttp = require('@opentelemetry/exporter-trace-otlp-http');
14
- var instrumentation = require('@opentelemetry/instrumentation');
15
- var resources = require('@opentelemetry/resources');
16
- var sdkLogs = require('@opentelemetry/sdk-logs');
17
- var sdkTraceNode = require('@opentelemetry/sdk-trace-node');
18
- var semanticConventions = require('@opentelemetry/semantic-conventions');
19
11
 
20
12
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
21
13
 
22
14
  var nodePath__default = /*#__PURE__*/_interopDefault(nodePath);
23
15
  var humanizeDuration__default = /*#__PURE__*/_interopDefault(humanizeDuration);
24
- var util__default = /*#__PURE__*/_interopDefault(util);
25
16
 
26
17
  var __defProp = Object.defineProperty;
27
18
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -43,1162 +34,863 @@ var __privateMethod = (obj, member, method) => {
43
34
  __accessCheck(obj, member, "access private method");
44
35
  return method;
45
36
  };
46
- var CreateAuthorizationCodeResponseSchema = zod.z.object({
47
- url: zod.z.string().url(),
48
- authorizationCode: zod.z.string()
49
- });
50
- var GetPersonalAccessTokenRequestSchema = zod.z.object({
51
- authorizationCode: zod.z.string()
52
- });
53
- var GetPersonalAccessTokenResponseSchema = zod.z.object({
54
- token: zod.z.object({
55
- token: zod.z.string(),
56
- obfuscatedToken: zod.z.string()
57
- }).nullable()
58
- });
59
- var TaskRunBuiltInError = zod.z.object({
60
- type: zod.z.literal("BUILT_IN_ERROR"),
61
- name: zod.z.string(),
62
- message: zod.z.string(),
63
- stackTrace: zod.z.string()
64
- });
65
- var TaskRunCustomErrorObject = zod.z.object({
66
- type: zod.z.literal("CUSTOM_ERROR"),
67
- raw: zod.z.string()
68
- });
69
- var TaskRunStringError = zod.z.object({
70
- type: zod.z.literal("STRING_ERROR"),
71
- raw: zod.z.string()
72
- });
73
- var TaskRunErrorCodes = {
74
- COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
75
- COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
76
- CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
77
- TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
78
- TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
79
- TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
80
- TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
81
- TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
82
- TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
83
- HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
84
- GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
85
- };
86
- var TaskRunInternalError = zod.z.object({
87
- type: zod.z.literal("INTERNAL_ERROR"),
88
- code: zod.z.enum([
89
- "COULD_NOT_FIND_EXECUTOR",
90
- "COULD_NOT_FIND_TASK",
91
- "CONFIGURED_INCORRECTLY",
92
- "TASK_ALREADY_RUNNING",
93
- "TASK_EXECUTION_FAILED",
94
- "TASK_EXECUTION_ABORTED",
95
- "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
96
- "TASK_RUN_CANCELLED",
97
- "TASK_OUTPUT_ERROR",
98
- "HANDLE_ERROR_ERROR",
99
- "GRACEFUL_EXIT_TIMEOUT"
100
- ]),
101
- message: zod.z.string().optional()
102
- });
103
- var TaskRunError = zod.z.discriminatedUnion("type", [
104
- TaskRunBuiltInError,
105
- TaskRunCustomErrorObject,
106
- TaskRunStringError,
107
- TaskRunInternalError
108
- ]);
109
- var TaskRun = zod.z.object({
110
- id: zod.z.string(),
111
- payload: zod.z.string(),
112
- payloadType: zod.z.string(),
113
- context: zod.z.any(),
114
- tags: zod.z.array(zod.z.string()),
115
- isTest: zod.z.boolean().default(false),
116
- createdAt: zod.z.coerce.date(),
117
- idempotencyKey: zod.z.string().optional()
118
- });
119
- var TaskRunExecutionTask = zod.z.object({
120
- id: zod.z.string(),
121
- filePath: zod.z.string(),
122
- exportName: zod.z.string()
123
- });
124
- var TaskRunExecutionAttempt = zod.z.object({
125
- id: zod.z.string(),
126
- number: zod.z.number(),
127
- startedAt: zod.z.coerce.date(),
128
- backgroundWorkerId: zod.z.string(),
129
- backgroundWorkerTaskId: zod.z.string(),
130
- status: zod.z.string()
131
- });
132
- var TaskRunExecutionEnvironment = zod.z.object({
133
- id: zod.z.string(),
134
- slug: zod.z.string(),
135
- type: zod.z.enum([
136
- "PRODUCTION",
137
- "STAGING",
138
- "DEVELOPMENT",
139
- "PREVIEW"
140
- ])
141
- });
142
- var TaskRunExecutionOrganization = zod.z.object({
143
- id: zod.z.string(),
144
- slug: zod.z.string(),
145
- name: zod.z.string()
146
- });
147
- var TaskRunExecutionProject = zod.z.object({
148
- id: zod.z.string(),
149
- ref: zod.z.string(),
150
- slug: zod.z.string(),
151
- name: zod.z.string()
152
- });
153
- var TaskRunExecutionQueue = zod.z.object({
154
- id: zod.z.string(),
155
- name: zod.z.string()
156
- });
157
- var TaskRunExecutionBatch = zod.z.object({
158
- id: zod.z.string()
159
- });
160
- var TaskRunExecution = zod.z.object({
161
- task: TaskRunExecutionTask,
162
- attempt: TaskRunExecutionAttempt,
163
- run: TaskRun,
164
- queue: TaskRunExecutionQueue,
165
- environment: TaskRunExecutionEnvironment,
166
- organization: TaskRunExecutionOrganization,
167
- project: TaskRunExecutionProject,
168
- batch: TaskRunExecutionBatch.optional()
169
- });
170
- var TaskRunContext = zod.z.object({
171
- task: TaskRunExecutionTask,
172
- attempt: TaskRunExecutionAttempt.omit({
173
- backgroundWorkerId: true,
174
- backgroundWorkerTaskId: true
175
- }),
176
- run: TaskRun.omit({
177
- payload: true,
178
- payloadType: true
179
- }),
180
- queue: TaskRunExecutionQueue,
181
- environment: TaskRunExecutionEnvironment,
182
- organization: TaskRunExecutionOrganization,
183
- project: TaskRunExecutionProject,
184
- batch: TaskRunExecutionBatch.optional()
185
- });
186
- var TaskRunExecutionRetry = zod.z.object({
187
- timestamp: zod.z.number(),
188
- delay: zod.z.number(),
189
- error: zod.z.unknown().optional()
190
- });
191
- var TaskRunFailedExecutionResult = zod.z.object({
192
- ok: zod.z.literal(false),
193
- id: zod.z.string(),
194
- error: TaskRunError,
195
- retry: TaskRunExecutionRetry.optional(),
196
- skippedRetrying: zod.z.boolean().optional()
197
- });
198
- var TaskRunSuccessfulExecutionResult = zod.z.object({
199
- ok: zod.z.literal(true),
200
- id: zod.z.string(),
201
- output: zod.z.string().optional(),
202
- outputType: zod.z.string()
203
- });
204
- var TaskRunExecutionResult = zod.z.discriminatedUnion("ok", [
205
- TaskRunSuccessfulExecutionResult,
206
- TaskRunFailedExecutionResult
207
- ]);
208
- var BatchTaskRunExecutionResult = zod.z.object({
209
- id: zod.z.string(),
210
- items: TaskRunExecutionResult.array()
211
- });
212
37
 
213
- // src/v3/schemas/messages.ts
214
- var EnvironmentType = zod.z.enum([
215
- "PRODUCTION",
216
- "STAGING",
217
- "DEVELOPMENT",
218
- "PREVIEW"
219
- ]);
220
- var MachineCpu = zod.z.union([
221
- zod.z.literal(0.25),
222
- zod.z.literal(0.5),
223
- zod.z.literal(1),
224
- zod.z.literal(2),
225
- zod.z.literal(4)
226
- ]).default(0.5);
227
- var MachineMemory = zod.z.union([
228
- zod.z.literal(0.25),
229
- zod.z.literal(0.5),
230
- zod.z.literal(1),
231
- zod.z.literal(2),
232
- zod.z.literal(4),
233
- zod.z.literal(8)
234
- ]).default(1);
235
- var Machine = zod.z.object({
236
- version: zod.z.literal("v1").default("v1"),
237
- cpu: MachineCpu,
238
- memory: MachineMemory
239
- });
240
- var TaskRunExecutionPayload = zod.z.object({
241
- execution: TaskRunExecution,
242
- traceContext: zod.z.record(zod.z.unknown()),
243
- environment: zod.z.record(zod.z.string()).optional()
244
- });
245
- var ProdTaskRunExecution = TaskRunExecution.extend({
246
- worker: zod.z.object({
247
- id: zod.z.string(),
248
- contentHash: zod.z.string(),
249
- version: zod.z.string()
250
- })
251
- });
252
- var ProdTaskRunExecutionPayload = zod.z.object({
253
- execution: ProdTaskRunExecution,
254
- traceContext: zod.z.record(zod.z.unknown()),
255
- environment: zod.z.record(zod.z.string()).optional()
256
- });
257
- var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
258
- zod.z.object({
259
- type: zod.z.literal("EXECUTE_RUNS"),
260
- payloads: zod.z.array(TaskRunExecutionPayload)
261
- }),
262
- zod.z.object({
263
- type: zod.z.literal("CANCEL_ATTEMPT"),
264
- taskAttemptId: zod.z.string(),
265
- taskRunId: zod.z.string()
266
- }),
267
- zod.z.object({
268
- type: zod.z.literal("SCHEDULE_ATTEMPT"),
269
- image: zod.z.string(),
270
- version: zod.z.string(),
271
- machine: Machine,
272
- // identifiers
273
- id: zod.z.string(),
274
- envId: zod.z.string(),
275
- envType: EnvironmentType,
276
- orgId: zod.z.string(),
277
- projectId: zod.z.string(),
278
- runId: zod.z.string()
279
- })
280
- ]);
281
- var serverWebsocketMessages = {
282
- SERVER_READY: zod.z.object({
283
- version: zod.z.literal("v1").default("v1"),
284
- id: zod.z.string()
285
- }),
286
- BACKGROUND_WORKER_MESSAGE: zod.z.object({
287
- version: zod.z.literal("v1").default("v1"),
288
- backgroundWorkerId: zod.z.string(),
289
- data: BackgroundWorkerServerMessages
290
- })
291
- };
292
- var BackgroundWorkerClientMessages = zod.z.discriminatedUnion("type", [
293
- zod.z.object({
294
- version: zod.z.literal("v1").default("v1"),
295
- type: zod.z.literal("TASK_RUN_COMPLETED"),
296
- completion: TaskRunExecutionResult,
297
- execution: TaskRunExecution
298
- }),
299
- zod.z.object({
300
- version: zod.z.literal("v1").default("v1"),
301
- type: zod.z.literal("TASK_HEARTBEAT"),
302
- id: zod.z.string()
303
- })
304
- ]);
305
- var BackgroundWorkerProperties = zod.z.object({
306
- id: zod.z.string(),
307
- version: zod.z.string(),
308
- contentHash: zod.z.string()
309
- });
310
- var clientWebsocketMessages = {
311
- READY_FOR_TASKS: zod.z.object({
312
- version: zod.z.literal("v1").default("v1"),
313
- backgroundWorkerId: zod.z.string()
314
- }),
315
- BACKGROUND_WORKER_DEPRECATED: zod.z.object({
316
- version: zod.z.literal("v1").default("v1"),
317
- backgroundWorkerId: zod.z.string()
318
- }),
319
- BACKGROUND_WORKER_MESSAGE: zod.z.object({
320
- version: zod.z.literal("v1").default("v1"),
321
- backgroundWorkerId: zod.z.string(),
322
- data: BackgroundWorkerClientMessages
323
- })
324
- };
325
- var workerToChildMessages = {
326
- EXECUTE_TASK_RUN: zod.z.object({
327
- version: zod.z.literal("v1").default("v1"),
328
- execution: TaskRunExecution,
329
- traceContext: zod.z.record(zod.z.unknown()),
330
- metadata: BackgroundWorkerProperties
331
- }),
332
- TASK_RUN_COMPLETED_NOTIFICATION: zod.z.object({
333
- version: zod.z.literal("v1").default("v1"),
334
- completion: TaskRunExecutionResult,
335
- execution: TaskRunExecution
336
- }),
337
- CLEANUP: zod.z.object({
338
- version: zod.z.literal("v1").default("v1"),
339
- flush: zod.z.boolean().default(false),
340
- kill: zod.z.boolean().default(true)
341
- })
342
- };
343
- var FixedWindowRateLimit = zod.z.object({
344
- type: zod.z.literal("fixed-window"),
345
- limit: zod.z.number(),
346
- window: zod.z.union([
347
- zod.z.object({
348
- seconds: zod.z.number()
349
- }),
350
- zod.z.object({
351
- minutes: zod.z.number()
352
- }),
353
- zod.z.object({
354
- hours: zod.z.number()
355
- })
356
- ])
357
- });
358
- var SlidingWindowRateLimit = zod.z.object({
359
- type: zod.z.literal("sliding-window"),
360
- limit: zod.z.number(),
361
- window: zod.z.union([
362
- zod.z.object({
363
- seconds: zod.z.number()
364
- }),
365
- zod.z.object({
366
- minutes: zod.z.number()
367
- }),
368
- zod.z.object({
369
- hours: zod.z.number()
370
- })
371
- ])
372
- });
373
- var RateLimitOptions = zod.z.discriminatedUnion("type", [
374
- FixedWindowRateLimit,
375
- SlidingWindowRateLimit
376
- ]);
377
- var RetryOptions = zod.z.object({
378
- /** The number of attempts before giving up */
379
- maxAttempts: zod.z.number().int().optional(),
380
- /** The exponential factor to use when calculating the next retry time.
381
- *
382
- * Each subsequent retry will be calculated as `previousTimeout * factor`
383
- */
384
- factor: zod.z.number().optional(),
385
- /** The minimum time to wait before retrying */
386
- minTimeoutInMs: zod.z.number().int().optional(),
387
- /** The maximum time to wait before retrying */
388
- maxTimeoutInMs: zod.z.number().int().optional(),
389
- /** Randomize the timeout between retries.
390
- *
391
- * This can be useful to prevent the thundering herd problem where all retries happen at the same time.
392
- */
393
- randomize: zod.z.boolean().optional()
394
- });
395
- var QueueOptions = zod.z.object({
396
- /** You can define a shared queue and then pass the name in to your task.
397
- *
398
- * @example
399
- *
400
- * ```ts
401
- * const myQueue = queue({
402
- name: "my-queue",
403
- concurrencyLimit: 1,
404
- });
405
-
406
- export const task1 = task({
407
- id: "task-1",
408
- queue: {
409
- name: "my-queue",
410
- },
411
- run: async (payload: { message: string }) => {
412
- // ...
413
- },
414
- });
415
-
416
- export const task2 = task({
417
- id: "task-2",
418
- queue: {
419
- name: "my-queue",
420
- },
421
- run: async (payload: { message: string }) => {
422
- // ...
423
- },
38
+ // src/v3/apiErrors.ts
39
+ var _APIError = class _APIError extends Error {
40
+ constructor(status, error, message, headers) {
41
+ super(`${_APIError.makeMessage(status, error, message)}`);
42
+ this.status = status;
43
+ this.headers = headers;
44
+ const data = error;
45
+ this.error = data;
46
+ this.code = data?.["code"];
47
+ this.param = data?.["param"];
48
+ this.type = data?.["type"];
49
+ }
50
+ static makeMessage(status, error, message) {
51
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
52
+ if (status && msg) {
53
+ return `${status} ${msg}`;
54
+ }
55
+ if (status) {
56
+ return `${status} status code (no body)`;
57
+ }
58
+ if (msg) {
59
+ return msg;
60
+ }
61
+ return "(no status code or body)";
62
+ }
63
+ static generate(status, errorResponse, message, headers) {
64
+ if (!status) {
65
+ return new APIConnectionError({
66
+ cause: castToError(errorResponse)
424
67
  });
425
- * ```
426
- */
427
- name: zod.z.string().optional(),
428
- /** An optional property that specifies the maximum number of concurrent run executions.
429
- *
430
- * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
431
- concurrencyLimit: zod.z.number().int().min(0).max(1e3).optional(),
432
- /** @deprecated This feature is coming soon */
433
- rateLimit: RateLimitOptions.optional()
434
- });
435
- var TaskMetadata = zod.z.object({
436
- id: zod.z.string(),
437
- packageVersion: zod.z.string(),
438
- queue: QueueOptions.optional(),
439
- retry: RetryOptions.optional(),
440
- machine: Machine.partial().optional(),
441
- triggerSource: zod.z.string().optional()
442
- });
443
- var TaskFileMetadata = zod.z.object({
444
- filePath: zod.z.string(),
445
- exportName: zod.z.string()
446
- });
447
- var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
448
- var UncaughtExceptionMessage = zod.z.object({
449
- version: zod.z.literal("v1").default("v1"),
450
- error: zod.z.object({
451
- name: zod.z.string(),
452
- message: zod.z.string(),
453
- stack: zod.z.string().optional()
454
- }),
455
- origin: zod.z.enum([
456
- "uncaughtException",
457
- "unhandledRejection"
458
- ])
459
- });
460
- var TaskMetadataFailedToParseData = zod.z.object({
461
- version: zod.z.literal("v1").default("v1"),
462
- tasks: zod.z.unknown(),
463
- zodIssues: zod.z.custom((v) => {
464
- return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
465
- })
466
- });
467
- var childToWorkerMessages = {
468
- TASK_RUN_COMPLETED: zod.z.object({
469
- version: zod.z.literal("v1").default("v1"),
470
- execution: TaskRunExecution,
471
- result: TaskRunExecutionResult
472
- }),
473
- TASKS_READY: zod.z.object({
474
- version: zod.z.literal("v1").default("v1"),
475
- tasks: TaskMetadataWithFilePath.array()
476
- }),
477
- TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
478
- TASK_HEARTBEAT: zod.z.object({
479
- version: zod.z.literal("v1").default("v1"),
480
- id: zod.z.string()
481
- }),
482
- READY_TO_DISPOSE: zod.z.undefined(),
483
- WAIT_FOR_DURATION: zod.z.object({
484
- version: zod.z.literal("v1").default("v1"),
485
- ms: zod.z.number()
486
- }),
487
- WAIT_FOR_TASK: zod.z.object({
488
- version: zod.z.literal("v1").default("v1"),
489
- id: zod.z.string()
490
- }),
491
- WAIT_FOR_BATCH: zod.z.object({
492
- version: zod.z.literal("v1").default("v1"),
493
- id: zod.z.string(),
494
- runs: zod.z.string().array()
495
- }),
496
- UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
68
+ }
69
+ const error = errorResponse?.["error"];
70
+ if (status === 400) {
71
+ return new BadRequestError(status, error, message, headers);
72
+ }
73
+ if (status === 401) {
74
+ return new AuthenticationError(status, error, message, headers);
75
+ }
76
+ if (status === 403) {
77
+ return new PermissionDeniedError(status, error, message, headers);
78
+ }
79
+ if (status === 404) {
80
+ return new NotFoundError(status, error, message, headers);
81
+ }
82
+ if (status === 409) {
83
+ return new ConflictError(status, error, message, headers);
84
+ }
85
+ if (status === 422) {
86
+ return new UnprocessableEntityError(status, error, message, headers);
87
+ }
88
+ if (status === 429) {
89
+ return new RateLimitError(status, error, message, headers);
90
+ }
91
+ if (status >= 500) {
92
+ return new InternalServerError(status, error, message, headers);
93
+ }
94
+ return new _APIError(status, error, message, headers);
95
+ }
497
96
  };
498
- var ProdChildToWorkerMessages = {
499
- TASK_RUN_COMPLETED: {
500
- message: zod.z.object({
501
- version: zod.z.literal("v1").default("v1"),
502
- execution: TaskRunExecution,
503
- result: TaskRunExecutionResult
504
- })
505
- },
506
- TASKS_READY: {
507
- message: zod.z.object({
508
- version: zod.z.literal("v1").default("v1"),
509
- tasks: TaskMetadataWithFilePath.array()
510
- })
511
- },
512
- TASKS_FAILED_TO_PARSE: {
513
- message: TaskMetadataFailedToParseData
514
- },
515
- TASK_HEARTBEAT: {
516
- message: zod.z.object({
517
- version: zod.z.literal("v1").default("v1"),
518
- id: zod.z.string()
519
- })
520
- },
521
- READY_TO_DISPOSE: {
522
- message: zod.z.undefined()
523
- },
524
- READY_FOR_CHECKPOINT: {
525
- message: zod.z.object({
526
- version: zod.z.literal("v1").default("v1")
527
- })
528
- },
529
- CANCEL_CHECKPOINT: {
530
- message: zod.z.object({
531
- version: zod.z.literal("v1").default("v1")
532
- })
533
- },
534
- WAIT_FOR_DURATION: {
535
- message: zod.z.object({
536
- version: zod.z.literal("v1").default("v1"),
537
- ms: zod.z.number(),
538
- now: zod.z.number()
539
- }),
540
- callback: zod.z.object({
541
- willCheckpointAndRestore: zod.z.boolean()
542
- })
543
- },
544
- WAIT_FOR_TASK: {
545
- message: zod.z.object({
546
- version: zod.z.literal("v1").default("v1"),
547
- friendlyId: zod.z.string()
548
- })
549
- },
550
- WAIT_FOR_BATCH: {
551
- message: zod.z.object({
552
- version: zod.z.literal("v1").default("v1"),
553
- batchFriendlyId: zod.z.string(),
554
- runFriendlyIds: zod.z.string().array()
555
- })
556
- },
557
- UNCAUGHT_EXCEPTION: {
558
- message: UncaughtExceptionMessage
97
+ __name(_APIError, "APIError");
98
+ var APIError = _APIError;
99
+ var _APIConnectionError = class _APIConnectionError extends APIError {
100
+ constructor({ message, cause }) {
101
+ super(void 0, void 0, message || "Connection error.", void 0);
102
+ __publicField(this, "status");
103
+ if (cause)
104
+ this.cause = cause;
559
105
  }
560
106
  };
561
- var ProdWorkerToChildMessages = {
562
- EXECUTE_TASK_RUN: {
563
- message: zod.z.object({
564
- version: zod.z.literal("v1").default("v1"),
565
- execution: TaskRunExecution,
566
- traceContext: zod.z.record(zod.z.unknown()),
567
- metadata: BackgroundWorkerProperties
568
- })
569
- },
570
- TASK_RUN_COMPLETED_NOTIFICATION: {
571
- message: zod.z.object({
572
- version: zod.z.literal("v1").default("v1"),
573
- completion: TaskRunExecutionResult,
574
- execution: TaskRunExecution
575
- })
576
- },
577
- CLEANUP: {
578
- message: zod.z.object({
579
- version: zod.z.literal("v1").default("v1"),
580
- flush: zod.z.boolean().default(false),
581
- kill: zod.z.boolean().default(true)
582
- }),
583
- callback: zod.z.void()
584
- },
585
- WAIT_COMPLETED_NOTIFICATION: {
586
- message: zod.z.object({
587
- version: zod.z.literal("v1").default("v1")
588
- })
107
+ __name(_APIConnectionError, "APIConnectionError");
108
+ var APIConnectionError = _APIConnectionError;
109
+ var _BadRequestError = class _BadRequestError extends APIError {
110
+ constructor() {
111
+ super(...arguments);
112
+ __publicField(this, "status", 400);
113
+ }
114
+ };
115
+ __name(_BadRequestError, "BadRequestError");
116
+ var BadRequestError = _BadRequestError;
117
+ var _AuthenticationError = class _AuthenticationError extends APIError {
118
+ constructor() {
119
+ super(...arguments);
120
+ __publicField(this, "status", 401);
121
+ }
122
+ };
123
+ __name(_AuthenticationError, "AuthenticationError");
124
+ var AuthenticationError = _AuthenticationError;
125
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
126
+ constructor() {
127
+ super(...arguments);
128
+ __publicField(this, "status", 403);
129
+ }
130
+ };
131
+ __name(_PermissionDeniedError, "PermissionDeniedError");
132
+ var PermissionDeniedError = _PermissionDeniedError;
133
+ var _NotFoundError = class _NotFoundError extends APIError {
134
+ constructor() {
135
+ super(...arguments);
136
+ __publicField(this, "status", 404);
137
+ }
138
+ };
139
+ __name(_NotFoundError, "NotFoundError");
140
+ var NotFoundError = _NotFoundError;
141
+ var _ConflictError = class _ConflictError extends APIError {
142
+ constructor() {
143
+ super(...arguments);
144
+ __publicField(this, "status", 409);
145
+ }
146
+ };
147
+ __name(_ConflictError, "ConflictError");
148
+ var ConflictError = _ConflictError;
149
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
150
+ constructor() {
151
+ super(...arguments);
152
+ __publicField(this, "status", 422);
153
+ }
154
+ };
155
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
156
+ var UnprocessableEntityError = _UnprocessableEntityError;
157
+ var _RateLimitError = class _RateLimitError extends APIError {
158
+ constructor() {
159
+ super(...arguments);
160
+ __publicField(this, "status", 429);
589
161
  }
590
162
  };
163
+ __name(_RateLimitError, "RateLimitError");
164
+ var RateLimitError = _RateLimitError;
165
+ var _InternalServerError = class _InternalServerError extends APIError {
166
+ };
167
+ __name(_InternalServerError, "InternalServerError");
168
+ var InternalServerError = _InternalServerError;
169
+ function castToError(err) {
170
+ if (err instanceof Error)
171
+ return err;
172
+ return new Error(err);
173
+ }
174
+ __name(castToError, "castToError");
591
175
 
592
- // src/v3/schemas/resources.ts
593
- var TaskResource = zod.z.object({
594
- id: zod.z.string(),
595
- filePath: zod.z.string(),
596
- exportName: zod.z.string(),
597
- queue: QueueOptions.optional(),
598
- retry: RetryOptions.optional(),
599
- machine: Machine.partial().optional(),
600
- triggerSource: zod.z.string().optional()
601
- });
602
- var BackgroundWorkerMetadata = zod.z.object({
603
- packageVersion: zod.z.string(),
604
- contentHash: zod.z.string(),
605
- cliPackageVersion: zod.z.string().optional(),
606
- tasks: zod.z.array(TaskResource)
607
- });
608
- var ImageDetailsMetadata = zod.z.object({
609
- contentHash: zod.z.string(),
610
- imageTag: zod.z.string()
611
- });
176
+ // src/retry.ts
177
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
178
+ if (!resets)
179
+ return;
180
+ switch (format) {
181
+ case "iso_8601_duration_openai_variant": {
182
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
183
+ }
184
+ case "iso_8601": {
185
+ return calculateISO8601ResetAt(resets, now);
186
+ }
187
+ case "unix_timestamp": {
188
+ return calculateUnixTimestampResetAt(resets, now);
189
+ }
190
+ case "unix_timestamp_in_ms": {
191
+ return calculateUnixTimestampInMsResetAt(resets, now);
192
+ }
193
+ }
194
+ }
195
+ __name(calculateResetAt, "calculateResetAt");
196
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
197
+ if (!resets)
198
+ return void 0;
199
+ const resetAt = parseInt(resets, 10);
200
+ if (isNaN(resetAt))
201
+ return void 0;
202
+ return new Date(resetAt * 1e3);
203
+ }
204
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
205
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
206
+ if (!resets)
207
+ return void 0;
208
+ const resetAt = parseInt(resets, 10);
209
+ if (isNaN(resetAt))
210
+ return void 0;
211
+ return new Date(resetAt);
212
+ }
213
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
214
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
215
+ if (!resets)
216
+ return void 0;
217
+ const resetAt = new Date(resets);
218
+ if (isNaN(resetAt.getTime()))
219
+ return void 0;
220
+ return resetAt;
221
+ }
222
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
223
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
224
+ if (!resets)
225
+ return void 0;
226
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
227
+ const match = resets.match(pattern);
228
+ if (!match)
229
+ return void 0;
230
+ const days = parseInt(match[1], 10) || 0;
231
+ const hours = parseInt(match[2], 10) || 0;
232
+ const minutes = parseInt(match[3], 10) || 0;
233
+ const seconds = parseFloat(match[4]) || 0;
234
+ const milliseconds = parseInt(match[5], 10) || 0;
235
+ const resetAt = new Date(now);
236
+ resetAt.setDate(resetAt.getDate() + days);
237
+ resetAt.setHours(resetAt.getHours() + hours);
238
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
239
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
240
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
241
+ return resetAt;
242
+ }
243
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
612
244
 
613
- // src/v3/schemas/api.ts
614
- var WhoAmIResponseSchema = zod.z.object({
615
- userId: zod.z.string(),
616
- email: zod.z.string().email(),
617
- dashboardUrl: zod.z.string()
618
- });
619
- var GetProjectResponseBody = zod.z.object({
620
- id: zod.z.string(),
621
- externalRef: zod.z.string(),
622
- name: zod.z.string(),
623
- slug: zod.z.string(),
624
- createdAt: zod.z.coerce.date(),
625
- organization: zod.z.object({
626
- id: zod.z.string(),
627
- title: zod.z.string(),
628
- slug: zod.z.string(),
629
- createdAt: zod.z.coerce.date()
630
- })
631
- });
632
- var GetProjectsResponseBody = zod.z.array(GetProjectResponseBody);
633
- var GetProjectEnvResponse = zod.z.object({
634
- apiKey: zod.z.string(),
635
- name: zod.z.string(),
636
- apiUrl: zod.z.string()
637
- });
638
- var CreateBackgroundWorkerRequestBody = zod.z.object({
639
- localOnly: zod.z.boolean(),
640
- metadata: BackgroundWorkerMetadata
641
- });
642
- var CreateBackgroundWorkerResponse = zod.z.object({
643
- id: zod.z.string(),
644
- version: zod.z.string(),
645
- contentHash: zod.z.string()
646
- });
647
- var TriggerTaskRequestBody = zod.z.object({
648
- payload: zod.z.any(),
649
- context: zod.z.any(),
650
- options: zod.z.object({
651
- dependentAttempt: zod.z.string().optional(),
652
- dependentBatch: zod.z.string().optional(),
653
- lockToVersion: zod.z.string().optional(),
654
- queue: QueueOptions.optional(),
655
- concurrencyKey: zod.z.string().optional(),
656
- idempotencyKey: zod.z.string().optional(),
657
- test: zod.z.boolean().optional(),
658
- payloadType: zod.z.string().optional()
659
- }).optional()
245
+ // src/v3/utils/retries.ts
246
+ var defaultRetryOptions = {
247
+ maxAttempts: 3,
248
+ factor: 2,
249
+ minTimeoutInMs: 1e3,
250
+ maxTimeoutInMs: 6e4,
251
+ randomize: true
252
+ };
253
+ var defaultFetchRetryOptions = {
254
+ byStatus: {
255
+ "429,408,409,5xx": {
256
+ strategy: "backoff",
257
+ ...defaultRetryOptions
258
+ }
259
+ },
260
+ connectionError: defaultRetryOptions,
261
+ timeout: defaultRetryOptions
262
+ };
263
+ function calculateNextRetryDelay(options, attempt) {
264
+ const opts = {
265
+ ...defaultRetryOptions,
266
+ ...options
267
+ };
268
+ if (attempt >= opts.maxAttempts) {
269
+ return;
270
+ }
271
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
272
+ const random = randomize ? Math.random() + 1 : 1;
273
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
274
+ return Math.round(timeout);
275
+ }
276
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
277
+ function calculateResetAt2(resets, format, now = Date.now()) {
278
+ const resetAt = calculateResetAt(resets, format, new Date(now));
279
+ return resetAt?.getTime();
280
+ }
281
+ __name(calculateResetAt2, "calculateResetAt");
282
+
283
+ // src/v3/zodfetch.ts
284
+ var defaultRetryOptions2 = {
285
+ maxAttempts: 3,
286
+ factor: 2,
287
+ minTimeoutInMs: 1e3,
288
+ maxTimeoutInMs: 6e4,
289
+ randomize: false
290
+ };
291
+ async function zodfetch(schema, url, requestInit, options) {
292
+ return await _doZodFetch(schema, url, requestInit, options);
293
+ }
294
+ __name(zodfetch, "zodfetch");
295
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
296
+ try {
297
+ const response = await fetch(url, requestInitWithCache(requestInit));
298
+ const responseHeaders = createResponseHeaders(response.headers);
299
+ if (!response.ok) {
300
+ const retryResult = shouldRetry(response, attempt, options?.retry);
301
+ if (retryResult.retry) {
302
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
303
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
304
+ } else {
305
+ const errText = await response.text().catch((e) => castToError2(e).message);
306
+ const errJSON = safeJsonParse(errText);
307
+ const errMessage = errJSON ? void 0 : errText;
308
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
309
+ }
310
+ }
311
+ const jsonBody = await response.json();
312
+ const parsedResult = schema.safeParse(jsonBody);
313
+ if (parsedResult.success) {
314
+ return parsedResult.data;
315
+ }
316
+ throw zodValidationError.fromZodError(parsedResult.error);
317
+ } catch (error) {
318
+ if (error instanceof APIError) {
319
+ throw error;
320
+ }
321
+ if (options?.retry) {
322
+ const retry = {
323
+ ...defaultRetryOptions2,
324
+ ...options.retry
325
+ };
326
+ const delay = calculateNextRetryDelay(retry, attempt);
327
+ if (delay) {
328
+ await new Promise((resolve) => setTimeout(resolve, delay));
329
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
330
+ }
331
+ }
332
+ throw new APIConnectionError({
333
+ cause: castToError2(error)
334
+ });
335
+ }
336
+ }
337
+ __name(_doZodFetch, "_doZodFetch");
338
+ function castToError2(err) {
339
+ if (err instanceof Error)
340
+ return err;
341
+ return new Error(err);
342
+ }
343
+ __name(castToError2, "castToError");
344
+ function shouldRetry(response, attempt, retryOptions) {
345
+ function shouldRetryForOptions() {
346
+ const retry = {
347
+ ...defaultRetryOptions2,
348
+ ...retryOptions
349
+ };
350
+ const delay = calculateNextRetryDelay(retry, attempt);
351
+ if (delay) {
352
+ return {
353
+ retry: true,
354
+ delay
355
+ };
356
+ } else {
357
+ return {
358
+ retry: false
359
+ };
360
+ }
361
+ }
362
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
363
+ const shouldRetryHeader = response.headers.get("x-should-retry");
364
+ if (shouldRetryHeader === "true")
365
+ return shouldRetryForOptions();
366
+ if (shouldRetryHeader === "false")
367
+ return {
368
+ retry: false
369
+ };
370
+ if (response.status === 408)
371
+ return shouldRetryForOptions();
372
+ if (response.status === 409)
373
+ return shouldRetryForOptions();
374
+ if (response.status === 429)
375
+ return shouldRetryForOptions();
376
+ if (response.status >= 500)
377
+ return shouldRetryForOptions();
378
+ return {
379
+ retry: false
380
+ };
381
+ }
382
+ __name(shouldRetry, "shouldRetry");
383
+ function safeJsonParse(text) {
384
+ try {
385
+ return JSON.parse(text);
386
+ } catch (e) {
387
+ return void 0;
388
+ }
389
+ }
390
+ __name(safeJsonParse, "safeJsonParse");
391
+ function createResponseHeaders(headers) {
392
+ return new Proxy(Object.fromEntries(
393
+ // @ts-ignore
394
+ headers.entries()
395
+ ), {
396
+ get(target, name) {
397
+ const key = name.toString();
398
+ return target[key.toLowerCase()] || target[key];
399
+ }
400
+ });
401
+ }
402
+ __name(createResponseHeaders, "createResponseHeaders");
403
+ function requestInitWithCache(requestInit) {
404
+ try {
405
+ const withCache = {
406
+ ...requestInit,
407
+ cache: "no-cache"
408
+ };
409
+ const _ = new Request("http://localhost", withCache);
410
+ return withCache;
411
+ } catch (error) {
412
+ return requestInit ?? {};
413
+ }
414
+ }
415
+ __name(requestInitWithCache, "requestInitWithCache");
416
+ var CreateAuthorizationCodeResponseSchema = zod.z.object({
417
+ url: zod.z.string().url(),
418
+ authorizationCode: zod.z.string()
660
419
  });
661
- var TriggerTaskResponse = zod.z.object({
662
- id: zod.z.string()
420
+ var GetPersonalAccessTokenRequestSchema = zod.z.object({
421
+ authorizationCode: zod.z.string()
663
422
  });
664
- var BatchTriggerTaskRequestBody = zod.z.object({
665
- items: TriggerTaskRequestBody.array(),
666
- dependentAttempt: zod.z.string().optional()
423
+ var GetPersonalAccessTokenResponseSchema = zod.z.object({
424
+ token: zod.z.object({
425
+ token: zod.z.string(),
426
+ obfuscatedToken: zod.z.string()
427
+ }).nullable()
667
428
  });
668
- var BatchTriggerTaskResponse = zod.z.object({
669
- batchId: zod.z.string(),
670
- runs: zod.z.string().array()
429
+ var TaskRunBuiltInError = zod.z.object({
430
+ type: zod.z.literal("BUILT_IN_ERROR"),
431
+ name: zod.z.string(),
432
+ message: zod.z.string(),
433
+ stackTrace: zod.z.string()
671
434
  });
672
- var GetBatchResponseBody = zod.z.object({
673
- id: zod.z.string(),
674
- items: zod.z.array(zod.z.object({
675
- id: zod.z.string(),
676
- taskRunId: zod.z.string(),
677
- status: zod.z.enum([
678
- "PENDING",
679
- "CANCELED",
680
- "COMPLETED",
681
- "FAILED"
682
- ])
683
- }))
435
+ var TaskRunCustomErrorObject = zod.z.object({
436
+ type: zod.z.literal("CUSTOM_ERROR"),
437
+ raw: zod.z.string()
684
438
  });
685
- var GetEnvironmentVariablesResponseBody = zod.z.object({
686
- variables: zod.z.record(zod.z.string())
439
+ var TaskRunStringError = zod.z.object({
440
+ type: zod.z.literal("STRING_ERROR"),
441
+ raw: zod.z.string()
687
442
  });
688
- var StartDeploymentIndexingRequestBody = zod.z.object({
689
- imageReference: zod.z.string()
443
+ var TaskRunErrorCodes = {
444
+ COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
445
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
446
+ CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
447
+ TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
448
+ TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
449
+ TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
450
+ TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
451
+ TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
452
+ TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
453
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
454
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
455
+ };
456
+ var TaskRunInternalError = zod.z.object({
457
+ type: zod.z.literal("INTERNAL_ERROR"),
458
+ code: zod.z.enum([
459
+ "COULD_NOT_FIND_EXECUTOR",
460
+ "COULD_NOT_FIND_TASK",
461
+ "CONFIGURED_INCORRECTLY",
462
+ "TASK_ALREADY_RUNNING",
463
+ "TASK_EXECUTION_FAILED",
464
+ "TASK_EXECUTION_ABORTED",
465
+ "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
466
+ "TASK_RUN_CANCELLED",
467
+ "TASK_OUTPUT_ERROR",
468
+ "HANDLE_ERROR_ERROR",
469
+ "GRACEFUL_EXIT_TIMEOUT"
470
+ ]),
471
+ message: zod.z.string().optional()
690
472
  });
691
- var StartDeploymentIndexingResponseBody = zod.z.object({
473
+ var TaskRunError = zod.z.discriminatedUnion("type", [
474
+ TaskRunBuiltInError,
475
+ TaskRunCustomErrorObject,
476
+ TaskRunStringError,
477
+ TaskRunInternalError
478
+ ]);
479
+ var TaskRun = zod.z.object({
692
480
  id: zod.z.string(),
693
- contentHash: zod.z.string()
481
+ payload: zod.z.string(),
482
+ payloadType: zod.z.string(),
483
+ context: zod.z.any(),
484
+ tags: zod.z.array(zod.z.string()),
485
+ isTest: zod.z.boolean().default(false),
486
+ createdAt: zod.z.coerce.date(),
487
+ idempotencyKey: zod.z.string().optional()
694
488
  });
695
- var ExternalBuildData = zod.z.object({
696
- buildId: zod.z.string(),
697
- buildToken: zod.z.string(),
698
- projectId: zod.z.string()
489
+ var TaskRunExecutionTask = zod.z.object({
490
+ id: zod.z.string(),
491
+ filePath: zod.z.string(),
492
+ exportName: zod.z.string()
699
493
  });
700
- var InitializeDeploymentResponseBody = zod.z.object({
494
+ var TaskRunExecutionAttempt = zod.z.object({
701
495
  id: zod.z.string(),
702
- contentHash: zod.z.string(),
703
- shortCode: zod.z.string(),
704
- version: zod.z.string(),
705
- imageTag: zod.z.string(),
706
- externalBuildData: ExternalBuildData.optional().nullable(),
707
- registryHost: zod.z.string().optional()
496
+ number: zod.z.number(),
497
+ startedAt: zod.z.coerce.date(),
498
+ backgroundWorkerId: zod.z.string(),
499
+ backgroundWorkerTaskId: zod.z.string(),
500
+ status: zod.z.string()
708
501
  });
709
- var InitializeDeploymentRequestBody = zod.z.object({
710
- contentHash: zod.z.string(),
711
- userId: zod.z.string().optional()
502
+ var TaskRunExecutionEnvironment = zod.z.object({
503
+ id: zod.z.string(),
504
+ slug: zod.z.string(),
505
+ type: zod.z.enum([
506
+ "PRODUCTION",
507
+ "STAGING",
508
+ "DEVELOPMENT",
509
+ "PREVIEW"
510
+ ])
712
511
  });
713
- var DeploymentErrorData = zod.z.object({
714
- name: zod.z.string(),
715
- message: zod.z.string(),
716
- stack: zod.z.string().optional()
512
+ var TaskRunExecutionOrganization = zod.z.object({
513
+ id: zod.z.string(),
514
+ slug: zod.z.string(),
515
+ name: zod.z.string()
717
516
  });
718
- var GetDeploymentResponseBody = zod.z.object({
517
+ var TaskRunExecutionProject = zod.z.object({
719
518
  id: zod.z.string(),
720
- status: zod.z.enum([
721
- "PENDING",
722
- "BUILDING",
723
- "DEPLOYING",
724
- "DEPLOYED",
725
- "FAILED",
726
- "CANCELED",
727
- "TIMED_OUT"
728
- ]),
729
- contentHash: zod.z.string(),
730
- shortCode: zod.z.string(),
731
- version: zod.z.string(),
732
- imageReference: zod.z.string().optional(),
733
- errorData: DeploymentErrorData.optional().nullable(),
734
- worker: zod.z.object({
735
- id: zod.z.string(),
736
- version: zod.z.string(),
737
- tasks: zod.z.array(zod.z.object({
738
- id: zod.z.string(),
739
- slug: zod.z.string(),
740
- filePath: zod.z.string(),
741
- exportName: zod.z.string()
742
- }))
743
- }).optional()
519
+ ref: zod.z.string(),
520
+ slug: zod.z.string(),
521
+ name: zod.z.string()
744
522
  });
745
- var CreateUploadPayloadUrlResponseBody = zod.z.object({
746
- presignedUrl: zod.z.string()
523
+ var TaskRunExecutionQueue = zod.z.object({
524
+ id: zod.z.string(),
525
+ name: zod.z.string()
747
526
  });
748
- var ReplayRunResponse = zod.z.object({
527
+ var TaskRunExecutionBatch = zod.z.object({
749
528
  id: zod.z.string()
750
529
  });
751
- var CanceledRunResponse = zod.z.object({
752
- message: zod.z.string()
530
+ var TaskRunExecution = zod.z.object({
531
+ task: TaskRunExecutionTask,
532
+ attempt: TaskRunExecutionAttempt,
533
+ run: TaskRun,
534
+ queue: TaskRunExecutionQueue,
535
+ environment: TaskRunExecutionEnvironment,
536
+ organization: TaskRunExecutionOrganization,
537
+ project: TaskRunExecutionProject,
538
+ batch: TaskRunExecutionBatch.optional()
753
539
  });
754
- var ScheduledTaskPayload = zod.z.object({
755
- /** The schedule id associated with this run (you can have many schedules for the same task).
756
- You can use this to remove the schedule, update it, etc */
757
- scheduleId: zod.z.string(),
758
- /** When the task was scheduled to run.
759
- * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
760
- timestamp: zod.z.date(),
761
- /** When the task was last run (it has been).
762
- This can be undefined if it's never been run */
763
- lastTimestamp: zod.z.date().optional(),
764
- /** You can optionally provide an external id when creating the schedule.
765
- Usually you would use a userId or some other unique identifier.
766
- This defaults to undefined if you didn't provide one. */
767
- externalId: zod.z.string().optional(),
768
- /** The next 5 dates this task is scheduled to run */
769
- upcoming: zod.z.array(zod.z.date())
540
+ var TaskRunContext = zod.z.object({
541
+ task: TaskRunExecutionTask,
542
+ attempt: TaskRunExecutionAttempt.omit({
543
+ backgroundWorkerId: true,
544
+ backgroundWorkerTaskId: true
545
+ }),
546
+ run: TaskRun.omit({
547
+ payload: true,
548
+ payloadType: true
549
+ }),
550
+ queue: TaskRunExecutionQueue,
551
+ environment: TaskRunExecutionEnvironment,
552
+ organization: TaskRunExecutionOrganization,
553
+ project: TaskRunExecutionProject,
554
+ batch: TaskRunExecutionBatch.optional()
770
555
  });
771
- var CreateScheduleOptions = zod.z.object({
772
- /** The id of the task you want to attach to. */
773
- task: zod.z.string(),
774
- /** The schedule in CRON format.
775
- *
776
- * ```txt
777
- * * * * * *
778
- ┬ ┬ ┬ ┬ ┬
779
- │ │ │ │ |
780
- │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
781
- │ │ │ └───── month (1 - 12)
782
- │ │ └────────── day of month (1 - 31, L)
783
- │ └─────────────── hour (0 - 23)
784
- └──────────────────── minute (0 - 59)
785
- * ```
786
-
787
- "L" means the last. In the "day of week" field, 1L means the last Monday of the month. In the day of month field, L means the last day of the month.
788
-
789
- */
790
- cron: zod.z.string(),
791
- /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
792
- *
793
- * This is useful if you don't want to create duplicate schedules for a user. */
794
- deduplicationKey: zod.z.string().optional(),
795
- /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
796
- *
797
- * This allows you to have per-user CRON tasks.
798
- */
799
- externalId: zod.z.string().optional()
556
+ var TaskRunExecutionRetry = zod.z.object({
557
+ timestamp: zod.z.number(),
558
+ delay: zod.z.number(),
559
+ error: zod.z.unknown().optional()
800
560
  });
801
- var UpdateScheduleOptions = CreateScheduleOptions;
802
- var ScheduleObject = zod.z.object({
561
+ var TaskRunFailedExecutionResult = zod.z.object({
562
+ ok: zod.z.literal(false),
803
563
  id: zod.z.string(),
804
- task: zod.z.string(),
805
- active: zod.z.boolean(),
806
- deduplicationKey: zod.z.string().nullish(),
807
- externalId: zod.z.string().nullish(),
808
- generator: zod.z.object({
809
- type: zod.z.literal("CRON"),
810
- expression: zod.z.string(),
811
- description: zod.z.string()
812
- }),
813
- nextRun: zod.z.coerce.date().nullish(),
814
- environments: zod.z.array(zod.z.object({
815
- id: zod.z.string(),
816
- type: zod.z.string(),
817
- userName: zod.z.string().nullish()
818
- }))
819
- });
820
- var DeletedScheduleObject = zod.z.object({
821
- id: zod.z.string()
564
+ error: TaskRunError,
565
+ retry: TaskRunExecutionRetry.optional(),
566
+ skippedRetrying: zod.z.boolean().optional()
822
567
  });
823
- var ListSchedulesResult = zod.z.object({
824
- data: zod.z.array(ScheduleObject),
825
- pagination: zod.z.object({
826
- currentPage: zod.z.number(),
827
- totalPages: zod.z.number(),
828
- count: zod.z.number()
829
- })
568
+ var TaskRunSuccessfulExecutionResult = zod.z.object({
569
+ ok: zod.z.literal(true),
570
+ id: zod.z.string(),
571
+ output: zod.z.string().optional(),
572
+ outputType: zod.z.string()
830
573
  });
831
- var ListScheduleOptions = zod.z.object({
832
- page: zod.z.number().optional(),
833
- perPage: zod.z.number().optional()
574
+ var TaskRunExecutionResult = zod.z.discriminatedUnion("ok", [
575
+ TaskRunSuccessfulExecutionResult,
576
+ TaskRunFailedExecutionResult
577
+ ]);
578
+ var BatchTaskRunExecutionResult = zod.z.object({
579
+ id: zod.z.string(),
580
+ items: TaskRunExecutionResult.array()
834
581
  });
835
- var PostStartCauses = zod.z.enum([
836
- "index",
837
- "create",
838
- "restore"
582
+
583
+ // src/v3/schemas/messages.ts
584
+ var EnvironmentType = zod.z.enum([
585
+ "PRODUCTION",
586
+ "STAGING",
587
+ "DEVELOPMENT",
588
+ "PREVIEW"
839
589
  ]);
840
- var PreStopCauses = zod.z.enum([
841
- "terminate"
842
- ]);
843
- var RegexSchema = zod.z.custom((val) => {
844
- try {
845
- return typeof val.test === "function";
846
- } catch {
847
- return false;
848
- }
590
+ var MachineCpu = zod.z.union([
591
+ zod.z.literal(0.25),
592
+ zod.z.literal(0.5),
593
+ zod.z.literal(1),
594
+ zod.z.literal(2),
595
+ zod.z.literal(4)
596
+ ]).default(0.5);
597
+ var MachineMemory = zod.z.union([
598
+ zod.z.literal(0.25),
599
+ zod.z.literal(0.5),
600
+ zod.z.literal(1),
601
+ zod.z.literal(2),
602
+ zod.z.literal(4),
603
+ zod.z.literal(8)
604
+ ]).default(1);
605
+ var Machine = zod.z.object({
606
+ version: zod.z.literal("v1").default("v1"),
607
+ cpu: MachineCpu,
608
+ memory: MachineMemory
849
609
  });
850
- var Config = zod.z.object({
851
- project: zod.z.string(),
852
- triggerDirectories: zod.z.string().array().optional(),
853
- triggerUrl: zod.z.string().optional(),
854
- projectDir: zod.z.string().optional(),
855
- tsconfigPath: zod.z.string().optional(),
856
- retries: zod.z.object({
857
- enabledInDev: zod.z.boolean().default(true),
858
- default: RetryOptions.optional()
859
- }).optional(),
860
- additionalPackages: zod.z.string().array().optional(),
861
- additionalFiles: zod.z.string().array().optional(),
862
- dependenciesToBundle: zod.z.array(zod.z.union([
863
- zod.z.string(),
864
- RegexSchema
865
- ])).optional(),
866
- logLevel: zod.z.string().optional(),
867
- enableConsoleLogging: zod.z.boolean().optional()
610
+ var TaskRunExecutionPayload = zod.z.object({
611
+ execution: TaskRunExecution,
612
+ traceContext: zod.z.record(zod.z.unknown()),
613
+ environment: zod.z.record(zod.z.string()).optional()
868
614
  });
869
- var WaitReason = zod.z.enum([
870
- "WAIT_FOR_DURATION",
871
- "WAIT_FOR_TASK",
872
- "WAIT_FOR_BATCH"
873
- ]);
874
- var ProviderToPlatformMessages = {
875
- LOG: {
876
- message: zod.z.object({
877
- version: zod.z.literal("v1").default("v1"),
878
- data: zod.z.string()
879
- })
880
- },
881
- LOG_WITH_ACK: {
882
- message: zod.z.object({
883
- version: zod.z.literal("v1").default("v1"),
884
- data: zod.z.string()
885
- }),
886
- callback: zod.z.object({
887
- status: zod.z.literal("ok")
888
- })
889
- },
890
- WORKER_CRASHED: {
891
- message: zod.z.object({
892
- version: zod.z.literal("v1").default("v1"),
893
- runId: zod.z.string(),
894
- reason: zod.z.string().optional(),
895
- exitCode: zod.z.number().optional(),
896
- message: zod.z.string().optional(),
897
- logs: zod.z.string().optional()
898
- })
899
- },
900
- INDEXING_FAILED: {
901
- message: zod.z.object({
902
- version: zod.z.literal("v1").default("v1"),
903
- deploymentId: zod.z.string(),
904
- error: zod.z.object({
905
- name: zod.z.string(),
906
- message: zod.z.string(),
907
- stack: zod.z.string().optional()
908
- })
909
- })
910
- }
911
- };
912
- var PlatformToProviderMessages = {
913
- HEALTH: {
914
- message: zod.z.object({
915
- version: zod.z.literal("v1").default("v1")
916
- }),
917
- callback: zod.z.object({
918
- status: zod.z.literal("ok")
919
- })
920
- },
921
- INDEX: {
922
- message: zod.z.object({
923
- version: zod.z.literal("v1").default("v1"),
924
- imageTag: zod.z.string(),
925
- shortCode: zod.z.string(),
926
- apiKey: zod.z.string(),
927
- apiUrl: zod.z.string(),
928
- // identifiers
929
- envId: zod.z.string(),
930
- envType: EnvironmentType,
931
- orgId: zod.z.string(),
932
- projectId: zod.z.string(),
933
- deploymentId: zod.z.string()
934
- }),
935
- callback: zod.z.discriminatedUnion("success", [
936
- zod.z.object({
937
- success: zod.z.literal(false),
938
- error: zod.z.object({
939
- name: zod.z.string(),
940
- message: zod.z.string(),
941
- stack: zod.z.string().optional()
942
- })
943
- }),
944
- zod.z.object({
945
- success: zod.z.literal(true)
946
- })
947
- ])
948
- },
949
- // TODO: this should be a shared queue message instead
950
- RESTORE: {
951
- message: zod.z.object({
952
- version: zod.z.literal("v1").default("v1"),
953
- type: zod.z.enum([
954
- "DOCKER",
955
- "KUBERNETES"
956
- ]),
957
- location: zod.z.string(),
958
- reason: zod.z.string().optional(),
959
- imageRef: zod.z.string(),
960
- machine: Machine,
961
- // identifiers
962
- checkpointId: zod.z.string(),
963
- envId: zod.z.string(),
964
- envType: EnvironmentType,
965
- orgId: zod.z.string(),
966
- projectId: zod.z.string(),
967
- runId: zod.z.string()
968
- })
969
- },
970
- DELETE: {
971
- message: zod.z.object({
972
- version: zod.z.literal("v1").default("v1"),
973
- name: zod.z.string()
974
- }),
975
- callback: zod.z.object({
976
- message: zod.z.string()
977
- })
978
- },
979
- GET: {
980
- message: zod.z.object({
981
- version: zod.z.literal("v1").default("v1"),
982
- name: zod.z.string()
983
- })
984
- }
985
- };
986
- var CoordinatorToPlatformMessages = {
987
- LOG: {
988
- message: zod.z.object({
989
- version: zod.z.literal("v1").default("v1"),
990
- metadata: zod.z.any(),
991
- text: zod.z.string()
992
- })
993
- },
994
- CREATE_WORKER: {
995
- message: zod.z.object({
996
- version: zod.z.literal("v1").default("v1"),
997
- projectRef: zod.z.string(),
998
- envId: zod.z.string(),
999
- deploymentId: zod.z.string(),
1000
- metadata: zod.z.object({
1001
- cliPackageVersion: zod.z.string().optional(),
1002
- contentHash: zod.z.string(),
1003
- packageVersion: zod.z.string(),
1004
- tasks: TaskResource.array()
1005
- })
1006
- }),
1007
- callback: zod.z.discriminatedUnion("success", [
1008
- zod.z.object({
1009
- success: zod.z.literal(false)
1010
- }),
1011
- zod.z.object({
1012
- success: zod.z.literal(true)
1013
- })
1014
- ])
1015
- },
1016
- READY_FOR_EXECUTION: {
1017
- message: zod.z.object({
1018
- version: zod.z.literal("v1").default("v1"),
1019
- runId: zod.z.string(),
1020
- totalCompletions: zod.z.number()
1021
- }),
1022
- callback: zod.z.discriminatedUnion("success", [
1023
- zod.z.object({
1024
- success: zod.z.literal(false)
1025
- }),
1026
- zod.z.object({
1027
- success: zod.z.literal(true),
1028
- payload: ProdTaskRunExecutionPayload
1029
- })
1030
- ])
1031
- },
1032
- READY_FOR_RESUME: {
1033
- message: zod.z.object({
1034
- version: zod.z.literal("v1").default("v1"),
1035
- attemptFriendlyId: zod.z.string(),
1036
- type: WaitReason
1037
- })
1038
- },
1039
- TASK_RUN_COMPLETED: {
1040
- message: zod.z.object({
1041
- version: zod.z.literal("v1").default("v1"),
1042
- execution: ProdTaskRunExecution,
1043
- completion: TaskRunExecutionResult,
1044
- checkpoint: zod.z.object({
1045
- docker: zod.z.boolean(),
1046
- location: zod.z.string()
1047
- }).optional()
1048
- })
1049
- },
1050
- TASK_HEARTBEAT: {
1051
- message: zod.z.object({
1052
- version: zod.z.literal("v1").default("v1"),
1053
- attemptFriendlyId: zod.z.string()
1054
- })
1055
- },
1056
- CHECKPOINT_CREATED: {
1057
- message: zod.z.object({
1058
- version: zod.z.literal("v1").default("v1"),
1059
- attemptFriendlyId: zod.z.string(),
1060
- docker: zod.z.boolean(),
1061
- location: zod.z.string(),
1062
- reason: zod.z.discriminatedUnion("type", [
1063
- zod.z.object({
1064
- type: zod.z.literal("WAIT_FOR_DURATION"),
1065
- ms: zod.z.number(),
1066
- now: zod.z.number()
1067
- }),
1068
- zod.z.object({
1069
- type: zod.z.literal("WAIT_FOR_BATCH"),
1070
- batchFriendlyId: zod.z.string(),
1071
- runFriendlyIds: zod.z.string().array()
1072
- }),
1073
- zod.z.object({
1074
- type: zod.z.literal("WAIT_FOR_TASK"),
1075
- friendlyId: zod.z.string()
1076
- }),
1077
- zod.z.object({
1078
- type: zod.z.literal("RETRYING_AFTER_FAILURE"),
1079
- attemptNumber: zod.z.number()
1080
- })
1081
- ])
1082
- })
1083
- },
1084
- INDEXING_FAILED: {
1085
- message: zod.z.object({
1086
- version: zod.z.literal("v1").default("v1"),
1087
- deploymentId: zod.z.string(),
1088
- error: zod.z.object({
1089
- name: zod.z.string(),
1090
- message: zod.z.string(),
1091
- stack: zod.z.string().optional()
1092
- })
1093
- })
1094
- }
1095
- };
1096
- var PlatformToCoordinatorMessages = {
1097
- RESUME_AFTER_DEPENDENCY: {
1098
- message: zod.z.object({
1099
- version: zod.z.literal("v1").default("v1"),
1100
- runId: zod.z.string(),
1101
- attemptId: zod.z.string(),
1102
- attemptFriendlyId: zod.z.string(),
1103
- completions: TaskRunExecutionResult.array(),
1104
- executions: TaskRunExecution.array()
1105
- })
1106
- },
1107
- RESUME_AFTER_DURATION: {
1108
- message: zod.z.object({
1109
- version: zod.z.literal("v1").default("v1"),
1110
- attemptId: zod.z.string(),
1111
- attemptFriendlyId: zod.z.string()
1112
- })
1113
- },
1114
- REQUEST_ATTEMPT_CANCELLATION: {
1115
- message: zod.z.object({
1116
- version: zod.z.literal("v1").default("v1"),
1117
- attemptId: zod.z.string(),
1118
- attemptFriendlyId: zod.z.string()
1119
- })
1120
- },
1121
- READY_FOR_RETRY: {
1122
- message: zod.z.object({
1123
- version: zod.z.literal("v1").default("v1"),
1124
- runId: zod.z.string()
1125
- })
1126
- }
615
+ var ProdTaskRunExecution = TaskRunExecution.extend({
616
+ worker: zod.z.object({
617
+ id: zod.z.string(),
618
+ contentHash: zod.z.string(),
619
+ version: zod.z.string()
620
+ })
621
+ });
622
+ var ProdTaskRunExecutionPayload = zod.z.object({
623
+ execution: ProdTaskRunExecution,
624
+ traceContext: zod.z.record(zod.z.unknown()),
625
+ environment: zod.z.record(zod.z.string()).optional()
626
+ });
627
+ var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
628
+ zod.z.object({
629
+ type: zod.z.literal("EXECUTE_RUNS"),
630
+ payloads: zod.z.array(TaskRunExecutionPayload)
631
+ }),
632
+ zod.z.object({
633
+ type: zod.z.literal("CANCEL_ATTEMPT"),
634
+ taskAttemptId: zod.z.string(),
635
+ taskRunId: zod.z.string()
636
+ }),
637
+ zod.z.object({
638
+ type: zod.z.literal("SCHEDULE_ATTEMPT"),
639
+ image: zod.z.string(),
640
+ version: zod.z.string(),
641
+ machine: Machine,
642
+ // identifiers
643
+ id: zod.z.string(),
644
+ envId: zod.z.string(),
645
+ envType: EnvironmentType,
646
+ orgId: zod.z.string(),
647
+ projectId: zod.z.string(),
648
+ runId: zod.z.string()
649
+ })
650
+ ]);
651
+ var serverWebsocketMessages = {
652
+ SERVER_READY: zod.z.object({
653
+ version: zod.z.literal("v1").default("v1"),
654
+ id: zod.z.string()
655
+ }),
656
+ BACKGROUND_WORKER_MESSAGE: zod.z.object({
657
+ version: zod.z.literal("v1").default("v1"),
658
+ backgroundWorkerId: zod.z.string(),
659
+ data: BackgroundWorkerServerMessages
660
+ })
1127
661
  };
1128
- var ClientToSharedQueueMessages = {
1129
- READY_FOR_TASKS: {
1130
- message: zod.z.object({
1131
- version: zod.z.literal("v1").default("v1"),
1132
- backgroundWorkerId: zod.z.string()
1133
- })
1134
- },
1135
- BACKGROUND_WORKER_DEPRECATED: {
1136
- message: zod.z.object({
1137
- version: zod.z.literal("v1").default("v1"),
1138
- backgroundWorkerId: zod.z.string()
1139
- })
1140
- },
1141
- BACKGROUND_WORKER_MESSAGE: {
1142
- message: zod.z.object({
1143
- version: zod.z.literal("v1").default("v1"),
1144
- backgroundWorkerId: zod.z.string(),
1145
- data: BackgroundWorkerClientMessages
1146
- })
1147
- }
662
+ var BackgroundWorkerClientMessages = zod.z.discriminatedUnion("type", [
663
+ zod.z.object({
664
+ version: zod.z.literal("v1").default("v1"),
665
+ type: zod.z.literal("TASK_RUN_COMPLETED"),
666
+ completion: TaskRunExecutionResult,
667
+ execution: TaskRunExecution
668
+ }),
669
+ zod.z.object({
670
+ version: zod.z.literal("v1").default("v1"),
671
+ type: zod.z.literal("TASK_HEARTBEAT"),
672
+ id: zod.z.string()
673
+ })
674
+ ]);
675
+ var BackgroundWorkerProperties = zod.z.object({
676
+ id: zod.z.string(),
677
+ version: zod.z.string(),
678
+ contentHash: zod.z.string()
679
+ });
680
+ var clientWebsocketMessages = {
681
+ READY_FOR_TASKS: zod.z.object({
682
+ version: zod.z.literal("v1").default("v1"),
683
+ backgroundWorkerId: zod.z.string()
684
+ }),
685
+ BACKGROUND_WORKER_DEPRECATED: zod.z.object({
686
+ version: zod.z.literal("v1").default("v1"),
687
+ backgroundWorkerId: zod.z.string()
688
+ }),
689
+ BACKGROUND_WORKER_MESSAGE: zod.z.object({
690
+ version: zod.z.literal("v1").default("v1"),
691
+ backgroundWorkerId: zod.z.string(),
692
+ data: BackgroundWorkerClientMessages
693
+ })
1148
694
  };
1149
- var SharedQueueToClientMessages = {
1150
- SERVER_READY: {
1151
- message: zod.z.object({
1152
- version: zod.z.literal("v1").default("v1"),
1153
- id: zod.z.string()
1154
- })
1155
- },
1156
- BACKGROUND_WORKER_MESSAGE: {
1157
- message: zod.z.object({
1158
- version: zod.z.literal("v1").default("v1"),
1159
- backgroundWorkerId: zod.z.string(),
1160
- data: BackgroundWorkerServerMessages
1161
- })
1162
- }
695
+ var workerToChildMessages = {
696
+ EXECUTE_TASK_RUN: zod.z.object({
697
+ version: zod.z.literal("v1").default("v1"),
698
+ execution: TaskRunExecution,
699
+ traceContext: zod.z.record(zod.z.unknown()),
700
+ metadata: BackgroundWorkerProperties
701
+ }),
702
+ TASK_RUN_COMPLETED_NOTIFICATION: zod.z.object({
703
+ version: zod.z.literal("v1").default("v1"),
704
+ completion: TaskRunExecutionResult,
705
+ execution: TaskRunExecution
706
+ }),
707
+ CLEANUP: zod.z.object({
708
+ version: zod.z.literal("v1").default("v1"),
709
+ flush: zod.z.boolean().default(false),
710
+ kill: zod.z.boolean().default(true)
711
+ })
1163
712
  };
1164
- var ProdWorkerToCoordinatorMessages = {
1165
- LOG: {
1166
- message: zod.z.object({
1167
- version: zod.z.literal("v1").default("v1"),
1168
- text: zod.z.string()
713
+ var FixedWindowRateLimit = zod.z.object({
714
+ type: zod.z.literal("fixed-window"),
715
+ limit: zod.z.number(),
716
+ window: zod.z.union([
717
+ zod.z.object({
718
+ seconds: zod.z.number()
1169
719
  }),
1170
- callback: zod.z.void()
1171
- },
1172
- INDEX_TASKS: {
720
+ zod.z.object({
721
+ minutes: zod.z.number()
722
+ }),
723
+ zod.z.object({
724
+ hours: zod.z.number()
725
+ })
726
+ ])
727
+ });
728
+ var SlidingWindowRateLimit = zod.z.object({
729
+ type: zod.z.literal("sliding-window"),
730
+ limit: zod.z.number(),
731
+ window: zod.z.union([
732
+ zod.z.object({
733
+ seconds: zod.z.number()
734
+ }),
735
+ zod.z.object({
736
+ minutes: zod.z.number()
737
+ }),
738
+ zod.z.object({
739
+ hours: zod.z.number()
740
+ })
741
+ ])
742
+ });
743
+ var RateLimitOptions = zod.z.discriminatedUnion("type", [
744
+ FixedWindowRateLimit,
745
+ SlidingWindowRateLimit
746
+ ]);
747
+ var RetryOptions = zod.z.object({
748
+ /** The number of attempts before giving up */
749
+ maxAttempts: zod.z.number().int().optional(),
750
+ /** The exponential factor to use when calculating the next retry time.
751
+ *
752
+ * Each subsequent retry will be calculated as `previousTimeout * factor`
753
+ */
754
+ factor: zod.z.number().optional(),
755
+ /** The minimum time to wait before retrying */
756
+ minTimeoutInMs: zod.z.number().int().optional(),
757
+ /** The maximum time to wait before retrying */
758
+ maxTimeoutInMs: zod.z.number().int().optional(),
759
+ /** Randomize the timeout between retries.
760
+ *
761
+ * This can be useful to prevent the thundering herd problem where all retries happen at the same time.
762
+ */
763
+ randomize: zod.z.boolean().optional()
764
+ });
765
+ var QueueOptions = zod.z.object({
766
+ /** You can define a shared queue and then pass the name in to your task.
767
+ *
768
+ * @example
769
+ *
770
+ * ```ts
771
+ * const myQueue = queue({
772
+ name: "my-queue",
773
+ concurrencyLimit: 1,
774
+ });
775
+
776
+ export const task1 = task({
777
+ id: "task-1",
778
+ queue: {
779
+ name: "my-queue",
780
+ },
781
+ run: async (payload: { message: string }) => {
782
+ // ...
783
+ },
784
+ });
785
+
786
+ export const task2 = task({
787
+ id: "task-2",
788
+ queue: {
789
+ name: "my-queue",
790
+ },
791
+ run: async (payload: { message: string }) => {
792
+ // ...
793
+ },
794
+ });
795
+ * ```
796
+ */
797
+ name: zod.z.string().optional(),
798
+ /** An optional property that specifies the maximum number of concurrent run executions.
799
+ *
800
+ * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
801
+ concurrencyLimit: zod.z.number().int().min(0).max(1e3).optional(),
802
+ /** @deprecated This feature is coming soon */
803
+ rateLimit: RateLimitOptions.optional()
804
+ });
805
+ var TaskMetadata = zod.z.object({
806
+ id: zod.z.string(),
807
+ packageVersion: zod.z.string(),
808
+ queue: QueueOptions.optional(),
809
+ retry: RetryOptions.optional(),
810
+ machine: Machine.partial().optional(),
811
+ triggerSource: zod.z.string().optional()
812
+ });
813
+ var TaskFileMetadata = zod.z.object({
814
+ filePath: zod.z.string(),
815
+ exportName: zod.z.string()
816
+ });
817
+ var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
818
+ var UncaughtExceptionMessage = zod.z.object({
819
+ version: zod.z.literal("v1").default("v1"),
820
+ error: zod.z.object({
821
+ name: zod.z.string(),
822
+ message: zod.z.string(),
823
+ stack: zod.z.string().optional()
824
+ }),
825
+ origin: zod.z.enum([
826
+ "uncaughtException",
827
+ "unhandledRejection"
828
+ ])
829
+ });
830
+ var TaskMetadataFailedToParseData = zod.z.object({
831
+ version: zod.z.literal("v1").default("v1"),
832
+ tasks: zod.z.unknown(),
833
+ zodIssues: zod.z.custom((v) => {
834
+ return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
835
+ })
836
+ });
837
+ var childToWorkerMessages = {
838
+ TASK_RUN_COMPLETED: zod.z.object({
839
+ version: zod.z.literal("v1").default("v1"),
840
+ execution: TaskRunExecution,
841
+ result: TaskRunExecutionResult
842
+ }),
843
+ TASKS_READY: zod.z.object({
844
+ version: zod.z.literal("v1").default("v1"),
845
+ tasks: TaskMetadataWithFilePath.array()
846
+ }),
847
+ TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
848
+ TASK_HEARTBEAT: zod.z.object({
849
+ version: zod.z.literal("v1").default("v1"),
850
+ id: zod.z.string()
851
+ }),
852
+ READY_TO_DISPOSE: zod.z.undefined(),
853
+ WAIT_FOR_DURATION: zod.z.object({
854
+ version: zod.z.literal("v1").default("v1"),
855
+ ms: zod.z.number()
856
+ }),
857
+ WAIT_FOR_TASK: zod.z.object({
858
+ version: zod.z.literal("v1").default("v1"),
859
+ id: zod.z.string()
860
+ }),
861
+ WAIT_FOR_BATCH: zod.z.object({
862
+ version: zod.z.literal("v1").default("v1"),
863
+ id: zod.z.string(),
864
+ runs: zod.z.string().array()
865
+ }),
866
+ UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
867
+ };
868
+ var ProdChildToWorkerMessages = {
869
+ TASK_RUN_COMPLETED: {
1173
870
  message: zod.z.object({
1174
871
  version: zod.z.literal("v1").default("v1"),
1175
- deploymentId: zod.z.string(),
1176
- tasks: TaskResource.array(),
1177
- packageVersion: zod.z.string()
1178
- }),
1179
- callback: zod.z.discriminatedUnion("success", [
1180
- zod.z.object({
1181
- success: zod.z.literal(false)
1182
- }),
1183
- zod.z.object({
1184
- success: zod.z.literal(true)
1185
- })
1186
- ])
872
+ execution: TaskRunExecution,
873
+ result: TaskRunExecutionResult
874
+ })
1187
875
  },
1188
- READY_FOR_EXECUTION: {
876
+ TASKS_READY: {
1189
877
  message: zod.z.object({
1190
878
  version: zod.z.literal("v1").default("v1"),
1191
- runId: zod.z.string(),
1192
- totalCompletions: zod.z.number()
879
+ tasks: TaskMetadataWithFilePath.array()
1193
880
  })
1194
881
  },
1195
- READY_FOR_RESUME: {
882
+ TASKS_FAILED_TO_PARSE: {
883
+ message: TaskMetadataFailedToParseData
884
+ },
885
+ TASK_HEARTBEAT: {
1196
886
  message: zod.z.object({
1197
887
  version: zod.z.literal("v1").default("v1"),
1198
- attemptFriendlyId: zod.z.string(),
1199
- type: WaitReason
888
+ id: zod.z.string()
1200
889
  })
1201
890
  },
891
+ READY_TO_DISPOSE: {
892
+ message: zod.z.undefined()
893
+ },
1202
894
  READY_FOR_CHECKPOINT: {
1203
895
  message: zod.z.object({
1204
896
  version: zod.z.literal("v1").default("v1")
@@ -1209,29 +901,11 @@ var ProdWorkerToCoordinatorMessages = {
1209
901
  version: zod.z.literal("v1").default("v1")
1210
902
  })
1211
903
  },
1212
- TASK_HEARTBEAT: {
1213
- message: zod.z.object({
1214
- version: zod.z.literal("v1").default("v1"),
1215
- attemptFriendlyId: zod.z.string()
1216
- })
1217
- },
1218
- TASK_RUN_COMPLETED: {
1219
- message: zod.z.object({
1220
- version: zod.z.literal("v1").default("v1"),
1221
- execution: ProdTaskRunExecution,
1222
- completion: TaskRunExecutionResult
1223
- }),
1224
- callback: zod.z.object({
1225
- willCheckpointAndRestore: zod.z.boolean(),
1226
- shouldExit: zod.z.boolean()
1227
- })
1228
- },
1229
904
  WAIT_FOR_DURATION: {
1230
905
  message: zod.z.object({
1231
906
  version: zod.z.literal("v1").default("v1"),
1232
907
  ms: zod.z.number(),
1233
- now: zod.z.number(),
1234
- attemptFriendlyId: zod.z.string()
908
+ now: zod.z.number()
1235
909
  }),
1236
910
  callback: zod.z.object({
1237
911
  willCheckpointAndRestore: zod.z.boolean()
@@ -1240,772 +914,1008 @@ var ProdWorkerToCoordinatorMessages = {
1240
914
  WAIT_FOR_TASK: {
1241
915
  message: zod.z.object({
1242
916
  version: zod.z.literal("v1").default("v1"),
1243
- friendlyId: zod.z.string(),
1244
- // This is the attempt that is waiting
1245
- attemptFriendlyId: zod.z.string()
1246
- }),
1247
- callback: zod.z.object({
1248
- willCheckpointAndRestore: zod.z.boolean()
917
+ friendlyId: zod.z.string()
1249
918
  })
1250
919
  },
1251
920
  WAIT_FOR_BATCH: {
1252
921
  message: zod.z.object({
1253
922
  version: zod.z.literal("v1").default("v1"),
1254
923
  batchFriendlyId: zod.z.string(),
1255
- runFriendlyIds: zod.z.string().array(),
1256
- // This is the attempt that is waiting
1257
- attemptFriendlyId: zod.z.string()
1258
- }),
1259
- callback: zod.z.object({
1260
- willCheckpointAndRestore: zod.z.boolean()
924
+ runFriendlyIds: zod.z.string().array()
1261
925
  })
1262
926
  },
1263
- INDEXING_FAILED: {
1264
- message: zod.z.object({
1265
- version: zod.z.literal("v1").default("v1"),
1266
- deploymentId: zod.z.string(),
1267
- error: zod.z.object({
1268
- name: zod.z.string(),
1269
- message: zod.z.string(),
1270
- stack: zod.z.string().optional()
1271
- })
1272
- })
927
+ UNCAUGHT_EXCEPTION: {
928
+ message: UncaughtExceptionMessage
1273
929
  }
1274
930
  };
1275
- var CoordinatorToProdWorkerMessages = {
1276
- RESUME_AFTER_DEPENDENCY: {
1277
- message: zod.z.object({
1278
- version: zod.z.literal("v1").default("v1"),
1279
- attemptId: zod.z.string(),
1280
- completions: TaskRunExecutionResult.array(),
1281
- executions: TaskRunExecution.array()
1282
- })
1283
- },
1284
- RESUME_AFTER_DURATION: {
931
+ var ProdWorkerToChildMessages = {
932
+ EXECUTE_TASK_RUN: {
1285
933
  message: zod.z.object({
1286
934
  version: zod.z.literal("v1").default("v1"),
1287
- attemptId: zod.z.string()
935
+ execution: TaskRunExecution,
936
+ traceContext: zod.z.record(zod.z.unknown()),
937
+ metadata: BackgroundWorkerProperties
1288
938
  })
1289
939
  },
1290
- EXECUTE_TASK_RUN: {
940
+ TASK_RUN_COMPLETED_NOTIFICATION: {
1291
941
  message: zod.z.object({
1292
942
  version: zod.z.literal("v1").default("v1"),
1293
- executionPayload: ProdTaskRunExecutionPayload
943
+ completion: TaskRunExecutionResult,
944
+ execution: TaskRunExecution
1294
945
  })
1295
946
  },
1296
- REQUEST_ATTEMPT_CANCELLATION: {
947
+ CLEANUP: {
1297
948
  message: zod.z.object({
1298
949
  version: zod.z.literal("v1").default("v1"),
1299
- attemptId: zod.z.string()
1300
- })
950
+ flush: zod.z.boolean().default(false),
951
+ kill: zod.z.boolean().default(true)
952
+ }),
953
+ callback: zod.z.void()
1301
954
  },
1302
- REQUEST_EXIT: {
955
+ WAIT_COMPLETED_NOTIFICATION: {
1303
956
  message: zod.z.object({
1304
957
  version: zod.z.literal("v1").default("v1")
1305
958
  })
1306
- },
1307
- READY_FOR_RETRY: {
1308
- message: zod.z.object({
1309
- version: zod.z.literal("v1").default("v1"),
1310
- runId: zod.z.string()
1311
- })
1312
959
  }
1313
960
  };
1314
- var ProdWorkerSocketData = zod.z.object({
961
+
962
+ // src/v3/schemas/resources.ts
963
+ var TaskResource = zod.z.object({
964
+ id: zod.z.string(),
965
+ filePath: zod.z.string(),
966
+ exportName: zod.z.string(),
967
+ queue: QueueOptions.optional(),
968
+ retry: RetryOptions.optional(),
969
+ machine: Machine.partial().optional(),
970
+ triggerSource: zod.z.string().optional()
971
+ });
972
+ var BackgroundWorkerMetadata = zod.z.object({
973
+ packageVersion: zod.z.string(),
1315
974
  contentHash: zod.z.string(),
1316
- projectRef: zod.z.string(),
1317
- envId: zod.z.string(),
1318
- runId: zod.z.string(),
1319
- attemptFriendlyId: zod.z.string().optional(),
1320
- podName: zod.z.string(),
1321
- deploymentId: zod.z.string(),
1322
- deploymentVersion: zod.z.string()
975
+ cliPackageVersion: zod.z.string().optional(),
976
+ tasks: zod.z.array(TaskResource)
1323
977
  });
1324
- var PRIMARY_VARIANT = "primary";
1325
- var Variant = zod.z.enum([
1326
- PRIMARY_VARIANT
1327
- ]);
1328
- var AccessoryItem = zod.z.object({
1329
- text: zod.z.string(),
1330
- variant: zod.z.string().optional(),
1331
- url: zod.z.string().optional()
978
+ var ImageDetailsMetadata = zod.z.object({
979
+ contentHash: zod.z.string(),
980
+ imageTag: zod.z.string()
981
+ });
982
+
983
+ // src/v3/schemas/api.ts
984
+ var WhoAmIResponseSchema = zod.z.object({
985
+ userId: zod.z.string(),
986
+ email: zod.z.string().email(),
987
+ dashboardUrl: zod.z.string()
988
+ });
989
+ var GetProjectResponseBody = zod.z.object({
990
+ id: zod.z.string(),
991
+ externalRef: zod.z.string(),
992
+ name: zod.z.string(),
993
+ slug: zod.z.string(),
994
+ createdAt: zod.z.coerce.date(),
995
+ organization: zod.z.object({
996
+ id: zod.z.string(),
997
+ title: zod.z.string(),
998
+ slug: zod.z.string(),
999
+ createdAt: zod.z.coerce.date()
1000
+ })
1001
+ });
1002
+ var GetProjectsResponseBody = zod.z.array(GetProjectResponseBody);
1003
+ var GetProjectEnvResponse = zod.z.object({
1004
+ apiKey: zod.z.string(),
1005
+ name: zod.z.string(),
1006
+ apiUrl: zod.z.string()
1007
+ });
1008
+ var CreateBackgroundWorkerRequestBody = zod.z.object({
1009
+ localOnly: zod.z.boolean(),
1010
+ metadata: BackgroundWorkerMetadata
1011
+ });
1012
+ var CreateBackgroundWorkerResponse = zod.z.object({
1013
+ id: zod.z.string(),
1014
+ version: zod.z.string(),
1015
+ contentHash: zod.z.string()
1016
+ });
1017
+ var TriggerTaskRequestBody = zod.z.object({
1018
+ payload: zod.z.any(),
1019
+ context: zod.z.any(),
1020
+ options: zod.z.object({
1021
+ dependentAttempt: zod.z.string().optional(),
1022
+ dependentBatch: zod.z.string().optional(),
1023
+ lockToVersion: zod.z.string().optional(),
1024
+ queue: QueueOptions.optional(),
1025
+ concurrencyKey: zod.z.string().optional(),
1026
+ idempotencyKey: zod.z.string().optional(),
1027
+ test: zod.z.boolean().optional(),
1028
+ payloadType: zod.z.string().optional()
1029
+ }).optional()
1030
+ });
1031
+ var TriggerTaskResponse = zod.z.object({
1032
+ id: zod.z.string()
1033
+ });
1034
+ var BatchTriggerTaskRequestBody = zod.z.object({
1035
+ items: TriggerTaskRequestBody.array(),
1036
+ dependentAttempt: zod.z.string().optional()
1037
+ });
1038
+ var BatchTriggerTaskResponse = zod.z.object({
1039
+ batchId: zod.z.string(),
1040
+ runs: zod.z.string().array()
1041
+ });
1042
+ var GetBatchResponseBody = zod.z.object({
1043
+ id: zod.z.string(),
1044
+ items: zod.z.array(zod.z.object({
1045
+ id: zod.z.string(),
1046
+ taskRunId: zod.z.string(),
1047
+ status: zod.z.enum([
1048
+ "PENDING",
1049
+ "CANCELED",
1050
+ "COMPLETED",
1051
+ "FAILED"
1052
+ ])
1053
+ }))
1054
+ });
1055
+ var GetEnvironmentVariablesResponseBody = zod.z.object({
1056
+ variables: zod.z.record(zod.z.string())
1057
+ });
1058
+ var StartDeploymentIndexingRequestBody = zod.z.object({
1059
+ imageReference: zod.z.string()
1060
+ });
1061
+ var StartDeploymentIndexingResponseBody = zod.z.object({
1062
+ id: zod.z.string(),
1063
+ contentHash: zod.z.string()
1064
+ });
1065
+ var ExternalBuildData = zod.z.object({
1066
+ buildId: zod.z.string(),
1067
+ buildToken: zod.z.string(),
1068
+ projectId: zod.z.string()
1069
+ });
1070
+ var InitializeDeploymentResponseBody = zod.z.object({
1071
+ id: zod.z.string(),
1072
+ contentHash: zod.z.string(),
1073
+ shortCode: zod.z.string(),
1074
+ version: zod.z.string(),
1075
+ imageTag: zod.z.string(),
1076
+ externalBuildData: ExternalBuildData.optional().nullable(),
1077
+ registryHost: zod.z.string().optional()
1078
+ });
1079
+ var InitializeDeploymentRequestBody = zod.z.object({
1080
+ contentHash: zod.z.string(),
1081
+ userId: zod.z.string().optional()
1082
+ });
1083
+ var DeploymentErrorData = zod.z.object({
1084
+ name: zod.z.string(),
1085
+ message: zod.z.string(),
1086
+ stack: zod.z.string().optional()
1332
1087
  });
1333
- var Accessory = zod.z.object({
1334
- items: zod.z.array(AccessoryItem),
1335
- style: zod.z.enum([
1336
- "codepath"
1337
- ]).optional()
1088
+ var GetDeploymentResponseBody = zod.z.object({
1089
+ id: zod.z.string(),
1090
+ status: zod.z.enum([
1091
+ "PENDING",
1092
+ "BUILDING",
1093
+ "DEPLOYING",
1094
+ "DEPLOYED",
1095
+ "FAILED",
1096
+ "CANCELED",
1097
+ "TIMED_OUT"
1098
+ ]),
1099
+ contentHash: zod.z.string(),
1100
+ shortCode: zod.z.string(),
1101
+ version: zod.z.string(),
1102
+ imageReference: zod.z.string().optional(),
1103
+ errorData: DeploymentErrorData.optional().nullable(),
1104
+ worker: zod.z.object({
1105
+ id: zod.z.string(),
1106
+ version: zod.z.string(),
1107
+ tasks: zod.z.array(zod.z.object({
1108
+ id: zod.z.string(),
1109
+ slug: zod.z.string(),
1110
+ filePath: zod.z.string(),
1111
+ exportName: zod.z.string()
1112
+ }))
1113
+ }).optional()
1338
1114
  });
1339
- var TaskEventStyle = zod.z.object({
1340
- icon: zod.z.string().optional(),
1341
- variant: Variant.optional(),
1342
- accessory: Accessory.optional()
1343
- }).default({
1344
- icon: void 0,
1345
- variant: void 0
1115
+ var CreateUploadPayloadUrlResponseBody = zod.z.object({
1116
+ presignedUrl: zod.z.string()
1346
1117
  });
1347
- var stringPatternMatchers = [
1348
- zod.z.object({
1349
- $endsWith: zod.z.string()
1350
- }),
1351
- zod.z.object({
1352
- $startsWith: zod.z.string()
1353
- }),
1354
- zod.z.object({
1355
- $ignoreCaseEquals: zod.z.string()
1356
- })
1357
- ];
1358
- var EventMatcher = zod.z.union([
1359
- /** Match against a string */
1360
- zod.z.array(zod.z.string()),
1361
- /** Match against a number */
1362
- zod.z.array(zod.z.number()),
1363
- /** Match against a boolean */
1364
- zod.z.array(zod.z.boolean()),
1365
- zod.z.array(zod.z.union([
1366
- ...stringPatternMatchers,
1367
- zod.z.object({
1368
- $exists: zod.z.boolean()
1369
- }),
1370
- zod.z.object({
1371
- $isNull: zod.z.boolean()
1372
- }),
1373
- zod.z.object({
1374
- $anythingBut: zod.z.union([
1375
- zod.z.string(),
1376
- zod.z.number(),
1377
- zod.z.boolean()
1378
- ])
1379
- }),
1380
- zod.z.object({
1381
- $anythingBut: zod.z.union([
1382
- zod.z.array(zod.z.string()),
1383
- zod.z.array(zod.z.number()),
1384
- zod.z.array(zod.z.boolean())
1385
- ])
1386
- }),
1387
- zod.z.object({
1388
- $gt: zod.z.number()
1389
- }),
1390
- zod.z.object({
1391
- $lt: zod.z.number()
1392
- }),
1393
- zod.z.object({
1394
- $gte: zod.z.number()
1395
- }),
1396
- zod.z.object({
1397
- $lte: zod.z.number()
1398
- }),
1399
- zod.z.object({
1400
- $between: zod.z.tuple([
1401
- zod.z.number(),
1402
- zod.z.number()
1403
- ])
1404
- }),
1405
- zod.z.object({
1406
- $includes: zod.z.union([
1407
- zod.z.string(),
1408
- zod.z.number(),
1409
- zod.z.boolean()
1410
- ])
1411
- }),
1412
- zod.z.object({
1413
- $not: zod.z.union([
1414
- zod.z.string(),
1415
- zod.z.number(),
1416
- zod.z.boolean()
1417
- ])
1418
- })
1419
- ]))
1420
- ]);
1421
- var EventFilter = zod.z.lazy(() => zod.z.record(zod.z.union([
1422
- EventMatcher,
1423
- EventFilter
1424
- ])));
1425
-
1426
- // src/v3/schemas/fetch.ts
1427
- var FetchRetryHeadersStrategy = zod.z.object({
1428
- /** The `headers` strategy retries the request using info from the response headers. */
1429
- strategy: zod.z.literal("headers"),
1430
- /** The header to use to determine the maximum number of times to retry the request. */
1431
- limitHeader: zod.z.string(),
1432
- /** The header to use to determine the number of remaining retries. */
1433
- remainingHeader: zod.z.string(),
1434
- /** The header to use to determine the time when the number of remaining retries will be reset. */
1435
- resetHeader: zod.z.string(),
1436
- /** The event filter to use to determine if the request should be retried. */
1437
- bodyFilter: EventFilter.optional(),
1438
- /** The format of the `resetHeader` value. */
1439
- resetFormat: zod.z.enum([
1440
- "unix_timestamp",
1441
- "unix_timestamp_in_ms",
1442
- "iso_8601",
1443
- "iso_8601_duration_openai_variant"
1444
- ]).default("unix_timestamp").optional()
1118
+ var ReplayRunResponse = zod.z.object({
1119
+ id: zod.z.string()
1445
1120
  });
1446
- var FetchRetryBackoffStrategy = RetryOptions.extend({
1447
- /** The `backoff` strategy retries the request with an exponential backoff. */
1448
- strategy: zod.z.literal("backoff"),
1449
- /** The event filter to use to determine if the request should be retried. */
1450
- bodyFilter: EventFilter.optional()
1121
+ var CanceledRunResponse = zod.z.object({
1122
+ message: zod.z.string()
1451
1123
  });
1452
- var FetchRetryStrategy = zod.z.discriminatedUnion("strategy", [
1453
- FetchRetryHeadersStrategy,
1454
- FetchRetryBackoffStrategy
1455
- ]);
1456
- var FetchRetryByStatusOptions = zod.z.record(zod.z.string(), FetchRetryStrategy);
1457
- var FetchTimeoutOptions = zod.z.object({
1458
- /** The maximum time to wait for the request to complete. */
1459
- durationInMs: zod.z.number().optional(),
1460
- retry: RetryOptions.optional()
1124
+ var ScheduledTaskPayload = zod.z.object({
1125
+ /** The schedule id associated with this run (you can have many schedules for the same task).
1126
+ You can use this to remove the schedule, update it, etc */
1127
+ scheduleId: zod.z.string(),
1128
+ /** When the task was scheduled to run.
1129
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
1130
+ timestamp: zod.z.date(),
1131
+ /** When the task was last run (it has been).
1132
+ This can be undefined if it's never been run */
1133
+ lastTimestamp: zod.z.date().optional(),
1134
+ /** You can optionally provide an external id when creating the schedule.
1135
+ Usually you would use a userId or some other unique identifier.
1136
+ This defaults to undefined if you didn't provide one. */
1137
+ externalId: zod.z.string().optional(),
1138
+ /** The next 5 dates this task is scheduled to run */
1139
+ upcoming: zod.z.array(zod.z.date())
1461
1140
  });
1462
- var FetchRetryOptions = zod.z.object({
1463
- /** The retrying strategy for specific status codes. */
1464
- byStatus: FetchRetryByStatusOptions.optional(),
1465
- /** The timeout options for the request. */
1466
- timeout: RetryOptions.optional(),
1467
- /**
1468
- * The retrying strategy for connection errors.
1141
+ var CreateScheduleOptions = zod.z.object({
1142
+ /** The id of the task you want to attach to. */
1143
+ task: zod.z.string(),
1144
+ /** The schedule in CRON format.
1145
+ *
1146
+ * ```txt
1147
+ * * * * * *
1148
+ ┬ ┬ ┬ ┬ ┬
1149
+ │ │ │ │ |
1150
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
1151
+ │ │ │ └───── month (1 - 12)
1152
+ │ │ └────────── day of month (1 - 31, L)
1153
+ │ └─────────────── hour (0 - 23)
1154
+ └──────────────────── minute (0 - 59)
1155
+ * ```
1156
+
1157
+ "L" means the last. In the "day of week" field, 1L means the last Monday of the month. In the day of month field, L means the last day of the month.
1158
+
1159
+ */
1160
+ cron: zod.z.string(),
1161
+ /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1162
+ *
1163
+ * This is useful if you don't want to create duplicate schedules for a user. */
1164
+ deduplicationKey: zod.z.string().optional(),
1165
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
1166
+ *
1167
+ * This allows you to have per-user CRON tasks.
1469
1168
  */
1470
- connectionError: RetryOptions.optional()
1471
- });
1472
- var ExceptionEventProperties = zod.z.object({
1473
- type: zod.z.string().optional(),
1474
- message: zod.z.string().optional(),
1475
- stacktrace: zod.z.string().optional()
1169
+ externalId: zod.z.string().optional()
1476
1170
  });
1477
- var ExceptionSpanEvent = zod.z.object({
1478
- name: zod.z.literal("exception"),
1479
- time: zod.z.coerce.date(),
1480
- properties: zod.z.object({
1481
- exception: ExceptionEventProperties
1482
- })
1171
+ var UpdateScheduleOptions = CreateScheduleOptions;
1172
+ var ScheduleObject = zod.z.object({
1173
+ id: zod.z.string(),
1174
+ task: zod.z.string(),
1175
+ active: zod.z.boolean(),
1176
+ deduplicationKey: zod.z.string().nullish(),
1177
+ externalId: zod.z.string().nullish(),
1178
+ generator: zod.z.object({
1179
+ type: zod.z.literal("CRON"),
1180
+ expression: zod.z.string(),
1181
+ description: zod.z.string()
1182
+ }),
1183
+ nextRun: zod.z.coerce.date().nullish(),
1184
+ environments: zod.z.array(zod.z.object({
1185
+ id: zod.z.string(),
1186
+ type: zod.z.string(),
1187
+ userName: zod.z.string().nullish()
1188
+ }))
1483
1189
  });
1484
- var CancellationSpanEvent = zod.z.object({
1485
- name: zod.z.literal("cancellation"),
1486
- time: zod.z.coerce.date(),
1487
- properties: zod.z.object({
1488
- reason: zod.z.string()
1489
- })
1190
+ var DeletedScheduleObject = zod.z.object({
1191
+ id: zod.z.string()
1490
1192
  });
1491
- var OtherSpanEvent = zod.z.object({
1492
- name: zod.z.string(),
1493
- time: zod.z.coerce.date(),
1494
- properties: zod.z.record(zod.z.unknown())
1193
+ var ListSchedulesResult = zod.z.object({
1194
+ data: zod.z.array(ScheduleObject),
1195
+ pagination: zod.z.object({
1196
+ currentPage: zod.z.number(),
1197
+ totalPages: zod.z.number(),
1198
+ count: zod.z.number()
1199
+ })
1495
1200
  });
1496
- var SpanEvent = zod.z.union([
1497
- ExceptionSpanEvent,
1498
- CancellationSpanEvent,
1499
- OtherSpanEvent
1500
- ]);
1501
- var SpanEvents = zod.z.array(SpanEvent);
1502
- function isExceptionSpanEvent(event) {
1503
- return event.name === "exception";
1504
- }
1505
- __name(isExceptionSpanEvent, "isExceptionSpanEvent");
1506
- function isCancellationSpanEvent(event) {
1507
- return event.name === "cancellation";
1508
- }
1509
- __name(isCancellationSpanEvent, "isCancellationSpanEvent");
1510
- var SpanMessagingEvent = zod.z.object({
1511
- system: zod.z.string().optional(),
1512
- client_id: zod.z.string().optional(),
1513
- operation: zod.z.enum([
1514
- "publish",
1515
- "create",
1516
- "receive",
1517
- "deliver"
1518
- ]),
1519
- message: zod.z.any(),
1520
- destination: zod.z.string().optional()
1201
+ var ListScheduleOptions = zod.z.object({
1202
+ page: zod.z.number().optional(),
1203
+ perPage: zod.z.number().optional()
1521
1204
  });
1522
-
1523
- // src/v3/apiErrors.ts
1524
- var _APIError = class _APIError extends Error {
1525
- constructor(status, error, message, headers) {
1526
- super(`${_APIError.makeMessage(status, error, message)}`);
1527
- this.status = status;
1528
- this.headers = headers;
1529
- const data = error;
1530
- this.error = data;
1531
- this.code = data?.["code"];
1532
- this.param = data?.["param"];
1533
- this.type = data?.["type"];
1534
- }
1535
- static makeMessage(status, error, message) {
1536
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1537
- if (status && msg) {
1538
- return `${status} ${msg}`;
1539
- }
1540
- if (status) {
1541
- return `${status} status code (no body)`;
1542
- }
1543
- if (msg) {
1544
- return msg;
1545
- }
1546
- return "(no status code or body)";
1547
- }
1548
- static generate(status, errorResponse, message, headers) {
1549
- if (!status) {
1550
- return new APIConnectionError({
1551
- cause: castToError(errorResponse)
1552
- });
1553
- }
1554
- const error = errorResponse?.["error"];
1555
- if (status === 400) {
1556
- return new BadRequestError(status, error, message, headers);
1557
- }
1558
- if (status === 401) {
1559
- return new AuthenticationError(status, error, message, headers);
1560
- }
1561
- if (status === 403) {
1562
- return new PermissionDeniedError(status, error, message, headers);
1563
- }
1564
- if (status === 404) {
1565
- return new NotFoundError(status, error, message, headers);
1566
- }
1567
- if (status === 409) {
1568
- return new ConflictError(status, error, message, headers);
1569
- }
1570
- if (status === 422) {
1571
- return new UnprocessableEntityError(status, error, message, headers);
1572
- }
1573
- if (status === 429) {
1574
- return new RateLimitError(status, error, message, headers);
1575
- }
1576
- if (status >= 500) {
1577
- return new InternalServerError(status, error, message, headers);
1578
- }
1579
- return new _APIError(status, error, message, headers);
1580
- }
1581
- };
1582
- __name(_APIError, "APIError");
1583
- var APIError = _APIError;
1584
- var _APIConnectionError = class _APIConnectionError extends APIError {
1585
- constructor({ message, cause }) {
1586
- super(void 0, void 0, message || "Connection error.", void 0);
1587
- __publicField(this, "status");
1588
- if (cause)
1589
- this.cause = cause;
1590
- }
1591
- };
1592
- __name(_APIConnectionError, "APIConnectionError");
1593
- var APIConnectionError = _APIConnectionError;
1594
- var _BadRequestError = class _BadRequestError extends APIError {
1595
- constructor() {
1596
- super(...arguments);
1597
- __publicField(this, "status", 400);
1598
- }
1599
- };
1600
- __name(_BadRequestError, "BadRequestError");
1601
- var BadRequestError = _BadRequestError;
1602
- var _AuthenticationError = class _AuthenticationError extends APIError {
1603
- constructor() {
1604
- super(...arguments);
1605
- __publicField(this, "status", 401);
1606
- }
1607
- };
1608
- __name(_AuthenticationError, "AuthenticationError");
1609
- var AuthenticationError = _AuthenticationError;
1610
- var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1611
- constructor() {
1612
- super(...arguments);
1613
- __publicField(this, "status", 403);
1614
- }
1615
- };
1616
- __name(_PermissionDeniedError, "PermissionDeniedError");
1617
- var PermissionDeniedError = _PermissionDeniedError;
1618
- var _NotFoundError = class _NotFoundError extends APIError {
1619
- constructor() {
1620
- super(...arguments);
1621
- __publicField(this, "status", 404);
1622
- }
1623
- };
1624
- __name(_NotFoundError, "NotFoundError");
1625
- var NotFoundError = _NotFoundError;
1626
- var _ConflictError = class _ConflictError extends APIError {
1627
- constructor() {
1628
- super(...arguments);
1629
- __publicField(this, "status", 409);
1205
+ var PostStartCauses = zod.z.enum([
1206
+ "index",
1207
+ "create",
1208
+ "restore"
1209
+ ]);
1210
+ var PreStopCauses = zod.z.enum([
1211
+ "terminate"
1212
+ ]);
1213
+ var RegexSchema = zod.z.custom((val) => {
1214
+ try {
1215
+ return typeof val.test === "function";
1216
+ } catch {
1217
+ return false;
1630
1218
  }
1631
- };
1632
- __name(_ConflictError, "ConflictError");
1633
- var ConflictError = _ConflictError;
1634
- var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1635
- constructor() {
1636
- super(...arguments);
1637
- __publicField(this, "status", 422);
1219
+ });
1220
+ var Config = zod.z.object({
1221
+ project: zod.z.string(),
1222
+ triggerDirectories: zod.z.string().array().optional(),
1223
+ triggerUrl: zod.z.string().optional(),
1224
+ projectDir: zod.z.string().optional(),
1225
+ tsconfigPath: zod.z.string().optional(),
1226
+ retries: zod.z.object({
1227
+ enabledInDev: zod.z.boolean().default(true),
1228
+ default: RetryOptions.optional()
1229
+ }).optional(),
1230
+ additionalPackages: zod.z.string().array().optional(),
1231
+ additionalFiles: zod.z.string().array().optional(),
1232
+ dependenciesToBundle: zod.z.array(zod.z.union([
1233
+ zod.z.string(),
1234
+ RegexSchema
1235
+ ])).optional(),
1236
+ logLevel: zod.z.string().optional(),
1237
+ enableConsoleLogging: zod.z.boolean().optional()
1238
+ });
1239
+ var WaitReason = zod.z.enum([
1240
+ "WAIT_FOR_DURATION",
1241
+ "WAIT_FOR_TASK",
1242
+ "WAIT_FOR_BATCH"
1243
+ ]);
1244
+ var ProviderToPlatformMessages = {
1245
+ LOG: {
1246
+ message: zod.z.object({
1247
+ version: zod.z.literal("v1").default("v1"),
1248
+ data: zod.z.string()
1249
+ })
1250
+ },
1251
+ LOG_WITH_ACK: {
1252
+ message: zod.z.object({
1253
+ version: zod.z.literal("v1").default("v1"),
1254
+ data: zod.z.string()
1255
+ }),
1256
+ callback: zod.z.object({
1257
+ status: zod.z.literal("ok")
1258
+ })
1259
+ },
1260
+ WORKER_CRASHED: {
1261
+ message: zod.z.object({
1262
+ version: zod.z.literal("v1").default("v1"),
1263
+ runId: zod.z.string(),
1264
+ reason: zod.z.string().optional(),
1265
+ exitCode: zod.z.number().optional(),
1266
+ message: zod.z.string().optional(),
1267
+ logs: zod.z.string().optional()
1268
+ })
1269
+ },
1270
+ INDEXING_FAILED: {
1271
+ message: zod.z.object({
1272
+ version: zod.z.literal("v1").default("v1"),
1273
+ deploymentId: zod.z.string(),
1274
+ error: zod.z.object({
1275
+ name: zod.z.string(),
1276
+ message: zod.z.string(),
1277
+ stack: zod.z.string().optional()
1278
+ })
1279
+ })
1638
1280
  }
1639
1281
  };
1640
- __name(_UnprocessableEntityError, "UnprocessableEntityError");
1641
- var UnprocessableEntityError = _UnprocessableEntityError;
1642
- var _RateLimitError = class _RateLimitError extends APIError {
1643
- constructor() {
1644
- super(...arguments);
1645
- __publicField(this, "status", 429);
1282
+ var PlatformToProviderMessages = {
1283
+ HEALTH: {
1284
+ message: zod.z.object({
1285
+ version: zod.z.literal("v1").default("v1")
1286
+ }),
1287
+ callback: zod.z.object({
1288
+ status: zod.z.literal("ok")
1289
+ })
1290
+ },
1291
+ INDEX: {
1292
+ message: zod.z.object({
1293
+ version: zod.z.literal("v1").default("v1"),
1294
+ imageTag: zod.z.string(),
1295
+ shortCode: zod.z.string(),
1296
+ apiKey: zod.z.string(),
1297
+ apiUrl: zod.z.string(),
1298
+ // identifiers
1299
+ envId: zod.z.string(),
1300
+ envType: EnvironmentType,
1301
+ orgId: zod.z.string(),
1302
+ projectId: zod.z.string(),
1303
+ deploymentId: zod.z.string()
1304
+ }),
1305
+ callback: zod.z.discriminatedUnion("success", [
1306
+ zod.z.object({
1307
+ success: zod.z.literal(false),
1308
+ error: zod.z.object({
1309
+ name: zod.z.string(),
1310
+ message: zod.z.string(),
1311
+ stack: zod.z.string().optional()
1312
+ })
1313
+ }),
1314
+ zod.z.object({
1315
+ success: zod.z.literal(true)
1316
+ })
1317
+ ])
1318
+ },
1319
+ // TODO: this should be a shared queue message instead
1320
+ RESTORE: {
1321
+ message: zod.z.object({
1322
+ version: zod.z.literal("v1").default("v1"),
1323
+ type: zod.z.enum([
1324
+ "DOCKER",
1325
+ "KUBERNETES"
1326
+ ]),
1327
+ location: zod.z.string(),
1328
+ reason: zod.z.string().optional(),
1329
+ imageRef: zod.z.string(),
1330
+ machine: Machine,
1331
+ // identifiers
1332
+ checkpointId: zod.z.string(),
1333
+ envId: zod.z.string(),
1334
+ envType: EnvironmentType,
1335
+ orgId: zod.z.string(),
1336
+ projectId: zod.z.string(),
1337
+ runId: zod.z.string()
1338
+ })
1339
+ },
1340
+ DELETE: {
1341
+ message: zod.z.object({
1342
+ version: zod.z.literal("v1").default("v1"),
1343
+ name: zod.z.string()
1344
+ }),
1345
+ callback: zod.z.object({
1346
+ message: zod.z.string()
1347
+ })
1348
+ },
1349
+ GET: {
1350
+ message: zod.z.object({
1351
+ version: zod.z.literal("v1").default("v1"),
1352
+ name: zod.z.string()
1353
+ })
1646
1354
  }
1647
1355
  };
1648
- __name(_RateLimitError, "RateLimitError");
1649
- var RateLimitError = _RateLimitError;
1650
- var _InternalServerError = class _InternalServerError extends APIError {
1651
- };
1652
- __name(_InternalServerError, "InternalServerError");
1653
- var InternalServerError = _InternalServerError;
1654
- function castToError(err) {
1655
- if (err instanceof Error)
1656
- return err;
1657
- return new Error(err);
1658
- }
1659
- __name(castToError, "castToError");
1660
-
1661
- // src/retry.ts
1662
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
1663
- if (!resets)
1664
- return;
1665
- switch (format) {
1666
- case "iso_8601_duration_openai_variant": {
1667
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
1668
- }
1669
- case "iso_8601": {
1670
- return calculateISO8601ResetAt(resets, now);
1671
- }
1672
- case "unix_timestamp": {
1673
- return calculateUnixTimestampResetAt(resets, now);
1674
- }
1675
- case "unix_timestamp_in_ms": {
1676
- return calculateUnixTimestampInMsResetAt(resets, now);
1677
- }
1356
+ var CoordinatorToPlatformMessages = {
1357
+ LOG: {
1358
+ message: zod.z.object({
1359
+ version: zod.z.literal("v1").default("v1"),
1360
+ metadata: zod.z.any(),
1361
+ text: zod.z.string()
1362
+ })
1363
+ },
1364
+ CREATE_WORKER: {
1365
+ message: zod.z.object({
1366
+ version: zod.z.literal("v1").default("v1"),
1367
+ projectRef: zod.z.string(),
1368
+ envId: zod.z.string(),
1369
+ deploymentId: zod.z.string(),
1370
+ metadata: zod.z.object({
1371
+ cliPackageVersion: zod.z.string().optional(),
1372
+ contentHash: zod.z.string(),
1373
+ packageVersion: zod.z.string(),
1374
+ tasks: TaskResource.array()
1375
+ })
1376
+ }),
1377
+ callback: zod.z.discriminatedUnion("success", [
1378
+ zod.z.object({
1379
+ success: zod.z.literal(false)
1380
+ }),
1381
+ zod.z.object({
1382
+ success: zod.z.literal(true)
1383
+ })
1384
+ ])
1385
+ },
1386
+ READY_FOR_EXECUTION: {
1387
+ message: zod.z.object({
1388
+ version: zod.z.literal("v1").default("v1"),
1389
+ runId: zod.z.string(),
1390
+ totalCompletions: zod.z.number()
1391
+ }),
1392
+ callback: zod.z.discriminatedUnion("success", [
1393
+ zod.z.object({
1394
+ success: zod.z.literal(false)
1395
+ }),
1396
+ zod.z.object({
1397
+ success: zod.z.literal(true),
1398
+ payload: ProdTaskRunExecutionPayload
1399
+ })
1400
+ ])
1401
+ },
1402
+ READY_FOR_RESUME: {
1403
+ message: zod.z.object({
1404
+ version: zod.z.literal("v1").default("v1"),
1405
+ attemptFriendlyId: zod.z.string(),
1406
+ type: WaitReason
1407
+ })
1408
+ },
1409
+ TASK_RUN_COMPLETED: {
1410
+ message: zod.z.object({
1411
+ version: zod.z.literal("v1").default("v1"),
1412
+ execution: ProdTaskRunExecution,
1413
+ completion: TaskRunExecutionResult,
1414
+ checkpoint: zod.z.object({
1415
+ docker: zod.z.boolean(),
1416
+ location: zod.z.string()
1417
+ }).optional()
1418
+ })
1419
+ },
1420
+ TASK_HEARTBEAT: {
1421
+ message: zod.z.object({
1422
+ version: zod.z.literal("v1").default("v1"),
1423
+ attemptFriendlyId: zod.z.string()
1424
+ })
1425
+ },
1426
+ CHECKPOINT_CREATED: {
1427
+ message: zod.z.object({
1428
+ version: zod.z.literal("v1").default("v1"),
1429
+ attemptFriendlyId: zod.z.string(),
1430
+ docker: zod.z.boolean(),
1431
+ location: zod.z.string(),
1432
+ reason: zod.z.discriminatedUnion("type", [
1433
+ zod.z.object({
1434
+ type: zod.z.literal("WAIT_FOR_DURATION"),
1435
+ ms: zod.z.number(),
1436
+ now: zod.z.number()
1437
+ }),
1438
+ zod.z.object({
1439
+ type: zod.z.literal("WAIT_FOR_BATCH"),
1440
+ batchFriendlyId: zod.z.string(),
1441
+ runFriendlyIds: zod.z.string().array()
1442
+ }),
1443
+ zod.z.object({
1444
+ type: zod.z.literal("WAIT_FOR_TASK"),
1445
+ friendlyId: zod.z.string()
1446
+ }),
1447
+ zod.z.object({
1448
+ type: zod.z.literal("RETRYING_AFTER_FAILURE"),
1449
+ attemptNumber: zod.z.number()
1450
+ })
1451
+ ])
1452
+ })
1453
+ },
1454
+ INDEXING_FAILED: {
1455
+ message: zod.z.object({
1456
+ version: zod.z.literal("v1").default("v1"),
1457
+ deploymentId: zod.z.string(),
1458
+ error: zod.z.object({
1459
+ name: zod.z.string(),
1460
+ message: zod.z.string(),
1461
+ stack: zod.z.string().optional()
1462
+ })
1463
+ })
1678
1464
  }
1679
- }
1680
- __name(calculateResetAt, "calculateResetAt");
1681
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
1682
- if (!resets)
1683
- return void 0;
1684
- const resetAt = parseInt(resets, 10);
1685
- if (isNaN(resetAt))
1686
- return void 0;
1687
- return new Date(resetAt * 1e3);
1688
- }
1689
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
1690
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
1691
- if (!resets)
1692
- return void 0;
1693
- const resetAt = parseInt(resets, 10);
1694
- if (isNaN(resetAt))
1695
- return void 0;
1696
- return new Date(resetAt);
1697
- }
1698
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
1699
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
1700
- if (!resets)
1701
- return void 0;
1702
- const resetAt = new Date(resets);
1703
- if (isNaN(resetAt.getTime()))
1704
- return void 0;
1705
- return resetAt;
1706
- }
1707
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
1708
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
1709
- if (!resets)
1710
- return void 0;
1711
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
1712
- const match = resets.match(pattern);
1713
- if (!match)
1714
- return void 0;
1715
- const days = parseInt(match[1], 10) || 0;
1716
- const hours = parseInt(match[2], 10) || 0;
1717
- const minutes = parseInt(match[3], 10) || 0;
1718
- const seconds = parseFloat(match[4]) || 0;
1719
- const milliseconds = parseInt(match[5], 10) || 0;
1720
- const resetAt = new Date(now);
1721
- resetAt.setDate(resetAt.getDate() + days);
1722
- resetAt.setHours(resetAt.getHours() + hours);
1723
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
1724
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
1725
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
1726
- return resetAt;
1727
- }
1728
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
1729
-
1730
- // src/v3/utils/retries.ts
1731
- var defaultRetryOptions = {
1732
- maxAttempts: 3,
1733
- factor: 2,
1734
- minTimeoutInMs: 1e3,
1735
- maxTimeoutInMs: 6e4,
1736
- randomize: true
1737
1465
  };
1738
- var defaultFetchRetryOptions = {
1739
- byStatus: {
1740
- "429,408,409,5xx": {
1741
- strategy: "backoff",
1742
- ...defaultRetryOptions
1743
- }
1466
+ var PlatformToCoordinatorMessages = {
1467
+ RESUME_AFTER_DEPENDENCY: {
1468
+ message: zod.z.object({
1469
+ version: zod.z.literal("v1").default("v1"),
1470
+ runId: zod.z.string(),
1471
+ attemptId: zod.z.string(),
1472
+ attemptFriendlyId: zod.z.string(),
1473
+ completions: TaskRunExecutionResult.array(),
1474
+ executions: TaskRunExecution.array()
1475
+ })
1476
+ },
1477
+ RESUME_AFTER_DURATION: {
1478
+ message: zod.z.object({
1479
+ version: zod.z.literal("v1").default("v1"),
1480
+ attemptId: zod.z.string(),
1481
+ attemptFriendlyId: zod.z.string()
1482
+ })
1744
1483
  },
1745
- connectionError: defaultRetryOptions,
1746
- timeout: defaultRetryOptions
1484
+ REQUEST_ATTEMPT_CANCELLATION: {
1485
+ message: zod.z.object({
1486
+ version: zod.z.literal("v1").default("v1"),
1487
+ attemptId: zod.z.string(),
1488
+ attemptFriendlyId: zod.z.string()
1489
+ })
1490
+ },
1491
+ READY_FOR_RETRY: {
1492
+ message: zod.z.object({
1493
+ version: zod.z.literal("v1").default("v1"),
1494
+ runId: zod.z.string()
1495
+ })
1496
+ }
1747
1497
  };
1748
- function calculateNextRetryDelay(options, attempt) {
1749
- const opts = {
1750
- ...defaultRetryOptions,
1751
- ...options
1752
- };
1753
- if (attempt >= opts.maxAttempts) {
1754
- return;
1498
+ var ClientToSharedQueueMessages = {
1499
+ READY_FOR_TASKS: {
1500
+ message: zod.z.object({
1501
+ version: zod.z.literal("v1").default("v1"),
1502
+ backgroundWorkerId: zod.z.string()
1503
+ })
1504
+ },
1505
+ BACKGROUND_WORKER_DEPRECATED: {
1506
+ message: zod.z.object({
1507
+ version: zod.z.literal("v1").default("v1"),
1508
+ backgroundWorkerId: zod.z.string()
1509
+ })
1510
+ },
1511
+ BACKGROUND_WORKER_MESSAGE: {
1512
+ message: zod.z.object({
1513
+ version: zod.z.literal("v1").default("v1"),
1514
+ backgroundWorkerId: zod.z.string(),
1515
+ data: BackgroundWorkerClientMessages
1516
+ })
1755
1517
  }
1756
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1757
- const random = randomize ? Math.random() + 1 : 1;
1758
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1759
- return Math.round(timeout);
1760
- }
1761
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1762
- function calculateResetAt2(resets, format, now = Date.now()) {
1763
- const resetAt = calculateResetAt(resets, format, new Date(now));
1764
- return resetAt?.getTime();
1765
- }
1766
- __name(calculateResetAt2, "calculateResetAt");
1767
-
1768
- // src/v3/zodfetch.ts
1769
- var defaultRetryOptions2 = {
1770
- maxAttempts: 3,
1771
- factor: 2,
1772
- minTimeoutInMs: 1e3,
1773
- maxTimeoutInMs: 6e4,
1774
- randomize: false
1775
1518
  };
1776
- async function zodfetch(schema, url, requestInit, options) {
1777
- return await _doZodFetch(schema, url, requestInit, options);
1778
- }
1779
- __name(zodfetch, "zodfetch");
1780
- async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1781
- try {
1782
- const response = await fetch(url, requestInitWithCache(requestInit));
1783
- const responseHeaders = createResponseHeaders(response.headers);
1784
- if (!response.ok) {
1785
- const retryResult = shouldRetry(response, attempt, options?.retry);
1786
- if (retryResult.retry) {
1787
- await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1788
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1789
- } else {
1790
- const errText = await response.text().catch((e) => castToError2(e).message);
1791
- const errJSON = safeJsonParse(errText);
1792
- const errMessage = errJSON ? void 0 : errText;
1793
- throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
1794
- }
1795
- }
1796
- const jsonBody = await response.json();
1797
- const parsedResult = schema.safeParse(jsonBody);
1798
- if (parsedResult.success) {
1799
- return parsedResult.data;
1800
- }
1801
- throw zodValidationError.fromZodError(parsedResult.error);
1802
- } catch (error) {
1803
- if (error instanceof APIError) {
1804
- throw error;
1805
- }
1806
- if (options?.retry) {
1807
- const retry = {
1808
- ...defaultRetryOptions2,
1809
- ...options.retry
1810
- };
1811
- const delay = calculateNextRetryDelay(retry, attempt);
1812
- if (delay) {
1813
- await new Promise((resolve) => setTimeout(resolve, delay));
1814
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1815
- }
1816
- }
1817
- throw new APIConnectionError({
1818
- cause: castToError2(error)
1819
- });
1519
+ var SharedQueueToClientMessages = {
1520
+ SERVER_READY: {
1521
+ message: zod.z.object({
1522
+ version: zod.z.literal("v1").default("v1"),
1523
+ id: zod.z.string()
1524
+ })
1525
+ },
1526
+ BACKGROUND_WORKER_MESSAGE: {
1527
+ message: zod.z.object({
1528
+ version: zod.z.literal("v1").default("v1"),
1529
+ backgroundWorkerId: zod.z.string(),
1530
+ data: BackgroundWorkerServerMessages
1531
+ })
1820
1532
  }
1821
- }
1822
- __name(_doZodFetch, "_doZodFetch");
1823
- function castToError2(err) {
1824
- if (err instanceof Error)
1825
- return err;
1826
- return new Error(err);
1827
- }
1828
- __name(castToError2, "castToError");
1829
- function shouldRetry(response, attempt, retryOptions) {
1830
- function shouldRetryForOptions() {
1831
- const retry = {
1832
- ...defaultRetryOptions2,
1833
- ...retryOptions
1834
- };
1835
- const delay = calculateNextRetryDelay(retry, attempt);
1836
- if (delay) {
1837
- return {
1838
- retry: true,
1839
- delay
1840
- };
1841
- } else {
1842
- return {
1843
- retry: false
1844
- };
1845
- }
1533
+ };
1534
+ var ProdWorkerToCoordinatorMessages = {
1535
+ LOG: {
1536
+ message: zod.z.object({
1537
+ version: zod.z.literal("v1").default("v1"),
1538
+ text: zod.z.string()
1539
+ }),
1540
+ callback: zod.z.void()
1541
+ },
1542
+ INDEX_TASKS: {
1543
+ message: zod.z.object({
1544
+ version: zod.z.literal("v1").default("v1"),
1545
+ deploymentId: zod.z.string(),
1546
+ tasks: TaskResource.array(),
1547
+ packageVersion: zod.z.string()
1548
+ }),
1549
+ callback: zod.z.discriminatedUnion("success", [
1550
+ zod.z.object({
1551
+ success: zod.z.literal(false)
1552
+ }),
1553
+ zod.z.object({
1554
+ success: zod.z.literal(true)
1555
+ })
1556
+ ])
1557
+ },
1558
+ READY_FOR_EXECUTION: {
1559
+ message: zod.z.object({
1560
+ version: zod.z.literal("v1").default("v1"),
1561
+ runId: zod.z.string(),
1562
+ totalCompletions: zod.z.number()
1563
+ })
1564
+ },
1565
+ READY_FOR_RESUME: {
1566
+ message: zod.z.object({
1567
+ version: zod.z.literal("v1").default("v1"),
1568
+ attemptFriendlyId: zod.z.string(),
1569
+ type: WaitReason
1570
+ })
1571
+ },
1572
+ READY_FOR_CHECKPOINT: {
1573
+ message: zod.z.object({
1574
+ version: zod.z.literal("v1").default("v1")
1575
+ })
1576
+ },
1577
+ CANCEL_CHECKPOINT: {
1578
+ message: zod.z.object({
1579
+ version: zod.z.literal("v1").default("v1")
1580
+ })
1581
+ },
1582
+ TASK_HEARTBEAT: {
1583
+ message: zod.z.object({
1584
+ version: zod.z.literal("v1").default("v1"),
1585
+ attemptFriendlyId: zod.z.string()
1586
+ })
1587
+ },
1588
+ TASK_RUN_COMPLETED: {
1589
+ message: zod.z.object({
1590
+ version: zod.z.literal("v1").default("v1"),
1591
+ execution: ProdTaskRunExecution,
1592
+ completion: TaskRunExecutionResult
1593
+ }),
1594
+ callback: zod.z.object({
1595
+ willCheckpointAndRestore: zod.z.boolean(),
1596
+ shouldExit: zod.z.boolean()
1597
+ })
1598
+ },
1599
+ WAIT_FOR_DURATION: {
1600
+ message: zod.z.object({
1601
+ version: zod.z.literal("v1").default("v1"),
1602
+ ms: zod.z.number(),
1603
+ now: zod.z.number(),
1604
+ attemptFriendlyId: zod.z.string()
1605
+ }),
1606
+ callback: zod.z.object({
1607
+ willCheckpointAndRestore: zod.z.boolean()
1608
+ })
1609
+ },
1610
+ WAIT_FOR_TASK: {
1611
+ message: zod.z.object({
1612
+ version: zod.z.literal("v1").default("v1"),
1613
+ friendlyId: zod.z.string(),
1614
+ // This is the attempt that is waiting
1615
+ attemptFriendlyId: zod.z.string()
1616
+ }),
1617
+ callback: zod.z.object({
1618
+ willCheckpointAndRestore: zod.z.boolean()
1619
+ })
1620
+ },
1621
+ WAIT_FOR_BATCH: {
1622
+ message: zod.z.object({
1623
+ version: zod.z.literal("v1").default("v1"),
1624
+ batchFriendlyId: zod.z.string(),
1625
+ runFriendlyIds: zod.z.string().array(),
1626
+ // This is the attempt that is waiting
1627
+ attemptFriendlyId: zod.z.string()
1628
+ }),
1629
+ callback: zod.z.object({
1630
+ willCheckpointAndRestore: zod.z.boolean()
1631
+ })
1632
+ },
1633
+ INDEXING_FAILED: {
1634
+ message: zod.z.object({
1635
+ version: zod.z.literal("v1").default("v1"),
1636
+ deploymentId: zod.z.string(),
1637
+ error: zod.z.object({
1638
+ name: zod.z.string(),
1639
+ message: zod.z.string(),
1640
+ stack: zod.z.string().optional()
1641
+ })
1642
+ })
1846
1643
  }
1847
- __name(shouldRetryForOptions, "shouldRetryForOptions");
1848
- const shouldRetryHeader = response.headers.get("x-should-retry");
1849
- if (shouldRetryHeader === "true")
1850
- return shouldRetryForOptions();
1851
- if (shouldRetryHeader === "false")
1852
- return {
1853
- retry: false
1854
- };
1855
- if (response.status === 408)
1856
- return shouldRetryForOptions();
1857
- if (response.status === 409)
1858
- return shouldRetryForOptions();
1859
- if (response.status === 429)
1860
- return shouldRetryForOptions();
1861
- if (response.status >= 500)
1862
- return shouldRetryForOptions();
1863
- return {
1864
- retry: false
1865
- };
1866
- }
1867
- __name(shouldRetry, "shouldRetry");
1868
- function safeJsonParse(text) {
1869
- try {
1870
- return JSON.parse(text);
1871
- } catch (e) {
1872
- return void 0;
1644
+ };
1645
+ var CoordinatorToProdWorkerMessages = {
1646
+ RESUME_AFTER_DEPENDENCY: {
1647
+ message: zod.z.object({
1648
+ version: zod.z.literal("v1").default("v1"),
1649
+ attemptId: zod.z.string(),
1650
+ completions: TaskRunExecutionResult.array(),
1651
+ executions: TaskRunExecution.array()
1652
+ })
1653
+ },
1654
+ RESUME_AFTER_DURATION: {
1655
+ message: zod.z.object({
1656
+ version: zod.z.literal("v1").default("v1"),
1657
+ attemptId: zod.z.string()
1658
+ })
1659
+ },
1660
+ EXECUTE_TASK_RUN: {
1661
+ message: zod.z.object({
1662
+ version: zod.z.literal("v1").default("v1"),
1663
+ executionPayload: ProdTaskRunExecutionPayload
1664
+ })
1665
+ },
1666
+ REQUEST_ATTEMPT_CANCELLATION: {
1667
+ message: zod.z.object({
1668
+ version: zod.z.literal("v1").default("v1"),
1669
+ attemptId: zod.z.string()
1670
+ })
1671
+ },
1672
+ REQUEST_EXIT: {
1673
+ message: zod.z.object({
1674
+ version: zod.z.literal("v1").default("v1")
1675
+ })
1676
+ },
1677
+ READY_FOR_RETRY: {
1678
+ message: zod.z.object({
1679
+ version: zod.z.literal("v1").default("v1"),
1680
+ runId: zod.z.string()
1681
+ })
1873
1682
  }
1683
+ };
1684
+ var ProdWorkerSocketData = zod.z.object({
1685
+ contentHash: zod.z.string(),
1686
+ projectRef: zod.z.string(),
1687
+ envId: zod.z.string(),
1688
+ runId: zod.z.string(),
1689
+ attemptFriendlyId: zod.z.string().optional(),
1690
+ podName: zod.z.string(),
1691
+ deploymentId: zod.z.string(),
1692
+ deploymentVersion: zod.z.string()
1693
+ });
1694
+ var PRIMARY_VARIANT = "primary";
1695
+ var Variant = zod.z.enum([
1696
+ PRIMARY_VARIANT
1697
+ ]);
1698
+ var AccessoryItem = zod.z.object({
1699
+ text: zod.z.string(),
1700
+ variant: zod.z.string().optional(),
1701
+ url: zod.z.string().optional()
1702
+ });
1703
+ var Accessory = zod.z.object({
1704
+ items: zod.z.array(AccessoryItem),
1705
+ style: zod.z.enum([
1706
+ "codepath"
1707
+ ]).optional()
1708
+ });
1709
+ var TaskEventStyle = zod.z.object({
1710
+ icon: zod.z.string().optional(),
1711
+ variant: Variant.optional(),
1712
+ accessory: Accessory.optional()
1713
+ }).default({
1714
+ icon: void 0,
1715
+ variant: void 0
1716
+ });
1717
+ var stringPatternMatchers = [
1718
+ zod.z.object({
1719
+ $endsWith: zod.z.string()
1720
+ }),
1721
+ zod.z.object({
1722
+ $startsWith: zod.z.string()
1723
+ }),
1724
+ zod.z.object({
1725
+ $ignoreCaseEquals: zod.z.string()
1726
+ })
1727
+ ];
1728
+ var EventMatcher = zod.z.union([
1729
+ /** Match against a string */
1730
+ zod.z.array(zod.z.string()),
1731
+ /** Match against a number */
1732
+ zod.z.array(zod.z.number()),
1733
+ /** Match against a boolean */
1734
+ zod.z.array(zod.z.boolean()),
1735
+ zod.z.array(zod.z.union([
1736
+ ...stringPatternMatchers,
1737
+ zod.z.object({
1738
+ $exists: zod.z.boolean()
1739
+ }),
1740
+ zod.z.object({
1741
+ $isNull: zod.z.boolean()
1742
+ }),
1743
+ zod.z.object({
1744
+ $anythingBut: zod.z.union([
1745
+ zod.z.string(),
1746
+ zod.z.number(),
1747
+ zod.z.boolean()
1748
+ ])
1749
+ }),
1750
+ zod.z.object({
1751
+ $anythingBut: zod.z.union([
1752
+ zod.z.array(zod.z.string()),
1753
+ zod.z.array(zod.z.number()),
1754
+ zod.z.array(zod.z.boolean())
1755
+ ])
1756
+ }),
1757
+ zod.z.object({
1758
+ $gt: zod.z.number()
1759
+ }),
1760
+ zod.z.object({
1761
+ $lt: zod.z.number()
1762
+ }),
1763
+ zod.z.object({
1764
+ $gte: zod.z.number()
1765
+ }),
1766
+ zod.z.object({
1767
+ $lte: zod.z.number()
1768
+ }),
1769
+ zod.z.object({
1770
+ $between: zod.z.tuple([
1771
+ zod.z.number(),
1772
+ zod.z.number()
1773
+ ])
1774
+ }),
1775
+ zod.z.object({
1776
+ $includes: zod.z.union([
1777
+ zod.z.string(),
1778
+ zod.z.number(),
1779
+ zod.z.boolean()
1780
+ ])
1781
+ }),
1782
+ zod.z.object({
1783
+ $not: zod.z.union([
1784
+ zod.z.string(),
1785
+ zod.z.number(),
1786
+ zod.z.boolean()
1787
+ ])
1788
+ })
1789
+ ]))
1790
+ ]);
1791
+ var EventFilter = zod.z.lazy(() => zod.z.record(zod.z.union([
1792
+ EventMatcher,
1793
+ EventFilter
1794
+ ])));
1795
+
1796
+ // src/v3/schemas/fetch.ts
1797
+ var FetchRetryHeadersStrategy = zod.z.object({
1798
+ /** The `headers` strategy retries the request using info from the response headers. */
1799
+ strategy: zod.z.literal("headers"),
1800
+ /** The header to use to determine the maximum number of times to retry the request. */
1801
+ limitHeader: zod.z.string(),
1802
+ /** The header to use to determine the number of remaining retries. */
1803
+ remainingHeader: zod.z.string(),
1804
+ /** The header to use to determine the time when the number of remaining retries will be reset. */
1805
+ resetHeader: zod.z.string(),
1806
+ /** The event filter to use to determine if the request should be retried. */
1807
+ bodyFilter: EventFilter.optional(),
1808
+ /** The format of the `resetHeader` value. */
1809
+ resetFormat: zod.z.enum([
1810
+ "unix_timestamp",
1811
+ "unix_timestamp_in_ms",
1812
+ "iso_8601",
1813
+ "iso_8601_duration_openai_variant"
1814
+ ]).default("unix_timestamp").optional()
1815
+ });
1816
+ var FetchRetryBackoffStrategy = RetryOptions.extend({
1817
+ /** The `backoff` strategy retries the request with an exponential backoff. */
1818
+ strategy: zod.z.literal("backoff"),
1819
+ /** The event filter to use to determine if the request should be retried. */
1820
+ bodyFilter: EventFilter.optional()
1821
+ });
1822
+ var FetchRetryStrategy = zod.z.discriminatedUnion("strategy", [
1823
+ FetchRetryHeadersStrategy,
1824
+ FetchRetryBackoffStrategy
1825
+ ]);
1826
+ var FetchRetryByStatusOptions = zod.z.record(zod.z.string(), FetchRetryStrategy);
1827
+ var FetchTimeoutOptions = zod.z.object({
1828
+ /** The maximum time to wait for the request to complete. */
1829
+ durationInMs: zod.z.number().optional(),
1830
+ retry: RetryOptions.optional()
1831
+ });
1832
+ var FetchRetryOptions = zod.z.object({
1833
+ /** The retrying strategy for specific status codes. */
1834
+ byStatus: FetchRetryByStatusOptions.optional(),
1835
+ /** The timeout options for the request. */
1836
+ timeout: RetryOptions.optional(),
1837
+ /**
1838
+ * The retrying strategy for connection errors.
1839
+ */
1840
+ connectionError: RetryOptions.optional()
1841
+ });
1842
+ var ExceptionEventProperties = zod.z.object({
1843
+ type: zod.z.string().optional(),
1844
+ message: zod.z.string().optional(),
1845
+ stacktrace: zod.z.string().optional()
1846
+ });
1847
+ var ExceptionSpanEvent = zod.z.object({
1848
+ name: zod.z.literal("exception"),
1849
+ time: zod.z.coerce.date(),
1850
+ properties: zod.z.object({
1851
+ exception: ExceptionEventProperties
1852
+ })
1853
+ });
1854
+ var CancellationSpanEvent = zod.z.object({
1855
+ name: zod.z.literal("cancellation"),
1856
+ time: zod.z.coerce.date(),
1857
+ properties: zod.z.object({
1858
+ reason: zod.z.string()
1859
+ })
1860
+ });
1861
+ var OtherSpanEvent = zod.z.object({
1862
+ name: zod.z.string(),
1863
+ time: zod.z.coerce.date(),
1864
+ properties: zod.z.record(zod.z.unknown())
1865
+ });
1866
+ var SpanEvent = zod.z.union([
1867
+ ExceptionSpanEvent,
1868
+ CancellationSpanEvent,
1869
+ OtherSpanEvent
1870
+ ]);
1871
+ var SpanEvents = zod.z.array(SpanEvent);
1872
+ function isExceptionSpanEvent(event) {
1873
+ return event.name === "exception";
1874
1874
  }
1875
- __name(safeJsonParse, "safeJsonParse");
1876
- function createResponseHeaders(headers) {
1877
- return new Proxy(Object.fromEntries(
1878
- // @ts-ignore
1879
- headers.entries()
1880
- ), {
1881
- get(target, name) {
1882
- const key = name.toString();
1883
- return target[key.toLowerCase()] || target[key];
1884
- }
1885
- });
1886
- }
1887
- __name(createResponseHeaders, "createResponseHeaders");
1888
- function requestInitWithCache(requestInit) {
1889
- try {
1890
- const withCache = {
1891
- ...requestInit,
1892
- cache: "no-cache"
1893
- };
1894
- const _ = new Request("http://localhost", withCache);
1895
- return withCache;
1896
- } catch (error) {
1897
- return requestInit ?? {};
1898
- }
1875
+ __name(isExceptionSpanEvent, "isExceptionSpanEvent");
1876
+ function isCancellationSpanEvent(event) {
1877
+ return event.name === "cancellation";
1899
1878
  }
1900
- __name(requestInitWithCache, "requestInitWithCache");
1879
+ __name(isCancellationSpanEvent, "isCancellationSpanEvent");
1880
+ var SpanMessagingEvent = zod.z.object({
1881
+ system: zod.z.string().optional(),
1882
+ client_id: zod.z.string().optional(),
1883
+ operation: zod.z.enum([
1884
+ "publish",
1885
+ "create",
1886
+ "receive",
1887
+ "deliver"
1888
+ ]),
1889
+ message: zod.z.any(),
1890
+ destination: zod.z.string().optional()
1891
+ });
1901
1892
 
1902
- // src/v3/utils/flattenAttributes.ts
1903
- function flattenAttributes(obj, prefix) {
1904
- const result = {};
1905
- if (!obj) {
1906
- return result;
1907
- }
1908
- if (typeof obj === "string") {
1909
- result[prefix || ""] = obj;
1910
- return result;
1911
- }
1912
- if (typeof obj === "number") {
1913
- result[prefix || ""] = obj;
1914
- return result;
1915
- }
1916
- if (typeof obj === "boolean") {
1917
- result[prefix || ""] = obj;
1918
- return result;
1919
- }
1920
- for (const [key, value] of Object.entries(obj)) {
1921
- const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
1922
- if (Array.isArray(value)) {
1923
- for (let i = 0; i < value.length; i++) {
1924
- if (typeof value[i] === "object" && value[i] !== null) {
1925
- Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
1926
- } else {
1927
- result[`${newPrefix}.[${i}]`] = value[i];
1928
- }
1929
- }
1930
- } else if (isRecord(value)) {
1931
- Object.assign(result, flattenAttributes(value, newPrefix));
1932
- } else {
1933
- if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
1934
- result[newPrefix] = value;
1935
- }
1936
- }
1937
- }
1938
- return result;
1939
- }
1940
- __name(flattenAttributes, "flattenAttributes");
1941
- function isRecord(value) {
1942
- return value !== null && typeof value === "object" && !Array.isArray(value);
1943
- }
1944
- __name(isRecord, "isRecord");
1945
- function unflattenAttributes(obj) {
1946
- if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
1947
- return obj;
1948
- }
1949
- const result = {};
1950
- for (const [key, value] of Object.entries(obj)) {
1951
- const parts = key.split(".").reduce((acc, part) => {
1952
- if (detectIsArrayIndex(part)) {
1953
- acc.push(part);
1954
- } else {
1955
- acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
1956
- }
1957
- return acc;
1958
- }, []);
1959
- let current = result;
1960
- for (let i = 0; i < parts.length - 1; i++) {
1961
- const part = parts[i];
1962
- const isArray = detectIsArrayIndex(part);
1963
- const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
1964
- const nextIsArray = detectIsArrayIndex(parts[i + 1]);
1965
- if (!current[cleanPart]) {
1966
- current[cleanPart] = nextIsArray ? [] : {};
1967
- }
1968
- current = current[cleanPart];
1969
- }
1970
- const lastPart = parts[parts.length - 1];
1971
- const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
1972
- current[cleanLastPart] = value;
1893
+ // src/v3/utils/platform.ts
1894
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
1895
+
1896
+ // src/v3/utils/globals.ts
1897
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
1898
+ var _global = _globalThis;
1899
+ function registerGlobal(type, instance, allowOverride = false) {
1900
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
1901
+ if (!allowOverride && api[type]) {
1902
+ return false;
1973
1903
  }
1974
- return result;
1904
+ api[type] = instance;
1905
+ return true;
1975
1906
  }
1976
- __name(unflattenAttributes, "unflattenAttributes");
1977
- function detectIsArrayIndex(key) {
1978
- const match = key.match(/^\[(\d+)\]$/);
1979
- if (match) {
1980
- return true;
1981
- }
1982
- return false;
1907
+ __name(registerGlobal, "registerGlobal");
1908
+ function getGlobal(type) {
1909
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
1983
1910
  }
1984
- __name(detectIsArrayIndex, "detectIsArrayIndex");
1985
- function primitiveValueOrflattenedAttributes(obj, prefix) {
1986
- if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
1987
- return obj;
1988
- }
1989
- const attributes = flattenAttributes(obj, prefix);
1990
- if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
1991
- return attributes[prefix];
1911
+ __name(getGlobal, "getGlobal");
1912
+ function unregisterGlobal(type) {
1913
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
1914
+ if (api) {
1915
+ delete api[type];
1992
1916
  }
1993
- return attributes;
1994
1917
  }
1995
- __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
1996
- var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
1997
- constructor() {
1998
- this.storage = new async_hooks.AsyncLocalStorage();
1999
- }
2000
- runWith(context3, fn) {
2001
- return this.storage.run(context3, fn);
2002
- }
2003
- getStore() {
2004
- return this.storage.getStore();
2005
- }
2006
- };
2007
- __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
2008
- var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
1918
+ __name(unregisterGlobal, "unregisterGlobal");
2009
1919
 
2010
1920
  // src/v3/semanticInternalAttributes.ts
2011
1921
  var SemanticInternalAttributes = {
@@ -2054,23 +1964,27 @@ var SemanticInternalAttributes = {
2054
1964
  IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
2055
1965
  };
2056
1966
 
2057
- // src/v3/tasks/taskContextManager.ts
2058
- var _getStore, getStore_fn;
2059
- var _TaskContextManager = class _TaskContextManager {
1967
+ // src/v3/taskContext/index.ts
1968
+ var API_NAME = "task-context";
1969
+ var _getTaskContext, getTaskContext_fn;
1970
+ var _TaskContextAPI = class _TaskContextAPI {
2060
1971
  constructor() {
2061
- __privateAdd(this, _getStore);
2062
- __publicField(this, "_storage", new SafeAsyncLocalStorage());
1972
+ __privateAdd(this, _getTaskContext);
1973
+ }
1974
+ static getInstance() {
1975
+ if (!this._instance) {
1976
+ this._instance = new _TaskContextAPI();
1977
+ }
1978
+ return this._instance;
2063
1979
  }
2064
1980
  get isInsideTask() {
2065
- return __privateMethod(this, _getStore, getStore_fn).call(this) !== void 0;
1981
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
2066
1982
  }
2067
1983
  get ctx() {
2068
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2069
- return store?.ctx;
1984
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
2070
1985
  }
2071
1986
  get worker() {
2072
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2073
- return store?.worker;
1987
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
2074
1988
  }
2075
1989
  get attributes() {
2076
1990
  if (this.ctx) {
@@ -2116,66 +2030,22 @@ var _TaskContextManager = class _TaskContextManager {
2116
2030
  }
2117
2031
  return {};
2118
2032
  }
2119
- runWith(context3, fn) {
2120
- return this._storage.runWith(context3, fn);
2121
- }
2122
- };
2123
- _getStore = new WeakSet();
2124
- getStore_fn = /* @__PURE__ */ __name(function() {
2125
- return this._storage.getStore();
2126
- }, "#getStore");
2127
- __name(_TaskContextManager, "TaskContextManager");
2128
- var TaskContextManager = _TaskContextManager;
2129
- var taskContextManager = new TaskContextManager();
2130
- var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
2131
- constructor(innerProcessor) {
2132
- this._innerProcessor = innerProcessor;
2133
- }
2134
- // Called when a span starts
2135
- onStart(span, parentContext) {
2136
- if (taskContextManager.ctx) {
2137
- span.setAttributes(flattenAttributes({
2138
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
2139
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
2140
- }, SemanticInternalAttributes.METADATA));
2141
- }
2142
- this._innerProcessor.onStart(span, parentContext);
2143
- }
2144
- // Delegate the rest of the methods to the wrapped processor
2145
- onEnd(span) {
2146
- this._innerProcessor.onEnd(span);
2147
- }
2148
- shutdown() {
2149
- return this._innerProcessor.shutdown();
2150
- }
2151
- forceFlush() {
2152
- return this._innerProcessor.forceFlush();
2153
- }
2154
- };
2155
- __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
2156
- var TaskContextSpanProcessor = _TaskContextSpanProcessor;
2157
- var _TaskContextLogProcessor = class _TaskContextLogProcessor {
2158
- constructor(innerProcessor) {
2159
- this._innerProcessor = innerProcessor;
2160
- }
2161
- forceFlush() {
2162
- return this._innerProcessor.forceFlush();
2163
- }
2164
- onEmit(logRecord, context3) {
2165
- if (taskContextManager.ctx) {
2166
- logRecord.setAttributes(flattenAttributes({
2167
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
2168
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
2169
- }, SemanticInternalAttributes.METADATA));
2170
- }
2171
- this._innerProcessor.onEmit(logRecord, context3);
2033
+ disable() {
2034
+ unregisterGlobal(API_NAME);
2172
2035
  }
2173
- shutdown() {
2174
- return this._innerProcessor.shutdown();
2036
+ setGlobalTaskContext(taskContext2) {
2037
+ return registerGlobal(API_NAME, taskContext2);
2175
2038
  }
2176
2039
  };
2177
- __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
2178
- var TaskContextLogProcessor = _TaskContextLogProcessor;
2040
+ _getTaskContext = new WeakSet();
2041
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
2042
+ return getGlobal(API_NAME);
2043
+ }, "#getTaskContext");
2044
+ __name(_TaskContextAPI, "TaskContextAPI");
2045
+ var TaskContextAPI = _TaskContextAPI;
2046
+
2047
+ // src/v3/task-context-api.ts
2048
+ var taskContext = TaskContextAPI.getInstance();
2179
2049
 
2180
2050
  // src/v3/utils/getEnv.ts
2181
2051
  function getEnvVar(name) {
@@ -2184,6 +2054,19 @@ function getEnvVar(name) {
2184
2054
  }
2185
2055
  }
2186
2056
  __name(getEnvVar, "getEnvVar");
2057
+ var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
2058
+ constructor() {
2059
+ this.storage = new async_hooks.AsyncLocalStorage();
2060
+ }
2061
+ runWith(context3, fn) {
2062
+ return this.storage.run(context3, fn);
2063
+ }
2064
+ getStore() {
2065
+ return this.storage.getStore();
2066
+ }
2067
+ };
2068
+ __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
2069
+ var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
2187
2070
 
2188
2071
  // src/v3/apiClient/index.ts
2189
2072
  var zodFetchOptions = {
@@ -2319,7 +2202,7 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2319
2202
  "Content-Type": "application/json",
2320
2203
  Authorization: `Bearer ${this.accessToken}`
2321
2204
  };
2322
- if (taskContextManager.isInsideTask) {
2205
+ if (taskContext.isInsideTask) {
2323
2206
  api.propagation.inject(api.context.active(), headers);
2324
2207
  if (spanParentAsLink) {
2325
2208
  headers["x-trigger-span-parent-as-link"] = "1";
@@ -2329,18 +2212,18 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2329
2212
  }, "#getHeaders");
2330
2213
  __name(_ApiClient, "ApiClient");
2331
2214
  var ApiClient = _ApiClient;
2332
- var _getStore2, getStore_fn2;
2215
+ var _getStore, getStore_fn;
2333
2216
  var _ApiClientManager = class _ApiClientManager {
2334
2217
  constructor() {
2335
- __privateAdd(this, _getStore2);
2218
+ __privateAdd(this, _getStore);
2336
2219
  __publicField(this, "_storage", new SafeAsyncLocalStorage());
2337
2220
  }
2338
2221
  get baseURL() {
2339
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2222
+ const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2340
2223
  return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
2341
2224
  }
2342
2225
  get accessToken() {
2343
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2226
+ const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2344
2227
  return store?.accessToken ?? getEnvVar("TRIGGER_SECRET_KEY");
2345
2228
  }
2346
2229
  get client() {
@@ -2353,13 +2236,61 @@ var _ApiClientManager = class _ApiClientManager {
2353
2236
  return this._storage.runWith(context3, fn);
2354
2237
  }
2355
2238
  };
2356
- _getStore2 = new WeakSet();
2357
- getStore_fn2 = /* @__PURE__ */ __name(function() {
2239
+ _getStore = new WeakSet();
2240
+ getStore_fn = /* @__PURE__ */ __name(function() {
2358
2241
  return this._storage.getStore();
2359
2242
  }, "#getStore");
2360
2243
  __name(_ApiClientManager, "ApiClientManager");
2361
2244
  var ApiClientManager = _ApiClientManager;
2362
2245
  var apiClientManager = new ApiClientManager();
2246
+ var _SimpleClock = class _SimpleClock {
2247
+ preciseNow() {
2248
+ const now = new preciseDate.PreciseDate();
2249
+ const nowStruct = now.toStruct();
2250
+ return [
2251
+ nowStruct.seconds,
2252
+ nowStruct.nanos
2253
+ ];
2254
+ }
2255
+ reset() {
2256
+ }
2257
+ };
2258
+ __name(_SimpleClock, "SimpleClock");
2259
+ var SimpleClock = _SimpleClock;
2260
+
2261
+ // src/v3/clock/index.ts
2262
+ var API_NAME2 = "clock";
2263
+ var SIMPLE_CLOCK = new SimpleClock();
2264
+ var _getClock, getClock_fn;
2265
+ var _ClockAPI = class _ClockAPI {
2266
+ constructor() {
2267
+ __privateAdd(this, _getClock);
2268
+ }
2269
+ static getInstance() {
2270
+ if (!this._instance) {
2271
+ this._instance = new _ClockAPI();
2272
+ }
2273
+ return this._instance;
2274
+ }
2275
+ setGlobalClock(clock2) {
2276
+ return registerGlobal(API_NAME2, clock2);
2277
+ }
2278
+ preciseNow() {
2279
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2280
+ }
2281
+ reset() {
2282
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2283
+ }
2284
+ };
2285
+ _getClock = new WeakSet();
2286
+ getClock_fn = /* @__PURE__ */ __name(function() {
2287
+ return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2288
+ }, "#getClock");
2289
+ __name(_ClockAPI, "ClockAPI");
2290
+ var ClockAPI = _ClockAPI;
2291
+
2292
+ // src/v3/clock-api.ts
2293
+ var clock = ClockAPI.getInstance();
2363
2294
  function parseError(error) {
2364
2295
  if (error instanceof Error) {
2365
2296
  return {
@@ -2471,261 +2402,146 @@ function groupTaskMetadataIssuesByTask(tasks, issues) {
2471
2402
  }
2472
2403
  __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
2473
2404
 
2474
- // src/v3/utils/platform.ts
2475
- var _globalThis = typeof globalThis === "object" ? globalThis : global;
2476
-
2477
- // src/v3/utils/globals.ts
2478
- var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
2479
- var _global = _globalThis;
2480
- function registerGlobal(type, instance, allowOverride = false) {
2481
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
2482
- if (!allowOverride && api[type]) {
2483
- return false;
2484
- }
2485
- api[type] = instance;
2486
- return true;
2487
- }
2488
- __name(registerGlobal, "registerGlobal");
2489
- function getGlobal(type) {
2490
- return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
2491
- }
2492
- __name(getGlobal, "getGlobal");
2493
- function unregisterGlobal(type) {
2494
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
2495
- if (api) {
2496
- delete api[type];
2405
+ // src/v3/limits.ts
2406
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2407
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
2408
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2409
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2410
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
2411
+ var OTEL_LINK_COUNT_LIMIT = 2;
2412
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
2413
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
2414
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
2415
+ function imposeAttributeLimits(attributes) {
2416
+ const newAttributes = {};
2417
+ for (const [key, value] of Object.entries(attributes)) {
2418
+ if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
2419
+ continue;
2420
+ }
2421
+ if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
2422
+ break;
2423
+ }
2424
+ newAttributes[key] = value;
2497
2425
  }
2426
+ return newAttributes;
2498
2427
  }
2499
- __name(unregisterGlobal, "unregisterGlobal");
2500
-
2501
- // src/v3/runtime/noopRuntimeManager.ts
2502
- var _NoopRuntimeManager = class _NoopRuntimeManager {
2503
- disable() {
2428
+ __name(imposeAttributeLimits, "imposeAttributeLimits");
2429
+ function calculateAttributeValueLength(value) {
2430
+ if (value === void 0 || value === null) {
2431
+ return 0;
2504
2432
  }
2505
- waitForDuration(ms) {
2506
- return Promise.resolve();
2433
+ if (typeof value === "string") {
2434
+ return value.length;
2507
2435
  }
2508
- waitUntil(date) {
2509
- return Promise.resolve();
2436
+ if (typeof value === "number") {
2437
+ return 8;
2510
2438
  }
2511
- waitForTask(params) {
2512
- return Promise.resolve({
2513
- ok: false,
2514
- id: params.id,
2515
- error: {
2516
- type: "INTERNAL_ERROR",
2517
- code: "CONFIGURED_INCORRECTLY"
2518
- }
2519
- });
2439
+ if (typeof value === "boolean") {
2440
+ return 4;
2520
2441
  }
2521
- waitForBatch(params) {
2522
- return Promise.resolve({
2523
- id: params.id,
2524
- items: []
2525
- });
2442
+ if (Array.isArray(value)) {
2443
+ return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
2526
2444
  }
2527
- };
2528
- __name(_NoopRuntimeManager, "NoopRuntimeManager");
2529
- var NoopRuntimeManager = _NoopRuntimeManager;
2445
+ return 0;
2446
+ }
2447
+ __name(calculateAttributeValueLength, "calculateAttributeValueLength");
2530
2448
 
2531
- // src/v3/runtime/index.ts
2532
- var API_NAME = "runtime";
2533
- var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
2534
- var _getRuntimeManager, getRuntimeManager_fn;
2535
- var _RuntimeAPI = class _RuntimeAPI {
2536
- constructor() {
2537
- __privateAdd(this, _getRuntimeManager);
2538
- }
2539
- static getInstance() {
2540
- if (!this._instance) {
2541
- this._instance = new _RuntimeAPI();
2542
- }
2543
- return this._instance;
2544
- }
2545
- waitForDuration(ms) {
2546
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2547
- }
2548
- waitUntil(date) {
2549
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
2550
- }
2551
- waitForTask(params) {
2552
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
2449
+ // src/v3/utils/flattenAttributes.ts
2450
+ function flattenAttributes(obj, prefix) {
2451
+ const result = {};
2452
+ if (!obj) {
2453
+ return result;
2553
2454
  }
2554
- waitForBatch(params) {
2555
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
2455
+ if (typeof obj === "string") {
2456
+ result[prefix || ""] = obj;
2457
+ return result;
2556
2458
  }
2557
- setGlobalRuntimeManager(runtimeManager) {
2558
- return registerGlobal(API_NAME, runtimeManager);
2459
+ if (typeof obj === "number") {
2460
+ result[prefix || ""] = obj;
2461
+ return result;
2559
2462
  }
2560
- disable() {
2561
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2562
- unregisterGlobal(API_NAME);
2463
+ if (typeof obj === "boolean") {
2464
+ result[prefix || ""] = obj;
2465
+ return result;
2563
2466
  }
2564
- };
2565
- _getRuntimeManager = new WeakSet();
2566
- getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
2567
- return getGlobal(API_NAME) ?? NOOP_RUNTIME_MANAGER;
2568
- }, "#getRuntimeManager");
2569
- __name(_RuntimeAPI, "RuntimeAPI");
2570
- var RuntimeAPI = _RuntimeAPI;
2571
-
2572
- // src/v3/runtime-api.ts
2573
- var runtime = RuntimeAPI.getInstance();
2574
- function iconStringForSeverity(severityNumber) {
2575
- switch (severityNumber) {
2576
- case apiLogs.SeverityNumber.UNSPECIFIED:
2577
- return void 0;
2578
- case apiLogs.SeverityNumber.TRACE:
2579
- case apiLogs.SeverityNumber.TRACE2:
2580
- case apiLogs.SeverityNumber.TRACE3:
2581
- case apiLogs.SeverityNumber.TRACE4:
2582
- return "trace";
2583
- case apiLogs.SeverityNumber.DEBUG:
2584
- case apiLogs.SeverityNumber.DEBUG2:
2585
- case apiLogs.SeverityNumber.DEBUG3:
2586
- case apiLogs.SeverityNumber.DEBUG4:
2587
- return "debug";
2588
- case apiLogs.SeverityNumber.INFO:
2589
- case apiLogs.SeverityNumber.INFO2:
2590
- case apiLogs.SeverityNumber.INFO3:
2591
- case apiLogs.SeverityNumber.INFO4:
2592
- return "info";
2593
- case apiLogs.SeverityNumber.WARN:
2594
- case apiLogs.SeverityNumber.WARN2:
2595
- case apiLogs.SeverityNumber.WARN3:
2596
- case apiLogs.SeverityNumber.WARN4:
2597
- return "warn";
2598
- case apiLogs.SeverityNumber.ERROR:
2599
- case apiLogs.SeverityNumber.ERROR2:
2600
- case apiLogs.SeverityNumber.ERROR3:
2601
- case apiLogs.SeverityNumber.ERROR4:
2602
- return "error";
2603
- case apiLogs.SeverityNumber.FATAL:
2604
- case apiLogs.SeverityNumber.FATAL2:
2605
- case apiLogs.SeverityNumber.FATAL3:
2606
- case apiLogs.SeverityNumber.FATAL4:
2607
- return "fatal";
2467
+ for (const [key, value] of Object.entries(obj)) {
2468
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
2469
+ if (Array.isArray(value)) {
2470
+ for (let i = 0; i < value.length; i++) {
2471
+ if (typeof value[i] === "object" && value[i] !== null) {
2472
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
2473
+ } else {
2474
+ result[`${newPrefix}.[${i}]`] = value[i];
2475
+ }
2476
+ }
2477
+ } else if (isRecord(value)) {
2478
+ Object.assign(result, flattenAttributes(value, newPrefix));
2479
+ } else {
2480
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
2481
+ result[newPrefix] = value;
2482
+ }
2483
+ }
2608
2484
  }
2485
+ return result;
2609
2486
  }
2610
- __name(iconStringForSeverity, "iconStringForSeverity");
2611
- var _SimpleClock = class _SimpleClock {
2612
- preciseNow() {
2613
- const now = new preciseDate.PreciseDate();
2614
- const nowStruct = now.toStruct();
2615
- return [
2616
- nowStruct.seconds,
2617
- nowStruct.nanos
2618
- ];
2619
- }
2620
- reset() {
2621
- }
2622
- };
2623
- __name(_SimpleClock, "SimpleClock");
2624
- var SimpleClock = _SimpleClock;
2625
-
2626
- // src/v3/clock/index.ts
2627
- var API_NAME2 = "clock";
2628
- var SIMPLE_CLOCK = new SimpleClock();
2629
- var _getClock, getClock_fn;
2630
- var _ClockAPI = class _ClockAPI {
2631
- constructor() {
2632
- __privateAdd(this, _getClock);
2487
+ __name(flattenAttributes, "flattenAttributes");
2488
+ function isRecord(value) {
2489
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2490
+ }
2491
+ __name(isRecord, "isRecord");
2492
+ function unflattenAttributes(obj) {
2493
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
2494
+ return obj;
2633
2495
  }
2634
- static getInstance() {
2635
- if (!this._instance) {
2636
- this._instance = new _ClockAPI();
2496
+ const result = {};
2497
+ for (const [key, value] of Object.entries(obj)) {
2498
+ const parts = key.split(".").reduce((acc, part) => {
2499
+ if (detectIsArrayIndex(part)) {
2500
+ acc.push(part);
2501
+ } else {
2502
+ acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
2503
+ }
2504
+ return acc;
2505
+ }, []);
2506
+ let current = result;
2507
+ for (let i = 0; i < parts.length - 1; i++) {
2508
+ const part = parts[i];
2509
+ const isArray = detectIsArrayIndex(part);
2510
+ const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
2511
+ const nextIsArray = detectIsArrayIndex(parts[i + 1]);
2512
+ if (!current[cleanPart]) {
2513
+ current[cleanPart] = nextIsArray ? [] : {};
2514
+ }
2515
+ current = current[cleanPart];
2637
2516
  }
2638
- return this._instance;
2639
- }
2640
- setGlobalClock(clock2) {
2641
- return registerGlobal(API_NAME2, clock2);
2642
- }
2643
- preciseNow() {
2644
- return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2645
- }
2646
- reset() {
2647
- __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2648
- }
2649
- };
2650
- _getClock = new WeakSet();
2651
- getClock_fn = /* @__PURE__ */ __name(function() {
2652
- return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2653
- }, "#getClock");
2654
- __name(_ClockAPI, "ClockAPI");
2655
- var ClockAPI = _ClockAPI;
2656
-
2657
- // src/v3/clock-api.ts
2658
- var clock = ClockAPI.getInstance();
2659
-
2660
- // src/v3/logger/taskLogger.ts
2661
- var logLevels = [
2662
- "none",
2663
- "error",
2664
- "warn",
2665
- "log",
2666
- "info",
2667
- "debug"
2668
- ];
2669
- var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
2670
- var _OtelTaskLogger = class _OtelTaskLogger {
2671
- constructor(_config) {
2672
- __privateAdd(this, _emitLog);
2673
- __privateAdd(this, _getTimestampInHrTime);
2674
- this._config = _config;
2675
- this._level = logLevels.indexOf(_config.level);
2676
- }
2677
- debug(message, properties) {
2678
- if (this._level < 5)
2679
- return;
2680
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", apiLogs.SeverityNumber.DEBUG, properties);
2681
- }
2682
- log(message, properties) {
2683
- if (this._level < 3)
2684
- return;
2685
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", apiLogs.SeverityNumber.INFO, properties);
2686
- }
2687
- info(message, properties) {
2688
- if (this._level < 4)
2689
- return;
2690
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", apiLogs.SeverityNumber.INFO, properties);
2517
+ const lastPart = parts[parts.length - 1];
2518
+ const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
2519
+ current[cleanLastPart] = value;
2691
2520
  }
2692
- warn(message, properties) {
2693
- if (this._level < 2)
2694
- return;
2695
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", apiLogs.SeverityNumber.WARN, properties);
2521
+ return result;
2522
+ }
2523
+ __name(unflattenAttributes, "unflattenAttributes");
2524
+ function detectIsArrayIndex(key) {
2525
+ const match = key.match(/^\[(\d+)\]$/);
2526
+ if (match) {
2527
+ return true;
2696
2528
  }
2697
- error(message, properties) {
2698
- if (this._level < 1)
2699
- return;
2700
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", apiLogs.SeverityNumber.ERROR, properties);
2529
+ return false;
2530
+ }
2531
+ __name(detectIsArrayIndex, "detectIsArrayIndex");
2532
+ function primitiveValueOrflattenedAttributes(obj, prefix) {
2533
+ if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
2534
+ return obj;
2701
2535
  }
2702
- trace(name, fn, options) {
2703
- return this._config.tracer.startActiveSpan(name, fn, options);
2536
+ const attributes = flattenAttributes(obj, prefix);
2537
+ if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
2538
+ return attributes[prefix];
2704
2539
  }
2705
- };
2706
- _emitLog = new WeakSet();
2707
- emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
2708
- let attributes = {
2709
- ...flattenAttributes(safeJsonProcess(properties))
2710
- };
2711
- const icon = iconStringForSeverity(severityNumber);
2712
- if (icon !== void 0) {
2713
- attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
2714
- }
2715
- this._config.logger.emit({
2716
- severityNumber,
2717
- severityText,
2718
- body: message,
2719
- attributes,
2720
- timestamp
2721
- });
2722
- }, "#emitLog");
2723
- _getTimestampInHrTime = new WeakSet();
2724
- getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
2725
- return clock.preciseNow();
2726
- }, "#getTimestampInHrTime");
2727
- __name(_OtelTaskLogger, "OtelTaskLogger");
2728
- var OtelTaskLogger = _OtelTaskLogger;
2540
+ return attributes;
2541
+ }
2542
+ __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
2543
+
2544
+ // src/v3/logger/taskLogger.ts
2729
2545
  var _NoopTaskLogger = class _NoopTaskLogger {
2730
2546
  debug() {
2731
2547
  }
@@ -2743,25 +2559,6 @@ var _NoopTaskLogger = class _NoopTaskLogger {
2743
2559
  };
2744
2560
  __name(_NoopTaskLogger, "NoopTaskLogger");
2745
2561
  var NoopTaskLogger = _NoopTaskLogger;
2746
- function safeJsonProcess(value) {
2747
- try {
2748
- return JSON.parse(JSON.stringify(value, jsonErrorReplacer));
2749
- } catch {
2750
- return value;
2751
- }
2752
- }
2753
- __name(safeJsonProcess, "safeJsonProcess");
2754
- function jsonErrorReplacer(key, value) {
2755
- if (value instanceof Error) {
2756
- return {
2757
- name: value.name,
2758
- message: value.message,
2759
- stack: value.stack
2760
- };
2761
- }
2762
- return value;
2763
- }
2764
- __name(jsonErrorReplacer, "jsonErrorReplacer");
2765
2562
 
2766
2563
  // src/v3/logger/index.ts
2767
2564
  var API_NAME3 = "logger";
@@ -2812,6 +2609,80 @@ var LoggerAPI = _LoggerAPI;
2812
2609
  // src/v3/logger-api.ts
2813
2610
  var logger = LoggerAPI.getInstance();
2814
2611
 
2612
+ // src/v3/runtime/noopRuntimeManager.ts
2613
+ var _NoopRuntimeManager = class _NoopRuntimeManager {
2614
+ disable() {
2615
+ }
2616
+ waitForDuration(ms) {
2617
+ return Promise.resolve();
2618
+ }
2619
+ waitUntil(date) {
2620
+ return Promise.resolve();
2621
+ }
2622
+ waitForTask(params) {
2623
+ return Promise.resolve({
2624
+ ok: false,
2625
+ id: params.id,
2626
+ error: {
2627
+ type: "INTERNAL_ERROR",
2628
+ code: "CONFIGURED_INCORRECTLY"
2629
+ }
2630
+ });
2631
+ }
2632
+ waitForBatch(params) {
2633
+ return Promise.resolve({
2634
+ id: params.id,
2635
+ items: []
2636
+ });
2637
+ }
2638
+ };
2639
+ __name(_NoopRuntimeManager, "NoopRuntimeManager");
2640
+ var NoopRuntimeManager = _NoopRuntimeManager;
2641
+
2642
+ // src/v3/runtime/index.ts
2643
+ var API_NAME4 = "runtime";
2644
+ var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
2645
+ var _getRuntimeManager, getRuntimeManager_fn;
2646
+ var _RuntimeAPI = class _RuntimeAPI {
2647
+ constructor() {
2648
+ __privateAdd(this, _getRuntimeManager);
2649
+ }
2650
+ static getInstance() {
2651
+ if (!this._instance) {
2652
+ this._instance = new _RuntimeAPI();
2653
+ }
2654
+ return this._instance;
2655
+ }
2656
+ waitForDuration(ms) {
2657
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2658
+ }
2659
+ waitUntil(date) {
2660
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
2661
+ }
2662
+ waitForTask(params) {
2663
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
2664
+ }
2665
+ waitForBatch(params) {
2666
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
2667
+ }
2668
+ setGlobalRuntimeManager(runtimeManager) {
2669
+ return registerGlobal(API_NAME4, runtimeManager);
2670
+ }
2671
+ disable() {
2672
+ __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2673
+ unregisterGlobal(API_NAME4);
2674
+ }
2675
+ };
2676
+ _getRuntimeManager = new WeakSet();
2677
+ getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
2678
+ return getGlobal(API_NAME4) ?? NOOP_RUNTIME_MANAGER;
2679
+ }, "#getRuntimeManager");
2680
+ __name(_RuntimeAPI, "RuntimeAPI");
2681
+ var RuntimeAPI = _RuntimeAPI;
2682
+
2683
+ // src/v3/runtime-api.ts
2684
+ var runtime = RuntimeAPI.getInstance();
2685
+
2815
2686
  // src/v3/task-catalog/noopTaskCatalog.ts
2816
2687
  var _NoopTaskCatalog = class _NoopTaskCatalog {
2817
2688
  registerTaskMetadata(task) {
@@ -2836,7 +2707,7 @@ __name(_NoopTaskCatalog, "NoopTaskCatalog");
2836
2707
  var NoopTaskCatalog = _NoopTaskCatalog;
2837
2708
 
2838
2709
  // src/v3/task-catalog/index.ts
2839
- var API_NAME4 = "task-catalog";
2710
+ var API_NAME5 = "task-catalog";
2840
2711
  var NOOP_TASK_CATALOG = new NoopTaskCatalog();
2841
2712
  var _getCatalog, getCatalog_fn;
2842
2713
  var _TaskCatalogAPI = class _TaskCatalogAPI {
@@ -2850,10 +2721,10 @@ var _TaskCatalogAPI = class _TaskCatalogAPI {
2850
2721
  return this._instance;
2851
2722
  }
2852
2723
  setGlobalTaskCatalog(taskCatalog2) {
2853
- return registerGlobal(API_NAME4, taskCatalog2);
2724
+ return registerGlobal(API_NAME5, taskCatalog2);
2854
2725
  }
2855
2726
  disable() {
2856
- unregisterGlobal(API_NAME4);
2727
+ unregisterGlobal(API_NAME5);
2857
2728
  }
2858
2729
  registerTaskMetadata(task) {
2859
2730
  __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskMetadata(task);
@@ -2876,57 +2747,13 @@ var _TaskCatalogAPI = class _TaskCatalogAPI {
2876
2747
  };
2877
2748
  _getCatalog = new WeakSet();
2878
2749
  getCatalog_fn = /* @__PURE__ */ __name(function() {
2879
- return getGlobal(API_NAME4) ?? NOOP_TASK_CATALOG;
2750
+ return getGlobal(API_NAME5) ?? NOOP_TASK_CATALOG;
2880
2751
  }, "#getCatalog");
2881
2752
  __name(_TaskCatalogAPI, "TaskCatalogAPI");
2882
2753
  var TaskCatalogAPI = _TaskCatalogAPI;
2883
2754
 
2884
2755
  // src/v3/task-catalog-api.ts
2885
2756
  var taskCatalog = TaskCatalogAPI.getInstance();
2886
-
2887
- // src/v3/limits.ts
2888
- var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2889
- var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
2890
- var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2891
- var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2892
- var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
2893
- var OTEL_LINK_COUNT_LIMIT = 2;
2894
- var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
2895
- var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
2896
- var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
2897
- function imposeAttributeLimits(attributes) {
2898
- const newAttributes = {};
2899
- for (const [key, value] of Object.entries(attributes)) {
2900
- if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
2901
- continue;
2902
- }
2903
- if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
2904
- break;
2905
- }
2906
- newAttributes[key] = value;
2907
- }
2908
- return newAttributes;
2909
- }
2910
- __name(imposeAttributeLimits, "imposeAttributeLimits");
2911
- function calculateAttributeValueLength(value) {
2912
- if (value === void 0 || value === null) {
2913
- return 0;
2914
- }
2915
- if (typeof value === "string") {
2916
- return value.length;
2917
- }
2918
- if (typeof value === "number") {
2919
- return 8;
2920
- }
2921
- if (typeof value === "boolean") {
2922
- return 4;
2923
- }
2924
- if (Array.isArray(value)) {
2925
- return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
2926
- }
2927
- return 0;
2928
- }
2929
- __name(calculateAttributeValueLength, "calculateAttributeValueLength");
2930
2757
  function dateDifference(date1, date2) {
2931
2758
  return Math.abs(date1.getTime() - date2.getTime());
2932
2759
  }
@@ -3072,146 +2899,6 @@ var _TriggerTracer = class _TriggerTracer {
3072
2899
  };
3073
2900
  __name(_TriggerTracer, "TriggerTracer");
3074
2901
  var TriggerTracer = _TriggerTracer;
3075
- var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
3076
- var _ConsoleInterceptor = class _ConsoleInterceptor {
3077
- constructor(logger2, sendToStdIO) {
3078
- __privateAdd(this, _handleLog);
3079
- __privateAdd(this, _getTimestampInHrTime2);
3080
- __privateAdd(this, _getAttributes);
3081
- this.logger = logger2;
3082
- this.sendToStdIO = sendToStdIO;
3083
- }
3084
- // Intercept the console and send logs to the OpenTelemetry logger
3085
- // during the execution of the callback
3086
- async intercept(console, callback) {
3087
- const originalConsole = {
3088
- log: console.log,
3089
- info: console.info,
3090
- warn: console.warn,
3091
- error: console.error,
3092
- debug: console.debug
3093
- };
3094
- console.log = this.log.bind(this);
3095
- console.info = this.info.bind(this);
3096
- console.warn = this.warn.bind(this);
3097
- console.error = this.error.bind(this);
3098
- console.debug = this.debug.bind(this);
3099
- try {
3100
- return await callback();
3101
- } finally {
3102
- console.log = originalConsole.log;
3103
- console.info = originalConsole.info;
3104
- console.warn = originalConsole.warn;
3105
- console.error = originalConsole.error;
3106
- console.debug = originalConsole.debug;
3107
- }
3108
- }
3109
- debug(...args) {
3110
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
3111
- }
3112
- log(...args) {
3113
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
3114
- }
3115
- info(...args) {
3116
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
3117
- }
3118
- warn(...args) {
3119
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
3120
- }
3121
- error(...args) {
3122
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
3123
- }
3124
- };
3125
- _handleLog = new WeakSet();
3126
- handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
3127
- const body = util__default.default.format(...args);
3128
- if (this.sendToStdIO) {
3129
- if (severityNumber === apiLogs.SeverityNumber.ERROR) {
3130
- process.stderr.write(body);
3131
- } else {
3132
- process.stdout.write(body);
3133
- }
3134
- }
3135
- const parsed = tryParseJSON(body);
3136
- if (parsed.ok) {
3137
- this.logger.emit({
3138
- severityNumber,
3139
- severityText,
3140
- body: getLogMessage(parsed.value, severityText),
3141
- attributes: {
3142
- ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3143
- ...flattenAttributes(parsed.value)
3144
- },
3145
- timestamp
3146
- });
3147
- return;
3148
- }
3149
- this.logger.emit({
3150
- severityNumber,
3151
- severityText,
3152
- body,
3153
- attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3154
- timestamp
3155
- });
3156
- }, "#handleLog");
3157
- _getTimestampInHrTime2 = new WeakSet();
3158
- getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
3159
- return clock.preciseNow();
3160
- }, "#getTimestampInHrTime");
3161
- _getAttributes = new WeakSet();
3162
- getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
3163
- const icon = iconStringForSeverity(severityNumber1);
3164
- let result = {};
3165
- if (icon !== void 0) {
3166
- result[SemanticInternalAttributes.STYLE_ICON] = icon;
3167
- }
3168
- return result;
3169
- }, "#getAttributes");
3170
- __name(_ConsoleInterceptor, "ConsoleInterceptor");
3171
- var ConsoleInterceptor = _ConsoleInterceptor;
3172
- function getLogMessage(value, fallback) {
3173
- if (typeof value["message"] === "string") {
3174
- return value["message"];
3175
- }
3176
- if (typeof value["msg"] === "string") {
3177
- return value["msg"];
3178
- }
3179
- if (typeof value["body"] === "string") {
3180
- return value["body"];
3181
- }
3182
- if (typeof value["error"] === "string") {
3183
- return value["error"];
3184
- }
3185
- return fallback;
3186
- }
3187
- __name(getLogMessage, "getLogMessage");
3188
- function tryParseJSON(value) {
3189
- try {
3190
- const parsed = JSON.parse(value);
3191
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
3192
- return {
3193
- ok: true,
3194
- value: parsed
3195
- };
3196
- }
3197
- return {
3198
- ok: false,
3199
- value
3200
- };
3201
- } catch (e) {
3202
- return {
3203
- ok: false,
3204
- value
3205
- };
3206
- }
3207
- }
3208
- __name(tryParseJSON, "tryParseJSON");
3209
-
3210
- // src/v3/utils/styleAttributes.ts
3211
- function accessoryAttributes(accessory) {
3212
- return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
3213
- }
3214
- __name(accessoryAttributes, "accessoryAttributes");
3215
2902
 
3216
2903
  // src/eventFilterMatches.ts
3217
2904
  function eventFilterMatches(payload, filter) {
@@ -3381,150 +3068,12 @@ function omit(obj, ...keys) {
3381
3068
  return result;
3382
3069
  }
3383
3070
  __name(omit, "omit");
3384
- var _a;
3385
- var AsyncResourceDetector = (_a = class {
3386
- constructor() {
3387
- __publicField(this, "_resolved", false);
3388
- this._promise = new Promise((resolver) => {
3389
- this._resolver = resolver;
3390
- });
3391
- }
3392
- detect(_config) {
3393
- return new resources.Resource({}, this._promise);
3394
- }
3395
- resolveWithAttributes(attributes) {
3396
- if (!this._resolver) {
3397
- throw new Error("Resolver not available");
3398
- }
3399
- if (this._resolved) {
3400
- return;
3401
- }
3402
- this._resolved = true;
3403
- this._resolver(attributes);
3404
- }
3405
- }, __name(_a, "AsyncResourceDetector"), _a);
3406
- var _TracingSDK = class _TracingSDK {
3407
- constructor(config) {
3408
- this.config = config;
3409
- this.asyncResourceDetector = new AsyncResourceDetector();
3410
- setLogLevel(config.diagLogLevel ?? "none");
3411
- const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
3412
- const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
3413
- const commonResources = resources.detectResourcesSync({
3414
- detectors: [
3415
- this.asyncResourceDetector,
3416
- resources.processDetectorSync
3417
- ]
3418
- }).merge(new resources.Resource({
3419
- [semanticConventions.SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
3420
- [SemanticInternalAttributes.TRIGGER]: true
3421
- })).merge(config.resource ?? new resources.Resource({})).merge(new resources.Resource(envResourceAttributes));
3422
- const traceProvider = new sdkTraceNode.NodeTracerProvider({
3423
- forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
3424
- resource: commonResources,
3425
- spanLimits: {
3426
- attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
3427
- attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
3428
- eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
3429
- attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
3430
- linkCountLimit: OTEL_LINK_COUNT_LIMIT,
3431
- attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
3432
- }
3433
- });
3434
- const spanExporter = new exporterTraceOtlpHttp.OTLPTraceExporter({
3435
- url: `${config.url}/v1/traces`,
3436
- timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
3437
- });
3438
- traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkTraceNode.BatchSpanProcessor(spanExporter, {
3439
- maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
3440
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
3441
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
3442
- maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
3443
- }) : new sdkTraceNode.SimpleSpanProcessor(spanExporter)));
3444
- traceProvider.register();
3445
- instrumentation.registerInstrumentations({
3446
- instrumentations: config.instrumentations ?? [],
3447
- tracerProvider: traceProvider
3448
- });
3449
- const logExporter = new exporterLogsOtlpHttp.OTLPLogExporter({
3450
- url: `${config.url}/v1/logs`
3451
- });
3452
- const loggerProvider = new sdkLogs.LoggerProvider({
3453
- resource: commonResources,
3454
- logRecordLimits: {
3455
- attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
3456
- attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
3457
- }
3458
- });
3459
- loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkLogs.BatchLogRecordProcessor(logExporter, {
3460
- maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
3461
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
3462
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
3463
- maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
3464
- }) : new sdkLogs.SimpleLogRecordProcessor(logExporter)));
3465
- this._logProvider = loggerProvider;
3466
- this._spanExporter = spanExporter;
3467
- this._traceProvider = traceProvider;
3468
- apiLogs.logs.setGlobalLoggerProvider(loggerProvider);
3469
- this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
3470
- this.getTracer = traceProvider.getTracer.bind(traceProvider);
3471
- }
3472
- async flush() {
3473
- await this._traceProvider.forceFlush();
3474
- await this._logProvider.forceFlush();
3475
- }
3476
- async shutdown() {
3477
- await this._traceProvider.shutdown();
3478
- await this._logProvider.shutdown();
3479
- }
3480
- };
3481
- __name(_TracingSDK, "TracingSDK");
3482
- var TracingSDK = _TracingSDK;
3483
- function setLogLevel(level) {
3484
- let diagLogLevel;
3485
- switch (level) {
3486
- case "none":
3487
- diagLogLevel = api.DiagLogLevel.NONE;
3488
- break;
3489
- case "error":
3490
- diagLogLevel = api.DiagLogLevel.ERROR;
3491
- break;
3492
- case "warn":
3493
- diagLogLevel = api.DiagLogLevel.WARN;
3494
- break;
3495
- case "info":
3496
- diagLogLevel = api.DiagLogLevel.INFO;
3497
- break;
3498
- case "debug":
3499
- diagLogLevel = api.DiagLogLevel.DEBUG;
3500
- break;
3501
- case "verbose":
3502
- diagLogLevel = api.DiagLogLevel.VERBOSE;
3503
- break;
3504
- case "all":
3505
- diagLogLevel = api.DiagLogLevel.ALL;
3506
- break;
3507
- default:
3508
- diagLogLevel = api.DiagLogLevel.NONE;
3509
- }
3510
- api.diag.setLogger(new api.DiagConsoleLogger(), diagLogLevel);
3511
- }
3512
- __name(setLogLevel, "setLogLevel");
3513
3071
 
3514
- // src/v3/otel/index.ts
3515
- function recordSpanException(span, error) {
3516
- if (error instanceof Error) {
3517
- span.recordException(error);
3518
- } else if (typeof error === "string") {
3519
- span.recordException(new Error(error));
3520
- } else {
3521
- span.recordException(new Error(JSON.stringify(error)));
3522
- }
3523
- span.setStatus({
3524
- code: api.SpanStatusCode.ERROR
3525
- });
3072
+ // src/v3/utils/styleAttributes.ts
3073
+ function accessoryAttributes(accessory) {
3074
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
3526
3075
  }
3527
- __name(recordSpanException, "recordSpanException");
3076
+ __name(accessoryAttributes, "accessoryAttributes");
3528
3077
 
3529
3078
  // package.json
3530
3079
  var dependencies = {
@@ -3823,94 +3372,6 @@ function safeJsonParse2(value) {
3823
3372
  }
3824
3373
  __name(safeJsonParse2, "safeJsonParse");
3825
3374
 
3826
- // src/v3/task-catalog/standardTaskCatalog.ts
3827
- var _StandardTaskCatalog = class _StandardTaskCatalog {
3828
- constructor() {
3829
- __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
3830
- __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
3831
- __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
3832
- }
3833
- registerTaskMetadata(task) {
3834
- const { fns, ...metadata } = task;
3835
- this._taskMetadata.set(task.id, metadata);
3836
- this._taskFunctions.set(task.id, fns);
3837
- }
3838
- updateTaskMetadata(id, updates) {
3839
- const existingMetadata = this._taskMetadata.get(id);
3840
- if (existingMetadata) {
3841
- this._taskMetadata.set(id, {
3842
- ...existingMetadata,
3843
- ...updates
3844
- });
3845
- }
3846
- if (updates.fns) {
3847
- const existingFunctions = this._taskFunctions.get(id);
3848
- if (existingFunctions) {
3849
- this._taskFunctions.set(id, {
3850
- ...existingFunctions,
3851
- ...updates.fns
3852
- });
3853
- }
3854
- }
3855
- }
3856
- registerTaskFileMetadata(id, metadata) {
3857
- this._taskFileMetadata.set(id, metadata);
3858
- }
3859
- // Return all the tasks, without the functions
3860
- getAllTaskMetadata() {
3861
- const result = [];
3862
- for (const [id, metadata] of this._taskMetadata) {
3863
- const fileMetadata = this._taskFileMetadata.get(id);
3864
- if (!fileMetadata) {
3865
- continue;
3866
- }
3867
- result.push({
3868
- ...metadata,
3869
- ...fileMetadata
3870
- });
3871
- }
3872
- return result;
3873
- }
3874
- getTaskMetadata(id) {
3875
- const metadata = this._taskMetadata.get(id);
3876
- const fileMetadata = this._taskFileMetadata.get(id);
3877
- if (!metadata || !fileMetadata) {
3878
- return void 0;
3879
- }
3880
- return {
3881
- ...metadata,
3882
- ...fileMetadata
3883
- };
3884
- }
3885
- getTask(id) {
3886
- const metadata = this._taskMetadata.get(id);
3887
- const fileMetadata = this._taskFileMetadata.get(id);
3888
- const fns = this._taskFunctions.get(id);
3889
- if (!metadata || !fns || !fileMetadata) {
3890
- return void 0;
3891
- }
3892
- return {
3893
- ...metadata,
3894
- ...fileMetadata,
3895
- fns
3896
- };
3897
- }
3898
- disable() {
3899
- }
3900
- };
3901
- __name(_StandardTaskCatalog, "StandardTaskCatalog");
3902
- var StandardTaskCatalog = _StandardTaskCatalog;
3903
-
3904
- // src/v3/index.ts
3905
- function parseTriggerTaskRequestBody(body) {
3906
- return TriggerTaskRequestBody.safeParse(body);
3907
- }
3908
- __name(parseTriggerTaskRequestBody, "parseTriggerTaskRequestBody");
3909
- function parseBatchTriggerTaskRequestBody(body) {
3910
- return BatchTriggerTaskRequestBody.safeParse(body);
3911
- }
3912
- __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
3913
-
3914
3375
  exports.APIConnectionError = APIConnectionError;
3915
3376
  exports.APIError = APIError;
3916
3377
  exports.ApiClient = ApiClient;
@@ -3929,7 +3390,6 @@ exports.CancellationSpanEvent = CancellationSpanEvent;
3929
3390
  exports.ClientToSharedQueueMessages = ClientToSharedQueueMessages;
3930
3391
  exports.Config = Config;
3931
3392
  exports.ConflictError = ConflictError;
3932
- exports.ConsoleInterceptor = ConsoleInterceptor;
3933
3393
  exports.CoordinatorToPlatformMessages = CoordinatorToPlatformMessages;
3934
3394
  exports.CoordinatorToProdWorkerMessages = CoordinatorToProdWorkerMessages;
3935
3395
  exports.CreateAuthorizationCodeResponseSchema = CreateAuthorizationCodeResponseSchema;
@@ -3978,7 +3438,6 @@ exports.OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_
3978
3438
  exports.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT;
3979
3439
  exports.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT;
3980
3440
  exports.OTEL_SPAN_EVENT_COUNT_LIMIT = OTEL_SPAN_EVENT_COUNT_LIMIT;
3981
- exports.OtelTaskLogger = OtelTaskLogger;
3982
3441
  exports.OtherSpanEvent = OtherSpanEvent;
3983
3442
  exports.PRIMARY_VARIANT = PRIMARY_VARIANT;
3984
3443
  exports.PermissionDeniedError = PermissionDeniedError;
@@ -4006,10 +3465,8 @@ exports.SlidingWindowRateLimit = SlidingWindowRateLimit;
4006
3465
  exports.SpanEvent = SpanEvent;
4007
3466
  exports.SpanEvents = SpanEvents;
4008
3467
  exports.SpanMessagingEvent = SpanMessagingEvent;
4009
- exports.StandardTaskCatalog = StandardTaskCatalog;
4010
3468
  exports.StartDeploymentIndexingRequestBody = StartDeploymentIndexingRequestBody;
4011
3469
  exports.StartDeploymentIndexingResponseBody = StartDeploymentIndexingResponseBody;
4012
- exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
4013
3470
  exports.TaskEventStyle = TaskEventStyle;
4014
3471
  exports.TaskFileMetadata = TaskFileMetadata;
4015
3472
  exports.TaskMetadata = TaskMetadata;
@@ -4037,7 +3494,6 @@ exports.TaskRunFailedExecutionResult = TaskRunFailedExecutionResult;
4037
3494
  exports.TaskRunInternalError = TaskRunInternalError;
4038
3495
  exports.TaskRunStringError = TaskRunStringError;
4039
3496
  exports.TaskRunSuccessfulExecutionResult = TaskRunSuccessfulExecutionResult;
4040
- exports.TracingSDK = TracingSDK;
4041
3497
  exports.TriggerTaskRequestBody = TriggerTaskRequestBody;
4042
3498
  exports.TriggerTaskResponse = TriggerTaskResponse;
4043
3499
  exports.TriggerTracer = TriggerTracer;
@@ -4068,31 +3524,25 @@ exports.formatDuration = formatDuration;
4068
3524
  exports.formatDurationInDays = formatDurationInDays;
4069
3525
  exports.formatDurationMilliseconds = formatDurationMilliseconds;
4070
3526
  exports.formatDurationNanoseconds = formatDurationNanoseconds;
4071
- exports.getEnvVar = getEnvVar;
4072
3527
  exports.groupTaskMetadataIssuesByTask = groupTaskMetadataIssuesByTask;
4073
- exports.iconStringForSeverity = iconStringForSeverity;
4074
3528
  exports.imposeAttributeLimits = imposeAttributeLimits;
4075
3529
  exports.isCancellationSpanEvent = isCancellationSpanEvent;
4076
3530
  exports.isExceptionSpanEvent = isExceptionSpanEvent;
4077
- exports.logLevels = logLevels;
4078
3531
  exports.logger = logger;
4079
3532
  exports.millisecondsToNanoseconds = millisecondsToNanoseconds;
4080
3533
  exports.nanosecondsToMilliseconds = nanosecondsToMilliseconds;
4081
3534
  exports.omit = omit;
4082
3535
  exports.packetRequiresOffloading = packetRequiresOffloading;
4083
- exports.parseBatchTriggerTaskRequestBody = parseBatchTriggerTaskRequestBody;
4084
3536
  exports.parseError = parseError;
4085
3537
  exports.parsePacket = parsePacket;
4086
- exports.parseTriggerTaskRequestBody = parseTriggerTaskRequestBody;
4087
3538
  exports.prettyPrintPacket = prettyPrintPacket;
4088
3539
  exports.primitiveValueOrflattenedAttributes = primitiveValueOrflattenedAttributes;
4089
- exports.recordSpanException = recordSpanException;
4090
3540
  exports.runtime = runtime;
4091
3541
  exports.serverWebsocketMessages = serverWebsocketMessages;
4092
3542
  exports.stringPatternMatchers = stringPatternMatchers;
4093
3543
  exports.stringifyIO = stringifyIO;
4094
3544
  exports.taskCatalog = taskCatalog;
4095
- exports.taskContextManager = taskContextManager;
3545
+ exports.taskContext = taskContext;
4096
3546
  exports.unflattenAttributes = unflattenAttributes;
4097
3547
  exports.workerToChildMessages = workerToChildMessages;
4098
3548
  //# sourceMappingURL=out.js.map