@trigger.dev/core 2.3.18 → 3.0.0-beta.0

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.
@@ -0,0 +1,4491 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+ var api = require('@opentelemetry/api');
5
+ var async_hooks = require('async_hooks');
6
+ var socket_ioClient = require('socket.io-client');
7
+ var crypto = require('crypto');
8
+ var nodePath = require('path');
9
+ var apiLogs = require('@opentelemetry/api-logs');
10
+ var preciseDate = require('@google-cloud/precise-date');
11
+ var humanizeDuration = require('humanize-duration');
12
+ var util = require('util');
13
+ var exporterLogsOtlpHttp = require('@opentelemetry/exporter-logs-otlp-http');
14
+ var exporterTraceOtlpHttp = require('@opentelemetry/exporter-trace-otlp-http');
15
+ var instrumentation = require('@opentelemetry/instrumentation');
16
+ var resources = require('@opentelemetry/resources');
17
+ var sdkLogs = require('@opentelemetry/sdk-logs');
18
+ var sdkTraceNode = require('@opentelemetry/sdk-trace-node');
19
+ var semanticConventions = require('@opentelemetry/semantic-conventions');
20
+ var superjson = require('superjson');
21
+
22
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
23
+
24
+ var nodePath__default = /*#__PURE__*/_interopDefault(nodePath);
25
+ var humanizeDuration__default = /*#__PURE__*/_interopDefault(humanizeDuration);
26
+ var util__default = /*#__PURE__*/_interopDefault(util);
27
+
28
+ var __defProp = Object.defineProperty;
29
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
30
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
31
+ var __publicField = (obj, key, value) => {
32
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
33
+ return value;
34
+ };
35
+ var __accessCheck = (obj, member, msg) => {
36
+ if (!member.has(obj))
37
+ throw TypeError("Cannot " + msg);
38
+ };
39
+ var __privateGet = (obj, member, getter) => {
40
+ __accessCheck(obj, member, "read from private field");
41
+ return getter ? getter.call(obj) : member.get(obj);
42
+ };
43
+ var __privateAdd = (obj, member, value) => {
44
+ if (member.has(obj))
45
+ throw TypeError("Cannot add the same private member more than once");
46
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
47
+ };
48
+ var __privateSet = (obj, member, value, setter) => {
49
+ __accessCheck(obj, member, "write to private field");
50
+ setter ? setter.call(obj, value) : member.set(obj, value);
51
+ return value;
52
+ };
53
+ var __privateWrapper = (obj, member, setter, getter) => ({
54
+ set _(value) {
55
+ __privateSet(obj, member, value, setter);
56
+ },
57
+ get _() {
58
+ return __privateGet(obj, member, getter);
59
+ }
60
+ });
61
+ var __privateMethod = (obj, member, method) => {
62
+ __accessCheck(obj, member, "access private method");
63
+ return method;
64
+ };
65
+ var CreateAuthorizationCodeResponseSchema = zod.z.object({
66
+ url: zod.z.string().url(),
67
+ authorizationCode: zod.z.string()
68
+ });
69
+ var GetPersonalAccessTokenRequestSchema = zod.z.object({
70
+ authorizationCode: zod.z.string()
71
+ });
72
+ var GetPersonalAccessTokenResponseSchema = zod.z.object({
73
+ token: zod.z.object({
74
+ token: zod.z.string(),
75
+ obfuscatedToken: zod.z.string()
76
+ }).nullable()
77
+ });
78
+ var TaskRunBuiltInError = zod.z.object({
79
+ type: zod.z.literal("BUILT_IN_ERROR"),
80
+ name: zod.z.string(),
81
+ message: zod.z.string(),
82
+ stackTrace: zod.z.string()
83
+ });
84
+ var TaskRunCustomErrorObject = zod.z.object({
85
+ type: zod.z.literal("CUSTOM_ERROR"),
86
+ raw: zod.z.string()
87
+ });
88
+ var TaskRunStringError = zod.z.object({
89
+ type: zod.z.literal("STRING_ERROR"),
90
+ raw: zod.z.string()
91
+ });
92
+ var TaskRunErrorCodes = {
93
+ COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
94
+ CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
95
+ TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
96
+ TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
97
+ TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
98
+ TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
99
+ TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
100
+ TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
101
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR"
102
+ };
103
+ var TaskRunInternalError = zod.z.object({
104
+ type: zod.z.literal("INTERNAL_ERROR"),
105
+ code: zod.z.enum([
106
+ "COULD_NOT_FIND_EXECUTOR",
107
+ "CONFIGURED_INCORRECTLY",
108
+ "TASK_ALREADY_RUNNING",
109
+ "TASK_EXECUTION_FAILED",
110
+ "TASK_EXECUTION_ABORTED",
111
+ "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
112
+ "TASK_RUN_CANCELLED",
113
+ "TASK_OUTPUT_ERROR",
114
+ "HANDLE_ERROR_ERROR"
115
+ ]),
116
+ message: zod.z.string().optional()
117
+ });
118
+ var TaskRunError = zod.z.discriminatedUnion("type", [
119
+ TaskRunBuiltInError,
120
+ TaskRunCustomErrorObject,
121
+ TaskRunStringError,
122
+ TaskRunInternalError
123
+ ]);
124
+ var TaskRun = zod.z.object({
125
+ id: zod.z.string(),
126
+ payload: zod.z.string(),
127
+ payloadType: zod.z.string(),
128
+ context: zod.z.any(),
129
+ tags: zod.z.array(zod.z.string()),
130
+ isTest: zod.z.boolean().default(false),
131
+ createdAt: zod.z.coerce.date()
132
+ });
133
+ var TaskRunExecutionTask = zod.z.object({
134
+ id: zod.z.string(),
135
+ filePath: zod.z.string(),
136
+ exportName: zod.z.string()
137
+ });
138
+ var TaskRunExecutionAttempt = zod.z.object({
139
+ id: zod.z.string(),
140
+ number: zod.z.number(),
141
+ startedAt: zod.z.coerce.date(),
142
+ backgroundWorkerId: zod.z.string(),
143
+ backgroundWorkerTaskId: zod.z.string(),
144
+ status: zod.z.string()
145
+ });
146
+ var TaskRunExecutionEnvironment = zod.z.object({
147
+ id: zod.z.string(),
148
+ slug: zod.z.string(),
149
+ type: zod.z.enum([
150
+ "PRODUCTION",
151
+ "STAGING",
152
+ "DEVELOPMENT",
153
+ "PREVIEW"
154
+ ])
155
+ });
156
+ var TaskRunExecutionOrganization = zod.z.object({
157
+ id: zod.z.string(),
158
+ slug: zod.z.string(),
159
+ name: zod.z.string()
160
+ });
161
+ var TaskRunExecutionProject = zod.z.object({
162
+ id: zod.z.string(),
163
+ ref: zod.z.string(),
164
+ slug: zod.z.string(),
165
+ name: zod.z.string()
166
+ });
167
+ var TaskRunExecutionQueue = zod.z.object({
168
+ id: zod.z.string(),
169
+ name: zod.z.string()
170
+ });
171
+ var TaskRunExecutionBatch = zod.z.object({
172
+ id: zod.z.string()
173
+ });
174
+ var TaskRunExecution = zod.z.object({
175
+ task: TaskRunExecutionTask,
176
+ attempt: TaskRunExecutionAttempt,
177
+ run: TaskRun,
178
+ queue: TaskRunExecutionQueue,
179
+ environment: TaskRunExecutionEnvironment,
180
+ organization: TaskRunExecutionOrganization,
181
+ project: TaskRunExecutionProject,
182
+ batch: TaskRunExecutionBatch.optional()
183
+ });
184
+ var TaskRunContext = zod.z.object({
185
+ task: TaskRunExecutionTask,
186
+ attempt: TaskRunExecutionAttempt.omit({
187
+ backgroundWorkerId: true,
188
+ backgroundWorkerTaskId: true
189
+ }),
190
+ run: TaskRun.omit({
191
+ payload: true,
192
+ payloadType: true
193
+ }),
194
+ queue: TaskRunExecutionQueue,
195
+ environment: TaskRunExecutionEnvironment,
196
+ organization: TaskRunExecutionOrganization,
197
+ project: TaskRunExecutionProject,
198
+ batch: TaskRunExecutionBatch.optional()
199
+ });
200
+ var TaskRunExecutionRetry = zod.z.object({
201
+ timestamp: zod.z.number(),
202
+ delay: zod.z.number(),
203
+ error: zod.z.unknown().optional()
204
+ });
205
+ var TaskRunFailedExecutionResult = zod.z.object({
206
+ ok: zod.z.literal(false),
207
+ id: zod.z.string(),
208
+ error: TaskRunError,
209
+ retry: TaskRunExecutionRetry.optional(),
210
+ skippedRetrying: zod.z.boolean().optional()
211
+ });
212
+ var TaskRunSuccessfulExecutionResult = zod.z.object({
213
+ ok: zod.z.literal(true),
214
+ id: zod.z.string(),
215
+ output: zod.z.string().optional(),
216
+ outputType: zod.z.string()
217
+ });
218
+ var TaskRunExecutionResult = zod.z.discriminatedUnion("ok", [
219
+ TaskRunSuccessfulExecutionResult,
220
+ TaskRunFailedExecutionResult
221
+ ]);
222
+ var BatchTaskRunExecutionResult = zod.z.object({
223
+ id: zod.z.string(),
224
+ items: TaskRunExecutionResult.array()
225
+ });
226
+
227
+ // src/v3/schemas/messages.ts
228
+ var TaskRunExecutionPayload = zod.z.object({
229
+ execution: TaskRunExecution,
230
+ traceContext: zod.z.record(zod.z.unknown()),
231
+ environment: zod.z.record(zod.z.string()).optional()
232
+ });
233
+ var ProdTaskRunExecution = TaskRunExecution.extend({
234
+ worker: zod.z.object({
235
+ id: zod.z.string(),
236
+ contentHash: zod.z.string(),
237
+ version: zod.z.string()
238
+ })
239
+ });
240
+ var ProdTaskRunExecutionPayload = zod.z.object({
241
+ execution: ProdTaskRunExecution,
242
+ traceContext: zod.z.record(zod.z.unknown()),
243
+ environment: zod.z.record(zod.z.string()).optional()
244
+ });
245
+ var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
246
+ zod.z.object({
247
+ type: zod.z.literal("EXECUTE_RUNS"),
248
+ payloads: zod.z.array(TaskRunExecutionPayload)
249
+ }),
250
+ zod.z.object({
251
+ type: zod.z.literal("CANCEL_ATTEMPT"),
252
+ taskAttemptId: zod.z.string(),
253
+ taskRunId: zod.z.string()
254
+ }),
255
+ zod.z.object({
256
+ type: zod.z.literal("SCHEDULE_ATTEMPT"),
257
+ id: zod.z.string(),
258
+ image: zod.z.string(),
259
+ envId: zod.z.string(),
260
+ runId: zod.z.string(),
261
+ version: zod.z.string()
262
+ })
263
+ ]);
264
+ var serverWebsocketMessages = {
265
+ SERVER_READY: zod.z.object({
266
+ version: zod.z.literal("v1").default("v1"),
267
+ id: zod.z.string()
268
+ }),
269
+ BACKGROUND_WORKER_MESSAGE: zod.z.object({
270
+ version: zod.z.literal("v1").default("v1"),
271
+ backgroundWorkerId: zod.z.string(),
272
+ data: BackgroundWorkerServerMessages
273
+ })
274
+ };
275
+ var BackgroundWorkerClientMessages = zod.z.discriminatedUnion("type", [
276
+ zod.z.object({
277
+ version: zod.z.literal("v1").default("v1"),
278
+ type: zod.z.literal("TASK_RUN_COMPLETED"),
279
+ completion: TaskRunExecutionResult,
280
+ execution: TaskRunExecution
281
+ }),
282
+ zod.z.object({
283
+ version: zod.z.literal("v1").default("v1"),
284
+ type: zod.z.literal("TASK_HEARTBEAT"),
285
+ id: zod.z.string()
286
+ })
287
+ ]);
288
+ var BackgroundWorkerProperties = zod.z.object({
289
+ id: zod.z.string(),
290
+ version: zod.z.string(),
291
+ contentHash: zod.z.string()
292
+ });
293
+ var clientWebsocketMessages = {
294
+ READY_FOR_TASKS: zod.z.object({
295
+ version: zod.z.literal("v1").default("v1"),
296
+ backgroundWorkerId: zod.z.string()
297
+ }),
298
+ BACKGROUND_WORKER_DEPRECATED: zod.z.object({
299
+ version: zod.z.literal("v1").default("v1"),
300
+ backgroundWorkerId: zod.z.string()
301
+ }),
302
+ BACKGROUND_WORKER_MESSAGE: zod.z.object({
303
+ version: zod.z.literal("v1").default("v1"),
304
+ backgroundWorkerId: zod.z.string(),
305
+ data: BackgroundWorkerClientMessages
306
+ })
307
+ };
308
+ var workerToChildMessages = {
309
+ EXECUTE_TASK_RUN: zod.z.object({
310
+ version: zod.z.literal("v1").default("v1"),
311
+ execution: TaskRunExecution,
312
+ traceContext: zod.z.record(zod.z.unknown()),
313
+ metadata: BackgroundWorkerProperties
314
+ }),
315
+ TASK_RUN_COMPLETED_NOTIFICATION: zod.z.object({
316
+ version: zod.z.literal("v1").default("v1"),
317
+ completion: TaskRunExecutionResult,
318
+ execution: TaskRunExecution
319
+ }),
320
+ CLEANUP: zod.z.object({
321
+ version: zod.z.literal("v1").default("v1"),
322
+ flush: zod.z.boolean().default(false),
323
+ kill: zod.z.boolean().default(true)
324
+ })
325
+ };
326
+ var FixedWindowRateLimit = zod.z.object({
327
+ type: zod.z.literal("fixed-window"),
328
+ limit: zod.z.number(),
329
+ window: zod.z.union([
330
+ zod.z.object({
331
+ seconds: zod.z.number()
332
+ }),
333
+ zod.z.object({
334
+ minutes: zod.z.number()
335
+ }),
336
+ zod.z.object({
337
+ hours: zod.z.number()
338
+ })
339
+ ])
340
+ });
341
+ var SlidingWindowRateLimit = zod.z.object({
342
+ type: zod.z.literal("sliding-window"),
343
+ limit: zod.z.number(),
344
+ window: zod.z.union([
345
+ zod.z.object({
346
+ seconds: zod.z.number()
347
+ }),
348
+ zod.z.object({
349
+ minutes: zod.z.number()
350
+ }),
351
+ zod.z.object({
352
+ hours: zod.z.number()
353
+ })
354
+ ])
355
+ });
356
+ var RateLimitOptions = zod.z.discriminatedUnion("type", [
357
+ FixedWindowRateLimit,
358
+ SlidingWindowRateLimit
359
+ ]);
360
+ var RetryOptions = zod.z.object({
361
+ /** The number of attempts before giving up */
362
+ maxAttempts: zod.z.number().int().optional(),
363
+ /** The exponential factor to use when calculating the next retry time.
364
+ *
365
+ * Each subsequent retry will be calculated as `previousTimeout * factor`
366
+ */
367
+ factor: zod.z.number().optional(),
368
+ /** The minimum time to wait before retrying */
369
+ minTimeoutInMs: zod.z.number().int().optional(),
370
+ /** The maximum time to wait before retrying */
371
+ maxTimeoutInMs: zod.z.number().int().optional(),
372
+ /** Randomize the timeout between retries.
373
+ *
374
+ * This can be useful to prevent the thundering herd problem where all retries happen at the same time.
375
+ */
376
+ randomize: zod.z.boolean().optional()
377
+ });
378
+ var QueueOptions = zod.z.object({
379
+ /** You can define a shared queue and then pass the name in to your task.
380
+ *
381
+ * @example
382
+ *
383
+ * ```ts
384
+ * const myQueue = queue({
385
+ name: "my-queue",
386
+ concurrencyLimit: 1,
387
+ });
388
+
389
+ export const task1 = task({
390
+ id: "task-1",
391
+ queue: {
392
+ name: "my-queue",
393
+ },
394
+ run: async (payload: { message: string }) => {
395
+ // ...
396
+ },
397
+ });
398
+
399
+ export const task2 = task({
400
+ id: "task-2",
401
+ queue: {
402
+ name: "my-queue",
403
+ },
404
+ run: async (payload: { message: string }) => {
405
+ // ...
406
+ },
407
+ });
408
+ * ```
409
+ */
410
+ name: zod.z.string().optional(),
411
+ /** An optional property that specifies the maximum number of concurrent run executions.
412
+ *
413
+ * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
414
+ concurrencyLimit: zod.z.number().int().min(1).max(1e3).optional(),
415
+ /** @deprecated This feature is coming soon */
416
+ rateLimit: RateLimitOptions.optional()
417
+ });
418
+ var TaskMetadata = zod.z.object({
419
+ id: zod.z.string(),
420
+ exportName: zod.z.string(),
421
+ packageVersion: zod.z.string(),
422
+ queue: QueueOptions.optional(),
423
+ retry: RetryOptions.optional()
424
+ });
425
+ var TaskMetadataWithFilePath = TaskMetadata.extend({
426
+ filePath: zod.z.string()
427
+ });
428
+ var UncaughtExceptionMessage = zod.z.object({
429
+ version: zod.z.literal("v1").default("v1"),
430
+ error: zod.z.object({
431
+ name: zod.z.string(),
432
+ message: zod.z.string(),
433
+ stack: zod.z.string().optional()
434
+ }),
435
+ origin: zod.z.enum([
436
+ "uncaughtException",
437
+ "unhandledRejection"
438
+ ])
439
+ });
440
+ var childToWorkerMessages = {
441
+ TASK_RUN_COMPLETED: zod.z.object({
442
+ version: zod.z.literal("v1").default("v1"),
443
+ execution: TaskRunExecution,
444
+ result: TaskRunExecutionResult
445
+ }),
446
+ TASKS_READY: zod.z.object({
447
+ version: zod.z.literal("v1").default("v1"),
448
+ tasks: TaskMetadataWithFilePath.array()
449
+ }),
450
+ TASK_HEARTBEAT: zod.z.object({
451
+ version: zod.z.literal("v1").default("v1"),
452
+ id: zod.z.string()
453
+ }),
454
+ READY_TO_DISPOSE: zod.z.undefined(),
455
+ WAIT_FOR_DURATION: zod.z.object({
456
+ version: zod.z.literal("v1").default("v1"),
457
+ ms: zod.z.number()
458
+ }),
459
+ WAIT_FOR_TASK: zod.z.object({
460
+ version: zod.z.literal("v1").default("v1"),
461
+ id: zod.z.string()
462
+ }),
463
+ WAIT_FOR_BATCH: zod.z.object({
464
+ version: zod.z.literal("v1").default("v1"),
465
+ id: zod.z.string(),
466
+ runs: zod.z.string().array()
467
+ }),
468
+ UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
469
+ };
470
+ var ProdChildToWorkerMessages = {
471
+ TASK_RUN_COMPLETED: {
472
+ message: zod.z.object({
473
+ version: zod.z.literal("v1").default("v1"),
474
+ execution: TaskRunExecution,
475
+ result: TaskRunExecutionResult
476
+ })
477
+ },
478
+ TASKS_READY: {
479
+ message: zod.z.object({
480
+ version: zod.z.literal("v1").default("v1"),
481
+ tasks: TaskMetadataWithFilePath.array()
482
+ })
483
+ },
484
+ TASK_HEARTBEAT: {
485
+ message: zod.z.object({
486
+ version: zod.z.literal("v1").default("v1"),
487
+ id: zod.z.string()
488
+ })
489
+ },
490
+ READY_TO_DISPOSE: {
491
+ message: zod.z.undefined()
492
+ },
493
+ READY_FOR_CHECKPOINT: {
494
+ message: zod.z.object({
495
+ version: zod.z.literal("v1").default("v1")
496
+ })
497
+ },
498
+ CANCEL_CHECKPOINT: {
499
+ message: zod.z.object({
500
+ version: zod.z.literal("v1").default("v1")
501
+ })
502
+ },
503
+ WAIT_FOR_DURATION: {
504
+ message: zod.z.object({
505
+ version: zod.z.literal("v1").default("v1"),
506
+ ms: zod.z.number(),
507
+ now: zod.z.number()
508
+ }),
509
+ callback: zod.z.object({
510
+ willCheckpointAndRestore: zod.z.boolean()
511
+ })
512
+ },
513
+ WAIT_FOR_TASK: {
514
+ message: zod.z.object({
515
+ version: zod.z.literal("v1").default("v1"),
516
+ friendlyId: zod.z.string()
517
+ })
518
+ },
519
+ WAIT_FOR_BATCH: {
520
+ message: zod.z.object({
521
+ version: zod.z.literal("v1").default("v1"),
522
+ batchFriendlyId: zod.z.string(),
523
+ runFriendlyIds: zod.z.string().array()
524
+ })
525
+ },
526
+ UNCAUGHT_EXCEPTION: {
527
+ message: UncaughtExceptionMessage
528
+ }
529
+ };
530
+ var ProdWorkerToChildMessages = {
531
+ EXECUTE_TASK_RUN: {
532
+ message: zod.z.object({
533
+ version: zod.z.literal("v1").default("v1"),
534
+ execution: TaskRunExecution,
535
+ traceContext: zod.z.record(zod.z.unknown()),
536
+ metadata: BackgroundWorkerProperties
537
+ })
538
+ },
539
+ TASK_RUN_COMPLETED_NOTIFICATION: {
540
+ message: zod.z.object({
541
+ version: zod.z.literal("v1").default("v1"),
542
+ completion: TaskRunExecutionResult,
543
+ execution: TaskRunExecution
544
+ })
545
+ },
546
+ CLEANUP: {
547
+ message: zod.z.object({
548
+ version: zod.z.literal("v1").default("v1"),
549
+ flush: zod.z.boolean().default(false),
550
+ kill: zod.z.boolean().default(true)
551
+ }),
552
+ callback: zod.z.void()
553
+ },
554
+ WAIT_COMPLETED_NOTIFICATION: {
555
+ message: zod.z.object({
556
+ version: zod.z.literal("v1").default("v1")
557
+ })
558
+ }
559
+ };
560
+
561
+ // src/v3/schemas/resources.ts
562
+ var TaskResource = zod.z.object({
563
+ id: zod.z.string(),
564
+ filePath: zod.z.string(),
565
+ exportName: zod.z.string(),
566
+ queue: QueueOptions.optional(),
567
+ retry: RetryOptions.optional()
568
+ });
569
+ var BackgroundWorkerMetadata = zod.z.object({
570
+ packageVersion: zod.z.string(),
571
+ contentHash: zod.z.string(),
572
+ cliPackageVersion: zod.z.string().optional(),
573
+ tasks: zod.z.array(TaskResource)
574
+ });
575
+ var ImageDetailsMetadata = zod.z.object({
576
+ contentHash: zod.z.string(),
577
+ imageTag: zod.z.string()
578
+ });
579
+
580
+ // src/v3/schemas/api.ts
581
+ var WhoAmIResponseSchema = zod.z.object({
582
+ userId: zod.z.string(),
583
+ email: zod.z.string().email(),
584
+ dashboardUrl: zod.z.string()
585
+ });
586
+ var GetProjectResponseBody = zod.z.object({
587
+ id: zod.z.string(),
588
+ externalRef: zod.z.string(),
589
+ name: zod.z.string(),
590
+ slug: zod.z.string(),
591
+ createdAt: zod.z.coerce.date(),
592
+ organization: zod.z.object({
593
+ id: zod.z.string(),
594
+ title: zod.z.string(),
595
+ slug: zod.z.string(),
596
+ createdAt: zod.z.coerce.date()
597
+ })
598
+ });
599
+ var GetProjectsResponseBody = zod.z.array(GetProjectResponseBody);
600
+ var GetProjectEnvResponse = zod.z.object({
601
+ apiKey: zod.z.string(),
602
+ name: zod.z.string(),
603
+ apiUrl: zod.z.string()
604
+ });
605
+ var CreateBackgroundWorkerRequestBody = zod.z.object({
606
+ localOnly: zod.z.boolean(),
607
+ metadata: BackgroundWorkerMetadata
608
+ });
609
+ var CreateBackgroundWorkerResponse = zod.z.object({
610
+ id: zod.z.string(),
611
+ version: zod.z.string(),
612
+ contentHash: zod.z.string()
613
+ });
614
+ var TriggerTaskRequestBody = zod.z.object({
615
+ payload: zod.z.any(),
616
+ context: zod.z.any(),
617
+ options: zod.z.object({
618
+ dependentAttempt: zod.z.string().optional(),
619
+ dependentBatch: zod.z.string().optional(),
620
+ lockToVersion: zod.z.string().optional(),
621
+ queue: QueueOptions.optional(),
622
+ concurrencyKey: zod.z.string().optional(),
623
+ test: zod.z.boolean().optional()
624
+ }).optional()
625
+ });
626
+ var TriggerTaskResponse = zod.z.object({
627
+ id: zod.z.string()
628
+ });
629
+ var BatchTriggerTaskRequestBody = zod.z.object({
630
+ items: TriggerTaskRequestBody.array(),
631
+ dependentAttempt: zod.z.string().optional()
632
+ });
633
+ var BatchTriggerTaskResponse = zod.z.object({
634
+ batchId: zod.z.string(),
635
+ runs: zod.z.string().array()
636
+ });
637
+ var GetBatchResponseBody = zod.z.object({
638
+ id: zod.z.string(),
639
+ items: zod.z.array(zod.z.object({
640
+ id: zod.z.string(),
641
+ taskRunId: zod.z.string(),
642
+ status: zod.z.enum([
643
+ "PENDING",
644
+ "CANCELED",
645
+ "COMPLETED",
646
+ "FAILED"
647
+ ])
648
+ }))
649
+ });
650
+ var GetEnvironmentVariablesResponseBody = zod.z.object({
651
+ variables: zod.z.record(zod.z.string())
652
+ });
653
+ var StartDeploymentIndexingRequestBody = zod.z.object({
654
+ imageReference: zod.z.string()
655
+ });
656
+ var StartDeploymentIndexingResponseBody = zod.z.object({
657
+ id: zod.z.string(),
658
+ contentHash: zod.z.string()
659
+ });
660
+ var ExternalBuildData = zod.z.object({
661
+ buildId: zod.z.string(),
662
+ buildToken: zod.z.string(),
663
+ projectId: zod.z.string()
664
+ });
665
+ var InitializeDeploymentResponseBody = zod.z.object({
666
+ id: zod.z.string(),
667
+ contentHash: zod.z.string(),
668
+ shortCode: zod.z.string(),
669
+ version: zod.z.string(),
670
+ imageTag: zod.z.string(),
671
+ externalBuildData: ExternalBuildData.optional().nullable(),
672
+ registryHost: zod.z.string().optional()
673
+ });
674
+ var InitializeDeploymentRequestBody = zod.z.object({
675
+ contentHash: zod.z.string(),
676
+ userId: zod.z.string().optional()
677
+ });
678
+ var GetDeploymentResponseBody = zod.z.object({
679
+ id: zod.z.string(),
680
+ status: zod.z.enum([
681
+ "PENDING",
682
+ "BUILDING",
683
+ "DEPLOYING",
684
+ "DEPLOYED",
685
+ "FAILED",
686
+ "CANCELED",
687
+ "TIMED_OUT"
688
+ ]),
689
+ contentHash: zod.z.string(),
690
+ shortCode: zod.z.string(),
691
+ version: zod.z.string(),
692
+ imageReference: zod.z.string().optional(),
693
+ errorData: zod.z.object({
694
+ name: zod.z.string(),
695
+ message: zod.z.string(),
696
+ stack: zod.z.string().optional()
697
+ }).optional().nullable(),
698
+ worker: zod.z.object({
699
+ id: zod.z.string(),
700
+ version: zod.z.string(),
701
+ tasks: zod.z.array(zod.z.object({
702
+ id: zod.z.string(),
703
+ slug: zod.z.string(),
704
+ filePath: zod.z.string(),
705
+ exportName: zod.z.string()
706
+ }))
707
+ }).optional()
708
+ });
709
+ var CreateUploadPayloadUrlResponseBody = zod.z.object({
710
+ presignedUrl: zod.z.string()
711
+ });
712
+ var RegexSchema = zod.z.custom((val) => {
713
+ try {
714
+ return typeof val.test === "function";
715
+ } catch {
716
+ return false;
717
+ }
718
+ });
719
+ var Config = zod.z.object({
720
+ project: zod.z.string(),
721
+ triggerDirectories: zod.z.string().array().optional(),
722
+ triggerUrl: zod.z.string().optional(),
723
+ projectDir: zod.z.string().optional(),
724
+ tsconfigPath: zod.z.string().optional(),
725
+ retries: zod.z.object({
726
+ enabledInDev: zod.z.boolean().default(true),
727
+ default: RetryOptions.optional()
728
+ }).optional(),
729
+ additionalPackages: zod.z.string().array().optional(),
730
+ additionalFiles: zod.z.string().array().optional(),
731
+ dependenciesToBundle: zod.z.array(zod.z.union([
732
+ zod.z.string(),
733
+ RegexSchema
734
+ ])).optional()
735
+ });
736
+ var Machine = zod.z.object({
737
+ cpu: zod.z.string().default("1").optional(),
738
+ memory: zod.z.string().default("500Mi").optional()
739
+ });
740
+ var WaitReason = zod.z.enum([
741
+ "WAIT_FOR_DURATION",
742
+ "WAIT_FOR_TASK",
743
+ "WAIT_FOR_BATCH"
744
+ ]);
745
+ var ProviderToPlatformMessages = {
746
+ LOG: {
747
+ message: zod.z.object({
748
+ version: zod.z.literal("v1").default("v1"),
749
+ data: zod.z.string()
750
+ })
751
+ },
752
+ LOG_WITH_ACK: {
753
+ message: zod.z.object({
754
+ version: zod.z.literal("v1").default("v1"),
755
+ data: zod.z.string()
756
+ }),
757
+ callback: zod.z.object({
758
+ status: zod.z.literal("ok")
759
+ })
760
+ }
761
+ };
762
+ var PlatformToProviderMessages = {
763
+ HEALTH: {
764
+ message: zod.z.object({
765
+ version: zod.z.literal("v1").default("v1")
766
+ }),
767
+ callback: zod.z.object({
768
+ status: zod.z.literal("ok")
769
+ })
770
+ },
771
+ INDEX: {
772
+ message: zod.z.object({
773
+ version: zod.z.literal("v1").default("v1"),
774
+ imageTag: zod.z.string(),
775
+ shortCode: zod.z.string(),
776
+ envId: zod.z.string(),
777
+ apiKey: zod.z.string(),
778
+ apiUrl: zod.z.string()
779
+ }),
780
+ callback: zod.z.discriminatedUnion("success", [
781
+ zod.z.object({
782
+ success: zod.z.literal(false),
783
+ error: zod.z.object({
784
+ name: zod.z.string(),
785
+ message: zod.z.string(),
786
+ stack: zod.z.string().optional()
787
+ })
788
+ }),
789
+ zod.z.object({
790
+ success: zod.z.literal(true)
791
+ })
792
+ ])
793
+ },
794
+ INVOKE: {
795
+ message: zod.z.object({
796
+ version: zod.z.literal("v1").default("v1"),
797
+ name: zod.z.string(),
798
+ machine: Machine
799
+ })
800
+ },
801
+ RESTORE: {
802
+ message: zod.z.object({
803
+ version: zod.z.literal("v1").default("v1"),
804
+ checkpointId: zod.z.string(),
805
+ runId: zod.z.string(),
806
+ type: zod.z.enum([
807
+ "DOCKER",
808
+ "KUBERNETES"
809
+ ]),
810
+ location: zod.z.string(),
811
+ reason: zod.z.string().optional(),
812
+ imageRef: zod.z.string()
813
+ })
814
+ },
815
+ DELETE: {
816
+ message: zod.z.object({
817
+ version: zod.z.literal("v1").default("v1"),
818
+ name: zod.z.string()
819
+ }),
820
+ callback: zod.z.object({
821
+ message: zod.z.string()
822
+ })
823
+ },
824
+ GET: {
825
+ message: zod.z.object({
826
+ version: zod.z.literal("v1").default("v1"),
827
+ name: zod.z.string()
828
+ })
829
+ }
830
+ };
831
+ var CoordinatorToPlatformMessages = {
832
+ LOG: {
833
+ message: zod.z.object({
834
+ version: zod.z.literal("v1").default("v1"),
835
+ metadata: zod.z.any(),
836
+ text: zod.z.string()
837
+ })
838
+ },
839
+ CREATE_WORKER: {
840
+ message: zod.z.object({
841
+ version: zod.z.literal("v1").default("v1"),
842
+ projectRef: zod.z.string(),
843
+ envId: zod.z.string(),
844
+ deploymentId: zod.z.string(),
845
+ metadata: zod.z.object({
846
+ cliPackageVersion: zod.z.string().optional(),
847
+ contentHash: zod.z.string(),
848
+ packageVersion: zod.z.string(),
849
+ tasks: TaskResource.array()
850
+ })
851
+ }),
852
+ callback: zod.z.discriminatedUnion("success", [
853
+ zod.z.object({
854
+ success: zod.z.literal(false)
855
+ }),
856
+ zod.z.object({
857
+ success: zod.z.literal(true)
858
+ })
859
+ ])
860
+ },
861
+ READY_FOR_EXECUTION: {
862
+ message: zod.z.object({
863
+ version: zod.z.literal("v1").default("v1"),
864
+ runId: zod.z.string(),
865
+ totalCompletions: zod.z.number()
866
+ }),
867
+ callback: zod.z.discriminatedUnion("success", [
868
+ zod.z.object({
869
+ success: zod.z.literal(false)
870
+ }),
871
+ zod.z.object({
872
+ success: zod.z.literal(true),
873
+ payload: ProdTaskRunExecutionPayload
874
+ })
875
+ ])
876
+ },
877
+ READY_FOR_RESUME: {
878
+ message: zod.z.object({
879
+ version: zod.z.literal("v1").default("v1"),
880
+ attemptFriendlyId: zod.z.string(),
881
+ type: WaitReason
882
+ })
883
+ },
884
+ TASK_RUN_COMPLETED: {
885
+ message: zod.z.object({
886
+ version: zod.z.literal("v1").default("v1"),
887
+ execution: ProdTaskRunExecution,
888
+ completion: TaskRunExecutionResult,
889
+ checkpoint: zod.z.object({
890
+ docker: zod.z.boolean(),
891
+ location: zod.z.string()
892
+ }).optional()
893
+ })
894
+ },
895
+ TASK_HEARTBEAT: {
896
+ message: zod.z.object({
897
+ version: zod.z.literal("v1").default("v1"),
898
+ attemptFriendlyId: zod.z.string()
899
+ })
900
+ },
901
+ CHECKPOINT_CREATED: {
902
+ message: zod.z.object({
903
+ version: zod.z.literal("v1").default("v1"),
904
+ attemptFriendlyId: zod.z.string(),
905
+ docker: zod.z.boolean(),
906
+ location: zod.z.string(),
907
+ reason: zod.z.discriminatedUnion("type", [
908
+ zod.z.object({
909
+ type: zod.z.literal("WAIT_FOR_DURATION"),
910
+ ms: zod.z.number(),
911
+ now: zod.z.number()
912
+ }),
913
+ zod.z.object({
914
+ type: zod.z.literal("WAIT_FOR_BATCH"),
915
+ batchFriendlyId: zod.z.string(),
916
+ runFriendlyIds: zod.z.string().array()
917
+ }),
918
+ zod.z.object({
919
+ type: zod.z.literal("WAIT_FOR_TASK"),
920
+ friendlyId: zod.z.string()
921
+ }),
922
+ zod.z.object({
923
+ type: zod.z.literal("RETRYING_AFTER_FAILURE"),
924
+ attemptNumber: zod.z.number()
925
+ })
926
+ ])
927
+ })
928
+ },
929
+ INDEXING_FAILED: {
930
+ message: zod.z.object({
931
+ version: zod.z.literal("v1").default("v1"),
932
+ deploymentId: zod.z.string(),
933
+ error: zod.z.object({
934
+ name: zod.z.string(),
935
+ message: zod.z.string(),
936
+ stack: zod.z.string().optional()
937
+ })
938
+ })
939
+ }
940
+ };
941
+ var PlatformToCoordinatorMessages = {
942
+ RESUME_AFTER_DEPENDENCY: {
943
+ message: zod.z.object({
944
+ version: zod.z.literal("v1").default("v1"),
945
+ runId: zod.z.string(),
946
+ attemptId: zod.z.string(),
947
+ attemptFriendlyId: zod.z.string(),
948
+ completions: TaskRunExecutionResult.array(),
949
+ executions: TaskRunExecution.array()
950
+ })
951
+ },
952
+ RESUME_AFTER_DURATION: {
953
+ message: zod.z.object({
954
+ version: zod.z.literal("v1").default("v1"),
955
+ attemptId: zod.z.string(),
956
+ attemptFriendlyId: zod.z.string()
957
+ })
958
+ },
959
+ REQUEST_ATTEMPT_CANCELLATION: {
960
+ message: zod.z.object({
961
+ version: zod.z.literal("v1").default("v1"),
962
+ attemptId: zod.z.string(),
963
+ attemptFriendlyId: zod.z.string()
964
+ })
965
+ },
966
+ READY_FOR_RETRY: {
967
+ message: zod.z.object({
968
+ version: zod.z.literal("v1").default("v1"),
969
+ runId: zod.z.string()
970
+ })
971
+ }
972
+ };
973
+ var ClientToSharedQueueMessages = {
974
+ READY_FOR_TASKS: {
975
+ message: zod.z.object({
976
+ version: zod.z.literal("v1").default("v1"),
977
+ backgroundWorkerId: zod.z.string()
978
+ })
979
+ },
980
+ BACKGROUND_WORKER_DEPRECATED: {
981
+ message: zod.z.object({
982
+ version: zod.z.literal("v1").default("v1"),
983
+ backgroundWorkerId: zod.z.string()
984
+ })
985
+ },
986
+ BACKGROUND_WORKER_MESSAGE: {
987
+ message: zod.z.object({
988
+ version: zod.z.literal("v1").default("v1"),
989
+ backgroundWorkerId: zod.z.string(),
990
+ data: BackgroundWorkerClientMessages
991
+ })
992
+ }
993
+ };
994
+ var SharedQueueToClientMessages = {
995
+ SERVER_READY: {
996
+ message: zod.z.object({
997
+ version: zod.z.literal("v1").default("v1"),
998
+ id: zod.z.string()
999
+ })
1000
+ },
1001
+ BACKGROUND_WORKER_MESSAGE: {
1002
+ message: zod.z.object({
1003
+ version: zod.z.literal("v1").default("v1"),
1004
+ backgroundWorkerId: zod.z.string(),
1005
+ data: BackgroundWorkerServerMessages
1006
+ })
1007
+ }
1008
+ };
1009
+ var ProdWorkerToCoordinatorMessages = {
1010
+ LOG: {
1011
+ message: zod.z.object({
1012
+ version: zod.z.literal("v1").default("v1"),
1013
+ text: zod.z.string()
1014
+ }),
1015
+ callback: zod.z.void()
1016
+ },
1017
+ INDEX_TASKS: {
1018
+ message: zod.z.object({
1019
+ version: zod.z.literal("v1").default("v1"),
1020
+ deploymentId: zod.z.string(),
1021
+ tasks: TaskResource.array(),
1022
+ packageVersion: zod.z.string()
1023
+ }),
1024
+ callback: zod.z.discriminatedUnion("success", [
1025
+ zod.z.object({
1026
+ success: zod.z.literal(false)
1027
+ }),
1028
+ zod.z.object({
1029
+ success: zod.z.literal(true)
1030
+ })
1031
+ ])
1032
+ },
1033
+ READY_FOR_EXECUTION: {
1034
+ message: zod.z.object({
1035
+ version: zod.z.literal("v1").default("v1"),
1036
+ runId: zod.z.string(),
1037
+ totalCompletions: zod.z.number()
1038
+ })
1039
+ },
1040
+ READY_FOR_RESUME: {
1041
+ message: zod.z.object({
1042
+ version: zod.z.literal("v1").default("v1"),
1043
+ attemptFriendlyId: zod.z.string(),
1044
+ type: WaitReason
1045
+ })
1046
+ },
1047
+ READY_FOR_CHECKPOINT: {
1048
+ message: zod.z.object({
1049
+ version: zod.z.literal("v1").default("v1")
1050
+ })
1051
+ },
1052
+ CANCEL_CHECKPOINT: {
1053
+ message: zod.z.object({
1054
+ version: zod.z.literal("v1").default("v1")
1055
+ })
1056
+ },
1057
+ TASK_HEARTBEAT: {
1058
+ message: zod.z.object({
1059
+ version: zod.z.literal("v1").default("v1"),
1060
+ attemptFriendlyId: zod.z.string()
1061
+ })
1062
+ },
1063
+ TASK_RUN_COMPLETED: {
1064
+ message: zod.z.object({
1065
+ version: zod.z.literal("v1").default("v1"),
1066
+ execution: ProdTaskRunExecution,
1067
+ completion: TaskRunExecutionResult
1068
+ }),
1069
+ callback: zod.z.object({
1070
+ willCheckpointAndRestore: zod.z.boolean(),
1071
+ shouldExit: zod.z.boolean()
1072
+ })
1073
+ },
1074
+ WAIT_FOR_DURATION: {
1075
+ message: zod.z.object({
1076
+ version: zod.z.literal("v1").default("v1"),
1077
+ ms: zod.z.number(),
1078
+ now: zod.z.number(),
1079
+ attemptFriendlyId: zod.z.string()
1080
+ }),
1081
+ callback: zod.z.object({
1082
+ willCheckpointAndRestore: zod.z.boolean()
1083
+ })
1084
+ },
1085
+ WAIT_FOR_TASK: {
1086
+ message: zod.z.object({
1087
+ version: zod.z.literal("v1").default("v1"),
1088
+ friendlyId: zod.z.string(),
1089
+ // This is the attempt that is waiting
1090
+ attemptFriendlyId: zod.z.string()
1091
+ }),
1092
+ callback: zod.z.object({
1093
+ willCheckpointAndRestore: zod.z.boolean()
1094
+ })
1095
+ },
1096
+ WAIT_FOR_BATCH: {
1097
+ message: zod.z.object({
1098
+ version: zod.z.literal("v1").default("v1"),
1099
+ batchFriendlyId: zod.z.string(),
1100
+ runFriendlyIds: zod.z.string().array(),
1101
+ // This is the attempt that is waiting
1102
+ attemptFriendlyId: zod.z.string()
1103
+ }),
1104
+ callback: zod.z.object({
1105
+ willCheckpointAndRestore: zod.z.boolean()
1106
+ })
1107
+ },
1108
+ INDEXING_FAILED: {
1109
+ message: zod.z.object({
1110
+ version: zod.z.literal("v1").default("v1"),
1111
+ deploymentId: zod.z.string(),
1112
+ error: zod.z.object({
1113
+ name: zod.z.string(),
1114
+ message: zod.z.string(),
1115
+ stack: zod.z.string().optional()
1116
+ })
1117
+ })
1118
+ }
1119
+ };
1120
+ var CoordinatorToProdWorkerMessages = {
1121
+ RESUME_AFTER_DEPENDENCY: {
1122
+ message: zod.z.object({
1123
+ version: zod.z.literal("v1").default("v1"),
1124
+ attemptId: zod.z.string(),
1125
+ completions: TaskRunExecutionResult.array(),
1126
+ executions: TaskRunExecution.array()
1127
+ })
1128
+ },
1129
+ RESUME_AFTER_DURATION: {
1130
+ message: zod.z.object({
1131
+ version: zod.z.literal("v1").default("v1"),
1132
+ attemptId: zod.z.string()
1133
+ })
1134
+ },
1135
+ EXECUTE_TASK_RUN: {
1136
+ message: zod.z.object({
1137
+ version: zod.z.literal("v1").default("v1"),
1138
+ executionPayload: ProdTaskRunExecutionPayload
1139
+ })
1140
+ },
1141
+ REQUEST_ATTEMPT_CANCELLATION: {
1142
+ message: zod.z.object({
1143
+ version: zod.z.literal("v1").default("v1"),
1144
+ attemptId: zod.z.string()
1145
+ })
1146
+ },
1147
+ REQUEST_EXIT: {
1148
+ message: zod.z.object({
1149
+ version: zod.z.literal("v1").default("v1")
1150
+ })
1151
+ },
1152
+ READY_FOR_RETRY: {
1153
+ message: zod.z.object({
1154
+ version: zod.z.literal("v1").default("v1"),
1155
+ runId: zod.z.string()
1156
+ })
1157
+ }
1158
+ };
1159
+ var ProdWorkerSocketData = zod.z.object({
1160
+ contentHash: zod.z.string(),
1161
+ projectRef: zod.z.string(),
1162
+ envId: zod.z.string(),
1163
+ runId: zod.z.string(),
1164
+ attemptFriendlyId: zod.z.string().optional(),
1165
+ podName: zod.z.string(),
1166
+ deploymentId: zod.z.string(),
1167
+ deploymentVersion: zod.z.string()
1168
+ });
1169
+ var PRIMARY_VARIANT = "primary";
1170
+ var Variant = zod.z.enum([
1171
+ PRIMARY_VARIANT
1172
+ ]);
1173
+ var AccessoryItem = zod.z.object({
1174
+ text: zod.z.string(),
1175
+ variant: zod.z.string().optional(),
1176
+ url: zod.z.string().optional()
1177
+ });
1178
+ var Accessory = zod.z.object({
1179
+ items: zod.z.array(AccessoryItem),
1180
+ style: zod.z.enum([
1181
+ "codepath"
1182
+ ]).optional()
1183
+ });
1184
+ var TaskEventStyle = zod.z.object({
1185
+ icon: zod.z.string().optional(),
1186
+ variant: Variant.optional(),
1187
+ accessory: Accessory.optional()
1188
+ }).default({
1189
+ icon: void 0,
1190
+ variant: void 0
1191
+ });
1192
+ var stringPatternMatchers = [
1193
+ zod.z.object({
1194
+ $endsWith: zod.z.string()
1195
+ }),
1196
+ zod.z.object({
1197
+ $startsWith: zod.z.string()
1198
+ }),
1199
+ zod.z.object({
1200
+ $ignoreCaseEquals: zod.z.string()
1201
+ })
1202
+ ];
1203
+ var EventMatcher = zod.z.union([
1204
+ /** Match against a string */
1205
+ zod.z.array(zod.z.string()),
1206
+ /** Match against a number */
1207
+ zod.z.array(zod.z.number()),
1208
+ /** Match against a boolean */
1209
+ zod.z.array(zod.z.boolean()),
1210
+ zod.z.array(zod.z.union([
1211
+ ...stringPatternMatchers,
1212
+ zod.z.object({
1213
+ $exists: zod.z.boolean()
1214
+ }),
1215
+ zod.z.object({
1216
+ $isNull: zod.z.boolean()
1217
+ }),
1218
+ zod.z.object({
1219
+ $anythingBut: zod.z.union([
1220
+ zod.z.string(),
1221
+ zod.z.number(),
1222
+ zod.z.boolean()
1223
+ ])
1224
+ }),
1225
+ zod.z.object({
1226
+ $anythingBut: zod.z.union([
1227
+ zod.z.array(zod.z.string()),
1228
+ zod.z.array(zod.z.number()),
1229
+ zod.z.array(zod.z.boolean())
1230
+ ])
1231
+ }),
1232
+ zod.z.object({
1233
+ $gt: zod.z.number()
1234
+ }),
1235
+ zod.z.object({
1236
+ $lt: zod.z.number()
1237
+ }),
1238
+ zod.z.object({
1239
+ $gte: zod.z.number()
1240
+ }),
1241
+ zod.z.object({
1242
+ $lte: zod.z.number()
1243
+ }),
1244
+ zod.z.object({
1245
+ $between: zod.z.tuple([
1246
+ zod.z.number(),
1247
+ zod.z.number()
1248
+ ])
1249
+ }),
1250
+ zod.z.object({
1251
+ $includes: zod.z.union([
1252
+ zod.z.string(),
1253
+ zod.z.number(),
1254
+ zod.z.boolean()
1255
+ ])
1256
+ }),
1257
+ zod.z.object({
1258
+ $not: zod.z.union([
1259
+ zod.z.string(),
1260
+ zod.z.number(),
1261
+ zod.z.boolean()
1262
+ ])
1263
+ })
1264
+ ]))
1265
+ ]);
1266
+ var EventFilter = zod.z.lazy(() => zod.z.record(zod.z.union([
1267
+ EventMatcher,
1268
+ EventFilter
1269
+ ])));
1270
+
1271
+ // src/v3/schemas/fetch.ts
1272
+ var FetchRetryHeadersStrategy = zod.z.object({
1273
+ /** The `headers` strategy retries the request using info from the response headers. */
1274
+ strategy: zod.z.literal("headers"),
1275
+ /** The header to use to determine the maximum number of times to retry the request. */
1276
+ limitHeader: zod.z.string(),
1277
+ /** The header to use to determine the number of remaining retries. */
1278
+ remainingHeader: zod.z.string(),
1279
+ /** The header to use to determine the time when the number of remaining retries will be reset. */
1280
+ resetHeader: zod.z.string(),
1281
+ /** The event filter to use to determine if the request should be retried. */
1282
+ bodyFilter: EventFilter.optional(),
1283
+ /** The format of the `resetHeader` value. */
1284
+ resetFormat: zod.z.enum([
1285
+ "unix_timestamp",
1286
+ "unix_timestamp_in_ms",
1287
+ "iso_8601",
1288
+ "iso_8601_duration_openai_variant"
1289
+ ]).default("unix_timestamp").optional()
1290
+ });
1291
+ var FetchRetryBackoffStrategy = RetryOptions.extend({
1292
+ /** The `backoff` strategy retries the request with an exponential backoff. */
1293
+ strategy: zod.z.literal("backoff"),
1294
+ /** The event filter to use to determine if the request should be retried. */
1295
+ bodyFilter: EventFilter.optional()
1296
+ });
1297
+ var FetchRetryStrategy = zod.z.discriminatedUnion("strategy", [
1298
+ FetchRetryHeadersStrategy,
1299
+ FetchRetryBackoffStrategy
1300
+ ]);
1301
+ var FetchRetryByStatusOptions = zod.z.record(zod.z.string(), FetchRetryStrategy);
1302
+ var FetchTimeoutOptions = zod.z.object({
1303
+ /** The maximum time to wait for the request to complete. */
1304
+ durationInMs: zod.z.number().optional(),
1305
+ retry: RetryOptions.optional()
1306
+ });
1307
+ var FetchRetryOptions = zod.z.object({
1308
+ /** The retrying strategy for specific status codes. */
1309
+ byStatus: FetchRetryByStatusOptions.optional(),
1310
+ /** The timeout options for the request. */
1311
+ timeout: RetryOptions.optional(),
1312
+ /**
1313
+ * The retrying strategy for connection errors.
1314
+ */
1315
+ connectionError: RetryOptions.optional()
1316
+ });
1317
+ var ExceptionEventProperties = zod.z.object({
1318
+ type: zod.z.string().optional(),
1319
+ message: zod.z.string().optional(),
1320
+ stacktrace: zod.z.string().optional()
1321
+ });
1322
+ var ExceptionSpanEvent = zod.z.object({
1323
+ name: zod.z.literal("exception"),
1324
+ time: zod.z.coerce.date(),
1325
+ properties: zod.z.object({
1326
+ exception: ExceptionEventProperties
1327
+ })
1328
+ });
1329
+ var CancellationSpanEvent = zod.z.object({
1330
+ name: zod.z.literal("cancellation"),
1331
+ time: zod.z.coerce.date(),
1332
+ properties: zod.z.object({
1333
+ reason: zod.z.string()
1334
+ })
1335
+ });
1336
+ var OtherSpanEvent = zod.z.object({
1337
+ name: zod.z.string(),
1338
+ time: zod.z.coerce.date(),
1339
+ properties: zod.z.record(zod.z.unknown())
1340
+ });
1341
+ var SpanEvent = zod.z.union([
1342
+ ExceptionSpanEvent,
1343
+ CancellationSpanEvent,
1344
+ OtherSpanEvent
1345
+ ]);
1346
+ var SpanEvents = zod.z.array(SpanEvent);
1347
+ function isExceptionSpanEvent(event) {
1348
+ return event.name === "exception";
1349
+ }
1350
+ __name(isExceptionSpanEvent, "isExceptionSpanEvent");
1351
+ function isCancellationSpanEvent(event) {
1352
+ return event.name === "cancellation";
1353
+ }
1354
+ __name(isCancellationSpanEvent, "isCancellationSpanEvent");
1355
+ var SpanMessagingEvent = zod.z.object({
1356
+ system: zod.z.string().optional(),
1357
+ client_id: zod.z.string().optional(),
1358
+ operation: zod.z.enum([
1359
+ "publish",
1360
+ "create",
1361
+ "receive",
1362
+ "deliver"
1363
+ ]),
1364
+ message: zod.z.any(),
1365
+ destination: zod.z.string().optional()
1366
+ });
1367
+
1368
+ // src/zodfetch.ts
1369
+ async function zodfetch(schema, url, requestInit) {
1370
+ try {
1371
+ const response = await fetch(url, requestInit);
1372
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
1373
+ return {
1374
+ ok: false,
1375
+ error: `404: ${response.statusText}`
1376
+ };
1377
+ }
1378
+ if (response.status >= 400 && response.status < 500) {
1379
+ const body = await response.json();
1380
+ if (!body.error) {
1381
+ return {
1382
+ ok: false,
1383
+ error: "Something went wrong"
1384
+ };
1385
+ }
1386
+ return {
1387
+ ok: false,
1388
+ error: body.error
1389
+ };
1390
+ }
1391
+ if (response.status !== 200) {
1392
+ return {
1393
+ ok: false,
1394
+ error: `Failed to fetch ${url}, got status code ${response.status}`
1395
+ };
1396
+ }
1397
+ const jsonBody = await response.json();
1398
+ const parsedResult = schema.safeParse(jsonBody);
1399
+ if (parsedResult.success) {
1400
+ return {
1401
+ ok: true,
1402
+ data: parsedResult.data
1403
+ };
1404
+ }
1405
+ if ("error" in jsonBody) {
1406
+ return {
1407
+ ok: false,
1408
+ error: typeof jsonBody.error === "string" ? jsonBody.error : JSON.stringify(jsonBody.error)
1409
+ };
1410
+ }
1411
+ return {
1412
+ ok: false,
1413
+ error: parsedResult.error.message
1414
+ };
1415
+ } catch (error) {
1416
+ return {
1417
+ ok: false,
1418
+ error: error instanceof Error ? error.message : JSON.stringify(error)
1419
+ };
1420
+ }
1421
+ }
1422
+ __name(zodfetch, "zodfetch");
1423
+
1424
+ // src/v3/utils/flattenAttributes.ts
1425
+ function flattenAttributes(obj, prefix) {
1426
+ const result = {};
1427
+ if (!obj) {
1428
+ return result;
1429
+ }
1430
+ if (typeof obj === "string") {
1431
+ result[prefix || ""] = obj;
1432
+ return result;
1433
+ }
1434
+ if (typeof obj === "number") {
1435
+ result[prefix || ""] = obj;
1436
+ return result;
1437
+ }
1438
+ if (typeof obj === "boolean") {
1439
+ result[prefix || ""] = obj;
1440
+ return result;
1441
+ }
1442
+ for (const [key, value] of Object.entries(obj)) {
1443
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
1444
+ if (Array.isArray(value)) {
1445
+ for (let i = 0; i < value.length; i++) {
1446
+ if (typeof value[i] === "object" && value[i] !== null) {
1447
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
1448
+ } else {
1449
+ result[`${newPrefix}.[${i}]`] = value[i];
1450
+ }
1451
+ }
1452
+ } else if (isRecord(value)) {
1453
+ Object.assign(result, flattenAttributes(value, newPrefix));
1454
+ } else {
1455
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
1456
+ result[newPrefix] = value;
1457
+ }
1458
+ }
1459
+ }
1460
+ return result;
1461
+ }
1462
+ __name(flattenAttributes, "flattenAttributes");
1463
+ function isRecord(value) {
1464
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1465
+ }
1466
+ __name(isRecord, "isRecord");
1467
+ function unflattenAttributes(obj) {
1468
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
1469
+ return obj;
1470
+ }
1471
+ const result = {};
1472
+ for (const [key, value] of Object.entries(obj)) {
1473
+ const parts = key.split(".").reduce((acc, part) => {
1474
+ if (detectIsArrayIndex(part)) {
1475
+ acc.push(part);
1476
+ } else {
1477
+ acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
1478
+ }
1479
+ return acc;
1480
+ }, []);
1481
+ let current = result;
1482
+ for (let i = 0; i < parts.length - 1; i++) {
1483
+ const part = parts[i];
1484
+ const isArray = detectIsArrayIndex(part);
1485
+ const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
1486
+ const nextIsArray = detectIsArrayIndex(parts[i + 1]);
1487
+ if (!current[cleanPart]) {
1488
+ current[cleanPart] = nextIsArray ? [] : {};
1489
+ }
1490
+ current = current[cleanPart];
1491
+ }
1492
+ const lastPart = parts[parts.length - 1];
1493
+ const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
1494
+ current[cleanLastPart] = value;
1495
+ }
1496
+ return result;
1497
+ }
1498
+ __name(unflattenAttributes, "unflattenAttributes");
1499
+ function detectIsArrayIndex(key) {
1500
+ const match = key.match(/^\[(\d+)\]$/);
1501
+ if (match) {
1502
+ return true;
1503
+ }
1504
+ return false;
1505
+ }
1506
+ __name(detectIsArrayIndex, "detectIsArrayIndex");
1507
+ function primitiveValueOrflattenedAttributes(obj, prefix) {
1508
+ if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
1509
+ return obj;
1510
+ }
1511
+ const attributes = flattenAttributes(obj, prefix);
1512
+ if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
1513
+ return attributes[prefix];
1514
+ }
1515
+ return attributes;
1516
+ }
1517
+ __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
1518
+ var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
1519
+ constructor() {
1520
+ this.storage = new async_hooks.AsyncLocalStorage();
1521
+ }
1522
+ runWith(context3, fn) {
1523
+ return this.storage.run(context3, fn);
1524
+ }
1525
+ getStore() {
1526
+ return this.storage.getStore();
1527
+ }
1528
+ };
1529
+ __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
1530
+ var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
1531
+
1532
+ // src/v3/semanticInternalAttributes.ts
1533
+ var SemanticInternalAttributes = {
1534
+ ENVIRONMENT_ID: "ctx.environment.id",
1535
+ ENVIRONMENT_TYPE: "ctx.environment.type",
1536
+ ORGANIZATION_ID: "ctx.organization.id",
1537
+ ORGANIZATION_SLUG: "ctx.organization.slug",
1538
+ ORGANIZATION_NAME: "ctx.organization.name",
1539
+ PROJECT_ID: "ctx.project.id",
1540
+ PROJECT_REF: "ctx.project.ref",
1541
+ PROJECT_NAME: "ctx.project.title",
1542
+ PROJECT_DIR: "project.dir",
1543
+ ATTEMPT_ID: "ctx.attempt.id",
1544
+ ATTEMPT_NUMBER: "ctx.attempt.number",
1545
+ RUN_ID: "ctx.run.id",
1546
+ RUN_IS_TEST: "ctx.run.isTest",
1547
+ BATCH_ID: "ctx.batch.id",
1548
+ TASK_SLUG: "ctx.task.id",
1549
+ TASK_PATH: "ctx.task.filePath",
1550
+ TASK_EXPORT_NAME: "ctx.task.exportName",
1551
+ QUEUE_NAME: "ctx.queue.name",
1552
+ QUEUE_ID: "ctx.queue.id",
1553
+ SPAN_PARTIAL: "$span.partial",
1554
+ SPAN_ID: "$span.span_id",
1555
+ OUTPUT: "$output",
1556
+ OUTPUT_TYPE: "$mime_type_output",
1557
+ STYLE: "$style",
1558
+ STYLE_ICON: "$style.icon",
1559
+ STYLE_VARIANT: "$style.variant",
1560
+ STYLE_ACCESSORY: "$style.accessory",
1561
+ METADATA: "$metadata",
1562
+ TRIGGER: "$trigger",
1563
+ PAYLOAD: "$payload",
1564
+ PAYLOAD_TYPE: "$mime_type_payload",
1565
+ SHOW: "$show",
1566
+ SHOW_ACTIONS: "$show.actions",
1567
+ WORKER_ID: "worker.id",
1568
+ WORKER_VERSION: "worker.version",
1569
+ CLI_VERSION: "cli.version",
1570
+ SDK_VERSION: "sdk.version",
1571
+ SDK_LANGUAGE: "sdk.language",
1572
+ RETRY_AT: "retry.at",
1573
+ RETRY_DELAY: "retry.delay",
1574
+ RETRY_COUNT: "retry.count"
1575
+ };
1576
+
1577
+ // src/v3/tasks/taskContextManager.ts
1578
+ var _getStore, getStore_fn;
1579
+ var _TaskContextManager = class _TaskContextManager {
1580
+ constructor() {
1581
+ __privateAdd(this, _getStore);
1582
+ __publicField(this, "_storage", new SafeAsyncLocalStorage());
1583
+ }
1584
+ get isInsideTask() {
1585
+ return __privateMethod(this, _getStore, getStore_fn).call(this) !== void 0;
1586
+ }
1587
+ get ctx() {
1588
+ const store = __privateMethod(this, _getStore, getStore_fn).call(this);
1589
+ return store?.ctx;
1590
+ }
1591
+ get worker() {
1592
+ const store = __privateMethod(this, _getStore, getStore_fn).call(this);
1593
+ return store?.worker;
1594
+ }
1595
+ get attributes() {
1596
+ if (this.ctx) {
1597
+ return {
1598
+ ...this.contextAttributes,
1599
+ ...this.workerAttributes
1600
+ };
1601
+ }
1602
+ return {};
1603
+ }
1604
+ get workerAttributes() {
1605
+ if (this.worker) {
1606
+ return {
1607
+ [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
1608
+ [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
1609
+ };
1610
+ }
1611
+ return {};
1612
+ }
1613
+ get contextAttributes() {
1614
+ if (this.ctx) {
1615
+ return {
1616
+ [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
1617
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
1618
+ [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
1619
+ [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
1620
+ [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
1621
+ [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
1622
+ [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
1623
+ [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
1624
+ [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
1625
+ [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
1626
+ [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
1627
+ [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
1628
+ [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
1629
+ [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
1630
+ [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
1631
+ [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
1632
+ [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
1633
+ [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id
1634
+ };
1635
+ }
1636
+ return {};
1637
+ }
1638
+ runWith(context3, fn) {
1639
+ return this._storage.runWith(context3, fn);
1640
+ }
1641
+ };
1642
+ _getStore = new WeakSet();
1643
+ getStore_fn = /* @__PURE__ */ __name(function() {
1644
+ return this._storage.getStore();
1645
+ }, "#getStore");
1646
+ __name(_TaskContextManager, "TaskContextManager");
1647
+ var TaskContextManager = _TaskContextManager;
1648
+ var taskContextManager = new TaskContextManager();
1649
+ var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
1650
+ constructor(innerProcessor) {
1651
+ this._innerProcessor = innerProcessor;
1652
+ }
1653
+ // Called when a span starts
1654
+ onStart(span, parentContext) {
1655
+ if (taskContextManager.ctx) {
1656
+ span.setAttributes(flattenAttributes({
1657
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
1658
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
1659
+ }, SemanticInternalAttributes.METADATA));
1660
+ }
1661
+ this._innerProcessor.onStart(span, parentContext);
1662
+ }
1663
+ // Delegate the rest of the methods to the wrapped processor
1664
+ onEnd(span) {
1665
+ this._innerProcessor.onEnd(span);
1666
+ }
1667
+ shutdown() {
1668
+ return this._innerProcessor.shutdown();
1669
+ }
1670
+ forceFlush() {
1671
+ return this._innerProcessor.forceFlush();
1672
+ }
1673
+ };
1674
+ __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
1675
+ var TaskContextSpanProcessor = _TaskContextSpanProcessor;
1676
+ var _TaskContextLogProcessor = class _TaskContextLogProcessor {
1677
+ constructor(innerProcessor) {
1678
+ this._innerProcessor = innerProcessor;
1679
+ }
1680
+ forceFlush() {
1681
+ return this._innerProcessor.forceFlush();
1682
+ }
1683
+ onEmit(logRecord, context3) {
1684
+ if (taskContextManager.ctx) {
1685
+ logRecord.setAttributes(flattenAttributes({
1686
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
1687
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
1688
+ }, SemanticInternalAttributes.METADATA));
1689
+ }
1690
+ this._innerProcessor.onEmit(logRecord, context3);
1691
+ }
1692
+ shutdown() {
1693
+ return this._innerProcessor.shutdown();
1694
+ }
1695
+ };
1696
+ __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
1697
+ var TaskContextLogProcessor = _TaskContextLogProcessor;
1698
+
1699
+ // src/v3/utils/getEnv.ts
1700
+ function getEnvVar(name) {
1701
+ if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
1702
+ return process.env[name];
1703
+ }
1704
+ }
1705
+ __name(getEnvVar, "getEnvVar");
1706
+
1707
+ // src/v3/apiClient/index.ts
1708
+ var _getHeaders, getHeaders_fn;
1709
+ var _ApiClient = class _ApiClient {
1710
+ constructor(baseUrl, accessToken) {
1711
+ __privateAdd(this, _getHeaders);
1712
+ this.accessToken = accessToken;
1713
+ this.baseUrl = baseUrl.replace(/\/$/, "");
1714
+ }
1715
+ triggerTask(taskId, body, options) {
1716
+ return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
1717
+ method: "POST",
1718
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1719
+ body: JSON.stringify(body)
1720
+ });
1721
+ }
1722
+ batchTriggerTask(taskId, body, options) {
1723
+ return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
1724
+ method: "POST",
1725
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1726
+ body: JSON.stringify(body)
1727
+ });
1728
+ }
1729
+ createUploadPayloadUrl(filename) {
1730
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1731
+ method: "PUT",
1732
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1733
+ });
1734
+ }
1735
+ getPayloadUrl(filename) {
1736
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1737
+ method: "GET",
1738
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1739
+ });
1740
+ }
1741
+ };
1742
+ _getHeaders = new WeakSet();
1743
+ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
1744
+ const headers = {
1745
+ "Content-Type": "application/json",
1746
+ Authorization: `Bearer ${this.accessToken}`
1747
+ };
1748
+ if (taskContextManager.isInsideTask) {
1749
+ api.propagation.inject(api.context.active(), headers);
1750
+ if (spanParentAsLink) {
1751
+ headers["x-trigger-span-parent-as-link"] = "1";
1752
+ }
1753
+ }
1754
+ return headers;
1755
+ }, "#getHeaders");
1756
+ __name(_ApiClient, "ApiClient");
1757
+ var ApiClient = _ApiClient;
1758
+ var _getStore2, getStore_fn2;
1759
+ var _ApiClientManager = class _ApiClientManager {
1760
+ constructor() {
1761
+ __privateAdd(this, _getStore2);
1762
+ __publicField(this, "_storage", new SafeAsyncLocalStorage());
1763
+ }
1764
+ get baseURL() {
1765
+ const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
1766
+ return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
1767
+ }
1768
+ get accessToken() {
1769
+ const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
1770
+ return store?.accessToken ?? getEnvVar("TRIGGER_SECRET_KEY");
1771
+ }
1772
+ get client() {
1773
+ if (!this.baseURL || !this.accessToken) {
1774
+ return void 0;
1775
+ }
1776
+ return new ApiClient(this.baseURL, this.accessToken);
1777
+ }
1778
+ runWith(context3, fn) {
1779
+ return this._storage.runWith(context3, fn);
1780
+ }
1781
+ };
1782
+ _getStore2 = new WeakSet();
1783
+ getStore_fn2 = /* @__PURE__ */ __name(function() {
1784
+ return this._storage.getStore();
1785
+ }, "#getStore");
1786
+ __name(_ApiClientManager, "ApiClientManager");
1787
+ var ApiClientManager = _ApiClientManager;
1788
+ var apiClientManager = new ApiClientManager();
1789
+ var ZodMessageSchema = zod.z.object({
1790
+ version: zod.z.literal("v1").default("v1"),
1791
+ type: zod.z.string(),
1792
+ payload: zod.z.unknown()
1793
+ });
1794
+ var _schema, _handlers;
1795
+ var _ZodMessageHandler = class _ZodMessageHandler {
1796
+ constructor(options) {
1797
+ __privateAdd(this, _schema, void 0);
1798
+ __privateAdd(this, _handlers, void 0);
1799
+ __privateSet(this, _schema, options.schema);
1800
+ __privateSet(this, _handlers, options.messages);
1801
+ }
1802
+ async handleMessage(message) {
1803
+ const parsedMessage = this.parseMessage(message);
1804
+ if (!__privateGet(this, _handlers)) {
1805
+ throw new Error("No handlers provided");
1806
+ }
1807
+ const handler = __privateGet(this, _handlers)[parsedMessage.type];
1808
+ if (!handler) {
1809
+ console.error(`No handler for message type: ${String(parsedMessage.type)}`);
1810
+ return;
1811
+ }
1812
+ const ack = await handler(parsedMessage.payload);
1813
+ return ack;
1814
+ }
1815
+ parseMessage(message) {
1816
+ const parsedMessage = ZodMessageSchema.safeParse(message);
1817
+ if (!parsedMessage.success) {
1818
+ throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
1819
+ }
1820
+ const schema = __privateGet(this, _schema)[parsedMessage.data.type];
1821
+ if (!schema) {
1822
+ throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
1823
+ }
1824
+ const parsedPayload = schema.safeParse(parsedMessage.data.payload);
1825
+ if (!parsedPayload.success) {
1826
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
1827
+ }
1828
+ return {
1829
+ type: parsedMessage.data.type,
1830
+ payload: parsedPayload.data
1831
+ };
1832
+ }
1833
+ registerHandlers(emitter, logger2) {
1834
+ const log = logger2 ?? console;
1835
+ if (!__privateGet(this, _handlers)) {
1836
+ log.info("No handlers provided");
1837
+ return;
1838
+ }
1839
+ for (const eventName of Object.keys(__privateGet(this, _schema))) {
1840
+ emitter.on(eventName, async (message, callback) => {
1841
+ log.info(`handling ${eventName}`, {
1842
+ payload: message,
1843
+ hasCallback: !!callback
1844
+ });
1845
+ let ack;
1846
+ if ("payload" in message) {
1847
+ ack = await this.handleMessage({
1848
+ type: eventName,
1849
+ ...message
1850
+ });
1851
+ } else {
1852
+ const { version, ...payload } = message;
1853
+ ack = await this.handleMessage({
1854
+ type: eventName,
1855
+ version,
1856
+ payload
1857
+ });
1858
+ }
1859
+ if (callback && typeof callback === "function") {
1860
+ callback(ack);
1861
+ }
1862
+ });
1863
+ }
1864
+ }
1865
+ };
1866
+ _schema = new WeakMap();
1867
+ _handlers = new WeakMap();
1868
+ __name(_ZodMessageHandler, "ZodMessageHandler");
1869
+ var ZodMessageHandler = _ZodMessageHandler;
1870
+ var _schema2, _sender;
1871
+ var _ZodMessageSender = class _ZodMessageSender {
1872
+ constructor(options) {
1873
+ __privateAdd(this, _schema2, void 0);
1874
+ __privateAdd(this, _sender, void 0);
1875
+ __privateSet(this, _schema2, options.schema);
1876
+ __privateSet(this, _sender, options.sender);
1877
+ }
1878
+ async send(type, payload) {
1879
+ const schema = __privateGet(this, _schema2)[type];
1880
+ if (!schema) {
1881
+ throw new Error(`Unknown message type: ${type}`);
1882
+ }
1883
+ const parsedPayload = schema.safeParse(payload);
1884
+ if (!parsedPayload.success) {
1885
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
1886
+ }
1887
+ await __privateGet(this, _sender).call(this, {
1888
+ type,
1889
+ payload,
1890
+ version: "v1"
1891
+ });
1892
+ }
1893
+ async forwardMessage(message) {
1894
+ const parsedMessage = ZodMessageSchema.safeParse(message);
1895
+ if (!parsedMessage.success) {
1896
+ throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
1897
+ }
1898
+ const schema = __privateGet(this, _schema2)[parsedMessage.data.type];
1899
+ if (!schema) {
1900
+ throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
1901
+ }
1902
+ const parsedPayload = schema.safeParse(parsedMessage.data.payload);
1903
+ if (!parsedPayload.success) {
1904
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
1905
+ }
1906
+ await __privateGet(this, _sender).call(this, {
1907
+ type: parsedMessage.data.type,
1908
+ payload: parsedPayload.data,
1909
+ version: "v1"
1910
+ });
1911
+ }
1912
+ };
1913
+ _schema2 = new WeakMap();
1914
+ _sender = new WeakMap();
1915
+ __name(_ZodMessageSender, "ZodMessageSender");
1916
+ var ZodMessageSender = _ZodMessageSender;
1917
+ var messageSchema = zod.z.object({
1918
+ version: zod.z.literal("v1").default("v1"),
1919
+ type: zod.z.string(),
1920
+ payload: zod.z.unknown()
1921
+ });
1922
+ var _schema3, _handlers2;
1923
+ var _ZodSocketMessageHandler = class _ZodSocketMessageHandler {
1924
+ constructor(options) {
1925
+ __privateAdd(this, _schema3, void 0);
1926
+ __privateAdd(this, _handlers2, void 0);
1927
+ __privateSet(this, _schema3, options.schema);
1928
+ __privateSet(this, _handlers2, options.handlers);
1929
+ }
1930
+ async handleMessage(message) {
1931
+ const parsedMessage = this.parseMessage(message);
1932
+ if (!__privateGet(this, _handlers2)) {
1933
+ throw new Error("No handlers provided");
1934
+ }
1935
+ const handler = __privateGet(this, _handlers2)[parsedMessage.type];
1936
+ if (!handler) {
1937
+ console.error(`No handler for message type: ${String(parsedMessage.type)}`);
1938
+ return;
1939
+ }
1940
+ const ack = await handler(parsedMessage.payload);
1941
+ return ack;
1942
+ }
1943
+ parseMessage(message) {
1944
+ const parsedMessage = messageSchema.safeParse(message);
1945
+ if (!parsedMessage.success) {
1946
+ throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
1947
+ }
1948
+ const schema = __privateGet(this, _schema3)[parsedMessage.data.type]["message"];
1949
+ if (!schema) {
1950
+ throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
1951
+ }
1952
+ const parsedPayload = schema.safeParse(parsedMessage.data.payload);
1953
+ if (!parsedPayload.success) {
1954
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
1955
+ }
1956
+ return {
1957
+ type: parsedMessage.data.type,
1958
+ payload: parsedPayload.data
1959
+ };
1960
+ }
1961
+ registerHandlers(emitter, logger2) {
1962
+ const log = logger2 ?? console;
1963
+ if (!__privateGet(this, _handlers2)) {
1964
+ log.info("No handlers provided");
1965
+ return;
1966
+ }
1967
+ for (const eventName of Object.keys(__privateGet(this, _handlers2))) {
1968
+ emitter.on(eventName, async (message, callback) => {
1969
+ log.info(`handling ${eventName}`, {
1970
+ payload: message,
1971
+ hasCallback: !!callback
1972
+ });
1973
+ let ack;
1974
+ try {
1975
+ if ("payload" in message) {
1976
+ ack = await this.handleMessage({
1977
+ type: eventName,
1978
+ ...message
1979
+ });
1980
+ } else {
1981
+ const { version, ...payload } = message;
1982
+ ack = await this.handleMessage({
1983
+ type: eventName,
1984
+ version,
1985
+ payload
1986
+ });
1987
+ }
1988
+ } catch (error) {
1989
+ log.error("Error while handling message", {
1990
+ error
1991
+ });
1992
+ return;
1993
+ }
1994
+ if (callback && typeof callback === "function") {
1995
+ callback(ack);
1996
+ }
1997
+ });
1998
+ }
1999
+ }
2000
+ };
2001
+ _schema3 = new WeakMap();
2002
+ _handlers2 = new WeakMap();
2003
+ __name(_ZodSocketMessageHandler, "ZodSocketMessageHandler");
2004
+ var ZodSocketMessageHandler = _ZodSocketMessageHandler;
2005
+ var _schema4, _socket;
2006
+ var _ZodSocketMessageSender = class _ZodSocketMessageSender {
2007
+ constructor(options) {
2008
+ __privateAdd(this, _schema4, void 0);
2009
+ __privateAdd(this, _socket, void 0);
2010
+ __privateSet(this, _schema4, options.schema);
2011
+ __privateSet(this, _socket, options.socket);
2012
+ }
2013
+ send(type, payload) {
2014
+ const schema = __privateGet(this, _schema4)[type]["message"];
2015
+ if (!schema) {
2016
+ throw new Error(`Unknown message type: ${type}`);
2017
+ }
2018
+ const parsedPayload = schema.safeParse(payload);
2019
+ if (!parsedPayload.success) {
2020
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2021
+ }
2022
+ __privateGet(this, _socket).emit(type, {
2023
+ payload,
2024
+ version: "v1"
2025
+ });
2026
+ return;
2027
+ }
2028
+ async sendWithAck(type, payload) {
2029
+ const schema = __privateGet(this, _schema4)[type]["message"];
2030
+ if (!schema) {
2031
+ throw new Error(`Unknown message type: ${type}`);
2032
+ }
2033
+ const parsedPayload = schema.safeParse(payload);
2034
+ if (!parsedPayload.success) {
2035
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2036
+ }
2037
+ const callbackResult = await __privateGet(this, _socket).emitWithAck(type, {
2038
+ payload,
2039
+ version: "v1"
2040
+ });
2041
+ return callbackResult;
2042
+ }
2043
+ };
2044
+ _schema4 = new WeakMap();
2045
+ _socket = new WeakMap();
2046
+ __name(_ZodSocketMessageSender, "ZodSocketMessageSender");
2047
+ var ZodSocketMessageSender = _ZodSocketMessageSender;
2048
+ var _sender2, _handler, _logger;
2049
+ var _ZodSocketConnection = class _ZodSocketConnection {
2050
+ constructor(opts) {
2051
+ __privateAdd(this, _sender2, void 0);
2052
+ __privateAdd(this, _handler, void 0);
2053
+ __privateAdd(this, _logger, void 0);
2054
+ this.socket = socket_ioClient.io(`ws://${opts.host}:${opts.port}/${opts.namespace}`, {
2055
+ transports: [
2056
+ "websocket"
2057
+ ],
2058
+ auth: {
2059
+ token: opts.authToken
2060
+ },
2061
+ extraHeaders: opts.extraHeaders
2062
+ });
2063
+ __privateSet(this, _logger, new SimpleStructuredLogger(opts.namespace, exports.LogLevel.info, {
2064
+ socketId: this.socket.id
2065
+ }));
2066
+ __privateSet(this, _handler, new ZodSocketMessageHandler({
2067
+ schema: opts.serverMessages,
2068
+ handlers: opts.handlers
2069
+ }));
2070
+ __privateGet(this, _handler).registerHandlers(this.socket, __privateGet(this, _logger));
2071
+ __privateSet(this, _sender2, new ZodSocketMessageSender({
2072
+ schema: opts.clientMessages,
2073
+ socket: this.socket
2074
+ }));
2075
+ this.socket.on("connect_error", async (error) => {
2076
+ __privateGet(this, _logger).error(`connect_error: ${error}`);
2077
+ if (opts.onError) {
2078
+ await opts.onError(this.socket, error, __privateGet(this, _logger));
2079
+ }
2080
+ });
2081
+ this.socket.on("connect", async () => {
2082
+ __privateGet(this, _logger).info("connect");
2083
+ if (opts.onConnection) {
2084
+ await opts.onConnection(this.socket, __privateGet(this, _handler), __privateGet(this, _sender2), __privateGet(this, _logger));
2085
+ }
2086
+ });
2087
+ this.socket.on("disconnect", async (reason, description) => {
2088
+ __privateGet(this, _logger).info("disconnect", {
2089
+ reason,
2090
+ description
2091
+ });
2092
+ if (opts.onDisconnect) {
2093
+ await opts.onDisconnect(this.socket, reason, description, __privateGet(this, _logger));
2094
+ }
2095
+ });
2096
+ }
2097
+ close() {
2098
+ this.socket.close();
2099
+ }
2100
+ connect() {
2101
+ this.socket.connect();
2102
+ }
2103
+ get send() {
2104
+ return __privateGet(this, _sender2).send.bind(__privateGet(this, _sender2));
2105
+ }
2106
+ get sendWithAck() {
2107
+ return __privateGet(this, _sender2).sendWithAck.bind(__privateGet(this, _sender2));
2108
+ }
2109
+ };
2110
+ _sender2 = new WeakMap();
2111
+ _handler = new WeakMap();
2112
+ _logger = new WeakMap();
2113
+ __name(_ZodSocketConnection, "ZodSocketConnection");
2114
+ var ZodSocketConnection = _ZodSocketConnection;
2115
+
2116
+ // src/v3/zodNamespace.ts
2117
+ exports.LogLevel = void 0;
2118
+ (function(LogLevel2) {
2119
+ LogLevel2[LogLevel2["log"] = 0] = "log";
2120
+ LogLevel2[LogLevel2["error"] = 1] = "error";
2121
+ LogLevel2[LogLevel2["warn"] = 2] = "warn";
2122
+ LogLevel2[LogLevel2["info"] = 3] = "info";
2123
+ LogLevel2[LogLevel2["debug"] = 4] = "debug";
2124
+ })(exports.LogLevel || (exports.LogLevel = {}));
2125
+ var _structuredLog, structuredLog_fn;
2126
+ var _SimpleStructuredLogger = class _SimpleStructuredLogger {
2127
+ constructor(name, level = [
2128
+ "1",
2129
+ "true"
2130
+ ].includes(process.env.DEBUG ?? "") ? exports.LogLevel.debug : exports.LogLevel.info, fields) {
2131
+ __privateAdd(this, _structuredLog);
2132
+ this.name = name;
2133
+ this.level = level;
2134
+ this.fields = fields;
2135
+ }
2136
+ child(fields, level) {
2137
+ return new _SimpleStructuredLogger(this.name, level, {
2138
+ ...this.fields,
2139
+ ...fields
2140
+ });
2141
+ }
2142
+ log(message, ...args) {
2143
+ if (this.level < exports.LogLevel.log)
2144
+ return;
2145
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.log, message, "log", ...args);
2146
+ }
2147
+ error(message, ...args) {
2148
+ if (this.level < exports.LogLevel.error)
2149
+ return;
2150
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.error, message, "error", ...args);
2151
+ }
2152
+ warn(message, ...args) {
2153
+ if (this.level < exports.LogLevel.warn)
2154
+ return;
2155
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.warn, message, "warn", ...args);
2156
+ }
2157
+ info(message, ...args) {
2158
+ if (this.level < exports.LogLevel.info)
2159
+ return;
2160
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.info, message, "info", ...args);
2161
+ }
2162
+ debug(message, ...args) {
2163
+ if (this.level < exports.LogLevel.debug)
2164
+ return;
2165
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.debug, message, "debug", ...args);
2166
+ }
2167
+ };
2168
+ _structuredLog = new WeakSet();
2169
+ structuredLog_fn = /* @__PURE__ */ __name(function(loggerFunction, message, level, ...args) {
2170
+ const structuredLog = {
2171
+ ...args.length === 1 ? args[0] : args,
2172
+ ...this.fields,
2173
+ timestamp: /* @__PURE__ */ new Date(),
2174
+ name: this.name,
2175
+ message,
2176
+ level
2177
+ };
2178
+ loggerFunction(JSON.stringify(structuredLog));
2179
+ }, "#structuredLog");
2180
+ __name(_SimpleStructuredLogger, "SimpleStructuredLogger");
2181
+ var SimpleStructuredLogger = _SimpleStructuredLogger;
2182
+ var _logger2, _handler2;
2183
+ var _ZodNamespace = class _ZodNamespace {
2184
+ constructor(opts) {
2185
+ __privateAdd(this, _logger2, void 0);
2186
+ __privateAdd(this, _handler2, void 0);
2187
+ __privateSet(this, _logger2, opts.logger ?? new SimpleStructuredLogger(opts.name));
2188
+ __privateSet(this, _handler2, new ZodSocketMessageHandler({
2189
+ schema: opts.clientMessages,
2190
+ handlers: opts.handlers
2191
+ }));
2192
+ this.io = opts.io;
2193
+ this.namespace = this.io.of(opts.name);
2194
+ this.sender = new ZodMessageSender({
2195
+ schema: opts.serverMessages,
2196
+ sender: async (message) => {
2197
+ return new Promise((resolve, reject) => {
2198
+ try {
2199
+ this.namespace.emit(message.type, message.payload);
2200
+ resolve();
2201
+ } catch (err) {
2202
+ reject(err);
2203
+ }
2204
+ });
2205
+ }
2206
+ });
2207
+ if (opts.preAuth) {
2208
+ this.namespace.use(async (socket, next) => {
2209
+ const logger2 = __privateGet(this, _logger2).child({
2210
+ socketId: socket.id,
2211
+ socketStage: "preAuth"
2212
+ });
2213
+ if (typeof opts.preAuth === "function") {
2214
+ await opts.preAuth(socket, next, logger2);
2215
+ }
2216
+ });
2217
+ }
2218
+ if (opts.authToken) {
2219
+ this.namespace.use((socket, next) => {
2220
+ const logger2 = __privateGet(this, _logger2).child({
2221
+ socketId: socket.id,
2222
+ socketStage: "auth"
2223
+ });
2224
+ const { auth } = socket.handshake;
2225
+ if (!("token" in auth)) {
2226
+ logger2.error("no token");
2227
+ return socket.disconnect(true);
2228
+ }
2229
+ if (auth.token !== opts.authToken) {
2230
+ logger2.error("invalid token");
2231
+ return socket.disconnect(true);
2232
+ }
2233
+ logger2.info("success");
2234
+ next();
2235
+ });
2236
+ }
2237
+ if (opts.postAuth) {
2238
+ this.namespace.use(async (socket, next) => {
2239
+ const logger2 = __privateGet(this, _logger2).child({
2240
+ socketId: socket.id,
2241
+ socketStage: "auth"
2242
+ });
2243
+ if (typeof opts.postAuth === "function") {
2244
+ await opts.postAuth(socket, next, logger2);
2245
+ }
2246
+ });
2247
+ }
2248
+ this.namespace.on("connection", async (socket) => {
2249
+ const logger2 = __privateGet(this, _logger2).child({
2250
+ socketId: socket.id,
2251
+ socketStage: "connection"
2252
+ });
2253
+ logger2.info("connected");
2254
+ __privateGet(this, _handler2).registerHandlers(socket, logger2);
2255
+ socket.on("disconnect", async (reason, description) => {
2256
+ logger2.info("disconnect", {
2257
+ reason,
2258
+ description
2259
+ });
2260
+ if (opts.onDisconnect) {
2261
+ await opts.onDisconnect(socket, reason, description, logger2);
2262
+ }
2263
+ });
2264
+ socket.on("error", async (error) => {
2265
+ logger2.error("error", {
2266
+ error
2267
+ });
2268
+ if (opts.onError) {
2269
+ await opts.onError(socket, error, logger2);
2270
+ }
2271
+ });
2272
+ if (opts.onConnection) {
2273
+ await opts.onConnection(socket, __privateGet(this, _handler2), this.sender, logger2);
2274
+ }
2275
+ });
2276
+ }
2277
+ fetchSockets() {
2278
+ return this.namespace.fetchSockets();
2279
+ }
2280
+ };
2281
+ _logger2 = new WeakMap();
2282
+ _handler2 = new WeakMap();
2283
+ __name(_ZodNamespace, "ZodNamespace");
2284
+ var ZodNamespace = _ZodNamespace;
2285
+ var messageSchema2 = zod.z.object({
2286
+ version: zod.z.literal("v1").default("v1"),
2287
+ type: zod.z.string(),
2288
+ payload: zod.z.unknown()
2289
+ });
2290
+ var _schema5, _handlers3, _sender3, _a;
2291
+ var ZodIpcMessageHandler = (_a = class {
2292
+ constructor(options) {
2293
+ __privateAdd(this, _schema5, void 0);
2294
+ __privateAdd(this, _handlers3, void 0);
2295
+ __privateAdd(this, _sender3, void 0);
2296
+ __privateSet(this, _schema5, options.schema);
2297
+ __privateSet(this, _handlers3, options.handlers);
2298
+ __privateSet(this, _sender3, options.sender);
2299
+ }
2300
+ async handleMessage(message) {
2301
+ const parsedMessage = this.parseMessage(message);
2302
+ if (!__privateGet(this, _handlers3)) {
2303
+ throw new Error("No handlers provided");
2304
+ }
2305
+ const handler = __privateGet(this, _handlers3)[parsedMessage.type];
2306
+ if (!handler) {
2307
+ return;
2308
+ }
2309
+ const ack = await handler(parsedMessage.payload, __privateGet(this, _sender3));
2310
+ return ack;
2311
+ }
2312
+ parseMessage(message) {
2313
+ const parsedMessage = messageSchema2.safeParse(message);
2314
+ if (!parsedMessage.success) {
2315
+ throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2316
+ }
2317
+ const schema = __privateGet(this, _schema5)[parsedMessage.data.type]["message"];
2318
+ if (!schema) {
2319
+ throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2320
+ }
2321
+ const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2322
+ if (!parsedPayload.success) {
2323
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2324
+ }
2325
+ return {
2326
+ type: parsedMessage.data.type,
2327
+ payload: parsedPayload.data
2328
+ };
2329
+ }
2330
+ }, _schema5 = new WeakMap(), _handlers3 = new WeakMap(), _sender3 = new WeakMap(), __name(_a, "ZodIpcMessageHandler"), _a);
2331
+ var Packet = zod.z.discriminatedUnion("type", [
2332
+ zod.z.object({
2333
+ type: zod.z.literal("CONNECT"),
2334
+ sessionId: zod.z.string().optional()
2335
+ }),
2336
+ zod.z.object({
2337
+ type: zod.z.literal("ACK"),
2338
+ message: zod.z.any(),
2339
+ id: zod.z.number()
2340
+ }),
2341
+ zod.z.object({
2342
+ type: zod.z.literal("EVENT"),
2343
+ message: zod.z.any(),
2344
+ id: zod.z.number().optional()
2345
+ })
2346
+ ]);
2347
+ var _sessionId, _messageCounter, _handler3, _acks, _registerHandlers, registerHandlers_fn, _handlePacket, handlePacket_fn, _sendPacket, sendPacket_fn;
2348
+ var _ZodIpcConnection = class _ZodIpcConnection {
2349
+ constructor(opts) {
2350
+ __privateAdd(this, _registerHandlers);
2351
+ __privateAdd(this, _handlePacket);
2352
+ __privateAdd(this, _sendPacket);
2353
+ __privateAdd(this, _sessionId, void 0);
2354
+ __privateAdd(this, _messageCounter, void 0);
2355
+ __privateAdd(this, _handler3, void 0);
2356
+ __privateAdd(this, _acks, void 0);
2357
+ this.opts = opts;
2358
+ __privateSet(this, _messageCounter, 0);
2359
+ __privateSet(this, _acks, /* @__PURE__ */ new Map());
2360
+ __privateSet(this, _handler3, new ZodIpcMessageHandler({
2361
+ schema: opts.listenSchema,
2362
+ handlers: opts.handlers,
2363
+ sender: {
2364
+ send: this.send.bind(this),
2365
+ sendWithAck: this.sendWithAck.bind(this)
2366
+ }
2367
+ }));
2368
+ __privateMethod(this, _registerHandlers, registerHandlers_fn).call(this);
2369
+ }
2370
+ async connect() {
2371
+ __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2372
+ type: "CONNECT"
2373
+ });
2374
+ }
2375
+ async send(type, payload) {
2376
+ const schema = this.opts.emitSchema[type]["message"];
2377
+ if (!schema) {
2378
+ throw new Error(`Unknown message type: ${type}`);
2379
+ }
2380
+ const parsedPayload = schema.safeParse(payload);
2381
+ if (!parsedPayload.success) {
2382
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2383
+ }
2384
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2385
+ type: "EVENT",
2386
+ message: {
2387
+ type,
2388
+ payload,
2389
+ version: "v1"
2390
+ }
2391
+ });
2392
+ }
2393
+ async sendWithAck(type, payload, timeoutInMs) {
2394
+ const currentId = __privateWrapper(this, _messageCounter)._++;
2395
+ return new Promise(async (resolve, reject) => {
2396
+ const defaultTimeoutInMs = 2e3;
2397
+ const timeout = setTimeout(() => {
2398
+ reject(JSON.stringify({
2399
+ reason: "sendWithAck() timeout",
2400
+ timeoutInMs: timeoutInMs ?? defaultTimeoutInMs,
2401
+ type,
2402
+ payload
2403
+ }));
2404
+ }, timeoutInMs ?? defaultTimeoutInMs);
2405
+ __privateGet(this, _acks).set(currentId, {
2406
+ resolve,
2407
+ reject,
2408
+ timeout
2409
+ });
2410
+ const schema = this.opts.emitSchema[type]["message"];
2411
+ if (!schema) {
2412
+ clearTimeout(timeout);
2413
+ return reject(`Unknown message type: ${type}`);
2414
+ }
2415
+ const parsedPayload = schema.safeParse(payload);
2416
+ if (!parsedPayload.success) {
2417
+ clearTimeout(timeout);
2418
+ return reject(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2419
+ }
2420
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2421
+ type: "EVENT",
2422
+ message: {
2423
+ type,
2424
+ payload,
2425
+ version: "v1"
2426
+ },
2427
+ id: currentId
2428
+ });
2429
+ });
2430
+ }
2431
+ };
2432
+ _sessionId = new WeakMap();
2433
+ _messageCounter = new WeakMap();
2434
+ _handler3 = new WeakMap();
2435
+ _acks = new WeakMap();
2436
+ _registerHandlers = new WeakSet();
2437
+ registerHandlers_fn = /* @__PURE__ */ __name(async function() {
2438
+ if (!this.opts.process.on) {
2439
+ return;
2440
+ }
2441
+ this.opts.process.on("message", async (message) => {
2442
+ __privateMethod(this, _handlePacket, handlePacket_fn).call(this, message);
2443
+ });
2444
+ }, "#registerHandlers");
2445
+ _handlePacket = new WeakSet();
2446
+ handlePacket_fn = /* @__PURE__ */ __name(async function(packet) {
2447
+ const parsedPacket = Packet.safeParse(packet);
2448
+ if (!parsedPacket.success) {
2449
+ return;
2450
+ }
2451
+ switch (parsedPacket.data.type) {
2452
+ case "ACK": {
2453
+ const ack = __privateGet(this, _acks).get(parsedPacket.data.id);
2454
+ if (!ack) {
2455
+ return;
2456
+ }
2457
+ clearTimeout(ack.timeout);
2458
+ ack.resolve(parsedPacket.data.message);
2459
+ break;
2460
+ }
2461
+ case "CONNECT": {
2462
+ if (!parsedPacket.data.sessionId) {
2463
+ const id = crypto.randomUUID();
2464
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2465
+ type: "CONNECT",
2466
+ sessionId: id
2467
+ });
2468
+ return;
2469
+ }
2470
+ if (__privateGet(this, _sessionId)) {
2471
+ return;
2472
+ }
2473
+ __privateSet(this, _sessionId, parsedPacket.data.sessionId);
2474
+ break;
2475
+ }
2476
+ case "EVENT": {
2477
+ const result = await __privateGet(this, _handler3).handleMessage(parsedPacket.data.message);
2478
+ if (typeof parsedPacket.data.id === "undefined") {
2479
+ return;
2480
+ }
2481
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2482
+ type: "ACK",
2483
+ id: parsedPacket.data.id,
2484
+ message: result
2485
+ });
2486
+ break;
2487
+ }
2488
+ }
2489
+ }, "#handlePacket");
2490
+ _sendPacket = new WeakSet();
2491
+ sendPacket_fn = /* @__PURE__ */ __name(async function(packet1) {
2492
+ await this.opts.process.send?.(packet1);
2493
+ }, "#sendPacket");
2494
+ __name(_ZodIpcConnection, "ZodIpcConnection");
2495
+ var ZodIpcConnection = _ZodIpcConnection;
2496
+ function parseError(error) {
2497
+ if (error instanceof Error) {
2498
+ return {
2499
+ type: "BUILT_IN_ERROR",
2500
+ name: error.name,
2501
+ message: error.message,
2502
+ stackTrace: error.stack ?? ""
2503
+ };
2504
+ }
2505
+ if (typeof error === "string") {
2506
+ return {
2507
+ type: "STRING_ERROR",
2508
+ raw: error
2509
+ };
2510
+ }
2511
+ try {
2512
+ return {
2513
+ type: "CUSTOM_ERROR",
2514
+ raw: JSON.stringify(error)
2515
+ };
2516
+ } catch (e) {
2517
+ return {
2518
+ type: "CUSTOM_ERROR",
2519
+ raw: String(error)
2520
+ };
2521
+ }
2522
+ }
2523
+ __name(parseError, "parseError");
2524
+ function createErrorTaskError(error) {
2525
+ switch (error.type) {
2526
+ case "BUILT_IN_ERROR": {
2527
+ const e = new Error(error.message);
2528
+ e.name = error.name;
2529
+ e.stack = error.stackTrace;
2530
+ return e;
2531
+ }
2532
+ case "STRING_ERROR": {
2533
+ return error.raw;
2534
+ }
2535
+ case "CUSTOM_ERROR": {
2536
+ return JSON.parse(error.raw);
2537
+ }
2538
+ case "INTERNAL_ERROR": {
2539
+ return new Error(`trigger.dev internal error (${error.code})`);
2540
+ }
2541
+ }
2542
+ }
2543
+ __name(createErrorTaskError, "createErrorTaskError");
2544
+ function correctErrorStackTrace(stackTrace, projectDir, options) {
2545
+ const [errorLine, ...traceLines] = stackTrace.split("\n");
2546
+ return [
2547
+ options?.removeFirstLine ? void 0 : errorLine,
2548
+ ...traceLines.map((line) => correctStackTraceLine(line, projectDir))
2549
+ ].filter(Boolean).join("\n");
2550
+ }
2551
+ __name(correctErrorStackTrace, "correctErrorStackTrace");
2552
+ function correctStackTraceLine(line, projectDir) {
2553
+ const regex = /at (.*?) \(?file:\/\/(\/.*?\.ts):(\d+):(\d+)\)?/;
2554
+ const match = regex.exec(line);
2555
+ if (!match) {
2556
+ return;
2557
+ }
2558
+ const [_, identifier, path, lineNum, colNum] = match;
2559
+ if (!path) {
2560
+ return;
2561
+ }
2562
+ if (nodePath__default.default.basename(path) === "__entryPoint.ts") {
2563
+ return;
2564
+ }
2565
+ if (projectDir && !path.includes(projectDir)) {
2566
+ return;
2567
+ }
2568
+ return line;
2569
+ }
2570
+ __name(correctStackTraceLine, "correctStackTraceLine");
2571
+
2572
+ // src/v3/utils/platform.ts
2573
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
2574
+
2575
+ // src/v3/utils/globals.ts
2576
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
2577
+ var _global = _globalThis;
2578
+ function registerGlobal(type, instance, allowOverride = false) {
2579
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
2580
+ if (!allowOverride && api[type]) {
2581
+ return false;
2582
+ }
2583
+ api[type] = instance;
2584
+ return true;
2585
+ }
2586
+ __name(registerGlobal, "registerGlobal");
2587
+ function getGlobal(type) {
2588
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
2589
+ }
2590
+ __name(getGlobal, "getGlobal");
2591
+ function unregisterGlobal(type) {
2592
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
2593
+ if (api) {
2594
+ delete api[type];
2595
+ }
2596
+ }
2597
+ __name(unregisterGlobal, "unregisterGlobal");
2598
+
2599
+ // src/v3/runtime/noopRuntimeManager.ts
2600
+ var _NoopRuntimeManager = class _NoopRuntimeManager {
2601
+ disable() {
2602
+ }
2603
+ registerTasks() {
2604
+ }
2605
+ getTaskMetadata(id) {
2606
+ return void 0;
2607
+ }
2608
+ waitForDuration(ms) {
2609
+ return Promise.resolve();
2610
+ }
2611
+ waitUntil(date) {
2612
+ return Promise.resolve();
2613
+ }
2614
+ waitForTask(params) {
2615
+ return Promise.resolve({
2616
+ ok: false,
2617
+ id: params.id,
2618
+ error: {
2619
+ type: "INTERNAL_ERROR",
2620
+ code: "CONFIGURED_INCORRECTLY"
2621
+ }
2622
+ });
2623
+ }
2624
+ waitForBatch(params) {
2625
+ return Promise.resolve({
2626
+ id: params.id,
2627
+ items: []
2628
+ });
2629
+ }
2630
+ };
2631
+ __name(_NoopRuntimeManager, "NoopRuntimeManager");
2632
+ var NoopRuntimeManager = _NoopRuntimeManager;
2633
+
2634
+ // src/v3/runtime/index.ts
2635
+ var API_NAME = "runtime";
2636
+ var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
2637
+ var _getRuntimeManager, getRuntimeManager_fn;
2638
+ var _RuntimeAPI = class _RuntimeAPI {
2639
+ constructor() {
2640
+ __privateAdd(this, _getRuntimeManager);
2641
+ }
2642
+ static getInstance() {
2643
+ if (!this._instance) {
2644
+ this._instance = new _RuntimeAPI();
2645
+ }
2646
+ return this._instance;
2647
+ }
2648
+ waitForDuration(ms) {
2649
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2650
+ }
2651
+ waitUntil(date) {
2652
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
2653
+ }
2654
+ waitForTask(params) {
2655
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
2656
+ }
2657
+ waitForBatch(params) {
2658
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
2659
+ }
2660
+ setGlobalRuntimeManager(runtimeManager) {
2661
+ return registerGlobal(API_NAME, runtimeManager);
2662
+ }
2663
+ disable() {
2664
+ __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2665
+ unregisterGlobal(API_NAME);
2666
+ }
2667
+ registerTasks(tasks) {
2668
+ __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).registerTasks(tasks);
2669
+ }
2670
+ getTaskMetadata(id) {
2671
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).getTaskMetadata(id);
2672
+ }
2673
+ };
2674
+ _getRuntimeManager = new WeakSet();
2675
+ getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
2676
+ return getGlobal(API_NAME) ?? NOOP_RUNTIME_MANAGER;
2677
+ }, "#getRuntimeManager");
2678
+ __name(_RuntimeAPI, "RuntimeAPI");
2679
+ var RuntimeAPI = _RuntimeAPI;
2680
+
2681
+ // src/v3/runtime-api.ts
2682
+ var runtime = RuntimeAPI.getInstance();
2683
+ function iconStringForSeverity(severityNumber) {
2684
+ switch (severityNumber) {
2685
+ case apiLogs.SeverityNumber.UNSPECIFIED:
2686
+ return void 0;
2687
+ case apiLogs.SeverityNumber.TRACE:
2688
+ case apiLogs.SeverityNumber.TRACE2:
2689
+ case apiLogs.SeverityNumber.TRACE3:
2690
+ case apiLogs.SeverityNumber.TRACE4:
2691
+ return "trace";
2692
+ case apiLogs.SeverityNumber.DEBUG:
2693
+ case apiLogs.SeverityNumber.DEBUG2:
2694
+ case apiLogs.SeverityNumber.DEBUG3:
2695
+ case apiLogs.SeverityNumber.DEBUG4:
2696
+ return "debug";
2697
+ case apiLogs.SeverityNumber.INFO:
2698
+ case apiLogs.SeverityNumber.INFO2:
2699
+ case apiLogs.SeverityNumber.INFO3:
2700
+ case apiLogs.SeverityNumber.INFO4:
2701
+ return "info";
2702
+ case apiLogs.SeverityNumber.WARN:
2703
+ case apiLogs.SeverityNumber.WARN2:
2704
+ case apiLogs.SeverityNumber.WARN3:
2705
+ case apiLogs.SeverityNumber.WARN4:
2706
+ return "warn";
2707
+ case apiLogs.SeverityNumber.ERROR:
2708
+ case apiLogs.SeverityNumber.ERROR2:
2709
+ case apiLogs.SeverityNumber.ERROR3:
2710
+ case apiLogs.SeverityNumber.ERROR4:
2711
+ return "error";
2712
+ case apiLogs.SeverityNumber.FATAL:
2713
+ case apiLogs.SeverityNumber.FATAL2:
2714
+ case apiLogs.SeverityNumber.FATAL3:
2715
+ case apiLogs.SeverityNumber.FATAL4:
2716
+ return "fatal";
2717
+ }
2718
+ }
2719
+ __name(iconStringForSeverity, "iconStringForSeverity");
2720
+ function preciseDateOriginNow() {
2721
+ return {
2722
+ hrtime: process.hrtime(),
2723
+ timestamp: new preciseDate.PreciseDate()
2724
+ };
2725
+ }
2726
+ __name(preciseDateOriginNow, "preciseDateOriginNow");
2727
+ function calculatePreciseDateHrTime(origin) {
2728
+ const elapsedHrTime = process.hrtime(origin.hrtime);
2729
+ const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
2730
+ const preciseDate$1 = new preciseDate.PreciseDate(origin.timestamp.getFullTime() + elapsedNanoseconds);
2731
+ const dateStruct = preciseDate$1.toStruct();
2732
+ return [
2733
+ dateStruct.seconds,
2734
+ dateStruct.nanos
2735
+ ];
2736
+ }
2737
+ __name(calculatePreciseDateHrTime, "calculatePreciseDateHrTime");
2738
+
2739
+ // src/v3/logger/taskLogger.ts
2740
+ var logLevels = [
2741
+ "error",
2742
+ "warn",
2743
+ "log",
2744
+ "info",
2745
+ "debug"
2746
+ ];
2747
+ var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
2748
+ var _OtelTaskLogger = class _OtelTaskLogger {
2749
+ constructor(_config) {
2750
+ __privateAdd(this, _emitLog);
2751
+ __privateAdd(this, _getTimestampInHrTime);
2752
+ this._config = _config;
2753
+ this._level = logLevels.indexOf(_config.level);
2754
+ }
2755
+ debug(message, properties) {
2756
+ if (this._level < 4)
2757
+ return;
2758
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "debug", apiLogs.SeverityNumber.DEBUG, properties);
2759
+ }
2760
+ log(message, properties) {
2761
+ if (this._level < 2)
2762
+ return;
2763
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "log", apiLogs.SeverityNumber.INFO, properties);
2764
+ }
2765
+ info(message, properties) {
2766
+ if (this._level < 3)
2767
+ return;
2768
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "info", apiLogs.SeverityNumber.INFO, properties);
2769
+ }
2770
+ warn(message, properties) {
2771
+ if (this._level < 1)
2772
+ return;
2773
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "warn", apiLogs.SeverityNumber.WARN, properties);
2774
+ }
2775
+ error(message, properties) {
2776
+ if (this._level < 0)
2777
+ return;
2778
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "error", apiLogs.SeverityNumber.ERROR, properties);
2779
+ }
2780
+ trace(name, fn, options) {
2781
+ return this._config.tracer.startActiveSpan(name, fn, options);
2782
+ }
2783
+ };
2784
+ _emitLog = new WeakSet();
2785
+ emitLog_fn = /* @__PURE__ */ __name(function(message, severityText, severityNumber, properties) {
2786
+ const timestamp = __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this);
2787
+ let attributes = {
2788
+ ...flattenAttributes(properties)
2789
+ };
2790
+ const icon = iconStringForSeverity(severityNumber);
2791
+ if (icon !== void 0) {
2792
+ attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
2793
+ }
2794
+ this._config.logger.emit({
2795
+ severityNumber,
2796
+ severityText,
2797
+ body: message,
2798
+ attributes,
2799
+ timestamp
2800
+ });
2801
+ }, "#emitLog");
2802
+ _getTimestampInHrTime = new WeakSet();
2803
+ getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
2804
+ return calculatePreciseDateHrTime(this._config.preciseDateOrigin);
2805
+ }, "#getTimestampInHrTime");
2806
+ __name(_OtelTaskLogger, "OtelTaskLogger");
2807
+ var OtelTaskLogger = _OtelTaskLogger;
2808
+ var _NoopTaskLogger = class _NoopTaskLogger {
2809
+ debug() {
2810
+ }
2811
+ log() {
2812
+ }
2813
+ info() {
2814
+ }
2815
+ warn() {
2816
+ }
2817
+ error() {
2818
+ }
2819
+ trace(name, fn) {
2820
+ return fn({});
2821
+ }
2822
+ };
2823
+ __name(_NoopTaskLogger, "NoopTaskLogger");
2824
+ var NoopTaskLogger = _NoopTaskLogger;
2825
+
2826
+ // src/v3/logger/index.ts
2827
+ var API_NAME2 = "logger";
2828
+ var NOOP_TASK_LOGGER = new NoopTaskLogger();
2829
+ var _getTaskLogger, getTaskLogger_fn;
2830
+ var _LoggerAPI = class _LoggerAPI {
2831
+ constructor() {
2832
+ __privateAdd(this, _getTaskLogger);
2833
+ }
2834
+ static getInstance() {
2835
+ if (!this._instance) {
2836
+ this._instance = new _LoggerAPI();
2837
+ }
2838
+ return this._instance;
2839
+ }
2840
+ disable() {
2841
+ unregisterGlobal(API_NAME2);
2842
+ }
2843
+ setGlobalTaskLogger(taskLogger) {
2844
+ return registerGlobal(API_NAME2, taskLogger);
2845
+ }
2846
+ debug(message, metadata) {
2847
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).debug(message, metadata);
2848
+ }
2849
+ log(message, metadata) {
2850
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).log(message, metadata);
2851
+ }
2852
+ info(message, metadata) {
2853
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).info(message, metadata);
2854
+ }
2855
+ warn(message, metadata) {
2856
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).warn(message, metadata);
2857
+ }
2858
+ error(message, metadata) {
2859
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).error(message, metadata);
2860
+ }
2861
+ trace(name, fn) {
2862
+ return __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).trace(name, fn);
2863
+ }
2864
+ };
2865
+ _getTaskLogger = new WeakSet();
2866
+ getTaskLogger_fn = /* @__PURE__ */ __name(function() {
2867
+ return getGlobal(API_NAME2) ?? NOOP_TASK_LOGGER;
2868
+ }, "#getTaskLogger");
2869
+ __name(_LoggerAPI, "LoggerAPI");
2870
+ var LoggerAPI = _LoggerAPI;
2871
+
2872
+ // src/v3/logger-api.ts
2873
+ var logger = LoggerAPI.getInstance();
2874
+
2875
+ // src/v3/limits.ts
2876
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2877
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
2878
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2879
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2880
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
2881
+ var OTEL_LINK_COUNT_LIMIT = 2;
2882
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
2883
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
2884
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
2885
+ function imposeAttributeLimits(attributes) {
2886
+ const newAttributes = {};
2887
+ for (const [key, value] of Object.entries(attributes)) {
2888
+ if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
2889
+ continue;
2890
+ }
2891
+ if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
2892
+ break;
2893
+ }
2894
+ newAttributes[key] = value;
2895
+ }
2896
+ return newAttributes;
2897
+ }
2898
+ __name(imposeAttributeLimits, "imposeAttributeLimits");
2899
+ function calculateAttributeValueLength(value) {
2900
+ if (value === void 0 || value === null) {
2901
+ return 0;
2902
+ }
2903
+ if (typeof value === "string") {
2904
+ return value.length;
2905
+ }
2906
+ if (typeof value === "number") {
2907
+ return 8;
2908
+ }
2909
+ if (typeof value === "boolean") {
2910
+ return 4;
2911
+ }
2912
+ if (Array.isArray(value)) {
2913
+ return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
2914
+ }
2915
+ return 0;
2916
+ }
2917
+ __name(calculateAttributeValueLength, "calculateAttributeValueLength");
2918
+ function dateDifference(date1, date2) {
2919
+ return Math.abs(date1.getTime() - date2.getTime());
2920
+ }
2921
+ __name(dateDifference, "dateDifference");
2922
+ function formatDuration(start, end, options) {
2923
+ if (!start || !end) {
2924
+ return "\u2013";
2925
+ }
2926
+ return formatDurationMilliseconds(dateDifference(start, end), options);
2927
+ }
2928
+ __name(formatDuration, "formatDuration");
2929
+ function nanosecondsToMilliseconds(nanoseconds) {
2930
+ return nanoseconds / 1e6;
2931
+ }
2932
+ __name(nanosecondsToMilliseconds, "nanosecondsToMilliseconds");
2933
+ function millisecondsToNanoseconds(milliseconds) {
2934
+ return milliseconds * 1e6;
2935
+ }
2936
+ __name(millisecondsToNanoseconds, "millisecondsToNanoseconds");
2937
+ function formatDurationNanoseconds(nanoseconds, options) {
2938
+ return formatDurationMilliseconds(nanosecondsToMilliseconds(nanoseconds), options);
2939
+ }
2940
+ __name(formatDurationNanoseconds, "formatDurationNanoseconds");
2941
+ var aboveOneSecondUnits = [
2942
+ "d",
2943
+ "h",
2944
+ "m",
2945
+ "s"
2946
+ ];
2947
+ var belowOneSecondUnits = [
2948
+ "ms"
2949
+ ];
2950
+ function formatDurationMilliseconds(milliseconds, options) {
2951
+ let duration = humanizeDuration__default.default(milliseconds, {
2952
+ units: options?.units ? options.units : milliseconds < 1e3 ? belowOneSecondUnits : aboveOneSecondUnits,
2953
+ maxDecimalPoints: options?.maxDecimalPoints ?? 1,
2954
+ largest: 2
2955
+ });
2956
+ if (!options) {
2957
+ return duration;
2958
+ }
2959
+ switch (options.style) {
2960
+ case "short":
2961
+ duration = duration.replace(" milliseconds", "ms");
2962
+ duration = duration.replace(" millisecond", "ms");
2963
+ duration = duration.replace(" seconds", "s");
2964
+ duration = duration.replace(" second", "s");
2965
+ duration = duration.replace(" minutes", "m");
2966
+ duration = duration.replace(" minute", "m");
2967
+ duration = duration.replace(" hours", "h");
2968
+ duration = duration.replace(" hour", "h");
2969
+ duration = duration.replace(" days", "d");
2970
+ duration = duration.replace(" day", "d");
2971
+ duration = duration.replace(" weeks", "w");
2972
+ duration = duration.replace(" week", "w");
2973
+ duration = duration.replace(" months", "mo");
2974
+ duration = duration.replace(" month", "mo");
2975
+ duration = duration.replace(" years", "y");
2976
+ duration = duration.replace(" year", "y");
2977
+ }
2978
+ return duration;
2979
+ }
2980
+ __name(formatDurationMilliseconds, "formatDurationMilliseconds");
2981
+ function formatDurationInDays(milliseconds) {
2982
+ let duration = humanizeDuration__default.default(milliseconds, {
2983
+ maxDecimalPoints: 0,
2984
+ largest: 2,
2985
+ units: [
2986
+ "d"
2987
+ ]
2988
+ });
2989
+ return duration;
2990
+ }
2991
+ __name(formatDurationInDays, "formatDurationInDays");
2992
+
2993
+ // src/v3/runtime/devRuntimeManager.ts
2994
+ var _DevRuntimeManager = class _DevRuntimeManager {
2995
+ constructor() {
2996
+ __publicField(this, "_taskWaits", /* @__PURE__ */ new Map());
2997
+ __publicField(this, "_batchWaits", /* @__PURE__ */ new Map());
2998
+ __publicField(this, "_tasks", /* @__PURE__ */ new Map());
2999
+ __publicField(this, "_pendingCompletionNotifications", /* @__PURE__ */ new Map());
3000
+ }
3001
+ disable() {
3002
+ }
3003
+ registerTasks(tasks) {
3004
+ for (const task of tasks) {
3005
+ this._tasks.set(task.id, task);
3006
+ }
3007
+ }
3008
+ getTaskMetadata(id) {
3009
+ return this._tasks.get(id);
3010
+ }
3011
+ async waitForDuration(ms) {
3012
+ return new Promise((resolve) => {
3013
+ setTimeout(resolve, ms);
3014
+ });
3015
+ }
3016
+ async waitUntil(date) {
3017
+ return new Promise((resolve) => {
3018
+ setTimeout(resolve, date.getTime() - Date.now());
3019
+ });
3020
+ }
3021
+ async waitForTask(params) {
3022
+ const pendingCompletion = this._pendingCompletionNotifications.get(params.id);
3023
+ if (pendingCompletion) {
3024
+ this._pendingCompletionNotifications.delete(params.id);
3025
+ return pendingCompletion;
3026
+ }
3027
+ const promise = new Promise((resolve, reject) => {
3028
+ this._taskWaits.set(params.id, {
3029
+ resolve,
3030
+ reject
3031
+ });
3032
+ });
3033
+ return await promise;
3034
+ }
3035
+ async waitForBatch(params) {
3036
+ if (!params.runs.length) {
3037
+ return Promise.resolve({
3038
+ id: params.id,
3039
+ items: []
3040
+ });
3041
+ }
3042
+ const promise = Promise.all(params.runs.map((runId) => {
3043
+ return new Promise((resolve, reject) => {
3044
+ const pendingCompletion = this._pendingCompletionNotifications.get(runId);
3045
+ if (pendingCompletion) {
3046
+ this._pendingCompletionNotifications.delete(runId);
3047
+ if (pendingCompletion.ok) {
3048
+ resolve(pendingCompletion);
3049
+ } else {
3050
+ reject(pendingCompletion);
3051
+ }
3052
+ return;
3053
+ }
3054
+ this._taskWaits.set(runId, {
3055
+ resolve,
3056
+ reject
3057
+ });
3058
+ });
3059
+ }));
3060
+ const results = await promise;
3061
+ return {
3062
+ id: params.id,
3063
+ items: results
3064
+ };
3065
+ }
3066
+ resumeTask(completion, execution) {
3067
+ const wait = this._taskWaits.get(execution.run.id);
3068
+ if (!wait) {
3069
+ this._pendingCompletionNotifications.set(execution.run.id, completion);
3070
+ return;
3071
+ }
3072
+ if (completion.ok) {
3073
+ wait.resolve(completion);
3074
+ } else {
3075
+ wait.reject(completion);
3076
+ }
3077
+ this._taskWaits.delete(execution.run.id);
3078
+ }
3079
+ };
3080
+ __name(_DevRuntimeManager, "DevRuntimeManager");
3081
+ var DevRuntimeManager = _DevRuntimeManager;
3082
+
3083
+ // src/v3/runtime/prodRuntimeManager.ts
3084
+ var _ProdRuntimeManager = class _ProdRuntimeManager {
3085
+ constructor(ipc) {
3086
+ this.ipc = ipc;
3087
+ this._taskWaits = /* @__PURE__ */ new Map();
3088
+ this._batchWaits = /* @__PURE__ */ new Map();
3089
+ this._tasks = /* @__PURE__ */ new Map();
3090
+ }
3091
+ disable() {
3092
+ }
3093
+ registerTasks(tasks) {
3094
+ for (const task of tasks) {
3095
+ this._tasks.set(task.id, task);
3096
+ }
3097
+ }
3098
+ getTaskMetadata(id) {
3099
+ return this._tasks.get(id);
3100
+ }
3101
+ async waitForDuration(ms) {
3102
+ let timeout;
3103
+ const now = Date.now();
3104
+ const resolveAfterDuration = new Promise((resolve) => {
3105
+ timeout = setTimeout(resolve, ms);
3106
+ });
3107
+ if (ms < 1e4) {
3108
+ await resolveAfterDuration;
3109
+ return;
3110
+ }
3111
+ const waitForRestore = new Promise((resolve, reject) => {
3112
+ this._waitForRestore = {
3113
+ resolve,
3114
+ reject
3115
+ };
3116
+ });
3117
+ const { willCheckpointAndRestore } = await this.ipc.sendWithAck("WAIT_FOR_DURATION", {
3118
+ ms,
3119
+ now
3120
+ });
3121
+ if (!willCheckpointAndRestore) {
3122
+ await resolveAfterDuration;
3123
+ return;
3124
+ }
3125
+ this.ipc.send("READY_FOR_CHECKPOINT", {});
3126
+ await Promise.race([
3127
+ waitForRestore,
3128
+ resolveAfterDuration
3129
+ ]);
3130
+ this.ipc.send("CANCEL_CHECKPOINT", {});
3131
+ clearTimeout(timeout);
3132
+ }
3133
+ resumeAfterRestore() {
3134
+ if (!this._waitForRestore) {
3135
+ return;
3136
+ }
3137
+ this._waitForRestore.resolve();
3138
+ this._waitForRestore = void 0;
3139
+ }
3140
+ async waitUntil(date) {
3141
+ return this.waitForDuration(date.getTime() - Date.now());
3142
+ }
3143
+ async waitForTask(params) {
3144
+ const promise = new Promise((resolve, reject) => {
3145
+ this._taskWaits.set(params.id, {
3146
+ resolve,
3147
+ reject
3148
+ });
3149
+ });
3150
+ await this.ipc.send("WAIT_FOR_TASK", {
3151
+ friendlyId: params.id
3152
+ });
3153
+ return await promise;
3154
+ }
3155
+ async waitForBatch(params) {
3156
+ if (!params.runs.length) {
3157
+ return Promise.resolve({
3158
+ id: params.id,
3159
+ items: []
3160
+ });
3161
+ }
3162
+ const promise = Promise.all(params.runs.map((runId) => {
3163
+ return new Promise((resolve, reject) => {
3164
+ this._taskWaits.set(runId, {
3165
+ resolve,
3166
+ reject
3167
+ });
3168
+ });
3169
+ }));
3170
+ await this.ipc.send("WAIT_FOR_BATCH", {
3171
+ batchFriendlyId: params.id,
3172
+ runFriendlyIds: params.runs
3173
+ });
3174
+ const results = await promise;
3175
+ return {
3176
+ id: params.id,
3177
+ items: results
3178
+ };
3179
+ }
3180
+ resumeTask(completion, execution) {
3181
+ const wait = this._taskWaits.get(execution.run.id);
3182
+ if (!wait) {
3183
+ return;
3184
+ }
3185
+ if (completion.ok) {
3186
+ wait.resolve(completion);
3187
+ } else {
3188
+ wait.reject(completion);
3189
+ }
3190
+ this._taskWaits.delete(execution.run.id);
3191
+ }
3192
+ };
3193
+ __name(_ProdRuntimeManager, "ProdRuntimeManager");
3194
+ var ProdRuntimeManager = _ProdRuntimeManager;
3195
+ var _TriggerTracer = class _TriggerTracer {
3196
+ constructor(_config) {
3197
+ this._config = _config;
3198
+ }
3199
+ get tracer() {
3200
+ if (!this._tracer) {
3201
+ if ("tracer" in this._config)
3202
+ return this._config.tracer;
3203
+ this._tracer = api.trace.getTracer(this._config.name, this._config.version);
3204
+ }
3205
+ return this._tracer;
3206
+ }
3207
+ get logger() {
3208
+ if (!this._logger) {
3209
+ if ("logger" in this._config)
3210
+ return this._config.logger;
3211
+ this._logger = apiLogs.logs.getLogger(this._config.name, this._config.version);
3212
+ }
3213
+ return this._logger;
3214
+ }
3215
+ extractContext(traceContext) {
3216
+ return api.propagation.extract(api.context.active(), traceContext ?? {});
3217
+ }
3218
+ startActiveSpan(name, fn, options, ctx) {
3219
+ const parentContext = ctx ?? api.context.active();
3220
+ const attributes = options?.attributes ?? {};
3221
+ return this.tracer.startActiveSpan(name, {
3222
+ ...options,
3223
+ attributes
3224
+ }, parentContext, async (span) => {
3225
+ this.tracer.startSpan(name, {
3226
+ ...options,
3227
+ attributes: {
3228
+ ...attributes,
3229
+ [SemanticInternalAttributes.SPAN_PARTIAL]: true,
3230
+ [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
3231
+ }
3232
+ }, parentContext).end();
3233
+ try {
3234
+ return await fn(span);
3235
+ } catch (e) {
3236
+ if (typeof e === "string" || e instanceof Error) {
3237
+ span.recordException(e);
3238
+ }
3239
+ span.setStatus({
3240
+ code: api.SpanStatusCode.ERROR
3241
+ });
3242
+ throw e;
3243
+ } finally {
3244
+ span.end();
3245
+ }
3246
+ });
3247
+ }
3248
+ startSpan(name, options, ctx) {
3249
+ const parentContext = ctx ?? api.context.active();
3250
+ const attributes = options?.attributes ?? {};
3251
+ const span = this.tracer.startSpan(name, options, ctx);
3252
+ this.tracer.startSpan(name, {
3253
+ ...options,
3254
+ attributes: {
3255
+ ...attributes,
3256
+ [SemanticInternalAttributes.SPAN_PARTIAL]: true,
3257
+ [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
3258
+ }
3259
+ }, parentContext).end();
3260
+ return span;
3261
+ }
3262
+ };
3263
+ __name(_TriggerTracer, "TriggerTracer");
3264
+ var TriggerTracer = _TriggerTracer;
3265
+ var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
3266
+ var _ConsoleInterceptor = class _ConsoleInterceptor {
3267
+ constructor(logger2, preciseDateOrigin) {
3268
+ __privateAdd(this, _handleLog);
3269
+ __privateAdd(this, _getTimestampInHrTime2);
3270
+ __privateAdd(this, _getAttributes);
3271
+ this.logger = logger2;
3272
+ this.preciseDateOrigin = preciseDateOrigin;
3273
+ }
3274
+ // Intercept the console and send logs to the OpenTelemetry logger
3275
+ // during the execution of the callback
3276
+ async intercept(console2, callback) {
3277
+ const originalConsole = {
3278
+ log: console2.log,
3279
+ info: console2.info,
3280
+ warn: console2.warn,
3281
+ error: console2.error
3282
+ };
3283
+ console2.log = this.log.bind(this);
3284
+ console2.info = this.info.bind(this);
3285
+ console2.warn = this.warn.bind(this);
3286
+ console2.error = this.error.bind(this);
3287
+ try {
3288
+ return await callback();
3289
+ } finally {
3290
+ console2.log = originalConsole.log;
3291
+ console2.info = originalConsole.info;
3292
+ console2.warn = originalConsole.warn;
3293
+ console2.error = originalConsole.error;
3294
+ }
3295
+ }
3296
+ log(...args) {
3297
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, "Log", ...args);
3298
+ }
3299
+ info(...args) {
3300
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, "Info", ...args);
3301
+ }
3302
+ warn(...args) {
3303
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.WARN, "Warn", ...args);
3304
+ }
3305
+ error(...args) {
3306
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.ERROR, "Error", ...args);
3307
+ }
3308
+ };
3309
+ _handleLog = new WeakSet();
3310
+ handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, severityText, ...args) {
3311
+ const body = util__default.default.format(...args);
3312
+ const timestamp = __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this);
3313
+ const parsed = tryParseJSON(body);
3314
+ if (parsed.ok) {
3315
+ this.logger.emit({
3316
+ severityNumber,
3317
+ severityText,
3318
+ body: getLogMessage(parsed.value, severityText),
3319
+ attributes: {
3320
+ ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3321
+ ...flattenAttributes(parsed.value)
3322
+ },
3323
+ timestamp
3324
+ });
3325
+ return;
3326
+ }
3327
+ this.logger.emit({
3328
+ severityNumber,
3329
+ severityText,
3330
+ body,
3331
+ attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3332
+ timestamp
3333
+ });
3334
+ }, "#handleLog");
3335
+ _getTimestampInHrTime2 = new WeakSet();
3336
+ getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
3337
+ return calculatePreciseDateHrTime(this.preciseDateOrigin);
3338
+ }, "#getTimestampInHrTime");
3339
+ _getAttributes = new WeakSet();
3340
+ getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
3341
+ const icon = iconStringForSeverity(severityNumber1);
3342
+ let result = {};
3343
+ if (icon !== void 0) {
3344
+ result[SemanticInternalAttributes.STYLE_ICON] = icon;
3345
+ }
3346
+ return result;
3347
+ }, "#getAttributes");
3348
+ __name(_ConsoleInterceptor, "ConsoleInterceptor");
3349
+ var ConsoleInterceptor = _ConsoleInterceptor;
3350
+ function getLogMessage(value, fallback) {
3351
+ if (typeof value["message"] === "string") {
3352
+ return value["message"];
3353
+ }
3354
+ if (typeof value["msg"] === "string") {
3355
+ return value["msg"];
3356
+ }
3357
+ if (typeof value["body"] === "string") {
3358
+ return value["body"];
3359
+ }
3360
+ if (typeof value["error"] === "string") {
3361
+ return value["error"];
3362
+ }
3363
+ return fallback;
3364
+ }
3365
+ __name(getLogMessage, "getLogMessage");
3366
+ function tryParseJSON(value) {
3367
+ try {
3368
+ const parsed = JSON.parse(value);
3369
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
3370
+ return {
3371
+ ok: true,
3372
+ value: parsed
3373
+ };
3374
+ }
3375
+ return {
3376
+ ok: false,
3377
+ value
3378
+ };
3379
+ } catch (e) {
3380
+ return {
3381
+ ok: false,
3382
+ value
3383
+ };
3384
+ }
3385
+ }
3386
+ __name(tryParseJSON, "tryParseJSON");
3387
+
3388
+ // src/retry.ts
3389
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
3390
+ if (!resets)
3391
+ return;
3392
+ switch (format) {
3393
+ case "iso_8601_duration_openai_variant": {
3394
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
3395
+ }
3396
+ case "iso_8601": {
3397
+ return calculateISO8601ResetAt(resets, now);
3398
+ }
3399
+ case "unix_timestamp": {
3400
+ return calculateUnixTimestampResetAt(resets, now);
3401
+ }
3402
+ case "unix_timestamp_in_ms": {
3403
+ return calculateUnixTimestampInMsResetAt(resets, now);
3404
+ }
3405
+ }
3406
+ }
3407
+ __name(calculateResetAt, "calculateResetAt");
3408
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
3409
+ if (!resets)
3410
+ return void 0;
3411
+ const resetAt = parseInt(resets, 10);
3412
+ if (isNaN(resetAt))
3413
+ return void 0;
3414
+ return new Date(resetAt * 1e3);
3415
+ }
3416
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
3417
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
3418
+ if (!resets)
3419
+ return void 0;
3420
+ const resetAt = parseInt(resets, 10);
3421
+ if (isNaN(resetAt))
3422
+ return void 0;
3423
+ return new Date(resetAt);
3424
+ }
3425
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
3426
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
3427
+ if (!resets)
3428
+ return void 0;
3429
+ const resetAt = new Date(resets);
3430
+ if (isNaN(resetAt.getTime()))
3431
+ return void 0;
3432
+ return resetAt;
3433
+ }
3434
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
3435
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
3436
+ if (!resets)
3437
+ return void 0;
3438
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
3439
+ const match = resets.match(pattern);
3440
+ if (!match)
3441
+ return void 0;
3442
+ const days = parseInt(match[1], 10) || 0;
3443
+ const hours = parseInt(match[2], 10) || 0;
3444
+ const minutes = parseInt(match[3], 10) || 0;
3445
+ const seconds = parseFloat(match[4]) || 0;
3446
+ const milliseconds = parseInt(match[5], 10) || 0;
3447
+ const resetAt = new Date(now);
3448
+ resetAt.setDate(resetAt.getDate() + days);
3449
+ resetAt.setHours(resetAt.getHours() + hours);
3450
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
3451
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
3452
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
3453
+ return resetAt;
3454
+ }
3455
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
3456
+
3457
+ // src/v3/utils/retries.ts
3458
+ var defaultRetryOptions = {
3459
+ maxAttempts: 3,
3460
+ factor: 2,
3461
+ minTimeoutInMs: 1e3,
3462
+ maxTimeoutInMs: 6e4,
3463
+ randomize: true
3464
+ };
3465
+ var defaultFetchRetryOptions = {
3466
+ byStatus: {
3467
+ "429,408,409,5xx": {
3468
+ strategy: "backoff",
3469
+ ...defaultRetryOptions
3470
+ }
3471
+ },
3472
+ connectionError: defaultRetryOptions,
3473
+ timeout: defaultRetryOptions
3474
+ };
3475
+ function calculateNextRetryDelay(options, attempt) {
3476
+ const opts = {
3477
+ ...defaultRetryOptions,
3478
+ ...options
3479
+ };
3480
+ if (attempt >= opts.maxAttempts) {
3481
+ return;
3482
+ }
3483
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
3484
+ const random = randomize ? Math.random() + 1 : 1;
3485
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
3486
+ return Math.round(timeout);
3487
+ }
3488
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
3489
+ function calculateResetAt2(resets, format, now = Date.now()) {
3490
+ const resetAt = calculateResetAt(resets, format, new Date(now));
3491
+ return resetAt?.getTime();
3492
+ }
3493
+ __name(calculateResetAt2, "calculateResetAt");
3494
+
3495
+ // src/v3/utils/styleAttributes.ts
3496
+ function accessoryAttributes(accessory) {
3497
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
3498
+ }
3499
+ __name(accessoryAttributes, "accessoryAttributes");
3500
+
3501
+ // src/eventFilterMatches.ts
3502
+ function eventFilterMatches(payload, filter) {
3503
+ if (payload === void 0 || payload === null) {
3504
+ if (Object.entries(filter).length === 0) {
3505
+ return true;
3506
+ } else {
3507
+ return false;
3508
+ }
3509
+ }
3510
+ for (const [patternKey, patternValue] of Object.entries(filter)) {
3511
+ const payloadValue = payload[patternKey];
3512
+ if (Array.isArray(patternValue)) {
3513
+ if (patternValue.length === 0) {
3514
+ continue;
3515
+ }
3516
+ if (patternValue.every((item) => typeof item === "string")) {
3517
+ if (patternValue.includes(payloadValue)) {
3518
+ continue;
3519
+ }
3520
+ return false;
3521
+ }
3522
+ if (patternValue.every((item) => typeof item === "number")) {
3523
+ if (patternValue.includes(payloadValue)) {
3524
+ continue;
3525
+ }
3526
+ return false;
3527
+ }
3528
+ if (patternValue.every((item) => typeof item === "boolean")) {
3529
+ if (patternValue.includes(payloadValue)) {
3530
+ continue;
3531
+ }
3532
+ return false;
3533
+ }
3534
+ const objectArray = patternValue;
3535
+ if (!contentFiltersMatches(payloadValue, objectArray)) {
3536
+ return false;
3537
+ }
3538
+ continue;
3539
+ } else if (typeof patternValue === "object") {
3540
+ if (Array.isArray(payloadValue)) {
3541
+ if (!payloadValue.some((item) => eventFilterMatches(item, patternValue))) {
3542
+ return false;
3543
+ }
3544
+ } else {
3545
+ if (!eventFilterMatches(payloadValue, patternValue)) {
3546
+ return false;
3547
+ }
3548
+ }
3549
+ }
3550
+ }
3551
+ return true;
3552
+ }
3553
+ __name(eventFilterMatches, "eventFilterMatches");
3554
+ function contentFiltersMatches(actualValue, contentFilters) {
3555
+ for (const contentFilter of contentFilters) {
3556
+ if (typeof contentFilter === "object") {
3557
+ Object.entries(contentFilter)[0];
3558
+ if (!contentFilterMatches(actualValue, contentFilter)) {
3559
+ return false;
3560
+ }
3561
+ }
3562
+ }
3563
+ return true;
3564
+ }
3565
+ __name(contentFiltersMatches, "contentFiltersMatches");
3566
+ function contentFilterMatches(actualValue, contentFilter) {
3567
+ if ("$endsWith" in contentFilter) {
3568
+ if (typeof actualValue !== "string") {
3569
+ return false;
3570
+ }
3571
+ return actualValue.endsWith(contentFilter.$endsWith);
3572
+ }
3573
+ if ("$startsWith" in contentFilter) {
3574
+ if (typeof actualValue !== "string") {
3575
+ return false;
3576
+ }
3577
+ return actualValue.startsWith(contentFilter.$startsWith);
3578
+ }
3579
+ if ("$anythingBut" in contentFilter) {
3580
+ if (Array.isArray(contentFilter.$anythingBut)) {
3581
+ if (contentFilter.$anythingBut.includes(actualValue)) {
3582
+ return false;
3583
+ }
3584
+ }
3585
+ if (contentFilter.$anythingBut === actualValue) {
3586
+ return false;
3587
+ }
3588
+ return true;
3589
+ }
3590
+ if ("$exists" in contentFilter) {
3591
+ if (contentFilter.$exists) {
3592
+ return actualValue !== void 0;
3593
+ }
3594
+ return actualValue === void 0;
3595
+ }
3596
+ if ("$gt" in contentFilter) {
3597
+ if (typeof actualValue !== "number") {
3598
+ return false;
3599
+ }
3600
+ return actualValue > contentFilter.$gt;
3601
+ }
3602
+ if ("$lt" in contentFilter) {
3603
+ if (typeof actualValue !== "number") {
3604
+ return false;
3605
+ }
3606
+ return actualValue < contentFilter.$lt;
3607
+ }
3608
+ if ("$gte" in contentFilter) {
3609
+ if (typeof actualValue !== "number") {
3610
+ return false;
3611
+ }
3612
+ return actualValue >= contentFilter.$gte;
3613
+ }
3614
+ if ("$lte" in contentFilter) {
3615
+ if (typeof actualValue !== "number") {
3616
+ return false;
3617
+ }
3618
+ return actualValue <= contentFilter.$lte;
3619
+ }
3620
+ if ("$between" in contentFilter) {
3621
+ if (typeof actualValue !== "number") {
3622
+ return false;
3623
+ }
3624
+ return actualValue >= contentFilter.$between[0] && actualValue <= contentFilter.$between[1];
3625
+ }
3626
+ if ("$includes" in contentFilter) {
3627
+ if (Array.isArray(actualValue)) {
3628
+ return actualValue.includes(contentFilter.$includes);
3629
+ }
3630
+ return false;
3631
+ }
3632
+ if ("$ignoreCaseEquals" in contentFilter) {
3633
+ if (typeof actualValue !== "string") {
3634
+ return false;
3635
+ }
3636
+ return actualValue.localeCompare(contentFilter.$ignoreCaseEquals, void 0, {
3637
+ sensitivity: "accent"
3638
+ }) === 0;
3639
+ }
3640
+ if ("$isNull" in contentFilter) {
3641
+ if (contentFilter.$isNull) {
3642
+ return actualValue === null;
3643
+ }
3644
+ return actualValue !== null;
3645
+ }
3646
+ if ("$not" in contentFilter) {
3647
+ if (Array.isArray(actualValue)) {
3648
+ return !actualValue.includes(contentFilter.$not);
3649
+ } else if (typeof actualValue === "number" || typeof actualValue === "boolean" || typeof actualValue === "string") {
3650
+ return actualValue !== contentFilter.$not;
3651
+ }
3652
+ return false;
3653
+ }
3654
+ return true;
3655
+ }
3656
+ __name(contentFilterMatches, "contentFilterMatches");
3657
+
3658
+ // src/v3/utils/omit.ts
3659
+ function omit(obj, ...keys) {
3660
+ const result = {};
3661
+ for (const key in obj) {
3662
+ if (!keys.includes(key)) {
3663
+ result[key] = obj[key];
3664
+ }
3665
+ }
3666
+ return result;
3667
+ }
3668
+ __name(omit, "omit");
3669
+ var _a2;
3670
+ var AsyncResourceDetector = (_a2 = class {
3671
+ constructor() {
3672
+ __publicField(this, "_resolved", false);
3673
+ this._promise = new Promise((resolver) => {
3674
+ this._resolver = resolver;
3675
+ });
3676
+ }
3677
+ detect(_config) {
3678
+ return new resources.Resource({}, this._promise);
3679
+ }
3680
+ resolveWithAttributes(attributes) {
3681
+ if (!this._resolver) {
3682
+ throw new Error("Resolver not available");
3683
+ }
3684
+ if (this._resolved) {
3685
+ return;
3686
+ }
3687
+ this._resolved = true;
3688
+ this._resolver(attributes);
3689
+ }
3690
+ }, __name(_a2, "AsyncResourceDetector"), _a2);
3691
+ var _TracingSDK = class _TracingSDK {
3692
+ constructor(config) {
3693
+ this.config = config;
3694
+ this.asyncResourceDetector = new AsyncResourceDetector();
3695
+ setLogLevel(config.diagLogLevel ?? "none");
3696
+ const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
3697
+ const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
3698
+ const commonResources = resources.detectResourcesSync({
3699
+ detectors: [
3700
+ this.asyncResourceDetector,
3701
+ resources.processDetectorSync
3702
+ ]
3703
+ }).merge(new resources.Resource({
3704
+ [semanticConventions.SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
3705
+ [SemanticInternalAttributes.TRIGGER]: true
3706
+ })).merge(config.resource ?? new resources.Resource({})).merge(new resources.Resource(envResourceAttributes));
3707
+ const traceProvider = new sdkTraceNode.NodeTracerProvider({
3708
+ forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
3709
+ resource: commonResources,
3710
+ spanLimits: {
3711
+ attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
3712
+ attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
3713
+ eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
3714
+ attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
3715
+ linkCountLimit: OTEL_LINK_COUNT_LIMIT,
3716
+ attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
3717
+ }
3718
+ });
3719
+ const spanExporter = new exporterTraceOtlpHttp.OTLPTraceExporter({
3720
+ url: `${config.url}/v1/traces`,
3721
+ timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
3722
+ });
3723
+ traceProvider.addSpanProcessor(new TaskContextSpanProcessor(new sdkTraceNode.SimpleSpanProcessor(spanExporter)));
3724
+ traceProvider.register();
3725
+ instrumentation.registerInstrumentations({
3726
+ instrumentations: config.instrumentations ?? [],
3727
+ tracerProvider: traceProvider
3728
+ });
3729
+ const logExporter = new exporterLogsOtlpHttp.OTLPLogExporter({
3730
+ url: `${config.url}/v1/logs`
3731
+ });
3732
+ const loggerProvider = new sdkLogs.LoggerProvider({
3733
+ resource: commonResources,
3734
+ logRecordLimits: {
3735
+ attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
3736
+ attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
3737
+ }
3738
+ });
3739
+ loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(new sdkLogs.SimpleLogRecordProcessor(logExporter)));
3740
+ this._logProvider = loggerProvider;
3741
+ this._spanExporter = spanExporter;
3742
+ this._traceProvider = traceProvider;
3743
+ apiLogs.logs.setGlobalLoggerProvider(loggerProvider);
3744
+ this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
3745
+ this.getTracer = traceProvider.getTracer.bind(traceProvider);
3746
+ }
3747
+ async flush() {
3748
+ await this._spanExporter.forceFlush?.();
3749
+ await this._logProvider.forceFlush();
3750
+ }
3751
+ async shutdown() {
3752
+ await this._spanExporter.shutdown();
3753
+ await this._logProvider.shutdown();
3754
+ }
3755
+ };
3756
+ __name(_TracingSDK, "TracingSDK");
3757
+ var TracingSDK = _TracingSDK;
3758
+ function setLogLevel(level) {
3759
+ let diagLogLevel;
3760
+ switch (level) {
3761
+ case "none":
3762
+ diagLogLevel = api.DiagLogLevel.NONE;
3763
+ break;
3764
+ case "error":
3765
+ diagLogLevel = api.DiagLogLevel.ERROR;
3766
+ break;
3767
+ case "warn":
3768
+ diagLogLevel = api.DiagLogLevel.WARN;
3769
+ break;
3770
+ case "info":
3771
+ diagLogLevel = api.DiagLogLevel.INFO;
3772
+ break;
3773
+ case "debug":
3774
+ diagLogLevel = api.DiagLogLevel.DEBUG;
3775
+ break;
3776
+ case "verbose":
3777
+ diagLogLevel = api.DiagLogLevel.VERBOSE;
3778
+ break;
3779
+ case "all":
3780
+ diagLogLevel = api.DiagLogLevel.ALL;
3781
+ break;
3782
+ default:
3783
+ diagLogLevel = api.DiagLogLevel.NONE;
3784
+ }
3785
+ api.diag.setLogger(new api.DiagConsoleLogger(), diagLogLevel);
3786
+ }
3787
+ __name(setLogLevel, "setLogLevel");
3788
+
3789
+ // src/v3/otel/index.ts
3790
+ function recordSpanException(span, error) {
3791
+ if (error instanceof Error) {
3792
+ span.recordException(error);
3793
+ } else if (typeof error === "string") {
3794
+ span.recordException(new Error(error));
3795
+ } else {
3796
+ span.recordException(new Error(JSON.stringify(error)));
3797
+ }
3798
+ span.setStatus({
3799
+ code: api.SpanStatusCode.ERROR
3800
+ });
3801
+ }
3802
+ __name(recordSpanException, "recordSpanException");
3803
+ function parsePacket(value) {
3804
+ if (!value.data) {
3805
+ return void 0;
3806
+ }
3807
+ switch (value.dataType) {
3808
+ case "application/json":
3809
+ return JSON.parse(value.data);
3810
+ case "application/super+json":
3811
+ return superjson.parse(value.data);
3812
+ case "text/plain":
3813
+ return value.data;
3814
+ case "application/store":
3815
+ throw new Error(`Cannot parse an application/store packet (${value.data}). Needs to be imported first.`);
3816
+ default:
3817
+ return value.data;
3818
+ }
3819
+ }
3820
+ __name(parsePacket, "parsePacket");
3821
+ function stringifyIO(value) {
3822
+ if (value === void 0) {
3823
+ return {
3824
+ dataType: "application/json"
3825
+ };
3826
+ }
3827
+ if (typeof value === "string") {
3828
+ return {
3829
+ data: value,
3830
+ dataType: "text/plain"
3831
+ };
3832
+ }
3833
+ return {
3834
+ data: superjson.stringify(value),
3835
+ dataType: "application/super+json"
3836
+ };
3837
+ }
3838
+ __name(stringifyIO, "stringifyIO");
3839
+ async function conditionallyExportPacket(packet, pathPrefix, tracer) {
3840
+ if (apiClientManager.client) {
3841
+ const { needsOffloading, size } = packetRequiresOffloading(packet);
3842
+ if (needsOffloading) {
3843
+ if (!tracer) {
3844
+ return await exportPacket(packet, pathPrefix);
3845
+ } else {
3846
+ const result = await tracer.startActiveSpan("store.uploadOutput", async (span) => {
3847
+ return await exportPacket(packet, pathPrefix);
3848
+ }, {
3849
+ attributes: {
3850
+ byteLength: size,
3851
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-upload"
3852
+ }
3853
+ });
3854
+ return result ?? packet;
3855
+ }
3856
+ }
3857
+ }
3858
+ return packet;
3859
+ }
3860
+ __name(conditionallyExportPacket, "conditionallyExportPacket");
3861
+ function packetRequiresOffloading(packet) {
3862
+ if (!packet.data) {
3863
+ return {
3864
+ needsOffloading: false,
3865
+ size: 0
3866
+ };
3867
+ }
3868
+ const byteSize = Buffer.byteLength(packet.data, "utf8");
3869
+ return {
3870
+ needsOffloading: byteSize >= OFFLOAD_IO_PACKET_LENGTH_LIMIT,
3871
+ size: byteSize
3872
+ };
3873
+ }
3874
+ __name(packetRequiresOffloading, "packetRequiresOffloading");
3875
+ async function exportPacket(packet, pathPrefix) {
3876
+ const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
3877
+ const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
3878
+ if (presignedResponse.ok) {
3879
+ const uploadResponse = await fetch(presignedResponse.data.presignedUrl, {
3880
+ method: "PUT",
3881
+ headers: {
3882
+ "Content-Type": packet.dataType
3883
+ },
3884
+ body: packet.data
3885
+ });
3886
+ if (!uploadResponse.ok) {
3887
+ throw new Error(`Failed to upload output to ${presignedResponse.data.presignedUrl}: ${uploadResponse.statusText}`);
3888
+ }
3889
+ return {
3890
+ data: filename,
3891
+ dataType: "application/store"
3892
+ };
3893
+ }
3894
+ return packet;
3895
+ }
3896
+ __name(exportPacket, "exportPacket");
3897
+ async function conditionallyImportPacket(packet, tracer) {
3898
+ if (packet.dataType !== "application/store") {
3899
+ return packet;
3900
+ }
3901
+ if (!tracer) {
3902
+ return await importPacket(packet);
3903
+ } else {
3904
+ const result = await tracer.startActiveSpan("store.downloadPayload", async (span) => {
3905
+ return await importPacket(packet, span);
3906
+ }, {
3907
+ attributes: {
3908
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
3909
+ }
3910
+ });
3911
+ return result ?? packet;
3912
+ }
3913
+ }
3914
+ __name(conditionallyImportPacket, "conditionallyImportPacket");
3915
+ async function importPacket(packet, span) {
3916
+ if (!packet.data) {
3917
+ return packet;
3918
+ }
3919
+ if (!apiClientManager.client) {
3920
+ return packet;
3921
+ }
3922
+ const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
3923
+ if (presignedResponse.ok) {
3924
+ const response = await fetch(presignedResponse.data.presignedUrl);
3925
+ if (!response.ok) {
3926
+ throw new Error(`Failed to import packet ${presignedResponse.data.presignedUrl}: ${response.statusText}`);
3927
+ }
3928
+ const data = await response.text();
3929
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
3930
+ return {
3931
+ data,
3932
+ dataType: response.headers.get("content-type") ?? "application/json"
3933
+ };
3934
+ }
3935
+ return packet;
3936
+ }
3937
+ __name(importPacket, "importPacket");
3938
+ function createPacketAttributes(packet, dataKey, dataTypeKey) {
3939
+ if (!packet.data) {
3940
+ return {};
3941
+ }
3942
+ switch (packet.dataType) {
3943
+ case "application/json":
3944
+ return {
3945
+ ...flattenAttributes(packet, dataKey),
3946
+ [dataTypeKey]: packet.dataType
3947
+ };
3948
+ case "application/super+json":
3949
+ const parsed = superjson.parse(packet.data);
3950
+ const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
3951
+ return {
3952
+ ...flattenAttributes(jsonified, dataKey),
3953
+ [dataTypeKey]: "application/json"
3954
+ };
3955
+ case "application/store":
3956
+ return {
3957
+ [dataKey]: packet.data,
3958
+ [dataTypeKey]: packet.dataType
3959
+ };
3960
+ case "text/plain":
3961
+ return {
3962
+ [SemanticInternalAttributes.OUTPUT]: packet.data,
3963
+ [SemanticInternalAttributes.OUTPUT_TYPE]: packet.dataType
3964
+ };
3965
+ default:
3966
+ return {};
3967
+ }
3968
+ }
3969
+ __name(createPacketAttributes, "createPacketAttributes");
3970
+ function createPackageAttributesAsJson(data, dataType) {
3971
+ if (typeof data === "string" || typeof data === "number" || typeof data === "boolean" || data === null || data === void 0) {
3972
+ return data;
3973
+ }
3974
+ switch (dataType) {
3975
+ case "application/json":
3976
+ return imposeAttributeLimits(flattenAttributes(data, void 0));
3977
+ case "application/super+json":
3978
+ const deserialized = superjson.deserialize(data);
3979
+ const jsonify = JSON.parse(JSON.stringify(deserialized, safeReplacer));
3980
+ return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
3981
+ case "application/store":
3982
+ return data;
3983
+ default:
3984
+ return {};
3985
+ }
3986
+ }
3987
+ __name(createPackageAttributesAsJson, "createPackageAttributesAsJson");
3988
+ function prettyPrintPacket(rawData, dataType) {
3989
+ if (rawData === void 0) {
3990
+ return "";
3991
+ }
3992
+ if (dataType === "application/super+json") {
3993
+ return prettyPrintPacket(superjson.deserialize(rawData), "application/json");
3994
+ }
3995
+ if (dataType === "application/json") {
3996
+ return JSON.stringify(rawData, safeReplacer, 2);
3997
+ }
3998
+ if (typeof rawData === "string") {
3999
+ return rawData;
4000
+ }
4001
+ return JSON.stringify(rawData, safeReplacer, 2);
4002
+ }
4003
+ __name(prettyPrintPacket, "prettyPrintPacket");
4004
+ function safeReplacer(key, value) {
4005
+ if (typeof value === "bigint") {
4006
+ return value.toString();
4007
+ }
4008
+ if (value instanceof RegExp) {
4009
+ return value.toString();
4010
+ }
4011
+ if (value instanceof Set) {
4012
+ return Array.from(value);
4013
+ }
4014
+ if (value instanceof Map) {
4015
+ const obj = {};
4016
+ value.forEach((v, k) => {
4017
+ obj[k] = v;
4018
+ });
4019
+ return obj;
4020
+ }
4021
+ return value;
4022
+ }
4023
+ __name(safeReplacer, "safeReplacer");
4024
+ function getPacketExtension(outputType) {
4025
+ switch (outputType) {
4026
+ case "application/json":
4027
+ return "json";
4028
+ case "application/super+json":
4029
+ return "json";
4030
+ case "text/plain":
4031
+ return "txt";
4032
+ default:
4033
+ return "txt";
4034
+ }
4035
+ }
4036
+ __name(getPacketExtension, "getPacketExtension");
4037
+
4038
+ // src/v3/workers/taskExecutor.ts
4039
+ var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
4040
+ var _TaskExecutor = class _TaskExecutor {
4041
+ constructor(task, options) {
4042
+ __privateAdd(this, _callRun);
4043
+ __privateAdd(this, _callTaskInit);
4044
+ __privateAdd(this, _callTaskCleanup);
4045
+ __privateAdd(this, _handleError);
4046
+ this.task = task;
4047
+ this._tracingSDK = options.tracingSDK;
4048
+ this._tracer = options.tracer;
4049
+ this._consoleInterceptor = options.consoleInterceptor;
4050
+ this._config = options.projectConfig;
4051
+ this._importedConfig = options.importedConfig;
4052
+ this._handleErrorFn = options.handleErrorFn;
4053
+ }
4054
+ async execute(execution, worker, traceContext) {
4055
+ const ctx = TaskRunContext.parse(execution);
4056
+ const attemptMessage = `Attempt ${execution.attempt.number}`;
4057
+ const originalPacket = {
4058
+ data: execution.run.payload,
4059
+ dataType: execution.run.payloadType
4060
+ };
4061
+ const result = await taskContextManager.runWith({
4062
+ ctx,
4063
+ worker
4064
+ }, async () => {
4065
+ this._tracingSDK.asyncResourceDetector.resolveWithAttributes({
4066
+ ...taskContextManager.attributes,
4067
+ [SemanticInternalAttributes.SDK_VERSION]: this.task.packageVersion,
4068
+ [SemanticInternalAttributes.SDK_LANGUAGE]: "typescript"
4069
+ });
4070
+ return await this._tracer.startActiveSpan(attemptMessage, async (span) => {
4071
+ return await this._consoleInterceptor.intercept(console, async () => {
4072
+ let parsedPayload;
4073
+ let initOutput;
4074
+ try {
4075
+ const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
4076
+ parsedPayload = parsePacket(payloadPacket);
4077
+ initOutput = await __privateMethod(this, _callTaskInit, callTaskInit_fn).call(this, parsedPayload, ctx);
4078
+ const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
4079
+ try {
4080
+ const stringifiedOutput = stringifyIO(output);
4081
+ const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
4082
+ span.setAttributes(createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE));
4083
+ return {
4084
+ ok: true,
4085
+ id: execution.attempt.id,
4086
+ output: finalOutput.data,
4087
+ outputType: finalOutput.dataType
4088
+ };
4089
+ } catch (stringifyError) {
4090
+ recordSpanException(span, stringifyError);
4091
+ return {
4092
+ ok: false,
4093
+ id: execution.attempt.id,
4094
+ error: {
4095
+ type: "INTERNAL_ERROR",
4096
+ code: TaskRunErrorCodes.TASK_OUTPUT_ERROR,
4097
+ message: stringifyError instanceof Error ? stringifyError.message : typeof stringifyError === "string" ? stringifyError : void 0
4098
+ }
4099
+ };
4100
+ }
4101
+ } catch (runError) {
4102
+ try {
4103
+ const handleErrorResult = await __privateMethod(this, _handleError, handleError_fn).call(this, execution, runError, parsedPayload, ctx);
4104
+ recordSpanException(span, handleErrorResult.error ?? runError);
4105
+ return {
4106
+ id: execution.attempt.id,
4107
+ ok: false,
4108
+ error: handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError),
4109
+ retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
4110
+ skippedRetrying: handleErrorResult.status === "skipped"
4111
+ };
4112
+ } catch (handleErrorError) {
4113
+ recordSpanException(span, handleErrorError);
4114
+ return {
4115
+ ok: false,
4116
+ id: execution.attempt.id,
4117
+ error: {
4118
+ type: "INTERNAL_ERROR",
4119
+ code: TaskRunErrorCodes.HANDLE_ERROR_ERROR,
4120
+ message: handleErrorError instanceof Error ? handleErrorError.message : typeof handleErrorError === "string" ? handleErrorError : void 0
4121
+ }
4122
+ };
4123
+ }
4124
+ } finally {
4125
+ await __privateMethod(this, _callTaskCleanup, callTaskCleanup_fn).call(this, parsedPayload, ctx, initOutput);
4126
+ }
4127
+ });
4128
+ }, {
4129
+ kind: api.SpanKind.CONSUMER,
4130
+ attributes: {
4131
+ [SemanticInternalAttributes.STYLE_ICON]: "attempt",
4132
+ ...accessoryAttributes({
4133
+ items: [
4134
+ {
4135
+ text: ctx.task.filePath
4136
+ },
4137
+ {
4138
+ text: `${ctx.task.exportName}.run()`
4139
+ }
4140
+ ],
4141
+ style: "codepath"
4142
+ })
4143
+ }
4144
+ }, this._tracer.extractContext(traceContext));
4145
+ });
4146
+ return result;
4147
+ }
4148
+ };
4149
+ _callRun = new WeakSet();
4150
+ callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
4151
+ const runFn = this.task.fns.run;
4152
+ const middlewareFn = this.task.fns.middleware;
4153
+ if (!runFn) {
4154
+ throw new Error("Task does not have a run function");
4155
+ }
4156
+ if (!middlewareFn) {
4157
+ return runFn(payload, {
4158
+ ctx
4159
+ });
4160
+ }
4161
+ return middlewareFn(payload, {
4162
+ ctx,
4163
+ next: async () => runFn(payload, {
4164
+ ctx,
4165
+ init
4166
+ })
4167
+ });
4168
+ }, "#callRun");
4169
+ _callTaskInit = new WeakSet();
4170
+ callTaskInit_fn = /* @__PURE__ */ __name(async function(payload1, ctx1) {
4171
+ const initFn = this.task.fns.init;
4172
+ if (!initFn) {
4173
+ return {};
4174
+ }
4175
+ return this._tracer.startActiveSpan("init", async (span) => {
4176
+ return await initFn(payload1, {
4177
+ ctx: ctx1
4178
+ });
4179
+ });
4180
+ }, "#callTaskInit");
4181
+ _callTaskCleanup = new WeakSet();
4182
+ callTaskCleanup_fn = /* @__PURE__ */ __name(async function(payload2, ctx2, init1) {
4183
+ const cleanupFn = this.task.fns.cleanup;
4184
+ if (!cleanupFn) {
4185
+ return;
4186
+ }
4187
+ return this._tracer.startActiveSpan("cleanup", async (span) => {
4188
+ return await cleanupFn(payload2, {
4189
+ ctx: ctx2,
4190
+ init: init1
4191
+ });
4192
+ });
4193
+ }, "#callTaskCleanup");
4194
+ _handleError = new WeakSet();
4195
+ handleError_fn = /* @__PURE__ */ __name(async function(execution, error, payload3, ctx3) {
4196
+ const retriesConfig = this._importedConfig?.retries ?? this._config.retries;
4197
+ const retry = this.task.retry ?? retriesConfig?.default;
4198
+ if (!retry) {
4199
+ return {
4200
+ status: "noop"
4201
+ };
4202
+ }
4203
+ const delay = calculateNextRetryDelay(retry, execution.attempt.number);
4204
+ if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
4205
+ return {
4206
+ status: "skipped"
4207
+ };
4208
+ }
4209
+ return this._tracer.startActiveSpan("handleError()", async (span) => {
4210
+ const handleErrorResult = this.task.fns.handleError ? await this.task.fns.handleError(payload3, error, {
4211
+ ctx: ctx3,
4212
+ retry,
4213
+ retryDelayInMs: delay,
4214
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
4215
+ }) : this._importedConfig ? await this._handleErrorFn?.(payload3, error, {
4216
+ ctx: ctx3,
4217
+ retry,
4218
+ retryDelayInMs: delay,
4219
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
4220
+ }) : void 0;
4221
+ if (!handleErrorResult) {
4222
+ return typeof delay === "undefined" ? {
4223
+ status: "noop"
4224
+ } : {
4225
+ status: "retry",
4226
+ retry: {
4227
+ timestamp: Date.now() + delay,
4228
+ delay
4229
+ }
4230
+ };
4231
+ }
4232
+ if (handleErrorResult.skipRetrying) {
4233
+ return {
4234
+ status: "skipped",
4235
+ error: handleErrorResult.error
4236
+ };
4237
+ }
4238
+ if (typeof handleErrorResult.retryAt !== "undefined") {
4239
+ return {
4240
+ status: "retry",
4241
+ retry: {
4242
+ timestamp: handleErrorResult.retryAt.getTime(),
4243
+ delay: handleErrorResult.retryAt.getTime() - Date.now()
4244
+ },
4245
+ error: handleErrorResult.error
4246
+ };
4247
+ }
4248
+ if (typeof handleErrorResult.retryDelayInMs === "number") {
4249
+ return {
4250
+ status: "retry",
4251
+ retry: {
4252
+ timestamp: Date.now() + handleErrorResult.retryDelayInMs,
4253
+ delay: handleErrorResult.retryDelayInMs
4254
+ },
4255
+ error: handleErrorResult.error
4256
+ };
4257
+ }
4258
+ if (handleErrorResult.retry && typeof handleErrorResult.retry === "object") {
4259
+ const delay2 = calculateNextRetryDelay(handleErrorResult.retry, execution.attempt.number);
4260
+ return typeof delay2 === "undefined" ? {
4261
+ status: "noop",
4262
+ error: handleErrorResult.error
4263
+ } : {
4264
+ status: "retry",
4265
+ retry: {
4266
+ timestamp: Date.now() + delay2,
4267
+ delay: delay2
4268
+ },
4269
+ error: handleErrorResult.error
4270
+ };
4271
+ }
4272
+ return {
4273
+ status: "noop",
4274
+ error: handleErrorResult.error
4275
+ };
4276
+ }, {
4277
+ attributes: {
4278
+ [SemanticInternalAttributes.STYLE_ICON]: "exclamation-circle"
4279
+ }
4280
+ });
4281
+ }, "#handleError");
4282
+ __name(_TaskExecutor, "TaskExecutor");
4283
+ var TaskExecutor = _TaskExecutor;
4284
+
4285
+ // package.json
4286
+ var dependencies = {
4287
+ "@google-cloud/precise-date": "^4.0.0",
4288
+ "@opentelemetry/api": "^1.8.0",
4289
+ "@opentelemetry/api-logs": "^0.48.0",
4290
+ "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
4291
+ "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
4292
+ "@opentelemetry/instrumentation": "^0.49.1",
4293
+ "@opentelemetry/resources": "^1.22.0",
4294
+ "@opentelemetry/sdk-logs": "^0.49.1",
4295
+ "@opentelemetry/sdk-node": "^0.49.1",
4296
+ "@opentelemetry/sdk-trace-base": "^1.22.0",
4297
+ "@opentelemetry/sdk-trace-node": "^1.22.0",
4298
+ "@opentelemetry/semantic-conventions": "^1.22.0",
4299
+ "humanize-duration": "^3.27.3",
4300
+ "socket.io": "^4.7.4",
4301
+ "socket.io-client": "^4.7.4",
4302
+ superjson: "^2.2.1",
4303
+ ulidx: "^2.2.1",
4304
+ zod: "3.22.3",
4305
+ "zod-error": "1.5.0"
4306
+ };
4307
+
4308
+ // src/v3/utils/detectDependencyVersion.ts
4309
+ function detectDependencyVersion(dependency) {
4310
+ return dependencies[dependency];
4311
+ }
4312
+ __name(detectDependencyVersion, "detectDependencyVersion");
4313
+
4314
+ // src/v3/index.ts
4315
+ function parseTriggerTaskRequestBody(body) {
4316
+ return TriggerTaskRequestBody.safeParse(body);
4317
+ }
4318
+ __name(parseTriggerTaskRequestBody, "parseTriggerTaskRequestBody");
4319
+ function parseBatchTriggerTaskRequestBody(body) {
4320
+ return BatchTriggerTaskRequestBody.safeParse(body);
4321
+ }
4322
+ __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
4323
+
4324
+ exports.ApiClient = ApiClient;
4325
+ exports.ApiClientManager = ApiClientManager;
4326
+ exports.BackgroundWorkerClientMessages = BackgroundWorkerClientMessages;
4327
+ exports.BackgroundWorkerMetadata = BackgroundWorkerMetadata;
4328
+ exports.BackgroundWorkerProperties = BackgroundWorkerProperties;
4329
+ exports.BackgroundWorkerServerMessages = BackgroundWorkerServerMessages;
4330
+ exports.BatchTaskRunExecutionResult = BatchTaskRunExecutionResult;
4331
+ exports.BatchTriggerTaskRequestBody = BatchTriggerTaskRequestBody;
4332
+ exports.BatchTriggerTaskResponse = BatchTriggerTaskResponse;
4333
+ exports.CancellationSpanEvent = CancellationSpanEvent;
4334
+ exports.ClientToSharedQueueMessages = ClientToSharedQueueMessages;
4335
+ exports.Config = Config;
4336
+ exports.ConsoleInterceptor = ConsoleInterceptor;
4337
+ exports.CoordinatorToPlatformMessages = CoordinatorToPlatformMessages;
4338
+ exports.CoordinatorToProdWorkerMessages = CoordinatorToProdWorkerMessages;
4339
+ exports.CreateAuthorizationCodeResponseSchema = CreateAuthorizationCodeResponseSchema;
4340
+ exports.CreateBackgroundWorkerRequestBody = CreateBackgroundWorkerRequestBody;
4341
+ exports.CreateBackgroundWorkerResponse = CreateBackgroundWorkerResponse;
4342
+ exports.CreateUploadPayloadUrlResponseBody = CreateUploadPayloadUrlResponseBody;
4343
+ exports.DevRuntimeManager = DevRuntimeManager;
4344
+ exports.EventFilter = EventFilter;
4345
+ exports.ExceptionEventProperties = ExceptionEventProperties;
4346
+ exports.ExceptionSpanEvent = ExceptionSpanEvent;
4347
+ exports.ExternalBuildData = ExternalBuildData;
4348
+ exports.FetchRetryBackoffStrategy = FetchRetryBackoffStrategy;
4349
+ exports.FetchRetryByStatusOptions = FetchRetryByStatusOptions;
4350
+ exports.FetchRetryHeadersStrategy = FetchRetryHeadersStrategy;
4351
+ exports.FetchRetryOptions = FetchRetryOptions;
4352
+ exports.FetchRetryStrategy = FetchRetryStrategy;
4353
+ exports.FetchTimeoutOptions = FetchTimeoutOptions;
4354
+ exports.FixedWindowRateLimit = FixedWindowRateLimit;
4355
+ exports.GetBatchResponseBody = GetBatchResponseBody;
4356
+ exports.GetDeploymentResponseBody = GetDeploymentResponseBody;
4357
+ exports.GetEnvironmentVariablesResponseBody = GetEnvironmentVariablesResponseBody;
4358
+ exports.GetPersonalAccessTokenRequestSchema = GetPersonalAccessTokenRequestSchema;
4359
+ exports.GetPersonalAccessTokenResponseSchema = GetPersonalAccessTokenResponseSchema;
4360
+ exports.GetProjectEnvResponse = GetProjectEnvResponse;
4361
+ exports.GetProjectResponseBody = GetProjectResponseBody;
4362
+ exports.GetProjectsResponseBody = GetProjectsResponseBody;
4363
+ exports.ImageDetailsMetadata = ImageDetailsMetadata;
4364
+ exports.InitializeDeploymentRequestBody = InitializeDeploymentRequestBody;
4365
+ exports.InitializeDeploymentResponseBody = InitializeDeploymentResponseBody;
4366
+ exports.Machine = Machine;
4367
+ exports.OFFLOAD_IO_PACKET_LENGTH_LIMIT = OFFLOAD_IO_PACKET_LENGTH_LIMIT;
4368
+ exports.OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT;
4369
+ exports.OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT;
4370
+ exports.OTEL_LINK_COUNT_LIMIT = OTEL_LINK_COUNT_LIMIT;
4371
+ exports.OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = OTEL_LOG_ATTRIBUTE_COUNT_LIMIT;
4372
+ exports.OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT;
4373
+ exports.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT;
4374
+ exports.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT;
4375
+ exports.OTEL_SPAN_EVENT_COUNT_LIMIT = OTEL_SPAN_EVENT_COUNT_LIMIT;
4376
+ exports.OtelTaskLogger = OtelTaskLogger;
4377
+ exports.OtherSpanEvent = OtherSpanEvent;
4378
+ exports.PRIMARY_VARIANT = PRIMARY_VARIANT;
4379
+ exports.PlatformToCoordinatorMessages = PlatformToCoordinatorMessages;
4380
+ exports.PlatformToProviderMessages = PlatformToProviderMessages;
4381
+ exports.ProdChildToWorkerMessages = ProdChildToWorkerMessages;
4382
+ exports.ProdRuntimeManager = ProdRuntimeManager;
4383
+ exports.ProdTaskRunExecution = ProdTaskRunExecution;
4384
+ exports.ProdTaskRunExecutionPayload = ProdTaskRunExecutionPayload;
4385
+ exports.ProdWorkerSocketData = ProdWorkerSocketData;
4386
+ exports.ProdWorkerToChildMessages = ProdWorkerToChildMessages;
4387
+ exports.ProdWorkerToCoordinatorMessages = ProdWorkerToCoordinatorMessages;
4388
+ exports.ProviderToPlatformMessages = ProviderToPlatformMessages;
4389
+ exports.QueueOptions = QueueOptions;
4390
+ exports.RateLimitOptions = RateLimitOptions;
4391
+ exports.RetryOptions = RetryOptions;
4392
+ exports.SemanticInternalAttributes = SemanticInternalAttributes;
4393
+ exports.SharedQueueToClientMessages = SharedQueueToClientMessages;
4394
+ exports.SimpleStructuredLogger = SimpleStructuredLogger;
4395
+ exports.SlidingWindowRateLimit = SlidingWindowRateLimit;
4396
+ exports.SpanEvent = SpanEvent;
4397
+ exports.SpanEvents = SpanEvents;
4398
+ exports.SpanMessagingEvent = SpanMessagingEvent;
4399
+ exports.StartDeploymentIndexingRequestBody = StartDeploymentIndexingRequestBody;
4400
+ exports.StartDeploymentIndexingResponseBody = StartDeploymentIndexingResponseBody;
4401
+ exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
4402
+ exports.TaskEventStyle = TaskEventStyle;
4403
+ exports.TaskExecutor = TaskExecutor;
4404
+ exports.TaskMetadata = TaskMetadata;
4405
+ exports.TaskMetadataWithFilePath = TaskMetadataWithFilePath;
4406
+ exports.TaskResource = TaskResource;
4407
+ exports.TaskRun = TaskRun;
4408
+ exports.TaskRunBuiltInError = TaskRunBuiltInError;
4409
+ exports.TaskRunContext = TaskRunContext;
4410
+ exports.TaskRunCustomErrorObject = TaskRunCustomErrorObject;
4411
+ exports.TaskRunError = TaskRunError;
4412
+ exports.TaskRunErrorCodes = TaskRunErrorCodes;
4413
+ exports.TaskRunExecution = TaskRunExecution;
4414
+ exports.TaskRunExecutionAttempt = TaskRunExecutionAttempt;
4415
+ exports.TaskRunExecutionBatch = TaskRunExecutionBatch;
4416
+ exports.TaskRunExecutionEnvironment = TaskRunExecutionEnvironment;
4417
+ exports.TaskRunExecutionOrganization = TaskRunExecutionOrganization;
4418
+ exports.TaskRunExecutionPayload = TaskRunExecutionPayload;
4419
+ exports.TaskRunExecutionProject = TaskRunExecutionProject;
4420
+ exports.TaskRunExecutionQueue = TaskRunExecutionQueue;
4421
+ exports.TaskRunExecutionResult = TaskRunExecutionResult;
4422
+ exports.TaskRunExecutionRetry = TaskRunExecutionRetry;
4423
+ exports.TaskRunExecutionTask = TaskRunExecutionTask;
4424
+ exports.TaskRunFailedExecutionResult = TaskRunFailedExecutionResult;
4425
+ exports.TaskRunInternalError = TaskRunInternalError;
4426
+ exports.TaskRunStringError = TaskRunStringError;
4427
+ exports.TaskRunSuccessfulExecutionResult = TaskRunSuccessfulExecutionResult;
4428
+ exports.TracingSDK = TracingSDK;
4429
+ exports.TriggerTaskRequestBody = TriggerTaskRequestBody;
4430
+ exports.TriggerTaskResponse = TriggerTaskResponse;
4431
+ exports.TriggerTracer = TriggerTracer;
4432
+ exports.UncaughtExceptionMessage = UncaughtExceptionMessage;
4433
+ exports.WaitReason = WaitReason;
4434
+ exports.WhoAmIResponseSchema = WhoAmIResponseSchema;
4435
+ exports.ZodIpcConnection = ZodIpcConnection;
4436
+ exports.ZodMessageHandler = ZodMessageHandler;
4437
+ exports.ZodMessageSchema = ZodMessageSchema;
4438
+ exports.ZodMessageSender = ZodMessageSender;
4439
+ exports.ZodNamespace = ZodNamespace;
4440
+ exports.ZodSocketConnection = ZodSocketConnection;
4441
+ exports.ZodSocketMessageHandler = ZodSocketMessageHandler;
4442
+ exports.ZodSocketMessageSender = ZodSocketMessageSender;
4443
+ exports.accessoryAttributes = accessoryAttributes;
4444
+ exports.apiClientManager = apiClientManager;
4445
+ exports.calculateNextRetryDelay = calculateNextRetryDelay;
4446
+ exports.calculatePreciseDateHrTime = calculatePreciseDateHrTime;
4447
+ exports.calculateResetAt = calculateResetAt2;
4448
+ exports.childToWorkerMessages = childToWorkerMessages;
4449
+ exports.clientWebsocketMessages = clientWebsocketMessages;
4450
+ exports.conditionallyExportPacket = conditionallyExportPacket;
4451
+ exports.conditionallyImportPacket = conditionallyImportPacket;
4452
+ exports.correctErrorStackTrace = correctErrorStackTrace;
4453
+ exports.createErrorTaskError = createErrorTaskError;
4454
+ exports.createPackageAttributesAsJson = createPackageAttributesAsJson;
4455
+ exports.createPacketAttributes = createPacketAttributes;
4456
+ exports.defaultFetchRetryOptions = defaultFetchRetryOptions;
4457
+ exports.defaultRetryOptions = defaultRetryOptions;
4458
+ exports.detectDependencyVersion = detectDependencyVersion;
4459
+ exports.eventFilterMatches = eventFilterMatches;
4460
+ exports.flattenAttributes = flattenAttributes;
4461
+ exports.formatDuration = formatDuration;
4462
+ exports.formatDurationInDays = formatDurationInDays;
4463
+ exports.formatDurationMilliseconds = formatDurationMilliseconds;
4464
+ exports.formatDurationNanoseconds = formatDurationNanoseconds;
4465
+ exports.getEnvVar = getEnvVar;
4466
+ exports.iconStringForSeverity = iconStringForSeverity;
4467
+ exports.imposeAttributeLimits = imposeAttributeLimits;
4468
+ exports.isCancellationSpanEvent = isCancellationSpanEvent;
4469
+ exports.isExceptionSpanEvent = isExceptionSpanEvent;
4470
+ exports.logger = logger;
4471
+ exports.millisecondsToNanoseconds = millisecondsToNanoseconds;
4472
+ exports.nanosecondsToMilliseconds = nanosecondsToMilliseconds;
4473
+ exports.omit = omit;
4474
+ exports.packetRequiresOffloading = packetRequiresOffloading;
4475
+ exports.parseBatchTriggerTaskRequestBody = parseBatchTriggerTaskRequestBody;
4476
+ exports.parseError = parseError;
4477
+ exports.parsePacket = parsePacket;
4478
+ exports.parseTriggerTaskRequestBody = parseTriggerTaskRequestBody;
4479
+ exports.preciseDateOriginNow = preciseDateOriginNow;
4480
+ exports.prettyPrintPacket = prettyPrintPacket;
4481
+ exports.primitiveValueOrflattenedAttributes = primitiveValueOrflattenedAttributes;
4482
+ exports.recordSpanException = recordSpanException;
4483
+ exports.runtime = runtime;
4484
+ exports.serverWebsocketMessages = serverWebsocketMessages;
4485
+ exports.stringPatternMatchers = stringPatternMatchers;
4486
+ exports.stringifyIO = stringifyIO;
4487
+ exports.taskContextManager = taskContextManager;
4488
+ exports.unflattenAttributes = unflattenAttributes;
4489
+ exports.workerToChildMessages = workerToChildMessages;
4490
+ //# sourceMappingURL=out.js.map
4491
+ //# sourceMappingURL=index.js.map