Repository navigation
Expand file tree
/
Copy pathclient.ts
More file actions
182 lines (163 loc) · 5.02 KB
/
Copy pathclient.ts
File metadata and controls
182 lines (163 loc) · 5.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import * as fs from "node:fs";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import axios, { type AxiosInstance } from "axios";
import chalk from "chalk";
import { printFriendlyError } from "./ui/errors.js";
import { setCurrentEndpoint, spinnerLabel } from "./ui/presenters.js";
import { withSpinner } from "./ui/spinner.js";
import { canAnimate } from "./ui/style.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const configPath = path.join(__dirname, "..", "config.json");
export interface AuthConfig {
token: string;
url: string;
}
function loadEnvFile(): void {
const envPath = path.resolve(process.cwd(), ".env");
if (!fs.existsSync(envPath)) return;
const content = fs.readFileSync(envPath, "utf8");
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eqIndex = trimmed.indexOf("=");
if (eqIndex === -1) continue;
const key = trimmed.slice(0, eqIndex).trim();
const value = trimmed
.slice(eqIndex + 1)
.trim()
.replace(/^["']|["']$/g, "");
if (!process.env[key]) {
process.env[key] = value;
}
}
}
export function readAuthConfig(): AuthConfig {
loadEnvFile();
const envToken =
process.env.DOKPLOY_API_KEY ?? process.env.DOKPLOY_AUTH_TOKEN;
const envUrl = process.env.DOKPLOY_URL;
if (envToken && envUrl) {
return { token: envToken, url: envUrl };
}
if (!fs.existsSync(configPath)) {
if (canAnimate()) {
printFriendlyError({
title: "Not connected to a Dokploy server",
details: [],
hints: [
"Run: dokploy auth --url <server-url> --token <api-key>",
"Or set DOKPLOY_URL and DOKPLOY_API_KEY in your environment or a .env file.",
],
});
} else {
console.error(
chalk.red(
"No configuration found. Please run 'dokploy auth' first or set DOKPLOY_URL and DOKPLOY_AUTH_TOKEN environment variables.",
),
);
}
process.exit(1);
}
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
const { token, url } = config;
if (!url || !token) {
if (canAnimate()) {
printFriendlyError({
title: "Saved credentials are incomplete",
details: [],
hints: ["Run: dokploy auth --url <server-url> --token <api-key>"],
});
} else {
console.error(
chalk.red(
"Incomplete auth config. Run 'dokploy auth' or set environment variables.",
),
);
}
process.exit(1);
}
return { token, url };
}
export function peekServerUrl(): string | null {
try {
// Same order as readAuthConfig: env only when both URL and key are set.
loadEnvFile();
const envToken =
process.env.DOKPLOY_API_KEY ?? process.env.DOKPLOY_AUTH_TOKEN;
if (envToken && process.env.DOKPLOY_URL) return process.env.DOKPLOY_URL;
if (!fs.existsSync(configPath)) return null;
const { url, token } = JSON.parse(fs.readFileSync(configPath, "utf8"));
return typeof url === "string" && url && token ? url : null;
} catch {
return null;
}
}
export function getConfigPath(): string {
return configPath;
}
function activityLabel(endpoint: string): string {
setCurrentEndpoint(endpoint);
const custom = spinnerLabel(endpoint);
if (custom) return custom;
const kebab = (s: string) =>
s.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
const [group = "", ...rest] = endpoint.split(".");
return `${kebab(group)} ${kebab(rest.join("."))}`.trim();
}
export function saveAuthConfig(url: string, token: string): void {
fs.writeFileSync(configPath, JSON.stringify({ url, token }, null, 2));
}
export function createClient(): AxiosInstance {
const auth = readAuthConfig();
return axios.create({
baseURL: `${auth.url}/api`,
headers: {
"x-api-key": auth.token,
"Content-Type": "application/json",
},
});
}
export function getApiErrorMessage(error: unknown): string {
if (axios.isAxiosError(error)) {
const body = error.response?.data?.error?.json;
const zodError = body?.data?.zodError;
const validationMessages: string[] = zodError
? [
...(zodError.formErrors ?? []),
...Object.values<string[]>(zodError.fieldErrors ?? {}).flat(),
]
: [];
if (validationMessages.length > 0) {
return validationMessages.join("\n");
}
if (typeof body?.message === "string" && body.message !== body.data?.code) {
return body.message;
}
}
return error instanceof Error ? error.message : String(error);
}
export async function apiPost(
endpoint: string,
data?: Record<string, unknown>,
) {
const client = createClient();
const response = await withSpinner(activityLabel(endpoint), () =>
client.post(`/trpc/${endpoint}`, data ? { json: data } : undefined),
);
return response.data?.result?.data?.json ?? response.data;
}
export async function apiGet(
endpoint: string,
params?: Record<string, unknown>,
) {
const client = createClient();
const query = params
? `?input=${encodeURIComponent(JSON.stringify(params))}`
: "";
const response = await withSpinner(activityLabel(endpoint), () =>
client.get(`/trpc/${endpoint}${query}`),
);
return response.data?.result?.data?.json ?? response.data;
}