@jinshuju/cli 0.1.3 → 0.3.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 (59) hide show
  1. package/README.md +80 -1
  2. package/dist/args.d.ts +47 -0
  3. package/dist/args.js +185 -0
  4. package/dist/auth.js +43 -11
  5. package/dist/cli-bin.js +1 -1
  6. package/dist/cli.d.ts +2 -20
  7. package/dist/cli.js +71 -659
  8. package/dist/commands/account.d.ts +2 -0
  9. package/dist/commands/account.js +20 -0
  10. package/dist/commands/comment.d.ts +2 -0
  11. package/dist/commands/comment.js +66 -0
  12. package/dist/commands/entry.d.ts +31 -0
  13. package/dist/commands/entry.js +723 -0
  14. package/dist/commands/field.d.ts +3 -0
  15. package/dist/commands/field.js +261 -0
  16. package/dist/commands/folder.d.ts +2 -0
  17. package/dist/commands/folder.js +31 -0
  18. package/dist/commands/form.d.ts +2 -0
  19. package/dist/commands/form.js +412 -0
  20. package/dist/commands/index.d.ts +16 -0
  21. package/dist/commands/index.js +68 -0
  22. package/dist/commands/local.d.ts +10 -0
  23. package/dist/commands/local.js +76 -0
  24. package/dist/commands/opensearch.d.ts +2 -0
  25. package/dist/commands/opensearch.js +73 -0
  26. package/dist/commands/shared.d.ts +57 -0
  27. package/dist/commands/shared.js +122 -0
  28. package/dist/commands/table.d.ts +2 -0
  29. package/dist/commands/table.js +101 -0
  30. package/dist/{commands.d.ts → commands/types.d.ts} +24 -30
  31. package/dist/commands/types.js +1 -0
  32. package/dist/commands/upload.d.ts +7 -0
  33. package/dist/commands/upload.js +40 -0
  34. package/dist/commands/view.d.ts +2 -0
  35. package/dist/commands/view.js +81 -0
  36. package/dist/config.d.ts +2 -0
  37. package/dist/config.js +45 -5
  38. package/dist/errors.d.ts +48 -0
  39. package/dist/errors.js +99 -0
  40. package/dist/help.d.ts +1 -1
  41. package/dist/help.js +11 -1
  42. package/dist/http.d.ts +37 -4
  43. package/dist/http.js +119 -14
  44. package/dist/local.d.ts +24 -0
  45. package/dist/local.js +208 -0
  46. package/dist/options.d.ts +8 -4
  47. package/dist/options.js +63 -18
  48. package/dist/payload.d.ts +14 -8
  49. package/dist/payload.js +22 -54
  50. package/dist/render.d.ts +21 -0
  51. package/dist/render.js +315 -0
  52. package/dist/result.d.ts +31 -0
  53. package/dist/result.js +32 -0
  54. package/dist/values.d.ts +4 -0
  55. package/dist/values.js +8 -0
  56. package/dist/version.d.ts +6 -0
  57. package/dist/version.js +16 -0
  58. package/package.json +23 -18
  59. package/dist/commands.js +0 -1690
package/dist/errors.js ADDED
@@ -0,0 +1,99 @@
1
+ /** The command line itself was wrong: a flag, an argument, an input file. */
2
+ export class UsageError extends Error {
3
+ name = 'UsageError';
4
+ }
5
+ /** No credential, or one the server would not take. */
6
+ export class AuthError extends Error {
7
+ name = 'AuthError';
8
+ }
9
+ /** A response the server sent and refused with. `status` and `body` are what it said. */
10
+ export class HttpError extends Error {
11
+ status;
12
+ body;
13
+ constructor(message, status, body) {
14
+ super(message);
15
+ this.status = status;
16
+ this.body = body;
17
+ this.name = 'HttpError';
18
+ }
19
+ }
20
+ /** No response at all: the connection failed, or the request ran out of time. */
21
+ export class TransportError extends Error {
22
+ timedOut;
23
+ constructor(message, timedOut, cause) {
24
+ super(message, { cause });
25
+ this.timedOut = timedOut;
26
+ this.name = 'TransportError';
27
+ }
28
+ }
29
+ /**
30
+ * The server took the request and turned down what it carried: an import
31
+ * whose rows it would not write, say. Exits as a refused 4xx would.
32
+ */
33
+ export class RefusedError extends Error {
34
+ name = 'RefusedError';
35
+ }
36
+ export const EXIT_CODES = {
37
+ unexpected: 1,
38
+ usage: 2,
39
+ auth: 3,
40
+ not_found: 4,
41
+ refused: 5,
42
+ server: 6,
43
+ transport: 7,
44
+ // Neither the caller's fault nor permanent: it wants waiting, not a corrected request.
45
+ rate_limited: 8
46
+ };
47
+ function kindOfStatus(status) {
48
+ if (status === 429)
49
+ return 'rate_limited';
50
+ if (status === 401 || status === 403)
51
+ return 'auth';
52
+ if (status === 404)
53
+ return 'not_found';
54
+ if (status >= 500)
55
+ return 'server';
56
+ if (status >= 400)
57
+ return 'refused';
58
+ // A 2xx that reached here carried a body nobody could read.
59
+ return 'server';
60
+ }
61
+ /** A rate limit's body carries how long to wait; it is the one number worth lifting out. */
62
+ function retryAfterIn(body) {
63
+ const value = body?.retry_after;
64
+ return typeof value === 'number' ? value : undefined;
65
+ }
66
+ /**
67
+ * Sorts a failure into its kind. An error that wraps another — "the form was
68
+ * created, but its settings were refused" — is sorted by what it wraps, so a
69
+ * partial failure exits the way its refused half would have.
70
+ */
71
+ export function classify(error) {
72
+ const message = error instanceof Error ? error.message : String(error);
73
+ if (error instanceof UsageError)
74
+ return { kind: 'usage', exitCode: EXIT_CODES.usage, message };
75
+ if (error instanceof AuthError)
76
+ return { kind: 'auth', exitCode: EXIT_CODES.auth, message };
77
+ if (error instanceof RefusedError)
78
+ return { kind: 'refused', exitCode: EXIT_CODES.refused, message };
79
+ if (error instanceof TransportError)
80
+ return { kind: 'transport', exitCode: EXIT_CODES.transport, message };
81
+ if (error instanceof HttpError) {
82
+ const kind = kindOfStatus(error.status);
83
+ const retry_after = retryAfterIn(error.body);
84
+ return {
85
+ kind,
86
+ exitCode: EXIT_CODES[kind],
87
+ message,
88
+ status: error.status,
89
+ body: error.body,
90
+ ...(retry_after === undefined ? {} : { retry_after })
91
+ };
92
+ }
93
+ const cause = error?.cause;
94
+ if (cause instanceof Error && cause !== error) {
95
+ const inner = classify(cause);
96
+ return { ...inner, message };
97
+ }
98
+ return { kind: 'unexpected', exitCode: EXIT_CODES.unexpected, message };
99
+ }
package/dist/help.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Command } from './commands.js';
1
+ import { type Command } from './commands/index.js';
2
2
  /**
3
3
  * Help is rendered from the command table, so a command cannot be reachable
4
4
  * without appearing here, and a flag cannot be accepted without being
package/dist/help.js CHANGED
@@ -1,4 +1,5 @@
1
- import { COMMANDS, RESOURCES, findCommand } from './commands.js';
1
+ import { COMMANDS, RESOURCES, findCommand } from './commands/index.js';
2
+ import { EXIT_CODES } from './errors.js';
2
3
  import { GLOBAL_OPTIONS, optionKey } from './options.js';
3
4
  /**
4
5
  * Help is rendered from the command table, so a command cannot be reachable
@@ -20,6 +21,13 @@ export function rootHelp(commands = COMMANDS) {
20
21
  ...GLOBAL_OPTIONS.map((option) => ` ${flagLabel(option).padEnd(width + 12)}${option.description}`),
21
22
  '',
22
23
  'Run `jinshuju <resource> --help` to see its verbs.',
24
+ '`jsj` is the same command, for typing less.',
25
+ '',
26
+ 'Exit codes: 0 ok, ' +
27
+ `${EXIT_CODES.unexpected} unexpected, ${EXIT_CODES.usage} usage, ${EXIT_CODES.auth} authentication, ` +
28
+ `${EXIT_CODES.not_found} not found, ${EXIT_CODES.refused} refused by the API, ${EXIT_CODES.server} server failure, ` +
29
+ `${EXIT_CODES.transport} no connection or timed out, ${EXIT_CODES.rate_limited} rate limited (wait and retry; ` +
30
+ '--output json carries retry_after).',
23
31
  ''
24
32
  ].join('\n');
25
33
  }
@@ -29,11 +37,13 @@ export function resourceHelp(resource, commands = COMMANDS) {
29
37
  if (owned.length === 0)
30
38
  return rootHelp(commands);
31
39
  const width = Math.max(...owned.map((command) => command.path.join(' ').length)) + 4;
40
+ const note = RESOURCES.find((entry) => entry.name === resource)?.note;
32
41
  return [
33
42
  `Usage: jinshuju ${resource} <verb> [args] [flags]`,
34
43
  '',
35
44
  'Commands:',
36
45
  ...owned.map((command) => ` ${command.path.join(' ').padEnd(width)}${command.summary}`),
46
+ ...(note ? ['', note] : []),
37
47
  '',
38
48
  `Run \`jinshuju ${resource} <verb> --help\` for one of them.`,
39
49
  ''
package/dist/http.d.ts CHANGED
@@ -1,8 +1,13 @@
1
1
  import { type LoadedConfig } from './config.js';
2
- export type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE';
2
+ export { HttpError, TransportError } from './errors.js';
3
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
4
+ /** A repeated parameter arrives as a list; everything else is one value. */
5
+ export type QueryValues = Record<string, string | readonly string[] | undefined>;
3
6
  export type HttpRequest = {
4
- method: HttpMethod | string;
7
+ method: HttpMethod;
5
8
  path: string;
9
+ /** The query string, as values; how they are spelled on the wire is this module's business. */
10
+ query?: QueryValues;
6
11
  body?: unknown;
7
12
  /**
8
13
  * A multipart body, for the three endpoints that take a file. fetch sets its
@@ -13,12 +18,40 @@ export type HttpRequest = {
13
18
  export interface HttpClient {
14
19
  request<T>(request: HttpRequest): Promise<T>;
15
20
  }
21
+ /**
22
+ * The path with its query string. A list value repeats its parameter as
23
+ * `name[]=a&name[]=b`, which is how Rails reads a list. Joining them with a
24
+ * comma would ask for one keyword containing a comma instead of two keywords.
25
+ */
26
+ export declare function withQuery(path: string, query?: QueryValues): string;
27
+ export type HttpClientOptions = {
28
+ /** How long one attempt may take. */
29
+ timeoutMs?: number;
30
+ /** How many times a retryable failure is tried again. */
31
+ retries?: number;
32
+ /** How to wait between attempts; tests replace it so nothing actually sleeps. */
33
+ sleep?: (ms: number) => Promise<void>;
34
+ };
35
+ /**
36
+ * A minute: long enough for an upload or a `--all` page on a slow link, short
37
+ * enough that a connection the network dropped does not hold a script forever.
38
+ */
39
+ export declare const DEFAULT_TIMEOUT_MS = 60000;
40
+ export declare const DEFAULT_RETRIES = 3;
16
41
  export declare class JinshujuHttpClient implements HttpClient {
17
42
  private config;
18
- private readonly baseUrl;
19
- constructor(config?: LoadedConfig, baseUrl?: string);
43
+ private readonly timeoutMs;
44
+ private readonly retries;
45
+ private readonly sleep;
46
+ constructor(config?: LoadedConfig, options?: HttpClientOptions);
20
47
  request<T>(request: HttpRequest): Promise<T>;
21
48
  private requestWithAuth;
49
+ /**
50
+ * One request, tried again when trying again is safe and could help. Every
51
+ * attempt has its own deadline; without one a connection the network quietly
52
+ * dropped would hold the command open for as long as the caller waited.
53
+ */
54
+ private send;
22
55
  /**
23
56
  * An explicitly configured credential outranks a stored session: someone who
24
57
  * set a token in the environment meant this request to use it, and finding a
package/dist/http.js CHANGED
@@ -1,5 +1,46 @@
1
1
  import { loadConfig } from './config.js';
2
2
  import { refreshOAuthToken, shouldRefresh } from './auth.js';
3
+ import { AuthError, HttpError, TransportError } from './errors.js';
4
+ export { HttpError, TransportError } from './errors.js';
5
+ import { VERSION } from './version.js';
6
+ /**
7
+ * The path with its query string. A list value repeats its parameter as
8
+ * `name[]=a&name[]=b`, which is how Rails reads a list. Joining them with a
9
+ * comma would ask for one keyword containing a comma instead of two keywords.
10
+ */
11
+ export function withQuery(path, query) {
12
+ const params = new URLSearchParams();
13
+ for (const [name, value] of Object.entries(query ?? {})) {
14
+ if (value === undefined)
15
+ continue;
16
+ if (typeof value === 'string') {
17
+ params.set(name, value);
18
+ }
19
+ else {
20
+ for (const item of value)
21
+ params.append(`${name}[]`, item);
22
+ }
23
+ }
24
+ const search = params.toString();
25
+ return search ? `${path}?${search}` : path;
26
+ }
27
+ /**
28
+ * A minute: long enough for an upload or a `--all` page on a slow link, short
29
+ * enough that a connection the network dropped does not hold a script forever.
30
+ */
31
+ export const DEFAULT_TIMEOUT_MS = 60_000;
32
+ export const DEFAULT_RETRIES = 3;
33
+ /** Backoff between attempts when the server does not say how long to wait. */
34
+ const BACKOFF_BASE_MS = 500;
35
+ const BACKOFF_CAP_MS = 8_000;
36
+ /**
37
+ * A 429 and a 503 say "not now", whatever the request was; the server has not
38
+ * acted on it. The other server-side failures are retried only for a read: a
39
+ * POST that timed out at a gateway may well have landed, and sending it again
40
+ * would create the entry twice.
41
+ */
42
+ const RETRY_ANY = new Set([429, 503]);
43
+ const RETRY_READS = new Set([500, 502, 504]);
3
44
  /** How much of an unexpected body is worth putting in front of a reader. */
4
45
  const MAX_SNIPPET = 200;
5
46
  function parseBody(text) {
@@ -59,12 +100,46 @@ function rowErrors(body) {
59
100
  });
60
101
  return `${lines.length} row${lines.length === 1 ? '' : 's'} rejected — ${lines.join('; ')}`;
61
102
  }
103
+ /**
104
+ * `Retry-After` is seconds or an HTTP date. Either becomes a wait in
105
+ * milliseconds; anything else means the server gave no usable answer.
106
+ */
107
+ function retryAfterMs(response) {
108
+ const header = response.headers.get('retry-after');
109
+ if (!header)
110
+ return undefined;
111
+ if (/^\d+$/.test(header))
112
+ return Number.parseInt(header, 10) * 1000;
113
+ const at = Date.parse(header);
114
+ return Number.isNaN(at) ? undefined : Math.max(0, at - Date.now());
115
+ }
116
+ /** Doubling from half a second, with a little jitter so retries do not march in step. */
117
+ function backoffMs(attempt) {
118
+ const base = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);
119
+ return Math.round(base * (0.75 + Math.random() * 0.5));
120
+ }
121
+ function isTimeout(error) {
122
+ const name = error?.name;
123
+ return name === 'TimeoutError' || name === 'AbortError';
124
+ }
125
+ function describeTransport(error) {
126
+ const cause = error?.cause;
127
+ const detail = cause?.code ?? cause?.message ?? error?.message ?? String(error);
128
+ return `could not reach the server: ${detail}`;
129
+ }
130
+ function wait(ms) {
131
+ return new Promise((resolve) => setTimeout(resolve, ms));
132
+ }
62
133
  export class JinshujuHttpClient {
63
134
  config;
64
- baseUrl;
65
- constructor(config = loadConfig(), baseUrl = config.host) {
135
+ timeoutMs;
136
+ retries;
137
+ sleep;
138
+ constructor(config = loadConfig(), options = {}) {
66
139
  this.config = config;
67
- this.baseUrl = baseUrl;
140
+ this.timeoutMs = options.timeoutMs ?? config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
141
+ this.retries = options.retries ?? DEFAULT_RETRIES;
142
+ this.sleep = options.sleep ?? wait;
68
143
  }
69
144
  async request(request) {
70
145
  return this.requestWithAuth(request, true);
@@ -72,18 +147,16 @@ export class JinshujuHttpClient {
72
147
  async requestWithAuth(request, allowRefresh) {
73
148
  const headers = {
74
149
  Authorization: await this.authorizationHeader(),
75
- Accept: 'application/json'
150
+ Accept: 'application/json',
151
+ 'User-Agent': `jinshuju-cli/${VERSION} node/${process.versions.node}`
76
152
  };
77
153
  if (!request.form)
78
154
  headers['Content-Type'] = 'application/json';
79
- const response = await fetch(`${this.baseUrl}${request.path}`, {
80
- method: request.method,
81
- headers,
82
- body: request.form ?? (request.body === undefined ? undefined : JSON.stringify(request.body))
83
- });
155
+ const response = await this.send(request, headers);
84
156
  // Only an OAuth session can be refreshed; an access token that stopped
85
157
  // working has to be replaced by whoever issued it.
86
158
  if (response.status === 401 && allowRefresh && !this.config.accessToken && this.config.auth?.refresh_token) {
159
+ await response.text();
87
160
  this.config.auth = await refreshOAuthToken(this.config);
88
161
  return this.requestWithAuth(request, false);
89
162
  }
@@ -94,15 +167,47 @@ export class JinshujuHttpClient {
94
167
  // turned both into "Unexpected token '<'", throwing away the status that was
95
168
  // the only thing that said what had happened.
96
169
  if (!response.ok) {
97
- const error = new Error(describeFailure(response, text, parsed));
98
- Object.assign(error, { status: response.status, body: parsed.json ? parsed.value : text });
99
- throw error;
170
+ throw new HttpError(describeFailure(response, text, parsed), response.status, parsed.json ? parsed.value : text);
100
171
  }
101
172
  if (!parsed.json) {
102
- throw new Error(`${response.status} ${response.statusText}, but the body is not JSON: ${snippet(text)}`);
173
+ throw new HttpError(`${response.status} ${response.statusText}, but the body is not JSON: ${snippet(text)}`, response.status, text);
103
174
  }
104
175
  return parsed.value;
105
176
  }
177
+ /**
178
+ * One request, tried again when trying again is safe and could help. Every
179
+ * attempt has its own deadline; without one a connection the network quietly
180
+ * dropped would hold the command open for as long as the caller waited.
181
+ */
182
+ async send(request, headers) {
183
+ const read = request.method === 'GET';
184
+ for (let attempt = 0;; attempt += 1) {
185
+ const last = attempt >= this.retries;
186
+ let response;
187
+ try {
188
+ response = await fetch(`${this.config.host}${withQuery(request.path, request.query)}`, {
189
+ method: request.method,
190
+ headers,
191
+ body: request.form ?? (request.body === undefined ? undefined : JSON.stringify(request.body)),
192
+ signal: AbortSignal.timeout(this.timeoutMs)
193
+ });
194
+ }
195
+ catch (error) {
196
+ const timedOut = isTimeout(error);
197
+ if (read && !last) {
198
+ await this.sleep(backoffMs(attempt));
199
+ continue;
200
+ }
201
+ throw new TransportError(timedOut ? `request timed out after ${this.timeoutMs}ms` : describeTransport(error), timedOut, error);
202
+ }
203
+ const again = RETRY_ANY.has(response.status) || (read && RETRY_READS.has(response.status));
204
+ if (!again || last)
205
+ return response;
206
+ // The body is drained so the connection goes back to the pool.
207
+ await response.text();
208
+ await this.sleep(retryAfterMs(response) ?? backoffMs(attempt));
209
+ }
210
+ }
106
211
  /**
107
212
  * An explicitly configured credential outranks a stored session: someone who
108
213
  * set a token in the environment meant this request to use it, and finding a
@@ -122,6 +227,6 @@ export class JinshujuHttpClient {
122
227
  }
123
228
  return `Bearer ${this.config.auth.access_token}`;
124
229
  }
125
- throw new Error('Missing authentication. Run `jinshuju auth login`, or configure JINSHUJU_ACCESS_TOKEN, or JINSHUJU_API_KEY with JINSHUJU_API_SECRET.');
230
+ throw new AuthError('Missing authentication. Run `jinshuju auth login`, or configure JINSHUJU_ACCESS_TOKEN, or JINSHUJU_API_KEY with JINSHUJU_API_SECRET.');
126
231
  }
127
232
  }
@@ -0,0 +1,24 @@
1
+ import { type OutputFormat } from './options.js';
2
+ import { type CliResult, type CliRuntime } from './result.js';
3
+ /**
4
+ * The commands that never reach the API: they read and write the config file,
5
+ * or run a browser login. They are dispatched by name here rather than through
6
+ * the command table, because what they do is not a request.
7
+ */
8
+ /** Everything the local (auth, config) commands read off the command line. */
9
+ type LocalOptions = {
10
+ output: OutputFormat;
11
+ configPath: string;
12
+ apiKey?: string;
13
+ apiSecret?: string;
14
+ host?: string;
15
+ authHost?: string;
16
+ clientId?: string;
17
+ scopes?: string;
18
+ noOpen: boolean;
19
+ verify: boolean;
20
+ showSecret: boolean;
21
+ };
22
+ export declare function localOptions(flags: Record<string, unknown>, stdin: () => string): LocalOptions;
23
+ export declare function runLocal(words: readonly string[], flags: Record<string, unknown>, runtime: CliRuntime, stdin: () => string): Promise<CliResult>;
24
+ export {};
package/dist/local.js ADDED
@@ -0,0 +1,208 @@
1
+ import { loginWithOAuth, refreshOAuthToken, revokeOAuthToken } from './auth.js';
2
+ import { bindOptions } from './args.js';
3
+ import { assertConfigKey, defaultConfigPath, getConfig, loadConfig, maskSecret, setConfigValue, unsetConfigValue } from './config.js';
4
+ import { JinshujuHttpClient } from './http.js';
5
+ import { GLOBAL_OPTIONS, LOCAL_OPTIONS, UsageError } from './options.js';
6
+ import { format } from './render.js';
7
+ import { ok, unknown } from './result.js';
8
+ import { isRecord } from './values.js';
9
+ export function localOptions(flags, stdin) {
10
+ const bound = bindOptions([...GLOBAL_OPTIONS, ...LOCAL_OPTIONS], flags, 'this command', stdin);
11
+ return {
12
+ output: bound.output ?? 'text',
13
+ configPath: bound.config ?? defaultConfigPath,
14
+ apiKey: bound.api_key,
15
+ apiSecret: bound.api_secret,
16
+ host: bound.host,
17
+ authHost: bound.auth_host,
18
+ clientId: bound.client_id,
19
+ scopes: bound.scopes,
20
+ noOpen: Boolean(bound.no_open),
21
+ verify: Boolean(bound.verify),
22
+ showSecret: Boolean(bound.show_secret)
23
+ };
24
+ }
25
+ export async function runLocal(words, flags, runtime, stdin) {
26
+ const options = localOptions(flags, stdin);
27
+ const key = words.slice(0, 2).join(' ');
28
+ switch (key) {
29
+ case 'auth login':
30
+ return await authLogin(options, runtime);
31
+ case 'auth status':
32
+ return await authStatus(options, runtime);
33
+ case 'auth refresh':
34
+ return await authRefresh(options, runtime);
35
+ case 'auth logout':
36
+ return await authLogout(options, runtime);
37
+ case 'config get':
38
+ return configGet(words, options);
39
+ case 'config set':
40
+ return configSet(words, options);
41
+ case 'config unset':
42
+ return configUnset(words, options);
43
+ default:
44
+ return unknown(words, options.output);
45
+ }
46
+ }
47
+ function requireArg(value, name) {
48
+ if (!value)
49
+ throw new UsageError(`Missing argument <${name}>`);
50
+ return value;
51
+ }
52
+ function createClient(options, runtime) {
53
+ return (runtime.client ??
54
+ new JinshujuHttpClient(loadConfig({
55
+ configPath: options.configPath,
56
+ env: runtime.env,
57
+ cli: { apiKey: options.apiKey, apiSecret: options.apiSecret, host: options.host }
58
+ })));
59
+ }
60
+ async function authLogin(options, runtime) {
61
+ const result = await loginWithOAuth({
62
+ configPath: options.configPath,
63
+ env: runtime.env,
64
+ host: options.host,
65
+ authHost: options.authHost,
66
+ clientId: options.clientId,
67
+ scopes: options.scopes,
68
+ openBrowser: !options.noOpen
69
+ });
70
+ const payload = {
71
+ authenticated: true,
72
+ mode: 'oauth',
73
+ auth_host: result.token.auth_host,
74
+ client_id: result.token.client_id,
75
+ scope: result.token.scope,
76
+ expires_at: result.token.expires_at
77
+ };
78
+ if (options.output !== 'text')
79
+ return ok(format(payload, options.output, 0));
80
+ return ok(`Authenticated with OAuth.\nConfig: ${options.configPath}`);
81
+ }
82
+ async function authStatus(options, runtime) {
83
+ const config = loadConfig({
84
+ configPath: options.configPath,
85
+ env: runtime.env,
86
+ cli: {
87
+ apiKey: options.apiKey,
88
+ apiSecret: options.apiSecret,
89
+ host: options.host,
90
+ authHost: options.authHost,
91
+ clientId: options.clientId
92
+ }
93
+ });
94
+ const authenticated = Boolean(config.accessToken || (config.apiKey && config.apiSecret) || config.auth?.access_token);
95
+ const mode = config.accessToken
96
+ ? 'access_token'
97
+ : config.apiKey && config.apiSecret
98
+ ? 'api_key_secret'
99
+ : config.auth?.access_token
100
+ ? 'oauth'
101
+ : 'none';
102
+ const payload = {
103
+ authenticated,
104
+ mode,
105
+ host: config.host,
106
+ auth_host: config.authHost,
107
+ sources: config.sources,
108
+ source: mode === 'access_token'
109
+ ? config.sources.accessToken
110
+ : mode === 'api_key_secret'
111
+ ? config.sources.apiKey
112
+ : mode === 'oauth'
113
+ ? config.sources.auth
114
+ : 'missing',
115
+ oauth: config.auth
116
+ ? {
117
+ client_id: config.auth.client_id,
118
+ scope: config.auth.scope,
119
+ expires_at: config.auth.expires_at,
120
+ has_refresh_token: Boolean(config.auth.refresh_token)
121
+ }
122
+ : undefined
123
+ };
124
+ // The call --verify already spends is enough to say *whose* credential this
125
+ // is, which is the question behind asking. Swapping tokens changes nothing in
126
+ // this output otherwise, and a caller with two accounts cannot tell which one
127
+ // it is about to write to.
128
+ const account = options.verify && authenticated ? await identify(createClient(options, runtime)) : undefined;
129
+ const full = { ...payload, ...(account ? { account } : {}) };
130
+ if (options.output !== 'text')
131
+ return ok(format(full, options.output, 0));
132
+ const whose = account ? ` Account: ${account.name}${account.plan ? ` (${account.plan})` : ''}.` : '';
133
+ if (mode === 'access_token')
134
+ return ok(`Authenticated with an access token (from ${config.sources.accessToken}).${whose}`);
135
+ if (mode === 'oauth')
136
+ return ok(`Authenticated with OAuth.${whose}`);
137
+ if (mode === 'api_key_secret')
138
+ return ok(`Authenticated with API Key / Secret.${whose}`);
139
+ return ok('Missing authentication. Run `jinshuju auth login`, or set an access token, or configure API Key / Secret.');
140
+ }
141
+ /**
142
+ * Who the credential belongs to. Reading the account proves the credential works
143
+ * — which is all --verify used to do with it — and answers the question that
144
+ * makes anyone ask: with two accounts configured, which one is this?
145
+ */
146
+ async function identify(client) {
147
+ const body = await client.request({ method: 'GET', path: '/api/v1/billing_account' });
148
+ const plan = isRecord(body.plan) ? body.plan.name : undefined;
149
+ return {
150
+ id: typeof body.id === 'string' ? body.id : undefined,
151
+ name: typeof body.name === 'string' ? body.name : undefined,
152
+ plan: typeof plan === 'string' ? plan : undefined
153
+ };
154
+ }
155
+ async function authRefresh(options, runtime) {
156
+ const config = loadConfig({
157
+ configPath: options.configPath,
158
+ env: runtime.env,
159
+ cli: { host: options.host, authHost: options.authHost, clientId: options.clientId }
160
+ });
161
+ const auth = await refreshOAuthToken(config);
162
+ if (options.output !== 'text')
163
+ return ok(format({ authenticated: true, mode: 'oauth', expires_at: auth.expires_at, scope: auth.scope }, options.output, 0));
164
+ return ok('OAuth token refreshed.');
165
+ }
166
+ async function authLogout(options, runtime) {
167
+ const config = loadConfig({ configPath: options.configPath, env: runtime.env });
168
+ await revokeOAuthToken(config);
169
+ return ok(options.output !== 'text' ? format({ authenticated: false }, options.output, 0) : 'Logged out.');
170
+ }
171
+ function configGet(positionals, options) {
172
+ const requestedKey = positionals[2];
173
+ if (requestedKey)
174
+ assertConfigKey(requestedKey);
175
+ const config = getConfig(options.configPath);
176
+ const secrets = new Set(['access_token', 'api_key', 'api_secret']);
177
+ const renderValue = (key, value) => options.showSecret || !secrets.has(key) ? value : maskSecret(value);
178
+ let payload;
179
+ if (requestedKey) {
180
+ const configKey = requestedKey;
181
+ payload = { [configKey]: renderValue(configKey, config[configKey]) };
182
+ }
183
+ else {
184
+ payload = {
185
+ access_token: renderValue('access_token', config.access_token),
186
+ api_key: renderValue('api_key', config.api_key),
187
+ api_secret: renderValue('api_secret', config.api_secret)
188
+ };
189
+ }
190
+ if (options.output !== 'text')
191
+ return ok(format(payload, options.output, 0));
192
+ return ok(Object.entries(payload)
193
+ .map(([k, v]) => `${k}: ${v ?? '(unset)'}`)
194
+ .join('\n'));
195
+ }
196
+ function configSet(positionals, options) {
197
+ const key = requireArg(positionals[2], 'key');
198
+ assertConfigKey(key);
199
+ const value = requireArg(positionals[3], 'value');
200
+ setConfigValue(options.configPath, key, value);
201
+ return ok(`Set ${key}`);
202
+ }
203
+ function configUnset(positionals, options) {
204
+ const key = requireArg(positionals[2], 'key');
205
+ assertConfigKey(key);
206
+ unsetConfigValue(options.configPath, key);
207
+ return ok(`Unset ${key}`);
208
+ }
package/dist/options.d.ts CHANGED
@@ -15,7 +15,7 @@ export interface OptionSpec {
15
15
  readonly choices?: readonly string[];
16
16
  readonly description: string;
17
17
  }
18
- export declare const OUTPUT_FORMATS: readonly ["text", "json"];
18
+ export declare const OUTPUT_FORMATS: readonly ["text", "json", "jsonl"];
19
19
  export type OutputFormat = (typeof OUTPUT_FORMATS)[number];
20
20
  /** Accepted by every command. */
21
21
  export declare const GLOBAL_OPTIONS: readonly OptionSpec[];
@@ -41,8 +41,7 @@ export declare const LIMIT_OPTION: OptionSpec;
41
41
  export declare const PAGINATION_OPTIONS: readonly OptionSpec[];
42
42
  export declare const JSON_OPTION: OptionSpec;
43
43
  export declare const MINE_OPTION: OptionSpec;
44
- export declare class UsageError extends Error {
45
- }
44
+ export { UsageError } from './errors.js';
46
45
  /** `--api-key` reads back as `api_key`. */
47
46
  export declare function optionKey(spec: OptionSpec): string;
48
47
  export interface FilterCondition {
@@ -98,5 +97,10 @@ export interface Containers {
98
97
  readonly tokens: readonly string[];
99
98
  readonly kind: 'form' | 'table';
100
99
  }
101
- /** The repeatable form of the above, for a read that answers about several. */
100
+ /**
101
+ * Every container named, of one kind, possibly none: a search that names no
102
+ * container lets the server choose. Still one kind per call.
103
+ */
104
+ export declare function namedContainers(options: Record<string, unknown>): Containers;
105
+ /** The repeatable form of resolveContainer, for a read that answers about several. */
102
106
  export declare function resolveContainers(options: Record<string, unknown>, max: number): Containers;