cm-tunnel 1.7.0 → 1.8.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.
package/README.md CHANGED
@@ -5,8 +5,9 @@
5
5
  Sem Express, sem configurar servidor: aponte as pastas `public` e `api` (ou uma porta existente), responda poucas perguntas e pronto.
6
6
 
7
7
  - CLI interativo em **português e inglês**
8
- - **Cloudflare Quick Tunnel** (URL na hora) ou **domínio próprio**
8
+ - **Cloudflare** (quick ou domínio próprio), **localtunnel** e **ngrok**
9
9
  - Pasta `api/` roda no servidor e **nunca** é exposta como arquivo
10
+ - Reinício automático da API (modo `server`) com backoff
10
11
  - Funciona com Node.js puro, sem framework
11
12
 
12
13
  ---
@@ -29,6 +30,7 @@ Sem Express, sem configurar servidor: aponte as pastas `public` e `api` (ou uma
29
30
  - [Problemas comuns](#problemas-comuns)
30
31
  - [FAQ](#faq)
31
32
  - [Desenvolvimento](#desenvolvimento)
33
+ - [Arquitetura e dívida técnica](https://github.com/cmstudioapps/cm-tunnel/blob/main/ARCHITECTURE.md)
32
34
  - [Licença](#licença)
33
35
 
34
36
  ---
@@ -39,12 +41,19 @@ Sem Express, sem configurar servidor: aponte as pastas `public` e `api` (ou uma
39
41
 
40
42
  ```bash
41
43
  node -v # precisa ser >= 18.3
42
- cloudflared --version # precisa existir no PATH
44
+ ```
45
+
46
+ Para o provedor **Cloudflare** (padrão), o `cloudflared` também precisa existir no PATH:
47
+
48
+ ```bash
49
+ cloudflared --version
43
50
  ```
44
51
 
45
52
  Se não tiver o `cloudflared`:
46
53
  [instalar cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/)
47
54
 
55
+ > Usando `--provider localtunnel` ou `--provider ngrok`, o `cloudflared` não é necessário.
56
+
48
57
  **Rode:**
49
58
 
50
59
  ```bash
@@ -218,6 +227,7 @@ O que a lib faz:
218
227
  - serve `public/` normalmente
219
228
  - encaminha `/api/*` para o app, removendo o prefixo
220
229
  - espera o app responder antes de subir o túnel
230
+ - reinicia o app automaticamente se ele cair (backoff de 500 ms a 30 s, até 5 tentativas; zera após 60 s no ar)
221
231
  - encerra o app no `Ctrl+C`
222
232
 
223
233
  Exemplo de `api/index.js`:
@@ -243,6 +253,8 @@ GET /api/users → app recebe /users
243
253
 
244
254
  > O app precisa escutar em `process.env.PORT`. Se ele já usa uma porta fixa, use o modo `--target <porta>`.
245
255
 
256
+ Se a API cair depois de subir, o supervisor reinicia o processo automaticamente. Desative com `apiRestart: false` (ou `apiRestartMaxAttempts: 0`) e ajuste as tentativas com `apiRestartMaxAttempts`.
257
+
246
258
  **Equivalente em código:**
247
259
 
248
260
  ```javascript
@@ -303,6 +315,24 @@ console.log(t.url);
303
315
  | **Indicado para** | testes, demos, uso rápido | produção, API pública |
304
316
  | **Ativa no CLI** | `--quick` | `--domain seu.dominio.com` |
305
317
 
318
+ ### Provedores de túnel
319
+
320
+ | Provedor | Flag | Domínio próprio | Observações |
321
+ |---|---|---|---|
322
+ | Cloudflare | `--provider cloudflare` (padrão) | sim | Requer `cloudflared` |
323
+ | localtunnel | `--provider localtunnel` | não | Zero dependências externas |
324
+ | ngrok | `--provider ngrok` | não | Define `NGROK_AUTHTOKEN` |
325
+
326
+ ```bash
327
+ # localtunnel com subdomínio fixo
328
+ npx cm-tunnel --yes --provider localtunnel --subdomain meuapp
329
+
330
+ # ngrok (token em NGROK_AUTHTOKEN)
331
+ npx cm-tunnel --yes --provider ngrok
332
+ ```
333
+
334
+ > `localtunnel` e `ngrok` só oferecem URL temporária. Se você pedir `--domain`, o CLI avisa e usa URL temporária.
335
+
306
336
  ### Domínio próprio: checklist
307
337
 
308
338
  1. O domínio precisa estar na Cloudflare com a zona **Active** (nameservers da Cloudflare no Registro.br).
@@ -423,7 +453,9 @@ npx cm-tunnel [opções]
423
453
  | `--api-prefix <prefixo>` | Prefixo da API (padrão: `/api`) |
424
454
  | `--target <porta>` | Tunelar um servidor que já está rodando |
425
455
  | `--port <porta>` | Porta do servidor interno (pastas + domínio) |
426
- | `--domain <domínio>` | Domínio próprio |
456
+ | `--provider <nome>` | `cloudflare` (padrão), `localtunnel` ou `ngrok` |
457
+ | `--subdomain <nome>` | Subdomínio fixo (`localtunnel`/`ngrok`) |
458
+ | `--domain <domínio>` | Domínio próprio (somente Cloudflare) |
427
459
  | `--token <token>` | Token do túnel (ou use `CLOUDFLARE_TOKEN`/`.env`) |
428
460
  | `--quick` | URL temporária, sem configuração |
429
461
  | `--yes`, `-y` | Não perguntar (usa flags/padrões) |
@@ -454,14 +486,18 @@ npx cm-tunnel --dry-run
454
486
 
455
487
  # inglês
456
488
  npx cm-tunnel --lang en
489
+
490
+ # sem Cloudflare (não precisa de cloudflared)
491
+ npx cm-tunnel --yes --provider localtunnel --subdomain meuapp
492
+ npx cm-tunnel --yes --provider ngrok
457
493
  ```
458
494
 
459
495
  **O que é salvo:**
460
496
 
461
497
  | Arquivo | Conteúdo |
462
498
  |---------|----------|
463
- | `.cm-tunnel.json` | modo, pastas (ou porta), `apiMode`/`apiEntry`, domínio (sem token) |
464
- | `.env` | `CLOUDFLARE_TOKEN` (permissão `600`) |
499
+ | `.cm-tunnel.json` | modo, pastas (ou porta), `apiMode`/`apiEntry`, provedor, subdomínio, domínio (sem token) |
500
+ | `.env` | `CLOUDFLARE_TOKEN` (permissão `600`) e/ou `NGROK_AUTHTOKEN` |
465
501
 
466
502
  ---
467
503
 
@@ -625,6 +661,8 @@ console.log(local.url); // http://127.0.0.1:<porta>
625
661
  | `apiEntry` | `string` | `<api>/index.js` | Arquivo de entrada no modo `server` |
626
662
  | `stripApiPrefix` | `boolean` | `true` | Remove `/api` antes de encaminhar ao servidor |
627
663
  | `apiTimeout` | `number` | `30000` | Tempo para o servidor ficar pronto |
664
+ | `apiRestart` | `boolean` | `true` | Reinicia a API se o processo cair (modo `server`) |
665
+ | `apiRestartMaxAttempts` | `number` | `5` | Tentativas consecutivas antes de desistir |
628
666
  | `onLog` | `(line: string) => void` | — | Recebe logs do servidor de API |
629
667
  | `apiPrefix` | `string` | `'/api'` | Prefixo das rotas de API |
630
668
  | `html` | `string` | — | HTML fixo para rotas não-API (prioridade sobre `public`) |
@@ -828,11 +866,14 @@ Sim, desde que o binário `cloudflared` esteja no `PATH`. `npx` e `npm run` são
828
866
 
829
867
  ## Desenvolvimento
830
868
 
869
+ > Arquitetura interna, fluxos, decisões e dívida técnica: [ARCHITECTURE.md](https://github.com/cmstudioapps/cm-tunnel/blob/main/ARCHITECTURE.md)
870
+
831
871
  ```bash
832
872
  npm install
833
873
  npm test # roda a suíte
834
874
  npm run lint
835
875
  npm run build # gera dist/ e deixa dist/cli.js executável
876
+ npm run check:self # impede self-dependency e node_modules/cm-tunnel
836
877
  ```
837
878
 
838
879
  Estrutura principal:
@@ -2,6 +2,16 @@ export interface RateLimitOptions {
2
2
  maxRequestsPerMinute: number;
3
3
  routes?: string[];
4
4
  }
5
+ /**
6
+ * Normaliza uma rota de configuração: garante barra inicial e remove
7
+ * barra final (exceto para a raiz `/`).
8
+ */
9
+ export declare function normalizeRoute(route: string): string;
10
+ /**
11
+ * Verifica se `url` pertence à rota `route` comparando segmentos.
12
+ * Evita que `/api` case com `/api2`.
13
+ */
14
+ export declare function pathMatchesRoute(url: string, route: string): boolean;
5
15
  export declare class RateLimiter {
6
16
  private targetPort;
7
17
  private options;
@@ -9,7 +19,14 @@ export declare class RateLimiter {
9
19
  private proxy;
10
20
  private port;
11
21
  private isGlobal;
22
+ private cleanupTimer;
12
23
  constructor(targetPort: number, options: RateLimitOptions | true);
13
24
  start(): Promise<number>;
25
+ /**
26
+ * Remove entradas cuja janela e bloqueio já expiraram.
27
+ * Retorna a quantidade de chaves removidas.
28
+ */
29
+ cleanupExpired(now?: number): Promise<number>;
30
+ private isExpired;
14
31
  stop(): void;
15
32
  }
@@ -1,6 +1,38 @@
1
1
  import http from 'http';
2
2
  import httpProxy from 'http-proxy';
3
3
  import bancoz from 'bancoz';
4
+ /** Tabela do bancoz usada para persistir os contadores. */
5
+ const TABLE = 'ratelimit';
6
+ /** Tamanho da janela de contagem. */
7
+ const WINDOW_MS = 60_000;
8
+ /** Tempo de bloqueio após exceder o limite. */
9
+ const BLOCK_MS = 60_000;
10
+ /** Intervalo entre limpezas de chaves expiradas. */
11
+ const CLEANUP_INTERVAL_MS = 5 * 60_000;
12
+ /**
13
+ * Normaliza uma rota de configuração: garante barra inicial e remove
14
+ * barra final (exceto para a raiz `/`).
15
+ */
16
+ export function normalizeRoute(route) {
17
+ let normalized = (route || '/').split('?')[0].trim();
18
+ if (!normalized.startsWith('/'))
19
+ normalized = `/${normalized}`;
20
+ if (normalized.length > 1 && normalized.endsWith('/')) {
21
+ normalized = normalized.slice(0, -1);
22
+ }
23
+ return normalized;
24
+ }
25
+ /**
26
+ * Verifica se `url` pertence à rota `route` comparando segmentos.
27
+ * Evita que `/api` case com `/api2`.
28
+ */
29
+ export function pathMatchesRoute(url, route) {
30
+ const path = (url || '/').split('?')[0] || '/';
31
+ const base = normalizeRoute(route);
32
+ if (base === '/')
33
+ return true;
34
+ return path === base || path.startsWith(`${base}/`);
35
+ }
4
36
  export class RateLimiter {
5
37
  targetPort;
6
38
  options;
@@ -8,6 +40,7 @@ export class RateLimiter {
8
40
  proxy = null;
9
41
  port = 0;
10
42
  isGlobal;
43
+ cleanupTimer = null;
11
44
  constructor(targetPort, options) {
12
45
  this.targetPort = targetPort;
13
46
  this.options = options;
@@ -32,7 +65,7 @@ export class RateLimiter {
32
65
  const url = req.url || '/';
33
66
  let shouldApplyLimit = this.isGlobal;
34
67
  if (!shouldApplyLimit && typeof this.options === 'object' && this.options.routes) {
35
- shouldApplyLimit = this.options.routes.some(route => url.startsWith(route));
68
+ shouldApplyLimit = this.options.routes.some((route) => pathMatchesRoute(url, route));
36
69
  }
37
70
  if (shouldApplyLimit) {
38
71
  const ip = req.headers['cf-connecting-ip'] ||
@@ -43,19 +76,19 @@ export class RateLimiter {
43
76
  const key = ip.replace(/[^a-zA-Z0-9_-]/g, '_'); // Sanitizar chave para o bancoz
44
77
  let data = {};
45
78
  try {
46
- data = await bancoz.ler('ratelimit', key);
79
+ data = (await bancoz.ler(TABLE, key)) || {};
47
80
  }
48
81
  catch (err) {
49
82
  // Se não existe, ignora e cria
50
83
  }
51
84
  const now = Date.now();
52
- if (data && data.blockedUntil && data.blockedUntil > now) {
85
+ if (data.blockedUntil && data.blockedUntil > now) {
53
86
  res.writeHead(429, { 'Content-Type': 'text/plain' });
54
87
  return res.end('Too Many Requests. IP Bloqueado Temporariamente.');
55
88
  }
56
- if (!data || !data.count || !data.windowStart || (now - data.windowStart > 60000)) {
89
+ if (!data.count || !data.windowStart || (now - data.windowStart > WINDOW_MS)) {
57
90
  // Nova janela de tempo
58
- await bancoz.criar('ratelimit', key, {
91
+ await bancoz.criar(TABLE, key, {
59
92
  count: 1,
60
93
  windowStart: now
61
94
  });
@@ -65,14 +98,14 @@ export class RateLimiter {
65
98
  const newCount = data.count + 1;
66
99
  if (newCount > maxReqs) {
67
100
  // Bloquear por 1 minuto
68
- await bancoz.atualizar('ratelimit', key, {
69
- blockedUntil: now + 60000
101
+ await bancoz.atualizar(TABLE, key, {
102
+ blockedUntil: now + BLOCK_MS
70
103
  });
71
104
  res.writeHead(429, { 'Content-Type': 'text/plain' });
72
105
  return res.end('Too Many Requests. Limite Excedido.');
73
106
  }
74
107
  else {
75
- await bancoz.atualizar('ratelimit', key, {
108
+ await bancoz.atualizar(TABLE, key, {
76
109
  count: newCount
77
110
  });
78
111
  }
@@ -96,12 +129,59 @@ export class RateLimiter {
96
129
  this.server.listen(0, '127.0.0.1', () => {
97
130
  const address = this.server.address();
98
131
  this.port = address.port;
132
+ // Limpeza periódica; unref() evita segurar o processo aberto.
133
+ this.cleanupTimer = setInterval(() => {
134
+ void this.cleanupExpired();
135
+ }, CLEANUP_INTERVAL_MS);
136
+ this.cleanupTimer.unref?.();
99
137
  resolve(this.port);
100
138
  });
101
139
  this.server.on('error', reject);
102
140
  });
103
141
  }
142
+ /**
143
+ * Remove entradas cuja janela e bloqueio já expiraram.
144
+ * Retorna a quantidade de chaves removidas.
145
+ */
146
+ async cleanupExpired(now = Date.now()) {
147
+ let entries = null;
148
+ try {
149
+ entries = (await bancoz.ler(TABLE));
150
+ }
151
+ catch {
152
+ // Arquivo ainda não existe ou bancoz indisponível: nada a limpar.
153
+ return 0;
154
+ }
155
+ if (!entries || typeof entries !== 'object')
156
+ return 0;
157
+ let removed = 0;
158
+ for (const [key, entry] of Object.entries(entries)) {
159
+ if (!this.isExpired(entry, now))
160
+ continue;
161
+ try {
162
+ await bancoz.deletar(TABLE, key);
163
+ removed++;
164
+ }
165
+ catch {
166
+ // Chave pode ter sido removida concorrentemente; segue adiante.
167
+ }
168
+ }
169
+ return removed;
170
+ }
171
+ isExpired(entry, now) {
172
+ if (!entry || typeof entry !== 'object')
173
+ return true;
174
+ const windowStart = typeof entry.windowStart === 'number' ? entry.windowStart : 0;
175
+ const blockedUntil = typeof entry.blockedUntil === 'number' ? entry.blockedUntil : 0;
176
+ const windowExpired = now - windowStart > WINDOW_MS;
177
+ const blockExpired = blockedUntil <= now;
178
+ return windowExpired && blockExpired;
179
+ }
104
180
  stop() {
181
+ if (this.cleanupTimer) {
182
+ clearInterval(this.cleanupTimer);
183
+ this.cleanupTimer = null;
184
+ }
105
185
  if (this.proxy) {
106
186
  this.proxy.close();
107
187
  this.proxy = null;
@@ -110,5 +190,7 @@ export class RateLimiter {
110
190
  this.server.close();
111
191
  this.server = null;
112
192
  }
193
+ // Limpeza best-effort ao encerrar; não bloqueia o shutdown.
194
+ void this.cleanupExpired();
113
195
  }
114
196
  }
@@ -28,6 +28,13 @@ export interface ServeOptions {
28
28
  port?: number;
29
29
  /** Recebe logs do servidor de API quando apiMode = "server" */
30
30
  onLog?: (line: string) => void;
31
+ /**
32
+ * Reinicia a API automaticamente se o processo cair depois de ficar pronto
33
+ * (padrão: true, apenas em `apiMode: "server"`).
34
+ */
35
+ apiRestart?: boolean;
36
+ /** Máximo de tentativas consecutivas de reinício (padrão: 5) */
37
+ apiRestartMaxAttempts?: number;
31
38
  }
32
39
  export declare class StaticServer {
33
40
  private options;
@@ -44,12 +51,36 @@ export declare class StaticServer {
44
51
  private apiProxy;
45
52
  private apiPort;
46
53
  private stopping;
54
+ private apiReady;
55
+ private apiRestartEnabled;
56
+ private apiRestartMaxAttempts;
57
+ private apiRestartAttempts;
58
+ private apiRestartTimer;
59
+ private apiHealthyTimer;
47
60
  private moduleCache;
48
61
  port: number;
49
62
  url: string;
50
63
  constructor(options: ServeOptions);
51
64
  private prepareRoots;
65
+ private createApiProxy;
66
+ /**
67
+ * Encerra apenas o processo/proxy da API, sem marcar o servidor como parado.
68
+ * Usado durante reinícios automáticos.
69
+ */
70
+ private teardownApi;
71
+ private logSupervisor;
72
+ /**
73
+ * Inicia o processo da API. Em reinícios, falhas não são fatais: o supervisor
74
+ * agenda uma nova tentativa com backoff.
75
+ */
52
76
  private startApiServer;
77
+ private spawnApiProcess;
78
+ /**
79
+ * Zera o contador de tentativas quando a API se mantém saudável tempo
80
+ * suficiente, para não desistir de reinícios pontuais ao longo do dia.
81
+ */
82
+ private scheduleApiHealthyReset;
83
+ private scheduleApiRestart;
53
84
  private stopApiServer;
54
85
  private rewriteApiUrl;
55
86
  private handleApiServer;
@@ -6,6 +6,11 @@ import { spawn } from 'child_process';
6
6
  import httpProxy from 'http-proxy';
7
7
  import { findFreePort, isPortInUse } from './net-utils.js';
8
8
  const API_EXTENSIONS = ['.js', '.mjs', '.cjs'];
9
+ /** Backoff do supervisor de API. */
10
+ const API_RESTART_BASE_DELAY_MS = 500;
11
+ const API_RESTART_MAX_DELAY_MS = 30_000;
12
+ /** Tempo que a API precisa ficar no ar para zerar o contador de tentativas. */
13
+ const API_HEALTHY_RESET_MS = 60_000;
9
14
  const MIME_TYPES = {
10
15
  '.html': 'text/html; charset=utf-8',
11
16
  '.css': 'text/css; charset=utf-8',
@@ -93,6 +98,12 @@ export class StaticServer {
93
98
  apiProxy = null;
94
99
  apiPort = null;
95
100
  stopping = false;
101
+ apiReady = false;
102
+ apiRestartEnabled;
103
+ apiRestartMaxAttempts;
104
+ apiRestartAttempts = 0;
105
+ apiRestartTimer = null;
106
+ apiHealthyTimer = null;
96
107
  moduleCache = new Map();
97
108
  port = 0;
98
109
  url = '';
@@ -107,6 +118,8 @@ export class StaticServer {
107
118
  this.apiPrefix = prefix.replace(/\/+$/, '') || '/api';
108
119
  this.apiMode = options.apiMode === 'server' ? 'server' : 'handlers';
109
120
  this.stripApiPrefix = options.stripApiPrefix !== false;
121
+ this.apiRestartEnabled = options.apiRestart !== false;
122
+ this.apiRestartMaxAttempts = Math.max(0, options.apiRestartMaxAttempts ?? 5);
110
123
  if (this.apiMode === 'server') {
111
124
  this.apiEntry = options.apiEntry
112
125
  ? path.resolve(options.apiEntry)
@@ -137,7 +150,77 @@ export class StaticServer {
137
150
  }
138
151
  }
139
152
  }
140
- async startApiServer() {
153
+ createApiProxy(port) {
154
+ const proxy = httpProxy.createProxyServer({
155
+ target: `http://127.0.0.1:${port}`,
156
+ ws: true,
157
+ });
158
+ proxy.on('error', (_err, _req, res) => {
159
+ const response = res;
160
+ if (response && typeof response.writeHead === 'function' && !response.headersSent) {
161
+ response.writeHead(502, {
162
+ 'Content-Type': 'application/json; charset=utf-8',
163
+ });
164
+ response.end(JSON.stringify({ error: 'Bad Gateway' }));
165
+ }
166
+ });
167
+ return proxy;
168
+ }
169
+ /**
170
+ * Encerra apenas o processo/proxy da API, sem marcar o servidor como parado.
171
+ * Usado durante reinícios automáticos.
172
+ */
173
+ teardownApi() {
174
+ if (this.apiProxy) {
175
+ try {
176
+ this.apiProxy.close();
177
+ }
178
+ catch {
179
+ // ignora
180
+ }
181
+ this.apiProxy = null;
182
+ }
183
+ if (this.apiProcess) {
184
+ try {
185
+ this.apiProcess.kill();
186
+ }
187
+ catch {
188
+ // ignora
189
+ }
190
+ this.apiProcess = null;
191
+ }
192
+ if (this.apiHealthyTimer) {
193
+ clearTimeout(this.apiHealthyTimer);
194
+ this.apiHealthyTimer = null;
195
+ }
196
+ this.apiPort = null;
197
+ this.apiReady = false;
198
+ }
199
+ logSupervisor(message) {
200
+ console.error(message);
201
+ this.options.onLog?.(`${message}\n`);
202
+ }
203
+ /**
204
+ * Inicia o processo da API. Em reinícios, falhas não são fatais: o supervisor
205
+ * agenda uma nova tentativa com backoff.
206
+ */
207
+ async startApiServer(isRestart = false) {
208
+ try {
209
+ await this.spawnApiProcess(isRestart);
210
+ }
211
+ catch (err) {
212
+ if (!isRestart) {
213
+ this.stopApiServer();
214
+ throw err;
215
+ }
216
+ this.teardownApi();
217
+ if (this.stopping)
218
+ return;
219
+ const message = err instanceof Error ? err.message : String(err);
220
+ this.scheduleApiRestart('Falha ao reiniciar a API:', message);
221
+ }
222
+ }
223
+ async spawnApiProcess(isRestart) {
141
224
  if (!this.apiEntry) {
142
225
  throw new Error('apiMode "server" requer um arquivo de entrada.');
143
226
  }
@@ -155,7 +238,6 @@ export class StaticServer {
155
238
  this.apiProcess = child;
156
239
  let output = '';
157
240
  let exited = false;
158
- let ready = false;
159
241
  let exitInfo = '';
160
242
  const forward = (data) => {
161
243
  const text = data.toString();
@@ -167,15 +249,22 @@ export class StaticServer {
167
249
  child.once('exit', (code, signal) => {
168
250
  exited = true;
169
251
  exitInfo = code !== null ? `código ${code}` : `sinal ${signal}`;
170
- if (!this.stopping && ready) {
171
- console.error(`[cm-tunnel] A API encerrou inesperadamente (${exitInfo}).`);
172
- }
252
+ // Só reage à saída do processo atual (não de um já substituído).
253
+ const wasCurrent = this.apiProcess === child;
254
+ if (!wasCurrent)
255
+ return;
256
+ this.apiProcess = null;
257
+ // Saída esperada (stop/kill) ou API que nunca chegou a ficar pronta:
258
+ // o loop de prontidão abaixo trata o erro.
259
+ if (this.stopping || !this.apiReady)
260
+ return;
261
+ this.teardownApi();
262
+ this.scheduleApiRestart('A API encerrou inesperadamente:', exitInfo);
173
263
  });
174
264
  const timeoutMs = this.options.apiTimeout ?? 30000;
175
265
  const deadline = Date.now() + timeoutMs;
176
266
  while (Date.now() < deadline) {
177
267
  if (exited) {
178
- this.stopApiServer();
179
268
  throw new Error(`API encerrou antes de ficar pronta (${exitInfo || 'sem código'}).\n` +
180
269
  'O arquivo de entrada precisa iniciar um servidor HTTP em process.env.PORT ' +
181
270
  '(ex: app.listen(process.env.PORT)). Se ele exporta apenas uma função (req, res), ' +
@@ -183,50 +272,64 @@ export class StaticServer {
183
272
  (output ? `\nSaída:\n${output}` : ''));
184
273
  }
185
274
  if (await isPortInUse(port)) {
186
- this.apiProxy = httpProxy.createProxyServer({
187
- target: `http://127.0.0.1:${port}`,
188
- ws: true,
189
- });
190
- this.apiProxy.on('error', (_err, _req, res) => {
191
- const response = res;
192
- if (response && typeof response.writeHead === 'function' && !response.headersSent) {
193
- response.writeHead(502, {
194
- 'Content-Type': 'application/json; charset=utf-8',
195
- });
196
- response.end(JSON.stringify({ error: 'Bad Gateway' }));
197
- }
198
- });
199
- ready = true;
275
+ this.apiProxy = this.createApiProxy(port);
276
+ this.apiReady = true;
277
+ this.scheduleApiHealthyReset();
278
+ if (isRestart) {
279
+ this.logSupervisor('[cm-tunnel] API reiniciada com sucesso.');
280
+ }
200
281
  return;
201
282
  }
202
283
  await new Promise((resolveWait) => setTimeout(resolveWait, 100));
203
284
  }
204
- this.stopApiServer();
205
285
  throw new Error(`API não ficou pronta em ${timeoutMs / 1000}s. ` +
206
286
  'Verifique se o entry chama app.listen(process.env.PORT).' +
207
287
  (output ? `\nSaída:\n${output}` : ''));
208
288
  }
289
+ /**
290
+ * Zera o contador de tentativas quando a API se mantém saudável tempo
291
+ * suficiente, para não desistir de reinícios pontuais ao longo do dia.
292
+ */
293
+ scheduleApiHealthyReset() {
294
+ if (this.apiHealthyTimer)
295
+ clearTimeout(this.apiHealthyTimer);
296
+ this.apiHealthyTimer = setTimeout(() => {
297
+ this.apiHealthyTimer = null;
298
+ this.apiRestartAttempts = 0;
299
+ }, API_HEALTHY_RESET_MS);
300
+ this.apiHealthyTimer.unref?.();
301
+ }
302
+ scheduleApiRestart(reason, detail = '') {
303
+ if (this.stopping)
304
+ return;
305
+ const suffix = detail ? ` ${detail}` : '';
306
+ if (!this.apiRestartEnabled) {
307
+ this.logSupervisor(`[cm-tunnel] ${reason}${suffix} Reinício automático desativado.`);
308
+ return;
309
+ }
310
+ if (this.apiRestartAttempts >= this.apiRestartMaxAttempts) {
311
+ this.logSupervisor(`[cm-tunnel] ${reason}${suffix} Limite de ${this.apiRestartMaxAttempts} ` +
312
+ 'reinícios atingido; a API ficará fora do ar.');
313
+ return;
314
+ }
315
+ this.apiRestartAttempts += 1;
316
+ const delay = Math.min(API_RESTART_BASE_DELAY_MS * 2 ** (this.apiRestartAttempts - 1), API_RESTART_MAX_DELAY_MS);
317
+ this.logSupervisor(`[cm-tunnel] ${reason}${suffix} Reiniciando em ${delay}ms ` +
318
+ `(tentativa ${this.apiRestartAttempts}/${this.apiRestartMaxAttempts}).`);
319
+ this.apiRestartTimer = setTimeout(() => {
320
+ this.apiRestartTimer = null;
321
+ if (this.stopping)
322
+ return;
323
+ void this.startApiServer(true);
324
+ }, delay);
325
+ }
209
326
  stopApiServer() {
210
327
  this.stopping = true;
211
- if (this.apiProxy) {
212
- try {
213
- this.apiProxy.close();
214
- }
215
- catch {
216
- // ignora
217
- }
218
- this.apiProxy = null;
328
+ if (this.apiRestartTimer) {
329
+ clearTimeout(this.apiRestartTimer);
330
+ this.apiRestartTimer = null;
219
331
  }
220
- if (this.apiProcess) {
221
- try {
222
- this.apiProcess.kill();
223
- }
224
- catch {
225
- // ignora
226
- }
227
- this.apiProcess = null;
228
- }
229
- this.apiPort = null;
332
+ this.teardownApi();
230
333
  }
231
334
  rewriteApiUrl(url) {
232
335
  if (!this.stripApiPrefix)
@@ -243,6 +346,7 @@ export class StaticServer {
243
346
  this.apiProxy.web(req, res);
244
347
  }
245
348
  async start() {
349
+ this.stopping = false;
246
350
  this.prepareRoots();
247
351
  if (this.apiMode === 'server') {
248
352
  await this.startApiServer();
package/dist/Tunnel.js CHANGED
@@ -76,38 +76,41 @@ export async function createTunnel(options) {
76
76
  let servedPort = null;
77
77
  // A porta do usuário (ou gerada pelo StaticServer) que o túnel/proxy vai mirar
78
78
  let targetPort = options.port || 3000;
79
- if (options.serve) {
80
- staticServerInstance = new StaticServer(options.serve);
81
- const serveResult = await staticServerInstance.start();
82
- servedPort = serveResult.port;
83
- targetPort = serveResult.port; // O túnel ou proxy apontará para o StaticServer
84
- }
85
- if (options.rateLimit) {
86
- rateLimiterInstance = new RateLimiter(targetPort, options.rateLimit);
87
- targetPort = await rateLimiterInstance.start(); // O túnel apontará para o proxy
88
- }
89
- const providerInstance = new ProviderClass({ ...options, port: targetPort });
79
+ const cleanup = () => {
80
+ rateLimiterInstance?.stop();
81
+ staticServerInstance?.stop();
82
+ };
90
83
  // We wrap the result in an EventEmitter to match the required API
91
84
  const emitter = new EventEmitter();
92
85
  let started = false;
93
- providerInstance.on("ready", (url) => {
94
- // Os providers emitem "ready" antes de start() resolver. Adiamos a
95
- // reemissão para que listeners registrados depois do await recebam o evento.
96
- setImmediate(() => emitter.emit("ready", url));
97
- });
98
- providerInstance.on("close", () => {
99
- rateLimiterInstance?.stop();
100
- staticServerInstance?.stop();
101
- emitter.emit("close");
102
- });
103
- providerInstance.on("error", (err) => {
104
- // Durante a inicialização o erro já é propagado pela rejeição de start().
105
- // Reemitir aqui, antes de o consumidor receber o emitter, derrubaria o
106
- // processo com um evento "error" sem listener.
107
- if (started)
108
- emitter.emit("error", err);
109
- });
110
86
  try {
87
+ if (options.serve) {
88
+ staticServerInstance = new StaticServer(options.serve);
89
+ const serveResult = await staticServerInstance.start();
90
+ servedPort = serveResult.port;
91
+ targetPort = serveResult.port; // O túnel ou proxy apontará para o StaticServer
92
+ }
93
+ if (options.rateLimit) {
94
+ rateLimiterInstance = new RateLimiter(targetPort, options.rateLimit);
95
+ targetPort = await rateLimiterInstance.start(); // O túnel apontará para o proxy
96
+ }
97
+ const providerInstance = new ProviderClass({ ...options, port: targetPort });
98
+ providerInstance.on("ready", (url) => {
99
+ // Os providers emitem "ready" antes de start() resolver. Adiamos a
100
+ // reemissão para que listeners registrados depois do await recebam o evento.
101
+ setImmediate(() => emitter.emit("ready", url));
102
+ });
103
+ providerInstance.on("close", () => {
104
+ cleanup();
105
+ emitter.emit("close");
106
+ });
107
+ providerInstance.on("error", (err) => {
108
+ // Durante a inicialização o erro já é propagado pela rejeição de start().
109
+ // Reemitir aqui, antes de o consumidor receber o emitter, derrubaria o
110
+ // processo com um evento "error" sem listener.
111
+ if (started)
112
+ emitter.emit("error", err);
113
+ });
111
114
  const result = await providerInstance.start();
112
115
  started = true;
113
116
  // Assign properties from result to the emitter instance to conform to TunnelInstance
@@ -116,8 +119,7 @@ export async function createTunnel(options) {
116
119
  url: result.url,
117
120
  port: options.port ?? servedPort ?? targetPort, // Porta original, do servidor interno ou do proxy
118
121
  stop: () => {
119
- rateLimiterInstance?.stop();
120
- staticServerInstance?.stop();
122
+ cleanup();
121
123
  result.stop();
122
124
  },
123
125
  process: result.process,
@@ -125,6 +127,9 @@ export async function createTunnel(options) {
125
127
  return emitter;
126
128
  }
127
129
  catch (err) {
130
+ // Se o provider falhar depois que serve/rateLimit subiram, eles precisam
131
+ // ser encerrados para não deixar portas/processos órfãos.
132
+ cleanup();
128
133
  throw new Error(`Falha ao iniciar o túnel: ${err.message}`);
129
134
  }
130
135
  }
@@ -4,6 +4,7 @@ export type Lang = "pt" | "en";
4
4
  export type Mode = "site" | "api" | "both";
5
5
  export type PublishMode = "quick" | "domain";
6
6
  export type Command = "doctor" | "dashboard";
7
+ export type ProviderName = "cloudflare" | "localtunnel" | "ngrok";
7
8
  export interface CliOptions {
8
9
  command?: Command;
9
10
  lang?: Lang;
@@ -22,6 +23,10 @@ export interface CliOptions {
22
23
  port?: number;
23
24
  domain?: string;
24
25
  token?: string;
26
+ /** Provedor do túnel (padrão: cloudflare) */
27
+ provider?: ProviderName;
28
+ /** Subdomínio fixo para localtunnel/ngrok */
29
+ subdomain?: string;
25
30
  quick: boolean;
26
31
  save: boolean;
27
32
  }
@@ -36,6 +41,10 @@ export interface Plan {
36
41
  apiPrefix: string;
37
42
  publish: PublishMode;
38
43
  domain?: string;
44
+ /** Provedor do túnel escolhido */
45
+ provider?: ProviderName;
46
+ /** Subdomínio fixo (localtunnel/ngrok) */
47
+ subdomain?: string;
39
48
  /** Porta de um servidor que já está rodando (modo proxy). */
40
49
  target?: number;
41
50
  /** Porta do servidor interno (modo pastas + domínio). */
@@ -72,6 +81,9 @@ export interface Strings {
72
81
  portInUse: (port: number) => string;
73
82
  missingToken: string;
74
83
  summaryTitle: string;
84
+ summaryPublishQuickWith: (provider: string) => string;
85
+ providerQuickOnly: (provider: string) => string;
86
+ ngrokTokenMissing: string;
75
87
  summarySite: (dir: string) => string;
76
88
  summaryApi: (dir: string, prefix: string) => string;
77
89
  summaryApiServer: (dir: string, entry: string) => string;
@@ -127,6 +139,7 @@ export interface Strings {
127
139
  dashboardModeBothServer: string;
128
140
  dashboardModeTarget: (port: number) => string;
129
141
  dashboardPublishQuick: string;
142
+ dashboardPublishQuickWith: (provider: string) => string;
130
143
  dashboardPublishDomain: (domain: string) => string;
131
144
  dashboardLocal: (value: string) => string;
132
145
  dashboardAwaitingLocal: string;
@@ -145,4 +158,4 @@ export declare function normalizeDomain(input: string): string;
145
158
  export declare function isValidDomain(domain: string): boolean;
146
159
  export declare function normalizePrefix(input?: string): string;
147
160
  export declare function guessMode(publicExists: boolean, apiExists: boolean): Mode;
148
- export declare function buildTunnelOptions(plan: Plan, token?: string): TunnelOptions;
161
+ export declare function buildTunnelOptions(plan: Plan, token?: string, ngrokToken?: string): TunnelOptions;
package/dist/cli-utils.js CHANGED
@@ -31,6 +31,9 @@ export const STRINGS = {
31
31
  portInUse: (port) => `A porta ${port} já está em uso. Escolha outra com --port.`,
32
32
  missingToken: "Token ausente. Defina CLOUDFLARE_TOKEN, use --token ou rode de forma interativa.",
33
33
  summaryTitle: "Resumo:",
34
+ summaryPublishQuickWith: (provider) => `Modo: URL temporária (${provider})`,
35
+ providerQuickOnly: (provider) => `${provider} não suporta domínio próprio; usando URL temporária.`,
36
+ ngrokTokenMissing: "Aviso: NGROK_AUTHTOKEN não definido. O ngrok pode exigir um authtoken (https://dashboard.ngrok.com/get-started/your-authtoken).",
34
37
  summarySite: (dir) => `Site: ${dir}`,
35
38
  summaryApi: (dir, prefix) => `API: ${dir} em ${prefix}`,
36
39
  summaryApiServer: (dir, entry) => `API: ${dir} (servidor: ${entry})`,
@@ -86,6 +89,7 @@ export const STRINGS = {
86
89
  dashboardModeBothServer: "Site + API (servidor)",
87
90
  dashboardModeTarget: (port) => `Servidor http://localhost:${port}`,
88
91
  dashboardPublishQuick: "URL temporária",
92
+ dashboardPublishQuickWith: (provider) => `URL temporária (${provider})`,
89
93
  dashboardPublishDomain: (domain) => `Domínio ${domain}`,
90
94
  dashboardLocal: (value) => `Local: ${value}`,
91
95
  dashboardAwaitingLocal: "Local: aguardando...",
@@ -126,6 +130,9 @@ export const STRINGS = {
126
130
  portInUse: (port) => `Port ${port} is already in use. Choose another with --port.`,
127
131
  missingToken: "Missing token. Set CLOUDFLARE_TOKEN, pass --token, or run interactively.",
128
132
  summaryTitle: "Summary:",
133
+ summaryPublishQuickWith: (provider) => `Mode: Temporary URL (${provider})`,
134
+ providerQuickOnly: (provider) => `${provider} does not support custom domains; using a temporary URL.`,
135
+ ngrokTokenMissing: "Warning: NGROK_AUTHTOKEN is not set. ngrok may require an authtoken (https://dashboard.ngrok.com/get-started/your-authtoken).",
129
136
  summarySite: (dir) => `Site: ${dir}`,
130
137
  summaryApi: (dir, prefix) => `API: ${dir} at ${prefix}`,
131
138
  summaryApiServer: (dir, entry) => `API: ${dir} (server: ${entry})`,
@@ -181,6 +188,7 @@ export const STRINGS = {
181
188
  dashboardModeBothServer: "Site + API (server)",
182
189
  dashboardModeTarget: (port) => `Server http://localhost:${port}`,
183
190
  dashboardPublishQuick: "Temporary URL",
191
+ dashboardPublishQuickWith: (provider) => `Temporary URL (${provider})`,
184
192
  dashboardPublishDomain: (domain) => `Domain ${domain}`,
185
193
  dashboardLocal: (value) => `Local: ${value}`,
186
194
  dashboardAwaitingLocal: "Local: waiting...",
@@ -211,7 +219,9 @@ Opções:
211
219
  --api-prefix <prefixo> Prefixo da API (padrão: /api)
212
220
  --target <porta> Tunelar um servidor que já está rodando
213
221
  --port <porta> Porta local (modo pastas + domínio)
214
- --domain <dominio> Domínio próprio
222
+ --provider <nome> cloudflare | localtunnel | ngrok (padrão: cloudflare)
223
+ --subdomain <nome> Subdomínio fixo (localtunnel/ngrok)
224
+ --domain <dominio> Domínio próprio (somente Cloudflare)
215
225
  --token <token> Token do túnel Cloudflare
216
226
  --quick URL temporária, sem configuração
217
227
  --yes, -y Não perguntar (usa flags/padrões)
@@ -224,7 +234,6 @@ Opções:
224
234
  en: `cm-tunnel — publish a site (public) and an API (api) in minutes
225
235
 
226
236
  Usage:
227
- Uso:
228
237
  npx cm-tunnel # interactive
229
238
  npx cm-tunnel --yes --quick # no questions
230
239
 
@@ -241,7 +250,9 @@ Options:
241
250
  --api-prefix <prefix> API prefix (default: /api)
242
251
  --target <port> Tunnel an already running server
243
252
  --port <port> Local port (folders + domain mode)
244
- --domain <domain> Custom domain
253
+ --provider <name> cloudflare | localtunnel | ngrok (default: cloudflare)
254
+ --subdomain <name> Fixed subdomain (localtunnel/ngrok)
255
+ --domain <domain> Custom domain (Cloudflare only)
245
256
  --token <token> Cloudflare tunnel token
246
257
  --quick Temporary URL, no setup
247
258
  --yes, -y Do not ask (use flags/defaults)
@@ -280,6 +291,8 @@ export function parseCliArgs(argv) {
280
291
  port: { type: "string" },
281
292
  domain: { type: "string" },
282
293
  token: { type: "string" },
294
+ provider: { type: "string" },
295
+ subdomain: { type: "string" },
283
296
  quick: { type: "boolean" },
284
297
  "no-save": { type: "boolean" },
285
298
  },
@@ -304,6 +317,13 @@ export function parseCliArgs(argv) {
304
317
  if (apiMode !== undefined && apiMode !== "handlers" && apiMode !== "server") {
305
318
  throw new Error(`Invalid --api-mode: "${apiMode}". Use handlers or server.`);
306
319
  }
320
+ const provider = values.provider;
321
+ if (provider !== undefined &&
322
+ provider !== "cloudflare" &&
323
+ provider !== "localtunnel" &&
324
+ provider !== "ngrok") {
325
+ throw new Error(`Invalid --provider: "${provider}". Use cloudflare, localtunnel or ngrok.`);
326
+ }
307
327
  const command = positionals[0];
308
328
  if (command !== undefined && command !== "doctor" && command !== "dashboard") {
309
329
  throw new Error(`Unknown command: "${command}". Use doctor or dashboard.`);
@@ -326,6 +346,8 @@ export function parseCliArgs(argv) {
326
346
  port,
327
347
  domain: values.domain,
328
348
  token: values.token,
349
+ provider: provider,
350
+ subdomain: values.subdomain,
329
351
  quick: !!values.quick,
330
352
  save: !values["no-save"],
331
353
  };
@@ -356,7 +378,8 @@ export function guessMode(publicExists, apiExists) {
356
378
  return "api";
357
379
  return "both";
358
380
  }
359
- export function buildTunnelOptions(plan, token) {
381
+ export function buildTunnelOptions(plan, token, ngrokToken) {
382
+ const provider = plan.provider ?? "cloudflare";
360
383
  const cloudflare = plan.publish === "quick"
361
384
  ? { mode: "quick" }
362
385
  : {
@@ -364,13 +387,20 @@ export function buildTunnelOptions(plan, token) {
364
387
  domain: plan.domain,
365
388
  token,
366
389
  };
390
+ const applyProviderOptions = (options) => {
391
+ if (plan.subdomain)
392
+ options.subdomain = plan.subdomain;
393
+ if (provider === "cloudflare") {
394
+ options.cloudflare = cloudflare;
395
+ }
396
+ else if (provider === "ngrok" && ngrokToken) {
397
+ options.authtoken = ngrokToken;
398
+ }
399
+ return options;
400
+ };
367
401
  // Modo servidor: apenas aponta o túnel para a porta já existente.
368
402
  if (plan.target) {
369
- return {
370
- provider: "cloudflare",
371
- port: plan.target,
372
- cloudflare,
373
- };
403
+ return applyProviderOptions({ provider, port: plan.target });
374
404
  }
375
405
  const serve = {
376
406
  apiPrefix: plan.apiPrefix,
@@ -386,7 +416,7 @@ export function buildTunnelOptions(plan, token) {
386
416
  if (plan.publish === "domain" && plan.port)
387
417
  serve.port = plan.port;
388
418
  const options = {
389
- provider: "cloudflare",
419
+ provider,
390
420
  serve,
391
421
  };
392
422
  if (plan.mode !== "site") {
@@ -395,6 +425,5 @@ export function buildTunnelOptions(plan, token) {
395
425
  routes: [plan.apiPrefix],
396
426
  };
397
427
  }
398
- options.cloudflare = cloudflare;
399
- return options;
428
+ return applyProviderOptions(options);
400
429
  }
package/dist/cli.js CHANGED
@@ -142,10 +142,6 @@ async function main() {
142
142
  if (!process.stdin.isTTY && !opts.yes) {
143
143
  throw new Error(s.needTty);
144
144
  }
145
- const check = spawnSync("cloudflared", ["--version"], { stdio: "ignore" });
146
- if (check.error) {
147
- throw new Error(s.cloudflaredMissing);
148
- }
149
145
  loadDotEnv();
150
146
  let saved = loadConfig();
151
147
  if (saved) {
@@ -153,6 +149,18 @@ async function main() {
153
149
  if (!useSaved)
154
150
  saved = null;
155
151
  }
152
+ const provider = opts.provider ?? saved?.provider ?? "cloudflare";
153
+ const subdomain = opts.subdomain ?? saved?.subdomain;
154
+ const ngrokToken = provider === "ngrok" ? process.env.NGROK_AUTHTOKEN || undefined : undefined;
155
+ if (provider === "ngrok" && !ngrokToken) {
156
+ console.warn(s.ngrokTokenMissing);
157
+ }
158
+ if (provider === "cloudflare") {
159
+ const check = spawnSync("cloudflared", ["--version"], { stdio: "ignore" });
160
+ if (check.error) {
161
+ throw new Error(s.cloudflaredMissing);
162
+ }
163
+ }
156
164
  const defaultPublic = opts.public ?? saved?.public ?? "public";
157
165
  const defaultApi = opts.api ?? saved?.api ?? "api";
158
166
  const suggestedMode = guessMode(existsSync(resolve(defaultPublic)), existsSync(resolve(defaultApi)));
@@ -240,7 +248,13 @@ async function main() {
240
248
  throw new Error(s.apiEntryInvalid(apiEntry));
241
249
  }
242
250
  let publish;
243
- if (opts.quick) {
251
+ if (provider !== "cloudflare") {
252
+ if (opts.domain || opts.token || saved?.publish === "domain") {
253
+ console.warn(s.providerQuickOnly(provider));
254
+ }
255
+ publish = "quick";
256
+ }
257
+ else if (opts.quick) {
244
258
  publish = "quick";
245
259
  }
246
260
  else if (opts.domain || opts.token) {
@@ -311,6 +325,8 @@ async function main() {
311
325
  apiPrefix: normalizePrefix(opts.apiPrefix ?? saved?.apiPrefix),
312
326
  publish,
313
327
  domain,
328
+ provider,
329
+ subdomain,
314
330
  target,
315
331
  port,
316
332
  };
@@ -329,7 +345,9 @@ async function main() {
329
345
  }
330
346
  }
331
347
  console.log(` ${publish === "quick"
332
- ? s.summaryPublishQuick
348
+ ? provider === "cloudflare"
349
+ ? s.summaryPublishQuick
350
+ : s.summaryPublishQuickWith(provider)
333
351
  : s.summaryPublishDomain(domain)}`);
334
352
  if (publish === "domain" && port && !target) {
335
353
  console.log(` ${s.summaryPort(port)}`);
@@ -349,7 +367,7 @@ async function main() {
349
367
  if (opts.command === "dashboard" && !process.stdout.isTTY) {
350
368
  console.log(s.dashboardNoTty);
351
369
  }
352
- const tunnelOptions = buildTunnelOptions(plan, token);
370
+ const tunnelOptions = buildTunnelOptions(plan, token, ngrokToken);
353
371
  if (wantLogs) {
354
372
  const logSink = (chunk) => {
355
373
  if (dashboard) {
package/dist/config.js CHANGED
@@ -62,6 +62,10 @@ export function loadConfig() {
62
62
  apiPrefix: typeof data.apiPrefix === 'string' ? normalizePrefix(data.apiPrefix) : '/api',
63
63
  publish: data.publish,
64
64
  domain: typeof data.domain === 'string' ? data.domain : undefined,
65
+ provider: data.provider === 'localtunnel' || data.provider === 'ngrok'
66
+ ? data.provider
67
+ : 'cloudflare',
68
+ subdomain: typeof data.subdomain === 'string' ? data.subdomain : undefined,
65
69
  target: typeof data.target === 'number' ? data.target : undefined,
66
70
  port: typeof data.port === 'number' ? data.port : undefined,
67
71
  };
package/dist/dashboard.js CHANGED
@@ -34,8 +34,12 @@ function modeLabel(plan, s) {
34
34
  : s.dashboardModeBoth;
35
35
  }
36
36
  function publishLabel(plan, s) {
37
- if (plan.publish === 'quick')
38
- return s.dashboardPublishQuick;
37
+ if (plan.publish === 'quick') {
38
+ const provider = plan.provider ?? 'cloudflare';
39
+ return provider === 'cloudflare'
40
+ ? s.dashboardPublishQuick
41
+ : s.dashboardPublishQuickWith(provider);
42
+ }
39
43
  return s.dashboardPublishDomain(plan.domain ?? '?');
40
44
  }
41
45
  export class Dashboard {
package/dist/doctor.js CHANGED
@@ -6,10 +6,15 @@ import { CONFIG_FILE, loadConfig, loadDotEnv } from './config.js';
6
6
  import { STRINGS } from './cli-utils.js';
7
7
  import { isPortFree, isPortInUse } from './net-utils.js';
8
8
  function describePlan(plan) {
9
+ const provider = plan.provider ?? 'cloudflare';
9
10
  if (plan.target) {
10
- return `server=${plan.target}, publish=${plan.publish}`;
11
+ return `server=${plan.target}, publish=${plan.publish}, provider=${provider}`;
11
12
  }
12
- const parts = [`mode=${plan.mode}`, `publish=${plan.publish}`];
13
+ const parts = [
14
+ `mode=${plan.mode}`,
15
+ `publish=${plan.publish}`,
16
+ `provider=${provider}`,
17
+ ];
13
18
  if (plan.publish === 'domain') {
14
19
  parts.push(`domain=${plan.domain ?? '?'}`, `port=${plan.port ?? '?'}`);
15
20
  }
@@ -40,20 +45,23 @@ export async function runDoctor(lang) {
40
45
  else {
41
46
  failLine(s.doctorNodeFail(process.versions.node));
42
47
  }
43
- const cloudflared = spawnSync('cloudflared', ['--version'], {
44
- encoding: 'utf8',
45
- timeout: 10000,
46
- });
47
- if (!cloudflared.error && cloudflared.status === 0) {
48
- const version = (cloudflared.stdout || cloudflared.stderr || '').split(/\r?\n/)[0].trim() ||
49
- 'ok';
50
- okLine(s.doctorCloudflaredOk(version));
51
- }
52
- else {
53
- failLine(s.doctorCloudflaredFail);
54
- }
55
48
  loadDotEnv();
56
49
  const plan = loadConfig();
50
+ const provider = plan?.provider ?? 'cloudflare';
51
+ if (provider === 'cloudflare') {
52
+ const cloudflared = spawnSync('cloudflared', ['--version'], {
53
+ encoding: 'utf8',
54
+ timeout: 10000,
55
+ });
56
+ if (!cloudflared.error && cloudflared.status === 0) {
57
+ const version = (cloudflared.stdout || cloudflared.stderr || '').split(/\r?\n/)[0].trim() ||
58
+ 'ok';
59
+ okLine(s.doctorCloudflaredOk(version));
60
+ }
61
+ else {
62
+ failLine(s.doctorCloudflaredFail);
63
+ }
64
+ }
57
65
  if (!plan) {
58
66
  if (existsSync(resolve(CONFIG_FILE))) {
59
67
  failLine(s.doctorConfigInvalid);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cm-tunnel",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "Exponha seu servidor HTTP local para a internet através do Cloudflare ou LocalTunnel de forma simples",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -21,8 +21,9 @@
21
21
  "test": "vitest run",
22
22
  "test:watch": "vitest",
23
23
  "lint": "tsc --noEmit",
24
+ "check:self": "node -e \"const fs=require('fs');const p=require('./package.json');if(p.dependencies&&p.dependencies['cm-tunnel']){console.error('Erro: cm-tunnel nao pode depender de si mesmo');process.exit(1)}if(fs.existsSync('node_modules/cm-tunnel')){console.error('Erro: node_modules/cm-tunnel aninhado');process.exit(1)}console.log('ok: sem self-dependency')\"",
24
25
  "format": "prettier --write \"src/**/*.ts\" \"examples/**/*.ts\" \"tests/**/*.ts\"",
25
- "prepublishOnly": "npm run lint && npm run test && npm run build"
26
+ "prepublishOnly": "npm run lint && npm run test && npm run check:self && npm run build"
26
27
  },
27
28
  "keywords": [
28
29
  "tunnel",
@@ -54,7 +55,6 @@
54
55
  "dependencies": {
55
56
  "@ngrok/ngrok": "^1.7.0",
56
57
  "bancoz": "^2.2.8",
57
- "cm-tunnel": "^1.5.0",
58
58
  "http-proxy": "^1.18.1",
59
59
  "localtunnel": "^2.0.2",
60
60
  "prompts": "^2.4.2"