soltask 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/dist/cli.js ADDED
@@ -0,0 +1,344 @@
1
+ import { hostname } from "node:os";
2
+ import { parseArgs } from "node:util";
3
+ import { ApiClient } from "./client.js";
4
+ import { buildRegistry } from "./commands/index.js";
5
+ import { ENV_COMMUNITY, ENV_CONFIG, ENV_COOKIE, ENV_SERVER, ENV_UNLOCK_KEY, hasEnvCredentials, hasSavedCredentials, loadConfig, resolveCommunity, resolveConfigPath, resolveServer, resolveSession, sameServerOrigin, saveConfig, } from "./config.js";
6
+ import { CliError, EXIT_OK, EXIT_RUNTIME, EXIT_VALIDATION, errorToJson } from "./errors.js";
7
+ import { emitJson, errOut, out, withOutputSinks } from "./output.js";
8
+ import { errorCode, errorMessage, nonEmptyString, utcNowIso } from "./util.js";
9
+ import { PROGRAM, VERSION } from "./version.js";
10
+ const DESCRIPTION = "Zero-dependency CLI for task board management, workflow automation, and realtime monitoring";
11
+ export const GLOBAL_OPTIONS = {
12
+ server: { type: "string", placeholder: "URL", description: `Server base URL (default: ${ENV_SERVER}, then the saved login)` },
13
+ config: {
14
+ type: "string",
15
+ placeholder: "PATH",
16
+ description: `Config file (default: ${ENV_CONFIG}, then $XDG_CONFIG_HOME/soltask/config.json or ~/.config/soltask/config.json; ` +
17
+ "%APPDATA%\\soltask\\config.json on Windows)",
18
+ },
19
+ community: {
20
+ type: "string",
21
+ short: "c",
22
+ placeholder: "ID",
23
+ description: `Target community ID (default: ${ENV_COMMUNITY}, then saved config)`,
24
+ },
25
+ json: { type: "boolean", description: "Print machine-readable JSON" },
26
+ "dry-run": { type: "boolean", description: "Show what would happen without changing anything" },
27
+ "wait-live": { type: "boolean", description: "Wait for cold communities to catch up before returning status or data" },
28
+ version: { type: "boolean", short: "V", description: "Print the version and exit" },
29
+ help: { type: "boolean", short: "h", description: "Show help" },
30
+ };
31
+ function toParseOptions(...groups) {
32
+ const result = {};
33
+ for (const group of groups) {
34
+ for (const [name, spec] of Object.entries(group ?? {})) {
35
+ result[name] = {
36
+ type: spec.type,
37
+ ...(spec.short === undefined ? {} : { short: spec.short }),
38
+ ...(spec.multiple === true ? { multiple: true } : {}),
39
+ };
40
+ }
41
+ }
42
+ return result;
43
+ }
44
+ /** The first positional argument (the command or subcommand word) and where it sits, reading leniently past unknown options. */
45
+ function firstPositional(args, options) {
46
+ const { tokens } = parseArgs({ args: [...args], options, strict: false, allowPositionals: true, tokens: true });
47
+ for (const token of tokens) {
48
+ if (token.kind === "positional") {
49
+ return { value: token.value, index: token.index };
50
+ }
51
+ if (token.kind === "option-terminator") {
52
+ break;
53
+ }
54
+ }
55
+ return undefined;
56
+ }
57
+ function without(args, index) {
58
+ return args.filter((_, position) => position !== index);
59
+ }
60
+ function parseCommandLine(argv, registry) {
61
+ const path = [];
62
+ let rest = [...argv];
63
+ const first = firstPositional(rest, toParseOptions(GLOBAL_OPTIONS));
64
+ if (first?.value === "help") {
65
+ return parseCommandLine([...without(rest, first.index), "--help"], registry);
66
+ }
67
+ if (first !== undefined) {
68
+ const command = registry.find((candidate) => candidate.name === first.value);
69
+ if (command === undefined) {
70
+ throw new CliError(`Unknown command: ${first.value}. Run '${PROGRAM} --help' to list the commands.`, {
71
+ exitCode: EXIT_VALIDATION,
72
+ });
73
+ }
74
+ path.push(command);
75
+ rest = without(rest, first.index);
76
+ if (command.subcommands !== undefined) {
77
+ const second = firstPositional(rest, toParseOptions(GLOBAL_OPTIONS, command.options, ...command.subcommands.map((candidate) => candidate.options)));
78
+ if (second !== undefined) {
79
+ const sub = command.subcommands.find((candidate) => candidate.name === second.value);
80
+ if (sub === undefined) {
81
+ throw new CliError(`Unknown ${command.name} subcommand: ${second.value}`, { exitCode: EXIT_VALIDATION });
82
+ }
83
+ path.push(sub);
84
+ rest = without(rest, second.index);
85
+ }
86
+ }
87
+ }
88
+ const spec = path[path.length - 1];
89
+ let parsed;
90
+ try {
91
+ parsed = parseArgs({
92
+ args: rest,
93
+ options: toParseOptions(GLOBAL_OPTIONS, ...path.map((step) => step.options)),
94
+ strict: true,
95
+ allowPositionals: true,
96
+ });
97
+ }
98
+ catch (err) {
99
+ const message = errorMessage(err).split(". ")[0] ?? "Invalid arguments";
100
+ const unknownOption = errorCode(err) === "ERR_PARSE_ARGS_UNKNOWN_OPTION";
101
+ const where = [PROGRAM, ...path.map((step) => step.name)].join(" ");
102
+ throw new CliError(unknownOption ? `${message}. Run '${where} --help' to list its options.` : message, {
103
+ exitCode: EXIT_VALIDATION,
104
+ });
105
+ }
106
+ const values = parsed.values;
107
+ return {
108
+ path,
109
+ spec,
110
+ values,
111
+ positionals: parsed.positionals,
112
+ global: {
113
+ server: typeof values["server"] === "string" ? values["server"] : undefined,
114
+ config: typeof values["config"] === "string" ? values["config"] : undefined,
115
+ community: typeof values["community"] === "string" ? values["community"] : undefined,
116
+ json: values["json"] === true,
117
+ dryRun: values["dry-run"] === true,
118
+ waitLive: values["wait-live"] === true,
119
+ },
120
+ wantsVersion: values["version"] === true,
121
+ wantsHelp: values["help"] === true,
122
+ };
123
+ }
124
+ function checkChoices(path, values) {
125
+ for (const step of path) {
126
+ for (const [name, option] of Object.entries(step.options ?? {})) {
127
+ const value = values[name];
128
+ if (option.choices === undefined || value === undefined || typeof value === "boolean") {
129
+ continue;
130
+ }
131
+ for (const item of typeof value === "string" ? [value] : value) {
132
+ if (typeof item === "string" && !option.choices.includes(item)) {
133
+ throw new CliError(`--${name} must be one of: ${option.choices.join(", ")} (got '${item}')`, {
134
+ exitCode: EXIT_VALIDATION,
135
+ });
136
+ }
137
+ }
138
+ }
139
+ }
140
+ }
141
+ function optionLine(name, spec) {
142
+ const short = spec.short === undefined ? "" : `-${spec.short}, `;
143
+ const value = spec.type === "string" ? ` ${spec.placeholder ?? "VALUE"}` : "";
144
+ const notes = [
145
+ ...(spec.choices === undefined ? [] : [`one of: ${spec.choices.join(", ")}`]),
146
+ ...(spec.default === undefined ? [] : [`default: ${spec.default}`]),
147
+ ];
148
+ return [`${short}--${name}${value}`, notes.length === 0 ? spec.description : `${spec.description} (${notes.join("; ")})`];
149
+ }
150
+ function table(rows) {
151
+ const width = Math.max(0, ...rows.map(([left]) => left.length));
152
+ return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`);
153
+ }
154
+ function renderHelp(path, registry) {
155
+ const lines = [];
156
+ const spec = path[path.length - 1];
157
+ if (spec === undefined) {
158
+ lines.push(`${PROGRAM} ${VERSION}`, DESCRIPTION, "", `Usage: ${PROGRAM} [global options] <command> [command options]`, "", "Commands:");
159
+ lines.push(...table([
160
+ ...registry.map((command) => [command.name, command.summary]),
161
+ ["help [command]", `Show help; the same as '${PROGRAM} <command> --help'`],
162
+ ]));
163
+ }
164
+ else {
165
+ lines.push(`Usage: ${PROGRAM} [global options] ${spec.usage}`, "", spec.summary);
166
+ if (spec.subcommands !== undefined) {
167
+ lines.push("", "Subcommands:", ...table(spec.subcommands.map((sub) => [sub.name, sub.summary])));
168
+ }
169
+ const own = path.flatMap((step) => Object.entries(step.options ?? {}));
170
+ if (own.length > 0) {
171
+ lines.push("", "Options:", ...table(own.map(([name, option]) => optionLine(name, option))));
172
+ }
173
+ }
174
+ lines.push("", "Global options (accepted before or after the command):");
175
+ lines.push(...table(Object.entries(GLOBAL_OPTIONS).map(([name, option]) => optionLine(name, option))));
176
+ if (spec === undefined) {
177
+ lines.push("", `Run '${PROGRAM} <command> --help' for the options of one command.`);
178
+ }
179
+ return lines.join("\n");
180
+ }
181
+ /** Builds a diagnostic hint explaining why no session credentials resolved for `serverUrl`. */
182
+ export function buildMissingAuthHint(cfg, serverUrl, env) {
183
+ const hasCookieEnv = nonEmptyString(env[ENV_COOKIE]) !== undefined;
184
+ const hasUnlockEnv = nonEmptyString(env[ENV_UNLOCK_KEY]) !== undefined;
185
+ if (hasCookieEnv !== hasUnlockEnv) {
186
+ return `(Both ${ENV_COOKIE} and ${ENV_UNLOCK_KEY} are required for cookie auth.)`;
187
+ }
188
+ if (hasCookieEnv && hasUnlockEnv) {
189
+ return `(${ENV_COOKIE} must be formatted as name=value.)`;
190
+ }
191
+ const savedServer = nonEmptyString(cfg["server"]);
192
+ if (!hasEnvCredentials(env) && hasSavedCredentials(cfg) && savedServer !== undefined && !sameServerOrigin(serverUrl, savedServer)) {
193
+ return `(A saved login exists for ${savedServer}, which has a different origin.)`;
194
+ }
195
+ return undefined;
196
+ }
197
+ function makeContext(parsed, io) {
198
+ const configPath = resolveConfigPath(parsed.global.config, { env: io.env, platform: io.platform });
199
+ let config;
200
+ let client;
201
+ const lastString = (value) => {
202
+ if (typeof value === "string") {
203
+ return value;
204
+ }
205
+ if (Array.isArray(value)) {
206
+ for (let i = value.length - 1; i >= 0; i -= 1) {
207
+ const item = value[i];
208
+ if (typeof item === "string") {
209
+ return item;
210
+ }
211
+ }
212
+ return undefined;
213
+ }
214
+ return undefined;
215
+ };
216
+ const ctx = {
217
+ global: parsed.global,
218
+ values: parsed.values,
219
+ positionals: parsed.positionals,
220
+ io,
221
+ configPath,
222
+ config: () => {
223
+ config ??= loadConfig(configPath);
224
+ return config;
225
+ },
226
+ community: () => resolveCommunity(parsed.global.community, ctx.config(), io.env),
227
+ client: () => {
228
+ if (client === undefined) {
229
+ const cfg = ctx.config();
230
+ const serverUrl = resolveServer(parsed.global.server, cfg, io.env);
231
+ const session = resolveSession(cfg, serverUrl, io.env);
232
+ const missingAuthHint = session === null ? buildMissingAuthHint(cfg, serverUrl, io.env) : undefined;
233
+ const onCookieRenewed = session?.source === "config"
234
+ ? (cookie) => {
235
+ const updated = {
236
+ ...ctx.config(),
237
+ cookie_name: cookie.name,
238
+ cookie_value: cookie.value,
239
+ saved_at: utcNowIso(),
240
+ };
241
+ config = updated;
242
+ try {
243
+ saveConfig(configPath, updated);
244
+ }
245
+ catch (err) {
246
+ errOut(`Warning: could not persist renewed session cookie: ${errorMessage(err)}`);
247
+ }
248
+ }
249
+ : undefined;
250
+ const clientOpts = {
251
+ ...(io.sleepFn === undefined ? {} : { sleepFn: io.sleepFn }),
252
+ ...io.clientOptions,
253
+ ...(missingAuthHint === undefined ? {} : { missingAuthHint }),
254
+ ...(onCookieRenewed === undefined ? {} : { onCookieRenewed }),
255
+ };
256
+ client = new ApiClient(serverUrl, session, clientOpts);
257
+ }
258
+ return client;
259
+ },
260
+ flag: (name) => parsed.values[name] === true,
261
+ opt: (name) => lastString(parsed.values[name]),
262
+ optList: (name) => {
263
+ const value = parsed.values[name];
264
+ const items = Array.isArray(value) ? value : [value];
265
+ return items.filter((item) => typeof item === "string");
266
+ },
267
+ };
268
+ return ctx;
269
+ }
270
+ function reportError(err, json, io) {
271
+ let cliError;
272
+ if (err instanceof CliError) {
273
+ cliError = err;
274
+ }
275
+ else {
276
+ const message = `Unexpected error: ${errorMessage(err)}`;
277
+ cliError = new CliError(message, {
278
+ exitCode: EXIT_RUNTIME,
279
+ payload: { ok: false, error: "unexpected_error", message },
280
+ });
281
+ if (io.env["SOLTASK_DEBUG"] && err instanceof Error && err.stack !== undefined) {
282
+ errOut(err.stack);
283
+ }
284
+ }
285
+ if (json) {
286
+ emitJson(errorToJson(cliError));
287
+ }
288
+ else {
289
+ errOut(cliError.message);
290
+ }
291
+ return cliError.exitCode;
292
+ }
293
+ async function execute(argv, io) {
294
+ let json = argv.includes("--json");
295
+ try {
296
+ const registry = buildRegistry();
297
+ const parsed = parseCommandLine(argv, registry);
298
+ json = parsed.global.json;
299
+ if (parsed.wantsVersion) {
300
+ if (json) {
301
+ emitJson({ version: VERSION });
302
+ }
303
+ else {
304
+ out(`${PROGRAM} ${VERSION}`);
305
+ }
306
+ return EXIT_OK;
307
+ }
308
+ if (parsed.wantsHelp || parsed.spec === undefined) {
309
+ out(renderHelp(parsed.path, registry));
310
+ return EXIT_OK;
311
+ }
312
+ const spec = parsed.spec;
313
+ if (spec.handler === undefined) {
314
+ const names = (spec.subcommands ?? []).map((sub) => sub.name).join(", ");
315
+ throw new CliError(`'${spec.name}' needs a subcommand: ${names}`, { exitCode: EXIT_VALIDATION });
316
+ }
317
+ checkChoices(parsed.path, parsed.values);
318
+ const { min, max } = spec.positionals ?? { min: 0, max: 0 };
319
+ if (parsed.positionals.length < min || parsed.positionals.length > max) {
320
+ throw new CliError(`Usage: ${PROGRAM} ${spec.usage}`, { exitCode: EXIT_VALIDATION });
321
+ }
322
+ return await spec.handler(makeContext(parsed, io));
323
+ }
324
+ catch (err) {
325
+ return reportError(err, json, io);
326
+ }
327
+ }
328
+ /**
329
+ * Runs one command line and returns the exit code; it never throws and never calls `process.exit`.
330
+ * `overrides` lets tests replace streams, environment, working directory, and transport seams.
331
+ */
332
+ export async function runCli(argv, overrides = {}) {
333
+ const { stdout, stderr, ...ioOverrides } = overrides;
334
+ const io = {
335
+ stdin: process.stdin,
336
+ env: process.env,
337
+ cwd: process.cwd(),
338
+ platform: process.platform,
339
+ hostname,
340
+ nodeVersion: process.versions.node,
341
+ ...ioOverrides,
342
+ };
343
+ return withOutputSinks({ stdout: stdout ?? process.stdout, stderr: stderr ?? process.stderr }, () => execute(argv, io));
344
+ }
@@ -0,0 +1,131 @@
1
+ import { type SessionAuth } from "./config.js";
2
+ import type { CommunityView, LinkState, MeResponse, SignInResponse, StreamEvent } from "./types.js";
3
+ import { type JsonObject } from "./util.js";
4
+ export declare const UNLOCK_HEADER = "X-Task-Board-Key";
5
+ export declare const REQUEST_TIMEOUT_MS = 30000;
6
+ export declare const MAX_RESPONSE_BYTES: number;
7
+ export declare const MAX_RATE_LIMIT_RETRIES = 2;
8
+ export declare const MAX_RETRY_SLEEP_MS = 5000;
9
+ export declare const DEFAULT_WAIT_LIVE_TIMEOUT_MS = 15000;
10
+ export declare const WAIT_LIVE_POLL_MS = 250;
11
+ export interface ParsedCookie {
12
+ name: string;
13
+ value: string;
14
+ cleared: boolean;
15
+ }
16
+ export interface ApiClientOptions {
17
+ timeoutMs?: number;
18
+ maxResponseBytes?: number;
19
+ /** Extra diagnostic sentence appended when an authenticated call has no session configured. */
20
+ missingAuthHint?: string;
21
+ /** Invoked whenever the server sends a non-empty `Set-Cookie` on an authenticated response. */
22
+ onCookieRenewed?: (cookie: {
23
+ name: string;
24
+ value: string;
25
+ }) => void;
26
+ /** Test seam: the `fetch` implementation. */
27
+ fetchFn?: typeof fetch;
28
+ /** Test seam: how waits (rate-limit backoff, waitUntilLive polling) sleep. */
29
+ sleepFn?: (ms: number, signal?: AbortSignal) => Promise<void>;
30
+ }
31
+ export interface RequestOptions {
32
+ query?: Readonly<Record<string, unknown>>;
33
+ jsonBody?: unknown;
34
+ headers?: Readonly<Record<string, string>>;
35
+ /** Sets `If-None-Match` and automatically permits HTTP 304 responses. */
36
+ etag?: string;
37
+ /** Send session credentials and refuse to run without them (default true). */
38
+ requireAuth?: boolean;
39
+ /** HTTP statuses returned to the caller instead of raised as errors. */
40
+ allowStatuses?: readonly number[];
41
+ /** Automatically retry HTTP 429 responses carrying a short Retry-After (default true). */
42
+ retryRateLimit?: boolean;
43
+ signal?: AbortSignal;
44
+ }
45
+ export interface ApiResponse<T = unknown> {
46
+ status: number;
47
+ /** Response headers, lower-cased. */
48
+ headers: Record<string, string>;
49
+ /** Parsed session `Set-Cookie` header when present. */
50
+ setCookie: ParsedCookie | null;
51
+ /** Response `ETag` header when present. */
52
+ etag: string | null;
53
+ body: T;
54
+ }
55
+ export interface WaitLiveResult {
56
+ communities: CommunityView[];
57
+ statuses: Record<string, LinkState>;
58
+ allLive: boolean;
59
+ waitedMs: number;
60
+ timedOut: boolean;
61
+ }
62
+ export interface StreamEventsOptions {
63
+ signal?: AbortSignal;
64
+ headers?: Readonly<Record<string, string>>;
65
+ }
66
+ /**
67
+ * Milliseconds to wait for a numeric `Retry-After` (seconds); null when absent, non-numeric, or > `MAX_RETRY_SLEEP_MS`.
68
+ */
69
+ export declare function retryDelayMs(header: string | undefined): number | null;
70
+ /**
71
+ * Extracts a `Set-Cookie` entry from `Headers` (via `getSetCookie()` when available) or raw header strings.
72
+ * Prefers `preferredName`, then any `task_board_session*` cookie, then the first valid cookie.
73
+ */
74
+ export declare function parseSetCookie(headers: Headers | readonly string[], preferredName?: string): ParsedCookie | null;
75
+ /** A short, safe description of a body that is not JSON: never the raw page, at most one trimmed line. */
76
+ export declare function describeNonJson(text: string, contentType: string): string;
77
+ export declare class ApiClient {
78
+ readonly serverUrl: string;
79
+ private currentSession;
80
+ private readonly timeoutMs;
81
+ private readonly maxResponseBytes;
82
+ private readonly missingAuthHint;
83
+ private readonly onCookieRenewed;
84
+ private readonly fetchFn;
85
+ private readonly sleepFn;
86
+ private warnedCleartext;
87
+ private warnedProtocol;
88
+ private minProtocolRequired;
89
+ constructor(serverUrl: string, session?: SessionAuth | null, options?: ApiClientOptions);
90
+ get session(): SessionAuth | null;
91
+ /** Higher protocol version advertised by the server's CLI min-version header, or null when compatible/absent. */
92
+ get requiredProtocolVersion(): number | null;
93
+ private checkProtocolHeader;
94
+ private maybeRenewCookie;
95
+ private buildUrl;
96
+ private attachAuthHeaders;
97
+ private rejectRedirect;
98
+ private attempt;
99
+ private readBounded;
100
+ private mapTransportError;
101
+ /** Throws `EXIT_AUTH` (`not_logged_in`) when no session credentials are configured. */
102
+ assertAuthenticated(): void;
103
+ /** Sends one HTTP request and returns the parsed JSON response (object, array, or undefined for 204/304). */
104
+ request<T = JsonObject>(method: string, path: string, options?: RequestOptions): Promise<ApiResponse<T>>;
105
+ private finish;
106
+ private buildHttpError;
107
+ /** Signs in with an `nsec` secret key (never stored or echoed by this client). */
108
+ signIn(nsec: string, signal?: AbortSignal): Promise<{
109
+ data: SignInResponse;
110
+ cookie: ParsedCookie | null;
111
+ }>;
112
+ /** Signs out the current session on the server (`DELETE /api/session`), allowing `401` if already expired. */
113
+ signOut(signal?: AbortSignal): Promise<{
114
+ revoked: boolean;
115
+ status: number;
116
+ }>;
117
+ /** Fetches the authenticated user's profile and communities (`GET /api/me`). */
118
+ me(signal?: AbortSignal): Promise<MeResponse>;
119
+ /** Lists configured communities with sync status and joined channels (`GET /api/communities`). */
120
+ communities(signal?: AbortSignal): Promise<CommunityView[]>;
121
+ /**
122
+ * Polls `GET /api/communities` while any target community reports `connecting` or `closed` (cold-vault catch-up),
123
+ * until all targets leave those states or `timeoutMs` elapses. Returns the final status map without failing on degraded.
124
+ */
125
+ waitUntilLive(communities?: readonly string[], timeoutMs?: number, signal?: AbortSignal): Promise<WaitLiveResult>;
126
+ /**
127
+ * Connects to `GET /api/stream` over native `fetch`, parses multi-chunk SSE frames (`task`, `typing`, `status`),
128
+ * skips `: keepalive` comments, and exits cleanly when `signal` aborts or when the server closes the stream.
129
+ */
130
+ streamEvents(options?: StreamEventsOptions): AsyncGenerator<StreamEvent, void, void>;
131
+ }