cm-tunnel 1.3.3 → 1.5.0

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,267 @@
1
+ import { parseArgs } from "node:util";
2
+ export const STRINGS = {
3
+ pt: {
4
+ needTty: "Este terminal não é interativo. Use as flags (ex: --yes --quick --public public --api api) ou rode em um terminal normal.",
5
+ cloudflaredMissing: "cloudflared não encontrado no PATH. Instale em: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/",
6
+ whatPublish: "O que você quer publicar?",
7
+ modeSite: "Só site (arquivos estáticos)",
8
+ modeApi: "Só API (funções de servidor)",
9
+ modeBoth: "Site + API",
10
+ modeServer: "Servidor já rodando (informar a porta)",
11
+ publicPath: "Pasta do site",
12
+ apiPath: "Pasta da API",
13
+ serverPortPrompt: "Porta em que seu servidor já está rodando",
14
+ serverNotRunning: (port) => `Aviso: nada parece estar escutando na porta ${port} ainda.`,
15
+ publishHow: "Como você quer publicar?",
16
+ publishQuick: "URL temporária (trycloudflare.com) — sem configuração",
17
+ publishDomain: "Domínio próprio (túnel Cloudflare)",
18
+ domainPrompt: "Domínio (ex: api.meudominio.com.br)",
19
+ tokenPrompt: "Token do túnel (não aparece na tela)",
20
+ portPrompt: "Porta local que o túnel vai apontar",
21
+ createFolder: (dir) => `A pasta "${dir}" não existe. Criar com um arquivo de exemplo?`,
22
+ folderNotDir: (dir) => `Pasta inválida: "${dir}".`,
23
+ createdFolder: (dir) => `Pasta criada: ${dir}`,
24
+ invalidDomain: "Domínio inválido.",
25
+ invalidPort: "Porta inválida (use um número entre 1 e 65535).",
26
+ portInUse: (port) => `A porta ${port} já está em uso. Escolha outra com --port.`,
27
+ missingToken: "Token ausente. Defina CLOUDFLARE_TOKEN, use --token ou rode de forma interativa.",
28
+ summaryTitle: "Resumo:",
29
+ summarySite: (dir) => `Site: ${dir}`,
30
+ summaryApi: (dir, prefix) => `API: ${dir} em ${prefix}`,
31
+ summaryServer: (port) => `Servidor: http://localhost:${port}`,
32
+ summaryPublishQuick: "Modo: URL temporária (trycloudflare.com)",
33
+ summaryPublishDomain: (domain) => `Modo: Domínio próprio (${domain})`,
34
+ summaryPort: (port) => `Porta: ${port}`,
35
+ confirm: "Tudo certo? Publicar agora",
36
+ cancelled: "Cancelado.",
37
+ starting: "Iniciando o túnel...",
38
+ tunnelUrl: (url) => `\nTúnel no ar: ${url}`,
39
+ siteServed: (dir) => `Site servido de ${dir}`,
40
+ apiServed: (dir, prefix) => `API servida de ${dir} em ${prefix}`,
41
+ domainHint: (domain, port) => `No dashboard da Cloudflare, o Public Hostname ${domain} deve apontar para http://localhost:${port}.`,
42
+ pressCtrlC: "Pressione Ctrl+C para encerrar.",
43
+ useSaved: "Configuração encontrada em .cm-tunnel.json. Usar?",
44
+ savedConfig: (file) => `Configuração salva em ${file}`,
45
+ tokenSaved: "Token salvo em .env",
46
+ dryRun: "Dry-run: nada foi iniciado.",
47
+ error: (message) => `Erro: ${message}`,
48
+ },
49
+ en: {
50
+ needTty: "This terminal is not interactive. Use flags (e.g. --yes --quick --public public --api api) or run it in a normal terminal.",
51
+ cloudflaredMissing: "cloudflared not found in PATH. Install it from: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/",
52
+ whatPublish: "What do you want to publish?",
53
+ modeSite: "Site only (static files)",
54
+ modeApi: "API only (server functions)",
55
+ modeBoth: "Site + API",
56
+ modeServer: "Server already running (enter its port)",
57
+ publicPath: "Site folder",
58
+ apiPath: "API folder",
59
+ serverPortPrompt: "Port your server is already running on",
60
+ serverNotRunning: (port) => `Warning: nothing seems to be listening on port ${port} yet.`,
61
+ publishHow: "How do you want to publish?",
62
+ publishQuick: "Temporary URL (trycloudflare.com) — no setup",
63
+ publishDomain: "Custom domain (Cloudflare tunnel)",
64
+ domainPrompt: "Domain (e.g. api.example.com)",
65
+ tokenPrompt: "Tunnel token (hidden)",
66
+ portPrompt: "Local port the tunnel should point to",
67
+ createFolder: (dir) => `Folder "${dir}" does not exist. Create it with a sample file?`,
68
+ folderNotDir: (dir) => `Invalid folder: "${dir}".`,
69
+ createdFolder: (dir) => `Folder created: ${dir}`,
70
+ invalidDomain: "Invalid domain.",
71
+ invalidPort: "Invalid port (use a number between 1 and 65535).",
72
+ portInUse: (port) => `Port ${port} is already in use. Choose another with --port.`,
73
+ missingToken: "Missing token. Set CLOUDFLARE_TOKEN, pass --token, or run interactively.",
74
+ summaryTitle: "Summary:",
75
+ summarySite: (dir) => `Site: ${dir}`,
76
+ summaryApi: (dir, prefix) => `API: ${dir} at ${prefix}`,
77
+ summaryServer: (port) => `Server: http://localhost:${port}`,
78
+ summaryPublishQuick: "Mode: Temporary URL (trycloudflare.com)",
79
+ summaryPublishDomain: (domain) => `Mode: Custom domain (${domain})`,
80
+ summaryPort: (port) => `Port: ${port}`,
81
+ confirm: "Looks good? Publish now",
82
+ cancelled: "Cancelled.",
83
+ starting: "Starting tunnel...",
84
+ tunnelUrl: (url) => `\nTunnel is live: ${url}`,
85
+ siteServed: (dir) => `Site served from ${dir}`,
86
+ apiServed: (dir, prefix) => `API served from ${dir} at ${prefix}`,
87
+ domainHint: (domain, port) => `In the Cloudflare dashboard, the Public Hostname ${domain} must point to http://localhost:${port}.`,
88
+ pressCtrlC: "Press Ctrl+C to stop.",
89
+ useSaved: "Found .cm-tunnel.json. Use it?",
90
+ savedConfig: (file) => `Config saved to ${file}`,
91
+ tokenSaved: "Token saved to .env",
92
+ dryRun: "Dry run: nothing was started.",
93
+ error: (message) => `Error: ${message}`,
94
+ },
95
+ };
96
+ export const HELP = {
97
+ pt: `cm-tunnel — publique site (public) e API (api) em minutos
98
+
99
+ Uso:
100
+ npx cm-tunnel # interativo
101
+ npx cm-tunnel --yes --quick # sem perguntas
102
+
103
+ Opções:
104
+ --mode site|api|both O que publicar
105
+ --public <pasta> Pasta do site (padrão: public)
106
+ --api <pasta> Pasta da API (padrão: api)
107
+ --api-prefix <prefixo> Prefixo da API (padrão: /api)
108
+ --target <porta> Tunelar um servidor que já está rodando
109
+ --port <porta> Porta local (modo pastas + domínio)
110
+ --domain <dominio> Domínio próprio
111
+ --token <token> Token do túnel Cloudflare
112
+ --quick URL temporária, sem configuração
113
+ --yes, -y Não perguntar (usa flags/padrões)
114
+ --dry-run Mostra o plano e não inicia
115
+ --no-save Não salvar .cm-tunnel.json
116
+ --lang pt|en Idioma
117
+ -h, --help Ajuda
118
+ -v, --version Versão`,
119
+ en: `cm-tunnel — publish a site (public) and an API (api) in minutes
120
+
121
+ Usage:
122
+ npx cm-tunnel # interactive
123
+ npx cm-tunnel --yes --quick # no questions
124
+
125
+ Options:
126
+ --mode site|api|both What to publish
127
+ --public <folder> Site folder (default: public)
128
+ --api <folder> API folder (default: api)
129
+ --api-prefix <prefix> API prefix (default: /api)
130
+ --target <port> Tunnel an already running server
131
+ --port <port> Local port (folders + domain mode)
132
+ --domain <domain> Custom domain
133
+ --token <token> Cloudflare tunnel token
134
+ --quick Temporary URL, no setup
135
+ --yes, -y Do not ask (use flags/defaults)
136
+ --dry-run Print the plan and do not start
137
+ --no-save Do not save .cm-tunnel.json
138
+ --lang pt|en Language
139
+ -h, --help Help
140
+ -v, --version Version`,
141
+ };
142
+ export function detectLang(explicit, env = process.env) {
143
+ if (explicit === "pt" || explicit === "en")
144
+ return explicit;
145
+ const raw = (env.CM_TUNNEL_LANG || env.LC_ALL || env.LANG || "").toLowerCase();
146
+ return raw.startsWith("pt") ? "pt" : "en";
147
+ }
148
+ export function parseCliArgs(argv) {
149
+ const { values } = parseArgs({
150
+ args: argv,
151
+ allowPositionals: false,
152
+ options: {
153
+ lang: { type: "string" },
154
+ help: { type: "boolean", short: "h" },
155
+ version: { type: "boolean", short: "v" },
156
+ yes: { type: "boolean", short: "y" },
157
+ "dry-run": { type: "boolean" },
158
+ mode: { type: "string" },
159
+ public: { type: "string" },
160
+ api: { type: "string" },
161
+ "api-prefix": { type: "string" },
162
+ target: { type: "string" },
163
+ port: { type: "string" },
164
+ domain: { type: "string" },
165
+ token: { type: "string" },
166
+ quick: { type: "boolean" },
167
+ "no-save": { type: "boolean" },
168
+ },
169
+ });
170
+ const mode = values.mode;
171
+ if (mode !== undefined && mode !== "site" && mode !== "api" && mode !== "both") {
172
+ throw new Error(`Invalid --mode: "${mode}". Use site, api or both.`);
173
+ }
174
+ const port = values.port !== undefined ? Number(values.port) : undefined;
175
+ if (port !== undefined && !isValidPort(port)) {
176
+ throw new Error(`Invalid --port: "${values.port}".`);
177
+ }
178
+ const target = values.target !== undefined ? Number(values.target) : undefined;
179
+ if (target !== undefined && !isValidPort(target)) {
180
+ throw new Error(`Invalid --target: "${values.target}".`);
181
+ }
182
+ const lang = values.lang;
183
+ if (lang !== undefined && lang !== "pt" && lang !== "en") {
184
+ throw new Error(`Invalid --lang: "${lang}". Use pt or en.`);
185
+ }
186
+ return {
187
+ lang: lang,
188
+ help: !!values.help,
189
+ version: !!values.version,
190
+ yes: !!values.yes,
191
+ dryRun: !!values["dry-run"],
192
+ mode: mode,
193
+ public: values.public,
194
+ api: values.api,
195
+ apiPrefix: values["api-prefix"],
196
+ target,
197
+ port,
198
+ domain: values.domain,
199
+ token: values.token,
200
+ quick: !!values.quick,
201
+ save: !values["no-save"],
202
+ };
203
+ }
204
+ export function isValidPort(port) {
205
+ return Number.isInteger(port) && port >= 1 && port <= 65535;
206
+ }
207
+ export function normalizeDomain(input) {
208
+ return input
209
+ .trim()
210
+ .replace(/^https?:\/\//i, "")
211
+ .replace(/\/+$/, "");
212
+ }
213
+ export function isValidDomain(domain) {
214
+ return /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i.test(domain);
215
+ }
216
+ export function normalizePrefix(input) {
217
+ let prefix = (input || "/api").trim();
218
+ if (!prefix.startsWith("/"))
219
+ prefix = `/${prefix}`;
220
+ prefix = prefix.replace(/\/+$/, "");
221
+ return prefix || "/api";
222
+ }
223
+ export function guessMode(publicExists, apiExists) {
224
+ if (publicExists && !apiExists)
225
+ return "site";
226
+ if (!publicExists && apiExists)
227
+ return "api";
228
+ return "both";
229
+ }
230
+ export function buildTunnelOptions(plan, token) {
231
+ const cloudflare = plan.publish === "quick"
232
+ ? { mode: "quick" }
233
+ : {
234
+ mode: "named",
235
+ domain: plan.domain,
236
+ token,
237
+ };
238
+ // Modo servidor: apenas aponta o túnel para a porta já existente.
239
+ if (plan.target) {
240
+ return {
241
+ provider: "cloudflare",
242
+ port: plan.target,
243
+ cloudflare,
244
+ };
245
+ }
246
+ const serve = {
247
+ apiPrefix: plan.apiPrefix,
248
+ };
249
+ if (plan.mode !== "api")
250
+ serve.public = plan.public;
251
+ if (plan.mode !== "site")
252
+ serve.api = plan.api;
253
+ if (plan.publish === "domain" && plan.port)
254
+ serve.port = plan.port;
255
+ const options = {
256
+ provider: "cloudflare",
257
+ serve,
258
+ };
259
+ if (plan.mode !== "site") {
260
+ options.rateLimit = {
261
+ maxRequestsPerMinute: 60,
262
+ routes: [plan.apiPrefix],
263
+ };
264
+ }
265
+ options.cloudflare = cloudflare;
266
+ return options;
267
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,426 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync, } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ import { createConnection, createServer } from "node:net";
6
+ import prompts from "prompts";
7
+ import tunnel from "./index.js";
8
+ import { HELP, STRINGS, buildTunnelOptions, detectLang, guessMode, isValidDomain, isValidPort, normalizeDomain, normalizePrefix, parseCliArgs, } from "./cli-utils.js";
9
+ const CONFIG_FILE = ".cm-tunnel.json";
10
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
11
+ function langFromArgv() {
12
+ const index = process.argv.indexOf("--lang");
13
+ return index >= 0 ? process.argv[index + 1] : undefined;
14
+ }
15
+ function loadDotEnv() {
16
+ if (!existsSync(".env"))
17
+ return;
18
+ if (typeof process.loadEnvFile === "function") {
19
+ try {
20
+ process.loadEnvFile(".env");
21
+ return;
22
+ }
23
+ catch {
24
+ // Cai no parser manual abaixo.
25
+ }
26
+ }
27
+ try {
28
+ const content = readFileSync(resolve(".env"), "utf8");
29
+ for (const raw of content.split(/\r?\n/)) {
30
+ const line = raw.trim();
31
+ if (!line || line.startsWith("#"))
32
+ continue;
33
+ const separator = line.indexOf("=");
34
+ if (separator <= 0)
35
+ continue;
36
+ const key = line.slice(0, separator).trim();
37
+ let value = line.slice(separator + 1).trim();
38
+ if ((value.startsWith('"') && value.endsWith('"')) ||
39
+ (value.startsWith("'") && value.endsWith("'"))) {
40
+ value = value.slice(1, -1);
41
+ }
42
+ if (!(key in process.env)) {
43
+ process.env[key] = value;
44
+ }
45
+ }
46
+ }
47
+ catch {
48
+ // .env inválido é ignorado; o usuário ainda pode usar variáveis de ambiente.
49
+ }
50
+ }
51
+ function loadConfig() {
52
+ const file = resolve(CONFIG_FILE);
53
+ if (!existsSync(file))
54
+ return null;
55
+ try {
56
+ const data = JSON.parse(readFileSync(file, "utf8"));
57
+ if (data?.mode !== "site" && data?.mode !== "api" && data?.mode !== "both") {
58
+ return null;
59
+ }
60
+ if (data?.publish !== "quick" && data?.publish !== "domain") {
61
+ return null;
62
+ }
63
+ return {
64
+ mode: data.mode,
65
+ public: typeof data.public === "string" ? data.public : undefined,
66
+ api: typeof data.api === "string" ? data.api : undefined,
67
+ apiPrefix: typeof data.apiPrefix === "string" ? normalizePrefix(data.apiPrefix) : "/api",
68
+ publish: data.publish,
69
+ domain: typeof data.domain === "string" ? data.domain : undefined,
70
+ target: typeof data.target === "number" ? data.target : undefined,
71
+ port: typeof data.port === "number" ? data.port : undefined,
72
+ };
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
78
+ function saveConfig(plan) {
79
+ writeFileSync(resolve(CONFIG_FILE), `${JSON.stringify(plan, null, 2)}\n`);
80
+ }
81
+ function saveTokenToEnv(token) {
82
+ const file = resolve(".env");
83
+ let content = existsSync(file) ? readFileSync(file, "utf8") : "";
84
+ const line = `CLOUDFLARE_TOKEN=${token}`;
85
+ if (/^CLOUDFLARE_TOKEN=.*$/m.test(content)) {
86
+ content = content.replace(/^CLOUDFLARE_TOKEN=.*$/m, line);
87
+ }
88
+ else {
89
+ if (content && !content.endsWith("\n"))
90
+ content += "\n";
91
+ content += `${line}\n`;
92
+ }
93
+ writeFileSync(file, content);
94
+ try {
95
+ chmodSync(file, 0o600);
96
+ }
97
+ catch {
98
+ // Em sistemas sem suporte a chmod, segue normalmente.
99
+ }
100
+ }
101
+ function starterHtml(lang) {
102
+ const language = lang === "pt" ? "pt-BR" : "en";
103
+ const title = lang === "pt" ? "Meu site" : "My site";
104
+ const text = lang === "pt"
105
+ ? "Site publicado com cm-tunnel."
106
+ : "Site published with cm-tunnel.";
107
+ return `<!doctype html>
108
+ <html lang="${language}">
109
+ <head>
110
+ <meta charset="utf-8" />
111
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
112
+ <title>${title}</title>
113
+ </head>
114
+ <body>
115
+ <h1>${text}</h1>
116
+ </body>
117
+ </html>
118
+ `;
119
+ }
120
+ const STARTER_API = `export default function handler(req, res) {
121
+ res.json({ ok: true, method: req.method, time: new Date().toISOString() });
122
+ }
123
+ `;
124
+ function onCancel(s) {
125
+ console.log(`\n${s.cancelled}`);
126
+ process.exit(0);
127
+ }
128
+ function isPortFree(port) {
129
+ return new Promise((resolvePort) => {
130
+ const server = createServer();
131
+ server.once("error", () => resolvePort(false));
132
+ server.once("listening", () => {
133
+ server.close(() => resolvePort(true));
134
+ });
135
+ server.listen(port, "127.0.0.1");
136
+ });
137
+ }
138
+ function isPortInUse(port) {
139
+ return new Promise((resolvePort) => {
140
+ const socket = createConnection({ port, host: "127.0.0.1" });
141
+ socket.once("connect", () => {
142
+ socket.destroy();
143
+ resolvePort(true);
144
+ });
145
+ socket.once("error", () => resolvePort(false));
146
+ });
147
+ }
148
+ async function askText(s, message, initial, validate) {
149
+ const res = await prompts({ type: "text", name: "value", message, initial, validate }, { onCancel: () => onCancel(s) });
150
+ return String(res.value ?? "").trim();
151
+ }
152
+ async function askPassword(s, message) {
153
+ const res = await prompts({ type: "password", name: "value", message }, { onCancel: () => onCancel(s) });
154
+ return String(res.value ?? "").trim();
155
+ }
156
+ async function askConfirm(s, message, initial) {
157
+ const res = await prompts({ type: "confirm", name: "value", message, initial }, { onCancel: () => onCancel(s) });
158
+ return !!res.value;
159
+ }
160
+ async function askSelect(s, message, choices, initial) {
161
+ const res = await prompts({ type: "select", name: "value", message, choices, initial }, { onCancel: () => onCancel(s) });
162
+ return res.value;
163
+ }
164
+ async function askPort(s, message, initial) {
165
+ const res = await prompts({
166
+ type: "number",
167
+ name: "value",
168
+ message,
169
+ initial,
170
+ min: 1,
171
+ max: 65535,
172
+ validate: (value) => isValidPort(Number(value)) || s.invalidPort,
173
+ }, { onCancel: () => onCancel(s) });
174
+ return Number(res.value);
175
+ }
176
+ async function ensureFolder(s, lang, dir, kind, yes, dryRun) {
177
+ if (!dir)
178
+ return;
179
+ if (dryRun)
180
+ return;
181
+ const abs = resolve(dir);
182
+ if (existsSync(abs)) {
183
+ if (!statSync(abs).isDirectory())
184
+ throw new Error(s.folderNotDir(dir));
185
+ return;
186
+ }
187
+ const create = yes || (await askConfirm(s, s.createFolder(dir), true));
188
+ if (!create)
189
+ throw new Error(s.folderNotDir(dir));
190
+ mkdirSync(abs, { recursive: true });
191
+ if (kind === "site") {
192
+ writeFileSync(join(abs, "index.html"), starterHtml(lang));
193
+ }
194
+ else {
195
+ writeFileSync(join(abs, "hello.js"), STARTER_API);
196
+ }
197
+ console.log(s.createdFolder(dir));
198
+ }
199
+ async function chooseFolder(s, kind, explicit, savedPath, yes) {
200
+ const fallback = kind === "site" ? "public" : "api";
201
+ const chosen = explicit ?? savedPath;
202
+ if (chosen)
203
+ return chosen;
204
+ // Se a pasta padrão já existe, usa direto sem perguntar.
205
+ if (existsSync(resolve(fallback)) || yes)
206
+ return fallback;
207
+ return await askText(s, kind === "site" ? s.publicPath : s.apiPath, fallback, (value) => (value.trim() ? true : s.folderNotDir(value)));
208
+ }
209
+ async function main() {
210
+ let opts;
211
+ try {
212
+ opts = parseCliArgs(process.argv.slice(2));
213
+ }
214
+ catch (err) {
215
+ console.log(HELP[detectLang(langFromArgv())]);
216
+ throw err;
217
+ }
218
+ const lang = detectLang(opts.lang);
219
+ const s = STRINGS[lang];
220
+ if (opts.help) {
221
+ console.log(HELP[lang]);
222
+ return;
223
+ }
224
+ if (opts.version) {
225
+ console.log(`cm-tunnel ${pkg.version}`);
226
+ return;
227
+ }
228
+ if (!process.stdin.isTTY && !opts.yes) {
229
+ throw new Error(s.needTty);
230
+ }
231
+ const check = spawnSync("cloudflared", ["--version"], { stdio: "ignore" });
232
+ if (check.error) {
233
+ throw new Error(s.cloudflaredMissing);
234
+ }
235
+ loadDotEnv();
236
+ let saved = loadConfig();
237
+ if (saved) {
238
+ const useSaved = opts.yes || (await askConfirm(s, s.useSaved, true));
239
+ if (!useSaved)
240
+ saved = null;
241
+ }
242
+ const defaultPublic = opts.public ?? saved?.public ?? "public";
243
+ const defaultApi = opts.api ?? saved?.api ?? "api";
244
+ const suggestedMode = guessMode(existsSync(resolve(defaultPublic)), existsSync(resolve(defaultApi)));
245
+ let mode;
246
+ let target;
247
+ if (opts.target !== undefined) {
248
+ target = opts.target;
249
+ mode = opts.mode ?? saved?.mode ?? "both";
250
+ }
251
+ else if (saved?.target) {
252
+ target = saved.target;
253
+ mode = saved.mode;
254
+ }
255
+ else if (opts.mode) {
256
+ mode = opts.mode;
257
+ }
258
+ else if (saved?.mode) {
259
+ // Configuração salva aceita: não repergunta o modo.
260
+ mode = saved.mode;
261
+ }
262
+ else if (opts.yes) {
263
+ mode = suggestedMode;
264
+ }
265
+ else {
266
+ const choice = await askSelect(s, s.whatPublish, [
267
+ { title: s.modeSite, value: "site" },
268
+ { title: s.modeApi, value: "api" },
269
+ { title: s.modeBoth, value: "both" },
270
+ { title: s.modeServer, value: "server" },
271
+ ], ["site", "api", "both"].indexOf(suggestedMode));
272
+ if (choice === "server") {
273
+ target = await askPort(s, s.serverPortPrompt, 3000);
274
+ mode = "both";
275
+ }
276
+ else {
277
+ mode = choice;
278
+ }
279
+ }
280
+ if (target !== undefined && !isValidPort(target)) {
281
+ throw new Error(s.invalidPort);
282
+ }
283
+ const publicPath = target || mode === "api"
284
+ ? undefined
285
+ : await chooseFolder(s, "site", opts.public, saved?.public, opts.yes);
286
+ const apiPath = target || mode === "site"
287
+ ? undefined
288
+ : await chooseFolder(s, "api", opts.api, saved?.api, opts.yes);
289
+ if (!target) {
290
+ await ensureFolder(s, lang, publicPath, "site", opts.yes, opts.dryRun);
291
+ await ensureFolder(s, lang, apiPath, "api", opts.yes, opts.dryRun);
292
+ }
293
+ let publish;
294
+ if (opts.quick) {
295
+ publish = "quick";
296
+ }
297
+ else if (opts.domain || opts.token) {
298
+ publish = "domain";
299
+ }
300
+ else if (saved?.publish) {
301
+ publish = saved.publish;
302
+ }
303
+ else if (opts.yes) {
304
+ publish = "quick";
305
+ }
306
+ else {
307
+ publish = await askSelect(s, s.publishHow, [
308
+ { title: s.publishQuick, value: "quick" },
309
+ { title: s.publishDomain, value: "domain" },
310
+ ], 0);
311
+ }
312
+ let domain;
313
+ let port;
314
+ let token;
315
+ if (publish === "domain") {
316
+ const domainAnswer = opts.domain ??
317
+ saved?.domain ??
318
+ (opts.yes ? "" : await askText(s, s.domainPrompt, undefined, (value) => isValidDomain(normalizeDomain(value)) || s.invalidDomain));
319
+ domain = normalizeDomain(domainAnswer);
320
+ if (!isValidDomain(domain)) {
321
+ throw new Error(s.invalidDomain);
322
+ }
323
+ token = opts.token || process.env.CLOUDFLARE_TOKEN;
324
+ let promptedToken = false;
325
+ if (!token && !opts.dryRun) {
326
+ if (opts.yes)
327
+ throw new Error(s.missingToken);
328
+ token = await askPassword(s, s.tokenPrompt);
329
+ promptedToken = true;
330
+ if (!token)
331
+ throw new Error(s.missingToken);
332
+ }
333
+ if (target) {
334
+ port = target;
335
+ if (!opts.dryRun && !(await isPortInUse(target))) {
336
+ console.warn(s.serverNotRunning(target));
337
+ }
338
+ }
339
+ else {
340
+ port =
341
+ opts.port ??
342
+ saved?.port ??
343
+ (opts.yes ? 3000 : await askPort(s, s.portPrompt, 3000));
344
+ if (!isValidPort(port)) {
345
+ throw new Error(s.invalidPort);
346
+ }
347
+ if (!opts.dryRun && !(await isPortFree(port))) {
348
+ throw new Error(s.portInUse(port));
349
+ }
350
+ }
351
+ if (promptedToken && token && opts.save && !opts.dryRun) {
352
+ saveTokenToEnv(token);
353
+ console.log(s.tokenSaved);
354
+ }
355
+ }
356
+ const plan = {
357
+ mode,
358
+ public: publicPath,
359
+ api: apiPath,
360
+ apiPrefix: normalizePrefix(opts.apiPrefix ?? saved?.apiPrefix),
361
+ publish,
362
+ domain,
363
+ target,
364
+ port,
365
+ };
366
+ console.log(`\n${s.summaryTitle}`);
367
+ if (target) {
368
+ console.log(` ${s.summaryServer(target)}`);
369
+ }
370
+ else {
371
+ if (mode !== "api" && publicPath) {
372
+ console.log(` ${s.summarySite(publicPath)}`);
373
+ }
374
+ if (mode !== "site" && apiPath) {
375
+ console.log(` ${s.summaryApi(apiPath, plan.apiPrefix)}`);
376
+ }
377
+ }
378
+ console.log(` ${publish === "quick"
379
+ ? s.summaryPublishQuick
380
+ : s.summaryPublishDomain(domain)}`);
381
+ if (publish === "domain" && port && !target) {
382
+ console.log(` ${s.summaryPort(port)}`);
383
+ }
384
+ console.log();
385
+ if (!opts.yes && !(await askConfirm(s, s.confirm, true))) {
386
+ console.log(s.cancelled);
387
+ return;
388
+ }
389
+ if (opts.save && !opts.dryRun) {
390
+ saveConfig(plan);
391
+ console.log(s.savedConfig(CONFIG_FILE));
392
+ }
393
+ if (opts.dryRun) {
394
+ console.log(s.dryRun);
395
+ return;
396
+ }
397
+ console.log(s.starting);
398
+ const t = await tunnel(buildTunnelOptions(plan, token));
399
+ console.log(s.tunnelUrl(t.url));
400
+ if (target) {
401
+ console.log(` ${s.summaryServer(target)}`);
402
+ }
403
+ else {
404
+ if (mode !== "api" && publicPath) {
405
+ console.log(` ${s.siteServed(publicPath)}`);
406
+ }
407
+ if (mode !== "site" && apiPath) {
408
+ console.log(` ${s.apiServed(apiPath, plan.apiPrefix)}`);
409
+ }
410
+ }
411
+ if (publish === "domain" && domain && port) {
412
+ console.log(` ${s.domainHint(domain, port)}`);
413
+ }
414
+ console.log(s.pressCtrlC);
415
+ const stop = () => {
416
+ t.stop();
417
+ process.exit(0);
418
+ };
419
+ process.on("SIGINT", stop);
420
+ process.on("SIGTERM", stop);
421
+ }
422
+ main().catch((err) => {
423
+ const lang = detectLang(langFromArgv());
424
+ console.error(STRINGS[lang].error(err instanceof Error ? err.message : String(err)));
425
+ process.exit(1);
426
+ });