@trigger.dev/core 3.0.0-beta.32 → 3.0.0-beta.34

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.
package/dist/v3/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  'use strict';
2
2
 
3
3
  var api = require('@opentelemetry/api');
4
- var zodValidationError = require('zod-validation-error');
5
4
  var zod = require('zod');
5
+ var zodValidationError = require('zod-validation-error');
6
+ var formDataEncoder = require('form-data-encoder');
7
+ var stream = require('stream');
6
8
  var preciseDate = require('@google-cloud/precise-date');
7
9
  var apiLogs = require('@opentelemetry/api-logs');
8
10
  var humanizeDuration = require('humanize-duration');
@@ -32,6 +34,31 @@ var __privateMethod = (obj, member, method) => {
32
34
  return method;
33
35
  };
34
36
 
37
+ // package.json
38
+ var version = "3.0.0-beta.34";
39
+ var dependencies = {
40
+ "@google-cloud/precise-date": "^4.0.0",
41
+ "@opentelemetry/api": "^1.8.0",
42
+ "@opentelemetry/api-logs": "^0.48.0",
43
+ "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
44
+ "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
45
+ "@opentelemetry/instrumentation": "^0.49.1",
46
+ "@opentelemetry/resources": "^1.22.0",
47
+ "@opentelemetry/sdk-logs": "^0.49.1",
48
+ "@opentelemetry/sdk-node": "^0.49.1",
49
+ "@opentelemetry/sdk-trace-base": "^1.22.0",
50
+ "@opentelemetry/sdk-trace-node": "^1.22.0",
51
+ "@opentelemetry/semantic-conventions": "^1.22.0",
52
+ "form-data-encoder": "^4.0.2",
53
+ "humanize-duration": "^3.27.3",
54
+ "socket.io-client": "4.7.4",
55
+ superjson: "^2.2.1",
56
+ ulidx: "^2.2.1",
57
+ zod: "3.22.3",
58
+ "zod-error": "1.5.0",
59
+ "zod-validation-error": "^1.5.0"
60
+ };
61
+
35
62
  // src/v3/apiErrors.ts
36
63
  var _APIError = class _APIError extends Error {
37
64
  constructor(status, error, message, headers) {
@@ -169,247 +196,6 @@ function castToError(err) {
169
196
  return new Error(err);
170
197
  }
171
198
  __name(castToError, "castToError");
172
-
173
- // src/retry.ts
174
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
175
- if (!resets)
176
- return;
177
- switch (format) {
178
- case "iso_8601_duration_openai_variant": {
179
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
180
- }
181
- case "iso_8601": {
182
- return calculateISO8601ResetAt(resets, now);
183
- }
184
- case "unix_timestamp": {
185
- return calculateUnixTimestampResetAt(resets, now);
186
- }
187
- case "unix_timestamp_in_ms": {
188
- return calculateUnixTimestampInMsResetAt(resets, now);
189
- }
190
- }
191
- }
192
- __name(calculateResetAt, "calculateResetAt");
193
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
194
- if (!resets)
195
- return void 0;
196
- const resetAt = parseInt(resets, 10);
197
- if (isNaN(resetAt))
198
- return void 0;
199
- return new Date(resetAt * 1e3);
200
- }
201
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
202
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
203
- if (!resets)
204
- return void 0;
205
- const resetAt = parseInt(resets, 10);
206
- if (isNaN(resetAt))
207
- return void 0;
208
- return new Date(resetAt);
209
- }
210
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
211
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
212
- if (!resets)
213
- return void 0;
214
- const resetAt = new Date(resets);
215
- if (isNaN(resetAt.getTime()))
216
- return void 0;
217
- return resetAt;
218
- }
219
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
220
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
221
- if (!resets)
222
- return void 0;
223
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
224
- const match = resets.match(pattern);
225
- if (!match)
226
- return void 0;
227
- const days = parseInt(match[1], 10) || 0;
228
- const hours = parseInt(match[2], 10) || 0;
229
- const minutes = parseInt(match[3], 10) || 0;
230
- const seconds = parseFloat(match[4]) || 0;
231
- const milliseconds = parseInt(match[5], 10) || 0;
232
- const resetAt = new Date(now);
233
- resetAt.setDate(resetAt.getDate() + days);
234
- resetAt.setHours(resetAt.getHours() + hours);
235
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
236
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
237
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
238
- return resetAt;
239
- }
240
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
241
-
242
- // src/v3/utils/retries.ts
243
- var defaultRetryOptions = {
244
- maxAttempts: 3,
245
- factor: 2,
246
- minTimeoutInMs: 1e3,
247
- maxTimeoutInMs: 6e4,
248
- randomize: true
249
- };
250
- var defaultFetchRetryOptions = {
251
- byStatus: {
252
- "429,408,409,5xx": {
253
- strategy: "backoff",
254
- ...defaultRetryOptions
255
- }
256
- },
257
- connectionError: defaultRetryOptions,
258
- timeout: defaultRetryOptions
259
- };
260
- function calculateNextRetryDelay(options, attempt) {
261
- const opts = {
262
- ...defaultRetryOptions,
263
- ...options
264
- };
265
- if (attempt >= opts.maxAttempts) {
266
- return;
267
- }
268
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
269
- const random = randomize ? Math.random() + 1 : 1;
270
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
271
- return Math.round(timeout);
272
- }
273
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
274
- function calculateResetAt2(resets, format, now = Date.now()) {
275
- const resetAt = calculateResetAt(resets, format, new Date(now));
276
- return resetAt?.getTime();
277
- }
278
- __name(calculateResetAt2, "calculateResetAt");
279
-
280
- // src/v3/zodfetch.ts
281
- var defaultRetryOptions2 = {
282
- maxAttempts: 3,
283
- factor: 2,
284
- minTimeoutInMs: 1e3,
285
- maxTimeoutInMs: 6e4,
286
- randomize: false
287
- };
288
- async function zodfetch(schema, url, requestInit, options) {
289
- return await _doZodFetch(schema, url, requestInit, options);
290
- }
291
- __name(zodfetch, "zodfetch");
292
- async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
293
- try {
294
- const response = await fetch(url, requestInitWithCache(requestInit));
295
- const responseHeaders = createResponseHeaders(response.headers);
296
- if (!response.ok) {
297
- const retryResult = shouldRetry(response, attempt, options?.retry);
298
- if (retryResult.retry) {
299
- await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
300
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
301
- } else {
302
- const errText = await response.text().catch((e) => castToError2(e).message);
303
- const errJSON = safeJsonParse(errText);
304
- const errMessage = errJSON ? void 0 : errText;
305
- throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
306
- }
307
- }
308
- const jsonBody = await response.json();
309
- const parsedResult = schema.safeParse(jsonBody);
310
- if (parsedResult.success) {
311
- return parsedResult.data;
312
- }
313
- throw zodValidationError.fromZodError(parsedResult.error);
314
- } catch (error) {
315
- if (error instanceof APIError) {
316
- throw error;
317
- }
318
- if (options?.retry) {
319
- const retry = {
320
- ...defaultRetryOptions2,
321
- ...options.retry
322
- };
323
- const delay = calculateNextRetryDelay(retry, attempt);
324
- if (delay) {
325
- await new Promise((resolve) => setTimeout(resolve, delay));
326
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
327
- }
328
- }
329
- throw new APIConnectionError({
330
- cause: castToError2(error)
331
- });
332
- }
333
- }
334
- __name(_doZodFetch, "_doZodFetch");
335
- function castToError2(err) {
336
- if (err instanceof Error)
337
- return err;
338
- return new Error(err);
339
- }
340
- __name(castToError2, "castToError");
341
- function shouldRetry(response, attempt, retryOptions) {
342
- function shouldRetryForOptions() {
343
- const retry = {
344
- ...defaultRetryOptions2,
345
- ...retryOptions
346
- };
347
- const delay = calculateNextRetryDelay(retry, attempt);
348
- if (delay) {
349
- return {
350
- retry: true,
351
- delay
352
- };
353
- } else {
354
- return {
355
- retry: false
356
- };
357
- }
358
- }
359
- __name(shouldRetryForOptions, "shouldRetryForOptions");
360
- const shouldRetryHeader = response.headers.get("x-should-retry");
361
- if (shouldRetryHeader === "true")
362
- return shouldRetryForOptions();
363
- if (shouldRetryHeader === "false")
364
- return {
365
- retry: false
366
- };
367
- if (response.status === 408)
368
- return shouldRetryForOptions();
369
- if (response.status === 409)
370
- return shouldRetryForOptions();
371
- if (response.status === 429)
372
- return shouldRetryForOptions();
373
- if (response.status >= 500)
374
- return shouldRetryForOptions();
375
- return {
376
- retry: false
377
- };
378
- }
379
- __name(shouldRetry, "shouldRetry");
380
- function safeJsonParse(text) {
381
- try {
382
- return JSON.parse(text);
383
- } catch (e) {
384
- return void 0;
385
- }
386
- }
387
- __name(safeJsonParse, "safeJsonParse");
388
- function createResponseHeaders(headers) {
389
- return new Proxy(Object.fromEntries(
390
- // @ts-ignore
391
- headers.entries()
392
- ), {
393
- get(target, name) {
394
- const key = name.toString();
395
- return target[key.toLowerCase()] || target[key];
396
- }
397
- });
398
- }
399
- __name(createResponseHeaders, "createResponseHeaders");
400
- function requestInitWithCache(requestInit) {
401
- try {
402
- const withCache = {
403
- ...requestInit,
404
- cache: "no-cache"
405
- };
406
- const _ = new Request("http://localhost", withCache);
407
- return withCache;
408
- } catch (error) {
409
- return requestInit ?? {};
410
- }
411
- }
412
- __name(requestInitWithCache, "requestInitWithCache");
413
199
  var CreateAuthorizationCodeResponseSchema = zod.z.object({
414
200
  url: zod.z.string().url(),
415
201
  authorizationCode: zod.z.string()
@@ -1044,6 +830,28 @@ var RetrieveRunResponse = zod.z.object({
1044
830
  completedAt: zod.z.coerce.date().optional()
1045
831
  }).optional())
1046
832
  });
833
+ var CreateEnvironmentVariableRequestBody = zod.z.object({
834
+ name: zod.z.string(),
835
+ value: zod.z.string()
836
+ });
837
+ var UpdateEnvironmentVariableRequestBody = zod.z.object({
838
+ value: zod.z.string()
839
+ });
840
+ var ImportEnvironmentVariablesRequestBody = zod.z.object({
841
+ variables: zod.z.record(zod.z.string()),
842
+ override: zod.z.boolean().optional()
843
+ });
844
+ var EnvironmentVariableResponseBody = zod.z.object({
845
+ success: zod.z.boolean()
846
+ });
847
+ var EnvironmentVariableValue = zod.z.object({
848
+ value: zod.z.string()
849
+ });
850
+ var EnvironmentVariable = zod.z.object({
851
+ name: zod.z.string(),
852
+ value: zod.z.string()
853
+ });
854
+ var EnvironmentVariables = zod.z.array(EnvironmentVariable);
1047
855
  var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
1048
856
  zod.z.object({
1049
857
  type: zod.z.literal("EXECUTE_RUNS"),
@@ -2022,89 +1830,443 @@ var SemanticInternalAttributes = {
2022
1830
  LINK_TITLE: "$link.title",
2023
1831
  IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
2024
1832
  };
2025
-
2026
- // src/v3/taskContext/index.ts
2027
- var API_NAME = "task-context";
2028
- var _getTaskContext, getTaskContext_fn;
2029
- var _TaskContextAPI = class _TaskContextAPI {
2030
- constructor() {
2031
- __privateAdd(this, _getTaskContext);
2032
- }
2033
- static getInstance() {
2034
- if (!this._instance) {
2035
- this._instance = new _TaskContextAPI();
1833
+
1834
+ // src/v3/taskContext/index.ts
1835
+ var API_NAME = "task-context";
1836
+ var _getTaskContext, getTaskContext_fn;
1837
+ var _TaskContextAPI = class _TaskContextAPI {
1838
+ constructor() {
1839
+ __privateAdd(this, _getTaskContext);
1840
+ }
1841
+ static getInstance() {
1842
+ if (!this._instance) {
1843
+ this._instance = new _TaskContextAPI();
1844
+ }
1845
+ return this._instance;
1846
+ }
1847
+ get isInsideTask() {
1848
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
1849
+ }
1850
+ get ctx() {
1851
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
1852
+ }
1853
+ get worker() {
1854
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
1855
+ }
1856
+ get attributes() {
1857
+ if (this.ctx) {
1858
+ return {
1859
+ ...this.contextAttributes,
1860
+ ...this.workerAttributes
1861
+ };
1862
+ }
1863
+ return {};
1864
+ }
1865
+ get workerAttributes() {
1866
+ if (this.worker) {
1867
+ return {
1868
+ [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
1869
+ [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
1870
+ };
1871
+ }
1872
+ return {};
1873
+ }
1874
+ get contextAttributes() {
1875
+ if (this.ctx) {
1876
+ return {
1877
+ [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
1878
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
1879
+ [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
1880
+ [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
1881
+ [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
1882
+ [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
1883
+ [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
1884
+ [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
1885
+ [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
1886
+ [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
1887
+ [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
1888
+ [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
1889
+ [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
1890
+ [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
1891
+ [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
1892
+ [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
1893
+ [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
1894
+ [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
1895
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
1896
+ };
1897
+ }
1898
+ return {};
1899
+ }
1900
+ disable() {
1901
+ unregisterGlobal(API_NAME);
1902
+ }
1903
+ setGlobalTaskContext(taskContext2) {
1904
+ return registerGlobal(API_NAME, taskContext2);
1905
+ }
1906
+ };
1907
+ _getTaskContext = new WeakSet();
1908
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
1909
+ return getGlobal(API_NAME);
1910
+ }, "#getTaskContext");
1911
+ __name(_TaskContextAPI, "TaskContextAPI");
1912
+ var TaskContextAPI = _TaskContextAPI;
1913
+
1914
+ // src/v3/task-context-api.ts
1915
+ var taskContext = TaskContextAPI.getInstance();
1916
+
1917
+ // src/retry.ts
1918
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
1919
+ if (!resets)
1920
+ return;
1921
+ switch (format) {
1922
+ case "iso_8601_duration_openai_variant": {
1923
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
1924
+ }
1925
+ case "iso_8601": {
1926
+ return calculateISO8601ResetAt(resets, now);
1927
+ }
1928
+ case "unix_timestamp": {
1929
+ return calculateUnixTimestampResetAt(resets, now);
1930
+ }
1931
+ case "unix_timestamp_in_ms": {
1932
+ return calculateUnixTimestampInMsResetAt(resets, now);
1933
+ }
1934
+ }
1935
+ }
1936
+ __name(calculateResetAt, "calculateResetAt");
1937
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
1938
+ if (!resets)
1939
+ return void 0;
1940
+ const resetAt = parseInt(resets, 10);
1941
+ if (isNaN(resetAt))
1942
+ return void 0;
1943
+ return new Date(resetAt * 1e3);
1944
+ }
1945
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
1946
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
1947
+ if (!resets)
1948
+ return void 0;
1949
+ const resetAt = parseInt(resets, 10);
1950
+ if (isNaN(resetAt))
1951
+ return void 0;
1952
+ return new Date(resetAt);
1953
+ }
1954
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
1955
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
1956
+ if (!resets)
1957
+ return void 0;
1958
+ const resetAt = new Date(resets);
1959
+ if (isNaN(resetAt.getTime()))
1960
+ return void 0;
1961
+ return resetAt;
1962
+ }
1963
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
1964
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
1965
+ if (!resets)
1966
+ return void 0;
1967
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
1968
+ const match = resets.match(pattern);
1969
+ if (!match)
1970
+ return void 0;
1971
+ const days = parseInt(match[1], 10) || 0;
1972
+ const hours = parseInt(match[2], 10) || 0;
1973
+ const minutes = parseInt(match[3], 10) || 0;
1974
+ const seconds = parseFloat(match[4]) || 0;
1975
+ const milliseconds = parseInt(match[5], 10) || 0;
1976
+ const resetAt = new Date(now);
1977
+ resetAt.setDate(resetAt.getDate() + days);
1978
+ resetAt.setHours(resetAt.getHours() + hours);
1979
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
1980
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
1981
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
1982
+ return resetAt;
1983
+ }
1984
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
1985
+
1986
+ // src/v3/utils/retries.ts
1987
+ var defaultRetryOptions = {
1988
+ maxAttempts: 3,
1989
+ factor: 2,
1990
+ minTimeoutInMs: 1e3,
1991
+ maxTimeoutInMs: 6e4,
1992
+ randomize: true
1993
+ };
1994
+ var defaultFetchRetryOptions = {
1995
+ byStatus: {
1996
+ "429,408,409,5xx": {
1997
+ strategy: "backoff",
1998
+ ...defaultRetryOptions
1999
+ }
2000
+ },
2001
+ connectionError: defaultRetryOptions,
2002
+ timeout: defaultRetryOptions
2003
+ };
2004
+ function calculateNextRetryDelay(options, attempt) {
2005
+ const opts = {
2006
+ ...defaultRetryOptions,
2007
+ ...options
2008
+ };
2009
+ if (attempt >= opts.maxAttempts) {
2010
+ return;
2011
+ }
2012
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
2013
+ const random = randomize ? Math.random() + 1 : 1;
2014
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
2015
+ return Math.round(timeout);
2016
+ }
2017
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
2018
+ function calculateResetAt2(resets, format, now = Date.now()) {
2019
+ const resetAt = calculateResetAt(resets, format, new Date(now));
2020
+ return resetAt?.getTime();
2021
+ }
2022
+ __name(calculateResetAt2, "calculateResetAt");
2023
+ var defaultRetryOptions2 = {
2024
+ maxAttempts: 3,
2025
+ factor: 2,
2026
+ minTimeoutInMs: 1e3,
2027
+ maxTimeoutInMs: 6e4,
2028
+ randomize: false
2029
+ };
2030
+ async function zodfetch(schema, url, requestInit, options) {
2031
+ return await _doZodFetch(schema, url, requestInit, options);
2032
+ }
2033
+ __name(zodfetch, "zodfetch");
2034
+ async function zodupload(schema, url, body, requestInit, options) {
2035
+ const form = await createForm(body);
2036
+ const encoder = new formDataEncoder.FormDataEncoder(form);
2037
+ const finalHeaders = {};
2038
+ for (const [key, value] of Object.entries(requestInit?.headers || {})) {
2039
+ finalHeaders[key] = value;
2040
+ }
2041
+ for (const [key, value] of Object.entries(encoder.headers)) {
2042
+ finalHeaders[key] = value;
2043
+ }
2044
+ finalHeaders["Content-Length"] = String(encoder.contentLength);
2045
+ const finalRequestInit = {
2046
+ ...requestInit,
2047
+ headers: finalHeaders,
2048
+ body: stream.Readable.from(encoder),
2049
+ // @ts-expect-error
2050
+ duplex: "half"
2051
+ };
2052
+ return await _doZodFetch(schema, url, finalRequestInit, options);
2053
+ }
2054
+ __name(zodupload, "zodupload");
2055
+ var createForm = /* @__PURE__ */ __name(async (body) => {
2056
+ const form = new FormData();
2057
+ await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
2058
+ return form;
2059
+ }, "createForm");
2060
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2061
+ try {
2062
+ const response = await fetch(url, requestInitWithCache(requestInit));
2063
+ const responseHeaders = createResponseHeaders(response.headers);
2064
+ if (!response.ok) {
2065
+ const retryResult = shouldRetry(response, attempt, options?.retry);
2066
+ if (retryResult.retry) {
2067
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
2068
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2069
+ } else {
2070
+ const errText = await response.text().catch((e) => castToError2(e).message);
2071
+ const errJSON = safeJsonParse(errText);
2072
+ const errMessage = errJSON ? void 0 : errText;
2073
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
2074
+ }
2036
2075
  }
2037
- return this._instance;
2038
- }
2039
- get isInsideTask() {
2040
- return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
2041
- }
2042
- get ctx() {
2043
- return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
2044
- }
2045
- get worker() {
2046
- return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
2047
- }
2048
- get attributes() {
2049
- if (this.ctx) {
2050
- return {
2051
- ...this.contextAttributes,
2052
- ...this.workerAttributes
2076
+ const jsonBody = await response.json();
2077
+ const parsedResult = schema.safeParse(jsonBody);
2078
+ if (parsedResult.success) {
2079
+ return parsedResult.data;
2080
+ }
2081
+ throw zodValidationError.fromZodError(parsedResult.error);
2082
+ } catch (error) {
2083
+ if (error instanceof APIError) {
2084
+ throw error;
2085
+ }
2086
+ if (options?.retry) {
2087
+ const retry = {
2088
+ ...defaultRetryOptions2,
2089
+ ...options.retry
2053
2090
  };
2091
+ const delay = calculateNextRetryDelay(retry, attempt);
2092
+ if (delay) {
2093
+ await new Promise((resolve) => setTimeout(resolve, delay));
2094
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2095
+ }
2054
2096
  }
2055
- return {};
2097
+ throw new APIConnectionError({
2098
+ cause: castToError2(error)
2099
+ });
2056
2100
  }
2057
- get workerAttributes() {
2058
- if (this.worker) {
2101
+ }
2102
+ __name(_doZodFetch, "_doZodFetch");
2103
+ function castToError2(err) {
2104
+ if (err instanceof Error)
2105
+ return err;
2106
+ return new Error(err);
2107
+ }
2108
+ __name(castToError2, "castToError");
2109
+ function shouldRetry(response, attempt, retryOptions) {
2110
+ function shouldRetryForOptions() {
2111
+ const retry = {
2112
+ ...defaultRetryOptions2,
2113
+ ...retryOptions
2114
+ };
2115
+ const delay = calculateNextRetryDelay(retry, attempt);
2116
+ if (delay) {
2059
2117
  return {
2060
- [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
2061
- [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
2118
+ retry: true,
2119
+ delay
2062
2120
  };
2063
- }
2064
- return {};
2065
- }
2066
- get contextAttributes() {
2067
- if (this.ctx) {
2121
+ } else {
2068
2122
  return {
2069
- [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
2070
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
2071
- [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
2072
- [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
2073
- [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
2074
- [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
2075
- [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
2076
- [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
2077
- [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
2078
- [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
2079
- [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
2080
- [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
2081
- [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
2082
- [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
2083
- [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
2084
- [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
2085
- [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
2086
- [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
2087
- [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
2123
+ retry: false
2088
2124
  };
2089
2125
  }
2090
- return {};
2091
2126
  }
2092
- disable() {
2093
- unregisterGlobal(API_NAME);
2127
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
2128
+ const shouldRetryHeader = response.headers.get("x-should-retry");
2129
+ if (shouldRetryHeader === "true")
2130
+ return shouldRetryForOptions();
2131
+ if (shouldRetryHeader === "false")
2132
+ return {
2133
+ retry: false
2134
+ };
2135
+ if (response.status === 408)
2136
+ return shouldRetryForOptions();
2137
+ if (response.status === 409)
2138
+ return shouldRetryForOptions();
2139
+ if (response.status === 429)
2140
+ return shouldRetryForOptions();
2141
+ if (response.status >= 500)
2142
+ return shouldRetryForOptions();
2143
+ return {
2144
+ retry: false
2145
+ };
2146
+ }
2147
+ __name(shouldRetry, "shouldRetry");
2148
+ function safeJsonParse(text) {
2149
+ try {
2150
+ return JSON.parse(text);
2151
+ } catch (e) {
2152
+ return void 0;
2094
2153
  }
2095
- setGlobalTaskContext(taskContext2) {
2096
- return registerGlobal(API_NAME, taskContext2);
2154
+ }
2155
+ __name(safeJsonParse, "safeJsonParse");
2156
+ function createResponseHeaders(headers) {
2157
+ return new Proxy(Object.fromEntries(
2158
+ // @ts-ignore
2159
+ headers.entries()
2160
+ ), {
2161
+ get(target, name) {
2162
+ const key = name.toString();
2163
+ return target[key.toLowerCase()] || target[key];
2164
+ }
2165
+ });
2166
+ }
2167
+ __name(createResponseHeaders, "createResponseHeaders");
2168
+ function requestInitWithCache(requestInit) {
2169
+ try {
2170
+ const withCache = {
2171
+ ...requestInit,
2172
+ cache: "no-cache"
2173
+ };
2174
+ const _ = new Request("http://localhost", withCache);
2175
+ return withCache;
2176
+ } catch (error) {
2177
+ return requestInit ?? {};
2097
2178
  }
2098
- };
2099
- _getTaskContext = new WeakSet();
2100
- getTaskContext_fn = /* @__PURE__ */ __name(function() {
2101
- return getGlobal(API_NAME);
2102
- }, "#getTaskContext");
2103
- __name(_TaskContextAPI, "TaskContextAPI");
2104
- var TaskContextAPI = _TaskContextAPI;
2105
-
2106
- // src/v3/task-context-api.ts
2107
- var taskContext = TaskContextAPI.getInstance();
2179
+ }
2180
+ __name(requestInitWithCache, "requestInitWithCache");
2181
+ var addFormValue = /* @__PURE__ */ __name(async (form, key, value) => {
2182
+ if (value === void 0)
2183
+ return;
2184
+ if (value == null) {
2185
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
2186
+ }
2187
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
2188
+ form.append(key, String(value));
2189
+ } else if (isUploadable(value) || isBlobLike(value) || value instanceof Buffer || value instanceof ArrayBuffer) {
2190
+ const file = await toFile(value);
2191
+ form.append(key, file);
2192
+ } else if (Array.isArray(value)) {
2193
+ await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
2194
+ } else if (typeof value === "object") {
2195
+ await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
2196
+ } else {
2197
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
2198
+ }
2199
+ }, "addFormValue");
2200
+ async function toFile(value, name, options) {
2201
+ value = await value;
2202
+ options ??= isFileLike(value) ? {
2203
+ lastModified: value.lastModified,
2204
+ type: value.type
2205
+ } : {};
2206
+ if (isResponseLike(value)) {
2207
+ const blob = await value.blob();
2208
+ name ||= new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file";
2209
+ return new File([
2210
+ blob
2211
+ ], name, options);
2212
+ }
2213
+ const bits = await getBytes(value);
2214
+ name ||= getName(value) ?? "unknown_file";
2215
+ if (!options.type) {
2216
+ const type = bits[0]?.type;
2217
+ if (typeof type === "string") {
2218
+ options = {
2219
+ ...options,
2220
+ type
2221
+ };
2222
+ }
2223
+ }
2224
+ return new File(bits, name, options);
2225
+ }
2226
+ __name(toFile, "toFile");
2227
+ function getName(value) {
2228
+ return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream
2229
+ getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop();
2230
+ }
2231
+ __name(getName, "getName");
2232
+ var getStringFromMaybeBuffer = /* @__PURE__ */ __name((x) => {
2233
+ if (typeof x === "string")
2234
+ return x;
2235
+ if (typeof Buffer !== "undefined" && x instanceof Buffer)
2236
+ return String(x);
2237
+ return void 0;
2238
+ }, "getStringFromMaybeBuffer");
2239
+ async function getBytes(value) {
2240
+ let parts = [];
2241
+ if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
2242
+ value instanceof ArrayBuffer) {
2243
+ parts.push(value);
2244
+ } else if (isBlobLike(value)) {
2245
+ parts.push(await value.arrayBuffer());
2246
+ } else if (isAsyncIterableIterator(value)) {
2247
+ for await (const chunk of value) {
2248
+ parts.push(chunk);
2249
+ }
2250
+ } else {
2251
+ throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);
2252
+ }
2253
+ return parts;
2254
+ }
2255
+ __name(getBytes, "getBytes");
2256
+ function propsForError(value) {
2257
+ const props = Object.getOwnPropertyNames(value);
2258
+ return `[${props.map((p) => `"${p}"`).join(", ")}]`;
2259
+ }
2260
+ __name(propsForError, "propsForError");
2261
+ var isAsyncIterableIterator = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterableIterator");
2262
+ var isResponseLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", "isResponseLike");
2263
+ var isFileLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), "isFileLike");
2264
+ 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");
2265
+ var isFsReadStream = /* @__PURE__ */ __name((value) => value instanceof stream.Readable, "isFsReadStream");
2266
+ var isUploadable = /* @__PURE__ */ __name((value) => {
2267
+ return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);
2268
+ }, "isUploadable");
2269
+ 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");
2108
2270
 
2109
2271
  // src/v3/apiClient/index.ts
2110
2272
  var zodFetchOptions = {
@@ -2239,14 +2401,62 @@ var _ApiClient = class _ApiClient {
2239
2401
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2240
2402
  });
2241
2403
  }
2404
+ listEnvVars(projectRef, slug) {
2405
+ return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2406
+ method: "GET",
2407
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2408
+ });
2409
+ }
2410
+ importEnvVars(projectRef, slug, body) {
2411
+ if (isRecordLike(body.variables)) {
2412
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
2413
+ method: "POST",
2414
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2415
+ body: JSON.stringify(body)
2416
+ });
2417
+ } else {
2418
+ return zodupload(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, body, {
2419
+ method: "POST",
2420
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2421
+ });
2422
+ }
2423
+ }
2424
+ retrieveEnvVar(projectRef, slug, key) {
2425
+ return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2426
+ method: "GET",
2427
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2428
+ });
2429
+ }
2430
+ createEnvVar(projectRef, slug, body) {
2431
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2432
+ method: "POST",
2433
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2434
+ body: JSON.stringify(body)
2435
+ });
2436
+ }
2437
+ updateEnvVar(projectRef, slug, key, body) {
2438
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2439
+ method: "PUT",
2440
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2441
+ body: JSON.stringify(body)
2442
+ });
2443
+ }
2444
+ deleteEnvVar(projectRef, slug, key) {
2445
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2446
+ method: "DELETE",
2447
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2448
+ });
2449
+ }
2242
2450
  };
2243
2451
  _getHeaders = new WeakSet();
2244
2452
  getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2245
2453
  const headers = {
2246
2454
  "Content-Type": "application/json",
2247
- Authorization: `Bearer ${this.accessToken}`
2455
+ Authorization: `Bearer ${this.accessToken}`,
2456
+ "trigger-version": version
2248
2457
  };
2249
2458
  if (taskContext.isInsideTask) {
2459
+ headers["x-trigger-worker"] = "true";
2250
2460
  api.propagation.inject(api.context.active(), headers);
2251
2461
  if (spanParentAsLink) {
2252
2462
  headers["x-trigger-span-parent-as-link"] = "1";
@@ -2783,7 +2993,7 @@ var _APIClientManagerAPI = class _APIClientManagerAPI {
2783
2993
  }
2784
2994
  get accessToken() {
2785
2995
  const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2786
- return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY");
2996
+ return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY") ?? getEnvVar("TRIGGER_ACCESS_TOKEN");
2787
2997
  }
2788
2998
  get client() {
2789
2999
  if (!this.baseURL || !this.accessToken) {
@@ -3200,29 +3410,6 @@ function accessoryAttributes(accessory) {
3200
3410
  }
3201
3411
  __name(accessoryAttributes, "accessoryAttributes");
3202
3412
 
3203
- // package.json
3204
- var dependencies = {
3205
- "@google-cloud/precise-date": "^4.0.0",
3206
- "@opentelemetry/api": "^1.8.0",
3207
- "@opentelemetry/api-logs": "^0.48.0",
3208
- "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
3209
- "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
3210
- "@opentelemetry/instrumentation": "^0.49.1",
3211
- "@opentelemetry/resources": "^1.22.0",
3212
- "@opentelemetry/sdk-logs": "^0.49.1",
3213
- "@opentelemetry/sdk-node": "^0.49.1",
3214
- "@opentelemetry/sdk-trace-base": "^1.22.0",
3215
- "@opentelemetry/sdk-trace-node": "^1.22.0",
3216
- "@opentelemetry/semantic-conventions": "^1.22.0",
3217
- "humanize-duration": "^3.27.3",
3218
- superjson: "^2.2.1",
3219
- ulidx: "^2.2.1",
3220
- zod: "3.22.3",
3221
- "zod-error": "1.5.0",
3222
- "zod-validation-error": "^1.5.0",
3223
- "socket.io-client": "4.7.4"
3224
- };
3225
-
3226
3413
  // src/v3/utils/detectDependencyVersion.ts
3227
3414
  function detectDependencyVersion(dependency) {
3228
3415
  return dependencies[dependency];
@@ -3521,11 +3708,16 @@ exports.CoordinatorToProdWorkerMessages = CoordinatorToProdWorkerMessages;
3521
3708
  exports.CreateAuthorizationCodeResponseSchema = CreateAuthorizationCodeResponseSchema;
3522
3709
  exports.CreateBackgroundWorkerRequestBody = CreateBackgroundWorkerRequestBody;
3523
3710
  exports.CreateBackgroundWorkerResponse = CreateBackgroundWorkerResponse;
3711
+ exports.CreateEnvironmentVariableRequestBody = CreateEnvironmentVariableRequestBody;
3524
3712
  exports.CreateScheduleOptions = CreateScheduleOptions;
3525
3713
  exports.CreateUploadPayloadUrlResponseBody = CreateUploadPayloadUrlResponseBody;
3526
3714
  exports.DeletedScheduleObject = DeletedScheduleObject;
3527
3715
  exports.DeploymentErrorData = DeploymentErrorData;
3528
3716
  exports.EnvironmentType = EnvironmentType;
3717
+ exports.EnvironmentVariable = EnvironmentVariable;
3718
+ exports.EnvironmentVariableResponseBody = EnvironmentVariableResponseBody;
3719
+ exports.EnvironmentVariableValue = EnvironmentVariableValue;
3720
+ exports.EnvironmentVariables = EnvironmentVariables;
3529
3721
  exports.EventFilter = EventFilter;
3530
3722
  exports.ExceptionEventProperties = ExceptionEventProperties;
3531
3723
  exports.ExceptionSpanEvent = ExceptionSpanEvent;
@@ -3546,6 +3738,7 @@ exports.GetProjectEnvResponse = GetProjectEnvResponse;
3546
3738
  exports.GetProjectResponseBody = GetProjectResponseBody;
3547
3739
  exports.GetProjectsResponseBody = GetProjectsResponseBody;
3548
3740
  exports.ImageDetailsMetadata = ImageDetailsMetadata;
3741
+ exports.ImportEnvironmentVariablesRequestBody = ImportEnvironmentVariablesRequestBody;
3549
3742
  exports.InitializeDeploymentRequestBody = InitializeDeploymentRequestBody;
3550
3743
  exports.InitializeDeploymentResponseBody = InitializeDeploymentResponseBody;
3551
3744
  exports.InternalServerError = InternalServerError;
@@ -3628,6 +3821,7 @@ exports.TriggerTaskResponse = TriggerTaskResponse;
3628
3821
  exports.TriggerTracer = TriggerTracer;
3629
3822
  exports.UncaughtExceptionMessage = UncaughtExceptionMessage;
3630
3823
  exports.UnprocessableEntityError = UnprocessableEntityError;
3824
+ exports.UpdateEnvironmentVariableRequestBody = UpdateEnvironmentVariableRequestBody;
3631
3825
  exports.UpdateScheduleOptions = UpdateScheduleOptions;
3632
3826
  exports.WaitReason = WaitReason;
3633
3827
  exports.WhoAmIResponseSchema = WhoAmIResponseSchema;