@orval/mock 6.21.0

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/README.md ADDED
@@ -0,0 +1,28 @@
1
+ [![npm version](https://badge.fury.io/js/orval.svg)](https://badge.fury.io/js/orval)
2
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
3
+ [![tests](https://github.com/anymaniax/orval/actions/workflows/tests.yaml/badge.svg)](https://github.com/anymaniax/orval/actions/workflows/tests.yaml)
4
+
5
+ <p align="center">
6
+ <img src="./logo/orval-logo-horizontal.svg?raw=true" width="500" height="160" alt="orval - Restful Client Generator" />
7
+ </p>
8
+ <h1 align="center">
9
+ Visit <a href="https://orval.dev" target="_blank">orval.dev</a> for docs, guides, API and beer!
10
+ </h1>
11
+
12
+ ### Code Generation
13
+
14
+ `orval` is able to generate client with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in `yaml` or `json` formats.
15
+
16
+ `Generate`, `valid`, `cache` and `mock` in your React, Vue, Svelte and Angular applications all with your OpenAPI specification.
17
+
18
+ ### Samples
19
+
20
+ You can find below some samples
21
+
22
+ - [react app](https://github.com/anymaniax/orval/tree/master/samples/react-app)
23
+ - [react query](https://github.com/anymaniax/orval/tree/master/samples/react-query)
24
+ - [svelte query](https://github.com/anymaniax/orval/tree/master/samples/svelte-query)
25
+ - [vue query](https://github.com/anymaniax/orval/tree/master/samples/vue-query)
26
+ - [react app with swr](https://github.com/anymaniax/orval/tree/master/samples/react-app-with-swr)
27
+ - [nx fastify react](https://github.com/anymaniax/orval/tree/master/samples/nx-fastify-react)
28
+ - [angular app](https://github.com/anymaniax/orval/tree/master/samples/angular-app)
@@ -0,0 +1,16 @@
1
+ import * as _orval_core from '@orval/core';
2
+ import { GlobalMockOptions, GenerateMockImports, GeneratorVerbOptions, GeneratorOptions } from '@orval/core';
3
+
4
+ declare const DEFAULT_MOCK_OPTIONS: GlobalMockOptions;
5
+ declare const generateMockImports: GenerateMockImports;
6
+ declare const generateMock: (generatorVerbOptions: GeneratorVerbOptions, generatorOptions: Omit<GeneratorOptions, 'mock'> & {
7
+ mock: GlobalMockOptions;
8
+ }) => {
9
+ implementation: {
10
+ function: string;
11
+ handler: string;
12
+ };
13
+ imports: _orval_core.GeneratorImport[];
14
+ };
15
+
16
+ export { DEFAULT_MOCK_OPTIONS, generateMock, generateMockImports };
package/dist/index.js ADDED
@@ -0,0 +1,870 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ DEFAULT_MOCK_OPTIONS: () => DEFAULT_MOCK_OPTIONS,
34
+ generateMock: () => generateMock,
35
+ generateMockImports: () => generateMockImports
36
+ });
37
+ module.exports = __toCommonJS(src_exports);
38
+
39
+ // src/msw/index.ts
40
+ var import_core7 = require("@orval/core");
41
+
42
+ // src/faker/getters/combine.ts
43
+ var import_core4 = require("@orval/core");
44
+ var import_lodash2 = __toESM(require("lodash.omit"));
45
+
46
+ // src/faker/resolvers/value.ts
47
+ var import_core3 = require("@orval/core");
48
+ var import_lodash = __toESM(require("lodash.get"));
49
+
50
+ // src/faker/getters/scalar.ts
51
+ var import_core2 = require("@orval/core");
52
+
53
+ // src/faker/getters/object.ts
54
+ var import_core = require("@orval/core");
55
+
56
+ // src/faker/constants.ts
57
+ var DEFAULT_FORMAT_MOCK = {
58
+ bic: "faker.finance.bic()",
59
+ city: "faker.location.city()",
60
+ country: "faker.location.country()",
61
+ date: "faker.date.past().toISOString().split('T')[0]",
62
+ "date-time": "`${faker.date.past().toISOString().split('.')[0]}Z`",
63
+ email: "faker.internet.email()",
64
+ firstName: "faker.person.firstName()",
65
+ gender: "faker.person.gender()",
66
+ iban: "faker.finance.iban()",
67
+ ipv4: "faker.internet.ipv4()",
68
+ ipv6: "faker.internet.ipv6()",
69
+ jobTitle: "faker.person.jobTitle()",
70
+ lastName: "faker.person.lastName()",
71
+ password: "faker.internet.password()",
72
+ phoneNumber: "faker.phone.number()",
73
+ streetName: "faker.location.street()",
74
+ uri: "faker.internet.url()",
75
+ url: "faker.internet.url()",
76
+ userName: "faker.internet.userName()",
77
+ uuid: "faker.string.uuid()",
78
+ zipCode: "faker.location.zipCode()"
79
+ };
80
+ var DEFAULT_OBJECT_KEY_MOCK = "faker.string.alphanumeric(5)";
81
+
82
+ // src/faker/getters/object.ts
83
+ var getMockObject = ({
84
+ item,
85
+ mockOptions,
86
+ operationId,
87
+ tags,
88
+ combine,
89
+ context,
90
+ imports,
91
+ existingReferencedProperties
92
+ }) => {
93
+ if ((0, import_core.isReference)(item)) {
94
+ return resolveMockValue({
95
+ schema: {
96
+ ...item,
97
+ name: item.name,
98
+ path: item.path ? `${item.path}.${item.name}` : item.name
99
+ },
100
+ mockOptions,
101
+ operationId,
102
+ tags,
103
+ context,
104
+ imports,
105
+ existingReferencedProperties
106
+ });
107
+ }
108
+ if (item.allOf || item.oneOf || item.anyOf) {
109
+ const separator = item.allOf ? "allOf" : item.oneOf ? "oneOf" : "anyOf";
110
+ return combineSchemasMock({
111
+ item,
112
+ separator,
113
+ mockOptions,
114
+ operationId,
115
+ tags,
116
+ combine,
117
+ context,
118
+ imports,
119
+ existingReferencedProperties
120
+ });
121
+ }
122
+ if (item.properties) {
123
+ let value = !combine || (combine == null ? void 0 : combine.separator) === "oneOf" || (combine == null ? void 0 : combine.separator) === "anyOf" ? "{" : "";
124
+ let imports2 = [];
125
+ let includedProperties = [];
126
+ value += Object.entries(item.properties).sort((a, b) => {
127
+ return a[0].localeCompare(b[0]);
128
+ }).map(([key, prop]) => {
129
+ if (combine == null ? void 0 : combine.includedProperties.includes(key)) {
130
+ return void 0;
131
+ }
132
+ const isRequired = (mockOptions == null ? void 0 : mockOptions.required) || (Array.isArray(item.required) ? item.required : []).includes(key);
133
+ if ("$ref" in prop && existingReferencedProperties.includes(prop.$ref.split("/").pop())) {
134
+ return void 0;
135
+ }
136
+ const resolvedValue = resolveMockValue({
137
+ schema: {
138
+ ...prop,
139
+ name: key,
140
+ path: item.path ? `${item.path}.${key}` : `#.${key}`
141
+ },
142
+ mockOptions,
143
+ operationId,
144
+ tags,
145
+ context,
146
+ imports: imports2,
147
+ existingReferencedProperties
148
+ });
149
+ imports2.push(...resolvedValue.imports);
150
+ includedProperties.push(key);
151
+ const keyDefinition = (0, import_core.getKey)(key);
152
+ if (!isRequired && !resolvedValue.overrided) {
153
+ return `${keyDefinition}: faker.helpers.arrayElement([${resolvedValue.value}, undefined])`;
154
+ }
155
+ return `${keyDefinition}: ${resolvedValue.value}`;
156
+ }).filter(Boolean).join(", ");
157
+ value += !combine || (combine == null ? void 0 : combine.separator) === "oneOf" || (combine == null ? void 0 : combine.separator) === "anyOf" ? "}" : "";
158
+ return {
159
+ value,
160
+ imports: imports2,
161
+ name: item.name,
162
+ includedProperties
163
+ };
164
+ }
165
+ if (item.additionalProperties) {
166
+ if ((0, import_core.isBoolean)(item.additionalProperties)) {
167
+ return { value: `{}`, imports: [], name: item.name };
168
+ }
169
+ const resolvedValue = resolveMockValue({
170
+ schema: {
171
+ ...item.additionalProperties,
172
+ name: item.name,
173
+ path: item.path ? `${item.path}.#` : "#"
174
+ },
175
+ mockOptions,
176
+ operationId,
177
+ tags,
178
+ context,
179
+ imports,
180
+ existingReferencedProperties
181
+ });
182
+ return {
183
+ ...resolvedValue,
184
+ value: `{
185
+ [${DEFAULT_OBJECT_KEY_MOCK}]: ${resolvedValue.value}
186
+ }`
187
+ };
188
+ }
189
+ return { value: "{}", imports: [], name: item.name };
190
+ };
191
+
192
+ // src/faker/getters/scalar.ts
193
+ var getMockScalar = ({
194
+ item,
195
+ imports,
196
+ mockOptions,
197
+ operationId,
198
+ tags,
199
+ combine,
200
+ context,
201
+ existingReferencedProperties
202
+ }) => {
203
+ var _a, _b, _c, _d, _e, _f;
204
+ if (item.isRef) {
205
+ existingReferencedProperties = [...existingReferencedProperties, item.name];
206
+ }
207
+ const operationProperty = resolveMockOverride(
208
+ (_b = (_a = mockOptions == null ? void 0 : mockOptions.operations) == null ? void 0 : _a[operationId]) == null ? void 0 : _b.properties,
209
+ item
210
+ );
211
+ if (operationProperty) {
212
+ return operationProperty;
213
+ }
214
+ const overrideTag = Object.entries((_c = mockOptions == null ? void 0 : mockOptions.tags) != null ? _c : {}).sort((a, b) => {
215
+ return a[0].localeCompare(b[0]);
216
+ }).reduce(
217
+ (acc, [tag, options]) => tags.includes(tag) ? (0, import_core2.mergeDeep)(acc, options) : acc,
218
+ {}
219
+ );
220
+ const tagProperty = resolveMockOverride(overrideTag == null ? void 0 : overrideTag.properties, item);
221
+ if (tagProperty) {
222
+ return tagProperty;
223
+ }
224
+ const property = resolveMockOverride(mockOptions == null ? void 0 : mockOptions.properties, item);
225
+ if (property) {
226
+ return property;
227
+ }
228
+ if ((((_e = (_d = context.override) == null ? void 0 : _d.mock) == null ? void 0 : _e.useExamples) || (mockOptions == null ? void 0 : mockOptions.useExamples)) && item.example) {
229
+ return {
230
+ value: JSON.stringify(item.example),
231
+ imports: [],
232
+ name: item.name,
233
+ overrided: true
234
+ };
235
+ }
236
+ const ALL_FORMAT = {
237
+ ...DEFAULT_FORMAT_MOCK,
238
+ ...(_f = mockOptions == null ? void 0 : mockOptions.format) != null ? _f : {}
239
+ };
240
+ if (item.format && ALL_FORMAT[item.format]) {
241
+ return {
242
+ value: getNullable(`${ALL_FORMAT[item.format]}`, item.nullable),
243
+ imports: [],
244
+ name: item.name,
245
+ overrided: false
246
+ };
247
+ }
248
+ switch (item.type) {
249
+ case "number":
250
+ case "integer": {
251
+ return {
252
+ value: getNullable(
253
+ `faker.number.int({min: ${item.minimum}, max: ${item.maximum}})`,
254
+ item.nullable
255
+ ),
256
+ imports: [],
257
+ name: item.name
258
+ };
259
+ }
260
+ case "boolean": {
261
+ return {
262
+ value: "faker.datatype.boolean()",
263
+ imports: [],
264
+ name: item.name
265
+ };
266
+ }
267
+ case "array": {
268
+ if (!item.items) {
269
+ return { value: "[]", imports: [], name: item.name };
270
+ }
271
+ if ("$ref" in item.items && existingReferencedProperties.includes(item.items.$ref.split("/").pop())) {
272
+ return { value: "[]", imports: [], name: item.name };
273
+ }
274
+ const {
275
+ value,
276
+ enums,
277
+ imports: resolvedImports,
278
+ name
279
+ } = resolveMockValue({
280
+ schema: {
281
+ ...item.items,
282
+ name: item.name,
283
+ path: item.path ? `${item.path}.[]` : "#.[]"
284
+ },
285
+ combine,
286
+ mockOptions,
287
+ operationId,
288
+ tags,
289
+ context,
290
+ imports,
291
+ existingReferencedProperties
292
+ });
293
+ if (enums) {
294
+ if (!(0, import_core2.isReference)(item.items)) {
295
+ return {
296
+ value,
297
+ imports: resolvedImports,
298
+ name: item.name
299
+ };
300
+ }
301
+ const enumImp = imports.find(
302
+ (imp) => name.replace("[]", "") === imp.name
303
+ );
304
+ const enumValue = (enumImp == null ? void 0 : enumImp.name) || name;
305
+ return {
306
+ value: `faker.helpers.arrayElements(Object.values(${enumValue}))`,
307
+ imports: enumImp ? [
308
+ ...resolvedImports,
309
+ {
310
+ ...enumImp,
311
+ values: true,
312
+ ...!(0, import_core2.isRootKey)(context.specKey, context.target) ? { specKey: context.specKey } : {}
313
+ }
314
+ ] : resolvedImports,
315
+ name: item.name
316
+ };
317
+ }
318
+ let mapValue = value;
319
+ if (combine && !value.startsWith("faker") && !value.startsWith("{")) {
320
+ mapValue = `{${value}}`;
321
+ }
322
+ return {
323
+ value: `Array.from({ length: faker.number.int({ min: ${mockOptions == null ? void 0 : mockOptions.arrayMin}, max: ${mockOptions == null ? void 0 : mockOptions.arrayMax} }) }, (_, i) => i + 1).map(() => (${mapValue}))`,
324
+ imports: resolvedImports,
325
+ name: item.name
326
+ };
327
+ }
328
+ case "string": {
329
+ let value = "faker.word.sample()";
330
+ let imports2 = [];
331
+ if (item.enum) {
332
+ let enumValue = "['" + item.enum.map((e) => (0, import_core2.escape)(e)).join("','") + "'] as const";
333
+ if (item.isRef) {
334
+ enumValue = `Object.values(${item.name})`;
335
+ imports2 = [
336
+ {
337
+ name: item.name,
338
+ values: true,
339
+ ...!(0, import_core2.isRootKey)(context.specKey, context.target) ? { specKey: context.specKey } : {}
340
+ }
341
+ ];
342
+ }
343
+ value = `faker.helpers.arrayElement(${enumValue})`;
344
+ }
345
+ return {
346
+ value: getNullable(value, item.nullable),
347
+ enums: item.enum,
348
+ name: item.name,
349
+ imports: imports2
350
+ };
351
+ }
352
+ case "object":
353
+ default: {
354
+ return getMockObject({
355
+ item,
356
+ mockOptions,
357
+ operationId,
358
+ tags,
359
+ combine,
360
+ context,
361
+ imports,
362
+ existingReferencedProperties
363
+ });
364
+ }
365
+ }
366
+ };
367
+
368
+ // src/faker/resolvers/value.ts
369
+ var isRegex = (key) => key[0] === "/" && key[key.length - 1] === "/";
370
+ var resolveMockOverride = (properties = {}, item) => {
371
+ const path = item.path ? item.path : `#.${item.name}`;
372
+ const property = Object.entries(properties).find(([key]) => {
373
+ if (isRegex(key)) {
374
+ const regex = new RegExp(key.slice(1, key.length - 1));
375
+ if (regex.test(item.name) || regex.test(path)) {
376
+ return true;
377
+ }
378
+ }
379
+ if (`#.${key}` === path) {
380
+ return true;
381
+ }
382
+ return false;
383
+ });
384
+ if (!property) {
385
+ return;
386
+ }
387
+ return {
388
+ value: getNullable(property[1], item.nullable),
389
+ imports: [],
390
+ name: item.name,
391
+ overrided: true
392
+ };
393
+ };
394
+ var getNullable = (value, nullable) => nullable ? `faker.helpers.arrayElement([${value}, null])` : value;
395
+ var resolveMockValue = ({
396
+ schema,
397
+ mockOptions,
398
+ operationId,
399
+ tags,
400
+ combine,
401
+ context,
402
+ imports,
403
+ existingReferencedProperties
404
+ }) => {
405
+ if ((0, import_core3.isReference)(schema)) {
406
+ const {
407
+ name,
408
+ specKey = context.specKey,
409
+ refPaths
410
+ } = (0, import_core3.getRefInfo)(schema.$ref, context);
411
+ const schemaRef = (0, import_lodash.default)(context.specs[specKey], refPaths);
412
+ const newSchema = {
413
+ ...schemaRef,
414
+ name,
415
+ path: schema.path,
416
+ isRef: true
417
+ };
418
+ const scalar2 = getMockScalar({
419
+ item: newSchema,
420
+ mockOptions,
421
+ operationId,
422
+ tags,
423
+ combine,
424
+ context: {
425
+ ...context,
426
+ specKey
427
+ },
428
+ imports,
429
+ existingReferencedProperties
430
+ });
431
+ return {
432
+ ...scalar2,
433
+ type: newSchema.type
434
+ };
435
+ }
436
+ const scalar = getMockScalar({
437
+ item: schema,
438
+ mockOptions,
439
+ operationId,
440
+ tags,
441
+ combine,
442
+ context,
443
+ imports,
444
+ existingReferencedProperties
445
+ });
446
+ return {
447
+ ...scalar,
448
+ type: schema.type
449
+ };
450
+ };
451
+
452
+ // src/faker/getters/combine.ts
453
+ var combineSchemasMock = ({
454
+ item,
455
+ separator,
456
+ mockOptions,
457
+ operationId,
458
+ tags,
459
+ combine,
460
+ context,
461
+ imports,
462
+ existingReferencedProperties
463
+ }) => {
464
+ var _a, _b, _c, _d;
465
+ let combineImports = [];
466
+ let includedProperties = ((_a = combine == null ? void 0 : combine.includedProperties) != null ? _a : []).slice(
467
+ 0
468
+ );
469
+ const isRefAndNotExisting = (0, import_core4.isReference)(item) && !existingReferencedProperties.includes(item.name);
470
+ const itemResolvedValue = isRefAndNotExisting || item.properties ? resolveMockValue({
471
+ schema: (0, import_lodash2.default)(item, separator),
472
+ combine: {
473
+ separator: "allOf",
474
+ includedProperties: []
475
+ },
476
+ mockOptions,
477
+ operationId,
478
+ tags,
479
+ context,
480
+ imports,
481
+ existingReferencedProperties
482
+ }) : void 0;
483
+ includedProperties.push(...(_b = itemResolvedValue == null ? void 0 : itemResolvedValue.includedProperties) != null ? _b : []);
484
+ combineImports.push(...(_c = itemResolvedValue == null ? void 0 : itemResolvedValue.imports) != null ? _c : []);
485
+ const value = ((_d = item[separator]) != null ? _d : []).reduce((acc, val, index, arr) => {
486
+ var _a2, _b2;
487
+ if ("$ref" in val && existingReferencedProperties.includes(val.$ref.split("/").pop())) {
488
+ if (arr.length === 1) {
489
+ return "undefined";
490
+ }
491
+ return acc;
492
+ }
493
+ const resolvedValue = resolveMockValue({
494
+ schema: {
495
+ ...val,
496
+ name: item.name,
497
+ path: item.path ? item.path : "#"
498
+ },
499
+ combine: {
500
+ separator,
501
+ includedProperties: separator !== "oneOf" ? includedProperties : (_a2 = itemResolvedValue == null ? void 0 : itemResolvedValue.includedProperties) != null ? _a2 : []
502
+ },
503
+ mockOptions,
504
+ operationId,
505
+ tags,
506
+ context,
507
+ imports,
508
+ existingReferencedProperties
509
+ });
510
+ combineImports.push(...resolvedValue.imports);
511
+ includedProperties.push(...(_b2 = resolvedValue.includedProperties) != null ? _b2 : []);
512
+ const isLastElement = index === arr.length - 1;
513
+ let currentValue = resolvedValue.value;
514
+ if ((itemResolvedValue == null ? void 0 : itemResolvedValue.value) && separator === "oneOf") {
515
+ currentValue = `${resolvedValue.value.slice(0, -1)},${itemResolvedValue.value}}`;
516
+ }
517
+ if ((itemResolvedValue == null ? void 0 : itemResolvedValue.value) && separator !== "oneOf" && isLastElement) {
518
+ currentValue = `${currentValue}${(itemResolvedValue == null ? void 0 : itemResolvedValue.value) ? `,${itemResolvedValue.value}` : ""}`;
519
+ }
520
+ const isObjectBounds = !combine || combine.separator === "oneOf" && separator === "allOf";
521
+ if (!index && isObjectBounds) {
522
+ if (resolvedValue.enums || separator === "oneOf" || separator === "anyOf" || resolvedValue.type === "array") {
523
+ if (arr.length === 1) {
524
+ return `faker.helpers.arrayElement([${currentValue}])`;
525
+ }
526
+ return `faker.helpers.arrayElement([${currentValue},`;
527
+ }
528
+ if (arr.length === 1) {
529
+ if (resolvedValue.type && resolvedValue.type !== "object") {
530
+ return currentValue;
531
+ }
532
+ return `{${currentValue}}`;
533
+ }
534
+ return `{${currentValue},`;
535
+ }
536
+ if (isLastElement) {
537
+ if (resolvedValue.enums || separator === "oneOf" || separator === "anyOf" || resolvedValue.type === "array") {
538
+ return `${acc}${currentValue}${!combine ? "])" : ""}`;
539
+ }
540
+ return `${acc}${currentValue}${isObjectBounds ? "}" : ""}`;
541
+ }
542
+ if (!currentValue) {
543
+ return acc;
544
+ }
545
+ return `${acc}${currentValue},`;
546
+ }, "");
547
+ return {
548
+ value,
549
+ imports: combineImports,
550
+ name: item.name,
551
+ includedProperties
552
+ };
553
+ };
554
+
555
+ // src/faker/getters/route.ts
556
+ var import_core5 = require("@orval/core");
557
+ var hasParam = (path) => /[^{]*{[\w*_-]*}.*/.test(path);
558
+ var getRoutePath = (path) => {
559
+ const matches = path.match(/([^{]*){?([\w*_-]*)}?(.*)/);
560
+ if (!(matches == null ? void 0 : matches.length))
561
+ return path;
562
+ const prev = matches[1];
563
+ const param = (0, import_core5.sanitize)((0, import_core5.camel)(matches[2]), {
564
+ es5keyword: true,
565
+ underscore: true,
566
+ dash: true,
567
+ dot: true
568
+ });
569
+ const next = hasParam(matches[3]) ? getRoutePath(matches[3]) : matches[3];
570
+ if (hasParam(path)) {
571
+ return `${prev}:${param}${next}`;
572
+ } else {
573
+ return `${prev}${param}${next}`;
574
+ }
575
+ };
576
+ var getRouteMSW = (route, baseUrl = "*") => {
577
+ const splittedRoute = route.split("/");
578
+ return splittedRoute.reduce((acc, path, i) => {
579
+ if (!path && !i) {
580
+ return acc;
581
+ }
582
+ if (!path.includes("{")) {
583
+ return `${acc}/${path}`;
584
+ }
585
+ return `${acc}/${getRoutePath(path)}`;
586
+ }, baseUrl);
587
+ };
588
+
589
+ // src/msw/mocks.ts
590
+ var import_core6 = require("@orval/core");
591
+ var getMockPropertiesWithoutFunc = (properties, spec) => Object.entries((0, import_core6.isFunction)(properties) ? properties(spec) : properties).reduce((acc, [key, value]) => {
592
+ const implementation = (0, import_core6.isFunction)(value) ? `(${value})()` : (0, import_core6.stringify)(value);
593
+ acc[key] = implementation == null ? void 0 : implementation.replace(
594
+ /import_faker.defaults|import_faker.faker/g,
595
+ "faker"
596
+ );
597
+ return acc;
598
+ }, {});
599
+ var getMockWithoutFunc = (spec, override) => {
600
+ var _a, _b, _c, _d, _e;
601
+ return {
602
+ arrayMin: (_a = override == null ? void 0 : override.mock) == null ? void 0 : _a.arrayMin,
603
+ arrayMax: (_b = override == null ? void 0 : override.mock) == null ? void 0 : _b.arrayMax,
604
+ required: (_c = override == null ? void 0 : override.mock) == null ? void 0 : _c.required,
605
+ ...((_d = override == null ? void 0 : override.mock) == null ? void 0 : _d.properties) ? {
606
+ properties: getMockPropertiesWithoutFunc(
607
+ override.mock.properties,
608
+ spec
609
+ )
610
+ } : {},
611
+ ...((_e = override == null ? void 0 : override.mock) == null ? void 0 : _e.format) ? {
612
+ format: getMockPropertiesWithoutFunc(override.mock.format, spec)
613
+ } : {},
614
+ ...(override == null ? void 0 : override.operations) ? {
615
+ operations: Object.entries(override.operations).reduce((acc, [key, value]) => {
616
+ var _a2;
617
+ if ((_a2 = value.mock) == null ? void 0 : _a2.properties) {
618
+ acc[key] = {
619
+ properties: getMockPropertiesWithoutFunc(
620
+ value.mock.properties,
621
+ spec
622
+ )
623
+ };
624
+ }
625
+ return acc;
626
+ }, {})
627
+ } : {},
628
+ ...(override == null ? void 0 : override.tags) ? {
629
+ tags: Object.entries(override.tags).reduce((acc, [key, value]) => {
630
+ var _a2;
631
+ if ((_a2 = value.mock) == null ? void 0 : _a2.properties) {
632
+ acc[key] = {
633
+ properties: getMockPropertiesWithoutFunc(
634
+ value.mock.properties,
635
+ spec
636
+ )
637
+ };
638
+ }
639
+ return acc;
640
+ }, {})
641
+ } : {}
642
+ };
643
+ };
644
+ var getMockScalarJsTypes = (definition, mockOptionsWithoutFunc) => {
645
+ const isArray = definition.endsWith("[]");
646
+ const type = isArray ? definition.slice(0, -2) : definition;
647
+ switch (type) {
648
+ case "number":
649
+ return isArray ? `Array.from({length: faker.number.int({min: ${mockOptionsWithoutFunc.arrayMin}, max: ${mockOptionsWithoutFunc.arrayMax}})}, () => faker.number.int())` : "faker.number.int().toString()";
650
+ case "string":
651
+ 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()";
652
+ default:
653
+ return "undefined";
654
+ }
655
+ };
656
+ var getResponsesMockDefinition = ({
657
+ operationId,
658
+ tags,
659
+ response,
660
+ mockOptionsWithoutFunc,
661
+ transformer,
662
+ context,
663
+ mockOptions
664
+ }) => {
665
+ return response.types.success.reduce(
666
+ (acc, { value: definition, originalSchema, example, examples, imports, isRef }) => {
667
+ var _a, _b, _c, _d, _e, _f;
668
+ if (((_b = (_a = context.override) == null ? void 0 : _a.mock) == null ? void 0 : _b.useExamples) || (mockOptions == null ? void 0 : mockOptions.useExamples)) {
669
+ const exampleValue = example || (originalSchema == null ? void 0 : originalSchema.example) || ((_c = Object.values(examples || {})[0]) == null ? void 0 : _c.value) || ((_d = originalSchema == null ? void 0 : originalSchema.examples) == null ? void 0 : _d[0]);
670
+ if (exampleValue) {
671
+ acc.definitions.push(
672
+ transformer ? transformer(exampleValue, response.definition.success) : JSON.stringify(exampleValue)
673
+ );
674
+ return acc;
675
+ }
676
+ }
677
+ if (!definition || import_core6.generalJSTypesWithArray.includes(definition)) {
678
+ const value = getMockScalarJsTypes(definition, mockOptionsWithoutFunc);
679
+ acc.definitions.push(
680
+ transformer ? transformer(value, response.definition.success) : value
681
+ );
682
+ return acc;
683
+ }
684
+ if (!originalSchema) {
685
+ return acc;
686
+ }
687
+ const resolvedRef = (0, import_core6.resolveRef)(originalSchema, context);
688
+ const scalar = getMockScalar({
689
+ item: {
690
+ name: definition,
691
+ ...resolvedRef.schema
692
+ },
693
+ imports,
694
+ mockOptions: mockOptionsWithoutFunc,
695
+ operationId,
696
+ tags,
697
+ context: isRef ? {
698
+ ...context,
699
+ specKey: (_f = (_e = response.imports[0]) == null ? void 0 : _e.specKey) != null ? _f : context.specKey
700
+ } : context,
701
+ existingReferencedProperties: []
702
+ });
703
+ acc.imports.push(...scalar.imports);
704
+ acc.definitions.push(
705
+ transformer ? transformer(scalar.value, response.definition.success) : scalar.value.toString()
706
+ );
707
+ return acc;
708
+ },
709
+ {
710
+ definitions: [],
711
+ imports: []
712
+ }
713
+ );
714
+ };
715
+ var getMockDefinition = ({
716
+ operationId,
717
+ tags,
718
+ response,
719
+ override,
720
+ transformer,
721
+ context,
722
+ mockOptions
723
+ }) => {
724
+ const mockOptionsWithoutFunc = getMockWithoutFunc(
725
+ context.specs[context.specKey],
726
+ override
727
+ );
728
+ const { definitions, imports } = getResponsesMockDefinition({
729
+ operationId,
730
+ tags,
731
+ response,
732
+ mockOptionsWithoutFunc,
733
+ transformer,
734
+ context,
735
+ mockOptions
736
+ });
737
+ return {
738
+ definition: "[" + definitions.join(", ") + "]",
739
+ definitions,
740
+ imports
741
+ };
742
+ };
743
+ var getMockOptionsDataOverride = (operationId, override) => {
744
+ var _a, _b, _c;
745
+ 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;
746
+ const implementation = (0, import_core6.isFunction)(responseOverride) ? `(${responseOverride})()` : (0, import_core6.stringify)(responseOverride);
747
+ return implementation == null ? void 0 : implementation.replace(
748
+ /import_faker.defaults|import_faker.faker/g,
749
+ "faker"
750
+ );
751
+ };
752
+
753
+ // src/delay.ts
754
+ var getDelay = (override, options) => {
755
+ var _a, _b;
756
+ const overrideDelay = typeof ((_a = override == null ? void 0 : override.mock) == null ? void 0 : _a.delay) === "number" ? (_b = override == null ? void 0 : override.mock) == null ? void 0 : _b.delay : options == null ? void 0 : options.delay;
757
+ switch (typeof overrideDelay) {
758
+ case "function":
759
+ return overrideDelay();
760
+ case "number":
761
+ return overrideDelay;
762
+ default:
763
+ return 1e3;
764
+ }
765
+ };
766
+
767
+ // src/msw/index.ts
768
+ var getMSWDependencies = (locale) => [
769
+ {
770
+ exports: [
771
+ { name: "http", values: true },
772
+ { name: "HttpResponse", values: true },
773
+ { name: "delay", values: true }
774
+ ],
775
+ dependency: "msw"
776
+ },
777
+ {
778
+ exports: [{ name: "faker", values: true }],
779
+ dependency: locale ? `@faker-js/faker/locale/${locale}` : "@faker-js/faker"
780
+ }
781
+ ];
782
+ var generateMSWImports = ({
783
+ implementation,
784
+ imports,
785
+ specsName,
786
+ hasSchemaDir,
787
+ isAllowSyntheticDefaultImports,
788
+ options
789
+ }) => {
790
+ return (0, import_core7.generateDependencyImports)(
791
+ implementation,
792
+ [...getMSWDependencies(options == null ? void 0 : options.locale), ...imports],
793
+ specsName,
794
+ hasSchemaDir,
795
+ isAllowSyntheticDefaultImports
796
+ );
797
+ };
798
+ var generateMSW = ({ operationId, response, verb, tags }, { pathRoute, override, context, mock }) => {
799
+ var _a, _b;
800
+ const { definitions, definition, imports } = getMockDefinition({
801
+ operationId,
802
+ tags,
803
+ response,
804
+ override,
805
+ context,
806
+ mockOptions: !(0, import_core7.isFunction)(mock) ? mock : void 0
807
+ });
808
+ const route = getRouteMSW(
809
+ pathRoute,
810
+ (_b = (_a = override == null ? void 0 : override.mock) == null ? void 0 : _a.baseUrl) != null ? _b : !(0, import_core7.isFunction)(mock) ? mock == null ? void 0 : mock.baseUrl : void 0
811
+ );
812
+ const mockData = getMockOptionsDataOverride(operationId, override);
813
+ let value = "";
814
+ if (mockData) {
815
+ value = mockData;
816
+ } else if (definitions.length > 1) {
817
+ value = `faker.helpers.arrayElement(${definition})`;
818
+ } else if (definitions[0]) {
819
+ value = definitions[0];
820
+ }
821
+ const isTextPlain = response.contentTypes.includes("text/plain");
822
+ const functionName = `get${(0, import_core7.pascal)(operationId)}Mock`;
823
+ return {
824
+ implementation: {
825
+ function: value && value !== "undefined" ? `export const ${functionName} = () => (${value})
826
+
827
+ ` : "",
828
+ handler: `http.${verb}('${route}', async () => {
829
+ await delay(${getDelay(
830
+ override,
831
+ !(0, import_core7.isFunction)(mock) ? mock : void 0
832
+ )});
833
+ return new HttpResponse(${value && value !== "undefined" ? isTextPlain ? `${functionName}()` : `JSON.stringify(${functionName}())` : null},
834
+ {
835
+ status: 200,
836
+ headers: {
837
+ 'Content-Type': '${isTextPlain ? "text/plain" : "application/json"}',
838
+ }
839
+ }
840
+ )
841
+ }),`
842
+ },
843
+ imports
844
+ };
845
+ };
846
+
847
+ // src/index.ts
848
+ var DEFAULT_MOCK_OPTIONS = {
849
+ type: "msw",
850
+ useExamples: false
851
+ };
852
+ var generateMockImports = (importOptions) => {
853
+ var _a;
854
+ switch ((_a = importOptions.options) == null ? void 0 : _a.type) {
855
+ default:
856
+ return generateMSWImports(importOptions);
857
+ }
858
+ };
859
+ var generateMock = (generatorVerbOptions, generatorOptions) => {
860
+ switch (generatorOptions.mock.type) {
861
+ default:
862
+ return generateMSW(generatorVerbOptions, generatorOptions);
863
+ }
864
+ };
865
+ // Annotate the CommonJS export names for ESM import in node:
866
+ 0 && (module.exports = {
867
+ DEFAULT_MOCK_OPTIONS,
868
+ generateMock,
869
+ generateMockImports
870
+ });
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@orval/mock",
3
+ "version": "6.21.0",
4
+ "license": "MIT",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsup ./src/index.ts --target node12 --clean --dts",
12
+ "dev": "tsup ./src/index.ts --target node12 --clean --watch src",
13
+ "lint": "eslint src/**/*.ts"
14
+ },
15
+ "dependencies": {
16
+ "@orval/core": "6.21.0",
17
+ "lodash.get": "^4.4.2",
18
+ "lodash.omit": "^4.5.0",
19
+ "openapi3-ts": "^3.0.0"
20
+ }
21
+ }