goals-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.
Files changed (46) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +125 -2
  3. package/dist/args.js +96 -0
  4. package/dist/auth/command.js +16 -0
  5. package/dist/auth/help.js +82 -0
  6. package/dist/auth/list.js +41 -0
  7. package/dist/auth/login.js +203 -0
  8. package/dist/auth/logout.js +25 -0
  9. package/dist/auth/select.js +30 -0
  10. package/dist/auth/status.js +43 -0
  11. package/dist/auth/use.js +10 -0
  12. package/dist/cli.js +112 -0
  13. package/dist/commands/export-help.js +49 -0
  14. package/dist/commands/export.js +194 -0
  15. package/dist/commands/goal-flags.js +111 -0
  16. package/dist/commands/goal-format.js +95 -0
  17. package/dist/commands/goal-help.js +214 -0
  18. package/dist/commands/goal-read.js +80 -0
  19. package/dist/commands/goal-write.js +186 -0
  20. package/dist/commands/goal.js +15 -0
  21. package/dist/commands/initiative-help.js +38 -0
  22. package/dist/commands/initiative.js +81 -0
  23. package/dist/commands/list-output.js +13 -0
  24. package/dist/commands/skill-help.js +18 -0
  25. package/dist/commands/skill.js +36 -0
  26. package/dist/credentials.js +270 -0
  27. package/dist/deps.js +46 -0
  28. package/dist/dispatch.js +16 -0
  29. package/dist/endpoints.js +82 -0
  30. package/dist/errors.js +29 -0
  31. package/dist/help.js +105 -0
  32. package/dist/http.js +199 -0
  33. package/dist/iso-week.js +18 -0
  34. package/dist/open-browser.js +47 -0
  35. package/dist/output.js +29 -0
  36. package/dist/vendor/cli-contract/index.js +26 -0
  37. package/dist/vendor/quarterly-markdown/dateFormat.js +101 -0
  38. package/dist/vendor/quarterly-markdown/generate.js +450 -0
  39. package/dist/vendor/quarterly-markdown/htmlToPlainText.js +101 -0
  40. package/dist/vendor/quarterly-markdown/index.js +4 -0
  41. package/dist/vendor/quarterly-markdown/types.js +1 -0
  42. package/dist/vendor/quarterly-markdown/year.js +45 -0
  43. package/dist/version.js +9 -0
  44. package/package.json +37 -4
  45. package/skills/goals-cli/REFERENCE.md +212 -0
  46. package/skills/goals-cli/SKILL.md +12 -0
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { runFamilyAction } from '../dispatch.js';
3
+ import { UsageError } from '../errors.js';
4
+ import { readCliVersion } from '../version.js';
5
+ const SKILL_DIR = new URL('../../skills/goals-cli/', import.meta.url);
6
+ /** One checked-in skill file; the same files are shipped in the package `files` list. */
7
+ function readSkillFile(name) {
8
+ return readFileSync(new URL(name, SKILL_DIR), 'utf8').trimEnd();
9
+ }
10
+ /** Install guidance, the stub in a `markdown` fence, `---`, then the full reference. */
11
+ function renderActivation(version, stub, reference) {
12
+ return [
13
+ `Goals CLI ${version} - agent skill`,
14
+ '',
15
+ "Save the stub below as a skill named `goals-cli` in your agent's skills directory (for example `.claude/skills/goals-cli/SKILL.md`) so you can find it later. The full reference follows the `---` line; read it before running goals commands.",
16
+ '',
17
+ '```markdown',
18
+ stub,
19
+ '```',
20
+ '',
21
+ '---',
22
+ '',
23
+ reference,
24
+ '',
25
+ ].join('\n');
26
+ }
27
+ /** Prints the skill; touches no credentials, network or files other than the two shipped files. */
28
+ async function runActivate(args, ctx) {
29
+ if (args.length > 0)
30
+ throw new UsageError('goals skill activate');
31
+ ctx.deps.stdout.write(renderActivation(readCliVersion(), readSkillFile('SKILL.md'), readSkillFile('REFERENCE.md')));
32
+ }
33
+ const ACTIONS = { activate: runActivate };
34
+ export async function runSkillCommand(args, ctx) {
35
+ await runFamilyAction('skill', ACTIONS, args, ctx);
36
+ }
@@ -0,0 +1,270 @@
1
+ import { randomUUID as uuid } from 'node:crypto';
2
+ import { chmod, mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, posix, win32 } from 'node:path';
5
+ import { parseOrigin } from './endpoints.js';
6
+ import { CliError, UsageError } from './errors.js';
7
+ export const LABEL_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
8
+ const ENVIRONMENT_PATTERN = /^[a-z0-9._-]{1,64}$/;
9
+ /** Trims/lowercases `--env`; undefined for empty; UsageError for an invalid qualifier. */
10
+ export function normalizeEnvironment(input) {
11
+ if (input === undefined)
12
+ return undefined;
13
+ const normalized = input.trim().toLowerCase();
14
+ if (normalized === '')
15
+ return undefined;
16
+ if (!ENVIRONMENT_PATTERN.test(normalized)) {
17
+ throw new UsageError("--env must contain only lowercase letters, digits, '.', '_' or '-' (max 64 characters)");
18
+ }
19
+ return normalized;
20
+ }
21
+ function homeDirectory(options, env) {
22
+ return options.homeDir ?? env.HOME ?? homedir();
23
+ }
24
+ function windowsHome(options, env) {
25
+ return options.homeDir ?? env.USERPROFILE ?? homeDirectory(options, env);
26
+ }
27
+ function windowsCredentialsPath(options, env) {
28
+ const appData = env.APPDATA ?? win32.join(windowsHome(options, env), 'AppData', 'Roaming');
29
+ return win32.join(appData, 'goals', 'credentials.json');
30
+ }
31
+ function darwinCredentialsPath(options, env) {
32
+ return posix.join(homeDirectory(options, env), 'Library', 'Application Support', 'goals', 'credentials.json');
33
+ }
34
+ function configDirectory(options, env) {
35
+ const configured = env.XDG_CONFIG_HOME;
36
+ if (configured !== undefined && configured !== '')
37
+ return configured;
38
+ return posix.join(homeDirectory(options, env), '.config');
39
+ }
40
+ function resolvePlatform(options) {
41
+ return options.platform ?? process.platform;
42
+ }
43
+ function resolveEnv(options) {
44
+ return options.env ?? process.env;
45
+ }
46
+ // Read/written only through readCredentials/writeCredentials; asserted by credentials.spec.ts.
47
+ // fallow-ignore-next-line unused-export
48
+ export function getCredentialsPath(options = {}) {
49
+ if (options.filePath !== undefined)
50
+ return options.filePath;
51
+ const platform = resolvePlatform(options);
52
+ const env = resolveEnv(options);
53
+ if (platform === 'win32')
54
+ return windowsCredentialsPath(options, env);
55
+ if (platform === 'darwin')
56
+ return darwinCredentialsPath(options, env);
57
+ return posix.join(configDirectory(options, env), 'goals', 'credentials.json');
58
+ }
59
+ // Read through readCredentials; asserted by credentials.spec.ts.
60
+ // fallow-ignore-next-line unused-export
61
+ export function createEmptyCredentials(randomUUID = uuid) {
62
+ return { schemaVersion: 1, installationId: randomUUID(), accounts: [] };
63
+ }
64
+ function isNonEmptyString(value) {
65
+ return typeof value === 'string' && value.trim() !== '';
66
+ }
67
+ function isValidDate(value) {
68
+ return typeof value === 'string' && !Number.isNaN(Date.parse(value));
69
+ }
70
+ function isOrigin(value) {
71
+ return typeof value === 'string' && parseOrigin(value) === value;
72
+ }
73
+ function isLabel(value) {
74
+ return typeof value === 'string' && LABEL_PATTERN.test(value);
75
+ }
76
+ function isOptionalEmail(value) {
77
+ return value === undefined || isNonEmptyString(value);
78
+ }
79
+ function isOptionalEnvironment(value) {
80
+ return value === undefined || (typeof value === 'string' && ENVIRONMENT_PATTERN.test(value));
81
+ }
82
+ const REQUIRED_STRING_FIELDS = ['label', 'userId', 'name', 'credentialId', 'token'];
83
+ const ORIGIN_FIELDS = ['webappUrl', 'convexUrl'];
84
+ const DATE_FIELDS = ['createdAt', 'expiresAt'];
85
+ const ACCOUNT_RULES = [
86
+ (account) => isLabel(account.label),
87
+ (account) => REQUIRED_STRING_FIELDS.every((field) => isNonEmptyString(account[field])),
88
+ (account) => ORIGIN_FIELDS.every((field) => isOrigin(account[field])),
89
+ (account) => DATE_FIELDS.every((field) => isValidDate(account[field])),
90
+ (account) => isOptionalEmail(account.email),
91
+ (account) => isOptionalEnvironment(account.environment),
92
+ ];
93
+ function isAccount(value) {
94
+ if (typeof value !== 'object' || value === null)
95
+ return false;
96
+ const account = value;
97
+ return ACCOUNT_RULES.every((rule) => rule(account));
98
+ }
99
+ function hasHeader(file) {
100
+ return (file.schemaVersion === 1 &&
101
+ isNonEmptyString(file.installationId) &&
102
+ Array.isArray(file.accounts));
103
+ }
104
+ function isAccountList(file) {
105
+ return Array.isArray(file.accounts) && file.accounts.every(isAccount);
106
+ }
107
+ function isCredentialsFile(value) {
108
+ if (typeof value !== 'object' || value === null)
109
+ return false;
110
+ const file = value;
111
+ return hasHeader(file) && isAccountList(file);
112
+ }
113
+ function failInvalid() {
114
+ throw new CliError('Invalid credentials file');
115
+ }
116
+ function hasUniqueKeys(values, keyOf) {
117
+ return new Set(values.map(keyOf)).size === values.length;
118
+ }
119
+ function isDefaultLabelValid(file) {
120
+ if (file.defaultLabel === undefined)
121
+ return true;
122
+ return file.accounts.some((account) => account.label === file.defaultLabel);
123
+ }
124
+ function hasUniqueLabelsAndIdentities(accounts) {
125
+ return (hasUniqueKeys(accounts, (account) => account.label) && hasUniqueKeys(accounts, identityKey));
126
+ }
127
+ // Applied by readCredentials/writeCredentials; asserted by credentials.spec.ts.
128
+ // fallow-ignore-next-line unused-export
129
+ export function validateCredentials(value) {
130
+ if (!isCredentialsFile(value))
131
+ failInvalid();
132
+ if (!hasUniqueLabelsAndIdentities(value.accounts))
133
+ failInvalid();
134
+ if (!isDefaultLabelValid(value))
135
+ failInvalid();
136
+ return value;
137
+ }
138
+ export function identityKey(credential) {
139
+ return `${credential.convexUrl}\n${credential.environment ?? ''}\n${credential.userId}`;
140
+ }
141
+ function labelOwnerIndex(file, credential, existingIndex) {
142
+ return file.accounts.findIndex((account, index) => index !== existingIndex && account.label === credential.label);
143
+ }
144
+ function withReplacedAccount(file, credential, existingIndex) {
145
+ if (existingIndex === -1)
146
+ return [...file.accounts, credential];
147
+ return file.accounts.map((account, index) => (index === existingIndex ? credential : account));
148
+ }
149
+ function isFirstAccount(file) {
150
+ return file.accounts.length === 0 && file.defaultLabel === undefined;
151
+ }
152
+ function isRenamedDefault(replaced, file) {
153
+ return replaced !== undefined && file.defaultLabel === replaced.label;
154
+ }
155
+ function nextDefaultLabel(file, credential, replaced) {
156
+ if (isFirstAccount(file))
157
+ return credential.label;
158
+ if (isRenamedDefault(replaced, file))
159
+ return credential.label;
160
+ return file.defaultLabel;
161
+ }
162
+ export function upsertCredential(file, credential) {
163
+ const key = identityKey(credential);
164
+ const existingIndex = file.accounts.findIndex((account) => identityKey(account) === key);
165
+ if (labelOwnerIndex(file, credential, existingIndex) !== -1) {
166
+ throw new UsageError(`identity label '${credential.label}' is already used by another account; pass --name ${credential.label} to choose a different one`);
167
+ }
168
+ const replaced = existingIndex === -1 ? undefined : file.accounts[existingIndex];
169
+ const accounts = withReplacedAccount(file, credential, existingIndex);
170
+ return {
171
+ ...file,
172
+ accounts,
173
+ defaultLabel: nextDefaultLabel(file, credential, replaced),
174
+ };
175
+ }
176
+ export function removeCredential(file, label) {
177
+ const accounts = file.accounts.filter((account) => account.label !== label);
178
+ const defaultLabel = file.defaultLabel === label ? undefined : file.defaultLabel;
179
+ return { ...file, accounts, defaultLabel };
180
+ }
181
+ export function setDefaultLabel(file, label) {
182
+ if (!file.accounts.some((account) => account.label === label)) {
183
+ throw new UsageError(`no identity labelled '${label}'; run \`goals auth list\` to see the stored identities`);
184
+ }
185
+ return { ...file, defaultLabel: label };
186
+ }
187
+ export function effectiveDefaultLabel(file) {
188
+ if (file.defaultLabel !== undefined)
189
+ return file.defaultLabel;
190
+ return file.accounts.length === 1 ? file.accounts[0]?.label : undefined;
191
+ }
192
+ function findAccount(file, label) {
193
+ const account = file.accounts.find((candidate) => candidate.label === label);
194
+ if (account === undefined) {
195
+ throw new UsageError(`no identity labelled '${label}'; run \`goals auth list\` to see the stored identities`);
196
+ }
197
+ return account;
198
+ }
199
+ function requestedLabel(options) {
200
+ const fromFlag = options.as?.trim();
201
+ if (fromFlag !== undefined && fromFlag !== '')
202
+ return fromFlag;
203
+ const fromEnv = options.env.GOALS_AS?.trim();
204
+ return fromEnv === '' ? undefined : fromEnv;
205
+ }
206
+ export function selectCredential(file, options) {
207
+ if (file.accounts.length === 0) {
208
+ throw new CliError('Not logged in; run `goals auth login`.');
209
+ }
210
+ const requested = requestedLabel(options);
211
+ if (requested !== undefined)
212
+ return findAccount(file, requested);
213
+ const defaultLabel = effectiveDefaultLabel(file);
214
+ if (defaultLabel !== undefined)
215
+ return findAccount(file, defaultLabel);
216
+ throw new UsageError('multiple identities are stored and none is the default; pass --as <label> or run `goals auth use <label>`');
217
+ }
218
+ function parseCredentialsFile(raw, path) {
219
+ try {
220
+ return validateCredentials(JSON.parse(raw));
221
+ }
222
+ catch {
223
+ throw new CliError(`Invalid credentials file: ${path}`);
224
+ }
225
+ }
226
+ export async function readCredentials(options = {}) {
227
+ const path = getCredentialsPath(options);
228
+ let raw;
229
+ try {
230
+ raw = await readFile(path, 'utf8');
231
+ }
232
+ catch (error) {
233
+ if (error.code === 'ENOENT') {
234
+ return { path, credentials: createEmptyCredentials(options.randomUUID) };
235
+ }
236
+ throw new CliError(`Unable to read credentials file: ${path}`);
237
+ }
238
+ const credentials = parseCredentialsFile(raw, path);
239
+ await chmod(dirname(path), 0o700).catch(() => { });
240
+ await chmod(path, 0o600).catch(() => { });
241
+ return { path, credentials };
242
+ }
243
+ export async function writeCredentials(credentials, options = {}) {
244
+ validateCredentials(credentials);
245
+ const path = getCredentialsPath(options);
246
+ const dir = dirname(path);
247
+ await mkdir(dir, { recursive: true, mode: 0o700 });
248
+ await chmod(dir, 0o700).catch(() => { });
249
+ const tmp = join(dir, `.credentials.${(options.randomUUID ?? uuid)()}.tmp`);
250
+ let created = false;
251
+ try {
252
+ const handle = await open(tmp, 'wx', 0o600);
253
+ created = true;
254
+ try {
255
+ await handle.writeFile(`${JSON.stringify(credentials, null, 2)}\n`);
256
+ await handle.sync();
257
+ }
258
+ finally {
259
+ await handle.close();
260
+ }
261
+ await chmod(tmp, 0o600).catch(() => { });
262
+ await rename(tmp, path);
263
+ return path;
264
+ }
265
+ catch (error) {
266
+ if (created)
267
+ await unlink(tmp).catch(() => { });
268
+ throw error;
269
+ }
270
+ }
package/dist/deps.js ADDED
@@ -0,0 +1,46 @@
1
+ import { hostname } from 'node:os';
2
+ import { openBrowserBestEffort } from './open-browser.js';
3
+ /** `setTimeout` as a promise that also settles early (without rejecting) on abort. */
4
+ function abortableSleep(ms, signal) {
5
+ return new Promise((resolve) => {
6
+ if (signal.aborted) {
7
+ resolve();
8
+ return;
9
+ }
10
+ const finish = () => {
11
+ clearTimeout(timer);
12
+ signal.removeEventListener('abort', finish);
13
+ resolve();
14
+ };
15
+ const timer = setTimeout(finish, ms);
16
+ signal.addEventListener('abort', finish, { once: true });
17
+ });
18
+ }
19
+ function onSigint(handler) {
20
+ process.once('SIGINT', handler);
21
+ return () => {
22
+ process.removeListener('SIGINT', handler);
23
+ };
24
+ }
25
+ export function defaultDeps() {
26
+ return {
27
+ stdout: {
28
+ write: (text) => {
29
+ process.stdout.write(text);
30
+ },
31
+ },
32
+ stderr: {
33
+ write: (text) => {
34
+ process.stderr.write(text);
35
+ },
36
+ },
37
+ env: process.env,
38
+ fetch: globalThis.fetch,
39
+ now: () => Date.now(),
40
+ sleep: abortableSleep,
41
+ openBrowser: (url) => openBrowserBestEffort(url),
42
+ hostname: () => hostname(),
43
+ onSigint,
44
+ storeOptions: {},
45
+ };
46
+ }
@@ -0,0 +1,16 @@
1
+ import { UsageError } from './errors.js';
2
+ /**
3
+ * Dispatches `goals <family> <action>`; the lookup is own-property only, so inherited
4
+ * object keys (`constructor`, `__proto__`) are unknown actions rather than crashes.
5
+ */
6
+ export async function runFamilyAction(family, actions, args, ctx) {
7
+ const action = args[0];
8
+ if (action === undefined) {
9
+ throw new UsageError(`goals ${family} <action>. Run \`goals ${family} --help\` for actions.`);
10
+ }
11
+ const runner = Object.hasOwn(actions, action) ? actions[action] : undefined;
12
+ if (runner === undefined) {
13
+ throw new UsageError(`unknown action '${action}' for 'goals ${family}'. Run \`goals ${family} --help\` for actions.`);
14
+ }
15
+ await runner(args.slice(1), ctx);
16
+ }
@@ -0,0 +1,82 @@
1
+ import { UsageError } from './errors.js';
2
+ /** Production endpoints used by `goals auth login` when no --webapp-url/--convex-url pair is given. */
3
+ // Asserted by endpoints.spec.ts and through the login flow in cli.spec.ts.
4
+ // fallow-ignore-next-line unused-export
5
+ export const DEFAULT_ENDPOINTS = {
6
+ webappUrl: 'https://goals-ten.vercel.app',
7
+ convexUrl: 'https://happy-otter-123.convex.site',
8
+ };
9
+ const WEBAPP_EXAMPLE = 'https://goals.example.com';
10
+ const CONVEX_EXAMPLE = 'https://example-123.convex.site';
11
+ /** Parses `value` as a URL, or `undefined` when it is not one. */
12
+ function toUrl(value) {
13
+ try {
14
+ return new URL(value.trim());
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ }
20
+ function isLocalHost(hostname) {
21
+ return hostname === 'localhost' || hostname === '127.0.0.1';
22
+ }
23
+ /** https anywhere, or plain http only for a local development server. */
24
+ function hasAllowedProtocol(url) {
25
+ return url.protocol === 'https:' || (url.protocol === 'http:' && isLocalHost(url.hostname));
26
+ }
27
+ function hasNoCredentials(url) {
28
+ return url.username === '' && url.password === '';
29
+ }
30
+ function hasNoQueryOrFragment(url) {
31
+ return url.search === '' && url.hash === '';
32
+ }
33
+ function isPlainOrigin(url) {
34
+ return (hasAllowedProtocol(url) &&
35
+ hasNoCredentials(url) &&
36
+ hasNoQueryOrFragment(url) &&
37
+ url.pathname === '/');
38
+ }
39
+ /**
40
+ * Normalized origin (no trailing slash) when `value` is an https origin (http only for
41
+ * localhost / 127.0.0.1) with no path, query, fragment or credentials; otherwise `undefined`.
42
+ */
43
+ export function parseOrigin(value) {
44
+ const url = toUrl(value);
45
+ if (url === undefined)
46
+ return undefined;
47
+ return isPlainOrigin(url) ? url.origin : undefined;
48
+ }
49
+ function requireOrigin(value, flag, example) {
50
+ const origin = parseOrigin(value);
51
+ if (origin === undefined) {
52
+ throw new UsageError(`${flag} must be an https origin such as ${example} (http is allowed only for localhost or 127.0.0.1)`);
53
+ }
54
+ return origin;
55
+ }
56
+ /** Validates both URLs; throws UsageError naming the offending flag. */
57
+ function validateEndpointPair(webappUrl, convexUrl) {
58
+ return {
59
+ webappUrl: requireOrigin(webappUrl, '--webapp-url', WEBAPP_EXAMPLE),
60
+ convexUrl: requireOrigin(convexUrl, '--convex-url', CONVEX_EXAMPLE),
61
+ };
62
+ }
63
+ /** The production pair, validated exactly like a user-supplied pair so a bad default fails loudly. */
64
+ function configuredDefaults() {
65
+ return validateEndpointPair(DEFAULT_ENDPOINTS.webappUrl, DEFAULT_ENDPOINTS.convexUrl);
66
+ }
67
+ function bothMissing(webappUrl, convexUrl) {
68
+ return webappUrl === undefined && convexUrl === undefined;
69
+ }
70
+ /**
71
+ * Endpoints for a login: both flags together, or neither (then DEFAULT_ENDPOINTS).
72
+ * Exactly one flag → UsageError('--webapp-url and --convex-url must be passed together').
73
+ */
74
+ export function resolveEndpoints(flags) {
75
+ const { webappUrl, convexUrl } = flags;
76
+ if (bothMissing(webappUrl, convexUrl))
77
+ return configuredDefaults();
78
+ if (webappUrl === undefined || convexUrl === undefined) {
79
+ throw new UsageError('--webapp-url and --convex-url must be passed together');
80
+ }
81
+ return validateEndpointPair(webappUrl, convexUrl);
82
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,29 @@
1
+ /** A failure of the user's environment or the backend (credentials, auth, network); exit code 1. */
2
+ export class CliError extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = 'CliError';
6
+ }
7
+ }
8
+ /** A misuse of the command line; exit code 2. The message always starts with `Usage:`. */
9
+ export class UsageError extends Error {
10
+ constructor(message) {
11
+ super(message.startsWith('Usage:') ? message : `Usage: ${message}`);
12
+ this.name = 'UsageError';
13
+ }
14
+ }
15
+ const SECRET_WORDS = /token|bearer|secret|device|handle|checksum/i;
16
+ /** The first line of `message` when it is safe to show, else `undefined`. */
17
+ function safeLine(message) {
18
+ const line = message.split(/\r?\n/, 1)[0]?.trim() ?? '';
19
+ return line === '' || SECRET_WORDS.test(line) ? undefined : line;
20
+ }
21
+ /**
22
+ * First line of `message` when it is non-empty and mentions no secret-ish word, else `fallback`.
23
+ * Used for every backend- or exception-derived text that reaches the terminal.
24
+ */
25
+ export function safeMessage(message, fallback) {
26
+ if (typeof message !== 'string')
27
+ return fallback;
28
+ return safeLine(message) ?? fallback;
29
+ }
package/dist/help.js ADDED
@@ -0,0 +1,105 @@
1
+ import { UsageError } from './errors.js';
2
+ function isHelpFlag(token) {
3
+ return token === '--help' || token === '-h';
4
+ }
5
+ /** True when the arguments ask for help; checked before every other interpretation. */
6
+ export function wantsHelp(argv) {
7
+ return argv.some(isHelpFlag);
8
+ }
9
+ /** The leading tokens of `argv` that do not start with `-` (stops at the first flag). */
10
+ function leadingWords(argv) {
11
+ const words = [];
12
+ for (const token of argv) {
13
+ if (token.startsWith('-'))
14
+ break;
15
+ words.push(token);
16
+ }
17
+ return words;
18
+ }
19
+ function padRows(rows) {
20
+ const width = rows.reduce((longest, [left]) => Math.max(longest, left.length), 0);
21
+ return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`);
22
+ }
23
+ function renderRootHelp(families) {
24
+ const lines = [
25
+ 'Usage: goals <command> [options]',
26
+ '',
27
+ 'Command-line access to your Goals app data.',
28
+ '',
29
+ 'Commands:',
30
+ ...padRows(families.map((family) => [family.name, family.summary])),
31
+ '',
32
+ 'Global options:',
33
+ ...padRows([
34
+ ['--help, -h', 'Show help for a command.'],
35
+ ['--version', 'Print the installed version.'],
36
+ ]),
37
+ '',
38
+ 'Getting started:',
39
+ ' goals auth login',
40
+ ' goals auth status',
41
+ ' goals <command> --help',
42
+ ];
43
+ return `${lines.join('\n')}\n`;
44
+ }
45
+ function renderFamilyHelp(family) {
46
+ const lines = [
47
+ `Usage: goals ${family.name} <action> [options]`,
48
+ '',
49
+ family.summary,
50
+ '',
51
+ 'Actions:',
52
+ ...padRows(Object.entries(family.actions).map(([name, action]) => [name, action.summary])),
53
+ '',
54
+ `Run \`goals ${family.name} <action> --help\` for details.`,
55
+ ];
56
+ return `${lines.join('\n')}\n`;
57
+ }
58
+ function renderActionSections(action) {
59
+ const sections = [
60
+ ['Examples:', action.examples],
61
+ ['Notes:', action.notes],
62
+ ];
63
+ return sections.flatMap(([title, entries]) => entries === undefined || entries.length === 0
64
+ ? []
65
+ : ['', title, ...entries.map((entry) => ` ${entry}`)]);
66
+ }
67
+ function renderActionHelp(action) {
68
+ const lines = [
69
+ `Usage: ${action.usage}`,
70
+ '',
71
+ action.summary,
72
+ '',
73
+ 'Options:',
74
+ ...padRows(action.options.map((option) => [option.syntax, option.description])),
75
+ ...renderActionSections(action),
76
+ ];
77
+ return `${lines.join('\n')}\n`;
78
+ }
79
+ function findFamily(name, families) {
80
+ const family = families.find((candidate) => candidate.name === name);
81
+ if (family === undefined) {
82
+ throw new UsageError(`unknown command '${name}'. Run \`goals --help\` for commands.`);
83
+ }
84
+ return family;
85
+ }
86
+ function findAction(family, name) {
87
+ const action = family.actions[name];
88
+ if (action === undefined) {
89
+ throw new UsageError(`unknown action '${name}' for 'goals ${family.name}'. Run \`goals ${family.name} --help\` for actions.`);
90
+ }
91
+ return action;
92
+ }
93
+ /**
94
+ * The help page named by `argv`: no command word → root; one → family; two or more → action.
95
+ * Extra words and flags after the action are ignored. Unknown names are usage errors.
96
+ */
97
+ export function resolveHelp(argv, families) {
98
+ const [familyName, actionName] = leadingWords(argv);
99
+ if (familyName === undefined)
100
+ return renderRootHelp(families);
101
+ const family = findFamily(familyName, families);
102
+ if (actionName === undefined)
103
+ return renderFamilyHelp(family);
104
+ return renderActionHelp(findAction(family, actionName));
105
+ }