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

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