@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.
@@ -1 +0,0 @@
1
- export * from "./gql.js";
@@ -1,240 +0,0 @@
1
- /**
2
- * Runtime schema introspection.
3
- *
4
- * Fetches the schema from the federation endpoint via an introspection query,
5
- * caches it on disk at ~/.sortlist/schema.json, and returns a GraphQLSchema
6
- * together with a field → subgraph map derived from the `@join__field`
7
- * directives the router injects into introspection responses.
8
- */
9
- import { createHash } from 'node:crypto';
10
- import fs from 'node:fs';
11
- import os from 'node:os';
12
- import path from 'node:path';
13
- import { buildClientSchema, getIntrospectionQuery, type GraphQLSchema, type IntrospectionQuery } from 'graphql';
14
-
15
- import { loadCredentials } from '../lib/auth.ts';
16
- import { getEndpoint } from '../lib/config.ts';
17
-
18
- const CACHE_DIR = path.join(os.homedir(), '.sortlist');
19
- const CACHE_PATH = path.join(CACHE_DIR, 'schema.json');
20
- const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
21
-
22
- export type FieldServiceMap = Map<string, Map<string, string>>;
23
-
24
- export interface IntrospectedSchema {
25
- schema: GraphQLSchema;
26
- fieldServices: FieldServiceMap;
27
- /** All subgraph names observed in the supergraph, regardless of scope visibility. */
28
- services: Set<string>;
29
- }
30
-
31
- let cached: IntrospectedSchema | null = null;
32
-
33
- /**
34
- * The router injects `appliedDirectives` into introspection responses — this
35
- * isn't a standard introspection field, so we read it from the raw JSON.
36
- */
37
- interface RawField {
38
- name: string;
39
- appliedDirectives?: Array<{
40
- name: string;
41
- args: Array<{ name: string; value: unknown }>;
42
- }>;
43
- }
44
-
45
- interface RawType {
46
- name: string;
47
- fields?: RawField[];
48
- }
49
-
50
- interface RawIntrospection {
51
- __schema: {
52
- queryType?: { name: string } | null;
53
- mutationType?: { name: string } | null;
54
- types: RawType[];
55
- };
56
- }
57
-
58
- interface CacheEnvelope {
59
- endpoint: string;
60
- fetchedAt: number;
61
- /** Short fingerprint of the access token so schemas for different scopes don't collide. */
62
- tokenFingerprint: string;
63
- introspection: IntrospectionQuery;
64
- raw: RawIntrospection;
65
- }
66
-
67
- function tokenFingerprint(token: string | null): string {
68
- if (!token) return 'anonymous';
69
- return createHash('sha256').update(token).digest('hex').slice(0, 16);
70
- }
71
-
72
- function readCache(
73
- endpoint: string,
74
- token: string | null,
75
- ): { introspection: IntrospectionQuery; raw: RawIntrospection } | null {
76
- try {
77
- const text = fs.readFileSync(CACHE_PATH, 'utf-8');
78
- const envelope: CacheEnvelope = JSON.parse(text);
79
- if (envelope.endpoint !== endpoint) return null;
80
- if (envelope.tokenFingerprint !== tokenFingerprint(token)) return null;
81
- if (Date.now() - envelope.fetchedAt > CACHE_TTL_MS) return null;
82
- if (!envelope.raw) return null;
83
- return { introspection: envelope.introspection, raw: envelope.raw };
84
- } catch {
85
- return null;
86
- }
87
- }
88
-
89
- function writeCache(
90
- endpoint: string,
91
- token: string | null,
92
- introspection: IntrospectionQuery,
93
- raw: RawIntrospection,
94
- ): void {
95
- try {
96
- if (!fs.existsSync(CACHE_DIR)) {
97
- fs.mkdirSync(CACHE_DIR, { recursive: true });
98
- }
99
- const envelope: CacheEnvelope = {
100
- endpoint,
101
- fetchedAt: Date.now(),
102
- tokenFingerprint: tokenFingerprint(token),
103
- introspection,
104
- raw,
105
- };
106
- fs.writeFileSync(CACHE_PATH, JSON.stringify(envelope));
107
- } catch {
108
- // Non-fatal — worst case we re-fetch next time
109
- }
110
- }
111
-
112
- async function fetchIntrospection(
113
- endpoint: string,
114
- token: string | null,
115
- ): Promise<{ introspection: IntrospectionQuery; raw: RawIntrospection }> {
116
- const headers: Record<string, string> = {
117
- 'Content-Type': 'application/json',
118
- 'X-API-Client': 'sl-cli',
119
- };
120
- if (token) headers['Authorization'] = `Bearer ${token}`;
121
-
122
- const res = await fetch(endpoint, {
123
- method: 'POST',
124
- headers,
125
- body: JSON.stringify({ query: getIntrospectionQuery() }),
126
- });
127
-
128
- if (!res.ok) {
129
- throw new Error(`Introspection failed: HTTP ${res.status} ${res.statusText}`);
130
- }
131
-
132
- const json = (await res.json()) as {
133
- data?: IntrospectionQuery & RawIntrospection;
134
- errors?: Array<{ message: string }>;
135
- };
136
-
137
- if (json.errors?.length) {
138
- throw new Error(`Introspection errors: ${json.errors.map((e) => e.message).join(', ')}`);
139
- }
140
-
141
- if (!json.data) {
142
- throw new Error('Introspection returned no data');
143
- }
144
-
145
- return { introspection: json.data as IntrospectionQuery, raw: json.data as RawIntrospection };
146
- }
147
-
148
- /**
149
- * Walk the raw introspection response and build:
150
- * - a `typeName → fieldName → subgraph` map from `@join__field(graph: ...)` directives
151
- * - the full set of subgraph names observed anywhere in the response (including types
152
- * whose root-fields were hidden by scope filtering — still useful so the CLI can
153
- * expose empty sub-commands that explain the scope gap)
154
- */
155
- function parseIntrospection(raw: RawIntrospection): { fieldServices: FieldServiceMap; services: Set<string> } {
156
- const fieldServices: FieldServiceMap = new Map();
157
- const services = new Set<string>();
158
-
159
- for (const type of raw.__schema.types ?? []) {
160
- if (!type.fields?.length) continue;
161
-
162
- let fieldMap: Map<string, string> | null = null;
163
-
164
- for (const field of type.fields) {
165
- const directive = field.appliedDirectives?.find((d) => d.name === 'join__field');
166
- if (!directive) continue;
167
- const graphArg = directive.args.find((a) => a.name === 'graph');
168
- if (!graphArg || typeof graphArg.value !== 'string') continue;
169
- services.add(graphArg.value);
170
- if (!fieldMap) fieldMap = new Map();
171
- fieldMap.set(field.name, graphArg.value);
172
- }
173
-
174
- if (fieldMap) fieldServices.set(type.name, fieldMap);
175
- }
176
-
177
- return { fieldServices, services };
178
- }
179
-
180
- /**
181
- * Fetches and caches the schema via introspection. Returns the built schema
182
- * along with a map of root-field → subgraph name used for CLI service grouping.
183
- *
184
- * @param endpointOverride - Override the configured endpoint URL
185
- */
186
- function currentAccessToken(): string | null {
187
- return loadCredentials()?.accessToken ?? null;
188
- }
189
-
190
- export async function getIntrospectedSchema(endpointOverride?: string): Promise<IntrospectedSchema> {
191
- if (cached) return cached;
192
-
193
- const endpoint = getEndpoint(endpointOverride);
194
- const token = currentAccessToken();
195
-
196
- const fromCache = readCache(endpoint, token);
197
- if (fromCache) {
198
- const { fieldServices, services } = parseIntrospection(fromCache.raw);
199
- cached = {
200
- schema: buildClientSchema(fromCache.introspection),
201
- fieldServices,
202
- services,
203
- };
204
- return cached;
205
- }
206
-
207
- const { introspection, raw } = await fetchIntrospection(endpoint, token);
208
- writeCache(endpoint, token, introspection, raw);
209
- const { fieldServices, services } = parseIntrospection(raw);
210
- cached = {
211
- schema: buildClientSchema(introspection),
212
- fieldServices,
213
- services,
214
- };
215
- return cached;
216
- }
217
-
218
- /**
219
- * Force-refresh the cached schema, bypassing the disk cache.
220
- */
221
- export async function refreshSchema(endpointOverride?: string): Promise<IntrospectedSchema> {
222
- cached = null;
223
- try {
224
- fs.unlinkSync(CACHE_PATH);
225
- } catch {
226
- // already gone
227
- }
228
-
229
- const endpoint = getEndpoint(endpointOverride);
230
- const token = currentAccessToken();
231
- const { introspection, raw } = await fetchIntrospection(endpoint, token);
232
- writeCache(endpoint, token, introspection, raw);
233
- const { fieldServices, services } = parseIntrospection(raw);
234
- cached = {
235
- schema: buildClientSchema(introspection),
236
- fieldServices,
237
- services,
238
- };
239
- return cached;
240
- }
@@ -1,16 +0,0 @@
1
- /**
2
- * Hand-maintained typed operations used by non-generated commands.
3
- * These need gql() for TypedDocumentNode inference.
4
- */
5
- import { gql } from '../generated/gql.ts';
6
-
7
- export const Me = gql(`
8
- query Me {
9
- me {
10
- sub
11
- email
12
- firstName
13
- lastName
14
- }
15
- }
16
- `);
@@ -1,54 +0,0 @@
1
- /**
2
- * Auto-generated from backend/supergraph.graphql — do not edit manually.
3
- * Re-generate with: npx tsx scripts/generate-operations.ts
4
- */
5
- import { gql } from '../generated/gql.ts';
6
-
7
- // ── Queries ──
8
-
9
- export const LogoutUrl = gql(`
10
- query LogoutUrl {
11
- logoutUrl
12
- }
13
- `);
14
-
15
- // ── Mutations ──
16
-
17
- export const DeviceAuthorize = gql(`
18
- mutation DeviceAuthorize($input: DeviceAuthorizeInput!) {
19
- deviceAuthorize(input: $input) {
20
- deviceCode
21
- expiresIn
22
- interval
23
- userCode
24
- verificationUri
25
- verificationUriComplete
26
- }
27
- }
28
- `);
29
-
30
- export const DeviceToken = gql(`
31
- mutation DeviceToken($input: DeviceTokenInput!) {
32
- deviceToken(input: $input) {
33
- accessToken
34
- error
35
- expiresIn
36
- idToken
37
- refreshToken
38
- tokenType
39
- }
40
- }
41
- `);
42
-
43
- export const RefreshToken = gql(`
44
- mutation RefreshToken($input: RefreshTokenInput!) {
45
- refreshToken(input: $input) {
46
- accessToken
47
- error
48
- expiresIn
49
- idToken
50
- refreshToken
51
- tokenType
52
- }
53
- }
54
- `);
@@ -1,239 +0,0 @@
1
- /**
2
- * Runtime GraphQL query builder.
3
- * Dynamically constructs operations from an introspected schema
4
- * with user-controlled depth and field selection.
5
- */
6
- import {
7
- isEnumType,
8
- isInterfaceType,
9
- isListType,
10
- isNonNullType,
11
- isObjectType,
12
- isScalarType,
13
- isUnionType,
14
- type GraphQLNamedType,
15
- type GraphQLOutputType,
16
- type GraphQLSchema,
17
- } from 'graphql';
18
-
19
- // ── Helpers ──
20
-
21
- function unwrap(type: GraphQLOutputType): GraphQLNamedType {
22
- if (isNonNullType(type)) return unwrap(type.ofType);
23
- if (isListType(type)) return unwrap(type.ofType);
24
- return type as GraphQLNamedType;
25
- }
26
-
27
- function isLeaf(type: GraphQLNamedType): boolean {
28
- return isScalarType(type) || isEnumType(type);
29
- }
30
-
31
- function ucfirst(s: string): string {
32
- return s.charAt(0).toUpperCase() + s.slice(1);
33
- }
34
-
35
- // Payload types where `id` often fails at runtime
36
- const PAYLOAD_TYPE_PATTERN = /(?:Response|Payload|MutationPayload)$/;
37
-
38
- // ── Selection set builder ──
39
-
40
- export interface QueryOptions {
41
- /** Max nesting depth for sub-objects (default: 0) */
42
- depth?: number;
43
- /** Only include these fields (dot-notation for nested, e.g. "organization.name") */
44
- fields?: string[];
45
- /** Exclude these fields (dot-notation for nested) */
46
- exclude?: string[];
47
- }
48
-
49
- function buildSelections(
50
- type: GraphQLNamedType,
51
- schema: GraphQLSchema,
52
- depth: number,
53
- exclude: Set<string>,
54
- prefix: string,
55
- visited: Set<string>,
56
- ): string[] {
57
- if (!isObjectType(type)) return [];
58
- if (visited.has(type.name)) return [];
59
- visited.add(type.name);
60
-
61
- const fields = type.getFields();
62
- const lines: string[] = [];
63
- const isPayload = PAYLOAD_TYPE_PATTERN.test(type.name);
64
-
65
- // Relay Connection pattern. The connection/`nodes` wrapper is not a semantic
66
- // nesting level, so the node type inherits the caller's `depth` unchanged —
67
- // otherwise object fields on the node (e.g. Contact.organization) would never
68
- // be selected regardless of --depth.
69
- if (type.name.endsWith('Connection') && fields.nodes && fields.pageInfo) {
70
- const nodesType = unwrap(fields.nodes.type);
71
- const nodeSelections = buildSelections(nodesType, schema, depth, exclude, `${prefix}nodes.`, new Set(visited));
72
- if (nodeSelections.length === 0) return [];
73
- lines.push(`nodes {`);
74
- for (const sel of nodeSelections) lines.push(` ${sel}`);
75
- lines.push(`}`);
76
- lines.push(`pageInfo {`);
77
- lines.push(` hasNextPage`);
78
- lines.push(` endCursor`);
79
- lines.push(`}`);
80
- if (fields.totalCount) lines.push(`totalCount`);
81
- return lines;
82
- }
83
-
84
- for (const [name, field] of Object.entries(fields)) {
85
- if (name.startsWith('__')) continue;
86
- if (name === 'id' && isPayload) continue;
87
-
88
- const fullPath = `${prefix}${name}`;
89
- if (exclude.has(fullPath) || exclude.has(name)) continue;
90
-
91
- // Skip fields with required arguments
92
- const hasRequiredArgs = field.args.some((a) => isNonNullType(a.type) && a.defaultValue === undefined);
93
- if (hasRequiredArgs) continue;
94
-
95
- const namedType = unwrap(field.type);
96
-
97
- if (isLeaf(namedType)) {
98
- lines.push(name);
99
- } else if (isObjectType(namedType) && depth > 0) {
100
- const subSelections = buildSelections(namedType, schema, depth - 1, exclude, `${fullPath}.`, new Set(visited));
101
- if (subSelections.length > 0) {
102
- lines.push(`${name} {`);
103
- for (const sel of subSelections) lines.push(` ${sel}`);
104
- lines.push(`}`);
105
- }
106
- }
107
- // Skip interfaces, unions at sub-levels
108
- }
109
-
110
- return lines;
111
- }
112
-
113
- // ── Public API ──
114
-
115
- export interface BuiltQuery {
116
- query: string;
117
- variables: Record<string, unknown>;
118
- /** The root field name (e.g. "agency", "createChat") */
119
- fieldName: string;
120
- }
121
-
122
- /**
123
- * Build a GraphQL query/mutation string for a root operation field.
124
- *
125
- * @param schema - The introspected GraphQL schema
126
- * @param kind - "query" or "mutation"
127
- * @param fieldName - The root field name (e.g. "agency", "createChat")
128
- * @param variables - Variable values to send
129
- * @param options - Depth, field inclusion/exclusion
130
- */
131
- export function buildQuery(
132
- schema: GraphQLSchema,
133
- kind: 'query' | 'mutation',
134
- fieldName: string,
135
- variables: Record<string, unknown>,
136
- options: QueryOptions = {},
137
- ): BuiltQuery {
138
- const rootType = kind === 'query' ? schema.getQueryType() : schema.getMutationType();
139
- if (!rootType) throw new Error(`No ${kind} type in schema`);
140
-
141
- const field = rootType.getFields()[fieldName];
142
- if (!field) throw new Error(`Unknown ${kind} field: ${fieldName}`);
143
-
144
- const depth = options.depth ?? 0;
145
- const exclude = new Set(options.exclude ?? []);
146
-
147
- const returnType = unwrap(field.type);
148
-
149
- // Build variable definitions from the field's arguments
150
- const allArgs = field.args;
151
-
152
- const varDefsInner = allArgs.map((a) => `$${a.name}: ${a.type.toString()}`).join(', ');
153
- const fieldArgsInner = allArgs.map((a) => `${a.name}: $${a.name}`).join(', ');
154
- const varDefs = allArgs.length > 0 ? `(${varDefsInner})` : '';
155
- const fieldArgs = allArgs.length > 0 ? `(${fieldArgsInner})` : '';
156
-
157
- // Build selection set
158
- let selectionBody: string;
159
- if (isLeaf(returnType) || isInterfaceType(returnType) || isUnionType(returnType)) {
160
- // Scalar return or interface/union — no sub-selections
161
- selectionBody = ` ${fieldName}${fieldArgs}`;
162
- } else {
163
- // Filter fields if --fields is provided
164
- let selections: string[];
165
- if (options.fields && options.fields.length > 0) {
166
- selections = buildFieldsFromList(returnType, schema, options.fields);
167
- } else {
168
- selections = buildSelections(returnType, schema, depth, exclude, '', new Set());
169
- }
170
-
171
- if (selections.length === 0) {
172
- // Fallback: at minimum select __typename
173
- selectionBody = ` ${fieldName}${fieldArgs} {\n __typename\n }`;
174
- } else {
175
- const indent = ' ';
176
- const body = selections.map((s) => `${indent}${s}`).join('\n');
177
- selectionBody = ` ${fieldName}${fieldArgs} {\n${body}\n }`;
178
- }
179
- }
180
-
181
- const opName = ucfirst(fieldName);
182
- const query = `${kind} ${opName}${varDefs} {\n${selectionBody}\n }`;
183
-
184
- return { query, variables, fieldName };
185
- }
186
-
187
- /**
188
- * Build selections from an explicit field list (e.g. --fields id,name,slug).
189
- */
190
- function buildFieldsFromList(type: GraphQLNamedType, schema: GraphQLSchema, fieldPaths: string[]): string[] {
191
- if (!isObjectType(type)) return [];
192
- const fields = type.getFields();
193
-
194
- // Relay Connection pattern — unwrap to the node type
195
- if (type.name.endsWith('Connection') && fields.nodes && fields.pageInfo) {
196
- const nodesType = unwrap(fields.nodes.type);
197
- const nodeSelections = buildFieldsFromList(nodesType, schema, fieldPaths);
198
- if (nodeSelections.length === 0) return [];
199
- const lines: string[] = [];
200
- lines.push('nodes {');
201
- for (const sel of nodeSelections) lines.push(` ${sel}`);
202
- lines.push('}');
203
- lines.push('pageInfo {');
204
- lines.push(' hasNextPage');
205
- lines.push(' endCursor');
206
- lines.push('}');
207
- if (fields.totalCount) lines.push('totalCount');
208
- return lines;
209
- }
210
-
211
- const lines: string[] = [];
212
-
213
- // Group by top-level field
214
- const grouped = new Map<string, string[]>();
215
- for (const fp of fieldPaths) {
216
- const [top, ...rest] = fp.split('.');
217
- if (!grouped.has(top)) grouped.set(top, []);
218
- if (rest.length > 0) grouped.get(top)!.push(rest.join('.'));
219
- }
220
-
221
- for (const [name, subPaths] of grouped) {
222
- const field = fields[name];
223
- if (!field) continue;
224
-
225
- const namedType = unwrap(field.type);
226
- if (isLeaf(namedType)) {
227
- lines.push(name);
228
- } else if (isObjectType(namedType) && subPaths.length > 0) {
229
- const subSelections = buildFieldsFromList(namedType, schema, subPaths);
230
- if (subSelections.length > 0) {
231
- lines.push(`${name} {`);
232
- for (const sel of subSelections) lines.push(` ${sel}`);
233
- lines.push(`}`);
234
- }
235
- }
236
- }
237
-
238
- return lines;
239
- }