buncargo 3.2.3 → 3.2.4

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.
@@ -0,0 +1,417 @@
1
+ import {
2
+ sleep
3
+ } from "./index-fkgqg6w2.js";
4
+
5
+ // src/core/quick-tunnel/index.ts
6
+ import { existsSync } from "node:fs";
7
+ import { createInterface } from "node:readline";
8
+
9
+ // src/core/quick-tunnel/cloudflared-process.ts
10
+ import { spawn } from "node:child_process";
11
+
12
+ // src/core/quick-tunnel/constants.ts
13
+ import { tmpdir } from "node:os";
14
+ import path from "node:path";
15
+ var CLOUDFLARED_VERSION = process.env.CLOUDFLARED_VERSION || "2023.10.0";
16
+ var RELEASE_BASE = "https://github.com/cloudflare/cloudflared/releases/";
17
+ var cloudflaredBinPath = path.join(tmpdir(), "buncargo-cloudflared", process.platform === "win32" ? `cloudflared.${CLOUDFLARED_VERSION}.exe` : `cloudflared.${CLOUDFLARED_VERSION}`);
18
+ var cloudflaredNotice = `
19
+ \uD83D\uDD25 Your installation of cloudflared software constitutes a symbol of your signature
20
+ indicating that you accept the terms of the Cloudflare License, Terms and Privacy Policy.
21
+
22
+ ❯ License: \`https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/license/\`
23
+ ❯ Terms: \`https://www.cloudflare.com/terms/\`
24
+ ❯ Privacy Policy: \`https://www.cloudflare.com/privacypolicy/\`
25
+ `;
26
+
27
+ // src/core/quick-tunnel/cloudflared-process.ts
28
+ var urlRegexPipe = /\|\s+(https?:\/\/\S+)/;
29
+ var urlRegexTryCloudflare = /(https:\/\/[a-zA-Z0-9][-a-zA-Z0-9.]*\.trycloudflare\.com)\b/;
30
+ var MAX_CAPTURED_LOG = 24000;
31
+ function parseQuickTunnelUrlFromOutput(log) {
32
+ const pipe = log.match(urlRegexPipe);
33
+ if (pipe?.[1]) {
34
+ return pipe[1];
35
+ }
36
+ const direct = log.match(urlRegexTryCloudflare);
37
+ return direct?.[1] ?? null;
38
+ }
39
+ function startCloudflaredTunnel(options) {
40
+ const args = ["tunnel"];
41
+ for (const [key, value] of Object.entries(options)) {
42
+ if (typeof value === "string") {
43
+ args.push(`${key}`, value);
44
+ } else if (typeof value === "number") {
45
+ args.push(`${key}`, value.toString());
46
+ } else if (value === null) {
47
+ args.push(`${key}`);
48
+ }
49
+ }
50
+ if (args.length === 1) {
51
+ args.push("--url", "localhost:8080");
52
+ }
53
+ const child = spawn(cloudflaredBinPath, args, {
54
+ stdio: ["ignore", "pipe", "pipe"]
55
+ });
56
+ if (process.env.DEBUG) {
57
+ child.stdout?.pipe(process.stdout);
58
+ child.stderr?.pipe(process.stderr);
59
+ }
60
+ let settled = false;
61
+ let urlResolver;
62
+ let urlRejector;
63
+ const url = new Promise((resolve, reject) => {
64
+ urlResolver = (v) => {
65
+ if (!settled) {
66
+ settled = true;
67
+ resolve(v);
68
+ }
69
+ };
70
+ urlRejector = (e) => {
71
+ if (!settled) {
72
+ settled = true;
73
+ reject(e);
74
+ }
75
+ };
76
+ });
77
+ const log = { buf: "" };
78
+ const append = (data) => {
79
+ log.buf += data.toString();
80
+ if (log.buf.length > MAX_CAPTURED_LOG) {
81
+ log.buf = log.buf.slice(-MAX_CAPTURED_LOG);
82
+ }
83
+ const url2 = parseQuickTunnelUrlFromOutput(log.buf);
84
+ if (url2) {
85
+ urlResolver(url2);
86
+ }
87
+ };
88
+ child.stdout?.on("data", append).on("error", urlRejector);
89
+ child.stderr?.on("data", append).on("error", urlRejector);
90
+ child.on("exit", (code, signal) => {
91
+ if (!settled) {
92
+ const tail = log.buf.trimEnd();
93
+ const excerpt = tail.length > 1200 ? `…${tail.slice(-1200)}` : tail;
94
+ const detail = excerpt ? `
95
+ cloudflared output (tail):
96
+ ${excerpt}` : "";
97
+ urlRejector(new Error(`cloudflared exited before a tunnel URL was parsed (code=${code}, signal=${signal ?? "none"}). ` + `Parallel quick-tunnel requests are often rate-limited; buncargo starts tunnels sequentially with a short pause. ` + `If this persists, try fewer expose targets or increase BUNCARGO_EXPOSE_TUNNEL_STAGGER_MS.${detail}`));
98
+ }
99
+ });
100
+ child.on("error", urlRejector);
101
+ const stop = () => child.kill("SIGINT");
102
+ return { url, child, stop };
103
+ }
104
+
105
+ // src/core/quick-tunnel/install.ts
106
+ import { execSync } from "node:child_process";
107
+ import fs from "node:fs";
108
+ import https from "node:https";
109
+ import path2 from "node:path";
110
+ var LINUX_URL = {
111
+ arm64: "cloudflared-linux-arm64",
112
+ arm: "cloudflared-linux-arm",
113
+ x64: "cloudflared-linux-amd64",
114
+ ia32: "cloudflared-linux-386"
115
+ };
116
+ var MACOS_URL = {
117
+ arm64: "cloudflared-darwin-amd64.tgz",
118
+ x64: "cloudflared-darwin-amd64.tgz"
119
+ };
120
+ var WINDOWS_URL = {
121
+ x64: "cloudflared-windows-amd64.exe",
122
+ ia32: "cloudflared-windows-386.exe"
123
+ };
124
+ function resolveBase(version) {
125
+ if (version === "latest") {
126
+ return `${RELEASE_BASE}latest/download/`;
127
+ }
128
+ return `${RELEASE_BASE}download/${version}/`;
129
+ }
130
+ function installCloudflared(to = cloudflaredBinPath, version = CLOUDFLARED_VERSION) {
131
+ switch (process.platform) {
132
+ case "linux": {
133
+ return installLinux(to, version);
134
+ }
135
+ case "darwin": {
136
+ return installMacos(to, version);
137
+ }
138
+ case "win32": {
139
+ return installWindows(to, version);
140
+ }
141
+ default: {
142
+ throw new Error(`Unsupported platform: ${process.platform}`);
143
+ }
144
+ }
145
+ }
146
+ async function installLinux(to, version = CLOUDFLARED_VERSION) {
147
+ const file = LINUX_URL[process.arch];
148
+ if (file === undefined) {
149
+ throw new Error(`Unsupported architecture: ${process.arch}`);
150
+ }
151
+ await download(resolveBase(version) + file, to);
152
+ fs.chmodSync(to, 493);
153
+ return to;
154
+ }
155
+ async function installMacos(to, version = CLOUDFLARED_VERSION) {
156
+ const file = MACOS_URL[process.arch];
157
+ if (file === undefined) {
158
+ throw new Error(`Unsupported architecture: ${process.arch}`);
159
+ }
160
+ await download(resolveBase(version) + file, `${to}.tgz`);
161
+ if (process.env.DEBUG) {
162
+ console.log(`Extracting to ${to}`);
163
+ }
164
+ execSync(`tar -xzf ${path2.basename(`${to}.tgz`)}`, {
165
+ cwd: path2.dirname(to)
166
+ });
167
+ fs.unlinkSync(`${to}.tgz`);
168
+ fs.renameSync(`${path2.dirname(to)}/cloudflared`, to);
169
+ return to;
170
+ }
171
+ async function installWindows(to, version = CLOUDFLARED_VERSION) {
172
+ const file = WINDOWS_URL[process.arch];
173
+ if (file === undefined) {
174
+ throw new Error(`Unsupported architecture: ${process.arch}`);
175
+ }
176
+ await download(resolveBase(version) + file, to);
177
+ return to;
178
+ }
179
+ function download(url, to, redirect = 0) {
180
+ if (redirect === 0) {
181
+ if (process.env.DEBUG) {
182
+ console.log(`Downloading ${url} to ${to}`);
183
+ }
184
+ } else if (process.env.DEBUG) {
185
+ console.log(`Redirecting to ${url}`);
186
+ }
187
+ return new Promise((resolve, reject) => {
188
+ if (!fs.existsSync(path2.dirname(to))) {
189
+ fs.mkdirSync(path2.dirname(to), { recursive: true });
190
+ }
191
+ let done = true;
192
+ const file = fs.createWriteStream(to);
193
+ const request = https.get(url, (res) => {
194
+ if (res.statusCode === 302 && res.headers.location !== undefined) {
195
+ const redirection = res.headers.location;
196
+ done = false;
197
+ file.close(() => {
198
+ download(redirection, to, redirect + 1).then(resolve, reject);
199
+ });
200
+ return;
201
+ }
202
+ res.pipe(file);
203
+ });
204
+ file.on("finish", () => {
205
+ if (done) {
206
+ file.close(() => {
207
+ resolve(to);
208
+ });
209
+ }
210
+ });
211
+ request.on("error", (err) => {
212
+ fs.unlink(to, () => {
213
+ reject(err);
214
+ });
215
+ });
216
+ file.on("error", (err) => {
217
+ fs.unlink(to, () => {
218
+ reject(err);
219
+ });
220
+ });
221
+ request.end();
222
+ });
223
+ }
224
+
225
+ // src/core/quick-tunnel/index.ts
226
+ var MAX_QUICK_TUNNEL_ATTEMPTS = 5;
227
+ function isQuickTunnelRateLimitedError(message) {
228
+ return message.includes("429") || message.includes("Too Many Requests") || message.includes('status_code="429');
229
+ }
230
+ async function startCloudflaredTunnelWithRetry(cfArgs) {
231
+ for (let attempt = 1;attempt <= MAX_QUICK_TUNNEL_ATTEMPTS; attempt++) {
232
+ const tunnel = startCloudflaredTunnel(cfArgs);
233
+ try {
234
+ await tunnel.url;
235
+ return tunnel;
236
+ } catch (e) {
237
+ const msg = String(e);
238
+ if (attempt < MAX_QUICK_TUNNEL_ATTEMPTS && isQuickTunnelRateLimitedError(msg)) {
239
+ const delayMs = 2000 * attempt;
240
+ console.log(`Cloudflare quick tunnel rate-limited (${attempt}/${MAX_QUICK_TUNNEL_ATTEMPTS}), retrying in ${delayMs}ms…`);
241
+ await sleep(delayMs);
242
+ continue;
243
+ }
244
+ throw e;
245
+ }
246
+ }
247
+ throw new Error("startCloudflaredTunnelWithRetry: exhausted attempts");
248
+ }
249
+ function resolvedLocalUrl(opts) {
250
+ return opts.url ?? `${opts.protocol || "http"}://${opts.hostname ?? "localhost"}:${opts.port ?? 3000}`;
251
+ }
252
+ function envAcceptsCloudflareNotice() {
253
+ const v = process.env.BUNCARGO_ACCEPT_CLOUDFLARE_NOTICE;
254
+ const u = process.env.UNTUN_ACCEPT_CLOUDFLARE_NOTICE;
255
+ return v === "1" || v === "true" || u === "1" || u === "true";
256
+ }
257
+ async function promptInstallCloudflared() {
258
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
259
+ return false;
260
+ }
261
+ return new Promise((resolve) => {
262
+ const rl = createInterface({
263
+ input: process.stdin,
264
+ output: process.stdout
265
+ });
266
+ rl.question("Do you agree with the above terms and wish to install the binary from GitHub? (y/N) ", (answer) => {
267
+ rl.close();
268
+ resolve(/^y(es)?$/i.test(answer.trim()));
269
+ });
270
+ });
271
+ }
272
+ async function startQuickTunnel(opts) {
273
+ const url = resolvedLocalUrl(opts);
274
+ console.log(`Starting cloudflared tunnel to ${url}`);
275
+ if (!existsSync(cloudflaredBinPath)) {
276
+ console.log(cloudflaredNotice);
277
+ const canInstall = opts.acceptCloudflareNotice || envAcceptsCloudflareNotice() || await promptInstallCloudflared();
278
+ if (!canInstall) {
279
+ console.error("Skipping tunnel setup.");
280
+ return;
281
+ }
282
+ await installCloudflared();
283
+ }
284
+ const cfArgs = { "--url": url };
285
+ if (!opts.verifyTLS) {
286
+ cfArgs["--no-tls-verify"] = null;
287
+ }
288
+ const tunnel = await startCloudflaredTunnelWithRetry(cfArgs);
289
+ const cleanup = async () => {
290
+ tunnel.stop();
291
+ };
292
+ return {
293
+ getURL: async () => await tunnel.url,
294
+ close: cleanup
295
+ };
296
+ }
297
+
298
+ // src/core/tunnel.ts
299
+ function parseExposeNames(exposeValue) {
300
+ if (exposeValue === undefined)
301
+ return null;
302
+ const names = exposeValue.split(",").map((name) => name.trim()).filter(Boolean);
303
+ return new Set(names);
304
+ }
305
+ async function resolvePublicUrl(tunnel) {
306
+ if (typeof tunnel.getURL === "function") {
307
+ return await tunnel.getURL();
308
+ }
309
+ return tunnel.url ?? tunnel.publicUrl ?? tunnel.tunnelUrl ?? null;
310
+ }
311
+ function toCloseFn(tunnel) {
312
+ const close = tunnel.close ?? tunnel.stop ?? tunnel.destroy;
313
+ if (!close)
314
+ return async () => {};
315
+ return async () => {
316
+ await close();
317
+ };
318
+ }
319
+ function resolveExposeTargets(env, exposeValue) {
320
+ const requestedNames = parseExposeNames(exposeValue);
321
+ const knownTargets = new Map;
322
+ const enabledTargets = new Map;
323
+ for (const [name, config] of Object.entries(env.services)) {
324
+ const port = env.ports[name];
325
+ if (port === undefined)
326
+ continue;
327
+ const target = { kind: "service", name, port };
328
+ knownTargets.set(name, target);
329
+ if (config.expose === true) {
330
+ enabledTargets.set(name, target);
331
+ }
332
+ }
333
+ for (const [name, config] of Object.entries(env.apps)) {
334
+ const port = env.ports[name];
335
+ if (port === undefined)
336
+ continue;
337
+ const target = { kind: "app", name, port };
338
+ knownTargets.set(name, target);
339
+ if (config.expose === true) {
340
+ enabledTargets.set(name, target);
341
+ }
342
+ }
343
+ if (requestedNames === null) {
344
+ return {
345
+ targets: Array.from(enabledTargets.values()),
346
+ unknownNames: [],
347
+ notEnabledNames: []
348
+ };
349
+ }
350
+ const unknownNames = [];
351
+ const notEnabledNames = [];
352
+ const targets = [];
353
+ for (const name of requestedNames) {
354
+ if (!knownTargets.has(name)) {
355
+ unknownNames.push(name);
356
+ continue;
357
+ }
358
+ const enabledTarget = enabledTargets.get(name);
359
+ if (!enabledTarget) {
360
+ notEnabledNames.push(name);
361
+ continue;
362
+ }
363
+ targets.push(enabledTarget);
364
+ }
365
+ return { targets, unknownNames, notEnabledNames };
366
+ }
367
+ function resolveExposeTunnelStaggerMs() {
368
+ const raw = process.env.BUNCARGO_EXPOSE_TUNNEL_STAGGER_MS;
369
+ if (raw === undefined || raw === "") {
370
+ return 900;
371
+ }
372
+ const n = Number.parseInt(raw, 10);
373
+ return Number.isFinite(n) && n >= 0 ? n : 900;
374
+ }
375
+ async function startPublicTunnels(targets, options = {}) {
376
+ const start = options.start ?? ((input) => startQuickTunnel(input));
377
+ const staggerMs = resolveExposeTunnelStaggerMs();
378
+ const tunnels = [];
379
+ try {
380
+ for (let i = 0;i < targets.length; i++) {
381
+ if (i > 0 && staggerMs > 0) {
382
+ await sleep(staggerMs);
383
+ }
384
+ const target = targets[i];
385
+ if (target === undefined) {
386
+ break;
387
+ }
388
+ const localUrl = `http://localhost:${target.port}`;
389
+ const tunnel = await start({
390
+ url: localUrl
391
+ });
392
+ if (tunnel === undefined) {
393
+ throw new Error(`Tunnel for "${target.name}" could not be started (cloudflared missing or install declined)`);
394
+ }
395
+ const publicUrl = await resolvePublicUrl(tunnel);
396
+ if (!publicUrl) {
397
+ throw new Error(`Tunnel for "${target.name}" did not provide a public URL`);
398
+ }
399
+ tunnels.push({
400
+ kind: target.kind,
401
+ name: target.name,
402
+ localUrl,
403
+ publicUrl,
404
+ close: toCloseFn(tunnel)
405
+ });
406
+ }
407
+ return tunnels;
408
+ } catch (e) {
409
+ await stopPublicTunnels(tunnels);
410
+ throw e;
411
+ }
412
+ }
413
+ async function stopPublicTunnels(tunnels) {
414
+ await Promise.allSettled(tunnels.map((tunnel) => tunnel.close()));
415
+ }
416
+
417
+ export { resolveExposeTargets, startPublicTunnels, stopPublicTunnels };
@@ -0,0 +1,250 @@
1
+ import {
2
+ resolveExposeTargets,
3
+ startPublicTunnels,
4
+ stopPublicTunnels
5
+ } from "./index-vr4ygtyj.js";
6
+ import {
7
+ spawnWatchdog,
8
+ startHeartbeat,
9
+ stopHeartbeat
10
+ } from "./index-mam0bcyz.js";
11
+ import {
12
+ killProcessesOnAppPorts
13
+ } from "./index-mm412dkp.js";
14
+
15
+ // src/cli/run-cli.ts
16
+ import { spawn } from "node:child_process";
17
+ var ACCEPTED_FLAGS = [
18
+ "--help",
19
+ "--down",
20
+ "--reset",
21
+ "--migrate",
22
+ "--seed",
23
+ "--up-only",
24
+ "--expose"
25
+ ];
26
+ function printHelp() {
27
+ console.log(`
28
+ Usage: buncargo dev [options]
29
+
30
+ Options:
31
+ --help Show this help message
32
+ --down Stop all containers
33
+ --reset Stop containers and remove volumes (fresh start)
34
+ --migrate Run migrations and exit
35
+ --seed Run migrations and seeders, then exit
36
+ --up-only Start containers and run migrations, then exit (no dev servers)
37
+ --expose Expose configured targets via public quick tunnels
38
+
39
+ Examples:
40
+ bun dev Start dev environment with all services
41
+ bun dev --seed Run migrations and seed the database
42
+ bun dev --down Stop all containers
43
+ bun dev --reset Stop containers and remove all data
44
+ bun dev --expose Expose all targets with expose: true
45
+ bun dev --expose=api,web Expose specific targets
46
+ `);
47
+ }
48
+ function getUnknownFlags(args) {
49
+ return args.filter((arg) => arg.startsWith("--") && !ACCEPTED_FLAGS.includes(arg.includes("=") ? arg.split("=")[0] : arg));
50
+ }
51
+ async function runCli(env, options = {}) {
52
+ const {
53
+ args = process.argv.slice(2),
54
+ watchdog = true,
55
+ watchdogTimeout = 10,
56
+ devServersCommand,
57
+ cliTestTunnel
58
+ } = options;
59
+ const tunnelApi = cliTestTunnel ?? {
60
+ resolveExposeTargets,
61
+ startPublicTunnels,
62
+ stopPublicTunnels
63
+ };
64
+ const exposeRequested = hasFlag(args, "--expose");
65
+ const exposeValue = getFlagValue(args, "--expose");
66
+ let tunnels = [];
67
+ async function cleanupTunnels() {
68
+ env.clearPublicUrls();
69
+ if (tunnels.length === 0)
70
+ return;
71
+ await tunnelApi.stopPublicTunnels(tunnels);
72
+ tunnels = [];
73
+ }
74
+ if (args.includes("--help")) {
75
+ printHelp();
76
+ process.exit(0);
77
+ }
78
+ const unknownFlags = getUnknownFlags(args);
79
+ if (unknownFlags.length > 0) {
80
+ console.error(`❌ Unknown flag${unknownFlags.length > 1 ? "s" : ""}: ${unknownFlags.join(", ")}`);
81
+ console.error("");
82
+ printHelp();
83
+ process.exit(1);
84
+ }
85
+ if (args.includes("--down")) {
86
+ env.logInfo();
87
+ await cleanupTunnels();
88
+ await env.stop();
89
+ process.exit(0);
90
+ }
91
+ if (args.includes("--reset")) {
92
+ env.logInfo();
93
+ await cleanupTunnels();
94
+ await env.stop({ removeVolumes: true });
95
+ process.exit(0);
96
+ }
97
+ const skipSeed = args.includes("--seed");
98
+ await env.start({
99
+ startServers: false,
100
+ wait: true,
101
+ skipSeed,
102
+ skipEnvironmentLog: exposeRequested
103
+ });
104
+ if (exposeRequested) {
105
+ const { targets, unknownNames, notEnabledNames } = tunnelApi.resolveExposeTargets(env, exposeValue);
106
+ if (unknownNames.length > 0) {
107
+ console.error(`❌ Unknown expose target${unknownNames.length > 1 ? "s" : ""}: ${unknownNames.join(", ")}`);
108
+ await cleanupTunnels();
109
+ process.exit(1);
110
+ }
111
+ if (notEnabledNames.length > 0) {
112
+ console.error(`❌ Target${notEnabledNames.length > 1 ? "s" : ""} missing expose: true: ${notEnabledNames.join(", ")}`);
113
+ console.error(" Mark these in dev.config.ts with expose: true or remove them from --expose.");
114
+ await cleanupTunnels();
115
+ process.exit(1);
116
+ }
117
+ if (targets.length === 0) {
118
+ console.error("❌ No expose targets selected. Add expose: true to services/apps or pass names with --expose=<name>.");
119
+ await cleanupTunnels();
120
+ process.exit(1);
121
+ }
122
+ tunnels = await tunnelApi.startPublicTunnels(targets);
123
+ env.setPublicUrls(Object.fromEntries(tunnels.map((tunnel) => [tunnel.name, tunnel.publicUrl])));
124
+ env.logInfo("Dev Environment", tunnels);
125
+ }
126
+ if (args.includes("--migrate")) {
127
+ console.log("");
128
+ console.log("✅ Migrations applied successfully");
129
+ await cleanupTunnels();
130
+ process.exit(0);
131
+ }
132
+ if (args.includes("--seed")) {
133
+ console.log("\uD83C\uDF31 Running seeders...");
134
+ const result = await env.exec("bun run run:seeder", {
135
+ throwOnError: false
136
+ });
137
+ if (result.exitCode !== 0) {
138
+ console.error("❌ Seeding failed");
139
+ if (result.stderr) {
140
+ console.error(result.stderr);
141
+ }
142
+ if (result.stdout) {
143
+ console.error(result.stdout);
144
+ }
145
+ await cleanupTunnels();
146
+ process.exit(1);
147
+ }
148
+ console.log("");
149
+ console.log("✅ Seeding complete");
150
+ await cleanupTunnels();
151
+ process.exit(0);
152
+ }
153
+ if (args.includes("--up-only")) {
154
+ console.log("");
155
+ console.log("✅ Containers started. Environment ready.");
156
+ console.log("");
157
+ await cleanupTunnels();
158
+ process.exit(0);
159
+ }
160
+ if (watchdog) {
161
+ await spawnWatchdog(env.projectName, env.root, {
162
+ timeoutMinutes: watchdogTimeout,
163
+ verbose: true,
164
+ composeFile: env.composeFile
165
+ });
166
+ startHeartbeat(env.projectName);
167
+ }
168
+ const command = devServersCommand ?? buildDevServersCommand(env.apps);
169
+ if (!command) {
170
+ console.log("✅ Containers ready. No apps configured.");
171
+ await new Promise(() => {});
172
+ await cleanupTunnels();
173
+ return;
174
+ }
175
+ await killProcessesOnAppPorts(env.apps, env.ports);
176
+ console.log("");
177
+ console.log("\uD83D\uDD27 Starting dev servers...");
178
+ console.log("");
179
+ await runCommand(command, env.root, env.buildEnvVars(), {
180
+ onSignal: async () => {
181
+ await cleanupTunnels();
182
+ stopHeartbeat();
183
+ }
184
+ });
185
+ stopHeartbeat();
186
+ await cleanupTunnels();
187
+ }
188
+ function buildDevServersCommand(apps) {
189
+ const appEntries = Object.entries(apps);
190
+ if (appEntries.length === 0)
191
+ return null;
192
+ const commands = [];
193
+ const names = [];
194
+ const colors = ["blue", "green", "yellow", "magenta", "cyan", "red"];
195
+ for (const [name, config] of appEntries) {
196
+ names.push(name);
197
+ const cwdPart = config.cwd ? `--cwd ${config.cwd}` : "";
198
+ commands.push(`"bun run ${cwdPart} ${config.devCommand}"`.replace(/\s+/g, " ").trim());
199
+ }
200
+ const namesArg = `-n ${names.join(",")}`;
201
+ const colorsArg = `-c ${colors.slice(0, names.length).join(",")}`;
202
+ const commandsArg = commands.join(" ");
203
+ return `bun concurrently ${namesArg} ${colorsArg} ${commandsArg}`;
204
+ }
205
+ function runCommand(command, cwd, envVars, options = {}) {
206
+ const { onSignal } = options;
207
+ return new Promise((resolve, reject) => {
208
+ const proc = spawn(command, [], {
209
+ cwd,
210
+ env: { ...process.env, ...envVars },
211
+ stdio: "inherit",
212
+ shell: true
213
+ });
214
+ proc.on("close", (code) => {
215
+ if (code === 0 || code === null) {
216
+ resolve();
217
+ } else {
218
+ reject(new Error(`Command exited with code ${code}`));
219
+ }
220
+ });
221
+ proc.on("error", reject);
222
+ const cleanup = () => {
223
+ if (onSignal) {
224
+ onSignal();
225
+ }
226
+ proc.kill("SIGTERM");
227
+ };
228
+ process.on("SIGINT", cleanup);
229
+ process.on("SIGTERM", cleanup);
230
+ });
231
+ }
232
+ function hasFlag(args, flag) {
233
+ return args.some((arg) => arg === flag || arg.startsWith(`${flag}=`));
234
+ }
235
+ function getFlagValue(args, flag) {
236
+ const prefixed = args.find((arg) => arg.startsWith(`${flag}=`));
237
+ if (prefixed) {
238
+ return prefixed.split("=")[1];
239
+ }
240
+ const index = args.indexOf(flag);
241
+ if (index !== -1 && index + 1 < args.length) {
242
+ const nextArg = args[index + 1];
243
+ if (nextArg !== undefined && !nextArg.startsWith("-")) {
244
+ return nextArg;
245
+ }
246
+ }
247
+ return;
248
+ }
249
+
250
+ export { runCli, hasFlag, getFlagValue };