cm-tunnel 1.3.3 → 1.7.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 +775 -106
- package/dist/StaticServer.d.ts +51 -0
- package/dist/StaticServer.js +480 -41
- package/dist/Tunnel.d.ts +2 -0
- package/dist/Tunnel.js +10 -3
- package/dist/cli-utils.d.ts +148 -0
- package/dist/cli-utils.js +400 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +423 -0
- package/dist/config.d.ts +7 -0
- package/dist/config.js +95 -0
- package/dist/dashboard.d.ts +23 -0
- package/dist/dashboard.js +163 -0
- package/dist/doctor.d.ts +2 -0
- package/dist/doctor.js +152 -0
- package/dist/net-utils.d.ts +6 -0
- package/dist/net-utils.js +40 -0
- package/dist/providers/cloudflare.js +3 -1
- package/package.json +13 -7
package/dist/cli.js
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync, } from "node:fs";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import prompts from "prompts";
|
|
6
|
+
import tunnel from "./index.js";
|
|
7
|
+
import { Dashboard } from "./dashboard.js";
|
|
8
|
+
import { runDoctor } from "./doctor.js";
|
|
9
|
+
import { CONFIG_FILE, loadConfig, loadDotEnv, saveConfig, saveTokenToEnv, } from "./config.js";
|
|
10
|
+
import { isPortFree, isPortInUse } from "./net-utils.js";
|
|
11
|
+
import { HELP, STRINGS, buildTunnelOptions, detectLang, guessMode, isValidDomain, isValidPort, normalizeDomain, normalizePrefix, parseCliArgs, } from "./cli-utils.js";
|
|
12
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
13
|
+
function langFromArgv() {
|
|
14
|
+
const index = process.argv.indexOf("--lang");
|
|
15
|
+
return index >= 0 ? process.argv[index + 1] : undefined;
|
|
16
|
+
}
|
|
17
|
+
function starterHtml(lang) {
|
|
18
|
+
const language = lang === "pt" ? "pt-BR" : "en";
|
|
19
|
+
const title = lang === "pt" ? "Meu site" : "My site";
|
|
20
|
+
const text = lang === "pt"
|
|
21
|
+
? "Site publicado com cm-tunnel."
|
|
22
|
+
: "Site published with cm-tunnel.";
|
|
23
|
+
return `<!doctype html>
|
|
24
|
+
<html lang="${language}">
|
|
25
|
+
<head>
|
|
26
|
+
<meta charset="utf-8" />
|
|
27
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
28
|
+
<title>${title}</title>
|
|
29
|
+
</head>
|
|
30
|
+
<body>
|
|
31
|
+
<h1>${text}</h1>
|
|
32
|
+
</body>
|
|
33
|
+
</html>
|
|
34
|
+
`;
|
|
35
|
+
}
|
|
36
|
+
const STARTER_API = `export default function handler(req, res) {
|
|
37
|
+
res.json({ ok: true, method: req.method, time: new Date().toISOString() });
|
|
38
|
+
}
|
|
39
|
+
`;
|
|
40
|
+
const STARTER_API_SERVER = `import http from 'node:http';
|
|
41
|
+
|
|
42
|
+
const port = Number(process.env.PORT);
|
|
43
|
+
|
|
44
|
+
const server = http.createServer((req, res) => {
|
|
45
|
+
res.setHeader('Content-Type', 'application/json');
|
|
46
|
+
res.end(JSON.stringify({ ok: true, url: req.url }));
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
server.listen(port, '127.0.0.1');
|
|
50
|
+
`;
|
|
51
|
+
function onCancel(s) {
|
|
52
|
+
console.log(`\n${s.cancelled}`);
|
|
53
|
+
process.exit(0);
|
|
54
|
+
}
|
|
55
|
+
async function askText(s, message, initial, validate) {
|
|
56
|
+
const res = await prompts({ type: "text", name: "value", message, initial, validate }, { onCancel: () => onCancel(s) });
|
|
57
|
+
return String(res.value ?? "").trim();
|
|
58
|
+
}
|
|
59
|
+
async function askPassword(s, message) {
|
|
60
|
+
const res = await prompts({ type: "password", name: "value", message }, { onCancel: () => onCancel(s) });
|
|
61
|
+
return String(res.value ?? "").trim();
|
|
62
|
+
}
|
|
63
|
+
async function askConfirm(s, message, initial) {
|
|
64
|
+
const res = await prompts({ type: "confirm", name: "value", message, initial }, { onCancel: () => onCancel(s) });
|
|
65
|
+
return !!res.value;
|
|
66
|
+
}
|
|
67
|
+
async function askSelect(s, message, choices, initial) {
|
|
68
|
+
const res = await prompts({ type: "select", name: "value", message, choices, initial }, { onCancel: () => onCancel(s) });
|
|
69
|
+
return res.value;
|
|
70
|
+
}
|
|
71
|
+
async function askPort(s, message, initial) {
|
|
72
|
+
const res = await prompts({
|
|
73
|
+
type: "number",
|
|
74
|
+
name: "value",
|
|
75
|
+
message,
|
|
76
|
+
initial,
|
|
77
|
+
min: 1,
|
|
78
|
+
max: 65535,
|
|
79
|
+
validate: (value) => isValidPort(Number(value)) || s.invalidPort,
|
|
80
|
+
}, { onCancel: () => onCancel(s) });
|
|
81
|
+
return Number(res.value);
|
|
82
|
+
}
|
|
83
|
+
async function ensureFolder(s, lang, dir, kind, yes, dryRun, apiMode = "handlers") {
|
|
84
|
+
if (!dir)
|
|
85
|
+
return;
|
|
86
|
+
if (dryRun)
|
|
87
|
+
return;
|
|
88
|
+
const abs = resolve(dir);
|
|
89
|
+
if (existsSync(abs)) {
|
|
90
|
+
if (!statSync(abs).isDirectory())
|
|
91
|
+
throw new Error(s.folderNotDir(dir));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const create = yes || (await askConfirm(s, s.createFolder(dir), true));
|
|
95
|
+
if (!create)
|
|
96
|
+
throw new Error(s.folderNotDir(dir));
|
|
97
|
+
mkdirSync(abs, { recursive: true });
|
|
98
|
+
if (kind === "site") {
|
|
99
|
+
writeFileSync(join(abs, "index.html"), starterHtml(lang));
|
|
100
|
+
}
|
|
101
|
+
else if (apiMode === "server") {
|
|
102
|
+
writeFileSync(join(abs, "index.js"), STARTER_API_SERVER);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
writeFileSync(join(abs, "hello.js"), STARTER_API);
|
|
106
|
+
}
|
|
107
|
+
console.log(s.createdFolder(dir));
|
|
108
|
+
}
|
|
109
|
+
async function chooseFolder(s, kind, explicit, savedPath, yes) {
|
|
110
|
+
const fallback = kind === "site" ? "public" : "api";
|
|
111
|
+
const chosen = explicit ?? savedPath;
|
|
112
|
+
if (chosen)
|
|
113
|
+
return chosen;
|
|
114
|
+
// Se a pasta padrão já existe, usa direto sem perguntar.
|
|
115
|
+
if (existsSync(resolve(fallback)) || yes)
|
|
116
|
+
return fallback;
|
|
117
|
+
return await askText(s, kind === "site" ? s.publicPath : s.apiPath, fallback, (value) => (value.trim() ? true : s.folderNotDir(value)));
|
|
118
|
+
}
|
|
119
|
+
async function main() {
|
|
120
|
+
let opts;
|
|
121
|
+
try {
|
|
122
|
+
opts = parseCliArgs(process.argv.slice(2));
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
console.log(HELP[detectLang(langFromArgv())]);
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
128
|
+
const lang = detectLang(opts.lang);
|
|
129
|
+
const s = STRINGS[lang];
|
|
130
|
+
if (opts.help) {
|
|
131
|
+
console.log(HELP[lang]);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (opts.version) {
|
|
135
|
+
console.log(`cm-tunnel ${pkg.version}`);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (opts.command === "doctor") {
|
|
139
|
+
process.exitCode = await runDoctor(lang);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (!process.stdin.isTTY && !opts.yes) {
|
|
143
|
+
throw new Error(s.needTty);
|
|
144
|
+
}
|
|
145
|
+
const check = spawnSync("cloudflared", ["--version"], { stdio: "ignore" });
|
|
146
|
+
if (check.error) {
|
|
147
|
+
throw new Error(s.cloudflaredMissing);
|
|
148
|
+
}
|
|
149
|
+
loadDotEnv();
|
|
150
|
+
let saved = loadConfig();
|
|
151
|
+
if (saved) {
|
|
152
|
+
const useSaved = opts.yes || (await askConfirm(s, s.useSaved, true));
|
|
153
|
+
if (!useSaved)
|
|
154
|
+
saved = null;
|
|
155
|
+
}
|
|
156
|
+
const defaultPublic = opts.public ?? saved?.public ?? "public";
|
|
157
|
+
const defaultApi = opts.api ?? saved?.api ?? "api";
|
|
158
|
+
const suggestedMode = guessMode(existsSync(resolve(defaultPublic)), existsSync(resolve(defaultApi)));
|
|
159
|
+
let mode;
|
|
160
|
+
let target;
|
|
161
|
+
if (opts.target !== undefined) {
|
|
162
|
+
target = opts.target;
|
|
163
|
+
mode = opts.mode ?? saved?.mode ?? "both";
|
|
164
|
+
}
|
|
165
|
+
else if (saved?.target) {
|
|
166
|
+
target = saved.target;
|
|
167
|
+
mode = saved.mode;
|
|
168
|
+
}
|
|
169
|
+
else if (opts.mode) {
|
|
170
|
+
mode = opts.mode;
|
|
171
|
+
}
|
|
172
|
+
else if (saved?.mode) {
|
|
173
|
+
// Configuração salva aceita: não repergunta o modo.
|
|
174
|
+
mode = saved.mode;
|
|
175
|
+
}
|
|
176
|
+
else if (opts.yes) {
|
|
177
|
+
mode = suggestedMode;
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
const choice = await askSelect(s, s.whatPublish, [
|
|
181
|
+
{ title: s.modeSite, value: "site" },
|
|
182
|
+
{ title: s.modeApi, value: "api" },
|
|
183
|
+
{ title: s.modeBoth, value: "both" },
|
|
184
|
+
{ title: s.modeServer, value: "server" },
|
|
185
|
+
], ["site", "api", "both"].indexOf(suggestedMode));
|
|
186
|
+
if (choice === "server") {
|
|
187
|
+
target = await askPort(s, s.serverPortPrompt, 3000);
|
|
188
|
+
mode = "both";
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
mode = choice;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (target !== undefined && !isValidPort(target)) {
|
|
195
|
+
throw new Error(s.invalidPort);
|
|
196
|
+
}
|
|
197
|
+
const publicPath = target || mode === "api"
|
|
198
|
+
? undefined
|
|
199
|
+
: await chooseFolder(s, "site", opts.public, saved?.public, opts.yes);
|
|
200
|
+
const apiPath = target || mode === "site"
|
|
201
|
+
? undefined
|
|
202
|
+
: await chooseFolder(s, "api", opts.api, saved?.api, opts.yes);
|
|
203
|
+
let apiMode;
|
|
204
|
+
let apiEntry;
|
|
205
|
+
if (!target && mode !== "site" && apiPath) {
|
|
206
|
+
const detectedEntry = ["index.js", "server.js", "app.js"]
|
|
207
|
+
.map((file) => join(apiPath, file))
|
|
208
|
+
.find((file) => existsSync(resolve(file)));
|
|
209
|
+
const suggestedApiMode = detectedEntry ? "server" : "handlers";
|
|
210
|
+
apiMode =
|
|
211
|
+
opts.apiMode ??
|
|
212
|
+
saved?.apiMode ??
|
|
213
|
+
(opts.yes
|
|
214
|
+
? suggestedApiMode
|
|
215
|
+
: await askSelect(s, s.apiModePrompt, [
|
|
216
|
+
{ title: s.apiModeHandlers, value: "handlers" },
|
|
217
|
+
{ title: s.apiModeServer, value: "server" },
|
|
218
|
+
], suggestedApiMode === "server" ? 1 : 0));
|
|
219
|
+
if (apiMode === "server") {
|
|
220
|
+
const defaultEntry = opts.apiEntry ??
|
|
221
|
+
saved?.apiEntry ??
|
|
222
|
+
detectedEntry ??
|
|
223
|
+
join(apiPath, "index.js");
|
|
224
|
+
apiEntry =
|
|
225
|
+
opts.apiEntry ??
|
|
226
|
+
saved?.apiEntry ??
|
|
227
|
+
(opts.yes
|
|
228
|
+
? defaultEntry
|
|
229
|
+
: await askText(s, s.apiEntryPrompt, defaultEntry));
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (!target) {
|
|
233
|
+
await ensureFolder(s, lang, publicPath, "site", opts.yes, opts.dryRun, apiMode);
|
|
234
|
+
await ensureFolder(s, lang, apiPath, "api", opts.yes, opts.dryRun, apiMode);
|
|
235
|
+
}
|
|
236
|
+
if (apiMode === "server" &&
|
|
237
|
+
apiEntry &&
|
|
238
|
+
!opts.dryRun &&
|
|
239
|
+
!existsSync(resolve(apiEntry))) {
|
|
240
|
+
throw new Error(s.apiEntryInvalid(apiEntry));
|
|
241
|
+
}
|
|
242
|
+
let publish;
|
|
243
|
+
if (opts.quick) {
|
|
244
|
+
publish = "quick";
|
|
245
|
+
}
|
|
246
|
+
else if (opts.domain || opts.token) {
|
|
247
|
+
publish = "domain";
|
|
248
|
+
}
|
|
249
|
+
else if (saved?.publish) {
|
|
250
|
+
publish = saved.publish;
|
|
251
|
+
}
|
|
252
|
+
else if (opts.yes) {
|
|
253
|
+
publish = "quick";
|
|
254
|
+
}
|
|
255
|
+
else {
|
|
256
|
+
publish = await askSelect(s, s.publishHow, [
|
|
257
|
+
{ title: s.publishQuick, value: "quick" },
|
|
258
|
+
{ title: s.publishDomain, value: "domain" },
|
|
259
|
+
], 0);
|
|
260
|
+
}
|
|
261
|
+
let domain;
|
|
262
|
+
let port;
|
|
263
|
+
let token;
|
|
264
|
+
if (publish === "domain") {
|
|
265
|
+
const domainAnswer = opts.domain ??
|
|
266
|
+
saved?.domain ??
|
|
267
|
+
(opts.yes ? "" : await askText(s, s.domainPrompt, undefined, (value) => isValidDomain(normalizeDomain(value)) || s.invalidDomain));
|
|
268
|
+
domain = normalizeDomain(domainAnswer);
|
|
269
|
+
if (!isValidDomain(domain)) {
|
|
270
|
+
throw new Error(s.invalidDomain);
|
|
271
|
+
}
|
|
272
|
+
token = opts.token || process.env.CLOUDFLARE_TOKEN;
|
|
273
|
+
let promptedToken = false;
|
|
274
|
+
if (!token && !opts.dryRun) {
|
|
275
|
+
if (opts.yes)
|
|
276
|
+
throw new Error(s.missingToken);
|
|
277
|
+
token = await askPassword(s, s.tokenPrompt);
|
|
278
|
+
promptedToken = true;
|
|
279
|
+
if (!token)
|
|
280
|
+
throw new Error(s.missingToken);
|
|
281
|
+
}
|
|
282
|
+
if (target) {
|
|
283
|
+
port = target;
|
|
284
|
+
if (!opts.dryRun && !(await isPortInUse(target))) {
|
|
285
|
+
console.warn(s.serverNotRunning(target));
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
port =
|
|
290
|
+
opts.port ??
|
|
291
|
+
saved?.port ??
|
|
292
|
+
(opts.yes ? 3000 : await askPort(s, s.portPrompt, 3000));
|
|
293
|
+
if (!isValidPort(port)) {
|
|
294
|
+
throw new Error(s.invalidPort);
|
|
295
|
+
}
|
|
296
|
+
if (!opts.dryRun && !(await isPortFree(port))) {
|
|
297
|
+
throw new Error(s.portInUse(port));
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (promptedToken && token && opts.save && !opts.dryRun) {
|
|
301
|
+
saveTokenToEnv(token);
|
|
302
|
+
console.log(s.tokenSaved);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const plan = {
|
|
306
|
+
mode,
|
|
307
|
+
public: publicPath,
|
|
308
|
+
api: apiPath,
|
|
309
|
+
apiMode,
|
|
310
|
+
apiEntry,
|
|
311
|
+
apiPrefix: normalizePrefix(opts.apiPrefix ?? saved?.apiPrefix),
|
|
312
|
+
publish,
|
|
313
|
+
domain,
|
|
314
|
+
target,
|
|
315
|
+
port,
|
|
316
|
+
};
|
|
317
|
+
console.log(`\n${s.summaryTitle}`);
|
|
318
|
+
if (target) {
|
|
319
|
+
console.log(` ${s.summaryServer(target)}`);
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
if (mode !== "api" && publicPath) {
|
|
323
|
+
console.log(` ${s.summarySite(publicPath)}`);
|
|
324
|
+
}
|
|
325
|
+
if (mode !== "site" && apiPath) {
|
|
326
|
+
console.log(` ${apiMode === "server"
|
|
327
|
+
? s.summaryApiServer(apiPath, apiEntry ?? "")
|
|
328
|
+
: s.summaryApi(apiPath, plan.apiPrefix)}`);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
console.log(` ${publish === "quick"
|
|
332
|
+
? s.summaryPublishQuick
|
|
333
|
+
: s.summaryPublishDomain(domain)}`);
|
|
334
|
+
if (publish === "domain" && port && !target) {
|
|
335
|
+
console.log(` ${s.summaryPort(port)}`);
|
|
336
|
+
}
|
|
337
|
+
console.log();
|
|
338
|
+
if (!opts.yes && !(await askConfirm(s, s.confirm, true))) {
|
|
339
|
+
console.log(s.cancelled);
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
if (opts.dryRun) {
|
|
343
|
+
console.log(s.dryRun);
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
const useDashboard = opts.command === "dashboard" && !!process.stdout.isTTY;
|
|
347
|
+
const wantLogs = opts.logs || opts.command === "dashboard";
|
|
348
|
+
const dashboard = useDashboard ? new Dashboard(lang, plan) : null;
|
|
349
|
+
if (opts.command === "dashboard" && !process.stdout.isTTY) {
|
|
350
|
+
console.log(s.dashboardNoTty);
|
|
351
|
+
}
|
|
352
|
+
const tunnelOptions = buildTunnelOptions(plan, token);
|
|
353
|
+
if (wantLogs) {
|
|
354
|
+
const logSink = (chunk) => {
|
|
355
|
+
if (dashboard) {
|
|
356
|
+
dashboard.push(chunk);
|
|
357
|
+
}
|
|
358
|
+
else {
|
|
359
|
+
process.stdout.write(chunk);
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
tunnelOptions.onLog = logSink;
|
|
363
|
+
if (tunnelOptions.serve) {
|
|
364
|
+
tunnelOptions.serve.onLog = logSink;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (dashboard) {
|
|
368
|
+
dashboard.start();
|
|
369
|
+
}
|
|
370
|
+
else {
|
|
371
|
+
console.log(s.starting);
|
|
372
|
+
}
|
|
373
|
+
let t;
|
|
374
|
+
try {
|
|
375
|
+
t = await tunnel(tunnelOptions);
|
|
376
|
+
}
|
|
377
|
+
catch (err) {
|
|
378
|
+
dashboard?.stop();
|
|
379
|
+
throw err;
|
|
380
|
+
}
|
|
381
|
+
if (dashboard) {
|
|
382
|
+
dashboard.setLocalPort(t.port);
|
|
383
|
+
dashboard.setUrl(t.url);
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
console.log(s.tunnelUrl(t.url));
|
|
387
|
+
if (target) {
|
|
388
|
+
console.log(` ${s.summaryServer(target)}`);
|
|
389
|
+
}
|
|
390
|
+
else {
|
|
391
|
+
if (mode !== "api" && publicPath) {
|
|
392
|
+
console.log(` ${s.siteServed(publicPath)}`);
|
|
393
|
+
}
|
|
394
|
+
if (mode !== "site" && apiPath) {
|
|
395
|
+
console.log(` ${apiMode === "server"
|
|
396
|
+
? s.summaryApiServer(apiPath, apiEntry ?? "")
|
|
397
|
+
: s.apiServed(apiPath, plan.apiPrefix)}`);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (publish === "domain" && domain && port) {
|
|
401
|
+
console.log(` ${s.domainHint(domain, port)}`);
|
|
402
|
+
}
|
|
403
|
+
console.log(s.pressCtrlC);
|
|
404
|
+
}
|
|
405
|
+
// Só salva a configuração depois que o túnel subiu com sucesso.
|
|
406
|
+
if (opts.save) {
|
|
407
|
+
saveConfig(plan);
|
|
408
|
+
if (!dashboard)
|
|
409
|
+
console.log(s.savedConfig(CONFIG_FILE));
|
|
410
|
+
}
|
|
411
|
+
const stop = () => {
|
|
412
|
+
dashboard?.stop();
|
|
413
|
+
t.stop();
|
|
414
|
+
process.exit(0);
|
|
415
|
+
};
|
|
416
|
+
process.on("SIGINT", stop);
|
|
417
|
+
process.on("SIGTERM", stop);
|
|
418
|
+
}
|
|
419
|
+
main().catch((err) => {
|
|
420
|
+
const lang = detectLang(langFromArgv());
|
|
421
|
+
console.error(STRINGS[lang].error(err instanceof Error ? err.message : String(err)));
|
|
422
|
+
process.exit(1);
|
|
423
|
+
});
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Plan } from './cli-utils.js';
|
|
2
|
+
export declare const CONFIG_FILE = ".cm-tunnel.json";
|
|
3
|
+
/** Carrega `.env` do diretório atual (com fallback para Node < 20.12). */
|
|
4
|
+
export declare function loadDotEnv(): void;
|
|
5
|
+
export declare function loadConfig(): Plan | null;
|
|
6
|
+
export declare function saveConfig(plan: Plan): void;
|
|
7
|
+
export declare function saveTokenToEnv(token: string): void;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { normalizePrefix } from './cli-utils.js';
|
|
4
|
+
export const CONFIG_FILE = '.cm-tunnel.json';
|
|
5
|
+
/** Carrega `.env` do diretório atual (com fallback para Node < 20.12). */
|
|
6
|
+
export function loadDotEnv() {
|
|
7
|
+
if (!existsSync('.env'))
|
|
8
|
+
return;
|
|
9
|
+
if (typeof process.loadEnvFile === 'function') {
|
|
10
|
+
try {
|
|
11
|
+
process.loadEnvFile('.env');
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
// Cai no parser manual abaixo.
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
const content = readFileSync(resolve('.env'), 'utf8');
|
|
20
|
+
for (const raw of content.split(/\r?\n/)) {
|
|
21
|
+
const line = raw.trim();
|
|
22
|
+
if (!line || line.startsWith('#'))
|
|
23
|
+
continue;
|
|
24
|
+
const separator = line.indexOf('=');
|
|
25
|
+
if (separator <= 0)
|
|
26
|
+
continue;
|
|
27
|
+
const key = line.slice(0, separator).trim();
|
|
28
|
+
let value = line.slice(separator + 1).trim();
|
|
29
|
+
if ((value.startsWith('"') && value.endsWith('"')) ||
|
|
30
|
+
(value.startsWith("'") && value.endsWith("'"))) {
|
|
31
|
+
value = value.slice(1, -1);
|
|
32
|
+
}
|
|
33
|
+
if (!(key in process.env)) {
|
|
34
|
+
process.env[key] = value;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// .env inválido é ignorado; o usuário ainda pode usar variáveis de ambiente.
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export function loadConfig() {
|
|
43
|
+
const file = resolve(CONFIG_FILE);
|
|
44
|
+
if (!existsSync(file))
|
|
45
|
+
return null;
|
|
46
|
+
try {
|
|
47
|
+
const data = JSON.parse(readFileSync(file, 'utf8'));
|
|
48
|
+
if (data?.mode !== 'site' && data?.mode !== 'api' && data?.mode !== 'both') {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
if (data?.publish !== 'quick' && data?.publish !== 'domain') {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
mode: data.mode,
|
|
56
|
+
public: typeof data.public === 'string' ? data.public : undefined,
|
|
57
|
+
api: typeof data.api === 'string' ? data.api : undefined,
|
|
58
|
+
apiMode: data.apiMode === 'server' || data.apiMode === 'handlers'
|
|
59
|
+
? data.apiMode
|
|
60
|
+
: undefined,
|
|
61
|
+
apiEntry: typeof data.apiEntry === 'string' ? data.apiEntry : undefined,
|
|
62
|
+
apiPrefix: typeof data.apiPrefix === 'string' ? normalizePrefix(data.apiPrefix) : '/api',
|
|
63
|
+
publish: data.publish,
|
|
64
|
+
domain: typeof data.domain === 'string' ? data.domain : undefined,
|
|
65
|
+
target: typeof data.target === 'number' ? data.target : undefined,
|
|
66
|
+
port: typeof data.port === 'number' ? data.port : undefined,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export function saveConfig(plan) {
|
|
74
|
+
writeFileSync(resolve(CONFIG_FILE), `${JSON.stringify(plan, null, 2)}\n`);
|
|
75
|
+
}
|
|
76
|
+
export function saveTokenToEnv(token) {
|
|
77
|
+
const file = resolve('.env');
|
|
78
|
+
let content = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
79
|
+
const line = `CLOUDFLARE_TOKEN=${token}`;
|
|
80
|
+
if (/^CLOUDFLARE_TOKEN=.*$/m.test(content)) {
|
|
81
|
+
content = content.replace(/^CLOUDFLARE_TOKEN=.*$/m, line);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
if (content && !content.endsWith('\n'))
|
|
85
|
+
content += '\n';
|
|
86
|
+
content += `${line}\n`;
|
|
87
|
+
}
|
|
88
|
+
writeFileSync(file, content);
|
|
89
|
+
try {
|
|
90
|
+
chmodSync(file, 0o600);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// Em sistemas sem suporte a chmod, segue normalmente.
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type Lang, type Plan } from './cli-utils.js';
|
|
2
|
+
export declare class Dashboard {
|
|
3
|
+
private lang;
|
|
4
|
+
private plan;
|
|
5
|
+
private logs;
|
|
6
|
+
private partial;
|
|
7
|
+
private url;
|
|
8
|
+
private localPort?;
|
|
9
|
+
private status;
|
|
10
|
+
private renderTimer;
|
|
11
|
+
private readonly enabled;
|
|
12
|
+
private readonly color;
|
|
13
|
+
constructor(lang: Lang, plan: Plan);
|
|
14
|
+
get isEnabled(): boolean;
|
|
15
|
+
push(chunk: string): void;
|
|
16
|
+
private scheduleRender;
|
|
17
|
+
setUrl(url: string): void;
|
|
18
|
+
setLocalPort(port: number): void;
|
|
19
|
+
start(): void;
|
|
20
|
+
stop(): void;
|
|
21
|
+
private paint;
|
|
22
|
+
private render;
|
|
23
|
+
}
|