@careerarchitect/cli 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CareerArchitect
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # CareerArchitect CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Score your CV, check your fit for a job, and optimise your CV from the terminal.
4
+ It talks to the same server as [careerarchitect.coach](https://careerarchitect.coach), so credits,
5
+ plans and results are shared with the website.
6
+
7
+ ```sh
8
+ npm install -g @careerarchitect/cli # Node 20 or newer
9
+ ca login
10
+ ca cv score ./cv.pdf
11
+ ca fit https://jobs.example.com/product-owner
12
+ ```
13
+
14
+ Or without installing: `npx @careerarchitect/cli lint ./cv.pdf`.
15
+
16
+ ## Commands
17
+
18
+ | Command | What it does | Credits |
19
+ |---|---|---|
20
+ | `ca login` / `ca logout` | Sign in through your browser and choose an access level; sign out and revoke | |
21
+ | `ca whoami` | Plan, credits and access level | |
22
+ | `ca cv score <file>` | Score a PDF, Word, text or Markdown CV (up to 3 MB) out of 5, with what to fix first | ✓ |
23
+ | `ca cv list` / `ca cv rm <id>` | CVs you've scored; delete one | |
24
+ | `ca cv show` | Your Master CV and its appraisal | |
25
+ | `ca lint <file>` | Offline checks: length, numbers in bullets, gaps. No account needed | |
26
+ | `ca fit <job-url>` | Import a job and run the fit report against your Master CV | ✓ |
27
+ | `ca job import <url>` / `--text <file>` | Save a job from its link, or from a description saved in a file | ✓ |
28
+ | `ca jobs` | Saved jobs with company, score and status | |
29
+ | `ca report <job>` | A job's fit report | |
30
+ | `ca job reject <job>` | Mark an application as rejected | |
31
+ | `ca journey start <job>` | Choose stages and start optimising your CV for a job | ✓ |
32
+ | `ca journey run <job>` | Run the next stage, or one with `--stage <key>` | ✓ |
33
+ | `ca journey status <job>` | Stages, scores and gaps; `--watch` follows a running stage | |
34
+ | `ca calendar` | Interviews, applications and activities this week | |
35
+
36
+ Coming soon: `ca recs`, `ca diff` and `ca export`. Answer a journey's questions, review changes and
37
+ export on the website for now.
38
+
39
+ ### Credits
40
+
41
+ Every command marked ✓ shows the server's price first and waits for `y`. `--yes` agrees without
42
+ asking. With no terminal and no `--yes`, the command stops with exit code 4 and spends nothing.
43
+
44
+ ### Questions during an import
45
+
46
+ Some job imports need an answer: the job's city, the employer's name, or whether the advert is from
47
+ a recruitment agency. The CLI asks in the terminal; `--city`, `--company` and `--agency yes|no`
48
+ answer up front for scripts. LinkedIn job pages can't be fetched: save the description to a file and
49
+ use `ca job import --text <file>`.
50
+
51
+ ## Scripting
52
+
53
+ Add `--json` to any command. Each command's output has its own shape with a version, e.g.
54
+ `{"schema": "jobs/v1", "jobs": [...]}`, so scripts keep working when the server's wording changes.
55
+ With `--json`, stdout carries only the JSON; prompts and notes go to stderr. Errors are
56
+ `{"schema": "error/v1", "error": "...", "message": "...", "exit_code": n}`.
57
+
58
+ ```sh
59
+ ca jobs --json | jq '.jobs[0]'
60
+ ca lint ./cv.pdf --strict || exit 1 # in CI: no account needed
61
+ ```
62
+
63
+ | Exit code | Meaning |
64
+ |---|---|
65
+ | 0 | OK |
66
+ | 1 | `ca lint` found a problem (`--strict`: warnings too) |
67
+ | 2 | Error: bad arguments, a refused action, or a server error |
68
+ | 3 | Not signed in, or the sign-in expired: run `ca login` |
69
+ | 4 | Needs an answer and there's no terminal: use `--yes` or the flag the message names |
70
+
71
+ ## Privacy and where your sign-in is kept
72
+
73
+ - `ca login` uses the OAuth device flow: the CLI shows a code, you check it matches in your browser,
74
+ and pick an access level (view only; view and update; view, update and use credits). No API keys.
75
+ - Your sign-in is stored in the system keychain (macOS Keychain, Windows Credential Manager, Linux
76
+ Secret Service). Where there is none, such as some SSH or WSL sessions, it's stored in
77
+ `~/.config/careerarchitect/credentials.json` (`%APPDATA%\careerarchitect` on Windows), readable
78
+ only by you, and the CLI says so.
79
+ - `ca cv score` sends the file to CareerArchitect, which reads its text exactly as the website does.
80
+ The text and the score are saved to your account; the file itself is not kept. A scored CV never
81
+ becomes your Master CV.
82
+ - `ca lint` runs entirely on your machine and sends nothing.
83
+ - `ca logout` revokes this terminal's access on the server and deletes the local copy.
84
+
85
+ ## Environment
86
+
87
+ | Variable | Use |
88
+ |---|---|
89
+ | `CA_BASE_URL` | Use another server (default `https://careerarchitect.coach`) |
90
+ | `CA_NO_KEYCHAIN=1` | Skip the keychain and use the file |
91
+ | `CA_CONFIG_DIR` | Where the credentials file goes |
92
+ | `CA_DEBUG=1` | Print stack traces for unexpected errors |
93
+
94
+ ## Development
95
+
96
+ ```sh
97
+ npm install
98
+ npm test # unit and contract tests, no network
99
+ npm run dev -- whoami
100
+ npm run build
101
+ ```
102
+
103
+ `test/fixtures.ts` holds the server's tool replies as the server builds them today. They are the
104
+ contract: if a server change breaks one, these tests fail first.
@@ -0,0 +1,125 @@
1
+ import { z } from "zod";
2
+ import { CLIENT_ID, cliVersion } from "../config.js";
3
+ import { CliError, EXIT } from "../errors.js";
4
+ /** OAuth 2.0 Device Authorization Grant (RFC 8628), plus refresh and revoke. */
5
+ export const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
6
+ const DeviceAuthorizationSchema = z.object({
7
+ device_code: z.string(),
8
+ user_code: z.string(),
9
+ verification_uri: z.string(),
10
+ verification_uri_complete: z.string().optional(),
11
+ expires_in: z.number(),
12
+ interval: z.number().optional(),
13
+ });
14
+ const TokenSchema = z.object({
15
+ access_token: z.string(),
16
+ refresh_token: z.string(),
17
+ expires_in: z.number(),
18
+ scope: z.string().optional(),
19
+ });
20
+ const ErrorSchema = z.object({ error: z.string(), error_description: z.string().optional() });
21
+ function userAgent() {
22
+ return `careerarchitect-cli/${cliVersion()} (node ${process.versions.node}; ${process.platform})`;
23
+ }
24
+ async function postForm(url, form) {
25
+ let res;
26
+ try {
27
+ res = await fetch(url, {
28
+ method: "POST",
29
+ headers: {
30
+ "Content-Type": "application/x-www-form-urlencoded",
31
+ Accept: "application/json",
32
+ "User-Agent": userAgent(),
33
+ },
34
+ body: new URLSearchParams(form).toString(),
35
+ });
36
+ }
37
+ catch (err) {
38
+ throw new CliError(`Could not reach ${new URL(url).origin}: ${err instanceof Error ? err.message : String(err)}`);
39
+ }
40
+ let body = null;
41
+ try {
42
+ body = await res.json();
43
+ }
44
+ catch {
45
+ body = null;
46
+ }
47
+ return { status: res.status, body };
48
+ }
49
+ export async function startDeviceAuthorization(baseUrl) {
50
+ const { status, body } = await postForm(`${baseUrl}/oauth/device_authorization`, { client_id: CLIENT_ID });
51
+ const ok = DeviceAuthorizationSchema.safeParse(body);
52
+ if (status === 200 && ok.success)
53
+ return ok.data;
54
+ const err = ErrorSchema.safeParse(body);
55
+ if (err.success && err.data.error_description)
56
+ throw new CliError(err.data.error_description);
57
+ throw new CliError(`Sign-in could not start (HTTP ${status}).`);
58
+ }
59
+ export function interpretTokenResponse(status, body) {
60
+ const tokens = TokenSchema.safeParse(body);
61
+ if (status === 200 && tokens.success)
62
+ return { kind: "tokens", tokens: tokens.data };
63
+ const err = ErrorSchema.safeParse(body);
64
+ switch (err.success ? err.data.error : "") {
65
+ case "authorization_pending":
66
+ return { kind: "pending" };
67
+ case "slow_down":
68
+ return { kind: "slow_down" };
69
+ case "access_denied":
70
+ return { kind: "denied" };
71
+ case "expired_token":
72
+ case "invalid_grant":
73
+ return { kind: "expired" };
74
+ default:
75
+ throw new CliError(`Sign-in failed (HTTP ${status}${err.success ? `: ${err.data.error}` : ""}).`);
76
+ }
77
+ }
78
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
79
+ /** Poll until the user approves, cancels, or the code expires. */
80
+ export async function pollForTokens(baseUrl, auth, now = Date.now, wait = sleep) {
81
+ let intervalSec = Math.max(1, auth.interval ?? 5);
82
+ const deadline = now() + auth.expires_in * 1000;
83
+ while (now() < deadline) {
84
+ await wait(intervalSec * 1000);
85
+ const { status, body } = await postForm(`${baseUrl}/oauth/token`, {
86
+ grant_type: DEVICE_CODE_GRANT_TYPE,
87
+ device_code: auth.device_code,
88
+ client_id: CLIENT_ID,
89
+ });
90
+ const outcome = interpretTokenResponse(status, body);
91
+ if (outcome.kind === "tokens")
92
+ return toCredentials(baseUrl, outcome.tokens, now());
93
+ if (outcome.kind === "slow_down")
94
+ intervalSec += 5;
95
+ if (outcome.kind === "denied")
96
+ throw new CliError("Sign-in was cancelled in the browser.", EXIT.auth);
97
+ if (outcome.kind === "expired")
98
+ break;
99
+ }
100
+ throw new CliError("The sign-in code expired. Run ca login again.", EXIT.auth);
101
+ }
102
+ export function toCredentials(baseUrl, t, nowMs) {
103
+ return {
104
+ base_url: baseUrl,
105
+ access_token: t.access_token,
106
+ refresh_token: t.refresh_token,
107
+ expires_at: nowMs + t.expires_in * 1000,
108
+ scope: t.scope ?? "",
109
+ };
110
+ }
111
+ /** Refresh tokens rotate: the old one stops working once used. */
112
+ export async function refreshCredentials(creds) {
113
+ const { status, body } = await postForm(`${creds.base_url}/oauth/token`, {
114
+ grant_type: "refresh_token",
115
+ refresh_token: creds.refresh_token,
116
+ client_id: CLIENT_ID,
117
+ });
118
+ const tokens = TokenSchema.safeParse(body);
119
+ if (status === 200 && tokens.success)
120
+ return toCredentials(creds.base_url, tokens.data, Date.now());
121
+ return null;
122
+ }
123
+ export async function revokeToken(baseUrl, token) {
124
+ await postForm(`${baseUrl}/oauth/revoke`, { token, client_id: CLIENT_ID }).catch(() => undefined);
125
+ }
@@ -0,0 +1,25 @@
1
+ import { baseUrl } from "../config.js";
2
+ import { CliError, EXIT } from "../errors.js";
3
+ import { refreshCredentials } from "./oauth.js";
4
+ import { loadCredentials, saveCredentials } from "./store.js";
5
+ const NOT_SIGNED_IN = "You're not signed in. Run ca login.";
6
+ /** Refresh a minute early so a token never expires mid-request. */
7
+ const EXPIRY_MARGIN_MS = 60_000;
8
+ export async function currentCredentials() {
9
+ const creds = await loadCredentials(baseUrl());
10
+ if (!creds)
11
+ throw new CliError(NOT_SIGNED_IN, EXIT.auth);
12
+ if (creds.expires_at - EXPIRY_MARGIN_MS > Date.now())
13
+ return creds;
14
+ return forceRefresh(creds);
15
+ }
16
+ export async function forceRefresh(creds) {
17
+ const fresh = await refreshCredentials(creds);
18
+ if (!fresh)
19
+ throw new CliError("Your sign-in has expired. Run ca login.", EXIT.auth);
20
+ await saveCredentials(fresh);
21
+ return fresh;
22
+ }
23
+ export function scopesOf(creds) {
24
+ return creds.scope.split(/[\s,]+/).filter(Boolean);
25
+ }
@@ -0,0 +1,122 @@
1
+ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { z } from "zod";
5
+ /**
6
+ * Where the sign-in is kept (design decision 10): the system keychain when there is one,
7
+ * otherwise a file only this user can read (0600), with a one-line warning.
8
+ */
9
+ export const CredentialsSchema = z.object({
10
+ base_url: z.string(),
11
+ access_token: z.string(),
12
+ refresh_token: z.string(),
13
+ /** Epoch milliseconds. */
14
+ expires_at: z.number(),
15
+ scope: z.string(),
16
+ });
17
+ const KEYCHAIN_SERVICE = "careerarchitect-cli";
18
+ async function keychainEntry(baseUrl) {
19
+ if (process.env.CA_NO_KEYCHAIN === "1")
20
+ return null;
21
+ try {
22
+ const mod = (await import("@napi-rs/keyring"));
23
+ const entry = new mod.Entry(KEYCHAIN_SERVICE, baseUrl);
24
+ // Touch it once: on Linux without a secret service this throws, and we fall back to the file.
25
+ entry.getPassword();
26
+ return entry;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ export function credentialsFilePath() {
33
+ if (process.env.CA_CONFIG_DIR)
34
+ return join(process.env.CA_CONFIG_DIR, "credentials.json");
35
+ if (process.platform === "win32" && process.env.APPDATA) {
36
+ return join(process.env.APPDATA, "careerarchitect", "credentials.json");
37
+ }
38
+ const xdg = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
39
+ return join(xdg, "careerarchitect", "credentials.json");
40
+ }
41
+ async function readFileStore() {
42
+ try {
43
+ const raw = JSON.parse(await readFile(credentialsFilePath(), "utf8"));
44
+ if (!raw || typeof raw !== "object")
45
+ return {};
46
+ const out = {};
47
+ for (const [k, v] of Object.entries(raw)) {
48
+ const parsed = CredentialsSchema.safeParse(v);
49
+ if (parsed.success)
50
+ out[k] = parsed.data;
51
+ }
52
+ return out;
53
+ }
54
+ catch {
55
+ return {};
56
+ }
57
+ }
58
+ async function writeFileStore(store) {
59
+ const path = credentialsFilePath();
60
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
61
+ await writeFile(path, JSON.stringify(store, null, 2) + "\n", { mode: 0o600 });
62
+ await chmod(path, 0o600).catch(() => undefined);
63
+ }
64
+ export async function loadCredentials(baseUrl) {
65
+ const entry = await keychainEntry(baseUrl);
66
+ if (entry) {
67
+ try {
68
+ const raw = entry.getPassword();
69
+ if (raw) {
70
+ const parsed = CredentialsSchema.safeParse(JSON.parse(raw));
71
+ if (parsed.success)
72
+ return parsed.data;
73
+ }
74
+ }
75
+ catch {
76
+ // Fall through to the file.
77
+ }
78
+ }
79
+ return (await readFileStore())[baseUrl] ?? null;
80
+ }
81
+ export async function saveCredentials(creds) {
82
+ const entry = await keychainEntry(creds.base_url);
83
+ if (entry) {
84
+ try {
85
+ entry.setPassword(JSON.stringify(creds));
86
+ // Never leave an older copy in the file once the keychain holds it.
87
+ await removeFromFile(creds.base_url);
88
+ return "keychain";
89
+ }
90
+ catch {
91
+ // Fall back to the file below.
92
+ }
93
+ }
94
+ const store = await readFileStore();
95
+ store[creds.base_url] = creds;
96
+ await writeFileStore(store);
97
+ return "file";
98
+ }
99
+ async function removeFromFile(baseUrl) {
100
+ const store = await readFileStore();
101
+ if (!(baseUrl in store))
102
+ return;
103
+ delete store[baseUrl];
104
+ if (Object.keys(store).length === 0) {
105
+ await rm(credentialsFilePath(), { force: true });
106
+ }
107
+ else {
108
+ await writeFileStore(store);
109
+ }
110
+ }
111
+ export async function deleteCredentials(baseUrl) {
112
+ const entry = await keychainEntry(baseUrl);
113
+ if (entry) {
114
+ try {
115
+ entry.deletePassword();
116
+ }
117
+ catch {
118
+ // Nothing stored there.
119
+ }
120
+ }
121
+ await removeFromFile(baseUrl);
122
+ }
package/dist/bin.js ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "./cli.js";
3
+ run(process.argv.slice(2)).then((code) => {
4
+ process.exitCode = code;
5
+ }, (err) => {
6
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
7
+ process.exitCode = 2;
8
+ });
package/dist/cli.js ADDED
@@ -0,0 +1,214 @@
1
+ import { parseArgs } from "node:util";
2
+ import { baseUrl, cliVersion } from "./config.js";
3
+ import { CliError, EXIT } from "./errors.js";
4
+ import { printJson, warn } from "./io.js";
5
+ import { login, logout, whoami } from "./commands/auth.js";
6
+ import { cvList, cvRm, cvScore, cvShow } from "./commands/cv.js";
7
+ import { lint } from "./commands/lint.js";
8
+ import { fit, jobImport, jobReject, jobs, report } from "./commands/jobs.js";
9
+ import { journeyRun, journeyStart, journeyStatus } from "./commands/journey.js";
10
+ import { calendar } from "./commands/calendar.js";
11
+ export const HELP = `CareerArchitect CLI ${cliVersion()}
12
+
13
+ Usage: ca <command> [options]
14
+
15
+ Account
16
+ login Sign in through your browser and choose an access level
17
+ logout Sign out and revoke this terminal's access
18
+ whoami Plan, credits and access level
19
+
20
+ CV
21
+ cv score <file> Score a PDF, Word, text or Markdown CV out of 5 (uses credits)
22
+ cv list CVs you've scored with ca cv score
23
+ cv rm <id> Delete a scored CV
24
+ cv show Your Master CV and its appraisal
25
+ lint <file> Offline checks: length, numbers in bullets, gaps (no account needed)
26
+
27
+ Jobs
28
+ fit <job-url> Import a job and run the fit report against your Master CV (uses credits)
29
+ job import <url> Save a job from its link (uses credits)
30
+ job import --text <file> Save a job from a pasted description in a file (uses credits)
31
+ jobs Saved jobs, numbered, with company, score and status
32
+ report <job> A job's fit report
33
+ job reject <job> Mark an application as rejected
34
+
35
+ Optimise
36
+ journey start <job> Choose stages and start optimising your CV for a job (uses credits)
37
+ journey run <job> Run the next stage, or one stage with --stage <key> (uses credits)
38
+ journey status <job> Stages, scores and gaps; --watch follows a running stage
39
+ calendar Interviews, applications and activities this week
40
+
41
+ <job> is the job's number from ca jobs (1 is the newest), last (the job you used last),
42
+ or the job's id. Leave it out to pick from your recent jobs.
43
+
44
+ Coming soon: recs, diff, export. Use the website for these for now.
45
+
46
+ Options
47
+ --json Machine-readable output, with a versioned "schema" field
48
+ -y, --yes Agree to credit spends and confirmations without a prompt
49
+ --no-browser ca login: print the link instead of opening a browser
50
+ --city, --company <name> ca fit / job import: answer the import's questions up front
51
+ --agency yes|no
52
+ --job <job> ca fit: run the report for a job you already saved
53
+ --refresh ca fit: run the report again even if one exists
54
+ --stages a,b --stage a ca journey start / run: which stages
55
+ --strict ca lint: warnings fail too
56
+ --limit <n> ca jobs / cv list: how many
57
+ --from, --to YYYY-MM-DD ca calendar: date range
58
+ --ended-at <stage> ca job reject: cv_screen, after_interview, went_quiet or withdrew
59
+ --feedback <text> ca job reject: what the employer said
60
+ -h, --help -v, --version
61
+
62
+ Exit codes: 0 ok · 1 lint failed · 2 error · 3 not signed in · 4 needs an answer (use --yes or a flag)
63
+ Set CA_BASE_URL to use another server.
64
+ `;
65
+ export function parseCli(argv) {
66
+ const { values, positionals } = parseArgs({
67
+ args: argv,
68
+ allowPositionals: true,
69
+ strict: true,
70
+ options: {
71
+ json: { type: "boolean", default: false },
72
+ yes: { type: "boolean", short: "y", default: false },
73
+ help: { type: "boolean", short: "h", default: false },
74
+ version: { type: "boolean", short: "v", default: false },
75
+ "no-browser": { type: "boolean", default: false },
76
+ city: { type: "string" },
77
+ company: { type: "string" },
78
+ agency: { type: "string" },
79
+ job: { type: "string" },
80
+ text: { type: "string" },
81
+ stages: { type: "string" },
82
+ stage: { type: "string" },
83
+ watch: { type: "boolean", default: false },
84
+ strict: { type: "boolean", default: false },
85
+ refresh: { type: "boolean", default: false },
86
+ limit: { type: "string" },
87
+ from: { type: "string" },
88
+ to: { type: "string" },
89
+ "ended-at": { type: "string" },
90
+ feedback: { type: "string" },
91
+ },
92
+ });
93
+ const flags = {
94
+ json: values.json ?? false,
95
+ yes: values.yes ?? false,
96
+ noBrowser: values["no-browser"] ?? false,
97
+ city: values.city,
98
+ company: values.company,
99
+ agency: values.agency,
100
+ text: values.text,
101
+ stages: values.stages,
102
+ stage: values.stage,
103
+ watch: values.watch ?? false,
104
+ strict: values.strict ?? false,
105
+ refresh: values.refresh ?? false,
106
+ limit: values.limit,
107
+ from: values.from,
108
+ to: values.to,
109
+ endedAt: values["ended-at"],
110
+ feedback: values.feedback,
111
+ };
112
+ return { flags, positionals, help: values.help ?? false, version: values.version ?? false, job: values.job };
113
+ }
114
+ const COMING_SOON = new Set(["recs", "diff", "export"]);
115
+ export async function run(argv) {
116
+ let parsed;
117
+ try {
118
+ parsed = parseCli(argv);
119
+ }
120
+ catch (err) {
121
+ warn(`${err instanceof Error ? err.message : String(err)}\nRun ca --help for usage.`);
122
+ return EXIT.error;
123
+ }
124
+ const { flags, positionals, help, version, job } = parsed;
125
+ const ctx = { json: flags.json, yes: flags.yes, flags };
126
+ const [cmd, sub, ...rest] = positionals;
127
+ if (version) {
128
+ process.stdout.write(`${cliVersion()}\n`);
129
+ return EXIT.ok;
130
+ }
131
+ if (help || !cmd) {
132
+ process.stdout.write(HELP);
133
+ return EXIT.ok;
134
+ }
135
+ try {
136
+ switch (cmd) {
137
+ case "login":
138
+ await login(ctx);
139
+ return EXIT.ok;
140
+ case "logout":
141
+ await logout(ctx);
142
+ return EXIT.ok;
143
+ case "whoami":
144
+ await whoami(ctx);
145
+ return EXIT.ok;
146
+ case "lint":
147
+ return await lint(ctx, sub);
148
+ case "cv":
149
+ if (sub === "score")
150
+ await cvScore(ctx, rest[0]);
151
+ else if (sub === "list" || sub === "ls")
152
+ await cvList(ctx);
153
+ else if (sub === "rm")
154
+ await cvRm(ctx, rest[0]);
155
+ else if (sub === "show" || sub === undefined)
156
+ await cvShow(ctx);
157
+ else
158
+ throw new CliError(`Unknown command: ca cv ${sub}. Try score, list, rm or show.`);
159
+ return EXIT.ok;
160
+ case "fit":
161
+ await fit(ctx, [sub, ...rest].filter((p) => Boolean(p)), job);
162
+ return EXIT.ok;
163
+ case "job":
164
+ if (sub === "import")
165
+ await jobImport(ctx, rest[0]);
166
+ else if (sub === "reject")
167
+ await jobReject(ctx, rest[0]);
168
+ else
169
+ throw new CliError(`Unknown command: ca job ${sub ?? ""}. Try import or reject.`);
170
+ return EXIT.ok;
171
+ case "jobs":
172
+ await jobs(ctx);
173
+ return EXIT.ok;
174
+ case "report":
175
+ await report(ctx, sub);
176
+ return EXIT.ok;
177
+ case "journey":
178
+ if (sub === "start")
179
+ await journeyStart(ctx, rest[0]);
180
+ else if (sub === "run")
181
+ await journeyRun(ctx, rest[0]);
182
+ else if (sub === "status")
183
+ await journeyStatus(ctx, rest[0]);
184
+ else
185
+ throw new CliError(`Unknown command: ca journey ${sub ?? ""}. Try start, run or status.`);
186
+ return EXIT.ok;
187
+ case "calendar":
188
+ await calendar(ctx);
189
+ return EXIT.ok;
190
+ default:
191
+ if (COMING_SOON.has(cmd)) {
192
+ throw new CliError(`ca ${cmd} is coming soon. For now, do this step on the website: ${baseUrl()}/app/jobs`);
193
+ }
194
+ throw new CliError(`Unknown command: ${cmd}. Run ca --help for the list.`);
195
+ }
196
+ }
197
+ catch (err) {
198
+ return reportError(ctx, err);
199
+ }
200
+ }
201
+ function reportError(ctx, err) {
202
+ const isCli = err instanceof CliError;
203
+ const message = err instanceof Error ? err.message : String(err);
204
+ const exitCode = isCli ? err.exitCode : EXIT.error;
205
+ if (ctx.json && exitCode !== EXIT.ok) {
206
+ printJson({ schema: "error/v1", error: isCli ? (err.code ?? "error") : "unexpected", message, exit_code: exitCode });
207
+ }
208
+ else {
209
+ warn(message);
210
+ }
211
+ if (!isCli && process.env.CA_DEBUG === "1" && err instanceof Error && err.stack)
212
+ warn(err.stack);
213
+ return exitCode;
214
+ }