buncargo 3.2.0 → 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,362 @@
1
+ // src/core/quick-tunnel/index.ts
2
+ import { existsSync } from "node:fs";
3
+ import { createInterface } from "node:readline";
4
+
5
+ // src/core/quick-tunnel/cloudflared-process.ts
6
+ import { spawn } from "node:child_process";
7
+
8
+ // src/core/quick-tunnel/constants.ts
9
+ import { tmpdir } from "node:os";
10
+ import path from "node:path";
11
+ var CLOUDFLARED_VERSION = process.env.CLOUDFLARED_VERSION || "2023.10.0";
12
+ var RELEASE_BASE = "https://github.com/cloudflare/cloudflared/releases/";
13
+ var cloudflaredBinPath = path.join(tmpdir(), "buncargo-cloudflared", process.platform === "win32" ? `cloudflared.${CLOUDFLARED_VERSION}.exe` : `cloudflared.${CLOUDFLARED_VERSION}`);
14
+ var cloudflaredNotice = `
15
+ \uD83D\uDD25 Your installation of cloudflared software constitutes a symbol of your signature
16
+ indicating that you accept the terms of the Cloudflare License, Terms and Privacy Policy.
17
+
18
+ ❯ License: \`https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/license/\`
19
+ ❯ Terms: \`https://www.cloudflare.com/terms/\`
20
+ ❯ Privacy Policy: \`https://www.cloudflare.com/privacypolicy/\`
21
+ `;
22
+
23
+ // src/core/quick-tunnel/cloudflared-process.ts
24
+ var urlRegex = /\|\s+(https?:\/\/\S+)/;
25
+ function startCloudflaredTunnel(options) {
26
+ const args = ["tunnel"];
27
+ for (const [key, value] of Object.entries(options)) {
28
+ if (typeof value === "string") {
29
+ args.push(`${key}`, value);
30
+ } else if (typeof value === "number") {
31
+ args.push(`${key}`, value.toString());
32
+ } else if (value === null) {
33
+ args.push(`${key}`);
34
+ }
35
+ }
36
+ if (args.length === 1) {
37
+ args.push("--url", "localhost:8080");
38
+ }
39
+ const child = spawn(cloudflaredBinPath, args, {
40
+ stdio: ["ignore", "pipe", "pipe"]
41
+ });
42
+ if (process.env.DEBUG) {
43
+ child.stdout?.pipe(process.stdout);
44
+ child.stderr?.pipe(process.stderr);
45
+ }
46
+ let settled = false;
47
+ let urlResolver;
48
+ let urlRejector;
49
+ const url = new Promise((resolve, reject) => {
50
+ urlResolver = (v) => {
51
+ if (!settled) {
52
+ settled = true;
53
+ resolve(v);
54
+ }
55
+ };
56
+ urlRejector = (e) => {
57
+ if (!settled) {
58
+ settled = true;
59
+ reject(e);
60
+ }
61
+ };
62
+ });
63
+ const parser = (data) => {
64
+ const str = data.toString();
65
+ const urlMatch = str.match(urlRegex);
66
+ if (urlMatch) {
67
+ urlResolver(urlMatch[1] ?? "");
68
+ }
69
+ };
70
+ child.stdout?.on("data", parser).on("error", urlRejector);
71
+ child.stderr?.on("data", parser).on("error", urlRejector);
72
+ child.on("exit", (code, signal) => {
73
+ if (!settled) {
74
+ urlRejector(new Error(`cloudflared exited before a tunnel URL was parsed (code=${code}, signal=${signal ?? "none"})`));
75
+ }
76
+ });
77
+ child.on("error", urlRejector);
78
+ const stop = () => child.kill("SIGINT");
79
+ return { url, child, stop };
80
+ }
81
+
82
+ // src/core/quick-tunnel/install.ts
83
+ import { execSync } from "node:child_process";
84
+ import fs from "node:fs";
85
+ import https from "node:https";
86
+ import path2 from "node:path";
87
+ var LINUX_URL = {
88
+ arm64: "cloudflared-linux-arm64",
89
+ arm: "cloudflared-linux-arm",
90
+ x64: "cloudflared-linux-amd64",
91
+ ia32: "cloudflared-linux-386"
92
+ };
93
+ var MACOS_URL = {
94
+ arm64: "cloudflared-darwin-amd64.tgz",
95
+ x64: "cloudflared-darwin-amd64.tgz"
96
+ };
97
+ var WINDOWS_URL = {
98
+ x64: "cloudflared-windows-amd64.exe",
99
+ ia32: "cloudflared-windows-386.exe"
100
+ };
101
+ function resolveBase(version) {
102
+ if (version === "latest") {
103
+ return `${RELEASE_BASE}latest/download/`;
104
+ }
105
+ return `${RELEASE_BASE}download/${version}/`;
106
+ }
107
+ function installCloudflared(to = cloudflaredBinPath, version = CLOUDFLARED_VERSION) {
108
+ switch (process.platform) {
109
+ case "linux": {
110
+ return installLinux(to, version);
111
+ }
112
+ case "darwin": {
113
+ return installMacos(to, version);
114
+ }
115
+ case "win32": {
116
+ return installWindows(to, version);
117
+ }
118
+ default: {
119
+ throw new Error(`Unsupported platform: ${process.platform}`);
120
+ }
121
+ }
122
+ }
123
+ async function installLinux(to, version = CLOUDFLARED_VERSION) {
124
+ const file = LINUX_URL[process.arch];
125
+ if (file === undefined) {
126
+ throw new Error(`Unsupported architecture: ${process.arch}`);
127
+ }
128
+ await download(resolveBase(version) + file, to);
129
+ fs.chmodSync(to, 493);
130
+ return to;
131
+ }
132
+ async function installMacos(to, version = CLOUDFLARED_VERSION) {
133
+ const file = MACOS_URL[process.arch];
134
+ if (file === undefined) {
135
+ throw new Error(`Unsupported architecture: ${process.arch}`);
136
+ }
137
+ await download(resolveBase(version) + file, `${to}.tgz`);
138
+ if (process.env.DEBUG) {
139
+ console.log(`Extracting to ${to}`);
140
+ }
141
+ execSync(`tar -xzf ${path2.basename(`${to}.tgz`)}`, {
142
+ cwd: path2.dirname(to)
143
+ });
144
+ fs.unlinkSync(`${to}.tgz`);
145
+ fs.renameSync(`${path2.dirname(to)}/cloudflared`, to);
146
+ return to;
147
+ }
148
+ async function installWindows(to, version = CLOUDFLARED_VERSION) {
149
+ const file = WINDOWS_URL[process.arch];
150
+ if (file === undefined) {
151
+ throw new Error(`Unsupported architecture: ${process.arch}`);
152
+ }
153
+ await download(resolveBase(version) + file, to);
154
+ return to;
155
+ }
156
+ function download(url, to, redirect = 0) {
157
+ if (redirect === 0) {
158
+ if (process.env.DEBUG) {
159
+ console.log(`Downloading ${url} to ${to}`);
160
+ }
161
+ } else if (process.env.DEBUG) {
162
+ console.log(`Redirecting to ${url}`);
163
+ }
164
+ return new Promise((resolve, reject) => {
165
+ if (!fs.existsSync(path2.dirname(to))) {
166
+ fs.mkdirSync(path2.dirname(to), { recursive: true });
167
+ }
168
+ let done = true;
169
+ const file = fs.createWriteStream(to);
170
+ const request = https.get(url, (res) => {
171
+ if (res.statusCode === 302 && res.headers.location !== undefined) {
172
+ const redirection = res.headers.location;
173
+ done = false;
174
+ file.close(() => {
175
+ download(redirection, to, redirect + 1).then(resolve, reject);
176
+ });
177
+ return;
178
+ }
179
+ res.pipe(file);
180
+ });
181
+ file.on("finish", () => {
182
+ if (done) {
183
+ file.close(() => {
184
+ resolve(to);
185
+ });
186
+ }
187
+ });
188
+ request.on("error", (err) => {
189
+ fs.unlink(to, () => {
190
+ reject(err);
191
+ });
192
+ });
193
+ file.on("error", (err) => {
194
+ fs.unlink(to, () => {
195
+ reject(err);
196
+ });
197
+ });
198
+ request.end();
199
+ });
200
+ }
201
+
202
+ // src/core/quick-tunnel/index.ts
203
+ function resolvedLocalUrl(opts) {
204
+ return opts.url ?? `${opts.protocol || "http"}://${opts.hostname ?? "localhost"}:${opts.port ?? 3000}`;
205
+ }
206
+ function envAcceptsCloudflareNotice() {
207
+ const v = process.env.BUNCARGO_ACCEPT_CLOUDFLARE_NOTICE;
208
+ const u = process.env.UNTUN_ACCEPT_CLOUDFLARE_NOTICE;
209
+ return v === "1" || v === "true" || u === "1" || u === "true";
210
+ }
211
+ async function promptInstallCloudflared() {
212
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
213
+ return false;
214
+ }
215
+ return new Promise((resolve) => {
216
+ const rl = createInterface({
217
+ input: process.stdin,
218
+ output: process.stdout
219
+ });
220
+ rl.question("Do you agree with the above terms and wish to install the binary from GitHub? (y/N) ", (answer) => {
221
+ rl.close();
222
+ resolve(/^y(es)?$/i.test(answer.trim()));
223
+ });
224
+ });
225
+ }
226
+ async function startQuickTunnel(opts) {
227
+ const url = resolvedLocalUrl(opts);
228
+ console.log(`Starting cloudflared tunnel to ${url}`);
229
+ if (!existsSync(cloudflaredBinPath)) {
230
+ console.log(cloudflaredNotice);
231
+ const canInstall = opts.acceptCloudflareNotice || envAcceptsCloudflareNotice() || await promptInstallCloudflared();
232
+ if (!canInstall) {
233
+ console.error("Skipping tunnel setup.");
234
+ return;
235
+ }
236
+ await installCloudflared();
237
+ }
238
+ const cfArgs = { "--url": url };
239
+ if (!opts.verifyTLS) {
240
+ cfArgs["--no-tls-verify"] = null;
241
+ }
242
+ const tunnel = startCloudflaredTunnel(cfArgs);
243
+ const cleanup = async () => {
244
+ tunnel.stop();
245
+ };
246
+ return {
247
+ getURL: async () => await tunnel.url,
248
+ close: cleanup
249
+ };
250
+ }
251
+
252
+ // src/core/tunnel.ts
253
+ function parseExposeNames(exposeValue) {
254
+ if (exposeValue === undefined)
255
+ return null;
256
+ const names = exposeValue.split(",").map((name) => name.trim()).filter(Boolean);
257
+ return new Set(names);
258
+ }
259
+ async function resolvePublicUrl(tunnel) {
260
+ if (typeof tunnel.getURL === "function") {
261
+ return await tunnel.getURL();
262
+ }
263
+ return tunnel.url ?? tunnel.publicUrl ?? tunnel.tunnelUrl ?? null;
264
+ }
265
+ function toCloseFn(tunnel) {
266
+ const close = tunnel.close ?? tunnel.stop ?? tunnel.destroy;
267
+ if (!close)
268
+ return async () => {};
269
+ return async () => {
270
+ await close();
271
+ };
272
+ }
273
+ function resolveExposeTargets(env, exposeValue) {
274
+ const requestedNames = parseExposeNames(exposeValue);
275
+ const knownTargets = new Map;
276
+ const enabledTargets = new Map;
277
+ for (const [name, config] of Object.entries(env.services)) {
278
+ const port = env.ports[name];
279
+ if (port === undefined)
280
+ continue;
281
+ const target = { kind: "service", name, port };
282
+ knownTargets.set(name, target);
283
+ if (config.expose === true) {
284
+ enabledTargets.set(name, target);
285
+ }
286
+ }
287
+ for (const [name, config] of Object.entries(env.apps)) {
288
+ const port = env.ports[name];
289
+ if (port === undefined)
290
+ continue;
291
+ const target = { kind: "app", name, port };
292
+ knownTargets.set(name, target);
293
+ if (config.expose === true) {
294
+ enabledTargets.set(name, target);
295
+ }
296
+ }
297
+ if (requestedNames === null) {
298
+ return {
299
+ targets: Array.from(enabledTargets.values()),
300
+ unknownNames: [],
301
+ notEnabledNames: []
302
+ };
303
+ }
304
+ const unknownNames = [];
305
+ const notEnabledNames = [];
306
+ const targets = [];
307
+ for (const name of requestedNames) {
308
+ if (!knownTargets.has(name)) {
309
+ unknownNames.push(name);
310
+ continue;
311
+ }
312
+ const enabledTarget = enabledTargets.get(name);
313
+ if (!enabledTarget) {
314
+ notEnabledNames.push(name);
315
+ continue;
316
+ }
317
+ targets.push(enabledTarget);
318
+ }
319
+ return { targets, unknownNames, notEnabledNames };
320
+ }
321
+ async function startPublicTunnels(targets, options = {}) {
322
+ const start = options.start ?? ((input) => startQuickTunnel(input));
323
+ const settled = await Promise.allSettled(targets.map(async (target) => {
324
+ const localUrl = `http://localhost:${target.port}`;
325
+ const tunnel = await start({
326
+ url: localUrl
327
+ });
328
+ if (tunnel === undefined) {
329
+ throw new Error(`Tunnel for "${target.name}" could not be started (cloudflared missing or install declined)`);
330
+ }
331
+ const publicUrl = await resolvePublicUrl(tunnel);
332
+ if (!publicUrl) {
333
+ throw new Error(`Tunnel for "${target.name}" did not provide a public URL`);
334
+ }
335
+ return {
336
+ kind: target.kind,
337
+ name: target.name,
338
+ localUrl,
339
+ publicUrl,
340
+ close: toCloseFn(tunnel)
341
+ };
342
+ }));
343
+ const tunnels = [];
344
+ const errors = [];
345
+ for (const result of settled) {
346
+ if (result.status === "fulfilled") {
347
+ tunnels.push(result.value);
348
+ } else {
349
+ errors.push(result.reason);
350
+ }
351
+ }
352
+ if (errors.length > 0) {
353
+ await stopPublicTunnels(tunnels);
354
+ throw errors[0];
355
+ }
356
+ return tunnels;
357
+ }
358
+ async function stopPublicTunnels(tunnels) {
359
+ await Promise.allSettled(tunnels.map((tunnel) => tunnel.close()));
360
+ }
361
+
362
+ export { resolveExposeTargets, startPublicTunnels, stopPublicTunnels };
@@ -0,0 +1,250 @@
1
+ import {
2
+ resolveExposeTargets,
3
+ startPublicTunnels,
4
+ stopPublicTunnels
5
+ } from "./index-mf4vjhm3.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 };