@trigger.dev/core 0.0.0-prerelease-20240418145424 → 0.0.0-prerelease-20240528152213

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/catalog-BUwiuDbt.d.mts +202 -0
  2. package/dist/catalog-eKgqBHUA.d.ts +202 -0
  3. package/dist/index.d.mts +60 -1
  4. package/dist/index.d.ts +60 -1
  5. package/dist/index.js +7 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +7 -1
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/manager-uPyMRN8k.d.mts +1159 -0
  10. package/dist/manager-uPyMRN8k.d.ts +1159 -0
  11. package/dist/messages-l9PdIyKF.d.mts +16741 -0
  12. package/dist/messages-l9PdIyKF.d.ts +16741 -0
  13. package/dist/schemas-b8tRw8dX.d.mts +2331 -0
  14. package/dist/schemas-b8tRw8dX.d.ts +2331 -0
  15. package/dist/v3/dev/index.d.mts +28 -0
  16. package/dist/v3/dev/index.d.ts +28 -0
  17. package/dist/v3/dev/index.js +93 -0
  18. package/dist/v3/dev/index.js.map +1 -0
  19. package/dist/v3/dev/index.mjs +91 -0
  20. package/dist/v3/dev/index.mjs.map +1 -0
  21. package/dist/v3/index.d.mts +517 -17166
  22. package/dist/v3/index.d.ts +517 -17166
  23. package/dist/v3/index.js +1591 -2828
  24. package/dist/v3/index.js.map +1 -1
  25. package/dist/v3/index.mjs +1580 -2802
  26. package/dist/v3/index.mjs.map +1 -1
  27. package/dist/v3/otel/index.js +85 -44
  28. package/dist/v3/otel/index.js.map +1 -1
  29. package/dist/v3/otel/index.mjs +85 -44
  30. package/dist/v3/otel/index.mjs.map +1 -1
  31. package/dist/v3/prod/index.d.mts +45 -0
  32. package/dist/v3/prod/index.d.ts +45 -0
  33. package/dist/v3/prod/index.js +304 -0
  34. package/dist/v3/prod/index.js.map +1 -0
  35. package/dist/v3/prod/index.mjs +302 -0
  36. package/dist/v3/prod/index.mjs.map +1 -0
  37. package/dist/v3/utils/structuredLogger.d.mts +31 -0
  38. package/dist/v3/utils/structuredLogger.d.ts +31 -0
  39. package/dist/v3/utils/structuredLogger.js +88 -0
  40. package/dist/v3/utils/structuredLogger.js.map +1 -0
  41. package/dist/v3/utils/structuredLogger.mjs +86 -0
  42. package/dist/v3/utils/structuredLogger.mjs.map +1 -0
  43. package/dist/v3/workers/index.d.mts +96 -0
  44. package/dist/v3/workers/index.d.ts +96 -0
  45. package/dist/v3/workers/index.js +2831 -0
  46. package/dist/v3/workers/index.js.map +1 -0
  47. package/dist/v3/workers/index.mjs +2815 -0
  48. package/dist/v3/workers/index.mjs.map +1 -0
  49. package/dist/v3/zodIpc.d.mts +32 -0
  50. package/dist/v3/zodIpc.d.ts +32 -0
  51. package/dist/v3/zodIpc.js +268 -0
  52. package/dist/v3/zodIpc.js.map +1 -0
  53. package/dist/v3/zodIpc.mjs +266 -0
  54. package/dist/v3/zodIpc.mjs.map +1 -0
  55. package/dist/v3/zodMessageHandler.d.mts +69 -0
  56. package/dist/v3/zodMessageHandler.d.ts +69 -0
  57. package/dist/v3/zodMessageHandler.js +168 -0
  58. package/dist/v3/zodMessageHandler.js.map +1 -0
  59. package/dist/v3/zodMessageHandler.mjs +163 -0
  60. package/dist/v3/zodMessageHandler.mjs.map +1 -0
  61. package/dist/v3/zodNamespace.d.mts +3663 -0
  62. package/dist/v3/zodNamespace.d.ts +3663 -0
  63. package/dist/v3/zodNamespace.js +366 -0
  64. package/dist/v3/zodNamespace.js.map +1 -0
  65. package/dist/v3/zodNamespace.mjs +364 -0
  66. package/dist/v3/zodNamespace.mjs.map +1 -0
  67. package/dist/v3/zodSocket.d.mts +88 -0
  68. package/dist/v3/zodSocket.d.ts +88 -0
  69. package/dist/v3/zodSocket.js +319 -0
  70. package/dist/v3/zodSocket.js.map +1 -0
  71. package/dist/v3/zodSocket.mjs +315 -0
  72. package/dist/v3/zodSocket.mjs.map +1 -0
  73. package/dist/v3/zodfetch.d.mts +78 -0
  74. package/dist/v3/zodfetch.d.ts +78 -0
  75. package/dist/v3/zodfetch.js +446 -0
  76. package/dist/v3/zodfetch.js.map +1 -0
  77. package/dist/v3/zodfetch.mjs +433 -0
  78. package/dist/v3/zodfetch.mjs.map +1 -0
  79. package/package.json +77 -4
package/dist/v3/index.js CHANGED
@@ -1,30 +1,17 @@
1
1
  'use strict';
2
2
 
3
- var zod = require('zod');
4
3
  var api = require('@opentelemetry/api');
4
+ var zod = require('zod');
5
5
  var zodValidationError = require('zod-validation-error');
6
- var async_hooks = require('async_hooks');
7
- var socket_ioClient = require('socket.io-client');
8
- var crypto = require('crypto');
9
- var nodePath = require('path');
10
- var apiLogs = require('@opentelemetry/api-logs');
6
+ var formDataEncoder = require('form-data-encoder');
7
+ var stream = require('stream');
11
8
  var preciseDate = require('@google-cloud/precise-date');
9
+ var apiLogs = require('@opentelemetry/api-logs');
12
10
  var humanizeDuration = require('humanize-duration');
13
- var promises = require('timers/promises');
14
- var util = require('util');
15
- var exporterLogsOtlpHttp = require('@opentelemetry/exporter-logs-otlp-http');
16
- var exporterTraceOtlpHttp = require('@opentelemetry/exporter-trace-otlp-http');
17
- var instrumentation = require('@opentelemetry/instrumentation');
18
- var resources = require('@opentelemetry/resources');
19
- var sdkLogs = require('@opentelemetry/sdk-logs');
20
- var sdkTraceNode = require('@opentelemetry/sdk-trace-node');
21
- var semanticConventions = require('@opentelemetry/semantic-conventions');
22
11
 
23
12
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
24
13
 
25
- var nodePath__default = /*#__PURE__*/_interopDefault(nodePath);
26
14
  var humanizeDuration__default = /*#__PURE__*/_interopDefault(humanizeDuration);
27
- var util__default = /*#__PURE__*/_interopDefault(util);
28
15
 
29
16
  var __defProp = Object.defineProperty;
30
17
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -37,32 +24,178 @@ var __accessCheck = (obj, member, msg) => {
37
24
  if (!member.has(obj))
38
25
  throw TypeError("Cannot " + msg);
39
26
  };
40
- var __privateGet = (obj, member, getter) => {
41
- __accessCheck(obj, member, "read from private field");
42
- return getter ? getter.call(obj) : member.get(obj);
43
- };
44
27
  var __privateAdd = (obj, member, value) => {
45
28
  if (member.has(obj))
46
29
  throw TypeError("Cannot add the same private member more than once");
47
30
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
48
31
  };
49
- var __privateSet = (obj, member, value, setter) => {
50
- __accessCheck(obj, member, "write to private field");
51
- setter ? setter.call(obj, value) : member.set(obj, value);
52
- return value;
53
- };
54
- var __privateWrapper = (obj, member, setter, getter) => ({
55
- set _(value) {
56
- __privateSet(obj, member, value, setter);
57
- },
58
- get _() {
59
- return __privateGet(obj, member, getter);
60
- }
61
- });
62
32
  var __privateMethod = (obj, member, method) => {
63
33
  __accessCheck(obj, member, "access private method");
64
34
  return method;
65
35
  };
36
+
37
+ // package.json
38
+ var version = "0.0.0-prerelease-20240528152213";
39
+ var dependencies = {
40
+ "@google-cloud/precise-date": "^4.0.0",
41
+ "@opentelemetry/api": "^1.8.0",
42
+ "@opentelemetry/api-logs": "^0.48.0",
43
+ "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
44
+ "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
45
+ "@opentelemetry/instrumentation": "^0.49.1",
46
+ "@opentelemetry/resources": "^1.22.0",
47
+ "@opentelemetry/sdk-logs": "^0.49.1",
48
+ "@opentelemetry/sdk-node": "^0.49.1",
49
+ "@opentelemetry/sdk-trace-base": "^1.22.0",
50
+ "@opentelemetry/sdk-trace-node": "^1.22.0",
51
+ "@opentelemetry/semantic-conventions": "^1.22.0",
52
+ "form-data-encoder": "^4.0.2",
53
+ "humanize-duration": "^3.27.3",
54
+ "socket.io-client": "4.7.4",
55
+ superjson: "^2.2.1",
56
+ ulidx: "^2.2.1",
57
+ zod: "3.22.3",
58
+ "zod-error": "1.5.0",
59
+ "zod-validation-error": "^1.5.0"
60
+ };
61
+
62
+ // src/v3/apiErrors.ts
63
+ var _APIError = class _APIError extends Error {
64
+ constructor(status, error, message, headers) {
65
+ super(`${_APIError.makeMessage(status, error, message)}`);
66
+ this.status = status;
67
+ this.headers = headers;
68
+ const data = error;
69
+ this.error = data;
70
+ this.code = data?.["code"];
71
+ this.param = data?.["param"];
72
+ this.type = data?.["type"];
73
+ }
74
+ static makeMessage(status, error, message) {
75
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
76
+ if (status && msg) {
77
+ return `${status} ${msg}`;
78
+ }
79
+ if (status) {
80
+ return `${status} status code (no body)`;
81
+ }
82
+ if (msg) {
83
+ return msg;
84
+ }
85
+ return "(no status code or body)";
86
+ }
87
+ static generate(status, errorResponse, message, headers) {
88
+ if (!status) {
89
+ return new APIConnectionError({
90
+ cause: castToError(errorResponse)
91
+ });
92
+ }
93
+ const error = errorResponse?.["error"];
94
+ if (status === 400) {
95
+ return new BadRequestError(status, error, message, headers);
96
+ }
97
+ if (status === 401) {
98
+ return new AuthenticationError(status, error, message, headers);
99
+ }
100
+ if (status === 403) {
101
+ return new PermissionDeniedError(status, error, message, headers);
102
+ }
103
+ if (status === 404) {
104
+ return new NotFoundError(status, error, message, headers);
105
+ }
106
+ if (status === 409) {
107
+ return new ConflictError(status, error, message, headers);
108
+ }
109
+ if (status === 422) {
110
+ return new UnprocessableEntityError(status, error, message, headers);
111
+ }
112
+ if (status === 429) {
113
+ return new RateLimitError(status, error, message, headers);
114
+ }
115
+ if (status >= 500) {
116
+ return new InternalServerError(status, error, message, headers);
117
+ }
118
+ return new _APIError(status, error, message, headers);
119
+ }
120
+ };
121
+ __name(_APIError, "APIError");
122
+ var APIError = _APIError;
123
+ var _APIConnectionError = class _APIConnectionError extends APIError {
124
+ constructor({ message, cause }) {
125
+ super(void 0, void 0, message || "Connection error.", void 0);
126
+ __publicField(this, "status");
127
+ if (cause)
128
+ this.cause = cause;
129
+ }
130
+ };
131
+ __name(_APIConnectionError, "APIConnectionError");
132
+ var APIConnectionError = _APIConnectionError;
133
+ var _BadRequestError = class _BadRequestError extends APIError {
134
+ constructor() {
135
+ super(...arguments);
136
+ __publicField(this, "status", 400);
137
+ }
138
+ };
139
+ __name(_BadRequestError, "BadRequestError");
140
+ var BadRequestError = _BadRequestError;
141
+ var _AuthenticationError = class _AuthenticationError extends APIError {
142
+ constructor() {
143
+ super(...arguments);
144
+ __publicField(this, "status", 401);
145
+ }
146
+ };
147
+ __name(_AuthenticationError, "AuthenticationError");
148
+ var AuthenticationError = _AuthenticationError;
149
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
150
+ constructor() {
151
+ super(...arguments);
152
+ __publicField(this, "status", 403);
153
+ }
154
+ };
155
+ __name(_PermissionDeniedError, "PermissionDeniedError");
156
+ var PermissionDeniedError = _PermissionDeniedError;
157
+ var _NotFoundError = class _NotFoundError extends APIError {
158
+ constructor() {
159
+ super(...arguments);
160
+ __publicField(this, "status", 404);
161
+ }
162
+ };
163
+ __name(_NotFoundError, "NotFoundError");
164
+ var NotFoundError = _NotFoundError;
165
+ var _ConflictError = class _ConflictError extends APIError {
166
+ constructor() {
167
+ super(...arguments);
168
+ __publicField(this, "status", 409);
169
+ }
170
+ };
171
+ __name(_ConflictError, "ConflictError");
172
+ var ConflictError = _ConflictError;
173
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
174
+ constructor() {
175
+ super(...arguments);
176
+ __publicField(this, "status", 422);
177
+ }
178
+ };
179
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
180
+ var UnprocessableEntityError = _UnprocessableEntityError;
181
+ var _RateLimitError = class _RateLimitError extends APIError {
182
+ constructor() {
183
+ super(...arguments);
184
+ __publicField(this, "status", 429);
185
+ }
186
+ };
187
+ __name(_RateLimitError, "RateLimitError");
188
+ var RateLimitError = _RateLimitError;
189
+ var _InternalServerError = class _InternalServerError extends APIError {
190
+ };
191
+ __name(_InternalServerError, "InternalServerError");
192
+ var InternalServerError = _InternalServerError;
193
+ function castToError(err) {
194
+ if (err instanceof Error)
195
+ return err;
196
+ return new Error(err);
197
+ }
198
+ __name(castToError, "castToError");
66
199
  var CreateAuthorizationCodeResponseSchema = zod.z.object({
67
200
  url: zod.z.string().url(),
68
201
  authorizationCode: zod.z.string()
@@ -98,6 +231,7 @@ var TaskRunErrorCodes = {
98
231
  TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
99
232
  TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
100
233
  TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
234
+ TASK_PROCESS_SIGKILL_TIMEOUT: "TASK_PROCESS_SIGKILL_TIMEOUT",
101
235
  TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
102
236
  TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
103
237
  HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
@@ -113,10 +247,12 @@ var TaskRunInternalError = zod.z.object({
113
247
  "TASK_EXECUTION_FAILED",
114
248
  "TASK_EXECUTION_ABORTED",
115
249
  "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
250
+ "TASK_PROCESS_SIGKILL_TIMEOUT",
116
251
  "TASK_RUN_CANCELLED",
117
252
  "TASK_OUTPUT_ERROR",
118
253
  "HANDLE_ERROR_ERROR",
119
- "GRACEFUL_EXIT_TIMEOUT"
254
+ "GRACEFUL_EXIT_TIMEOUT",
255
+ "TASK_RUN_HEARTBEAT_TIMEOUT"
120
256
  ]),
121
257
  message: zod.z.string().optional()
122
258
  });
@@ -133,7 +269,8 @@ var TaskRun = zod.z.object({
133
269
  context: zod.z.any(),
134
270
  tags: zod.z.array(zod.z.string()),
135
271
  isTest: zod.z.boolean().default(false),
136
- createdAt: zod.z.coerce.date()
272
+ createdAt: zod.z.coerce.date(),
273
+ idempotencyKey: zod.z.string().optional()
137
274
  });
138
275
  var TaskRunExecutionTask = zod.z.object({
139
276
  id: zod.z.string(),
@@ -229,7 +366,7 @@ var BatchTaskRunExecutionResult = zod.z.object({
229
366
  items: TaskRunExecutionResult.array()
230
367
  });
231
368
 
232
- // src/v3/schemas/messages.ts
369
+ // src/v3/schemas/schemas.ts
233
370
  var EnvironmentType = zod.z.enum([
234
371
  "PRODUCTION",
235
372
  "STAGING",
@@ -273,92 +410,6 @@ var ProdTaskRunExecutionPayload = zod.z.object({
273
410
  traceContext: zod.z.record(zod.z.unknown()),
274
411
  environment: zod.z.record(zod.z.string()).optional()
275
412
  });
276
- var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
277
- zod.z.object({
278
- type: zod.z.literal("EXECUTE_RUNS"),
279
- payloads: zod.z.array(TaskRunExecutionPayload)
280
- }),
281
- zod.z.object({
282
- type: zod.z.literal("CANCEL_ATTEMPT"),
283
- taskAttemptId: zod.z.string(),
284
- taskRunId: zod.z.string()
285
- }),
286
- zod.z.object({
287
- type: zod.z.literal("SCHEDULE_ATTEMPT"),
288
- image: zod.z.string(),
289
- version: zod.z.string(),
290
- machine: Machine,
291
- // identifiers
292
- id: zod.z.string(),
293
- envId: zod.z.string(),
294
- envType: EnvironmentType,
295
- orgId: zod.z.string(),
296
- projectId: zod.z.string(),
297
- runId: zod.z.string()
298
- })
299
- ]);
300
- var serverWebsocketMessages = {
301
- SERVER_READY: zod.z.object({
302
- version: zod.z.literal("v1").default("v1"),
303
- id: zod.z.string()
304
- }),
305
- BACKGROUND_WORKER_MESSAGE: zod.z.object({
306
- version: zod.z.literal("v1").default("v1"),
307
- backgroundWorkerId: zod.z.string(),
308
- data: BackgroundWorkerServerMessages
309
- })
310
- };
311
- var BackgroundWorkerClientMessages = zod.z.discriminatedUnion("type", [
312
- zod.z.object({
313
- version: zod.z.literal("v1").default("v1"),
314
- type: zod.z.literal("TASK_RUN_COMPLETED"),
315
- completion: TaskRunExecutionResult,
316
- execution: TaskRunExecution
317
- }),
318
- zod.z.object({
319
- version: zod.z.literal("v1").default("v1"),
320
- type: zod.z.literal("TASK_HEARTBEAT"),
321
- id: zod.z.string()
322
- })
323
- ]);
324
- var BackgroundWorkerProperties = zod.z.object({
325
- id: zod.z.string(),
326
- version: zod.z.string(),
327
- contentHash: zod.z.string()
328
- });
329
- var clientWebsocketMessages = {
330
- READY_FOR_TASKS: zod.z.object({
331
- version: zod.z.literal("v1").default("v1"),
332
- backgroundWorkerId: zod.z.string()
333
- }),
334
- BACKGROUND_WORKER_DEPRECATED: zod.z.object({
335
- version: zod.z.literal("v1").default("v1"),
336
- backgroundWorkerId: zod.z.string()
337
- }),
338
- BACKGROUND_WORKER_MESSAGE: zod.z.object({
339
- version: zod.z.literal("v1").default("v1"),
340
- backgroundWorkerId: zod.z.string(),
341
- data: BackgroundWorkerClientMessages
342
- })
343
- };
344
- var workerToChildMessages = {
345
- EXECUTE_TASK_RUN: zod.z.object({
346
- version: zod.z.literal("v1").default("v1"),
347
- execution: TaskRunExecution,
348
- traceContext: zod.z.record(zod.z.unknown()),
349
- metadata: BackgroundWorkerProperties
350
- }),
351
- TASK_RUN_COMPLETED_NOTIFICATION: zod.z.object({
352
- version: zod.z.literal("v1").default("v1"),
353
- completion: TaskRunExecutionResult,
354
- execution: TaskRunExecution
355
- }),
356
- CLEANUP: zod.z.object({
357
- version: zod.z.literal("v1").default("v1"),
358
- flush: zod.z.boolean().default(false),
359
- kill: zod.z.boolean().default(true)
360
- })
361
- };
362
413
  var FixedWindowRateLimit = zod.z.object({
363
414
  type: zod.z.literal("fixed-window"),
364
415
  limit: zod.z.number(),
@@ -464,149 +515,53 @@ var TaskFileMetadata = zod.z.object({
464
515
  exportName: zod.z.string()
465
516
  });
466
517
  var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
467
- var UncaughtExceptionMessage = zod.z.object({
468
- version: zod.z.literal("v1").default("v1"),
469
- error: zod.z.object({
470
- name: zod.z.string(),
471
- message: zod.z.string(),
472
- stack: zod.z.string().optional()
473
- }),
474
- origin: zod.z.enum([
475
- "uncaughtException",
476
- "unhandledRejection"
477
- ])
518
+ var PostStartCauses = zod.z.enum([
519
+ "index",
520
+ "create",
521
+ "restore"
522
+ ]);
523
+ var PreStopCauses = zod.z.enum([
524
+ "terminate"
525
+ ]);
526
+ var RegexSchema = zod.z.custom((val) => {
527
+ try {
528
+ return typeof val.test === "function";
529
+ } catch {
530
+ return false;
531
+ }
478
532
  });
479
- var TaskMetadataFailedToParseData = zod.z.object({
480
- version: zod.z.literal("v1").default("v1"),
481
- tasks: zod.z.unknown(),
482
- zodIssues: zod.z.custom((v) => {
483
- return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
484
- })
533
+ var Config = zod.z.object({
534
+ project: zod.z.string(),
535
+ triggerDirectories: zod.z.string().array().optional(),
536
+ triggerUrl: zod.z.string().optional(),
537
+ projectDir: zod.z.string().optional(),
538
+ tsconfigPath: zod.z.string().optional(),
539
+ retries: zod.z.object({
540
+ enabledInDev: zod.z.boolean().default(true),
541
+ default: RetryOptions.optional()
542
+ }).optional(),
543
+ additionalPackages: zod.z.string().array().optional(),
544
+ additionalFiles: zod.z.string().array().optional(),
545
+ dependenciesToBundle: zod.z.array(zod.z.union([
546
+ zod.z.string(),
547
+ RegexSchema
548
+ ])).optional(),
549
+ logLevel: zod.z.string().optional(),
550
+ enableConsoleLogging: zod.z.boolean().optional(),
551
+ postInstall: zod.z.string().optional()
552
+ });
553
+ var WaitReason = zod.z.enum([
554
+ "WAIT_FOR_DURATION",
555
+ "WAIT_FOR_TASK",
556
+ "WAIT_FOR_BATCH"
557
+ ]);
558
+ var TaskRunExecutionLazyAttemptPayload = zod.z.object({
559
+ runId: zod.z.string(),
560
+ messageId: zod.z.string(),
561
+ isTest: zod.z.boolean(),
562
+ traceContext: zod.z.record(zod.z.unknown()),
563
+ environment: zod.z.record(zod.z.string()).optional()
485
564
  });
486
- var childToWorkerMessages = {
487
- TASK_RUN_COMPLETED: zod.z.object({
488
- version: zod.z.literal("v1").default("v1"),
489
- execution: TaskRunExecution,
490
- result: TaskRunExecutionResult
491
- }),
492
- TASKS_READY: zod.z.object({
493
- version: zod.z.literal("v1").default("v1"),
494
- tasks: TaskMetadataWithFilePath.array()
495
- }),
496
- TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
497
- TASK_HEARTBEAT: zod.z.object({
498
- version: zod.z.literal("v1").default("v1"),
499
- id: zod.z.string()
500
- }),
501
- READY_TO_DISPOSE: zod.z.undefined(),
502
- WAIT_FOR_DURATION: zod.z.object({
503
- version: zod.z.literal("v1").default("v1"),
504
- ms: zod.z.number()
505
- }),
506
- WAIT_FOR_TASK: zod.z.object({
507
- version: zod.z.literal("v1").default("v1"),
508
- id: zod.z.string()
509
- }),
510
- WAIT_FOR_BATCH: zod.z.object({
511
- version: zod.z.literal("v1").default("v1"),
512
- id: zod.z.string(),
513
- runs: zod.z.string().array()
514
- }),
515
- UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
516
- };
517
- var ProdChildToWorkerMessages = {
518
- TASK_RUN_COMPLETED: {
519
- message: zod.z.object({
520
- version: zod.z.literal("v1").default("v1"),
521
- execution: TaskRunExecution,
522
- result: TaskRunExecutionResult
523
- })
524
- },
525
- TASKS_READY: {
526
- message: zod.z.object({
527
- version: zod.z.literal("v1").default("v1"),
528
- tasks: TaskMetadataWithFilePath.array()
529
- })
530
- },
531
- TASKS_FAILED_TO_PARSE: {
532
- message: TaskMetadataFailedToParseData
533
- },
534
- TASK_HEARTBEAT: {
535
- message: zod.z.object({
536
- version: zod.z.literal("v1").default("v1"),
537
- id: zod.z.string()
538
- })
539
- },
540
- READY_TO_DISPOSE: {
541
- message: zod.z.undefined()
542
- },
543
- READY_FOR_CHECKPOINT: {
544
- message: zod.z.object({
545
- version: zod.z.literal("v1").default("v1")
546
- })
547
- },
548
- CANCEL_CHECKPOINT: {
549
- message: zod.z.object({
550
- version: zod.z.literal("v1").default("v1")
551
- })
552
- },
553
- WAIT_FOR_DURATION: {
554
- message: zod.z.object({
555
- version: zod.z.literal("v1").default("v1"),
556
- ms: zod.z.number(),
557
- now: zod.z.number()
558
- }),
559
- callback: zod.z.object({
560
- willCheckpointAndRestore: zod.z.boolean()
561
- })
562
- },
563
- WAIT_FOR_TASK: {
564
- message: zod.z.object({
565
- version: zod.z.literal("v1").default("v1"),
566
- friendlyId: zod.z.string()
567
- })
568
- },
569
- WAIT_FOR_BATCH: {
570
- message: zod.z.object({
571
- version: zod.z.literal("v1").default("v1"),
572
- batchFriendlyId: zod.z.string(),
573
- runFriendlyIds: zod.z.string().array()
574
- })
575
- },
576
- UNCAUGHT_EXCEPTION: {
577
- message: UncaughtExceptionMessage
578
- }
579
- };
580
- var ProdWorkerToChildMessages = {
581
- EXECUTE_TASK_RUN: {
582
- message: zod.z.object({
583
- version: zod.z.literal("v1").default("v1"),
584
- execution: TaskRunExecution,
585
- traceContext: zod.z.record(zod.z.unknown()),
586
- metadata: BackgroundWorkerProperties
587
- })
588
- },
589
- TASK_RUN_COMPLETED_NOTIFICATION: {
590
- message: zod.z.object({
591
- version: zod.z.literal("v1").default("v1"),
592
- completion: TaskRunExecutionResult,
593
- execution: TaskRunExecution
594
- })
595
- },
596
- CLEANUP: {
597
- message: zod.z.object({
598
- version: zod.z.literal("v1").default("v1"),
599
- flush: zod.z.boolean().default(false),
600
- kill: zod.z.boolean().default(true)
601
- }),
602
- callback: zod.z.void()
603
- },
604
- WAIT_COMPLETED_NOTIFICATION: {
605
- message: zod.z.object({
606
- version: zod.z.literal("v1").default("v1")
607
- })
608
- }
609
- };
610
565
 
611
566
  // src/v3/schemas/resources.ts
612
567
  var TaskResource = zod.z.object({
@@ -656,7 +611,8 @@ var GetProjectEnvResponse = zod.z.object({
656
611
  });
657
612
  var CreateBackgroundWorkerRequestBody = zod.z.object({
658
613
  localOnly: zod.z.boolean(),
659
- metadata: BackgroundWorkerMetadata
614
+ metadata: BackgroundWorkerMetadata,
615
+ supportsLazyAttempts: zod.z.boolean().optional()
660
616
  });
661
617
  var CreateBackgroundWorkerResponse = zod.z.object({
662
618
  id: zod.z.string(),
@@ -705,7 +661,8 @@ var GetEnvironmentVariablesResponseBody = zod.z.object({
705
661
  variables: zod.z.record(zod.z.string())
706
662
  });
707
663
  var StartDeploymentIndexingRequestBody = zod.z.object({
708
- imageReference: zod.z.string()
664
+ imageReference: zod.z.string(),
665
+ selfHosted: zod.z.boolean().optional()
709
666
  });
710
667
  var StartDeploymentIndexingResponseBody = zod.z.object({
711
668
  id: zod.z.string(),
@@ -851,54 +808,350 @@ var ListScheduleOptions = zod.z.object({
851
808
  page: zod.z.number().optional(),
852
809
  perPage: zod.z.number().optional()
853
810
  });
854
- var PostStartCauses = zod.z.enum([
855
- "index",
856
- "create",
857
- "restore"
811
+ var RunStatus = zod.z.enum([
812
+ "PENDING",
813
+ "EXECUTING",
814
+ "PAUSED",
815
+ "COMPLETED",
816
+ "FAILED",
817
+ "CANCELED"
858
818
  ]);
859
- var PreStopCauses = zod.z.enum([
860
- "terminate"
819
+ var AttemptStatus = zod.z.enum([
820
+ "PENDING",
821
+ "EXECUTING",
822
+ "PAUSED",
823
+ "COMPLETED",
824
+ "FAILED",
825
+ "CANCELED"
861
826
  ]);
862
- var RegexSchema = zod.z.custom((val) => {
863
- try {
864
- return typeof val.test === "function";
865
- } catch {
866
- return false;
867
- }
827
+ var RetrieveRunResponse = zod.z.object({
828
+ id: zod.z.string(),
829
+ status: RunStatus,
830
+ taskIdentifier: zod.z.string(),
831
+ idempotencyKey: zod.z.string().optional(),
832
+ version: zod.z.string().optional(),
833
+ createdAt: zod.z.coerce.date(),
834
+ updatedAt: zod.z.coerce.date(),
835
+ attempts: zod.z.array(zod.z.object({
836
+ id: zod.z.string(),
837
+ status: AttemptStatus,
838
+ createdAt: zod.z.coerce.date(),
839
+ updatedAt: zod.z.coerce.date(),
840
+ startedAt: zod.z.coerce.date().optional(),
841
+ completedAt: zod.z.coerce.date().optional()
842
+ }).optional())
843
+ });
844
+ var CreateEnvironmentVariableRequestBody = zod.z.object({
845
+ name: zod.z.string(),
846
+ value: zod.z.string()
868
847
  });
869
- var Config = zod.z.object({
870
- project: zod.z.string(),
871
- triggerDirectories: zod.z.string().array().optional(),
872
- triggerUrl: zod.z.string().optional(),
873
- projectDir: zod.z.string().optional(),
874
- tsconfigPath: zod.z.string().optional(),
875
- retries: zod.z.object({
876
- enabledInDev: zod.z.boolean().default(true),
877
- default: RetryOptions.optional()
878
- }).optional(),
879
- additionalPackages: zod.z.string().array().optional(),
880
- additionalFiles: zod.z.string().array().optional(),
881
- dependenciesToBundle: zod.z.array(zod.z.union([
882
- zod.z.string(),
883
- RegexSchema
884
- ])).optional(),
885
- logLevel: zod.z.string().optional(),
886
- enableConsoleLogging: zod.z.boolean().optional()
848
+ var UpdateEnvironmentVariableRequestBody = zod.z.object({
849
+ value: zod.z.string()
887
850
  });
888
- var WaitReason = zod.z.enum([
889
- "WAIT_FOR_DURATION",
890
- "WAIT_FOR_TASK",
891
- "WAIT_FOR_BATCH"
851
+ var ImportEnvironmentVariablesRequestBody = zod.z.object({
852
+ variables: zod.z.record(zod.z.string()),
853
+ override: zod.z.boolean().optional()
854
+ });
855
+ var EnvironmentVariableResponseBody = zod.z.object({
856
+ success: zod.z.boolean()
857
+ });
858
+ var EnvironmentVariableValue = zod.z.object({
859
+ value: zod.z.string()
860
+ });
861
+ var EnvironmentVariable = zod.z.object({
862
+ name: zod.z.string(),
863
+ value: zod.z.string()
864
+ });
865
+ var EnvironmentVariables = zod.z.array(EnvironmentVariable);
866
+ var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
867
+ zod.z.object({
868
+ type: zod.z.literal("EXECUTE_RUNS"),
869
+ payloads: zod.z.array(TaskRunExecutionPayload)
870
+ }),
871
+ zod.z.object({
872
+ type: zod.z.literal("CANCEL_ATTEMPT"),
873
+ taskAttemptId: zod.z.string(),
874
+ taskRunId: zod.z.string()
875
+ }),
876
+ zod.z.object({
877
+ type: zod.z.literal("SCHEDULE_ATTEMPT"),
878
+ image: zod.z.string(),
879
+ version: zod.z.string(),
880
+ machine: Machine,
881
+ // identifiers
882
+ id: zod.z.string().optional(),
883
+ envId: zod.z.string(),
884
+ envType: EnvironmentType,
885
+ orgId: zod.z.string(),
886
+ projectId: zod.z.string(),
887
+ runId: zod.z.string()
888
+ }),
889
+ zod.z.object({
890
+ type: zod.z.literal("EXECUTE_RUN_LAZY_ATTEMPT"),
891
+ payload: TaskRunExecutionLazyAttemptPayload
892
+ })
892
893
  ]);
893
- var ProviderToPlatformMessages = {
894
- LOG: {
895
- message: zod.z.object({
896
- version: zod.z.literal("v1").default("v1"),
897
- data: zod.z.string()
898
- })
899
- },
900
- LOG_WITH_ACK: {
901
- message: zod.z.object({
894
+ var serverWebsocketMessages = {
895
+ SERVER_READY: zod.z.object({
896
+ version: zod.z.literal("v1").default("v1"),
897
+ id: zod.z.string()
898
+ }),
899
+ BACKGROUND_WORKER_MESSAGE: zod.z.object({
900
+ version: zod.z.literal("v1").default("v1"),
901
+ backgroundWorkerId: zod.z.string(),
902
+ data: BackgroundWorkerServerMessages
903
+ })
904
+ };
905
+ var BackgroundWorkerClientMessages = zod.z.discriminatedUnion("type", [
906
+ zod.z.object({
907
+ version: zod.z.literal("v1").default("v1"),
908
+ type: zod.z.literal("TASK_RUN_COMPLETED"),
909
+ completion: TaskRunExecutionResult,
910
+ execution: TaskRunExecution
911
+ }),
912
+ zod.z.object({
913
+ version: zod.z.literal("v1").default("v1"),
914
+ type: zod.z.literal("TASK_RUN_FAILED_TO_RUN"),
915
+ completion: TaskRunFailedExecutionResult
916
+ }),
917
+ zod.z.object({
918
+ version: zod.z.literal("v1").default("v1"),
919
+ type: zod.z.literal("TASK_HEARTBEAT"),
920
+ id: zod.z.string()
921
+ }),
922
+ zod.z.object({
923
+ version: zod.z.literal("v1").default("v1"),
924
+ type: zod.z.literal("TASK_RUN_HEARTBEAT"),
925
+ id: zod.z.string()
926
+ })
927
+ ]);
928
+ var BackgroundWorkerProperties = zod.z.object({
929
+ id: zod.z.string(),
930
+ version: zod.z.string(),
931
+ contentHash: zod.z.string()
932
+ });
933
+ var clientWebsocketMessages = {
934
+ READY_FOR_TASKS: zod.z.object({
935
+ version: zod.z.literal("v1").default("v1"),
936
+ backgroundWorkerId: zod.z.string(),
937
+ inProgressRuns: zod.z.string().array().optional()
938
+ }),
939
+ BACKGROUND_WORKER_DEPRECATED: zod.z.object({
940
+ version: zod.z.literal("v1").default("v1"),
941
+ backgroundWorkerId: zod.z.string()
942
+ }),
943
+ BACKGROUND_WORKER_MESSAGE: zod.z.object({
944
+ version: zod.z.literal("v1").default("v1"),
945
+ backgroundWorkerId: zod.z.string(),
946
+ data: BackgroundWorkerClientMessages
947
+ })
948
+ };
949
+ var workerToChildMessages = {
950
+ EXECUTE_TASK_RUN: zod.z.object({
951
+ version: zod.z.literal("v1").default("v1"),
952
+ execution: TaskRunExecution,
953
+ traceContext: zod.z.record(zod.z.unknown()),
954
+ metadata: BackgroundWorkerProperties
955
+ }),
956
+ TASK_RUN_COMPLETED_NOTIFICATION: zod.z.discriminatedUnion("version", [
957
+ zod.z.object({
958
+ version: zod.z.literal("v1"),
959
+ completion: TaskRunExecutionResult,
960
+ execution: TaskRunExecution
961
+ }),
962
+ zod.z.object({
963
+ version: zod.z.literal("v2"),
964
+ completion: TaskRunExecutionResult
965
+ })
966
+ ]),
967
+ CLEANUP: zod.z.object({
968
+ version: zod.z.literal("v1").default("v1"),
969
+ flush: zod.z.boolean().default(false),
970
+ kill: zod.z.boolean().default(true)
971
+ })
972
+ };
973
+ var UncaughtExceptionMessage = zod.z.object({
974
+ version: zod.z.literal("v1").default("v1"),
975
+ error: zod.z.object({
976
+ name: zod.z.string(),
977
+ message: zod.z.string(),
978
+ stack: zod.z.string().optional()
979
+ }),
980
+ origin: zod.z.enum([
981
+ "uncaughtException",
982
+ "unhandledRejection"
983
+ ])
984
+ });
985
+ var TaskMetadataFailedToParseData = zod.z.object({
986
+ version: zod.z.literal("v1").default("v1"),
987
+ tasks: zod.z.unknown(),
988
+ zodIssues: zod.z.custom((v) => {
989
+ return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
990
+ })
991
+ });
992
+ var childToWorkerMessages = {
993
+ TASK_RUN_COMPLETED: zod.z.object({
994
+ version: zod.z.literal("v1").default("v1"),
995
+ execution: TaskRunExecution,
996
+ result: TaskRunExecutionResult
997
+ }),
998
+ TASKS_READY: zod.z.object({
999
+ version: zod.z.literal("v1").default("v1"),
1000
+ tasks: TaskMetadataWithFilePath.array()
1001
+ }),
1002
+ TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
1003
+ TASK_HEARTBEAT: zod.z.object({
1004
+ version: zod.z.literal("v1").default("v1"),
1005
+ id: zod.z.string()
1006
+ }),
1007
+ TASK_RUN_HEARTBEAT: zod.z.object({
1008
+ version: zod.z.literal("v1").default("v1"),
1009
+ id: zod.z.string()
1010
+ }),
1011
+ READY_TO_DISPOSE: zod.z.undefined(),
1012
+ WAIT_FOR_DURATION: zod.z.object({
1013
+ version: zod.z.literal("v1").default("v1"),
1014
+ ms: zod.z.number()
1015
+ }),
1016
+ WAIT_FOR_TASK: zod.z.object({
1017
+ version: zod.z.literal("v1").default("v1"),
1018
+ id: zod.z.string()
1019
+ }),
1020
+ WAIT_FOR_BATCH: zod.z.object({
1021
+ version: zod.z.literal("v1").default("v1"),
1022
+ id: zod.z.string(),
1023
+ runs: zod.z.string().array()
1024
+ }),
1025
+ UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
1026
+ };
1027
+ var ProdChildToWorkerMessages = {
1028
+ TASK_RUN_COMPLETED: {
1029
+ message: zod.z.object({
1030
+ version: zod.z.literal("v1").default("v1"),
1031
+ execution: TaskRunExecution,
1032
+ result: TaskRunExecutionResult
1033
+ })
1034
+ },
1035
+ TASKS_READY: {
1036
+ message: zod.z.object({
1037
+ version: zod.z.literal("v1").default("v1"),
1038
+ tasks: TaskMetadataWithFilePath.array()
1039
+ })
1040
+ },
1041
+ TASKS_FAILED_TO_PARSE: {
1042
+ message: TaskMetadataFailedToParseData
1043
+ },
1044
+ TASK_HEARTBEAT: {
1045
+ message: zod.z.object({
1046
+ version: zod.z.literal("v1").default("v1"),
1047
+ id: zod.z.string()
1048
+ })
1049
+ },
1050
+ TASK_RUN_HEARTBEAT: {
1051
+ message: zod.z.object({
1052
+ version: zod.z.literal("v1").default("v1"),
1053
+ id: zod.z.string()
1054
+ })
1055
+ },
1056
+ READY_TO_DISPOSE: {
1057
+ message: zod.z.undefined()
1058
+ },
1059
+ READY_FOR_CHECKPOINT: {
1060
+ message: zod.z.object({
1061
+ version: zod.z.literal("v1").default("v1")
1062
+ })
1063
+ },
1064
+ CANCEL_CHECKPOINT: {
1065
+ message: zod.z.discriminatedUnion("version", [
1066
+ zod.z.object({
1067
+ version: zod.z.literal("v1")
1068
+ }),
1069
+ zod.z.object({
1070
+ version: zod.z.literal("v2"),
1071
+ reason: WaitReason.optional()
1072
+ })
1073
+ ]).default({
1074
+ version: "v1"
1075
+ }),
1076
+ callback: zod.z.object({
1077
+ // TODO: Figure out how best to handle callback schema parsing in zod IPC
1078
+ version: zod.z.literal("v2"),
1079
+ checkpointCanceled: zod.z.boolean(),
1080
+ reason: WaitReason.optional()
1081
+ })
1082
+ },
1083
+ WAIT_FOR_DURATION: {
1084
+ message: zod.z.object({
1085
+ version: zod.z.literal("v1").default("v1"),
1086
+ ms: zod.z.number(),
1087
+ now: zod.z.number()
1088
+ }),
1089
+ callback: zod.z.object({
1090
+ willCheckpointAndRestore: zod.z.boolean()
1091
+ })
1092
+ },
1093
+ WAIT_FOR_TASK: {
1094
+ message: zod.z.object({
1095
+ version: zod.z.literal("v1").default("v1"),
1096
+ friendlyId: zod.z.string()
1097
+ })
1098
+ },
1099
+ WAIT_FOR_BATCH: {
1100
+ message: zod.z.object({
1101
+ version: zod.z.literal("v1").default("v1"),
1102
+ batchFriendlyId: zod.z.string(),
1103
+ runFriendlyIds: zod.z.string().array()
1104
+ })
1105
+ },
1106
+ UNCAUGHT_EXCEPTION: {
1107
+ message: UncaughtExceptionMessage
1108
+ }
1109
+ };
1110
+ var ProdWorkerToChildMessages = {
1111
+ EXECUTE_TASK_RUN: {
1112
+ message: zod.z.object({
1113
+ version: zod.z.literal("v1").default("v1"),
1114
+ execution: TaskRunExecution,
1115
+ traceContext: zod.z.record(zod.z.unknown()),
1116
+ metadata: BackgroundWorkerProperties
1117
+ })
1118
+ },
1119
+ TASK_RUN_COMPLETED_NOTIFICATION: {
1120
+ message: zod.z.discriminatedUnion("version", [
1121
+ zod.z.object({
1122
+ version: zod.z.literal("v1"),
1123
+ completion: TaskRunExecutionResult,
1124
+ execution: TaskRunExecution
1125
+ }),
1126
+ zod.z.object({
1127
+ version: zod.z.literal("v2"),
1128
+ completion: TaskRunExecutionResult
1129
+ })
1130
+ ])
1131
+ },
1132
+ CLEANUP: {
1133
+ message: zod.z.object({
1134
+ version: zod.z.literal("v1").default("v1"),
1135
+ flush: zod.z.boolean().default(false),
1136
+ kill: zod.z.boolean().default(true)
1137
+ }),
1138
+ callback: zod.z.void()
1139
+ },
1140
+ WAIT_COMPLETED_NOTIFICATION: {
1141
+ message: zod.z.object({
1142
+ version: zod.z.literal("v1").default("v1")
1143
+ })
1144
+ }
1145
+ };
1146
+ var ProviderToPlatformMessages = {
1147
+ LOG: {
1148
+ message: zod.z.object({
1149
+ version: zod.z.literal("v1").default("v1"),
1150
+ data: zod.z.string()
1151
+ })
1152
+ },
1153
+ LOG_WITH_ACK: {
1154
+ message: zod.z.object({
902
1155
  version: zod.z.literal("v1").default("v1"),
903
1156
  data: zod.z.string()
904
1157
  }),
@@ -1002,6 +1255,17 @@ var PlatformToProviderMessages = {
1002
1255
  })
1003
1256
  }
1004
1257
  };
1258
+ var CreateWorkerMessage = zod.z.object({
1259
+ projectRef: zod.z.string(),
1260
+ envId: zod.z.string(),
1261
+ deploymentId: zod.z.string(),
1262
+ metadata: zod.z.object({
1263
+ cliPackageVersion: zod.z.string().optional(),
1264
+ contentHash: zod.z.string(),
1265
+ packageVersion: zod.z.string(),
1266
+ tasks: TaskResource.array()
1267
+ })
1268
+ });
1005
1269
  var CoordinatorToPlatformMessages = {
1006
1270
  LOG: {
1007
1271
  message: zod.z.object({
@@ -1011,18 +1275,15 @@ var CoordinatorToPlatformMessages = {
1011
1275
  })
1012
1276
  },
1013
1277
  CREATE_WORKER: {
1014
- message: zod.z.object({
1015
- version: zod.z.literal("v1").default("v1"),
1016
- projectRef: zod.z.string(),
1017
- envId: zod.z.string(),
1018
- deploymentId: zod.z.string(),
1019
- metadata: zod.z.object({
1020
- cliPackageVersion: zod.z.string().optional(),
1021
- contentHash: zod.z.string(),
1022
- packageVersion: zod.z.string(),
1023
- tasks: TaskResource.array()
1278
+ message: zod.z.discriminatedUnion("version", [
1279
+ CreateWorkerMessage.extend({
1280
+ version: zod.z.literal("v1")
1281
+ }),
1282
+ CreateWorkerMessage.extend({
1283
+ version: zod.z.literal("v2"),
1284
+ supportsLazyAttempts: zod.z.boolean()
1024
1285
  })
1025
- }),
1286
+ ]),
1026
1287
  callback: zod.z.discriminatedUnion("success", [
1027
1288
  zod.z.object({
1028
1289
  success: zod.z.literal(false)
@@ -1032,23 +1293,58 @@ var CoordinatorToPlatformMessages = {
1032
1293
  })
1033
1294
  ])
1034
1295
  },
1035
- READY_FOR_EXECUTION: {
1296
+ CREATE_TASK_RUN_ATTEMPT: {
1036
1297
  message: zod.z.object({
1037
1298
  version: zod.z.literal("v1").default("v1"),
1038
1299
  runId: zod.z.string(),
1039
- totalCompletions: zod.z.number()
1300
+ envId: zod.z.string()
1040
1301
  }),
1041
1302
  callback: zod.z.discriminatedUnion("success", [
1042
1303
  zod.z.object({
1043
- success: zod.z.literal(false)
1304
+ success: zod.z.literal(false),
1305
+ reason: zod.z.string().optional()
1044
1306
  }),
1045
1307
  zod.z.object({
1046
1308
  success: zod.z.literal(true),
1047
- payload: ProdTaskRunExecutionPayload
1309
+ executionPayload: ProdTaskRunExecutionPayload
1048
1310
  })
1049
1311
  ])
1050
1312
  },
1051
- READY_FOR_RESUME: {
1313
+ READY_FOR_EXECUTION: {
1314
+ message: zod.z.object({
1315
+ version: zod.z.literal("v1").default("v1"),
1316
+ runId: zod.z.string(),
1317
+ totalCompletions: zod.z.number()
1318
+ }),
1319
+ callback: zod.z.discriminatedUnion("success", [
1320
+ zod.z.object({
1321
+ success: zod.z.literal(false)
1322
+ }),
1323
+ zod.z.object({
1324
+ success: zod.z.literal(true),
1325
+ payload: ProdTaskRunExecutionPayload
1326
+ })
1327
+ ])
1328
+ },
1329
+ READY_FOR_LAZY_ATTEMPT: {
1330
+ message: zod.z.object({
1331
+ version: zod.z.literal("v1").default("v1"),
1332
+ runId: zod.z.string(),
1333
+ envId: zod.z.string(),
1334
+ totalCompletions: zod.z.number()
1335
+ }),
1336
+ callback: zod.z.discriminatedUnion("success", [
1337
+ zod.z.object({
1338
+ success: zod.z.literal(false),
1339
+ reason: zod.z.string().optional()
1340
+ }),
1341
+ zod.z.object({
1342
+ success: zod.z.literal(true),
1343
+ lazyPayload: TaskRunExecutionLazyAttemptPayload
1344
+ })
1345
+ ])
1346
+ },
1347
+ READY_FOR_RESUME: {
1052
1348
  message: zod.z.object({
1053
1349
  version: zod.z.literal("v1").default("v1"),
1054
1350
  attemptFriendlyId: zod.z.string(),
@@ -1066,12 +1362,24 @@ var CoordinatorToPlatformMessages = {
1066
1362
  }).optional()
1067
1363
  })
1068
1364
  },
1365
+ TASK_RUN_FAILED_TO_RUN: {
1366
+ message: zod.z.object({
1367
+ version: zod.z.literal("v1").default("v1"),
1368
+ completion: TaskRunFailedExecutionResult
1369
+ })
1370
+ },
1069
1371
  TASK_HEARTBEAT: {
1070
1372
  message: zod.z.object({
1071
1373
  version: zod.z.literal("v1").default("v1"),
1072
1374
  attemptFriendlyId: zod.z.string()
1073
1375
  })
1074
1376
  },
1377
+ TASK_RUN_HEARTBEAT: {
1378
+ message: zod.z.object({
1379
+ version: zod.z.literal("v1").default("v1"),
1380
+ runId: zod.z.string()
1381
+ })
1382
+ },
1075
1383
  CHECKPOINT_CREATED: {
1076
1384
  message: zod.z.object({
1077
1385
  version: zod.z.literal("v1").default("v1"),
@@ -1110,6 +1418,17 @@ var CoordinatorToPlatformMessages = {
1110
1418
  stack: zod.z.string().optional()
1111
1419
  })
1112
1420
  })
1421
+ },
1422
+ RUN_CRASHED: {
1423
+ message: zod.z.object({
1424
+ version: zod.z.literal("v1").default("v1"),
1425
+ runId: zod.z.string(),
1426
+ error: zod.z.object({
1427
+ name: zod.z.string(),
1428
+ message: zod.z.string(),
1429
+ stack: zod.z.string().optional()
1430
+ })
1431
+ })
1113
1432
  }
1114
1433
  };
1115
1434
  var PlatformToCoordinatorMessages = {
@@ -1137,6 +1456,13 @@ var PlatformToCoordinatorMessages = {
1137
1456
  attemptFriendlyId: zod.z.string()
1138
1457
  })
1139
1458
  },
1459
+ REQUEST_RUN_CANCELLATION: {
1460
+ message: zod.z.object({
1461
+ version: zod.z.literal("v1").default("v1"),
1462
+ runId: zod.z.string(),
1463
+ delayInMs: zod.z.number().optional()
1464
+ })
1465
+ },
1140
1466
  READY_FOR_RETRY: {
1141
1467
  message: zod.z.object({
1142
1468
  version: zod.z.literal("v1").default("v1"),
@@ -1180,6 +1506,12 @@ var SharedQueueToClientMessages = {
1180
1506
  })
1181
1507
  }
1182
1508
  };
1509
+ var IndexTasksMessage = zod.z.object({
1510
+ version: zod.z.literal("v1"),
1511
+ deploymentId: zod.z.string(),
1512
+ tasks: TaskResource.array(),
1513
+ packageVersion: zod.z.string()
1514
+ });
1183
1515
  var ProdWorkerToCoordinatorMessages = {
1184
1516
  LOG: {
1185
1517
  message: zod.z.object({
@@ -1189,12 +1521,15 @@ var ProdWorkerToCoordinatorMessages = {
1189
1521
  callback: zod.z.void()
1190
1522
  },
1191
1523
  INDEX_TASKS: {
1192
- message: zod.z.object({
1193
- version: zod.z.literal("v1").default("v1"),
1194
- deploymentId: zod.z.string(),
1195
- tasks: TaskResource.array(),
1196
- packageVersion: zod.z.string()
1197
- }),
1524
+ message: zod.z.discriminatedUnion("version", [
1525
+ IndexTasksMessage.extend({
1526
+ version: zod.z.literal("v1")
1527
+ }),
1528
+ IndexTasksMessage.extend({
1529
+ version: zod.z.literal("v2"),
1530
+ supportsLazyAttempts: zod.z.boolean()
1531
+ })
1532
+ ]),
1198
1533
  callback: zod.z.discriminatedUnion("success", [
1199
1534
  zod.z.object({
1200
1535
  success: zod.z.literal(false)
@@ -1211,6 +1546,13 @@ var ProdWorkerToCoordinatorMessages = {
1211
1546
  totalCompletions: zod.z.number()
1212
1547
  })
1213
1548
  },
1549
+ READY_FOR_LAZY_ATTEMPT: {
1550
+ message: zod.z.object({
1551
+ version: zod.z.literal("v1").default("v1"),
1552
+ runId: zod.z.string(),
1553
+ totalCompletions: zod.z.number()
1554
+ })
1555
+ },
1214
1556
  READY_FOR_RESUME: {
1215
1557
  message: zod.z.object({
1216
1558
  version: zod.z.literal("v1").default("v1"),
@@ -1224,8 +1566,21 @@ var ProdWorkerToCoordinatorMessages = {
1224
1566
  })
1225
1567
  },
1226
1568
  CANCEL_CHECKPOINT: {
1227
- message: zod.z.object({
1228
- version: zod.z.literal("v1").default("v1")
1569
+ message: zod.z.discriminatedUnion("version", [
1570
+ zod.z.object({
1571
+ version: zod.z.literal("v1")
1572
+ }),
1573
+ zod.z.object({
1574
+ version: zod.z.literal("v2"),
1575
+ reason: WaitReason.optional()
1576
+ })
1577
+ ]).default({
1578
+ version: "v1"
1579
+ }),
1580
+ callback: zod.z.object({
1581
+ version: zod.z.literal("v2").default("v2"),
1582
+ checkpointCanceled: zod.z.boolean(),
1583
+ reason: WaitReason.optional()
1229
1584
  })
1230
1585
  },
1231
1586
  TASK_HEARTBEAT: {
@@ -1234,6 +1589,12 @@ var ProdWorkerToCoordinatorMessages = {
1234
1589
  attemptFriendlyId: zod.z.string()
1235
1590
  })
1236
1591
  },
1592
+ TASK_RUN_HEARTBEAT: {
1593
+ message: zod.z.object({
1594
+ version: zod.z.literal("v1").default("v1"),
1595
+ runId: zod.z.string()
1596
+ })
1597
+ },
1237
1598
  TASK_RUN_COMPLETED: {
1238
1599
  message: zod.z.object({
1239
1600
  version: zod.z.literal("v1").default("v1"),
@@ -1245,6 +1606,12 @@ var ProdWorkerToCoordinatorMessages = {
1245
1606
  shouldExit: zod.z.boolean()
1246
1607
  })
1247
1608
  },
1609
+ TASK_RUN_FAILED_TO_RUN: {
1610
+ message: zod.z.object({
1611
+ version: zod.z.literal("v1").default("v1"),
1612
+ completion: TaskRunFailedExecutionResult
1613
+ })
1614
+ },
1248
1615
  WAIT_FOR_DURATION: {
1249
1616
  message: zod.z.object({
1250
1617
  version: zod.z.literal("v1").default("v1"),
@@ -1289,6 +1656,32 @@ var ProdWorkerToCoordinatorMessages = {
1289
1656
  stack: zod.z.string().optional()
1290
1657
  })
1291
1658
  })
1659
+ },
1660
+ CREATE_TASK_RUN_ATTEMPT: {
1661
+ message: zod.z.object({
1662
+ version: zod.z.literal("v1").default("v1"),
1663
+ runId: zod.z.string()
1664
+ }),
1665
+ callback: zod.z.discriminatedUnion("success", [
1666
+ zod.z.object({
1667
+ success: zod.z.literal(false),
1668
+ reason: zod.z.string().optional()
1669
+ }),
1670
+ zod.z.object({
1671
+ success: zod.z.literal(true),
1672
+ executionPayload: ProdTaskRunExecutionPayload
1673
+ })
1674
+ ])
1675
+ },
1676
+ UNRECOVERABLE_ERROR: {
1677
+ message: zod.z.object({
1678
+ version: zod.z.literal("v1").default("v1"),
1679
+ error: zod.z.object({
1680
+ name: zod.z.string(),
1681
+ message: zod.z.string(),
1682
+ stack: zod.z.string().optional()
1683
+ })
1684
+ })
1292
1685
  }
1293
1686
  };
1294
1687
  var CoordinatorToProdWorkerMessages = {
@@ -1312,6 +1705,12 @@ var CoordinatorToProdWorkerMessages = {
1312
1705
  executionPayload: ProdTaskRunExecutionPayload
1313
1706
  })
1314
1707
  },
1708
+ EXECUTE_TASK_RUN_LAZY_ATTEMPT: {
1709
+ message: zod.z.object({
1710
+ version: zod.z.literal("v1").default("v1"),
1711
+ lazyPayload: TaskRunExecutionLazyAttemptPayload
1712
+ })
1713
+ },
1315
1714
  REQUEST_ATTEMPT_CANCELLATION: {
1316
1715
  message: zod.z.object({
1317
1716
  version: zod.z.literal("v1").default("v1"),
@@ -1319,9 +1718,15 @@ var CoordinatorToProdWorkerMessages = {
1319
1718
  })
1320
1719
  },
1321
1720
  REQUEST_EXIT: {
1322
- message: zod.z.object({
1323
- version: zod.z.literal("v1").default("v1")
1324
- })
1721
+ message: zod.z.discriminatedUnion("version", [
1722
+ zod.z.object({
1723
+ version: zod.z.literal("v1")
1724
+ }),
1725
+ zod.z.object({
1726
+ version: zod.z.literal("v2"),
1727
+ delayInMs: zod.z.number().optional()
1728
+ })
1729
+ ])
1325
1730
  },
1326
1731
  READY_FOR_RETRY: {
1327
1732
  message: zod.z.object({
@@ -1539,143 +1944,162 @@ var SpanMessagingEvent = zod.z.object({
1539
1944
  destination: zod.z.string().optional()
1540
1945
  });
1541
1946
 
1542
- // src/v3/apiErrors.ts
1543
- var _APIError = class _APIError extends Error {
1544
- constructor(status, error, message, headers) {
1545
- super(`${_APIError.makeMessage(status, error, message)}`);
1546
- this.status = status;
1547
- this.headers = headers;
1548
- const data = error;
1549
- this.error = data;
1550
- this.code = data?.["code"];
1551
- this.param = data?.["param"];
1552
- this.type = data?.["type"];
1947
+ // src/v3/utils/platform.ts
1948
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
1949
+
1950
+ // src/v3/utils/globals.ts
1951
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
1952
+ var _global = _globalThis;
1953
+ function registerGlobal(type, instance, allowOverride = false) {
1954
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
1955
+ if (!allowOverride && api[type]) {
1956
+ return false;
1553
1957
  }
1554
- static makeMessage(status, error, message) {
1555
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1556
- if (status && msg) {
1557
- return `${status} ${msg}`;
1558
- }
1559
- if (status) {
1560
- return `${status} status code (no body)`;
1561
- }
1562
- if (msg) {
1563
- return msg;
1564
- }
1565
- return "(no status code or body)";
1958
+ api[type] = instance;
1959
+ return true;
1960
+ }
1961
+ __name(registerGlobal, "registerGlobal");
1962
+ function getGlobal(type) {
1963
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
1964
+ }
1965
+ __name(getGlobal, "getGlobal");
1966
+ function unregisterGlobal(type) {
1967
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
1968
+ if (api) {
1969
+ delete api[type];
1566
1970
  }
1567
- static generate(status, errorResponse, message, headers) {
1568
- if (!status) {
1569
- return new APIConnectionError({
1570
- cause: castToError(errorResponse)
1571
- });
1572
- }
1573
- const error = errorResponse?.["error"];
1574
- if (status === 400) {
1575
- return new BadRequestError(status, error, message, headers);
1576
- }
1577
- if (status === 401) {
1578
- return new AuthenticationError(status, error, message, headers);
1971
+ }
1972
+ __name(unregisterGlobal, "unregisterGlobal");
1973
+
1974
+ // src/v3/semanticInternalAttributes.ts
1975
+ var SemanticInternalAttributes = {
1976
+ ENVIRONMENT_ID: "ctx.environment.id",
1977
+ ENVIRONMENT_TYPE: "ctx.environment.type",
1978
+ ORGANIZATION_ID: "ctx.organization.id",
1979
+ ORGANIZATION_SLUG: "ctx.organization.slug",
1980
+ ORGANIZATION_NAME: "ctx.organization.name",
1981
+ PROJECT_ID: "ctx.project.id",
1982
+ PROJECT_REF: "ctx.project.ref",
1983
+ PROJECT_NAME: "ctx.project.title",
1984
+ PROJECT_DIR: "project.dir",
1985
+ ATTEMPT_ID: "ctx.attempt.id",
1986
+ ATTEMPT_NUMBER: "ctx.attempt.number",
1987
+ RUN_ID: "ctx.run.id",
1988
+ RUN_IS_TEST: "ctx.run.isTest",
1989
+ BATCH_ID: "ctx.batch.id",
1990
+ TASK_SLUG: "ctx.task.id",
1991
+ TASK_PATH: "ctx.task.filePath",
1992
+ TASK_EXPORT_NAME: "ctx.task.exportName",
1993
+ QUEUE_NAME: "ctx.queue.name",
1994
+ QUEUE_ID: "ctx.queue.id",
1995
+ SPAN_PARTIAL: "$span.partial",
1996
+ SPAN_ID: "$span.span_id",
1997
+ OUTPUT: "$output",
1998
+ OUTPUT_TYPE: "$mime_type_output",
1999
+ STYLE: "$style",
2000
+ STYLE_ICON: "$style.icon",
2001
+ STYLE_VARIANT: "$style.variant",
2002
+ STYLE_ACCESSORY: "$style.accessory",
2003
+ METADATA: "$metadata",
2004
+ TRIGGER: "$trigger",
2005
+ PAYLOAD: "$payload",
2006
+ PAYLOAD_TYPE: "$mime_type_payload",
2007
+ SHOW: "$show",
2008
+ SHOW_ACTIONS: "$show.actions",
2009
+ WORKER_ID: "worker.id",
2010
+ WORKER_VERSION: "worker.version",
2011
+ CLI_VERSION: "cli.version",
2012
+ SDK_VERSION: "sdk.version",
2013
+ SDK_LANGUAGE: "sdk.language",
2014
+ RETRY_AT: "retry.at",
2015
+ RETRY_DELAY: "retry.delay",
2016
+ RETRY_COUNT: "retry.count",
2017
+ LINK_TITLE: "$link.title",
2018
+ IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
2019
+ };
2020
+
2021
+ // src/v3/taskContext/index.ts
2022
+ var API_NAME = "task-context";
2023
+ var _getTaskContext, getTaskContext_fn;
2024
+ var _TaskContextAPI = class _TaskContextAPI {
2025
+ constructor() {
2026
+ __privateAdd(this, _getTaskContext);
2027
+ }
2028
+ static getInstance() {
2029
+ if (!this._instance) {
2030
+ this._instance = new _TaskContextAPI();
1579
2031
  }
1580
- if (status === 403) {
1581
- return new PermissionDeniedError(status, error, message, headers);
2032
+ return this._instance;
2033
+ }
2034
+ get isInsideTask() {
2035
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
2036
+ }
2037
+ get ctx() {
2038
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
2039
+ }
2040
+ get worker() {
2041
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
2042
+ }
2043
+ get attributes() {
2044
+ if (this.ctx) {
2045
+ return {
2046
+ ...this.contextAttributes,
2047
+ ...this.workerAttributes
2048
+ };
1582
2049
  }
1583
- if (status === 404) {
1584
- return new NotFoundError(status, error, message, headers);
2050
+ return {};
2051
+ }
2052
+ get workerAttributes() {
2053
+ if (this.worker) {
2054
+ return {
2055
+ [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
2056
+ [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
2057
+ };
1585
2058
  }
1586
- if (status === 409) {
1587
- return new ConflictError(status, error, message, headers);
1588
- }
1589
- if (status === 422) {
1590
- return new UnprocessableEntityError(status, error, message, headers);
1591
- }
1592
- if (status === 429) {
1593
- return new RateLimitError(status, error, message, headers);
1594
- }
1595
- if (status >= 500) {
1596
- return new InternalServerError(status, error, message, headers);
1597
- }
1598
- return new _APIError(status, error, message, headers);
1599
- }
1600
- };
1601
- __name(_APIError, "APIError");
1602
- var APIError = _APIError;
1603
- var _APIConnectionError = class _APIConnectionError extends APIError {
1604
- constructor({ message, cause }) {
1605
- super(void 0, void 0, message || "Connection error.", void 0);
1606
- __publicField(this, "status");
1607
- if (cause)
1608
- this.cause = cause;
1609
- }
1610
- };
1611
- __name(_APIConnectionError, "APIConnectionError");
1612
- var APIConnectionError = _APIConnectionError;
1613
- var _BadRequestError = class _BadRequestError extends APIError {
1614
- constructor() {
1615
- super(...arguments);
1616
- __publicField(this, "status", 400);
1617
- }
1618
- };
1619
- __name(_BadRequestError, "BadRequestError");
1620
- var BadRequestError = _BadRequestError;
1621
- var _AuthenticationError = class _AuthenticationError extends APIError {
1622
- constructor() {
1623
- super(...arguments);
1624
- __publicField(this, "status", 401);
1625
- }
1626
- };
1627
- __name(_AuthenticationError, "AuthenticationError");
1628
- var AuthenticationError = _AuthenticationError;
1629
- var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1630
- constructor() {
1631
- super(...arguments);
1632
- __publicField(this, "status", 403);
1633
- }
1634
- };
1635
- __name(_PermissionDeniedError, "PermissionDeniedError");
1636
- var PermissionDeniedError = _PermissionDeniedError;
1637
- var _NotFoundError = class _NotFoundError extends APIError {
1638
- constructor() {
1639
- super(...arguments);
1640
- __publicField(this, "status", 404);
2059
+ return {};
1641
2060
  }
1642
- };
1643
- __name(_NotFoundError, "NotFoundError");
1644
- var NotFoundError = _NotFoundError;
1645
- var _ConflictError = class _ConflictError extends APIError {
1646
- constructor() {
1647
- super(...arguments);
1648
- __publicField(this, "status", 409);
2061
+ get contextAttributes() {
2062
+ if (this.ctx) {
2063
+ return {
2064
+ [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
2065
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
2066
+ [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
2067
+ [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
2068
+ [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
2069
+ [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
2070
+ [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
2071
+ [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
2072
+ [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
2073
+ [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
2074
+ [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
2075
+ [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
2076
+ [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
2077
+ [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
2078
+ [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
2079
+ [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
2080
+ [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
2081
+ [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
2082
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
2083
+ };
2084
+ }
2085
+ return {};
1649
2086
  }
1650
- };
1651
- __name(_ConflictError, "ConflictError");
1652
- var ConflictError = _ConflictError;
1653
- var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1654
- constructor() {
1655
- super(...arguments);
1656
- __publicField(this, "status", 422);
2087
+ disable() {
2088
+ unregisterGlobal(API_NAME);
1657
2089
  }
1658
- };
1659
- __name(_UnprocessableEntityError, "UnprocessableEntityError");
1660
- var UnprocessableEntityError = _UnprocessableEntityError;
1661
- var _RateLimitError = class _RateLimitError extends APIError {
1662
- constructor() {
1663
- super(...arguments);
1664
- __publicField(this, "status", 429);
2090
+ setGlobalTaskContext(taskContext2) {
2091
+ return registerGlobal(API_NAME, taskContext2);
1665
2092
  }
1666
2093
  };
1667
- __name(_RateLimitError, "RateLimitError");
1668
- var RateLimitError = _RateLimitError;
1669
- var _InternalServerError = class _InternalServerError extends APIError {
1670
- };
1671
- __name(_InternalServerError, "InternalServerError");
1672
- var InternalServerError = _InternalServerError;
1673
- function castToError(err) {
1674
- if (err instanceof Error)
1675
- return err;
1676
- return new Error(err);
1677
- }
1678
- __name(castToError, "castToError");
2094
+ _getTaskContext = new WeakSet();
2095
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
2096
+ return getGlobal(API_NAME);
2097
+ }, "#getTaskContext");
2098
+ __name(_TaskContextAPI, "TaskContextAPI");
2099
+ var TaskContextAPI = _TaskContextAPI;
2100
+
2101
+ // src/v3/task-context-api.ts
2102
+ var taskContext = TaskContextAPI.getInstance();
1679
2103
 
1680
2104
  // src/retry.ts
1681
2105
  function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
@@ -1783,8 +2207,6 @@ function calculateResetAt2(resets, format, now = Date.now()) {
1783
2207
  return resetAt?.getTime();
1784
2208
  }
1785
2209
  __name(calculateResetAt2, "calculateResetAt");
1786
-
1787
- // src/v3/zodfetch.ts
1788
2210
  var defaultRetryOptions2 = {
1789
2211
  maxAttempts: 3,
1790
2212
  factor: 2,
@@ -1796,6 +2218,32 @@ async function zodfetch(schema, url, requestInit, options) {
1796
2218
  return await _doZodFetch(schema, url, requestInit, options);
1797
2219
  }
1798
2220
  __name(zodfetch, "zodfetch");
2221
+ async function zodupload(schema, url, body, requestInit, options) {
2222
+ const form = await createForm(body);
2223
+ const encoder = new formDataEncoder.FormDataEncoder(form);
2224
+ const finalHeaders = {};
2225
+ for (const [key, value] of Object.entries(requestInit?.headers || {})) {
2226
+ finalHeaders[key] = value;
2227
+ }
2228
+ for (const [key, value] of Object.entries(encoder.headers)) {
2229
+ finalHeaders[key] = value;
2230
+ }
2231
+ finalHeaders["Content-Length"] = String(encoder.contentLength);
2232
+ const finalRequestInit = {
2233
+ ...requestInit,
2234
+ headers: finalHeaders,
2235
+ body: stream.Readable.from(encoder),
2236
+ // @ts-expect-error
2237
+ duplex: "half"
2238
+ };
2239
+ return await _doZodFetch(schema, url, finalRequestInit, options);
2240
+ }
2241
+ __name(zodupload, "zodupload");
2242
+ var createForm = /* @__PURE__ */ __name(async (body) => {
2243
+ const form = new FormData();
2244
+ await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
2245
+ return form;
2246
+ }, "createForm");
1799
2247
  async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1800
2248
  try {
1801
2249
  const response = await fetch(url, requestInitWithCache(requestInit));
@@ -1917,345 +2365,177 @@ function requestInitWithCache(requestInit) {
1917
2365
  }
1918
2366
  }
1919
2367
  __name(requestInitWithCache, "requestInitWithCache");
1920
-
1921
- // src/v3/utils/flattenAttributes.ts
1922
- function flattenAttributes(obj, prefix) {
1923
- const result = {};
1924
- if (!obj) {
1925
- return result;
1926
- }
1927
- if (typeof obj === "string") {
1928
- result[prefix || ""] = obj;
1929
- return result;
2368
+ var addFormValue = /* @__PURE__ */ __name(async (form, key, value) => {
2369
+ if (value === void 0)
2370
+ return;
2371
+ if (value == null) {
2372
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
2373
+ }
2374
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
2375
+ form.append(key, String(value));
2376
+ } else if (isUploadable(value) || isBlobLike(value) || value instanceof Buffer || value instanceof ArrayBuffer) {
2377
+ const file = await toFile(value);
2378
+ form.append(key, file);
2379
+ } else if (Array.isArray(value)) {
2380
+ await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
2381
+ } else if (typeof value === "object") {
2382
+ await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
2383
+ } else {
2384
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
2385
+ }
2386
+ }, "addFormValue");
2387
+ async function toFile(value, name, options) {
2388
+ value = await value;
2389
+ options ??= isFileLike(value) ? {
2390
+ lastModified: value.lastModified,
2391
+ type: value.type
2392
+ } : {};
2393
+ if (isResponseLike(value)) {
2394
+ const blob = await value.blob();
2395
+ name ||= new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file";
2396
+ return new File([
2397
+ blob
2398
+ ], name, options);
2399
+ }
2400
+ const bits = await getBytes(value);
2401
+ name ||= getName(value) ?? "unknown_file";
2402
+ if (!options.type) {
2403
+ const type = bits[0]?.type;
2404
+ if (typeof type === "string") {
2405
+ options = {
2406
+ ...options,
2407
+ type
2408
+ };
2409
+ }
1930
2410
  }
1931
- if (typeof obj === "number") {
1932
- result[prefix || ""] = obj;
1933
- return result;
2411
+ return new File(bits, name, options);
2412
+ }
2413
+ __name(toFile, "toFile");
2414
+ function getName(value) {
2415
+ return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream
2416
+ getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop();
2417
+ }
2418
+ __name(getName, "getName");
2419
+ var getStringFromMaybeBuffer = /* @__PURE__ */ __name((x) => {
2420
+ if (typeof x === "string")
2421
+ return x;
2422
+ if (typeof Buffer !== "undefined" && x instanceof Buffer)
2423
+ return String(x);
2424
+ return void 0;
2425
+ }, "getStringFromMaybeBuffer");
2426
+ async function getBytes(value) {
2427
+ let parts = [];
2428
+ if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
2429
+ value instanceof ArrayBuffer) {
2430
+ parts.push(value);
2431
+ } else if (isBlobLike(value)) {
2432
+ parts.push(await value.arrayBuffer());
2433
+ } else if (isAsyncIterableIterator(value)) {
2434
+ for await (const chunk of value) {
2435
+ parts.push(chunk);
2436
+ }
2437
+ } else {
2438
+ throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);
2439
+ }
2440
+ return parts;
2441
+ }
2442
+ __name(getBytes, "getBytes");
2443
+ function propsForError(value) {
2444
+ const props = Object.getOwnPropertyNames(value);
2445
+ return `[${props.map((p) => `"${p}"`).join(", ")}]`;
2446
+ }
2447
+ __name(propsForError, "propsForError");
2448
+ var isAsyncIterableIterator = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterableIterator");
2449
+ var isResponseLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", "isResponseLike");
2450
+ var isFileLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), "isFileLike");
2451
+ var isBlobLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", "isBlobLike");
2452
+ var isFsReadStream = /* @__PURE__ */ __name((value) => value instanceof stream.Readable, "isFsReadStream");
2453
+ var isUploadable = /* @__PURE__ */ __name((value) => {
2454
+ return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);
2455
+ }, "isUploadable");
2456
+ var isRecordLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => typeof key === "string" && typeof value[key] === "string"), "isRecordLike");
2457
+
2458
+ // src/v3/apiClient/index.ts
2459
+ var zodFetchOptions = {
2460
+ retry: {
2461
+ maxAttempts: 3,
2462
+ minTimeoutInMs: 1e3,
2463
+ maxTimeoutInMs: 3e4,
2464
+ factor: 2,
2465
+ randomize: false
1934
2466
  }
1935
- if (typeof obj === "boolean") {
1936
- result[prefix || ""] = obj;
1937
- return result;
2467
+ };
2468
+ var _getHeaders, getHeaders_fn;
2469
+ var _ApiClient = class _ApiClient {
2470
+ constructor(baseUrl, accessToken) {
2471
+ __privateAdd(this, _getHeaders);
2472
+ this.accessToken = accessToken;
2473
+ this.baseUrl = baseUrl.replace(/\/$/, "");
1938
2474
  }
1939
- for (const [key, value] of Object.entries(obj)) {
1940
- const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
1941
- if (Array.isArray(value)) {
1942
- for (let i = 0; i < value.length; i++) {
1943
- if (typeof value[i] === "object" && value[i] !== null) {
1944
- Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
1945
- } else {
1946
- result[`${newPrefix}.[${i}]`] = value[i];
2475
+ async getRunResult(runId) {
2476
+ try {
2477
+ return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
2478
+ method: "GET",
2479
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2480
+ }, zodFetchOptions);
2481
+ } catch (error) {
2482
+ if (error instanceof APIError) {
2483
+ if (error.status === 404) {
2484
+ return void 0;
1947
2485
  }
1948
2486
  }
1949
- } else if (isRecord(value)) {
1950
- Object.assign(result, flattenAttributes(value, newPrefix));
1951
- } else {
1952
- if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
1953
- result[newPrefix] = value;
1954
- }
2487
+ throw error;
1955
2488
  }
1956
2489
  }
1957
- return result;
1958
- }
1959
- __name(flattenAttributes, "flattenAttributes");
1960
- function isRecord(value) {
1961
- return value !== null && typeof value === "object" && !Array.isArray(value);
1962
- }
1963
- __name(isRecord, "isRecord");
1964
- function unflattenAttributes(obj) {
1965
- if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
1966
- return obj;
2490
+ async getBatchResults(batchId) {
2491
+ return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
2492
+ method: "GET",
2493
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2494
+ }, zodFetchOptions);
1967
2495
  }
1968
- const result = {};
1969
- for (const [key, value] of Object.entries(obj)) {
1970
- const parts = key.split(".").reduce((acc, part) => {
1971
- if (detectIsArrayIndex(part)) {
1972
- acc.push(part);
1973
- } else {
1974
- acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
1975
- }
1976
- return acc;
1977
- }, []);
1978
- let current = result;
1979
- for (let i = 0; i < parts.length - 1; i++) {
1980
- const part = parts[i];
1981
- const isArray = detectIsArrayIndex(part);
1982
- const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
1983
- const nextIsArray = detectIsArrayIndex(parts[i + 1]);
1984
- if (!current[cleanPart]) {
1985
- current[cleanPart] = nextIsArray ? [] : {};
1986
- }
1987
- current = current[cleanPart];
1988
- }
1989
- const lastPart = parts[parts.length - 1];
1990
- const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
1991
- current[cleanLastPart] = value;
2496
+ triggerTask(taskId, body, options) {
2497
+ return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
2498
+ method: "POST",
2499
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2500
+ body: JSON.stringify(body)
2501
+ }, zodFetchOptions);
1992
2502
  }
1993
- return result;
1994
- }
1995
- __name(unflattenAttributes, "unflattenAttributes");
1996
- function detectIsArrayIndex(key) {
1997
- const match = key.match(/^\[(\d+)\]$/);
1998
- if (match) {
1999
- return true;
2503
+ batchTriggerTask(taskId, body, options) {
2504
+ return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
2505
+ method: "POST",
2506
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2507
+ body: JSON.stringify(body)
2508
+ }, zodFetchOptions);
2000
2509
  }
2001
- return false;
2002
- }
2003
- __name(detectIsArrayIndex, "detectIsArrayIndex");
2004
- function primitiveValueOrflattenedAttributes(obj, prefix) {
2005
- if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
2006
- return obj;
2510
+ createUploadPayloadUrl(filename) {
2511
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2512
+ method: "PUT",
2513
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2514
+ }, zodFetchOptions);
2007
2515
  }
2008
- const attributes = flattenAttributes(obj, prefix);
2009
- if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
2010
- return attributes[prefix];
2516
+ getPayloadUrl(filename) {
2517
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2518
+ method: "GET",
2519
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2520
+ }, zodFetchOptions);
2011
2521
  }
2012
- return attributes;
2013
- }
2014
- __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
2015
- var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
2016
- constructor() {
2017
- this.storage = new async_hooks.AsyncLocalStorage();
2522
+ retrieveRun(runId) {
2523
+ return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v3/runs/${runId}`, {
2524
+ method: "GET",
2525
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2526
+ }, zodFetchOptions);
2018
2527
  }
2019
- runWith(context3, fn) {
2020
- return this.storage.run(context3, fn);
2528
+ replayRun(runId) {
2529
+ return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2530
+ method: "POST",
2531
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2532
+ }, zodFetchOptions);
2021
2533
  }
2022
- getStore() {
2023
- return this.storage.getStore();
2024
- }
2025
- };
2026
- __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
2027
- var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
2028
-
2029
- // src/v3/semanticInternalAttributes.ts
2030
- var SemanticInternalAttributes = {
2031
- ENVIRONMENT_ID: "ctx.environment.id",
2032
- ENVIRONMENT_TYPE: "ctx.environment.type",
2033
- ORGANIZATION_ID: "ctx.organization.id",
2034
- ORGANIZATION_SLUG: "ctx.organization.slug",
2035
- ORGANIZATION_NAME: "ctx.organization.name",
2036
- PROJECT_ID: "ctx.project.id",
2037
- PROJECT_REF: "ctx.project.ref",
2038
- PROJECT_NAME: "ctx.project.title",
2039
- PROJECT_DIR: "project.dir",
2040
- ATTEMPT_ID: "ctx.attempt.id",
2041
- ATTEMPT_NUMBER: "ctx.attempt.number",
2042
- RUN_ID: "ctx.run.id",
2043
- RUN_IS_TEST: "ctx.run.isTest",
2044
- BATCH_ID: "ctx.batch.id",
2045
- TASK_SLUG: "ctx.task.id",
2046
- TASK_PATH: "ctx.task.filePath",
2047
- TASK_EXPORT_NAME: "ctx.task.exportName",
2048
- QUEUE_NAME: "ctx.queue.name",
2049
- QUEUE_ID: "ctx.queue.id",
2050
- SPAN_PARTIAL: "$span.partial",
2051
- SPAN_ID: "$span.span_id",
2052
- OUTPUT: "$output",
2053
- OUTPUT_TYPE: "$mime_type_output",
2054
- STYLE: "$style",
2055
- STYLE_ICON: "$style.icon",
2056
- STYLE_VARIANT: "$style.variant",
2057
- STYLE_ACCESSORY: "$style.accessory",
2058
- METADATA: "$metadata",
2059
- TRIGGER: "$trigger",
2060
- PAYLOAD: "$payload",
2061
- PAYLOAD_TYPE: "$mime_type_payload",
2062
- SHOW: "$show",
2063
- SHOW_ACTIONS: "$show.actions",
2064
- WORKER_ID: "worker.id",
2065
- WORKER_VERSION: "worker.version",
2066
- CLI_VERSION: "cli.version",
2067
- SDK_VERSION: "sdk.version",
2068
- SDK_LANGUAGE: "sdk.language",
2069
- RETRY_AT: "retry.at",
2070
- RETRY_DELAY: "retry.delay",
2071
- RETRY_COUNT: "retry.count",
2072
- LINK_TITLE: "$link.title"
2073
- };
2074
-
2075
- // src/v3/tasks/taskContextManager.ts
2076
- var _getStore, getStore_fn;
2077
- var _TaskContextManager = class _TaskContextManager {
2078
- constructor() {
2079
- __privateAdd(this, _getStore);
2080
- __publicField(this, "_storage", new SafeAsyncLocalStorage());
2081
- }
2082
- get isInsideTask() {
2083
- return __privateMethod(this, _getStore, getStore_fn).call(this) !== void 0;
2084
- }
2085
- get ctx() {
2086
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2087
- return store?.ctx;
2088
- }
2089
- get worker() {
2090
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2091
- return store?.worker;
2092
- }
2093
- get attributes() {
2094
- if (this.ctx) {
2095
- return {
2096
- ...this.contextAttributes,
2097
- ...this.workerAttributes
2098
- };
2099
- }
2100
- return {};
2101
- }
2102
- get workerAttributes() {
2103
- if (this.worker) {
2104
- return {
2105
- [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
2106
- [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
2107
- };
2108
- }
2109
- return {};
2110
- }
2111
- get contextAttributes() {
2112
- if (this.ctx) {
2113
- return {
2114
- [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
2115
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
2116
- [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
2117
- [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
2118
- [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
2119
- [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
2120
- [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
2121
- [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
2122
- [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
2123
- [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
2124
- [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
2125
- [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
2126
- [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
2127
- [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
2128
- [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
2129
- [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
2130
- [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
2131
- [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id
2132
- };
2133
- }
2134
- return {};
2135
- }
2136
- runWith(context3, fn) {
2137
- return this._storage.runWith(context3, fn);
2138
- }
2139
- };
2140
- _getStore = new WeakSet();
2141
- getStore_fn = /* @__PURE__ */ __name(function() {
2142
- return this._storage.getStore();
2143
- }, "#getStore");
2144
- __name(_TaskContextManager, "TaskContextManager");
2145
- var TaskContextManager = _TaskContextManager;
2146
- var taskContextManager = new TaskContextManager();
2147
- var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
2148
- constructor(innerProcessor) {
2149
- this._innerProcessor = innerProcessor;
2150
- }
2151
- // Called when a span starts
2152
- onStart(span, parentContext) {
2153
- if (taskContextManager.ctx) {
2154
- span.setAttributes(flattenAttributes({
2155
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
2156
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
2157
- }, SemanticInternalAttributes.METADATA));
2158
- }
2159
- this._innerProcessor.onStart(span, parentContext);
2160
- }
2161
- // Delegate the rest of the methods to the wrapped processor
2162
- onEnd(span) {
2163
- this._innerProcessor.onEnd(span);
2164
- }
2165
- shutdown() {
2166
- return this._innerProcessor.shutdown();
2167
- }
2168
- forceFlush() {
2169
- return this._innerProcessor.forceFlush();
2170
- }
2171
- };
2172
- __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
2173
- var TaskContextSpanProcessor = _TaskContextSpanProcessor;
2174
- var _TaskContextLogProcessor = class _TaskContextLogProcessor {
2175
- constructor(innerProcessor) {
2176
- this._innerProcessor = innerProcessor;
2177
- }
2178
- forceFlush() {
2179
- return this._innerProcessor.forceFlush();
2180
- }
2181
- onEmit(logRecord, context3) {
2182
- if (taskContextManager.ctx) {
2183
- logRecord.setAttributes(flattenAttributes({
2184
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
2185
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
2186
- }, SemanticInternalAttributes.METADATA));
2187
- }
2188
- this._innerProcessor.onEmit(logRecord, context3);
2189
- }
2190
- shutdown() {
2191
- return this._innerProcessor.shutdown();
2192
- }
2193
- };
2194
- __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
2195
- var TaskContextLogProcessor = _TaskContextLogProcessor;
2196
-
2197
- // src/v3/utils/getEnv.ts
2198
- function getEnvVar(name) {
2199
- if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
2200
- return process.env[name];
2201
- }
2202
- }
2203
- __name(getEnvVar, "getEnvVar");
2204
-
2205
- // src/v3/apiClient/index.ts
2206
- var zodFetchOptions = {
2207
- retry: {
2208
- maxAttempts: 3,
2209
- minTimeoutInMs: 1e3,
2210
- maxTimeoutInMs: 3e4,
2211
- factor: 2,
2212
- randomize: false
2213
- }
2214
- };
2215
- var _getHeaders, getHeaders_fn;
2216
- var _ApiClient = class _ApiClient {
2217
- constructor(baseUrl, accessToken) {
2218
- __privateAdd(this, _getHeaders);
2219
- this.accessToken = accessToken;
2220
- this.baseUrl = baseUrl.replace(/\/$/, "");
2221
- }
2222
- triggerTask(taskId, body, options) {
2223
- return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
2224
- method: "POST",
2225
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2226
- body: JSON.stringify(body)
2227
- }, zodFetchOptions);
2228
- }
2229
- batchTriggerTask(taskId, body, options) {
2230
- return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
2231
- method: "POST",
2232
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2233
- body: JSON.stringify(body)
2234
- }, zodFetchOptions);
2235
- }
2236
- createUploadPayloadUrl(filename) {
2237
- return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2238
- method: "PUT",
2239
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2240
- }, zodFetchOptions);
2241
- }
2242
- getPayloadUrl(filename) {
2243
- return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2244
- method: "GET",
2245
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2246
- }, zodFetchOptions);
2247
- }
2248
- replayRun(runId) {
2249
- return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2250
- method: "POST",
2251
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2252
- }, zodFetchOptions);
2253
- }
2254
- cancelRun(runId) {
2255
- return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
2256
- method: "POST",
2257
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2258
- }, zodFetchOptions);
2534
+ cancelRun(runId) {
2535
+ return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
2536
+ method: "POST",
2537
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2538
+ }, zodFetchOptions);
2259
2539
  }
2260
2540
  createSchedule(options) {
2261
2541
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
@@ -2308,14 +2588,62 @@ var _ApiClient = class _ApiClient {
2308
2588
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2309
2589
  });
2310
2590
  }
2591
+ listEnvVars(projectRef, slug) {
2592
+ return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2593
+ method: "GET",
2594
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2595
+ });
2596
+ }
2597
+ importEnvVars(projectRef, slug, body) {
2598
+ if (isRecordLike(body.variables)) {
2599
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
2600
+ method: "POST",
2601
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2602
+ body: JSON.stringify(body)
2603
+ });
2604
+ } else {
2605
+ return zodupload(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, body, {
2606
+ method: "POST",
2607
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2608
+ });
2609
+ }
2610
+ }
2611
+ retrieveEnvVar(projectRef, slug, key) {
2612
+ return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2613
+ method: "GET",
2614
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2615
+ });
2616
+ }
2617
+ createEnvVar(projectRef, slug, body) {
2618
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2619
+ method: "POST",
2620
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2621
+ body: JSON.stringify(body)
2622
+ });
2623
+ }
2624
+ updateEnvVar(projectRef, slug, key, body) {
2625
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2626
+ method: "PUT",
2627
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2628
+ body: JSON.stringify(body)
2629
+ });
2630
+ }
2631
+ deleteEnvVar(projectRef, slug, key) {
2632
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2633
+ method: "DELETE",
2634
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2635
+ });
2636
+ }
2311
2637
  };
2312
2638
  _getHeaders = new WeakSet();
2313
2639
  getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2314
2640
  const headers = {
2315
2641
  "Content-Type": "application/json",
2316
- Authorization: `Bearer ${this.accessToken}`
2642
+ Authorization: `Bearer ${this.accessToken}`,
2643
+ "trigger-version": version
2317
2644
  };
2318
- if (taskContextManager.isInsideTask) {
2645
+ if (taskContext.isInsideTask) {
2646
+ headers["x-trigger-worker"] = "true";
2319
2647
  api.propagation.inject(api.context.active(), headers);
2320
2648
  if (spanParentAsLink) {
2321
2649
  headers["x-trigger-span-parent-as-link"] = "1";
@@ -2325,767 +2653,63 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2325
2653
  }, "#getHeaders");
2326
2654
  __name(_ApiClient, "ApiClient");
2327
2655
  var ApiClient = _ApiClient;
2328
- var _getStore2, getStore_fn2;
2329
- var _ApiClientManager = class _ApiClientManager {
2330
- constructor() {
2331
- __privateAdd(this, _getStore2);
2332
- __publicField(this, "_storage", new SafeAsyncLocalStorage());
2656
+ var _SimpleClock = class _SimpleClock {
2657
+ preciseNow() {
2658
+ const now = new preciseDate.PreciseDate();
2659
+ const nowStruct = now.toStruct();
2660
+ return [
2661
+ nowStruct.seconds,
2662
+ nowStruct.nanos
2663
+ ];
2333
2664
  }
2334
- get baseURL() {
2335
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2336
- return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
2665
+ reset() {
2337
2666
  }
2338
- get accessToken() {
2339
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2340
- return store?.accessToken ?? getEnvVar("TRIGGER_SECRET_KEY");
2667
+ };
2668
+ __name(_SimpleClock, "SimpleClock");
2669
+ var SimpleClock = _SimpleClock;
2670
+
2671
+ // src/v3/clock/index.ts
2672
+ var API_NAME2 = "clock";
2673
+ var SIMPLE_CLOCK = new SimpleClock();
2674
+ var _getClock, getClock_fn;
2675
+ var _ClockAPI = class _ClockAPI {
2676
+ constructor() {
2677
+ __privateAdd(this, _getClock);
2341
2678
  }
2342
- get client() {
2343
- if (!this.baseURL || !this.accessToken) {
2344
- return void 0;
2679
+ static getInstance() {
2680
+ if (!this._instance) {
2681
+ this._instance = new _ClockAPI();
2345
2682
  }
2346
- return new ApiClient(this.baseURL, this.accessToken);
2683
+ return this._instance;
2684
+ }
2685
+ setGlobalClock(clock2) {
2686
+ return registerGlobal(API_NAME2, clock2);
2347
2687
  }
2348
- runWith(context3, fn) {
2349
- return this._storage.runWith(context3, fn);
2688
+ preciseNow() {
2689
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2350
2690
  }
2351
- };
2352
- _getStore2 = new WeakSet();
2353
- getStore_fn2 = /* @__PURE__ */ __name(function() {
2354
- return this._storage.getStore();
2355
- }, "#getStore");
2356
- __name(_ApiClientManager, "ApiClientManager");
2357
- var ApiClientManager = _ApiClientManager;
2358
- var apiClientManager = new ApiClientManager();
2359
- var _ZodSchemaParsedError = class _ZodSchemaParsedError extends Error {
2360
- constructor(error, payload) {
2361
- super(error.message);
2362
- this.error = error;
2363
- this.payload = payload;
2691
+ reset() {
2692
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2364
2693
  }
2365
2694
  };
2366
- __name(_ZodSchemaParsedError, "ZodSchemaParsedError");
2367
- var ZodSchemaParsedError = _ZodSchemaParsedError;
2368
- var ZodMessageSchema = zod.z.object({
2369
- version: zod.z.literal("v1").default("v1"),
2370
- type: zod.z.string(),
2371
- payload: zod.z.unknown()
2372
- });
2373
- var _schema, _handlers;
2374
- var _ZodMessageHandler = class _ZodMessageHandler {
2375
- constructor(options) {
2376
- __privateAdd(this, _schema, void 0);
2377
- __privateAdd(this, _handlers, void 0);
2378
- __privateSet(this, _schema, options.schema);
2379
- __privateSet(this, _handlers, options.messages);
2380
- }
2381
- async handleMessage(message) {
2382
- const parsedMessage = this.parseMessage(message);
2383
- if (!__privateGet(this, _handlers)) {
2384
- throw new Error("No handlers provided");
2385
- }
2386
- const handler = __privateGet(this, _handlers)[parsedMessage.type];
2387
- if (!handler) {
2388
- console.error(`No handler for message type: ${String(parsedMessage.type)}`);
2389
- return;
2390
- }
2391
- const ack = await handler(parsedMessage.payload);
2392
- return ack;
2393
- }
2394
- parseMessage(message) {
2395
- const parsedMessage = ZodMessageSchema.safeParse(message);
2396
- if (!parsedMessage.success) {
2397
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2398
- }
2399
- const schema = __privateGet(this, _schema)[parsedMessage.data.type];
2400
- if (!schema) {
2401
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2402
- }
2403
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2404
- if (!parsedPayload.success) {
2405
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2406
- }
2695
+ _getClock = new WeakSet();
2696
+ getClock_fn = /* @__PURE__ */ __name(function() {
2697
+ return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2698
+ }, "#getClock");
2699
+ __name(_ClockAPI, "ClockAPI");
2700
+ var ClockAPI = _ClockAPI;
2701
+
2702
+ // src/v3/clock-api.ts
2703
+ var clock = ClockAPI.getInstance();
2704
+
2705
+ // src/v3/errors.ts
2706
+ function parseError(error) {
2707
+ if (error instanceof Error) {
2407
2708
  return {
2408
- type: parsedMessage.data.type,
2409
- payload: parsedPayload.data
2410
- };
2411
- }
2412
- registerHandlers(emitter, logger2) {
2413
- const log = logger2 ?? console;
2414
- if (!__privateGet(this, _handlers)) {
2415
- log.info("No handlers provided");
2416
- return;
2417
- }
2418
- for (const eventName of Object.keys(__privateGet(this, _schema))) {
2419
- emitter.on(eventName, async (message, callback) => {
2420
- log.info(`handling ${eventName}`, {
2421
- payload: message,
2422
- hasCallback: !!callback
2423
- });
2424
- let ack;
2425
- if ("payload" in message) {
2426
- ack = await this.handleMessage({
2427
- type: eventName,
2428
- ...message
2429
- });
2430
- } else {
2431
- const { version, ...payload } = message;
2432
- ack = await this.handleMessage({
2433
- type: eventName,
2434
- version,
2435
- payload
2436
- });
2437
- }
2438
- if (callback && typeof callback === "function") {
2439
- callback(ack);
2440
- }
2441
- });
2442
- }
2443
- }
2444
- };
2445
- _schema = new WeakMap();
2446
- _handlers = new WeakMap();
2447
- __name(_ZodMessageHandler, "ZodMessageHandler");
2448
- var ZodMessageHandler = _ZodMessageHandler;
2449
- var _schema2, _sender;
2450
- var _ZodMessageSender = class _ZodMessageSender {
2451
- constructor(options) {
2452
- __privateAdd(this, _schema2, void 0);
2453
- __privateAdd(this, _sender, void 0);
2454
- __privateSet(this, _schema2, options.schema);
2455
- __privateSet(this, _sender, options.sender);
2456
- }
2457
- async send(type, payload) {
2458
- const schema = __privateGet(this, _schema2)[type];
2459
- if (!schema) {
2460
- throw new Error(`Unknown message type: ${type}`);
2461
- }
2462
- const parsedPayload = schema.safeParse(payload);
2463
- if (!parsedPayload.success) {
2464
- throw new ZodSchemaParsedError(parsedPayload.error, payload);
2465
- }
2466
- await __privateGet(this, _sender).call(this, {
2467
- type,
2468
- payload,
2469
- version: "v1"
2470
- });
2471
- }
2472
- async forwardMessage(message) {
2473
- const parsedMessage = ZodMessageSchema.safeParse(message);
2474
- if (!parsedMessage.success) {
2475
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2476
- }
2477
- const schema = __privateGet(this, _schema2)[parsedMessage.data.type];
2478
- if (!schema) {
2479
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2480
- }
2481
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2482
- if (!parsedPayload.success) {
2483
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2484
- }
2485
- await __privateGet(this, _sender).call(this, {
2486
- type: parsedMessage.data.type,
2487
- payload: parsedPayload.data,
2488
- version: "v1"
2489
- });
2490
- }
2491
- };
2492
- _schema2 = new WeakMap();
2493
- _sender = new WeakMap();
2494
- __name(_ZodMessageSender, "ZodMessageSender");
2495
- var ZodMessageSender = _ZodMessageSender;
2496
- var messageSchema = zod.z.object({
2497
- version: zod.z.literal("v1").default("v1"),
2498
- type: zod.z.string(),
2499
- payload: zod.z.unknown()
2500
- });
2501
- var _schema3, _handlers2;
2502
- var _ZodSocketMessageHandler = class _ZodSocketMessageHandler {
2503
- constructor(options) {
2504
- __privateAdd(this, _schema3, void 0);
2505
- __privateAdd(this, _handlers2, void 0);
2506
- __privateSet(this, _schema3, options.schema);
2507
- __privateSet(this, _handlers2, options.handlers);
2508
- }
2509
- async handleMessage(message) {
2510
- const parsedMessage = this.parseMessage(message);
2511
- if (!__privateGet(this, _handlers2)) {
2512
- throw new Error("No handlers provided");
2513
- }
2514
- const handler = __privateGet(this, _handlers2)[parsedMessage.type];
2515
- if (!handler) {
2516
- console.error(`No handler for message type: ${String(parsedMessage.type)}`);
2517
- return;
2518
- }
2519
- const ack = await handler(parsedMessage.payload);
2520
- return ack;
2521
- }
2522
- parseMessage(message) {
2523
- const parsedMessage = messageSchema.safeParse(message);
2524
- if (!parsedMessage.success) {
2525
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2526
- }
2527
- const schema = __privateGet(this, _schema3)[parsedMessage.data.type]["message"];
2528
- if (!schema) {
2529
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2530
- }
2531
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2532
- if (!parsedPayload.success) {
2533
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2534
- }
2535
- return {
2536
- type: parsedMessage.data.type,
2537
- payload: parsedPayload.data
2538
- };
2539
- }
2540
- registerHandlers(emitter, logger2) {
2541
- const log = logger2 ?? console;
2542
- if (!__privateGet(this, _handlers2)) {
2543
- log.info("No handlers provided");
2544
- return;
2545
- }
2546
- for (const eventName of Object.keys(__privateGet(this, _handlers2))) {
2547
- emitter.on(eventName, async (message, callback) => {
2548
- log.info(`handling ${eventName}`, {
2549
- payload: message,
2550
- hasCallback: !!callback
2551
- });
2552
- let ack;
2553
- try {
2554
- if ("payload" in message) {
2555
- ack = await this.handleMessage({
2556
- type: eventName,
2557
- ...message
2558
- });
2559
- } else {
2560
- const { version, ...payload } = message;
2561
- ack = await this.handleMessage({
2562
- type: eventName,
2563
- version,
2564
- payload
2565
- });
2566
- }
2567
- } catch (error) {
2568
- log.error("Error while handling message", {
2569
- error
2570
- });
2571
- return;
2572
- }
2573
- if (callback && typeof callback === "function") {
2574
- callback(ack);
2575
- }
2576
- });
2577
- }
2578
- }
2579
- };
2580
- _schema3 = new WeakMap();
2581
- _handlers2 = new WeakMap();
2582
- __name(_ZodSocketMessageHandler, "ZodSocketMessageHandler");
2583
- var ZodSocketMessageHandler = _ZodSocketMessageHandler;
2584
- var _schema4, _socket;
2585
- var _ZodSocketMessageSender = class _ZodSocketMessageSender {
2586
- constructor(options) {
2587
- __privateAdd(this, _schema4, void 0);
2588
- __privateAdd(this, _socket, void 0);
2589
- __privateSet(this, _schema4, options.schema);
2590
- __privateSet(this, _socket, options.socket);
2591
- }
2592
- send(type, payload) {
2593
- const schema = __privateGet(this, _schema4)[type]["message"];
2594
- if (!schema) {
2595
- throw new Error(`Unknown message type: ${type}`);
2596
- }
2597
- const parsedPayload = schema.safeParse(payload);
2598
- if (!parsedPayload.success) {
2599
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2600
- }
2601
- __privateGet(this, _socket).emit(type, {
2602
- payload,
2603
- version: "v1"
2604
- });
2605
- return;
2606
- }
2607
- async sendWithAck(type, payload) {
2608
- const schema = __privateGet(this, _schema4)[type]["message"];
2609
- if (!schema) {
2610
- throw new Error(`Unknown message type: ${type}`);
2611
- }
2612
- const parsedPayload = schema.safeParse(payload);
2613
- if (!parsedPayload.success) {
2614
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2615
- }
2616
- const callbackResult = await __privateGet(this, _socket).emitWithAck(type, {
2617
- payload,
2618
- version: "v1"
2619
- });
2620
- return callbackResult;
2621
- }
2622
- };
2623
- _schema4 = new WeakMap();
2624
- _socket = new WeakMap();
2625
- __name(_ZodSocketMessageSender, "ZodSocketMessageSender");
2626
- var ZodSocketMessageSender = _ZodSocketMessageSender;
2627
- var _sender2, _handler, _logger;
2628
- var _ZodSocketConnection = class _ZodSocketConnection {
2629
- constructor(opts) {
2630
- __privateAdd(this, _sender2, void 0);
2631
- __privateAdd(this, _handler, void 0);
2632
- __privateAdd(this, _logger, void 0);
2633
- const uri = `${opts.secure ? "wss" : "ws"}://${opts.host}:${opts.port ?? (opts.secure ? "443" : "80")}/${opts.namespace}`;
2634
- const logger2 = new SimpleStructuredLogger(opts.namespace, exports.LogLevel.info);
2635
- logger2.log("new zod socket", {
2636
- uri
2637
- });
2638
- this.socket = socket_ioClient.io(uri, {
2639
- transports: [
2640
- "websocket"
2641
- ],
2642
- auth: {
2643
- token: opts.authToken
2644
- },
2645
- extraHeaders: opts.extraHeaders,
2646
- reconnectionDelay: 500,
2647
- reconnectionDelayMax: 1e3
2648
- });
2649
- __privateSet(this, _logger, logger2.child({
2650
- socketId: this.socket.id
2651
- }));
2652
- __privateSet(this, _handler, new ZodSocketMessageHandler({
2653
- schema: opts.serverMessages,
2654
- handlers: opts.handlers
2655
- }));
2656
- __privateGet(this, _handler).registerHandlers(this.socket, __privateGet(this, _logger));
2657
- __privateSet(this, _sender2, new ZodSocketMessageSender({
2658
- schema: opts.clientMessages,
2659
- socket: this.socket
2660
- }));
2661
- this.socket.on("connect_error", async (error) => {
2662
- __privateGet(this, _logger).error(`connect_error: ${error}`);
2663
- if (opts.onError) {
2664
- await opts.onError(this.socket, error, __privateGet(this, _logger));
2665
- }
2666
- });
2667
- this.socket.on("connect", async () => {
2668
- __privateGet(this, _logger).info("connect");
2669
- if (opts.onConnection) {
2670
- await opts.onConnection(this.socket, __privateGet(this, _handler), __privateGet(this, _sender2), __privateGet(this, _logger));
2671
- }
2672
- });
2673
- this.socket.on("disconnect", async (reason, description) => {
2674
- __privateGet(this, _logger).info("disconnect", {
2675
- reason,
2676
- description
2677
- });
2678
- if (opts.onDisconnect) {
2679
- await opts.onDisconnect(this.socket, reason, description, __privateGet(this, _logger));
2680
- }
2681
- });
2682
- }
2683
- close() {
2684
- this.socket.close();
2685
- }
2686
- connect() {
2687
- this.socket.connect();
2688
- }
2689
- get send() {
2690
- return __privateGet(this, _sender2).send.bind(__privateGet(this, _sender2));
2691
- }
2692
- get sendWithAck() {
2693
- return __privateGet(this, _sender2).sendWithAck.bind(__privateGet(this, _sender2));
2694
- }
2695
- };
2696
- _sender2 = new WeakMap();
2697
- _handler = new WeakMap();
2698
- _logger = new WeakMap();
2699
- __name(_ZodSocketConnection, "ZodSocketConnection");
2700
- var ZodSocketConnection = _ZodSocketConnection;
2701
-
2702
- // src/v3/zodNamespace.ts
2703
- exports.LogLevel = void 0;
2704
- (function(LogLevel2) {
2705
- LogLevel2[LogLevel2["log"] = 0] = "log";
2706
- LogLevel2[LogLevel2["error"] = 1] = "error";
2707
- LogLevel2[LogLevel2["warn"] = 2] = "warn";
2708
- LogLevel2[LogLevel2["info"] = 3] = "info";
2709
- LogLevel2[LogLevel2["debug"] = 4] = "debug";
2710
- })(exports.LogLevel || (exports.LogLevel = {}));
2711
- var _structuredLog, structuredLog_fn;
2712
- var _SimpleStructuredLogger = class _SimpleStructuredLogger {
2713
- constructor(name, level = [
2714
- "1",
2715
- "true"
2716
- ].includes(process.env.DEBUG ?? "") ? exports.LogLevel.debug : exports.LogLevel.info, fields) {
2717
- __privateAdd(this, _structuredLog);
2718
- this.name = name;
2719
- this.level = level;
2720
- this.fields = fields;
2721
- }
2722
- child(fields, level) {
2723
- return new _SimpleStructuredLogger(this.name, level, {
2724
- ...this.fields,
2725
- ...fields
2726
- });
2727
- }
2728
- log(message, ...args) {
2729
- if (this.level < exports.LogLevel.log)
2730
- return;
2731
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.log, message, "log", ...args);
2732
- }
2733
- error(message, ...args) {
2734
- if (this.level < exports.LogLevel.error)
2735
- return;
2736
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.error, message, "error", ...args);
2737
- }
2738
- warn(message, ...args) {
2739
- if (this.level < exports.LogLevel.warn)
2740
- return;
2741
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.warn, message, "warn", ...args);
2742
- }
2743
- info(message, ...args) {
2744
- if (this.level < exports.LogLevel.info)
2745
- return;
2746
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.info, message, "info", ...args);
2747
- }
2748
- debug(message, ...args) {
2749
- if (this.level < exports.LogLevel.debug)
2750
- return;
2751
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.debug, message, "debug", ...args);
2752
- }
2753
- };
2754
- _structuredLog = new WeakSet();
2755
- structuredLog_fn = /* @__PURE__ */ __name(function(loggerFunction, message, level, ...args) {
2756
- const structuredLog = {
2757
- ...args.length === 1 ? args[0] : args,
2758
- ...this.fields,
2759
- timestamp: /* @__PURE__ */ new Date(),
2760
- name: this.name,
2761
- message,
2762
- level
2763
- };
2764
- loggerFunction(JSON.stringify(structuredLog));
2765
- }, "#structuredLog");
2766
- __name(_SimpleStructuredLogger, "SimpleStructuredLogger");
2767
- var SimpleStructuredLogger = _SimpleStructuredLogger;
2768
- var _logger2, _handler2;
2769
- var _ZodNamespace = class _ZodNamespace {
2770
- constructor(opts) {
2771
- __privateAdd(this, _logger2, void 0);
2772
- __privateAdd(this, _handler2, void 0);
2773
- __privateSet(this, _logger2, opts.logger ?? new SimpleStructuredLogger(opts.name));
2774
- __privateSet(this, _handler2, new ZodSocketMessageHandler({
2775
- schema: opts.clientMessages,
2776
- handlers: opts.handlers
2777
- }));
2778
- this.io = opts.io;
2779
- this.namespace = this.io.of(opts.name);
2780
- this.sender = new ZodMessageSender({
2781
- schema: opts.serverMessages,
2782
- sender: async (message) => {
2783
- return new Promise((resolve, reject) => {
2784
- try {
2785
- this.namespace.emit(message.type, message.payload);
2786
- resolve();
2787
- } catch (err) {
2788
- reject(err);
2789
- }
2790
- });
2791
- }
2792
- });
2793
- if (opts.preAuth) {
2794
- this.namespace.use(async (socket, next) => {
2795
- const logger2 = __privateGet(this, _logger2).child({
2796
- socketId: socket.id,
2797
- socketStage: "preAuth"
2798
- });
2799
- if (typeof opts.preAuth === "function") {
2800
- await opts.preAuth(socket, next, logger2);
2801
- }
2802
- });
2803
- }
2804
- if (opts.authToken) {
2805
- this.namespace.use((socket, next) => {
2806
- const logger2 = __privateGet(this, _logger2).child({
2807
- socketId: socket.id,
2808
- socketStage: "auth"
2809
- });
2810
- const { auth } = socket.handshake;
2811
- if (!("token" in auth)) {
2812
- logger2.error("no token");
2813
- return socket.disconnect(true);
2814
- }
2815
- if (auth.token !== opts.authToken) {
2816
- logger2.error("invalid token");
2817
- return socket.disconnect(true);
2818
- }
2819
- logger2.info("success");
2820
- next();
2821
- });
2822
- }
2823
- if (opts.postAuth) {
2824
- this.namespace.use(async (socket, next) => {
2825
- const logger2 = __privateGet(this, _logger2).child({
2826
- socketId: socket.id,
2827
- socketStage: "auth"
2828
- });
2829
- if (typeof opts.postAuth === "function") {
2830
- await opts.postAuth(socket, next, logger2);
2831
- }
2832
- });
2833
- }
2834
- this.namespace.on("connection", async (socket) => {
2835
- const logger2 = __privateGet(this, _logger2).child({
2836
- socketId: socket.id,
2837
- socketStage: "connection"
2838
- });
2839
- logger2.info("connected");
2840
- __privateGet(this, _handler2).registerHandlers(socket, logger2);
2841
- socket.on("disconnect", async (reason, description) => {
2842
- logger2.info("disconnect", {
2843
- reason,
2844
- description
2845
- });
2846
- if (opts.onDisconnect) {
2847
- await opts.onDisconnect(socket, reason, description, logger2);
2848
- }
2849
- });
2850
- socket.on("error", async (error) => {
2851
- logger2.error("error", {
2852
- error
2853
- });
2854
- if (opts.onError) {
2855
- await opts.onError(socket, error, logger2);
2856
- }
2857
- });
2858
- if (opts.onConnection) {
2859
- await opts.onConnection(socket, __privateGet(this, _handler2), this.sender, logger2);
2860
- }
2861
- });
2862
- }
2863
- fetchSockets() {
2864
- return this.namespace.fetchSockets();
2865
- }
2866
- };
2867
- _logger2 = new WeakMap();
2868
- _handler2 = new WeakMap();
2869
- __name(_ZodNamespace, "ZodNamespace");
2870
- var ZodNamespace = _ZodNamespace;
2871
- var messageSchema2 = zod.z.object({
2872
- version: zod.z.literal("v1").default("v1"),
2873
- type: zod.z.string(),
2874
- payload: zod.z.unknown()
2875
- });
2876
- var _schema5, _handlers3, _sender3, _a;
2877
- var ZodIpcMessageHandler = (_a = class {
2878
- constructor(options) {
2879
- __privateAdd(this, _schema5, void 0);
2880
- __privateAdd(this, _handlers3, void 0);
2881
- __privateAdd(this, _sender3, void 0);
2882
- __privateSet(this, _schema5, options.schema);
2883
- __privateSet(this, _handlers3, options.handlers);
2884
- __privateSet(this, _sender3, options.sender);
2885
- }
2886
- async handleMessage(message) {
2887
- const parsedMessage = this.parseMessage(message);
2888
- if (!__privateGet(this, _handlers3)) {
2889
- throw new Error("No handlers provided");
2890
- }
2891
- const handler = __privateGet(this, _handlers3)[parsedMessage.type];
2892
- if (!handler) {
2893
- return;
2894
- }
2895
- const ack = await handler(parsedMessage.payload, __privateGet(this, _sender3));
2896
- return ack;
2897
- }
2898
- parseMessage(message) {
2899
- const parsedMessage = messageSchema2.safeParse(message);
2900
- if (!parsedMessage.success) {
2901
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2902
- }
2903
- const schema = __privateGet(this, _schema5)[parsedMessage.data.type]["message"];
2904
- if (!schema) {
2905
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2906
- }
2907
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2908
- if (!parsedPayload.success) {
2909
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2910
- }
2911
- return {
2912
- type: parsedMessage.data.type,
2913
- payload: parsedPayload.data
2914
- };
2915
- }
2916
- }, _schema5 = new WeakMap(), _handlers3 = new WeakMap(), _sender3 = new WeakMap(), __name(_a, "ZodIpcMessageHandler"), _a);
2917
- var Packet = zod.z.discriminatedUnion("type", [
2918
- zod.z.object({
2919
- type: zod.z.literal("CONNECT"),
2920
- sessionId: zod.z.string().optional()
2921
- }),
2922
- zod.z.object({
2923
- type: zod.z.literal("ACK"),
2924
- message: zod.z.any(),
2925
- id: zod.z.number()
2926
- }),
2927
- zod.z.object({
2928
- type: zod.z.literal("EVENT"),
2929
- message: zod.z.any(),
2930
- id: zod.z.number().optional()
2931
- })
2932
- ]);
2933
- var _sessionId, _messageCounter, _handler3, _acks, _registerHandlers, registerHandlers_fn, _handlePacket, handlePacket_fn, _sendPacket, sendPacket_fn;
2934
- var _ZodIpcConnection = class _ZodIpcConnection {
2935
- constructor(opts) {
2936
- __privateAdd(this, _registerHandlers);
2937
- __privateAdd(this, _handlePacket);
2938
- __privateAdd(this, _sendPacket);
2939
- __privateAdd(this, _sessionId, void 0);
2940
- __privateAdd(this, _messageCounter, void 0);
2941
- __privateAdd(this, _handler3, void 0);
2942
- __privateAdd(this, _acks, void 0);
2943
- this.opts = opts;
2944
- __privateSet(this, _messageCounter, 0);
2945
- __privateSet(this, _acks, /* @__PURE__ */ new Map());
2946
- __privateSet(this, _handler3, new ZodIpcMessageHandler({
2947
- schema: opts.listenSchema,
2948
- handlers: opts.handlers,
2949
- sender: {
2950
- send: this.send.bind(this),
2951
- sendWithAck: this.sendWithAck.bind(this)
2952
- }
2953
- }));
2954
- __privateMethod(this, _registerHandlers, registerHandlers_fn).call(this);
2955
- }
2956
- async connect() {
2957
- __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2958
- type: "CONNECT"
2959
- });
2960
- }
2961
- async send(type, payload) {
2962
- const schema = this.opts.emitSchema[type]["message"];
2963
- if (!schema) {
2964
- throw new Error(`Unknown message type: ${type}`);
2965
- }
2966
- const parsedPayload = schema.safeParse(payload);
2967
- if (!parsedPayload.success) {
2968
- throw new ZodSchemaParsedError(parsedPayload.error, payload);
2969
- }
2970
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2971
- type: "EVENT",
2972
- message: {
2973
- type,
2974
- payload,
2975
- version: "v1"
2976
- }
2977
- });
2978
- }
2979
- async sendWithAck(type, payload, timeoutInMs) {
2980
- const currentId = __privateWrapper(this, _messageCounter)._++;
2981
- return new Promise(async (resolve, reject) => {
2982
- const defaultTimeoutInMs = 2e3;
2983
- const timeout = setTimeout(() => {
2984
- reject(JSON.stringify({
2985
- reason: "sendWithAck() timeout",
2986
- timeoutInMs: timeoutInMs ?? defaultTimeoutInMs,
2987
- type,
2988
- payload
2989
- }));
2990
- }, timeoutInMs ?? defaultTimeoutInMs);
2991
- __privateGet(this, _acks).set(currentId, {
2992
- resolve,
2993
- reject,
2994
- timeout
2995
- });
2996
- const schema = this.opts.emitSchema[type]["message"];
2997
- if (!schema) {
2998
- clearTimeout(timeout);
2999
- return reject(`Unknown message type: ${type}`);
3000
- }
3001
- const parsedPayload = schema.safeParse(payload);
3002
- if (!parsedPayload.success) {
3003
- clearTimeout(timeout);
3004
- return reject(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
3005
- }
3006
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
3007
- type: "EVENT",
3008
- message: {
3009
- type,
3010
- payload,
3011
- version: "v1"
3012
- },
3013
- id: currentId
3014
- });
3015
- });
3016
- }
3017
- };
3018
- _sessionId = new WeakMap();
3019
- _messageCounter = new WeakMap();
3020
- _handler3 = new WeakMap();
3021
- _acks = new WeakMap();
3022
- _registerHandlers = new WeakSet();
3023
- registerHandlers_fn = /* @__PURE__ */ __name(async function() {
3024
- if (!this.opts.process.on) {
3025
- return;
3026
- }
3027
- this.opts.process.on("message", async (message) => {
3028
- __privateMethod(this, _handlePacket, handlePacket_fn).call(this, message);
3029
- });
3030
- }, "#registerHandlers");
3031
- _handlePacket = new WeakSet();
3032
- handlePacket_fn = /* @__PURE__ */ __name(async function(packet) {
3033
- const parsedPacket = Packet.safeParse(packet);
3034
- if (!parsedPacket.success) {
3035
- return;
3036
- }
3037
- switch (parsedPacket.data.type) {
3038
- case "ACK": {
3039
- const ack = __privateGet(this, _acks).get(parsedPacket.data.id);
3040
- if (!ack) {
3041
- return;
3042
- }
3043
- clearTimeout(ack.timeout);
3044
- ack.resolve(parsedPacket.data.message);
3045
- break;
3046
- }
3047
- case "CONNECT": {
3048
- if (!parsedPacket.data.sessionId) {
3049
- const id = crypto.randomUUID();
3050
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
3051
- type: "CONNECT",
3052
- sessionId: id
3053
- });
3054
- return;
3055
- }
3056
- if (__privateGet(this, _sessionId)) {
3057
- return;
3058
- }
3059
- __privateSet(this, _sessionId, parsedPacket.data.sessionId);
3060
- break;
3061
- }
3062
- case "EVENT": {
3063
- const result = await __privateGet(this, _handler3).handleMessage(parsedPacket.data.message);
3064
- if (typeof parsedPacket.data.id === "undefined") {
3065
- return;
3066
- }
3067
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
3068
- type: "ACK",
3069
- id: parsedPacket.data.id,
3070
- message: result
3071
- });
3072
- break;
3073
- }
3074
- }
3075
- }, "#handlePacket");
3076
- _sendPacket = new WeakSet();
3077
- sendPacket_fn = /* @__PURE__ */ __name(async function(packet1) {
3078
- await this.opts.process.send?.(packet1);
3079
- }, "#sendPacket");
3080
- __name(_ZodIpcConnection, "ZodIpcConnection");
3081
- var ZodIpcConnection = _ZodIpcConnection;
3082
- function parseError(error) {
3083
- if (error instanceof Error) {
3084
- return {
3085
- type: "BUILT_IN_ERROR",
3086
- name: error.name,
3087
- message: error.message,
3088
- stackTrace: error.stack ?? ""
2709
+ type: "BUILT_IN_ERROR",
2710
+ name: error.name,
2711
+ message: error.message,
2712
+ stackTrace: error.stack ?? ""
3089
2713
  };
3090
2714
  }
3091
2715
  if (typeof error === "string") {
@@ -3127,31 +2751,62 @@ function createErrorTaskError(error) {
3127
2751
  }
3128
2752
  }
3129
2753
  __name(createErrorTaskError, "createErrorTaskError");
2754
+ function createJsonErrorObject(error) {
2755
+ switch (error.type) {
2756
+ case "BUILT_IN_ERROR": {
2757
+ return {
2758
+ name: error.name,
2759
+ message: error.message,
2760
+ stackTrace: error.stackTrace
2761
+ };
2762
+ }
2763
+ case "STRING_ERROR": {
2764
+ return {
2765
+ message: error.raw
2766
+ };
2767
+ }
2768
+ case "CUSTOM_ERROR": {
2769
+ return {
2770
+ message: error.raw
2771
+ };
2772
+ }
2773
+ case "INTERNAL_ERROR": {
2774
+ return {
2775
+ message: `trigger.dev internal error (${error.code})`
2776
+ };
2777
+ }
2778
+ }
2779
+ }
2780
+ __name(createJsonErrorObject, "createJsonErrorObject");
3130
2781
  function correctErrorStackTrace(stackTrace, projectDir, options) {
3131
2782
  const [errorLine, ...traceLines] = stackTrace.split("\n");
3132
2783
  return [
3133
2784
  options?.removeFirstLine ? void 0 : errorLine,
3134
- ...traceLines.map((line) => correctStackTraceLine(line, projectDir))
2785
+ ...traceLines.map((line) => correctStackTraceLine(line, projectDir, options?.isDev))
3135
2786
  ].filter(Boolean).join("\n");
3136
2787
  }
3137
2788
  __name(correctErrorStackTrace, "correctErrorStackTrace");
3138
- function correctStackTraceLine(line, projectDir) {
3139
- const regex = /at (.*?) \(?file:\/\/(\/.*?\.ts):(\d+):(\d+)\)?/;
3140
- const match = regex.exec(line);
3141
- if (!match) {
3142
- return;
3143
- }
3144
- const [_, identifier, path, lineNum, colNum] = match;
3145
- if (!path) {
3146
- return;
3147
- }
3148
- if (nodePath__default.default.basename(path) === "__entryPoint.ts") {
2789
+ var LINES_TO_IGNORE = [
2790
+ /ConsoleInterceptor/,
2791
+ /TriggerTracer/,
2792
+ /TaskExecutor/,
2793
+ /EXECUTE_TASK_RUN/,
2794
+ /@trigger.dev\/core/,
2795
+ /packages\/core\/src\/v3/,
2796
+ /safeJsonProcess/,
2797
+ /__entryPoint.ts/,
2798
+ /ZodIpc/,
2799
+ /startActiveSpan/,
2800
+ /processTicksAndRejections/
2801
+ ];
2802
+ function correctStackTraceLine(line, projectDir, isDev) {
2803
+ if (LINES_TO_IGNORE.some((regex) => regex.test(line))) {
3149
2804
  return;
3150
2805
  }
3151
- if (projectDir && !path.includes(projectDir)) {
2806
+ if (isDev && projectDir && !line.includes(projectDir)) {
3152
2807
  return;
3153
2808
  }
3154
- return line;
2809
+ return line.trim();
3155
2810
  }
3156
2811
  __name(correctStackTraceLine, "correctStackTraceLine");
3157
2812
  function groupTaskMetadataIssuesByTask(tasks, issues) {
@@ -3190,335 +2845,363 @@ function groupTaskMetadataIssuesByTask(tasks, issues) {
3190
2845
  }
3191
2846
  __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
3192
2847
 
3193
- // src/v3/utils/platform.ts
3194
- var _globalThis = typeof globalThis === "object" ? globalThis : global;
3195
-
3196
- // src/v3/utils/globals.ts
3197
- var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
3198
- var _global = _globalThis;
3199
- function registerGlobal(type, instance, allowOverride = false) {
3200
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
3201
- if (!allowOverride && api[type]) {
3202
- return false;
2848
+ // src/v3/limits.ts
2849
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2850
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
2851
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2852
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2853
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
2854
+ var OTEL_LINK_COUNT_LIMIT = 2;
2855
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
2856
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
2857
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
2858
+ function imposeAttributeLimits(attributes) {
2859
+ const newAttributes = {};
2860
+ for (const [key, value] of Object.entries(attributes)) {
2861
+ if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
2862
+ continue;
2863
+ }
2864
+ if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
2865
+ break;
2866
+ }
2867
+ newAttributes[key] = value;
3203
2868
  }
3204
- api[type] = instance;
3205
- return true;
3206
- }
3207
- __name(registerGlobal, "registerGlobal");
3208
- function getGlobal(type) {
3209
- return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
2869
+ return newAttributes;
3210
2870
  }
3211
- __name(getGlobal, "getGlobal");
3212
- function unregisterGlobal(type) {
3213
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
3214
- if (api) {
3215
- delete api[type];
2871
+ __name(imposeAttributeLimits, "imposeAttributeLimits");
2872
+ function calculateAttributeValueLength(value) {
2873
+ if (value === void 0 || value === null) {
2874
+ return 0;
3216
2875
  }
3217
- }
3218
- __name(unregisterGlobal, "unregisterGlobal");
3219
-
3220
- // src/v3/runtime/noopRuntimeManager.ts
3221
- var _NoopRuntimeManager = class _NoopRuntimeManager {
3222
- disable() {
3223
- }
3224
- waitForDuration(ms) {
3225
- return Promise.resolve();
2876
+ if (typeof value === "string") {
2877
+ return value.length;
3226
2878
  }
3227
- waitUntil(date) {
3228
- return Promise.resolve();
2879
+ if (typeof value === "number") {
2880
+ return 8;
3229
2881
  }
3230
- waitForTask(params) {
3231
- return Promise.resolve({
3232
- ok: false,
3233
- id: params.id,
3234
- error: {
3235
- type: "INTERNAL_ERROR",
3236
- code: "CONFIGURED_INCORRECTLY"
3237
- }
3238
- });
2882
+ if (typeof value === "boolean") {
2883
+ return 4;
3239
2884
  }
3240
- waitForBatch(params) {
3241
- return Promise.resolve({
3242
- id: params.id,
3243
- items: []
3244
- });
2885
+ if (Array.isArray(value)) {
2886
+ return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
3245
2887
  }
3246
- };
3247
- __name(_NoopRuntimeManager, "NoopRuntimeManager");
3248
- var NoopRuntimeManager = _NoopRuntimeManager;
2888
+ return 0;
2889
+ }
2890
+ __name(calculateAttributeValueLength, "calculateAttributeValueLength");
3249
2891
 
3250
- // src/v3/runtime/index.ts
3251
- var API_NAME = "runtime";
3252
- var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
3253
- var _getRuntimeManager, getRuntimeManager_fn;
3254
- var _RuntimeAPI = class _RuntimeAPI {
3255
- constructor() {
3256
- __privateAdd(this, _getRuntimeManager);
2892
+ // src/v3/utils/flattenAttributes.ts
2893
+ var NULL_SENTINEL = "$@null((";
2894
+ function flattenAttributes(obj, prefix) {
2895
+ const result = {};
2896
+ if (obj === void 0) {
2897
+ return result;
3257
2898
  }
3258
- static getInstance() {
3259
- if (!this._instance) {
3260
- this._instance = new _RuntimeAPI();
2899
+ if (obj === null) {
2900
+ result[prefix || ""] = NULL_SENTINEL;
2901
+ return result;
2902
+ }
2903
+ if (typeof obj === "string") {
2904
+ result[prefix || ""] = obj;
2905
+ return result;
2906
+ }
2907
+ if (typeof obj === "number") {
2908
+ result[prefix || ""] = obj;
2909
+ return result;
2910
+ }
2911
+ if (typeof obj === "boolean") {
2912
+ result[prefix || ""] = obj;
2913
+ return result;
2914
+ }
2915
+ for (const [key, value] of Object.entries(obj)) {
2916
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${key}]` : key}`;
2917
+ if (Array.isArray(value)) {
2918
+ for (let i = 0; i < value.length; i++) {
2919
+ if (typeof value[i] === "object" && value[i] !== null) {
2920
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
2921
+ } else {
2922
+ if (value[i] === null) {
2923
+ result[`${newPrefix}.[${i}]`] = NULL_SENTINEL;
2924
+ } else {
2925
+ result[`${newPrefix}.[${i}]`] = value[i];
2926
+ }
2927
+ }
2928
+ }
2929
+ } else if (isRecord(value)) {
2930
+ Object.assign(result, flattenAttributes(value, newPrefix));
2931
+ } else {
2932
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
2933
+ result[newPrefix] = value;
2934
+ } else if (value === null) {
2935
+ result[newPrefix] = NULL_SENTINEL;
2936
+ }
3261
2937
  }
3262
- return this._instance;
3263
2938
  }
3264
- waitForDuration(ms) {
3265
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2939
+ return result;
2940
+ }
2941
+ __name(flattenAttributes, "flattenAttributes");
2942
+ function isRecord(value) {
2943
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2944
+ }
2945
+ __name(isRecord, "isRecord");
2946
+ function unflattenAttributes(obj) {
2947
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
2948
+ return obj;
3266
2949
  }
3267
- waitUntil(date) {
3268
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
2950
+ if (typeof obj === "object" && obj !== null && Object.keys(obj).length === 1 && Object.keys(obj)[0] === "") {
2951
+ return rehydrateNull(obj[""]);
3269
2952
  }
3270
- waitForTask(params) {
3271
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
2953
+ if (Object.keys(obj).length === 0) {
2954
+ return;
3272
2955
  }
3273
- waitForBatch(params) {
3274
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
2956
+ const result = {};
2957
+ for (const [key, value] of Object.entries(obj)) {
2958
+ const parts = key.split(".").reduce((acc, part) => {
2959
+ if (part.includes("[")) {
2960
+ const subparts = part.split(/\[|\]/).filter((p) => p !== "");
2961
+ acc.push(...subparts);
2962
+ } else {
2963
+ acc.push(part);
2964
+ }
2965
+ return acc;
2966
+ }, []);
2967
+ let current = result;
2968
+ for (let i = 0; i < parts.length - 1; i++) {
2969
+ const part = parts[i];
2970
+ const nextPart = parts[i + 1];
2971
+ const isArray = /^\d+$/.test(nextPart);
2972
+ if (isArray && !Array.isArray(current[part])) {
2973
+ current[part] = [];
2974
+ } else if (!isArray && current[part] === void 0) {
2975
+ current[part] = {};
2976
+ }
2977
+ current = current[part];
2978
+ }
2979
+ const lastPart = parts[parts.length - 1];
2980
+ current[lastPart] = rehydrateNull(value);
3275
2981
  }
3276
- setGlobalRuntimeManager(runtimeManager) {
3277
- return registerGlobal(API_NAME, runtimeManager);
2982
+ if (Object.keys(result).every((k) => /^\d+$/.test(k))) {
2983
+ const maxIndex = Math.max(...Object.keys(result).map((k) => parseInt(k)));
2984
+ const arrayResult = Array(maxIndex + 1);
2985
+ for (const key in result) {
2986
+ arrayResult[parseInt(key)] = result[key];
2987
+ }
2988
+ return arrayResult;
3278
2989
  }
3279
- disable() {
3280
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
3281
- unregisterGlobal(API_NAME);
2990
+ return result;
2991
+ }
2992
+ __name(unflattenAttributes, "unflattenAttributes");
2993
+ function primitiveValueOrflattenedAttributes(obj, prefix) {
2994
+ if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
2995
+ return obj;
3282
2996
  }
3283
- };
3284
- _getRuntimeManager = new WeakSet();
3285
- getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
3286
- return getGlobal(API_NAME) ?? NOOP_RUNTIME_MANAGER;
3287
- }, "#getRuntimeManager");
3288
- __name(_RuntimeAPI, "RuntimeAPI");
3289
- var RuntimeAPI = _RuntimeAPI;
3290
-
3291
- // src/v3/runtime-api.ts
3292
- var runtime = RuntimeAPI.getInstance();
3293
- function iconStringForSeverity(severityNumber) {
3294
- switch (severityNumber) {
3295
- case apiLogs.SeverityNumber.UNSPECIFIED:
3296
- return void 0;
3297
- case apiLogs.SeverityNumber.TRACE:
3298
- case apiLogs.SeverityNumber.TRACE2:
3299
- case apiLogs.SeverityNumber.TRACE3:
3300
- case apiLogs.SeverityNumber.TRACE4:
3301
- return "trace";
3302
- case apiLogs.SeverityNumber.DEBUG:
3303
- case apiLogs.SeverityNumber.DEBUG2:
3304
- case apiLogs.SeverityNumber.DEBUG3:
3305
- case apiLogs.SeverityNumber.DEBUG4:
3306
- return "debug";
3307
- case apiLogs.SeverityNumber.INFO:
3308
- case apiLogs.SeverityNumber.INFO2:
3309
- case apiLogs.SeverityNumber.INFO3:
3310
- case apiLogs.SeverityNumber.INFO4:
3311
- return "info";
3312
- case apiLogs.SeverityNumber.WARN:
3313
- case apiLogs.SeverityNumber.WARN2:
3314
- case apiLogs.SeverityNumber.WARN3:
3315
- case apiLogs.SeverityNumber.WARN4:
3316
- return "warn";
3317
- case apiLogs.SeverityNumber.ERROR:
3318
- case apiLogs.SeverityNumber.ERROR2:
3319
- case apiLogs.SeverityNumber.ERROR3:
3320
- case apiLogs.SeverityNumber.ERROR4:
3321
- return "error";
3322
- case apiLogs.SeverityNumber.FATAL:
3323
- case apiLogs.SeverityNumber.FATAL2:
3324
- case apiLogs.SeverityNumber.FATAL3:
3325
- case apiLogs.SeverityNumber.FATAL4:
3326
- return "fatal";
2997
+ const attributes = flattenAttributes(obj, prefix);
2998
+ if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
2999
+ return attributes[prefix];
3327
3000
  }
3001
+ return attributes;
3328
3002
  }
3329
- __name(iconStringForSeverity, "iconStringForSeverity");
3330
- var _SimpleClock = class _SimpleClock {
3331
- preciseNow() {
3332
- const now = new preciseDate.PreciseDate();
3333
- const nowStruct = now.toStruct();
3334
- return [
3335
- nowStruct.seconds,
3336
- nowStruct.nanos
3337
- ];
3003
+ __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
3004
+ function rehydrateNull(value) {
3005
+ if (value === NULL_SENTINEL) {
3006
+ return null;
3338
3007
  }
3339
- reset() {
3008
+ return value;
3009
+ }
3010
+ __name(rehydrateNull, "rehydrateNull");
3011
+
3012
+ // src/v3/logger/taskLogger.ts
3013
+ var _NoopTaskLogger = class _NoopTaskLogger {
3014
+ debug() {
3015
+ }
3016
+ log() {
3017
+ }
3018
+ info() {
3019
+ }
3020
+ warn() {
3021
+ }
3022
+ error() {
3023
+ }
3024
+ trace(name, fn) {
3025
+ return fn({});
3340
3026
  }
3341
3027
  };
3342
- __name(_SimpleClock, "SimpleClock");
3343
- var SimpleClock = _SimpleClock;
3028
+ __name(_NoopTaskLogger, "NoopTaskLogger");
3029
+ var NoopTaskLogger = _NoopTaskLogger;
3344
3030
 
3345
- // src/v3/clock/index.ts
3346
- var API_NAME2 = "clock";
3347
- var SIMPLE_CLOCK = new SimpleClock();
3348
- var _getClock, getClock_fn;
3349
- var _ClockAPI = class _ClockAPI {
3031
+ // src/v3/logger/index.ts
3032
+ var API_NAME3 = "logger";
3033
+ var NOOP_TASK_LOGGER = new NoopTaskLogger();
3034
+ var _getTaskLogger, getTaskLogger_fn;
3035
+ var _LoggerAPI = class _LoggerAPI {
3350
3036
  constructor() {
3351
- __privateAdd(this, _getClock);
3037
+ __privateAdd(this, _getTaskLogger);
3352
3038
  }
3353
3039
  static getInstance() {
3354
3040
  if (!this._instance) {
3355
- this._instance = new _ClockAPI();
3041
+ this._instance = new _LoggerAPI();
3356
3042
  }
3357
3043
  return this._instance;
3358
3044
  }
3359
- setGlobalClock(clock2) {
3360
- return registerGlobal(API_NAME2, clock2);
3045
+ disable() {
3046
+ unregisterGlobal(API_NAME3);
3361
3047
  }
3362
- preciseNow() {
3363
- return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
3048
+ setGlobalTaskLogger(taskLogger) {
3049
+ return registerGlobal(API_NAME3, taskLogger);
3364
3050
  }
3365
- reset() {
3366
- __privateMethod(this, _getClock, getClock_fn).call(this).reset();
3051
+ debug(message, metadata) {
3052
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).debug(message, metadata);
3053
+ }
3054
+ log(message, metadata) {
3055
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).log(message, metadata);
3056
+ }
3057
+ info(message, metadata) {
3058
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).info(message, metadata);
3059
+ }
3060
+ warn(message, metadata) {
3061
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).warn(message, metadata);
3062
+ }
3063
+ error(message, metadata) {
3064
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).error(message, metadata);
3065
+ }
3066
+ trace(name, fn) {
3067
+ return __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).trace(name, fn);
3367
3068
  }
3368
3069
  };
3369
- _getClock = new WeakSet();
3370
- getClock_fn = /* @__PURE__ */ __name(function() {
3371
- return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
3372
- }, "#getClock");
3373
- __name(_ClockAPI, "ClockAPI");
3374
- var ClockAPI = _ClockAPI;
3070
+ _getTaskLogger = new WeakSet();
3071
+ getTaskLogger_fn = /* @__PURE__ */ __name(function() {
3072
+ return getGlobal(API_NAME3) ?? NOOP_TASK_LOGGER;
3073
+ }, "#getTaskLogger");
3074
+ __name(_LoggerAPI, "LoggerAPI");
3075
+ var LoggerAPI = _LoggerAPI;
3375
3076
 
3376
- // src/v3/clock-api.ts
3377
- var clock = ClockAPI.getInstance();
3077
+ // src/v3/logger-api.ts
3078
+ var logger = LoggerAPI.getInstance();
3378
3079
 
3379
- // src/v3/logger/taskLogger.ts
3380
- var logLevels = [
3381
- "none",
3382
- "error",
3383
- "warn",
3384
- "log",
3385
- "info",
3386
- "debug"
3387
- ];
3388
- var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
3389
- var _OtelTaskLogger = class _OtelTaskLogger {
3390
- constructor(_config) {
3391
- __privateAdd(this, _emitLog);
3392
- __privateAdd(this, _getTimestampInHrTime);
3393
- this._config = _config;
3394
- this._level = logLevels.indexOf(_config.level);
3080
+ // src/v3/runtime/noopRuntimeManager.ts
3081
+ var _NoopRuntimeManager = class _NoopRuntimeManager {
3082
+ disable() {
3395
3083
  }
3396
- debug(message, properties) {
3397
- if (this._level < 5)
3398
- return;
3399
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", apiLogs.SeverityNumber.DEBUG, properties);
3084
+ waitForDuration(ms) {
3085
+ return Promise.resolve();
3400
3086
  }
3401
- log(message, properties) {
3402
- if (this._level < 3)
3403
- return;
3404
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", apiLogs.SeverityNumber.INFO, properties);
3087
+ waitUntil(date) {
3088
+ return Promise.resolve();
3405
3089
  }
3406
- info(message, properties) {
3407
- if (this._level < 4)
3408
- return;
3409
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", apiLogs.SeverityNumber.INFO, properties);
3090
+ waitForTask(params) {
3091
+ return Promise.resolve({
3092
+ ok: false,
3093
+ id: params.id,
3094
+ error: {
3095
+ type: "INTERNAL_ERROR",
3096
+ code: "CONFIGURED_INCORRECTLY"
3097
+ }
3098
+ });
3410
3099
  }
3411
- warn(message, properties) {
3412
- if (this._level < 2)
3413
- return;
3414
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", apiLogs.SeverityNumber.WARN, properties);
3100
+ waitForBatch(params) {
3101
+ return Promise.resolve({
3102
+ id: params.id,
3103
+ items: []
3104
+ });
3415
3105
  }
3416
- error(message, properties) {
3417
- if (this._level < 1)
3418
- return;
3419
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", apiLogs.SeverityNumber.ERROR, properties);
3106
+ };
3107
+ __name(_NoopRuntimeManager, "NoopRuntimeManager");
3108
+ var NoopRuntimeManager = _NoopRuntimeManager;
3109
+
3110
+ // src/v3/runtime/index.ts
3111
+ var API_NAME4 = "runtime";
3112
+ var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
3113
+ var _getRuntimeManager, getRuntimeManager_fn;
3114
+ var _RuntimeAPI = class _RuntimeAPI {
3115
+ constructor() {
3116
+ __privateAdd(this, _getRuntimeManager);
3420
3117
  }
3421
- trace(name, fn, options) {
3422
- return this._config.tracer.startActiveSpan(name, fn, options);
3118
+ static getInstance() {
3119
+ if (!this._instance) {
3120
+ this._instance = new _RuntimeAPI();
3121
+ }
3122
+ return this._instance;
3423
3123
  }
3424
- };
3425
- _emitLog = new WeakSet();
3426
- emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
3427
- let attributes = {
3428
- ...flattenAttributes(safeJsonProcess(properties))
3429
- };
3430
- const icon = iconStringForSeverity(severityNumber);
3431
- if (icon !== void 0) {
3432
- attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
3433
- }
3434
- this._config.logger.emit({
3435
- severityNumber,
3436
- severityText,
3437
- body: message,
3438
- attributes,
3439
- timestamp
3440
- });
3441
- }, "#emitLog");
3442
- _getTimestampInHrTime = new WeakSet();
3443
- getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
3444
- return clock.preciseNow();
3445
- }, "#getTimestampInHrTime");
3446
- __name(_OtelTaskLogger, "OtelTaskLogger");
3447
- var OtelTaskLogger = _OtelTaskLogger;
3448
- var _NoopTaskLogger = class _NoopTaskLogger {
3449
- debug() {
3124
+ waitForDuration(ms) {
3125
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
3450
3126
  }
3451
- log() {
3127
+ waitUntil(date) {
3128
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
3452
3129
  }
3453
- info() {
3130
+ waitForTask(params) {
3131
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
3454
3132
  }
3455
- warn() {
3133
+ waitForBatch(params) {
3134
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
3456
3135
  }
3457
- error() {
3136
+ setGlobalRuntimeManager(runtimeManager) {
3137
+ return registerGlobal(API_NAME4, runtimeManager);
3458
3138
  }
3459
- trace(name, fn) {
3460
- return fn({});
3139
+ disable() {
3140
+ __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
3141
+ unregisterGlobal(API_NAME4);
3461
3142
  }
3462
3143
  };
3463
- __name(_NoopTaskLogger, "NoopTaskLogger");
3464
- var NoopTaskLogger = _NoopTaskLogger;
3465
- function safeJsonProcess(value) {
3466
- try {
3467
- return JSON.parse(JSON.stringify(value));
3468
- } catch {
3469
- return value;
3144
+ _getRuntimeManager = new WeakSet();
3145
+ getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
3146
+ return getGlobal(API_NAME4) ?? NOOP_RUNTIME_MANAGER;
3147
+ }, "#getRuntimeManager");
3148
+ __name(_RuntimeAPI, "RuntimeAPI");
3149
+ var RuntimeAPI = _RuntimeAPI;
3150
+
3151
+ // src/v3/runtime-api.ts
3152
+ var runtime = RuntimeAPI.getInstance();
3153
+
3154
+ // src/v3/utils/getEnv.ts
3155
+ function getEnvVar(name) {
3156
+ if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
3157
+ return process.env[name];
3470
3158
  }
3471
3159
  }
3472
- __name(safeJsonProcess, "safeJsonProcess");
3160
+ __name(getEnvVar, "getEnvVar");
3473
3161
 
3474
- // src/v3/logger/index.ts
3475
- var API_NAME3 = "logger";
3476
- var NOOP_TASK_LOGGER = new NoopTaskLogger();
3477
- var _getTaskLogger, getTaskLogger_fn;
3478
- var _LoggerAPI = class _LoggerAPI {
3162
+ // src/v3/apiClientManager/index.ts
3163
+ var API_NAME5 = "api-client";
3164
+ var _getConfig, getConfig_fn;
3165
+ var _APIClientManagerAPI = class _APIClientManagerAPI {
3479
3166
  constructor() {
3480
- __privateAdd(this, _getTaskLogger);
3167
+ __privateAdd(this, _getConfig);
3481
3168
  }
3482
3169
  static getInstance() {
3483
3170
  if (!this._instance) {
3484
- this._instance = new _LoggerAPI();
3171
+ this._instance = new _APIClientManagerAPI();
3485
3172
  }
3486
3173
  return this._instance;
3487
3174
  }
3488
3175
  disable() {
3489
- unregisterGlobal(API_NAME3);
3490
- }
3491
- setGlobalTaskLogger(taskLogger) {
3492
- return registerGlobal(API_NAME3, taskLogger);
3176
+ unregisterGlobal(API_NAME5);
3493
3177
  }
3494
- debug(message, metadata) {
3495
- __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).debug(message, metadata);
3496
- }
3497
- log(message, metadata) {
3498
- __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).log(message, metadata);
3499
- }
3500
- info(message, metadata) {
3501
- __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).info(message, metadata);
3178
+ setGlobalAPIClientConfiguration(config) {
3179
+ return registerGlobal(API_NAME5, config);
3502
3180
  }
3503
- warn(message, metadata) {
3504
- __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).warn(message, metadata);
3181
+ get baseURL() {
3182
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
3183
+ return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
3505
3184
  }
3506
- error(message, metadata) {
3507
- __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).error(message, metadata);
3185
+ get accessToken() {
3186
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
3187
+ return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY") ?? getEnvVar("TRIGGER_ACCESS_TOKEN");
3508
3188
  }
3509
- trace(name, fn) {
3510
- return __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).trace(name, fn);
3189
+ get client() {
3190
+ if (!this.baseURL || !this.accessToken) {
3191
+ return void 0;
3192
+ }
3193
+ return new ApiClient(this.baseURL, this.accessToken);
3511
3194
  }
3512
3195
  };
3513
- _getTaskLogger = new WeakSet();
3514
- getTaskLogger_fn = /* @__PURE__ */ __name(function() {
3515
- return getGlobal(API_NAME3) ?? NOOP_TASK_LOGGER;
3516
- }, "#getTaskLogger");
3517
- __name(_LoggerAPI, "LoggerAPI");
3518
- var LoggerAPI = _LoggerAPI;
3196
+ _getConfig = new WeakSet();
3197
+ getConfig_fn = /* @__PURE__ */ __name(function() {
3198
+ return getGlobal(API_NAME5);
3199
+ }, "#getConfig");
3200
+ __name(_APIClientManagerAPI, "APIClientManagerAPI");
3201
+ var APIClientManagerAPI = _APIClientManagerAPI;
3519
3202
 
3520
- // src/v3/logger-api.ts
3521
- var logger = LoggerAPI.getInstance();
3203
+ // src/v3/apiClientManager-api.ts
3204
+ var apiClientManager = APIClientManagerAPI.getInstance();
3522
3205
 
3523
3206
  // src/v3/task-catalog/noopTaskCatalog.ts
3524
3207
  var _NoopTaskCatalog = class _NoopTaskCatalog {
@@ -3537,6 +3220,9 @@ var _NoopTaskCatalog = class _NoopTaskCatalog {
3537
3220
  getTask(id) {
3538
3221
  return void 0;
3539
3222
  }
3223
+ taskExists(id) {
3224
+ return false;
3225
+ }
3540
3226
  disable() {
3541
3227
  }
3542
3228
  };
@@ -3544,7 +3230,7 @@ __name(_NoopTaskCatalog, "NoopTaskCatalog");
3544
3230
  var NoopTaskCatalog = _NoopTaskCatalog;
3545
3231
 
3546
3232
  // src/v3/task-catalog/index.ts
3547
- var API_NAME4 = "task-catalog";
3233
+ var API_NAME6 = "task-catalog";
3548
3234
  var NOOP_TASK_CATALOG = new NoopTaskCatalog();
3549
3235
  var _getCatalog, getCatalog_fn;
3550
3236
  var _TaskCatalogAPI = class _TaskCatalogAPI {
@@ -3558,10 +3244,10 @@ var _TaskCatalogAPI = class _TaskCatalogAPI {
3558
3244
  return this._instance;
3559
3245
  }
3560
3246
  setGlobalTaskCatalog(taskCatalog2) {
3561
- return registerGlobal(API_NAME4, taskCatalog2);
3247
+ return registerGlobal(API_NAME6, taskCatalog2);
3562
3248
  }
3563
3249
  disable() {
3564
- unregisterGlobal(API_NAME4);
3250
+ unregisterGlobal(API_NAME6);
3565
3251
  }
3566
3252
  registerTaskMetadata(task) {
3567
3253
  __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskMetadata(task);
@@ -3581,60 +3267,19 @@ var _TaskCatalogAPI = class _TaskCatalogAPI {
3581
3267
  getTask(id) {
3582
3268
  return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTask(id);
3583
3269
  }
3270
+ taskExists(id) {
3271
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).taskExists(id);
3272
+ }
3584
3273
  };
3585
3274
  _getCatalog = new WeakSet();
3586
3275
  getCatalog_fn = /* @__PURE__ */ __name(function() {
3587
- return getGlobal(API_NAME4) ?? NOOP_TASK_CATALOG;
3276
+ return getGlobal(API_NAME6) ?? NOOP_TASK_CATALOG;
3588
3277
  }, "#getCatalog");
3589
3278
  __name(_TaskCatalogAPI, "TaskCatalogAPI");
3590
3279
  var TaskCatalogAPI = _TaskCatalogAPI;
3591
3280
 
3592
3281
  // src/v3/task-catalog-api.ts
3593
3282
  var taskCatalog = TaskCatalogAPI.getInstance();
3594
-
3595
- // src/v3/limits.ts
3596
- var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
3597
- var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
3598
- var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
3599
- var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
3600
- var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
3601
- var OTEL_LINK_COUNT_LIMIT = 2;
3602
- var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
3603
- var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
3604
- var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
3605
- function imposeAttributeLimits(attributes) {
3606
- const newAttributes = {};
3607
- for (const [key, value] of Object.entries(attributes)) {
3608
- if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
3609
- continue;
3610
- }
3611
- if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
3612
- break;
3613
- }
3614
- newAttributes[key] = value;
3615
- }
3616
- return newAttributes;
3617
- }
3618
- __name(imposeAttributeLimits, "imposeAttributeLimits");
3619
- function calculateAttributeValueLength(value) {
3620
- if (value === void 0 || value === null) {
3621
- return 0;
3622
- }
3623
- if (typeof value === "string") {
3624
- return value.length;
3625
- }
3626
- if (typeof value === "number") {
3627
- return 8;
3628
- }
3629
- if (typeof value === "boolean") {
3630
- return 4;
3631
- }
3632
- if (Array.isArray(value)) {
3633
- return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
3634
- }
3635
- return 0;
3636
- }
3637
- __name(calculateAttributeValueLength, "calculateAttributeValueLength");
3638
3283
  function dateDifference(date1, date2) {
3639
3284
  return Math.abs(date1.getTime() - date2.getTime());
3640
3285
  }
@@ -3654,291 +3299,61 @@ function millisecondsToNanoseconds(milliseconds) {
3654
3299
  return milliseconds * 1e6;
3655
3300
  }
3656
3301
  __name(millisecondsToNanoseconds, "millisecondsToNanoseconds");
3657
- function formatDurationNanoseconds(nanoseconds, options) {
3658
- return formatDurationMilliseconds(nanosecondsToMilliseconds(nanoseconds), options);
3659
- }
3660
- __name(formatDurationNanoseconds, "formatDurationNanoseconds");
3661
- var aboveOneSecondUnits = [
3662
- "d",
3663
- "h",
3664
- "m",
3665
- "s"
3666
- ];
3667
- var belowOneSecondUnits = [
3668
- "ms"
3669
- ];
3670
- function formatDurationMilliseconds(milliseconds, options) {
3671
- let duration = humanizeDuration__default.default(milliseconds, {
3672
- units: options?.units ? options.units : milliseconds < 1e3 ? belowOneSecondUnits : aboveOneSecondUnits,
3673
- maxDecimalPoints: options?.maxDecimalPoints ?? 1,
3674
- largest: 2
3675
- });
3676
- if (!options) {
3677
- return duration;
3678
- }
3679
- switch (options.style) {
3680
- case "short":
3681
- duration = duration.replace(" milliseconds", "ms");
3682
- duration = duration.replace(" millisecond", "ms");
3683
- duration = duration.replace(" seconds", "s");
3684
- duration = duration.replace(" second", "s");
3685
- duration = duration.replace(" minutes", "m");
3686
- duration = duration.replace(" minute", "m");
3687
- duration = duration.replace(" hours", "h");
3688
- duration = duration.replace(" hour", "h");
3689
- duration = duration.replace(" days", "d");
3690
- duration = duration.replace(" day", "d");
3691
- duration = duration.replace(" weeks", "w");
3692
- duration = duration.replace(" week", "w");
3693
- duration = duration.replace(" months", "mo");
3694
- duration = duration.replace(" month", "mo");
3695
- duration = duration.replace(" years", "y");
3696
- duration = duration.replace(" year", "y");
3697
- }
3698
- return duration;
3699
- }
3700
- __name(formatDurationMilliseconds, "formatDurationMilliseconds");
3701
- function formatDurationInDays(milliseconds) {
3702
- let duration = humanizeDuration__default.default(milliseconds, {
3703
- maxDecimalPoints: 0,
3704
- largest: 2,
3705
- units: [
3706
- "d"
3707
- ]
3708
- });
3709
- return duration;
3710
- }
3711
- __name(formatDurationInDays, "formatDurationInDays");
3712
- async function unboundedTimeout(delay = 0, value, options) {
3713
- const maxDelay = 2147483647;
3714
- const fullTimeouts = Math.floor(delay / maxDelay);
3715
- const remainingDelay = delay % maxDelay;
3716
- let lastTimeoutResult = await promises.setTimeout(remainingDelay, value, options);
3717
- for (let i = 0; i < fullTimeouts; i++) {
3718
- lastTimeoutResult = await promises.setTimeout(maxDelay, value, options);
3719
- }
3720
- return lastTimeoutResult;
3721
- }
3722
- __name(unboundedTimeout, "unboundedTimeout");
3723
-
3724
- // src/v3/runtime/devRuntimeManager.ts
3725
- var _DevRuntimeManager = class _DevRuntimeManager {
3726
- constructor() {
3727
- __publicField(this, "_taskWaits", /* @__PURE__ */ new Map());
3728
- __publicField(this, "_batchWaits", /* @__PURE__ */ new Map());
3729
- __publicField(this, "_pendingCompletionNotifications", /* @__PURE__ */ new Map());
3730
- }
3731
- disable() {
3732
- }
3733
- async waitForDuration(ms) {
3734
- await unboundedTimeout(ms);
3735
- }
3736
- async waitUntil(date) {
3737
- return this.waitForDuration(date.getTime() - Date.now());
3738
- }
3739
- async waitForTask(params) {
3740
- const pendingCompletion = this._pendingCompletionNotifications.get(params.id);
3741
- if (pendingCompletion) {
3742
- this._pendingCompletionNotifications.delete(params.id);
3743
- return pendingCompletion;
3744
- }
3745
- const promise = new Promise((resolve, reject) => {
3746
- this._taskWaits.set(params.id, {
3747
- resolve,
3748
- reject
3749
- });
3750
- });
3751
- return await promise;
3752
- }
3753
- async waitForBatch(params) {
3754
- if (!params.runs.length) {
3755
- return Promise.resolve({
3756
- id: params.id,
3757
- items: []
3758
- });
3759
- }
3760
- const promise = Promise.all(params.runs.map((runId) => {
3761
- return new Promise((resolve, reject) => {
3762
- const pendingCompletion = this._pendingCompletionNotifications.get(runId);
3763
- if (pendingCompletion) {
3764
- this._pendingCompletionNotifications.delete(runId);
3765
- if (pendingCompletion.ok) {
3766
- resolve(pendingCompletion);
3767
- } else {
3768
- reject(pendingCompletion);
3769
- }
3770
- return;
3771
- }
3772
- this._taskWaits.set(runId, {
3773
- resolve,
3774
- reject
3775
- });
3776
- });
3777
- }));
3778
- const results = await promise;
3779
- return {
3780
- id: params.id,
3781
- items: results
3782
- };
3783
- }
3784
- resumeTask(completion, execution) {
3785
- const wait = this._taskWaits.get(execution.run.id);
3786
- if (!wait) {
3787
- this._pendingCompletionNotifications.set(execution.run.id, completion);
3788
- return;
3789
- }
3790
- if (completion.ok) {
3791
- wait.resolve(completion);
3792
- } else {
3793
- wait.reject(completion);
3794
- }
3795
- this._taskWaits.delete(execution.run.id);
3796
- }
3797
- };
3798
- __name(_DevRuntimeManager, "DevRuntimeManager");
3799
- var DevRuntimeManager = _DevRuntimeManager;
3800
-
3801
- // src/v3/runtime/prodRuntimeManager.ts
3802
- var _ProdRuntimeManager = class _ProdRuntimeManager {
3803
- constructor(ipc, options = {}) {
3804
- this.ipc = ipc;
3805
- this.options = options;
3806
- this._taskWaits = /* @__PURE__ */ new Map();
3807
- this._batchWaits = /* @__PURE__ */ new Map();
3808
- }
3809
- disable() {
3810
- }
3811
- async waitForDuration(ms) {
3812
- const now = Date.now();
3813
- const resolveAfterDuration = unboundedTimeout(ms, "duration");
3814
- if (ms <= this.waitThresholdInMs) {
3815
- await resolveAfterDuration;
3816
- return;
3817
- }
3818
- const waitForRestore = new Promise((resolve, reject) => {
3819
- this._waitForRestore = {
3820
- resolve,
3821
- reject
3822
- };
3823
- });
3824
- const { willCheckpointAndRestore } = await this.ipc.sendWithAck("WAIT_FOR_DURATION", {
3825
- ms,
3826
- now
3827
- });
3828
- if (!willCheckpointAndRestore) {
3829
- await resolveAfterDuration;
3830
- return;
3831
- }
3832
- this.ipc.send("READY_FOR_CHECKPOINT", {});
3833
- await Promise.race([
3834
- waitForRestore,
3835
- resolveAfterDuration
3836
- ]);
3837
- this.ipc.send("CANCEL_CHECKPOINT", {});
3838
- }
3839
- resumeAfterRestore() {
3840
- if (!this._waitForRestore) {
3841
- return;
3842
- }
3843
- clock.reset();
3844
- this._waitForRestore.resolve("restore");
3845
- this._waitForRestore = void 0;
3846
- }
3847
- async waitUntil(date) {
3848
- return this.waitForDuration(date.getTime() - Date.now());
3849
- }
3850
- async waitForTask(params) {
3851
- const promise = new Promise((resolve, reject) => {
3852
- this._taskWaits.set(params.id, {
3853
- resolve,
3854
- reject
3855
- });
3856
- });
3857
- await this.ipc.send("WAIT_FOR_TASK", {
3858
- friendlyId: params.id
3859
- });
3860
- return await promise;
3861
- }
3862
- async waitForBatch(params) {
3863
- if (!params.runs.length) {
3864
- return Promise.resolve({
3865
- id: params.id,
3866
- items: []
3867
- });
3868
- }
3869
- const promise = Promise.all(params.runs.map((runId) => {
3870
- return new Promise((resolve, reject) => {
3871
- this._taskWaits.set(runId, {
3872
- resolve,
3873
- reject
3874
- });
3875
- });
3876
- }));
3877
- await this.ipc.send("WAIT_FOR_BATCH", {
3878
- batchFriendlyId: params.id,
3879
- runFriendlyIds: params.runs
3880
- });
3881
- const results = await promise;
3882
- return {
3883
- id: params.id,
3884
- items: results
3885
- };
3886
- }
3887
- resumeTask(completion, execution) {
3888
- const wait = this._taskWaits.get(execution.run.id);
3889
- if (!wait) {
3890
- return;
3891
- }
3892
- if (completion.ok) {
3893
- wait.resolve(completion);
3894
- } else {
3895
- wait.reject(completion);
3896
- }
3897
- this._taskWaits.delete(execution.run.id);
3898
- }
3899
- get waitThresholdInMs() {
3900
- return this.options.waitThresholdInMs ?? 3e4;
3901
- }
3902
- };
3903
- __name(_ProdRuntimeManager, "ProdRuntimeManager");
3904
- var ProdRuntimeManager = _ProdRuntimeManager;
3905
- var _originClockTime, originClockTime_get, _originPreciseDate, originPreciseDate_get;
3906
- var _PreciseWallClock = class _PreciseWallClock {
3907
- constructor(options = {}) {
3908
- __privateAdd(this, _originClockTime);
3909
- __privateAdd(this, _originPreciseDate);
3910
- this._origin = {
3911
- clockTime: options.origin ?? process.hrtime(),
3912
- preciseDate: options.now ?? new preciseDate.PreciseDate()
3913
- };
3914
- }
3915
- preciseNow() {
3916
- const elapsedHrTime = process.hrtime(__privateGet(this, _originClockTime, originClockTime_get));
3917
- const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
3918
- const preciseDate$1 = new preciseDate.PreciseDate(__privateGet(this, _originPreciseDate, originPreciseDate_get).getFullTime() + elapsedNanoseconds);
3919
- const dateStruct = preciseDate$1.toStruct();
3920
- return [
3921
- dateStruct.seconds,
3922
- dateStruct.nanos
3923
- ];
3302
+ function formatDurationNanoseconds(nanoseconds, options) {
3303
+ return formatDurationMilliseconds(nanosecondsToMilliseconds(nanoseconds), options);
3304
+ }
3305
+ __name(formatDurationNanoseconds, "formatDurationNanoseconds");
3306
+ var aboveOneSecondUnits = [
3307
+ "d",
3308
+ "h",
3309
+ "m",
3310
+ "s"
3311
+ ];
3312
+ var belowOneSecondUnits = [
3313
+ "ms"
3314
+ ];
3315
+ function formatDurationMilliseconds(milliseconds, options) {
3316
+ let duration = humanizeDuration__default.default(milliseconds, {
3317
+ units: options?.units ? options.units : milliseconds < 1e3 ? belowOneSecondUnits : aboveOneSecondUnits,
3318
+ maxDecimalPoints: options?.maxDecimalPoints ?? 1,
3319
+ largest: 2
3320
+ });
3321
+ if (!options) {
3322
+ return duration;
3924
3323
  }
3925
- reset() {
3926
- this._origin = {
3927
- clockTime: process.hrtime(),
3928
- preciseDate: new preciseDate.PreciseDate()
3929
- };
3324
+ switch (options.style) {
3325
+ case "short":
3326
+ duration = duration.replace(" milliseconds", "ms");
3327
+ duration = duration.replace(" millisecond", "ms");
3328
+ duration = duration.replace(" seconds", "s");
3329
+ duration = duration.replace(" second", "s");
3330
+ duration = duration.replace(" minutes", "m");
3331
+ duration = duration.replace(" minute", "m");
3332
+ duration = duration.replace(" hours", "h");
3333
+ duration = duration.replace(" hour", "h");
3334
+ duration = duration.replace(" days", "d");
3335
+ duration = duration.replace(" day", "d");
3336
+ duration = duration.replace(" weeks", "w");
3337
+ duration = duration.replace(" week", "w");
3338
+ duration = duration.replace(" months", "mo");
3339
+ duration = duration.replace(" month", "mo");
3340
+ duration = duration.replace(" years", "y");
3341
+ duration = duration.replace(" year", "y");
3930
3342
  }
3931
- };
3932
- _originClockTime = new WeakSet();
3933
- originClockTime_get = /* @__PURE__ */ __name(function() {
3934
- return this._origin.clockTime;
3935
- }, "#originClockTime");
3936
- _originPreciseDate = new WeakSet();
3937
- originPreciseDate_get = /* @__PURE__ */ __name(function() {
3938
- return this._origin.preciseDate;
3939
- }, "#originPreciseDate");
3940
- __name(_PreciseWallClock, "PreciseWallClock");
3941
- var PreciseWallClock = _PreciseWallClock;
3343
+ return duration;
3344
+ }
3345
+ __name(formatDurationMilliseconds, "formatDurationMilliseconds");
3346
+ function formatDurationInDays(milliseconds) {
3347
+ let duration = humanizeDuration__default.default(milliseconds, {
3348
+ maxDecimalPoints: 0,
3349
+ largest: 2,
3350
+ units: [
3351
+ "d"
3352
+ ]
3353
+ });
3354
+ return duration;
3355
+ }
3356
+ __name(formatDurationInDays, "formatDurationInDays");
3942
3357
  var _TriggerTracer = class _TriggerTracer {
3943
3358
  constructor(_config) {
3944
3359
  this._config = _config;
@@ -4010,146 +3425,6 @@ var _TriggerTracer = class _TriggerTracer {
4010
3425
  };
4011
3426
  __name(_TriggerTracer, "TriggerTracer");
4012
3427
  var TriggerTracer = _TriggerTracer;
4013
- var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
4014
- var _ConsoleInterceptor = class _ConsoleInterceptor {
4015
- constructor(logger2, sendToStdIO) {
4016
- __privateAdd(this, _handleLog);
4017
- __privateAdd(this, _getTimestampInHrTime2);
4018
- __privateAdd(this, _getAttributes);
4019
- this.logger = logger2;
4020
- this.sendToStdIO = sendToStdIO;
4021
- }
4022
- // Intercept the console and send logs to the OpenTelemetry logger
4023
- // during the execution of the callback
4024
- async intercept(console2, callback) {
4025
- const originalConsole = {
4026
- log: console2.log,
4027
- info: console2.info,
4028
- warn: console2.warn,
4029
- error: console2.error,
4030
- debug: console2.debug
4031
- };
4032
- console2.log = this.log.bind(this);
4033
- console2.info = this.info.bind(this);
4034
- console2.warn = this.warn.bind(this);
4035
- console2.error = this.error.bind(this);
4036
- console2.debug = this.debug.bind(this);
4037
- try {
4038
- return await callback();
4039
- } finally {
4040
- console2.log = originalConsole.log;
4041
- console2.info = originalConsole.info;
4042
- console2.warn = originalConsole.warn;
4043
- console2.error = originalConsole.error;
4044
- console2.debug = originalConsole.debug;
4045
- }
4046
- }
4047
- debug(...args) {
4048
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
4049
- }
4050
- log(...args) {
4051
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
4052
- }
4053
- info(...args) {
4054
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
4055
- }
4056
- warn(...args) {
4057
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
4058
- }
4059
- error(...args) {
4060
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
4061
- }
4062
- };
4063
- _handleLog = new WeakSet();
4064
- handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
4065
- const body = util__default.default.format(...args);
4066
- if (this.sendToStdIO) {
4067
- if (severityNumber === apiLogs.SeverityNumber.ERROR) {
4068
- process.stderr.write(body);
4069
- } else {
4070
- process.stdout.write(body);
4071
- }
4072
- }
4073
- const parsed = tryParseJSON(body);
4074
- if (parsed.ok) {
4075
- this.logger.emit({
4076
- severityNumber,
4077
- severityText,
4078
- body: getLogMessage(parsed.value, severityText),
4079
- attributes: {
4080
- ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
4081
- ...flattenAttributes(parsed.value)
4082
- },
4083
- timestamp
4084
- });
4085
- return;
4086
- }
4087
- this.logger.emit({
4088
- severityNumber,
4089
- severityText,
4090
- body,
4091
- attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
4092
- timestamp
4093
- });
4094
- }, "#handleLog");
4095
- _getTimestampInHrTime2 = new WeakSet();
4096
- getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
4097
- return clock.preciseNow();
4098
- }, "#getTimestampInHrTime");
4099
- _getAttributes = new WeakSet();
4100
- getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
4101
- const icon = iconStringForSeverity(severityNumber1);
4102
- let result = {};
4103
- if (icon !== void 0) {
4104
- result[SemanticInternalAttributes.STYLE_ICON] = icon;
4105
- }
4106
- return result;
4107
- }, "#getAttributes");
4108
- __name(_ConsoleInterceptor, "ConsoleInterceptor");
4109
- var ConsoleInterceptor = _ConsoleInterceptor;
4110
- function getLogMessage(value, fallback) {
4111
- if (typeof value["message"] === "string") {
4112
- return value["message"];
4113
- }
4114
- if (typeof value["msg"] === "string") {
4115
- return value["msg"];
4116
- }
4117
- if (typeof value["body"] === "string") {
4118
- return value["body"];
4119
- }
4120
- if (typeof value["error"] === "string") {
4121
- return value["error"];
4122
- }
4123
- return fallback;
4124
- }
4125
- __name(getLogMessage, "getLogMessage");
4126
- function tryParseJSON(value) {
4127
- try {
4128
- const parsed = JSON.parse(value);
4129
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
4130
- return {
4131
- ok: true,
4132
- value: parsed
4133
- };
4134
- }
4135
- return {
4136
- ok: false,
4137
- value
4138
- };
4139
- } catch (e) {
4140
- return {
4141
- ok: false,
4142
- value
4143
- };
4144
- }
4145
- }
4146
- __name(tryParseJSON, "tryParseJSON");
4147
-
4148
- // src/v3/utils/styleAttributes.ts
4149
- function accessoryAttributes(accessory) {
4150
- return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
4151
- }
4152
- __name(accessoryAttributes, "accessoryAttributes");
4153
3428
 
4154
3429
  // src/eventFilterMatches.ts
4155
3430
  function eventFilterMatches(payload, filter) {
@@ -4319,150 +3594,18 @@ function omit(obj, ...keys) {
4319
3594
  return result;
4320
3595
  }
4321
3596
  __name(omit, "omit");
4322
- var _a2;
4323
- var AsyncResourceDetector = (_a2 = class {
4324
- constructor() {
4325
- __publicField(this, "_resolved", false);
4326
- this._promise = new Promise((resolver) => {
4327
- this._resolver = resolver;
4328
- });
4329
- }
4330
- detect(_config) {
4331
- return new resources.Resource({}, this._promise);
4332
- }
4333
- resolveWithAttributes(attributes) {
4334
- if (!this._resolver) {
4335
- throw new Error("Resolver not available");
4336
- }
4337
- if (this._resolved) {
4338
- return;
4339
- }
4340
- this._resolved = true;
4341
- this._resolver(attributes);
4342
- }
4343
- }, __name(_a2, "AsyncResourceDetector"), _a2);
4344
- var _TracingSDK = class _TracingSDK {
4345
- constructor(config) {
4346
- this.config = config;
4347
- this.asyncResourceDetector = new AsyncResourceDetector();
4348
- setLogLevel(config.diagLogLevel ?? "none");
4349
- const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
4350
- const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
4351
- const commonResources = resources.detectResourcesSync({
4352
- detectors: [
4353
- this.asyncResourceDetector,
4354
- resources.processDetectorSync
4355
- ]
4356
- }).merge(new resources.Resource({
4357
- [semanticConventions.SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
4358
- [SemanticInternalAttributes.TRIGGER]: true
4359
- })).merge(config.resource ?? new resources.Resource({})).merge(new resources.Resource(envResourceAttributes));
4360
- const traceProvider = new sdkTraceNode.NodeTracerProvider({
4361
- forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
4362
- resource: commonResources,
4363
- spanLimits: {
4364
- attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
4365
- attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
4366
- eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
4367
- attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
4368
- linkCountLimit: OTEL_LINK_COUNT_LIMIT,
4369
- attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
4370
- }
4371
- });
4372
- const spanExporter = new exporterTraceOtlpHttp.OTLPTraceExporter({
4373
- url: `${config.url}/v1/traces`,
4374
- timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
4375
- });
4376
- traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkTraceNode.BatchSpanProcessor(spanExporter, {
4377
- maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
4378
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
4379
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
4380
- maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
4381
- }) : new sdkTraceNode.SimpleSpanProcessor(spanExporter)));
4382
- traceProvider.register();
4383
- instrumentation.registerInstrumentations({
4384
- instrumentations: config.instrumentations ?? [],
4385
- tracerProvider: traceProvider
4386
- });
4387
- const logExporter = new exporterLogsOtlpHttp.OTLPLogExporter({
4388
- url: `${config.url}/v1/logs`
4389
- });
4390
- const loggerProvider = new sdkLogs.LoggerProvider({
4391
- resource: commonResources,
4392
- logRecordLimits: {
4393
- attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
4394
- attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
4395
- }
4396
- });
4397
- loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkLogs.BatchLogRecordProcessor(logExporter, {
4398
- maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
4399
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
4400
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
4401
- maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
4402
- }) : new sdkLogs.SimpleLogRecordProcessor(logExporter)));
4403
- this._logProvider = loggerProvider;
4404
- this._spanExporter = spanExporter;
4405
- this._traceProvider = traceProvider;
4406
- apiLogs.logs.setGlobalLoggerProvider(loggerProvider);
4407
- this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
4408
- this.getTracer = traceProvider.getTracer.bind(traceProvider);
4409
- }
4410
- async flush() {
4411
- await this._traceProvider.forceFlush();
4412
- await this._logProvider.forceFlush();
4413
- }
4414
- async shutdown() {
4415
- await this._traceProvider.shutdown();
4416
- await this._logProvider.shutdown();
4417
- }
4418
- };
4419
- __name(_TracingSDK, "TracingSDK");
4420
- var TracingSDK = _TracingSDK;
4421
- function setLogLevel(level) {
4422
- let diagLogLevel;
4423
- switch (level) {
4424
- case "none":
4425
- diagLogLevel = api.DiagLogLevel.NONE;
4426
- break;
4427
- case "error":
4428
- diagLogLevel = api.DiagLogLevel.ERROR;
4429
- break;
4430
- case "warn":
4431
- diagLogLevel = api.DiagLogLevel.WARN;
4432
- break;
4433
- case "info":
4434
- diagLogLevel = api.DiagLogLevel.INFO;
4435
- break;
4436
- case "debug":
4437
- diagLogLevel = api.DiagLogLevel.DEBUG;
4438
- break;
4439
- case "verbose":
4440
- diagLogLevel = api.DiagLogLevel.VERBOSE;
4441
- break;
4442
- case "all":
4443
- diagLogLevel = api.DiagLogLevel.ALL;
4444
- break;
4445
- default:
4446
- diagLogLevel = api.DiagLogLevel.NONE;
4447
- }
4448
- api.diag.setLogger(new api.DiagConsoleLogger(), diagLogLevel);
3597
+
3598
+ // src/v3/utils/styleAttributes.ts
3599
+ function accessoryAttributes(accessory) {
3600
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
4449
3601
  }
4450
- __name(setLogLevel, "setLogLevel");
3602
+ __name(accessoryAttributes, "accessoryAttributes");
4451
3603
 
4452
- // src/v3/otel/index.ts
4453
- function recordSpanException(span, error) {
4454
- if (error instanceof Error) {
4455
- span.recordException(error);
4456
- } else if (typeof error === "string") {
4457
- span.recordException(new Error(error));
4458
- } else {
4459
- span.recordException(new Error(JSON.stringify(error)));
4460
- }
4461
- span.setStatus({
4462
- code: api.SpanStatusCode.ERROR
4463
- });
3604
+ // src/v3/utils/detectDependencyVersion.ts
3605
+ function detectDependencyVersion(dependency) {
3606
+ return dependencies[dependency];
4464
3607
  }
4465
- __name(recordSpanException, "recordSpanException");
3608
+ __name(detectDependencyVersion, "detectDependencyVersion");
4466
3609
 
4467
3610
  // src/v3/utils/ioSerialization.ts
4468
3611
  async function parsePacket(value) {
@@ -4622,11 +3765,12 @@ async function createPacketAttributes(packet, dataKey, dataTypeKey) {
4622
3765
  try {
4623
3766
  const parsed = parse(packet.data);
4624
3767
  const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
4625
- return {
3768
+ const result = {
4626
3769
  ...flattenAttributes(jsonified, dataKey),
4627
3770
  [dataTypeKey]: "application/json"
4628
3771
  };
4629
- } catch {
3772
+ return result;
3773
+ } catch (e) {
4630
3774
  return;
4631
3775
  }
4632
3776
  case "application/store":
@@ -4732,378 +3876,10 @@ function safeJsonParse2(value) {
4732
3876
  }
4733
3877
  __name(safeJsonParse2, "safeJsonParse");
4734
3878
 
4735
- // src/v3/workers/taskExecutor.ts
4736
- var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
4737
- var _TaskExecutor = class _TaskExecutor {
4738
- constructor(task, options) {
4739
- __privateAdd(this, _callRun);
4740
- __privateAdd(this, _callTaskInit);
4741
- __privateAdd(this, _callTaskCleanup);
4742
- __privateAdd(this, _handleError);
4743
- this.task = task;
4744
- this._tracingSDK = options.tracingSDK;
4745
- this._tracer = options.tracer;
4746
- this._consoleInterceptor = options.consoleInterceptor;
4747
- this._config = options.projectConfig;
4748
- this._importedConfig = options.importedConfig;
4749
- this._handleErrorFn = options.handleErrorFn;
4750
- }
4751
- async execute(execution, worker, traceContext) {
4752
- const ctx = TaskRunContext.parse(execution);
4753
- const attemptMessage = `Attempt ${execution.attempt.number}`;
4754
- const originalPacket = {
4755
- data: execution.run.payload,
4756
- dataType: execution.run.payloadType
4757
- };
4758
- const result = await taskContextManager.runWith({
4759
- ctx,
4760
- worker
4761
- }, async () => {
4762
- this._tracingSDK.asyncResourceDetector.resolveWithAttributes({
4763
- ...taskContextManager.attributes,
4764
- [SemanticInternalAttributes.SDK_VERSION]: this.task.packageVersion,
4765
- [SemanticInternalAttributes.SDK_LANGUAGE]: "typescript"
4766
- });
4767
- return await this._tracer.startActiveSpan(attemptMessage, async (span) => {
4768
- return await this._consoleInterceptor.intercept(console, async () => {
4769
- let parsedPayload;
4770
- let initOutput;
4771
- try {
4772
- const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
4773
- parsedPayload = await parsePacket(payloadPacket);
4774
- initOutput = await __privateMethod(this, _callTaskInit, callTaskInit_fn).call(this, parsedPayload, ctx);
4775
- const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
4776
- try {
4777
- const stringifiedOutput = await stringifyIO(output);
4778
- const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
4779
- const attributes = await createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE);
4780
- if (attributes) {
4781
- span.setAttributes(attributes);
4782
- }
4783
- return {
4784
- ok: true,
4785
- id: execution.attempt.id,
4786
- output: finalOutput.data,
4787
- outputType: finalOutput.dataType
4788
- };
4789
- } catch (stringifyError) {
4790
- recordSpanException(span, stringifyError);
4791
- return {
4792
- ok: false,
4793
- id: execution.attempt.id,
4794
- error: {
4795
- type: "INTERNAL_ERROR",
4796
- code: TaskRunErrorCodes.TASK_OUTPUT_ERROR,
4797
- message: stringifyError instanceof Error ? stringifyError.message : typeof stringifyError === "string" ? stringifyError : void 0
4798
- }
4799
- };
4800
- }
4801
- } catch (runError) {
4802
- try {
4803
- const handleErrorResult = await __privateMethod(this, _handleError, handleError_fn).call(this, execution, runError, parsedPayload, ctx);
4804
- recordSpanException(span, handleErrorResult.error ?? runError);
4805
- return {
4806
- id: execution.attempt.id,
4807
- ok: false,
4808
- error: handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError),
4809
- retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
4810
- skippedRetrying: handleErrorResult.status === "skipped"
4811
- };
4812
- } catch (handleErrorError) {
4813
- recordSpanException(span, handleErrorError);
4814
- return {
4815
- ok: false,
4816
- id: execution.attempt.id,
4817
- error: {
4818
- type: "INTERNAL_ERROR",
4819
- code: TaskRunErrorCodes.HANDLE_ERROR_ERROR,
4820
- message: handleErrorError instanceof Error ? handleErrorError.message : typeof handleErrorError === "string" ? handleErrorError : void 0
4821
- }
4822
- };
4823
- }
4824
- } finally {
4825
- await __privateMethod(this, _callTaskCleanup, callTaskCleanup_fn).call(this, parsedPayload, ctx, initOutput);
4826
- }
4827
- });
4828
- }, {
4829
- kind: api.SpanKind.CONSUMER,
4830
- attributes: {
4831
- [SemanticInternalAttributes.STYLE_ICON]: "attempt",
4832
- ...accessoryAttributes({
4833
- items: [
4834
- {
4835
- text: ctx.task.filePath
4836
- },
4837
- {
4838
- text: `${ctx.task.exportName}.run()`
4839
- }
4840
- ],
4841
- style: "codepath"
4842
- })
4843
- }
4844
- }, this._tracer.extractContext(traceContext));
4845
- });
4846
- return result;
4847
- }
4848
- };
4849
- _callRun = new WeakSet();
4850
- callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
4851
- const runFn = this.task.fns.run;
4852
- const middlewareFn = this.task.fns.middleware;
4853
- if (!runFn) {
4854
- throw new Error("Task does not have a run function");
4855
- }
4856
- if (!middlewareFn) {
4857
- return runFn(payload, {
4858
- ctx
4859
- });
4860
- }
4861
- return middlewareFn(payload, {
4862
- ctx,
4863
- next: async () => runFn(payload, {
4864
- ctx,
4865
- init
4866
- })
4867
- });
4868
- }, "#callRun");
4869
- _callTaskInit = new WeakSet();
4870
- callTaskInit_fn = /* @__PURE__ */ __name(async function(payload1, ctx1) {
4871
- const initFn = this.task.fns.init;
4872
- if (!initFn) {
4873
- return {};
4874
- }
4875
- return this._tracer.startActiveSpan("init", async (span) => {
4876
- return await initFn(payload1, {
4877
- ctx: ctx1
4878
- });
4879
- });
4880
- }, "#callTaskInit");
4881
- _callTaskCleanup = new WeakSet();
4882
- callTaskCleanup_fn = /* @__PURE__ */ __name(async function(payload2, ctx2, init1) {
4883
- const cleanupFn = this.task.fns.cleanup;
4884
- if (!cleanupFn) {
4885
- return;
4886
- }
4887
- return this._tracer.startActiveSpan("cleanup", async (span) => {
4888
- return await cleanupFn(payload2, {
4889
- ctx: ctx2,
4890
- init: init1
4891
- });
4892
- });
4893
- }, "#callTaskCleanup");
4894
- _handleError = new WeakSet();
4895
- handleError_fn = /* @__PURE__ */ __name(async function(execution, error, payload3, ctx3) {
4896
- const retriesConfig = this._importedConfig?.retries ?? this._config.retries;
4897
- const retry = this.task.retry ?? retriesConfig?.default;
4898
- if (!retry) {
4899
- return {
4900
- status: "noop"
4901
- };
4902
- }
4903
- const delay = calculateNextRetryDelay(retry, execution.attempt.number);
4904
- if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
4905
- return {
4906
- status: "skipped"
4907
- };
4908
- }
4909
- return this._tracer.startActiveSpan("handleError()", async (span) => {
4910
- const handleErrorResult = this.task.fns.handleError ? await this.task.fns.handleError(payload3, error, {
4911
- ctx: ctx3,
4912
- retry,
4913
- retryDelayInMs: delay,
4914
- retryAt: delay ? new Date(Date.now() + delay) : void 0
4915
- }) : this._importedConfig ? await this._handleErrorFn?.(payload3, error, {
4916
- ctx: ctx3,
4917
- retry,
4918
- retryDelayInMs: delay,
4919
- retryAt: delay ? new Date(Date.now() + delay) : void 0
4920
- }) : void 0;
4921
- if (!handleErrorResult) {
4922
- return typeof delay === "undefined" ? {
4923
- status: "noop"
4924
- } : {
4925
- status: "retry",
4926
- retry: {
4927
- timestamp: Date.now() + delay,
4928
- delay
4929
- }
4930
- };
4931
- }
4932
- if (handleErrorResult.skipRetrying) {
4933
- return {
4934
- status: "skipped",
4935
- error: handleErrorResult.error
4936
- };
4937
- }
4938
- if (typeof handleErrorResult.retryAt !== "undefined") {
4939
- return {
4940
- status: "retry",
4941
- retry: {
4942
- timestamp: handleErrorResult.retryAt.getTime(),
4943
- delay: handleErrorResult.retryAt.getTime() - Date.now()
4944
- },
4945
- error: handleErrorResult.error
4946
- };
4947
- }
4948
- if (typeof handleErrorResult.retryDelayInMs === "number") {
4949
- return {
4950
- status: "retry",
4951
- retry: {
4952
- timestamp: Date.now() + handleErrorResult.retryDelayInMs,
4953
- delay: handleErrorResult.retryDelayInMs
4954
- },
4955
- error: handleErrorResult.error
4956
- };
4957
- }
4958
- if (handleErrorResult.retry && typeof handleErrorResult.retry === "object") {
4959
- const delay2 = calculateNextRetryDelay(handleErrorResult.retry, execution.attempt.number);
4960
- return typeof delay2 === "undefined" ? {
4961
- status: "noop",
4962
- error: handleErrorResult.error
4963
- } : {
4964
- status: "retry",
4965
- retry: {
4966
- timestamp: Date.now() + delay2,
4967
- delay: delay2
4968
- },
4969
- error: handleErrorResult.error
4970
- };
4971
- }
4972
- return {
4973
- status: "noop",
4974
- error: handleErrorResult.error
4975
- };
4976
- }, {
4977
- attributes: {
4978
- [SemanticInternalAttributes.STYLE_ICON]: "exclamation-circle"
4979
- }
4980
- });
4981
- }, "#handleError");
4982
- __name(_TaskExecutor, "TaskExecutor");
4983
- var TaskExecutor = _TaskExecutor;
4984
-
4985
- // package.json
4986
- var dependencies = {
4987
- "@google-cloud/precise-date": "^4.0.0",
4988
- "@opentelemetry/api": "^1.8.0",
4989
- "@opentelemetry/api-logs": "^0.48.0",
4990
- "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
4991
- "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
4992
- "@opentelemetry/instrumentation": "^0.49.1",
4993
- "@opentelemetry/resources": "^1.22.0",
4994
- "@opentelemetry/sdk-logs": "^0.49.1",
4995
- "@opentelemetry/sdk-node": "^0.49.1",
4996
- "@opentelemetry/sdk-trace-base": "^1.22.0",
4997
- "@opentelemetry/sdk-trace-node": "^1.22.0",
4998
- "@opentelemetry/semantic-conventions": "^1.22.0",
4999
- "humanize-duration": "^3.27.3",
5000
- "socket.io": "^4.7.4",
5001
- "socket.io-client": "^4.7.4",
5002
- superjson: "^2.2.1",
5003
- ulidx: "^2.2.1",
5004
- zod: "3.22.3",
5005
- "zod-error": "1.5.0",
5006
- "zod-validation-error": "^1.5.0"
5007
- };
5008
-
5009
- // src/v3/utils/detectDependencyVersion.ts
5010
- function detectDependencyVersion(dependency) {
5011
- return dependencies[dependency];
5012
- }
5013
- __name(detectDependencyVersion, "detectDependencyVersion");
5014
-
5015
- // src/v3/task-catalog/standardTaskCatalog.ts
5016
- var _StandardTaskCatalog = class _StandardTaskCatalog {
5017
- constructor() {
5018
- __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
5019
- __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
5020
- __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
5021
- }
5022
- registerTaskMetadata(task) {
5023
- const { fns, ...metadata } = task;
5024
- this._taskMetadata.set(task.id, metadata);
5025
- this._taskFunctions.set(task.id, fns);
5026
- }
5027
- updateTaskMetadata(id, updates) {
5028
- const existingMetadata = this._taskMetadata.get(id);
5029
- if (existingMetadata) {
5030
- this._taskMetadata.set(id, {
5031
- ...existingMetadata,
5032
- ...updates
5033
- });
5034
- }
5035
- if (updates.fns) {
5036
- const existingFunctions = this._taskFunctions.get(id);
5037
- if (existingFunctions) {
5038
- this._taskFunctions.set(id, {
5039
- ...existingFunctions,
5040
- ...updates.fns
5041
- });
5042
- }
5043
- }
5044
- }
5045
- registerTaskFileMetadata(id, metadata) {
5046
- this._taskFileMetadata.set(id, metadata);
5047
- }
5048
- // Return all the tasks, without the functions
5049
- getAllTaskMetadata() {
5050
- const result = [];
5051
- for (const [id, metadata] of this._taskMetadata) {
5052
- const fileMetadata = this._taskFileMetadata.get(id);
5053
- if (!fileMetadata) {
5054
- continue;
5055
- }
5056
- result.push({
5057
- ...metadata,
5058
- ...fileMetadata
5059
- });
5060
- }
5061
- return result;
5062
- }
5063
- getTaskMetadata(id) {
5064
- const metadata = this._taskMetadata.get(id);
5065
- const fileMetadata = this._taskFileMetadata.get(id);
5066
- if (!metadata || !fileMetadata) {
5067
- return void 0;
5068
- }
5069
- return {
5070
- ...metadata,
5071
- ...fileMetadata
5072
- };
5073
- }
5074
- getTask(id) {
5075
- const metadata = this._taskMetadata.get(id);
5076
- const fileMetadata = this._taskFileMetadata.get(id);
5077
- const fns = this._taskFunctions.get(id);
5078
- if (!metadata || !fns || !fileMetadata) {
5079
- return void 0;
5080
- }
5081
- return {
5082
- ...metadata,
5083
- ...fileMetadata,
5084
- fns
5085
- };
5086
- }
5087
- disable() {
5088
- }
5089
- };
5090
- __name(_StandardTaskCatalog, "StandardTaskCatalog");
5091
- var StandardTaskCatalog = _StandardTaskCatalog;
5092
-
5093
- // src/v3/index.ts
5094
- function parseTriggerTaskRequestBody(body) {
5095
- return TriggerTaskRequestBody.safeParse(body);
5096
- }
5097
- __name(parseTriggerTaskRequestBody, "parseTriggerTaskRequestBody");
5098
- function parseBatchTriggerTaskRequestBody(body) {
5099
- return BatchTriggerTaskRequestBody.safeParse(body);
5100
- }
5101
- __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
5102
-
5103
3879
  exports.APIConnectionError = APIConnectionError;
5104
3880
  exports.APIError = APIError;
5105
3881
  exports.ApiClient = ApiClient;
5106
- exports.ApiClientManager = ApiClientManager;
3882
+ exports.AttemptStatus = AttemptStatus;
5107
3883
  exports.AuthenticationError = AuthenticationError;
5108
3884
  exports.BackgroundWorkerClientMessages = BackgroundWorkerClientMessages;
5109
3885
  exports.BackgroundWorkerMetadata = BackgroundWorkerMetadata;
@@ -5118,19 +3894,21 @@ exports.CancellationSpanEvent = CancellationSpanEvent;
5118
3894
  exports.ClientToSharedQueueMessages = ClientToSharedQueueMessages;
5119
3895
  exports.Config = Config;
5120
3896
  exports.ConflictError = ConflictError;
5121
- exports.ConsoleInterceptor = ConsoleInterceptor;
5122
3897
  exports.CoordinatorToPlatformMessages = CoordinatorToPlatformMessages;
5123
3898
  exports.CoordinatorToProdWorkerMessages = CoordinatorToProdWorkerMessages;
5124
3899
  exports.CreateAuthorizationCodeResponseSchema = CreateAuthorizationCodeResponseSchema;
5125
3900
  exports.CreateBackgroundWorkerRequestBody = CreateBackgroundWorkerRequestBody;
5126
3901
  exports.CreateBackgroundWorkerResponse = CreateBackgroundWorkerResponse;
3902
+ exports.CreateEnvironmentVariableRequestBody = CreateEnvironmentVariableRequestBody;
5127
3903
  exports.CreateScheduleOptions = CreateScheduleOptions;
5128
3904
  exports.CreateUploadPayloadUrlResponseBody = CreateUploadPayloadUrlResponseBody;
5129
3905
  exports.DeletedScheduleObject = DeletedScheduleObject;
5130
3906
  exports.DeploymentErrorData = DeploymentErrorData;
5131
- exports.DevRuntimeManager = DevRuntimeManager;
5132
- exports.DurableClock = PreciseWallClock;
5133
3907
  exports.EnvironmentType = EnvironmentType;
3908
+ exports.EnvironmentVariable = EnvironmentVariable;
3909
+ exports.EnvironmentVariableResponseBody = EnvironmentVariableResponseBody;
3910
+ exports.EnvironmentVariableValue = EnvironmentVariableValue;
3911
+ exports.EnvironmentVariables = EnvironmentVariables;
5134
3912
  exports.EventFilter = EventFilter;
5135
3913
  exports.ExceptionEventProperties = ExceptionEventProperties;
5136
3914
  exports.ExceptionSpanEvent = ExceptionSpanEvent;
@@ -5151,6 +3929,7 @@ exports.GetProjectEnvResponse = GetProjectEnvResponse;
5151
3929
  exports.GetProjectResponseBody = GetProjectResponseBody;
5152
3930
  exports.GetProjectsResponseBody = GetProjectsResponseBody;
5153
3931
  exports.ImageDetailsMetadata = ImageDetailsMetadata;
3932
+ exports.ImportEnvironmentVariablesRequestBody = ImportEnvironmentVariablesRequestBody;
5154
3933
  exports.InitializeDeploymentRequestBody = InitializeDeploymentRequestBody;
5155
3934
  exports.InitializeDeploymentResponseBody = InitializeDeploymentResponseBody;
5156
3935
  exports.InternalServerError = InternalServerError;
@@ -5159,6 +3938,7 @@ exports.ListSchedulesResult = ListSchedulesResult;
5159
3938
  exports.Machine = Machine;
5160
3939
  exports.MachineCpu = MachineCpu;
5161
3940
  exports.MachineMemory = MachineMemory;
3941
+ exports.NULL_SENTINEL = NULL_SENTINEL;
5162
3942
  exports.NotFoundError = NotFoundError;
5163
3943
  exports.OFFLOAD_IO_PACKET_LENGTH_LIMIT = OFFLOAD_IO_PACKET_LENGTH_LIMIT;
5164
3944
  exports.OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT;
@@ -5169,7 +3949,6 @@ exports.OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_
5169
3949
  exports.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT;
5170
3950
  exports.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT;
5171
3951
  exports.OTEL_SPAN_EVENT_COUNT_LIMIT = OTEL_SPAN_EVENT_COUNT_LIMIT;
5172
- exports.OtelTaskLogger = OtelTaskLogger;
5173
3952
  exports.OtherSpanEvent = OtherSpanEvent;
5174
3953
  exports.PRIMARY_VARIANT = PRIMARY_VARIANT;
5175
3954
  exports.PermissionDeniedError = PermissionDeniedError;
@@ -5178,7 +3957,6 @@ exports.PlatformToProviderMessages = PlatformToProviderMessages;
5178
3957
  exports.PostStartCauses = PostStartCauses;
5179
3958
  exports.PreStopCauses = PreStopCauses;
5180
3959
  exports.ProdChildToWorkerMessages = ProdChildToWorkerMessages;
5181
- exports.ProdRuntimeManager = ProdRuntimeManager;
5182
3960
  exports.ProdTaskRunExecution = ProdTaskRunExecution;
5183
3961
  exports.ProdTaskRunExecutionPayload = ProdTaskRunExecutionPayload;
5184
3962
  exports.ProdWorkerSocketData = ProdWorkerSocketData;
@@ -5189,22 +3967,20 @@ exports.QueueOptions = QueueOptions;
5189
3967
  exports.RateLimitError = RateLimitError;
5190
3968
  exports.RateLimitOptions = RateLimitOptions;
5191
3969
  exports.ReplayRunResponse = ReplayRunResponse;
3970
+ exports.RetrieveRunResponse = RetrieveRunResponse;
5192
3971
  exports.RetryOptions = RetryOptions;
3972
+ exports.RunStatus = RunStatus;
5193
3973
  exports.ScheduleObject = ScheduleObject;
5194
3974
  exports.ScheduledTaskPayload = ScheduledTaskPayload;
5195
3975
  exports.SemanticInternalAttributes = SemanticInternalAttributes;
5196
3976
  exports.SharedQueueToClientMessages = SharedQueueToClientMessages;
5197
- exports.SimpleStructuredLogger = SimpleStructuredLogger;
5198
3977
  exports.SlidingWindowRateLimit = SlidingWindowRateLimit;
5199
3978
  exports.SpanEvent = SpanEvent;
5200
3979
  exports.SpanEvents = SpanEvents;
5201
3980
  exports.SpanMessagingEvent = SpanMessagingEvent;
5202
- exports.StandardTaskCatalog = StandardTaskCatalog;
5203
3981
  exports.StartDeploymentIndexingRequestBody = StartDeploymentIndexingRequestBody;
5204
3982
  exports.StartDeploymentIndexingResponseBody = StartDeploymentIndexingResponseBody;
5205
- exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
5206
3983
  exports.TaskEventStyle = TaskEventStyle;
5207
- exports.TaskExecutor = TaskExecutor;
5208
3984
  exports.TaskFileMetadata = TaskFileMetadata;
5209
3985
  exports.TaskMetadata = TaskMetadata;
5210
3986
  exports.TaskMetadataFailedToParseData = TaskMetadataFailedToParseData;
@@ -5220,6 +3996,7 @@ exports.TaskRunExecution = TaskRunExecution;
5220
3996
  exports.TaskRunExecutionAttempt = TaskRunExecutionAttempt;
5221
3997
  exports.TaskRunExecutionBatch = TaskRunExecutionBatch;
5222
3998
  exports.TaskRunExecutionEnvironment = TaskRunExecutionEnvironment;
3999
+ exports.TaskRunExecutionLazyAttemptPayload = TaskRunExecutionLazyAttemptPayload;
5223
4000
  exports.TaskRunExecutionOrganization = TaskRunExecutionOrganization;
5224
4001
  exports.TaskRunExecutionPayload = TaskRunExecutionPayload;
5225
4002
  exports.TaskRunExecutionProject = TaskRunExecutionProject;
@@ -5231,24 +4008,15 @@ exports.TaskRunFailedExecutionResult = TaskRunFailedExecutionResult;
5231
4008
  exports.TaskRunInternalError = TaskRunInternalError;
5232
4009
  exports.TaskRunStringError = TaskRunStringError;
5233
4010
  exports.TaskRunSuccessfulExecutionResult = TaskRunSuccessfulExecutionResult;
5234
- exports.TracingSDK = TracingSDK;
5235
4011
  exports.TriggerTaskRequestBody = TriggerTaskRequestBody;
5236
4012
  exports.TriggerTaskResponse = TriggerTaskResponse;
5237
4013
  exports.TriggerTracer = TriggerTracer;
5238
4014
  exports.UncaughtExceptionMessage = UncaughtExceptionMessage;
5239
4015
  exports.UnprocessableEntityError = UnprocessableEntityError;
4016
+ exports.UpdateEnvironmentVariableRequestBody = UpdateEnvironmentVariableRequestBody;
5240
4017
  exports.UpdateScheduleOptions = UpdateScheduleOptions;
5241
4018
  exports.WaitReason = WaitReason;
5242
4019
  exports.WhoAmIResponseSchema = WhoAmIResponseSchema;
5243
- exports.ZodIpcConnection = ZodIpcConnection;
5244
- exports.ZodMessageHandler = ZodMessageHandler;
5245
- exports.ZodMessageSchema = ZodMessageSchema;
5246
- exports.ZodMessageSender = ZodMessageSender;
5247
- exports.ZodNamespace = ZodNamespace;
5248
- exports.ZodSchemaParsedError = ZodSchemaParsedError;
5249
- exports.ZodSocketConnection = ZodSocketConnection;
5250
- exports.ZodSocketMessageHandler = ZodSocketMessageHandler;
5251
- exports.ZodSocketMessageSender = ZodSocketMessageSender;
5252
4020
  exports.accessoryAttributes = accessoryAttributes;
5253
4021
  exports.apiClientManager = apiClientManager;
5254
4022
  exports.calculateNextRetryDelay = calculateNextRetryDelay;
@@ -5260,6 +4028,7 @@ exports.conditionallyExportPacket = conditionallyExportPacket;
5260
4028
  exports.conditionallyImportPacket = conditionallyImportPacket;
5261
4029
  exports.correctErrorStackTrace = correctErrorStackTrace;
5262
4030
  exports.createErrorTaskError = createErrorTaskError;
4031
+ exports.createJsonErrorObject = createJsonErrorObject;
5263
4032
  exports.createPacketAttributes = createPacketAttributes;
5264
4033
  exports.createPacketAttributesAsJson = createPacketAttributesAsJson;
5265
4034
  exports.defaultFetchRetryOptions = defaultFetchRetryOptions;
@@ -5271,31 +4040,25 @@ exports.formatDuration = formatDuration;
5271
4040
  exports.formatDurationInDays = formatDurationInDays;
5272
4041
  exports.formatDurationMilliseconds = formatDurationMilliseconds;
5273
4042
  exports.formatDurationNanoseconds = formatDurationNanoseconds;
5274
- exports.getEnvVar = getEnvVar;
5275
4043
  exports.groupTaskMetadataIssuesByTask = groupTaskMetadataIssuesByTask;
5276
- exports.iconStringForSeverity = iconStringForSeverity;
5277
4044
  exports.imposeAttributeLimits = imposeAttributeLimits;
5278
4045
  exports.isCancellationSpanEvent = isCancellationSpanEvent;
5279
4046
  exports.isExceptionSpanEvent = isExceptionSpanEvent;
5280
- exports.logLevels = logLevels;
5281
4047
  exports.logger = logger;
5282
4048
  exports.millisecondsToNanoseconds = millisecondsToNanoseconds;
5283
4049
  exports.nanosecondsToMilliseconds = nanosecondsToMilliseconds;
5284
4050
  exports.omit = omit;
5285
4051
  exports.packetRequiresOffloading = packetRequiresOffloading;
5286
- exports.parseBatchTriggerTaskRequestBody = parseBatchTriggerTaskRequestBody;
5287
4052
  exports.parseError = parseError;
5288
4053
  exports.parsePacket = parsePacket;
5289
- exports.parseTriggerTaskRequestBody = parseTriggerTaskRequestBody;
5290
4054
  exports.prettyPrintPacket = prettyPrintPacket;
5291
4055
  exports.primitiveValueOrflattenedAttributes = primitiveValueOrflattenedAttributes;
5292
- exports.recordSpanException = recordSpanException;
5293
4056
  exports.runtime = runtime;
5294
4057
  exports.serverWebsocketMessages = serverWebsocketMessages;
5295
4058
  exports.stringPatternMatchers = stringPatternMatchers;
5296
4059
  exports.stringifyIO = stringifyIO;
5297
4060
  exports.taskCatalog = taskCatalog;
5298
- exports.taskContextManager = taskContextManager;
4061
+ exports.taskContext = taskContext;
5299
4062
  exports.unflattenAttributes = unflattenAttributes;
5300
4063
  exports.workerToChildMessages = workerToChildMessages;
5301
4064
  //# sourceMappingURL=out.js.map