@constructive-io/graphql-query 3.2.5 → 3.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.
Files changed (88) hide show
  1. package/README.md +411 -65
  2. package/ast.d.ts +4 -4
  3. package/ast.js +24 -9
  4. package/client/error.d.ts +95 -0
  5. package/client/error.js +277 -0
  6. package/client/execute.d.ts +57 -0
  7. package/client/execute.js +124 -0
  8. package/client/index.d.ts +8 -0
  9. package/client/index.js +20 -0
  10. package/client/typed-document.d.ts +31 -0
  11. package/client/typed-document.js +44 -0
  12. package/custom-ast.d.ts +22 -8
  13. package/custom-ast.js +16 -1
  14. package/esm/ast.js +22 -7
  15. package/esm/client/error.js +271 -0
  16. package/esm/client/execute.js +120 -0
  17. package/esm/client/index.js +8 -0
  18. package/esm/client/typed-document.js +40 -0
  19. package/esm/custom-ast.js +16 -1
  20. package/esm/generators/field-selector.js +381 -0
  21. package/esm/generators/index.js +13 -0
  22. package/esm/generators/mutations.js +200 -0
  23. package/esm/generators/naming-helpers.js +154 -0
  24. package/esm/generators/select.js +661 -0
  25. package/esm/index.js +30 -0
  26. package/esm/introspect/index.js +9 -0
  27. package/esm/introspect/infer-tables.js +697 -0
  28. package/esm/introspect/schema-query.js +120 -0
  29. package/esm/introspect/transform-schema.js +271 -0
  30. package/esm/introspect/transform.js +38 -0
  31. package/esm/meta-object/convert.js +3 -0
  32. package/esm/meta-object/format.json +11 -41
  33. package/esm/meta-object/validate.js +20 -4
  34. package/esm/query-builder.js +14 -18
  35. package/esm/types/index.js +18 -0
  36. package/esm/types/introspection.js +54 -0
  37. package/esm/types/mutation.js +4 -0
  38. package/esm/types/query.js +4 -0
  39. package/esm/types/schema.js +5 -0
  40. package/esm/types/selection.js +4 -0
  41. package/esm/utils.js +69 -0
  42. package/generators/field-selector.d.ts +30 -0
  43. package/generators/field-selector.js +387 -0
  44. package/generators/index.d.ts +9 -0
  45. package/generators/index.js +42 -0
  46. package/generators/mutations.d.ts +30 -0
  47. package/generators/mutations.js +238 -0
  48. package/generators/naming-helpers.d.ts +48 -0
  49. package/generators/naming-helpers.js +169 -0
  50. package/generators/select.d.ts +39 -0
  51. package/generators/select.js +705 -0
  52. package/index.d.ts +19 -0
  53. package/index.js +34 -1
  54. package/introspect/index.d.ts +9 -0
  55. package/introspect/index.js +25 -0
  56. package/introspect/infer-tables.d.ts +42 -0
  57. package/introspect/infer-tables.js +700 -0
  58. package/introspect/schema-query.d.ts +20 -0
  59. package/introspect/schema-query.js +123 -0
  60. package/introspect/transform-schema.d.ts +86 -0
  61. package/introspect/transform-schema.js +281 -0
  62. package/introspect/transform.d.ts +20 -0
  63. package/introspect/transform.js +43 -0
  64. package/meta-object/convert.d.ts +3 -0
  65. package/meta-object/convert.js +3 -0
  66. package/meta-object/format.json +11 -41
  67. package/meta-object/validate.d.ts +8 -3
  68. package/meta-object/validate.js +20 -4
  69. package/package.json +4 -3
  70. package/query-builder.d.ts +11 -12
  71. package/query-builder.js +25 -29
  72. package/{types.d.ts → types/core.d.ts} +25 -18
  73. package/types/index.d.ts +12 -0
  74. package/types/index.js +34 -0
  75. package/types/introspection.d.ts +121 -0
  76. package/types/introspection.js +62 -0
  77. package/types/mutation.d.ts +45 -0
  78. package/types/mutation.js +5 -0
  79. package/types/query.d.ts +91 -0
  80. package/types/query.js +5 -0
  81. package/types/schema.d.ts +265 -0
  82. package/types/schema.js +6 -0
  83. package/types/selection.d.ts +43 -0
  84. package/types/selection.js +5 -0
  85. package/utils.d.ts +17 -0
  86. package/utils.js +72 -0
  87. /package/esm/{types.js → types/core.js} +0 -0
  88. /package/{types.js → types/core.js} +0 -0
@@ -0,0 +1,697 @@
1
+ /**
2
+ * Infer PostGraphile table metadata from standard GraphQL introspection
3
+ *
4
+ * This module replaces the need for the _meta query by recognizing PostGraphile's
5
+ * naming conventions and type patterns from standard GraphQL introspection.
6
+ *
7
+ * Key patterns recognized:
8
+ * - Connection types: {PluralName}Connection → entity name
9
+ * - Filter types: {Name}Filter
10
+ * - Input types: Create{Name}Input, Update{Name}Input, Delete{Name}Input
11
+ * - Payload types: Create{Name}Payload, Update{Name}Payload, Delete{Name}Payload
12
+ * - Query operations: {pluralName} (list), {singularName} (single)
13
+ * - Mutation operations: create{Name}, update{Name}, delete{Name}
14
+ */
15
+ import { lcFirst, pluralize, singularize, ucFirst } from 'inflekt';
16
+ import { stripSmartComments } from '../utils';
17
+ import { getBaseTypeName, isList, isNonNull, unwrapType } from '../types/introspection';
18
+ // ============================================================================
19
+ // Pattern Matching Constants
20
+ // ============================================================================
21
+ /**
22
+ * PostGraphile naming patterns for type detection
23
+ */
24
+ const PATTERNS = {
25
+ // Type suffixes
26
+ connection: /^(.+)Connection$/,
27
+ edge: /^(.+)Edge$/,
28
+ filter: /^(.+)Filter$/,
29
+ condition: /^(.+)Condition$/,
30
+ orderBy: /^(.+)OrderBy$/,
31
+ patch: /^(.+)Patch$/,
32
+ // Input type patterns
33
+ createInput: /^Create(.+)Input$/,
34
+ updateInput: /^Update(.+)Input$/,
35
+ deleteInput: /^Delete(.+)Input$/,
36
+ // Payload type patterns
37
+ createPayload: /^Create(.+)Payload$/,
38
+ updatePayload: /^Update(.+)Payload$/,
39
+ deletePayload: /^Delete(.+)Payload$/,
40
+ // Mutation name patterns (camelCase)
41
+ createMutation: /^create([A-Z][a-zA-Z0-9]*)$/,
42
+ updateMutation: /^update([A-Z][a-zA-Z0-9]*)$/,
43
+ deleteMutation: /^delete([A-Z][a-zA-Z0-9]*)$/,
44
+ };
45
+ /**
46
+ * Built-in GraphQL types to ignore
47
+ */
48
+ const BUILTIN_TYPES = new Set([
49
+ 'Query',
50
+ 'Mutation',
51
+ 'Subscription',
52
+ 'String',
53
+ 'Int',
54
+ 'Float',
55
+ 'Boolean',
56
+ 'ID',
57
+ // PostGraphile built-in types
58
+ 'Node',
59
+ 'PageInfo',
60
+ 'Cursor',
61
+ 'UUID',
62
+ 'Datetime',
63
+ 'Date',
64
+ 'Time',
65
+ 'JSON',
66
+ 'BigInt',
67
+ 'BigFloat',
68
+ ]);
69
+ /**
70
+ * Types that start with __ are internal GraphQL types
71
+ */
72
+ function isInternalType(name) {
73
+ return name.startsWith('__');
74
+ }
75
+ /**
76
+ * Infer CleanTable[] from GraphQL introspection by recognizing PostGraphile patterns
77
+ *
78
+ * @param introspection - Standard GraphQL introspection response
79
+ * @param options - Optional configuration
80
+ * @returns Array of CleanTable objects compatible with existing generators
81
+ */
82
+ export function inferTablesFromIntrospection(introspection, options = {}) {
83
+ const { __schema: schema } = introspection;
84
+ const { types, queryType, mutationType } = schema;
85
+ const commentsEnabled = options.comments !== false;
86
+ // Build lookup maps for efficient access
87
+ const typeMap = buildTypeMap(types);
88
+ const { entityNames, entityToConnection, connectionToEntity } = buildEntityConnectionMaps(types, typeMap);
89
+ const queryFields = getTypeFields(typeMap.get(queryType.name));
90
+ const mutationFields = mutationType
91
+ ? getTypeFields(typeMap.get(mutationType.name))
92
+ : [];
93
+ // Step 1: Build CleanTable for each inferred entity
94
+ const tables = [];
95
+ for (const entityName of entityNames) {
96
+ const entityType = typeMap.get(entityName);
97
+ if (!entityType)
98
+ continue;
99
+ // Infer all metadata for this entity
100
+ const { table, hasRealOperation } = buildCleanTable(entityName, entityType, typeMap, queryFields, mutationFields, entityToConnection, connectionToEntity, commentsEnabled);
101
+ // Only include tables that have at least one real operation
102
+ if (hasRealOperation) {
103
+ tables.push(table);
104
+ }
105
+ }
106
+ return tables;
107
+ }
108
+ /**
109
+ * Infer entity <-> connection mappings from schema types.
110
+ *
111
+ * Prefer deriving entity names from the `nodes` field of connection types.
112
+ * This is robust across v4/v5 naming variations (e.g. `UsersConnection` and
113
+ * `UserConnection`).
114
+ */
115
+ function buildEntityConnectionMaps(types, typeMap) {
116
+ const entityNames = new Set();
117
+ const entityToConnection = new Map();
118
+ const connectionToEntity = new Map();
119
+ const typeNames = new Set(types.map((t) => t.name));
120
+ for (const type of types) {
121
+ // Skip internal types
122
+ if (isInternalType(type.name))
123
+ continue;
124
+ if (BUILTIN_TYPES.has(type.name))
125
+ continue;
126
+ // Check for Connection pattern
127
+ const connectionMatch = type.name.match(PATTERNS.connection);
128
+ if (connectionMatch) {
129
+ const fallbackEntityName = singularize(connectionMatch[1]);
130
+ const entityName = resolveEntityNameFromConnectionType(type, typeMap) ?? fallbackEntityName;
131
+ // Verify the entity type actually exists and is not a built-in/internal type.
132
+ if (typeNames.has(entityName) &&
133
+ !BUILTIN_TYPES.has(entityName) &&
134
+ !isInternalType(entityName)) {
135
+ entityNames.add(entityName);
136
+ entityToConnection.set(entityName, type.name);
137
+ connectionToEntity.set(type.name, entityName);
138
+ }
139
+ }
140
+ }
141
+ return {
142
+ entityNames,
143
+ entityToConnection,
144
+ connectionToEntity,
145
+ };
146
+ }
147
+ /**
148
+ * Attempt to resolve an entity name from a connection type by inspecting its
149
+ * `nodes` field.
150
+ */
151
+ function resolveEntityNameFromConnectionType(connectionType, typeMap) {
152
+ if (!connectionType.fields)
153
+ return null;
154
+ const nodesField = connectionType.fields.find((field) => field.name === 'nodes');
155
+ if (!nodesField)
156
+ return null;
157
+ const nodeTypeName = getBaseTypeName(nodesField.type);
158
+ if (!nodeTypeName)
159
+ return null;
160
+ const nodeType = typeMap.get(nodeTypeName);
161
+ if (!nodeType || nodeType.kind !== 'OBJECT')
162
+ return null;
163
+ if (nodeTypeName.endsWith('Connection'))
164
+ return null;
165
+ if (BUILTIN_TYPES.has(nodeTypeName))
166
+ return null;
167
+ if (isInternalType(nodeTypeName))
168
+ return null;
169
+ return nodeTypeName;
170
+ }
171
+ /**
172
+ * Build a complete CleanTable from an entity type
173
+ */
174
+ function buildCleanTable(entityName, entityType, typeMap, queryFields, mutationFields, entityToConnection, connectionToEntity, commentsEnabled) {
175
+ // Extract scalar fields from entity type
176
+ const fields = extractEntityFields(entityType, typeMap, entityToConnection, commentsEnabled);
177
+ // Infer relations from entity fields
178
+ const relations = inferRelations(entityType, entityToConnection, connectionToEntity);
179
+ // Match query and mutation operations
180
+ const queryOps = matchQueryOperations(entityName, queryFields, entityToConnection);
181
+ const mutationOps = matchMutationOperations(entityName, mutationFields);
182
+ // Check if we found at least one real operation (not a fallback)
183
+ const hasRealOperation = !!(queryOps.all ||
184
+ queryOps.one ||
185
+ mutationOps.create ||
186
+ mutationOps.update ||
187
+ mutationOps.delete);
188
+ // Infer primary key from mutation inputs
189
+ const constraints = inferConstraints(entityName, typeMap);
190
+ // Infer the patch field name from UpdateXxxInput (e.g., "userPatch")
191
+ const patchFieldName = inferPatchFieldName(entityName, typeMap);
192
+ // Build inflection map from discovered types
193
+ const inflection = buildInflection(entityName, typeMap, entityToConnection);
194
+ // Combine query operations with fallbacks for UI purposes
195
+ // (but hasRealOperation indicates if we should include this table)
196
+ const query = {
197
+ all: queryOps.all ?? lcFirst(pluralize(entityName)),
198
+ one: queryOps.one,
199
+ create: mutationOps.create ?? `create${entityName}`,
200
+ update: mutationOps.update,
201
+ delete: mutationOps.delete,
202
+ patchFieldName,
203
+ };
204
+ // Extract description from entity type (PostgreSQL COMMENT), strip smart comments
205
+ const description = commentsEnabled ? stripSmartComments(entityType.description) : undefined;
206
+ return {
207
+ table: {
208
+ name: entityName,
209
+ ...(description ? { description } : {}),
210
+ fields,
211
+ relations,
212
+ inflection,
213
+ query,
214
+ constraints,
215
+ },
216
+ hasRealOperation,
217
+ };
218
+ }
219
+ // ============================================================================
220
+ // Field Extraction
221
+ // ============================================================================
222
+ /**
223
+ * Extract scalar fields from an entity type
224
+ * Excludes relation fields (those returning other entity types or connections)
225
+ */
226
+ function extractEntityFields(entityType, typeMap, entityToConnection, commentsEnabled) {
227
+ const fields = [];
228
+ if (!entityType.fields)
229
+ return fields;
230
+ // Build a lookup of CreateXxxInput fields to infer hasDefault.
231
+ // If a field is NOT NULL on the entity but NOT required in CreateXxxInput,
232
+ // then it likely has a server-side default (serial, uuid_generate_v4, now(), etc.).
233
+ const createInputRequiredFields = buildCreateInputRequiredFieldSet(entityType.name, typeMap);
234
+ for (const field of entityType.fields) {
235
+ const baseTypeName = getBaseTypeName(field.type);
236
+ if (!baseTypeName)
237
+ continue;
238
+ // Skip relation fields (those returning other objects or connections)
239
+ const fieldType = typeMap.get(baseTypeName);
240
+ if (fieldType?.kind === 'OBJECT') {
241
+ // Check if it's a Connection type (hasMany) or entity type (belongsTo)
242
+ if (baseTypeName.endsWith('Connection') ||
243
+ isEntityType(baseTypeName, entityToConnection)) {
244
+ continue; // Skip relation fields
245
+ }
246
+ }
247
+ // Infer isNotNull from the NON_NULL wrapper on the entity type field
248
+ const fieldIsNotNull = isNonNull(field.type);
249
+ // Infer hasDefault: if a field is NOT NULL on the entity but NOT required
250
+ // in CreateXxxInput, it likely has a default value.
251
+ // Also: if it's absent from CreateInput entirely, it's likely computed/generated.
252
+ let fieldHasDefault = null;
253
+ if (createInputRequiredFields !== null) {
254
+ if (fieldIsNotNull && !createInputRequiredFields.has(field.name)) {
255
+ fieldHasDefault = true;
256
+ }
257
+ else {
258
+ fieldHasDefault = false;
259
+ }
260
+ }
261
+ // Include scalar, enum, and other non-relation fields
262
+ const fieldDescription = commentsEnabled ? stripSmartComments(field.description) : undefined;
263
+ fields.push({
264
+ name: field.name,
265
+ ...(fieldDescription ? { description: fieldDescription } : {}),
266
+ type: convertToCleanFieldType(field.type),
267
+ isNotNull: fieldIsNotNull,
268
+ hasDefault: fieldHasDefault,
269
+ });
270
+ }
271
+ return fields;
272
+ }
273
+ /**
274
+ * Build a set of field names that are required (NON_NULL) in the CreateXxxInput type.
275
+ * Returns null if the CreateXxxInput type doesn't exist (no create mutation).
276
+ */
277
+ function buildCreateInputRequiredFieldSet(entityName, typeMap) {
278
+ const createInputName = `Create${entityName}Input`;
279
+ const createInput = typeMap.get(createInputName);
280
+ if (!createInput?.inputFields)
281
+ return null;
282
+ // The CreateXxxInput typically has a single field like { user: UserInput! }
283
+ // We need to look inside the actual entity input type (e.g., UserInput)
284
+ const entityInputName = `${entityName}Input`;
285
+ const entityInput = typeMap.get(entityInputName);
286
+ if (!entityInput?.inputFields)
287
+ return null;
288
+ const requiredFields = new Set();
289
+ for (const inputField of entityInput.inputFields) {
290
+ if (isNonNull(inputField.type)) {
291
+ requiredFields.add(inputField.name);
292
+ }
293
+ }
294
+ return requiredFields;
295
+ }
296
+ /**
297
+ * Check if a type name is an entity type (has a corresponding Connection)
298
+ */
299
+ function isEntityType(typeName, entityToConnection) {
300
+ return entityToConnection.has(typeName);
301
+ }
302
+ /**
303
+ * Convert IntrospectionTypeRef to CleanFieldType
304
+ */
305
+ function convertToCleanFieldType(typeRef) {
306
+ const baseType = unwrapType(typeRef);
307
+ const isArray = isList(typeRef);
308
+ return {
309
+ gqlType: baseType.name ?? 'Unknown',
310
+ isArray,
311
+ // PostgreSQL-specific fields are not available from introspection
312
+ // They were optional anyway and not used by generators
313
+ };
314
+ }
315
+ // ============================================================================
316
+ // Relation Inference
317
+ // ============================================================================
318
+ /**
319
+ * Infer relations from entity type fields
320
+ */
321
+ function inferRelations(entityType, entityToConnection, connectionToEntity) {
322
+ const belongsTo = [];
323
+ const hasMany = [];
324
+ const manyToMany = [];
325
+ if (!entityType.fields) {
326
+ return { belongsTo, hasOne: [], hasMany, manyToMany };
327
+ }
328
+ for (const field of entityType.fields) {
329
+ const baseTypeName = getBaseTypeName(field.type);
330
+ if (!baseTypeName)
331
+ continue;
332
+ // Check for Connection type → hasMany or manyToMany
333
+ if (baseTypeName.endsWith('Connection')) {
334
+ const resolvedRelation = inferHasManyOrManyToMany(field, baseTypeName, connectionToEntity);
335
+ if (resolvedRelation.type === 'manyToMany') {
336
+ manyToMany.push(resolvedRelation.relation);
337
+ }
338
+ else {
339
+ hasMany.push(resolvedRelation.relation);
340
+ }
341
+ continue;
342
+ }
343
+ // Check for entity type → belongsTo
344
+ if (isEntityType(baseTypeName, entityToConnection)) {
345
+ belongsTo.push({
346
+ fieldName: field.name,
347
+ isUnique: false, // Can't determine from introspection alone
348
+ referencesTable: baseTypeName,
349
+ type: baseTypeName,
350
+ keys: [], // Would need FK info to populate
351
+ });
352
+ }
353
+ }
354
+ return { belongsTo, hasOne: [], hasMany, manyToMany };
355
+ }
356
+ /**
357
+ * Determine if a Connection field is hasMany or manyToMany
358
+ *
359
+ * ManyToMany pattern: field name contains "By" and "And"
360
+ * e.g., "productsByOrderItemOrderIdAndProductId"
361
+ */
362
+ function inferHasManyOrManyToMany(field, connectionTypeName, connectionToEntity) {
363
+ // Resolve the related entity from discovered connection mappings first.
364
+ const relatedEntityName = connectionToEntity.get(connectionTypeName) ?? (() => {
365
+ const match = connectionTypeName.match(PATTERNS.connection);
366
+ const relatedPluralName = match ? match[1] : connectionTypeName;
367
+ return singularize(relatedPluralName);
368
+ })();
369
+ // Check for manyToMany pattern in field name
370
+ const isManyToMany = field.name.includes('By') && field.name.includes('And');
371
+ if (isManyToMany) {
372
+ // For ManyToMany, extract the actual entity name from the field name prefix
373
+ // Field name pattern: {relatedEntities}By{JunctionTable}{Keys}
374
+ // e.g., "usersByMembershipActorIdAndEntityId" → "users" → "User"
375
+ // e.g., "productsByOrderItemOrderIdAndProductId" → "products" → "Product"
376
+ const prefixMatch = field.name.match(/^([a-z]+)By/i);
377
+ const actualEntityName = prefixMatch
378
+ ? singularize(ucFirst(prefixMatch[1]))
379
+ : relatedEntityName;
380
+ // Try to extract junction table from field name
381
+ // Pattern: {relatedEntities}By{JunctionTable}{Keys}
382
+ // e.g., "productsByProductCategoryProductIdAndCategoryId" → "ProductCategory"
383
+ // The junction table name ends where the first field key begins (identified by capital letter after lowercase)
384
+ const junctionMatch = field.name.match(/By([A-Z][a-z]+(?:[A-Z][a-z]+)*?)(?:[A-Z][a-z]+Id)/);
385
+ const junctionTable = junctionMatch ? junctionMatch[1] : 'Unknown';
386
+ return {
387
+ type: 'manyToMany',
388
+ relation: {
389
+ fieldName: field.name,
390
+ rightTable: actualEntityName,
391
+ junctionTable,
392
+ type: connectionTypeName,
393
+ },
394
+ };
395
+ }
396
+ return {
397
+ type: 'hasMany',
398
+ relation: {
399
+ fieldName: field.name,
400
+ isUnique: false,
401
+ referencedByTable: relatedEntityName,
402
+ type: connectionTypeName,
403
+ keys: [],
404
+ },
405
+ };
406
+ }
407
+ /**
408
+ * Match query operations for an entity
409
+ *
410
+ * Looks for:
411
+ * - List query: returns {PluralName}Connection (e.g., users → UsersConnection)
412
+ * - Single query: returns {EntityName} with id/nodeId arg (e.g., user → User)
413
+ */
414
+ function matchQueryOperations(entityName, queryFields, entityToConnection) {
415
+ const pluralName = pluralize(entityName);
416
+ const connectionTypeName = entityToConnection.get(entityName) ?? `${pluralName}Connection`;
417
+ let all = null;
418
+ let one = null;
419
+ for (const field of queryFields) {
420
+ const returnTypeName = getBaseTypeName(field.type);
421
+ if (!returnTypeName)
422
+ continue;
423
+ // Match list query by return type (Connection)
424
+ if (returnTypeName === connectionTypeName) {
425
+ // Prefer the simple plural name, but accept any that returns the connection
426
+ if (!all || field.name === lcFirst(pluralName)) {
427
+ all = field.name;
428
+ }
429
+ }
430
+ // Match single query by return type (Entity) and having an id-like arg
431
+ if (returnTypeName === entityName) {
432
+ const hasIdArg = field.args.some((arg) => arg.name === 'id' ||
433
+ arg.name === 'nodeId' ||
434
+ arg.name.toLowerCase().endsWith('id'));
435
+ if (hasIdArg) {
436
+ // Prefer exact match (e.g., "user" for "User")
437
+ if (!one || field.name === lcFirst(entityName)) {
438
+ one = field.name;
439
+ }
440
+ }
441
+ }
442
+ }
443
+ return { all, one };
444
+ }
445
+ /**
446
+ * Match mutation operations for an entity
447
+ *
448
+ * Looks for mutations named:
449
+ * - create{EntityName}
450
+ * - update{EntityName} or update{EntityName}ById
451
+ * - delete{EntityName} or delete{EntityName}ById
452
+ */
453
+ function matchMutationOperations(entityName, mutationFields) {
454
+ let create = null;
455
+ let update = null;
456
+ let del = null;
457
+ const expectedCreate = `create${entityName}`;
458
+ const expectedUpdate = `update${entityName}`;
459
+ const expectedDelete = `delete${entityName}`;
460
+ for (const field of mutationFields) {
461
+ // Exact match for create
462
+ if (field.name === expectedCreate) {
463
+ create = field.name;
464
+ }
465
+ // Match update (could be updateUser or updateUserById)
466
+ if (field.name === expectedUpdate ||
467
+ field.name === `${expectedUpdate}ById`) {
468
+ // Prefer non-ById version
469
+ if (!update || field.name === expectedUpdate) {
470
+ update = field.name;
471
+ }
472
+ }
473
+ // Match delete (could be deleteUser or deleteUserById)
474
+ if (field.name === expectedDelete ||
475
+ field.name === `${expectedDelete}ById`) {
476
+ // Prefer non-ById version
477
+ if (!del || field.name === expectedDelete) {
478
+ del = field.name;
479
+ }
480
+ }
481
+ }
482
+ return { create, update, delete: del };
483
+ }
484
+ // ============================================================================
485
+ // Constraint Inference
486
+ // ============================================================================
487
+ /**
488
+ * Infer constraints from mutation input types
489
+ *
490
+ * Primary key can be inferred from Update/Delete mutation input types,
491
+ * which typically have an 'id' field or similar.
492
+ */
493
+ function inferConstraints(entityName, typeMap) {
494
+ const primaryKey = [];
495
+ // Try to find Update or Delete input type to extract PK
496
+ const updateInputName = `Update${entityName}Input`;
497
+ const deleteInputName = `Delete${entityName}Input`;
498
+ const updateInput = typeMap.get(updateInputName);
499
+ const deleteInput = typeMap.get(deleteInputName);
500
+ const keyInputField = inferPrimaryKeyFromInputObject(updateInput) ||
501
+ inferPrimaryKeyFromInputObject(deleteInput);
502
+ if (keyInputField) {
503
+ primaryKey.push({
504
+ name: 'primary',
505
+ fields: [
506
+ {
507
+ name: keyInputField.name,
508
+ type: convertToCleanFieldType(keyInputField.type),
509
+ },
510
+ ],
511
+ });
512
+ }
513
+ // If no PK found from inputs, try to find 'id' field in entity type
514
+ if (primaryKey.length === 0) {
515
+ const entityType = typeMap.get(entityName);
516
+ if (entityType?.fields) {
517
+ const idField = entityType.fields.find((f) => f.name === 'id' || f.name === 'nodeId');
518
+ if (idField) {
519
+ primaryKey.push({
520
+ name: 'primary',
521
+ fields: [
522
+ {
523
+ name: idField.name,
524
+ type: convertToCleanFieldType(idField.type),
525
+ },
526
+ ],
527
+ });
528
+ }
529
+ }
530
+ }
531
+ return {
532
+ primaryKey,
533
+ foreignKey: [], // Would need FK info to populate
534
+ unique: [], // Would need constraint info to populate
535
+ };
536
+ }
537
+ /**
538
+ * Infer a single-row lookup key from an Update/Delete input object.
539
+ *
540
+ * Priority:
541
+ * 1. Canonical keys: id, nodeId, rowId
542
+ * 2. Single non-patch/non-clientMutationId scalar-ish field
543
+ *
544
+ * If multiple possible key fields remain, return null to avoid guessing.
545
+ */
546
+ function inferPrimaryKeyFromInputObject(inputType) {
547
+ const inputFields = inputType?.inputFields ?? [];
548
+ if (inputFields.length === 0)
549
+ return null;
550
+ const canonicalKey = inputFields.find((field) => field.name === 'id' || field.name === 'nodeId' || field.name === 'rowId');
551
+ if (canonicalKey)
552
+ return canonicalKey;
553
+ const candidates = inputFields.filter((field) => {
554
+ if (field.name === 'clientMutationId')
555
+ return false;
556
+ const baseTypeName = getBaseTypeName(field.type);
557
+ const lowerName = field.name.toLowerCase();
558
+ // Exclude patch payload fields (patch / fooPatch)
559
+ if (lowerName === 'patch' || lowerName.endsWith('patch'))
560
+ return false;
561
+ if (baseTypeName?.endsWith('Patch'))
562
+ return false;
563
+ return true;
564
+ });
565
+ return candidates.length === 1 ? candidates[0] : null;
566
+ }
567
+ /**
568
+ * Infer the patch field name from an Update input type.
569
+ *
570
+ * PostGraphile v5 uses entity-specific patch field names:
571
+ * UpdateUserInput → { id, userPatch: UserPatch }
572
+ * UpdateDatabaseInput → { id, databasePatch: DatabasePatch }
573
+ *
574
+ * Pattern: {lcFirst(entityTypeName)}Patch
575
+ */
576
+ function inferPatchFieldName(entityName, typeMap) {
577
+ const updateInputName = `Update${entityName}Input`;
578
+ const updateInput = typeMap.get(updateInputName);
579
+ const inputFields = updateInput?.inputFields ?? [];
580
+ // Find the field whose type name ends in 'Patch'
581
+ const patchField = inputFields.find((f) => {
582
+ const baseName = getBaseTypeName(f.type);
583
+ return baseName?.endsWith('Patch');
584
+ });
585
+ if (patchField)
586
+ return patchField.name;
587
+ // Fallback: compute from entity name (v5 default inflection)
588
+ return lcFirst(entityName) + 'Patch';
589
+ }
590
+ // ============================================================================
591
+ // Inflection Building
592
+ // ============================================================================
593
+ /**
594
+ * Build inflection map from discovered types
595
+ */
596
+ function buildInflection(entityName, typeMap, entityToConnection) {
597
+ const pluralName = pluralize(entityName);
598
+ const singularFieldName = lcFirst(entityName);
599
+ const pluralFieldName = lcFirst(pluralName);
600
+ const connectionTypeName = entityToConnection.get(entityName) ?? `${pluralName}Connection`;
601
+ // Check which types actually exist in the schema
602
+ const hasFilter = typeMap.has(`${entityName}Filter`);
603
+ const hasPatch = typeMap.has(`${entityName}Patch`);
604
+ const hasUpdatePayload = typeMap.has(`Update${entityName}Payload`);
605
+ // Detect the actual OrderBy type from schema
606
+ // PostGraphile typically generates {PluralName}OrderBy (e.g., AddressesOrderBy)
607
+ // but we check for the actual type in case of custom inflection
608
+ const expectedOrderByType = `${pluralName}OrderBy`;
609
+ const orderByType = findOrderByType(entityName, pluralName, typeMap) || expectedOrderByType;
610
+ return {
611
+ allRows: pluralFieldName,
612
+ allRowsSimple: pluralFieldName,
613
+ conditionType: `${entityName}Condition`,
614
+ connection: connectionTypeName,
615
+ createField: `create${entityName}`,
616
+ createInputType: `Create${entityName}Input`,
617
+ createPayloadType: `Create${entityName}Payload`,
618
+ deleteByPrimaryKey: `delete${entityName}`,
619
+ deletePayloadType: `Delete${entityName}Payload`,
620
+ edge: `${pluralName}Edge`,
621
+ edgeField: lcFirst(pluralName),
622
+ enumType: `${entityName}Enum`,
623
+ filterType: hasFilter ? `${entityName}Filter` : null,
624
+ inputType: `${entityName}Input`,
625
+ orderByType,
626
+ patchField: singularFieldName,
627
+ patchType: hasPatch ? `${entityName}Patch` : null,
628
+ tableFieldName: singularFieldName,
629
+ tableType: entityName,
630
+ typeName: entityName,
631
+ updateByPrimaryKey: `update${entityName}`,
632
+ updatePayloadType: hasUpdatePayload ? `Update${entityName}Payload` : null,
633
+ };
634
+ }
635
+ /**
636
+ * Find the actual OrderBy enum type for an entity from the schema
637
+ *
638
+ * PostGraphile generates OrderBy enums with various patterns:
639
+ * - {PluralName}OrderBy (e.g., AddressesOrderBy, UsersOrderBy)
640
+ * - Sometimes with custom inflection (e.g., SchemataOrderBy for Schema)
641
+ *
642
+ * We search for the actual type in the schema to handle all cases.
643
+ */
644
+ function findOrderByType(entityName, pluralName, typeMap) {
645
+ // Try the standard pattern first: {PluralName}OrderBy
646
+ const standardName = `${pluralName}OrderBy`;
647
+ if (typeMap.has(standardName)) {
648
+ return standardName;
649
+ }
650
+ // Build a list of candidate OrderBy names to check
651
+ // These are variations of the entity name with common plural suffixes
652
+ const candidates = [
653
+ `${entityName}sOrderBy`, // Simple 's' plural: User -> UsersOrderBy
654
+ `${entityName}esOrderBy`, // 'es' plural: Address -> AddressesOrderBy
655
+ `${entityName}OrderBy`, // No change (already plural or singular OK)
656
+ ];
657
+ // Check each candidate
658
+ for (const candidate of candidates) {
659
+ if (typeMap.has(candidate) && typeMap.get(candidate)?.kind === 'ENUM') {
660
+ return candidate;
661
+ }
662
+ }
663
+ // Fallback: search for an enum that EXACTLY matches the entity plural pattern
664
+ // We look for types that are the pluralized entity name + OrderBy
665
+ // This avoids matching SchemaGrantsOrderBy when looking for Schema's OrderBy
666
+ for (const [typeName, type] of typeMap) {
667
+ if (type.kind !== 'ENUM' || !typeName.endsWith('OrderBy'))
668
+ continue;
669
+ // Extract the base name (without OrderBy suffix)
670
+ const baseName = typeName.slice(0, -7); // Remove 'OrderBy'
671
+ // Check if singularizing the base name gives us the entity name
672
+ // e.g., 'Schemata' -> 'Schema', 'Users' -> 'User', 'Addresses' -> 'Address'
673
+ if (singularize(baseName) === entityName) {
674
+ return typeName;
675
+ }
676
+ }
677
+ return null;
678
+ }
679
+ // ============================================================================
680
+ // Utility Functions
681
+ // ============================================================================
682
+ /**
683
+ * Build a map of type name → IntrospectionType for efficient lookup
684
+ */
685
+ function buildTypeMap(types) {
686
+ const map = new Map();
687
+ for (const type of types) {
688
+ map.set(type.name, type);
689
+ }
690
+ return map;
691
+ }
692
+ /**
693
+ * Get fields from a type, returning empty array if null
694
+ */
695
+ function getTypeFields(type) {
696
+ return type?.fields ?? [];
697
+ }