frontmost 0.0.0-stage → 0.6.1

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/src/home.js ADDED
@@ -0,0 +1,113 @@
1
+ // The screen for "frontmost" with no command on a terminal: the latest scan at a glance.
2
+ import { projectSetting } from "./config.js";
3
+ import { request } from "./http.js";
4
+ import { clean, percent } from "./output.js";
5
+ import { padEnd, padStart } from "./style.js";
6
+
7
+ const RIVALS_SHOWN = 3;
8
+
9
+ /** The welcome when nothing is signed in. @param {import("./style.js").Style} s */
10
+ export function welcome(s) {
11
+ return [
12
+ "",
13
+ ` ${s.logo()}`,
14
+ "",
15
+ " See how AI apps answer your buyers' questions.",
16
+ "",
17
+ ` ${s.dim(padEnd("Sign in", 10))}${s.bold("frontmost login")}`,
18
+ ` ${s.dim(padEnd("Commands", 10))}${s.bold("frontmost --help")}`,
19
+ "",
20
+ ].join("\n");
21
+ }
22
+
23
+ /** "2026-10-05" is "Oct 5". @param {string} day */
24
+ const shortDate = (day) => new Date(`${day}T12:00:00Z`).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
25
+
26
+ /** "▲ 2 pts", "▼ 10 pts", or "" when nothing changed or nothing came before. @param {any} rate */
27
+ function change(rate) {
28
+ if (typeof rate?.previous !== "number") return "";
29
+ const points = Math.round(rate.value * 100) - Math.round(rate.previous * 100);
30
+ if (!points) return "same as before";
31
+ return `${points > 0 ? "▲" : "▼"} ${Math.abs(points)} ${Math.abs(points) === 1 ? "pt" : "pts"}`;
32
+ }
33
+
34
+ /**
35
+ * @param {import("./http.js").Client} client
36
+ * @param {{ env: import("./config.js").Env, cwd: string, width?: number, project?: string }} io
37
+ * @param {import("./style.js").Style} s
38
+ */
39
+ export async function home(client, io, s) {
40
+ /** @param {string} path @param {Record<string, string>} [query] */
41
+ const get = async (path, query) => (await request(client, "GET", path, { query })).body;
42
+ const [workspace, projects] = await Promise.all([get("/workspace"), get("/projects", { limit: "100" })]);
43
+ const head = ["", ` ${s.logo()} ${s.dim(clean(`${workspace.name} · ${plan(workspace.plan)}`))}`, ""];
44
+
45
+ const set = projectSetting({ flag: io.project, env: io.env, cwd: io.cwd });
46
+ const project = set ? projects.data.find((/** @type {any} */ p) => String(p.id) === set) : projects.data.length === 1 ? projects.data[0] : undefined;
47
+ if (!project) return [...head, ...pick(projects.data, set, s), ""].join("\n");
48
+
49
+ const [metrics, rivals] = await Promise.all([get(`/projects/${project.id}/metrics`), get(`/projects/${project.id}/rivals`, { limit: "100" })]);
50
+ const lines = [...head, ` ${s.bold(clean(project.name))}`];
51
+ const totals = metrics.totals;
52
+ if (!totals?.visibility?.denominator) {
53
+ lines.push(` ${s.dim(clean(metrics.message ?? "No scan is delivered yet."))}`, "", ...next(["frontmost scans", "frontmost --help"], s), "");
54
+ return lines.join("\n");
55
+ }
56
+
57
+ const answers = totals.visibility.denominator;
58
+ const apps = metrics.scope?.apps?.length ?? 0;
59
+ lines.push(s.dim(` Scan of ${shortDate(metrics.scope.period.end)} · ${answers} answers · ${apps} AI ${apps === 1 ? "app" : "apps"}`), "");
60
+
61
+ const dots = Math.max(10, Math.min(40, (io.width ?? 80) - 44));
62
+ /** @param {string} name @param {any} rate */
63
+ const rateRow = (name, rate) =>
64
+ ` ${padEnd(name, 12)}${padStart(s.bold(percent(rate.value)), 4)} ${s.tally(rate.numerator, rate.denominator, dots)} ${s.dim(padStart(`${rate.numerator} of ${rate.denominator}`, 8))} ${s.dim(change(rate))}`;
65
+ lines.push(rateRow("Visibility", totals.visibility), rateRow("Win rate", totals.win_rate));
66
+ if (typeof totals.position?.value === "number") {
67
+ const was = typeof totals.position.previous === "number" ? `was ${totals.position.previous}` : "";
68
+ lines.push(` ${padEnd("Position", 12)}${padStart(s.bold(String(totals.position.value)), 4)} ${s.dim(`average place when named${was ? ` · ${was}` : ""}`)}`);
69
+ }
70
+
71
+ const board = ranking(rivals.data, totals.visibility, s);
72
+ if (board.length) lines.push("", ` ${s.bold("Named most")}`, ...board);
73
+ lines.push("", ...next(["frontmost rivals", "frontmost answers", "frontmost --help"], s));
74
+ if (project.url) lines.push(` ${s.dim(padEnd("Open", 6))}${s.dim(clean(project.url))}`);
75
+ lines.push("");
76
+ return lines.join("\n");
77
+ }
78
+
79
+ /** "scale" is "Scale". @param {unknown} name */
80
+ const plan = (name) => clean(name).replace(/^./, (c) => c.toUpperCase());
81
+
82
+ /** @param {string[]} commands @param {import("./style.js").Style} s */
83
+ const next = (commands, s) => [` ${s.dim(padEnd("Next", 6))}${commands.map((c) => s.bold(c)).join(s.dim(" · "))}`];
84
+
85
+ /**
86
+ * The top rivals and you, ranked by the answers that named each one. Your row is the one yellow row.
87
+ * @param {any[]} rivals @param {any} you @param {import("./style.js").Style} s
88
+ */
89
+ function ranking(rivals, you, s) {
90
+ const named = (/** @type {any} */ r) => Number(r.visibility?.numerator) || 0;
91
+ const rank = 1 + rivals.filter((r) => named(r) > you.numerator).length;
92
+ const rows = rivals.slice(0, RIVALS_SHOWN).map((r, i) => ({ place: i + 1, name: clean(r.name), count: named(r), you: false }));
93
+ const me = { place: rank, name: "You", count: you.numerator, you: true };
94
+ rows.splice(Math.min(rank - 1, rows.length), 0, me);
95
+ const width = Math.max(...rows.map((r) => r.name.length), 3);
96
+ const lines = rows.map((r) => {
97
+ const text = `${padStart(String(r.place), 3)} ${padEnd(r.name, width)} ${padStart(String(r.count), 3)} of ${you.denominator}`;
98
+ return r.you ? ` ${s.named(text)}` : ` ${text.replace(/ of \d+$/, (t) => s.dim(t))}`;
99
+ });
100
+ // Rivals between the top ones and you are left out. A gray mark shows the gap.
101
+ if (rank > RIVALS_SHOWN + 1) lines.splice(RIVALS_SHOWN, 0, ` ${s.gray(" ⋮")}`);
102
+ return lines;
103
+ }
104
+
105
+ /** With more than one project and none chosen, list them. @param {any[]} projects @param {string | undefined} set @param {import("./style.js").Style} s */
106
+ function pick(projects, set, s) {
107
+ if (!projects.length) return [" No project yet.", "", ...next(["frontmost projects create <domain>"], s)];
108
+ const lines = set ? [` Project ${clean(set)} is not in this workspace.`, ""] : [];
109
+ const width = Math.max(...projects.map((p) => String(p.id).length));
110
+ lines.push(` ${s.bold("Projects")}`, ...projects.map((p) => ` ${s.dim(padStart(clean(p.id), width))} ${clean(p.name)}`), "");
111
+ lines.push(` ${s.dim("Choose one with")} ${s.bold("--project <id>")}${s.dim(", or set")} ${s.bold("FRONTMOST_PROJECT")}`);
112
+ return lines;
113
+ }
package/src/http.js ADDED
@@ -0,0 +1,67 @@
1
+ // One API request. One retry, only when the API says to slow down.
2
+ import { ApiError } from "./errors.js";
3
+ import { VERSION } from "./spec.js";
4
+
5
+ const TIMEOUT_MS = 60_000;
6
+ const MAX_RETRY_WAIT_S = 60;
7
+
8
+ /**
9
+ * @typedef {{ base: string, token: () => Promise<string>, fetch: typeof fetch, sleep: (ms: number) => Promise<unknown> }} Client `token` gives the API key, or the access of a browser sign-in.
10
+ * @typedef {{ query?: Record<string, string>, body?: unknown, headers?: Record<string, string> }} Options
11
+ * @typedef {{ status: number, body: any, headers: Headers }} Reply
12
+ */
13
+
14
+ /**
15
+ * @param {Client} client @param {string} method @param {string} path @param {Options} [options]
16
+ * @returns {Promise<Reply>}
17
+ */
18
+ export async function request(client, method, path, options = {}, retried = false) {
19
+ const url = new URL(client.base + path);
20
+ if (url.origin !== new URL(client.base).origin) throw new ApiError("The path must stay on the Frontmost API.");
21
+ for (const [k, v] of Object.entries(options.query ?? {})) url.searchParams.set(k, v);
22
+
23
+ const token = await client.token();
24
+ let res;
25
+ let text;
26
+ try {
27
+ res = await client.fetch(url, {
28
+ method,
29
+ redirect: "error",
30
+ signal: AbortSignal.timeout(TIMEOUT_MS),
31
+ headers: {
32
+ authorization: `Bearer ${token}`,
33
+ accept: "application/json",
34
+ "user-agent": `frontmost-cli/${VERSION}`,
35
+ ...(options.body === undefined ? {} : { "content-type": "application/json" }),
36
+ ...options.headers,
37
+ },
38
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
39
+ });
40
+ text = await res.text();
41
+ } catch (cause) {
42
+ const timedOut = cause instanceof Error && cause.name === "TimeoutError";
43
+ throw new ApiError(timedOut ? "The API did not answer in 60 seconds. Try again." : `Could not reach ${url.host}. Check the network, then try again.`);
44
+ }
45
+
46
+ if (res.status === 429 && !retried) {
47
+ const wait = Number(res.headers.get("retry-after")) || 1;
48
+ if (wait <= MAX_RETRY_WAIT_S) {
49
+ await client.sleep(wait * 1000);
50
+ return request(client, method, path, options, true);
51
+ }
52
+ }
53
+
54
+ let body = null;
55
+ try {
56
+ if (text) body = JSON.parse(text);
57
+ } catch {
58
+ // Not JSON. Reported below.
59
+ }
60
+ if (!res.ok) {
61
+ const error = body?.error ?? {};
62
+ throw new ApiError(error.message ?? `The API answered with status ${res.status}.`, { code: error.code, request_id: error.request_id, body });
63
+ }
64
+ // A proxy or a sign-in page of the network can answer in place of the API.
65
+ if (res.status !== 204 && (typeof body !== "object" || body === null)) throw new ApiError(`${url.host} sent a reply that is not from the Frontmost API. Check the network, then try again.`);
66
+ return { status: res.status, body, headers: res.headers };
67
+ }
package/src/oauth.js ADDED
@@ -0,0 +1,228 @@
1
+ // Sign in with the browser: OAuth 2.0 with PKCE on a loopback address (RFC 8252), or a device code (RFC 8628).
2
+ import { spawn } from "node:child_process";
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import { createServer } from "node:http";
5
+ import { readSignIn, safeUrl, saveSignIn } from "./config.js";
6
+ import { ApiError } from "./errors.js";
7
+ import { clean } from "./output.js";
8
+ import { VERSION } from "./spec.js";
9
+
10
+ /** The CLI's public client ID. It is not a secret: the sign-in is proven with PKCE. */
11
+ const CLIENT_ID = "client_01M7BCKNW128JXV6J6DX8PAS9T";
12
+ const SCOPE = "offline_access";
13
+ const BROWSER_WAIT_MS = 5 * 60_000;
14
+ const REQUEST_TIMEOUT_MS = 30_000;
15
+ /** Get a new access token this long before the old one expires. */
16
+ const EARLY_MS = 60_000;
17
+ const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
18
+ const AGAIN = 'Run "frontmost login" again.';
19
+
20
+ /**
21
+ * @typedef {import("./cli.js").Io} Io
22
+ * @typedef {import("./config.js").SignIn} SignIn
23
+ * @typedef {{ issuer: string, authorization_endpoint: string, token_endpoint: string, device_authorization_endpoint?: string }} Endpoints
24
+ */
25
+
26
+ /** @param {Buffer} bytes */
27
+ const base64url = (bytes) => bytes.toString("base64url");
28
+
29
+ /**
30
+ * One request to the sign-in server. The reply is JSON, or {} when it is not.
31
+ * @param {Io} io @param {string} url @param {Record<string, string>} [form] Sent as a POST when given.
32
+ * @returns {Promise<{ ok: boolean, body: any }>}
33
+ */
34
+ async function call(io, url, form) {
35
+ if (!safeUrl(url)) throw new ApiError("The sign-in server gave an address that is not https. Sign-in stopped.");
36
+ let res;
37
+ let text;
38
+ try {
39
+ res = await io.fetch(url, {
40
+ method: form ? "POST" : "GET",
41
+ redirect: "error",
42
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
43
+ headers: { accept: "application/json", "user-agent": `frontmost-cli/${VERSION}`, ...(form ? { "content-type": "application/x-www-form-urlencoded" } : {}) },
44
+ body: form ? new URLSearchParams(form).toString() : undefined,
45
+ });
46
+ text = await res.text();
47
+ } catch {
48
+ throw new ApiError(`Could not reach ${new URL(url).host}. Check the network, then try again.`);
49
+ }
50
+ try {
51
+ const body = text ? JSON.parse(text) : {};
52
+ return { ok: res.ok, body: typeof body === "object" && body !== null ? body : {} };
53
+ } catch {
54
+ return { ok: false, body: {} };
55
+ }
56
+ }
57
+
58
+ /**
59
+ * The API names its sign-in server (RFC 9728). The sign-in server names its endpoints (RFC 8414).
60
+ * @param {Io} io @param {string} base The API address. @returns {Promise<Endpoints>}
61
+ */
62
+ async function discover(io, base) {
63
+ const api = new URL(base);
64
+ const resource = await call(io, `${api.origin}/.well-known/oauth-protected-resource${api.pathname}`);
65
+ const issuer = resource.body.authorization_servers?.[0];
66
+ const meta = typeof issuer === "string" ? (await call(io, `${issuer.replace(/\/$/, "")}/.well-known/oauth-authorization-server`)).body : {};
67
+ const usable = meta.issuer === issuer && [meta.authorization_endpoint, meta.token_endpoint].every((u) => typeof u === "string" && safeUrl(u));
68
+ if (!usable) throw new ApiError(`${api.host} did not say where to sign in. Try again, or use an API key: frontmost login --with-key`);
69
+ return meta;
70
+ }
71
+
72
+ /**
73
+ * @param {any} body A token reply. @param {Endpoints | SignIn} from
74
+ * @returns {SignIn}
75
+ */
76
+ function signInFrom(body, from) {
77
+ if (typeof body.access_token !== "string" || !body.access_token) throw new ApiError(`The sign-in server sent no access. ${AGAIN}`);
78
+ return {
79
+ access_token: body.access_token,
80
+ refresh_token: typeof body.refresh_token === "string" ? body.refresh_token : "refresh_token" in from ? from.refresh_token : undefined,
81
+ expires_at: Date.now() + (Number(body.expires_in) || 300) * 1000,
82
+ token_endpoint: from.token_endpoint,
83
+ };
84
+ }
85
+
86
+ // The brand mark: an ink speech bubble with two yellow quote marks (wordmouth site/brand/frontmost-mark.svg).
87
+ const MARK = '<svg width="40" height="40" viewBox="0 0 30 30" aria-hidden="true"><path d="M15 1.5C7.5 1.5 1.5 7.3 1.5 14.6c0 3 1 5.7 2.7 7.9L2.6 28l6-2.1c1.9 1 4.1 1.6 6.4 1.6 7.5 0 13.5-5.8 13.5-13 0-7.2-6-13-13.5-13Z" fill="#111"/><path d="M9.2 10.6h3.4l-2.1 8.2H7.4l1.8-8.2Zm6.4 0H19l-2.1 8.2h-3.1l1.8-8.2Z" fill="#E5F54B"/></svg>';
88
+
89
+ /** The page that the browser shows last. @param {boolean} done */
90
+ export const page = (done) => `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Frontmost AI</title>
91
+ <style>
92
+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:#FAFAF7;color:#111;font:16px/1.5 Geist,ui-sans-serif,system-ui,-apple-system,sans-serif;-webkit-font-smoothing:antialiased}
93
+ main{box-sizing:border-box;width:min(26rem,100% - 2rem);padding:2.5rem 2rem;background:#fff;border:1px solid rgba(17,17,17,.08);border-radius:20px}
94
+ h1{margin:1.5rem 0 .375rem;font-size:1.375rem;line-height:1.25;font-weight:600;letter-spacing:-.01em}
95
+ p{margin:0;color:#62625C}
96
+ code{display:inline-block;margin-top:1.25rem;padding:.375rem .625rem;border-radius:8px;background:#F2F2EE;font:14px/1.4 "Geist Mono",ui-monospace,SFMono-Regular,Menlo,monospace;color:#111}
97
+ .dot{display:inline-block;width:.5rem;height:.5rem;margin-right:.5rem;border-radius:50%;background:${done ? "#E5F54B;box-shadow:0 0 0 1px rgba(17,17,17,.16)" : "#B42318"};vertical-align:.1em}
98
+ </style>
99
+ <main>${MARK}
100
+ <h1><span class="dot"></span>${done ? "You are signed in" : "The sign-in did not finish"}</h1>
101
+ <p>${done ? "Close this tab. To see your latest scan, run this in the terminal:" : "Close this tab. To try again, run this in the terminal:"}</p>
102
+ ${done ? "<code>frontmost</code>" : "<code>frontmost login</code>"}
103
+ </main></html>`;
104
+
105
+ /**
106
+ * Open the sign-in page and wait for the browser to come back to this computer.
107
+ * @param {Io} io @param {Endpoints} ends @param {string} resource
108
+ * @returns {Promise<SignIn | null>} null when no browser can open.
109
+ */
110
+ async function withBrowser(io, ends, resource) {
111
+ const verifier = base64url(randomBytes(32));
112
+ const state = base64url(randomBytes(16));
113
+ const server = createServer();
114
+ await new Promise((ready, fail) => server.once("error", fail).listen(0, "127.0.0.1", () => ready(undefined)));
115
+ const address = server.address();
116
+ const redirect = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}/callback`;
117
+
118
+ const url = new URL(ends.authorization_endpoint);
119
+ for (const [k, v] of Object.entries({
120
+ response_type: "code",
121
+ client_id: CLIENT_ID,
122
+ redirect_uri: redirect,
123
+ code_challenge: base64url(createHash("sha256").update(verifier).digest()),
124
+ code_challenge_method: "S256",
125
+ state,
126
+ scope: SCOPE,
127
+ resource,
128
+ })) url.searchParams.set(k, v);
129
+
130
+ /** @type {NodeJS.Timeout | undefined} */ let timer;
131
+ try {
132
+ /** @type {Promise<URLSearchParams | null>} */
133
+ const returned = new Promise((resolve) => {
134
+ timer = setTimeout(() => resolve(null), BROWSER_WAIT_MS);
135
+ server.on("request", (req, res) => {
136
+ const back = new URL(req.url ?? "/", redirect).searchParams;
137
+ // Only the reply to this sign-in counts. Any other request gets no page and does not stop the wait.
138
+ if (!req.url?.startsWith("/callback?") || back.get("state") !== state) return void res.writeHead(404).end();
139
+ const done = Boolean(back.get("code")) && (back.get("iss") ?? ends.issuer) === ends.issuer;
140
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", connection: "close" }).end(page(done));
141
+ resolve(done ? back : new URLSearchParams({ error: back.get("error") ?? "wrong_issuer" }));
142
+ });
143
+ });
144
+ if (!(await io.open(url.href))) return null;
145
+ io.note(`Your browser is open. Sign in there.\nIf the browser did not open, go to:\n${url.href}`);
146
+ const back = await returned;
147
+ if (!back) throw new ApiError(`No sign-in arrived in 5 minutes. ${AGAIN}`);
148
+ const code = back.get("code");
149
+ if (!code) throw new ApiError(back.get("error") === "access_denied" ? "The sign-in was refused." : `The sign-in did not finish. ${AGAIN}`);
150
+ const { ok, body } = await call(io, ends.token_endpoint, { grant_type: "authorization_code", code, redirect_uri: redirect, client_id: CLIENT_ID, code_verifier: verifier, resource });
151
+ if (!ok) throw new ApiError(`The sign-in did not finish. ${AGAIN}`);
152
+ return signInFrom(body, ends);
153
+ } finally {
154
+ clearTimeout(timer);
155
+ server.close();
156
+ server.closeAllConnections();
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Show a code to enter on any device, then wait for the person to approve it there.
162
+ * @param {Io} io @param {Endpoints} ends @param {string} resource @returns {Promise<SignIn>}
163
+ */
164
+ async function withCode(io, ends, resource) {
165
+ if (!ends.device_authorization_endpoint) throw new ApiError("No browser can open here. Use an API key: frontmost login --with-key");
166
+ const { ok, body: device } = await call(io, ends.device_authorization_endpoint, { client_id: CLIENT_ID, scope: SCOPE, resource });
167
+ if (!ok || typeof device.device_code !== "string" || !safeUrl(String(device.verification_uri))) throw new ApiError("The sign-in could not start. Try again.");
168
+ io.note(clean(`Open this page on any device:\n ${device.verification_uri}\nThen enter this code:\n ${device.user_code}`));
169
+
170
+ let wait = Number(device.interval) || 5;
171
+ for (let left = Number(device.expires_in) || 300; left > 0; left -= wait) {
172
+ await io.sleep(wait * 1000);
173
+ const reply = await call(io, ends.token_endpoint, { grant_type: DEVICE_GRANT, device_code: device.device_code, client_id: CLIENT_ID, resource });
174
+ if (reply.ok) return signInFrom(reply.body, ends);
175
+ if (reply.body.error === "slow_down") wait += 5;
176
+ else if (reply.body.error === "access_denied") throw new ApiError("The sign-in was refused.");
177
+ else if (reply.body.error !== "authorization_pending") break;
178
+ }
179
+ throw new ApiError(`The code expired. ${AGAIN}`);
180
+ }
181
+
182
+ /**
183
+ * Sign in a person. The browser is first. The code is for a computer with no browser, such as one reached over SSH.
184
+ * @param {Io} io @param {string} base The API address. @param {{ browser: boolean }} how @returns {Promise<SignIn>}
185
+ */
186
+ export async function signIn(io, base, { browser }) {
187
+ const ends = await discover(io, base);
188
+ const remote = Boolean(io.env.SSH_CONNECTION || io.env.SSH_TTY);
189
+ return ((browser && !remote && (await withBrowser(io, ends, base))) || withCode(io, ends, base));
190
+ }
191
+
192
+ /**
193
+ * The access token of the saved sign-in. Access lasts minutes, so this gets a new one when the old one is near its end.
194
+ * Each request names the API (RFC 8707). Without that name, the sign-in server gives access that the API refuses.
195
+ * @param {Io} io @param {string} base The API address. @returns {() => Promise<string>}
196
+ */
197
+ export function accessToken(io, base) {
198
+ /** @type {SignIn | undefined} */ let now;
199
+ return async () => {
200
+ now ??= readSignIn(io.env);
201
+ if (!now) throw new ApiError(`The saved sign-in is gone. ${AGAIN}`);
202
+ if (now.expires_at - EARLY_MS > Date.now()) return now.access_token;
203
+ if (!now.refresh_token) throw new ApiError(`Your sign-in ended. ${AGAIN}`);
204
+ const { ok, body } = await call(io, now.token_endpoint, { grant_type: "refresh_token", refresh_token: now.refresh_token, client_id: CLIENT_ID, resource: base });
205
+ if (ok) {
206
+ now = signInFrom(body, now);
207
+ saveSignIn(io.env, now);
208
+ return now.access_token;
209
+ }
210
+ // Each use replaces the saved sign-in. Another frontmost command can get there first, and then its copy is the good one.
211
+ const other = readSignIn(io.env);
212
+ if (other && other.refresh_token !== now.refresh_token && other.expires_at - EARLY_MS > Date.now()) return (now = other).access_token;
213
+ throw new ApiError(`Your sign-in ended. ${AGAIN}`);
214
+ };
215
+ }
216
+
217
+ /**
218
+ * Open a page in the person's browser. @param {string} url
219
+ * @returns {Promise<boolean>} False when this computer has no browser to open.
220
+ */
221
+ export function openBrowser(url) {
222
+ const [command, ...args] = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler", url] : ["xdg-open", url];
223
+ return new Promise((resolve) => {
224
+ const child = spawn(command, args, { stdio: "ignore" });
225
+ child.once("error", () => resolve(false));
226
+ child.once("exit", (code) => resolve(code === 0));
227
+ });
228
+ }
package/src/output.js ADDED
@@ -0,0 +1,108 @@
1
+ // Plain text for people. Text from the API can never send control codes to the terminal.
2
+ import { PLAIN } from "./style.js";
3
+
4
+ // Control codes except tab and newline, plus the Unicode marks that reorder text.
5
+ const UNSAFE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/g;
6
+ const MAX_CELL = 48;
7
+
8
+ /** @param {unknown} text */
9
+ export const clean = (text) => String(text).replace(UNSAFE, "");
10
+ /** JSON text with the same values, and with each unsafe character written as \\uXXXX. @param {unknown} value */
11
+ export const json = (value) => JSON.stringify(value, null, 2).replace(UNSAFE, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
12
+ /** @param {unknown} text */
13
+ const oneLine = (text) => clean(text).replace(/\s+/g, " ").trim();
14
+
15
+ /** @param {unknown} v @returns {v is Record<string, unknown>} */
16
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
17
+ /** @param {unknown} v @returns {v is Record<string, unknown>[]} */
18
+ const isRows = (v) => Array.isArray(v) && v.length > 0 && v.every(isObject);
19
+
20
+ /** @param {unknown} v */
21
+ function cell(v) {
22
+ if (v === null || v === undefined) return "";
23
+ if (Array.isArray(v)) return v.every((x) => !isObject(x)) ? v.join(", ") : String(v.length);
24
+ return String(v);
25
+ }
26
+
27
+ /** 0.3226 is 32%. @param {number} share */
28
+ export const percent = (share) => `${Math.round(share * 100)}%`;
29
+
30
+ /** A field name as a label: win_rate is "Win rate", questions.used is "Questions used". @param {string} key */
31
+ export const label = (key) => key.replace(/[._]/g, " ").replace(/\bid\b/gi, "ID").replace(/^./, (c) => c.toUpperCase());
32
+
33
+ /**
34
+ * One level of key and value pairs. {a: {b: 1}} becomes a.b.
35
+ * A rate {value, numerator, denominator} is one cell with its counts on a terminal: 16% (4/25).
36
+ * In a pipe, the value keeps the plain name and each other field has its own column: a, a.numerator, a.denominator.
37
+ * @param {Record<string, unknown>} obj @param {boolean} tty @returns {[string, unknown][]}
38
+ */
39
+ export function flatten(obj, tty, prefix = "") {
40
+ return Object.entries(obj).flatMap(([k, v]) => {
41
+ if (!isObject(v)) return [[prefix + k, v]];
42
+ if (!("value" in v)) return flatten(v, tty, `${prefix}${k}.`);
43
+ if (!tty) return Object.entries(v).map(([field, x]) => /** @type {[string, unknown]} */ ([field === "value" ? prefix + k : `${prefix}${k}.${field}`, x]));
44
+ const counted = v.value !== null && typeof v.numerator === "number" && typeof v.denominator === "number";
45
+ return [[prefix + k, counted ? `${percent(Number(v.value))} (${v.numerator}/${v.denominator})` : v.value]];
46
+ });
47
+ }
48
+
49
+ /**
50
+ * @param {Record<string, unknown>[]} rows
51
+ * @param {View} view On a terminal: aligned columns that fit the width. Else: tab-separated, all columns.
52
+ */
53
+ export function table(rows, { tty, width = 80, style = PLAIN }) {
54
+ const flat = rows.map((r) => new Map(flatten(r, tty).map(([k, v]) => [k, oneLine(cell(v))])));
55
+ const all = [...new Set(flat.flatMap((r) => [...r.keys()]))].filter((c) => c !== "object");
56
+ if (!tty) return [all.join("\t"), ...flat.map((r) => all.map((c) => r.get(c) ?? "").join("\t"))].join("\n");
57
+ // On a terminal, a column with no value in any row is left out.
58
+ const columns = all.filter((c) => flat.some((r) => r.get(c)));
59
+
60
+ /** @param {string} s */
61
+ const fit = (s) => (s.length > MAX_CELL ? `${s.slice(0, MAX_CELL - 1)}…` : s);
62
+ const widths = columns.map((c) => Math.max(label(c).length, ...flat.map((r) => fit(r.get(c) ?? "").length)));
63
+ let shown = 0;
64
+ for (let used = 0; shown < columns.length; shown++) {
65
+ used += widths[shown] + (shown ? 2 : 0);
66
+ if (used > width && shown > 0) break;
67
+ }
68
+ /** @param {string[]} cells */
69
+ const line = (cells) => cells.slice(0, shown).map((s, i) => fit(s).padEnd(widths[i])).join(" ").trimEnd();
70
+ const lines = [style.dim(line(columns.map(label))), ...flat.map((r) => line(columns.map((c) => r.get(c) ?? "")))];
71
+ const hidden = columns.length - shown;
72
+ if (hidden) lines.push("", style.dim(`${hidden} more ${hidden === 1 ? "column does" : "columns do"} not fit. Add --json to see all fields.`));
73
+ return lines.join("\n");
74
+ }
75
+
76
+ /**
77
+ * One object as "key value" lines. On a terminal, long text keeps its lines and lists of objects follow as tables.
78
+ * In a pipe, every line is key, tab, value: text is on one line, and a list of objects is one line per field (rivals.0.name).
79
+ * @param {Record<string, unknown>} obj @param {View} view
80
+ */
81
+ export function record(obj, view) {
82
+ const style = view.style ?? PLAIN;
83
+ const pairs = flatten(obj, view.tty).filter(([k]) => k !== "object");
84
+ if (!view.tty) {
85
+ return pairs
86
+ .flatMap(([k, v]) => (isRows(v) ? v.flatMap((row, i) => flatten(row, false, `${k}.${i}.`).filter(([key]) => !key.endsWith(".object"))) : [[k, v]]))
87
+ .map(([k, v]) => `${k}\t${oneLine(cell(v))}`)
88
+ .join("\n");
89
+ }
90
+ const plain = pairs.filter(([, v]) => !isRows(v));
91
+ const pad = Math.max(0, ...plain.map(([k]) => label(k).length));
92
+ const lines = plain.map(([k, v]) => {
93
+ const text = clean(cell(v)).trim();
94
+ return text.includes("\n") ? `${style.dim(label(k))}\n${text}` : `${style.dim(label(k).padEnd(pad))} ${text}`;
95
+ });
96
+ for (const [k, v] of pairs) if (isRows(v)) lines.push("", style.bold(label(k)), table(v, view));
97
+ return lines.join("\n");
98
+ }
99
+
100
+ /** @typedef {{ tty: boolean, width?: number, style?: import("./style.js").Style }} View */
101
+
102
+ /**
103
+ * @param {any} body @param {View} view
104
+ */
105
+ export function render(body, view) {
106
+ if (body?.object !== "list") return isObject(body) ? record(body, view) : json(body);
107
+ return body.data.length ? table(body.data, view) : "";
108
+ }
package/src/spec.js ADDED
@@ -0,0 +1,141 @@
1
+ // Every API command comes from openapi.json. A new API route needs a new copy of that file, not new code.
2
+ import { readFileSync } from "node:fs";
3
+
4
+ /** @param {string} file */
5
+ const read = (file) => JSON.parse(readFileSync(new URL(`../${file}`, import.meta.url), "utf8"));
6
+
7
+ // A standalone binary has no files next to it. scripts/binary-entry.js embeds both files and sets this.
8
+ const embedded = /** @type {{ spec: any, version: string } | undefined} */ (/** @type {any} */ (globalThis).__FRONTMOST_EMBED__);
9
+
10
+ export const spec = embedded?.spec ?? read("openapi.json");
11
+ export const VERSION = embedded?.version ?? read("package.json").version;
12
+
13
+ /**
14
+ * @typedef {{ name: string, key: string, in: "query" | "body" | "item", parent?: string, type: "string" | "integer" | "boolean" | "list", enum?: string[], deprecated?: boolean, nullable: boolean, default?: unknown, description: string }} Flag
15
+ * @typedef {{ name: string, method: string, path: string, summary: string, inProject: boolean, args: string[], flags: Map<string, Flag>, hasBody: boolean, required: string[], positional?: { field: string, list?: string, label: string }, preset?: Record<string, unknown>, isList: boolean, retryKey: boolean }} Command
16
+ */
17
+
18
+ const VERBS = /** @type {Record<string, string>} */ ({ post: "add", patch: "update", delete: "remove" });
19
+ const RENAMES = /** @type {Record<string, string>} */ ({ workspace: "whoami", "projects add": "projects create" });
20
+
21
+ /** Body fields that a command also accepts without a flag name. */
22
+ const POSITIONAL = /** @type {Record<string, { field: string, list?: string, label: string }>} */ ({
23
+ "projects create": { field: "domain", label: "[domain]" },
24
+ "profiles add": { field: "name", label: "<name>" },
25
+ "questions add": { field: "text", list: "questions", label: "<question>..." },
26
+ });
27
+
28
+ /** Short forms of one command with one body field already set. */
29
+ const SHORTCUTS = /** @type {Record<string, { of: string, preset: Record<string, unknown>, summary: string }>} */ ({
30
+ "questions pause": { of: "questions update", preset: { active: false }, summary: "Pause a question. It keeps its history and frees room in the plan" },
31
+ "questions resume": { of: "questions update", preset: { active: true }, summary: "Ask a paused question again" },
32
+ "recommendations done": { of: "recommendations update", preset: { status: "done" }, summary: "Mark a recommendation done" },
33
+ "recommendations dismiss": { of: "recommendations update", preset: { status: "dismissed" }, summary: "Dismiss a recommendation" },
34
+ "recommendations reopen": { of: "recommendations update", preset: { status: "open" }, summary: "Open a recommendation again" },
35
+ });
36
+
37
+ /** @param {string} name */
38
+ export const dashed = (name) => name.replaceAll("_", "-").toLowerCase();
39
+
40
+ /**
41
+ * The flag type for a schema, or null when the value is not one string, number, true/false, or list of strings.
42
+ * @param {any} schema
43
+ */
44
+ function scalar(schema) {
45
+ const options = schema.anyOf ?? [schema];
46
+ const real = options.filter((/** @type {any} */ s) => s.type !== "null");
47
+ if (real.length !== 1) return null;
48
+ const [s] = real;
49
+ const nullable = real.length < options.length;
50
+ const trueFalse = s.enum?.length === 2 && s.enum.includes("true") && s.enum.includes("false");
51
+ if (s.type === "boolean" || trueFalse) return { type: /** @type {const} */ ("boolean"), nullable };
52
+ if (s.type === "integer") return { type: /** @type {const} */ ("integer"), nullable, default: s.default };
53
+ if (s.type === "string") return { type: /** @type {const} */ ("string"), nullable, enum: s.enum, default: s.default };
54
+ if (s.type === "array" && s.items?.type === "string") return { type: /** @type {const} */ ("list"), nullable, enum: s.items.enum };
55
+ return null;
56
+ }
57
+
58
+ /**
59
+ * @param {string} method
60
+ * @param {string} path
61
+ * @param {any} op
62
+ * @returns {Command}
63
+ */
64
+ function command(method, path, op) {
65
+ const parts = path.split("/").filter(Boolean);
66
+ const noun = parts.findLast((p) => !p.startsWith("{")) ?? "";
67
+ const verb = method === "get" ? (parts.at(-1)?.startsWith("{") ? "get" : "") : VERBS[method];
68
+ const derived = verb ? `${noun} ${verb}` : noun;
69
+ const name = RENAMES[derived] ?? derived;
70
+ const inProject = path.startsWith("/projects/{id}");
71
+ const params = /** @type {any[]} */ (op.parameters ?? []);
72
+ const body = op.requestBody?.content["application/json"].schema;
73
+ const positional = POSITIONAL[name];
74
+
75
+ /** @type {Map<string, Flag>} */
76
+ const flags = new Map();
77
+ /** @param {string} key @param {any} schema @param {Flag["in"]} where @param {string} [description] @param {string} [parent] */
78
+ const add = (key, schema, where, description = "", parent) => {
79
+ const type = scalar(schema);
80
+ if (!type) return;
81
+ const name = dashed(key);
82
+ const taken = flags.get(name);
83
+ // A member of a body object, such as run_config.cadence, takes the name of the older top-level field it replaces.
84
+ if (taken && !(parent && taken.deprecated)) throw new Error(`Two fields of ${method.toUpperCase()} ${path} map to --${name}`);
85
+ flags.set(name, { name, key, in: where, parent, description, deprecated: schema.deprecated === true, ...type });
86
+ };
87
+ for (const p of params) if (p.in === "query") add(p.name, p.schema, "query", p.description);
88
+ for (const [key, schema] of Object.entries(body?.properties ?? {})) add(key, schema, "body", schema.description);
89
+ for (const [parent, schema] of Object.entries(body?.properties ?? {}))
90
+ for (const [key, member] of Object.entries(schema.type === "object" ? (schema.properties ?? {}) : {})) add(key, member, "body", member.description, parent);
91
+ if (positional?.list) {
92
+ const item = body.properties[positional.list].items;
93
+ for (const [key, schema] of Object.entries(item.properties)) if (key !== positional.field) add(key, schema, "item", schema.description);
94
+ }
95
+
96
+ return {
97
+ name,
98
+ method: method.toUpperCase(),
99
+ path,
100
+ summary: op.summary,
101
+ inProject,
102
+ args: params.filter((p) => p.in === "path" && !(inProject && p.name === "id")).map((p) => p.name),
103
+ flags,
104
+ hasBody: Boolean(body),
105
+ required: body?.required ?? [],
106
+ positional,
107
+ isList: flags.has("cursor"),
108
+ retryKey: params.some((p) => p.in === "header" && p.name === "Idempotency-Key"),
109
+ };
110
+ }
111
+
112
+ /** @type {Map<string, Command>} */
113
+ export const commands = new Map();
114
+ for (const [path, ops] of Object.entries(spec.paths)) {
115
+ for (const [method, op] of Object.entries(ops)) {
116
+ const c = command(method, path, op);
117
+ if (commands.has(c.name)) throw new Error(`Two API routes map to "${c.name}"`);
118
+ commands.set(c.name, c);
119
+ }
120
+ }
121
+ for (const [name, s] of Object.entries(SHORTCUTS)) {
122
+ const of = commands.get(s.of);
123
+ if (!of) continue;
124
+ const flags = new Map([...of.flags].filter(([, f]) => !(f.key in s.preset)));
125
+ commands.set(name, { ...of, name, summary: s.summary, flags, preset: s.preset });
126
+ }
127
+
128
+ /** Flags that every command accepts. */
129
+ export const GLOBALS = /** @type {const} */ ({
130
+ json: { type: "boolean", description: "Print the API response as JSON" },
131
+ project: { type: "string", description: "Project ID. Not needed when the workspace has one project" },
132
+ all: { type: "boolean", description: "Get every page of a list" },
133
+ body: { type: "string", description: "Request body as JSON. Use - to read it from stdin" },
134
+ "idempotency-key": { type: "string", description: "Retry key for projects create. Default: made from the request body" },
135
+ wait: { type: "boolean", description: "Return at once when a project setup is still running" },
136
+ "api-key": { type: "string", description: "API key. Prefer FRONTMOST_API_KEY or frontmost login" },
137
+ browser: { type: "boolean", description: "For login. Sign in with a code. For a computer with no browser" },
138
+ "with-key": { type: "boolean", description: "For login. Save an API key in place of a browser sign-in" },
139
+ help: { type: "boolean", short: "h", description: "Show help" },
140
+ version: { type: "boolean", short: "v", description: "Show the version" },
141
+ });