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