@vite-hub/cli 0.1.0 → 0.3.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 +52 -13
- package/dist/commands-DPg3kL8m.js +3104 -0
- package/dist/console-auth-xl7kLQNt.js +315 -0
- package/dist/console-env-C5YeAm2-.js +198 -0
- package/dist/env-DzoVtVJO.js +5820 -0
- package/dist/envelope-Cf56AJLa.js +88 -0
- package/dist/index.d.ts +22 -50
- package/dist/index.js +665 -1212
- package/dist/provision-C9p1wSzq.d.ts +170 -0
- package/dist/provision-D8OvBBzi.js +2262 -0
- package/dist/setup/index.d.ts +919 -0
- package/dist/setup/index.js +231 -0
- package/package.json +31 -12
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { m as cliErrorDiagnostics } from "./provision-D8OvBBzi.js";
|
|
2
|
+
import { o as writeSetupError, r as setupExitCodes, s as writeSetupJson } from "./envelope-Cf56AJLa.js";
|
|
3
|
+
import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { homedir, hostname } from "node:os";
|
|
6
|
+
import { parseArgs } from "node:util";
|
|
7
|
+
//#region src/setup/console-auth.ts
|
|
8
|
+
/** The hosted Console. `--console` and `VITEHUB_CONSOLE_URL` name a self-hosted one. */
|
|
9
|
+
const defaultConsoleUrl = "https://console.vitehub.dev";
|
|
10
|
+
/** An API key for CI. It wins over the saved key, and `vitehub logout` does not remove it. */
|
|
11
|
+
const consoleTokenVariable = "VITEHUB_CONSOLE_TOKEN";
|
|
12
|
+
const consoleUrlVariable = "VITEHUB_CONSOLE_URL";
|
|
13
|
+
const clientId = "vitehub-cli";
|
|
14
|
+
/** `$XDG_CONFIG_HOME/vitehub/credentials.json`, else `~/.config/vitehub/credentials.json`. */
|
|
15
|
+
function consoleCredentialsFile(env) {
|
|
16
|
+
const base = env.XDG_CONFIG_HOME || join(env.HOME || env.USERPROFILE || homedir(), ".config");
|
|
17
|
+
return join(base, "vitehub", "credentials.json");
|
|
18
|
+
}
|
|
19
|
+
async function readCredentials(file) {
|
|
20
|
+
const text = await readFile(file, "utf8").catch((error) => {
|
|
21
|
+
if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return void 0;
|
|
22
|
+
throw error;
|
|
23
|
+
});
|
|
24
|
+
if (text === void 0) return {
|
|
25
|
+
version: 1,
|
|
26
|
+
consoles: {}
|
|
27
|
+
};
|
|
28
|
+
const parsed = JSON.parse(text);
|
|
29
|
+
const consoles = parsed instanceof Object ? Reflect.get(parsed, "consoles") : void 0;
|
|
30
|
+
return {
|
|
31
|
+
version: 1,
|
|
32
|
+
consoles: consoles instanceof Object ? consoles : {}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** Writes the file with mode 600 in a folder with mode 700. A temporary file and a rename keep it whole. */
|
|
36
|
+
async function writeCredentials(file, value) {
|
|
37
|
+
await mkdir(dirname(file), {
|
|
38
|
+
mode: 448,
|
|
39
|
+
recursive: true
|
|
40
|
+
});
|
|
41
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
42
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 384 });
|
|
43
|
+
await chmod(temporary, 384);
|
|
44
|
+
await rename(temporary, file);
|
|
45
|
+
}
|
|
46
|
+
/** The origin of a Console URL. Plain `http` is accepted only for a Console on this machine. */
|
|
47
|
+
function consoleOrigin(value) {
|
|
48
|
+
let url;
|
|
49
|
+
try {
|
|
50
|
+
url = new URL(value);
|
|
51
|
+
} catch {
|
|
52
|
+
throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --console must be a URL, such as ${defaultConsoleUrl}. Got ${JSON.stringify(value)}.` });
|
|
53
|
+
}
|
|
54
|
+
const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
|
|
55
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --console must be an https:// URL. Plain http:// is only for a Console on localhost. Got ${url.origin}.` });
|
|
56
|
+
return url.origin;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The key that a command sends to a Console, and where it came from: `VITEHUB_CONSOLE_TOKEN`, else the key that
|
|
60
|
+
* `vitehub login` saved for the Console. Without `console`, the Console is `VITEHUB_CONSOLE_URL`, else the only saved
|
|
61
|
+
* Console, else console.vitehub.dev. `undefined` when there is no key.
|
|
62
|
+
*/
|
|
63
|
+
async function readConsoleCredential(env, console) {
|
|
64
|
+
const file = await readCredentials(consoleCredentialsFile(env));
|
|
65
|
+
const named = console ?? env["VITEHUB_CONSOLE_URL"];
|
|
66
|
+
const saved = Object.keys(file.consoles);
|
|
67
|
+
const origin = consoleOrigin(named ?? (saved.length === 1 ? saved[0] : "https://console.vitehub.dev"));
|
|
68
|
+
const token = env[consoleTokenVariable];
|
|
69
|
+
if (token) return {
|
|
70
|
+
origin,
|
|
71
|
+
source: "env",
|
|
72
|
+
token
|
|
73
|
+
};
|
|
74
|
+
const credential = file.consoles[origin];
|
|
75
|
+
return credential ? {
|
|
76
|
+
origin,
|
|
77
|
+
saved: credential,
|
|
78
|
+
source: "file",
|
|
79
|
+
token: credential.token
|
|
80
|
+
} : void 0;
|
|
81
|
+
}
|
|
82
|
+
function readArgs(args, usage, extra = {}) {
|
|
83
|
+
try {
|
|
84
|
+
return parseArgs({
|
|
85
|
+
args,
|
|
86
|
+
options: {
|
|
87
|
+
...extra.console ? { console: { type: "string" } } : {},
|
|
88
|
+
help: {
|
|
89
|
+
short: "h",
|
|
90
|
+
type: "boolean",
|
|
91
|
+
default: false
|
|
92
|
+
},
|
|
93
|
+
json: {
|
|
94
|
+
type: "boolean",
|
|
95
|
+
default: false
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
strict: true
|
|
99
|
+
}).values;
|
|
100
|
+
} catch (error) {
|
|
101
|
+
throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage}` });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async function postJson(context, url, body) {
|
|
105
|
+
const response = await (context.fetch ?? fetch)(url, {
|
|
106
|
+
body: JSON.stringify(body),
|
|
107
|
+
headers: {
|
|
108
|
+
accept: "application/json",
|
|
109
|
+
"content-type": "application/json"
|
|
110
|
+
},
|
|
111
|
+
method: "POST"
|
|
112
|
+
});
|
|
113
|
+
const data = await response.json().catch(() => ({}));
|
|
114
|
+
return {
|
|
115
|
+
data: data instanceof Object ? data : {},
|
|
116
|
+
headers: response.headers,
|
|
117
|
+
status: response.status
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function loginFailed(origin, message) {
|
|
121
|
+
return cliErrorDiagnostics.CLI_CONSOLE_LOGIN_FAILED({
|
|
122
|
+
console: origin,
|
|
123
|
+
message
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
const wait = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
|
|
127
|
+
const dateFormat = new Intl.DateTimeFormat("en-GB", {
|
|
128
|
+
day: "numeric",
|
|
129
|
+
month: "short",
|
|
130
|
+
year: "numeric",
|
|
131
|
+
timeZone: "UTC"
|
|
132
|
+
});
|
|
133
|
+
/** The user code in two groups, such as `WDJB-MJHT`, as RFC 8628 suggests. The Console accepts it with or without the dash. */
|
|
134
|
+
function groupCode(code) {
|
|
135
|
+
return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
|
|
136
|
+
}
|
|
137
|
+
/** Runs the device flow against `origin` and returns the API key. The key is never written to a stream. */
|
|
138
|
+
async function deviceLogin(origin, context, prompt) {
|
|
139
|
+
const started = await postJson(context, `${origin}/api/auth/device/code`, {
|
|
140
|
+
client_id: clientId,
|
|
141
|
+
client_name: `vitehub CLI on ${hostname()}`
|
|
142
|
+
}).catch((error) => {
|
|
143
|
+
throw loginFailed(origin, `The Console did not answer: ${error instanceof Error ? error.message : String(error)}`);
|
|
144
|
+
});
|
|
145
|
+
if (started.status !== 200 || typeof started.data.device_code !== "string") throw loginFailed(origin, `The Console answered ${started.status} to the device code request${typeof started.data.error === "string" ? ` (${started.data.error})` : ""}. Is ${origin} a ViteHub Console?`);
|
|
146
|
+
const code = started.data;
|
|
147
|
+
prompt.write(`Open ${code.verification_uri} and enter the code ${groupCode(code.user_code)}\n`);
|
|
148
|
+
if (code.verification_uri_complete) prompt.write(`Or open ${code.verification_uri_complete}\n`);
|
|
149
|
+
prompt.write("Waiting for approval...\n");
|
|
150
|
+
let interval = Number.isFinite(code.interval) ? code.interval : 5;
|
|
151
|
+
const deadline = Date.now() + code.expires_in * 1e3;
|
|
152
|
+
while (Date.now() < deadline) {
|
|
153
|
+
await wait(interval);
|
|
154
|
+
const answer = await postJson(context, `${origin}/api/auth/cli/token`, {
|
|
155
|
+
client_id: clientId,
|
|
156
|
+
device_code: code.device_code
|
|
157
|
+
});
|
|
158
|
+
if (answer.status === 200 && typeof answer.data.access_token === "string") return answer.data;
|
|
159
|
+
if (answer.status === 429) {
|
|
160
|
+
interval = Math.max(interval, Number(answer.headers.get("retry-after")) || 60);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
const error = answer.data.error;
|
|
164
|
+
if (error === "authorization_pending") continue;
|
|
165
|
+
if (error === "slow_down") {
|
|
166
|
+
interval += 5;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (error === "access_denied") throw loginFailed(origin, "The sign-in was denied in the browser.");
|
|
170
|
+
if (error === "expired_token") break;
|
|
171
|
+
throw loginFailed(origin, `The Console answered ${answer.status}${typeof error === "string" ? ` (${error})` : ""}.`);
|
|
172
|
+
}
|
|
173
|
+
throw loginFailed(origin, "The code expired before anyone approved it.");
|
|
174
|
+
}
|
|
175
|
+
const loginUsage = "vitehub login [--console <url>] [--json]";
|
|
176
|
+
const loginCommand = {
|
|
177
|
+
description: `Sign in to a ViteHub Console with the device flow, and save an API key for this machine. The default Console is ${defaultConsoleUrl}; --console or ${consoleUrlVariable} names another.`,
|
|
178
|
+
name: "login",
|
|
179
|
+
usage: loginUsage,
|
|
180
|
+
run: async (args, context) => {
|
|
181
|
+
const json = args.includes("--json");
|
|
182
|
+
try {
|
|
183
|
+
const values = readArgs(args, loginUsage, { console: true });
|
|
184
|
+
if (values.help) {
|
|
185
|
+
context.stdout.write(`Usage: ${loginUsage}\n\n${loginCommand.description}\n`);
|
|
186
|
+
return setupExitCodes.done;
|
|
187
|
+
}
|
|
188
|
+
const origin = consoleOrigin(values.console ?? context.env["VITEHUB_CONSOLE_URL"] ?? "https://console.vitehub.dev");
|
|
189
|
+
const answer = await deviceLogin(origin, context, json ? context.stderr : context.stdout);
|
|
190
|
+
const file = consoleCredentialsFile(context.env);
|
|
191
|
+
const saved = await readCredentials(file);
|
|
192
|
+
const credential = {
|
|
193
|
+
expiresAt: Date.now() + answer.expires_in * 1e3,
|
|
194
|
+
keyId: answer.key_id,
|
|
195
|
+
team: answer.team,
|
|
196
|
+
token: answer.access_token,
|
|
197
|
+
user: answer.user
|
|
198
|
+
};
|
|
199
|
+
await writeCredentials(file, {
|
|
200
|
+
version: 1,
|
|
201
|
+
consoles: {
|
|
202
|
+
...saved.consoles,
|
|
203
|
+
[origin]: credential
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
const result = {
|
|
207
|
+
console: origin,
|
|
208
|
+
expiresAt: new Date(credential.expiresAt).toISOString(),
|
|
209
|
+
file,
|
|
210
|
+
team: credential.team,
|
|
211
|
+
user: credential.user
|
|
212
|
+
};
|
|
213
|
+
if (json) writeSetupJson(context, result);
|
|
214
|
+
else context.stdout.write(`Signed in to ${origin} as ${credential.user.name}${credential.user.email ? ` (${credential.user.email})` : ""} in team ${credential.team.name}.\nThe API key expires on ${dateFormat.format(new Date(credential.expiresAt))}. Saved in ${file}.\n`);
|
|
215
|
+
if (context.env["VITEHUB_CONSOLE_TOKEN"]) context.stderr.write(`[vitehub] ${consoleTokenVariable} is set, so commands use it instead of this key.\n`);
|
|
216
|
+
return setupExitCodes.done;
|
|
217
|
+
} catch (error) {
|
|
218
|
+
return writeSetupError(context, json, error);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
const whoamiUsage = "vitehub whoami [--console <url>] [--json]";
|
|
223
|
+
const whoamiCommand = {
|
|
224
|
+
description: `Show the person and the team of the Console API key: ${consoleTokenVariable}, else the key of \`vitehub login\`.`,
|
|
225
|
+
name: "whoami",
|
|
226
|
+
usage: whoamiUsage,
|
|
227
|
+
run: async (args, context) => {
|
|
228
|
+
const json = args.includes("--json");
|
|
229
|
+
try {
|
|
230
|
+
const values = readArgs(args, whoamiUsage, { console: true });
|
|
231
|
+
if (values.help) {
|
|
232
|
+
context.stdout.write(`Usage: ${whoamiUsage}\n\n${whoamiCommand.description}\n`);
|
|
233
|
+
return setupExitCodes.done;
|
|
234
|
+
}
|
|
235
|
+
const credential = await readConsoleCredential(context.env, values.console);
|
|
236
|
+
if (!credential) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: consoleOrigin(values.console ?? context.env["VITEHUB_CONSOLE_URL"] ?? "https://console.vitehub.dev") });
|
|
237
|
+
const response = await (context.fetch ?? fetch)(`${credential.origin}/api/whoami`, { headers: {
|
|
238
|
+
accept: "application/json",
|
|
239
|
+
authorization: `Bearer ${credential.token}`
|
|
240
|
+
} });
|
|
241
|
+
if (response.status === 401) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: credential.origin });
|
|
242
|
+
if (!response.ok) throw cliErrorDiagnostics.CLI_R0001({ message: `[vitehub] ${credential.origin} answered ${response.status} to /api/whoami.` });
|
|
243
|
+
const me = await response.json();
|
|
244
|
+
const source = credential.source === "env" ? consoleTokenVariable : consoleCredentialsFile(context.env);
|
|
245
|
+
if (json) writeSetupJson(context, {
|
|
246
|
+
console: credential.origin,
|
|
247
|
+
expiresAt: new Date(me.key.expiresAt).toISOString(),
|
|
248
|
+
projectIds: me.projectIds,
|
|
249
|
+
roles: me.roles,
|
|
250
|
+
source,
|
|
251
|
+
team: me.team,
|
|
252
|
+
user: me.user
|
|
253
|
+
});
|
|
254
|
+
else {
|
|
255
|
+
context.stdout.write(`${me.user.name}${me.user.email ? ` (${me.user.email})` : ""} in team ${me.team.name} (${me.roles.join(", ")}) on ${credential.origin}\n`);
|
|
256
|
+
context.stdout.write(`Key from ${source}, for ${me.projectIds ? `${me.projectIds.length} project${me.projectIds.length === 1 ? "" : "s"}` : "every project of the team"}, expires on ${dateFormat.format(new Date(me.key.expiresAt))}.\n`);
|
|
257
|
+
}
|
|
258
|
+
return setupExitCodes.done;
|
|
259
|
+
} catch (error) {
|
|
260
|
+
return writeSetupError(context, json, error);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
const logoutUsage = "vitehub logout [--console <url>] [--json]";
|
|
265
|
+
const logoutCommand = {
|
|
266
|
+
description: "Revoke the API key of `vitehub login` on the Console and remove it from this machine.",
|
|
267
|
+
name: "logout",
|
|
268
|
+
usage: logoutUsage,
|
|
269
|
+
run: async (args, context) => {
|
|
270
|
+
const json = args.includes("--json");
|
|
271
|
+
try {
|
|
272
|
+
const values = readArgs(args, logoutUsage, { console: true });
|
|
273
|
+
if (values.help) {
|
|
274
|
+
context.stdout.write(`Usage: ${logoutUsage}\n\n${logoutCommand.description}\n`);
|
|
275
|
+
return setupExitCodes.done;
|
|
276
|
+
}
|
|
277
|
+
const file = consoleCredentialsFile(context.env);
|
|
278
|
+
const saved = await readCredentials(file);
|
|
279
|
+
const credential = await readConsoleCredential({
|
|
280
|
+
...context.env,
|
|
281
|
+
[consoleTokenVariable]: void 0
|
|
282
|
+
}, values.console);
|
|
283
|
+
if (!credential) {
|
|
284
|
+
if (json) writeSetupJson(context, { removed: false });
|
|
285
|
+
else context.stdout.write("Not signed in.\n");
|
|
286
|
+
return setupExitCodes.done;
|
|
287
|
+
}
|
|
288
|
+
const response = await (context.fetch ?? fetch)(`${credential.origin}/api/api-keys/current`, {
|
|
289
|
+
headers: { authorization: `Bearer ${credential.token}` },
|
|
290
|
+
method: "DELETE"
|
|
291
|
+
}).catch(() => void 0);
|
|
292
|
+
const revoked = response !== void 0 && (response.status === 204 || response.status === 401 || response.status === 404);
|
|
293
|
+
const { [credential.origin]: _removed, ...consoles } = saved.consoles;
|
|
294
|
+
await writeCredentials(file, {
|
|
295
|
+
version: 1,
|
|
296
|
+
consoles
|
|
297
|
+
});
|
|
298
|
+
if (json) writeSetupJson(context, {
|
|
299
|
+
console: credential.origin,
|
|
300
|
+
removed: true,
|
|
301
|
+
revoked
|
|
302
|
+
});
|
|
303
|
+
else {
|
|
304
|
+
context.stdout.write(`Signed out of ${credential.origin}.\n`);
|
|
305
|
+
if (!revoked) context.stderr.write("[vitehub] The Console did not revoke the key. Revoke it in Account settings, under API keys.\n");
|
|
306
|
+
}
|
|
307
|
+
if (context.env["VITEHUB_CONSOLE_TOKEN"]) context.stderr.write(`[vitehub] ${consoleTokenVariable} is still set. Unset it to sign out completely.\n`);
|
|
308
|
+
return setupExitCodes.done;
|
|
309
|
+
} catch (error) {
|
|
310
|
+
return writeSetupError(context, json, error);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
//#endregion
|
|
315
|
+
export { defaultConsoleUrl as a, readConsoleCredential as c, consoleUrlVariable as i, whoamiCommand as l, consoleOrigin as n, loginCommand as o, consoleTokenVariable as r, logoutCommand as s, consoleCredentialsFile as t };
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { m as cliErrorDiagnostics } from "./provision-D8OvBBzi.js";
|
|
2
|
+
import { o as writeSetupError, s as writeSetupJson } from "./envelope-Cf56AJLa.js";
|
|
3
|
+
import { c as readConsoleCredential, n as consoleOrigin } from "./console-auth-xl7kLQNt.js";
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { mkdtemp, open, rename, rm } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
//#region src/setup/console-env.ts
|
|
9
|
+
const pullUsage = "vitehub env pull --from console [--stage <name>] [--project <id>] [--console <url>] [--yes] [--json]";
|
|
10
|
+
const stagePattern = /^[a-z0-9][a-z0-9_-]{0,62}$/;
|
|
11
|
+
/** One line of a `.env` file. A value that a parser could read in two ways goes in quotes. */
|
|
12
|
+
function dotenvLine(name, value) {
|
|
13
|
+
if (/^[\w./:@+,-]*$/.test(value)) return `${name}=${value}`;
|
|
14
|
+
const escaped = value.replace(/\$/g, "\\$");
|
|
15
|
+
const quote = [
|
|
16
|
+
"'",
|
|
17
|
+
"`",
|
|
18
|
+
"\""
|
|
19
|
+
].find((candidate) => !value.includes(candidate) && (candidate !== "\"" || !/\\[nr]/.test(value)));
|
|
20
|
+
if (!quote || value.includes("\r")) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Cannot represent ${name} faithfully in a dotenv file. Use a value without carriage returns and with an available dotenv quote delimiter.` });
|
|
21
|
+
return `${name}=${quote}${escaped}${quote}`;
|
|
22
|
+
}
|
|
23
|
+
/** Run git in `cwd`. `undefined` when git is missing. */
|
|
24
|
+
function git(cwd, args) {
|
|
25
|
+
return new Promise((resolve) => {
|
|
26
|
+
execFile("git", args, {
|
|
27
|
+
cwd,
|
|
28
|
+
env: {
|
|
29
|
+
...process.env,
|
|
30
|
+
LC_ALL: "C"
|
|
31
|
+
}
|
|
32
|
+
}, (error) => {
|
|
33
|
+
if (!error) return resolve(0);
|
|
34
|
+
const code = Reflect.get(error, "code");
|
|
35
|
+
resolve(typeof code === "number" ? code : void 0);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Git must not commit the file. In a repository, the file must be ignored and not tracked. Outside a repository, there is
|
|
41
|
+
* nothing to commit it to.
|
|
42
|
+
*/
|
|
43
|
+
async function checkIgnored(cwd, file) {
|
|
44
|
+
if (await git(cwd, ["rev-parse", "--is-inside-work-tree"]) !== 0) return;
|
|
45
|
+
if (await git(cwd, [
|
|
46
|
+
"ls-files",
|
|
47
|
+
"--error-unmatch",
|
|
48
|
+
"--",
|
|
49
|
+
file
|
|
50
|
+
]) === 0) throw cliErrorDiagnostics.CLI_ENV_FILE_NOT_IGNORED({
|
|
51
|
+
file,
|
|
52
|
+
tracked: true
|
|
53
|
+
});
|
|
54
|
+
if (await git(cwd, [
|
|
55
|
+
"check-ignore",
|
|
56
|
+
"-q",
|
|
57
|
+
"--no-index",
|
|
58
|
+
"--",
|
|
59
|
+
file
|
|
60
|
+
]) !== 0) throw cliErrorDiagnostics.CLI_ENV_FILE_NOT_IGNORED({
|
|
61
|
+
file,
|
|
62
|
+
tracked: false
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
function readPullArgs(args) {
|
|
66
|
+
try {
|
|
67
|
+
return parseArgs({
|
|
68
|
+
args,
|
|
69
|
+
options: {
|
|
70
|
+
console: { type: "string" },
|
|
71
|
+
from: { type: "string" },
|
|
72
|
+
help: {
|
|
73
|
+
default: false,
|
|
74
|
+
short: "h",
|
|
75
|
+
type: "boolean"
|
|
76
|
+
},
|
|
77
|
+
json: {
|
|
78
|
+
default: false,
|
|
79
|
+
type: "boolean"
|
|
80
|
+
},
|
|
81
|
+
project: { type: "string" },
|
|
82
|
+
stage: {
|
|
83
|
+
default: "production",
|
|
84
|
+
type: "string"
|
|
85
|
+
},
|
|
86
|
+
yes: {
|
|
87
|
+
default: false,
|
|
88
|
+
short: "y",
|
|
89
|
+
type: "boolean"
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
strict: true
|
|
93
|
+
}).values;
|
|
94
|
+
} catch (error) {
|
|
95
|
+
throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${pullUsage}` });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async function readJson(response) {
|
|
99
|
+
const body = await response.json().catch(() => ({}));
|
|
100
|
+
return body instanceof Object ? body : {};
|
|
101
|
+
}
|
|
102
|
+
function consoleFailure(origin, path, status, body) {
|
|
103
|
+
const why = typeof body.message === "string" ? body.message : `${origin} answered ${status} to ${path}.`;
|
|
104
|
+
const message = typeof body.fix === "string" ? `${why} ${body.fix}` : why;
|
|
105
|
+
return cliErrorDiagnostics.CLI_ENV_PULL_FAILED({
|
|
106
|
+
code: typeof body.code === "string" ? body.code : String(status),
|
|
107
|
+
message
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* `vitehub env pull --from console`: write the values of one stage of a project from a self-hosted Console to
|
|
112
|
+
* `.env.<stage>`, with mode 600. It refuses to replace a file without `--yes`, and refuses a file that git would commit.
|
|
113
|
+
*/
|
|
114
|
+
const envPullFeature = {
|
|
115
|
+
description: "Write the env values of a stage from a self-hosted Console to .env.<stage>. Needs `vitehub login` and the owner or admin role.",
|
|
116
|
+
name: "pull",
|
|
117
|
+
usage: pullUsage,
|
|
118
|
+
run: async (args, context) => {
|
|
119
|
+
const json = args.includes("--json");
|
|
120
|
+
try {
|
|
121
|
+
const values = readPullArgs(args);
|
|
122
|
+
if (values.help) {
|
|
123
|
+
context.stdout.write(`Usage: ${pullUsage}\n\n${envPullFeature.description}\n`);
|
|
124
|
+
return 0;
|
|
125
|
+
}
|
|
126
|
+
if (values.from !== "console") throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] env pull reads values from a Console: pass --from console. Usage: ${pullUsage}` });
|
|
127
|
+
if (!stagePattern.test(values.stage)) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --stage is lowercase letters, digits, "-", and "_", such as production. Got ${JSON.stringify(values.stage)}.` });
|
|
128
|
+
const file = `.env.${values.stage}`;
|
|
129
|
+
const target = join(context.cwd, file);
|
|
130
|
+
await checkIgnored(context.cwd, file);
|
|
131
|
+
const credential = await readConsoleCredential(context.env, values.console);
|
|
132
|
+
if (!credential) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: consoleOrigin(values.console ?? context.env["VITEHUB_CONSOLE_URL"] ?? "https://console.vitehub.dev") });
|
|
133
|
+
const request = async (path, init = {}) => {
|
|
134
|
+
const response = await (context.fetch ?? fetch)(`${credential.origin}${path}`, {
|
|
135
|
+
...init,
|
|
136
|
+
headers: {
|
|
137
|
+
accept: "application/json",
|
|
138
|
+
authorization: `Bearer ${credential.token}`,
|
|
139
|
+
...init.body ? { "content-type": "application/json" } : {}
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
if (response.status === 401) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: credential.origin });
|
|
143
|
+
const body = await readJson(response);
|
|
144
|
+
if (!response.ok) throw consoleFailure(credential.origin, path, response.status, body);
|
|
145
|
+
return body;
|
|
146
|
+
};
|
|
147
|
+
let project = values.project;
|
|
148
|
+
if (!project) {
|
|
149
|
+
const listed = await request("/api/projects");
|
|
150
|
+
const projects = Array.isArray(listed.projects) ? listed.projects : [];
|
|
151
|
+
if (projects.length !== 1) {
|
|
152
|
+
const choices = projects.map((item) => `${item.id} (${item.url})`).join(", ");
|
|
153
|
+
throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] The key opens ${projects.length} projects. Pass --project <id>${choices ? `: ${choices}` : ""}.` });
|
|
154
|
+
}
|
|
155
|
+
project = projects[0].id;
|
|
156
|
+
}
|
|
157
|
+
const answer = await request(`/api/projects/${encodeURIComponent(project)}/env/${values.stage}/reveal`, {
|
|
158
|
+
body: "{}",
|
|
159
|
+
method: "POST"
|
|
160
|
+
});
|
|
161
|
+
const pulled = answer.values instanceof Object ? Object.entries(answer.values).filter((entry) => typeof entry[1] === "string") : [];
|
|
162
|
+
const text = `# Pulled from ${credential.origin}, project ${project}, stage ${values.stage}. Do not commit this file.\n${pulled.map(([name, value]) => dotenvLine(name, value)).join("\n")}\n`;
|
|
163
|
+
const temporary = values.yes ? await mkdtemp(join(context.cwd, ".vitehub-env-")) : void 0;
|
|
164
|
+
try {
|
|
165
|
+
const destination = temporary ? join(temporary, "values") : target;
|
|
166
|
+
const handle = await open(destination, "wx", 384).catch((error) => {
|
|
167
|
+
if (error instanceof Error && Reflect.get(error, "code") === "EEXIST") throw cliErrorDiagnostics.CLI_ENV_FILE_EXISTS({ file });
|
|
168
|
+
throw error;
|
|
169
|
+
});
|
|
170
|
+
try {
|
|
171
|
+
await handle.writeFile(text);
|
|
172
|
+
} finally {
|
|
173
|
+
await handle.close();
|
|
174
|
+
}
|
|
175
|
+
if (temporary) await rename(destination, target);
|
|
176
|
+
} finally {
|
|
177
|
+
if (temporary) await rm(temporary, {
|
|
178
|
+
recursive: true,
|
|
179
|
+
force: true
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
const names = pulled.map(([name]) => name);
|
|
183
|
+
if (json) writeSetupJson(context, {
|
|
184
|
+
console: credential.origin,
|
|
185
|
+
file,
|
|
186
|
+
names,
|
|
187
|
+
project,
|
|
188
|
+
stage: values.stage
|
|
189
|
+
});
|
|
190
|
+
else context.stdout.write(`Wrote ${names.length} value${names.length === 1 ? "" : "s"} of ${values.stage} to ${file} (mode 600)${names.length ? `: ${names.join(", ")}` : ""}.\n`);
|
|
191
|
+
return 0;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
return writeSetupError(context, json, error);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
//#endregion
|
|
198
|
+
export { envPullFeature };
|