@sortlist/cli 0.35.0 → 0.37.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/src/index.ts DELETED
@@ -1,186 +0,0 @@
1
- import fs from 'node:fs';
2
- import { Command } from 'commander';
3
-
4
- import { configCommand } from './commands/config.ts';
5
- import { buildServiceCommands, formatTypeInspection } from './commands/dynamic.ts';
6
- import { loginCommand } from './commands/login.ts';
7
- import { logoutCommand } from './commands/logout.ts';
8
- import { tokenCommand } from './commands/token.ts';
9
- import { whoamiCommand } from './commands/whoami.ts';
10
- import { getIntrospectedSchema, refreshSchema } from './graphql/introspection.ts';
11
- import { error, hint, info } from './lib/output.ts';
12
- import { captureException, flushSentry, initSentry } from './lib/sentry.ts';
13
- import { checkForUpdates } from './lib/version-check.ts';
14
-
15
- initSentry();
16
-
17
- // ── Colored help output ──
18
-
19
- const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
20
- const ansi = {
21
- reset: '\x1b[0m',
22
- bold: '\x1b[1m',
23
- dim: '\x1b[2m',
24
- cyan: '\x1b[36m',
25
- yellow: '\x1b[33m',
26
- green: '\x1b[32m',
27
- };
28
-
29
- function colorizeHelp(text: string): string {
30
- if (!useColor) return text;
31
- return text.replace(
32
- /^(Usage|Options|Commands|Arguments|Quick start|Services|Examples|Queries|Mutations):(.*)$/gm,
33
- `${ansi.cyan}${ansi.bold}$1:$2${ansi.reset}`,
34
- );
35
- }
36
-
37
- const colorOutput = {
38
- writeOut: (str: string) => process.stdout.write(colorizeHelp(str)),
39
- writeErr: (str: string) => process.stderr.write(colorizeHelp(str)),
40
- };
41
-
42
- function applyColorToAllCommands(cmd: Command): void {
43
- cmd.configureOutput(colorOutput);
44
- for (const sub of cmd.commands) {
45
- applyColorToAllCommands(sub as Command);
46
- }
47
- }
48
-
49
- const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
50
-
51
- const BASE_DESCRIPTION =
52
- 'Sortlist CLI — query and manage the Sortlist platform from your terminal\n\n' +
53
- 'Quick start:\n' +
54
- ' sl login Authenticate with your Sortlist account\n' +
55
- " sl whoami Check who you're logged in as";
56
-
57
- function buildRootDescription(services: Map<string, { exampleQuery: string | null; description: string }>): string {
58
- const parts = [BASE_DESCRIPTION];
59
-
60
- if (services.size > 0) {
61
- const entries = [...services.entries()];
62
- const labels = entries.map(([name]) => `sl ${name} <operation>`);
63
- const pad = Math.max(...labels.map((l) => l.length));
64
-
65
- parts.push(
66
- 'Services:\n' + entries.map(([name, info], i) => ` ${labels[i].padEnd(pad)} ${info.description}`).join('\n'),
67
- );
68
-
69
- const examples: string[] = [];
70
- for (const [name, info] of entries) {
71
- if (info.exampleQuery) examples.push(` sl ${name} ${info.exampleQuery}`);
72
- if (examples.length >= 2) break;
73
- }
74
- examples.push(' sl config show View current endpoint and agency context');
75
- parts.push('Examples:\n' + examples.join('\n'));
76
- }
77
-
78
- return parts.join('\n\n');
79
- }
80
-
81
- const program = new Command()
82
- .name('sl')
83
- .configureOutput({
84
- writeOut: (str) => process.stdout.write(colorizeHelp(str)),
85
- writeErr: (str) => process.stderr.write(colorizeHelp(str)),
86
- })
87
- .description(BASE_DESCRIPTION)
88
- .version(pkg.version)
89
- .option('--endpoint <url>', 'Override the federation endpoint URL')
90
- .option('--json', 'Output as JSON (auto-enabled when stdout is not a TTY)')
91
- .option('--no-color', 'Disable colored output');
92
-
93
- // Auth commands (hand-written — interactive flows)
94
- program.addCommand(loginCommand);
95
- program.addCommand(logoutCommand);
96
- program.addCommand(whoamiCommand);
97
- program.addCommand(tokenCommand);
98
- program.addCommand(configCommand);
99
-
100
- // Schema refresh command
101
- const schemaCommand = new Command('schema').description('Manage the cached GraphQL schema');
102
-
103
- schemaCommand
104
- .command('refresh')
105
- .description('Force-refresh the cached schema from the federation endpoint')
106
- .action(async function (this: Command) {
107
- const opts = this.optsWithGlobals();
108
- try {
109
- await refreshSchema(opts.endpoint);
110
- info('Schema refreshed successfully.');
111
- } catch (err) {
112
- error(`Failed to refresh schema: ${(err as Error).message}`);
113
- hint('Check your network connection and endpoint: sl config show');
114
- process.exit(1);
115
- }
116
- });
117
-
118
- schemaCommand
119
- .command('inspect <type>')
120
- .description('Show the fields/values of a schema type (e.g. an input filter or enum)')
121
- .action(async function (this: Command, typeName: string) {
122
- const opts = this.optsWithGlobals();
123
- try {
124
- const { schema } = await getIntrospectedSchema(opts.endpoint);
125
- const formatted = formatTypeInspection(schema, typeName);
126
- if (!formatted) {
127
- error(`No type named "${typeName}" in the schema.`);
128
- hint('Type names are case-sensitive, e.g. `sl schema inspect OrganizationFilterInput`.');
129
- hint('Find argument types in any command’s --help output.');
130
- process.exit(1);
131
- }
132
- info(formatted);
133
- } catch (err) {
134
- error(`Could not read the schema: ${(err as Error).message}`);
135
- hint('Check your network connection and endpoint: sl config show');
136
- process.exit(1);
137
- }
138
- });
139
-
140
- program.addCommand(schemaCommand);
141
-
142
- // Parse --endpoint early so introspection uses the right URL
143
- const endpointIdx = process.argv.indexOf('--endpoint');
144
- const endpointOverride = endpointIdx !== -1 ? process.argv[endpointIdx + 1] : undefined;
145
-
146
- // Dynamically register subgraph commands from introspected schema
147
- try {
148
- const { schema, fieldServices } = await getIntrospectedSchema(endpointOverride);
149
- const serviceCommands = buildServiceCommands(schema, fieldServices);
150
-
151
- const servicesForHelp = new Map<string, { exampleQuery: string | null; description: string }>();
152
-
153
- for (const [name, entry] of serviceCommands) {
154
- const cmd = entry.command;
155
- program.addCommand(cmd);
156
- servicesForHelp.set(name, {
157
- exampleQuery: entry.exampleQuery,
158
- description: cmd.description(),
159
- });
160
- }
161
-
162
- program.description(buildRootDescription(servicesForHelp));
163
- } catch (err) {
164
- // Schema fetch failed — still allow non-subgraph commands (login, config, etc.)
165
- const message = (err as Error).message;
166
- if (!process.argv.some((a) => ['login', 'logout', 'config', 'token', 'whoami', 'schema'].includes(a))) {
167
- error(`Could not fetch schema: ${message}`);
168
- hint('Check your network connection and endpoint: sl config show');
169
- hint('You can still use: sl login, sl config, sl schema refresh');
170
- process.exit(1);
171
- }
172
- }
173
-
174
- applyColorToAllCommands(program);
175
-
176
- await checkForUpdates();
177
-
178
- try {
179
- await program.parseAsync(process.argv);
180
- } catch (err) {
181
- captureException(err);
182
- await flushSentry();
183
- throw err;
184
- }
185
-
186
- await flushSentry();
package/src/lib/auth.ts DELETED
@@ -1,58 +0,0 @@
1
- import fs from 'fs';
2
- import os from 'os';
3
- import path from 'path';
4
-
5
- import { error, hint } from './output.ts';
6
-
7
- const CREDENTIALS_PATH = path.join(os.homedir(), '.sortlist', 'credentials.json');
8
-
9
- export interface Credentials {
10
- accessToken: string;
11
- refreshToken: string;
12
- idToken: string;
13
- expiresAt: number;
14
- }
15
-
16
- function ensureDir(): void {
17
- const dir = path.dirname(CREDENTIALS_PATH);
18
- if (!fs.existsSync(dir)) {
19
- fs.mkdirSync(dir, { recursive: true });
20
- }
21
- }
22
-
23
- export function saveCredentials(creds: Credentials): void {
24
- ensureDir();
25
- fs.writeFileSync(CREDENTIALS_PATH, JSON.stringify(creds, null, 2) + '\n', { mode: 0o600 });
26
- }
27
-
28
- export function loadCredentials(): Credentials | null {
29
- try {
30
- const raw = fs.readFileSync(CREDENTIALS_PATH, 'utf-8');
31
- return JSON.parse(raw) as Credentials;
32
- } catch {
33
- return null;
34
- }
35
- }
36
-
37
- export function clearCredentials(): void {
38
- try {
39
- fs.unlinkSync(CREDENTIALS_PATH);
40
- } catch {
41
- // already gone
42
- }
43
- }
44
-
45
- export function isExpired(creds: Credentials): boolean {
46
- // 60s buffer before actual expiry
47
- return Date.now() >= (creds.expiresAt - 60) * 1000;
48
- }
49
-
50
- export function ensureAuthenticated(): Credentials {
51
- const creds = loadCredentials();
52
- if (!creds) {
53
- error('You are not logged in.');
54
- hint('Run `sl login` to authenticate with your Sortlist account.');
55
- process.exit(2);
56
- }
57
- return creds;
58
- }
@@ -1,11 +0,0 @@
1
- import { execFile } from 'node:child_process';
2
-
3
- export function openBrowser(url: string): void {
4
- if (process.platform === 'win32') {
5
- // `start` is a cmd built-in; the empty string is the window title slot.
6
- execFile('cmd', ['/c', 'start', '', url], () => {});
7
- return;
8
- }
9
- const cmd = process.platform === 'darwin' ? 'open' : 'xdg-open';
10
- execFile(cmd, [url], () => {});
11
- }
@@ -1,15 +0,0 @@
1
- import { type UserContext } from './config.ts';
2
-
3
- /**
4
- * Resolve the active company id for a request.
5
- *
6
- * Resolution order:
7
- * 1. --company-id flag
8
- * 2. config.companyId
9
- */
10
- export function resolveCompanyId(opts: {
11
- companyId?: string | undefined;
12
- ctx: UserContext | undefined;
13
- }): string | undefined {
14
- return opts.companyId || opts.ctx?.companyId;
15
- }
package/src/lib/config.ts DELETED
@@ -1,80 +0,0 @@
1
- import fs from 'fs';
2
- import os from 'os';
3
- import path from 'path';
4
-
5
- const SORTLIST_DIR = path.join(os.homedir(), '.sortlist');
6
- const CONFIG_PATH = path.join(SORTLIST_DIR, 'config.json');
7
-
8
- export interface CliConfig {
9
- endpoint: string;
10
- oauthId?: string;
11
- companyId?: string;
12
- }
13
-
14
- const DEFAULT_CONFIG: CliConfig = {
15
- endpoint: 'https://federation.sortlist.com/graphql',
16
- };
17
-
18
- function ensureDir(): void {
19
- if (!fs.existsSync(SORTLIST_DIR)) {
20
- fs.mkdirSync(SORTLIST_DIR, { recursive: true });
21
- }
22
- }
23
-
24
- export function loadConfig(): CliConfig {
25
- try {
26
- const raw = fs.readFileSync(CONFIG_PATH, 'utf-8');
27
- return { ...DEFAULT_CONFIG, ...JSON.parse(raw) };
28
- } catch {
29
- return { ...DEFAULT_CONFIG };
30
- }
31
- }
32
-
33
- export function saveConfig(config: Partial<CliConfig>): void {
34
- ensureDir();
35
- const current = loadConfig();
36
- const merged = { ...current, ...config };
37
- fs.writeFileSync(CONFIG_PATH, JSON.stringify(merged, null, 2) + '\n');
38
- }
39
-
40
- export function resetConfig(): void {
41
- try {
42
- fs.unlinkSync(CONFIG_PATH);
43
- } catch {
44
- // already gone
45
- }
46
- }
47
-
48
- /**
49
- * Drops the cached identity (user + company/agency context) while preserving
50
- * non-identity settings like the endpoint. Used by `logout` so the next login
51
- * can't surface the previous account's user and company.
52
- */
53
- export function clearIdentity(): void {
54
- const { endpoint } = loadConfig();
55
- ensureDir();
56
- fs.writeFileSync(CONFIG_PATH, JSON.stringify({ endpoint }, null, 2) + '\n');
57
- }
58
-
59
- export function getEndpoint(override?: string): string {
60
- if (override) return override;
61
- if (process.env.SL_ENDPOINT) return process.env.SL_ENDPOINT;
62
- return loadConfig().endpoint;
63
- }
64
-
65
- /**
66
- * Context variables that are auto-injected into generated commands.
67
- * These are read from config and can be overridden via CLI flags.
68
- */
69
- export interface UserContext {
70
- oauthId?: string;
71
- companyId?: string;
72
- }
73
-
74
- export function getUserContext(): UserContext {
75
- const config = loadConfig();
76
- return {
77
- oauthId: config.oauthId,
78
- companyId: config.companyId,
79
- };
80
- }
package/src/lib/env.ts DELETED
@@ -1,10 +0,0 @@
1
- import fs from 'node:fs';
2
-
3
- /**
4
- * Whether the CLI is running from the platform monorepo (dev checkout)
5
- * vs a globally-installed npm package.
6
- *
7
- * Published builds contain a `.published` sentinel file stamped by CI.
8
- * Its absence means we're running from source.
9
- */
10
- export const isLocalDev = !fs.existsSync(new URL('../../.published', import.meta.url));
package/src/lib/output.ts DELETED
@@ -1,58 +0,0 @@
1
- // ── Color helpers (respect --no-color / NO_COLOR) ──
2
-
3
- function colorEnabled(): boolean {
4
- return process.stderr.isTTY === true && !process.env.NO_COLOR;
5
- }
6
-
7
- const ansi = {
8
- reset: '\x1b[0m',
9
- dim: '\x1b[2m',
10
- red: '\x1b[31m',
11
- green: '\x1b[32m',
12
- yellow: '\x1b[33m',
13
- };
14
-
15
- function c(code: keyof typeof ansi, text: string): string {
16
- if (!colorEnabled()) return text;
17
- return `${ansi[code]}${text}${ansi.reset}`;
18
- }
19
-
20
- // ── JSON mode detection ──
21
-
22
- export function isJsonMode(options: { json?: boolean }): boolean {
23
- if (options.json) return true;
24
- return !process.stdout.isTTY;
25
- }
26
-
27
- export function printJson(data: unknown): void {
28
- process.stdout.write(JSON.stringify(data, null, 2) + '\n');
29
- }
30
-
31
- // ── Message helpers ──
32
- // Every function uses a text prefix so status is conveyed independent of color.
33
- // Color is enhancement only — never the sole status indicator.
34
-
35
- /** General informational message (no prefix). */
36
- export function info(msg: string): void {
37
- process.stderr.write(`${msg}\n`);
38
- }
39
-
40
- /** Success: confirms an outcome. Use after a completed action. */
41
- export function success(msg: string): void {
42
- process.stderr.write(`${c('green', '\u2713')} ${msg}\n`);
43
- }
44
-
45
- /** Warning: something is off but not fatal. */
46
- export function warn(msg: string): void {
47
- process.stderr.write(`${c('yellow', '\u26A0')} ${msg}\n`);
48
- }
49
-
50
- /** Error: state what failed, why, and what to do next. */
51
- export function error(msg: string): void {
52
- process.stderr.write(`${c('red', '\u2717')} Error: ${msg}\n`);
53
- }
54
-
55
- /** Hint: suggest a next step or recovery action. Indented for readability. */
56
- export function hint(msg: string): void {
57
- process.stderr.write(`${c('dim', ' ' + msg)}\n`);
58
- }
package/src/lib/sentry.ts DELETED
@@ -1,70 +0,0 @@
1
- import fs from 'node:fs';
2
- import * as Sentry from '@sentry/node';
3
-
4
- import { isLocalDev } from './env.ts';
5
-
6
- const pkg = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf-8'));
7
-
8
- const SENTRY_DSN = 'https://306d2e4389b8baa0bf14e587c2ceff04@o27611.ingest.us.sentry.io/4511229468409856';
9
- const SENTRY_ENVIRONMENT = process.env.SL_SENTRY_ENV ?? (isLocalDev ? 'development' : 'production');
10
-
11
- const IGNORED_ERRORS = [
12
- /Network Error/i,
13
- /Failed to fetch/i,
14
- /fetch failed/i,
15
- /ECONNREFUSED/i,
16
- /ENOTFOUND/i,
17
- /ETIMEDOUT/i,
18
- /Request aborted/i,
19
- ];
20
-
21
- function isIgnoredError(message: string): boolean {
22
- return IGNORED_ERRORS.some((pattern) =>
23
- typeof pattern === 'string' ? message.includes(pattern) : pattern.test(message),
24
- );
25
- }
26
-
27
- export function initSentry(): void {
28
- if (isLocalDev) {
29
- return;
30
- }
31
-
32
- Sentry.init({
33
- dsn: SENTRY_DSN,
34
- environment: SENTRY_ENVIRONMENT,
35
- release: `${pkg.name}@${pkg.version}`,
36
- tracesSampleRate: 0,
37
- maxBreadcrumbs: 50,
38
- attachStacktrace: true,
39
- beforeSend(event) {
40
- const message = event.exception?.values?.[0]?.value ?? '';
41
- if (isIgnoredError(message)) {
42
- return null;
43
- }
44
- return event;
45
- },
46
- });
47
-
48
- Sentry.setTag('cli_version', pkg.version);
49
- }
50
-
51
- export function captureException(error: unknown, extra?: Record<string, unknown>): void {
52
- if (isLocalDev) {
53
- return;
54
- }
55
- Sentry.captureException(error, extra ? { extra } : undefined);
56
- }
57
-
58
- export function addBreadcrumb(breadcrumb: Sentry.Breadcrumb): void {
59
- if (isLocalDev) {
60
- return;
61
- }
62
- Sentry.addBreadcrumb(breadcrumb);
63
- }
64
-
65
- export async function flushSentry(timeout = 2000): Promise<void> {
66
- if (isLocalDev) {
67
- return;
68
- }
69
- await Sentry.flush(timeout);
70
- }
@@ -1,88 +0,0 @@
1
- import { execFileSync } from 'node:child_process';
2
- import fs from 'node:fs';
3
-
4
- import { isLocalDev } from './env.ts';
5
- import { error, hint, info, success, warn } from './output.ts';
6
-
7
- const PACKAGE_NAME = '@sortlist/cli';
8
-
9
- function getCurrentVersion(): string {
10
- const pkg = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf-8'));
11
- return pkg.version;
12
- }
13
-
14
- async function fetchLatestVersion(): Promise<string | null> {
15
- try {
16
- const controller = new AbortController();
17
- const timeout = setTimeout(() => controller.abort(), 3000);
18
- const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(PACKAGE_NAME)}/latest`, {
19
- signal: controller.signal,
20
- });
21
- clearTimeout(timeout);
22
- if (!res.ok) return null;
23
- const data = (await res.json()) as { version: string };
24
- return data.version;
25
- } catch {
26
- return null;
27
- }
28
- }
29
-
30
- function parseSemver(version: string): [number, number, number] {
31
- const [major, minor, patch] = version.split('.').map(Number);
32
- return [major ?? 0, minor ?? 0, patch ?? 0];
33
- }
34
-
35
- function autoUpdate(current: string, latest: string): void {
36
- info(`Updating ${PACKAGE_NAME}: ${current} \u2192 ${latest}...`);
37
-
38
- try {
39
- // Clean stale temp directories that cause ENOTEMPTY errors. npm stages a
40
- // package under a sibling `.<name>-<hash>` dir; for scoped names the dot
41
- // sits on the final segment, e.g. `@sortlist/.cli-<hash>`.
42
- const prefix = execFileSync('npm', ['prefix', '-g'], { stdio: 'pipe', encoding: 'utf-8' }).trim();
43
- const lastSlash = PACKAGE_NAME.lastIndexOf('/');
44
- const scope = lastSlash === -1 ? '' : `${PACKAGE_NAME.slice(0, lastSlash)}/`;
45
- const name = lastSlash === -1 ? PACKAGE_NAME : PACKAGE_NAME.slice(lastSlash + 1);
46
- const staleDir = `${prefix}/lib/node_modules/${scope}.${name}-`;
47
- execFileSync('sh', ['-c', `rm -rf "${staleDir}"* 2>/dev/null || true`], { stdio: 'pipe' });
48
-
49
- execFileSync('npm', ['install', '-g', '--prefer-online', `${PACKAGE_NAME}@${latest}`], {
50
- stdio: 'pipe',
51
- });
52
- success(`Updated to ${latest}. Restart \`sl\` to use the new version.`);
53
- } catch (err) {
54
- const stderr = err && typeof err === 'object' && 'stderr' in err ? String(err.stderr).trim() : '';
55
- const detail = stderr ? ` (${stderr.split('\n')[0]})` : '';
56
- warn(`Auto-update failed${detail}.`);
57
- hint(`Run \`npm i -g ${PACKAGE_NAME}\` to update manually.`);
58
- }
59
- }
60
-
61
- /**
62
- * Checks npm for the latest version.
63
- * - Major mismatch: blocks execution and exits.
64
- * - Minor/patch mismatch: auto-updates with a spinner, then continues.
65
- */
66
- export async function checkForUpdates(): Promise<void> {
67
- if (isLocalDev) return;
68
-
69
- const current = getCurrentVersion();
70
- const latest = await fetchLatestVersion();
71
- if (!latest || latest === current) return;
72
-
73
- const [curMajor] = parseSemver(current);
74
- const [latMajor] = parseSemver(latest);
75
-
76
- if (latMajor > curMajor) {
77
- error(`Breaking update: ${current} \u2192 ${latest}`);
78
- info('');
79
- info(' Your CLI is incompatible with the current API.');
80
- info(' Update before continuing:');
81
- info('');
82
- info(` npm i -g ${PACKAGE_NAME}`);
83
- info('');
84
- process.exit(1);
85
- }
86
-
87
- autoUpdate(current, latest);
88
- }