@contello/client 2.2.2 → 2.3.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.
@@ -0,0 +1,1068 @@
1
+ #!/usr/bin/env node
2
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { glob } from "node:fs/promises";
4
+ import { dirname, relative, resolve } from "node:path";
5
+ import { Kind, NoFragmentCyclesRule, NoUnusedFragmentsRule, Source, buildClientSchema, doTypesOverlap, getIntrospectionQuery, getLocation, isCompositeType, isEnumType, isInputObjectType, isInterfaceType, isListType, isNonNullType, isObjectType, isScalarType, isUnionType, parse, print, specifiedRules, typeFromAST, validate, visit } from "graphql";
6
+ import { pathToFileURL } from "node:url";
7
+ //#region src/generate/config.ts
8
+ const CONFIG_NAMES = [
9
+ "contello.config.ts",
10
+ "contello.config.js",
11
+ "contello.config.mjs"
12
+ ];
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)) throw new Error(`${name}: expected "projects" to be an array`);
20
+ for (const [i, project] of config.projects.entries()) {
21
+ if (!project.url) throw new Error(`${name}: projects[${i}].url is required`);
22
+ if (!project.project) throw new Error(`${name}: projects[${i}].project is required`);
23
+ if (!project.token) throw new Error(`${name}: projects[${i}].token is required`);
24
+ if (!project.documents) throw new Error(`${name}: projects[${i}].documents is required`);
25
+ if (!project.output) throw new Error(`${name}: projects[${i}].output is required`);
26
+ }
27
+ return config;
28
+ } catch (error) {
29
+ if (error.code === "ERR_MODULE_NOT_FOUND" || error.code === "ENOENT") continue;
30
+ throw error;
31
+ }
32
+ }
33
+ throw new Error(`no config file found (tried: ${CONFIG_NAMES.join(", ")})`);
34
+ }
35
+ //#endregion
36
+ //#region src/generate/documents.ts
37
+ const SUPPRESSED_RULE_NAMES = /* @__PURE__ */ new Set([NoFragmentCyclesRule.name, NoUnusedFragmentsRule.name]);
38
+ const VALIDATION_RULES = specifiedRules.filter((rule) => !SUPPRESSED_RULE_NAMES.has(rule.name));
39
+ function collectFragments(documents) {
40
+ const fragments = /* @__PURE__ */ new Map();
41
+ for (const doc of documents) for (const def of doc.definitions) if (def.kind === Kind.FRAGMENT_DEFINITION) fragments.set(def.name.value, def);
42
+ return fragments;
43
+ }
44
+ function collectOperations(documents) {
45
+ const operations = [];
46
+ const seen = /* @__PURE__ */ new Set();
47
+ const definitions = documents.flatMap((doc) => doc.definitions);
48
+ for (const def of definitions) {
49
+ if (def.kind !== Kind.OPERATION_DEFINITION) continue;
50
+ if (!def.name) throw new Error(`unnamed operations are not supported:\n\n${print(def)}`);
51
+ if (seen.has(def.name.value)) throw new Error(`duplicate operation name: "${def.name.value}"`);
52
+ seen.add(def.name.value);
53
+ operations.push(def);
54
+ }
55
+ return operations;
56
+ }
57
+ function collectUsedFragments(node, allFragments, collected) {
58
+ const selections = [...node.selectionSet?.selections ?? []];
59
+ while (selections.length > 0) {
60
+ const sel = selections.pop();
61
+ if (sel.kind === Kind.FRAGMENT_SPREAD) {
62
+ const name = sel.name.value;
63
+ if (!collected.has(name)) {
64
+ const fragment = allFragments.get(name);
65
+ if (!fragment) throw new Error(`unknown fragment: "${name}"`);
66
+ collected.set(name, fragment);
67
+ collectUsedFragments(fragment, allFragments, collected);
68
+ }
69
+ } else if ("selectionSet" in sel && sel.selectionSet) selections.push(...sel.selectionSet.selections);
70
+ }
71
+ }
72
+ function sortFragmentsByDependency(fragments) {
73
+ const sorted = [];
74
+ const visited = /* @__PURE__ */ new Set();
75
+ function visit(name) {
76
+ if (visited.has(name)) return;
77
+ visited.add(name);
78
+ const fragment = fragments.get(name);
79
+ if (!fragment) return;
80
+ const deps = /* @__PURE__ */ new Map();
81
+ collectUsedFragments(fragment, fragments, deps);
82
+ for (const [depName] of deps) if (depName !== name) visit(depName);
83
+ sorted.push(fragment);
84
+ }
85
+ for (const [name] of fragments) visit(name);
86
+ return sorted;
87
+ }
88
+ function validateDocuments(schema, fragments, operations) {
89
+ const errors = validate(schema, {
90
+ kind: Kind.DOCUMENT,
91
+ definitions: [...fragments.values(), ...operations]
92
+ }, VALIDATION_RULES);
93
+ if (errors.length === 0) return;
94
+ const formatted = errors.map((err) => {
95
+ const locations = (err.nodes ?? []).map((node) => {
96
+ if (!node.loc) return null;
97
+ const { source, start } = node.loc;
98
+ const { line, column } = getLocation(source, start);
99
+ return ` at ${source.name}:${line}:${column}`;
100
+ }).filter((s) => s !== null);
101
+ return locations.length > 0 ? ` ${err.message}\n${locations.join("\n")}` : ` ${err.message}`;
102
+ });
103
+ throw new Error(`graphql validation failed:\n\n${formatted.join("\n\n")}\n`);
104
+ }
105
+ /**
106
+ * Returns the TS-source expression for an operation's document — a template literal
107
+ * interpolating each used fragment's `<Name>FragmentSchema` const on a single line
108
+ * (refs joined by escaped `\n`), followed by the inlined operation body on its own
109
+ * lines. The atomic schema consts are shared with sources, so the fragment text
110
+ * appears once in the generated file even if reused across operations.
111
+ */
112
+ function operationDocumentExpression(operation, allFragments) {
113
+ const usedFragments = /* @__PURE__ */ new Map();
114
+ collectUsedFragments(operation, allFragments, usedFragments);
115
+ const refs = sortFragmentsByDependency(usedFragments).map((f) => `\${${f.name.value}FragmentSchema}`);
116
+ return `\`${(refs.length > 0 ? [refs.join(String.raw`\n`), print(operation)] : [print(operation)]).join("\n")}\``;
117
+ }
118
+ /**
119
+ * Returns the TS-source expression for a fragment's "bundle" — the fragment plus
120
+ * its transitive deps, each referenced via its shared `<Name>FragmentSchema` const.
121
+ * If the fragment has no deps, returns the bare const identifier (no template wrap).
122
+ */
123
+ function fragmentBundleExpression(fragment, allFragments) {
124
+ const usedFragments = /* @__PURE__ */ new Map();
125
+ collectUsedFragments(fragment, allFragments, usedFragments);
126
+ usedFragments.set(fragment.name.value, fragment);
127
+ const sortedFragments = sortFragmentsByDependency(usedFragments);
128
+ if (sortedFragments.length === 1) return `${sortedFragments[0].name.value}FragmentSchema`;
129
+ return `\`${sortedFragments.map((f) => `\${${f.name.value}FragmentSchema}`).join(String.raw`\n`)}\``;
130
+ }
131
+ /** Emits `const <Name>FragmentSchema = \`...\`;` for each (transformed) fragment. */
132
+ function generateFragmentSchemas(fragments) {
133
+ return fragments.values().toArray().toSorted((a, b) => a.name.value.localeCompare(b.name.value)).map((fragment) => `const ${fragment.name.value}FragmentSchema = \`${print(fragment)}\`;`).join("\n");
134
+ }
135
+ //#endregion
136
+ //#region src/generate/introspect.ts
137
+ async function introspectSchema(url, project, token) {
138
+ const endpoint = `${url}/graphql/projects/${project}`;
139
+ const response = await fetch(endpoint, {
140
+ method: "POST",
141
+ headers: {
142
+ "content-type": "application/json",
143
+ token
144
+ },
145
+ body: JSON.stringify({ query: getIntrospectionQuery() })
146
+ });
147
+ if (!response.ok) throw new Error(`introspection failed: ${response.status} ${response.statusText} (${endpoint})`);
148
+ const json = await response.json();
149
+ if (json.errors?.length) throw new Error(`introspection errors: ${json.errors.map((e) => e.message).join(", ")}`);
150
+ if (!json.data) throw new Error(`introspection returned no data (${endpoint})`);
151
+ return buildClientSchema(json.data);
152
+ }
153
+ //#endregion
154
+ //#region src/generate/scalar-types.ts
155
+ const SCALAR_MAP = {
156
+ String: "string",
157
+ Int: "number",
158
+ Float: "number",
159
+ Boolean: "boolean",
160
+ ID: "string",
161
+ DateTime: "string",
162
+ LocalDateTime: "LocalDateTime",
163
+ LocalDate: "LocalDate"
164
+ };
165
+ const MANAGED_SCALARS = ["LocalDateTime", "LocalDate"];
166
+ const DEFAULT_CUSTOM_SCALAR = "unknown";
167
+ function resolveScalarType(name) {
168
+ return SCALAR_MAP[name] ?? "unknown";
169
+ }
170
+ //#endregion
171
+ //#region src/generate/utils.ts
172
+ /** standard sorting stub */
173
+ function compareCodeUnits(a, b) {
174
+ if (a < b) return -1;
175
+ if (a > b) return 1;
176
+ return 0;
177
+ }
178
+ function uncapitalize(name) {
179
+ return name.charAt(0).toLowerCase() + name.slice(1);
180
+ }
181
+ function pascalCase(name) {
182
+ return name.charAt(0).toUpperCase() + name.slice(1);
183
+ }
184
+ function deriveModelName(typeName) {
185
+ for (const suffix of ["Entity", "Component"]) if (typeName.endsWith(suffix)) return uncapitalize(typeName.slice(0, -suffix.length));
186
+ }
187
+ function isContelloModel(schema, typeName) {
188
+ for (const unionName of ["ContelloEntity", "ContelloComponent"]) {
189
+ const union = schema.getType(unionName);
190
+ if (union && typeof union === "object" && "getTypes" in union) {
191
+ if (union.getTypes().some((m) => m.name === typeName)) return true;
192
+ }
193
+ }
194
+ return false;
195
+ }
196
+ //#endregion
197
+ //#region src/generate/operation-types.ts
198
+ function unwrapType(type) {
199
+ let isList = false;
200
+ let isNonNull = false;
201
+ let current = type;
202
+ if (isNonNullType(current)) {
203
+ isNonNull = true;
204
+ current = current.ofType;
205
+ }
206
+ if (isListType(current)) {
207
+ isList = true;
208
+ current = current.ofType;
209
+ if (isNonNullType(current)) current = current.ofType;
210
+ }
211
+ return {
212
+ namedType: current,
213
+ isList,
214
+ isNonNull
215
+ };
216
+ }
217
+ function resolveSelectionSet(schema, selectionSet, parentType, fragments, indent) {
218
+ const fields = [];
219
+ const inlineUnions = [];
220
+ const fragmentRefs = [];
221
+ let hasTypenameField = false;
222
+ for (const selection of selectionSet.selections) {
223
+ const contribution = resolveSelection(schema, selection, parentType, fragments, indent);
224
+ fields.push(...contribution.fields);
225
+ inlineUnions.push(...contribution.inlineUnions);
226
+ fragmentRefs.push(...contribution.fragmentRefs);
227
+ if (contribution.hasTypenameField) hasTypenameField = true;
228
+ }
229
+ return {
230
+ fields,
231
+ inlineUnions,
232
+ fragmentRefs,
233
+ hasTypenameField
234
+ };
235
+ }
236
+ function resolveSelection(schema, selection, parentType, fragments, indent) {
237
+ const fields = [];
238
+ const inlineUnions = [];
239
+ const fragmentRefs = [];
240
+ switch (selection.kind) {
241
+ case Kind.FIELD: {
242
+ if (selection.name.value === "__typename") return {
243
+ fields,
244
+ inlineUnions,
245
+ fragmentRefs,
246
+ hasTypenameField: true
247
+ };
248
+ const fieldName = selection.alias?.value ?? selection.name.value;
249
+ const schemaField = isObjectType(parentType) || isInterfaceType(parentType) ? parentType.getFields()[selection.name.value] : void 0;
250
+ if (!schemaField) throw new Error(`field "${selection.name.value}" does not exist on type "${parentType.name}"`);
251
+ const { namedType, isList, isNonNull } = unwrapType(schemaField.type);
252
+ let tsType;
253
+ if (selection.selectionSet && isCompositeType(namedType)) tsType = resolveSelectionSetType(schema, selection.selectionSet, namedType, fragments, `${indent} `);
254
+ else if (isScalarType(namedType)) tsType = resolveScalarType(namedType.name);
255
+ else if (isEnumType(namedType)) tsType = namedType.name;
256
+ else tsType = namedType.toString();
257
+ if (isList) tsType = `${/[ |&]/.test(tsType) ? `(${tsType})` : tsType}[]`;
258
+ if (isNonNull) fields.push(`${indent} ${fieldName}: ${tsType};`);
259
+ else fields.push(`${indent} ${fieldName}?: ${tsType} | undefined;`);
260
+ break;
261
+ }
262
+ case Kind.INLINE_FRAGMENT:
263
+ if (selection.typeCondition && selection.selectionSet) {
264
+ const typeName = selection.typeCondition.name.value;
265
+ const conditionalType = schema.getType(typeName);
266
+ if (!conditionalType) throw new Error(`unknown type "${typeName}" in inline fragment`);
267
+ if (isCompositeType(conditionalType)) if (isInterfaceType(conditionalType)) {
268
+ const inner = resolveSelectionSet(schema, selection.selectionSet, conditionalType, fragments, indent);
269
+ fields.push(...inner.fields);
270
+ fragmentRefs.push(...inner.fragmentRefs);
271
+ } else if (isObjectType(conditionalType)) {
272
+ const nested = resolveSelectionSetType(schema, selection.selectionSet, conditionalType, fragments, indent);
273
+ const model = isContelloModel(schema, conditionalType.name) ? deriveModelName(conditionalType.name) : void 0;
274
+ if (nested.startsWith("{")) {
275
+ const discriminant = model ? `${indent} __typename: '${conditionalType.name}';\n${indent} __model: '${model}';` : `${indent} __typename: '${conditionalType.name}';`;
276
+ inlineUnions.push(`{\n${discriminant}\n${nested.slice(2)}`);
277
+ } else {
278
+ const discriminant = model ? `{\n${indent} __typename: '${conditionalType.name}';\n${indent} __model: '${model}';\n${indent}}` : `{\n${indent} __typename: '${conditionalType.name}';\n${indent}}`;
279
+ inlineUnions.push(`${discriminant} & ${nested}`);
280
+ }
281
+ } else {
282
+ const nested = resolveSelectionSetType(schema, selection.selectionSet, conditionalType, fragments, indent);
283
+ inlineUnions.push(nested);
284
+ }
285
+ }
286
+ break;
287
+ case Kind.FRAGMENT_SPREAD: {
288
+ const fragmentName = selection.name.value;
289
+ const fragment = fragments.get(fragmentName);
290
+ if (fragment?.selectionSet) {
291
+ const fragmentType = schema.getType(fragment.typeCondition.name.value);
292
+ if (fragmentType && isCompositeType(fragmentType)) {
293
+ if (!doTypesOverlap(schema, parentType, fragmentType)) throw new Error(`fragment "${fragmentName}" (on ${fragmentType.name}) cannot be spread on type "${parentType.name}"`);
294
+ fragmentRefs.push(`${fragmentName}Fragment`);
295
+ }
296
+ }
297
+ break;
298
+ }
299
+ }
300
+ return {
301
+ fields,
302
+ inlineUnions,
303
+ fragmentRefs,
304
+ hasTypenameField: false
305
+ };
306
+ }
307
+ function resolveSelectionSetType(schema, selectionSet, parentType, fragments, indent) {
308
+ const { fields, inlineUnions, fragmentRefs, hasTypenameField } = resolveSelectionSet(schema, selectionSet, parentType, fragments, indent);
309
+ if (hasTypenameField && inlineUnions.length === 0) {
310
+ const typenameField = isObjectType(parentType) ? `${indent} __typename: '${parentType.name}';` : `${indent} __typename: string;`;
311
+ fields.unshift(typenameField);
312
+ }
313
+ if (fields.length === 0 && fragmentRefs.length === 0 && inlineUnions.length > 0) return inlineUnions.join(" | ");
314
+ const parts = [];
315
+ if (fields.length > 0) parts.push(`{\n${fields.join("\n")}\n${indent}}`);
316
+ parts.push(...fragmentRefs);
317
+ if (inlineUnions.length > 0) parts.push(`(${inlineUnions.join(" | ")})`);
318
+ if (parts.length === 0) return "{}";
319
+ return parts.join(" & ");
320
+ }
321
+ function generateVariablesType(schema, operation) {
322
+ const vars = operation.variableDefinitions ?? [];
323
+ if (vars.length === 0) return "Record<string, never>";
324
+ const fields = [];
325
+ for (const v of vars) {
326
+ const varType = typeFromAST(schema, v.type);
327
+ if (!varType) throw new Error(`cannot resolve type for variable "$${v.variable.name.value}"`);
328
+ const isRequired = isNonNullType(varType) && !v.defaultValue;
329
+ const tsType = graphqlTypeToTs(varType);
330
+ if (isRequired) fields.push(` ${v.variable.name.value}: ${tsType};`);
331
+ else fields.push(` ${v.variable.name.value}?: ${tsType} | undefined;`);
332
+ }
333
+ return `{\n${fields.join("\n")}\n}`;
334
+ }
335
+ function graphqlTypeToTs(type) {
336
+ let current = type;
337
+ while (isNonNullType(current)) current = current.ofType;
338
+ if (isListType(current)) return `${graphqlTypeToTs(current.ofType)}[]`;
339
+ if (isScalarType(current)) return resolveScalarType(current.name);
340
+ if (isEnumType(current)) return current.name;
341
+ return current.name;
342
+ }
343
+ function generateFragmentTypes(schema, fragments) {
344
+ const lines = [];
345
+ for (const [name, fragment] of fragments) {
346
+ const typeName = `${name}Fragment`;
347
+ const parentType = schema.getType(fragment.typeCondition.name.value);
348
+ if (parentType && isCompositeType(parentType)) {
349
+ const resultType = resolveSelectionSetType(schema, fragment.selectionSet, parentType, fragments, "");
350
+ lines.push(`export type ${typeName} = ${resultType};`);
351
+ } else lines.push(`export type ${typeName} = {};`);
352
+ lines.push("");
353
+ }
354
+ return lines.join("\n");
355
+ }
356
+ function generateOperationTypes(schema, operations, fragments) {
357
+ const lines = [];
358
+ for (const op of operations) {
359
+ const resultTypeName = `${op.name.value}${pascalCase(op.operation)}`;
360
+ const variablesTypeName = `${resultTypeName}Variables`;
361
+ const rootType = op.operation === "query" ? schema.getQueryType() : op.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
362
+ if (rootType && op.selectionSet) {
363
+ const resultType = resolveSelectionSetType(schema, op.selectionSet, rootType, fragments, "");
364
+ lines.push(`export type ${resultTypeName} = ${resultType};`);
365
+ } else lines.push(`export type ${resultTypeName} = {};`);
366
+ lines.push("");
367
+ const variablesType = generateVariablesType(schema, op);
368
+ lines.push(`export type ${variablesTypeName} = ${variablesType};`, "");
369
+ }
370
+ return lines.join("\n");
371
+ }
372
+ //#endregion
373
+ //#region src/generate/operations.ts
374
+ /** Emits `export type Operations = { ... }`. */
375
+ function generateOperationsType(operations) {
376
+ const lines = ["export type Operations = {"];
377
+ for (const op of operations) {
378
+ const name = op.name.value;
379
+ const camelName = uncapitalize(name);
380
+ const resultType = `${name}${pascalCase(op.operation)}`;
381
+ const variablesType = `${resultType}Variables`;
382
+ lines.push(` ${camelName}: {`, ` document: string;`, ` kind: '${op.operation}';`, ` __result?: ${resultType} | undefined;`, ` __variables?: ${variablesType} | undefined;`, " };");
383
+ }
384
+ lines.push("};");
385
+ return lines.join("\n");
386
+ }
387
+ /**
388
+ * Emits the typed `operations` const body for inclusion in the schema bundle:
389
+ * const operations: Operations = { getProducts: { document: getProductsDocument, kind: 'query' }, ... };
390
+ */
391
+ function generateOperationsConst(operations) {
392
+ const lines = ["const operations: Operations = {"];
393
+ for (const op of operations) {
394
+ const camelName = uncapitalize(op.name.value);
395
+ lines.push(` ${camelName}: { document: ${camelName}Document, kind: '${op.operation}' },`);
396
+ }
397
+ lines.push("};");
398
+ return lines.join("\n");
399
+ }
400
+ //#endregion
401
+ //#region src/generate/schema-types.ts
402
+ function typeToTs(type, nonNull = false) {
403
+ let current = type;
404
+ let isNonNullWrapped = nonNull;
405
+ while (isNonNullType(current)) {
406
+ current = current.ofType;
407
+ isNonNullWrapped = true;
408
+ }
409
+ if (isListType(current)) {
410
+ const inner = typeToTs(current.ofType);
411
+ const wrapped = inner.includes(" | ") ? `(${inner})` : inner;
412
+ return isNonNullWrapped ? `${wrapped}[]` : `${wrapped}[] | undefined`;
413
+ }
414
+ const name = isScalarType(current) ? resolveScalarType(current.name) : current.name;
415
+ return isNonNullWrapped ? name : `${name} | undefined`;
416
+ }
417
+ function inputTypeToTs(type, nonNull = false) {
418
+ return typeToTs(type, nonNull);
419
+ }
420
+ function generateEnum(type) {
421
+ const values = type.getValues().map((v) => `'${v.value}'`).toSorted(compareCodeUnits).join(" | ");
422
+ return `export type ${type.name} = ${values};`;
423
+ }
424
+ function sortedFields(type) {
425
+ return Object.values(type.getFields()).toSorted((a, b) => a.name.localeCompare(b.name));
426
+ }
427
+ function generateObjectType(type, modelNames) {
428
+ const fields = sortedFields(type);
429
+ const lines = [];
430
+ const model = modelNames.get(type.name);
431
+ lines.push(`export type ${type.name} = {`, ` __typename?: '${type.name}' | undefined;`);
432
+ if (model) lines.push(` __model?: '${model}' | undefined;`);
433
+ for (const field of fields) lines.push(` ${field.name}${isNonNullType(field.type) ? "" : "?"}: ${typeToTs(field.type)};`);
434
+ lines.push("};");
435
+ return lines.join("\n");
436
+ }
437
+ function generateInputType(type) {
438
+ const fields = sortedFields(type);
439
+ const lines = [`export type ${type.name} = {`];
440
+ for (const field of fields) lines.push(` ${field.name}${isNonNullType(field.type) ? "" : "?"}: ${inputTypeToTs(field.type)};`);
441
+ lines.push("};");
442
+ return lines.join("\n");
443
+ }
444
+ function generateUnion(type) {
445
+ const members = type.getTypes().map((t) => t.name).toSorted(compareCodeUnits);
446
+ return `export type ${type.name} = ${members.join(" | ")};`;
447
+ }
448
+ function isInternalType(name) {
449
+ return name.startsWith("__");
450
+ }
451
+ function generateSchemaTypes(schema) {
452
+ const typeMap = schema.getTypeMap();
453
+ const lines = [];
454
+ const byName = (a, b) => a.name.localeCompare(b.name);
455
+ const customScalars = Object.values(typeMap).filter((t) => isScalarType(t) && !isInternalType(t.name) && !Object.hasOwn(SCALAR_MAP, t.name)).toSorted(byName);
456
+ if (customScalars.length > 0) {
457
+ for (const scalar of customScalars) lines.push(`export type ${scalar.name} = ${DEFAULT_CUSTOM_SCALAR};`);
458
+ lines.push("");
459
+ }
460
+ const enums = Object.values(typeMap).filter((t) => isEnumType(t) && !isInternalType(t.name)).toSorted(byName);
461
+ for (const e of enums) lines.push(generateEnum(e));
462
+ if (enums.length > 0) lines.push("");
463
+ const inputs = Object.values(typeMap).filter((t) => isInputObjectType(t) && !isInternalType(t.name)).toSorted(byName);
464
+ for (const input of inputs) lines.push(generateInputType(input), "");
465
+ const modelNames = /* @__PURE__ */ new Map();
466
+ const entityModelNames = /* @__PURE__ */ new Map();
467
+ for (const unionName of ["ContelloEntity", "ContelloComponent"]) {
468
+ const union = typeMap[unionName];
469
+ if (union && isUnionType(union)) for (const member of union.getTypes()) {
470
+ const model = deriveModelName(member.name);
471
+ if (model) {
472
+ modelNames.set(member.name, model);
473
+ if (unionName === "ContelloEntity") entityModelNames.set(member.name, model);
474
+ }
475
+ }
476
+ }
477
+ const objects = Object.values(typeMap).filter((t) => isObjectType(t) && !isInternalType(t.name)).toSorted(byName);
478
+ for (const obj of objects) lines.push(generateObjectType(obj, modelNames), "");
479
+ const interfaces = Object.values(typeMap).filter((t) => isInterfaceType(t) && !isInternalType(t.name)).toSorted(byName);
480
+ for (const iface of interfaces) {
481
+ const fields = Object.values(iface.getFields()).toSorted((a, b) => a.name.localeCompare(b.name));
482
+ const fieldLines = [`export type ${iface.name} = {`, ` __typename?: string | undefined;`];
483
+ for (const field of fields) fieldLines.push(` ${field.name}${isNonNullType(field.type) ? "" : "?"}: ${typeToTs(field.type)};`);
484
+ fieldLines.push("};");
485
+ lines.push(fieldLines.join("\n"), "");
486
+ }
487
+ const unions = Object.values(typeMap).filter((t) => isUnionType(t) && !isInternalType(t.name)).toSorted(byName);
488
+ for (const union of unions) lines.push(generateUnion(union));
489
+ if (unions.length > 0) lines.push("");
490
+ return lines.join("\n");
491
+ }
492
+ /**
493
+ * Returns the model-reference-name → typename map for entities in `ContelloEntity`.
494
+ * Used by the schema bundle assembly to emit `models: { category: 'CategoryEntity', ... }`.
495
+ */
496
+ function extractEntityModels(schema) {
497
+ const map = /* @__PURE__ */ new Map();
498
+ const union = schema.getTypeMap()["ContelloEntity"];
499
+ if (!union || !isUnionType(union)) return map;
500
+ for (const member of union.getTypes()) {
501
+ const model = deriveModelName(member.name);
502
+ if (model) map.set(model, member.name);
503
+ }
504
+ return map;
505
+ }
506
+ //#endregion
507
+ //#region src/generate/sources.ts
508
+ /** Built-in (non-entity) types that are source-able through dedicated Subscription fields. */
509
+ const BUILT_IN_SOURCES = [
510
+ {
511
+ typeName: "ContelloRoute",
512
+ cardinality: "route",
513
+ fieldName: "contelloRoutesBatch"
514
+ },
515
+ {
516
+ typeName: "ContelloAsset",
517
+ cardinality: "asset",
518
+ fieldName: "contelloAssetsBatch"
519
+ },
520
+ {
521
+ typeName: "ContelloI18nMessage",
522
+ cardinality: "i18nMessage",
523
+ fieldName: "contelloI18nMessagesBatch"
524
+ }
525
+ ];
526
+ /**
527
+ * Walks Subscription fields once and indexes, for each contello-entity type, the
528
+ * subscription that feeds the store (a `[Entity!]!` field → entity-collection; a non-list
529
+ * `Entity` field → singleton). Types without a matching Subscription field don't
530
+ * appear in the map and stay non-source-able.
531
+ */
532
+ function indexEntitySources(schema) {
533
+ const result = /* @__PURE__ */ new Map();
534
+ const subscription = schema.getSubscriptionType();
535
+ if (!subscription) return result;
536
+ const singletonCandidates = /* @__PURE__ */ new Map();
537
+ for (const field of Object.values(subscription.getFields())) {
538
+ const { entityType, isList } = unwrapEntity(field.type);
539
+ if (!entityType || !isContelloModel(schema, entityType.name)) continue;
540
+ const model = deriveModelName(entityType.name);
541
+ if (!model) continue;
542
+ if (isList) result.set(entityType.name, {
543
+ cardinality: "entity",
544
+ fieldName: field.name,
545
+ model
546
+ });
547
+ else if (!singletonCandidates.has(entityType.name)) singletonCandidates.set(entityType.name, { fieldName: field.name });
548
+ }
549
+ for (const [typeName, { fieldName }] of singletonCandidates) {
550
+ if (result.has(typeName)) continue;
551
+ const model = deriveModelName(typeName);
552
+ if (!model) continue;
553
+ result.set(typeName, {
554
+ cardinality: "singleton",
555
+ fieldName,
556
+ model
557
+ });
558
+ }
559
+ return result;
560
+ }
561
+ /**
562
+ * Indexes the built-in (route/asset/i18nMessage) types that the schema actually exposes
563
+ * as batch subscriptions. A type is included only when both the GraphQL type and the
564
+ * matching subscription field are present.
565
+ */
566
+ function indexBuiltInSources(schema) {
567
+ const result = /* @__PURE__ */ new Map();
568
+ const subscription = schema.getSubscriptionType();
569
+ if (!subscription) return result;
570
+ const fields = subscription.getFields();
571
+ for (const builtIn of BUILT_IN_SOURCES) {
572
+ if (!schema.getType(builtIn.typeName) || !Object.hasOwn(fields, builtIn.fieldName)) continue;
573
+ result.set(builtIn.typeName, {
574
+ cardinality: builtIn.cardinality,
575
+ fieldName: builtIn.fieldName
576
+ });
577
+ }
578
+ return result;
579
+ }
580
+ function unwrapEntity(type) {
581
+ let current = type;
582
+ let isList = false;
583
+ if (isNonNullType(current)) current = current.ofType;
584
+ if (isListType(current)) {
585
+ isList = true;
586
+ current = current.ofType;
587
+ if (isNonNullType(current)) current = current.ofType;
588
+ }
589
+ return {
590
+ entityType: isObjectType(current) ? current : void 0,
591
+ isList
592
+ };
593
+ }
594
+ /**
595
+ * Dedupe + sort entries by source key. Throws on duplicates.
596
+ */
597
+ function organize(entries) {
598
+ const byKey = /* @__PURE__ */ new Map();
599
+ for (const entry of entries) {
600
+ const existing = byKey.get(entry.binding.sourceKey);
601
+ if (existing) throw new Error(`multiple fragments target the same source key "${entry.binding.sourceKey}": "${existing.fragmentName}" and "${entry.fragmentName}". A source key can have at most one fragment — merge the fragments or use the raw client for the alternative shape.`);
602
+ byKey.set(entry.binding.sourceKey, entry);
603
+ }
604
+ return byKey.values().toArray().toSorted((a, b) => a.binding.sourceKey.localeCompare(b.binding.sourceKey));
605
+ }
606
+ /** Emits `export type Sources = { ... }`. */
607
+ function generateSourcesType(entries) {
608
+ const sorted = organize(entries);
609
+ if (sorted.length === 0) return "";
610
+ const lines = ["export type Sources = {"];
611
+ for (const { fragmentName, binding } of sorted) {
612
+ const type = `SourceDef<'${binding.sourceKey}', '${binding.cardinality}', ${fragmentName}Fragment>`;
613
+ lines.push(` ${binding.sourceKey}: ${type};`);
614
+ }
615
+ lines.push("};");
616
+ return lines.join("\n");
617
+ }
618
+ /** Emits `const sources: Sources = { ... }` for inclusion in the schema bundle. */
619
+ function generateSourcesConst(entries) {
620
+ const sorted = organize(entries);
621
+ if (sorted.length === 0) return "";
622
+ const lines = ["const sources: Sources = {"];
623
+ for (const { fragmentName, binding, fragmentExpression } of sorted) lines.push(` ${binding.sourceKey}: {`, ` document: ${fragmentExpression},`, ` fragment: '${fragmentName}',`, ` subscription: '${binding.fieldName}',`, ` __model: '${binding.sourceKey}',`, ` __cardinality: '${binding.cardinality}',`, ` },`);
624
+ lines.push("};");
625
+ return lines.join("\n");
626
+ }
627
+ //#endregion
628
+ //#region src/generate/transform-components.ts
629
+ const FLAT_PREFIX = "_flat_";
630
+ const FLAT_COMPONENT_TYPE = "ContelloFlatComponent";
631
+ const COMPONENT_UNION = "ContelloComponent";
632
+ /**
633
+ * checks if a schema type (unwrapped from list/non-null) is the ContelloComponent union.
634
+ */
635
+ function isComponentUnion(schema, typeName) {
636
+ const type = schema.getType(typeName);
637
+ return !!type && isUnionType(type) && type.name === COMPONENT_UNION;
638
+ }
639
+ /**
640
+ * checks if a named object type is a member of the ContelloComponent union
641
+ * (i.e. a concrete component type like `TextComponent`, `SectionComponent`, `ContelloFlatComponent`).
642
+ */
643
+ function isComponentSubtype(schema, typeName) {
644
+ const union = schema.getType(COMPONENT_UNION);
645
+ if (!union || !isUnionType(union)) return false;
646
+ return union.getTypes().some((t) => t.name === typeName);
647
+ }
648
+ /**
649
+ * unwraps NonNull and List wrappers to get the named type.
650
+ */
651
+ function getNamedTypeName(type) {
652
+ let current = type;
653
+ while (isNonNullType(current) || isListType(current)) current = current.ofType;
654
+ return current?.name;
655
+ }
656
+ /**
657
+ * the flat ref selection for the `_flat_*` companion: `{ __typename ... on ContelloFlatComponent { _flatId } }`.
658
+ * `__typename` is kept here because the companion carries the full components and the runtime derives
659
+ * `__model` from it.
660
+ */
661
+ const FLAT_REF_SELECTIONS = parse(`{ __typename ... on ${FLAT_COMPONENT_TYPE} { _flatId } }`).definitions.flatMap((d) => "selectionSet" in d ? [d.selectionSet] : [])[0];
662
+ /**
663
+ * the lightweight ref selection for the inline component field: `{ ... on ContelloFlatComponent { _flatId } }`.
664
+ * only `_flatId` is needed — the runtime resolves these refs against the `_flat_*` companion by id and never
665
+ * reads their `__typename`, so it is omitted to keep the wire payload small.
666
+ */
667
+ const FLAT_REF_ONLY_SELECTIONS = parse(`{ ... on ${FLAT_COMPONENT_TYPE} { _flatId } }`).definitions.flatMap((d) => "selectionSet" in d ? [d.selectionSet] : [])[0];
668
+ /**
669
+ * checks if a fragment on ContelloComponent already has the FlatComponent pattern
670
+ * (i.e. already has `... on ContelloFlatComponent { _flatId }`)
671
+ */
672
+ function hasExistingFlatSpread(selectionSet) {
673
+ return selectionSet.selections.some((s) => s.kind === Kind.INLINE_FRAGMENT && s.typeCondition?.name.value === FLAT_COMPONENT_TYPE);
674
+ }
675
+ /**
676
+ * adds flat ref selections (__typename + ... on ContelloFlatComponent { _flatId })
677
+ * to a selection set, if not already present.
678
+ */
679
+ function addFlatRefSelections(selectionSet) {
680
+ if (hasExistingFlatSpread(selectionSet)) return selectionSet;
681
+ return {
682
+ ...selectionSet,
683
+ selections: [...FLAT_REF_SELECTIONS.selections, ...selectionSet.selections]
684
+ };
685
+ }
686
+ /**
687
+ * transforms a selection set by rewriting ContelloComponent fields:
688
+ * - the original field gets flat ref selections only
689
+ * - a `_flat_{fieldName}` sibling is added with the original selections + flat refs
690
+ */
691
+ function transformSelectionSet$1(schema, selectionSet, parentTypeName, fragments, refsOnly = false) {
692
+ const parentType = schema.getType(parentTypeName);
693
+ if (!parentType || !isObjectType(parentType)) return selectionSet;
694
+ const parentFields = parentType.getFields();
695
+ const newSelections = [];
696
+ let changed = false;
697
+ function recurse(node, typeName) {
698
+ if (!node.selectionSet) {
699
+ newSelections.push(node);
700
+ return;
701
+ }
702
+ const transformed = transformSelectionSet$1(schema, node.selectionSet, typeName, fragments, refsOnly);
703
+ if (transformed === node.selectionSet) newSelections.push(node);
704
+ else {
705
+ changed = true;
706
+ newSelections.push({
707
+ ...node,
708
+ selectionSet: transformed
709
+ });
710
+ }
711
+ }
712
+ for (const selection of selectionSet.selections) if (selection.kind === Kind.FIELD) {
713
+ const fieldName = selection.name.value;
714
+ const schemaField = parentFields[fieldName];
715
+ if (!schemaField) {
716
+ newSelections.push(selection);
717
+ continue;
718
+ }
719
+ const namedTypeName = getNamedTypeName(schemaField.type);
720
+ if (namedTypeName && isComponentUnion(schema, namedTypeName) && selection.selectionSet) {
721
+ const flatFieldName = `${FLAT_PREFIX}${fieldName}`;
722
+ if (!Object.hasOwn(parentFields, flatFieldName)) {
723
+ newSelections.push(selection);
724
+ continue;
725
+ }
726
+ changed = true;
727
+ newSelections.push({
728
+ ...selection,
729
+ selectionSet: FLAT_REF_ONLY_SELECTIONS
730
+ });
731
+ if (!refsOnly) newSelections.push({
732
+ kind: Kind.FIELD,
733
+ name: {
734
+ kind: Kind.NAME,
735
+ value: flatFieldName
736
+ },
737
+ selectionSet: addFlatRefSelections(selection.selectionSet)
738
+ });
739
+ } else if (namedTypeName) recurse(selection, namedTypeName);
740
+ else newSelections.push(selection);
741
+ } else if (selection.kind === Kind.INLINE_FRAGMENT) {
742
+ const typeName = selection.typeCondition?.name.value;
743
+ const type = typeName ? schema.getType(typeName) : void 0;
744
+ if (typeName && type && isCompositeType(type) && isObjectType(type)) recurse(selection, typeName);
745
+ else newSelections.push(selection);
746
+ } else newSelections.push(selection);
747
+ if (!changed) return selectionSet;
748
+ return {
749
+ ...selectionSet,
750
+ selections: newSelections
751
+ };
752
+ }
753
+ /**
754
+ * transforms an operation by rewriting ContelloComponent fields in the query.
755
+ * returns the original operation if no transform was needed.
756
+ */
757
+ function transformOperation(schema, operation, fragments) {
758
+ const rootType = operation.operation === "query" ? schema.getQueryType() : operation.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
759
+ if (!rootType || !operation.selectionSet) return operation;
760
+ const transformed = transformSelectionSet$1(schema, operation.selectionSet, rootType.name, fragments);
761
+ if (transformed === operation.selectionSet) return operation;
762
+ return {
763
+ ...operation,
764
+ selectionSet: transformed
765
+ };
766
+ }
767
+ /**
768
+ * transforms a fragment definition by rewriting ContelloComponent fields.
769
+ * also ensures fragments on ContelloComponent include flat ref selections.
770
+ */
771
+ function transformFragment(schema, fragment, fragments) {
772
+ const typeName = fragment.typeCondition.name.value;
773
+ const type = schema.getType(typeName);
774
+ if (!type || !isCompositeType(type)) return fragment;
775
+ let selectionSet = fragment.selectionSet;
776
+ if (typeName === COMPONENT_UNION) selectionSet = addFlatRefSelections(selectionSet);
777
+ if (isObjectType(type)) {
778
+ const refsOnly = isComponentSubtype(schema, typeName);
779
+ selectionSet = transformSelectionSet$1(schema, selectionSet, typeName, fragments, refsOnly);
780
+ } else if (isUnionType(type)) {
781
+ const newSelections = selectionSet.selections.map((sel) => {
782
+ if (sel.kind === Kind.INLINE_FRAGMENT && sel.typeCondition && sel.selectionSet) {
783
+ const inlineTypeName = sel.typeCondition.name.value;
784
+ const inlineType = schema.getType(inlineTypeName);
785
+ if (inlineType && isObjectType(inlineType)) {
786
+ const transformed = transformSelectionSet$1(schema, sel.selectionSet, inlineTypeName, fragments, true);
787
+ if (transformed !== sel.selectionSet) return {
788
+ ...sel,
789
+ selectionSet: transformed
790
+ };
791
+ }
792
+ }
793
+ return sel;
794
+ });
795
+ selectionSet = {
796
+ ...selectionSet,
797
+ selections: newSelections
798
+ };
799
+ }
800
+ if (selectionSet === fragment.selectionSet) return fragment;
801
+ return {
802
+ ...fragment,
803
+ selectionSet
804
+ };
805
+ }
806
+ //#endregion
807
+ //#region src/generate/transform-scalars.ts
808
+ const SCALAR_PREFIX = {
809
+ LocalDateTime: "_ldt_",
810
+ LocalDate: "_ld_"
811
+ };
812
+ function namedTypeName(type) {
813
+ let current = type;
814
+ while (isNonNullType(current) || isListType(current)) current = current.ofType;
815
+ return isScalarType(current) ? current.name : void 0;
816
+ }
817
+ function prefixFor(typeName) {
818
+ return SCALAR_PREFIX[typeName];
819
+ }
820
+ /**
821
+ * walks a selection set and aliases scalar fields whose type is a managed scalar
822
+ * (LocalDateTime, LocalDate) with a marker prefix. the runtime transform reads the
823
+ * prefix, decodes the wire string to a struct, and renames the key back.
824
+ *
825
+ * recurses through nested object selections and inline fragments — fragment spreads
826
+ * are left intact (their definitions are transformed separately).
827
+ */
828
+ function transformSelectionSet(schema, selectionSet, parentTypeName) {
829
+ const parentType = schema.getType(parentTypeName);
830
+ if (!parentType || !isObjectType(parentType) && !isInterfaceType(parentType)) return selectionSet;
831
+ const parentFields = parentType.getFields();
832
+ const newSelections = [];
833
+ let changed = false;
834
+ for (const selection of selectionSet.selections) if (selection.kind === Kind.FIELD) {
835
+ const schemaField = parentFields[selection.name.value];
836
+ if (!schemaField) {
837
+ newSelections.push(selection);
838
+ continue;
839
+ }
840
+ const scalarName = namedTypeName(schemaField.type);
841
+ const prefix = scalarName ? prefixFor(scalarName) : void 0;
842
+ if (prefix) {
843
+ const aliasValue = selection.alias?.value ?? selection.name.value;
844
+ if (aliasValue.startsWith(prefix)) newSelections.push(selection);
845
+ else {
846
+ changed = true;
847
+ newSelections.push({
848
+ ...selection,
849
+ alias: {
850
+ kind: Kind.NAME,
851
+ value: `${prefix}${aliasValue}`
852
+ }
853
+ });
854
+ }
855
+ continue;
856
+ }
857
+ if (selection.selectionSet) {
858
+ const nestedTypeName = namedCompositeName(schemaField.type);
859
+ if (nestedTypeName) {
860
+ const transformed = transformSelectionSet(schema, selection.selectionSet, nestedTypeName);
861
+ if (transformed !== selection.selectionSet) {
862
+ changed = true;
863
+ newSelections.push({
864
+ ...selection,
865
+ selectionSet: transformed
866
+ });
867
+ continue;
868
+ }
869
+ }
870
+ }
871
+ newSelections.push(selection);
872
+ } else if (selection.kind === Kind.INLINE_FRAGMENT) {
873
+ const typeName = selection.typeCondition?.name.value;
874
+ if (typeName && selection.selectionSet) {
875
+ const type = schema.getType(typeName);
876
+ if (type && isCompositeType(type)) {
877
+ const transformed = transformSelectionSet(schema, selection.selectionSet, typeName);
878
+ if (transformed !== selection.selectionSet) {
879
+ changed = true;
880
+ newSelections.push({
881
+ ...selection,
882
+ selectionSet: transformed
883
+ });
884
+ continue;
885
+ }
886
+ }
887
+ }
888
+ newSelections.push(selection);
889
+ } else newSelections.push(selection);
890
+ if (!changed) return selectionSet;
891
+ return {
892
+ ...selectionSet,
893
+ selections: newSelections
894
+ };
895
+ }
896
+ function namedCompositeName(type) {
897
+ let current = type;
898
+ while (isNonNullType(current) || isListType(current)) current = current.ofType;
899
+ return isCompositeType(current) ? current.name : void 0;
900
+ }
901
+ function transformScalarOperation(schema, operation) {
902
+ const rootType = operation.operation === "query" ? schema.getQueryType() : operation.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
903
+ if (!rootType || !operation.selectionSet) return operation;
904
+ const transformed = transformSelectionSet(schema, operation.selectionSet, rootType.name);
905
+ if (transformed === operation.selectionSet) return operation;
906
+ return {
907
+ ...operation,
908
+ selectionSet: transformed
909
+ };
910
+ }
911
+ function transformScalarFragment(schema, fragment) {
912
+ const type = schema.getType(fragment.typeCondition.name.value);
913
+ if (!type || !isCompositeType(type)) return fragment;
914
+ const transformed = transformSelectionSet(schema, fragment.selectionSet, type.name);
915
+ if (transformed === fragment.selectionSet) return fragment;
916
+ return {
917
+ ...fragment,
918
+ selectionSet: transformed
919
+ };
920
+ }
921
+ //#endregion
922
+ //#region src/generate/index.ts
923
+ const ctrlSeq = "\x1B[";
924
+ const styled = (s, pre, post) => `${ctrlSeq}${pre}${s}${ctrlSeq}${post}`;
925
+ const dim = (s) => styled(s, "2m", "22m");
926
+ const bold = (s) => styled(s, "1m", "22m");
927
+ const green = (s) => styled(s, "32m", "39m");
928
+ const yellow = (s) => styled(s, "33m", "39m");
929
+ const cyan = (s) => styled(s, "36m", "39m");
930
+ function collectFragmentSpreads(fragment) {
931
+ const refs = /* @__PURE__ */ new Set();
932
+ visit(fragment, { [Kind.FRAGMENT_SPREAD](node) {
933
+ refs.add(node.name.value);
934
+ } });
935
+ return refs;
936
+ }
937
+ function collectEntitySourceEntries(fragments, entityBindings, transformedFragments) {
938
+ const entries = [];
939
+ for (const [name, fragment] of fragments) {
940
+ const entityBinding = entityBindings.get(fragment.typeCondition.name.value);
941
+ if (!entityBinding) continue;
942
+ const transformed = transformedFragments.get(name);
943
+ if (!transformed) continue;
944
+ entries.push({
945
+ fragmentName: name,
946
+ binding: {
947
+ cardinality: entityBinding.cardinality,
948
+ fieldName: entityBinding.fieldName,
949
+ sourceKey: entityBinding.model
950
+ },
951
+ fragmentExpression: fragmentBundleExpression(transformed, transformedFragments)
952
+ });
953
+ }
954
+ return entries;
955
+ }
956
+ function collectBuiltInSourceEntries(fragments, builtInBindings, transformedFragments) {
957
+ const entries = [];
958
+ for (const [typeName, builtInBinding] of builtInBindings) {
959
+ const candidates = [];
960
+ for (const [name, fragment] of fragments) if (fragment.typeCondition.name.value === typeName) candidates.push({
961
+ name,
962
+ fragment
963
+ });
964
+ if (candidates.length === 0) continue;
965
+ const candidateNames = new Set(candidates.map((c) => c.name));
966
+ const spreadByOther = /* @__PURE__ */ new Set();
967
+ for (const { name, fragment } of candidates) for (const ref of collectFragmentSpreads(fragment)) if (ref !== name && candidateNames.has(ref)) spreadByOther.add(ref);
968
+ const roots = candidates.filter((c) => !spreadByOther.has(c.name));
969
+ const picked = roots.length === 1 ? roots[0] : void 0;
970
+ if (!picked) throw new Error(`multiple fragments target the built-in type "${typeName}" without a clear root: ${candidates.map((c) => `"${c.name}"`).join(", ")}. Either have one fragment spread the others, or remove the extras.`);
971
+ const transformed = transformedFragments.get(picked.name);
972
+ if (!transformed) continue;
973
+ entries.push({
974
+ fragmentName: picked.name,
975
+ binding: {
976
+ cardinality: builtInBinding.cardinality,
977
+ fieldName: builtInBinding.fieldName,
978
+ sourceKey: uncapitalize(picked.name)
979
+ },
980
+ fragmentExpression: fragmentBundleExpression(transformed, transformedFragments)
981
+ });
982
+ }
983
+ return entries;
984
+ }
985
+ async function main() {
986
+ const cwd = process.cwd();
987
+ const config = await loadConfig(cwd);
988
+ console.log("");
989
+ console.log(`${bold("@contello/client")} ${dim("generate")}`);
990
+ console.log("");
991
+ for (const project of config.projects) {
992
+ const start = performance.now();
993
+ console.log(`${cyan("●")} ${bold(project.project)}`);
994
+ rmSync(resolve(cwd, project.output), { force: true });
995
+ const schema = await introspectSchema(project.url, project.project, project.token);
996
+ const patterns = Array.isArray(project.documents) ? project.documents : [project.documents];
997
+ const documentPaths = (await Promise.all(patterns.map((p) => Array.fromAsync(glob(p, { cwd }))))).flat().toSorted(compareCodeUnits);
998
+ if (documentPaths.length === 0) {
999
+ console.warn(` ${yellow("⚠")} no documents found matching "${project.documents}"`);
1000
+ continue;
1001
+ }
1002
+ const documents = documentPaths.map((p) => parse(new Source(readFileSync(resolve(cwd, p), "utf8"), p)));
1003
+ const fragments = collectFragments(documents);
1004
+ const operations = collectOperations(documents);
1005
+ validateDocuments(schema, fragments, operations);
1006
+ const transformedFragments = new Map([...fragments].map(([name, frag]) => [name, transformFragment(schema, frag, fragments)]));
1007
+ const transformedOperations = operations.map((op) => transformOperation(schema, op, transformedFragments));
1008
+ for (const [name, frag] of transformedFragments) transformedFragments.set(name, transformScalarFragment(schema, frag));
1009
+ for (let i = 0; i < transformedOperations.length; i++) transformedOperations[i] = transformScalarOperation(schema, transformedOperations[i]);
1010
+ const entityBindings = indexEntitySources(schema);
1011
+ const builtInBindings = indexBuiltInSources(schema);
1012
+ const sourceEntries = [...collectEntitySourceEntries(fragments, entityBindings, transformedFragments), ...collectBuiltInSourceEntries(fragments, builtInBindings, transformedFragments)];
1013
+ const entityModels = extractEntityModels(schema);
1014
+ const parts = [
1015
+ "/* eslint-disable */",
1016
+ "// @ts-nocheck",
1017
+ "/* this file is generated by contello-client — do not edit */",
1018
+ ""
1019
+ ];
1020
+ const typeMap = schema.getTypeMap();
1021
+ const clientImports = ["SourceDef"];
1022
+ for (const scalar of MANAGED_SCALARS) if (Object.hasOwn(typeMap, scalar)) clientImports.push(scalar);
1023
+ parts.push(`import type { ${clientImports.toSorted(compareCodeUnits).join(", ")} } from '@contello/client';`, "", generateSchemaTypes(schema), generateFragmentTypes(schema, fragments), generateOperationTypes(schema, operations, fragments));
1024
+ if (transformedFragments.size > 0) parts.push(generateFragmentSchemas(transformedFragments), "");
1025
+ for (const [i, operation] of operations.entries()) {
1026
+ const camelName = uncapitalize(operation.name.value);
1027
+ const docExpr = operationDocumentExpression(transformedOperations[i], transformedFragments);
1028
+ parts.push(`export const ${camelName}Document = ${docExpr};`);
1029
+ }
1030
+ if (operations.length > 0) parts.push("");
1031
+ parts.push(generateOperationsType(operations), "");
1032
+ const sourcesTypeSrc = generateSourcesType(sourceEntries);
1033
+ if (sourcesTypeSrc) parts.push(sourcesTypeSrc, "");
1034
+ parts.push(generateOperationsConst(operations), "");
1035
+ const sourcesConstSrc = generateSourcesConst(sourceEntries);
1036
+ if (sourcesConstSrc) parts.push(sourcesConstSrc, "");
1037
+ if (entityModels.size > 0) {
1038
+ const sorted = entityModels.entries().toArray().toSorted(([a], [b]) => a.localeCompare(b));
1039
+ parts.push("const models = {");
1040
+ for (const [model, typeName] of sorted) parts.push(` ${model}: '${typeName}',`);
1041
+ parts.push("} as const;", "");
1042
+ } else parts.push("const models = {} as const;", "");
1043
+ const sourcesPart = sourcesConstSrc ? ", sources" : ", sources: {}";
1044
+ parts.push(`export const schema = { operations${sourcesPart}, models };`, "export type Schema = typeof schema;");
1045
+ let output = parts.join("\n");
1046
+ if (project.namespace) {
1047
+ const indented = output.split("\n").map((line) => line ? ` ${line}` : "").join("\n");
1048
+ output = `export namespace ${project.namespace} {\n${indented}\n}\n`;
1049
+ }
1050
+ const outputPath = resolve(cwd, project.output);
1051
+ mkdirSync(dirname(outputPath), { recursive: true });
1052
+ writeFileSync(outputPath, output, "utf8");
1053
+ const elapsed = Math.round(performance.now() - start);
1054
+ console.log(` ${green("✓")} ${relative(cwd, outputPath)} ${dim(`${elapsed}ms`)}`);
1055
+ console.log(` ${dim("operations")} ${operations.length} ${dim("fragments")} ${fragments.size}`);
1056
+ console.log("");
1057
+ }
1058
+ }
1059
+ try {
1060
+ await main();
1061
+ } catch (error) {
1062
+ console.error(error);
1063
+ process.exit(1);
1064
+ }
1065
+ //#endregion
1066
+ export {};
1067
+
1068
+ //# sourceMappingURL=generate-DIoN94iO.js.map