@trigger.dev/core 3.0.0-beta.3 → 3.0.0-beta.30

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 (65) hide show
  1. package/dist/catalog-KbyTBoap.d.ts +2496 -0
  2. package/dist/catalog-ck7x04PV.d.mts +2496 -0
  3. package/dist/manager-WNMVbgHf.d.mts +1158 -0
  4. package/dist/manager-WNMVbgHf.d.ts +1158 -0
  5. package/dist/messages-vq7Bk4Ap.d.mts +12838 -0
  6. package/dist/messages-vq7Bk4Ap.d.ts +12838 -0
  7. package/dist/v3/dev/index.d.mts +28 -0
  8. package/dist/v3/dev/index.d.ts +28 -0
  9. package/dist/v3/dev/index.js +93 -0
  10. package/dist/v3/dev/index.js.map +1 -0
  11. package/dist/v3/dev/index.mjs +91 -0
  12. package/dist/v3/dev/index.mjs.map +1 -0
  13. package/dist/v3/index.d.mts +850 -16919
  14. package/dist/v3/index.d.ts +850 -16919
  15. package/dist/v3/index.js +1676 -2763
  16. package/dist/v3/index.js.map +1 -1
  17. package/dist/v3/index.mjs +1681 -2767
  18. package/dist/v3/index.mjs.map +1 -1
  19. package/dist/v3/otel/index.js +83 -45
  20. package/dist/v3/otel/index.js.map +1 -1
  21. package/dist/v3/otel/index.mjs +83 -45
  22. package/dist/v3/otel/index.mjs.map +1 -1
  23. package/dist/v3/prod/index.d.mts +45 -0
  24. package/dist/v3/prod/index.d.ts +45 -0
  25. package/dist/v3/prod/index.js +229 -0
  26. package/dist/v3/prod/index.js.map +1 -0
  27. package/dist/v3/prod/index.mjs +227 -0
  28. package/dist/v3/prod/index.mjs.map +1 -0
  29. package/dist/v3/utils/structuredLogger.d.mts +31 -0
  30. package/dist/v3/utils/structuredLogger.d.ts +31 -0
  31. package/dist/v3/utils/structuredLogger.js +88 -0
  32. package/dist/v3/utils/structuredLogger.js.map +1 -0
  33. package/dist/v3/utils/structuredLogger.mjs +86 -0
  34. package/dist/v3/utils/structuredLogger.mjs.map +1 -0
  35. package/dist/v3/workers/index.d.mts +95 -0
  36. package/dist/v3/workers/index.d.ts +95 -0
  37. package/dist/v3/workers/index.js +2631 -0
  38. package/dist/v3/workers/index.js.map +1 -0
  39. package/dist/v3/workers/index.mjs +2615 -0
  40. package/dist/v3/workers/index.mjs.map +1 -0
  41. package/dist/v3/zodIpc.d.mts +32 -0
  42. package/dist/v3/zodIpc.d.ts +32 -0
  43. package/dist/v3/zodIpc.js +268 -0
  44. package/dist/v3/zodIpc.js.map +1 -0
  45. package/dist/v3/zodIpc.mjs +266 -0
  46. package/dist/v3/zodIpc.mjs.map +1 -0
  47. package/dist/v3/zodMessageHandler.d.mts +69 -0
  48. package/dist/v3/zodMessageHandler.d.ts +69 -0
  49. package/dist/v3/zodMessageHandler.js +168 -0
  50. package/dist/v3/zodMessageHandler.js.map +1 -0
  51. package/dist/v3/zodMessageHandler.mjs +163 -0
  52. package/dist/v3/zodMessageHandler.mjs.map +1 -0
  53. package/dist/v3/zodNamespace.d.mts +3663 -0
  54. package/dist/v3/zodNamespace.d.ts +3663 -0
  55. package/dist/v3/zodNamespace.js +356 -0
  56. package/dist/v3/zodNamespace.js.map +1 -0
  57. package/dist/v3/zodNamespace.mjs +354 -0
  58. package/dist/v3/zodNamespace.mjs.map +1 -0
  59. package/dist/v3/zodSocket.d.mts +88 -0
  60. package/dist/v3/zodSocket.d.ts +88 -0
  61. package/dist/v3/zodSocket.js +309 -0
  62. package/dist/v3/zodSocket.js.map +1 -0
  63. package/dist/v3/zodSocket.mjs +305 -0
  64. package/dist/v3/zodSocket.mjs.map +1 -0
  65. package/package.json +72 -7
@@ -0,0 +1,2631 @@
1
+ 'use strict';
2
+
3
+ var api = require('@opentelemetry/api');
4
+ var apiLogs = require('@opentelemetry/api-logs');
5
+ var exporterLogsOtlpHttp = require('@opentelemetry/exporter-logs-otlp-http');
6
+ var exporterTraceOtlpHttp = require('@opentelemetry/exporter-trace-otlp-http');
7
+ var instrumentation = require('@opentelemetry/instrumentation');
8
+ var resources = require('@opentelemetry/resources');
9
+ var sdkLogs = require('@opentelemetry/sdk-logs');
10
+ var sdkTraceNode = require('@opentelemetry/sdk-trace-node');
11
+ var semanticConventions = require('@opentelemetry/semantic-conventions');
12
+ var zod = require('zod');
13
+ var zodValidationError = require('zod-validation-error');
14
+ var preciseDate = require('@google-cloud/precise-date');
15
+ var util = require('util');
16
+
17
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
18
+
19
+ var util__default = /*#__PURE__*/_interopDefault(util);
20
+
21
+ var __defProp = Object.defineProperty;
22
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
23
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
24
+ var __publicField = (obj, key, value) => {
25
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
26
+ return value;
27
+ };
28
+ var __accessCheck = (obj, member, msg) => {
29
+ if (!member.has(obj))
30
+ throw TypeError("Cannot " + msg);
31
+ };
32
+ var __privateGet = (obj, member, getter) => {
33
+ __accessCheck(obj, member, "read from private field");
34
+ return getter ? getter.call(obj) : member.get(obj);
35
+ };
36
+ var __privateAdd = (obj, member, value) => {
37
+ if (member.has(obj))
38
+ throw TypeError("Cannot add the same private member more than once");
39
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
40
+ };
41
+ var __privateMethod = (obj, member, method) => {
42
+ __accessCheck(obj, member, "access private method");
43
+ return method;
44
+ };
45
+
46
+ // src/v3/errors.ts
47
+ function parseError(error) {
48
+ if (error instanceof Error) {
49
+ return {
50
+ type: "BUILT_IN_ERROR",
51
+ name: error.name,
52
+ message: error.message,
53
+ stackTrace: error.stack ?? ""
54
+ };
55
+ }
56
+ if (typeof error === "string") {
57
+ return {
58
+ type: "STRING_ERROR",
59
+ raw: error
60
+ };
61
+ }
62
+ try {
63
+ return {
64
+ type: "CUSTOM_ERROR",
65
+ raw: JSON.stringify(error)
66
+ };
67
+ } catch (e) {
68
+ return {
69
+ type: "CUSTOM_ERROR",
70
+ raw: String(error)
71
+ };
72
+ }
73
+ }
74
+ __name(parseError, "parseError");
75
+
76
+ // src/v3/limits.ts
77
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
78
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
79
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
80
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
81
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
82
+ var OTEL_LINK_COUNT_LIMIT = 2;
83
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
84
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
85
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
86
+
87
+ // src/v3/semanticInternalAttributes.ts
88
+ var SemanticInternalAttributes = {
89
+ ENVIRONMENT_ID: "ctx.environment.id",
90
+ ENVIRONMENT_TYPE: "ctx.environment.type",
91
+ ORGANIZATION_ID: "ctx.organization.id",
92
+ ORGANIZATION_SLUG: "ctx.organization.slug",
93
+ ORGANIZATION_NAME: "ctx.organization.name",
94
+ PROJECT_ID: "ctx.project.id",
95
+ PROJECT_REF: "ctx.project.ref",
96
+ PROJECT_NAME: "ctx.project.title",
97
+ PROJECT_DIR: "project.dir",
98
+ ATTEMPT_ID: "ctx.attempt.id",
99
+ ATTEMPT_NUMBER: "ctx.attempt.number",
100
+ RUN_ID: "ctx.run.id",
101
+ RUN_IS_TEST: "ctx.run.isTest",
102
+ BATCH_ID: "ctx.batch.id",
103
+ TASK_SLUG: "ctx.task.id",
104
+ TASK_PATH: "ctx.task.filePath",
105
+ TASK_EXPORT_NAME: "ctx.task.exportName",
106
+ QUEUE_NAME: "ctx.queue.name",
107
+ QUEUE_ID: "ctx.queue.id",
108
+ SPAN_PARTIAL: "$span.partial",
109
+ SPAN_ID: "$span.span_id",
110
+ OUTPUT: "$output",
111
+ OUTPUT_TYPE: "$mime_type_output",
112
+ STYLE: "$style",
113
+ STYLE_ICON: "$style.icon",
114
+ STYLE_VARIANT: "$style.variant",
115
+ STYLE_ACCESSORY: "$style.accessory",
116
+ METADATA: "$metadata",
117
+ TRIGGER: "$trigger",
118
+ PAYLOAD: "$payload",
119
+ PAYLOAD_TYPE: "$mime_type_payload",
120
+ SHOW: "$show",
121
+ SHOW_ACTIONS: "$show.actions",
122
+ WORKER_ID: "worker.id",
123
+ WORKER_VERSION: "worker.version",
124
+ CLI_VERSION: "cli.version",
125
+ SDK_VERSION: "sdk.version",
126
+ SDK_LANGUAGE: "sdk.language",
127
+ RETRY_AT: "retry.at",
128
+ RETRY_DELAY: "retry.delay",
129
+ RETRY_COUNT: "retry.count",
130
+ LINK_TITLE: "$link.title",
131
+ IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
132
+ };
133
+
134
+ // src/v3/utils/flattenAttributes.ts
135
+ var NULL_SENTINEL = "$@null((";
136
+ function flattenAttributes(obj, prefix) {
137
+ const result = {};
138
+ if (obj === void 0) {
139
+ return result;
140
+ }
141
+ if (obj === null) {
142
+ result[prefix || ""] = NULL_SENTINEL;
143
+ return result;
144
+ }
145
+ if (typeof obj === "string") {
146
+ result[prefix || ""] = obj;
147
+ return result;
148
+ }
149
+ if (typeof obj === "number") {
150
+ result[prefix || ""] = obj;
151
+ return result;
152
+ }
153
+ if (typeof obj === "boolean") {
154
+ result[prefix || ""] = obj;
155
+ return result;
156
+ }
157
+ for (const [key, value] of Object.entries(obj)) {
158
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${key}]` : key}`;
159
+ if (Array.isArray(value)) {
160
+ for (let i = 0; i < value.length; i++) {
161
+ if (typeof value[i] === "object" && value[i] !== null) {
162
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
163
+ } else {
164
+ if (value[i] === null) {
165
+ result[`${newPrefix}.[${i}]`] = NULL_SENTINEL;
166
+ } else {
167
+ result[`${newPrefix}.[${i}]`] = value[i];
168
+ }
169
+ }
170
+ }
171
+ } else if (isRecord(value)) {
172
+ Object.assign(result, flattenAttributes(value, newPrefix));
173
+ } else {
174
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
175
+ result[newPrefix] = value;
176
+ } else if (value === null) {
177
+ result[newPrefix] = NULL_SENTINEL;
178
+ }
179
+ }
180
+ }
181
+ return result;
182
+ }
183
+ __name(flattenAttributes, "flattenAttributes");
184
+ function isRecord(value) {
185
+ return value !== null && typeof value === "object" && !Array.isArray(value);
186
+ }
187
+ __name(isRecord, "isRecord");
188
+
189
+ // src/v3/utils/platform.ts
190
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
191
+
192
+ // src/v3/utils/globals.ts
193
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
194
+ var _global = _globalThis;
195
+ function registerGlobal(type, instance, allowOverride = false) {
196
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
197
+ if (!allowOverride && api[type]) {
198
+ return false;
199
+ }
200
+ api[type] = instance;
201
+ return true;
202
+ }
203
+ __name(registerGlobal, "registerGlobal");
204
+ function getGlobal(type) {
205
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
206
+ }
207
+ __name(getGlobal, "getGlobal");
208
+ function unregisterGlobal(type) {
209
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
210
+ if (api) {
211
+ delete api[type];
212
+ }
213
+ }
214
+ __name(unregisterGlobal, "unregisterGlobal");
215
+
216
+ // src/v3/taskContext/index.ts
217
+ var API_NAME = "task-context";
218
+ var _getTaskContext, getTaskContext_fn;
219
+ var _TaskContextAPI = class _TaskContextAPI {
220
+ constructor() {
221
+ __privateAdd(this, _getTaskContext);
222
+ }
223
+ static getInstance() {
224
+ if (!this._instance) {
225
+ this._instance = new _TaskContextAPI();
226
+ }
227
+ return this._instance;
228
+ }
229
+ get isInsideTask() {
230
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
231
+ }
232
+ get ctx() {
233
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
234
+ }
235
+ get worker() {
236
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
237
+ }
238
+ get attributes() {
239
+ if (this.ctx) {
240
+ return {
241
+ ...this.contextAttributes,
242
+ ...this.workerAttributes
243
+ };
244
+ }
245
+ return {};
246
+ }
247
+ get workerAttributes() {
248
+ if (this.worker) {
249
+ return {
250
+ [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
251
+ [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
252
+ };
253
+ }
254
+ return {};
255
+ }
256
+ get contextAttributes() {
257
+ if (this.ctx) {
258
+ return {
259
+ [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
260
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
261
+ [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
262
+ [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
263
+ [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
264
+ [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
265
+ [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
266
+ [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
267
+ [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
268
+ [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
269
+ [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
270
+ [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
271
+ [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
272
+ [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
273
+ [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
274
+ [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
275
+ [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
276
+ [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
277
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
278
+ };
279
+ }
280
+ return {};
281
+ }
282
+ disable() {
283
+ unregisterGlobal(API_NAME);
284
+ }
285
+ setGlobalTaskContext(taskContext2) {
286
+ return registerGlobal(API_NAME, taskContext2);
287
+ }
288
+ };
289
+ _getTaskContext = new WeakSet();
290
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
291
+ return getGlobal(API_NAME);
292
+ }, "#getTaskContext");
293
+ __name(_TaskContextAPI, "TaskContextAPI");
294
+ var TaskContextAPI = _TaskContextAPI;
295
+
296
+ // src/v3/task-context-api.ts
297
+ var taskContext = TaskContextAPI.getInstance();
298
+
299
+ // src/v3/taskContext/otelProcessors.ts
300
+ var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
301
+ constructor(innerProcessor) {
302
+ this._innerProcessor = innerProcessor;
303
+ }
304
+ // Called when a span starts
305
+ onStart(span, parentContext) {
306
+ if (taskContext.ctx) {
307
+ span.setAttributes(flattenAttributes({
308
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContext.ctx.attempt.id,
309
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContext.ctx.attempt.number
310
+ }, SemanticInternalAttributes.METADATA));
311
+ }
312
+ this._innerProcessor.onStart(span, parentContext);
313
+ }
314
+ // Delegate the rest of the methods to the wrapped processor
315
+ onEnd(span) {
316
+ this._innerProcessor.onEnd(span);
317
+ }
318
+ shutdown() {
319
+ return this._innerProcessor.shutdown();
320
+ }
321
+ forceFlush() {
322
+ return this._innerProcessor.forceFlush();
323
+ }
324
+ };
325
+ __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
326
+ var TaskContextSpanProcessor = _TaskContextSpanProcessor;
327
+ var _TaskContextLogProcessor = class _TaskContextLogProcessor {
328
+ constructor(innerProcessor) {
329
+ this._innerProcessor = innerProcessor;
330
+ }
331
+ forceFlush() {
332
+ return this._innerProcessor.forceFlush();
333
+ }
334
+ onEmit(logRecord, context2) {
335
+ if (taskContext.ctx) {
336
+ logRecord.setAttributes(flattenAttributes({
337
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContext.ctx.attempt.id,
338
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContext.ctx.attempt.number
339
+ }, SemanticInternalAttributes.METADATA));
340
+ }
341
+ this._innerProcessor.onEmit(logRecord, context2);
342
+ }
343
+ shutdown() {
344
+ return this._innerProcessor.shutdown();
345
+ }
346
+ };
347
+ __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
348
+ var TaskContextLogProcessor = _TaskContextLogProcessor;
349
+
350
+ // src/v3/utils/getEnv.ts
351
+ function getEnvVar(name) {
352
+ if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
353
+ return process.env[name];
354
+ }
355
+ }
356
+ __name(getEnvVar, "getEnvVar");
357
+
358
+ // src/v3/otel/tracingSDK.ts
359
+ var _a;
360
+ var AsyncResourceDetector = (_a = class {
361
+ constructor() {
362
+ __publicField(this, "_resolved", false);
363
+ this._promise = new Promise((resolver) => {
364
+ this._resolver = resolver;
365
+ });
366
+ }
367
+ detect(_config) {
368
+ return new resources.Resource({}, this._promise);
369
+ }
370
+ resolveWithAttributes(attributes) {
371
+ if (!this._resolver) {
372
+ throw new Error("Resolver not available");
373
+ }
374
+ if (this._resolved) {
375
+ return;
376
+ }
377
+ this._resolved = true;
378
+ this._resolver(attributes);
379
+ }
380
+ }, __name(_a, "AsyncResourceDetector"), _a);
381
+ var _TracingSDK = class _TracingSDK {
382
+ constructor(config) {
383
+ this.config = config;
384
+ this.asyncResourceDetector = new AsyncResourceDetector();
385
+ setLogLevel(config.diagLogLevel ?? "none");
386
+ const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
387
+ const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
388
+ const commonResources = resources.detectResourcesSync({
389
+ detectors: [
390
+ this.asyncResourceDetector,
391
+ resources.processDetectorSync
392
+ ]
393
+ }).merge(new resources.Resource({
394
+ [semanticConventions.SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
395
+ [SemanticInternalAttributes.TRIGGER]: true
396
+ })).merge(config.resource ?? new resources.Resource({})).merge(new resources.Resource(envResourceAttributes));
397
+ const traceProvider = new sdkTraceNode.NodeTracerProvider({
398
+ forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
399
+ resource: commonResources,
400
+ spanLimits: {
401
+ attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
402
+ attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
403
+ eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
404
+ attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
405
+ linkCountLimit: OTEL_LINK_COUNT_LIMIT,
406
+ attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
407
+ }
408
+ });
409
+ const spanExporter = new exporterTraceOtlpHttp.OTLPTraceExporter({
410
+ url: `${config.url}/v1/traces`,
411
+ timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
412
+ });
413
+ traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkTraceNode.BatchSpanProcessor(spanExporter, {
414
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
415
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
416
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
417
+ maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
418
+ }) : new sdkTraceNode.SimpleSpanProcessor(spanExporter)));
419
+ traceProvider.register();
420
+ instrumentation.registerInstrumentations({
421
+ instrumentations: config.instrumentations ?? [],
422
+ tracerProvider: traceProvider
423
+ });
424
+ const logExporter = new exporterLogsOtlpHttp.OTLPLogExporter({
425
+ url: `${config.url}/v1/logs`
426
+ });
427
+ const loggerProvider = new sdkLogs.LoggerProvider({
428
+ resource: commonResources,
429
+ logRecordLimits: {
430
+ attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
431
+ attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
432
+ }
433
+ });
434
+ loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkLogs.BatchLogRecordProcessor(logExporter, {
435
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
436
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
437
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
438
+ maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
439
+ }) : new sdkLogs.SimpleLogRecordProcessor(logExporter)));
440
+ this._logProvider = loggerProvider;
441
+ this._spanExporter = spanExporter;
442
+ this._traceProvider = traceProvider;
443
+ apiLogs.logs.setGlobalLoggerProvider(loggerProvider);
444
+ this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
445
+ this.getTracer = traceProvider.getTracer.bind(traceProvider);
446
+ }
447
+ async flush() {
448
+ await this._traceProvider.forceFlush();
449
+ await this._logProvider.forceFlush();
450
+ }
451
+ async shutdown() {
452
+ await this._traceProvider.shutdown();
453
+ await this._logProvider.shutdown();
454
+ }
455
+ };
456
+ __name(_TracingSDK, "TracingSDK");
457
+ var TracingSDK = _TracingSDK;
458
+ function setLogLevel(level) {
459
+ let diagLogLevel;
460
+ switch (level) {
461
+ case "none":
462
+ diagLogLevel = api.DiagLogLevel.NONE;
463
+ break;
464
+ case "error":
465
+ diagLogLevel = api.DiagLogLevel.ERROR;
466
+ break;
467
+ case "warn":
468
+ diagLogLevel = api.DiagLogLevel.WARN;
469
+ break;
470
+ case "info":
471
+ diagLogLevel = api.DiagLogLevel.INFO;
472
+ break;
473
+ case "debug":
474
+ diagLogLevel = api.DiagLogLevel.DEBUG;
475
+ break;
476
+ case "verbose":
477
+ diagLogLevel = api.DiagLogLevel.VERBOSE;
478
+ break;
479
+ case "all":
480
+ diagLogLevel = api.DiagLogLevel.ALL;
481
+ break;
482
+ default:
483
+ diagLogLevel = api.DiagLogLevel.NONE;
484
+ }
485
+ api.diag.setLogger(new api.DiagConsoleLogger(), diagLogLevel);
486
+ }
487
+ __name(setLogLevel, "setLogLevel");
488
+
489
+ // src/v3/otel/index.ts
490
+ function recordSpanException(span, error) {
491
+ if (error instanceof Error) {
492
+ span.recordException(error);
493
+ } else if (typeof error === "string") {
494
+ span.recordException(new Error(error));
495
+ } else {
496
+ span.recordException(new Error(JSON.stringify(error)));
497
+ }
498
+ span.setStatus({
499
+ code: api.SpanStatusCode.ERROR
500
+ });
501
+ }
502
+ __name(recordSpanException, "recordSpanException");
503
+ var TaskRunBuiltInError = zod.z.object({
504
+ type: zod.z.literal("BUILT_IN_ERROR"),
505
+ name: zod.z.string(),
506
+ message: zod.z.string(),
507
+ stackTrace: zod.z.string()
508
+ });
509
+ var TaskRunCustomErrorObject = zod.z.object({
510
+ type: zod.z.literal("CUSTOM_ERROR"),
511
+ raw: zod.z.string()
512
+ });
513
+ var TaskRunStringError = zod.z.object({
514
+ type: zod.z.literal("STRING_ERROR"),
515
+ raw: zod.z.string()
516
+ });
517
+ var TaskRunErrorCodes = {
518
+ COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
519
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
520
+ CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
521
+ TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
522
+ TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
523
+ TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
524
+ TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
525
+ TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
526
+ TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
527
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
528
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
529
+ };
530
+ var TaskRunInternalError = zod.z.object({
531
+ type: zod.z.literal("INTERNAL_ERROR"),
532
+ code: zod.z.enum([
533
+ "COULD_NOT_FIND_EXECUTOR",
534
+ "COULD_NOT_FIND_TASK",
535
+ "CONFIGURED_INCORRECTLY",
536
+ "TASK_ALREADY_RUNNING",
537
+ "TASK_EXECUTION_FAILED",
538
+ "TASK_EXECUTION_ABORTED",
539
+ "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
540
+ "TASK_RUN_CANCELLED",
541
+ "TASK_OUTPUT_ERROR",
542
+ "HANDLE_ERROR_ERROR",
543
+ "GRACEFUL_EXIT_TIMEOUT"
544
+ ]),
545
+ message: zod.z.string().optional()
546
+ });
547
+ var TaskRunError = zod.z.discriminatedUnion("type", [
548
+ TaskRunBuiltInError,
549
+ TaskRunCustomErrorObject,
550
+ TaskRunStringError,
551
+ TaskRunInternalError
552
+ ]);
553
+ var TaskRun = zod.z.object({
554
+ id: zod.z.string(),
555
+ payload: zod.z.string(),
556
+ payloadType: zod.z.string(),
557
+ context: zod.z.any(),
558
+ tags: zod.z.array(zod.z.string()),
559
+ isTest: zod.z.boolean().default(false),
560
+ createdAt: zod.z.coerce.date(),
561
+ idempotencyKey: zod.z.string().optional()
562
+ });
563
+ var TaskRunExecutionTask = zod.z.object({
564
+ id: zod.z.string(),
565
+ filePath: zod.z.string(),
566
+ exportName: zod.z.string()
567
+ });
568
+ var TaskRunExecutionAttempt = zod.z.object({
569
+ id: zod.z.string(),
570
+ number: zod.z.number(),
571
+ startedAt: zod.z.coerce.date(),
572
+ backgroundWorkerId: zod.z.string(),
573
+ backgroundWorkerTaskId: zod.z.string(),
574
+ status: zod.z.string()
575
+ });
576
+ var TaskRunExecutionEnvironment = zod.z.object({
577
+ id: zod.z.string(),
578
+ slug: zod.z.string(),
579
+ type: zod.z.enum([
580
+ "PRODUCTION",
581
+ "STAGING",
582
+ "DEVELOPMENT",
583
+ "PREVIEW"
584
+ ])
585
+ });
586
+ var TaskRunExecutionOrganization = zod.z.object({
587
+ id: zod.z.string(),
588
+ slug: zod.z.string(),
589
+ name: zod.z.string()
590
+ });
591
+ var TaskRunExecutionProject = zod.z.object({
592
+ id: zod.z.string(),
593
+ ref: zod.z.string(),
594
+ slug: zod.z.string(),
595
+ name: zod.z.string()
596
+ });
597
+ var TaskRunExecutionQueue = zod.z.object({
598
+ id: zod.z.string(),
599
+ name: zod.z.string()
600
+ });
601
+ var TaskRunExecutionBatch = zod.z.object({
602
+ id: zod.z.string()
603
+ });
604
+ var TaskRunExecution = zod.z.object({
605
+ task: TaskRunExecutionTask,
606
+ attempt: TaskRunExecutionAttempt,
607
+ run: TaskRun,
608
+ queue: TaskRunExecutionQueue,
609
+ environment: TaskRunExecutionEnvironment,
610
+ organization: TaskRunExecutionOrganization,
611
+ project: TaskRunExecutionProject,
612
+ batch: TaskRunExecutionBatch.optional()
613
+ });
614
+ var TaskRunContext = zod.z.object({
615
+ task: TaskRunExecutionTask,
616
+ attempt: TaskRunExecutionAttempt.omit({
617
+ backgroundWorkerId: true,
618
+ backgroundWorkerTaskId: true
619
+ }),
620
+ run: TaskRun.omit({
621
+ payload: true,
622
+ payloadType: true
623
+ }),
624
+ queue: TaskRunExecutionQueue,
625
+ environment: TaskRunExecutionEnvironment,
626
+ organization: TaskRunExecutionOrganization,
627
+ project: TaskRunExecutionProject,
628
+ batch: TaskRunExecutionBatch.optional()
629
+ });
630
+ var TaskRunExecutionRetry = zod.z.object({
631
+ timestamp: zod.z.number(),
632
+ delay: zod.z.number(),
633
+ error: zod.z.unknown().optional()
634
+ });
635
+ var TaskRunFailedExecutionResult = zod.z.object({
636
+ ok: zod.z.literal(false),
637
+ id: zod.z.string(),
638
+ error: TaskRunError,
639
+ retry: TaskRunExecutionRetry.optional(),
640
+ skippedRetrying: zod.z.boolean().optional()
641
+ });
642
+ var TaskRunSuccessfulExecutionResult = zod.z.object({
643
+ ok: zod.z.literal(true),
644
+ id: zod.z.string(),
645
+ output: zod.z.string().optional(),
646
+ outputType: zod.z.string()
647
+ });
648
+ var TaskRunExecutionResult = zod.z.discriminatedUnion("ok", [
649
+ TaskRunSuccessfulExecutionResult,
650
+ TaskRunFailedExecutionResult
651
+ ]);
652
+ var BatchTaskRunExecutionResult = zod.z.object({
653
+ id: zod.z.string(),
654
+ items: TaskRunExecutionResult.array()
655
+ });
656
+
657
+ // src/v3/schemas/schemas.ts
658
+ zod.z.enum([
659
+ "PRODUCTION",
660
+ "STAGING",
661
+ "DEVELOPMENT",
662
+ "PREVIEW"
663
+ ]);
664
+ var MachineCpu = zod.z.union([
665
+ zod.z.literal(0.25),
666
+ zod.z.literal(0.5),
667
+ zod.z.literal(1),
668
+ zod.z.literal(2),
669
+ zod.z.literal(4)
670
+ ]).default(0.5);
671
+ var MachineMemory = zod.z.union([
672
+ zod.z.literal(0.25),
673
+ zod.z.literal(0.5),
674
+ zod.z.literal(1),
675
+ zod.z.literal(2),
676
+ zod.z.literal(4),
677
+ zod.z.literal(8)
678
+ ]).default(1);
679
+ var Machine = zod.z.object({
680
+ version: zod.z.literal("v1").default("v1"),
681
+ cpu: MachineCpu,
682
+ memory: MachineMemory
683
+ });
684
+ zod.z.object({
685
+ execution: TaskRunExecution,
686
+ traceContext: zod.z.record(zod.z.unknown()),
687
+ environment: zod.z.record(zod.z.string()).optional()
688
+ });
689
+ var ProdTaskRunExecution = TaskRunExecution.extend({
690
+ worker: zod.z.object({
691
+ id: zod.z.string(),
692
+ contentHash: zod.z.string(),
693
+ version: zod.z.string()
694
+ })
695
+ });
696
+ zod.z.object({
697
+ execution: ProdTaskRunExecution,
698
+ traceContext: zod.z.record(zod.z.unknown()),
699
+ environment: zod.z.record(zod.z.string()).optional()
700
+ });
701
+ var FixedWindowRateLimit = zod.z.object({
702
+ type: zod.z.literal("fixed-window"),
703
+ limit: zod.z.number(),
704
+ window: zod.z.union([
705
+ zod.z.object({
706
+ seconds: zod.z.number()
707
+ }),
708
+ zod.z.object({
709
+ minutes: zod.z.number()
710
+ }),
711
+ zod.z.object({
712
+ hours: zod.z.number()
713
+ })
714
+ ])
715
+ });
716
+ var SlidingWindowRateLimit = zod.z.object({
717
+ type: zod.z.literal("sliding-window"),
718
+ limit: zod.z.number(),
719
+ window: zod.z.union([
720
+ zod.z.object({
721
+ seconds: zod.z.number()
722
+ }),
723
+ zod.z.object({
724
+ minutes: zod.z.number()
725
+ }),
726
+ zod.z.object({
727
+ hours: zod.z.number()
728
+ })
729
+ ])
730
+ });
731
+ var RateLimitOptions = zod.z.discriminatedUnion("type", [
732
+ FixedWindowRateLimit,
733
+ SlidingWindowRateLimit
734
+ ]);
735
+ var RetryOptions = zod.z.object({
736
+ /** The number of attempts before giving up */
737
+ maxAttempts: zod.z.number().int().optional(),
738
+ /** The exponential factor to use when calculating the next retry time.
739
+ *
740
+ * Each subsequent retry will be calculated as `previousTimeout * factor`
741
+ */
742
+ factor: zod.z.number().optional(),
743
+ /** The minimum time to wait before retrying */
744
+ minTimeoutInMs: zod.z.number().int().optional(),
745
+ /** The maximum time to wait before retrying */
746
+ maxTimeoutInMs: zod.z.number().int().optional(),
747
+ /** Randomize the timeout between retries.
748
+ *
749
+ * This can be useful to prevent the thundering herd problem where all retries happen at the same time.
750
+ */
751
+ randomize: zod.z.boolean().optional()
752
+ });
753
+ var QueueOptions = zod.z.object({
754
+ /** You can define a shared queue and then pass the name in to your task.
755
+ *
756
+ * @example
757
+ *
758
+ * ```ts
759
+ * const myQueue = queue({
760
+ name: "my-queue",
761
+ concurrencyLimit: 1,
762
+ });
763
+
764
+ export const task1 = task({
765
+ id: "task-1",
766
+ queue: {
767
+ name: "my-queue",
768
+ },
769
+ run: async (payload: { message: string }) => {
770
+ // ...
771
+ },
772
+ });
773
+
774
+ export const task2 = task({
775
+ id: "task-2",
776
+ queue: {
777
+ name: "my-queue",
778
+ },
779
+ run: async (payload: { message: string }) => {
780
+ // ...
781
+ },
782
+ });
783
+ * ```
784
+ */
785
+ name: zod.z.string().optional(),
786
+ /** An optional property that specifies the maximum number of concurrent run executions.
787
+ *
788
+ * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
789
+ concurrencyLimit: zod.z.number().int().min(0).max(1e3).optional(),
790
+ /** @deprecated This feature is coming soon */
791
+ rateLimit: RateLimitOptions.optional()
792
+ });
793
+ var TaskMetadata = zod.z.object({
794
+ id: zod.z.string(),
795
+ packageVersion: zod.z.string(),
796
+ queue: QueueOptions.optional(),
797
+ retry: RetryOptions.optional(),
798
+ machine: Machine.partial().optional(),
799
+ triggerSource: zod.z.string().optional()
800
+ });
801
+ var TaskFileMetadata = zod.z.object({
802
+ filePath: zod.z.string(),
803
+ exportName: zod.z.string()
804
+ });
805
+ TaskMetadata.merge(TaskFileMetadata);
806
+ zod.z.enum([
807
+ "index",
808
+ "create",
809
+ "restore"
810
+ ]);
811
+ zod.z.enum([
812
+ "terminate"
813
+ ]);
814
+ var RegexSchema = zod.z.custom((val) => {
815
+ try {
816
+ return typeof val.test === "function";
817
+ } catch {
818
+ return false;
819
+ }
820
+ });
821
+ zod.z.object({
822
+ project: zod.z.string(),
823
+ triggerDirectories: zod.z.string().array().optional(),
824
+ triggerUrl: zod.z.string().optional(),
825
+ projectDir: zod.z.string().optional(),
826
+ tsconfigPath: zod.z.string().optional(),
827
+ retries: zod.z.object({
828
+ enabledInDev: zod.z.boolean().default(true),
829
+ default: RetryOptions.optional()
830
+ }).optional(),
831
+ additionalPackages: zod.z.string().array().optional(),
832
+ additionalFiles: zod.z.string().array().optional(),
833
+ dependenciesToBundle: zod.z.array(zod.z.union([
834
+ zod.z.string(),
835
+ RegexSchema
836
+ ])).optional(),
837
+ logLevel: zod.z.string().optional(),
838
+ enableConsoleLogging: zod.z.boolean().optional(),
839
+ postInstall: zod.z.string().optional()
840
+ });
841
+ zod.z.enum([
842
+ "WAIT_FOR_DURATION",
843
+ "WAIT_FOR_TASK",
844
+ "WAIT_FOR_BATCH"
845
+ ]);
846
+
847
+ // src/v3/schemas/resources.ts
848
+ var TaskResource = zod.z.object({
849
+ id: zod.z.string(),
850
+ filePath: zod.z.string(),
851
+ exportName: zod.z.string(),
852
+ queue: QueueOptions.optional(),
853
+ retry: RetryOptions.optional(),
854
+ machine: Machine.partial().optional(),
855
+ triggerSource: zod.z.string().optional()
856
+ });
857
+ var BackgroundWorkerMetadata = zod.z.object({
858
+ packageVersion: zod.z.string(),
859
+ contentHash: zod.z.string(),
860
+ cliPackageVersion: zod.z.string().optional(),
861
+ tasks: zod.z.array(TaskResource)
862
+ });
863
+ zod.z.object({
864
+ contentHash: zod.z.string(),
865
+ imageTag: zod.z.string()
866
+ });
867
+
868
+ // src/v3/schemas/api.ts
869
+ zod.z.object({
870
+ userId: zod.z.string(),
871
+ email: zod.z.string().email(),
872
+ dashboardUrl: zod.z.string()
873
+ });
874
+ var GetProjectResponseBody = zod.z.object({
875
+ id: zod.z.string(),
876
+ externalRef: zod.z.string(),
877
+ name: zod.z.string(),
878
+ slug: zod.z.string(),
879
+ createdAt: zod.z.coerce.date(),
880
+ organization: zod.z.object({
881
+ id: zod.z.string(),
882
+ title: zod.z.string(),
883
+ slug: zod.z.string(),
884
+ createdAt: zod.z.coerce.date()
885
+ })
886
+ });
887
+ zod.z.array(GetProjectResponseBody);
888
+ zod.z.object({
889
+ apiKey: zod.z.string(),
890
+ name: zod.z.string(),
891
+ apiUrl: zod.z.string()
892
+ });
893
+ zod.z.object({
894
+ localOnly: zod.z.boolean(),
895
+ metadata: BackgroundWorkerMetadata
896
+ });
897
+ zod.z.object({
898
+ id: zod.z.string(),
899
+ version: zod.z.string(),
900
+ contentHash: zod.z.string()
901
+ });
902
+ var TriggerTaskRequestBody = zod.z.object({
903
+ payload: zod.z.any(),
904
+ context: zod.z.any(),
905
+ options: zod.z.object({
906
+ dependentAttempt: zod.z.string().optional(),
907
+ dependentBatch: zod.z.string().optional(),
908
+ lockToVersion: zod.z.string().optional(),
909
+ queue: QueueOptions.optional(),
910
+ concurrencyKey: zod.z.string().optional(),
911
+ idempotencyKey: zod.z.string().optional(),
912
+ test: zod.z.boolean().optional(),
913
+ payloadType: zod.z.string().optional()
914
+ }).optional()
915
+ });
916
+ var TriggerTaskResponse = zod.z.object({
917
+ id: zod.z.string()
918
+ });
919
+ zod.z.object({
920
+ items: TriggerTaskRequestBody.array(),
921
+ dependentAttempt: zod.z.string().optional()
922
+ });
923
+ var BatchTriggerTaskResponse = zod.z.object({
924
+ batchId: zod.z.string(),
925
+ runs: zod.z.string().array()
926
+ });
927
+ zod.z.object({
928
+ id: zod.z.string(),
929
+ items: zod.z.array(zod.z.object({
930
+ id: zod.z.string(),
931
+ taskRunId: zod.z.string(),
932
+ status: zod.z.enum([
933
+ "PENDING",
934
+ "CANCELED",
935
+ "COMPLETED",
936
+ "FAILED"
937
+ ])
938
+ }))
939
+ });
940
+ zod.z.object({
941
+ variables: zod.z.record(zod.z.string())
942
+ });
943
+ zod.z.object({
944
+ imageReference: zod.z.string(),
945
+ selfHosted: zod.z.boolean().optional()
946
+ });
947
+ zod.z.object({
948
+ id: zod.z.string(),
949
+ contentHash: zod.z.string()
950
+ });
951
+ var ExternalBuildData = zod.z.object({
952
+ buildId: zod.z.string(),
953
+ buildToken: zod.z.string(),
954
+ projectId: zod.z.string()
955
+ });
956
+ zod.z.object({
957
+ id: zod.z.string(),
958
+ contentHash: zod.z.string(),
959
+ shortCode: zod.z.string(),
960
+ version: zod.z.string(),
961
+ imageTag: zod.z.string(),
962
+ externalBuildData: ExternalBuildData.optional().nullable(),
963
+ registryHost: zod.z.string().optional()
964
+ });
965
+ zod.z.object({
966
+ contentHash: zod.z.string(),
967
+ userId: zod.z.string().optional()
968
+ });
969
+ var DeploymentErrorData = zod.z.object({
970
+ name: zod.z.string(),
971
+ message: zod.z.string(),
972
+ stack: zod.z.string().optional()
973
+ });
974
+ zod.z.object({
975
+ id: zod.z.string(),
976
+ status: zod.z.enum([
977
+ "PENDING",
978
+ "BUILDING",
979
+ "DEPLOYING",
980
+ "DEPLOYED",
981
+ "FAILED",
982
+ "CANCELED",
983
+ "TIMED_OUT"
984
+ ]),
985
+ contentHash: zod.z.string(),
986
+ shortCode: zod.z.string(),
987
+ version: zod.z.string(),
988
+ imageReference: zod.z.string().optional(),
989
+ errorData: DeploymentErrorData.optional().nullable(),
990
+ worker: zod.z.object({
991
+ id: zod.z.string(),
992
+ version: zod.z.string(),
993
+ tasks: zod.z.array(zod.z.object({
994
+ id: zod.z.string(),
995
+ slug: zod.z.string(),
996
+ filePath: zod.z.string(),
997
+ exportName: zod.z.string()
998
+ }))
999
+ }).optional()
1000
+ });
1001
+ var CreateUploadPayloadUrlResponseBody = zod.z.object({
1002
+ presignedUrl: zod.z.string()
1003
+ });
1004
+ var ReplayRunResponse = zod.z.object({
1005
+ id: zod.z.string()
1006
+ });
1007
+ var CanceledRunResponse = zod.z.object({
1008
+ message: zod.z.string()
1009
+ });
1010
+ zod.z.object({
1011
+ /** The schedule id associated with this run (you can have many schedules for the same task).
1012
+ You can use this to remove the schedule, update it, etc */
1013
+ scheduleId: zod.z.string(),
1014
+ /** When the task was scheduled to run.
1015
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
1016
+ timestamp: zod.z.date(),
1017
+ /** When the task was last run (it has been).
1018
+ This can be undefined if it's never been run */
1019
+ lastTimestamp: zod.z.date().optional(),
1020
+ /** You can optionally provide an external id when creating the schedule.
1021
+ Usually you would use a userId or some other unique identifier.
1022
+ This defaults to undefined if you didn't provide one. */
1023
+ externalId: zod.z.string().optional(),
1024
+ /** The next 5 dates this task is scheduled to run */
1025
+ upcoming: zod.z.array(zod.z.date())
1026
+ });
1027
+ zod.z.object({
1028
+ /** The id of the task you want to attach to. */
1029
+ task: zod.z.string(),
1030
+ /** The schedule in CRON format.
1031
+ *
1032
+ * ```txt
1033
+ * * * * * *
1034
+ ┬ ┬ ┬ ┬ ┬
1035
+ │ │ │ │ |
1036
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
1037
+ │ │ │ └───── month (1 - 12)
1038
+ │ │ └────────── day of month (1 - 31, L)
1039
+ │ └─────────────── hour (0 - 23)
1040
+ └──────────────────── minute (0 - 59)
1041
+ * ```
1042
+
1043
+ "L" means the last. In the "day of week" field, 1L means the last Monday of the month. In the day of month field, L means the last day of the month.
1044
+
1045
+ */
1046
+ cron: zod.z.string(),
1047
+ /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1048
+ *
1049
+ * This is useful if you don't want to create duplicate schedules for a user. */
1050
+ deduplicationKey: zod.z.string().optional(),
1051
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
1052
+ *
1053
+ * This allows you to have per-user CRON tasks.
1054
+ */
1055
+ externalId: zod.z.string().optional()
1056
+ });
1057
+ var ScheduleObject = zod.z.object({
1058
+ id: zod.z.string(),
1059
+ task: zod.z.string(),
1060
+ active: zod.z.boolean(),
1061
+ deduplicationKey: zod.z.string().nullish(),
1062
+ externalId: zod.z.string().nullish(),
1063
+ generator: zod.z.object({
1064
+ type: zod.z.literal("CRON"),
1065
+ expression: zod.z.string(),
1066
+ description: zod.z.string()
1067
+ }),
1068
+ nextRun: zod.z.coerce.date().nullish(),
1069
+ environments: zod.z.array(zod.z.object({
1070
+ id: zod.z.string(),
1071
+ type: zod.z.string(),
1072
+ userName: zod.z.string().nullish()
1073
+ }))
1074
+ });
1075
+ var DeletedScheduleObject = zod.z.object({
1076
+ id: zod.z.string()
1077
+ });
1078
+ var ListSchedulesResult = zod.z.object({
1079
+ data: zod.z.array(ScheduleObject),
1080
+ pagination: zod.z.object({
1081
+ currentPage: zod.z.number(),
1082
+ totalPages: zod.z.number(),
1083
+ count: zod.z.number()
1084
+ })
1085
+ });
1086
+ zod.z.object({
1087
+ page: zod.z.number().optional(),
1088
+ perPage: zod.z.number().optional()
1089
+ });
1090
+ var RunStatus = zod.z.enum([
1091
+ "PENDING",
1092
+ "EXECUTING",
1093
+ "PAUSED",
1094
+ "COMPLETED",
1095
+ "FAILED",
1096
+ "CANCELED"
1097
+ ]);
1098
+ var AttemptStatus = zod.z.enum([
1099
+ "PENDING",
1100
+ "EXECUTING",
1101
+ "PAUSED",
1102
+ "COMPLETED",
1103
+ "FAILED",
1104
+ "CANCELED"
1105
+ ]);
1106
+ var RetrieveRunResponse = zod.z.object({
1107
+ id: zod.z.string(),
1108
+ status: RunStatus,
1109
+ taskIdentifier: zod.z.string(),
1110
+ idempotencyKey: zod.z.string().optional(),
1111
+ version: zod.z.string().optional(),
1112
+ createdAt: zod.z.coerce.date(),
1113
+ updatedAt: zod.z.coerce.date(),
1114
+ attempts: zod.z.array(zod.z.object({
1115
+ id: zod.z.string(),
1116
+ status: AttemptStatus,
1117
+ createdAt: zod.z.coerce.date(),
1118
+ updatedAt: zod.z.coerce.date(),
1119
+ startedAt: zod.z.coerce.date().optional(),
1120
+ completedAt: zod.z.coerce.date().optional()
1121
+ }).optional())
1122
+ });
1123
+
1124
+ // src/v3/apiErrors.ts
1125
+ var _APIError = class _APIError extends Error {
1126
+ constructor(status, error, message, headers) {
1127
+ super(`${_APIError.makeMessage(status, error, message)}`);
1128
+ this.status = status;
1129
+ this.headers = headers;
1130
+ const data = error;
1131
+ this.error = data;
1132
+ this.code = data?.["code"];
1133
+ this.param = data?.["param"];
1134
+ this.type = data?.["type"];
1135
+ }
1136
+ static makeMessage(status, error, message) {
1137
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1138
+ if (status && msg) {
1139
+ return `${status} ${msg}`;
1140
+ }
1141
+ if (status) {
1142
+ return `${status} status code (no body)`;
1143
+ }
1144
+ if (msg) {
1145
+ return msg;
1146
+ }
1147
+ return "(no status code or body)";
1148
+ }
1149
+ static generate(status, errorResponse, message, headers) {
1150
+ if (!status) {
1151
+ return new APIConnectionError({
1152
+ cause: castToError(errorResponse)
1153
+ });
1154
+ }
1155
+ const error = errorResponse?.["error"];
1156
+ if (status === 400) {
1157
+ return new BadRequestError(status, error, message, headers);
1158
+ }
1159
+ if (status === 401) {
1160
+ return new AuthenticationError(status, error, message, headers);
1161
+ }
1162
+ if (status === 403) {
1163
+ return new PermissionDeniedError(status, error, message, headers);
1164
+ }
1165
+ if (status === 404) {
1166
+ return new NotFoundError(status, error, message, headers);
1167
+ }
1168
+ if (status === 409) {
1169
+ return new ConflictError(status, error, message, headers);
1170
+ }
1171
+ if (status === 422) {
1172
+ return new UnprocessableEntityError(status, error, message, headers);
1173
+ }
1174
+ if (status === 429) {
1175
+ return new RateLimitError(status, error, message, headers);
1176
+ }
1177
+ if (status >= 500) {
1178
+ return new InternalServerError(status, error, message, headers);
1179
+ }
1180
+ return new _APIError(status, error, message, headers);
1181
+ }
1182
+ };
1183
+ __name(_APIError, "APIError");
1184
+ var APIError = _APIError;
1185
+ var _APIConnectionError = class _APIConnectionError extends APIError {
1186
+ constructor({ message, cause }) {
1187
+ super(void 0, void 0, message || "Connection error.", void 0);
1188
+ __publicField(this, "status");
1189
+ if (cause)
1190
+ this.cause = cause;
1191
+ }
1192
+ };
1193
+ __name(_APIConnectionError, "APIConnectionError");
1194
+ var APIConnectionError = _APIConnectionError;
1195
+ var _BadRequestError = class _BadRequestError extends APIError {
1196
+ constructor() {
1197
+ super(...arguments);
1198
+ __publicField(this, "status", 400);
1199
+ }
1200
+ };
1201
+ __name(_BadRequestError, "BadRequestError");
1202
+ var BadRequestError = _BadRequestError;
1203
+ var _AuthenticationError = class _AuthenticationError extends APIError {
1204
+ constructor() {
1205
+ super(...arguments);
1206
+ __publicField(this, "status", 401);
1207
+ }
1208
+ };
1209
+ __name(_AuthenticationError, "AuthenticationError");
1210
+ var AuthenticationError = _AuthenticationError;
1211
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1212
+ constructor() {
1213
+ super(...arguments);
1214
+ __publicField(this, "status", 403);
1215
+ }
1216
+ };
1217
+ __name(_PermissionDeniedError, "PermissionDeniedError");
1218
+ var PermissionDeniedError = _PermissionDeniedError;
1219
+ var _NotFoundError = class _NotFoundError extends APIError {
1220
+ constructor() {
1221
+ super(...arguments);
1222
+ __publicField(this, "status", 404);
1223
+ }
1224
+ };
1225
+ __name(_NotFoundError, "NotFoundError");
1226
+ var NotFoundError = _NotFoundError;
1227
+ var _ConflictError = class _ConflictError extends APIError {
1228
+ constructor() {
1229
+ super(...arguments);
1230
+ __publicField(this, "status", 409);
1231
+ }
1232
+ };
1233
+ __name(_ConflictError, "ConflictError");
1234
+ var ConflictError = _ConflictError;
1235
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1236
+ constructor() {
1237
+ super(...arguments);
1238
+ __publicField(this, "status", 422);
1239
+ }
1240
+ };
1241
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
1242
+ var UnprocessableEntityError = _UnprocessableEntityError;
1243
+ var _RateLimitError = class _RateLimitError extends APIError {
1244
+ constructor() {
1245
+ super(...arguments);
1246
+ __publicField(this, "status", 429);
1247
+ }
1248
+ };
1249
+ __name(_RateLimitError, "RateLimitError");
1250
+ var RateLimitError = _RateLimitError;
1251
+ var _InternalServerError = class _InternalServerError extends APIError {
1252
+ };
1253
+ __name(_InternalServerError, "InternalServerError");
1254
+ var InternalServerError = _InternalServerError;
1255
+ function castToError(err) {
1256
+ if (err instanceof Error)
1257
+ return err;
1258
+ return new Error(err);
1259
+ }
1260
+ __name(castToError, "castToError");
1261
+
1262
+ // src/v3/utils/retries.ts
1263
+ var defaultRetryOptions = {
1264
+ maxAttempts: 3,
1265
+ factor: 2,
1266
+ minTimeoutInMs: 1e3,
1267
+ maxTimeoutInMs: 6e4,
1268
+ randomize: true
1269
+ };
1270
+ function calculateNextRetryDelay(options, attempt) {
1271
+ const opts = {
1272
+ ...defaultRetryOptions,
1273
+ ...options
1274
+ };
1275
+ if (attempt >= opts.maxAttempts) {
1276
+ return;
1277
+ }
1278
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1279
+ const random = randomize ? Math.random() + 1 : 1;
1280
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1281
+ return Math.round(timeout);
1282
+ }
1283
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1284
+
1285
+ // src/v3/zodfetch.ts
1286
+ var defaultRetryOptions2 = {
1287
+ maxAttempts: 3,
1288
+ factor: 2,
1289
+ minTimeoutInMs: 1e3,
1290
+ maxTimeoutInMs: 6e4,
1291
+ randomize: false
1292
+ };
1293
+ async function zodfetch(schema, url, requestInit, options) {
1294
+ return await _doZodFetch(schema, url, requestInit, options);
1295
+ }
1296
+ __name(zodfetch, "zodfetch");
1297
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1298
+ try {
1299
+ const response = await fetch(url, requestInitWithCache(requestInit));
1300
+ const responseHeaders = createResponseHeaders(response.headers);
1301
+ if (!response.ok) {
1302
+ const retryResult = shouldRetry(response, attempt, options?.retry);
1303
+ if (retryResult.retry) {
1304
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1305
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1306
+ } else {
1307
+ const errText = await response.text().catch((e) => castToError2(e).message);
1308
+ const errJSON = safeJsonParse(errText);
1309
+ const errMessage = errJSON ? void 0 : errText;
1310
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
1311
+ }
1312
+ }
1313
+ const jsonBody = await response.json();
1314
+ const parsedResult = schema.safeParse(jsonBody);
1315
+ if (parsedResult.success) {
1316
+ return parsedResult.data;
1317
+ }
1318
+ throw zodValidationError.fromZodError(parsedResult.error);
1319
+ } catch (error) {
1320
+ if (error instanceof APIError) {
1321
+ throw error;
1322
+ }
1323
+ if (options?.retry) {
1324
+ const retry = {
1325
+ ...defaultRetryOptions2,
1326
+ ...options.retry
1327
+ };
1328
+ const delay = calculateNextRetryDelay(retry, attempt);
1329
+ if (delay) {
1330
+ await new Promise((resolve) => setTimeout(resolve, delay));
1331
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1332
+ }
1333
+ }
1334
+ throw new APIConnectionError({
1335
+ cause: castToError2(error)
1336
+ });
1337
+ }
1338
+ }
1339
+ __name(_doZodFetch, "_doZodFetch");
1340
+ function castToError2(err) {
1341
+ if (err instanceof Error)
1342
+ return err;
1343
+ return new Error(err);
1344
+ }
1345
+ __name(castToError2, "castToError");
1346
+ function shouldRetry(response, attempt, retryOptions) {
1347
+ function shouldRetryForOptions() {
1348
+ const retry = {
1349
+ ...defaultRetryOptions2,
1350
+ ...retryOptions
1351
+ };
1352
+ const delay = calculateNextRetryDelay(retry, attempt);
1353
+ if (delay) {
1354
+ return {
1355
+ retry: true,
1356
+ delay
1357
+ };
1358
+ } else {
1359
+ return {
1360
+ retry: false
1361
+ };
1362
+ }
1363
+ }
1364
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
1365
+ const shouldRetryHeader = response.headers.get("x-should-retry");
1366
+ if (shouldRetryHeader === "true")
1367
+ return shouldRetryForOptions();
1368
+ if (shouldRetryHeader === "false")
1369
+ return {
1370
+ retry: false
1371
+ };
1372
+ if (response.status === 408)
1373
+ return shouldRetryForOptions();
1374
+ if (response.status === 409)
1375
+ return shouldRetryForOptions();
1376
+ if (response.status === 429)
1377
+ return shouldRetryForOptions();
1378
+ if (response.status >= 500)
1379
+ return shouldRetryForOptions();
1380
+ return {
1381
+ retry: false
1382
+ };
1383
+ }
1384
+ __name(shouldRetry, "shouldRetry");
1385
+ function safeJsonParse(text) {
1386
+ try {
1387
+ return JSON.parse(text);
1388
+ } catch (e) {
1389
+ return void 0;
1390
+ }
1391
+ }
1392
+ __name(safeJsonParse, "safeJsonParse");
1393
+ function createResponseHeaders(headers) {
1394
+ return new Proxy(Object.fromEntries(
1395
+ // @ts-ignore
1396
+ headers.entries()
1397
+ ), {
1398
+ get(target, name) {
1399
+ const key = name.toString();
1400
+ return target[key.toLowerCase()] || target[key];
1401
+ }
1402
+ });
1403
+ }
1404
+ __name(createResponseHeaders, "createResponseHeaders");
1405
+ function requestInitWithCache(requestInit) {
1406
+ try {
1407
+ const withCache = {
1408
+ ...requestInit,
1409
+ cache: "no-cache"
1410
+ };
1411
+ const _ = new Request("http://localhost", withCache);
1412
+ return withCache;
1413
+ } catch (error) {
1414
+ return requestInit ?? {};
1415
+ }
1416
+ }
1417
+ __name(requestInitWithCache, "requestInitWithCache");
1418
+
1419
+ // src/v3/apiClient/index.ts
1420
+ var zodFetchOptions = {
1421
+ retry: {
1422
+ maxAttempts: 3,
1423
+ minTimeoutInMs: 1e3,
1424
+ maxTimeoutInMs: 3e4,
1425
+ factor: 2,
1426
+ randomize: false
1427
+ }
1428
+ };
1429
+ var _getHeaders, getHeaders_fn;
1430
+ var _ApiClient = class _ApiClient {
1431
+ constructor(baseUrl, accessToken) {
1432
+ __privateAdd(this, _getHeaders);
1433
+ this.accessToken = accessToken;
1434
+ this.baseUrl = baseUrl.replace(/\/$/, "");
1435
+ }
1436
+ async getRunResult(runId) {
1437
+ try {
1438
+ return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
1439
+ method: "GET",
1440
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1441
+ }, zodFetchOptions);
1442
+ } catch (error) {
1443
+ if (error instanceof APIError) {
1444
+ if (error.status === 404) {
1445
+ return void 0;
1446
+ }
1447
+ }
1448
+ throw error;
1449
+ }
1450
+ }
1451
+ async getBatchResults(batchId) {
1452
+ return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
1453
+ method: "GET",
1454
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1455
+ }, zodFetchOptions);
1456
+ }
1457
+ triggerTask(taskId, body, options) {
1458
+ return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
1459
+ method: "POST",
1460
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1461
+ body: JSON.stringify(body)
1462
+ }, zodFetchOptions);
1463
+ }
1464
+ batchTriggerTask(taskId, body, options) {
1465
+ return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
1466
+ method: "POST",
1467
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1468
+ body: JSON.stringify(body)
1469
+ }, zodFetchOptions);
1470
+ }
1471
+ createUploadPayloadUrl(filename) {
1472
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1473
+ method: "PUT",
1474
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1475
+ }, zodFetchOptions);
1476
+ }
1477
+ getPayloadUrl(filename) {
1478
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1479
+ method: "GET",
1480
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1481
+ }, zodFetchOptions);
1482
+ }
1483
+ retrieveRun(runId) {
1484
+ return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v3/runs/${runId}`, {
1485
+ method: "GET",
1486
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1487
+ }, zodFetchOptions);
1488
+ }
1489
+ replayRun(runId) {
1490
+ return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
1491
+ method: "POST",
1492
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1493
+ }, zodFetchOptions);
1494
+ }
1495
+ cancelRun(runId) {
1496
+ return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
1497
+ method: "POST",
1498
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1499
+ }, zodFetchOptions);
1500
+ }
1501
+ createSchedule(options) {
1502
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
1503
+ method: "POST",
1504
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1505
+ body: JSON.stringify(options)
1506
+ });
1507
+ }
1508
+ listSchedules(options) {
1509
+ const searchParams = new URLSearchParams();
1510
+ if (options?.page) {
1511
+ searchParams.append("page", options.page.toString());
1512
+ }
1513
+ if (options?.perPage) {
1514
+ searchParams.append("perPage", options.perPage.toString());
1515
+ }
1516
+ return zodfetch(ListSchedulesResult, `${this.baseUrl}/api/v1/schedules${searchParams.size > 0 ? `?${searchParams}` : ""}`, {
1517
+ method: "GET",
1518
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1519
+ });
1520
+ }
1521
+ retrieveSchedule(scheduleId) {
1522
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
1523
+ method: "GET",
1524
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1525
+ });
1526
+ }
1527
+ updateSchedule(scheduleId, options) {
1528
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
1529
+ method: "PUT",
1530
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1531
+ body: JSON.stringify(options)
1532
+ });
1533
+ }
1534
+ deactivateSchedule(scheduleId) {
1535
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
1536
+ method: "POST",
1537
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1538
+ });
1539
+ }
1540
+ activateSchedule(scheduleId) {
1541
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
1542
+ method: "POST",
1543
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1544
+ });
1545
+ }
1546
+ deleteSchedule(scheduleId) {
1547
+ return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
1548
+ method: "DELETE",
1549
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1550
+ });
1551
+ }
1552
+ };
1553
+ _getHeaders = new WeakSet();
1554
+ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
1555
+ const headers = {
1556
+ "Content-Type": "application/json",
1557
+ Authorization: `Bearer ${this.accessToken}`
1558
+ };
1559
+ if (taskContext.isInsideTask) {
1560
+ api.propagation.inject(api.context.active(), headers);
1561
+ if (spanParentAsLink) {
1562
+ headers["x-trigger-span-parent-as-link"] = "1";
1563
+ }
1564
+ }
1565
+ return headers;
1566
+ }, "#getHeaders");
1567
+ __name(_ApiClient, "ApiClient");
1568
+ var ApiClient = _ApiClient;
1569
+
1570
+ // src/v3/apiClientManager/index.ts
1571
+ var API_NAME2 = "api-client";
1572
+ var _getConfig, getConfig_fn;
1573
+ var _APIClientManagerAPI = class _APIClientManagerAPI {
1574
+ constructor() {
1575
+ __privateAdd(this, _getConfig);
1576
+ }
1577
+ static getInstance() {
1578
+ if (!this._instance) {
1579
+ this._instance = new _APIClientManagerAPI();
1580
+ }
1581
+ return this._instance;
1582
+ }
1583
+ disable() {
1584
+ unregisterGlobal(API_NAME2);
1585
+ }
1586
+ setGlobalAPIClientConfiguration(config) {
1587
+ return registerGlobal(API_NAME2, config);
1588
+ }
1589
+ get baseURL() {
1590
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
1591
+ return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
1592
+ }
1593
+ get accessToken() {
1594
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
1595
+ return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY");
1596
+ }
1597
+ get client() {
1598
+ if (!this.baseURL || !this.accessToken) {
1599
+ return void 0;
1600
+ }
1601
+ return new ApiClient(this.baseURL, this.accessToken);
1602
+ }
1603
+ };
1604
+ _getConfig = new WeakSet();
1605
+ getConfig_fn = /* @__PURE__ */ __name(function() {
1606
+ return getGlobal(API_NAME2);
1607
+ }, "#getConfig");
1608
+ __name(_APIClientManagerAPI, "APIClientManagerAPI");
1609
+ var APIClientManagerAPI = _APIClientManagerAPI;
1610
+
1611
+ // src/v3/apiClientManager-api.ts
1612
+ var apiClientManager = APIClientManagerAPI.getInstance();
1613
+
1614
+ // src/v3/utils/ioSerialization.ts
1615
+ async function parsePacket(value) {
1616
+ if (!value.data) {
1617
+ return void 0;
1618
+ }
1619
+ switch (value.dataType) {
1620
+ case "application/json":
1621
+ return JSON.parse(value.data);
1622
+ case "application/super+json":
1623
+ const { parse } = await loadSuperJSON();
1624
+ return parse(value.data);
1625
+ case "text/plain":
1626
+ return value.data;
1627
+ case "application/store":
1628
+ throw new Error(`Cannot parse an application/store packet (${value.data}). Needs to be imported first.`);
1629
+ default:
1630
+ return value.data;
1631
+ }
1632
+ }
1633
+ __name(parsePacket, "parsePacket");
1634
+ async function stringifyIO(value) {
1635
+ if (value === void 0) {
1636
+ return {
1637
+ dataType: "application/json"
1638
+ };
1639
+ }
1640
+ if (typeof value === "string") {
1641
+ return {
1642
+ data: value,
1643
+ dataType: "text/plain"
1644
+ };
1645
+ }
1646
+ try {
1647
+ const { stringify } = await loadSuperJSON();
1648
+ const data = stringify(value);
1649
+ return {
1650
+ data,
1651
+ dataType: "application/super+json"
1652
+ };
1653
+ } catch {
1654
+ return {
1655
+ data: value,
1656
+ dataType: "application/json"
1657
+ };
1658
+ }
1659
+ }
1660
+ __name(stringifyIO, "stringifyIO");
1661
+ async function conditionallyExportPacket(packet, pathPrefix, tracer) {
1662
+ if (apiClientManager.client) {
1663
+ const { needsOffloading, size } = packetRequiresOffloading(packet);
1664
+ if (needsOffloading) {
1665
+ if (!tracer) {
1666
+ return await exportPacket(packet, pathPrefix);
1667
+ } else {
1668
+ const result = await tracer.startActiveSpan("store.uploadOutput", async (span) => {
1669
+ return await exportPacket(packet, pathPrefix);
1670
+ }, {
1671
+ attributes: {
1672
+ byteLength: size,
1673
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-upload"
1674
+ }
1675
+ });
1676
+ return result ?? packet;
1677
+ }
1678
+ }
1679
+ }
1680
+ return packet;
1681
+ }
1682
+ __name(conditionallyExportPacket, "conditionallyExportPacket");
1683
+ function packetRequiresOffloading(packet) {
1684
+ if (!packet.data) {
1685
+ return {
1686
+ needsOffloading: false,
1687
+ size: 0
1688
+ };
1689
+ }
1690
+ const byteSize = Buffer.byteLength(packet.data, "utf8");
1691
+ return {
1692
+ needsOffloading: byteSize >= OFFLOAD_IO_PACKET_LENGTH_LIMIT,
1693
+ size: byteSize
1694
+ };
1695
+ }
1696
+ __name(packetRequiresOffloading, "packetRequiresOffloading");
1697
+ async function exportPacket(packet, pathPrefix) {
1698
+ const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
1699
+ const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
1700
+ const uploadResponse = await fetch(presignedResponse.presignedUrl, {
1701
+ method: "PUT",
1702
+ headers: {
1703
+ "Content-Type": packet.dataType
1704
+ },
1705
+ body: packet.data
1706
+ });
1707
+ if (!uploadResponse.ok) {
1708
+ throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
1709
+ }
1710
+ return {
1711
+ data: filename,
1712
+ dataType: "application/store"
1713
+ };
1714
+ }
1715
+ __name(exportPacket, "exportPacket");
1716
+ async function conditionallyImportPacket(packet, tracer) {
1717
+ if (packet.dataType !== "application/store") {
1718
+ return packet;
1719
+ }
1720
+ if (!tracer) {
1721
+ return await importPacket(packet);
1722
+ } else {
1723
+ const result = await tracer.startActiveSpan("store.downloadPayload", async (span) => {
1724
+ return await importPacket(packet, span);
1725
+ }, {
1726
+ attributes: {
1727
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
1728
+ }
1729
+ });
1730
+ return result ?? packet;
1731
+ }
1732
+ }
1733
+ __name(conditionallyImportPacket, "conditionallyImportPacket");
1734
+ async function importPacket(packet, span) {
1735
+ if (!packet.data) {
1736
+ return packet;
1737
+ }
1738
+ if (!apiClientManager.client) {
1739
+ return packet;
1740
+ }
1741
+ const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
1742
+ const response = await fetch(presignedResponse.presignedUrl);
1743
+ if (!response.ok) {
1744
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
1745
+ }
1746
+ const data = await response.text();
1747
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
1748
+ return {
1749
+ data,
1750
+ dataType: response.headers.get("content-type") ?? "application/json"
1751
+ };
1752
+ }
1753
+ __name(importPacket, "importPacket");
1754
+ async function createPacketAttributes(packet, dataKey, dataTypeKey) {
1755
+ if (!packet.data) {
1756
+ return;
1757
+ }
1758
+ switch (packet.dataType) {
1759
+ case "application/json":
1760
+ return {
1761
+ ...flattenAttributes(packet, dataKey),
1762
+ [dataTypeKey]: packet.dataType
1763
+ };
1764
+ case "application/super+json":
1765
+ const { parse } = await loadSuperJSON();
1766
+ if (typeof packet.data === "undefined" || packet.data === null) {
1767
+ return;
1768
+ }
1769
+ try {
1770
+ const parsed = parse(packet.data);
1771
+ const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
1772
+ const result = {
1773
+ ...flattenAttributes(jsonified, dataKey),
1774
+ [dataTypeKey]: "application/json"
1775
+ };
1776
+ return result;
1777
+ } catch (e) {
1778
+ return;
1779
+ }
1780
+ case "application/store":
1781
+ return {
1782
+ [dataKey]: packet.data,
1783
+ [dataTypeKey]: packet.dataType
1784
+ };
1785
+ case "text/plain":
1786
+ return {
1787
+ [dataKey]: packet.data,
1788
+ [dataTypeKey]: packet.dataType
1789
+ };
1790
+ default:
1791
+ return;
1792
+ }
1793
+ }
1794
+ __name(createPacketAttributes, "createPacketAttributes");
1795
+ function safeReplacer(key, value) {
1796
+ if (typeof value === "bigint") {
1797
+ return value.toString();
1798
+ }
1799
+ if (value instanceof RegExp) {
1800
+ return value.toString();
1801
+ }
1802
+ if (value instanceof Set) {
1803
+ return Array.from(value);
1804
+ }
1805
+ if (value instanceof Map) {
1806
+ const obj = {};
1807
+ value.forEach((v, k) => {
1808
+ obj[k] = v;
1809
+ });
1810
+ return obj;
1811
+ }
1812
+ return value;
1813
+ }
1814
+ __name(safeReplacer, "safeReplacer");
1815
+ function getPacketExtension(outputType) {
1816
+ switch (outputType) {
1817
+ case "application/json":
1818
+ return "json";
1819
+ case "application/super+json":
1820
+ return "json";
1821
+ case "text/plain":
1822
+ return "txt";
1823
+ default:
1824
+ return "txt";
1825
+ }
1826
+ }
1827
+ __name(getPacketExtension, "getPacketExtension");
1828
+ async function loadSuperJSON() {
1829
+ return await import('superjson');
1830
+ }
1831
+ __name(loadSuperJSON, "loadSuperJSON");
1832
+
1833
+ // src/v3/utils/styleAttributes.ts
1834
+ function accessoryAttributes(accessory) {
1835
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
1836
+ }
1837
+ __name(accessoryAttributes, "accessoryAttributes");
1838
+
1839
+ // src/v3/workers/taskExecutor.ts
1840
+ var _callRun, callRun_fn, _callInitFunctions, callInitFunctions_fn, _callConfigInit, callConfigInit_fn, _callOnSuccessFunctions, callOnSuccessFunctions_fn, _callOnSuccessFunction, callOnSuccessFunction_fn, _callOnFailureFunctions, callOnFailureFunctions_fn, _callOnFailureFunction, callOnFailureFunction_fn, _callOnStartFunctions, callOnStartFunctions_fn, _callOnStartFunction, callOnStartFunction_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
1841
+ var _TaskExecutor = class _TaskExecutor {
1842
+ constructor(task, options) {
1843
+ __privateAdd(this, _callRun);
1844
+ __privateAdd(this, _callInitFunctions);
1845
+ __privateAdd(this, _callConfigInit);
1846
+ __privateAdd(this, _callOnSuccessFunctions);
1847
+ __privateAdd(this, _callOnSuccessFunction);
1848
+ __privateAdd(this, _callOnFailureFunctions);
1849
+ __privateAdd(this, _callOnFailureFunction);
1850
+ __privateAdd(this, _callOnStartFunctions);
1851
+ __privateAdd(this, _callOnStartFunction);
1852
+ __privateAdd(this, _callTaskCleanup);
1853
+ __privateAdd(this, _handleError);
1854
+ this.task = task;
1855
+ this._tracingSDK = options.tracingSDK;
1856
+ this._tracer = options.tracer;
1857
+ this._consoleInterceptor = options.consoleInterceptor;
1858
+ this._config = options.projectConfig;
1859
+ this._importedConfig = options.importedConfig;
1860
+ this._handleErrorFn = options.handleErrorFn;
1861
+ }
1862
+ async execute(execution, worker, traceContext) {
1863
+ const ctx = TaskRunContext.parse(execution);
1864
+ const attemptMessage = `Attempt ${execution.attempt.number}`;
1865
+ const originalPacket = {
1866
+ data: execution.run.payload,
1867
+ dataType: execution.run.payloadType
1868
+ };
1869
+ taskContext.setGlobalTaskContext({
1870
+ ctx,
1871
+ worker
1872
+ });
1873
+ this._tracingSDK.asyncResourceDetector.resolveWithAttributes({
1874
+ ...taskContext.attributes,
1875
+ [SemanticInternalAttributes.SDK_VERSION]: this.task.packageVersion,
1876
+ [SemanticInternalAttributes.SDK_LANGUAGE]: "typescript"
1877
+ });
1878
+ const result = await this._tracer.startActiveSpan(attemptMessage, async (span) => {
1879
+ return await this._consoleInterceptor.intercept(console, async () => {
1880
+ let parsedPayload;
1881
+ let initOutput;
1882
+ try {
1883
+ const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
1884
+ parsedPayload = await parsePacket(payloadPacket);
1885
+ if (execution.attempt.number === 1) {
1886
+ await __privateMethod(this, _callOnStartFunctions, callOnStartFunctions_fn).call(this, parsedPayload, ctx);
1887
+ }
1888
+ initOutput = await __privateMethod(this, _callInitFunctions, callInitFunctions_fn).call(this, parsedPayload, ctx);
1889
+ const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
1890
+ await __privateMethod(this, _callOnSuccessFunctions, callOnSuccessFunctions_fn).call(this, parsedPayload, output, ctx, initOutput);
1891
+ try {
1892
+ const stringifiedOutput = await stringifyIO(output);
1893
+ const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
1894
+ const attributes = await createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE);
1895
+ if (attributes) {
1896
+ span.setAttributes(attributes);
1897
+ }
1898
+ return {
1899
+ ok: true,
1900
+ id: execution.run.id,
1901
+ output: finalOutput.data,
1902
+ outputType: finalOutput.dataType
1903
+ };
1904
+ } catch (stringifyError) {
1905
+ recordSpanException(span, stringifyError);
1906
+ return {
1907
+ ok: false,
1908
+ id: execution.run.id,
1909
+ error: {
1910
+ type: "INTERNAL_ERROR",
1911
+ code: TaskRunErrorCodes.TASK_OUTPUT_ERROR,
1912
+ message: stringifyError instanceof Error ? stringifyError.message : typeof stringifyError === "string" ? stringifyError : void 0
1913
+ }
1914
+ };
1915
+ }
1916
+ } catch (runError) {
1917
+ try {
1918
+ const handleErrorResult = await __privateMethod(this, _handleError, handleError_fn).call(this, execution, runError, parsedPayload, ctx);
1919
+ recordSpanException(span, handleErrorResult.error ?? runError);
1920
+ if (handleErrorResult.status !== "retry") {
1921
+ await __privateMethod(this, _callOnFailureFunctions, callOnFailureFunctions_fn).call(this, parsedPayload, handleErrorResult.error ?? runError, ctx, initOutput);
1922
+ }
1923
+ return {
1924
+ id: execution.run.id,
1925
+ ok: false,
1926
+ error: handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError),
1927
+ retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
1928
+ skippedRetrying: handleErrorResult.status === "skipped"
1929
+ };
1930
+ } catch (handleErrorError) {
1931
+ recordSpanException(span, handleErrorError);
1932
+ return {
1933
+ ok: false,
1934
+ id: execution.run.id,
1935
+ error: {
1936
+ type: "INTERNAL_ERROR",
1937
+ code: TaskRunErrorCodes.HANDLE_ERROR_ERROR,
1938
+ message: handleErrorError instanceof Error ? handleErrorError.message : typeof handleErrorError === "string" ? handleErrorError : void 0
1939
+ }
1940
+ };
1941
+ }
1942
+ } finally {
1943
+ await __privateMethod(this, _callTaskCleanup, callTaskCleanup_fn).call(this, parsedPayload, ctx, initOutput);
1944
+ }
1945
+ });
1946
+ }, {
1947
+ kind: api.SpanKind.CONSUMER,
1948
+ attributes: {
1949
+ [SemanticInternalAttributes.STYLE_ICON]: "attempt",
1950
+ ...accessoryAttributes({
1951
+ items: [
1952
+ {
1953
+ text: ctx.task.filePath
1954
+ },
1955
+ {
1956
+ text: `${ctx.task.exportName}.run()`
1957
+ }
1958
+ ],
1959
+ style: "codepath"
1960
+ })
1961
+ }
1962
+ }, this._tracer.extractContext(traceContext));
1963
+ return result;
1964
+ }
1965
+ };
1966
+ _callRun = new WeakSet();
1967
+ callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
1968
+ const runFn = this.task.fns.run;
1969
+ const middlewareFn = this.task.fns.middleware;
1970
+ if (!runFn) {
1971
+ throw new Error("Task does not have a run function");
1972
+ }
1973
+ if (!middlewareFn) {
1974
+ return runFn(payload, {
1975
+ ctx
1976
+ });
1977
+ }
1978
+ return middlewareFn(payload, {
1979
+ ctx,
1980
+ next: async () => runFn(payload, {
1981
+ ctx,
1982
+ init
1983
+ })
1984
+ });
1985
+ }, "#callRun");
1986
+ _callInitFunctions = new WeakSet();
1987
+ callInitFunctions_fn = /* @__PURE__ */ __name(async function(payload1, ctx1) {
1988
+ await __privateMethod(this, _callConfigInit, callConfigInit_fn).call(this, payload1, ctx1);
1989
+ const initFn = this.task.fns.init;
1990
+ if (!initFn) {
1991
+ return {};
1992
+ }
1993
+ return this._tracer.startActiveSpan("init", async (span) => {
1994
+ return await initFn(payload1, {
1995
+ ctx: ctx1
1996
+ });
1997
+ }, {
1998
+ attributes: {
1999
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2000
+ }
2001
+ });
2002
+ }, "#callInitFunctions");
2003
+ _callConfigInit = new WeakSet();
2004
+ callConfigInit_fn = /* @__PURE__ */ __name(async function(payload2, ctx2) {
2005
+ const initFn = this._importedConfig?.init;
2006
+ if (!initFn) {
2007
+ return {};
2008
+ }
2009
+ return this._tracer.startActiveSpan("config.init", async (span) => {
2010
+ return await initFn(payload2, {
2011
+ ctx: ctx2
2012
+ });
2013
+ }, {
2014
+ attributes: {
2015
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2016
+ }
2017
+ });
2018
+ }, "#callConfigInit");
2019
+ _callOnSuccessFunctions = new WeakSet();
2020
+ callOnSuccessFunctions_fn = /* @__PURE__ */ __name(async function(payload3, output, ctx3, initOutput) {
2021
+ await __privateMethod(this, _callOnSuccessFunction, callOnSuccessFunction_fn).call(this, this.task.fns.onSuccess, "task.onSuccess", payload3, output, ctx3, initOutput);
2022
+ await __privateMethod(this, _callOnSuccessFunction, callOnSuccessFunction_fn).call(this, this._importedConfig?.onSuccess, "config.onSuccess", payload3, output, ctx3, initOutput);
2023
+ }, "#callOnSuccessFunctions");
2024
+ _callOnSuccessFunction = new WeakSet();
2025
+ callOnSuccessFunction_fn = /* @__PURE__ */ __name(async function(onSuccessFn, name, payload4, output1, ctx4, initOutput1) {
2026
+ if (!onSuccessFn) {
2027
+ return;
2028
+ }
2029
+ try {
2030
+ await this._tracer.startActiveSpan(name, async (span) => {
2031
+ return await onSuccessFn(payload4, output1, {
2032
+ ctx: ctx4,
2033
+ init: initOutput1
2034
+ });
2035
+ }, {
2036
+ attributes: {
2037
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2038
+ }
2039
+ });
2040
+ } catch {
2041
+ }
2042
+ }, "#callOnSuccessFunction");
2043
+ _callOnFailureFunctions = new WeakSet();
2044
+ callOnFailureFunctions_fn = /* @__PURE__ */ __name(async function(payload5, error, ctx5, initOutput2) {
2045
+ await __privateMethod(this, _callOnFailureFunction, callOnFailureFunction_fn).call(this, this.task.fns.onFailure, "task.onFailure", payload5, error, ctx5, initOutput2);
2046
+ await __privateMethod(this, _callOnFailureFunction, callOnFailureFunction_fn).call(this, this._importedConfig?.onFailure, "config.onFailure", payload5, error, ctx5, initOutput2);
2047
+ }, "#callOnFailureFunctions");
2048
+ _callOnFailureFunction = new WeakSet();
2049
+ callOnFailureFunction_fn = /* @__PURE__ */ __name(async function(onFailureFn, name1, payload6, error1, ctx6, initOutput3) {
2050
+ if (!onFailureFn) {
2051
+ return;
2052
+ }
2053
+ try {
2054
+ return await this._tracer.startActiveSpan(name1, async (span) => {
2055
+ return await onFailureFn(payload6, error1, {
2056
+ ctx: ctx6,
2057
+ init: initOutput3
2058
+ });
2059
+ }, {
2060
+ attributes: {
2061
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2062
+ }
2063
+ });
2064
+ } catch (e) {
2065
+ }
2066
+ }, "#callOnFailureFunction");
2067
+ _callOnStartFunctions = new WeakSet();
2068
+ callOnStartFunctions_fn = /* @__PURE__ */ __name(async function(payload7, ctx7) {
2069
+ await __privateMethod(this, _callOnStartFunction, callOnStartFunction_fn).call(this, this._importedConfig?.onStart, "config.onStart", payload7, ctx7, {});
2070
+ await __privateMethod(this, _callOnStartFunction, callOnStartFunction_fn).call(this, this.task.fns.onStart, "task.onStart", payload7, ctx7, {});
2071
+ }, "#callOnStartFunctions");
2072
+ _callOnStartFunction = new WeakSet();
2073
+ callOnStartFunction_fn = /* @__PURE__ */ __name(async function(onStartFn, name2, payload8, ctx8, initOutput4) {
2074
+ if (!onStartFn) {
2075
+ return;
2076
+ }
2077
+ try {
2078
+ await this._tracer.startActiveSpan(name2, async (span) => {
2079
+ return await onStartFn(payload8, {
2080
+ ctx: ctx8
2081
+ });
2082
+ }, {
2083
+ attributes: {
2084
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2085
+ }
2086
+ });
2087
+ } catch {
2088
+ }
2089
+ }, "#callOnStartFunction");
2090
+ _callTaskCleanup = new WeakSet();
2091
+ callTaskCleanup_fn = /* @__PURE__ */ __name(async function(payload9, ctx9, init1) {
2092
+ const cleanupFn = this.task.fns.cleanup;
2093
+ if (!cleanupFn) {
2094
+ return;
2095
+ }
2096
+ return this._tracer.startActiveSpan("cleanup", async (span) => {
2097
+ return await cleanupFn(payload9, {
2098
+ ctx: ctx9,
2099
+ init: init1
2100
+ });
2101
+ });
2102
+ }, "#callTaskCleanup");
2103
+ _handleError = new WeakSet();
2104
+ handleError_fn = /* @__PURE__ */ __name(async function(execution, error2, payload10, ctx10) {
2105
+ const retriesConfig = this._importedConfig?.retries ?? this._config.retries;
2106
+ const retry = this.task.retry ?? retriesConfig?.default;
2107
+ if (!retry) {
2108
+ return {
2109
+ status: "noop"
2110
+ };
2111
+ }
2112
+ const delay = calculateNextRetryDelay(retry, execution.attempt.number);
2113
+ if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
2114
+ return {
2115
+ status: "skipped"
2116
+ };
2117
+ }
2118
+ return this._tracer.startActiveSpan("handleError()", async (span) => {
2119
+ const handleErrorResult = this.task.fns.handleError ? await this.task.fns.handleError(payload10, error2, {
2120
+ ctx: ctx10,
2121
+ retry,
2122
+ retryDelayInMs: delay,
2123
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
2124
+ }) : this._importedConfig ? await this._handleErrorFn?.(payload10, error2, {
2125
+ ctx: ctx10,
2126
+ retry,
2127
+ retryDelayInMs: delay,
2128
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
2129
+ }) : void 0;
2130
+ if (!handleErrorResult) {
2131
+ return typeof delay === "undefined" ? {
2132
+ status: "noop"
2133
+ } : {
2134
+ status: "retry",
2135
+ retry: {
2136
+ timestamp: Date.now() + delay,
2137
+ delay
2138
+ }
2139
+ };
2140
+ }
2141
+ if (handleErrorResult.skipRetrying) {
2142
+ return {
2143
+ status: "skipped",
2144
+ error: handleErrorResult.error
2145
+ };
2146
+ }
2147
+ if (typeof handleErrorResult.retryAt !== "undefined") {
2148
+ return {
2149
+ status: "retry",
2150
+ retry: {
2151
+ timestamp: handleErrorResult.retryAt.getTime(),
2152
+ delay: handleErrorResult.retryAt.getTime() - Date.now()
2153
+ },
2154
+ error: handleErrorResult.error
2155
+ };
2156
+ }
2157
+ if (typeof handleErrorResult.retryDelayInMs === "number") {
2158
+ return {
2159
+ status: "retry",
2160
+ retry: {
2161
+ timestamp: Date.now() + handleErrorResult.retryDelayInMs,
2162
+ delay: handleErrorResult.retryDelayInMs
2163
+ },
2164
+ error: handleErrorResult.error
2165
+ };
2166
+ }
2167
+ if (handleErrorResult.retry && typeof handleErrorResult.retry === "object") {
2168
+ const delay2 = calculateNextRetryDelay(handleErrorResult.retry, execution.attempt.number);
2169
+ return typeof delay2 === "undefined" ? {
2170
+ status: "noop",
2171
+ error: handleErrorResult.error
2172
+ } : {
2173
+ status: "retry",
2174
+ retry: {
2175
+ timestamp: Date.now() + delay2,
2176
+ delay: delay2
2177
+ },
2178
+ error: handleErrorResult.error
2179
+ };
2180
+ }
2181
+ return {
2182
+ status: "noop",
2183
+ error: handleErrorResult.error
2184
+ };
2185
+ }, {
2186
+ attributes: {
2187
+ [SemanticInternalAttributes.STYLE_ICON]: "exclamation-circle"
2188
+ }
2189
+ });
2190
+ }, "#handleError");
2191
+ __name(_TaskExecutor, "TaskExecutor");
2192
+ var TaskExecutor = _TaskExecutor;
2193
+ var _originClockTime, originClockTime_get, _originPreciseDate, originPreciseDate_get;
2194
+ var _PreciseWallClock = class _PreciseWallClock {
2195
+ constructor(options = {}) {
2196
+ __privateAdd(this, _originClockTime);
2197
+ __privateAdd(this, _originPreciseDate);
2198
+ this._origin = {
2199
+ clockTime: options.origin ?? process.hrtime(),
2200
+ preciseDate: options.now ?? new preciseDate.PreciseDate()
2201
+ };
2202
+ }
2203
+ preciseNow() {
2204
+ const elapsedHrTime = process.hrtime(__privateGet(this, _originClockTime, originClockTime_get));
2205
+ const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
2206
+ const preciseDate$1 = new preciseDate.PreciseDate(__privateGet(this, _originPreciseDate, originPreciseDate_get).getFullTime() + elapsedNanoseconds);
2207
+ const dateStruct = preciseDate$1.toStruct();
2208
+ return [
2209
+ dateStruct.seconds,
2210
+ dateStruct.nanos
2211
+ ];
2212
+ }
2213
+ reset() {
2214
+ this._origin = {
2215
+ clockTime: process.hrtime(),
2216
+ preciseDate: new preciseDate.PreciseDate()
2217
+ };
2218
+ }
2219
+ };
2220
+ _originClockTime = new WeakSet();
2221
+ originClockTime_get = /* @__PURE__ */ __name(function() {
2222
+ return this._origin.clockTime;
2223
+ }, "#originClockTime");
2224
+ _originPreciseDate = new WeakSet();
2225
+ originPreciseDate_get = /* @__PURE__ */ __name(function() {
2226
+ return this._origin.preciseDate;
2227
+ }, "#originPreciseDate");
2228
+ __name(_PreciseWallClock, "PreciseWallClock");
2229
+ var PreciseWallClock = _PreciseWallClock;
2230
+ function iconStringForSeverity(severityNumber) {
2231
+ switch (severityNumber) {
2232
+ case apiLogs.SeverityNumber.UNSPECIFIED:
2233
+ return void 0;
2234
+ case apiLogs.SeverityNumber.TRACE:
2235
+ case apiLogs.SeverityNumber.TRACE2:
2236
+ case apiLogs.SeverityNumber.TRACE3:
2237
+ case apiLogs.SeverityNumber.TRACE4:
2238
+ return "trace";
2239
+ case apiLogs.SeverityNumber.DEBUG:
2240
+ case apiLogs.SeverityNumber.DEBUG2:
2241
+ case apiLogs.SeverityNumber.DEBUG3:
2242
+ case apiLogs.SeverityNumber.DEBUG4:
2243
+ return "debug";
2244
+ case apiLogs.SeverityNumber.INFO:
2245
+ case apiLogs.SeverityNumber.INFO2:
2246
+ case apiLogs.SeverityNumber.INFO3:
2247
+ case apiLogs.SeverityNumber.INFO4:
2248
+ return "info";
2249
+ case apiLogs.SeverityNumber.WARN:
2250
+ case apiLogs.SeverityNumber.WARN2:
2251
+ case apiLogs.SeverityNumber.WARN3:
2252
+ case apiLogs.SeverityNumber.WARN4:
2253
+ return "warn";
2254
+ case apiLogs.SeverityNumber.ERROR:
2255
+ case apiLogs.SeverityNumber.ERROR2:
2256
+ case apiLogs.SeverityNumber.ERROR3:
2257
+ case apiLogs.SeverityNumber.ERROR4:
2258
+ return "error";
2259
+ case apiLogs.SeverityNumber.FATAL:
2260
+ case apiLogs.SeverityNumber.FATAL2:
2261
+ case apiLogs.SeverityNumber.FATAL3:
2262
+ case apiLogs.SeverityNumber.FATAL4:
2263
+ return "fatal";
2264
+ }
2265
+ }
2266
+ __name(iconStringForSeverity, "iconStringForSeverity");
2267
+ var _SimpleClock = class _SimpleClock {
2268
+ preciseNow() {
2269
+ const now = new preciseDate.PreciseDate();
2270
+ const nowStruct = now.toStruct();
2271
+ return [
2272
+ nowStruct.seconds,
2273
+ nowStruct.nanos
2274
+ ];
2275
+ }
2276
+ reset() {
2277
+ }
2278
+ };
2279
+ __name(_SimpleClock, "SimpleClock");
2280
+ var SimpleClock = _SimpleClock;
2281
+
2282
+ // src/v3/clock/index.ts
2283
+ var API_NAME3 = "clock";
2284
+ var SIMPLE_CLOCK = new SimpleClock();
2285
+ var _getClock, getClock_fn;
2286
+ var _ClockAPI = class _ClockAPI {
2287
+ constructor() {
2288
+ __privateAdd(this, _getClock);
2289
+ }
2290
+ static getInstance() {
2291
+ if (!this._instance) {
2292
+ this._instance = new _ClockAPI();
2293
+ }
2294
+ return this._instance;
2295
+ }
2296
+ setGlobalClock(clock2) {
2297
+ return registerGlobal(API_NAME3, clock2);
2298
+ }
2299
+ preciseNow() {
2300
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2301
+ }
2302
+ reset() {
2303
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2304
+ }
2305
+ };
2306
+ _getClock = new WeakSet();
2307
+ getClock_fn = /* @__PURE__ */ __name(function() {
2308
+ return getGlobal(API_NAME3) ?? SIMPLE_CLOCK;
2309
+ }, "#getClock");
2310
+ __name(_ClockAPI, "ClockAPI");
2311
+ var ClockAPI = _ClockAPI;
2312
+
2313
+ // src/v3/clock-api.ts
2314
+ var clock = ClockAPI.getInstance();
2315
+
2316
+ // src/v3/logger/taskLogger.ts
2317
+ var logLevels = [
2318
+ "none",
2319
+ "error",
2320
+ "warn",
2321
+ "info",
2322
+ "debug"
2323
+ ];
2324
+ var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
2325
+ var _OtelTaskLogger = class _OtelTaskLogger {
2326
+ constructor(_config) {
2327
+ __privateAdd(this, _emitLog);
2328
+ __privateAdd(this, _getTimestampInHrTime);
2329
+ this._config = _config;
2330
+ this._level = logLevels.indexOf(_config.level);
2331
+ }
2332
+ debug(message, properties) {
2333
+ if (this._level < 4)
2334
+ return;
2335
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", apiLogs.SeverityNumber.DEBUG, properties);
2336
+ }
2337
+ log(message, properties) {
2338
+ if (this._level < 3)
2339
+ return;
2340
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", apiLogs.SeverityNumber.INFO, properties);
2341
+ }
2342
+ info(message, properties) {
2343
+ if (this._level < 3)
2344
+ return;
2345
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", apiLogs.SeverityNumber.INFO, properties);
2346
+ }
2347
+ warn(message, properties) {
2348
+ if (this._level < 2)
2349
+ return;
2350
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", apiLogs.SeverityNumber.WARN, properties);
2351
+ }
2352
+ error(message, properties) {
2353
+ if (this._level < 1)
2354
+ return;
2355
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", apiLogs.SeverityNumber.ERROR, properties);
2356
+ }
2357
+ trace(name, fn, options) {
2358
+ return this._config.tracer.startActiveSpan(name, fn, options);
2359
+ }
2360
+ };
2361
+ _emitLog = new WeakSet();
2362
+ emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
2363
+ let attributes = {
2364
+ ...flattenAttributes(safeJsonProcess(properties))
2365
+ };
2366
+ const icon = iconStringForSeverity(severityNumber);
2367
+ if (icon !== void 0) {
2368
+ attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
2369
+ }
2370
+ this._config.logger.emit({
2371
+ severityNumber,
2372
+ severityText,
2373
+ body: message,
2374
+ attributes,
2375
+ timestamp
2376
+ });
2377
+ }, "#emitLog");
2378
+ _getTimestampInHrTime = new WeakSet();
2379
+ getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
2380
+ return clock.preciseNow();
2381
+ }, "#getTimestampInHrTime");
2382
+ __name(_OtelTaskLogger, "OtelTaskLogger");
2383
+ var OtelTaskLogger = _OtelTaskLogger;
2384
+ function safeJsonProcess(value) {
2385
+ try {
2386
+ return JSON.parse(JSON.stringify(value, jsonErrorReplacer));
2387
+ } catch {
2388
+ return value;
2389
+ }
2390
+ }
2391
+ __name(safeJsonProcess, "safeJsonProcess");
2392
+ function jsonErrorReplacer(key, value) {
2393
+ if (value instanceof Error) {
2394
+ return {
2395
+ name: value.name,
2396
+ message: value.message,
2397
+ stack: value.stack
2398
+ };
2399
+ }
2400
+ return value;
2401
+ }
2402
+ __name(jsonErrorReplacer, "jsonErrorReplacer");
2403
+ var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
2404
+ var _ConsoleInterceptor = class _ConsoleInterceptor {
2405
+ constructor(logger, sendToStdIO) {
2406
+ __privateAdd(this, _handleLog);
2407
+ __privateAdd(this, _getTimestampInHrTime2);
2408
+ __privateAdd(this, _getAttributes);
2409
+ this.logger = logger;
2410
+ this.sendToStdIO = sendToStdIO;
2411
+ }
2412
+ // Intercept the console and send logs to the OpenTelemetry logger
2413
+ // during the execution of the callback
2414
+ async intercept(console2, callback) {
2415
+ const originalConsole = {
2416
+ log: console2.log,
2417
+ info: console2.info,
2418
+ warn: console2.warn,
2419
+ error: console2.error,
2420
+ debug: console2.debug
2421
+ };
2422
+ console2.log = this.log.bind(this);
2423
+ console2.info = this.info.bind(this);
2424
+ console2.warn = this.warn.bind(this);
2425
+ console2.error = this.error.bind(this);
2426
+ console2.debug = this.debug.bind(this);
2427
+ try {
2428
+ return await callback();
2429
+ } finally {
2430
+ console2.log = originalConsole.log;
2431
+ console2.info = originalConsole.info;
2432
+ console2.warn = originalConsole.warn;
2433
+ console2.error = originalConsole.error;
2434
+ console2.debug = originalConsole.debug;
2435
+ }
2436
+ }
2437
+ debug(...args) {
2438
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
2439
+ }
2440
+ log(...args) {
2441
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
2442
+ }
2443
+ info(...args) {
2444
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
2445
+ }
2446
+ warn(...args) {
2447
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
2448
+ }
2449
+ error(...args) {
2450
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
2451
+ }
2452
+ };
2453
+ _handleLog = new WeakSet();
2454
+ handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
2455
+ const body = util__default.default.format(...args);
2456
+ if (this.sendToStdIO) {
2457
+ if (severityNumber === apiLogs.SeverityNumber.ERROR) {
2458
+ process.stderr.write(body);
2459
+ } else {
2460
+ process.stdout.write(body);
2461
+ }
2462
+ }
2463
+ const parsed = tryParseJSON(body);
2464
+ if (parsed.ok) {
2465
+ this.logger.emit({
2466
+ severityNumber,
2467
+ severityText,
2468
+ body: getLogMessage(parsed.value, severityText),
2469
+ attributes: {
2470
+ ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
2471
+ ...flattenAttributes(parsed.value)
2472
+ },
2473
+ timestamp
2474
+ });
2475
+ return;
2476
+ }
2477
+ this.logger.emit({
2478
+ severityNumber,
2479
+ severityText,
2480
+ body,
2481
+ attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
2482
+ timestamp
2483
+ });
2484
+ }, "#handleLog");
2485
+ _getTimestampInHrTime2 = new WeakSet();
2486
+ getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
2487
+ return clock.preciseNow();
2488
+ }, "#getTimestampInHrTime");
2489
+ _getAttributes = new WeakSet();
2490
+ getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
2491
+ const icon = iconStringForSeverity(severityNumber1);
2492
+ let result = {};
2493
+ if (icon !== void 0) {
2494
+ result[SemanticInternalAttributes.STYLE_ICON] = icon;
2495
+ }
2496
+ return result;
2497
+ }, "#getAttributes");
2498
+ __name(_ConsoleInterceptor, "ConsoleInterceptor");
2499
+ var ConsoleInterceptor = _ConsoleInterceptor;
2500
+ function getLogMessage(value, fallback) {
2501
+ if (typeof value["message"] === "string") {
2502
+ return value["message"];
2503
+ }
2504
+ if (typeof value["msg"] === "string") {
2505
+ return value["msg"];
2506
+ }
2507
+ if (typeof value["body"] === "string") {
2508
+ return value["body"];
2509
+ }
2510
+ if (typeof value["error"] === "string") {
2511
+ return value["error"];
2512
+ }
2513
+ return fallback;
2514
+ }
2515
+ __name(getLogMessage, "getLogMessage");
2516
+ function tryParseJSON(value) {
2517
+ try {
2518
+ const parsed = JSON.parse(value);
2519
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
2520
+ return {
2521
+ ok: true,
2522
+ value: parsed
2523
+ };
2524
+ }
2525
+ return {
2526
+ ok: false,
2527
+ value
2528
+ };
2529
+ } catch (e) {
2530
+ return {
2531
+ ok: false,
2532
+ value
2533
+ };
2534
+ }
2535
+ }
2536
+ __name(tryParseJSON, "tryParseJSON");
2537
+
2538
+ // src/v3/task-catalog/standardTaskCatalog.ts
2539
+ var _StandardTaskCatalog = class _StandardTaskCatalog {
2540
+ constructor() {
2541
+ __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
2542
+ __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
2543
+ __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
2544
+ }
2545
+ registerTaskMetadata(task) {
2546
+ const { fns, ...metadata } = task;
2547
+ this._taskMetadata.set(task.id, metadata);
2548
+ this._taskFunctions.set(task.id, fns);
2549
+ }
2550
+ updateTaskMetadata(id, updates) {
2551
+ const existingMetadata = this._taskMetadata.get(id);
2552
+ if (existingMetadata) {
2553
+ this._taskMetadata.set(id, {
2554
+ ...existingMetadata,
2555
+ ...updates
2556
+ });
2557
+ }
2558
+ if (updates.fns) {
2559
+ const existingFunctions = this._taskFunctions.get(id);
2560
+ if (existingFunctions) {
2561
+ this._taskFunctions.set(id, {
2562
+ ...existingFunctions,
2563
+ ...updates.fns
2564
+ });
2565
+ }
2566
+ }
2567
+ }
2568
+ registerTaskFileMetadata(id, metadata) {
2569
+ this._taskFileMetadata.set(id, metadata);
2570
+ }
2571
+ // Return all the tasks, without the functions
2572
+ getAllTaskMetadata() {
2573
+ const result = [];
2574
+ for (const [id, metadata] of this._taskMetadata) {
2575
+ const fileMetadata = this._taskFileMetadata.get(id);
2576
+ if (!fileMetadata) {
2577
+ continue;
2578
+ }
2579
+ result.push({
2580
+ ...metadata,
2581
+ ...fileMetadata
2582
+ });
2583
+ }
2584
+ return result;
2585
+ }
2586
+ getTaskMetadata(id) {
2587
+ const metadata = this._taskMetadata.get(id);
2588
+ const fileMetadata = this._taskFileMetadata.get(id);
2589
+ if (!metadata || !fileMetadata) {
2590
+ return void 0;
2591
+ }
2592
+ return {
2593
+ ...metadata,
2594
+ ...fileMetadata
2595
+ };
2596
+ }
2597
+ getTask(id) {
2598
+ const metadata = this._taskMetadata.get(id);
2599
+ const fileMetadata = this._taskFileMetadata.get(id);
2600
+ const fns = this._taskFunctions.get(id);
2601
+ if (!metadata || !fns || !fileMetadata) {
2602
+ return void 0;
2603
+ }
2604
+ return {
2605
+ ...metadata,
2606
+ ...fileMetadata,
2607
+ fns
2608
+ };
2609
+ }
2610
+ taskExists(id) {
2611
+ return this._taskMetadata.has(id);
2612
+ }
2613
+ disable() {
2614
+ }
2615
+ };
2616
+ __name(_StandardTaskCatalog, "StandardTaskCatalog");
2617
+ var StandardTaskCatalog = _StandardTaskCatalog;
2618
+
2619
+ exports.ConsoleInterceptor = ConsoleInterceptor;
2620
+ exports.DurableClock = PreciseWallClock;
2621
+ exports.OtelTaskLogger = OtelTaskLogger;
2622
+ exports.StandardTaskCatalog = StandardTaskCatalog;
2623
+ exports.TaskContextLogProcessor = TaskContextLogProcessor;
2624
+ exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
2625
+ exports.TaskExecutor = TaskExecutor;
2626
+ exports.TracingSDK = TracingSDK;
2627
+ exports.getEnvVar = getEnvVar;
2628
+ exports.logLevels = logLevels;
2629
+ exports.recordSpanException = recordSpanException;
2630
+ //# sourceMappingURL=out.js.map
2631
+ //# sourceMappingURL=index.js.map