forked from orval-labs/orval
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray-item-factory.ts
More file actions
386 lines (344 loc) · 10.5 KB
/
Copy patharray-item-factory.ts
File metadata and controls
386 lines (344 loc) · 10.5 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
import {
type ContextSpec,
type GeneratorImport,
getOperationTagKey,
getRefInfo,
isFunction,
isReference,
type OpenApiSchemaObject,
OutputMockType,
OutputMode,
pascal,
resolveRef,
} from '@orval/core';
import {
formatMockFactoryDeclaration,
getMockFactorySignatureParts,
getStrictMockTypeName,
isStrictMock,
} from '../../mock-types';
import type { MockSchema } from '../../types';
import { overrideVarName } from './object';
import { extractItemsRef } from './scalar';
/**
* Scope key for file-level array-item factory dedup. Must match how writers
* group mock output: one bucket per tag file in tags modes, otherwise one
* bucket for the whole target.
*/
export function getArrayItemMockFileScope(
context: ContextSpec,
tags: string[],
): string {
const mode = context.output.mode;
const mockType = context.activeMockOutputType ?? OutputMockType.MSW;
let base: string;
if (mode === OutputMode.TAGS || mode === OutputMode.TAGS_SPLIT) {
base = `tag:${getOperationTagKey({ tags })}`;
} else if (mode === OutputMode.SPLIT) {
base = 'split';
} else {
base = 'single';
}
return `${base}:${mockType}`;
}
function getFileLevelExtractedFactories(
context: ContextSpec,
scope: string,
): Set<string> {
context.arrayItemMockFactories ??= new Map();
const existing = context.arrayItemMockFactories.get(scope);
if (existing) {
return existing;
}
const factories = new Set<string>();
context.arrayItemMockFactories.set(scope, factories);
return factories;
}
/**
* True when any mock generator entry opts into reusable array-item mock
* factories for object-like array item schemas in operation responses.
*/
export function shouldExtractArrayItemFactories(context: ContextSpec): boolean {
return context.output.mock.generators.some(
(g) => !isFunction(g) && g.arrayItems === true,
);
}
/**
* True when `schemas: true` already emits a consolidated factory for this
* `$ref` item under `components/schemas`, so we must not re-export it from
* the operation mock file.
*/
function hasConsolidatedSchemaFactory(
items: MockSchema,
context: ContextSpec,
): boolean {
if (!context.output.schemas) {
return false;
}
const itemsRef = extractItemsRef(items);
if (!itemsRef) {
return false;
}
const { refPaths } = getRefInfo(itemsRef, context);
const isComponentsSchema =
Array.isArray(refPaths) &&
refPaths[0] === 'components' &&
refPaths[1] === 'schemas';
if (!isComponentsSchema) {
return false;
}
return context.output.mock.generators.some(
(g) =>
!isFunction(g) && g.type === OutputMockType.FAKER && g.schemas === true,
);
}
/**
* True when `parentName` looks like a nested property key rather than the
* generated response wrapper type (e.g. `outer` vs `GetTenants200`). Inlining
* avoids factory/type-name collisions and mismatched `<Parent><Prop>Item` aliases.
*/
function isAmbiguousInlineItemContext(
operationId: string,
parentName?: string,
): boolean {
if (!parentName) {
return false;
}
return !parentName.toLowerCase().includes(operationId.toLowerCase());
}
function isNullableArrayItem(schema: OpenApiSchemaObject): boolean {
if (schema.nullable === true) {
return true;
}
return Array.isArray(schema.type) && schema.type.includes('null');
}
function isResolvedSchemaObjectLike(schema: OpenApiSchemaObject): boolean {
if (schema.type === 'object' || schema.properties) {
return true;
}
if (schema.allOf) {
return true;
}
return false;
}
/**
* True when array `items` resolve to an object-like schema worth extracting.
* Conservative: skips scalar refs, oneOf/anyOf, nullable items, and nested
* contexts where generated item type names cannot be inferred reliably.
*/
function shouldExtractArrayItem(
items: MockSchema,
context: ContextSpec,
operationId: string,
parentName?: string,
): boolean {
const itemsRef = extractItemsRef(items);
if (itemsRef) {
try {
const { schema } = resolveRef<OpenApiSchemaObject>(
{ $ref: itemsRef },
context,
);
return isResolvedSchemaObjectLike(schema);
} catch {
return false;
}
}
if (isReference(items)) {
return false;
}
const schema = items as OpenApiSchemaObject;
if (isNullableArrayItem(schema)) {
return false;
}
if (schema.oneOf || schema.anyOf) {
return false;
}
if (schema.allOf) {
return true;
}
if (schema.type === 'object' || schema.properties) {
return !isAmbiguousInlineItemContext(operationId, parentName);
}
return false;
}
/**
* True when `mapValue` is already a bare factory call or a single spread of one.
*/
function isAlreadyFactoryCall(mapValue: string): boolean {
return /^(?:\{\s*\.\.\.\s*get\w+Mock\(\)\s*\}|get\w+Mock\(\))$/.test(
mapValue.trim(),
);
}
interface ArrayItemFactoryNames {
factoryName: string;
typeName: string;
}
/**
* Derive the exported factory and TypeScript type names for an array item.
*/
function getArrayItemFactoryNames({
items,
propertyName,
parentName,
operationId,
context,
}: {
items: MockSchema;
propertyName: string;
parentName?: string;
operationId: string;
context: ContextSpec;
}): ArrayItemFactoryNames | undefined {
if (!shouldExtractArrayItem(items, context, operationId, parentName)) {
return undefined;
}
const itemsRef = extractItemsRef(items);
if (itemsRef) {
const { name } = getRefInfo(itemsRef, context);
const typeName = pascal(name);
return {
factoryName: `get${typeName}Mock`,
typeName,
};
}
const itemSuffix = context.output.override.components.schemas.itemSuffix;
let typeName: string;
if (parentName) {
typeName = `${pascal(parentName)}${pascal(propertyName)}${itemSuffix}`;
} else {
// No `parentName`: the array IS the top-level response schema, and
// `propertyName` here is the response definition string produced by
// `getResReqTypes` (core/getters/res-req-types.ts) rather than a nested
// property key. Two shapes reach this point:
// - inline top-level array responses, where `propertyName` is the
// response type expression with a trailing `[]`; the part before
// `[]` is the element alias core already emitted via
// `createTypeAliasIfNeeded` (core/resolvers/object.ts), when that
// part is a bare identifier;
// - `$ref`'d array schemas (`items` here is the array's resolved,
// non-`$ref` items schema), where `propertyName` is the bare ref
// name and core aliases the array's items as
// `${pascal(refName)}${itemSuffix}` (core/getters/array.ts).
// Nullable top-level arrays reach this branch too: core's scalar getter
// appends a trailing ` | null` to either shape above (e.g.
// `CatalogItems | null` or `GetFoo200Item[] | null`), so that suffix is
// stripped before testing/deriving the type name below. `factoryName`
// still keys off the original, unstripped `propertyName` — outputs on
// the nullable path never compiled before this fix, so factory naming
// there is not a compatibility surface.
// If neither shape holds with certainty, bail (`undefined`) so the call
// site keeps the pre-#3514 inline item body, which is always
// type-correct, instead of referencing a name core never emitted (#3706).
const nullableSuffix = ' | null';
const workingName = propertyName.endsWith(nullableSuffix)
? propertyName.slice(0, -nullableSuffix.length)
: propertyName;
if (workingName.endsWith('[]')) {
const base = workingName.slice(0, -2);
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(base)) {
return undefined;
}
typeName = base;
} else {
const schema = items as OpenApiSchemaObject;
if (schema.allOf && !schema.properties && schema.type !== 'object') {
return undefined;
}
// Defense-in-depth: `workingName` should be a bare ref name here, but
// guard against anything that isn't a valid identifier (e.g. a
// malformed union expression) rather than emitting a phantom type.
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(workingName)) {
return undefined;
}
typeName = `${pascal(workingName)}${itemSuffix}`;
}
}
return {
factoryName: `get${pascal(operationId)}Response${pascal(propertyName)}ItemMock`,
typeName,
};
}
interface ExtractArrayItemMockOptions {
items: MockSchema;
propertyName: string;
parentName?: string;
operationId: string;
tags: string[];
mapValue: string;
context: ContextSpec;
splitMockImplementations: string[];
imports: GeneratorImport[];
}
/**
* When `arrayItems: true`, lift an object-like array item mock body into a
* reusable exported factory and return the call site expression for `.map()`.
*/
export function extractArrayItemMock({
items,
propertyName,
parentName,
operationId,
tags,
mapValue,
context,
splitMockImplementations,
imports,
}: ExtractArrayItemMockOptions): string | undefined {
if (!shouldExtractArrayItemFactories(context)) {
return undefined;
}
if (
!mapValue ||
mapValue === '[]' ||
isAlreadyFactoryCall(mapValue) ||
hasConsolidatedSchemaFactory(items, context)
) {
return undefined;
}
const names = getArrayItemFactoryNames({
items,
propertyName,
parentName,
operationId,
context,
});
if (!names) {
return undefined;
}
const { factoryName, typeName } = names;
const scope = getArrayItemMockFileScope(context, tags);
const fileLevelFactories = getFileLevelExtractedFactories(context, scope);
const mockOptions = context.output.override.mock;
const alreadyExtracted =
fileLevelFactories.has(factoryName) ||
splitMockImplementations.some((f) =>
f.includes(`export const ${factoryName}`),
);
if (!alreadyExtracted) {
const { param, returnType, returnCast } = getMockFactorySignatureParts(
typeName,
mockOptions,
{
isOverridable: true,
overrideType: `Partial<${typeName}>`,
},
);
const spreadPrefix = mapValue.startsWith('...') ? '' : '...';
const func = formatMockFactoryDeclaration(
factoryName,
param,
returnType,
`{${spreadPrefix}${mapValue}, ...${overrideVarName}}`,
returnCast,
{ terminateStatement: true },
);
splitMockImplementations.push(func);
fileLevelFactories.add(factoryName);
}
imports.push({ name: typeName });
const strictCast = isStrictMock(mockOptions)
? ` as ${getStrictMockTypeName(typeName)}`
: '';
return `{...${factoryName}()${strictCast}}`;
}