metal-orm 1.1.10 → 1.1.16

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 (192) hide show
  1. package/README.md +758 -769
  2. package/dist/index.cjs +106 -43
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +5 -5
  5. package/dist/index.d.ts +5 -5
  6. package/dist/index.js +106 -43
  7. package/dist/index.js.map +1 -1
  8. package/package.json +100 -96
  9. package/scripts/generate-entities/render.mjs +21 -12
  10. package/scripts/generate-entities/schema.mjs +209 -195
  11. package/scripts/generate-entities/tree-detection.mjs +159 -153
  12. package/scripts/inflection/pt-br.mjs +468 -468
  13. package/scripts/run-eslint.mjs +33 -34
  14. package/scripts/show-sql-seed.sql +102 -0
  15. package/scripts/show-sql.mjs +321 -325
  16. package/src/bulk/bulk-delete-executor.ts +3 -5
  17. package/src/bulk/bulk-insert-executor.ts +7 -7
  18. package/src/bulk/bulk-update-executor.ts +2 -2
  19. package/src/bulk/bulk-upsert-executor.ts +5 -7
  20. package/src/codegen/naming-strategy.ts +54 -54
  21. package/src/codegen/typescript.ts +482 -482
  22. package/src/core/ast/adapters.ts +1 -1
  23. package/src/core/ast/builders.ts +123 -123
  24. package/src/core/ast/expression-builders.ts +745 -745
  25. package/src/core/ast/expression-nodes.ts +304 -304
  26. package/src/core/ast/expression-visitor.ts +212 -212
  27. package/src/core/ast/expression.ts +20 -20
  28. package/src/core/ast/helpers.ts +14 -14
  29. package/src/core/ast/join.ts +18 -18
  30. package/src/core/ast/query.ts +200 -200
  31. package/src/core/ddl/dialects/base-schema-dialect.ts +1 -1
  32. package/src/core/ddl/dialects/mssql-schema-dialect.ts +1 -1
  33. package/src/core/ddl/dialects/mysql-schema-dialect.ts +1 -1
  34. package/src/core/ddl/dialects/postgres-schema-dialect.ts +1 -1
  35. package/src/core/ddl/dialects/render-reference.test.ts +70 -70
  36. package/src/core/ddl/dialects/sqlite-schema-dialect.ts +1 -1
  37. package/src/core/ddl/introspect/catalogs/index.ts +5 -5
  38. package/src/core/ddl/introspect/catalogs/postgres.ts +146 -146
  39. package/src/core/ddl/introspect/context.ts +15 -15
  40. package/src/core/ddl/introspect/functions/postgres.ts +35 -35
  41. package/src/core/ddl/introspect/mysql.ts +113 -36
  42. package/src/core/ddl/introspect/registry.ts +40 -40
  43. package/src/core/ddl/introspect/run-select.ts +35 -35
  44. package/src/core/ddl/introspect/utils.ts +56 -56
  45. package/src/core/ddl/naming-strategy.ts +16 -16
  46. package/src/core/ddl/schema-dialect.ts +56 -56
  47. package/src/core/ddl/schema-diff.ts +234 -234
  48. package/src/core/ddl/schema-generator.ts +1 -1
  49. package/src/core/ddl/schema-introspect.ts +25 -25
  50. package/src/core/ddl/sql-writing.ts +171 -171
  51. package/src/core/dialect/abstract.ts +541 -541
  52. package/src/core/dialect/base/cte-compiler.ts +33 -33
  53. package/src/core/dialect/base/function-table-formatter.ts +103 -103
  54. package/src/core/dialect/base/groupby-compiler.ts +21 -21
  55. package/src/core/dialect/base/join-compiler.ts +25 -25
  56. package/src/core/dialect/base/orderby-compiler.ts +35 -35
  57. package/src/core/dialect/base/pagination-strategy.ts +32 -32
  58. package/src/core/dialect/base/returning-strategy.ts +57 -57
  59. package/src/core/dialect/base/sql-dialect.ts +294 -294
  60. package/src/core/dialect/dialect-factory.ts +91 -91
  61. package/src/core/dialect/mssql/functions.ts +120 -120
  62. package/src/core/dialect/mssql/index.ts +317 -317
  63. package/src/core/dialect/mysql/functions.ts +103 -103
  64. package/src/core/dialect/mysql/index.ts +105 -105
  65. package/src/core/dialect/postgres/functions.ts +108 -108
  66. package/src/core/dialect/postgres/index.ts +91 -91
  67. package/src/core/dialect/sqlite/functions.ts +129 -129
  68. package/src/core/dialect/sqlite/index.ts +67 -67
  69. package/src/core/driver/database-driver.ts +19 -19
  70. package/src/core/driver/mssql-driver.ts +23 -23
  71. package/src/core/driver/mysql-driver.ts +23 -23
  72. package/src/core/driver/postgres-driver.ts +23 -23
  73. package/src/core/driver/sqlite-driver.ts +23 -23
  74. package/src/core/execution/db-executor.ts +92 -92
  75. package/src/core/execution/executors/better-sqlite3-executor.ts +94 -94
  76. package/src/core/execution/executors/mssql-executor.ts +184 -184
  77. package/src/core/execution/executors/mysql-executor.ts +88 -88
  78. package/src/core/execution/executors/postgres-executor.ts +26 -26
  79. package/src/core/execution/executors/sqlite-executor.ts +42 -42
  80. package/src/core/execution/pooling/pool-types.ts +30 -30
  81. package/src/core/execution/pooling/pool.ts +275 -275
  82. package/src/core/functions/array.ts +35 -35
  83. package/src/core/functions/control-flow.ts +79 -79
  84. package/src/core/functions/datetime.ts +237 -237
  85. package/src/core/functions/json.ts +70 -70
  86. package/src/core/functions/numeric.ts +297 -297
  87. package/src/core/functions/text.ts +334 -334
  88. package/src/core/functions/types.ts +33 -33
  89. package/src/core/hydration/types.ts +51 -51
  90. package/src/core/sql/sql-operator-config.ts +39 -39
  91. package/src/core/sql/sql.ts +152 -152
  92. package/src/decorators/column-decorator.ts +87 -87
  93. package/src/decorators/decorator-metadata.ts +143 -143
  94. package/src/decorators/entity.ts +93 -93
  95. package/src/decorators/index.ts +39 -39
  96. package/src/decorators/relations.ts +231 -231
  97. package/src/decorators/transformers/built-in/string-transformers.ts +231 -231
  98. package/src/decorators/transformers/transformer-decorators.ts +134 -134
  99. package/src/decorators/transformers/transformer-executor.ts +171 -171
  100. package/src/decorators/transformers/transformer-metadata.ts +73 -73
  101. package/src/decorators/validators/built-in/br-cep-validator.ts +55 -55
  102. package/src/decorators/validators/built-in/br-cnpj-validator.ts +105 -105
  103. package/src/decorators/validators/built-in/br-cpf-validator.ts +103 -103
  104. package/src/decorators/validators/country-validator-registry.ts +64 -64
  105. package/src/decorators/validators/country-validators-decorators.ts +203 -203
  106. package/src/decorators/validators/country-validators.ts +105 -105
  107. package/src/decorators/validators/validator-metadata.ts +59 -59
  108. package/src/dto/dto-types.ts +226 -226
  109. package/src/dto/filter-types.ts +141 -141
  110. package/src/dto/index.ts +95 -95
  111. package/src/dto/openapi/generators/base.ts +29 -29
  112. package/src/dto/openapi/generators/column.ts +37 -37
  113. package/src/dto/openapi/generators/dto.ts +91 -91
  114. package/src/dto/openapi/generators/filter.ts +75 -75
  115. package/src/dto/openapi/generators/nested-dto.ts +618 -618
  116. package/src/dto/openapi/generators/pagination.ts +111 -111
  117. package/src/dto/openapi/generators/relation-filter.ts +228 -228
  118. package/src/dto/openapi/index.ts +12 -12
  119. package/src/dto/openapi/types.ts +101 -101
  120. package/src/dto/openapi/utilities.ts +95 -95
  121. package/src/dto/pagination-utils.ts +150 -150
  122. package/src/dto/transform.ts +197 -197
  123. package/src/index.ts +86 -86
  124. package/src/orm/als.ts +58 -58
  125. package/src/orm/domain-event-bus.ts +119 -119
  126. package/src/orm/entity-context.ts +86 -86
  127. package/src/orm/entity-materializer.ts +159 -159
  128. package/src/orm/entity-meta.ts +97 -97
  129. package/src/orm/entity-registry.ts +39 -39
  130. package/src/orm/entity-relation-cache.ts +39 -39
  131. package/src/orm/execute.ts +194 -194
  132. package/src/orm/execution-context.ts +18 -18
  133. package/src/orm/hydration-context.ts +26 -26
  134. package/src/orm/hydration.ts +112 -112
  135. package/src/orm/identity-map.ts +61 -61
  136. package/src/orm/interceptor-pipeline.ts +16 -16
  137. package/src/orm/lazy-batch/belongs-to-many.ts +119 -119
  138. package/src/orm/lazy-batch/belongs-to.ts +108 -108
  139. package/src/orm/lazy-batch/has-many.ts +69 -69
  140. package/src/orm/lazy-batch/has-one.ts +68 -68
  141. package/src/orm/lazy-batch/shared.ts +125 -125
  142. package/src/orm/orm-session.ts +620 -620
  143. package/src/orm/orm.ts +34 -34
  144. package/src/orm/pooled-executor-factory.ts +121 -121
  145. package/src/orm/query-logger.ts +40 -40
  146. package/src/orm/relation-change-processor.ts +420 -420
  147. package/src/orm/relations/belongs-to.ts +143 -143
  148. package/src/orm/relations/has-many.ts +204 -204
  149. package/src/orm/relations/has-one.ts +174 -174
  150. package/src/orm/relations/many-to-many.ts +288 -288
  151. package/src/orm/relations/morph-many.ts +156 -156
  152. package/src/orm/relations/morph-one.ts +151 -151
  153. package/src/orm/relations/morph-to.ts +162 -162
  154. package/src/orm/runtime-types.ts +92 -92
  155. package/src/orm/save-graph.ts +561 -561
  156. package/src/orm/transaction-runner.ts +24 -24
  157. package/src/orm/unit-of-work.ts +426 -426
  158. package/src/query/index.ts +69 -69
  159. package/src/query/target.ts +46 -46
  160. package/src/query-builder/column-selector.ts +81 -81
  161. package/src/query-builder/delete.ts +141 -141
  162. package/src/query-builder/insert-query-state.ts +149 -149
  163. package/src/query-builder/insert.ts +117 -117
  164. package/src/query-builder/query-ast-service.ts +287 -287
  165. package/src/query-builder/query-resolution.ts +78 -78
  166. package/src/query-builder/raw-column-parser.ts +38 -38
  167. package/src/query-builder/relation-filter-utils.ts +153 -153
  168. package/src/query-builder/relation-join-planner.ts +10 -10
  169. package/src/query-builder/relation-manager.ts +87 -87
  170. package/src/query-builder/relation-projection-helper.ts +102 -102
  171. package/src/query-builder/relation-types.ts +9 -9
  172. package/src/query-builder/relation-utils.ts +15 -15
  173. package/src/query-builder/select/cte-facet.ts +40 -40
  174. package/src/query-builder/select/from-facet.ts +80 -80
  175. package/src/query-builder/select/join-facet.ts +62 -62
  176. package/src/query-builder/select/predicate-facet.ts +104 -104
  177. package/src/query-builder/select/projection-facet.ts +70 -70
  178. package/src/query-builder/select/relation-facet.ts +81 -81
  179. package/src/query-builder/select/setop-facet.ts +36 -36
  180. package/src/query-builder/select-helpers.ts +1 -1
  181. package/src/query-builder/select-query-builder-deps.ts +130 -130
  182. package/src/query-builder/select-query-state.ts +207 -207
  183. package/src/query-builder/update.ts +151 -151
  184. package/src/schema/column-types.ts +322 -322
  185. package/src/schema/table-guards.ts +37 -37
  186. package/src/schema/table.ts +281 -281
  187. package/src/tree/index.ts +13 -13
  188. package/src/tree/nested-set-strategy.ts +545 -545
  189. package/src/tree/tree-decorator.ts +397 -397
  190. package/src/tree/tree-manager.ts +754 -754
  191. package/src/tree/tree-query.ts +427 -427
  192. package/src/tree/tree-types.ts +299 -299
@@ -1,618 +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, 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
- }
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
+ }