frontmost 0.0.0-stage → 0.6.2

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/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "frontmost",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.2",
4
+ "description": "See how AI apps answer your buyers' questions, from the terminal.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "frontmost": "bin/frontmost.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "openapi.json"
14
+ ],
15
+ "engines": {
16
+ "node": ">=22.12"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/frontmost-ai/cli.git"
21
+ },
22
+ "homepage": "https://frontmost.ai",
23
+ "bugs": "https://github.com/frontmost-ai/cli/issues",
24
+ "keywords": [
25
+ "frontmost",
26
+ "ai visibility",
27
+ "cli"
28
+ ],
29
+ "scripts": {
30
+ "test": "node --test \"test/*.test.js\"",
31
+ "typecheck": "tsc",
32
+ "check-spec": "node scripts/check-spec.js"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^22.0.0",
36
+ "typescript": "^5.9.0"
37
+ }
38
+ }
package/src/cli.js ADDED
@@ -0,0 +1,363 @@
1
+ // frontmost <command>: read the arguments, send one API request, print the reply.
2
+ import { createHash } from "node:crypto";
3
+ import { parseArgs } from "node:util";
4
+ import { apiKey, baseUrl, checkKey, KEYS_URL, projectSetting, readSignIn, removeKey, saveKey, saveSignIn } from "./config.js";
5
+ import { ApiError, UsageError } from "./errors.js";
6
+ import { commandHelp, firstWords, group, nearest, overview, usage } from "./help.js";
7
+ import { home, welcome } from "./home.js";
8
+ import { request } from "./http.js";
9
+ import { accessToken, openBrowser, signIn } from "./oauth.js";
10
+ import { clean, json, render } from "./output.js";
11
+ import { commands, GLOBALS, VERSION } from "./spec.js";
12
+ import { PLAIN, spinner, styleFor } from "./style.js";
13
+
14
+ const SETUP_LIMIT_MS = 10 * 60_000;
15
+ const METHODS = new Set(["GET", "POST", "PATCH", "PUT", "DELETE"]);
16
+
17
+ /**
18
+ * Everything the CLI touches outside itself. Tests replace it.
19
+ * @typedef {object} Io
20
+ * @property {import("./config.js").Env} env
21
+ * @property {string} cwd
22
+ * @property {typeof fetch} fetch
23
+ * @property {(ms: number) => Promise<unknown>} sleep
24
+ * @property {(text: string) => void} out Results. Goes to stdout.
25
+ * @property {(text: string) => void} note Progress and errors. Goes to stderr.
26
+ * @property {() => Promise<string>} readStdin
27
+ * @property {() => Promise<string>} readSecret
28
+ * @property {(url: string) => Promise<boolean>} open Opens a page in the browser. False when no browser can open.
29
+ * @property {boolean} tty True when stdout is a terminal.
30
+ * @property {number} [width]
31
+ * @property {import("./style.js").Style} [style] For stdout. Plain when it is not a terminal.
32
+ * @property {import("./style.js").Style} [noteStyle] For stderr.
33
+ */
34
+
35
+ /** @param {boolean} quiet No moving dots, for --json. @returns {Io} */
36
+ function realIo(quiet) {
37
+ const { stdin, stdout, stderr, env } = process;
38
+ const noteStyle = styleFor(stderr, env);
39
+ const spin = !quiet && stderr.isTTY && env.TERM !== "dumb" ? spinner(stderr, noteStyle) : null;
40
+ const readStdin = async () => {
41
+ let text = "";
42
+ for await (const chunk of stdin) text += chunk;
43
+ return text;
44
+ };
45
+ return {
46
+ env,
47
+ cwd: process.cwd(),
48
+ fetch: spin ? (url, init) => spin.around(fetch(url, init)) : fetch,
49
+ sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
50
+ out: (text) => (spin?.clear(), stdout.write(`${text}\n`)),
51
+ note: (text) => (spin?.clear(), stderr.write(`${text}\n`)),
52
+ readStdin,
53
+ readSecret: () => (stdin.isTTY ? promptSecret() : readStdin()),
54
+ open: openBrowser,
55
+ tty: Boolean(stdout.isTTY),
56
+ width: stdout.columns,
57
+ style: styleFor(stdout, env),
58
+ noteStyle,
59
+ };
60
+ }
61
+
62
+ /** Ask for the key without showing it on the screen. @returns {Promise<string>} */
63
+ function promptSecret() {
64
+ const { stdin, stderr } = process;
65
+ stderr.write(`Paste an API key from ${KEYS_URL}: `);
66
+ stdin.setRawMode(true);
67
+ stdin.resume();
68
+ return new Promise((resolve, reject) => {
69
+ let text = "";
70
+ /** @param {() => void} then */
71
+ const stop = (then) => {
72
+ stdin.setRawMode(false);
73
+ stdin.pause();
74
+ stdin.off("data", onData);
75
+ stderr.write("\n");
76
+ then();
77
+ };
78
+ /** @param {Buffer} chunk */
79
+ const onData = (chunk) => {
80
+ for (const ch of chunk.toString("utf8")) {
81
+ if (ch === "\r" || ch === "\n") return stop(() => resolve(text));
82
+ if (ch === "\u0003" || ch === "\u0004") return stop(() => reject(new UsageError("Stopped. No key was saved.")));
83
+ text = ch === "\u007f" ? text.slice(0, -1) : text + ch;
84
+ }
85
+ };
86
+ stdin.on("data", onData);
87
+ });
88
+ }
89
+
90
+ /** One parser for all commands, so flags can go before or after the command words. */
91
+ const OPTIONS = /** @type {Record<string, { type: "string" | "boolean", short?: string }>} */ ({});
92
+ for (const c of commands.values()) for (const f of c.flags.values()) OPTIONS[f.name] = { type: f.type === "boolean" ? "boolean" : "string" };
93
+ for (const [name, g] of Object.entries(GLOBALS)) OPTIONS[name] = { type: g.type, ...("short" in g ? { short: g.short } : {}) };
94
+
95
+ /** @param {string[]} argv */
96
+ function parse(argv) {
97
+ try {
98
+ return parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, allowNegative: true, strict: true });
99
+ } catch (e) {
100
+ const unknown = e instanceof Error && /^Unknown option '--([^']+)'/.exec(e.message)?.[1];
101
+ const close = unknown && nearest(unknown.replace(/^no-/, ""), Object.keys(OPTIONS));
102
+ if (unknown) throw new UsageError(`--${unknown} is not an option.${close ? ` Did you mean --${close}?` : ""} Run "frontmost --help" to see the commands.`);
103
+ const reason = e instanceof Error ? e.message.split(". ")[0].replace(/\.$/, "") : "Wrong arguments";
104
+ throw new UsageError(`${reason}. Run "frontmost --help" to see the commands.`);
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Run the CLI. Returns the exit code: 0 success, 1 API or network error, 2 wrong command.
110
+ * @param {string[]} argv @param {Io} [io]
111
+ */
112
+ export async function run(argv, io = realIo(argv.includes("--json"))) {
113
+ try {
114
+ await main(argv, io);
115
+ return 0;
116
+ } catch (e) {
117
+ if (!(e instanceof ApiError || e instanceof UsageError)) throw e;
118
+ const wrongCommand = e instanceof UsageError;
119
+ if (argv.includes("--json")) {
120
+ const body = e instanceof ApiError && e.body ? e.body : { error: { code: wrongCommand ? "usage" : "network", message: e.message } };
121
+ io.note(json(body));
122
+ } else {
123
+ const s = io.noteStyle ?? PLAIN;
124
+ // On a terminal, the commands in a message stand out: Run "frontmost login" shows frontmost login in bold.
125
+ const message = s.on ? clean(e.message).replace(/"(frontmost [^"]+)"/g, (_, c) => s.bold(c)) : clean(e.message);
126
+ io.note(`${s.errorDot()} ${message}`);
127
+ if (e instanceof ApiError && e.code) io.note(s.dim(clean(`Code: ${e.code}${e.requestId ? `. Request ID: ${e.requestId}` : ""}`)));
128
+ }
129
+ return wrongCommand ? 2 : 1;
130
+ }
131
+ }
132
+
133
+ /** @param {string[]} argv @param {Io} io */
134
+ async function main(argv, io) {
135
+ const { values, positionals } = parse(argv);
136
+ if (values.version) return io.out(VERSION);
137
+ if (positionals[0] === "help") {
138
+ positionals.shift();
139
+ values.help = true;
140
+ }
141
+ const s = io.style ?? PLAIN;
142
+ if (!positionals.length) return values.help ? io.out(overview(s)) : start(values, io);
143
+
144
+ const two = positionals.slice(0, 2).join(" ");
145
+ const name = commandHelp(two) !== null && positionals.length > 1 ? two : positionals[0];
146
+ const args = positionals.slice(name === two ? 2 : 1);
147
+ const help = commandHelp(name, s);
148
+ if (help === null) {
149
+ const choices = group(name);
150
+ if (choices && values.help) return io.out(group(name, s) ?? choices);
151
+ if (choices) throw new UsageError(`"frontmost ${name}" needs one more word:\n${choices}`);
152
+ const close = nearest(name, firstWords());
153
+ throw new UsageError(`"${name}" is not a command. ${close ? `Did you mean "frontmost ${close}"?` : 'Run "frontmost --help" to see the commands.'}`);
154
+ }
155
+ if (values.help) return io.out(help);
156
+
157
+ if (name === "logout") return logout(io);
158
+ if (name === "login") return login(values, io);
159
+ const client = signedIn(values, io);
160
+ if (!client) throw new UsageError('Not signed in. Run "frontmost login", or set FRONTMOST_API_KEY.');
161
+ if (name === "api") return api(client, args, values, io);
162
+ return execute(client, /** @type {import("./spec.js").Command} */ (commands.get(name)), args, values, io);
163
+ }
164
+
165
+ /** The API client, or null when nothing is signed in. @param {Record<string, unknown>} values @param {Io} io */
166
+ function signedIn(values, io) {
167
+ const key = apiKey({ flag: str(values["api-key"]), ...io });
168
+ if (!key && !readSignIn(io.env)) return null;
169
+ const base = baseUrl(io.env);
170
+ return { base, token: key ? async () => key : accessToken(io, base), fetch: io.fetch, sleep: io.sleep };
171
+ }
172
+
173
+ /**
174
+ * "frontmost" alone. A person at a terminal sees the latest scan, or a welcome before the first sign-in.
175
+ * A script or an agent gets the help, as before.
176
+ * @param {Record<string, unknown>} values @param {Io} io
177
+ */
178
+ async function start(values, io) {
179
+ const s = io.style ?? PLAIN;
180
+ if (!io.tty || values.json) return io.out(overview(s));
181
+ const client = signedIn(values, io);
182
+ io.out(client ? await home(client, { ...io, project: str(values.project) }, s) : welcome(s));
183
+ }
184
+
185
+ /** @param {unknown} v */
186
+ const str = (v) => (typeof v === "string" ? v : undefined);
187
+
188
+ /** @param {Record<string, unknown>} values @param {Io} io */
189
+ async function login(values, io) {
190
+ const base = baseUrl(io.env);
191
+ /** The sign-in is saved only after the API accepts it. @param {string} token */
192
+ const workspace = async (token) => (await request({ base, token: async () => token, fetch: io.fetch, sleep: io.sleep }, "GET", "/workspace")).body.name;
193
+
194
+ const flag = str(values["api-key"]);
195
+ if (flag || values["with-key"]) {
196
+ const key = checkKey((flag ?? (await io.readSecret())).trim());
197
+ const name = await workspace(key);
198
+ return signedInNote(io, name, `Key saved to ${saveKey(io.env, key)}.`);
199
+ }
200
+ const saved = await signIn(io, base, { browser: values.browser !== false });
201
+ const name = await workspace(saved.access_token);
202
+ signedInNote(io, name, `Sign-in saved to ${saveSignIn(io.env, saved)}.`);
203
+ }
204
+
205
+ /** @param {Io} io @param {unknown} name @param {string} saved */
206
+ function signedInNote(io, name, saved) {
207
+ const s = io.noteStyle ?? PLAIN;
208
+ if (!s.on) return io.note(clean(`Signed in to ${name}. ${saved}`));
209
+ io.note(`Signed in to ${s.bold(clean(name))}. ${s.dim(clean(saved))}\nRun ${s.bold("frontmost")} to see the latest scan.`);
210
+ }
211
+
212
+ /** @param {Io} io */
213
+ async function logout(io) {
214
+ const removed = removeKey(io.env);
215
+ io.note(removed ? `Signed out. Removed ${removed}.` : "No sign-in is saved on this computer.");
216
+ }
217
+
218
+ /** @param {string | undefined} raw @param {Io} io */
219
+ async function readBody(raw, io) {
220
+ if (raw === undefined) return {};
221
+ try {
222
+ const body = JSON.parse(raw === "-" ? await io.readStdin() : raw);
223
+ if (typeof body === "object" && body !== null && !Array.isArray(body)) return body;
224
+ } catch {
225
+ // Reported below.
226
+ }
227
+ throw new UsageError('--body must be a JSON object, for example --body \'{"name":"Acme"}\'.');
228
+ }
229
+
230
+ /** @param {import("./http.js").Client} client @param {string[]} args @param {Record<string, unknown>} values @param {Io} io */
231
+ async function api(client, args, values, io) {
232
+ const [method, full] = args.length === 1 ? ["GET", args[0]] : [args[0]?.toUpperCase(), args[1]];
233
+ // Docs show the full address, so a pasted "/api/v1/projects" works too.
234
+ const path = full?.replace(/^\/api\/v1(?=[/?]|$)/, "") || "/";
235
+ if (args.length > 2 || !METHODS.has(method) || !full?.startsWith("/")) throw new UsageError('Use: frontmost api [METHOD] <path>. The path starts with /, for example "/projects?limit=5".');
236
+ const key = str(values["idempotency-key"]);
237
+ const body = values.body === undefined ? undefined : await readBody(str(values.body), io);
238
+ const reply = await request(client, method, path, { body, headers: key ? { "Idempotency-Key": key } : {} });
239
+ if (reply.body !== null) io.out(json(reply.body));
240
+ }
241
+
242
+ /**
243
+ * The value to send for one flag. Wrong values stop here, before any request.
244
+ * @param {import("./spec.js").Flag} flag @param {string | boolean} value
245
+ */
246
+ function convert(flag, value) {
247
+ const query = flag.in === "query";
248
+ if (flag.type === "boolean") return query ? String(value) : value;
249
+ if (flag.type === "integer") {
250
+ if (!/^\d+$/.test(String(value))) throw new UsageError(`--${flag.name} must be a whole number.`);
251
+ return query ? value : Number(value);
252
+ }
253
+ if (flag.type === "list") {
254
+ const items = String(value).split(",").map((v) => v.trim()).filter(Boolean);
255
+ const wrong = flag.enum && items.find((v) => !flag.enum?.includes(v));
256
+ if (!items.length || wrong) throw new UsageError(`--${flag.name} takes a comma-separated list${flag.enum ? ` of: ${flag.enum.join(", ")}` : ""}.`);
257
+ return items;
258
+ }
259
+ if (flag.enum && !flag.enum.includes(String(value))) throw new UsageError(`--${flag.name} must be one of: ${flag.enum.join(", ")}.`);
260
+ return value === "" && flag.nullable && !query ? null : value;
261
+ }
262
+
263
+ /** The project to use when a command needs one. @param {import("./http.js").Client} client @param {Record<string, unknown>} values @param {Io} io */
264
+ async function projectId(client, values, io) {
265
+ const set = projectSetting({ flag: str(values.project), ...io });
266
+ if (set) return set;
267
+ const { body } = await request(client, "GET", "/projects", { query: { limit: "2" } });
268
+ if (body.data.length === 1) return String(body.data[0].id);
269
+ throw new UsageError(
270
+ body.data.length
271
+ ? 'This workspace has more than one project. Run "frontmost projects" to see the IDs, then add --project <id> or set FRONTMOST_PROJECT.'
272
+ : 'This workspace has no project yet. Create one with "frontmost projects create <domain>".',
273
+ );
274
+ }
275
+
276
+ /**
277
+ * @param {import("./http.js").Client} client @param {import("./spec.js").Command} cmd
278
+ * @param {string[]} args @param {Record<string, any>} values @param {Io} io
279
+ */
280
+ async function execute(client, cmd, args, values, io) {
281
+ const wrong = (/** @type {string} */ why) => new UsageError(`${why}\nUse: frontmost ${usage(cmd)}\nRun "frontmost ${cmd.name} --help" to see the options.`);
282
+ const rest = [...args];
283
+
284
+ // Flags
285
+ /** @type {Record<string, string>} */ const query = {};
286
+ /** @type {Record<string, unknown>} */ const item = {};
287
+ if (values.body !== undefined && !cmd.hasBody) throw wrong("This command sends no body, so --body does not apply.");
288
+ if (values.all && !cmd.isList) throw wrong("--all works only on lists.");
289
+ const body = cmd.hasBody ? await readBody(values.body, io) : undefined;
290
+ for (const [name, value] of Object.entries(values)) {
291
+ if (name in GLOBALS) continue;
292
+ const flag = cmd.flags.get(name);
293
+ if (!flag) {
294
+ const close = nearest(name, [...cmd.flags.keys()]);
295
+ throw wrong(`--${name} is not an option of this command.${close ? ` Did you mean --${close}?` : ""}`);
296
+ }
297
+ const top = /** @type {Record<string, any>} */ (body);
298
+ const target = flag.in === "query" ? query : flag.in === "item" ? item : flag.parent ? (top[flag.parent] ??= {}) : body;
299
+ /** @type {Record<string, unknown>} */ (target)[flag.key] = convert(flag, value);
300
+ }
301
+
302
+ // Arguments
303
+ /** @type {Record<string, string>} */ const ids = {};
304
+ for (const arg of cmd.args) {
305
+ const value = rest.shift();
306
+ if (value === undefined) throw wrong(`Missing <${arg.replaceAll("_", "-")}>.`);
307
+ ids[arg] = value;
308
+ }
309
+ const named = cmd.path === "/projects/{id}" ? rest.shift() : undefined;
310
+ if (body && cmd.positional && rest.length) {
311
+ const { field, list } = cmd.positional;
312
+ if (list) body[list] = rest.splice(0).map((text) => ({ [field]: text, ...item }));
313
+ else body[field] = rest.shift();
314
+ }
315
+ if (rest.length) {
316
+ const choices = group(cmd.name);
317
+ throw choices ? new UsageError(`"frontmost ${cmd.name} ${rest[0]}" is not a command. The commands are:\n${choices}`) : wrong(`"${rest[0]}" is one argument too many.`);
318
+ }
319
+ if (body) {
320
+ Object.assign(body, cmd.preset);
321
+ const missing = cmd.required.filter((k) => !(k in body));
322
+ if (missing.length) throw wrong(`Missing ${missing.join(", ")}.`);
323
+ if (!Object.keys(body).length) throw wrong("Nothing to send. Add at least one option.");
324
+ }
325
+ // Last, because it can take a request: every other mistake is reported first.
326
+ if (cmd.inProject) ids.id = named ?? (await projectId(client, values, io));
327
+
328
+ const path = cmd.path.replace(/\{(\w+)\}/g, (_, param) => encodeURIComponent(ids[param]));
329
+ const headers = cmd.retryKey && body && !body.setup_id ? { "Idempotency-Key": str(values["idempotency-key"]) ?? createHash("sha256").update(JSON.stringify(body)).digest("hex") } : undefined;
330
+ if (values.all) query.limit ??= "100";
331
+ let reply = await request(client, cmd.method, path, { query, body, headers });
332
+
333
+ // A project setup takes a few minutes. The API says when to ask again.
334
+ const deadline = Date.now() + SETUP_LIMIT_MS;
335
+ let waited = false;
336
+ while (reply.status === 202 && values.wait !== false) {
337
+ const setup = reply.body;
338
+ const again = `frontmost projects create --setup-id ${setup.id}`;
339
+ if (Date.now() >= deadline) throw new ApiError(`The setup is still running. Run "${again}" in a few minutes to get the project.`);
340
+ if (!waited) io.note(clean(`Setting up ${setup.domain}. This takes a few minutes. If you stop now, continue with "${again}".`));
341
+ waited = true;
342
+ await io.sleep((Number(setup.retry_after) || 30) * 1000);
343
+ reply = await request(client, cmd.method, path, { body: setup.next?.body ?? { setup_id: setup.id } });
344
+ }
345
+
346
+ while (values.all && reply.body.has_more) {
347
+ const next = await request(client, cmd.method, path, { query: { ...query, cursor: reply.body.next_cursor } });
348
+ next.body.data.unshift(...reply.body.data);
349
+ reply = next;
350
+ }
351
+ show(reply.body, values.json, io);
352
+ }
353
+
354
+ /** @param {any} body @param {boolean} asJson @param {Io} io */
355
+ function show(body, asJson, io) {
356
+ if (body === null) return asJson ? undefined : io.note("Done.");
357
+ if (asJson) return io.out(json(body));
358
+ const text = render(body, io);
359
+ if (text) io.out(text);
360
+ if (body.message) io.note(clean(body.message));
361
+ else if (!text) io.note("No results.");
362
+ if (body.has_more) io.note(`More results. Add --all, or --cursor ${clean(body.next_cursor)} for the next page.`);
363
+ }
package/src/config.js ADDED
@@ -0,0 +1,114 @@
1
+ // Where the sign-in, the API key, and the project ID come from.
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { UsageError } from "./errors.js";
6
+ import { spec } from "./spec.js";
7
+
8
+ export const KEYS_URL = "https://app.frontmost.ai/team";
9
+ const KEY_SHAPE = /^fmk_[0-9A-Za-z]{32}$/;
10
+ const LOCAL = new Set(["localhost", "127.0.0.1", "[::1]"]);
11
+
12
+ /** @typedef {Record<string, string | undefined>} Env */
13
+
14
+ /** @param {Env} env */
15
+ export const configPath = (env) => join(env.XDG_CONFIG_HOME || join(env.HOME || homedir(), ".config"), "frontmost", "config.json");
16
+
17
+ /**
18
+ * A browser sign-in. Access lasts minutes. The refresh token gets the next access.
19
+ * @typedef {{ access_token: string, refresh_token?: string, expires_at: number, token_endpoint: string }} SignIn
20
+ */
21
+
22
+ /** @param {Env} env @returns {{ api_key?: string, sign_in?: SignIn }} */
23
+ function readConfig(env) {
24
+ try {
25
+ return JSON.parse(readFileSync(configPath(env), "utf8"));
26
+ } catch {
27
+ return {};
28
+ }
29
+ }
30
+
31
+ /** Save one way to sign in, so that only this user can read it. @param {Env} env @param {{ api_key: string } | { sign_in: SignIn }} saved */
32
+ function save(env, saved) {
33
+ const file = configPath(env);
34
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
35
+ writeFileSync(file, `${JSON.stringify(saved, null, 2)}\n`, { mode: 0o600 });
36
+ chmodSync(file, 0o600);
37
+ return file;
38
+ }
39
+
40
+ /** @param {Env} env @param {string} key */
41
+ export const saveKey = (env, key) => save(env, { api_key: key });
42
+ /** @param {Env} env @param {SignIn} signIn */
43
+ export const saveSignIn = (env, signIn) => save(env, { sign_in: signIn });
44
+
45
+ /** The saved browser sign-in, when the file holds a usable one. @param {Env} env @returns {SignIn | undefined} */
46
+ export function readSignIn(env) {
47
+ const s = readConfig(env).sign_in;
48
+ const usable = s && typeof s.access_token === "string" && typeof s.expires_at === "number" && typeof s.token_endpoint === "string" && safeUrl(s.token_endpoint);
49
+ return usable ? s : undefined;
50
+ }
51
+
52
+ /** Remove the saved key or sign-in. @param {Env} env @returns {string | null} The file removed, or null when none was saved. */
53
+ export function removeKey(env) {
54
+ if (!existsSync(configPath(env))) return null;
55
+ rmSync(configPath(env), { force: true });
56
+ return configPath(env);
57
+ }
58
+
59
+ /**
60
+ * FRONTMOST_API_KEY and FRONTMOST_PROJECT from ./.env. No other name is read.
61
+ * @param {string} cwd @returns {Env}
62
+ */
63
+ function dotEnv(cwd) {
64
+ let text;
65
+ try {
66
+ text = readFileSync(join(cwd, ".env"), "utf8");
67
+ } catch {
68
+ return {};
69
+ }
70
+ /** @type {Env} */
71
+ const out = {};
72
+ for (const line of text.split(/\r?\n/)) {
73
+ const m = /^\s*(?:export\s+)?(FRONTMOST_API_KEY|FRONTMOST_PROJECT)\s*=\s*(.*?)\s*$/.exec(line);
74
+ if (m) out[m[1]] = m[2].replace(/^(["'])(.*)\1$/, "$2");
75
+ }
76
+ return out;
77
+ }
78
+
79
+ /** @param {string} key */
80
+ export function checkKey(key) {
81
+ if (!KEY_SHAPE.test(key)) throw new UsageError("That is not a Frontmost API key. A key starts with fmk_ and has 36 characters.");
82
+ return key;
83
+ }
84
+
85
+ /**
86
+ * The first API key found: --api-key, the environment, ./.env, then the saved key. Undefined when there is none.
87
+ * @param {{ flag?: string, env: Env, cwd: string }} from
88
+ */
89
+ export function apiKey({ flag, env, cwd }) {
90
+ const key = flag || env.FRONTMOST_API_KEY || dotEnv(cwd).FRONTMOST_API_KEY || readConfig(env).api_key;
91
+ return key ? checkKey(key) : undefined;
92
+ }
93
+
94
+ /** The project ID from --project, the environment, or ./.env. @param {{ flag?: string, env: Env, cwd: string }} from */
95
+ export const projectSetting = ({ flag, env, cwd }) => flag || env.FRONTMOST_PROJECT || dotEnv(cwd).FRONTMOST_PROJECT;
96
+
97
+ /** True for an https address, or an http address on this computer. @param {string} raw */
98
+ export function safeUrl(raw) {
99
+ let url;
100
+ try {
101
+ url = new URL(raw);
102
+ } catch {
103
+ return false;
104
+ }
105
+ return (url.protocol === "https:" || (url.protocol === "http:" && LOCAL.has(url.hostname))) && !url.username && !url.password;
106
+ }
107
+
108
+ /** The API address. Only the real environment can change it, and only to https or this computer. @param {Env} env */
109
+ export function baseUrl(env) {
110
+ const raw = env.FRONTMOST_API_URL || spec.servers[0].url;
111
+ if (!URL.canParse(raw)) throw new UsageError("FRONTMOST_API_URL is not a URL.");
112
+ if (!safeUrl(raw)) throw new UsageError("FRONTMOST_API_URL must start with https://.");
113
+ return raw.replace(/\/+$/, "");
114
+ }
package/src/errors.js ADDED
@@ -0,0 +1,13 @@
1
+ /** A wrong command, flag, or setting. Exit code 2. No request was sent. */
2
+ export class UsageError extends Error {}
3
+
4
+ /** The API refused the request, or the network failed. Exit code 1. */
5
+ export class ApiError extends Error {
6
+ /** @param {string} message @param {{ code?: string, request_id?: string, body?: unknown }} [info] */
7
+ constructor(message, info = {}) {
8
+ super(message);
9
+ this.code = info.code;
10
+ this.requestId = info.request_id;
11
+ this.body = info.body;
12
+ }
13
+ }
package/src/help.js ADDED
@@ -0,0 +1,140 @@
1
+ // Help text, made from the same command list that runs the commands.
2
+ import { KEYS_URL } from "./config.js";
3
+ import { commands, GLOBALS } from "./spec.js";
4
+ import { PLAIN } from "./style.js";
5
+
6
+ const DOCS_URL = "https://app.frontmost.ai/docs/api.md";
7
+
8
+ const ACCOUNT = /** @type {Record<string, { usage: string, summary: string, more?: string }>} */ ({
9
+ login: {
10
+ usage: "login",
11
+ summary: "Sign in with your browser",
12
+ more: `Your browser opens. Sign in there, and the CLI is ready. The sign-in stays on this computer until "frontmost logout".
13
+
14
+ Options
15
+ --no-browser Sign in with a code. For a computer with no browser, such as one that you reach over SSH
16
+ --with-key Save an API key in place of a browser sign-in. Paste the key when asked, or pipe it in
17
+ Create a key at ${KEYS_URL}`,
18
+ },
19
+ logout: { usage: "logout", summary: "Sign out on this computer" },
20
+ api: {
21
+ usage: "api [METHOD] <path>",
22
+ summary: "Call any API route",
23
+ more: 'The method is GET when you leave it out. The output is always JSON.\nThe path is the part after /api/v1. Add --body \'<json>\' to send data.\nExample: frontmost api "/projects?limit=5"',
24
+ },
25
+ });
26
+
27
+ /** @param {import("./spec.js").Command} c */
28
+ export function usage(c) {
29
+ const ownProject = c.path === "/projects/{id}";
30
+ const parts = [c.name, ...c.args.map((a) => `<${a.replaceAll("_", "-")}>`), ownProject ? "[project-id]" : "", c.positional?.label ?? ""];
31
+ return parts.filter(Boolean).join(" ");
32
+ }
33
+
34
+ /** @param {[string, string][]} rows @param {import("./style.js").Style} [s] @param {number} [pad] The width of the left column. */
35
+ function columns(rows, s = PLAIN, pad = Math.max(...rows.map(([left]) => left.length))) {
36
+ return rows.map(([left, right]) => (right ? ` ${left.padEnd(pad)} ${s.dim(right)}` : ` ${left}`)).join("\n");
37
+ }
38
+
39
+ /** @param {string[]} names @returns {[string, string][]} */
40
+ const globalRows = (names) => names.map((n) => [n === "wait" ? "--no-wait" : `--${n}${GLOBALS[/** @type {keyof typeof GLOBALS} */ (n)].type === "string" ? " <value>" : ""}`, GLOBALS[/** @type {keyof typeof GLOBALS} */ (n)].description]);
41
+ /** @param {string[]} names @param {import("./style.js").Style} [s] */
42
+ const globals = (names, s = PLAIN) => columns(globalRows(names), s);
43
+
44
+ /** @param {import("./style.js").Style} [s] On a terminal: the logo, bold headings, and gray descriptions. */
45
+ export function overview(s = PLAIN) {
46
+ const all = [...commands.values()];
47
+ const nouns = [...new Set(all.map((c) => c.name.split(" ")[0]))];
48
+ /** @param {import("./spec.js").Command} c */
49
+ const order = (c) => nouns.indexOf(c.name.split(" ")[0]);
50
+ /** Commands of one noun stay together. @param {(c: import("./spec.js").Command) => boolean} keep @returns {[string, string][]} */
51
+ const rows = (keep) => all.filter(keep).sort((a, b) => order(a) - order(b)).map((c) => [usage(c), c.summary]);
52
+ /** @type {[string, string][]} */
53
+ const account = Object.values(ACCOUNT).map((a) => [a.usage, a.summary]);
54
+ const sections = { read: rows((c) => c.method === "GET"), change: rows((c) => c.method !== "GET"), account, options: globalRows(["json", "project", "all", "help", "version"]) };
55
+ // One left column for every section, so that all descriptions start at the same place.
56
+ const pad = Math.max(...Object.values(sections).flat().map(([left]) => left.length));
57
+ /** @param {[string, string][]} list */
58
+ const col = (list) => columns(list, s, pad);
59
+ const h = s.bold;
60
+ return `${s.on ? `${s.logo()} ` : ""}See how AI apps answer your buyers' questions.
61
+
62
+ ${h("Usage")}
63
+ frontmost <command> [options]
64
+
65
+ ${h("Read")}
66
+ ${col(sections.read)}
67
+
68
+ ${h("Change")}
69
+ ${col(sections.change)}
70
+
71
+ ${h("Account")}
72
+ ${col(sections.account)}
73
+
74
+ ${h("Options")}
75
+ ${col(sections.options)}
76
+
77
+ ${h("Sign in")}
78
+ Run "frontmost login". Your browser opens, and you sign in there.
79
+ For scripts and CI, create an API key at ${KEYS_URL} and set FRONTMOST_API_KEY.
80
+
81
+ ${h("AI agents and scripts")}
82
+ Add --json to every command. With no sign-in, ask the person to run "frontmost login".
83
+ Exit code 0 is success. 1 is an API or network error. 2 is a wrong command.
84
+ Run "frontmost <command> --help" to see the options of one command.
85
+ API reference: ${DOCS_URL}`;
86
+ }
87
+
88
+ /** @param {import("./spec.js").Flag} f */
89
+ function flagRow(f) {
90
+ const left = f.type === "boolean" ? `--${f.name}, --no-${f.name}` : `--${f.name} <${f.type === "list" ? `${f.enum ? f.enum.join("|") : "text"},...` : f.enum ? f.enum.join("|") : f.type === "integer" ? "number" : "text"}>`;
91
+ const notes = [f.description, f.default === undefined ? "" : `Default: ${f.default}`, f.nullable && f.in === "body" ? 'Use "" to clear it' : ""];
92
+ return /** @type {[string, string]} */ ([left, notes.filter(Boolean).join(". ")]);
93
+ }
94
+
95
+ /** Help for one command, or null when the name is not a command. @param {string} name @param {import("./style.js").Style} [s] */
96
+ export function commandHelp(name, s = PLAIN) {
97
+ const account = ACCOUNT[name];
98
+ if (account) return `${account.summary}\n\n${s.bold("Usage")}\n frontmost ${account.usage}${account.more ? `\n\n${account.more.replace(/^Options$/m, s.bold("Options"))}` : ""}`;
99
+ const c = commands.get(name);
100
+ if (!c) return null;
101
+ // A deprecated flag still works, so older scripts run, but help shows only the current options.
102
+ const own = [...c.flags.values()].filter((f) => !f.deprecated).map(flagRow);
103
+ const shared = ["json", c.inProject && "project", c.isList && "all", c.hasBody && "body", c.retryKey && "idempotency-key", c.retryKey && "wait", "api-key"];
104
+ return [
105
+ c.summary,
106
+ `${s.bold("Usage")}\n frontmost ${usage(c)}${own.length ? " [options]" : ""}`,
107
+ own.length ? `${s.bold("Options")}\n${columns(own, s)}` : "",
108
+ `${s.bold("Other options")}\n${globals(/** @type {string[]} */ (shared.filter(Boolean)), s)}`,
109
+ ].filter(Boolean).join("\n\n");
110
+ }
111
+
112
+ /** The commands that start with one word, for "frontmost profiles" when the word alone is not a command. @param {string} noun @param {import("./style.js").Style} [s] */
113
+ export function group(noun, s = PLAIN) {
114
+ const rows = [...commands.values()].filter((c) => c.name.startsWith(`${noun} `)).map((c) => /** @type {[string, string]} */ ([usage(c), c.summary]));
115
+ return rows.length ? columns(rows, s) : null;
116
+ }
117
+
118
+ /**
119
+ * The one choice that starts with the word, else the choice closest to it, or null when none is close.
120
+ * @param {string} word @param {Iterable<string>} choices
121
+ */
122
+ export function nearest(word, choices) {
123
+ /** @param {string} a @param {string} b */
124
+ const distance = (a, b) => {
125
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
126
+ for (let i = 1; i <= a.length; i++) {
127
+ const next = [i];
128
+ for (let j = 1; j <= b.length; j++) next[j] = Math.min(next[j - 1] + 1, row[j] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
129
+ row = next;
130
+ }
131
+ return row[b.length];
132
+ };
133
+ const starts = [...choices].filter((c) => c.startsWith(word));
134
+ if (starts.length === 1) return starts[0];
135
+ const [best] = [...choices].map((c) => /** @type {const} */ ([c, distance(word, c)])).sort((a, b) => a[1] - b[1]);
136
+ return best && best[1] <= Math.max(1, Math.floor(word.length / 3)) ? best[0] : null;
137
+ }
138
+
139
+ /** The first word of every command. */
140
+ export const firstWords = () => new Set([...Object.keys(ACCOUNT), ...[...commands.keys()].map((n) => n.split(" ")[0])]);