@sortlist/cli 0.26.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/.published +1 -0
- package/README.md +145 -0
- package/bin/sl.mjs +73 -0
- package/codegen.ts +36 -0
- package/package.json +62 -0
- package/src/commands/chat/chat.ts +302 -0
- package/src/commands/chat/interactive/App.tsx +119 -0
- package/src/commands/chat/interactive/components/ChatInput.tsx +115 -0
- package/src/commands/chat/interactive/components/ChoicePrompt.tsx +35 -0
- package/src/commands/chat/interactive/components/MessageView.tsx +63 -0
- package/src/commands/chat/interactive/components/ThinkingBox.tsx +54 -0
- package/src/commands/chat/interactive/connection.ts +111 -0
- package/src/commands/chat/interactive/debug-log.ts +19 -0
- package/src/commands/chat/interactive/hooks/useChat.ts +440 -0
- package/src/commands/chat/interactive/hooks/useTerminalSize.ts +23 -0
- package/src/commands/chat/interactive/index.tsx +26 -0
- package/src/commands/chat/interactive/markdown.ts +29 -0
- package/src/commands/chat/interactive/types.ts +34 -0
- package/src/commands/config.ts +94 -0
- package/src/commands/dynamic.ts +396 -0
- package/src/commands/login.ts +191 -0
- package/src/commands/logout.ts +43 -0
- package/src/commands/offer.ts +96 -0
- package/src/commands/switch.ts +72 -0
- package/src/commands/token.ts +23 -0
- package/src/commands/whoami.ts +50 -0
- package/src/graphql/client.ts +257 -0
- package/src/graphql/generated/gql.ts +106 -0
- package/src/graphql/generated/graphql.ts +7732 -0
- package/src/graphql/generated/index.ts +1 -0
- package/src/graphql/introspection.ts +240 -0
- package/src/graphql/operations/common.ts +115 -0
- package/src/graphql/operations/hermes.ts +54 -0
- package/src/graphql/query-builder.ts +236 -0
- package/src/index.ts +176 -0
- package/src/lib/auth.ts +58 -0
- package/src/lib/browser.ts +6 -0
- package/src/lib/company.ts +35 -0
- package/src/lib/config.ts +73 -0
- package/src/lib/env.ts +10 -0
- package/src/lib/output.ts +84 -0
- package/src/lib/parse.ts +8 -0
- package/src/lib/sentry.ts +77 -0
- package/src/lib/sequence-buffer.ts +95 -0
- package/src/lib/version-check.ts +88 -0
- package/src/types/marked-terminal.d.ts +20 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./gql.js";
|
|
@@ -0,0 +1,240 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
companies {
|
|
15
|
+
nodes {
|
|
16
|
+
id
|
|
17
|
+
name
|
|
18
|
+
slug
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
memberships {
|
|
22
|
+
nodes {
|
|
23
|
+
conversation {
|
|
24
|
+
id
|
|
25
|
+
}
|
|
26
|
+
company {
|
|
27
|
+
id
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
`);
|
|
34
|
+
|
|
35
|
+
// ── Chat ──
|
|
36
|
+
|
|
37
|
+
export const Conversation = gql(`
|
|
38
|
+
query Conversation($id: ID!) {
|
|
39
|
+
node(id: $id) {
|
|
40
|
+
... on Conversation {
|
|
41
|
+
id
|
|
42
|
+
title
|
|
43
|
+
status
|
|
44
|
+
modelId
|
|
45
|
+
createdAt
|
|
46
|
+
updatedAt
|
|
47
|
+
messages(last: 50) {
|
|
48
|
+
nodes {
|
|
49
|
+
id
|
|
50
|
+
role
|
|
51
|
+
content
|
|
52
|
+
modelId
|
|
53
|
+
inputTokens
|
|
54
|
+
outputTokens
|
|
55
|
+
createdAt
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
`);
|
|
62
|
+
|
|
63
|
+
export const SendMessage = gql(`
|
|
64
|
+
mutation SendMessage($input: SendMessageInput!) {
|
|
65
|
+
sendMessage(input: $input) {
|
|
66
|
+
id
|
|
67
|
+
role
|
|
68
|
+
content
|
|
69
|
+
createdAt
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
`);
|
|
73
|
+
|
|
74
|
+
export const RespondToToolCall = gql(`
|
|
75
|
+
mutation RespondToToolCall($input: RespondToToolCallInput!) {
|
|
76
|
+
respondToToolCall(input: $input) {
|
|
77
|
+
ok
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
`);
|
|
81
|
+
|
|
82
|
+
export const CancelConversation = gql(`
|
|
83
|
+
mutation CancelConversation($input: CancelConversationInput!) {
|
|
84
|
+
cancelConversation(input: $input) {
|
|
85
|
+
ok
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
`);
|
|
89
|
+
|
|
90
|
+
export const CreateSalesOffer = gql(`
|
|
91
|
+
mutation CreateSalesOffer($input: CreateSalesOfferInput!) {
|
|
92
|
+
createSalesOffer(input: $input) {
|
|
93
|
+
inviteUrl
|
|
94
|
+
offerId
|
|
95
|
+
companyId
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
`);
|
|
99
|
+
|
|
100
|
+
export const ConversationEvent = gql(`
|
|
101
|
+
subscription ConversationEvent($conversationId: ID!) {
|
|
102
|
+
conversationEvent(conversationId: $conversationId) {
|
|
103
|
+
__typename
|
|
104
|
+
agentLoopId
|
|
105
|
+
agentLoopSequence
|
|
106
|
+
... on MessageChunkEvent { content }
|
|
107
|
+
... on ToolCallEvent { toolName toolCallId arguments }
|
|
108
|
+
... on ToolResultEvent { toolCallId content }
|
|
109
|
+
... on AgentPickedEvent { agent reason turn }
|
|
110
|
+
... on SupervisorVerdictEvent { verdict reason turn }
|
|
111
|
+
... on AgentLoopCompletedEvent { messageId }
|
|
112
|
+
... on AgentLoopFailedEvent { message }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
`);
|
|
@@ -0,0 +1,54 @@
|
|
|
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
|
+
`);
|
|
@@ -0,0 +1,236 @@
|
|
|
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: 1) */
|
|
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
|
|
66
|
+
if (type.name.endsWith('Connection') && fields.nodes && fields.pageInfo) {
|
|
67
|
+
const nodesType = unwrap(fields.nodes.type);
|
|
68
|
+
const nodeSelections = buildSelections(nodesType, schema, 0, exclude, `${prefix}nodes.`, new Set(visited));
|
|
69
|
+
if (nodeSelections.length === 0) return [];
|
|
70
|
+
lines.push(`nodes {`);
|
|
71
|
+
for (const sel of nodeSelections) lines.push(` ${sel}`);
|
|
72
|
+
lines.push(`}`);
|
|
73
|
+
lines.push(`pageInfo {`);
|
|
74
|
+
lines.push(` hasNextPage`);
|
|
75
|
+
lines.push(` endCursor`);
|
|
76
|
+
lines.push(`}`);
|
|
77
|
+
if (fields.totalCount) lines.push(`totalCount`);
|
|
78
|
+
return lines;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
82
|
+
if (name.startsWith('__')) continue;
|
|
83
|
+
if (name === 'id' && isPayload) continue;
|
|
84
|
+
|
|
85
|
+
const fullPath = `${prefix}${name}`;
|
|
86
|
+
if (exclude.has(fullPath) || exclude.has(name)) continue;
|
|
87
|
+
|
|
88
|
+
// Skip fields with required arguments
|
|
89
|
+
const hasRequiredArgs = field.args.some((a) => isNonNullType(a.type) && a.defaultValue === undefined);
|
|
90
|
+
if (hasRequiredArgs) continue;
|
|
91
|
+
|
|
92
|
+
const namedType = unwrap(field.type);
|
|
93
|
+
|
|
94
|
+
if (isLeaf(namedType)) {
|
|
95
|
+
lines.push(name);
|
|
96
|
+
} else if (isObjectType(namedType) && depth > 0) {
|
|
97
|
+
const subSelections = buildSelections(namedType, schema, depth - 1, exclude, `${fullPath}.`, new Set(visited));
|
|
98
|
+
if (subSelections.length > 0) {
|
|
99
|
+
lines.push(`${name} {`);
|
|
100
|
+
for (const sel of subSelections) lines.push(` ${sel}`);
|
|
101
|
+
lines.push(`}`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// Skip interfaces, unions at sub-levels
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return lines;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ── Public API ──
|
|
111
|
+
|
|
112
|
+
export interface BuiltQuery {
|
|
113
|
+
query: string;
|
|
114
|
+
variables: Record<string, unknown>;
|
|
115
|
+
/** The root field name (e.g. "agency", "createChat") */
|
|
116
|
+
fieldName: string;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Build a GraphQL query/mutation string for a root operation field.
|
|
121
|
+
*
|
|
122
|
+
* @param schema - The introspected GraphQL schema
|
|
123
|
+
* @param kind - "query" or "mutation"
|
|
124
|
+
* @param fieldName - The root field name (e.g. "agency", "createChat")
|
|
125
|
+
* @param variables - Variable values to send
|
|
126
|
+
* @param options - Depth, field inclusion/exclusion
|
|
127
|
+
*/
|
|
128
|
+
export function buildQuery(
|
|
129
|
+
schema: GraphQLSchema,
|
|
130
|
+
kind: 'query' | 'mutation',
|
|
131
|
+
fieldName: string,
|
|
132
|
+
variables: Record<string, unknown>,
|
|
133
|
+
options: QueryOptions = {},
|
|
134
|
+
): BuiltQuery {
|
|
135
|
+
const rootType = kind === 'query' ? schema.getQueryType() : schema.getMutationType();
|
|
136
|
+
if (!rootType) throw new Error(`No ${kind} type in schema`);
|
|
137
|
+
|
|
138
|
+
const field = rootType.getFields()[fieldName];
|
|
139
|
+
if (!field) throw new Error(`Unknown ${kind} field: ${fieldName}`);
|
|
140
|
+
|
|
141
|
+
const depth = options.depth ?? 0;
|
|
142
|
+
const exclude = new Set(options.exclude ?? []);
|
|
143
|
+
|
|
144
|
+
const returnType = unwrap(field.type);
|
|
145
|
+
|
|
146
|
+
// Build variable definitions from the field's arguments
|
|
147
|
+
const allArgs = field.args;
|
|
148
|
+
|
|
149
|
+
const varDefsInner = allArgs.map((a) => `$${a.name}: ${a.type.toString()}`).join(', ');
|
|
150
|
+
const fieldArgsInner = allArgs.map((a) => `${a.name}: $${a.name}`).join(', ');
|
|
151
|
+
const varDefs = allArgs.length > 0 ? `(${varDefsInner})` : '';
|
|
152
|
+
const fieldArgs = allArgs.length > 0 ? `(${fieldArgsInner})` : '';
|
|
153
|
+
|
|
154
|
+
// Build selection set
|
|
155
|
+
let selectionBody: string;
|
|
156
|
+
if (isLeaf(returnType) || isInterfaceType(returnType) || isUnionType(returnType)) {
|
|
157
|
+
// Scalar return or interface/union — no sub-selections
|
|
158
|
+
selectionBody = ` ${fieldName}${fieldArgs}`;
|
|
159
|
+
} else {
|
|
160
|
+
// Filter fields if --fields is provided
|
|
161
|
+
let selections: string[];
|
|
162
|
+
if (options.fields && options.fields.length > 0) {
|
|
163
|
+
selections = buildFieldsFromList(returnType, schema, options.fields);
|
|
164
|
+
} else {
|
|
165
|
+
selections = buildSelections(returnType, schema, depth, exclude, '', new Set());
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (selections.length === 0) {
|
|
169
|
+
// Fallback: at minimum select __typename
|
|
170
|
+
selectionBody = ` ${fieldName}${fieldArgs} {\n __typename\n }`;
|
|
171
|
+
} else {
|
|
172
|
+
const indent = ' ';
|
|
173
|
+
const body = selections.map((s) => `${indent}${s}`).join('\n');
|
|
174
|
+
selectionBody = ` ${fieldName}${fieldArgs} {\n${body}\n }`;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const opName = ucfirst(fieldName);
|
|
179
|
+
const query = `${kind} ${opName}${varDefs} {\n${selectionBody}\n }`;
|
|
180
|
+
|
|
181
|
+
return { query, variables, fieldName };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Build selections from an explicit field list (e.g. --fields id,name,slug).
|
|
186
|
+
*/
|
|
187
|
+
function buildFieldsFromList(type: GraphQLNamedType, schema: GraphQLSchema, fieldPaths: string[]): string[] {
|
|
188
|
+
if (!isObjectType(type)) return [];
|
|
189
|
+
const fields = type.getFields();
|
|
190
|
+
|
|
191
|
+
// Relay Connection pattern — unwrap to the node type
|
|
192
|
+
if (type.name.endsWith('Connection') && fields.nodes && fields.pageInfo) {
|
|
193
|
+
const nodesType = unwrap(fields.nodes.type);
|
|
194
|
+
const nodeSelections = buildFieldsFromList(nodesType, schema, fieldPaths);
|
|
195
|
+
if (nodeSelections.length === 0) return [];
|
|
196
|
+
const lines: string[] = [];
|
|
197
|
+
lines.push('nodes {');
|
|
198
|
+
for (const sel of nodeSelections) lines.push(` ${sel}`);
|
|
199
|
+
lines.push('}');
|
|
200
|
+
lines.push('pageInfo {');
|
|
201
|
+
lines.push(' hasNextPage');
|
|
202
|
+
lines.push(' endCursor');
|
|
203
|
+
lines.push('}');
|
|
204
|
+
if (fields.totalCount) lines.push('totalCount');
|
|
205
|
+
return lines;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const lines: string[] = [];
|
|
209
|
+
|
|
210
|
+
// Group by top-level field
|
|
211
|
+
const grouped = new Map<string, string[]>();
|
|
212
|
+
for (const fp of fieldPaths) {
|
|
213
|
+
const [top, ...rest] = fp.split('.');
|
|
214
|
+
if (!grouped.has(top)) grouped.set(top, []);
|
|
215
|
+
if (rest.length > 0) grouped.get(top)!.push(rest.join('.'));
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
for (const [name, subPaths] of grouped) {
|
|
219
|
+
const field = fields[name];
|
|
220
|
+
if (!field) continue;
|
|
221
|
+
|
|
222
|
+
const namedType = unwrap(field.type);
|
|
223
|
+
if (isLeaf(namedType)) {
|
|
224
|
+
lines.push(name);
|
|
225
|
+
} else if (isObjectType(namedType) && subPaths.length > 0) {
|
|
226
|
+
const subSelections = buildFieldsFromList(namedType, schema, subPaths);
|
|
227
|
+
if (subSelections.length > 0) {
|
|
228
|
+
lines.push(`${name} {`);
|
|
229
|
+
for (const sel of subSelections) lines.push(` ${sel}`);
|
|
230
|
+
lines.push(`}`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return lines;
|
|
236
|
+
}
|