@contello/client 1.0.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/dist/cli.js +15 -0
- package/dist/generate-OTWB5J56.js +827 -0
- package/dist/index.cjs +476 -0
- package/dist/index.d.cts +83 -0
- package/dist/index.d.ts +83 -0
- package/dist/index.js +438 -0
- package/package.json +46 -0
|
@@ -0,0 +1,827 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/generate/index.ts
|
|
4
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
|
|
5
|
+
import { glob } from "fs/promises";
|
|
6
|
+
import { dirname, resolve as resolve2 } from "path";
|
|
7
|
+
import { parse as parse2 } from "graphql";
|
|
8
|
+
|
|
9
|
+
// src/generate/config.ts
|
|
10
|
+
import { resolve } from "path";
|
|
11
|
+
import { pathToFileURL } from "url";
|
|
12
|
+
var CONFIG_NAMES = ["contello.config.ts", "contello.config.js", "contello.config.mjs"];
|
|
13
|
+
async function loadConfig(cwd) {
|
|
14
|
+
for (const name of CONFIG_NAMES) {
|
|
15
|
+
const configPath = resolve(cwd, name);
|
|
16
|
+
try {
|
|
17
|
+
const mod = await import(pathToFileURL(configPath).href);
|
|
18
|
+
const config = mod.default ?? mod;
|
|
19
|
+
if (!config.projects || !Array.isArray(config.projects)) {
|
|
20
|
+
throw new Error(`${name}: expected "projects" to be an array`);
|
|
21
|
+
}
|
|
22
|
+
for (const [i, project] of config.projects.entries()) {
|
|
23
|
+
if (!project.url) throw new Error(`${name}: projects[${i}].url is required`);
|
|
24
|
+
if (!project.project) throw new Error(`${name}: projects[${i}].project is required`);
|
|
25
|
+
if (!project.token) throw new Error(`${name}: projects[${i}].token is required`);
|
|
26
|
+
if (!project.documents) throw new Error(`${name}: projects[${i}].documents is required`);
|
|
27
|
+
if (!project.output) throw new Error(`${name}: projects[${i}].output is required`);
|
|
28
|
+
}
|
|
29
|
+
return config;
|
|
30
|
+
} catch (e) {
|
|
31
|
+
if (e.code === "ERR_MODULE_NOT_FOUND" || e.code === "ENOENT") {
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
throw e;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
throw new Error(`no config file found (tried: ${CONFIG_NAMES.join(", ")})`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/generate/documents.ts
|
|
41
|
+
import { Kind, print } from "graphql";
|
|
42
|
+
function collectFragments(documents) {
|
|
43
|
+
const fragments = /* @__PURE__ */ new Map();
|
|
44
|
+
for (const doc of documents) {
|
|
45
|
+
for (const def of doc.definitions) {
|
|
46
|
+
if (def.kind === Kind.FRAGMENT_DEFINITION) {
|
|
47
|
+
fragments.set(def.name.value, def);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return fragments;
|
|
52
|
+
}
|
|
53
|
+
function collectOperations(documents) {
|
|
54
|
+
const operations = [];
|
|
55
|
+
const seen = /* @__PURE__ */ new Set();
|
|
56
|
+
for (const doc of documents) {
|
|
57
|
+
for (const def of doc.definitions) {
|
|
58
|
+
if (def.kind === Kind.OPERATION_DEFINITION) {
|
|
59
|
+
if (!def.name) {
|
|
60
|
+
throw new Error(`unnamed operations are not supported:
|
|
61
|
+
|
|
62
|
+
${print(def)}`);
|
|
63
|
+
}
|
|
64
|
+
if (seen.has(def.name.value)) {
|
|
65
|
+
throw new Error(`duplicate operation name: "${def.name.value}"`);
|
|
66
|
+
}
|
|
67
|
+
seen.add(def.name.value);
|
|
68
|
+
operations.push(def);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return operations;
|
|
73
|
+
}
|
|
74
|
+
function collectUsedFragments(node, allFragments, collected) {
|
|
75
|
+
const selections = [...node.selectionSet?.selections ?? []];
|
|
76
|
+
while (selections.length > 0) {
|
|
77
|
+
const sel = selections.pop();
|
|
78
|
+
if (sel.kind === Kind.FRAGMENT_SPREAD) {
|
|
79
|
+
const name = sel.name.value;
|
|
80
|
+
if (!collected.has(name)) {
|
|
81
|
+
const fragment = allFragments.get(name);
|
|
82
|
+
if (!fragment) {
|
|
83
|
+
throw new Error(`unknown fragment: "${name}"`);
|
|
84
|
+
}
|
|
85
|
+
collected.set(name, fragment);
|
|
86
|
+
collectUsedFragments(fragment, allFragments, collected);
|
|
87
|
+
}
|
|
88
|
+
} else if ("selectionSet" in sel && sel.selectionSet) {
|
|
89
|
+
selections.push(...sel.selectionSet.selections);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function sortFragmentsByDependency(fragments) {
|
|
94
|
+
const sorted = [];
|
|
95
|
+
const visited = /* @__PURE__ */ new Set();
|
|
96
|
+
function visit(name) {
|
|
97
|
+
if (visited.has(name)) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
visited.add(name);
|
|
101
|
+
const fragment = fragments.get(name);
|
|
102
|
+
if (!fragment) {
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const deps = /* @__PURE__ */ new Map();
|
|
106
|
+
collectUsedFragments(fragment, fragments, deps);
|
|
107
|
+
for (const [depName] of deps) {
|
|
108
|
+
if (depName !== name) {
|
|
109
|
+
visit(depName);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
sorted.push(fragment);
|
|
113
|
+
}
|
|
114
|
+
for (const [name] of fragments) {
|
|
115
|
+
visit(name);
|
|
116
|
+
}
|
|
117
|
+
return sorted;
|
|
118
|
+
}
|
|
119
|
+
function generateDocumentString(operation, allFragments) {
|
|
120
|
+
const usedFragments = /* @__PURE__ */ new Map();
|
|
121
|
+
collectUsedFragments(operation, allFragments, usedFragments);
|
|
122
|
+
const sortedFragments = sortFragmentsByDependency(usedFragments);
|
|
123
|
+
const parts = [...sortedFragments.map((f) => print(f)), print(operation)];
|
|
124
|
+
return parts.join("\n");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// src/generate/introspect.ts
|
|
128
|
+
import { buildClientSchema, getIntrospectionQuery } from "graphql";
|
|
129
|
+
async function introspectSchema(url, project, token) {
|
|
130
|
+
const endpoint = `${url}/graphql/projects/${project}`;
|
|
131
|
+
const response = await fetch(endpoint, {
|
|
132
|
+
method: "POST",
|
|
133
|
+
headers: { "content-type": "application/json", token },
|
|
134
|
+
body: JSON.stringify({ query: getIntrospectionQuery() })
|
|
135
|
+
});
|
|
136
|
+
if (!response.ok) {
|
|
137
|
+
throw new Error(`introspection failed: ${response.status} ${response.statusText} (${endpoint})`);
|
|
138
|
+
}
|
|
139
|
+
const json = await response.json();
|
|
140
|
+
if (json.errors?.length) {
|
|
141
|
+
throw new Error(`introspection errors: ${json.errors.map((e) => e.message).join(", ")}`);
|
|
142
|
+
}
|
|
143
|
+
if (!json.data) {
|
|
144
|
+
throw new Error(`introspection returned no data (${endpoint})`);
|
|
145
|
+
}
|
|
146
|
+
return buildClientSchema(json.data);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/generate/operation-types.ts
|
|
150
|
+
import {
|
|
151
|
+
Kind as Kind2,
|
|
152
|
+
isCompositeType,
|
|
153
|
+
isEnumType,
|
|
154
|
+
isInterfaceType,
|
|
155
|
+
isListType,
|
|
156
|
+
isNonNullType,
|
|
157
|
+
isObjectType,
|
|
158
|
+
isScalarType,
|
|
159
|
+
typeFromAST
|
|
160
|
+
} from "graphql";
|
|
161
|
+
|
|
162
|
+
// src/generate/scalar-types.ts
|
|
163
|
+
var SCALAR_MAP = {
|
|
164
|
+
String: "string",
|
|
165
|
+
Int: "number",
|
|
166
|
+
Float: "number",
|
|
167
|
+
Boolean: "boolean",
|
|
168
|
+
ID: "string",
|
|
169
|
+
DateTime: "string"
|
|
170
|
+
};
|
|
171
|
+
var DEFAULT_CUSTOM_SCALAR = "unknown";
|
|
172
|
+
function resolveScalarType(name) {
|
|
173
|
+
return SCALAR_MAP[name] ?? DEFAULT_CUSTOM_SCALAR;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// src/generate/utils.ts
|
|
177
|
+
function uncapitalize(name) {
|
|
178
|
+
return name.charAt(0).toLowerCase() + name.slice(1);
|
|
179
|
+
}
|
|
180
|
+
function pascalCase(name) {
|
|
181
|
+
return name.charAt(0).toUpperCase() + name.slice(1);
|
|
182
|
+
}
|
|
183
|
+
function deriveModelName(typeName) {
|
|
184
|
+
for (const suffix of ["Entity", "Component"]) {
|
|
185
|
+
if (typeName.endsWith(suffix)) {
|
|
186
|
+
return uncapitalize(typeName.slice(0, -suffix.length));
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return void 0;
|
|
190
|
+
}
|
|
191
|
+
function isContelloModel(schema, typeName) {
|
|
192
|
+
for (const unionName of ["ContelloEntity", "ContelloComponent"]) {
|
|
193
|
+
const union = schema.getType(unionName);
|
|
194
|
+
if (union && typeof union === "object" && "getTypes" in union) {
|
|
195
|
+
const members = union.getTypes();
|
|
196
|
+
if (members.some((m) => m.name === typeName)) {
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// src/generate/operation-types.ts
|
|
205
|
+
function unwrapType(type) {
|
|
206
|
+
let isList = false;
|
|
207
|
+
let isNonNull = false;
|
|
208
|
+
let current = type;
|
|
209
|
+
if (isNonNullType(current)) {
|
|
210
|
+
isNonNull = true;
|
|
211
|
+
current = current.ofType;
|
|
212
|
+
}
|
|
213
|
+
if (isListType(current)) {
|
|
214
|
+
isList = true;
|
|
215
|
+
current = current.ofType;
|
|
216
|
+
if (isNonNullType(current)) {
|
|
217
|
+
current = current.ofType;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return { namedType: current, isList, isNonNull };
|
|
221
|
+
}
|
|
222
|
+
function resolveSelectionSet(schema, selectionSet, parentType, fragments, indent, visited) {
|
|
223
|
+
const fields = [];
|
|
224
|
+
const inlineUnions = [];
|
|
225
|
+
let hasTypenameField = false;
|
|
226
|
+
for (const selection of selectionSet.selections) {
|
|
227
|
+
if (selection.kind === Kind2.FIELD) {
|
|
228
|
+
const fieldName = selection.alias?.value ?? selection.name.value;
|
|
229
|
+
if (selection.name.value === "__typename") {
|
|
230
|
+
hasTypenameField = true;
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
const schemaField = isObjectType(parentType) || isInterfaceType(parentType) ? parentType.getFields()[selection.name.value] : void 0;
|
|
234
|
+
if (!schemaField) {
|
|
235
|
+
throw new Error(`field "${selection.name.value}" does not exist on type "${parentType.name}"`);
|
|
236
|
+
}
|
|
237
|
+
const { namedType, isList, isNonNull } = unwrapType(schemaField.type);
|
|
238
|
+
let tsType;
|
|
239
|
+
if (selection.selectionSet && isCompositeType(namedType)) {
|
|
240
|
+
tsType = resolveSelectionSetType(schema, selection.selectionSet, namedType, fragments, `${indent} `, visited);
|
|
241
|
+
} else if (isScalarType(namedType)) {
|
|
242
|
+
tsType = resolveScalarType(namedType.name);
|
|
243
|
+
} else if (isEnumType(namedType)) {
|
|
244
|
+
tsType = namedType.name;
|
|
245
|
+
} else {
|
|
246
|
+
tsType = namedType.toString();
|
|
247
|
+
}
|
|
248
|
+
if (isList) {
|
|
249
|
+
const wrapped = tsType.includes(" | ") ? `(${tsType})` : tsType;
|
|
250
|
+
tsType = `${wrapped}[]`;
|
|
251
|
+
}
|
|
252
|
+
if (isNonNull) {
|
|
253
|
+
fields.push(`${indent} ${fieldName}: ${tsType};`);
|
|
254
|
+
} else {
|
|
255
|
+
fields.push(`${indent} ${fieldName}?: ${tsType} | undefined;`);
|
|
256
|
+
}
|
|
257
|
+
} else if (selection.kind === Kind2.INLINE_FRAGMENT) {
|
|
258
|
+
if (selection.typeCondition && selection.selectionSet) {
|
|
259
|
+
const typeName = selection.typeCondition.name.value;
|
|
260
|
+
const conditionalType = schema.getType(typeName);
|
|
261
|
+
if (!conditionalType) {
|
|
262
|
+
throw new Error(`unknown type "${typeName}" in inline fragment`);
|
|
263
|
+
}
|
|
264
|
+
if (isCompositeType(conditionalType)) {
|
|
265
|
+
if (isInterfaceType(conditionalType)) {
|
|
266
|
+
const inner = resolveSelectionSet(
|
|
267
|
+
schema,
|
|
268
|
+
selection.selectionSet,
|
|
269
|
+
conditionalType,
|
|
270
|
+
fragments,
|
|
271
|
+
indent,
|
|
272
|
+
visited
|
|
273
|
+
);
|
|
274
|
+
fields.push(...inner.fields);
|
|
275
|
+
} else if (isObjectType(conditionalType)) {
|
|
276
|
+
const nested = resolveSelectionSetType(
|
|
277
|
+
schema,
|
|
278
|
+
selection.selectionSet,
|
|
279
|
+
conditionalType,
|
|
280
|
+
fragments,
|
|
281
|
+
indent,
|
|
282
|
+
visited
|
|
283
|
+
);
|
|
284
|
+
if (nested.startsWith("{")) {
|
|
285
|
+
const model = isContelloModel(schema, conditionalType.name) ? deriveModelName(conditionalType.name) : void 0;
|
|
286
|
+
const discriminant = model ? `${indent} __typename: '${conditionalType.name}';
|
|
287
|
+
${indent} __model: '${model}';` : `${indent} __typename: '${conditionalType.name}';`;
|
|
288
|
+
inlineUnions.push(`{
|
|
289
|
+
${discriminant}
|
|
290
|
+
${nested.slice(2)}`);
|
|
291
|
+
} else {
|
|
292
|
+
inlineUnions.push(nested);
|
|
293
|
+
}
|
|
294
|
+
} else {
|
|
295
|
+
const nested = resolveSelectionSetType(
|
|
296
|
+
schema,
|
|
297
|
+
selection.selectionSet,
|
|
298
|
+
conditionalType,
|
|
299
|
+
fragments,
|
|
300
|
+
indent,
|
|
301
|
+
visited
|
|
302
|
+
);
|
|
303
|
+
inlineUnions.push(nested);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
} else if (selection.kind === Kind2.FRAGMENT_SPREAD) {
|
|
308
|
+
const fragmentName = selection.name.value;
|
|
309
|
+
if (visited.has(fragmentName)) {
|
|
310
|
+
inlineUnions.push(`${fragmentName}Fragment`);
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
const fragment = fragments.get(fragmentName);
|
|
314
|
+
if (fragment?.selectionSet) {
|
|
315
|
+
const fragmentType = schema.getType(fragment.typeCondition.name.value);
|
|
316
|
+
if (fragmentType && isCompositeType(fragmentType)) {
|
|
317
|
+
const nextVisited = new Set(visited);
|
|
318
|
+
nextVisited.add(fragmentName);
|
|
319
|
+
const fragmentResult = resolveSelectionSet(
|
|
320
|
+
schema,
|
|
321
|
+
fragment.selectionSet,
|
|
322
|
+
fragmentType,
|
|
323
|
+
fragments,
|
|
324
|
+
indent,
|
|
325
|
+
nextVisited
|
|
326
|
+
);
|
|
327
|
+
fields.push(...fragmentResult.fields);
|
|
328
|
+
inlineUnions.push(...fragmentResult.inlineUnions);
|
|
329
|
+
if (fragmentResult.hasTypenameField) {
|
|
330
|
+
hasTypenameField = true;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return { fields, inlineUnions, hasTypenameField };
|
|
337
|
+
}
|
|
338
|
+
function resolveSelectionSetType(schema, selectionSet, parentType, fragments, indent, visited = /* @__PURE__ */ new Set()) {
|
|
339
|
+
const { fields, inlineUnions, hasTypenameField } = resolveSelectionSet(
|
|
340
|
+
schema,
|
|
341
|
+
selectionSet,
|
|
342
|
+
parentType,
|
|
343
|
+
fragments,
|
|
344
|
+
indent,
|
|
345
|
+
visited
|
|
346
|
+
);
|
|
347
|
+
if (hasTypenameField && inlineUnions.length === 0) {
|
|
348
|
+
const typenameField = isObjectType(parentType) ? `${indent} __typename: '${parentType.name}';` : `${indent} __typename: string;`;
|
|
349
|
+
fields.unshift(typenameField);
|
|
350
|
+
}
|
|
351
|
+
if (inlineUnions.length > 0 && fields.length === 0) {
|
|
352
|
+
return inlineUnions.join(" | ");
|
|
353
|
+
}
|
|
354
|
+
const baseType = fields.length > 0 ? `{
|
|
355
|
+
${fields.join("\n")}
|
|
356
|
+
${indent}}` : "{}";
|
|
357
|
+
if (inlineUnions.length > 0) {
|
|
358
|
+
return `${baseType} & (${inlineUnions.join(" | ")})`;
|
|
359
|
+
}
|
|
360
|
+
return baseType;
|
|
361
|
+
}
|
|
362
|
+
function generateVariablesType(schema, operation) {
|
|
363
|
+
const vars = operation.variableDefinitions ?? [];
|
|
364
|
+
if (vars.length === 0) {
|
|
365
|
+
return "Record<string, never>";
|
|
366
|
+
}
|
|
367
|
+
const fields = [];
|
|
368
|
+
for (const v of vars) {
|
|
369
|
+
const varType = typeFromAST(schema, v.type);
|
|
370
|
+
if (!varType) {
|
|
371
|
+
throw new Error(`cannot resolve type for variable "$${v.variable.name.value}"`);
|
|
372
|
+
}
|
|
373
|
+
const isRequired = isNonNullType(varType) && !v.defaultValue;
|
|
374
|
+
const tsType = graphqlTypeToTs(varType);
|
|
375
|
+
if (isRequired) {
|
|
376
|
+
fields.push(` ${v.variable.name.value}: ${tsType};`);
|
|
377
|
+
} else {
|
|
378
|
+
fields.push(` ${v.variable.name.value}?: ${tsType} | undefined;`);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
return `{
|
|
382
|
+
${fields.join("\n")}
|
|
383
|
+
}`;
|
|
384
|
+
}
|
|
385
|
+
function graphqlTypeToTs(type) {
|
|
386
|
+
if (isNonNullType(type)) {
|
|
387
|
+
return graphqlTypeToTs(type.ofType);
|
|
388
|
+
}
|
|
389
|
+
if (isListType(type)) {
|
|
390
|
+
return `${graphqlTypeToTs(type.ofType)}[]`;
|
|
391
|
+
}
|
|
392
|
+
if (isScalarType(type)) {
|
|
393
|
+
return resolveScalarType(type.name);
|
|
394
|
+
}
|
|
395
|
+
if (isEnumType(type)) {
|
|
396
|
+
return type.name;
|
|
397
|
+
}
|
|
398
|
+
return type.name;
|
|
399
|
+
}
|
|
400
|
+
function generateFragmentTypes(schema, fragments) {
|
|
401
|
+
const lines = [];
|
|
402
|
+
for (const [name, fragment] of fragments) {
|
|
403
|
+
const typeName = `${name}Fragment`;
|
|
404
|
+
const parentType = schema.getType(fragment.typeCondition.name.value);
|
|
405
|
+
if (parentType && isCompositeType(parentType)) {
|
|
406
|
+
const resultType = resolveSelectionSetType(schema, fragment.selectionSet, parentType, fragments, "");
|
|
407
|
+
lines.push(`export type ${typeName} = ${resultType};`);
|
|
408
|
+
} else {
|
|
409
|
+
lines.push(`export type ${typeName} = {};`);
|
|
410
|
+
}
|
|
411
|
+
lines.push("");
|
|
412
|
+
}
|
|
413
|
+
return lines.join("\n");
|
|
414
|
+
}
|
|
415
|
+
function generateOperationTypes(schema, operations, fragments) {
|
|
416
|
+
const lines = [];
|
|
417
|
+
for (const op of operations) {
|
|
418
|
+
const name = op.name.value;
|
|
419
|
+
const typeSuffix = pascalCase(op.operation);
|
|
420
|
+
const resultTypeName = `${name}${typeSuffix}`;
|
|
421
|
+
const variablesTypeName = `${resultTypeName}Variables`;
|
|
422
|
+
const rootType = op.operation === "query" ? schema.getQueryType() : op.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
|
|
423
|
+
if (rootType && op.selectionSet) {
|
|
424
|
+
const resultType = resolveSelectionSetType(schema, op.selectionSet, rootType, fragments, "");
|
|
425
|
+
lines.push(`export type ${resultTypeName} = ${resultType};`);
|
|
426
|
+
} else {
|
|
427
|
+
lines.push(`export type ${resultTypeName} = {};`);
|
|
428
|
+
}
|
|
429
|
+
lines.push("");
|
|
430
|
+
const variablesType = generateVariablesType(schema, op);
|
|
431
|
+
lines.push(`export type ${variablesTypeName} = ${variablesType};`);
|
|
432
|
+
lines.push("");
|
|
433
|
+
}
|
|
434
|
+
return lines.join("\n");
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// src/generate/operations.ts
|
|
438
|
+
function generateOperationsObject(operations) {
|
|
439
|
+
const lines = [];
|
|
440
|
+
lines.push("export type Operations = {");
|
|
441
|
+
for (const op of operations) {
|
|
442
|
+
const name = op.name.value;
|
|
443
|
+
const camelName = uncapitalize(name);
|
|
444
|
+
const typeSuffix = pascalCase(op.operation);
|
|
445
|
+
const resultType = `${name}${typeSuffix}`;
|
|
446
|
+
const variablesType = `${resultType}Variables`;
|
|
447
|
+
lines.push(` ${camelName}: {`);
|
|
448
|
+
lines.push(` document: string;`);
|
|
449
|
+
lines.push(` kind: '${op.operation}';`);
|
|
450
|
+
lines.push(` __result?: ${resultType} | undefined;`);
|
|
451
|
+
lines.push(` __variables?: ${variablesType} | undefined;`);
|
|
452
|
+
lines.push(" };");
|
|
453
|
+
}
|
|
454
|
+
lines.push("};");
|
|
455
|
+
lines.push("");
|
|
456
|
+
lines.push("export const operations: Operations = {");
|
|
457
|
+
for (const op of operations) {
|
|
458
|
+
const camelName = uncapitalize(op.name.value);
|
|
459
|
+
lines.push(` ${camelName}: { document: ${camelName}Document, kind: '${op.operation}' },`);
|
|
460
|
+
}
|
|
461
|
+
lines.push("} as Operations;");
|
|
462
|
+
return lines.join("\n");
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// src/generate/schema-types.ts
|
|
466
|
+
import {
|
|
467
|
+
isEnumType as isEnumType2,
|
|
468
|
+
isInputObjectType,
|
|
469
|
+
isInterfaceType as isInterfaceType2,
|
|
470
|
+
isListType as isListType2,
|
|
471
|
+
isNonNullType as isNonNullType2,
|
|
472
|
+
isObjectType as isObjectType2,
|
|
473
|
+
isScalarType as isScalarType2,
|
|
474
|
+
isUnionType
|
|
475
|
+
} from "graphql";
|
|
476
|
+
function typeToTs(type, nonNull = false) {
|
|
477
|
+
if (isNonNullType2(type)) {
|
|
478
|
+
return typeToTs(type.ofType, true);
|
|
479
|
+
}
|
|
480
|
+
if (isListType2(type)) {
|
|
481
|
+
const inner = typeToTs(type.ofType);
|
|
482
|
+
const wrapped = inner.includes(" | ") ? `(${inner})` : inner;
|
|
483
|
+
return nonNull ? `${wrapped}[]` : `${wrapped}[] | undefined`;
|
|
484
|
+
}
|
|
485
|
+
let name;
|
|
486
|
+
if (isScalarType2(type)) {
|
|
487
|
+
name = resolveScalarType(type.name);
|
|
488
|
+
} else {
|
|
489
|
+
name = type.name;
|
|
490
|
+
}
|
|
491
|
+
return nonNull ? name : `${name} | undefined`;
|
|
492
|
+
}
|
|
493
|
+
function inputTypeToTs(type, nonNull = false) {
|
|
494
|
+
return typeToTs(type, nonNull);
|
|
495
|
+
}
|
|
496
|
+
function generateEnum(type) {
|
|
497
|
+
const values = type.getValues().map((v) => `'${v.value}'`).sort().join(" | ");
|
|
498
|
+
return `export type ${type.name} = ${values};`;
|
|
499
|
+
}
|
|
500
|
+
function sortedFields(type) {
|
|
501
|
+
return Object.values(type.getFields()).sort((a, b) => a.name.localeCompare(b.name));
|
|
502
|
+
}
|
|
503
|
+
function generateObjectType(type, modelNames) {
|
|
504
|
+
const fields = sortedFields(type);
|
|
505
|
+
const lines = [];
|
|
506
|
+
const model = modelNames.get(type.name);
|
|
507
|
+
lines.push(`export type ${type.name} = {`);
|
|
508
|
+
lines.push(` __typename?: '${type.name}' | undefined;`);
|
|
509
|
+
if (model) {
|
|
510
|
+
lines.push(` __model?: '${model}' | undefined;`);
|
|
511
|
+
}
|
|
512
|
+
for (const field of fields) {
|
|
513
|
+
lines.push(` ${field.name}${isNonNullType2(field.type) ? "" : "?"}: ${typeToTs(field.type)};`);
|
|
514
|
+
}
|
|
515
|
+
lines.push("};");
|
|
516
|
+
return lines.join("\n");
|
|
517
|
+
}
|
|
518
|
+
function generateInputType(type) {
|
|
519
|
+
const fields = sortedFields(type);
|
|
520
|
+
const lines = [];
|
|
521
|
+
lines.push(`export type ${type.name} = {`);
|
|
522
|
+
for (const field of fields) {
|
|
523
|
+
lines.push(` ${field.name}${isNonNullType2(field.type) ? "" : "?"}: ${inputTypeToTs(field.type)};`);
|
|
524
|
+
}
|
|
525
|
+
lines.push("};");
|
|
526
|
+
return lines.join("\n");
|
|
527
|
+
}
|
|
528
|
+
function generateUnion(type) {
|
|
529
|
+
const members = type.getTypes().map((t) => t.name).sort();
|
|
530
|
+
return `export type ${type.name} = ${members.join(" | ")};`;
|
|
531
|
+
}
|
|
532
|
+
function isInternalType(name) {
|
|
533
|
+
return name.startsWith("__");
|
|
534
|
+
}
|
|
535
|
+
function generateSchemaTypes(schema) {
|
|
536
|
+
const typeMap = schema.getTypeMap();
|
|
537
|
+
const lines = [];
|
|
538
|
+
const byName = (a, b) => a.name.localeCompare(b.name);
|
|
539
|
+
const customScalars = Object.values(typeMap).filter((t) => isScalarType2(t) && !isInternalType(t.name) && !SCALAR_MAP[t.name]).sort(byName);
|
|
540
|
+
if (customScalars.length > 0) {
|
|
541
|
+
for (const scalar of customScalars) {
|
|
542
|
+
lines.push(`export type ${scalar.name} = ${DEFAULT_CUSTOM_SCALAR};`);
|
|
543
|
+
}
|
|
544
|
+
lines.push("");
|
|
545
|
+
}
|
|
546
|
+
const enums = Object.values(typeMap).filter((t) => isEnumType2(t) && !isInternalType(t.name)).sort(byName);
|
|
547
|
+
for (const e of enums) {
|
|
548
|
+
lines.push(generateEnum(e));
|
|
549
|
+
}
|
|
550
|
+
if (enums.length > 0) {
|
|
551
|
+
lines.push("");
|
|
552
|
+
}
|
|
553
|
+
const inputs = Object.values(typeMap).filter((t) => isInputObjectType(t) && !isInternalType(t.name)).sort(byName);
|
|
554
|
+
for (const input of inputs) {
|
|
555
|
+
lines.push(generateInputType(input));
|
|
556
|
+
lines.push("");
|
|
557
|
+
}
|
|
558
|
+
const modelNames = /* @__PURE__ */ new Map();
|
|
559
|
+
for (const unionName of ["ContelloEntity", "ContelloComponent"]) {
|
|
560
|
+
const union = typeMap[unionName];
|
|
561
|
+
if (union && isUnionType(union)) {
|
|
562
|
+
for (const member of union.getTypes()) {
|
|
563
|
+
const model = deriveModelName(member.name);
|
|
564
|
+
if (model) {
|
|
565
|
+
modelNames.set(member.name, model);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
const objects = Object.values(typeMap).filter((t) => isObjectType2(t) && !isInternalType(t.name)).sort(byName);
|
|
571
|
+
for (const obj of objects) {
|
|
572
|
+
lines.push(generateObjectType(obj, modelNames));
|
|
573
|
+
lines.push("");
|
|
574
|
+
}
|
|
575
|
+
const interfaces = Object.values(typeMap).filter((t) => isInterfaceType2(t) && !isInternalType(t.name)).sort(byName);
|
|
576
|
+
for (const iface of interfaces) {
|
|
577
|
+
const fields = Object.values(iface.getFields()).sort(
|
|
578
|
+
(a, b) => a.name.localeCompare(b.name)
|
|
579
|
+
);
|
|
580
|
+
const fieldLines = [];
|
|
581
|
+
fieldLines.push(`export type ${iface.name} = {`);
|
|
582
|
+
fieldLines.push(` __typename?: string | undefined;`);
|
|
583
|
+
for (const field of fields) {
|
|
584
|
+
fieldLines.push(` ${field.name}${isNonNullType2(field.type) ? "" : "?"}: ${typeToTs(field.type)};`);
|
|
585
|
+
}
|
|
586
|
+
fieldLines.push("};");
|
|
587
|
+
lines.push(fieldLines.join("\n"));
|
|
588
|
+
lines.push("");
|
|
589
|
+
}
|
|
590
|
+
const unions = Object.values(typeMap).filter((t) => isUnionType(t) && !isInternalType(t.name)).sort(byName);
|
|
591
|
+
for (const union of unions) {
|
|
592
|
+
lines.push(generateUnion(union));
|
|
593
|
+
}
|
|
594
|
+
if (unions.length > 0) {
|
|
595
|
+
lines.push("");
|
|
596
|
+
}
|
|
597
|
+
const contelloEntityUnion = unions.find((u) => u.name === "ContelloEntity");
|
|
598
|
+
if (contelloEntityUnion) {
|
|
599
|
+
const typeNames = contelloEntityUnion.getTypes().map((t) => t.name);
|
|
600
|
+
const modelNames2 = typeNames.map((n) => n.replace(/Entity$/, "")).map((n) => n.charAt(0).toLowerCase() + n.slice(1));
|
|
601
|
+
lines.push("export const models = {");
|
|
602
|
+
for (let i = 0; i < modelNames2.length; i++) {
|
|
603
|
+
lines.push(` ${modelNames2[i]}: '${typeNames[i]}',`);
|
|
604
|
+
}
|
|
605
|
+
lines.push("} as const;");
|
|
606
|
+
lines.push("");
|
|
607
|
+
lines.push("export type ModelType = keyof typeof models;");
|
|
608
|
+
lines.push("");
|
|
609
|
+
}
|
|
610
|
+
return lines.join("\n");
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// src/generate/transform-components.ts
|
|
614
|
+
import {
|
|
615
|
+
Kind as Kind3,
|
|
616
|
+
isCompositeType as isCompositeType2,
|
|
617
|
+
isListType as isListType3,
|
|
618
|
+
isNonNullType as isNonNullType3,
|
|
619
|
+
isObjectType as isObjectType3,
|
|
620
|
+
isUnionType as isUnionType2,
|
|
621
|
+
parse
|
|
622
|
+
} from "graphql";
|
|
623
|
+
var FLAT_PREFIX = "_flat_";
|
|
624
|
+
var FLAT_COMPONENT_TYPE = "ContelloFlatComponent";
|
|
625
|
+
var COMPONENT_UNION = "ContelloComponent";
|
|
626
|
+
function isComponentUnion(schema, typeName) {
|
|
627
|
+
const type = schema.getType(typeName);
|
|
628
|
+
return !!type && isUnionType2(type) && type.name === COMPONENT_UNION;
|
|
629
|
+
}
|
|
630
|
+
function getNamedTypeName(type) {
|
|
631
|
+
if (isNonNullType3(type)) return getNamedTypeName(type.ofType);
|
|
632
|
+
if (isListType3(type)) return getNamedTypeName(type.ofType);
|
|
633
|
+
return type?.name;
|
|
634
|
+
}
|
|
635
|
+
var FLAT_REF_SELECTIONS = parse(
|
|
636
|
+
`{ __typename ... on ${FLAT_COMPONENT_TYPE} { _flatId } }`
|
|
637
|
+
).definitions.flatMap((d) => "selectionSet" in d ? [d.selectionSet] : [])[0];
|
|
638
|
+
function hasExistingFlatSpread(selectionSet) {
|
|
639
|
+
return selectionSet.selections.some(
|
|
640
|
+
(s) => s.kind === Kind3.INLINE_FRAGMENT && s.typeCondition?.name.value === FLAT_COMPONENT_TYPE
|
|
641
|
+
);
|
|
642
|
+
}
|
|
643
|
+
function addFlatRefSelections(selectionSet) {
|
|
644
|
+
if (hasExistingFlatSpread(selectionSet)) {
|
|
645
|
+
return selectionSet;
|
|
646
|
+
}
|
|
647
|
+
return {
|
|
648
|
+
...selectionSet,
|
|
649
|
+
selections: [...FLAT_REF_SELECTIONS.selections, ...selectionSet.selections]
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
function transformSelectionSet(schema, selectionSet, parentTypeName, fragments, refsOnly = false) {
|
|
653
|
+
const parentType = schema.getType(parentTypeName);
|
|
654
|
+
if (!parentType || !isObjectType3(parentType)) {
|
|
655
|
+
return selectionSet;
|
|
656
|
+
}
|
|
657
|
+
const parentFields = parentType.getFields();
|
|
658
|
+
const newSelections = [];
|
|
659
|
+
let changed = false;
|
|
660
|
+
for (const selection of selectionSet.selections) {
|
|
661
|
+
if (selection.kind === Kind3.FIELD) {
|
|
662
|
+
const fieldName = selection.name.value;
|
|
663
|
+
const schemaField = parentFields[fieldName];
|
|
664
|
+
if (!schemaField) {
|
|
665
|
+
newSelections.push(selection);
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
const namedTypeName = getNamedTypeName(schemaField.type);
|
|
669
|
+
if (namedTypeName && isComponentUnion(schema, namedTypeName) && selection.selectionSet) {
|
|
670
|
+
const flatFieldName = `${FLAT_PREFIX}${fieldName}`;
|
|
671
|
+
if (!parentFields[flatFieldName]) {
|
|
672
|
+
newSelections.push(selection);
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
changed = true;
|
|
676
|
+
const flatRefField = {
|
|
677
|
+
...selection,
|
|
678
|
+
selectionSet: FLAT_REF_SELECTIONS
|
|
679
|
+
};
|
|
680
|
+
newSelections.push(flatRefField);
|
|
681
|
+
if (!refsOnly) {
|
|
682
|
+
const flatSiblingField = {
|
|
683
|
+
kind: Kind3.FIELD,
|
|
684
|
+
name: { kind: Kind3.NAME, value: flatFieldName },
|
|
685
|
+
selectionSet: addFlatRefSelections(selection.selectionSet)
|
|
686
|
+
};
|
|
687
|
+
newSelections.push(flatSiblingField);
|
|
688
|
+
}
|
|
689
|
+
} else if (selection.selectionSet && namedTypeName) {
|
|
690
|
+
const transformed = transformSelectionSet(schema, selection.selectionSet, namedTypeName, fragments, refsOnly);
|
|
691
|
+
if (transformed !== selection.selectionSet) {
|
|
692
|
+
changed = true;
|
|
693
|
+
newSelections.push({ ...selection, selectionSet: transformed });
|
|
694
|
+
} else {
|
|
695
|
+
newSelections.push(selection);
|
|
696
|
+
}
|
|
697
|
+
} else {
|
|
698
|
+
newSelections.push(selection);
|
|
699
|
+
}
|
|
700
|
+
} else if (selection.kind === Kind3.INLINE_FRAGMENT) {
|
|
701
|
+
if (selection.typeCondition && selection.selectionSet) {
|
|
702
|
+
const typeName = selection.typeCondition.name.value;
|
|
703
|
+
const type = schema.getType(typeName);
|
|
704
|
+
if (type && isCompositeType2(type) && isObjectType3(type)) {
|
|
705
|
+
const transformed = transformSelectionSet(schema, selection.selectionSet, typeName, fragments, refsOnly);
|
|
706
|
+
if (transformed !== selection.selectionSet) {
|
|
707
|
+
changed = true;
|
|
708
|
+
newSelections.push({ ...selection, selectionSet: transformed });
|
|
709
|
+
} else {
|
|
710
|
+
newSelections.push(selection);
|
|
711
|
+
}
|
|
712
|
+
} else {
|
|
713
|
+
newSelections.push(selection);
|
|
714
|
+
}
|
|
715
|
+
} else {
|
|
716
|
+
newSelections.push(selection);
|
|
717
|
+
}
|
|
718
|
+
} else if (selection.kind === Kind3.FRAGMENT_SPREAD) {
|
|
719
|
+
newSelections.push(selection);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
if (!changed) {
|
|
723
|
+
return selectionSet;
|
|
724
|
+
}
|
|
725
|
+
return { ...selectionSet, selections: newSelections };
|
|
726
|
+
}
|
|
727
|
+
function transformOperation(schema, operation, fragments) {
|
|
728
|
+
const rootType = operation.operation === "query" ? schema.getQueryType() : operation.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
|
|
729
|
+
if (!rootType || !operation.selectionSet) {
|
|
730
|
+
return operation;
|
|
731
|
+
}
|
|
732
|
+
const transformed = transformSelectionSet(schema, operation.selectionSet, rootType.name, fragments);
|
|
733
|
+
if (transformed === operation.selectionSet) {
|
|
734
|
+
return operation;
|
|
735
|
+
}
|
|
736
|
+
return { ...operation, selectionSet: transformed };
|
|
737
|
+
}
|
|
738
|
+
function transformFragment(schema, fragment, fragments) {
|
|
739
|
+
const typeName = fragment.typeCondition.name.value;
|
|
740
|
+
const type = schema.getType(typeName);
|
|
741
|
+
if (!type || !isCompositeType2(type)) {
|
|
742
|
+
return fragment;
|
|
743
|
+
}
|
|
744
|
+
let selectionSet = fragment.selectionSet;
|
|
745
|
+
if (typeName === COMPONENT_UNION) {
|
|
746
|
+
selectionSet = addFlatRefSelections(selectionSet);
|
|
747
|
+
}
|
|
748
|
+
if (isObjectType3(type)) {
|
|
749
|
+
selectionSet = transformSelectionSet(schema, selectionSet, typeName, fragments, true);
|
|
750
|
+
} else if (isUnionType2(type)) {
|
|
751
|
+
const newSelections = selectionSet.selections.map((sel) => {
|
|
752
|
+
if (sel.kind === Kind3.INLINE_FRAGMENT && sel.typeCondition && sel.selectionSet) {
|
|
753
|
+
const inlineTypeName = sel.typeCondition.name.value;
|
|
754
|
+
const inlineType = schema.getType(inlineTypeName);
|
|
755
|
+
if (inlineType && isObjectType3(inlineType)) {
|
|
756
|
+
const transformed = transformSelectionSet(schema, sel.selectionSet, inlineTypeName, fragments, true);
|
|
757
|
+
if (transformed !== sel.selectionSet) {
|
|
758
|
+
return { ...sel, selectionSet: transformed };
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
return sel;
|
|
763
|
+
});
|
|
764
|
+
selectionSet = { ...selectionSet, selections: newSelections };
|
|
765
|
+
}
|
|
766
|
+
if (selectionSet === fragment.selectionSet) {
|
|
767
|
+
return fragment;
|
|
768
|
+
}
|
|
769
|
+
return { ...fragment, selectionSet };
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// src/generate/index.ts
|
|
773
|
+
async function main() {
|
|
774
|
+
const cwd = process.cwd();
|
|
775
|
+
const config = await loadConfig(cwd);
|
|
776
|
+
for (const project of config.projects) {
|
|
777
|
+
console.log(`generating types for project "${project.project}"...`);
|
|
778
|
+
rmSync(resolve2(cwd, project.output), { force: true });
|
|
779
|
+
const schema = await introspectSchema(project.url, project.project, project.token);
|
|
780
|
+
const patterns = Array.isArray(project.documents) ? project.documents : [project.documents];
|
|
781
|
+
const documentPaths = (await Promise.all(patterns.map((p) => Array.fromAsync(glob(p, { cwd }))))).flat().sort();
|
|
782
|
+
if (documentPaths.length === 0) {
|
|
783
|
+
console.warn(` no documents found matching "${project.documents}"`);
|
|
784
|
+
continue;
|
|
785
|
+
}
|
|
786
|
+
const documents = documentPaths.map((p) => parse2(readFileSync(resolve2(cwd, p), "utf-8")));
|
|
787
|
+
const fragments = collectFragments(documents);
|
|
788
|
+
const operations = collectOperations(documents);
|
|
789
|
+
console.log(` found ${operations.length} operations, ${fragments.size} fragments`);
|
|
790
|
+
const transformedFragments = new Map(
|
|
791
|
+
[...fragments].map(([name, frag]) => [name, transformFragment(schema, frag, fragments)])
|
|
792
|
+
);
|
|
793
|
+
const transformedOperations = operations.map((op) => transformOperation(schema, op, transformedFragments));
|
|
794
|
+
const parts = [];
|
|
795
|
+
parts.push("/* eslint-disable */");
|
|
796
|
+
parts.push("// @ts-nocheck");
|
|
797
|
+
parts.push("/* this file is generated by contello-client \u2014 do not edit */");
|
|
798
|
+
parts.push("");
|
|
799
|
+
parts.push(generateSchemaTypes(schema));
|
|
800
|
+
parts.push(generateFragmentTypes(schema, fragments));
|
|
801
|
+
parts.push(generateOperationTypes(schema, operations, fragments));
|
|
802
|
+
for (let i = 0; i < operations.length; i++) {
|
|
803
|
+
const camelName = uncapitalize(operations[i].name.value);
|
|
804
|
+
const docString = generateDocumentString(transformedOperations[i], transformedFragments);
|
|
805
|
+
parts.push(`export const ${camelName}Document = \`${docString}\`;`);
|
|
806
|
+
parts.push("");
|
|
807
|
+
}
|
|
808
|
+
parts.push(generateOperationsObject(operations));
|
|
809
|
+
let output = parts.join("\n");
|
|
810
|
+
if (project.namespace) {
|
|
811
|
+
const indented = output.split("\n").map((line) => line ? ` ${line}` : "").join("\n");
|
|
812
|
+
output = `export namespace ${project.namespace} {
|
|
813
|
+
${indented}
|
|
814
|
+
}
|
|
815
|
+
`;
|
|
816
|
+
}
|
|
817
|
+
const outputPath = resolve2(cwd, project.output);
|
|
818
|
+
mkdirSync(dirname(outputPath), { recursive: true });
|
|
819
|
+
writeFileSync(outputPath, output, "utf-8");
|
|
820
|
+
console.log(` wrote ${outputPath}`);
|
|
821
|
+
}
|
|
822
|
+
console.log("done");
|
|
823
|
+
}
|
|
824
|
+
main().catch((err) => {
|
|
825
|
+
console.error(err);
|
|
826
|
+
process.exit(1);
|
|
827
|
+
});
|