trigger.dev 0.0.0-prerelease-20240219135254

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/index.js ADDED
@@ -0,0 +1,3106 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'module';const require = createRequire(import.meta.url);
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined")
13
+ return require.apply(this, arguments);
14
+ throw Error('Dynamic require of "' + x + '" is not supported');
15
+ });
16
+ var __commonJS = (cb, mod) => function __require2() {
17
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
+ };
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, { get: all[name], enumerable: true });
22
+ };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (let key of __getOwnPropNames(from))
26
+ if (!__hasOwnProp.call(to, key) && key !== except)
27
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
+ }
29
+ return to;
30
+ };
31
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
32
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
33
+ // If the importer is in node compatibility mode or this is not an ESM
34
+ // file that has been converted to a CommonJS file using a Babel-
35
+ // compatible transform (i.e. "__esModule" has not been set), then set
36
+ // "default" to the CommonJS "module.exports" for node compatibility.
37
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
+ mod
39
+ ));
40
+
41
+ // ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/lib/XDGAppPaths.js
42
+ var require_XDGAppPaths = __commonJS({
43
+ "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/lib/XDGAppPaths.js"(exports) {
44
+ "use strict";
45
+ exports.__esModule = true;
46
+ exports.Adapt = void 0;
47
+ function isBoolean(t) {
48
+ return typeOf(t) === "boolean";
49
+ }
50
+ function isObject(t) {
51
+ return typeOf(t) === "object";
52
+ }
53
+ function isString(t) {
54
+ return typeOf(t) === "string";
55
+ }
56
+ function typeOf(t) {
57
+ return typeof t;
58
+ }
59
+ function Adapt(adapter_) {
60
+ var meta = adapter_.meta, path6 = adapter_.path, xdg = adapter_.xdg;
61
+ var XDGAppPaths_ = /* @__PURE__ */ function() {
62
+ function XDGAppPaths_2(options_) {
63
+ if (options_ === void 0) {
64
+ options_ = {};
65
+ }
66
+ var _a, _b, _c;
67
+ function XDGAppPaths(options2) {
68
+ if (options2 === void 0) {
69
+ options2 = {};
70
+ }
71
+ return new XDGAppPaths_2(options2);
72
+ }
73
+ var options = isObject(options_) ? options_ : { name: options_ };
74
+ var suffix = (_a = options.suffix) !== null && _a !== void 0 ? _a : "";
75
+ var isolated_ = (_b = options.isolated) !== null && _b !== void 0 ? _b : true;
76
+ var namePriorityList = [
77
+ options.name,
78
+ meta.pkgMainFilename(),
79
+ meta.mainFilename()
80
+ ];
81
+ var nameFallback = "$eval";
82
+ var name = path6.parse(((_c = namePriorityList.find(function(e) {
83
+ return isString(e);
84
+ })) !== null && _c !== void 0 ? _c : nameFallback) + suffix).name;
85
+ XDGAppPaths.$name = function $name() {
86
+ return name;
87
+ };
88
+ XDGAppPaths.$isolated = function $isolated() {
89
+ return isolated_;
90
+ };
91
+ function isIsolated(dirOptions) {
92
+ var _a2;
93
+ dirOptions = dirOptions !== null && dirOptions !== void 0 ? dirOptions : { isolated: isolated_ };
94
+ var isolated = isBoolean(dirOptions) ? dirOptions : (_a2 = dirOptions.isolated) !== null && _a2 !== void 0 ? _a2 : isolated_;
95
+ return isolated;
96
+ }
97
+ function finalPathSegment(dirOptions) {
98
+ return isIsolated(dirOptions) ? name : "";
99
+ }
100
+ XDGAppPaths.cache = function cache(dirOptions) {
101
+ return path6.join(xdg.cache(), finalPathSegment(dirOptions));
102
+ };
103
+ XDGAppPaths.config = function config(dirOptions) {
104
+ return path6.join(xdg.config(), finalPathSegment(dirOptions));
105
+ };
106
+ XDGAppPaths.data = function data(dirOptions) {
107
+ return path6.join(xdg.data(), finalPathSegment(dirOptions));
108
+ };
109
+ XDGAppPaths.runtime = function runtime(dirOptions) {
110
+ return xdg.runtime() ? path6.join(xdg.runtime(), finalPathSegment(dirOptions)) : void 0;
111
+ };
112
+ XDGAppPaths.state = function state(dirOptions) {
113
+ return path6.join(xdg.state(), finalPathSegment(dirOptions));
114
+ };
115
+ XDGAppPaths.configDirs = function configDirs(dirOptions) {
116
+ return xdg.configDirs().map(function(s) {
117
+ return path6.join(s, finalPathSegment(dirOptions));
118
+ });
119
+ };
120
+ XDGAppPaths.dataDirs = function dataDirs(dirOptions) {
121
+ return xdg.dataDirs().map(function(s) {
122
+ return path6.join(s, finalPathSegment(dirOptions));
123
+ });
124
+ };
125
+ return XDGAppPaths;
126
+ }
127
+ return XDGAppPaths_2;
128
+ }();
129
+ return { XDGAppPaths: new XDGAppPaths_() };
130
+ }
131
+ exports.Adapt = Adapt;
132
+ }
133
+ });
134
+
135
+ // ../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/lib/XDG.js
136
+ var require_XDG = __commonJS({
137
+ "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/lib/XDG.js"(exports) {
138
+ "use strict";
139
+ var __spreadArray = exports && exports.__spreadArray || function(to, from) {
140
+ for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
141
+ to[j] = from[i];
142
+ return to;
143
+ };
144
+ exports.__esModule = true;
145
+ exports.Adapt = void 0;
146
+ function Adapt(adapter_) {
147
+ var env = adapter_.env, osPaths = adapter_.osPaths, path6 = adapter_.path;
148
+ var isMacOS = /^darwin$/i.test(adapter_.process.platform);
149
+ var isWinOS = /^win/i.test(adapter_.process.platform);
150
+ function baseDir() {
151
+ return osPaths.home() || osPaths.temp();
152
+ }
153
+ function valOrPath(val, pathSegments) {
154
+ return val || path6.join.apply(path6, pathSegments);
155
+ }
156
+ var linux = function() {
157
+ var cache = function() {
158
+ return valOrPath(env.get("XDG_CACHE_HOME"), [baseDir(), ".cache"]);
159
+ };
160
+ var config = function() {
161
+ return valOrPath(env.get("XDG_CONFIG_HOME"), [baseDir(), ".config"]);
162
+ };
163
+ var data = function() {
164
+ return valOrPath(env.get("XDG_DATA_HOME"), [baseDir(), ".local", "share"]);
165
+ };
166
+ var runtime = function() {
167
+ return env.get("XDG_RUNTIME_DIR") || void 0;
168
+ };
169
+ var state = function() {
170
+ return valOrPath(env.get("XDG_STATE_HOME"), [baseDir(), ".local", "state"]);
171
+ };
172
+ return { cache, config, data, runtime, state };
173
+ };
174
+ var macos = function() {
175
+ var cache = function() {
176
+ return valOrPath(env.get("XDG_CACHE_HOME"), [baseDir(), "Library", "Caches"]);
177
+ };
178
+ var config = function() {
179
+ return valOrPath(env.get("XDG_CONFIG_HOME"), [baseDir(), "Library", "Preferences"]);
180
+ };
181
+ var data = function() {
182
+ return valOrPath(env.get("XDG_DATA_HOME"), [baseDir(), "Library", "Application Support"]);
183
+ };
184
+ var runtime = function() {
185
+ return env.get("XDG_RUNTIME_DIR") || void 0;
186
+ };
187
+ var state = function() {
188
+ return valOrPath(env.get("XDG_STATE_HOME"), [baseDir(), "Library", "State"]);
189
+ };
190
+ return { cache, config, data, runtime, state };
191
+ };
192
+ var windows = function() {
193
+ function appData() {
194
+ return valOrPath(env.get("APPDATA"), [baseDir(), "AppData", "Roaming"]);
195
+ }
196
+ function localAppData() {
197
+ return valOrPath(env.get("LOCALAPPDATA"), [baseDir(), "AppData", "Local"]);
198
+ }
199
+ var cache = function() {
200
+ return valOrPath(env.get("XDG_CACHE_HOME"), [localAppData(), "xdg.cache"]);
201
+ };
202
+ var config = function() {
203
+ return valOrPath(env.get("XDG_CONFIG_HOME"), [appData(), "xdg.config"]);
204
+ };
205
+ var data = function() {
206
+ return valOrPath(env.get("XDG_DATA_HOME"), [appData(), "xdg.data"]);
207
+ };
208
+ var runtime = function() {
209
+ return env.get("XDG_RUNTIME_DIR") || void 0;
210
+ };
211
+ var state = function() {
212
+ return valOrPath(env.get("XDG_STATE_HOME"), [localAppData(), "xdg.state"]);
213
+ };
214
+ return { cache, config, data, runtime, state };
215
+ };
216
+ var XDG_ = /* @__PURE__ */ function() {
217
+ function XDG_2() {
218
+ function XDG() {
219
+ return new XDG_2();
220
+ }
221
+ var extension = isMacOS ? macos() : isWinOS ? windows() : linux();
222
+ XDG.cache = extension.cache;
223
+ XDG.config = extension.config;
224
+ XDG.data = extension.data;
225
+ XDG.runtime = extension.runtime;
226
+ XDG.state = extension.state;
227
+ XDG.configDirs = function configDirs() {
228
+ var pathList = env.get("XDG_CONFIG_DIRS");
229
+ return __spreadArray([extension.config()], pathList ? pathList.split(path6.delimiter) : []);
230
+ };
231
+ XDG.dataDirs = function dataDirs() {
232
+ var pathList = env.get("XDG_DATA_DIRS");
233
+ return __spreadArray([extension.data()], pathList ? pathList.split(path6.delimiter) : []);
234
+ };
235
+ return XDG;
236
+ }
237
+ return XDG_2;
238
+ }();
239
+ return { XDG: new XDG_() };
240
+ }
241
+ exports.Adapt = Adapt;
242
+ }
243
+ });
244
+
245
+ // ../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/lib/OSPaths.js
246
+ var require_OSPaths = __commonJS({
247
+ "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/lib/OSPaths.js"(exports) {
248
+ "use strict";
249
+ var __spreadArray = exports && exports.__spreadArray || function(to, from) {
250
+ for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
251
+ to[j] = from[i];
252
+ return to;
253
+ };
254
+ exports.__esModule = true;
255
+ exports.Adapt = void 0;
256
+ function isEmpty(s) {
257
+ return !s;
258
+ }
259
+ function Adapt(adapter_) {
260
+ var env = adapter_.env, os2 = adapter_.os, path6 = adapter_.path;
261
+ var isWinOS = /^win/i.test(adapter_.process.platform);
262
+ function normalizePath(path_) {
263
+ return path_ ? adapter_.path.normalize(adapter_.path.join(path_, ".")) : void 0;
264
+ }
265
+ function home() {
266
+ var posix = function() {
267
+ return normalizePath((typeof os2.homedir === "function" ? os2.homedir() : void 0) || env.get("HOME"));
268
+ };
269
+ var windows = function() {
270
+ var priorityList = [
271
+ typeof os2.homedir === "function" ? os2.homedir() : void 0,
272
+ env.get("USERPROFILE"),
273
+ env.get("HOME"),
274
+ env.get("HOMEDRIVE") || env.get("HOMEPATH") ? path6.join(env.get("HOMEDRIVE") || "", env.get("HOMEPATH") || "") : void 0
275
+ ];
276
+ return normalizePath(priorityList.find(function(v) {
277
+ return !isEmpty(v);
278
+ }));
279
+ };
280
+ return isWinOS ? windows() : posix();
281
+ }
282
+ function temp() {
283
+ function joinPathToBase(base, segments) {
284
+ return base ? path6.join.apply(path6, __spreadArray([base], segments)) : void 0;
285
+ }
286
+ function posix() {
287
+ var fallback = "/tmp";
288
+ var priorityList = [
289
+ typeof os2.tmpdir === "function" ? os2.tmpdir() : void 0,
290
+ env.get("TMPDIR"),
291
+ env.get("TEMP"),
292
+ env.get("TMP")
293
+ ];
294
+ return normalizePath(priorityList.find(function(v) {
295
+ return !isEmpty(v);
296
+ })) || fallback;
297
+ }
298
+ function windows() {
299
+ var fallback = "C:\\Temp";
300
+ var priorityListLazy = [
301
+ typeof os2.tmpdir === "function" ? os2.tmpdir : function() {
302
+ return void 0;
303
+ },
304
+ function() {
305
+ return env.get("TEMP");
306
+ },
307
+ function() {
308
+ return env.get("TMP");
309
+ },
310
+ function() {
311
+ return joinPathToBase(env.get("LOCALAPPDATA"), ["Temp"]);
312
+ },
313
+ function() {
314
+ return joinPathToBase(home(), ["AppData", "Local", "Temp"]);
315
+ },
316
+ function() {
317
+ return joinPathToBase(env.get("ALLUSERSPROFILE"), ["Temp"]);
318
+ },
319
+ function() {
320
+ return joinPathToBase(env.get("SystemRoot"), ["Temp"]);
321
+ },
322
+ function() {
323
+ return joinPathToBase(env.get("windir"), ["Temp"]);
324
+ },
325
+ function() {
326
+ return joinPathToBase(env.get("SystemDrive"), ["\\", "Temp"]);
327
+ }
328
+ ];
329
+ var v = priorityListLazy.find(function(v2) {
330
+ return v2 && !isEmpty(v2());
331
+ });
332
+ return v && normalizePath(v()) || fallback;
333
+ }
334
+ return isWinOS ? windows() : posix();
335
+ }
336
+ var OSPaths_ = /* @__PURE__ */ function() {
337
+ function OSPaths_2() {
338
+ function OSPaths() {
339
+ return new OSPaths_2();
340
+ }
341
+ OSPaths.home = home;
342
+ OSPaths.temp = temp;
343
+ return OSPaths;
344
+ }
345
+ return OSPaths_2;
346
+ }();
347
+ return { OSPaths: new OSPaths_() };
348
+ }
349
+ exports.Adapt = Adapt;
350
+ }
351
+ });
352
+
353
+ // ../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/platform-adapters/node.js
354
+ var require_node = __commonJS({
355
+ "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/platform-adapters/node.js"(exports) {
356
+ "use strict";
357
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
358
+ if (k2 === void 0)
359
+ k2 = k;
360
+ Object.defineProperty(o, k2, { enumerable: true, get: function() {
361
+ return m[k];
362
+ } });
363
+ } : function(o, m, k, k2) {
364
+ if (k2 === void 0)
365
+ k2 = k;
366
+ o[k2] = m[k];
367
+ });
368
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
369
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
370
+ } : function(o, v) {
371
+ o["default"] = v;
372
+ });
373
+ var __importStar = exports && exports.__importStar || function(mod) {
374
+ if (mod && mod.__esModule)
375
+ return mod;
376
+ var result = {};
377
+ if (mod != null) {
378
+ for (var k in mod)
379
+ if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
380
+ __createBinding(result, mod, k);
381
+ }
382
+ __setModuleDefault(result, mod);
383
+ return result;
384
+ };
385
+ exports.__esModule = true;
386
+ exports.adapter = void 0;
387
+ var os2 = __importStar(__require("os"));
388
+ var path6 = __importStar(__require("path"));
389
+ exports.adapter = {
390
+ atImportPermissions: { env: true },
391
+ env: {
392
+ get: function(s) {
393
+ return process.env[s];
394
+ }
395
+ },
396
+ os: os2,
397
+ path: path6,
398
+ process
399
+ };
400
+ }
401
+ });
402
+
403
+ // ../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/mod.cjs.js
404
+ var require_mod_cjs = __commonJS({
405
+ "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/mod.cjs.js"(exports, module) {
406
+ "use strict";
407
+ var OSPaths_js_1 = require_OSPaths();
408
+ var node_js_1 = require_node();
409
+ module.exports = OSPaths_js_1.Adapt(node_js_1.adapter).OSPaths;
410
+ }
411
+ });
412
+
413
+ // ../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/platform-adapters/node.js
414
+ var require_node2 = __commonJS({
415
+ "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/platform-adapters/node.js"(exports) {
416
+ "use strict";
417
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
418
+ if (k2 === void 0)
419
+ k2 = k;
420
+ Object.defineProperty(o, k2, { enumerable: true, get: function() {
421
+ return m[k];
422
+ } });
423
+ } : function(o, m, k, k2) {
424
+ if (k2 === void 0)
425
+ k2 = k;
426
+ o[k2] = m[k];
427
+ });
428
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
429
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
430
+ } : function(o, v) {
431
+ o["default"] = v;
432
+ });
433
+ var __importStar = exports && exports.__importStar || function(mod) {
434
+ if (mod && mod.__esModule)
435
+ return mod;
436
+ var result = {};
437
+ if (mod != null) {
438
+ for (var k in mod)
439
+ if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
440
+ __createBinding(result, mod, k);
441
+ }
442
+ __setModuleDefault(result, mod);
443
+ return result;
444
+ };
445
+ var __importDefault = exports && exports.__importDefault || function(mod) {
446
+ return mod && mod.__esModule ? mod : { "default": mod };
447
+ };
448
+ exports.__esModule = true;
449
+ exports.adapter = void 0;
450
+ var path6 = __importStar(__require("path"));
451
+ var os_paths_1 = __importDefault(require_mod_cjs());
452
+ exports.adapter = {
453
+ atImportPermissions: { env: true },
454
+ env: {
455
+ get: function(s) {
456
+ return process.env[s];
457
+ }
458
+ },
459
+ osPaths: os_paths_1["default"],
460
+ path: path6,
461
+ process
462
+ };
463
+ }
464
+ });
465
+
466
+ // ../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/mod.cjs.js
467
+ var require_mod_cjs2 = __commonJS({
468
+ "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/mod.cjs.js"(exports, module) {
469
+ "use strict";
470
+ var XDG_js_1 = require_XDG();
471
+ var node_js_1 = require_node2();
472
+ module.exports = XDG_js_1.Adapt(node_js_1.adapter).XDG;
473
+ }
474
+ });
475
+
476
+ // ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/platform-adapters/node.js
477
+ var require_node3 = __commonJS({
478
+ "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/platform-adapters/node.js"(exports) {
479
+ "use strict";
480
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
481
+ if (k2 === void 0)
482
+ k2 = k;
483
+ Object.defineProperty(o, k2, { enumerable: true, get: function() {
484
+ return m[k];
485
+ } });
486
+ } : function(o, m, k, k2) {
487
+ if (k2 === void 0)
488
+ k2 = k;
489
+ o[k2] = m[k];
490
+ });
491
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
492
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
493
+ } : function(o, v) {
494
+ o["default"] = v;
495
+ });
496
+ var __importStar = exports && exports.__importStar || function(mod) {
497
+ if (mod && mod.__esModule)
498
+ return mod;
499
+ var result = {};
500
+ if (mod != null) {
501
+ for (var k in mod)
502
+ if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
503
+ __createBinding(result, mod, k);
504
+ }
505
+ __setModuleDefault(result, mod);
506
+ return result;
507
+ };
508
+ var __importDefault = exports && exports.__importDefault || function(mod) {
509
+ return mod && mod.__esModule ? mod : { "default": mod };
510
+ };
511
+ exports.__esModule = true;
512
+ exports.adapter = void 0;
513
+ var path6 = __importStar(__require("path"));
514
+ var xdg_portable_1 = __importDefault(require_mod_cjs2());
515
+ exports.adapter = {
516
+ atImportPermissions: { env: true, read: true },
517
+ meta: {
518
+ mainFilename: function() {
519
+ var requireMain = typeof __require !== "undefined" && __require !== null && __require.main ? __require.main : { filename: void 0 };
520
+ var requireMainFilename = requireMain.filename;
521
+ var filename = (requireMainFilename !== process.execArgv[0] ? requireMainFilename : void 0) || (typeof process._eval === "undefined" ? process.argv[1] : void 0);
522
+ return filename;
523
+ },
524
+ pkgMainFilename: function() {
525
+ return process.pkg ? process.execPath : void 0;
526
+ }
527
+ },
528
+ path: path6,
529
+ process,
530
+ xdg: xdg_portable_1["default"]
531
+ };
532
+ }
533
+ });
534
+
535
+ // ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/mod.cjs.js
536
+ var require_mod_cjs3 = __commonJS({
537
+ "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/mod.cjs.js"(exports, module) {
538
+ "use strict";
539
+ var XDGAppPaths_js_1 = require_XDGAppPaths();
540
+ var node_js_1 = require_node3();
541
+ module.exports = XDGAppPaths_js_1.Adapt(node_js_1.adapter).XDGAppPaths;
542
+ }
543
+ });
544
+
545
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js
546
+ var require_retry_operation = __commonJS({
547
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module) {
548
+ "use strict";
549
+ function RetryOperation(timeouts, options) {
550
+ if (typeof options === "boolean") {
551
+ options = { forever: options };
552
+ }
553
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
554
+ this._timeouts = timeouts;
555
+ this._options = options || {};
556
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
557
+ this._fn = null;
558
+ this._errors = [];
559
+ this._attempts = 1;
560
+ this._operationTimeout = null;
561
+ this._operationTimeoutCb = null;
562
+ this._timeout = null;
563
+ this._operationStart = null;
564
+ this._timer = null;
565
+ if (this._options.forever) {
566
+ this._cachedTimeouts = this._timeouts.slice(0);
567
+ }
568
+ }
569
+ module.exports = RetryOperation;
570
+ RetryOperation.prototype.reset = function() {
571
+ this._attempts = 1;
572
+ this._timeouts = this._originalTimeouts.slice(0);
573
+ };
574
+ RetryOperation.prototype.stop = function() {
575
+ if (this._timeout) {
576
+ clearTimeout(this._timeout);
577
+ }
578
+ if (this._timer) {
579
+ clearTimeout(this._timer);
580
+ }
581
+ this._timeouts = [];
582
+ this._cachedTimeouts = null;
583
+ };
584
+ RetryOperation.prototype.retry = function(err) {
585
+ if (this._timeout) {
586
+ clearTimeout(this._timeout);
587
+ }
588
+ if (!err) {
589
+ return false;
590
+ }
591
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
592
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
593
+ this._errors.push(err);
594
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
595
+ return false;
596
+ }
597
+ this._errors.push(err);
598
+ var timeout = this._timeouts.shift();
599
+ if (timeout === void 0) {
600
+ if (this._cachedTimeouts) {
601
+ this._errors.splice(0, this._errors.length - 1);
602
+ timeout = this._cachedTimeouts.slice(-1);
603
+ } else {
604
+ return false;
605
+ }
606
+ }
607
+ var self = this;
608
+ this._timer = setTimeout(function() {
609
+ self._attempts++;
610
+ if (self._operationTimeoutCb) {
611
+ self._timeout = setTimeout(function() {
612
+ self._operationTimeoutCb(self._attempts);
613
+ }, self._operationTimeout);
614
+ if (self._options.unref) {
615
+ self._timeout.unref();
616
+ }
617
+ }
618
+ self._fn(self._attempts);
619
+ }, timeout);
620
+ if (this._options.unref) {
621
+ this._timer.unref();
622
+ }
623
+ return true;
624
+ };
625
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
626
+ this._fn = fn;
627
+ if (timeoutOps) {
628
+ if (timeoutOps.timeout) {
629
+ this._operationTimeout = timeoutOps.timeout;
630
+ }
631
+ if (timeoutOps.cb) {
632
+ this._operationTimeoutCb = timeoutOps.cb;
633
+ }
634
+ }
635
+ var self = this;
636
+ if (this._operationTimeoutCb) {
637
+ this._timeout = setTimeout(function() {
638
+ self._operationTimeoutCb();
639
+ }, self._operationTimeout);
640
+ }
641
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
642
+ this._fn(this._attempts);
643
+ };
644
+ RetryOperation.prototype.try = function(fn) {
645
+ console.log("Using RetryOperation.try() is deprecated");
646
+ this.attempt(fn);
647
+ };
648
+ RetryOperation.prototype.start = function(fn) {
649
+ console.log("Using RetryOperation.start() is deprecated");
650
+ this.attempt(fn);
651
+ };
652
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
653
+ RetryOperation.prototype.errors = function() {
654
+ return this._errors;
655
+ };
656
+ RetryOperation.prototype.attempts = function() {
657
+ return this._attempts;
658
+ };
659
+ RetryOperation.prototype.mainError = function() {
660
+ if (this._errors.length === 0) {
661
+ return null;
662
+ }
663
+ var counts = {};
664
+ var mainError = null;
665
+ var mainErrorCount = 0;
666
+ for (var i = 0; i < this._errors.length; i++) {
667
+ var error = this._errors[i];
668
+ var message = error.message;
669
+ var count = (counts[message] || 0) + 1;
670
+ counts[message] = count;
671
+ if (count >= mainErrorCount) {
672
+ mainError = error;
673
+ mainErrorCount = count;
674
+ }
675
+ }
676
+ return mainError;
677
+ };
678
+ }
679
+ });
680
+
681
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js
682
+ var require_retry = __commonJS({
683
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) {
684
+ "use strict";
685
+ var RetryOperation = require_retry_operation();
686
+ exports.operation = function(options) {
687
+ var timeouts = exports.timeouts(options);
688
+ return new RetryOperation(timeouts, {
689
+ forever: options && (options.forever || options.retries === Infinity),
690
+ unref: options && options.unref,
691
+ maxRetryTime: options && options.maxRetryTime
692
+ });
693
+ };
694
+ exports.timeouts = function(options) {
695
+ if (options instanceof Array) {
696
+ return [].concat(options);
697
+ }
698
+ var opts = {
699
+ retries: 10,
700
+ factor: 2,
701
+ minTimeout: 1 * 1e3,
702
+ maxTimeout: Infinity,
703
+ randomize: false
704
+ };
705
+ for (var key in options) {
706
+ opts[key] = options[key];
707
+ }
708
+ if (opts.minTimeout > opts.maxTimeout) {
709
+ throw new Error("minTimeout is greater than maxTimeout");
710
+ }
711
+ var timeouts = [];
712
+ for (var i = 0; i < opts.retries; i++) {
713
+ timeouts.push(this.createTimeout(i, opts));
714
+ }
715
+ if (options && options.forever && !timeouts.length) {
716
+ timeouts.push(this.createTimeout(i, opts));
717
+ }
718
+ timeouts.sort(function(a, b) {
719
+ return a - b;
720
+ });
721
+ return timeouts;
722
+ };
723
+ exports.createTimeout = function(attempt, opts) {
724
+ var random = opts.randomize ? Math.random() + 1 : 1;
725
+ var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
726
+ timeout = Math.min(timeout, opts.maxTimeout);
727
+ return timeout;
728
+ };
729
+ exports.wrap = function(obj, options, methods) {
730
+ if (options instanceof Array) {
731
+ methods = options;
732
+ options = null;
733
+ }
734
+ if (!methods) {
735
+ methods = [];
736
+ for (var key in obj) {
737
+ if (typeof obj[key] === "function") {
738
+ methods.push(key);
739
+ }
740
+ }
741
+ }
742
+ for (var i = 0; i < methods.length; i++) {
743
+ var method = methods[i];
744
+ var original = obj[method];
745
+ obj[method] = function retryWrapper(original2) {
746
+ var op = exports.operation(options);
747
+ var args = Array.prototype.slice.call(arguments, 1);
748
+ var callback = args.pop();
749
+ args.push(function(err) {
750
+ if (op.retry(err)) {
751
+ return;
752
+ }
753
+ if (err) {
754
+ arguments[0] = op.mainError();
755
+ }
756
+ callback.apply(this, arguments);
757
+ });
758
+ op.attempt(function() {
759
+ original2.apply(obj, args);
760
+ });
761
+ }.bind(obj, original);
762
+ obj[method].options = options;
763
+ }
764
+ };
765
+ }
766
+ });
767
+
768
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js
769
+ var require_retry2 = __commonJS({
770
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module) {
771
+ "use strict";
772
+ module.exports = require_retry();
773
+ }
774
+ });
775
+
776
+ // src/cli/index.ts
777
+ import { Command } from "commander";
778
+ import { z as z5 } from "zod";
779
+
780
+ // src/commands/dev.tsx
781
+ import {
782
+ ZodMessageHandler as ZodMessageHandler2,
783
+ ZodMessageSender as ZodMessageSender2,
784
+ clientWebsocketMessages,
785
+ serverWebsocketMessages
786
+ } from "@trigger.dev/core/v3";
787
+ import chalk5 from "chalk";
788
+ import { watch } from "chokidar";
789
+ import { context } from "esbuild";
790
+ import { findUp } from "find-up";
791
+ import { resolve as importResolve } from "import-meta-resolve";
792
+ import { Box, Text, render, useApp, useInput } from "ink";
793
+ import { createHash } from "node:crypto";
794
+ import fs, { readFileSync as readFileSync2 } from "node:fs";
795
+ import { basename, dirname, join, relative, resolve } from "node:path";
796
+ import { pathToFileURL } from "node:url";
797
+ import pThrottle from "p-throttle";
798
+ import { WebSocket } from "partysocket";
799
+ import React, { Suspense, useEffect } from "react";
800
+ import { WebSocket as wsWebSocket } from "ws";
801
+ import { z as z3 } from "zod";
802
+
803
+ // package.json
804
+ var version = "0.0.0-prerelease-20240219135254";
805
+ var package_default = {
806
+ name: "trigger.dev",
807
+ version,
808
+ description: "A Command-Line Interface for Trigger.dev (v3) projects",
809
+ main: "./dist/index.js",
810
+ types: "./dist/index.d.ts",
811
+ license: "MIT",
812
+ repository: {
813
+ type: "git",
814
+ url: "https://github.com/triggerdotdev/trigger.dev.git",
815
+ directory: "packages/cli-v3"
816
+ },
817
+ publishConfig: {
818
+ access: "public"
819
+ },
820
+ keywords: [
821
+ "typescript",
822
+ "trigger.dev",
823
+ "workflows",
824
+ "orchestration",
825
+ "events",
826
+ "webhooks",
827
+ "integrations",
828
+ "apis",
829
+ "jobs",
830
+ "background jobs",
831
+ "nextjs"
832
+ ],
833
+ files: [
834
+ "dist"
835
+ ],
836
+ type: "module",
837
+ exports: "./dist/index.js",
838
+ bin: {
839
+ "trigger.dev": "./dist/index.js"
840
+ },
841
+ devDependencies: {
842
+ "@trigger.dev/core": "workspace:*",
843
+ "@trigger.dev/tsconfig": "workspace:*",
844
+ "@types/gradient-string": "^1.1.2",
845
+ "@types/mock-fs": "^4.13.1",
846
+ "@types/node": "18",
847
+ "@types/object-hash": "^3.0.6",
848
+ "@types/react": "^18.2.48",
849
+ "@types/ws": "^8.5.3",
850
+ "npm-run-all": "^4.1.5",
851
+ open: "^10.0.3",
852
+ "p-retry": "^6.1.0",
853
+ rimraf: "^3.0.2",
854
+ tsup: "^8.0.1",
855
+ "type-fest": "^3.6.0",
856
+ typescript: "^5.3.3",
857
+ vitest: "^0.34.4",
858
+ "xdg-app-paths": "^8.3.0"
859
+ },
860
+ scripts: {
861
+ typecheck: "tsc",
862
+ build: "npm run clean && run-p build:**",
863
+ "build:main": "tsup",
864
+ "build:facade": "tsup --config tsup.facade.config.ts",
865
+ dev: "npm run clean && run-p dev:**",
866
+ "dev:main": "tsup --watch",
867
+ "dev:facade": "tsup --config tsup.facade.config.ts --watch",
868
+ clean: "rimraf dist",
869
+ start: "node dist/index.js",
870
+ test: "vitest"
871
+ },
872
+ dependencies: {
873
+ "@clack/prompts": "^0.7.0",
874
+ "@opentelemetry/api": "^1.7.0",
875
+ "@opentelemetry/api-logs": "^0.48.0",
876
+ "@opentelemetry/auto-instrumentations-node": "^0.40.3",
877
+ "@opentelemetry/exporter-collector": "^0.25.0",
878
+ "@opentelemetry/exporter-logs-otlp-http": "^0.48.0",
879
+ "@opentelemetry/exporter-trace-otlp-http": "^0.48.0",
880
+ "@opentelemetry/instrumentation": "^0.48.0",
881
+ "@opentelemetry/instrumentation-fetch": "^0.48.0",
882
+ "@opentelemetry/instrumentation-http": "^0.48.0",
883
+ "@opentelemetry/resources": "^1.21.0",
884
+ "@opentelemetry/sdk-logs": "^0.48.0",
885
+ "@opentelemetry/sdk-node": "^0.48.0",
886
+ "@opentelemetry/sdk-trace-base": "^1.21.0",
887
+ "@opentelemetry/sdk-trace-node": "^1.21.0",
888
+ "@opentelemetry/semantic-conventions": "^1.21.0",
889
+ "@trigger.dev/core": "workspace:*",
890
+ "@types/degit": "^2.8.3",
891
+ chalk: "^5.2.0",
892
+ chokidar: "^3.5.3",
893
+ "cli-table3": "^0.6.3",
894
+ commander: "^9.4.1",
895
+ degit: "^2.8.4",
896
+ dotenv: "^16.3.1",
897
+ esbuild: "^0.19.11",
898
+ evt: "^2.4.13",
899
+ execa: "^7.0.0",
900
+ "find-up": "^7.0.0",
901
+ "gradient-string": "^2.0.2",
902
+ "import-meta-resolve": "^4.0.0",
903
+ ink: "^4.4.1",
904
+ liquidjs: "^10.9.2",
905
+ "mock-fs": "^5.2.0",
906
+ nanoid: "^4.0.2",
907
+ "node-fetch": "^3.3.0",
908
+ "npm-check-updates": "^16.12.2",
909
+ "object-hash": "^3.0.0",
910
+ "p-throttle": "^6.1.0",
911
+ partysocket: "^0.0.17",
912
+ "posthog-node": "^3.1.1",
913
+ "proxy-agent": "^6.3.0",
914
+ react: "^18.2.0",
915
+ "react-error-boundary": "^4.0.12",
916
+ "simple-git": "^3.19.0",
917
+ "source-map": "^0.7.4",
918
+ "supports-color": "^9.4.0",
919
+ "terminal-link": "^3.0.0",
920
+ "update-check": "^1.5.4",
921
+ url: "^0.11.1",
922
+ ws: "^8.12.0",
923
+ zod: "3.22.3"
924
+ },
925
+ engines: {
926
+ node: ">=18.0.0"
927
+ }
928
+ };
929
+
930
+ // src/apiClient.ts
931
+ import {
932
+ CreateAuthorizationCodeResponseSchema,
933
+ GetPersonalAccessTokenResponseSchema,
934
+ GetProjectDevResponse,
935
+ WhoAmIResponseSchema,
936
+ CreateBackgroundWorkerResponse
937
+ } from "@trigger.dev/core/v3";
938
+ var ApiClient = class {
939
+ constructor(apiURL, accessToken) {
940
+ this.apiURL = apiURL;
941
+ this.accessToken = accessToken;
942
+ }
943
+ async createAuthorizationCode() {
944
+ return zodfetch(
945
+ CreateAuthorizationCodeResponseSchema,
946
+ `${this.apiURL}/api/v1/authorization-code`,
947
+ {
948
+ method: "POST"
949
+ }
950
+ );
951
+ }
952
+ async getPersonalAccessToken(authorizationCode) {
953
+ return zodfetch(GetPersonalAccessTokenResponseSchema, `${this.apiURL}/api/v1/token`, {
954
+ method: "POST",
955
+ body: JSON.stringify({
956
+ authorizationCode
957
+ })
958
+ });
959
+ }
960
+ async whoAmI() {
961
+ if (!this.accessToken) {
962
+ throw new Error("whoAmI: No access token");
963
+ }
964
+ return zodfetch(WhoAmIResponseSchema, `${this.apiURL}/api/v2/whoami`, {
965
+ headers: {
966
+ Authorization: `Bearer ${this.accessToken}`,
967
+ "Content-Type": "application/json"
968
+ }
969
+ });
970
+ }
971
+ async createBackgroundWorker(projectRef, body) {
972
+ if (!this.accessToken) {
973
+ throw new Error("indexProject: No access token");
974
+ }
975
+ return zodfetch(
976
+ CreateBackgroundWorkerResponse,
977
+ `${this.apiURL}/api/v1/projects/${projectRef}/background-workers`,
978
+ {
979
+ method: "POST",
980
+ headers: {
981
+ Authorization: `Bearer ${this.accessToken}`,
982
+ "Content-Type": "application/json"
983
+ },
984
+ body: JSON.stringify(body)
985
+ }
986
+ );
987
+ }
988
+ async getProjectDevEnv({ projectRef }) {
989
+ if (!this.accessToken) {
990
+ throw new Error("getProjectDevEnv: No access token");
991
+ }
992
+ return zodfetch(GetProjectDevResponse, `${this.apiURL}/api/v1/projects/${projectRef}/dev`, {
993
+ headers: {
994
+ Authorization: `Bearer ${this.accessToken}`,
995
+ "Content-Type": "application/json"
996
+ }
997
+ });
998
+ }
999
+ };
1000
+ async function zodfetch(schema, url, requestInit) {
1001
+ try {
1002
+ const response = await fetch(url, requestInit);
1003
+ if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
1004
+ return {
1005
+ success: false,
1006
+ error: `404: ${response.statusText}`
1007
+ };
1008
+ }
1009
+ if (response.status >= 400 && response.status < 500) {
1010
+ const body = await response.json();
1011
+ if (!body.error) {
1012
+ return { success: false, error: "Something went wrong" };
1013
+ }
1014
+ return { success: false, error: body.error };
1015
+ }
1016
+ if (response.status !== 200) {
1017
+ return {
1018
+ success: false,
1019
+ error: `Failed to fetch ${url}, got status code ${response.status}`
1020
+ };
1021
+ }
1022
+ const jsonBody = await response.json();
1023
+ const parsedResult = schema.safeParse(jsonBody);
1024
+ if (parsedResult.success) {
1025
+ return { success: true, data: parsedResult.data };
1026
+ }
1027
+ if ("error" in jsonBody) {
1028
+ return {
1029
+ success: false,
1030
+ error: typeof jsonBody.error === "string" ? jsonBody.error : JSON.stringify(jsonBody.error)
1031
+ };
1032
+ }
1033
+ return { success: false, error: parsedResult.error.message };
1034
+ } catch (error) {
1035
+ return {
1036
+ success: false,
1037
+ error: error instanceof Error ? error.message : JSON.stringify(error)
1038
+ };
1039
+ }
1040
+ }
1041
+
1042
+ // src/consts.ts
1043
+ import path from "path";
1044
+ import { fileURLToPath } from "url";
1045
+ var __filename = fileURLToPath(import.meta.url);
1046
+ var distPath = path.dirname(__filename);
1047
+ var PKG_ROOT = path.join(distPath, "../");
1048
+ var COMMAND_NAME = "trigger.dev";
1049
+ var CLOUD_API_URL = "https://api.trigger.dev";
1050
+
1051
+ // src/dev/backgroundWorker.ts
1052
+ import {
1053
+ ZodMessageHandler,
1054
+ ZodMessageSender,
1055
+ childToWorkerMessages,
1056
+ workerToChildMessages
1057
+ } from "@trigger.dev/core/v3";
1058
+ import chalk2 from "chalk";
1059
+ import { Evt } from "evt";
1060
+ import { fork } from "node:child_process";
1061
+ import { readFileSync } from "node:fs";
1062
+ import nodePath from "node:path";
1063
+ import { SourceMapConsumer } from "source-map";
1064
+ import terminalLink from "terminal-link";
1065
+
1066
+ // src/utilities/logger.ts
1067
+ import { format } from "node:util";
1068
+ import chalk from "chalk";
1069
+ import CLITable from "cli-table3";
1070
+ import { formatMessagesSync } from "esbuild";
1071
+
1072
+ // src/utilities/getEnvironmentVariableFactory.ts
1073
+ function getEnvironmentVariableFactory({
1074
+ variableName,
1075
+ deprecatedName,
1076
+ defaultValue
1077
+ }) {
1078
+ let hasWarned = false;
1079
+ return () => {
1080
+ if (process.env[variableName]) {
1081
+ return process.env[variableName];
1082
+ } else if (deprecatedName && process.env[deprecatedName]) {
1083
+ if (!hasWarned) {
1084
+ hasWarned = true;
1085
+ logger.warn(
1086
+ `Using "${deprecatedName}" environment variable. This is deprecated. Please use "${variableName}", instead.`
1087
+ );
1088
+ }
1089
+ return process.env[deprecatedName];
1090
+ } else {
1091
+ return defaultValue?.();
1092
+ }
1093
+ };
1094
+ }
1095
+
1096
+ // src/utilities/logger.ts
1097
+ var LOGGER_LEVELS = {
1098
+ none: -1,
1099
+ error: 0,
1100
+ warn: 1,
1101
+ info: 2,
1102
+ log: 3,
1103
+ debug: 4
1104
+ };
1105
+ var LOGGER_LEVEL_FORMAT_TYPE_MAP = {
1106
+ error: "error",
1107
+ warn: "warning",
1108
+ info: void 0,
1109
+ log: void 0,
1110
+ debug: void 0
1111
+ };
1112
+ var getLogLevelFromEnv = getEnvironmentVariableFactory({
1113
+ variableName: "TRIGGER_LOG_LEVEL"
1114
+ });
1115
+ function getLoggerLevel() {
1116
+ const fromEnv = getLogLevelFromEnv()?.toLowerCase();
1117
+ if (fromEnv !== void 0) {
1118
+ if (fromEnv in LOGGER_LEVELS)
1119
+ return fromEnv;
1120
+ const expected = Object.keys(LOGGER_LEVELS).map((level) => `"${level}"`).join(" | ");
1121
+ console.warn(
1122
+ `Unrecognised WRANGLER_LOG value ${JSON.stringify(
1123
+ fromEnv
1124
+ )}, expected ${expected}, defaulting to "log"...`
1125
+ );
1126
+ }
1127
+ return "log";
1128
+ }
1129
+ var Logger = class {
1130
+ constructor() {
1131
+ }
1132
+ loggerLevel = getLoggerLevel();
1133
+ columns = process.stdout.columns;
1134
+ debug = (...args) => this.doLog("debug", args);
1135
+ debugWithSanitization = (label, ...args) => {
1136
+ this.doLog("debug", [label, ...args]);
1137
+ };
1138
+ info = (...args) => this.doLog("info", args);
1139
+ log = (...args) => this.doLog("log", args);
1140
+ warn = (...args) => this.doLog("warn", args);
1141
+ error = (...args) => this.doLog("error", args);
1142
+ table(data) {
1143
+ const keys = data.length === 0 ? [] : Object.keys(data[0]);
1144
+ const t = new CLITable({
1145
+ head: keys,
1146
+ style: {
1147
+ head: chalk.level ? ["blue"] : [],
1148
+ border: chalk.level ? ["gray"] : []
1149
+ }
1150
+ });
1151
+ t.push(...data.map((row) => keys.map((k) => row[k])));
1152
+ return this.doLog("log", [t.toString()]);
1153
+ }
1154
+ doLog(messageLevel, args) {
1155
+ const message = this.formatMessage(messageLevel, format(...args));
1156
+ if (LOGGER_LEVELS[this.loggerLevel] >= LOGGER_LEVELS[messageLevel]) {
1157
+ console[messageLevel](message);
1158
+ }
1159
+ }
1160
+ formatMessage(level, message) {
1161
+ const kind = LOGGER_LEVEL_FORMAT_TYPE_MAP[level];
1162
+ if (kind) {
1163
+ const [firstLine, ...otherLines] = message.split("\n");
1164
+ const notes = otherLines.length > 0 ? otherLines.map((text) => ({ text })) : void 0;
1165
+ return formatMessagesSync([{ text: firstLine, notes }], {
1166
+ color: true,
1167
+ kind,
1168
+ terminalWidth: this.columns
1169
+ })[0];
1170
+ } else {
1171
+ return message;
1172
+ }
1173
+ }
1174
+ };
1175
+ var logger = new Logger();
1176
+
1177
+ // src/dev/backgroundWorker.ts
1178
+ var BackgroundWorkerCoordinator = class {
1179
+ constructor(baseURL) {
1180
+ this.baseURL = baseURL;
1181
+ this.onTaskCompleted.attach(async ({ completion, execution }) => {
1182
+ await this.#notifyWorkersOfTaskCompletion(completion, execution);
1183
+ });
1184
+ }
1185
+ onTaskCompleted = new Evt();
1186
+ onWorkerRegistered = new Evt();
1187
+ onWorkerDeprecated = new Evt();
1188
+ _backgroundWorkers = /* @__PURE__ */ new Map();
1189
+ _records = /* @__PURE__ */ new Map();
1190
+ async #notifyWorkersOfTaskCompletion(completion, execution) {
1191
+ for (const worker of this._backgroundWorkers.values()) {
1192
+ await worker.handleTaskRunCompletion(completion, execution);
1193
+ }
1194
+ }
1195
+ get currentWorkers() {
1196
+ return Array.from(this._backgroundWorkers.entries()).map(([id, worker]) => ({
1197
+ id,
1198
+ worker,
1199
+ record: this._records.get(id)
1200
+ }));
1201
+ }
1202
+ async registerWorker(record, worker) {
1203
+ for (const [workerId, existingWorker] of this._backgroundWorkers.entries()) {
1204
+ if (workerId === record.id) {
1205
+ continue;
1206
+ }
1207
+ this.onWorkerDeprecated.post({ worker: existingWorker, id: workerId });
1208
+ }
1209
+ this._backgroundWorkers.set(record.id, worker);
1210
+ this._records.set(record.id, record);
1211
+ this.onWorkerRegistered.post({ worker, id: record.id, record });
1212
+ }
1213
+ close() {
1214
+ for (const worker of this._backgroundWorkers.values()) {
1215
+ worker.close();
1216
+ }
1217
+ this._backgroundWorkers.clear();
1218
+ this._records.clear();
1219
+ }
1220
+ async handleMessage(id, message) {
1221
+ switch (message.type) {
1222
+ case "EXECUTE_RUNS": {
1223
+ await Promise.all(message.payloads.map((payload) => this.#executeTaskRun(id, payload)));
1224
+ }
1225
+ }
1226
+ }
1227
+ async #executeTaskRun(id, payload) {
1228
+ const worker = this._backgroundWorkers.get(id);
1229
+ if (!worker) {
1230
+ logger.error(`Could not find worker ${id}`);
1231
+ return;
1232
+ }
1233
+ const record = this._records.get(id);
1234
+ if (!record) {
1235
+ logger.error(`Could not find worker record ${id}`);
1236
+ return;
1237
+ }
1238
+ const { execution } = payload;
1239
+ const link = chalk2.bgBlueBright(
1240
+ terminalLink("view logs", `${this.baseURL}/runs/${execution.run.id}`)
1241
+ );
1242
+ const workerPrefix = chalk2.green(`[worker:${record.version}]`);
1243
+ const taskPrefix = chalk2.yellow(`[task:${execution.task.id}]`);
1244
+ const runId = chalk2.blue(execution.run.id);
1245
+ const attempt = chalk2.blue(`.${execution.attempt.number}`);
1246
+ logger.log(`${workerPrefix}${taskPrefix} ${runId}${attempt} ${link}`);
1247
+ const now = performance.now();
1248
+ const completion = await worker.executeTaskRun(payload);
1249
+ const elapsed = performance.now() - now;
1250
+ const resultText = !completion.ok ? chalk2.red("error") : chalk2.green("success");
1251
+ const errorText = !completion.ok ? `
1252
+
1253
+ ${chalk2.bgRed("Error")} ${this.#formatErrorLog(completion.error)}` : "";
1254
+ const elapsedText = chalk2.dim(`(${elapsed.toFixed(2)}ms)`);
1255
+ logger.log(
1256
+ `${workerPrefix}${taskPrefix} ${runId}${attempt} ${resultText} ${elapsedText} ${link}${errorText}`
1257
+ );
1258
+ this.onTaskCompleted.post({ completion, execution, worker, backgroundWorkerId: id });
1259
+ }
1260
+ #formatErrorLog(error) {
1261
+ switch (error.type) {
1262
+ case "INTERNAL_ERROR": {
1263
+ return `Internal error: ${error.code}`;
1264
+ }
1265
+ case "STRING_ERROR": {
1266
+ return error.raw;
1267
+ }
1268
+ case "CUSTOM_ERROR": {
1269
+ return error.raw;
1270
+ }
1271
+ case "BUILT_IN_ERROR": {
1272
+ return `${error.name === "Error" ? "" : `(${error.name})`} ${error.message}
1273
+ ${error.stackTrace.split("\n").map((line) => ` ${line}`).join("\n")}
1274
+ `;
1275
+ }
1276
+ }
1277
+ }
1278
+ };
1279
+ var BackgroundWorker = class {
1280
+ constructor(path6, params) {
1281
+ this.path = path6;
1282
+ this.params = params;
1283
+ this._rawSourceMap = JSON.parse(readFileSync(`${path6}.map`, "utf-8"));
1284
+ }
1285
+ _rawSourceMap;
1286
+ _initialized = false;
1287
+ _handler = new ZodMessageHandler({
1288
+ schema: childToWorkerMessages
1289
+ });
1290
+ _onTaskCompleted = new Evt();
1291
+ _onClose = new Evt();
1292
+ tasks = [];
1293
+ metadata;
1294
+ _taskExecutions = /* @__PURE__ */ new Map();
1295
+ close() {
1296
+ this._onClose.post();
1297
+ }
1298
+ async initialize() {
1299
+ if (this._initialized) {
1300
+ throw new Error("Worker already initialized");
1301
+ }
1302
+ let resolved = false;
1303
+ this.tasks = await new Promise((resolve2, reject) => {
1304
+ const child = fork(this.path, {
1305
+ stdio: [
1306
+ /*stdin*/
1307
+ "ignore",
1308
+ /*stdout*/
1309
+ "pipe",
1310
+ /*stderr*/
1311
+ "pipe",
1312
+ "ipc"
1313
+ ],
1314
+ env: {
1315
+ ...this.params.env
1316
+ }
1317
+ });
1318
+ const timeout = setTimeout(() => {
1319
+ if (resolved) {
1320
+ return;
1321
+ }
1322
+ resolved = true;
1323
+ child.kill();
1324
+ reject(new Error("Worker timed out"));
1325
+ }, 1e3);
1326
+ child.on("message", async (msg) => {
1327
+ const message = this._handler.parseMessage(msg);
1328
+ if (message.type === "TASKS_READY" && !resolved) {
1329
+ clearTimeout(timeout);
1330
+ resolved = true;
1331
+ resolve2(message.payload.tasks);
1332
+ child.kill();
1333
+ }
1334
+ });
1335
+ child.stdout?.on("data", (data) => {
1336
+ logger.log(data.toString());
1337
+ });
1338
+ child.stderr?.on("data", (data) => {
1339
+ logger.error(data.toString());
1340
+ });
1341
+ child.on("exit", (code) => {
1342
+ if (!resolved) {
1343
+ clearTimeout(timeout);
1344
+ resolved = true;
1345
+ reject(new Error(`Worker exited with code ${code}`));
1346
+ }
1347
+ });
1348
+ });
1349
+ this._initialized = true;
1350
+ }
1351
+ async handleTaskRunCompletion(completion, execution) {
1352
+ this._onTaskCompleted.post({ completion, execution });
1353
+ }
1354
+ // We need to fork the process before we can execute any tasks
1355
+ async executeTaskRun(payload) {
1356
+ const metadata = this.metadata;
1357
+ if (!metadata) {
1358
+ throw new Error("Worker not registered");
1359
+ }
1360
+ const { execution, traceContext } = payload;
1361
+ const child = fork(this.path, {
1362
+ stdio: [
1363
+ /*stdin*/
1364
+ "ignore",
1365
+ /*stdout*/
1366
+ "pipe",
1367
+ /*stderr*/
1368
+ "pipe",
1369
+ "ipc"
1370
+ ],
1371
+ env: {
1372
+ ...this.params.env
1373
+ }
1374
+ });
1375
+ const sender = new ZodMessageSender({
1376
+ schema: workerToChildMessages,
1377
+ sender: async (message) => {
1378
+ if (!child.connected) {
1379
+ return;
1380
+ }
1381
+ child.send(message);
1382
+ }
1383
+ });
1384
+ const ctx = Evt.newCtx();
1385
+ this._onTaskCompleted.attach(ctx, async (taskCompletion) => {
1386
+ if (execution.attempt.id === taskCompletion.execution.attempt.id) {
1387
+ return;
1388
+ }
1389
+ await sender.send("TASK_RUN_COMPLETED", taskCompletion);
1390
+ });
1391
+ this._onClose.attachOnce(ctx, () => {
1392
+ child.kill();
1393
+ });
1394
+ let resolved = false;
1395
+ let resolver;
1396
+ let rejecter;
1397
+ const promise = new Promise((resolve2, reject) => {
1398
+ resolver = resolve2;
1399
+ rejecter = reject;
1400
+ });
1401
+ child.on("message", async (msg) => {
1402
+ const message = this._handler.parseMessage(msg);
1403
+ if (message.type === "TASK_RUN_COMPLETED") {
1404
+ resolved = true;
1405
+ resolver(message.payload.result);
1406
+ this._onTaskCompleted.detach(ctx);
1407
+ this._onClose.detach(ctx);
1408
+ await sender.send("CLEANUP", { flush: true });
1409
+ } else if (message.type === "READY_TO_DISPOSE") {
1410
+ if (!child.killed) {
1411
+ child.kill();
1412
+ }
1413
+ }
1414
+ });
1415
+ child.on("exit", (code) => {
1416
+ if (!resolved) {
1417
+ resolved = true;
1418
+ this._onTaskCompleted.detach(ctx);
1419
+ this._onClose.detach(ctx);
1420
+ rejecter(new Error(`Worker exited with code ${code}`));
1421
+ }
1422
+ });
1423
+ child.stdout?.on("data", (data) => {
1424
+ logger.log(
1425
+ `[${metadata.version}][${execution.run.id}.${execution.attempt.number}] ${data.toString()}`
1426
+ );
1427
+ });
1428
+ await sender.send("EXECUTE_TASK_RUN", { execution, traceContext, metadata });
1429
+ const result = await promise;
1430
+ if (result.ok) {
1431
+ return result;
1432
+ }
1433
+ const error = result.error;
1434
+ if (error.type === "BUILT_IN_ERROR") {
1435
+ const mappedError = await this.#correctError(error, execution);
1436
+ return {
1437
+ ...result,
1438
+ error: mappedError
1439
+ };
1440
+ }
1441
+ return result;
1442
+ }
1443
+ async #correctError(error, execution) {
1444
+ return {
1445
+ ...error,
1446
+ stackTrace: await this.#correctErrorStackTrace(error.stackTrace, execution)
1447
+ };
1448
+ }
1449
+ async #correctErrorStackTrace(stackTrace, execution) {
1450
+ const lines = stackTrace.split("\n");
1451
+ lines.shift();
1452
+ return SourceMapConsumer.with(
1453
+ this._rawSourceMap,
1454
+ null,
1455
+ (consumer) => lines.map((line) => this.#correctStackTraceLine(line, consumer, execution)).filter(Boolean).join("\n")
1456
+ );
1457
+ }
1458
+ #correctStackTraceLine(line, consumer, execution) {
1459
+ const regex = /at (.*?) \(file:\/\/(\/.*?\.mjs):(\d+):(\d+)\)/;
1460
+ const match = regex.exec(line);
1461
+ if (!match) {
1462
+ return line;
1463
+ }
1464
+ const [_2, identifier, path6, lineNum, colNum] = match;
1465
+ const originalPosition = consumer.originalPositionFor({
1466
+ line: Number(lineNum),
1467
+ column: Number(colNum)
1468
+ });
1469
+ if (!originalPosition.source) {
1470
+ return line;
1471
+ }
1472
+ const { source, line: originalLine, column: originalColumn } = originalPosition;
1473
+ if (this.#shouldFilterLine({ identifier, path: source })) {
1474
+ return;
1475
+ }
1476
+ const sourcePath = path6 ? nodePath.relative(this.params.projectDir, nodePath.resolve(nodePath.dirname(path6), source)) : source;
1477
+ return `at ${identifier === "Object.run" ? `${execution.task.exportName}.run` : identifier} (${sourcePath}:${originalLine}:${originalColumn})`;
1478
+ }
1479
+ #shouldFilterLine(line) {
1480
+ const filename = nodePath.basename(line.path ?? "");
1481
+ if (filename === "__entryPoint.ts") {
1482
+ return true;
1483
+ }
1484
+ if (line.identifier === "async ZodMessageHandler.handleMessage") {
1485
+ return true;
1486
+ }
1487
+ return false;
1488
+ }
1489
+ };
1490
+
1491
+ // src/utilities/initialBanner.ts
1492
+ import { spinner } from "@clack/prompts";
1493
+ import chalk4 from "chalk";
1494
+ import supportsColor from "supports-color";
1495
+ import checkForUpdate from "update-check";
1496
+
1497
+ // src/utilities/colors.ts
1498
+ import chalk3 from "chalk";
1499
+ var green = "#4FFF54";
1500
+ var purple = "#735BF3";
1501
+ function chalkGrey(text) {
1502
+ return chalk3.hex("#666")(text);
1503
+ }
1504
+ function chalkError(text) {
1505
+ return chalk3.red(text);
1506
+ }
1507
+ function chalkSuccess(text) {
1508
+ return chalk3.green(text);
1509
+ }
1510
+ function chalkLink(text) {
1511
+ return chalk3.underline.blue(text);
1512
+ }
1513
+ function logo() {
1514
+ return `${chalk3.hex(green).bold("Trigger")}${chalk3.hex(purple).bold(".dev")}`;
1515
+ }
1516
+
1517
+ // src/utilities/getVersion.ts
1518
+ import path2 from "path";
1519
+
1520
+ // src/utilities/fileSystem.ts
1521
+ import fsSync from "fs";
1522
+ import fsModule, { writeFile } from "fs/promises";
1523
+ async function pathExists(path6) {
1524
+ return fsSync.existsSync(path6);
1525
+ }
1526
+ async function writeJSONFile(path6, json) {
1527
+ await writeFile(path6, JSON.stringify(json, null, 2));
1528
+ }
1529
+ function readJSONFileSync(path6) {
1530
+ const fileContents = fsSync.readFileSync(path6, "utf8");
1531
+ return JSON.parse(fileContents);
1532
+ }
1533
+
1534
+ // src/utilities/getVersion.ts
1535
+ function getVersion() {
1536
+ const packageJsonPath = path2.join(PKG_ROOT, "package.json");
1537
+ const packageJsonContent = readJSONFileSync(packageJsonPath);
1538
+ return packageJsonContent.version ?? "1.0.0";
1539
+ }
1540
+
1541
+ // src/utilities/initialBanner.ts
1542
+ async function printInitialBanner(performUpdateCheck = true) {
1543
+ const packageVersion = getVersion();
1544
+ const text = `
1545
+ ${logo()} ${chalkGrey(`(${packageVersion})`)}
1546
+ `;
1547
+ logger.info(text);
1548
+ let maybeNewVersion;
1549
+ if (performUpdateCheck) {
1550
+ const loadingSpinner = spinner();
1551
+ loadingSpinner.start("Checking for updates");
1552
+ maybeNewVersion = await updateCheck();
1553
+ if (maybeNewVersion !== void 0) {
1554
+ loadingSpinner.stop(`Update available ${chalk4.green(maybeNewVersion)}`);
1555
+ const currentMajor = parseInt(packageVersion.split(".")[0]);
1556
+ const newMajor = parseInt(maybeNewVersion.split(".")[0]);
1557
+ if (newMajor > currentMajor) {
1558
+ logger.warn(
1559
+ `Please update to the latest version of \`trigger.dev\` to prevent critical errors.
1560
+ Run \`npm install --save-dev trigger.dev@${newMajor}\` to update to the latest version.
1561
+ After installation, run Trigger.dev with \`npx trigger.dev\`.`
1562
+ );
1563
+ }
1564
+ } else {
1565
+ loadingSpinner.stop("On latest version");
1566
+ }
1567
+ }
1568
+ }
1569
+ async function printStandloneInitialBanner(performUpdateCheck = true) {
1570
+ const packageVersion = getVersion();
1571
+ let text = `
1572
+ ${logo()} ${chalkGrey(`${packageVersion}`)}`;
1573
+ if (performUpdateCheck) {
1574
+ const maybeNewVersion = await updateCheck();
1575
+ if (maybeNewVersion !== void 0) {
1576
+ text = `${text} (update available ${chalk4.green(maybeNewVersion)})`;
1577
+ }
1578
+ }
1579
+ logger.log(
1580
+ text + "\n" + (supportsColor.stdout ? chalk4.hex(green)("-".repeat(54)) : "-".repeat(54))
1581
+ );
1582
+ }
1583
+ async function doUpdateCheck() {
1584
+ let update = null;
1585
+ try {
1586
+ update = await checkForUpdate(package_default, {
1587
+ distTag: package_default.version.startsWith("0.0.0") ? "beta" : "latest"
1588
+ });
1589
+ } catch (err) {
1590
+ }
1591
+ return update?.latest;
1592
+ }
1593
+ var updateCheckPromise;
1594
+ function updateCheck() {
1595
+ return updateCheckPromise ??= doUpdateCheck();
1596
+ }
1597
+
1598
+ // src/utilities/configFiles.ts
1599
+ import { mkdirSync, writeFileSync } from "node:fs";
1600
+ import path3 from "node:path";
1601
+
1602
+ // ../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/esm-wrapper/mod.esm.js
1603
+ var mod_esm_exports = {};
1604
+ __export(mod_esm_exports, {
1605
+ default: () => mod_esm_default
1606
+ });
1607
+ var import_mod_cjs = __toESM(require_mod_cjs3(), 1);
1608
+ __reExport(mod_esm_exports, __toESM(require_mod_cjs3(), 1));
1609
+ var mod_esm_default = import_mod_cjs.default;
1610
+
1611
+ // src/utilities/configFiles.ts
1612
+ import { z } from "zod";
1613
+ function getGlobalConfigFolderPath() {
1614
+ const configDir = mod_esm_default(".trigger").config();
1615
+ return configDir;
1616
+ }
1617
+ var UserAuthConfigSchema = z.object({
1618
+ accessToken: z.string().optional(),
1619
+ apiUrl: z.string().optional()
1620
+ });
1621
+ function getAuthConfigFilePath() {
1622
+ return path3.join(getGlobalConfigFolderPath(), "config", "default.json");
1623
+ }
1624
+ function writeAuthConfigFile(config) {
1625
+ const authConfigFilePath = getAuthConfigFilePath();
1626
+ mkdirSync(path3.dirname(authConfigFilePath), {
1627
+ recursive: true
1628
+ });
1629
+ writeFileSync(path3.join(authConfigFilePath), JSON.stringify(config), {
1630
+ encoding: "utf-8"
1631
+ });
1632
+ }
1633
+ function readAuthConfigFile() {
1634
+ try {
1635
+ const authConfigFilePath = getAuthConfigFilePath();
1636
+ const json = readJSONFileSync(authConfigFilePath);
1637
+ const parsed = UserAuthConfigSchema.parse(json);
1638
+ return parsed;
1639
+ } catch (error) {
1640
+ logger.debug(`Error reading auth config file: ${error}`);
1641
+ return void 0;
1642
+ }
1643
+ }
1644
+
1645
+ // src/utilities/session.ts
1646
+ async function isLoggedIn() {
1647
+ const config = readAuthConfigFile();
1648
+ if (!config?.accessToken || !config?.apiUrl) {
1649
+ return { ok: false, error: "You must login first" };
1650
+ }
1651
+ const apiClient2 = new ApiClient(config.apiUrl, config.accessToken);
1652
+ const userData = await apiClient2.whoAmI();
1653
+ if (!userData.success) {
1654
+ return {
1655
+ ok: false,
1656
+ error: userData.error
1657
+ };
1658
+ }
1659
+ return {
1660
+ ok: true,
1661
+ config: {
1662
+ apiUrl: config.apiUrl,
1663
+ accessToken: config.accessToken
1664
+ }
1665
+ };
1666
+ }
1667
+
1668
+ // src/cli/common.ts
1669
+ import { z as z2 } from "zod";
1670
+ var CommonCommandOptions = z2.object({
1671
+ logLevel: z2.enum(["debug", "info", "log", "warn", "error", "none"]).default("log")
1672
+ });
1673
+
1674
+ // src/commands/dev.tsx
1675
+ var CONFIG_FILES = ["trigger.config.js", "trigger.config.mjs"];
1676
+ var ConfigSchema = z3.object({
1677
+ project: z3.string(),
1678
+ triggerDirectories: z3.string().array().optional(),
1679
+ triggerUrl: z3.string().optional(),
1680
+ projectDir: z3.string().optional()
1681
+ });
1682
+ var apiClient;
1683
+ var DevCommandOptions = CommonCommandOptions;
1684
+ function configureDevCommand(program2) {
1685
+ program2.command("dev").description("Run your Trigger.dev tasks locally").argument("[path]", "The path to the project", ".").option(
1686
+ "-l, --log-level <level>",
1687
+ "The log level to use (debug, info, log, warn, error, none)",
1688
+ "log"
1689
+ ).action(async (path6, options) => {
1690
+ try {
1691
+ await devCommand(path6, options);
1692
+ } catch (e) {
1693
+ throw e;
1694
+ }
1695
+ });
1696
+ }
1697
+ async function devCommand(dir, anyOptions) {
1698
+ const options = DevCommandOptions.safeParse(anyOptions);
1699
+ if (!options.success) {
1700
+ throw new Error(`Invalid options: ${options.error}`);
1701
+ }
1702
+ const authorization = await isLoggedIn();
1703
+ if (!authorization.ok) {
1704
+ logger.error("You must login first. Use `trigger.dev login` to login.");
1705
+ process.exitCode = 1;
1706
+ return;
1707
+ }
1708
+ let watcher;
1709
+ try {
1710
+ const devInstance = await startDev(dir, options.data, authorization.config);
1711
+ watcher = devInstance.watcher;
1712
+ const { waitUntilExit } = devInstance.devReactElement;
1713
+ await waitUntilExit();
1714
+ } finally {
1715
+ await watcher?.close();
1716
+ }
1717
+ }
1718
+ async function startDev(dir, options, authorization) {
1719
+ let watcher;
1720
+ let rerender;
1721
+ try {
1722
+ if (options.logLevel) {
1723
+ logger.loggerLevel = options.logLevel;
1724
+ }
1725
+ await printStandloneInitialBanner(true);
1726
+ const configPath = await getConfigPath(dir);
1727
+ let config = await readConfig(configPath);
1728
+ watcher = watch(configPath, {
1729
+ persistent: true
1730
+ }).on("change", async (_event) => {
1731
+ config = await readConfig(configPath);
1732
+ logger.log(`${basename(configPath)} changed...`);
1733
+ logger.debug("New config", { config });
1734
+ rerender(await getDevReactElement(config, authorization));
1735
+ });
1736
+ async function getDevReactElement(configParam, authorization2) {
1737
+ const accessToken = authorization2.accessToken;
1738
+ const apiUrl = authorization2.apiUrl;
1739
+ apiClient = new ApiClient(apiUrl, accessToken);
1740
+ const devEnv = await apiClient.getProjectDevEnv({ projectRef: config.project });
1741
+ if (!devEnv.success) {
1742
+ throw new Error(devEnv.error);
1743
+ }
1744
+ const environmentClient = new ApiClient(apiUrl, devEnv.data.apiKey);
1745
+ return /* @__PURE__ */ React.createElement(
1746
+ DevUI,
1747
+ {
1748
+ config: configParam,
1749
+ apiUrl,
1750
+ apiKey: devEnv.data.apiKey,
1751
+ environmentClient,
1752
+ projectName: devEnv.data.name
1753
+ }
1754
+ );
1755
+ }
1756
+ const devReactElement = render(await getDevReactElement(config, authorization));
1757
+ rerender = devReactElement.rerender;
1758
+ return {
1759
+ devReactElement,
1760
+ watcher,
1761
+ stop: async () => {
1762
+ devReactElement.unmount();
1763
+ await watcher?.close();
1764
+ }
1765
+ };
1766
+ } catch (e) {
1767
+ await watcher?.close();
1768
+ throw e;
1769
+ }
1770
+ }
1771
+ function useDev({ config, apiUrl, apiKey, environmentClient, projectName }) {
1772
+ useEffect(() => {
1773
+ const websocketUrl = new URL(apiUrl);
1774
+ websocketUrl.protocol = websocketUrl.protocol.replace("http", "ws");
1775
+ websocketUrl.pathname = `/ws`;
1776
+ const websocket = new WebSocket(websocketUrl.href, [], {
1777
+ WebSocket: WebsocketFactory(apiKey),
1778
+ connectionTimeout: 1e4,
1779
+ maxRetries: 6
1780
+ });
1781
+ websocket.addEventListener("open", (foo) => {
1782
+ });
1783
+ websocket.addEventListener("close", (event) => {
1784
+ });
1785
+ websocket.addEventListener("error", (event) => {
1786
+ });
1787
+ const sender = new ZodMessageSender2({
1788
+ schema: clientWebsocketMessages,
1789
+ sender: async (message) => {
1790
+ websocket?.send(JSON.stringify(message));
1791
+ }
1792
+ });
1793
+ const backgroundWorkerCoordinator = new BackgroundWorkerCoordinator(
1794
+ `${apiUrl}/projects/v3/${config.project}`
1795
+ );
1796
+ backgroundWorkerCoordinator.onTaskCompleted.attach(
1797
+ async ({ backgroundWorkerId, completion }) => {
1798
+ await sender.send("BACKGROUND_WORKER_MESSAGE", {
1799
+ backgroundWorkerId,
1800
+ data: {
1801
+ type: "TASK_RUN_COMPLETED",
1802
+ completion
1803
+ }
1804
+ });
1805
+ }
1806
+ );
1807
+ backgroundWorkerCoordinator.onWorkerRegistered.attach(async ({ id, worker, record }) => {
1808
+ await sender.send("READY_FOR_TASKS", {
1809
+ backgroundWorkerId: id
1810
+ });
1811
+ });
1812
+ backgroundWorkerCoordinator.onWorkerDeprecated.attach(async ({ id }) => {
1813
+ await sender.send("WORKER_DEPRECATED", {
1814
+ backgroundWorkerId: id
1815
+ });
1816
+ });
1817
+ websocket.addEventListener("message", async (event) => {
1818
+ const data = JSON.parse(
1819
+ typeof event.data === "string" ? event.data : new TextDecoder("utf-8").decode(event.data)
1820
+ );
1821
+ const messageHandler = new ZodMessageHandler2({
1822
+ schema: serverWebsocketMessages,
1823
+ messages: {
1824
+ SERVER_READY: async (payload) => {
1825
+ },
1826
+ BACKGROUND_WORKER_MESSAGE: async (payload) => {
1827
+ await backgroundWorkerCoordinator.handleMessage(
1828
+ payload.backgroundWorkerId,
1829
+ payload.data
1830
+ );
1831
+ }
1832
+ }
1833
+ });
1834
+ await messageHandler.handleMessage(data);
1835
+ });
1836
+ let ctx;
1837
+ async function runBuild() {
1838
+ if (ctx) {
1839
+ await ctx.cancel();
1840
+ await ctx.dispose();
1841
+ }
1842
+ let latestWorkerContentHash;
1843
+ const taskFiles = await gatherTaskFiles(config);
1844
+ const workerFacade = readFileSync2(
1845
+ new URL(importResolve("./worker-facade.js", import.meta.url)).href.replace("file://", ""),
1846
+ "utf-8"
1847
+ );
1848
+ const entryPointContents = workerFacade.replace(
1849
+ "__TASKS__",
1850
+ createTaskFileImports(taskFiles)
1851
+ );
1852
+ let firstBuild = true;
1853
+ logger.log(chalk5.dim("\u2394 Building background worker..."));
1854
+ ctx = await context({
1855
+ stdin: {
1856
+ contents: entryPointContents,
1857
+ resolveDir: process.cwd(),
1858
+ sourcefile: "__entryPoint.ts"
1859
+ },
1860
+ bundle: true,
1861
+ metafile: true,
1862
+ write: false,
1863
+ minify: false,
1864
+ sourcemap: true,
1865
+ logLevel: "silent",
1866
+ platform: "node",
1867
+ format: "esm",
1868
+ target: ["node18", "es2020"],
1869
+ outdir: "out",
1870
+ define: {
1871
+ TRIGGER_API_URL: `"${config.triggerUrl}"`
1872
+ },
1873
+ banner: {
1874
+ js: "import { createRequire } from 'module';const require = createRequire(import.meta.url);"
1875
+ },
1876
+ plugins: [
1877
+ {
1878
+ name: "trigger.dev v3",
1879
+ setup(build) {
1880
+ build.onEnd(async (result) => {
1881
+ if (result.errors.length > 0)
1882
+ return;
1883
+ if (!result || !result.outputFiles) {
1884
+ logger.error("Build failed: no result");
1885
+ return;
1886
+ }
1887
+ if (!firstBuild) {
1888
+ logger.log(chalk5.dim("\u2394 Rebuilding background worker..."));
1889
+ }
1890
+ const metaOutputKey = join("out", `stdin.js`);
1891
+ const metaOutput = result.metafile.outputs[metaOutputKey];
1892
+ if (!metaOutput) {
1893
+ throw new Error(`Could not find metafile`);
1894
+ }
1895
+ const outputFileKey = join(config.projectDir, metaOutputKey);
1896
+ const outputFile = result.outputFiles.find((file) => file.path === outputFileKey);
1897
+ if (!outputFile) {
1898
+ throw new Error(
1899
+ `Could not find output file for entry point ${metaOutput.entryPoint}`
1900
+ );
1901
+ }
1902
+ const sourceMapFileKey = join(config.projectDir, `${metaOutputKey}.map`);
1903
+ const sourceMapFile = result.outputFiles.find(
1904
+ (file) => file.path === sourceMapFileKey
1905
+ );
1906
+ if (!sourceMapFile) {
1907
+ throw new Error(
1908
+ `Could not find source map file for entry point ${metaOutput.entryPoint}`
1909
+ );
1910
+ }
1911
+ const md5Hasher = createHash("md5");
1912
+ md5Hasher.update(Buffer.from(outputFile.contents.buffer));
1913
+ const contentHash = md5Hasher.digest("hex");
1914
+ if (latestWorkerContentHash === contentHash) {
1915
+ logger.log(chalk5.dim("\u2394 No changes detected, skipping build..."));
1916
+ logger.debug(`No changes detected, skipping build`);
1917
+ return;
1918
+ }
1919
+ const fullPath = join(config.projectDir, ".trigger", `${contentHash}.mjs`);
1920
+ await fs.promises.mkdir(dirname(fullPath), { recursive: true });
1921
+ await fs.promises.writeFile(fullPath, outputFile.text);
1922
+ const sourceMapPath = `${fullPath}.map`;
1923
+ await fs.promises.writeFile(sourceMapPath, sourceMapFile.text);
1924
+ const backgroundWorker = new BackgroundWorker(fullPath, {
1925
+ projectDir: config.projectDir,
1926
+ env: {
1927
+ TRIGGER_API_URL: apiUrl,
1928
+ TRIGGER_API_KEY: apiKey
1929
+ }
1930
+ });
1931
+ await backgroundWorker.initialize();
1932
+ latestWorkerContentHash = contentHash;
1933
+ let packageVersion;
1934
+ const taskResources = [];
1935
+ if (!backgroundWorker.tasks) {
1936
+ throw new Error(`Background Worker started without tasks`);
1937
+ }
1938
+ for (const task of backgroundWorker.tasks) {
1939
+ taskResources.push({
1940
+ id: task.id,
1941
+ filePath: task.filePath,
1942
+ exportName: task.exportName
1943
+ });
1944
+ packageVersion = task.packageVersion;
1945
+ }
1946
+ if (!packageVersion) {
1947
+ throw new Error(`Background Worker started without package version`);
1948
+ }
1949
+ const backgroundWorkerBody = {
1950
+ localOnly: true,
1951
+ metadata: {
1952
+ packageVersion,
1953
+ // This is a hack to get around the funky node16 typescript module resolution issue
1954
+ cliPackageVersion: version,
1955
+ tasks: taskResources,
1956
+ contentHash
1957
+ }
1958
+ };
1959
+ const backgroundWorkerRecord = await environmentClient.createBackgroundWorker(
1960
+ config.project,
1961
+ backgroundWorkerBody
1962
+ );
1963
+ if (!backgroundWorkerRecord.success) {
1964
+ throw new Error(backgroundWorkerRecord.error);
1965
+ }
1966
+ backgroundWorker.metadata = backgroundWorkerRecord.data;
1967
+ if (firstBuild) {
1968
+ logger.log(
1969
+ chalk5.green(
1970
+ `Background worker started (${backgroundWorkerRecord.data.version})`
1971
+ )
1972
+ );
1973
+ } else {
1974
+ logger.log(
1975
+ chalk5.dim(`Background worker rebuilt (${backgroundWorkerRecord.data.version})`)
1976
+ );
1977
+ }
1978
+ firstBuild = false;
1979
+ await backgroundWorkerCoordinator.registerWorker(
1980
+ backgroundWorkerRecord.data,
1981
+ backgroundWorker
1982
+ );
1983
+ });
1984
+ }
1985
+ }
1986
+ ]
1987
+ });
1988
+ await ctx.watch();
1989
+ }
1990
+ const throttle = pThrottle({
1991
+ limit: 2,
1992
+ interval: 1e3
1993
+ });
1994
+ const throttledRebuild = throttle(runBuild);
1995
+ const taskFileWatcher = watch(
1996
+ config.triggerDirectories.map((triggerDir) => `${triggerDir}/*.ts`),
1997
+ {
1998
+ ignoreInitial: true
1999
+ }
2000
+ );
2001
+ taskFileWatcher.on("add", async (path6) => {
2002
+ throttledRebuild().catch((error) => {
2003
+ logger.error(error);
2004
+ });
2005
+ });
2006
+ taskFileWatcher.on("unlink", async (path6) => {
2007
+ throttledRebuild().catch((error) => {
2008
+ logger.error(error);
2009
+ });
2010
+ });
2011
+ throttledRebuild().catch((error) => {
2012
+ logger.error(error);
2013
+ });
2014
+ return () => {
2015
+ logger.debug(`Shutting down dev session for ${config.project}`);
2016
+ taskFileWatcher.close();
2017
+ websocket?.close();
2018
+ backgroundWorkerCoordinator.close();
2019
+ ctx?.dispose().catch((error) => {
2020
+ console.error(error);
2021
+ });
2022
+ };
2023
+ }, [config, apiUrl, apiKey, environmentClient]);
2024
+ }
2025
+ function DevUI(props) {
2026
+ return /* @__PURE__ */ React.createElement(Suspense, null, /* @__PURE__ */ React.createElement(DevUIImp, { ...props }));
2027
+ }
2028
+ function DevUIImp(props) {
2029
+ const dev = useDev(props);
2030
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(HotKeys, null));
2031
+ }
2032
+ function useHotkeys() {
2033
+ const { exit } = useApp();
2034
+ useInput(async (input, key) => {
2035
+ if (key.return) {
2036
+ console.log("");
2037
+ return;
2038
+ }
2039
+ switch (input.toLowerCase()) {
2040
+ case "c":
2041
+ console.clear();
2042
+ console.log();
2043
+ break;
2044
+ case "b": {
2045
+ break;
2046
+ }
2047
+ case "q":
2048
+ case "x":
2049
+ exit();
2050
+ break;
2051
+ default:
2052
+ break;
2053
+ }
2054
+ });
2055
+ }
2056
+ function HotKeys() {
2057
+ useHotkeys();
2058
+ return /* @__PURE__ */ React.createElement(Box, { borderStyle: "round", paddingLeft: 1, paddingRight: 1 }, /* @__PURE__ */ React.createElement(Text, { bold: true }, "[b]"), /* @__PURE__ */ React.createElement(Text, null, " open a browser, "), /* @__PURE__ */ React.createElement(Text, { bold: true }, "[c]"), /* @__PURE__ */ React.createElement(Text, null, " clear console, "), /* @__PURE__ */ React.createElement(Text, { bold: true }, "[x]"), /* @__PURE__ */ React.createElement(Text, null, " to exit"));
2059
+ }
2060
+ function WebsocketFactory(apiKey) {
2061
+ return class extends wsWebSocket {
2062
+ constructor(address, options) {
2063
+ super(address, { ...options ?? {}, headers: { Authorization: `Bearer ${apiKey}` } });
2064
+ }
2065
+ };
2066
+ }
2067
+ function createTaskFileImports(taskFiles) {
2068
+ return taskFiles.map(
2069
+ (taskFile) => `import * as ${taskFile.importName} from "./${taskFile.importPath}"; TaskFileImports["${taskFile.importName}"] = ${taskFile.importName}; TaskFiles["${taskFile.importName}"] = ${JSON.stringify(
2070
+ taskFile
2071
+ )};`
2072
+ ).join("\n");
2073
+ }
2074
+ async function gatherTaskFiles(config) {
2075
+ const taskFiles = [];
2076
+ for (const triggerDir of config.triggerDirectories) {
2077
+ const files = await fs.promises.readdir(triggerDir, { withFileTypes: true });
2078
+ for (const file of files) {
2079
+ if (!file.isFile())
2080
+ continue;
2081
+ if (!file.name.endsWith(".js") && !file.name.endsWith(".ts"))
2082
+ continue;
2083
+ const fullPath = join(triggerDir, file.name);
2084
+ const filePath = relative(config.projectDir, fullPath);
2085
+ const importPath = filePath.replace(/\.(js|ts)$/, "");
2086
+ const importName = importPath.replace(/\//g, "_");
2087
+ taskFiles.push({ triggerDir, importPath, importName, filePath });
2088
+ }
2089
+ }
2090
+ return taskFiles;
2091
+ }
2092
+ async function getConfigPath(dir) {
2093
+ const path6 = await findUp(CONFIG_FILES, { cwd: dir });
2094
+ if (!path6) {
2095
+ throw new Error("No config file found.");
2096
+ }
2097
+ return path6;
2098
+ }
2099
+ async function readConfig(path6) {
2100
+ try {
2101
+ const userConfigModule = await import(`${pathToFileURL(path6).href}?_ts=${Date.now()}`);
2102
+ const rawConfig = await normalizeConfig(userConfigModule ? userConfigModule.default : {});
2103
+ const config = ConfigSchema.parse(rawConfig);
2104
+ return resolveConfig(path6, config);
2105
+ } catch (error) {
2106
+ console.error(`Failed to load config file at ${path6}`);
2107
+ throw error;
2108
+ }
2109
+ }
2110
+ async function resolveConfig(path6, config) {
2111
+ if (!config.triggerDirectories) {
2112
+ config.triggerDirectories = await findTriggerDirectories(path6);
2113
+ }
2114
+ config.triggerDirectories = resolveTriggerDirectories(config.triggerDirectories);
2115
+ if (!config.triggerUrl) {
2116
+ config.triggerUrl = CLOUD_API_URL;
2117
+ }
2118
+ if (!config.projectDir) {
2119
+ config.projectDir = dirname(path6);
2120
+ }
2121
+ return config;
2122
+ }
2123
+ async function normalizeConfig(config) {
2124
+ if (typeof config === "function") {
2125
+ config = config();
2126
+ }
2127
+ return await config;
2128
+ }
2129
+ function resolveTriggerDirectories(dirs) {
2130
+ return dirs.map((dir) => resolve(dir));
2131
+ }
2132
+ var IGNORED_DIRS = ["node_modules", ".git", "dist", "build"];
2133
+ async function findTriggerDirectories(filePath) {
2134
+ const dirPath = dirname(filePath);
2135
+ return getTriggerDirectories(dirPath);
2136
+ }
2137
+ async function getTriggerDirectories(dirPath) {
2138
+ const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
2139
+ const triggerDirectories = [];
2140
+ for (const entry of entries) {
2141
+ if (!entry.isDirectory() || IGNORED_DIRS.includes(entry.name))
2142
+ continue;
2143
+ const fullPath = join(dirPath, entry.name);
2144
+ if (entry.name === "trigger") {
2145
+ triggerDirectories.push(fullPath);
2146
+ }
2147
+ triggerDirectories.push(...await getTriggerDirectories(fullPath));
2148
+ }
2149
+ return triggerDirectories;
2150
+ }
2151
+
2152
+ // src/commands/login.ts
2153
+ import { intro, log, outro, select, spinner as spinner3 } from "@clack/prompts";
2154
+
2155
+ // ../../node_modules/.pnpm/open@10.0.3/node_modules/open/index.js
2156
+ import process6 from "node:process";
2157
+ import { Buffer as Buffer2 } from "node:buffer";
2158
+ import path4 from "node:path";
2159
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
2160
+ import childProcess from "node:child_process";
2161
+ import fs5, { constants as fsConstants } from "node:fs/promises";
2162
+
2163
+ // ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
2164
+ import process2 from "node:process";
2165
+ import os from "node:os";
2166
+ import fs4 from "node:fs";
2167
+
2168
+ // ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
2169
+ import fs3 from "node:fs";
2170
+
2171
+ // ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
2172
+ import fs2 from "node:fs";
2173
+ var isDockerCached;
2174
+ function hasDockerEnv() {
2175
+ try {
2176
+ fs2.statSync("/.dockerenv");
2177
+ return true;
2178
+ } catch {
2179
+ return false;
2180
+ }
2181
+ }
2182
+ function hasDockerCGroup() {
2183
+ try {
2184
+ return fs2.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
2185
+ } catch {
2186
+ return false;
2187
+ }
2188
+ }
2189
+ function isDocker() {
2190
+ if (isDockerCached === void 0) {
2191
+ isDockerCached = hasDockerEnv() || hasDockerCGroup();
2192
+ }
2193
+ return isDockerCached;
2194
+ }
2195
+
2196
+ // ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
2197
+ var cachedResult;
2198
+ var hasContainerEnv = () => {
2199
+ try {
2200
+ fs3.statSync("/run/.containerenv");
2201
+ return true;
2202
+ } catch {
2203
+ return false;
2204
+ }
2205
+ };
2206
+ function isInsideContainer() {
2207
+ if (cachedResult === void 0) {
2208
+ cachedResult = hasContainerEnv() || isDocker();
2209
+ }
2210
+ return cachedResult;
2211
+ }
2212
+
2213
+ // ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
2214
+ var isWsl = () => {
2215
+ if (process2.platform !== "linux") {
2216
+ return false;
2217
+ }
2218
+ if (os.release().toLowerCase().includes("microsoft")) {
2219
+ if (isInsideContainer()) {
2220
+ return false;
2221
+ }
2222
+ return true;
2223
+ }
2224
+ try {
2225
+ return fs4.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
2226
+ } catch {
2227
+ return false;
2228
+ }
2229
+ };
2230
+ var is_wsl_default = process2.env.__IS_WSL_TEST__ ? isWsl : isWsl();
2231
+
2232
+ // ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
2233
+ function defineLazyProperty(object, propertyName, valueGetter) {
2234
+ const define = (value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true });
2235
+ Object.defineProperty(object, propertyName, {
2236
+ configurable: true,
2237
+ enumerable: true,
2238
+ get() {
2239
+ const result = valueGetter();
2240
+ define(result);
2241
+ return result;
2242
+ },
2243
+ set(value) {
2244
+ define(value);
2245
+ }
2246
+ });
2247
+ return object;
2248
+ }
2249
+
2250
+ // ../../node_modules/.pnpm/default-browser@5.2.1/node_modules/default-browser/index.js
2251
+ import { promisify as promisify4 } from "node:util";
2252
+ import process5 from "node:process";
2253
+ import { execFile as execFile4 } from "node:child_process";
2254
+
2255
+ // ../../node_modules/.pnpm/default-browser-id@5.0.0/node_modules/default-browser-id/index.js
2256
+ import { promisify } from "node:util";
2257
+ import process3 from "node:process";
2258
+ import { execFile } from "node:child_process";
2259
+ var execFileAsync = promisify(execFile);
2260
+ async function defaultBrowserId() {
2261
+ if (process3.platform !== "darwin") {
2262
+ throw new Error("macOS only");
2263
+ }
2264
+ const { stdout } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
2265
+ const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
2266
+ return match?.groups.id ?? "com.apple.Safari";
2267
+ }
2268
+
2269
+ // ../../node_modules/.pnpm/run-applescript@7.0.0/node_modules/run-applescript/index.js
2270
+ import process4 from "node:process";
2271
+ import { promisify as promisify2 } from "node:util";
2272
+ import { execFile as execFile2, execFileSync } from "node:child_process";
2273
+ var execFileAsync2 = promisify2(execFile2);
2274
+ async function runAppleScript(script, { humanReadableOutput = true } = {}) {
2275
+ if (process4.platform !== "darwin") {
2276
+ throw new Error("macOS only");
2277
+ }
2278
+ const outputArguments = humanReadableOutput ? [] : ["-ss"];
2279
+ const { stdout } = await execFileAsync2("osascript", ["-e", script, outputArguments]);
2280
+ return stdout.trim();
2281
+ }
2282
+
2283
+ // ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
2284
+ async function bundleName(bundleId) {
2285
+ return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
2286
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
2287
+ }
2288
+
2289
+ // ../../node_modules/.pnpm/default-browser@5.2.1/node_modules/default-browser/windows.js
2290
+ import { promisify as promisify3 } from "node:util";
2291
+ import { execFile as execFile3 } from "node:child_process";
2292
+ var execFileAsync3 = promisify3(execFile3);
2293
+ var windowsBrowserProgIds = {
2294
+ AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
2295
+ MSEdgeDHTML: { name: "Edge", id: "com.microsoft.edge" },
2296
+ // On macOS, it's "com.microsoft.edgemac"
2297
+ MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
2298
+ // Newer Edge/Win10 releases
2299
+ "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" },
2300
+ FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
2301
+ ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
2302
+ BraveHTML: { name: "Brave", id: "com.brave.Browser" },
2303
+ BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
2304
+ BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" }
2305
+ };
2306
+ var UnknownBrowserError = class extends Error {
2307
+ };
2308
+ async function defaultBrowser(_execFileAsync = execFileAsync3) {
2309
+ const { stdout } = await _execFileAsync("reg", [
2310
+ "QUERY",
2311
+ " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
2312
+ "/v",
2313
+ "ProgId"
2314
+ ]);
2315
+ const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
2316
+ if (!match) {
2317
+ throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
2318
+ }
2319
+ const { id } = match.groups;
2320
+ const browser = windowsBrowserProgIds[id];
2321
+ if (!browser) {
2322
+ throw new UnknownBrowserError(`Unknown browser ID: ${id}`);
2323
+ }
2324
+ return browser;
2325
+ }
2326
+
2327
+ // ../../node_modules/.pnpm/default-browser@5.2.1/node_modules/default-browser/index.js
2328
+ var execFileAsync4 = promisify4(execFile4);
2329
+ var titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
2330
+ async function defaultBrowser2() {
2331
+ if (process5.platform === "darwin") {
2332
+ const id = await defaultBrowserId();
2333
+ const name = await bundleName(id);
2334
+ return { name, id };
2335
+ }
2336
+ if (process5.platform === "linux") {
2337
+ const { stdout } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
2338
+ const id = stdout.trim();
2339
+ const name = titleize(id.replace(/.desktop$/, "").replace("-", " "));
2340
+ return { name, id };
2341
+ }
2342
+ if (process5.platform === "win32") {
2343
+ return defaultBrowser();
2344
+ }
2345
+ throw new Error("Only macOS, Linux, and Windows are supported");
2346
+ }
2347
+
2348
+ // ../../node_modules/.pnpm/open@10.0.3/node_modules/open/index.js
2349
+ var __dirname = path4.dirname(fileURLToPath2(import.meta.url));
2350
+ var localXdgOpenPath = path4.join(__dirname, "xdg-open");
2351
+ var { platform, arch } = process6;
2352
+ var getWslDrivesMountPoint = /* @__PURE__ */ (() => {
2353
+ const defaultMountPoint = "/mnt/";
2354
+ let mountPoint;
2355
+ return async function() {
2356
+ if (mountPoint) {
2357
+ return mountPoint;
2358
+ }
2359
+ const configFilePath = "/etc/wsl.conf";
2360
+ let isConfigFileExists = false;
2361
+ try {
2362
+ await fs5.access(configFilePath, fsConstants.F_OK);
2363
+ isConfigFileExists = true;
2364
+ } catch {
2365
+ }
2366
+ if (!isConfigFileExists) {
2367
+ return defaultMountPoint;
2368
+ }
2369
+ const configContent = await fs5.readFile(configFilePath, { encoding: "utf8" });
2370
+ const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
2371
+ if (!configMountPoint) {
2372
+ return defaultMountPoint;
2373
+ }
2374
+ mountPoint = configMountPoint.groups.mountPoint.trim();
2375
+ mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
2376
+ return mountPoint;
2377
+ };
2378
+ })();
2379
+ var pTryEach = async (array, mapper) => {
2380
+ let latestError;
2381
+ for (const item of array) {
2382
+ try {
2383
+ return await mapper(item);
2384
+ } catch (error) {
2385
+ latestError = error;
2386
+ }
2387
+ }
2388
+ throw latestError;
2389
+ };
2390
+ var baseOpen = async (options) => {
2391
+ options = {
2392
+ wait: false,
2393
+ background: false,
2394
+ newInstance: false,
2395
+ allowNonzeroExitCode: false,
2396
+ ...options
2397
+ };
2398
+ if (Array.isArray(options.app)) {
2399
+ return pTryEach(options.app, (singleApp) => baseOpen({
2400
+ ...options,
2401
+ app: singleApp
2402
+ }));
2403
+ }
2404
+ let { name: app, arguments: appArguments = [] } = options.app ?? {};
2405
+ appArguments = [...appArguments];
2406
+ if (Array.isArray(app)) {
2407
+ return pTryEach(app, (appName) => baseOpen({
2408
+ ...options,
2409
+ app: {
2410
+ name: appName,
2411
+ arguments: appArguments
2412
+ }
2413
+ }));
2414
+ }
2415
+ if (app === "browser" || app === "browserPrivate") {
2416
+ const ids = {
2417
+ "com.google.chrome": "chrome",
2418
+ "google-chrome.desktop": "chrome",
2419
+ "org.mozilla.firefox": "firefox",
2420
+ "firefox.desktop": "firefox",
2421
+ "com.microsoft.msedge": "edge",
2422
+ "com.microsoft.edge": "edge",
2423
+ "microsoft-edge.desktop": "edge"
2424
+ };
2425
+ const flags = {
2426
+ chrome: "--incognito",
2427
+ firefox: "--private-window",
2428
+ edge: "--inPrivate"
2429
+ };
2430
+ const browser = await defaultBrowser2();
2431
+ if (browser.id in ids) {
2432
+ const browserName = ids[browser.id];
2433
+ if (app === "browserPrivate") {
2434
+ appArguments.push(flags[browserName]);
2435
+ }
2436
+ return baseOpen({
2437
+ ...options,
2438
+ app: {
2439
+ name: apps[browserName],
2440
+ arguments: appArguments
2441
+ }
2442
+ });
2443
+ }
2444
+ throw new Error(`${browser.name} is not supported as a default browser`);
2445
+ }
2446
+ let command;
2447
+ const cliArguments = [];
2448
+ const childProcessOptions = {};
2449
+ if (platform === "darwin") {
2450
+ command = "open";
2451
+ if (options.wait) {
2452
+ cliArguments.push("--wait-apps");
2453
+ }
2454
+ if (options.background) {
2455
+ cliArguments.push("--background");
2456
+ }
2457
+ if (options.newInstance) {
2458
+ cliArguments.push("--new");
2459
+ }
2460
+ if (app) {
2461
+ cliArguments.push("-a", app);
2462
+ }
2463
+ } else if (platform === "win32" || is_wsl_default && !isInsideContainer() && !app) {
2464
+ const mountPoint = await getWslDrivesMountPoint();
2465
+ command = is_wsl_default ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${process6.env.SYSTEMROOT || process6.env.windir || "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
2466
+ cliArguments.push(
2467
+ "-NoProfile",
2468
+ "-NonInteractive",
2469
+ "-ExecutionPolicy",
2470
+ "Bypass",
2471
+ "-EncodedCommand"
2472
+ );
2473
+ if (!is_wsl_default) {
2474
+ childProcessOptions.windowsVerbatimArguments = true;
2475
+ }
2476
+ const encodedArguments = ["Start"];
2477
+ if (options.wait) {
2478
+ encodedArguments.push("-Wait");
2479
+ }
2480
+ if (app) {
2481
+ encodedArguments.push(`"\`"${app}\`""`);
2482
+ if (options.target) {
2483
+ appArguments.push(options.target);
2484
+ }
2485
+ } else if (options.target) {
2486
+ encodedArguments.push(`"${options.target}"`);
2487
+ }
2488
+ if (appArguments.length > 0) {
2489
+ appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
2490
+ encodedArguments.push("-ArgumentList", appArguments.join(","));
2491
+ }
2492
+ options.target = Buffer2.from(encodedArguments.join(" "), "utf16le").toString("base64");
2493
+ } else {
2494
+ if (app) {
2495
+ command = app;
2496
+ } else {
2497
+ const isBundled = !__dirname || __dirname === "/";
2498
+ let exeLocalXdgOpen = false;
2499
+ try {
2500
+ await fs5.access(localXdgOpenPath, fsConstants.X_OK);
2501
+ exeLocalXdgOpen = true;
2502
+ } catch {
2503
+ }
2504
+ const useSystemXdgOpen = process6.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen);
2505
+ command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
2506
+ }
2507
+ if (appArguments.length > 0) {
2508
+ cliArguments.push(...appArguments);
2509
+ }
2510
+ if (!options.wait) {
2511
+ childProcessOptions.stdio = "ignore";
2512
+ childProcessOptions.detached = true;
2513
+ }
2514
+ }
2515
+ if (platform === "darwin" && appArguments.length > 0) {
2516
+ cliArguments.push("--args", ...appArguments);
2517
+ }
2518
+ if (options.target) {
2519
+ cliArguments.push(options.target);
2520
+ }
2521
+ const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
2522
+ if (options.wait) {
2523
+ return new Promise((resolve2, reject) => {
2524
+ subprocess.once("error", reject);
2525
+ subprocess.once("close", (exitCode) => {
2526
+ if (!options.allowNonzeroExitCode && exitCode > 0) {
2527
+ reject(new Error(`Exited with code ${exitCode}`));
2528
+ return;
2529
+ }
2530
+ resolve2(subprocess);
2531
+ });
2532
+ });
2533
+ }
2534
+ subprocess.unref();
2535
+ return subprocess;
2536
+ };
2537
+ var open = (target, options) => {
2538
+ if (typeof target !== "string") {
2539
+ throw new TypeError("Expected a `target`");
2540
+ }
2541
+ return baseOpen({
2542
+ ...options,
2543
+ target
2544
+ });
2545
+ };
2546
+ function detectArchBinary(binary) {
2547
+ if (typeof binary === "string" || Array.isArray(binary)) {
2548
+ return binary;
2549
+ }
2550
+ const { [arch]: archBinary } = binary;
2551
+ if (!archBinary) {
2552
+ throw new Error(`${arch} is not supported`);
2553
+ }
2554
+ return archBinary;
2555
+ }
2556
+ function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
2557
+ if (wsl && is_wsl_default) {
2558
+ return detectArchBinary(wsl);
2559
+ }
2560
+ if (!platformBinary) {
2561
+ throw new Error(`${platform} is not supported`);
2562
+ }
2563
+ return detectArchBinary(platformBinary);
2564
+ }
2565
+ var apps = {};
2566
+ defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
2567
+ darwin: "google chrome",
2568
+ win32: "chrome",
2569
+ linux: ["google-chrome", "google-chrome-stable", "chromium"]
2570
+ }, {
2571
+ wsl: {
2572
+ ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
2573
+ x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
2574
+ }
2575
+ }));
2576
+ defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
2577
+ darwin: "firefox",
2578
+ win32: "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
2579
+ linux: "firefox"
2580
+ }, {
2581
+ wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
2582
+ }));
2583
+ defineLazyProperty(apps, "edge", () => detectPlatformBinary({
2584
+ darwin: "microsoft edge",
2585
+ win32: "msedge",
2586
+ linux: ["microsoft-edge", "microsoft-edge-dev"]
2587
+ }, {
2588
+ wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
2589
+ }));
2590
+ defineLazyProperty(apps, "browser", () => "browser");
2591
+ defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
2592
+ var open_default = open;
2593
+
2594
+ // ../../node_modules/.pnpm/p-retry@6.1.0/node_modules/p-retry/index.js
2595
+ var import_retry = __toESM(require_retry2(), 1);
2596
+
2597
+ // ../../node_modules/.pnpm/is-network-error@1.0.0/node_modules/is-network-error/index.js
2598
+ var objectToString = Object.prototype.toString;
2599
+ var isError = (value) => objectToString.call(value) === "[object Error]";
2600
+ var errorMessages = /* @__PURE__ */ new Set([
2601
+ "Failed to fetch",
2602
+ // Chrome
2603
+ "NetworkError when attempting to fetch resource.",
2604
+ // Firefox
2605
+ "The Internet connection appears to be offline.",
2606
+ // Safari 16
2607
+ "Load failed",
2608
+ // Safari 17+
2609
+ "Network request failed",
2610
+ // `cross-fetch`
2611
+ "fetch failed"
2612
+ // Undici (Node.js)
2613
+ ]);
2614
+ function isNetworkError(error) {
2615
+ const isValid = error && isError(error) && error.name === "TypeError" && typeof error.message === "string";
2616
+ if (!isValid) {
2617
+ return false;
2618
+ }
2619
+ if (error.message === "Load failed") {
2620
+ return error.stack === void 0;
2621
+ }
2622
+ return errorMessages.has(error.message);
2623
+ }
2624
+
2625
+ // ../../node_modules/.pnpm/p-retry@6.1.0/node_modules/p-retry/index.js
2626
+ var AbortError = class extends Error {
2627
+ constructor(message) {
2628
+ super();
2629
+ if (message instanceof Error) {
2630
+ this.originalError = message;
2631
+ ({ message } = message);
2632
+ } else {
2633
+ this.originalError = new Error(message);
2634
+ this.originalError.stack = this.stack;
2635
+ }
2636
+ this.name = "AbortError";
2637
+ this.message = message;
2638
+ }
2639
+ };
2640
+ var decorateErrorWithCounts = (error, attemptNumber, options) => {
2641
+ const retriesLeft = options.retries - (attemptNumber - 1);
2642
+ error.attemptNumber = attemptNumber;
2643
+ error.retriesLeft = retriesLeft;
2644
+ return error;
2645
+ };
2646
+ async function pRetry(input, options) {
2647
+ return new Promise((resolve2, reject) => {
2648
+ options = {
2649
+ onFailedAttempt() {
2650
+ },
2651
+ retries: 10,
2652
+ ...options
2653
+ };
2654
+ const operation = import_retry.default.operation(options);
2655
+ const abortHandler = () => {
2656
+ operation.stop();
2657
+ reject(options.signal?.reason);
2658
+ };
2659
+ if (options.signal && !options.signal.aborted) {
2660
+ options.signal.addEventListener("abort", abortHandler, { once: true });
2661
+ }
2662
+ const cleanUp = () => {
2663
+ options.signal?.removeEventListener("abort", abortHandler);
2664
+ operation.stop();
2665
+ };
2666
+ operation.attempt(async (attemptNumber) => {
2667
+ try {
2668
+ const result = await input(attemptNumber);
2669
+ cleanUp();
2670
+ resolve2(result);
2671
+ } catch (error) {
2672
+ try {
2673
+ if (!(error instanceof Error)) {
2674
+ throw new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
2675
+ }
2676
+ if (error instanceof AbortError) {
2677
+ throw error.originalError;
2678
+ }
2679
+ if (error instanceof TypeError && !isNetworkError(error)) {
2680
+ throw error;
2681
+ }
2682
+ await options.onFailedAttempt(decorateErrorWithCounts(error, attemptNumber, options));
2683
+ if (!operation.retry(error)) {
2684
+ throw operation.mainError();
2685
+ }
2686
+ } catch (finalError) {
2687
+ decorateErrorWithCounts(finalError, attemptNumber, options);
2688
+ cleanUp();
2689
+ reject(finalError);
2690
+ }
2691
+ }
2692
+ });
2693
+ });
2694
+ }
2695
+
2696
+ // src/commands/whoami.ts
2697
+ import { note, spinner as spinner2 } from "@clack/prompts";
2698
+ var WhoamiCommandOptions = CommonCommandOptions;
2699
+ function configureWhoamiCommand(program2) {
2700
+ program2.command("whoami").description("display the current logged in user and project details").option(
2701
+ "-l, --log-level <level>",
2702
+ "The log level to use (debug, info, log, warn, error, none)",
2703
+ "log"
2704
+ ).action(async (options) => {
2705
+ try {
2706
+ await printInitialBanner();
2707
+ await whoAmI(WhoamiCommandOptions.parse(options));
2708
+ } catch (e) {
2709
+ throw e;
2710
+ }
2711
+ });
2712
+ }
2713
+ async function whoAmI(options) {
2714
+ if (options?.logLevel) {
2715
+ logger.loggerLevel = options?.logLevel;
2716
+ }
2717
+ const loadingSpinner = spinner2();
2718
+ loadingSpinner.start("Checking your account details");
2719
+ const authentication = await isLoggedIn();
2720
+ if (!authentication.ok) {
2721
+ loadingSpinner.stop("You must login first. Use `trigger.dev login` to login.");
2722
+ return {
2723
+ success: false,
2724
+ error: authentication.error
2725
+ };
2726
+ }
2727
+ const apiClient2 = new ApiClient(authentication.config.apiUrl, authentication.config.accessToken);
2728
+ const userData = await apiClient2.whoAmI();
2729
+ if (!userData.success) {
2730
+ loadingSpinner.stop("Error getting your account details");
2731
+ logger.error(userData.error);
2732
+ return {
2733
+ success: false,
2734
+ error: userData.error
2735
+ };
2736
+ }
2737
+ loadingSpinner.stop("Retrieved your account details");
2738
+ note(
2739
+ `User ID: ${userData.data.userId}
2740
+ Email: ${userData.data.email}
2741
+ URL: ${chalkLink(authentication.config.apiUrl)}
2742
+ `,
2743
+ "Account details"
2744
+ );
2745
+ return userData;
2746
+ }
2747
+
2748
+ // src/commands/login.ts
2749
+ async function loginCommand(options) {
2750
+ const result = ApiUrlOptionsSchema.safeParse(options);
2751
+ if (!result.success) {
2752
+ logger.error(result.error.message);
2753
+ return;
2754
+ }
2755
+ return login(result.data.apiUrl);
2756
+ }
2757
+ async function login(apiUrl) {
2758
+ const apiClient2 = new ApiClient(apiUrl);
2759
+ intro("Logging in to Trigger.dev");
2760
+ const existingAccessToken = readAuthConfigFile()?.accessToken;
2761
+ if (existingAccessToken) {
2762
+ const whoAmiI = await whoAmI();
2763
+ const continueOption = await select({
2764
+ message: "You are already logged in.",
2765
+ options: [
2766
+ {
2767
+ value: false,
2768
+ label: "Exit"
2769
+ },
2770
+ {
2771
+ value: true,
2772
+ label: "Login with a different account"
2773
+ }
2774
+ ],
2775
+ initialValue: false
2776
+ });
2777
+ if (continueOption !== true) {
2778
+ outro("Already logged in");
2779
+ return {
2780
+ success: true,
2781
+ accessToken: existingAccessToken
2782
+ };
2783
+ }
2784
+ }
2785
+ const createAuthCodeSpinner = spinner3();
2786
+ createAuthCodeSpinner.start("Creating authorition code");
2787
+ const authorizationCodeResult = await apiClient2.createAuthorizationCode();
2788
+ if (!authorizationCodeResult.success) {
2789
+ createAuthCodeSpinner.stop(
2790
+ `Failed to create authorization code
2791
+ ${authorizationCodeResult.error}`
2792
+ );
2793
+ return {
2794
+ success: false,
2795
+ error: authorizationCodeResult.error
2796
+ };
2797
+ }
2798
+ createAuthCodeSpinner.stop("Created authorization code");
2799
+ log.step(
2800
+ `Please visit the following URL to login:
2801
+ ${chalkLink(authorizationCodeResult.data.url)}`
2802
+ );
2803
+ await open_default(authorizationCodeResult.data.url);
2804
+ const getPersonalAccessTokenSpinner = spinner3();
2805
+ getPersonalAccessTokenSpinner.start("Waiting for you to login");
2806
+ try {
2807
+ const indexResult = await pRetry(
2808
+ () => getPersonalAccessToken(apiClient2, authorizationCodeResult.data.authorizationCode),
2809
+ {
2810
+ //this means we're polling, same distance between each attempt
2811
+ factor: 1,
2812
+ retries: 60,
2813
+ minTimeout: 1e3
2814
+ }
2815
+ );
2816
+ getPersonalAccessTokenSpinner.stop(`Logged in with token ${indexResult.obfuscatedToken}`);
2817
+ writeAuthConfigFile({ accessToken: indexResult.token, apiUrl });
2818
+ outro("Logged in successfully");
2819
+ return {
2820
+ success: true,
2821
+ accessToken: indexResult.token
2822
+ };
2823
+ } catch (e) {
2824
+ getPersonalAccessTokenSpinner.stop(`Failed to get access token`);
2825
+ if (e instanceof AbortError) {
2826
+ log.error(e.message);
2827
+ }
2828
+ return {
2829
+ success: false,
2830
+ error: e instanceof Error ? e.message : JSON.stringify(e)
2831
+ };
2832
+ }
2833
+ }
2834
+ async function getPersonalAccessToken(apiClient2, authorizationCode) {
2835
+ const token = await apiClient2.getPersonalAccessToken(authorizationCode);
2836
+ if (!token.success) {
2837
+ throw new AbortError(token.error);
2838
+ }
2839
+ if (!token.data.token) {
2840
+ throw new Error("No token found yet");
2841
+ }
2842
+ return {
2843
+ token: token.data.token.token,
2844
+ obfuscatedToken: token.data.token.obfuscatedToken
2845
+ };
2846
+ }
2847
+
2848
+ // src/commands/logout.ts
2849
+ async function logoutCommand(options) {
2850
+ const config = readAuthConfigFile();
2851
+ if (!config?.accessToken) {
2852
+ logger.info("You are already logged out");
2853
+ return;
2854
+ }
2855
+ writeAuthConfigFile({ ...config, accessToken: void 0, apiUrl: void 0 });
2856
+ logger.info("Logged out");
2857
+ }
2858
+
2859
+ // src/commands/update.ts
2860
+ import { confirm, spinner as spinner5 } from "@clack/prompts";
2861
+ import { run } from "npm-check-updates";
2862
+ import path5 from "path";
2863
+ import { z as z4 } from "zod";
2864
+
2865
+ // src/utilities/installDependencies.ts
2866
+ import { spinner as spinner4 } from "@clack/prompts";
2867
+ import chalk6 from "chalk";
2868
+ import { execa } from "execa";
2869
+
2870
+ // src/utilities/getUserPackageManager.ts
2871
+ import pathModule from "path";
2872
+ async function getUserPackageManager(path6) {
2873
+ try {
2874
+ return await detectPackageManagerFromArtifacts(path6);
2875
+ } catch (error) {
2876
+ return detectPackageManagerFromCurrentCommand();
2877
+ }
2878
+ }
2879
+ function detectPackageManagerFromCurrentCommand() {
2880
+ const userAgent = process.env.npm_config_user_agent;
2881
+ if (userAgent) {
2882
+ if (userAgent.startsWith("yarn")) {
2883
+ return "yarn";
2884
+ } else if (userAgent.startsWith("pnpm")) {
2885
+ return "pnpm";
2886
+ } else {
2887
+ return "npm";
2888
+ }
2889
+ } else {
2890
+ return "npm";
2891
+ }
2892
+ }
2893
+ async function detectPackageManagerFromArtifacts(path6) {
2894
+ const packageFiles = [
2895
+ { name: "yarn.lock", pm: "yarn" },
2896
+ { name: "pnpm-lock.yaml", pm: "pnpm" },
2897
+ { name: "package-lock.json", pm: "npm" },
2898
+ { name: "npm-shrinkwrap.json", pm: "npm" }
2899
+ ];
2900
+ for (const { name, pm } of packageFiles) {
2901
+ const exists = await pathExists(pathModule.join(path6, name));
2902
+ if (exists) {
2903
+ return pm;
2904
+ }
2905
+ }
2906
+ throw new Error("Could not detect package manager from artifacts");
2907
+ }
2908
+
2909
+ // src/utilities/installDependencies.ts
2910
+ async function installDependencies(projectDir) {
2911
+ logger.info("Installing dependencies...");
2912
+ const pkgManager = await getUserPackageManager(projectDir);
2913
+ const installSpinner = await runInstallCommand(pkgManager, projectDir);
2914
+ (installSpinner || spinner4()).stop(chalk6.green("Successfully installed dependencies!\n"));
2915
+ }
2916
+ async function runInstallCommand(pkgManager, projectDir) {
2917
+ switch (pkgManager) {
2918
+ case "npm":
2919
+ await execa(pkgManager, ["install"], {
2920
+ cwd: projectDir,
2921
+ stderr: "inherit"
2922
+ });
2923
+ return null;
2924
+ case "pnpm": {
2925
+ const loadingSpinner = spinner4();
2926
+ loadingSpinner.start("Running pnpm install...");
2927
+ const pnpmSubprocess = execa(pkgManager, ["install"], {
2928
+ cwd: projectDir,
2929
+ stdout: "pipe"
2930
+ });
2931
+ await new Promise((res, rej) => {
2932
+ pnpmSubprocess.stdout?.on("data", (data) => {
2933
+ const text = data.toString();
2934
+ if (text.includes("Progress")) {
2935
+ loadingSpinner.message(text.includes("|") ? text.split(" | ")[1] ?? "" : text);
2936
+ }
2937
+ });
2938
+ pnpmSubprocess.on("error", (e) => rej(e));
2939
+ pnpmSubprocess.on("close", () => res());
2940
+ });
2941
+ return loadingSpinner;
2942
+ }
2943
+ case "yarn": {
2944
+ const loadingSpinner = spinner4();
2945
+ loadingSpinner.start("Running yarn...");
2946
+ const yarnSubprocess = execa(pkgManager, [], {
2947
+ cwd: projectDir,
2948
+ stdout: "pipe"
2949
+ });
2950
+ await new Promise((res, rej) => {
2951
+ yarnSubprocess.stdout?.on("data", (data) => {
2952
+ loadingSpinner.message(data.toString());
2953
+ });
2954
+ yarnSubprocess.on("error", (e) => rej(e));
2955
+ yarnSubprocess.on("close", () => res());
2956
+ });
2957
+ return loadingSpinner;
2958
+ }
2959
+ }
2960
+ }
2961
+
2962
+ // src/commands/update.ts
2963
+ var UpdateCommandOptionsSchema = z4.object({
2964
+ to: z4.string().optional()
2965
+ });
2966
+ async function updateCommand(projectPath, anyOptions) {
2967
+ const loadingSpinner = spinner5();
2968
+ loadingSpinner.start("Checking settings");
2969
+ const parseRes = UpdateCommandOptionsSchema.safeParse(anyOptions);
2970
+ if (!parseRes.success) {
2971
+ loadingSpinner.stop(chalkError(parseRes.error.message));
2972
+ return;
2973
+ }
2974
+ const options = parseRes.data;
2975
+ const triggerDevPackage = "@trigger.dev";
2976
+ const packageJSONPath = path5.join(projectPath, "package.json");
2977
+ const packageData = readJSONFileSync(packageJSONPath);
2978
+ if (!packageData) {
2979
+ loadingSpinner.stop(chalkError("Couldn't load package.json"));
2980
+ return;
2981
+ }
2982
+ loadingSpinner.message("Checking for updates");
2983
+ const packageMaps = {};
2984
+ const packageDependencies = packageData.dependencies || {};
2985
+ const packageDevDependencies = packageData.devDependencies || {};
2986
+ Object.keys(packageDependencies).forEach((i) => {
2987
+ packageMaps[i] = { type: "dependencies", version: packageDependencies[i] };
2988
+ });
2989
+ Object.keys(packageDevDependencies).forEach((i) => {
2990
+ packageMaps[i] = {
2991
+ type: "devDependencies",
2992
+ version: packageDevDependencies[i]
2993
+ };
2994
+ });
2995
+ const targetVersion = getTargetVersion(options.to);
2996
+ const ncuOptions = {
2997
+ packageData,
2998
+ upgrade: true,
2999
+ jsonUpgraded: true,
3000
+ target: targetVersion
3001
+ };
3002
+ const updatedDependencies = await run(ncuOptions);
3003
+ if (!updatedDependencies) {
3004
+ loadingSpinner.stop(chalkError("Couldn't update dependencies"));
3005
+ return;
3006
+ }
3007
+ const ifUpdatedDependenciesIsPackageJSON = updatedDependencies.hasOwnProperty("dependencies") || updatedDependencies.hasOwnProperty("devDependencies");
3008
+ const dependencies = updatedDependencies.dependencies || {};
3009
+ const devDependencies = updatedDependencies.devDependencies || {};
3010
+ const allDependencies = ifUpdatedDependenciesIsPackageJSON ? Object.keys({ ...dependencies, ...devDependencies }) : Object.keys(updatedDependencies);
3011
+ const triggerPackages = allDependencies.filter((pkg) => pkg.startsWith(triggerDevPackage));
3012
+ if (triggerPackages.length === 0) {
3013
+ loadingSpinner.stop(chalkSuccess(`All @trigger.dev/* packages are already up to date.`));
3014
+ return;
3015
+ }
3016
+ const packagesToUpdate = triggerPackages.filter((pkg) => updatedDependencies[pkg]);
3017
+ if (packagesToUpdate.length === 0) {
3018
+ loadingSpinner.stop(chalkSuccess(`All @trigger.dev/* packages are already up to date.`));
3019
+ return;
3020
+ }
3021
+ let applyUpdates = targetVersion !== "latest";
3022
+ if (targetVersion === "latest") {
3023
+ applyUpdates = await hasUserConfirmed(packagesToUpdate, packageMaps, updatedDependencies);
3024
+ }
3025
+ if (applyUpdates) {
3026
+ const newPackageJSON = packageData;
3027
+ packagesToUpdate.forEach((packageName) => {
3028
+ const tmp = packageMaps[packageName];
3029
+ if (tmp) {
3030
+ newPackageJSON[tmp.type][packageName] = updatedDependencies[packageName];
3031
+ }
3032
+ });
3033
+ await writeJSONFile(packageJSONPath, newPackageJSON);
3034
+ await installDependencies(projectPath);
3035
+ }
3036
+ }
3037
+ function getTargetVersion(toVersion) {
3038
+ if (!toVersion) {
3039
+ return "latest";
3040
+ }
3041
+ return toVersion === "latest" ? "latest" : `@${toVersion}`;
3042
+ }
3043
+ async function hasUserConfirmed(packagesToUpdate, packageMaps, updatedDependencies) {
3044
+ console.log("\nNewer versions found for the following packages:");
3045
+ console.table(
3046
+ packagesToUpdate.map((i) => ({
3047
+ name: i,
3048
+ old: packageMaps[i]?.version,
3049
+ new: updatedDependencies[i]
3050
+ }))
3051
+ );
3052
+ const shouldContinue = await confirm({
3053
+ message: "Do you want to update these packages in package.json and re-install dependencies?"
3054
+ });
3055
+ return shouldContinue;
3056
+ }
3057
+
3058
+ // src/cli/index.ts
3059
+ var program = new Command();
3060
+ var ApiUrlOptionsSchema = z5.object({
3061
+ apiUrl: z5.string()
3062
+ });
3063
+ program.name(COMMAND_NAME).description("Create, run locally and deploy Trigger.dev background tasks.").version(getVersion(), "-v, --version", "Display the version number");
3064
+ program.command("login").description("Login with Trigger.dev so you can perform authenticated actions").option(
3065
+ "-a, --api-url <value>",
3066
+ "Override the API URL, defaults to https://api.trigger.dev",
3067
+ "https://api.trigger.dev"
3068
+ ).version(getVersion(), "-v, --version", "Display the version number").action(async (options) => {
3069
+ try {
3070
+ await printInitialBanner(false);
3071
+ await loginCommand(options);
3072
+ } catch (e) {
3073
+ throw e;
3074
+ }
3075
+ });
3076
+ program.command("logout").description("Logout of Trigger.dev").version(getVersion(), "-v, --version", "Display the version number").action(async (options) => {
3077
+ try {
3078
+ await printInitialBanner(false);
3079
+ await logoutCommand(options);
3080
+ } catch (e) {
3081
+ throw e;
3082
+ }
3083
+ });
3084
+ configureDevCommand(program);
3085
+ program.command("update").description(
3086
+ "Updates all @trigger.dev/* packages to their latest compatible versions or the specified version"
3087
+ ).argument("[path]", "The path to the directory that contains the package.json file", ".").option("-t, --to <version tag>", "The version to update to (ex: 2.1.4)", "latest").action(async (path6, options) => {
3088
+ await printInitialBanner(false);
3089
+ await updateCommand(path6, options);
3090
+ });
3091
+ configureWhoamiCommand(program);
3092
+
3093
+ // src/index.ts
3094
+ var main = async () => {
3095
+ await program.parseAsync();
3096
+ };
3097
+ main().catch((err) => {
3098
+ if (err instanceof Error) {
3099
+ logger.error(err);
3100
+ } else {
3101
+ logger.error("An unknown error has occurred. Please open an issue on github with the below:");
3102
+ logger.error(err);
3103
+ }
3104
+ process.exit(1);
3105
+ });
3106
+ //# sourceMappingURL=index.js.map