-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathintrospect-graphql-schema.ts
407 lines (354 loc) · 12 KB
/
introspect-graphql-schema.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import fs from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";
import zlib from "zlib";
import { existsSync } from "fs";
// Get the directory name for the current module
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Path to the schemas configuration file
export const SCHEMAS_CONFIG_PATH = path.join(
__dirname,
"..",
"data",
"schemas.json"
);
// Function to get the schema path for a specific API
export async function getSchemaPath(
api: string,
version?: string
): Promise<string> {
try {
const schemasConfigContent = await fs.readFile(SCHEMAS_CONFIG_PATH, "utf8");
const schemasConfig = JSON.parse(schemasConfigContent);
const schemaConfig = schemasConfig.find(
(config: any) =>
config.api === api && (!version || config.version === version)
);
if (!schemaConfig) {
throw new Error(
`Schema configuration for API "${api}"${
version ? ` version "${version}"` : ""
} not found`
);
}
return path.join(__dirname, "..", "data", schemaConfig.file);
} catch (error) {
console.error(
`[shopify-admin-schema-tool] Error reading schema configuration: ${error}`
);
throw error;
}
}
// Function to load schema content, handling decompression if needed
export async function loadSchemaContent(schemaPath: string): Promise<string> {
// Strip .gz extension if present for the uncompressed path check
const uncompressedPath = schemaPath.endsWith(".gz")
? schemaPath.slice(0, -3)
: schemaPath;
// If uncompressed file doesn't exist but gzipped does, decompress it
if (!existsSync(uncompressedPath) && existsSync(schemaPath)) {
console.error(
`[shopify-admin-schema-tool] Decompressing GraphQL schema from ${schemaPath}`
);
const compressedData = await fs.readFile(schemaPath);
const schemaContent = zlib.gunzipSync(compressedData).toString("utf-8");
// Save the uncompressed content to disk
await fs.writeFile(uncompressedPath, schemaContent, "utf-8");
console.error(
`[shopify-admin-schema-tool] Saved uncompressed schema to ${uncompressedPath}`
);
return schemaContent;
}
// If uncompressed file exists, read it directly
if (existsSync(uncompressedPath)) {
console.error(
`[shopify-admin-schema-tool] Reading GraphQL schema from ${uncompressedPath}`
);
return fs.readFile(uncompressedPath, "utf8");
}
throw new Error(`Schema file not found: ${schemaPath}`);
}
// Maximum number of fields to extract from an object
export const MAX_FIELDS_TO_SHOW = 50;
// Helper function to filter, sort, and truncate schema items
export const filterAndSortItems = (
items: any[],
searchTerm: string,
maxItems: number
) => {
// Filter items based on search term
const filtered = items.filter((item: any) =>
item.name?.toLowerCase().includes(searchTerm)
);
// Sort filtered items by name length (shorter names first)
filtered.sort((a: any, b: any) => {
if (!a.name) return 1;
if (!b.name) return -1;
return a.name.length - b.name.length;
});
// Return truncation info and limited items
return {
wasTruncated: filtered.length > maxItems,
items: filtered.slice(0, maxItems),
};
};
// Helper functions to format GraphQL schema types as plain text
export const formatType = (type: any): string => {
if (!type) return "null";
if (type.kind === "NON_NULL") {
return `${formatType(type.ofType)}!`;
} else if (type.kind === "LIST") {
return `[${formatType(type.ofType)}]`;
} else {
return type.name;
}
};
export const formatArg = (arg: any): string => {
return `${arg.name}: ${formatType(arg.type)}${
arg.defaultValue !== null ? ` = ${arg.defaultValue}` : ""
}`;
};
export const formatField = (field: any): string => {
let result = ` ${field.name}`;
// Add arguments if present
if (field.args && field.args.length > 0) {
result += `(${field.args.map(formatArg).join(", ")})`;
}
result += `: ${formatType(field.type)}`;
// Add deprecation info if present
if (field.isDeprecated) {
result += ` @deprecated`;
if (field.deprecationReason) {
result += ` (${field.deprecationReason})`;
}
}
return result;
};
export const formatSchemaType = (item: any): string => {
let result = `${item.kind} ${item.name}`;
if (item.description) {
// Truncate description if too long
const maxDescLength = 150;
const desc = item.description.replace(/\n/g, " ");
result += `\n Description: ${
desc.length > maxDescLength
? desc.substring(0, maxDescLength) + "..."
: desc
}`;
}
// Add interfaces if present
if (item.interfaces && item.interfaces.length > 0) {
result += `\n Implements: ${item.interfaces
.map((i: any) => i.name)
.join(", ")}`;
}
// For INPUT_OBJECT types, use inputFields instead of fields
if (
item.kind === "INPUT_OBJECT" &&
item.inputFields &&
item.inputFields.length > 0
) {
result += "\n Input Fields:";
// Extract at most MAX_FIELDS_TO_SHOW fields
const fieldsToShow = item.inputFields.slice(0, MAX_FIELDS_TO_SHOW);
for (const field of fieldsToShow) {
result += `\n${formatField(field)}`;
}
if (item.inputFields.length > MAX_FIELDS_TO_SHOW) {
result += `\n ... and ${
item.inputFields.length - MAX_FIELDS_TO_SHOW
} more input fields`;
}
}
// For regular object types, use fields
else if (item.fields && item.fields.length > 0) {
result += "\n Fields:";
// Extract at most MAX_FIELDS_TO_SHOW fields
const fieldsToShow = item.fields.slice(0, MAX_FIELDS_TO_SHOW);
for (const field of fieldsToShow) {
result += `\n${formatField(field)}`;
}
if (item.fields.length > MAX_FIELDS_TO_SHOW) {
result += `\n ... and ${
item.fields.length - MAX_FIELDS_TO_SHOW
} more fields`;
}
}
return result;
};
export const formatGraphqlOperation = (query: any): string => {
let result = `${query.name}`;
if (query.description) {
// Truncate description if too long
const maxDescLength = 100;
const desc = query.description.replace(/\n/g, " ");
result += `\n Description: ${
desc.length > maxDescLength
? desc.substring(0, maxDescLength) + "..."
: desc
}`;
}
// Add arguments if present
if (query.args && query.args.length > 0) {
result += "\n Arguments:";
for (const arg of query.args) {
result += `\n ${formatArg(arg)}`;
}
}
// Add return type
result += `\n Returns: ${formatType(query.type)}`;
return result;
};
// Function to search and format schema data
export async function introspectGraphqlSchema(
query: string,
{
api = "admin",
version = "2025-01",
filter = ["all"],
}: {
api?: "admin" | "storefront";
version?: "2024-04" | "2024-07" | "2024-10" | "2025-01";
filter?: Array<"all" | "types" | "queries" | "mutations">;
} = {}
) {
try {
// Get the appropriate schema path based on the API and version
const schemaPath = await getSchemaPath(api, version);
// Load the schema content
const schemaContent = await loadSchemaContent(schemaPath);
// Parse the schema content
const schemaJson = JSON.parse(schemaContent);
// If a query is provided, filter the schema
let resultSchema = schemaJson;
let wasTruncated = false;
let queriesWereTruncated = false;
let mutationsWereTruncated = false;
if (query && query.trim()) {
// Normalize search term: remove trailing 's' and remove all spaces
let normalizedQuery = query.trim();
if (normalizedQuery.endsWith("s")) {
normalizedQuery = normalizedQuery.slice(0, -1);
}
normalizedQuery = normalizedQuery.replace(/\s+/g, "");
console.error(
`[shopify-admin-schema-tool] Filtering schema with query: ${query} (normalized: ${normalizedQuery})`
);
const searchTerm = normalizedQuery.toLowerCase();
// Example filtering logic (adjust based on actual schema structure)
if (schemaJson?.data?.__schema?.types) {
const MAX_RESULTS = 10;
// Process types
const processedTypes = filterAndSortItems(
schemaJson.data.__schema.types,
searchTerm,
MAX_RESULTS
);
wasTruncated = processedTypes.wasTruncated;
const limitedTypes = processedTypes.items;
// Find the Query and Mutation types
const queryType = schemaJson.data.__schema.types.find(
(type: any) => type.name === "QueryRoot"
);
const mutationType = schemaJson.data.__schema.types.find(
(type: any) => type.name === "Mutation"
);
// Process queries if available
let matchingQueries: any[] = [];
if (
queryType &&
queryType.fields &&
(filter.includes("all") || filter.includes("queries"))
) {
const processedQueries = filterAndSortItems(
queryType.fields,
searchTerm,
MAX_RESULTS
);
queriesWereTruncated = processedQueries.wasTruncated;
matchingQueries = processedQueries.items;
}
// Process mutations if available
let matchingMutations: any[] = [];
if (
mutationType &&
mutationType.fields &&
(filter.includes("all") || filter.includes("mutations"))
) {
const processedMutations = filterAndSortItems(
mutationType.fields,
searchTerm,
MAX_RESULTS
);
mutationsWereTruncated = processedMutations.wasTruncated;
matchingMutations = processedMutations.items;
}
// Create a modified schema that includes matching types
resultSchema = {
data: {
__schema: {
...schemaJson.data.__schema,
types: limitedTypes,
matchingQueries,
matchingMutations,
},
},
};
}
}
// Create the response text with truncation message if needed
let responseText = "";
if (filter.includes("all") || filter.includes("types")) {
responseText += "## Matching GraphQL Types:\n";
if (wasTruncated) {
responseText += `(Results limited to 10 items. Refine your search for more specific results.)\n\n`;
}
if (resultSchema.data.__schema.types.length > 0) {
responseText +=
resultSchema.data.__schema.types.map(formatSchemaType).join("\n\n") +
"\n\n";
} else {
responseText += "No matching types found.\n\n";
}
}
// Add queries section if showing all or queries
if (filter.includes("all") || filter.includes("queries")) {
responseText += "## Matching GraphQL Queries:\n";
if (queriesWereTruncated) {
responseText += `(Results limited to 10 items. Refine your search for more specific results.)\n\n`;
}
if (resultSchema.data.__schema.matchingQueries?.length > 0) {
responseText +=
resultSchema.data.__schema.matchingQueries
.map(formatGraphqlOperation)
.join("\n\n") + "\n\n";
} else {
responseText += "No matching queries found.\n\n";
}
}
// Add mutations section if showing all or mutations
if (filter.includes("all") || filter.includes("mutations")) {
responseText += "## Matching GraphQL Mutations:\n";
if (mutationsWereTruncated) {
responseText += `(Results limited to 10 items. Refine your search for more specific results.)\n\n`;
}
if (resultSchema.data.__schema.matchingMutations?.length > 0) {
responseText += resultSchema.data.__schema.matchingMutations
.map(formatGraphqlOperation)
.join("\n\n");
} else {
responseText += "No matching mutations found.";
}
}
return { success: true as const, responseText };
} catch (error) {
console.error(
`[shopify-admin-schema-tool] Error processing GraphQL schema: ${error}`
);
return {
success: false as const,
error: error instanceof Error ? error.message : String(error),
};
}
}