@orval/mock 7.11.2 → 7.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1165 +1,830 @@
1
- "use strict";
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
8
  var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
17
  };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- DEFAULT_MOCK_OPTIONS: () => DEFAULT_MOCK_OPTIONS,
24
- generateMock: () => generateMock,
25
- generateMockImports: () => generateMockImports
26
- });
27
- module.exports = __toCommonJS(index_exports);
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
28
22
 
29
- // src/msw/index.ts
30
- var import_core8 = require("@orval/core");
23
+ //#endregion
24
+ let __orval_core = require("@orval/core");
25
+ __orval_core = __toESM(__orval_core);
26
+ require("openapi3-ts/oas30");
31
27
 
32
- // src/delay.ts
33
- var getDelay = (override, options) => {
34
- var _a, _b, _c, _d;
35
- const overrideDelay = ((_a = override == null ? void 0 : override.mock) == null ? void 0 : _a.delay) !== void 0 ? (_b = override == null ? void 0 : override.mock) == null ? void 0 : _b.delay : options == null ? void 0 : options.delay;
36
- const delayFunctionLazyExecute = (_d = (_c = override == null ? void 0 : override.mock) == null ? void 0 : _c.delayFunctionLazyExecute) != null ? _d : options == null ? void 0 : options.delayFunctionLazyExecute;
37
- switch (typeof overrideDelay) {
38
- case "function":
39
- return delayFunctionLazyExecute ? overrideDelay : overrideDelay();
40
- case "number":
41
- case "boolean":
42
- return overrideDelay;
43
- default:
44
- return 1e3;
45
- }
28
+ //#region src/delay.ts
29
+ const getDelay = (override, options) => {
30
+ const overrideDelay = override?.mock?.delay === void 0 ? options?.delay : override?.mock?.delay;
31
+ const delayFunctionLazyExecute = override?.mock?.delayFunctionLazyExecute ?? options?.delayFunctionLazyExecute;
32
+ switch (typeof overrideDelay) {
33
+ case "function": return delayFunctionLazyExecute ? overrideDelay : overrideDelay();
34
+ case "number":
35
+ case "boolean": return overrideDelay;
36
+ default: return 1e3;
37
+ }
46
38
  };
47
39
 
48
- // src/faker/getters/combine.ts
49
- var import_core5 = require("@orval/core");
50
-
51
- // src/faker/resolvers/value.ts
52
- var import_core4 = require("@orval/core");
53
-
54
- // src/faker/getters/scalar.ts
55
- var import_core3 = require("@orval/core");
40
+ //#endregion
41
+ //#region src/faker/compatibleV9.ts
42
+ const getFakerPackageVersion = (packageJson) => {
43
+ return packageJson.dependencies?.["@faker-js/faker"] ?? packageJson.devDependencies?.["@faker-js/faker"] ?? packageJson.peerDependencies?.["@faker-js/faker"];
44
+ };
45
+ const isFakerVersionV9 = (packageJson) => {
46
+ const version = getFakerPackageVersion(packageJson);
47
+ if (!version) return false;
48
+ const withoutRc = version.split("-")[0];
49
+ return (0, __orval_core.compareVersions)(withoutRc, "9.0.0");
50
+ };
56
51
 
57
- // src/faker/constants.ts
58
- var DEFAULT_FORMAT_MOCK = {
59
- bic: "faker.finance.bic()",
60
- binary: "new Blob(faker.helpers.arrayElements(faker.word.words(10).split(' ')))",
61
- city: "faker.location.city()",
62
- country: "faker.location.country()",
63
- date: "faker.date.past().toISOString().split('T')[0]",
64
- "date-time": "`${faker.date.past().toISOString().split('.')[0]}Z`",
65
- email: "faker.internet.email()",
66
- firstName: "faker.person.firstName()",
67
- gender: "faker.person.gender()",
68
- iban: "faker.finance.iban()",
69
- ipv4: "faker.internet.ipv4()",
70
- ipv6: "faker.internet.ipv6()",
71
- jobTitle: "faker.person.jobTitle()",
72
- lastName: "faker.person.lastName()",
73
- password: "faker.internet.password()",
74
- phoneNumber: "faker.phone.number()",
75
- streetName: "faker.location.street()",
76
- uri: "faker.internet.url()",
77
- url: "faker.internet.url()",
78
- userName: "faker.internet.userName()",
79
- uuid: "faker.string.uuid()",
80
- zipCode: "faker.location.zipCode()"
52
+ //#endregion
53
+ //#region src/faker/constants.ts
54
+ const DEFAULT_FORMAT_MOCK = {
55
+ bic: "faker.finance.bic()",
56
+ binary: "new Blob(faker.helpers.arrayElements(faker.word.words(10).split(' ')))",
57
+ city: "faker.location.city()",
58
+ country: "faker.location.country()",
59
+ date: "faker.date.past().toISOString().split('T')[0]",
60
+ "date-time": "`${faker.date.past().toISOString().split('.')[0]}Z`",
61
+ email: "faker.internet.email()",
62
+ firstName: "faker.person.firstName()",
63
+ gender: "faker.person.gender()",
64
+ iban: "faker.finance.iban()",
65
+ ipv4: "faker.internet.ipv4()",
66
+ ipv6: "faker.internet.ipv6()",
67
+ jobTitle: "faker.person.jobTitle()",
68
+ lastName: "faker.person.lastName()",
69
+ password: "faker.internet.password()",
70
+ phoneNumber: "faker.phone.number()",
71
+ streetName: "faker.location.street()",
72
+ uri: "faker.internet.url()",
73
+ url: "faker.internet.url()",
74
+ userName: "faker.internet.userName()",
75
+ uuid: "faker.string.uuid()",
76
+ zipCode: "faker.location.zipCode()"
81
77
  };
82
- var DEFAULT_OBJECT_KEY_MOCK = "faker.string.alphanumeric(5)";
78
+ const DEFAULT_OBJECT_KEY_MOCK = "faker.string.alphanumeric(5)";
83
79
 
84
- // src/faker/getters/object.ts
85
- var import_core = require("@orval/core");
86
- var overrideVarName = "overrideResponse";
87
- var getMockObject = ({
88
- item,
89
- mockOptions,
90
- operationId,
91
- tags,
92
- combine,
93
- context,
94
- imports,
95
- existingReferencedProperties,
96
- splitMockImplementations,
97
- allowOverride = false
98
- }) => {
99
- if ((0, import_core.isReference)(item)) {
100
- return resolveMockValue({
101
- schema: {
102
- ...item,
103
- name: item.name,
104
- path: item.path ? `${item.path}.${item.name}` : item.name
105
- },
106
- mockOptions,
107
- operationId,
108
- tags,
109
- context,
110
- imports,
111
- existingReferencedProperties,
112
- splitMockImplementations
113
- });
114
- }
115
- if (item.allOf || item.oneOf || item.anyOf) {
116
- const separator = item.allOf ? "allOf" : item.oneOf ? "oneOf" : "anyOf";
117
- return combineSchemasMock({
118
- item,
119
- separator,
120
- mockOptions,
121
- operationId,
122
- tags,
123
- combine,
124
- context,
125
- imports,
126
- existingReferencedProperties,
127
- splitMockImplementations
128
- });
129
- }
130
- if (Array.isArray(item.type)) {
131
- return combineSchemasMock({
132
- item: {
133
- anyOf: item.type.map((type) => ({ type })),
134
- name: item.name
135
- },
136
- separator: "anyOf",
137
- mockOptions,
138
- operationId,
139
- tags,
140
- combine,
141
- context,
142
- imports,
143
- existingReferencedProperties,
144
- splitMockImplementations
145
- });
146
- }
147
- if (item.properties) {
148
- let value = !combine || (combine == null ? void 0 : combine.separator) === "oneOf" || (combine == null ? void 0 : combine.separator) === "anyOf" ? "{" : "";
149
- const imports2 = [];
150
- const includedProperties = [];
151
- const entries = Object.entries(item.properties);
152
- if (context.output.propertySortOrder === import_core.PropertySortOrder.ALPHABETICAL) {
153
- entries.sort((a, b) => {
154
- return a[0].localeCompare(b[0]);
155
- });
156
- }
157
- const properyScalars = entries.map(([key, prop]) => {
158
- if (combine == null ? void 0 : combine.includedProperties.includes(key)) {
159
- return void 0;
160
- }
161
- const isRequired = (mockOptions == null ? void 0 : mockOptions.required) || (Array.isArray(item.required) ? item.required : []).includes(key);
162
- if ("$ref" in prop && existingReferencedProperties.includes(
163
- (0, import_core.pascal)(prop.$ref.split("/").pop())
164
- )) {
165
- return void 0;
166
- }
167
- const resolvedValue = resolveMockValue({
168
- schema: {
169
- ...prop,
170
- name: key,
171
- path: item.path ? `${item.path}.${key}` : `#.${key}`
172
- },
173
- mockOptions,
174
- operationId,
175
- tags,
176
- context,
177
- imports: imports2,
178
- existingReferencedProperties,
179
- splitMockImplementations
180
- });
181
- imports2.push(...resolvedValue.imports);
182
- includedProperties.push(key);
183
- const keyDefinition = (0, import_core.getKey)(key);
184
- if (!isRequired && !resolvedValue.overrided) {
185
- return `${keyDefinition}: faker.helpers.arrayElement([${resolvedValue.value}, undefined])`;
186
- }
187
- return `${keyDefinition}: ${resolvedValue.value}`;
188
- }).filter(Boolean);
189
- if (allowOverride) {
190
- properyScalars.push(`...${overrideVarName}`);
191
- }
192
- value += properyScalars.join(", ");
193
- value += !combine || (combine == null ? void 0 : combine.separator) === "oneOf" || (combine == null ? void 0 : combine.separator) === "anyOf" ? "}" : "";
194
- return {
195
- value,
196
- imports: imports2,
197
- name: item.name,
198
- includedProperties
199
- };
200
- }
201
- if (item.additionalProperties) {
202
- if ((0, import_core.isBoolean)(item.additionalProperties)) {
203
- return { value: `{}`, imports: [], name: item.name };
204
- }
205
- if ((0, import_core.isReference)(item.additionalProperties) && existingReferencedProperties.includes(
206
- item.additionalProperties.$ref.split("/").pop()
207
- )) {
208
- return { value: `{}`, imports: [], name: item.name };
209
- }
210
- const resolvedValue = resolveMockValue({
211
- schema: {
212
- ...item.additionalProperties,
213
- name: item.name,
214
- path: item.path ? `${item.path}.#` : "#"
215
- },
216
- mockOptions,
217
- operationId,
218
- tags,
219
- context,
220
- imports,
221
- existingReferencedProperties,
222
- splitMockImplementations
223
- });
224
- return {
225
- ...resolvedValue,
226
- value: `{
80
+ //#endregion
81
+ //#region src/faker/getters/object.ts
82
+ const overrideVarName = "overrideResponse";
83
+ const getMockObject = ({ item, mockOptions, operationId, tags, combine, context, imports, existingReferencedProperties, splitMockImplementations, allowOverride = false }) => {
84
+ if ((0, __orval_core.isReference)(item)) return resolveMockValue({
85
+ schema: {
86
+ ...item,
87
+ name: item.name,
88
+ path: item.path ? `${item.path}.${item.name}` : item.name
89
+ },
90
+ mockOptions,
91
+ operationId,
92
+ tags,
93
+ context,
94
+ imports,
95
+ existingReferencedProperties,
96
+ splitMockImplementations
97
+ });
98
+ if (item.allOf || item.oneOf || item.anyOf) {
99
+ const separator = item.allOf ? "allOf" : item.oneOf ? "oneOf" : "anyOf";
100
+ return combineSchemasMock({
101
+ item,
102
+ separator,
103
+ mockOptions,
104
+ operationId,
105
+ tags,
106
+ combine,
107
+ context,
108
+ imports,
109
+ existingReferencedProperties,
110
+ splitMockImplementations
111
+ });
112
+ }
113
+ if (Array.isArray(item.type)) return combineSchemasMock({
114
+ item: {
115
+ anyOf: item.type.map((type) => ({ type })),
116
+ name: item.name
117
+ },
118
+ separator: "anyOf",
119
+ mockOptions,
120
+ operationId,
121
+ tags,
122
+ combine,
123
+ context,
124
+ imports,
125
+ existingReferencedProperties,
126
+ splitMockImplementations
127
+ });
128
+ if (item.properties) {
129
+ let value = !combine || combine?.separator === "oneOf" || combine?.separator === "anyOf" ? "{" : "";
130
+ const imports$1 = [];
131
+ const includedProperties = [];
132
+ const entries = Object.entries(item.properties);
133
+ if (context.output.propertySortOrder === __orval_core.PropertySortOrder.ALPHABETICAL) entries.sort((a, b) => {
134
+ return a[0].localeCompare(b[0]);
135
+ });
136
+ const properyScalars = entries.map(([key, prop]) => {
137
+ if (combine?.includedProperties.includes(key)) return;
138
+ const isRequired = mockOptions?.required || (Array.isArray(item.required) ? item.required : []).includes(key);
139
+ if ("$ref" in prop && existingReferencedProperties.includes((0, __orval_core.pascal)(prop.$ref.split("/").pop()))) return;
140
+ const resolvedValue = resolveMockValue({
141
+ schema: {
142
+ ...prop,
143
+ name: key,
144
+ path: item.path ? `${item.path}.${key}` : `#.${key}`
145
+ },
146
+ mockOptions,
147
+ operationId,
148
+ tags,
149
+ context,
150
+ imports: imports$1,
151
+ existingReferencedProperties,
152
+ splitMockImplementations
153
+ });
154
+ imports$1.push(...resolvedValue.imports);
155
+ includedProperties.push(key);
156
+ const keyDefinition = (0, __orval_core.getKey)(key);
157
+ if (!isRequired && !resolvedValue.overrided) return `${keyDefinition}: faker.helpers.arrayElement([${resolvedValue.value}, undefined])`;
158
+ return `${keyDefinition}: ${resolvedValue.value}`;
159
+ }).filter(Boolean);
160
+ if (allowOverride) properyScalars.push(`...${overrideVarName}`);
161
+ value += properyScalars.join(", ");
162
+ value += !combine || combine?.separator === "oneOf" || combine?.separator === "anyOf" ? "}" : "";
163
+ return {
164
+ value,
165
+ imports: imports$1,
166
+ name: item.name,
167
+ includedProperties
168
+ };
169
+ }
170
+ if (item.additionalProperties) {
171
+ if ((0, __orval_core.isBoolean)(item.additionalProperties)) return {
172
+ value: `{}`,
173
+ imports: [],
174
+ name: item.name
175
+ };
176
+ if ((0, __orval_core.isReference)(item.additionalProperties) && existingReferencedProperties.includes(item.additionalProperties.$ref.split("/").pop())) return {
177
+ value: `{}`,
178
+ imports: [],
179
+ name: item.name
180
+ };
181
+ const resolvedValue = resolveMockValue({
182
+ schema: {
183
+ ...item.additionalProperties,
184
+ name: item.name,
185
+ path: item.path ? `${item.path}.#` : "#"
186
+ },
187
+ mockOptions,
188
+ operationId,
189
+ tags,
190
+ context,
191
+ imports,
192
+ existingReferencedProperties,
193
+ splitMockImplementations
194
+ });
195
+ return {
196
+ ...resolvedValue,
197
+ value: `{
227
198
  [${DEFAULT_OBJECT_KEY_MOCK}]: ${resolvedValue.value}
228
199
  }`
229
- };
230
- }
231
- return { value: "{}", imports: [], name: item.name };
200
+ };
201
+ }
202
+ return {
203
+ value: "{}",
204
+ imports: [],
205
+ name: item.name
206
+ };
232
207
  };
233
208
 
234
- // src/faker/compatibleV9.ts
235
- var import_core2 = require("@orval/core");
236
- var getFakerPackageVersion = (packageJson) => {
237
- var _a, _b, _c, _d, _e;
238
- return (_e = (_c = (_a = packageJson.dependencies) == null ? void 0 : _a["@faker-js/faker"]) != null ? _c : (_b = packageJson.devDependencies) == null ? void 0 : _b["@faker-js/faker"]) != null ? _e : (_d = packageJson.peerDependencies) == null ? void 0 : _d["@faker-js/faker"];
239
- };
240
- var isFakerVersionV9 = (packageJson) => {
241
- const version = getFakerPackageVersion(packageJson);
242
- if (!version) {
243
- return false;
244
- }
245
- const withoutRc = version.split("-")[0];
246
- return (0, import_core2.compareVersions)(withoutRc, "9.0.0");
247
- };
248
-
249
- // src/faker/getters/scalar.ts
250
- var getMockScalar = ({
251
- item,
252
- imports,
253
- mockOptions,
254
- operationId,
255
- tags,
256
- combine,
257
- context,
258
- existingReferencedProperties,
259
- splitMockImplementations,
260
- allowOverride = false
261
- }) => {
262
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
263
- if (item.isRef) {
264
- existingReferencedProperties = [...existingReferencedProperties, item.name];
265
- }
266
- const operationProperty = resolveMockOverride(
267
- (_b = (_a = mockOptions == null ? void 0 : mockOptions.operations) == null ? void 0 : _a[operationId]) == null ? void 0 : _b.properties,
268
- item
269
- );
270
- if (operationProperty) {
271
- return operationProperty;
272
- }
273
- const overrideTag = Object.entries((_c = mockOptions == null ? void 0 : mockOptions.tags) != null ? _c : {}).sort((a, b) => {
274
- return a[0].localeCompare(b[0]);
275
- }).reduce(
276
- (acc, [tag, options]) => tags.includes(tag) ? (0, import_core3.mergeDeep)(acc, options) : acc,
277
- {}
278
- );
279
- const tagProperty = resolveMockOverride(overrideTag == null ? void 0 : overrideTag.properties, item);
280
- if (tagProperty) {
281
- return tagProperty;
282
- }
283
- const property = resolveMockOverride(mockOptions == null ? void 0 : mockOptions.properties, item);
284
- if (property) {
285
- return property;
286
- }
287
- if ((((_e = (_d = context.output.override) == null ? void 0 : _d.mock) == null ? void 0 : _e.useExamples) || (mockOptions == null ? void 0 : mockOptions.useExamples)) && item.example !== void 0) {
288
- return {
289
- value: JSON.stringify(item.example),
290
- imports: [],
291
- name: item.name,
292
- overrided: true
293
- };
294
- }
295
- const ALL_FORMAT = {
296
- ...DEFAULT_FORMAT_MOCK,
297
- ...(_f = mockOptions == null ? void 0 : mockOptions.format) != null ? _f : {}
298
- };
299
- if (item.format && ALL_FORMAT[item.format]) {
300
- let value = ALL_FORMAT[item.format];
301
- const dateFormats = ["date", "date-time"];
302
- if (dateFormats.includes(item.format) && context.output.override.useDates) {
303
- value = `new Date(${value})`;
304
- }
305
- return {
306
- value: getNullable(value, item.nullable),
307
- imports: [],
308
- name: item.name,
309
- overrided: false
310
- };
311
- }
312
- const type = getItemType(item);
313
- const isFakerV9 = !!context.output.packageJson && isFakerVersionV9(context.output.packageJson);
314
- switch (type) {
315
- case "number":
316
- case "integer": {
317
- const intFunction = item.format === "int64" && context.output.override.useBigInt ? "bigInt" : "int";
318
- let value = getNullable(
319
- `faker.number.${intFunction}({min: ${(_g = item.minimum) != null ? _g : mockOptions == null ? void 0 : mockOptions.numberMin}, max: ${(_h = item.maximum) != null ? _h : mockOptions == null ? void 0 : mockOptions.numberMax}${isFakerV9 ? `, multipleOf: ${item.multipleOf}` : ""}})`,
320
- item.nullable
321
- );
322
- if (type === "number") {
323
- value = getNullable(
324
- `faker.number.float({min: ${(_i = item.minimum) != null ? _i : mockOptions == null ? void 0 : mockOptions.numberMin}, max: ${(_j = item.maximum) != null ? _j : mockOptions == null ? void 0 : mockOptions.numberMax}, ${item.multipleOf ? `multipleOf: ${item.multipleOf}` : `fractionDigits: ${mockOptions == null ? void 0 : mockOptions.fractionDigits}`}})`,
325
- item.nullable
326
- );
327
- }
328
- const numberImports = [];
329
- if (item.enum) {
330
- value = getEnum(
331
- item,
332
- numberImports,
333
- context,
334
- existingReferencedProperties,
335
- "number"
336
- );
337
- } else if ("const" in item) {
338
- value = "" + item.const;
339
- }
340
- return {
341
- value,
342
- enums: item.enum,
343
- imports: numberImports,
344
- name: item.name
345
- };
346
- }
347
- case "boolean": {
348
- let value = "faker.datatype.boolean()";
349
- if ("const" in item) {
350
- value = "" + item.const;
351
- }
352
- return {
353
- value,
354
- imports: [],
355
- name: item.name
356
- };
357
- }
358
- case "array": {
359
- if (!item.items) {
360
- return { value: "[]", imports: [], name: item.name };
361
- }
362
- if ("$ref" in item.items && existingReferencedProperties.includes(
363
- (0, import_core3.pascal)(item.items.$ref.split("/").pop())
364
- )) {
365
- return { value: "[]", imports: [], name: item.name };
366
- }
367
- const {
368
- value,
369
- enums,
370
- imports: resolvedImports
371
- } = resolveMockValue({
372
- schema: {
373
- ...item.items,
374
- name: item.name,
375
- path: item.path ? `${item.path}.[]` : "#.[]"
376
- },
377
- combine,
378
- mockOptions,
379
- operationId,
380
- tags,
381
- context,
382
- imports,
383
- existingReferencedProperties,
384
- splitMockImplementations
385
- });
386
- if (enums) {
387
- return {
388
- value,
389
- imports: resolvedImports,
390
- name: item.name
391
- };
392
- }
393
- let mapValue = value;
394
- if (combine && !value.startsWith("faker") && !value.startsWith("{")) {
395
- mapValue = `{${value}}`;
396
- }
397
- return {
398
- value: `Array.from({ length: faker.number.int({ min: ${(_k = item.minItems) != null ? _k : mockOptions == null ? void 0 : mockOptions.arrayMin}, max: ${(_l = item.maxItems) != null ? _l : mockOptions == null ? void 0 : mockOptions.arrayMax} }) }, (_, i) => i + 1).map(() => (${mapValue}))`,
399
- imports: resolvedImports,
400
- name: item.name
401
- };
402
- }
403
- case "string": {
404
- const length = `{length: {min: ${(_m = item.minLength) != null ? _m : mockOptions == null ? void 0 : mockOptions.stringMin}, max: ${(_n = item.maxLength) != null ? _n : mockOptions == null ? void 0 : mockOptions.stringMax}}}`;
405
- let value = `faker.string.alpha(${length})`;
406
- const stringImports = [];
407
- if (item.enum) {
408
- value = getEnum(
409
- item,
410
- stringImports,
411
- context,
412
- existingReferencedProperties,
413
- "string"
414
- );
415
- } else if (item.pattern) {
416
- value = `faker.helpers.fromRegExp('${item.pattern}')`;
417
- } else if ("const" in item) {
418
- value = `'${item.const}'`;
419
- }
420
- return {
421
- value: getNullable(value, item.nullable),
422
- enums: item.enum,
423
- name: item.name,
424
- imports: stringImports
425
- };
426
- }
427
- case "null":
428
- return {
429
- value: "null",
430
- imports: [],
431
- name: item.name
432
- };
433
- default: {
434
- if (item.enum) {
435
- const enumImports = [];
436
- const value = getEnum(
437
- item,
438
- enumImports,
439
- context,
440
- existingReferencedProperties,
441
- void 0
442
- );
443
- return {
444
- value,
445
- enums: item.enum,
446
- imports: enumImports,
447
- name: item.name
448
- };
449
- }
450
- return getMockObject({
451
- item,
452
- mockOptions,
453
- operationId,
454
- tags,
455
- combine: combine ? {
456
- separator: combine.separator,
457
- includedProperties: []
458
- } : void 0,
459
- context,
460
- imports,
461
- existingReferencedProperties,
462
- splitMockImplementations,
463
- allowOverride
464
- });
465
- }
466
- }
209
+ //#endregion
210
+ //#region src/faker/getters/scalar.ts
211
+ const getMockScalar = ({ item, imports, mockOptions, operationId, tags, combine, context, existingReferencedProperties, splitMockImplementations, allowOverride = false }) => {
212
+ if (item.isRef) existingReferencedProperties = [...existingReferencedProperties, item.name];
213
+ const operationProperty = resolveMockOverride(mockOptions?.operations?.[operationId]?.properties, item);
214
+ if (operationProperty) return operationProperty;
215
+ const overrideTag = Object.entries(mockOptions?.tags ?? {}).sort((a, b) => {
216
+ return a[0].localeCompare(b[0]);
217
+ }).reduce((acc, [tag, options]) => tags.includes(tag) ? (0, __orval_core.mergeDeep)(acc, options) : acc, {});
218
+ const tagProperty = resolveMockOverride(overrideTag?.properties, item);
219
+ if (tagProperty) return tagProperty;
220
+ const property = resolveMockOverride(mockOptions?.properties, item);
221
+ if (property) return property;
222
+ if ((context.output.override?.mock?.useExamples || mockOptions?.useExamples) && item.example !== void 0) return {
223
+ value: JSON.stringify(item.example),
224
+ imports: [],
225
+ name: item.name,
226
+ overrided: true
227
+ };
228
+ const ALL_FORMAT = {
229
+ ...DEFAULT_FORMAT_MOCK,
230
+ ...mockOptions?.format
231
+ };
232
+ if (item.format && ALL_FORMAT[item.format]) {
233
+ let value = ALL_FORMAT[item.format];
234
+ if (["date", "date-time"].includes(item.format) && context.output.override.useDates) value = `new Date(${value})`;
235
+ return {
236
+ value: getNullable(value, item.nullable),
237
+ imports: [],
238
+ name: item.name,
239
+ overrided: false
240
+ };
241
+ }
242
+ const type = getItemType(item);
243
+ const isFakerV9 = !!context.output.packageJson && isFakerVersionV9(context.output.packageJson);
244
+ switch (type) {
245
+ case "number":
246
+ case "integer": {
247
+ const intFunction = context.output.override.useBigInt && (item.format === "int64" || item.format === "uint64") ? "bigInt" : "int";
248
+ let value = getNullable(`faker.number.${intFunction}({min: ${item.minimum ?? mockOptions?.numberMin}, max: ${item.maximum ?? mockOptions?.numberMax}${isFakerV9 && item.multipleOf !== void 0 ? `, multipleOf: ${item.multipleOf}` : ""}})`, item.nullable);
249
+ if (type === "number") value = getNullable(`faker.number.float({min: ${item.minimum ?? mockOptions?.numberMin}, max: ${item.maximum ?? mockOptions?.numberMax}${isFakerV9 && item.multipleOf !== void 0 ? `, multipleOf: ${item.multipleOf}` : `, fractionDigits: ${mockOptions?.fractionDigits}`}})`, item.nullable);
250
+ const numberImports = [];
251
+ if (item.enum) value = getEnum(item, numberImports, context, existingReferencedProperties, "number");
252
+ else if ("const" in item) value = "" + item.const;
253
+ return {
254
+ value,
255
+ enums: item.enum,
256
+ imports: numberImports,
257
+ name: item.name
258
+ };
259
+ }
260
+ case "boolean": {
261
+ let value = "faker.datatype.boolean()";
262
+ if ("const" in item) value = "" + item.const;
263
+ return {
264
+ value,
265
+ imports: [],
266
+ name: item.name
267
+ };
268
+ }
269
+ case "array": {
270
+ if (!item.items) return {
271
+ value: "[]",
272
+ imports: [],
273
+ name: item.name
274
+ };
275
+ if ("$ref" in item.items && existingReferencedProperties.includes((0, __orval_core.pascal)(item.items.$ref.split("/").pop()))) return {
276
+ value: "[]",
277
+ imports: [],
278
+ name: item.name
279
+ };
280
+ const { value, enums, imports: resolvedImports } = resolveMockValue({
281
+ schema: {
282
+ ...item.items,
283
+ name: item.name,
284
+ path: item.path ? `${item.path}.[]` : "#.[]"
285
+ },
286
+ combine,
287
+ mockOptions,
288
+ operationId,
289
+ tags,
290
+ context,
291
+ imports,
292
+ existingReferencedProperties,
293
+ splitMockImplementations
294
+ });
295
+ if (enums) return {
296
+ value,
297
+ imports: resolvedImports,
298
+ name: item.name
299
+ };
300
+ let mapValue = value;
301
+ if (combine && !value.startsWith("faker") && !value.startsWith("{") && !value.startsWith("Array.from")) mapValue = `{${value}}`;
302
+ return {
303
+ value: `Array.from({ length: faker.number.int({ min: ${item.minItems ?? mockOptions?.arrayMin}, max: ${item.maxItems ?? mockOptions?.arrayMax} }) }, (_, i) => i + 1).map(() => (${mapValue}))`,
304
+ imports: resolvedImports,
305
+ name: item.name
306
+ };
307
+ }
308
+ case "string": {
309
+ let value = `faker.string.alpha(${`{length: {min: ${item.minLength ?? mockOptions?.stringMin}, max: ${item.maxLength ?? mockOptions?.stringMax}}}`})`;
310
+ const stringImports = [];
311
+ if (item.enum) value = getEnum(item, stringImports, context, existingReferencedProperties, "string");
312
+ else if (item.pattern) value = `faker.helpers.fromRegExp('${item.pattern}')`;
313
+ else if ("const" in item) value = `'${item.const}'`;
314
+ return {
315
+ value: getNullable(value, item.nullable),
316
+ enums: item.enum,
317
+ name: item.name,
318
+ imports: stringImports
319
+ };
320
+ }
321
+ case "null": return {
322
+ value: "null",
323
+ imports: [],
324
+ name: item.name
325
+ };
326
+ default:
327
+ if (item.enum) {
328
+ const enumImports = [];
329
+ return {
330
+ value: getEnum(item, enumImports, context, existingReferencedProperties),
331
+ enums: item.enum,
332
+ imports: enumImports,
333
+ name: item.name
334
+ };
335
+ }
336
+ return getMockObject({
337
+ item,
338
+ mockOptions,
339
+ operationId,
340
+ tags,
341
+ combine: combine ? {
342
+ separator: combine.separator,
343
+ includedProperties: []
344
+ } : void 0,
345
+ context,
346
+ imports,
347
+ existingReferencedProperties,
348
+ splitMockImplementations,
349
+ allowOverride
350
+ });
351
+ }
467
352
  };
468
353
  function getItemType(item) {
469
- if (item.type) return item.type;
470
- if (!item.enum) return;
471
- const uniqTypes = new Set(item.enum.map((value) => typeof value));
472
- if (uniqTypes.size > 1) return;
473
- const type = Array.from(uniqTypes.values()).at(0);
474
- if (!type) return;
475
- return ["string", "number"].includes(type) ? type : void 0;
354
+ if (item.type) return item.type;
355
+ if (!item.enum) return;
356
+ const uniqTypes = new Set(item.enum.map((value) => typeof value));
357
+ if (uniqTypes.size > 1) return;
358
+ const type = [...uniqTypes.values()].at(0);
359
+ if (!type) return;
360
+ return ["string", "number"].includes(type) ? type : void 0;
476
361
  }
477
- var getEnum = (item, imports, context, existingReferencedProperties, type) => {
478
- var _a, _b;
479
- if (!item.enum) return "";
480
- const joindEnumValues = item.enum.filter((e) => e !== null).map(
481
- (e) => type === "string" || type === void 0 && typeof e === "string" ? `'${(0, import_core3.escape)(e)}'` : e
482
- ).join(",");
483
- let enumValue = `[${joindEnumValues}]`;
484
- if (context.output.override.enumGenerationType === import_core3.EnumGeneration.ENUM) {
485
- if (item.isRef || existingReferencedProperties.length === 0) {
486
- enumValue += ` as ${item.name}${item.name.endsWith("[]") ? "" : "[]"}`;
487
- imports.push({
488
- name: item.name,
489
- ...!(0, import_core3.isRootKey)(context.specKey, context.target) ? { specKey: context.specKey } : {}
490
- });
491
- } else {
492
- enumValue += ` as ${existingReferencedProperties[existingReferencedProperties.length - 1]}['${item.name}']`;
493
- if (!((_a = item.path) == null ? void 0 : _a.endsWith("[]"))) enumValue += "[]";
494
- imports.push({
495
- name: existingReferencedProperties[existingReferencedProperties.length - 1],
496
- ...!(0, import_core3.isRootKey)(context.specKey, context.target) ? { specKey: context.specKey } : {}
497
- });
498
- }
499
- } else {
500
- enumValue += " as const";
501
- }
502
- if (item.isRef && type === "string") {
503
- enumValue = `Object.values(${item.name})`;
504
- imports.push({
505
- name: item.name,
506
- values: true,
507
- ...!(0, import_core3.isRootKey)(context.specKey, context.target) ? { specKey: context.specKey } : {}
508
- });
509
- }
510
- return ((_b = item.path) == null ? void 0 : _b.endsWith("[]")) ? `faker.helpers.arrayElements(${enumValue})` : `faker.helpers.arrayElement(${enumValue})`;
362
+ const getEnum = (item, imports, context, existingReferencedProperties, type) => {
363
+ if (!item.enum) return "";
364
+ let enumValue = `[${item.enum.filter((e) => e !== null).map((e) => type === "string" || type === void 0 && typeof e === "string" ? `'${(0, __orval_core.escape)(e)}'` : e).join(",")}]`;
365
+ if (context.output.override.enumGenerationType === __orval_core.EnumGeneration.ENUM) if (item.isRef || existingReferencedProperties.length === 0) {
366
+ enumValue += ` as ${item.name}${item.name.endsWith("[]") ? "" : "[]"}`;
367
+ imports.push({
368
+ name: item.name,
369
+ ...(0, __orval_core.isRootKey)(context.specKey, context.target) ? {} : { specKey: context.specKey }
370
+ });
371
+ } else {
372
+ enumValue += ` as ${existingReferencedProperties[existingReferencedProperties.length - 1]}['${item.name}']`;
373
+ if (!item.path?.endsWith("[]")) enumValue += "[]";
374
+ imports.push({
375
+ name: existingReferencedProperties[existingReferencedProperties.length - 1],
376
+ ...(0, __orval_core.isRootKey)(context.specKey, context.target) ? {} : { specKey: context.specKey }
377
+ });
378
+ }
379
+ else enumValue += " as const";
380
+ if (item.isRef && type === "string") {
381
+ enumValue = `Object.values(${item.name})`;
382
+ imports.push({
383
+ name: item.name,
384
+ values: true,
385
+ ...(0, __orval_core.isRootKey)(context.specKey, context.target) ? {} : { specKey: context.specKey }
386
+ });
387
+ }
388
+ return item.path?.endsWith("[]") ? `faker.helpers.arrayElements(${enumValue})` : `faker.helpers.arrayElement(${enumValue})`;
511
389
  };
512
390
 
513
- // src/faker/resolvers/value.ts
514
- var isRegex = (key) => key[0] === "/" && key[key.length - 1] === "/";
515
- var resolveMockOverride = (properties = {}, item) => {
516
- const path = item.path ? item.path : `#.${item.name}`;
517
- const property = Object.entries(properties).find(([key]) => {
518
- if (isRegex(key)) {
519
- const regex = new RegExp(key.slice(1, key.length - 1));
520
- if (regex.test(item.name) || regex.test(path)) {
521
- return true;
522
- }
523
- }
524
- if (`#.${key}` === path) {
525
- return true;
526
- }
527
- return false;
528
- });
529
- if (!property) {
530
- return;
531
- }
532
- return {
533
- value: getNullable(property[1], item.nullable),
534
- imports: [],
535
- name: item.name,
536
- overrided: true
537
- };
391
+ //#endregion
392
+ //#region src/faker/resolvers/value.ts
393
+ const isRegex = (key) => key.startsWith("/") && key.endsWith("/");
394
+ const resolveMockOverride = (properties = {}, item) => {
395
+ const path = item.path ? item.path : `#.${item.name}`;
396
+ const property = Object.entries(properties).find(([key]) => {
397
+ if (isRegex(key)) {
398
+ const regex = new RegExp(key.slice(1, -1));
399
+ if (regex.test(item.name) || regex.test(path)) return true;
400
+ }
401
+ if (`#.${key}` === path) return true;
402
+ return false;
403
+ });
404
+ if (!property) return;
405
+ return {
406
+ value: getNullable(property[1], item.nullable),
407
+ imports: [],
408
+ name: item.name,
409
+ overrided: true
410
+ };
538
411
  };
539
- var getNullable = (value, nullable) => nullable ? `faker.helpers.arrayElement([${value}, null])` : value;
540
- var resolveMockValue = ({
541
- schema,
542
- mockOptions,
543
- operationId,
544
- tags,
545
- combine,
546
- context,
547
- imports,
548
- existingReferencedProperties,
549
- splitMockImplementations,
550
- allowOverride
551
- }) => {
552
- var _a, _b, _c;
553
- if ((0, import_core4.isReference)(schema)) {
554
- const {
555
- originalName,
556
- specKey = context.specKey,
557
- refPaths
558
- } = (0, import_core4.getRefInfo)(schema.$ref, context);
559
- const schemaRef = Array.isArray(refPaths) ? refPaths.reduce(
560
- (obj, key) => obj && typeof obj === "object" ? obj[key] : void 0,
561
- context.specs[specKey]
562
- ) : void 0;
563
- const newSchema = {
564
- ...schemaRef,
565
- name: (0, import_core4.pascal)(originalName),
566
- path: schema.path,
567
- isRef: true,
568
- required: [...(_a = schemaRef == null ? void 0 : schemaRef.required) != null ? _a : [], ...(_b = schema == null ? void 0 : schema.required) != null ? _b : []]
569
- };
570
- const newSeparator = newSchema.allOf ? "allOf" : newSchema.oneOf ? "oneOf" : "anyOf";
571
- const scalar2 = getMockScalar({
572
- item: newSchema,
573
- mockOptions,
574
- operationId,
575
- tags,
576
- combine: combine ? {
577
- separator: combine.separator === "anyOf" ? newSeparator : combine.separator,
578
- includedProperties: newSeparator === "allOf" ? [] : combine.includedProperties
579
- } : void 0,
580
- context: {
581
- ...context,
582
- specKey
583
- },
584
- imports,
585
- existingReferencedProperties,
586
- splitMockImplementations,
587
- allowOverride
588
- });
589
- if (scalar2.value && (newSchema.type === "object" || newSchema.allOf) && (combine == null ? void 0 : combine.separator) === "oneOf") {
590
- const funcName = `get${(0, import_core4.pascal)(operationId)}Response${(0, import_core4.pascal)(newSchema.name)}Mock`;
591
- if (!(splitMockImplementations == null ? void 0 : splitMockImplementations.some(
592
- (f) => f.includes(`export const ${funcName}`)
593
- ))) {
594
- const discriminatedProperty = (_c = newSchema.discriminator) == null ? void 0 : _c.propertyName;
595
- let type = `Partial<${newSchema.name}>`;
596
- if (discriminatedProperty) {
597
- type = `Omit<${type}, '${discriminatedProperty}'>`;
598
- }
599
- const args = `${overrideVarName}: ${type} = {}`;
600
- const func = `export const ${funcName} = (${args}): ${newSchema.name} => ({${scalar2.value.startsWith("...") ? "" : "..."}${scalar2.value}, ...${overrideVarName}});`;
601
- splitMockImplementations == null ? void 0 : splitMockImplementations.push(func);
602
- }
603
- if (newSchema.nullable) {
604
- scalar2.value = `${funcName}()`;
605
- } else {
606
- scalar2.value = `{...${funcName}()}`;
607
- }
608
- scalar2.imports.push({
609
- name: newSchema.name,
610
- specKey: (0, import_core4.isRootKey)(specKey, context.target) ? void 0 : specKey
611
- });
612
- }
613
- return {
614
- ...scalar2,
615
- type: getType(newSchema)
616
- };
617
- }
618
- const scalar = getMockScalar({
619
- item: schema,
620
- mockOptions,
621
- operationId,
622
- tags,
623
- combine,
624
- context,
625
- imports,
626
- existingReferencedProperties,
627
- splitMockImplementations,
628
- allowOverride
629
- });
630
- return {
631
- ...scalar,
632
- type: getType(schema)
633
- };
412
+ const getNullable = (value, nullable) => nullable ? `faker.helpers.arrayElement([${value}, null])` : value;
413
+ const resolveMockValue = ({ schema, mockOptions, operationId, tags, combine, context, imports, existingReferencedProperties, splitMockImplementations, allowOverride }) => {
414
+ if ((0, __orval_core.isReference)(schema)) {
415
+ const { originalName, specKey = context.specKey, refPaths } = (0, __orval_core.getRefInfo)(schema.$ref, context);
416
+ const schemaRef = Array.isArray(refPaths) ? refPaths.reduce((obj, key) => obj && typeof obj === "object" ? obj[key] : void 0, context.specs[specKey]) : void 0;
417
+ const newSchema = {
418
+ ...schemaRef,
419
+ name: (0, __orval_core.pascal)(originalName),
420
+ path: schema.path,
421
+ isRef: true,
422
+ required: [...schemaRef?.required ?? [], ...schema?.required ?? []]
423
+ };
424
+ const newSeparator = newSchema.allOf ? "allOf" : newSchema.oneOf ? "oneOf" : "anyOf";
425
+ const scalar = getMockScalar({
426
+ item: newSchema,
427
+ mockOptions,
428
+ operationId,
429
+ tags,
430
+ combine: combine ? {
431
+ separator: combine.separator === "anyOf" ? newSeparator : combine.separator,
432
+ includedProperties: newSeparator === "allOf" ? [] : combine.includedProperties
433
+ } : void 0,
434
+ context: {
435
+ ...context,
436
+ specKey
437
+ },
438
+ imports,
439
+ existingReferencedProperties,
440
+ splitMockImplementations,
441
+ allowOverride
442
+ });
443
+ if (scalar.value && (newSchema.type === "object" || newSchema.allOf) && combine?.separator === "oneOf") {
444
+ const funcName = `get${(0, __orval_core.pascal)(operationId)}Response${(0, __orval_core.pascal)(newSchema.name)}Mock`;
445
+ if (!splitMockImplementations?.some((f) => f.includes(`export const ${funcName}`))) {
446
+ const discriminatedProperty = newSchema.discriminator?.propertyName;
447
+ let type = `Partial<${newSchema.name}>`;
448
+ if (discriminatedProperty) type = `Omit<${type}, '${discriminatedProperty}'>`;
449
+ const args = `${overrideVarName}: ${type} = {}`;
450
+ const func = `export const ${funcName} = (${args}): ${newSchema.name} => ({${scalar.value.startsWith("...") ? "" : "..."}${scalar.value}, ...${overrideVarName}});`;
451
+ splitMockImplementations?.push(func);
452
+ }
453
+ scalar.value = newSchema.nullable ? `${funcName}()` : `{...${funcName}()}`;
454
+ scalar.imports.push({
455
+ name: newSchema.name,
456
+ specKey: (0, __orval_core.isRootKey)(specKey, context.target) ? void 0 : specKey
457
+ });
458
+ }
459
+ return {
460
+ ...scalar,
461
+ type: getType(newSchema)
462
+ };
463
+ }
464
+ return {
465
+ ...getMockScalar({
466
+ item: schema,
467
+ mockOptions,
468
+ operationId,
469
+ tags,
470
+ combine,
471
+ context,
472
+ imports,
473
+ existingReferencedProperties,
474
+ splitMockImplementations,
475
+ allowOverride
476
+ }),
477
+ type: getType(schema)
478
+ };
634
479
  };
635
- var getType = (schema) => {
636
- var _a;
637
- return (_a = schema.type) != null ? _a : schema.properties ? "object" : schema.items ? "array" : void 0;
480
+ const getType = (schema) => {
481
+ return schema.type ?? (schema.properties ? "object" : schema.items ? "array" : void 0);
638
482
  };
639
483
 
640
- // src/faker/getters/combine.ts
641
- var combineSchemasMock = ({
642
- item,
643
- separator,
644
- mockOptions,
645
- operationId,
646
- tags,
647
- combine,
648
- context,
649
- imports,
650
- existingReferencedProperties,
651
- splitMockImplementations
652
- }) => {
653
- var _a, _b, _c, _d;
654
- const combineImports = [];
655
- const includedProperties = ((_a = combine == null ? void 0 : combine.includedProperties) != null ? _a : []).slice(0);
656
- const isRefAndNotExisting = (0, import_core5.isReference)(item) && !existingReferencedProperties.includes(item.name);
657
- const itemResolvedValue = isRefAndNotExisting || item.properties ? resolveMockValue({
658
- schema: Object.fromEntries(
659
- Object.entries(item).filter(([key]) => key !== separator)
660
- ),
661
- combine: {
662
- separator: "allOf",
663
- includedProperties: []
664
- },
665
- mockOptions,
666
- operationId,
667
- tags,
668
- context,
669
- imports,
670
- existingReferencedProperties,
671
- splitMockImplementations
672
- }) : void 0;
673
- includedProperties.push(...(_b = itemResolvedValue == null ? void 0 : itemResolvedValue.includedProperties) != null ? _b : []);
674
- combineImports.push(...(_c = itemResolvedValue == null ? void 0 : itemResolvedValue.imports) != null ? _c : []);
675
- let containsOnlyPrimitiveValues = true;
676
- const value = ((_d = item[separator]) != null ? _d : []).reduce(
677
- (acc, val, _, arr) => {
678
- var _a2, _b2;
679
- if ("$ref" in val && existingReferencedProperties.includes(
680
- (0, import_core5.pascal)(val.$ref.split("/").pop())
681
- )) {
682
- if (arr.length === 1) {
683
- return "undefined";
684
- }
685
- return acc;
686
- }
687
- if (separator === "allOf" && item.required) {
688
- if ((0, import_core5.isSchema)(val) && val.required) {
689
- val = { ...val, required: [...item.required, ...val.required] };
690
- } else {
691
- val = { ...val, required: item.required };
692
- }
693
- }
694
- const resolvedValue = resolveMockValue({
695
- schema: {
696
- ...val,
697
- name: item.name,
698
- path: item.path ? item.path : "#"
699
- },
700
- combine: {
701
- separator,
702
- includedProperties: separator !== "oneOf" ? includedProperties : (_a2 = itemResolvedValue == null ? void 0 : itemResolvedValue.includedProperties) != null ? _a2 : []
703
- },
704
- mockOptions,
705
- operationId,
706
- tags,
707
- context,
708
- imports,
709
- existingReferencedProperties,
710
- splitMockImplementations
711
- });
712
- combineImports.push(...resolvedValue.imports);
713
- includedProperties.push(...(_b2 = resolvedValue.includedProperties) != null ? _b2 : []);
714
- if (resolvedValue.value === "{}") {
715
- containsOnlyPrimitiveValues = false;
716
- return acc;
717
- }
718
- if (separator === "allOf") {
719
- if (resolvedValue.value.startsWith("{") || !resolvedValue.type) {
720
- containsOnlyPrimitiveValues = false;
721
- return `${acc}...${resolvedValue.value},`;
722
- } else if (resolvedValue.type === "object") {
723
- containsOnlyPrimitiveValues = false;
724
- if (resolvedValue.value.startsWith("faker")) {
725
- return `${acc}...${resolvedValue.value},`;
726
- } else {
727
- return `${acc}...{${resolvedValue.value}},`;
728
- }
729
- }
730
- }
731
- return `${acc}${resolvedValue.value},`;
732
- },
733
- `${separator === "allOf" ? "" : "faker.helpers.arrayElement(["}`
734
- );
735
- let finalValue = value === "undefined" ? value : `${separator === "allOf" && !containsOnlyPrimitiveValues ? "{" : ""}${value}${separator === "allOf" ? containsOnlyPrimitiveValues ? "" : "}" : "])"}`;
736
- if (itemResolvedValue) {
737
- if (finalValue.startsWith("...")) {
738
- finalValue = `...{${finalValue}, ${itemResolvedValue.value}}`;
739
- } else {
740
- finalValue = `{...${finalValue}, ${itemResolvedValue.value}}`;
741
- }
742
- }
743
- if (finalValue.endsWith(",")) {
744
- finalValue = finalValue.substring(0, finalValue.length - 1);
745
- }
746
- return {
747
- value: finalValue,
748
- imports: combineImports,
749
- name: item.name,
750
- includedProperties
751
- };
484
+ //#endregion
485
+ //#region src/faker/getters/combine.ts
486
+ const combineSchemasMock = ({ item, separator, mockOptions, operationId, tags, combine, context, imports, existingReferencedProperties, splitMockImplementations }) => {
487
+ const combineImports = [];
488
+ const includedProperties = [...combine?.includedProperties ?? []];
489
+ const itemResolvedValue = (0, __orval_core.isReference)(item) && !existingReferencedProperties.includes(item.name) || item.properties ? resolveMockValue({
490
+ schema: Object.fromEntries(Object.entries(item).filter(([key]) => key !== separator)),
491
+ combine: {
492
+ separator: "allOf",
493
+ includedProperties: []
494
+ },
495
+ mockOptions,
496
+ operationId,
497
+ tags,
498
+ context,
499
+ imports,
500
+ existingReferencedProperties,
501
+ splitMockImplementations
502
+ }) : void 0;
503
+ includedProperties.push(...itemResolvedValue?.includedProperties ?? []);
504
+ combineImports.push(...itemResolvedValue?.imports ?? []);
505
+ let containsOnlyPrimitiveValues = true;
506
+ const value = (item[separator] ?? []).reduce((acc, val, _, arr) => {
507
+ if ("$ref" in val && existingReferencedProperties.includes((0, __orval_core.pascal)(val.$ref.split("/").pop()))) {
508
+ if (arr.length === 1) return "undefined";
509
+ return acc;
510
+ }
511
+ if (separator === "allOf" && item.required) val = (0, __orval_core.isSchema)(val) && val.required ? {
512
+ ...val,
513
+ required: [...item.required, ...val.required]
514
+ } : {
515
+ ...val,
516
+ required: item.required
517
+ };
518
+ const resolvedValue = resolveMockValue({
519
+ schema: {
520
+ ...val,
521
+ name: item.name,
522
+ path: item.path ? item.path : "#"
523
+ },
524
+ combine: {
525
+ separator,
526
+ includedProperties: separator === "oneOf" ? itemResolvedValue?.includedProperties ?? [] : includedProperties
527
+ },
528
+ mockOptions,
529
+ operationId,
530
+ tags,
531
+ context,
532
+ imports,
533
+ existingReferencedProperties,
534
+ splitMockImplementations
535
+ });
536
+ combineImports.push(...resolvedValue.imports);
537
+ includedProperties.push(...resolvedValue.includedProperties ?? []);
538
+ if (resolvedValue.value === "{}") {
539
+ containsOnlyPrimitiveValues = false;
540
+ return acc;
541
+ }
542
+ if (separator === "allOf") {
543
+ if (resolvedValue.value.startsWith("{") || !resolvedValue.type) {
544
+ containsOnlyPrimitiveValues = false;
545
+ return `${acc}...${resolvedValue.value},`;
546
+ } else if (resolvedValue.type === "object") {
547
+ containsOnlyPrimitiveValues = false;
548
+ return resolvedValue.value.startsWith("faker") ? `${acc}...${resolvedValue.value},` : `${acc}...{${resolvedValue.value}},`;
549
+ }
550
+ }
551
+ return `${acc}${resolvedValue.value},`;
552
+ }, separator === "allOf" ? "" : "faker.helpers.arrayElement([");
553
+ let finalValue = value === "undefined" ? value : `${separator === "allOf" && !containsOnlyPrimitiveValues ? "{" : ""}${value}${separator === "allOf" ? containsOnlyPrimitiveValues ? "" : "}" : "])"}`;
554
+ if (itemResolvedValue) finalValue = finalValue.startsWith("...") ? `...{${finalValue}, ${itemResolvedValue.value}}` : `{...${finalValue}, ${itemResolvedValue.value}}`;
555
+ if (finalValue.endsWith(",")) finalValue = finalValue.slice(0, Math.max(0, finalValue.length - 1));
556
+ return {
557
+ value: finalValue,
558
+ imports: combineImports,
559
+ name: item.name,
560
+ includedProperties
561
+ };
752
562
  };
753
563
 
754
- // src/faker/getters/route.ts
755
- var import_core6 = require("@orval/core");
756
- var hasParam = (path) => /[^{]*{[\w*_-]*}.*/.test(path);
757
- var getRoutePath = (path) => {
758
- const matches = path.match(/([^{]*){?([\w*_-]*)}?(.*)/);
759
- if (!(matches == null ? void 0 : matches.length)) return path;
760
- const prev = matches[1];
761
- const param = (0, import_core6.sanitize)((0, import_core6.camel)(matches[2]), {
762
- es5keyword: true,
763
- underscore: true,
764
- dash: true,
765
- dot: true
766
- });
767
- const next = hasParam(matches[3]) ? getRoutePath(matches[3]) : matches[3];
768
- if (hasParam(path)) {
769
- return `${prev}:${param}${next}`;
770
- } else {
771
- return `${prev}${param}${next}`;
772
- }
564
+ //#endregion
565
+ //#region src/faker/getters/route.ts
566
+ const hasParam = (path) => /[^{]*{[\w*_-]*}.*/.test(path);
567
+ const getRoutePath = (path) => {
568
+ const matches = /([^{]*){?([\w*_-]*)}?(.*)/.exec(path);
569
+ if (!matches?.length) return path;
570
+ const prev = matches[1];
571
+ const param = (0, __orval_core.sanitize)((0, __orval_core.camel)(matches[2]), {
572
+ es5keyword: true,
573
+ underscore: true,
574
+ dash: true,
575
+ dot: true
576
+ });
577
+ const next = hasParam(matches[3]) ? getRoutePath(matches[3]) : matches[3];
578
+ return hasParam(path) ? `${prev}:${param}${next}` : `${prev}${param}${next}`;
773
579
  };
774
- var getRouteMSW = (route, baseUrl = "*") => {
775
- const splittedRoute = route.split("/");
776
- return splittedRoute.reduce((acc, path, i) => {
777
- if (!path && !i) {
778
- return acc;
779
- }
780
- if (!path.includes("{")) {
781
- return `${acc}/${path}`;
782
- }
783
- return `${acc}/${getRoutePath(path)}`;
784
- }, baseUrl);
580
+ const getRouteMSW = (route, baseUrl = "*") => {
581
+ route = route.replaceAll(":", "\\:");
582
+ return route.split("/").reduce((acc, path, i) => {
583
+ if (!path && !i) return acc;
584
+ if (!path.includes("{")) return `${acc}/${path}`;
585
+ return `${acc}/${getRoutePath(path)}`;
586
+ }, baseUrl);
785
587
  };
786
588
 
787
- // src/msw/mocks.ts
788
- var import_core7 = require("@orval/core");
789
- var getMockPropertiesWithoutFunc = (properties, spec) => Object.entries((0, import_core7.isFunction)(properties) ? properties(spec) : properties).reduce((acc, [key, value]) => {
790
- const implementation = (0, import_core7.isFunction)(value) ? `(${value})()` : (0, import_core7.stringify)(value);
791
- acc[key] = implementation == null ? void 0 : implementation.replace(
792
- /import_faker.defaults|import_faker.faker/g,
793
- "faker"
794
- );
795
- return acc;
589
+ //#endregion
590
+ //#region src/msw/mocks.ts
591
+ const getMockPropertiesWithoutFunc = (properties, spec) => Object.entries((0, __orval_core.isFunction)(properties) ? properties(spec) : properties).reduce((acc, [key, value]) => {
592
+ acc[key] = ((0, __orval_core.isFunction)(value) ? `(${value})()` : (0, __orval_core.stringify)(value))?.replaceAll(/import_faker.defaults|import_faker.faker/g, "faker");
593
+ return acc;
796
594
  }, {});
797
- var getMockWithoutFunc = (spec, override) => {
798
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
799
- return {
800
- arrayMin: (_a = override == null ? void 0 : override.mock) == null ? void 0 : _a.arrayMin,
801
- arrayMax: (_b = override == null ? void 0 : override.mock) == null ? void 0 : _b.arrayMax,
802
- stringMin: (_c = override == null ? void 0 : override.mock) == null ? void 0 : _c.stringMin,
803
- stringMax: (_d = override == null ? void 0 : override.mock) == null ? void 0 : _d.stringMax,
804
- numberMin: (_e = override == null ? void 0 : override.mock) == null ? void 0 : _e.numberMin,
805
- numberMax: (_f = override == null ? void 0 : override.mock) == null ? void 0 : _f.numberMax,
806
- required: (_g = override == null ? void 0 : override.mock) == null ? void 0 : _g.required,
807
- fractionDigits: (_h = override == null ? void 0 : override.mock) == null ? void 0 : _h.fractionDigits,
808
- ...((_i = override == null ? void 0 : override.mock) == null ? void 0 : _i.properties) ? {
809
- properties: getMockPropertiesWithoutFunc(
810
- override.mock.properties,
811
- spec
812
- )
813
- } : {},
814
- ...((_j = override == null ? void 0 : override.mock) == null ? void 0 : _j.format) ? {
815
- format: getMockPropertiesWithoutFunc(override.mock.format, spec)
816
- } : {},
817
- ...(override == null ? void 0 : override.operations) ? {
818
- operations: Object.entries(override.operations).reduce((acc, [key, value]) => {
819
- var _a2;
820
- if ((_a2 = value.mock) == null ? void 0 : _a2.properties) {
821
- acc[key] = {
822
- properties: getMockPropertiesWithoutFunc(
823
- value.mock.properties,
824
- spec
825
- )
826
- };
827
- }
828
- return acc;
829
- }, {})
830
- } : {},
831
- ...(override == null ? void 0 : override.tags) ? {
832
- tags: Object.entries(override.tags).reduce((acc, [key, value]) => {
833
- var _a2;
834
- if ((_a2 = value.mock) == null ? void 0 : _a2.properties) {
835
- acc[key] = {
836
- properties: getMockPropertiesWithoutFunc(
837
- value.mock.properties,
838
- spec
839
- )
840
- };
841
- }
842
- return acc;
843
- }, {})
844
- } : {}
845
- };
846
- };
847
- var getMockScalarJsTypes = (definition, mockOptionsWithoutFunc) => {
848
- const isArray = definition.endsWith("[]");
849
- const type = isArray ? definition.slice(0, -2) : definition;
850
- switch (type) {
851
- case "number":
852
- return isArray ? `Array.from({length: faker.number.int({min: ${mockOptionsWithoutFunc.arrayMin}, max: ${mockOptionsWithoutFunc.arrayMax}})}, () => faker.number.int())` : "faker.number.int()";
853
- case "string":
854
- return isArray ? `Array.from({length: faker.number.int({min: ${mockOptionsWithoutFunc == null ? void 0 : mockOptionsWithoutFunc.arrayMin},max: ${mockOptionsWithoutFunc == null ? void 0 : mockOptionsWithoutFunc.arrayMax}})}, () => faker.word.sample())` : "faker.word.sample()";
855
- default:
856
- return "undefined";
857
- }
595
+ const getMockWithoutFunc = (spec, override) => ({
596
+ arrayMin: override?.mock?.arrayMin,
597
+ arrayMax: override?.mock?.arrayMax,
598
+ stringMin: override?.mock?.stringMin,
599
+ stringMax: override?.mock?.stringMax,
600
+ numberMin: override?.mock?.numberMin,
601
+ numberMax: override?.mock?.numberMax,
602
+ required: override?.mock?.required,
603
+ fractionDigits: override?.mock?.fractionDigits,
604
+ ...override?.mock?.properties ? { properties: getMockPropertiesWithoutFunc(override.mock.properties, spec) } : {},
605
+ ...override?.mock?.format ? { format: getMockPropertiesWithoutFunc(override.mock.format, spec) } : {},
606
+ ...override?.operations ? { operations: Object.entries(override.operations).reduce((acc, [key, value]) => {
607
+ if (value.mock?.properties) acc[key] = { properties: getMockPropertiesWithoutFunc(value.mock.properties, spec) };
608
+ return acc;
609
+ }, {}) } : {},
610
+ ...override?.tags ? { tags: Object.entries(override.tags).reduce((acc, [key, value]) => {
611
+ if (value.mock?.properties) acc[key] = { properties: getMockPropertiesWithoutFunc(value.mock.properties, spec) };
612
+ return acc;
613
+ }, {}) } : {}
614
+ });
615
+ const getMockScalarJsTypes = (definition, mockOptionsWithoutFunc) => {
616
+ const isArray = definition.endsWith("[]");
617
+ switch (isArray ? definition.slice(0, -2) : definition) {
618
+ case "number": return isArray ? `Array.from({length: faker.number.int({min: ${mockOptionsWithoutFunc.arrayMin}, max: ${mockOptionsWithoutFunc.arrayMax}})}, () => faker.number.int())` : "faker.number.int()";
619
+ case "string": return isArray ? `Array.from({length: faker.number.int({min: ${mockOptionsWithoutFunc?.arrayMin},max: ${mockOptionsWithoutFunc?.arrayMax}})}, () => faker.word.sample())` : "faker.word.sample()";
620
+ default: return "undefined";
621
+ }
858
622
  };
859
- var getResponsesMockDefinition = ({
860
- operationId,
861
- tags,
862
- returnType,
863
- responses,
864
- imports: responseImports,
865
- mockOptionsWithoutFunc,
866
- transformer,
867
- context,
868
- mockOptions,
869
- splitMockImplementations
870
- }) => {
871
- return responses.reduce(
872
- (acc, { value: definition, originalSchema, example, examples, imports, isRef }) => {
873
- var _a, _b, _c, _d, _e, _f;
874
- if (((_b = (_a = context.output.override) == null ? void 0 : _a.mock) == null ? void 0 : _b.useExamples) || (mockOptions == null ? void 0 : mockOptions.useExamples)) {
875
- let exampleValue = example || (originalSchema == null ? void 0 : originalSchema.example) || Object.values(examples || {})[0] || ((_c = originalSchema == null ? void 0 : originalSchema.examples) == null ? void 0 : _c[0]);
876
- exampleValue = (_d = exampleValue == null ? void 0 : exampleValue.value) != null ? _d : exampleValue;
877
- if (exampleValue) {
878
- acc.definitions.push(
879
- transformer ? transformer(exampleValue, returnType) : JSON.stringify(exampleValue)
880
- );
881
- return acc;
882
- }
883
- }
884
- if (!definition || import_core7.generalJSTypesWithArray.includes(definition)) {
885
- const value = getMockScalarJsTypes(definition, mockOptionsWithoutFunc);
886
- acc.definitions.push(
887
- transformer ? transformer(value, returnType) : value
888
- );
889
- return acc;
890
- }
891
- if (!originalSchema) {
892
- return acc;
893
- }
894
- const resolvedRef = (0, import_core7.resolveRef)(originalSchema, context);
895
- const scalar = getMockScalar({
896
- item: {
897
- name: definition,
898
- ...resolvedRef.schema
899
- },
900
- imports,
901
- mockOptions: mockOptionsWithoutFunc,
902
- operationId,
903
- tags,
904
- context: isRef ? {
905
- ...context,
906
- specKey: (_f = (_e = responseImports[0]) == null ? void 0 : _e.specKey) != null ? _f : context.specKey
907
- } : context,
908
- existingReferencedProperties: [],
909
- splitMockImplementations,
910
- allowOverride: true
911
- });
912
- acc.imports.push(...scalar.imports);
913
- acc.definitions.push(
914
- transformer ? transformer(scalar.value, returnType) : scalar.value.toString()
915
- );
916
- return acc;
917
- },
918
- {
919
- definitions: [],
920
- imports: []
921
- }
922
- );
623
+ const getResponsesMockDefinition = ({ operationId, tags, returnType, responses, imports: responseImports, mockOptionsWithoutFunc, transformer, context, mockOptions, splitMockImplementations }) => {
624
+ return responses.reduce((acc, { value: definition, originalSchema, example, examples, imports, isRef }) => {
625
+ if (context.output.override?.mock?.useExamples || mockOptions?.useExamples) {
626
+ let exampleValue = example || originalSchema?.example || Object.values(examples || {})[0] || originalSchema?.examples?.[0];
627
+ exampleValue = exampleValue?.value ?? exampleValue;
628
+ if (exampleValue) {
629
+ acc.definitions.push(transformer ? transformer(exampleValue, returnType) : JSON.stringify(exampleValue));
630
+ return acc;
631
+ }
632
+ }
633
+ if (!definition || __orval_core.generalJSTypesWithArray.includes(definition)) {
634
+ const value = getMockScalarJsTypes(definition, mockOptionsWithoutFunc);
635
+ acc.definitions.push(transformer ? transformer(value, returnType) : value);
636
+ return acc;
637
+ }
638
+ if (!originalSchema) return acc;
639
+ const resolvedRef = (0, __orval_core.resolveRef)(originalSchema, context);
640
+ const scalar = getMockScalar({
641
+ item: {
642
+ name: definition,
643
+ ...resolvedRef.schema
644
+ },
645
+ imports,
646
+ mockOptions: mockOptionsWithoutFunc,
647
+ operationId,
648
+ tags,
649
+ context: isRef ? {
650
+ ...context,
651
+ specKey: responseImports[0]?.specKey ?? context.specKey
652
+ } : context,
653
+ existingReferencedProperties: [],
654
+ splitMockImplementations,
655
+ allowOverride: true
656
+ });
657
+ acc.imports.push(...scalar.imports);
658
+ acc.definitions.push(transformer ? transformer(scalar.value, returnType) : scalar.value.toString());
659
+ return acc;
660
+ }, {
661
+ definitions: [],
662
+ imports: []
663
+ });
923
664
  };
924
- var getMockDefinition = ({
925
- operationId,
926
- tags,
927
- returnType,
928
- responses,
929
- imports: responseImports,
930
- override,
931
- transformer,
932
- context,
933
- mockOptions,
934
- splitMockImplementations
935
- }) => {
936
- const mockOptionsWithoutFunc = getMockWithoutFunc(
937
- context.specs[context.specKey],
938
- override
939
- );
940
- const { definitions, imports } = getResponsesMockDefinition({
941
- operationId,
942
- tags,
943
- returnType,
944
- responses,
945
- imports: responseImports,
946
- mockOptionsWithoutFunc,
947
- transformer,
948
- context,
949
- mockOptions,
950
- splitMockImplementations
951
- });
952
- return {
953
- definition: "[" + definitions.join(", ") + "]",
954
- definitions,
955
- imports
956
- };
665
+ const getMockDefinition = ({ operationId, tags, returnType, responses, imports: responseImports, override, transformer, context, mockOptions, splitMockImplementations }) => {
666
+ const mockOptionsWithoutFunc = getMockWithoutFunc(context.specs[context.specKey], override);
667
+ const { definitions, imports } = getResponsesMockDefinition({
668
+ operationId,
669
+ tags,
670
+ returnType,
671
+ responses,
672
+ imports: responseImports,
673
+ mockOptionsWithoutFunc,
674
+ transformer,
675
+ context,
676
+ mockOptions,
677
+ splitMockImplementations
678
+ });
679
+ return {
680
+ definition: "[" + definitions.join(", ") + "]",
681
+ definitions,
682
+ imports
683
+ };
957
684
  };
958
- var getMockOptionsDataOverride = (operationTags, operationId, override) => {
959
- var _a, _b, _c;
960
- const responseOverride = ((_c = (_b = (_a = override == null ? void 0 : override.operations) == null ? void 0 : _a[operationId]) == null ? void 0 : _b.mock) == null ? void 0 : _c.data) || operationTags.map((operationTag) => {
961
- var _a2, _b2, _c2;
962
- return (_c2 = (_b2 = (_a2 = override == null ? void 0 : override.tags) == null ? void 0 : _a2[operationTag]) == null ? void 0 : _b2.mock) == null ? void 0 : _c2.data;
963
- }).find((e) => e !== void 0);
964
- const implementation = (0, import_core7.isFunction)(responseOverride) ? `(${responseOverride})()` : (0, import_core7.stringify)(responseOverride);
965
- return implementation == null ? void 0 : implementation.replace(
966
- /import_faker.defaults|import_faker.faker/g,
967
- "faker"
968
- );
685
+ const getMockOptionsDataOverride = (operationTags, operationId, override) => {
686
+ const responseOverride = override?.operations?.[operationId]?.mock?.data || operationTags.map((operationTag) => override?.tags?.[operationTag]?.mock?.data).find((e) => e !== void 0);
687
+ return ((0, __orval_core.isFunction)(responseOverride) ? `(${responseOverride})()` : (0, __orval_core.stringify)(responseOverride))?.replaceAll(/import_faker.defaults|import_faker.faker/g, "faker");
969
688
  };
970
689
 
971
- // src/msw/index.ts
972
- var getMSWDependencies = (options) => {
973
- const hasDelay = (options == null ? void 0 : options.delay) !== false;
974
- const locale = options == null ? void 0 : options.locale;
975
- const exports2 = [
976
- { name: "http", values: true },
977
- { name: "HttpResponse", values: true }
978
- ];
979
- if (hasDelay) {
980
- exports2.push({ name: "delay", values: true });
981
- }
982
- return [
983
- {
984
- exports: exports2,
985
- dependency: "msw"
986
- },
987
- {
988
- exports: [{ name: "faker", values: true }],
989
- dependency: locale ? `@faker-js/faker/locale/${locale}` : "@faker-js/faker"
990
- }
991
- ];
690
+ //#endregion
691
+ //#region src/msw/index.ts
692
+ const getMSWDependencies = (options) => {
693
+ const hasDelay = options?.delay !== false;
694
+ const locale = options?.locale;
695
+ const exports$1 = [
696
+ {
697
+ name: "http",
698
+ values: true
699
+ },
700
+ {
701
+ name: "HttpResponse",
702
+ values: true
703
+ },
704
+ {
705
+ name: "RequestHandlerOptions",
706
+ values: false
707
+ }
708
+ ];
709
+ if (hasDelay) exports$1.push({
710
+ name: "delay",
711
+ values: true
712
+ });
713
+ return [{
714
+ exports: exports$1,
715
+ dependency: "msw"
716
+ }, {
717
+ exports: [{
718
+ name: "faker",
719
+ values: true
720
+ }],
721
+ dependency: locale ? `@faker-js/faker/locale/${locale}` : "@faker-js/faker"
722
+ }];
992
723
  };
993
- var generateMSWImports = ({
994
- implementation,
995
- imports,
996
- specsName,
997
- hasSchemaDir,
998
- isAllowSyntheticDefaultImports,
999
- options
1000
- }) => {
1001
- return (0, import_core8.generateDependencyImports)(
1002
- implementation,
1003
- [...getMSWDependencies(options), ...imports],
1004
- specsName,
1005
- hasSchemaDir,
1006
- isAllowSyntheticDefaultImports
1007
- );
724
+ const generateMSWImports = ({ implementation, imports, specsName, hasSchemaDir, isAllowSyntheticDefaultImports, options }) => {
725
+ return (0, __orval_core.generateDependencyImports)(implementation, [...getMSWDependencies(options), ...imports], specsName, hasSchemaDir, isAllowSyntheticDefaultImports);
1008
726
  };
1009
- var generateDefinition = (name, route, getResponseMockFunctionNameBase, handlerNameBase, { operationId, response, verb, tags }, { override, context, mock }, returnType, status, responseImports, responses, contentTypes, splitMockImplementations) => {
1010
- const oldSplitMockImplementations = [...splitMockImplementations];
1011
- const { definitions, definition, imports } = getMockDefinition({
1012
- operationId,
1013
- tags,
1014
- returnType,
1015
- responses,
1016
- imports: responseImports,
1017
- override,
1018
- context,
1019
- mockOptions: !(0, import_core8.isFunction)(mock) ? mock : void 0,
1020
- splitMockImplementations
1021
- });
1022
- const mockData = getMockOptionsDataOverride(tags, operationId, override);
1023
- let value = "";
1024
- if (mockData) {
1025
- value = mockData;
1026
- } else if (definitions.length > 1) {
1027
- value = `faker.helpers.arrayElement(${definition})`;
1028
- } else if (definitions[0]) {
1029
- value = definitions[0];
1030
- }
1031
- const isResponseOverridable = value.includes(overrideVarName);
1032
- const isTextPlain = contentTypes.includes("text/plain");
1033
- const isReturnHttpResponse = value && value !== "undefined";
1034
- const getResponseMockFunctionName = `${getResponseMockFunctionNameBase}${(0, import_core8.pascal)(
1035
- name
1036
- )}`;
1037
- const handlerName = `${handlerNameBase}${(0, import_core8.pascal)(name)}`;
1038
- const addedSplitMockImplementations = splitMockImplementations.slice(
1039
- oldSplitMockImplementations.length
1040
- );
1041
- splitMockImplementations.push(...addedSplitMockImplementations);
1042
- const mockImplementations = addedSplitMockImplementations.length ? `${addedSplitMockImplementations.join("\n\n")}
1043
-
1044
- ` : "";
1045
- const mockImplementation = isReturnHttpResponse ? `${mockImplementations}export const ${getResponseMockFunctionName} = (${isResponseOverridable ? `overrideResponse: Partial< ${returnType} > = {}` : ""})${mockData ? "" : `: ${returnType}`} => (${value})
1046
-
1047
- ` : mockImplementations;
1048
- const delay = getDelay(override, !(0, import_core8.isFunction)(mock) ? mock : void 0);
1049
- const infoParam = "info";
1050
- const overrideResponse = `overrideResponse !== undefined
727
+ const generateDefinition = (name, route, getResponseMockFunctionNameBase, handlerNameBase, { operationId, response, verb, tags }, { override, context, mock }, returnType, status, responseImports, responses, contentTypes, splitMockImplementations) => {
728
+ const oldSplitMockImplementations = [...splitMockImplementations];
729
+ const { definitions, definition, imports } = getMockDefinition({
730
+ operationId,
731
+ tags,
732
+ returnType,
733
+ responses,
734
+ imports: responseImports,
735
+ override,
736
+ context,
737
+ mockOptions: (0, __orval_core.isFunction)(mock) ? void 0 : mock,
738
+ splitMockImplementations
739
+ });
740
+ const mockData = getMockOptionsDataOverride(tags, operationId, override);
741
+ let value = "";
742
+ if (mockData) value = mockData;
743
+ else if (definitions.length > 1) value = `faker.helpers.arrayElement(${definition})`;
744
+ else if (definitions[0]) value = definitions[0];
745
+ const isResponseOverridable = value.includes(overrideVarName);
746
+ const isTextPlain = contentTypes.includes("text/plain");
747
+ const isReturnHttpResponse = value && value !== "undefined";
748
+ const getResponseMockFunctionName = `${getResponseMockFunctionNameBase}${(0, __orval_core.pascal)(name)}`;
749
+ const handlerName = `${handlerNameBase}${(0, __orval_core.pascal)(name)}`;
750
+ const addedSplitMockImplementations = splitMockImplementations.slice(oldSplitMockImplementations.length);
751
+ splitMockImplementations.push(...addedSplitMockImplementations);
752
+ const mockImplementations = addedSplitMockImplementations.length > 0 ? `${addedSplitMockImplementations.join("\n\n")}\n\n` : "";
753
+ const mockImplementation = isReturnHttpResponse ? `${mockImplementations}export const ${getResponseMockFunctionName} = (${isResponseOverridable ? `overrideResponse: Partial< ${returnType} > = {}` : ""})${mockData ? "" : `: ${returnType}`} => (${value})\n\n` : mockImplementations;
754
+ const delay = getDelay(override, (0, __orval_core.isFunction)(mock) ? void 0 : mock);
755
+ const infoParam = "info";
756
+ const overrideResponse = `overrideResponse !== undefined
1051
757
  ? (typeof overrideResponse === "function" ? await overrideResponse(${infoParam}) : overrideResponse)
1052
758
  : ${getResponseMockFunctionName}()`;
1053
- const handlerImplementation = `
1054
- export const ${handlerName} = (overrideResponse?: ${returnType} | ((${infoParam}: Parameters<Parameters<typeof http.${verb}>[1]>[0]) => Promise<${returnType}> | ${returnType})) => {
1055
- return http.${verb}('${route}', async (${infoParam}) => {${delay !== false ? `await delay(${(0, import_core8.isFunction)(delay) ? `(${delay})()` : delay});` : ""}
759
+ const handlerImplementation = `
760
+ export const ${handlerName} = (overrideResponse?: ${returnType} | ((${infoParam}: Parameters<Parameters<typeof http.${verb}>[1]>[0]) => Promise<${returnType}> | ${returnType}), options?: RequestHandlerOptions) => {
761
+ return http.${verb}('${route}', async (${infoParam}) => {${delay === false ? "" : `await delay(${(0, __orval_core.isFunction)(delay) ? `(${delay})()` : delay});`}
1056
762
  ${isReturnHttpResponse ? "" : `if (typeof overrideResponse === 'function') {await overrideResponse(info); }`}
1057
763
  return new HttpResponse(${isReturnHttpResponse ? isTextPlain ? overrideResponse : `JSON.stringify(${overrideResponse})` : null},
1058
764
  { status: ${status === "default" ? 200 : status.replace(/XX$/, "00")},
1059
765
  ${isReturnHttpResponse ? `headers: { 'Content-Type': ${isTextPlain ? "'text/plain'" : "'application/json'"} }` : ""}
1060
766
  })
1061
- })
1062
- }
1063
- `;
1064
- const includeResponseImports = !isTextPlain ? [
1065
- ...imports,
1066
- ...response.imports.filter((r) => {
1067
- const reg = new RegExp(`\\b${r.name}\\b`);
1068
- return reg.test(handlerImplementation) || reg.test(mockImplementation);
1069
- })
1070
- ] : imports;
1071
- return {
1072
- implementation: {
1073
- function: mockImplementation,
1074
- handlerName,
1075
- handler: handlerImplementation
1076
- },
1077
- imports: includeResponseImports
1078
- };
767
+ }, options)
768
+ }\n`;
769
+ const includeResponseImports = isTextPlain ? imports : [...imports, ...response.imports.filter((r) => {
770
+ const reg = /* @__PURE__ */ new RegExp(`\\b${r.name}\\b`);
771
+ return reg.test(handlerImplementation) || reg.test(mockImplementation);
772
+ })];
773
+ return {
774
+ implementation: {
775
+ function: mockImplementation,
776
+ handlerName,
777
+ handler: handlerImplementation
778
+ },
779
+ imports: includeResponseImports
780
+ };
1079
781
  };
1080
- var generateMSW = (generatorVerbOptions, generatorOptions) => {
1081
- var _a, _b, _c, _d;
1082
- const { pathRoute, override, mock } = generatorOptions;
1083
- const { operationId, response } = generatorVerbOptions;
1084
- const route = getRouteMSW(
1085
- pathRoute,
1086
- (_b = (_a = override == null ? void 0 : override.mock) == null ? void 0 : _a.baseUrl) != null ? _b : !(0, import_core8.isFunction)(mock) ? mock == null ? void 0 : mock.baseUrl : void 0
1087
- );
1088
- const handlerName = `get${(0, import_core8.pascal)(operationId)}MockHandler`;
1089
- const getResponseMockFunctionName = `get${(0, import_core8.pascal)(operationId)}ResponseMock`;
1090
- const splitMockImplementations = [];
1091
- const baseDefinition = generateDefinition(
1092
- "",
1093
- route,
1094
- getResponseMockFunctionName,
1095
- handlerName,
1096
- generatorVerbOptions,
1097
- generatorOptions,
1098
- response.definition.success,
1099
- (_d = (_c = response.types.success[0]) == null ? void 0 : _c.key) != null ? _d : "200",
1100
- response.imports,
1101
- response.types.success,
1102
- response.contentTypes,
1103
- splitMockImplementations
1104
- );
1105
- const mockImplementations = [baseDefinition.implementation.function];
1106
- const handlerImplementations = [baseDefinition.implementation.handler];
1107
- const imports = [...baseDefinition.imports];
1108
- if (generatorOptions.mock && (0, import_core8.isObject)(generatorOptions.mock) && generatorOptions.mock.generateEachHttpStatus) {
1109
- [...response.types.success, ...response.types.errors].forEach(
1110
- (statusResponse) => {
1111
- const definition = generateDefinition(
1112
- statusResponse.key,
1113
- route,
1114
- getResponseMockFunctionName,
1115
- handlerName,
1116
- generatorVerbOptions,
1117
- generatorOptions,
1118
- statusResponse.value,
1119
- statusResponse.key,
1120
- response.imports,
1121
- [statusResponse],
1122
- [statusResponse.contentType],
1123
- splitMockImplementations
1124
- );
1125
- mockImplementations.push(definition.implementation.function);
1126
- handlerImplementations.push(definition.implementation.handler);
1127
- imports.push(...definition.imports);
1128
- }
1129
- );
1130
- }
1131
- return {
1132
- implementation: {
1133
- function: mockImplementations.join("\n"),
1134
- handlerName,
1135
- handler: handlerImplementations.join("\n")
1136
- },
1137
- imports
1138
- };
782
+ const generateMSW = (generatorVerbOptions, generatorOptions) => {
783
+ const { pathRoute, override, mock } = generatorOptions;
784
+ const { operationId, response } = generatorVerbOptions;
785
+ const route = getRouteMSW(pathRoute, override?.mock?.baseUrl ?? ((0, __orval_core.isFunction)(mock) ? void 0 : mock?.baseUrl));
786
+ const handlerName = `get${(0, __orval_core.pascal)(operationId)}MockHandler`;
787
+ const getResponseMockFunctionName = `get${(0, __orval_core.pascal)(operationId)}ResponseMock`;
788
+ const splitMockImplementations = [];
789
+ const baseDefinition = generateDefinition("", route, getResponseMockFunctionName, handlerName, generatorVerbOptions, generatorOptions, response.definition.success, response.types.success[0]?.key ?? "200", response.imports, response.types.success, response.contentTypes, splitMockImplementations);
790
+ const mockImplementations = [baseDefinition.implementation.function];
791
+ const handlerImplementations = [baseDefinition.implementation.handler];
792
+ const imports = [...baseDefinition.imports];
793
+ if (generatorOptions.mock && (0, __orval_core.isObject)(generatorOptions.mock) && generatorOptions.mock.generateEachHttpStatus) for (const statusResponse of [...response.types.success, ...response.types.errors]) {
794
+ const definition = generateDefinition(statusResponse.key, route, getResponseMockFunctionName, handlerName, generatorVerbOptions, generatorOptions, statusResponse.value, statusResponse.key, response.imports, [statusResponse], [statusResponse.contentType], splitMockImplementations);
795
+ mockImplementations.push(definition.implementation.function);
796
+ handlerImplementations.push(definition.implementation.handler);
797
+ imports.push(...definition.imports);
798
+ }
799
+ return {
800
+ implementation: {
801
+ function: mockImplementations.join("\n"),
802
+ handlerName,
803
+ handler: handlerImplementations.join("\n")
804
+ },
805
+ imports
806
+ };
1139
807
  };
1140
808
 
1141
- // src/index.ts
1142
- var DEFAULT_MOCK_OPTIONS = {
1143
- type: "msw",
1144
- useExamples: false
809
+ //#endregion
810
+ //#region src/index.ts
811
+ const DEFAULT_MOCK_OPTIONS = {
812
+ type: "msw",
813
+ useExamples: false
1145
814
  };
1146
- var generateMockImports = (importOptions) => {
1147
- var _a;
1148
- switch ((_a = importOptions.options) == null ? void 0 : _a.type) {
1149
- default:
1150
- return generateMSWImports(importOptions);
1151
- }
815
+ const generateMockImports = (importOptions) => {
816
+ switch (importOptions.options?.type) {
817
+ default: return generateMSWImports(importOptions);
818
+ }
1152
819
  };
1153
- var generateMock = (generatorVerbOptions, generatorOptions) => {
1154
- switch (generatorOptions.mock.type) {
1155
- default:
1156
- return generateMSW(generatorVerbOptions, generatorOptions);
1157
- }
820
+ const generateMock = (generatorVerbOptions, generatorOptions) => {
821
+ switch (generatorOptions.mock.type) {
822
+ default: return generateMSW(generatorVerbOptions, generatorOptions);
823
+ }
1158
824
  };
1159
- // Annotate the CommonJS export names for ESM import in node:
1160
- 0 && (module.exports = {
1161
- DEFAULT_MOCK_OPTIONS,
1162
- generateMock,
1163
- generateMockImports
1164
- });
825
+
826
+ //#endregion
827
+ exports.DEFAULT_MOCK_OPTIONS = DEFAULT_MOCK_OPTIONS;
828
+ exports.generateMock = generateMock;
829
+ exports.generateMockImports = generateMockImports;
1165
830
  //# sourceMappingURL=index.js.map