-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathutils.ts
More file actions
682 lines (598 loc) · 20.9 KB
/
Copy pathutils.ts
File metadata and controls
682 lines (598 loc) · 20.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
/**
* Codegen utilities - naming conventions, type mapping, and helpers
*/
import {
lcFirst,
pluralize,
toCamelCase,
toConstantCase,
toPascalCase,
ucFirst,
} from 'inflekt';
import type {
Field,
FieldType,
Table,
TypeRegistry,
} from '../../types/schema';
import { scalarToFilterType, scalarToTsType } from './scalars';
// Re-export string manipulation helpers from inflekt (single source of truth)
export { lcFirst, toCamelCase, toConstantCase, toPascalCase, ucFirst };
// ============================================================================
// Naming conventions for generated code
// ============================================================================
export interface TableNames {
/** PascalCase singular (e.g., "Car") */
typeName: string;
/** camelCase singular (e.g., "car") */
singularName: string;
/** camelCase plural (e.g., "cars") */
pluralName: string;
/** PascalCase plural (e.g., "Cars") */
pluralTypeName: string;
}
/**
* Derive all naming variants from a table
*/
export function getTableNames(table: Table): TableNames {
const typeName = table.name;
const singularName = table.inflection?.tableFieldName || lcFirst(typeName);
const pluralName =
table.query?.all ||
table.inflection?.allRows ||
lcFirst(pluralize(typeName));
const pluralTypeName = ucFirst(pluralName);
return {
typeName,
singularName,
pluralName,
pluralTypeName,
};
}
/**
* Generate hook function name for list query
* e.g., "useCarsQuery"
*/
export function getListQueryHookName(table: Table): string {
const { pluralName } = getTableNames(table);
return `use${ucFirst(pluralName)}Query`;
}
/**
* Generate hook function name for single item query
* e.g., "useCarQuery"
*/
export function getSingleQueryHookName(table: Table): string {
const { singularName } = getTableNames(table);
return `use${ucFirst(singularName)}Query`;
}
/**
* Generate hook function name for create mutation
* e.g., "useCreateCarMutation"
*/
export function getCreateMutationHookName(table: Table): string {
const { typeName } = getTableNames(table);
return `useCreate${typeName}Mutation`;
}
/**
* Generate hook function name for update mutation
* e.g., "useUpdateCarMutation"
*/
export function getUpdateMutationHookName(table: Table): string {
const { typeName } = getTableNames(table);
return `useUpdate${typeName}Mutation`;
}
/**
* Generate hook function name for delete mutation
* e.g., "useDeleteCarMutation"
*/
export function getDeleteMutationHookName(table: Table): string {
const { typeName } = getTableNames(table);
return `useDelete${typeName}Mutation`;
}
/**
* Generate file name for list query hook
* e.g., "useCarsQuery.ts"
*/
export function getListQueryFileName(table: Table): string {
return `${getListQueryHookName(table)}.ts`;
}
/**
* Generate file name for single query hook
* e.g., "useCarQuery.ts"
*/
export function getSingleQueryFileName(table: Table): string {
return `${getSingleQueryHookName(table)}.ts`;
}
/**
* Generate file name for create mutation hook
*/
export function getCreateMutationFileName(table: Table): string {
return `${getCreateMutationHookName(table)}.ts`;
}
/**
* Generate file name for update mutation hook
*/
export function getUpdateMutationFileName(table: Table): string {
return `${getUpdateMutationHookName(table)}.ts`;
}
/**
* Generate file name for delete mutation hook
*/
export function getDeleteMutationFileName(table: Table): string {
return `${getDeleteMutationHookName(table)}.ts`;
}
/**
* Generate hook function name for subscription
* e.g., "useContactSubscription"
*/
export function getSubscriptionHookName(table: Table): string {
const { singularName } = getTableNames(table);
return `use${ucFirst(singularName)}Subscription`;
}
/**
* Generate file name for subscription hook
* e.g., "useContactSubscription.ts"
*/
export function getSubscriptionFileName(table: Table): string {
return `${getSubscriptionHookName(table)}.ts`;
}
/**
* Generate the GraphQL subscription field name
* e.g., "onContactChanged"
*/
export function getSubscriptionFieldName(table: Table): string {
const { singularName } = getTableNames(table);
return `on${ucFirst(singularName)}Changed`;
}
// ============================================================================
// GraphQL operation names
// ============================================================================
/**
* Get the GraphQL query name for fetching all rows
* Uses inflection from introspection, falls back to convention
*/
export function getAllRowsQueryName(table: Table): string {
return (
table.query?.all ||
table.inflection?.allRows ||
lcFirst(pluralize(table.name))
);
}
/**
* Get the GraphQL query name for fetching single row
*/
export function getSingleRowQueryName(table: Table): string {
return (
table.query?.one || table.inflection?.tableFieldName || lcFirst(table.name)
);
}
/**
* Get the GraphQL mutation name for creating
*/
export function getCreateMutationName(table: Table): string {
return table.query?.create || `create${table.name}`;
}
/**
* Get the GraphQL mutation name for updating
*/
export function getUpdateMutationName(table: Table): string {
return table.query?.update || `update${table.name}`;
}
/**
* Get the GraphQL mutation name for deleting
*/
export function getDeleteMutationName(table: Table): string {
return table.query?.delete || `delete${table.name}`;
}
// ============================================================================
// Bulk mutation naming helpers
// ============================================================================
export function getBulkCreateMutationHookName(table: Table): string {
const { typeName } = getTableNames(table);
return `useBulkCreate${typeName}Mutation`;
}
export function getBulkUpsertMutationHookName(table: Table): string {
const { typeName } = getTableNames(table);
return `useBulkUpsert${typeName}Mutation`;
}
export function getBulkUpdateMutationHookName(table: Table): string {
const { typeName } = getTableNames(table);
return `useBulkUpdate${typeName}Mutation`;
}
export function getBulkDeleteMutationHookName(table: Table): string {
const { typeName } = getTableNames(table);
return `useBulkDelete${typeName}Mutation`;
}
export function getBulkCreateMutationFileName(table: Table): string {
return `${getBulkCreateMutationHookName(table)}.ts`;
}
export function getBulkUpsertMutationFileName(table: Table): string {
return `${getBulkUpsertMutationHookName(table)}.ts`;
}
export function getBulkUpdateMutationFileName(table: Table): string {
return `${getBulkUpdateMutationHookName(table)}.ts`;
}
export function getBulkDeleteMutationFileName(table: Table): string {
return `${getBulkDeleteMutationHookName(table)}.ts`;
}
// ============================================================================
// Type names
// ============================================================================
/**
* Get PostGraphile filter type name
* e.g., "CarFilter"
*/
export function getFilterTypeName(table: Table): string {
return table.inflection?.filterType || `${table.name}Filter`;
}
/**
* Get PostGraphile OrderBy enum type name
* e.g., "CarsOrderBy", "AddressesOrderBy"
*/
export function getOrderByTypeName(table: Table): string {
return table.inflection?.orderByType || `${pluralize(table.name)}OrderBy`;
}
/**
* Get PostGraphile Condition type name (simple equality filter)
* e.g., "CarCondition", "AddressCondition"
*/
export function getConditionTypeName(table: Table): string {
return table.inflection?.conditionType || `${table.name}Condition`;
}
/**
* Get PostGraphile create input type name
* e.g., "CreateCarInput"
*/
export function getCreateInputTypeName(table: Table): string {
return table.inflection?.createInputType || `Create${table.name}Input`;
}
/**
* Get PostGraphile patch type name for updates
* e.g., "CarPatch"
*/
export function getPatchTypeName(table: Table): string {
return table.inflection?.patchType || `${table.name}Patch`;
}
/**
* Get PostGraphile update input type name
* Derives from actual mutation name when available (handles composite PK naming
* like UpdatePostTagByPostIdAndTagIdInput), falls back to Update${Entity}Input.
*/
export function getUpdateInputTypeName(table: Table): string {
const mutationName = table.query?.update;
return mutationName ? ucFirst(mutationName) + 'Input' : `Update${table.name}Input`;
}
/**
* Get PostGraphile delete input type name
* Derives from actual mutation name when available (handles composite PK naming
* like DeletePostTagByPostIdAndTagIdInput), falls back to Delete${Entity}Input.
*/
export function getDeleteInputTypeName(table: Table): string {
const mutationName = table.query?.delete;
return mutationName ? ucFirst(mutationName) + 'Input' : `Delete${table.name}Input`;
}
// ============================================================================
// Extra input keys (partition keys for update/delete mutations)
// ============================================================================
export interface ExtraInputKey {
name: string;
gqlType: string;
tsType: string;
}
/**
* Discover extra required fields on a mutation input type beyond the standard
* ones (clientMutationId, PK fields, patch field). PostGraphile adds these for
* partitioned tables (e.g. databaseId as the partition key).
*/
export function getExtraInputKeys(
inputTypeName: string,
pkFieldNames: Set<string>,
patchFieldName: string | null,
typeRegistry?: TypeRegistry,
): ExtraInputKey[] {
if (!typeRegistry) return [];
const inputType = typeRegistry.get(inputTypeName);
if (!inputType || inputType.kind !== 'INPUT_OBJECT' || !inputType.inputFields) return [];
const skip = new Set<string>(['clientMutationId', ...(patchFieldName ? [patchFieldName] : [])]);
for (const pk of pkFieldNames) skip.add(pk);
const extras: ExtraInputKey[] = [];
for (const field of inputType.inputFields) {
if (skip.has(field.name)) continue;
if (field.type.kind !== 'NON_NULL') continue;
const innerName = field.type.ofType?.name;
if (!innerName) continue;
let tsType = 'string';
if (innerName === 'Int' || innerName === 'Float' || innerName === 'BigFloat') tsType = 'number';
else if (innerName === 'Boolean') tsType = 'boolean';
extras.push({ name: field.name, gqlType: innerName, tsType });
}
return extras;
}
// ============================================================================
// Type mapping: GraphQL → TypeScript
// ============================================================================
/**
* Convert GraphQL type to TypeScript type
*/
export function gqlTypeToTs(gqlType: string, isArray: boolean = false): string {
// Remove non-null markers
const cleanType = gqlType.replace(/!/g, '');
// Look up in map, fallback to the type name itself (custom type)
const tsType = scalarToTsType(cleanType, { unknownScalar: 'name' });
return isArray ? `${tsType}[]` : tsType;
}
/**
* Convert FieldType to TypeScript type string
*/
export function fieldTypeToTs(fieldType: FieldType): string {
return gqlTypeToTs(fieldType.gqlType, fieldType.isArray);
}
// ============================================================================
// Type mapping: GraphQL → Filter type
// ============================================================================
/**
* Get the PostGraphile filter type for a GraphQL scalar
* @param gqlType - The GraphQL type string (e.g., "String", "UUID")
* @param isArray - Whether this is an array type
*/
export function getScalarFilterType(
gqlType: string,
isArray = false,
): string | null {
const cleanType = gqlType.replace(/!/g, '');
return scalarToFilterType(cleanType, isArray);
}
// ============================================================================
// Field filtering utilities
// ============================================================================
/**
* Check if a field is a relation field (not a scalar)
*/
export function isRelationField(fieldName: string, table: Table): boolean {
const { belongsTo, hasOne, hasMany, manyToMany } = table.relations;
return (
belongsTo.some((r) => r.fieldName === fieldName) ||
hasOne.some((r) => r.fieldName === fieldName) ||
hasMany.some((r) => r.fieldName === fieldName) ||
manyToMany.some((r) => r.fieldName === fieldName)
);
}
/**
* Get only scalar fields (non-relation fields)
*/
export function getScalarFields(table: Table): Field[] {
return table.fields.filter((f) => !isRelationField(f.name, table));
}
/**
* Resolve the inner input type from a CreateXInput.
* PostGraphile create inputs wrap the actual field definitions in an inner type
* (e.g. CreateUserInput -> { user: UserInput }) — this resolves that inner type
* and returns the set of field names it contains.
*/
export function resolveInnerInputType(
inputTypeName: string,
typeRegistry: TypeRegistry,
): { name: string; fields: Set<string> } | null {
const inputType = typeRegistry.get(inputTypeName);
if (!inputType?.inputFields) return null;
for (const inputField of inputType.inputFields) {
const innerTypeName = inputField.type.name
|| inputField.type.ofType?.name
|| inputField.type.ofType?.ofType?.name;
if (!innerTypeName) continue;
const innerType = typeRegistry.get(innerTypeName);
if (!innerType?.inputFields) continue;
const fields = new Set(innerType.inputFields.map((f) => f.name));
return { name: innerTypeName, fields };
}
return null;
}
/**
* Get the set of field names that actually exist in the create input type.
* Fields not in this set (e.g. computed fields like searchTsvRank, hashUuid)
* are plugin-added computed fields that don't correspond to real database columns.
* Returns null when no typeRegistry is provided (caller should treat as "no filtering").
*/
export function getWritableFieldNames(
table: Table,
typeRegistry?: TypeRegistry,
): Set<string> | null {
if (!typeRegistry) return null;
const createInputTypeName = getCreateInputTypeName(table);
const resolved = resolveInnerInputType(createInputTypeName, typeRegistry);
return resolved?.fields ?? null;
}
/**
* Get scalar fields that represent actual database columns (not computed/plugin-added).
* When a TypeRegistry is provided, filters out fields that don't exist in the
* create input type — these are computed fields added by plugins (e.g. search scores,
* hash UUIDs) that aren't real columns and shouldn't appear in default selections.
* Without a TypeRegistry, falls back to all scalar fields.
*/
export function getSelectableScalarFields(
table: Table,
typeRegistry?: TypeRegistry,
): Field[] {
const writableFields = getWritableFieldNames(table, typeRegistry);
return getScalarFields(table).filter(
(f) => writableFields === null || writableFields.has(f.name),
);
}
/**
* Primary key field information
*/
export interface PrimaryKeyField {
/** Field name */
name: string;
/** GraphQL type (e.g., "UUID", "Int", "String") */
gqlType: string;
/** TypeScript type (e.g., "string", "number") */
tsType: string;
}
/**
* Get primary key field information from table constraints
* Returns array to support composite primary keys
*/
export function getPrimaryKeyInfo(table: Table): PrimaryKeyField[] {
const pk = table.constraints?.primaryKey?.[0];
if (!pk || pk.fields.length === 0) {
// Fallback: try to find 'id' field in table fields
const idField = table.fields.find((f) => f.name.toLowerCase() === 'id');
if (idField) {
return [
{
name: idField.name,
gqlType: idField.type.gqlType,
tsType: fieldTypeToTs(idField.type),
},
];
}
// Last resort: assume 'id' of type string (UUID)
return [{ name: 'id', gqlType: 'UUID', tsType: 'string' }];
}
return pk.fields.map((f) => ({
name: f.name,
gqlType: f.type.gqlType,
tsType: fieldTypeToTs(f.type),
}));
}
/**
* Get primary key field names (convenience wrapper)
*/
export function getPrimaryKeyFields(table: Table): string[] {
return getPrimaryKeyInfo(table).map((pk) => pk.name);
}
/**
* Check if table has a valid single-field primary key
* Used to determine if a single query hook can be generated
* Tables with composite keys return false (handled as custom queries)
*/
export function hasValidPrimaryKey(table: Table): boolean {
// Check for explicit primary key constraint with single field
const pk = table.constraints?.primaryKey?.[0];
if (pk && pk.fields.length === 1) {
return true;
}
// Check for 'id' field as fallback
const idField = table.fields.find((f) => f.name.toLowerCase() === 'id');
if (idField) {
return true;
}
return false;
}
// ============================================================================
// Query key generation
// ============================================================================
/**
* Generate query key prefix for a table
* e.g., "cars" for list queries, "car" for detail queries
*/
export function getQueryKeyPrefix(table: Table): string {
return lcFirst(table.name);
}
// ============================================================================
// Smart Comment Utilities
// ============================================================================
/**
* PostGraphile smart comment tags that should be stripped from descriptions.
* Smart comments start with `@` and control PostGraphile behavior
* (e.g., `@omit`, `@name`, `@foreignKey`, etc.)
*
* A PostgreSQL COMMENT may contain both human-readable text and smart comments:
* COMMENT ON TABLE users IS 'User accounts for the application\n@omit delete';
*
* PostGraphile's introspection already separates these: the GraphQL `description`
* field contains only the human-readable part. So in most cases, the description
* we receive from introspection is already clean.
*
* However, as a safety measure, this utility strips any remaining `@`-prefixed
* lines that may have leaked through.
*/
/**
* PostGraphile auto-generated boilerplate descriptions that add no value.
* These are generic descriptions PostGraphile puts on every mutation input,
* clientMutationId field, etc. We filter them out to keep generated code clean.
*/
const POSTGRAPHILE_BOILERPLATE: string[] = [
'The exclusive input argument for this mutation.',
'An arbitrary string value with no semantic meaning.',
'The exact same `clientMutationId` that was provided in the mutation input,',
'The output of our',
'All input for the',
'A cursor for use in pagination.',
'An edge for our',
'Information to aid in pagination.',
'Reads and enables pagination through a set of',
'A list of edges which contains the',
'The count of *all* `',
'A list of `',
'Our root query field',
'Reads a single',
'The root query type',
'The root mutation type',
];
/**
* Check if a description is generic PostGraphile boilerplate that should be suppressed.
*/
function isBoilerplateDescription(description: string): boolean {
const trimmed = description.trim();
return POSTGRAPHILE_BOILERPLATE.some((bp) => trimmed.startsWith(bp));
}
/**
* Strip PostGraphile smart comments and boilerplate from a description string.
*
* Smart comments are lines starting with `@` (e.g., `@omit`, `@name newName`).
* Boilerplate descriptions are generic PostGraphile-generated text that repeats
* on every mutation input, clientMutationId field, etc.
*
* This returns only the meaningful human-readable portion of the comment,
* or undefined if the result is empty or boilerplate.
*
* @param description - Raw description from GraphQL introspection
* @returns Cleaned description, or undefined if empty/boilerplate
*/
export function stripSmartComments(
description: string | null | undefined,
enabled: boolean = true,
): string | undefined {
if (!enabled) return undefined;
if (!description) return undefined;
// Check if entire description is boilerplate
if (isBoilerplateDescription(description)) return undefined;
const lines = description.split('\n');
const cleanLines: string[] = [];
for (const line of lines) {
const trimmed = line.trim();
// Skip lines that start with @ (smart comment directives)
if (trimmed.startsWith('@')) continue;
cleanLines.push(line);
}
const result = cleanLines.join('\n').trim();
if (result.length === 0) return undefined;
// Re-check after stripping smart comments
if (isBoilerplateDescription(result)) return undefined;
return result;
}
// ============================================================================
// Code generation helpers
// ============================================================================
/**
* Generate a doc comment header for generated files
*/
export function getGeneratedFileHeader(description: string): string {
return `/**
* ${description}
* @generated by @constructive-io/graphql-codegen
* DO NOT EDIT - changes will be overwritten
*/`;
}
/**
* Indent a multi-line string
*/
export function indent(str: string, spaces: number = 2): string {
const pad = ' '.repeat(spaces);
return str
.split('\n')
.map((line) => (line.trim() ? pad + line : line))
.join('\n');
}