metal-orm 1.0.90 → 1.0.92

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 (37) hide show
  1. package/dist/index.cjs +214 -118
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +71 -32
  4. package/dist/index.d.ts +71 -32
  5. package/dist/index.js +206 -118
  6. package/dist/index.js.map +1 -1
  7. package/package.json +4 -2
  8. package/scripts/generate-entities/render.mjs +16 -3
  9. package/src/core/ddl/introspect/utils.ts +45 -45
  10. package/src/decorators/bootstrap.ts +37 -37
  11. package/src/decorators/column-decorator.ts +3 -1
  12. package/src/dto/apply-filter.ts +279 -281
  13. package/src/dto/dto-types.ts +229 -229
  14. package/src/dto/filter-types.ts +193 -193
  15. package/src/dto/index.ts +97 -97
  16. package/src/dto/openapi/generators/base.ts +29 -29
  17. package/src/dto/openapi/generators/column.ts +37 -34
  18. package/src/dto/openapi/generators/dto.ts +94 -94
  19. package/src/dto/openapi/generators/filter.ts +75 -74
  20. package/src/dto/openapi/generators/nested-dto.ts +618 -532
  21. package/src/dto/openapi/generators/pagination.ts +111 -111
  22. package/src/dto/openapi/generators/relation-filter.ts +228 -210
  23. package/src/dto/openapi/index.ts +17 -17
  24. package/src/dto/openapi/type-mappings.ts +191 -191
  25. package/src/dto/openapi/types.ts +101 -83
  26. package/src/dto/openapi/utilities.ts +90 -45
  27. package/src/dto/pagination-utils.ts +150 -150
  28. package/src/dto/transform.ts +197 -193
  29. package/src/index.ts +69 -69
  30. package/src/orm/entity-context.ts +9 -9
  31. package/src/orm/entity-metadata.ts +14 -14
  32. package/src/orm/entity.ts +74 -74
  33. package/src/orm/orm-session.ts +159 -159
  34. package/src/orm/relation-change-processor.ts +3 -3
  35. package/src/orm/runtime-types.ts +5 -5
  36. package/src/schema/column-types.ts +4 -4
  37. package/src/schema/types.ts +5 -1
@@ -1,532 +1,618 @@
1
- import type { TableDef } from '../../../schema/table.js';
2
- import type { EntityConstructor } from '../../../orm/entity-metadata.js';
3
- import type {
4
- RelationDef,
5
- BelongsToRelation,
6
- HasManyRelation,
7
- HasOneRelation,
8
- BelongsToManyRelation
9
- } from '../../../schema/relation.js';
10
- import type { OpenApiSchema, OpenApiComponent } from '../types.js';
11
- import { columnToOpenApiSchema } from './column.js';
12
- import { getColumnMap } from './base.js';
13
- import { RelationKinds } from '../../../schema/relation.js';
14
-
15
- export interface ComponentOptions {
16
- prefix?: string;
17
- exclude?: string[];
18
- include?: string[];
19
- }
20
-
21
- export interface NestedDtoOptions {
22
- maxDepth?: number;
23
- includeRelations?: boolean;
24
- componentOptions?: ComponentOptions;
25
- }
26
-
27
- export interface ComponentReference {
28
- $ref: string;
29
- }
30
-
31
- export function isComponentReference(schema: OpenApiSchema): schema is ComponentReference {
32
- return '$ref' in schema;
33
- }
34
-
35
- export function nestedDtoToOpenApiSchema<T extends TableDef | EntityConstructor>(
36
- target: T,
37
- options?: NestedDtoOptions
38
- ): OpenApiSchema {
39
- const depth = options?.maxDepth ?? 2;
40
- const includeRelations = options?.includeRelations ?? true;
41
-
42
- return nestedDtoSchema(target, depth, includeRelations, options?.componentOptions);
43
- }
44
-
45
- function nestedDtoSchema(
46
- target: TableDef | EntityConstructor,
47
- depth: number,
48
- includeRelations: boolean,
49
- componentOptions?: ComponentOptions
50
- ): OpenApiSchema {
51
- if (depth <= 0) {
52
- return { type: 'object', properties: {} };
53
- }
54
-
55
- const columns = getColumnMap(target);
56
- const properties: Record<string, OpenApiSchema> = {};
57
-
58
- for (const [key, col] of Object.entries(columns)) {
59
- if (componentOptions?.exclude?.includes(key)) {
60
- continue;
61
- }
62
-
63
- if (componentOptions?.include && !componentOptions.include.includes(key)) {
64
- continue;
65
- }
66
-
67
- properties[key] = columnToOpenApiSchema(col);
68
- }
69
-
70
- const tableDef = target as TableDef;
71
- if (includeRelations && tableDef.relations) {
72
- for (const [relationName, relation] of Object.entries(tableDef.relations)) {
73
- if (componentOptions?.exclude?.includes(relationName)) {
74
- continue;
75
- }
76
-
77
- if (componentOptions?.include && !componentOptions.include.includes(relationName)) {
78
- continue;
79
- }
80
-
81
- properties[relationName] = nestedRelationSchema(relation, depth - 1, componentOptions);
82
- }
83
- }
84
-
85
- return {
86
- type: 'object',
87
- properties,
88
- };
89
- }
90
-
91
- function nestedRelationSchema(
92
- relation: RelationDef,
93
- depth: number,
94
- componentOptions?: ComponentOptions
95
- ): OpenApiSchema {
96
- if (depth <= 0) {
97
- return { type: 'object', properties: {} };
98
- }
99
-
100
- if (relation.type === RelationKinds.BelongsTo || relation.type === RelationKinds.HasOne) {
101
- const target = (relation as BelongsToRelation | HasOneRelation).target;
102
- return nestedDtoSchema(target, depth, true, componentOptions);
103
- }
104
-
105
- if (relation.type === RelationKinds.HasMany || relation.type === RelationKinds.BelongsToMany) {
106
- const target = (relation as HasManyRelation | BelongsToManyRelation).target;
107
- return {
108
- type: 'array',
109
- items: nestedDtoSchema(target, depth - 1, true, componentOptions),
110
- };
111
- }
112
-
113
- return { type: 'object', properties: {} };
114
- }
115
-
116
- export function updateDtoWithRelationsToOpenApiSchema<T extends TableDef | EntityConstructor>(
117
- target: T,
118
- _options?: NestedDtoOptions
119
- ): OpenApiSchema {
120
- const columns = getColumnMap(target);
121
- const properties: Record<string, OpenApiSchema> = {};
122
-
123
- for (const [key, col] of Object.entries(columns)) {
124
- if (col.autoIncrement || col.generated) {
125
- continue;
126
- }
127
-
128
- properties[key] = {
129
- ...columnToOpenApiSchema(col),
130
- nullable: true,
131
- };
132
- }
133
-
134
- const tableDef = target as TableDef;
135
- if (_options?.includeRelations !== false && tableDef.relations) {
136
- for (const [relationName, relation] of Object.entries(tableDef.relations)) {
137
- if (relation.type === RelationKinds.BelongsTo || relation.type === RelationKinds.HasOne) {
138
- properties[relationName] = updateDtoToOpenApiSchemaForComponent(
139
- (relation as BelongsToRelation | HasOneRelation).target
140
- );
141
- }
142
- }
143
- }
144
-
145
- return {
146
- type: 'object',
147
- properties,
148
- };
149
- }
150
-
151
- function updateDtoToOpenApiSchemaForComponent(
152
- target: TableDef | EntityConstructor
153
- ): OpenApiSchema {
154
- const columns = getColumnMap(target);
155
- const properties: Record<string, OpenApiSchema> = {};
156
-
157
- for (const [key, col] of Object.entries(columns)) {
158
- if (col.autoIncrement || col.generated) {
159
- continue;
160
- }
161
-
162
- properties[key] = {
163
- ...columnToOpenApiSchema(col),
164
- nullable: true,
165
- };
166
- }
167
-
168
- return {
169
- type: 'object',
170
- properties,
171
- };
172
- }
173
-
174
- export function generateComponentSchemas(
175
- targets: Array<{ name: string; table: TableDef | EntityConstructor }>,
176
- options?: ComponentOptions
177
- ): Record<string, OpenApiSchema> {
178
- const components: Record<string, OpenApiSchema> = {};
179
- const prefix = options?.prefix ?? '';
180
-
181
- for (const target of targets) {
182
- const componentName = `${prefix}${target.name}`;
183
- components[componentName] = dtoToOpenApiSchemaForComponent(
184
- target.table,
185
- options
186
- );
187
- }
188
-
189
- return components;
190
- }
191
-
192
- function dtoToOpenApiSchemaForComponent(
193
- target: TableDef | EntityConstructor,
194
- options?: ComponentOptions
195
- ): OpenApiSchema {
196
- const columns = getColumnMap(target);
197
- const properties: Record<string, OpenApiSchema> = {};
198
- const required: string[] = [];
199
-
200
- for (const [key, col] of Object.entries(columns)) {
201
- if (options?.exclude?.includes(key)) {
202
- continue;
203
- }
204
-
205
- if (options?.include && !options.include.includes(key)) {
206
- continue;
207
- }
208
-
209
- properties[key] = columnToOpenApiSchema(col);
210
-
211
- if (col.notNull || col.primary) {
212
- required.push(key);
213
- }
214
- }
215
-
216
- return {
217
- type: 'object',
218
- properties,
219
- ...(required.length > 0 && { required }),
220
- };
221
- }
222
-
223
- export function generateRelationComponents(
224
- tables: Array<{ name: string; table: TableDef }>,
225
- options?: ComponentOptions
226
- ): Record<string, OpenApiSchema> {
227
- const components: Record<string, OpenApiSchema> = {};
228
- const prefix = options?.prefix ?? '';
229
-
230
- for (const { name, table } of tables) {
231
- const baseName = `${prefix}${name}`;
232
- components[`${baseName}Create`] = createDtoToOpenApiSchemaForComponent(table);
233
- components[`${baseName}Update`] = updateDtoToOpenApiSchemaForComponent(table);
234
- components[`${baseName}Filter`] = whereInputWithRelationsToOpenApiSchema(table, {
235
- columnExclude: options?.exclude,
236
- columnInclude: options?.include,
237
- maxDepth: 2,
238
- });
239
- }
240
-
241
- return components;
242
- }
243
-
244
- function createDtoToOpenApiSchemaForComponent(
245
- target: TableDef | EntityConstructor
246
- ): OpenApiSchema {
247
- const columns = getColumnMap(target);
248
- const properties: Record<string, OpenApiSchema> = {};
249
-
250
- for (const [key, col] of Object.entries(columns)) {
251
- if (col.autoIncrement || col.generated) {
252
- continue;
253
- }
254
-
255
- properties[key] = columnToOpenApiSchema(col);
256
- }
257
-
258
- return {
259
- type: 'object',
260
- properties,
261
- };
262
- }
263
-
264
- function whereInputWithRelationsToOpenApiSchema(
265
- target: TableDef | EntityConstructor,
266
- options?: {
267
- columnExclude?: string[];
268
- columnInclude?: string[];
269
- relationExclude?: string[];
270
- relationInclude?: string[];
271
- maxDepth?: number;
272
- prefix?: string;
273
- }
274
- ): OpenApiSchema {
275
- const columns = getColumnMap(target);
276
- const properties: Record<string, OpenApiSchema> = {};
277
- const depth = options?.maxDepth ?? 3;
278
-
279
- for (const [key, col] of Object.entries(columns)) {
280
- if (options?.columnExclude?.includes(key)) {
281
- continue;
282
- }
283
-
284
- if (options?.columnInclude && !options.columnInclude.includes(key)) {
285
- continue;
286
- }
287
-
288
- properties[key] = columnToOpenApiSchema(col);
289
- }
290
-
291
- const tableDef = target as TableDef;
292
- if (tableDef.relations && depth > 0) {
293
- for (const [relationName, relation] of Object.entries(tableDef.relations)) {
294
- if (options?.relationExclude?.includes(relationName)) {
295
- continue;
296
- }
297
-
298
- if (options?.relationInclude && !options.relationInclude.includes(relationName)) {
299
- continue;
300
- }
301
-
302
- properties[relationName] = relationFilterToOpenApiSchema(relation, {
303
- exclude: options?.columnExclude,
304
- include: options?.columnInclude,
305
- });
306
- }
307
- }
308
-
309
- return {
310
- type: 'object',
311
- properties,
312
- };
313
- }
314
-
315
- function relationFilterToOpenApiSchema(
316
- relation: RelationDef,
317
- options?: {
318
- exclude?: string[];
319
- include?: string[];
320
- }
321
- ): OpenApiSchema {
322
- if (relation.type === RelationKinds.BelongsTo || relation.type === RelationKinds.HasOne) {
323
- return singleRelationFilterToOpenApiSchema((relation as BelongsToRelation | HasOneRelation).target, options);
324
- }
325
-
326
- if (relation.type === RelationKinds.HasMany || relation.type === RelationKinds.BelongsToMany) {
327
- return manyRelationFilterToOpenApiSchema((relation as HasManyRelation | BelongsToManyRelation).target);
328
- }
329
-
330
- return { type: 'object', properties: {} };
331
- }
332
-
333
- function singleRelationFilterToOpenApiSchema(
334
- target: TableDef | EntityConstructor,
335
- options?: { exclude?: string[]; include?: string[] }
336
- ): OpenApiSchema {
337
- const columns = getColumnMap(target);
338
- const properties: Record<string, OpenApiSchema> = {};
339
-
340
- for (const [key, col] of Object.entries(columns)) {
341
- if (options?.exclude?.includes(key)) {
342
- continue;
343
- }
344
-
345
- if (options?.include && !options.include.includes(key)) {
346
- continue;
347
- }
348
-
349
- properties[key] = columnToOpenApiSchema(col);
350
- }
351
-
352
- return {
353
- type: 'object',
354
- properties,
355
- };
356
- }
357
-
358
- function manyRelationFilterToOpenApiSchema(
359
- target: TableDef | EntityConstructor
360
- ): OpenApiSchema {
361
- return {
362
- type: 'object',
363
- properties: {
364
- some: {
365
- type: 'object',
366
- description: 'Filter related records that match all conditions',
367
- properties: generateNestedProperties(target),
368
- },
369
- every: {
370
- type: 'object',
371
- description: 'Filter related records where all match conditions',
372
- properties: generateNestedProperties(target),
373
- },
374
- none: {
375
- type: 'object',
376
- description: 'Filter where no related records match',
377
- properties: generateNestedProperties(target),
378
- },
379
- isEmpty: {
380
- type: 'boolean',
381
- description: 'Filter where relation has no related records',
382
- },
383
- isNotEmpty: {
384
- type: 'boolean',
385
- description: 'Filter where relation has related records',
386
- },
387
- },
388
- };
389
- }
390
-
391
- function generateNestedProperties(
392
- target: TableDef | EntityConstructor
393
- ): Record<string, OpenApiSchema> {
394
- const columns = getColumnMap(target);
395
- const properties: Record<string, OpenApiSchema> = {};
396
-
397
- for (const [key, col] of Object.entries(columns)) {
398
- properties[key] = columnToOpenApiSchema(col);
399
- }
400
-
401
- return properties;
402
- }
403
-
404
- export function createApiComponentsSection(
405
- schemas: Record<string, OpenApiSchema>,
406
- parameters?: Record<string, OpenApiSchema>,
407
- responses?: Record<string, OpenApiSchema>
408
- ): OpenApiComponent {
409
- const component: OpenApiComponent = {};
410
-
411
- if (Object.keys(schemas).length > 0) {
412
- component.schemas = schemas;
413
- }
414
-
415
- if (parameters && Object.keys(parameters).length > 0) {
416
- component.parameters = parameters;
417
- }
418
-
419
- if (responses && Object.keys(responses).length > 0) {
420
- component.responses = responses;
421
- }
422
-
423
- return component;
424
- }
425
-
426
- export function createRef(path: string): ComponentReference {
427
- return { $ref: `#/components/${path}` };
428
- }
429
-
430
- export function schemaToRef(schemaName: string): ComponentReference {
431
- return createRef(`schemas/${schemaName}`);
432
- }
433
-
434
- export function parameterToRef(paramName: string): ComponentReference {
435
- return createRef(`parameters/${paramName}`);
436
- }
437
-
438
- export function responseToRef(responseName: string): ComponentReference {
439
- return createRef(`responses/${responseName}`);
440
- }
441
-
442
- export function replaceWithRefs(
443
- schema: OpenApiSchema,
444
- schemaMap: Record<string, OpenApiSchema>,
445
- path: string = 'components/schemas'
446
- ): OpenApiSchema {
447
- if (typeof schema === 'object' && schema !== null) {
448
- if ('$ref' in schema) {
449
- return schema;
450
- }
451
-
452
- const schemaJson = JSON.stringify(schema);
453
- for (const [name, mapSchema] of Object.entries(schemaMap)) {
454
- if (JSON.stringify(mapSchema) === schemaJson) {
455
- return { $ref: `#/${path}/${name}` };
456
- }
457
- }
458
-
459
- if ('type' in schema && schema.type === 'object' && 'properties' in schema) {
460
- const newProperties: Record<string, OpenApiSchema> = {};
461
-
462
- for (const [key, value] of Object.entries(schema.properties || {})) {
463
- newProperties[key] = replaceWithRefs(value as OpenApiSchema, schemaMap, path);
464
- }
465
-
466
- return {
467
- ...schema,
468
- properties: newProperties,
469
- };
470
- }
471
-
472
- if ('items' in schema && typeof schema.items === 'object') {
473
- return {
474
- ...schema,
475
- items: replaceWithRefs(schema.items, schemaMap, path),
476
- };
477
- }
478
-
479
- if ('allOf' in schema && Array.isArray(schema.allOf)) {
480
- return {
481
- ...schema,
482
- allOf: schema.allOf.map(item => replaceWithRefs(item, schemaMap, path)),
483
- };
484
- }
485
-
486
- if ('oneOf' in schema && Array.isArray(schema.oneOf)) {
487
- return {
488
- ...schema,
489
- oneOf: schema.oneOf.map(item => replaceWithRefs(item, schemaMap, path)),
490
- };
491
- }
492
- }
493
-
494
- return schema;
495
- }
496
-
497
- export function extractReusableSchemas(
498
- schema: OpenApiSchema,
499
- existing: Record<string, OpenApiSchema> = {},
500
- prefix: string = ''
501
- ): Record<string, OpenApiSchema> {
502
- if (typeof schema !== 'object' || schema === null) {
503
- return existing;
504
- }
505
-
506
- if ('type' in schema && schema.type === 'object' && 'properties' in schema) {
507
- for (const [key, value] of Object.entries(schema.properties || {})) {
508
- extractReusableSchemas(value as OpenApiSchema, existing, `${prefix}${key.charAt(0).toUpperCase() + key.slice(1)}`);
509
- }
510
- } else if ('items' in schema && typeof schema.items === 'object') {
511
- extractReusableSchemas(schema.items as OpenApiSchema, existing, prefix);
512
- } else if ('allOf' in schema && Array.isArray(schema.allOf)) {
513
- for (const item of schema.allOf) {
514
- extractReusableSchemas(item, existing, prefix);
515
- }
516
- } else if ('oneOf' in schema && Array.isArray(schema.oneOf)) {
517
- for (const item of schema.oneOf) {
518
- extractReusableSchemas(item, existing, prefix);
519
- }
520
- }
521
-
522
- if (!('$ref' in schema)) {
523
- const name = prefix;
524
- if (name && 'type' in schema && schema.type === 'object' && 'properties' in schema) {
525
- if (!(name in existing) && Object.keys(schema.properties || {}).length > 0) {
526
- existing[name] = { ...schema };
527
- }
528
- }
529
- }
530
-
531
- return existing;
532
- }
1
+ import type { TableDef } from '../../../schema/table.js';
2
+ import type { EntityConstructor } from '../../../orm/entity-metadata.js';
3
+ import type {
4
+ RelationDef,
5
+ BelongsToRelation,
6
+ HasManyRelation,
7
+ HasOneRelation,
8
+ BelongsToManyRelation
9
+ } from '../../../schema/relation.js';
10
+ import type { OpenApiSchema, OpenApiComponent, OpenApiDialect, OpenApiParameterObject, OpenApiResponseObject } from '../types.js';
11
+ import { columnToOpenApiSchema } from './column.js';
12
+ import { columnToFilterSchema } from './filter.js';
13
+ import { getColumnMap } from './base.js';
14
+ import { RelationKinds } from '../../../schema/relation.js';
15
+
16
+ export interface ComponentOptions {
17
+ prefix?: string;
18
+ exclude?: string[];
19
+ include?: string[];
20
+ }
21
+
22
+ export interface NestedDtoOptions {
23
+ maxDepth?: number;
24
+ includeRelations?: boolean;
25
+ componentOptions?: ComponentOptions;
26
+ }
27
+
28
+ export interface ComponentReference {
29
+ $ref: string;
30
+ }
31
+
32
+ export function isComponentReference(schema: OpenApiSchema): schema is ComponentReference {
33
+ return '$ref' in schema;
34
+ }
35
+
36
+ export function nestedDtoToOpenApiSchema<T extends TableDef | EntityConstructor>(
37
+ target: T,
38
+ options?: NestedDtoOptions
39
+ ): OpenApiSchema {
40
+ const depth = options?.maxDepth ?? 2;
41
+ const includeRelations = options?.includeRelations ?? true;
42
+
43
+ return nestedDtoSchema(target, depth, includeRelations, options?.componentOptions);
44
+ }
45
+
46
+ function nestedDtoSchema(
47
+ target: TableDef | EntityConstructor,
48
+ depth: number,
49
+ includeRelations: boolean,
50
+ componentOptions?: ComponentOptions
51
+ ): OpenApiSchema {
52
+ if (depth <= 0) {
53
+ return { type: 'object', properties: {} };
54
+ }
55
+
56
+ const columns = getColumnMap(target);
57
+ const properties: Record<string, OpenApiSchema> = {};
58
+
59
+ for (const [key, col] of Object.entries(columns)) {
60
+ if (componentOptions?.exclude?.includes(key)) {
61
+ continue;
62
+ }
63
+
64
+ if (componentOptions?.include && !componentOptions.include.includes(key)) {
65
+ continue;
66
+ }
67
+
68
+ properties[key] = columnToOpenApiSchema(col);
69
+ }
70
+
71
+ const tableDef = target as TableDef;
72
+ if (includeRelations && tableDef.relations) {
73
+ for (const [relationName, relation] of Object.entries(tableDef.relations)) {
74
+ if (componentOptions?.exclude?.includes(relationName)) {
75
+ continue;
76
+ }
77
+
78
+ if (componentOptions?.include && !componentOptions.include.includes(relationName)) {
79
+ continue;
80
+ }
81
+
82
+ properties[relationName] = nestedRelationSchema(relation, depth - 1, componentOptions);
83
+ }
84
+ }
85
+
86
+ return {
87
+ type: 'object',
88
+ properties,
89
+ };
90
+ }
91
+
92
+ function nestedRelationSchema(
93
+ relation: RelationDef,
94
+ depth: number,
95
+ componentOptions?: ComponentOptions
96
+ ): OpenApiSchema {
97
+ if (depth <= 0) {
98
+ return { type: 'object', properties: {} };
99
+ }
100
+
101
+ if (relation.type === RelationKinds.BelongsTo || relation.type === RelationKinds.HasOne) {
102
+ const target = (relation as BelongsToRelation | HasOneRelation).target;
103
+ return nestedDtoSchema(target, depth, true, componentOptions);
104
+ }
105
+
106
+ if (relation.type === RelationKinds.HasMany || relation.type === RelationKinds.BelongsToMany) {
107
+ const target = (relation as HasManyRelation | BelongsToManyRelation).target;
108
+ return {
109
+ type: 'array',
110
+ items: nestedDtoSchema(target, depth - 1, true, componentOptions),
111
+ };
112
+ }
113
+
114
+ return { type: 'object', properties: {} };
115
+ }
116
+
117
+ export function updateDtoWithRelationsToOpenApiSchema<T extends TableDef | EntityConstructor>(
118
+ target: T,
119
+ _options?: NestedDtoOptions
120
+ ): OpenApiSchema {
121
+ const columns = getColumnMap(target);
122
+ const properties: Record<string, OpenApiSchema> = {};
123
+
124
+ for (const [key, col] of Object.entries(columns)) {
125
+ if (col.autoIncrement || col.generated) {
126
+ continue;
127
+ }
128
+
129
+ properties[key] = columnToOpenApiSchema(col);
130
+ }
131
+
132
+ const tableDef = target as TableDef;
133
+ if (_options?.includeRelations !== false && tableDef.relations) {
134
+ for (const [relationName, relation] of Object.entries(tableDef.relations)) {
135
+ if (relation.type === RelationKinds.BelongsTo || relation.type === RelationKinds.HasOne) {
136
+ properties[relationName] = updateDtoToOpenApiSchemaForComponent(
137
+ (relation as BelongsToRelation | HasOneRelation).target
138
+ );
139
+ }
140
+ }
141
+ }
142
+
143
+ return {
144
+ type: 'object',
145
+ properties,
146
+ };
147
+ }
148
+
149
+ function updateDtoToOpenApiSchemaForComponent(
150
+ target: TableDef | EntityConstructor
151
+ ): OpenApiSchema {
152
+ const columns = getColumnMap(target);
153
+ const properties: Record<string, OpenApiSchema> = {};
154
+
155
+ for (const [key, col] of Object.entries(columns)) {
156
+ if (col.autoIncrement || col.generated) {
157
+ continue;
158
+ }
159
+
160
+ properties[key] = columnToOpenApiSchema(col);
161
+ }
162
+
163
+ return {
164
+ type: 'object',
165
+ properties,
166
+ };
167
+ }
168
+
169
+ export function generateComponentSchemas(
170
+ targets: Array<{ name: string; table: TableDef | EntityConstructor }>,
171
+ options?: ComponentOptions
172
+ ): Record<string, OpenApiSchema> {
173
+ const components: Record<string, OpenApiSchema> = {};
174
+ const prefix = options?.prefix ?? '';
175
+
176
+ for (const target of targets) {
177
+ const componentName = `${prefix}${target.name}`;
178
+ components[componentName] = dtoToOpenApiSchemaForComponent(
179
+ target.table,
180
+ options
181
+ );
182
+ }
183
+
184
+ return components;
185
+ }
186
+
187
+ function dtoToOpenApiSchemaForComponent(
188
+ target: TableDef | EntityConstructor,
189
+ options?: ComponentOptions
190
+ ): OpenApiSchema {
191
+ const columns = getColumnMap(target);
192
+ const properties: Record<string, OpenApiSchema> = {};
193
+ const required: string[] = [];
194
+
195
+ for (const [key, col] of Object.entries(columns)) {
196
+ if (options?.exclude?.includes(key)) {
197
+ continue;
198
+ }
199
+
200
+ if (options?.include && !options.include.includes(key)) {
201
+ continue;
202
+ }
203
+
204
+ properties[key] = columnToOpenApiSchema(col);
205
+
206
+ if (col.notNull || col.primary) {
207
+ required.push(key);
208
+ }
209
+ }
210
+
211
+ return {
212
+ type: 'object',
213
+ properties,
214
+ ...(required.length > 0 && { required }),
215
+ };
216
+ }
217
+
218
+ export function generateRelationComponents(
219
+ tables: Array<{ name: string; table: TableDef }>,
220
+ options?: ComponentOptions
221
+ ): Record<string, OpenApiSchema> {
222
+ const components: Record<string, OpenApiSchema> = {};
223
+ const prefix = options?.prefix ?? '';
224
+
225
+ for (const { name, table } of tables) {
226
+ const baseName = `${prefix}${name}`;
227
+ components[`${baseName}Create`] = createDtoToOpenApiSchemaForComponent(table);
228
+ components[`${baseName}Update`] = updateDtoToOpenApiSchemaForComponent(table);
229
+ components[`${baseName}Filter`] = whereInputWithRelationsToOpenApiSchema(table, {
230
+ columnExclude: options?.exclude,
231
+ columnInclude: options?.include,
232
+ maxDepth: 2,
233
+ });
234
+ }
235
+
236
+ return components;
237
+ }
238
+
239
+ function createDtoToOpenApiSchemaForComponent(
240
+ target: TableDef | EntityConstructor
241
+ ): OpenApiSchema {
242
+ const columns = getColumnMap(target);
243
+ const properties: Record<string, OpenApiSchema> = {};
244
+
245
+ for (const [key, col] of Object.entries(columns)) {
246
+ if (col.autoIncrement || col.generated) {
247
+ continue;
248
+ }
249
+
250
+ properties[key] = columnToOpenApiSchema(col);
251
+ }
252
+
253
+ return {
254
+ type: 'object',
255
+ properties,
256
+ };
257
+ }
258
+
259
+ function whereInputWithRelationsToOpenApiSchema(
260
+ target: TableDef | EntityConstructor,
261
+ options?: {
262
+ columnExclude?: string[];
263
+ columnInclude?: string[];
264
+ relationExclude?: string[];
265
+ relationInclude?: string[];
266
+ maxDepth?: number;
267
+ prefix?: string;
268
+ },
269
+ dialect: OpenApiDialect = 'openapi-3.1'
270
+ ): OpenApiSchema {
271
+ const columns = getColumnMap(target);
272
+ const properties: Record<string, OpenApiSchema> = {};
273
+ const depth = options?.maxDepth ?? 3;
274
+
275
+ for (const [key, col] of Object.entries(columns)) {
276
+ if (options?.columnExclude?.includes(key)) {
277
+ continue;
278
+ }
279
+
280
+ if (options?.columnInclude && !options.columnInclude.includes(key)) {
281
+ continue;
282
+ }
283
+
284
+ properties[key] = columnToFilterSchema(col, dialect);
285
+ }
286
+
287
+ const tableDef = target as TableDef;
288
+ if (tableDef.relations && depth > 0) {
289
+ for (const [relationName, relation] of Object.entries(tableDef.relations)) {
290
+ if (options?.relationExclude?.includes(relationName)) {
291
+ continue;
292
+ }
293
+
294
+ if (options?.relationInclude && !options.relationInclude.includes(relationName)) {
295
+ continue;
296
+ }
297
+
298
+ properties[relationName] = relationFilterToOpenApiSchema(relation, {
299
+ exclude: options.columnExclude,
300
+ include: options.columnInclude,
301
+ }, dialect);
302
+ }
303
+ }
304
+
305
+ return {
306
+ type: 'object',
307
+ properties,
308
+ };
309
+ }
310
+
311
+ function relationFilterToOpenApiSchema(
312
+ relation: RelationDef,
313
+ options?: {
314
+ exclude?: string[];
315
+ include?: string[];
316
+ },
317
+ dialect: OpenApiDialect = 'openapi-3.1'
318
+ ): OpenApiSchema {
319
+ if (relation.type === RelationKinds.BelongsTo || relation.type === RelationKinds.HasOne) {
320
+ return singleRelationFilterToOpenApiSchema((relation as BelongsToRelation | HasOneRelation).target, options, dialect);
321
+ }
322
+
323
+ if (relation.type === RelationKinds.HasMany || relation.type === RelationKinds.BelongsToMany) {
324
+ return manyRelationFilterToOpenApiSchema((relation as HasManyRelation | BelongsToManyRelation).target);
325
+ }
326
+
327
+ return { type: 'object', properties: {} };
328
+ }
329
+
330
+ function singleRelationFilterToOpenApiSchema(
331
+ target: TableDef | EntityConstructor,
332
+ options?: { exclude?: string[]; include?: string[] },
333
+ dialect: OpenApiDialect = 'openapi-3.1'
334
+ ): OpenApiSchema {
335
+ const columns = getColumnMap(target);
336
+ const properties: Record<string, OpenApiSchema> = {};
337
+
338
+ for (const [key, col] of Object.entries(columns)) {
339
+ if (options?.exclude?.includes(key)) {
340
+ continue;
341
+ }
342
+
343
+ if (options?.include && !options.include.includes(key)) {
344
+ continue;
345
+ }
346
+
347
+ properties[key] = columnToFilterSchema(col, dialect);
348
+ }
349
+
350
+ return {
351
+ type: 'object',
352
+ properties,
353
+ };
354
+ }
355
+
356
+ function manyRelationFilterToOpenApiSchema(
357
+ target: TableDef | EntityConstructor
358
+ ): OpenApiSchema {
359
+ return {
360
+ type: 'object',
361
+ properties: {
362
+ some: {
363
+ type: 'object',
364
+ description: 'Filter related records that match all conditions',
365
+ properties: generateNestedProperties(target),
366
+ },
367
+ every: {
368
+ type: 'object',
369
+ description: 'Filter related records where all match conditions',
370
+ properties: generateNestedProperties(target),
371
+ },
372
+ none: {
373
+ type: 'object',
374
+ description: 'Filter where no related records match',
375
+ properties: generateNestedProperties(target),
376
+ },
377
+ isEmpty: {
378
+ type: 'boolean',
379
+ description: 'Filter where relation has no related records',
380
+ },
381
+ isNotEmpty: {
382
+ type: 'boolean',
383
+ description: 'Filter where relation has related records',
384
+ },
385
+ },
386
+ };
387
+ }
388
+
389
+ function generateNestedProperties(
390
+ target: TableDef | EntityConstructor
391
+ ): Record<string, OpenApiSchema> {
392
+ const columns = getColumnMap(target);
393
+ const properties: Record<string, OpenApiSchema> = {};
394
+
395
+ for (const [key, col] of Object.entries(columns)) {
396
+ properties[key] = columnToFilterSchema(col);
397
+ }
398
+
399
+ return properties;
400
+ }
401
+
402
+ export function createApiComponentsSection(
403
+ schemas: Record<string, OpenApiSchema>,
404
+ parameters?: Record<string, OpenApiParameterObject>,
405
+ responses?: Record<string, OpenApiResponseObject>
406
+ ): OpenApiComponent {
407
+ const component: OpenApiComponent = {};
408
+
409
+ if (Object.keys(schemas).length > 0) {
410
+ component.schemas = schemas;
411
+ }
412
+
413
+ if (parameters && Object.keys(parameters).length > 0) {
414
+ component.parameters = parameters;
415
+ }
416
+
417
+ if (responses && Object.keys(responses).length > 0) {
418
+ component.responses = responses;
419
+ }
420
+
421
+ return component;
422
+ }
423
+
424
+ export function createRef(path: string): ComponentReference {
425
+ return { $ref: `#/components/${path}` };
426
+ }
427
+
428
+ export function schemaToRef(schemaName: string): ComponentReference {
429
+ return createRef(`schemas/${schemaName}`);
430
+ }
431
+
432
+ export function parameterToRef(paramName: string): ComponentReference {
433
+ return createRef(`parameters/${paramName}`);
434
+ }
435
+
436
+ export function responseToRef(responseName: string): ComponentReference {
437
+ return createRef(`responses/${responseName}`);
438
+ }
439
+
440
+ export function canonicalizeSchema(schema: OpenApiSchema): OpenApiSchema {
441
+ if (typeof schema !== 'object' || schema === null) {
442
+ return schema;
443
+ }
444
+
445
+ if (Array.isArray(schema)) {
446
+ return schema.map(canonicalizeSchema) as unknown as OpenApiSchema;
447
+ }
448
+
449
+ const canonical: OpenApiSchema = {};
450
+
451
+ const keys = Object.keys(schema).sort();
452
+
453
+ for (const key of keys) {
454
+ if (key === 'description' || key === 'example') {
455
+ continue;
456
+ }
457
+
458
+ const value = schema[key as keyof OpenApiSchema];
459
+
460
+ if (typeof value === 'object' && value !== null) {
461
+ (canonical as Record<string, unknown>)[key] = canonicalizeSchema(value as OpenApiSchema);
462
+ } else {
463
+ (canonical as Record<string, unknown>)[key] = value;
464
+ }
465
+ }
466
+
467
+ return canonical;
468
+ }
469
+
470
+ export function computeSchemaHash(schema: OpenApiSchema): string {
471
+ const canonical = canonicalizeSchema(schema);
472
+ const json = JSON.stringify(canonical);
473
+ let hash = 0;
474
+
475
+ for (let i = 0; i < json.length; i++) {
476
+ const char = json.charCodeAt(i);
477
+ hash = ((hash << 5) - hash) + char;
478
+ hash = hash & hash;
479
+ }
480
+
481
+ const hex = Math.abs(hash).toString(16);
482
+ return hex.padStart(8, '0').slice(0, 6);
483
+ }
484
+
485
+ interface DeterministicNamingState {
486
+ contentHashToName: Map<string, string>;
487
+ nameToContentHash: Map<string, string>;
488
+ }
489
+
490
+ export function createDeterministicNamingState(): DeterministicNamingState {
491
+ return {
492
+ contentHashToName: new Map(),
493
+ nameToContentHash: new Map(),
494
+ };
495
+ }
496
+
497
+ export function getDeterministicComponentName(
498
+ baseName: string,
499
+ schema: OpenApiSchema,
500
+ state: DeterministicNamingState
501
+ ): string {
502
+ const hash = computeSchemaHash(schema);
503
+ const normalizedBase = baseName.replace(/[^A-Za-z0-9_]/g, '');
504
+
505
+ const existingName = state.contentHashToName.get(hash);
506
+ if (existingName) {
507
+ return existingName;
508
+ }
509
+
510
+ if (!state.nameToContentHash.has(normalizedBase)) {
511
+ state.contentHashToName.set(hash, normalizedBase);
512
+ state.nameToContentHash.set(normalizedBase, hash);
513
+ return normalizedBase;
514
+ }
515
+
516
+ const existingHash = state.nameToContentHash.get(normalizedBase)!;
517
+ if (existingHash === hash) {
518
+ return normalizedBase;
519
+ }
520
+
521
+ const uniqueName = `${normalizedBase}_${hash}`;
522
+ state.contentHashToName.set(hash, uniqueName);
523
+ state.nameToContentHash.set(uniqueName, hash);
524
+
525
+ return uniqueName;
526
+ }
527
+
528
+ export function replaceWithRefs(
529
+ schema: OpenApiSchema,
530
+ schemaMap: Record<string, OpenApiSchema>,
531
+ path: string = 'components/schemas'
532
+ ): OpenApiSchema {
533
+ if (typeof schema === 'object' && schema !== null) {
534
+ if ('$ref' in schema) {
535
+ return schema;
536
+ }
537
+
538
+ const schemaJson = JSON.stringify(schema);
539
+ for (const [name, mapSchema] of Object.entries(schemaMap)) {
540
+ if (JSON.stringify(mapSchema) === schemaJson) {
541
+ return { $ref: `#/${path}/${name}` };
542
+ }
543
+ }
544
+
545
+ if ('type' in schema && schema.type === 'object' && 'properties' in schema) {
546
+ const newProperties: Record<string, OpenApiSchema> = {};
547
+
548
+ for (const [key, value] of Object.entries(schema.properties || {})) {
549
+ newProperties[key] = replaceWithRefs(value as OpenApiSchema, schemaMap, path);
550
+ }
551
+
552
+ return {
553
+ ...schema,
554
+ properties: newProperties,
555
+ };
556
+ }
557
+
558
+ if ('items' in schema && typeof schema.items === 'object') {
559
+ return {
560
+ ...schema,
561
+ items: replaceWithRefs(schema.items, schemaMap, path),
562
+ };
563
+ }
564
+
565
+ if ('allOf' in schema && Array.isArray(schema.allOf)) {
566
+ return {
567
+ ...schema,
568
+ allOf: schema.allOf.map(item => replaceWithRefs(item, schemaMap, path)),
569
+ };
570
+ }
571
+
572
+ if ('oneOf' in schema && Array.isArray(schema.oneOf)) {
573
+ return {
574
+ ...schema,
575
+ oneOf: schema.oneOf.map(item => replaceWithRefs(item, schemaMap, path)),
576
+ };
577
+ }
578
+ }
579
+
580
+ return schema;
581
+ }
582
+
583
+ export function extractReusableSchemas(
584
+ schema: OpenApiSchema,
585
+ existing: Record<string, OpenApiSchema> = {},
586
+ prefix: string = ''
587
+ ): Record<string, OpenApiSchema> {
588
+ if (typeof schema !== 'object' || schema === null) {
589
+ return existing;
590
+ }
591
+
592
+ if ('type' in schema && schema.type === 'object' && 'properties' in schema) {
593
+ for (const [key, value] of Object.entries(schema.properties || {})) {
594
+ extractReusableSchemas(value as OpenApiSchema, existing, `${prefix}${key.charAt(0).toUpperCase() + key.slice(1)}`);
595
+ }
596
+ } else if ('items' in schema && typeof schema.items === 'object') {
597
+ extractReusableSchemas(schema.items as OpenApiSchema, existing, prefix);
598
+ } else if ('allOf' in schema && Array.isArray(schema.allOf)) {
599
+ for (const item of schema.allOf) {
600
+ extractReusableSchemas(item, existing, prefix);
601
+ }
602
+ } else if ('oneOf' in schema && Array.isArray(schema.oneOf)) {
603
+ for (const item of schema.oneOf) {
604
+ extractReusableSchemas(item, existing, prefix);
605
+ }
606
+ }
607
+
608
+ if (!('$ref' in schema)) {
609
+ const name = prefix;
610
+ if (name && 'type' in schema && schema.type === 'object' && 'properties' in schema) {
611
+ if (!(name in existing) && Object.keys(schema.properties || {}).length > 0) {
612
+ existing[name] = { ...schema };
613
+ }
614
+ }
615
+ }
616
+
617
+ return existing;
618
+ }