@orval/core 8.14.0 → 8.16.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/dist/index.d.mts +143 -4
- package/dist/index.mjs +318 -141
- package/dist/index.mjs.map +1 -1
- package/package.json +11 -31
- /package/dist/{chunk-BpYLSNr0.mjs → chunk-8H4AJuhK.mjs} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as __exportAll } from "./chunk-
|
|
1
|
+
import { t as __exportAll } from "./chunk-8H4AJuhK.mjs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { entries, groupBy, isArray, isBoolean, isBoolean as isBoolean$1, isEmptyish, isFunction, isFunction as isFunction$1, isNullish, isNullish as isNullish$1, isNumber, isString, isString as isString$1, prop, unique, uniqueBy, uniqueWith } from "remeda";
|
|
4
4
|
import { keyword } from "esutils";
|
|
@@ -137,9 +137,12 @@ const TEMPLATE_TAG_REGEX = /\${(.+?)}/g;
|
|
|
137
137
|
//#endregion
|
|
138
138
|
//#region src/utils/assertion.ts
|
|
139
139
|
/**
|
|
140
|
-
*
|
|
140
|
+
* Type guard for an OpenAPI {@link OpenApiReferenceObject}.
|
|
141
141
|
*
|
|
142
|
-
*
|
|
142
|
+
* Returns `true` when `obj` has a `$ref` property, indicating a static
|
|
143
|
+
* JSON Pointer reference rather than an inline schema.
|
|
144
|
+
*
|
|
145
|
+
* @param obj - Value to test.
|
|
143
146
|
*/
|
|
144
147
|
function isReference(obj) {
|
|
145
148
|
return !isNullish$1(obj) && Object.hasOwn(obj, "$ref");
|
|
@@ -150,27 +153,71 @@ function isReference(obj) {
|
|
|
150
153
|
* Returns `true` when `obj` has a `$dynamicRef` string property,
|
|
151
154
|
* indicating it is an OpenAPI 3.1 dynamic reference rather than a
|
|
152
155
|
* static `$ref`.
|
|
156
|
+
*
|
|
157
|
+
* @param obj - Value to test.
|
|
158
|
+
*
|
|
159
|
+
* @see https://json-schema.org/draft/2020-12/json-schema-core#section-8.2.4
|
|
153
160
|
*/
|
|
154
161
|
function isDynamicReference(obj) {
|
|
155
162
|
return !isNullish$1(obj) && Object.hasOwn(obj, "$dynamicRef") && typeof obj.$dynamicRef === "string";
|
|
156
163
|
}
|
|
164
|
+
/**
|
|
165
|
+
* Returns `true` when `pathValue` has no file extension and is treated as a
|
|
166
|
+
* directory path.
|
|
167
|
+
*
|
|
168
|
+
* @param pathValue - Path string to inspect.
|
|
169
|
+
*/
|
|
157
170
|
function isDirectory(pathValue) {
|
|
158
171
|
return !nodePath.extname(pathValue);
|
|
159
172
|
}
|
|
173
|
+
/**
|
|
174
|
+
* Type guard for plain objects created with `{}` or `new Object()`.
|
|
175
|
+
*
|
|
176
|
+
* Excludes `null`, arrays, dates, and other non-plain object values.
|
|
177
|
+
*
|
|
178
|
+
* @param x - Value to test.
|
|
179
|
+
*/
|
|
160
180
|
function isObject(x) {
|
|
161
181
|
return Object.prototype.toString.call(x) === "[object Object]";
|
|
162
182
|
}
|
|
183
|
+
/**
|
|
184
|
+
* Type guard for string primitives and `String` wrapper objects.
|
|
185
|
+
*
|
|
186
|
+
* @param val - Value to test.
|
|
187
|
+
*/
|
|
163
188
|
function isStringLike(val) {
|
|
164
189
|
if (isString$1(val)) return true;
|
|
165
190
|
return Object.prototype.toString.call(val) === "[object String]";
|
|
166
191
|
}
|
|
192
|
+
/**
|
|
193
|
+
* Type guard for ES module namespace objects.
|
|
194
|
+
*
|
|
195
|
+
* @param x - Value to test.
|
|
196
|
+
*/
|
|
167
197
|
function isModule(x) {
|
|
168
198
|
return Object.prototype.toString.call(x) === "[object Module]";
|
|
169
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Type guard for integer numbers and numeric strings.
|
|
202
|
+
*
|
|
203
|
+
* Accepts finite integers (`42`) and strings that match `/^-?\d+$/`
|
|
204
|
+
* (`"-1"`, `"0"`). Rejects floats, empty strings, and non-numeric values.
|
|
205
|
+
*
|
|
206
|
+
* @param x - Value to test.
|
|
207
|
+
*/
|
|
170
208
|
function isNumeric(x) {
|
|
171
209
|
if (typeof x === "number") return Number.isInteger(x);
|
|
172
210
|
return isString$1(x) && /^-?\d+$/.test(x);
|
|
173
211
|
}
|
|
212
|
+
/**
|
|
213
|
+
* Type guard for an inline OpenAPI {@link OpenApiSchemaObject}.
|
|
214
|
+
*
|
|
215
|
+
* Returns `true` when `x` looks like a schema definition: it has a known
|
|
216
|
+
* `type`, composition keywords (`allOf`, `anyOf`, `oneOf`), or `properties`.
|
|
217
|
+
* Does not match reference objects; use {@link isReference} for those.
|
|
218
|
+
*
|
|
219
|
+
* @param x - Value to test.
|
|
220
|
+
*/
|
|
174
221
|
function isSchema(x) {
|
|
175
222
|
if (!isObject(x)) return false;
|
|
176
223
|
if (isString$1(x.type) && Object.values(SchemaType).includes(x.type)) return true;
|
|
@@ -179,9 +226,22 @@ function isSchema(x) {
|
|
|
179
226
|
if (isObject(x.properties)) return true;
|
|
180
227
|
return false;
|
|
181
228
|
}
|
|
229
|
+
/**
|
|
230
|
+
* Type guard for HTTP methods defined in {@link Verbs}.
|
|
231
|
+
*
|
|
232
|
+
* @param verb - Method name to test (for example, `"get"`, `"post"`).
|
|
233
|
+
*/
|
|
182
234
|
function isVerb(verb) {
|
|
183
235
|
return Object.values(Verbs).includes(verb);
|
|
184
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* Returns `true` when `str` is a valid absolute URL with an `http:` or
|
|
239
|
+
* `https:` protocol.
|
|
240
|
+
*
|
|
241
|
+
* Empty or whitespace-only strings are rejected.
|
|
242
|
+
*
|
|
243
|
+
* @param str - URL string to validate.
|
|
244
|
+
*/
|
|
185
245
|
function isUrl(str) {
|
|
186
246
|
if (!str.trim()) return false;
|
|
187
247
|
try {
|
|
@@ -194,6 +254,8 @@ function isUrl(str) {
|
|
|
194
254
|
/**
|
|
195
255
|
* Type guard for the MSW mock generator. Use to narrow a
|
|
196
256
|
* `GlobalMockOptions | ClientMockBuilder` value to `MswMockOptions`.
|
|
257
|
+
*
|
|
258
|
+
* @param mock - Mock configuration or builder to test.
|
|
197
259
|
*/
|
|
198
260
|
function isMswMock(mock) {
|
|
199
261
|
return !isFunction$1(mock) && mock.type === OutputMockType.MSW;
|
|
@@ -201,6 +263,8 @@ function isMswMock(mock) {
|
|
|
201
263
|
/**
|
|
202
264
|
* Type guard for the Faker mock generator. Use to narrow a
|
|
203
265
|
* `GlobalMockOptions | ClientMockBuilder` value to `FakerMockOptions`.
|
|
266
|
+
*
|
|
267
|
+
* @param mock - Mock configuration or builder to test.
|
|
204
268
|
*/
|
|
205
269
|
function isFakerMock(mock) {
|
|
206
270
|
return !isFunction$1(mock) && mock.type === OutputMockType.FAKER;
|
|
@@ -267,10 +331,11 @@ const pascalMemory = {};
|
|
|
267
331
|
function pascal(s = "") {
|
|
268
332
|
if (pascalMemory[s]) return pascalMemory[s];
|
|
269
333
|
const isStartWithUnderscore = s.startsWith("_");
|
|
334
|
+
const cacheKey = s;
|
|
270
335
|
if (regexps.upper.test(s)) s = low(s);
|
|
271
336
|
const pascalString = (s.match(/[a-zA-Z0-9\u00C0-\u017F]+/g) ?? []).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
|
|
272
337
|
const pascalWithUnderscore = isStartWithUnderscore ? `_${pascalString}` : pascalString;
|
|
273
|
-
pascalMemory[
|
|
338
|
+
pascalMemory[cacheKey] = pascalWithUnderscore;
|
|
274
339
|
return pascalWithUnderscore;
|
|
275
340
|
}
|
|
276
341
|
function camel(s = "") {
|
|
@@ -394,6 +459,20 @@ function createDebugger(ns, options = {}) {
|
|
|
394
459
|
const search = String.raw`\*/`;
|
|
395
460
|
const replacement = String.raw`*\/`;
|
|
396
461
|
const regex = new RegExp(search, "g");
|
|
462
|
+
function trimTrailingEmptyLines(lines) {
|
|
463
|
+
let lastLineIndex = lines.length - 1;
|
|
464
|
+
while (lastLineIndex >= 0 && lines[lastLineIndex]?.trim() === "") lastLineIndex--;
|
|
465
|
+
return lines.slice(0, lastLineIndex + 1);
|
|
466
|
+
}
|
|
467
|
+
function escapeJsDoc(value) {
|
|
468
|
+
return value.replaceAll(regex, replacement);
|
|
469
|
+
}
|
|
470
|
+
function getDescriptionLines(description) {
|
|
471
|
+
return trimTrailingEmptyLines((Array.isArray(description) ? description.filter((line) => !line.includes("eslint-disable")) : [description ?? ""]).flatMap((block) => block.split(/\r?\n/).map((line) => escapeJsDoc(line))));
|
|
472
|
+
}
|
|
473
|
+
function getEslintDisable(description) {
|
|
474
|
+
return Array.isArray(description) ? description.find((line) => line.includes("eslint-disable")) : void 0;
|
|
475
|
+
}
|
|
397
476
|
const itemValidationKeys = [
|
|
398
477
|
"minLength",
|
|
399
478
|
"maxLength",
|
|
@@ -417,93 +496,56 @@ function getItemValidationDocEntries(schema, prefix = "items", visited = /* @__P
|
|
|
417
496
|
}];
|
|
418
497
|
}), ...getItemValidationDocEntries(schema.items, `${prefix}.items`, visited)];
|
|
419
498
|
}
|
|
499
|
+
function toJsDocEntry(key, value) {
|
|
500
|
+
if (value === void 0 || value === false || value === "") return [];
|
|
501
|
+
return [{
|
|
502
|
+
key,
|
|
503
|
+
value
|
|
504
|
+
}];
|
|
505
|
+
}
|
|
506
|
+
function getSchemaDocEntries(schema, itemValidationDocEntries, isNullable) {
|
|
507
|
+
const { deprecated, summary, minLength, maxLength, minimum, maximum, exclusiveMinimum, exclusiveMaximum, minItems, maxItems, pattern } = schema;
|
|
508
|
+
return [
|
|
509
|
+
...toJsDocEntry("deprecated", deprecated),
|
|
510
|
+
...toJsDocEntry("summary", summary),
|
|
511
|
+
...toJsDocEntry("minLength", minLength),
|
|
512
|
+
...toJsDocEntry("maxLength", maxLength),
|
|
513
|
+
...toJsDocEntry("minimum", minimum),
|
|
514
|
+
...toJsDocEntry("maximum", maximum),
|
|
515
|
+
...toJsDocEntry("exclusiveMinimum", exclusiveMinimum),
|
|
516
|
+
...toJsDocEntry("exclusiveMaximum", exclusiveMaximum),
|
|
517
|
+
...toJsDocEntry("minItems", minItems),
|
|
518
|
+
...toJsDocEntry("maxItems", maxItems),
|
|
519
|
+
...toJsDocEntry("nullable", isNullable),
|
|
520
|
+
...toJsDocEntry("pattern", pattern),
|
|
521
|
+
...itemValidationDocEntries.flatMap(({ key, value }) => toJsDocEntry(key, value))
|
|
522
|
+
];
|
|
523
|
+
}
|
|
524
|
+
function formatJsDocEntry({ key, value }) {
|
|
525
|
+
if (value === true) return `@${key}`;
|
|
526
|
+
return `@${key} ${escapeJsDoc(value.toString())}`;
|
|
527
|
+
}
|
|
528
|
+
function renderJsDocBlock(lines, tryOneLine = false) {
|
|
529
|
+
if (lines.length === 0) return "";
|
|
530
|
+
if (lines.length === 1 && tryOneLine) return `/** ${lines[0]} */\n`;
|
|
531
|
+
const linePrefix = `${tryOneLine ? " " : ""} *`;
|
|
532
|
+
const closingPrefix = ` ${tryOneLine ? " " : ""}`;
|
|
533
|
+
return `/**\n${lines.map((line) => `${linePrefix}${line ? ` ${line}` : ""}`).join("\n")}\n${closingPrefix}*/\n`;
|
|
534
|
+
}
|
|
420
535
|
function jsDoc(schema, tryOneLine = false, context) {
|
|
421
536
|
if (context?.output.override.jsDoc) {
|
|
422
537
|
const { filter } = context.output.override.jsDoc;
|
|
423
538
|
if (filter) return keyValuePairsToJsDoc(filter(schema));
|
|
424
539
|
}
|
|
425
|
-
const { description, deprecated, summary, minLength, maxLength, minimum, maximum, exclusiveMinimum, exclusiveMaximum, minItems, maxItems, pattern } = schema;
|
|
426
540
|
const isNullable = schema.type === "null" || Array.isArray(schema.type) && schema.type.includes("null");
|
|
427
541
|
const itemValidationDocEntries = getItemValidationDocEntries(schema.items);
|
|
428
|
-
const lines = (
|
|
429
|
-
const
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
summary,
|
|
433
|
-
minLength?.toString(),
|
|
434
|
-
maxLength?.toString(),
|
|
435
|
-
minimum?.toString(),
|
|
436
|
-
maximum?.toString(),
|
|
437
|
-
exclusiveMinimum?.toString(),
|
|
438
|
-
exclusiveMaximum?.toString(),
|
|
439
|
-
minItems?.toString(),
|
|
440
|
-
maxItems?.toString(),
|
|
441
|
-
isNullable ? "null" : "",
|
|
442
|
-
pattern,
|
|
443
|
-
...itemValidationDocEntries.map(({ value }) => value.toString())
|
|
444
|
-
].filter(Boolean).length;
|
|
445
|
-
if (!count) return "";
|
|
446
|
-
const oneLine = count === 1 && tryOneLine;
|
|
447
|
-
const eslintDisable = Array.isArray(description) ? description.find((d) => d.includes("eslint-disable"))?.replaceAll(regex, replacement) : void 0;
|
|
448
|
-
let doc = `${eslintDisable ? `/* ${eslintDisable} */\n` : ""}/**`;
|
|
449
|
-
if (description) {
|
|
450
|
-
if (!oneLine) doc += `\n${tryOneLine ? " " : ""} *`;
|
|
451
|
-
doc += ` ${lines.join("\n * ")}`;
|
|
452
|
-
}
|
|
453
|
-
function appendPrefix() {
|
|
454
|
-
if (!oneLine) doc += `\n${tryOneLine ? " " : ""} *`;
|
|
455
|
-
}
|
|
456
|
-
function tryAppendStringDocLine(key, value) {
|
|
457
|
-
if (value) {
|
|
458
|
-
appendPrefix();
|
|
459
|
-
doc += ` @${key} ${value.replaceAll(regex, replacement)}`;
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
function tryAppendBooleanDocLine(key, value) {
|
|
463
|
-
if (value === true) {
|
|
464
|
-
appendPrefix();
|
|
465
|
-
doc += ` @${key}`;
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
function tryAppendNumberDocLine(key, value) {
|
|
469
|
-
if (value !== void 0) {
|
|
470
|
-
appendPrefix();
|
|
471
|
-
doc += ` @${key} ${value}`;
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
tryAppendBooleanDocLine("deprecated", deprecated);
|
|
475
|
-
tryAppendStringDocLine("summary", summary?.replaceAll(regex, replacement));
|
|
476
|
-
tryAppendNumberDocLine("minLength", minLength);
|
|
477
|
-
tryAppendNumberDocLine("maxLength", maxLength);
|
|
478
|
-
tryAppendNumberDocLine("minimum", minimum);
|
|
479
|
-
tryAppendNumberDocLine("maximum", maximum);
|
|
480
|
-
tryAppendNumberDocLine("exclusiveMinimum", exclusiveMinimum);
|
|
481
|
-
tryAppendNumberDocLine("exclusiveMaximum", exclusiveMaximum);
|
|
482
|
-
tryAppendNumberDocLine("minItems", minItems);
|
|
483
|
-
tryAppendNumberDocLine("maxItems", maxItems);
|
|
484
|
-
tryAppendBooleanDocLine("nullable", isNullable);
|
|
485
|
-
tryAppendStringDocLine("pattern", pattern);
|
|
486
|
-
for (const { key, value } of itemValidationDocEntries) {
|
|
487
|
-
if (typeof value === "string") {
|
|
488
|
-
tryAppendStringDocLine(key, value);
|
|
489
|
-
continue;
|
|
490
|
-
}
|
|
491
|
-
if (typeof value === "number") {
|
|
492
|
-
tryAppendNumberDocLine(key, value);
|
|
493
|
-
continue;
|
|
494
|
-
}
|
|
495
|
-
tryAppendBooleanDocLine(key, value);
|
|
496
|
-
}
|
|
497
|
-
doc += oneLine ? " " : `\n ${tryOneLine ? " " : ""}`;
|
|
498
|
-
doc += "*/\n";
|
|
499
|
-
return doc;
|
|
542
|
+
const lines = [...getDescriptionLines(schema.description), ...getSchemaDocEntries(schema, itemValidationDocEntries, isNullable).map((entry) => formatJsDocEntry(entry))];
|
|
543
|
+
const eslintDisable = getEslintDisable(schema.description);
|
|
544
|
+
const doc = renderJsDocBlock(lines, tryOneLine);
|
|
545
|
+
return `${eslintDisable ? `/* ${escapeJsDoc(eslintDisable)} */\n` : ""}${doc}`;
|
|
500
546
|
}
|
|
501
547
|
function keyValuePairsToJsDoc(keyValues) {
|
|
502
|
-
|
|
503
|
-
let doc = "/**\n";
|
|
504
|
-
for (const { key, value } of keyValues) doc += ` * @${key} ${value}\n`;
|
|
505
|
-
doc += " */\n";
|
|
506
|
-
return doc;
|
|
548
|
+
return renderJsDocBlock(keyValues.map(({ key, value }) => `@${key} ${value}`));
|
|
507
549
|
}
|
|
508
550
|
//#endregion
|
|
509
551
|
//#region src/utils/dynamic-import.ts
|
|
@@ -666,9 +708,6 @@ const LogLevels = {
|
|
|
666
708
|
warn: 2,
|
|
667
709
|
info: 3
|
|
668
710
|
};
|
|
669
|
-
let lastType;
|
|
670
|
-
let lastMsg;
|
|
671
|
-
let sameCount = 0;
|
|
672
711
|
function clearScreen() {
|
|
673
712
|
const repeatCount = process.stdout.rows - 2;
|
|
674
713
|
const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : "";
|
|
@@ -678,6 +717,9 @@ function clearScreen() {
|
|
|
678
717
|
}
|
|
679
718
|
function createLogger(level = "info", options = {}) {
|
|
680
719
|
const { prefix = "[vite]", allowClearScreen = true } = options;
|
|
720
|
+
let lastType;
|
|
721
|
+
let lastMsg;
|
|
722
|
+
let sameCount = 0;
|
|
681
723
|
const thresh = LogLevels[level];
|
|
682
724
|
const clear = allowClearScreen && process.stdout.isTTY && !process.env.CI ? clearScreen : () => {};
|
|
683
725
|
function output(type, msg, options = {}) {
|
|
@@ -877,6 +919,16 @@ function resolveInstalledVersions(packageJson, fromDir) {
|
|
|
877
919
|
return resolved;
|
|
878
920
|
}
|
|
879
921
|
//#endregion
|
|
922
|
+
//#region src/utils/schemas-options.ts
|
|
923
|
+
/**
|
|
924
|
+
* Extracts the custom package import specifier from a normalized `schemas`
|
|
925
|
+
* config. Returns `undefined` when `schemas` is a plain string, `false`,
|
|
926
|
+
* `undefined`, or when `importPath` is not set.
|
|
927
|
+
*/
|
|
928
|
+
function getSchemasImportPath(schemas) {
|
|
929
|
+
if (isObject(schemas)) return schemas.importPath;
|
|
930
|
+
}
|
|
931
|
+
//#endregion
|
|
880
932
|
//#region src/utils/sort.ts
|
|
881
933
|
const sortByPriority = (arr) => arr.toSorted((a, b) => {
|
|
882
934
|
if (a.default) return 1;
|
|
@@ -1047,6 +1099,34 @@ function jsStringEscape(input) {
|
|
|
1047
1099
|
});
|
|
1048
1100
|
}
|
|
1049
1101
|
/**
|
|
1102
|
+
* Escape a string for embedding inside a single-quoted JS string literal.
|
|
1103
|
+
*
|
|
1104
|
+
* Unlike {@link jsStringEscape}, this escapes only what a string literal
|
|
1105
|
+
* actually needs: backslashes, single quotes, and line terminators. It
|
|
1106
|
+
* deliberately does NOT escape `/` or `*`, which are meaningless inside a
|
|
1107
|
+
* string literal, so escaping them produces "useless escapes" that round-trip
|
|
1108
|
+
* to the same value but trip ESLint's `no-useless-escape` in generated code
|
|
1109
|
+
* (e.g. RegExp pattern literals, see #3337).
|
|
1110
|
+
*
|
|
1111
|
+
* Use {@link jsStringEscape} instead when the value is embedded in a JS comment,
|
|
1112
|
+
* where the comment delimiters must be neutralized.
|
|
1113
|
+
*
|
|
1114
|
+
* @param input String to escape
|
|
1115
|
+
*/
|
|
1116
|
+
function jsStringLiteralEscape(input) {
|
|
1117
|
+
return input.replaceAll(/['\\\n\r\u2028\u2029]/g, (character) => {
|
|
1118
|
+
switch (character) {
|
|
1119
|
+
case "'":
|
|
1120
|
+
case "\\": return "\\" + character;
|
|
1121
|
+
case "\n": return String.raw`\n`;
|
|
1122
|
+
case "\r": return String.raw`\r`;
|
|
1123
|
+
case "\u2028": return String.raw`\u2028`;
|
|
1124
|
+
case "\u2029": return String.raw`\u2029`;
|
|
1125
|
+
default: return "";
|
|
1126
|
+
}
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1050
1130
|
* Deduplicates a TypeScript union type string.
|
|
1051
1131
|
* Handles types like "A | B | B" → "A | B" and "null | null" → "null".
|
|
1052
1132
|
* Only splits on top-level | (not inside {} () [] <> or string literals).
|
|
@@ -1701,28 +1781,54 @@ function getObject({ item, name, context, nullable, formDataContext }) {
|
|
|
1701
1781
|
const itemOneOf = schemaItem.oneOf;
|
|
1702
1782
|
const itemAnyOf = schemaItem.anyOf;
|
|
1703
1783
|
const itemType = schemaItem.type;
|
|
1704
|
-
if (itemAllOf || itemOneOf || itemAnyOf)
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1784
|
+
if (itemAllOf || itemOneOf || itemAnyOf) {
|
|
1785
|
+
const separator = itemAllOf ? "allOf" : itemOneOf ? "oneOf" : "anyOf";
|
|
1786
|
+
const members = separator === "anyOf" ? itemAnyOf : separator === "oneOf" ? itemOneOf : void 0;
|
|
1787
|
+
if (members) {
|
|
1788
|
+
const isNullMember = (member) => {
|
|
1789
|
+
if (isReference(member)) return false;
|
|
1790
|
+
const memberType = member.type;
|
|
1791
|
+
return memberType === "null" || Array.isArray(memberType) && memberType.length === 1 && memberType[0] === "null";
|
|
1792
|
+
};
|
|
1793
|
+
const nonNullMembers = members.filter((member) => !isNullMember(member));
|
|
1794
|
+
const nonNullMember = nonNullMembers[0];
|
|
1795
|
+
const nonNullMemberType = nonNullMember && !isReference(nonNullMember) ? nonNullMember.type : void 0;
|
|
1796
|
+
const nonNullMemberProperties = nonNullMember && !isReference(nonNullMember) ? nonNullMember.properties : void 0;
|
|
1797
|
+
if (members.some(isNullMember) && nonNullMembers.length === 1 && nonNullMember != null && !isReference(nonNullMember) && (nonNullMemberType === "object" || nonNullMemberType == null && nonNullMemberProperties != null) && nonNullMemberProperties != null && Object.keys(nonNullMemberProperties).length > 0) return getObject({
|
|
1798
|
+
item: nonNullMember,
|
|
1799
|
+
name,
|
|
1800
|
+
context,
|
|
1801
|
+
nullable: nullable || " | null",
|
|
1802
|
+
formDataContext
|
|
1803
|
+
});
|
|
1804
|
+
}
|
|
1715
1805
|
return combineSchemas({
|
|
1716
|
-
schema:
|
|
1717
|
-
...baseItem,
|
|
1718
|
-
type
|
|
1719
|
-
})) },
|
|
1806
|
+
schema: schemaItem,
|
|
1720
1807
|
name,
|
|
1721
|
-
separator
|
|
1808
|
+
separator,
|
|
1722
1809
|
context,
|
|
1723
|
-
nullable
|
|
1810
|
+
nullable,
|
|
1811
|
+
formDataContext
|
|
1724
1812
|
});
|
|
1725
1813
|
}
|
|
1814
|
+
if (Array.isArray(itemType)) {
|
|
1815
|
+
const typeArray = itemType;
|
|
1816
|
+
const nonNullTypes = typeArray.filter((type) => type !== "null");
|
|
1817
|
+
const typeArrayProperties = schemaItem.properties;
|
|
1818
|
+
if (!(nonNullTypes.length === 1 && nonNullTypes[0] === "object" && typeArrayProperties != null && Object.keys(typeArrayProperties).length > 0)) {
|
|
1819
|
+
const baseItem = schemaItem;
|
|
1820
|
+
return combineSchemas({
|
|
1821
|
+
schema: { anyOf: typeArray.map((type) => ({
|
|
1822
|
+
...baseItem,
|
|
1823
|
+
type
|
|
1824
|
+
})) },
|
|
1825
|
+
name,
|
|
1826
|
+
separator: "anyOf",
|
|
1827
|
+
context,
|
|
1828
|
+
nullable
|
|
1829
|
+
});
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1726
1832
|
const itemProperties = schemaItem.properties;
|
|
1727
1833
|
if (itemProperties && Object.entries(itemProperties).length > 0) {
|
|
1728
1834
|
const entries = Object.entries(itemProperties);
|
|
@@ -1824,13 +1930,13 @@ function getObject({ item, name, context, nullable, formDataContext }) {
|
|
|
1824
1930
|
acc.useTypeAlias = true;
|
|
1825
1931
|
acc.imports.push(...recordType.imports);
|
|
1826
1932
|
acc.dependencies.push(...recordType.dependencies);
|
|
1933
|
+
acc.imports.push(...resolvedValue.imports);
|
|
1934
|
+
acc.schemas.push(...resolvedValue.schemas);
|
|
1935
|
+
acc.dependencies.push(...resolvedValue.dependencies);
|
|
1827
1936
|
} else {
|
|
1828
1937
|
const keyType = getIndexSignatureKey(schemaItem);
|
|
1829
|
-
acc.value += `\n [key: ${keyType}]:
|
|
1938
|
+
acc.value += `\n [key: ${keyType}]: unknown;\n}`;
|
|
1830
1939
|
}
|
|
1831
|
-
acc.imports.push(...resolvedValue.imports);
|
|
1832
|
-
acc.schemas.push(...resolvedValue.schemas);
|
|
1833
|
-
acc.dependencies.push(...resolvedValue.dependencies);
|
|
1834
1940
|
}
|
|
1835
1941
|
else acc.value += "\n}";
|
|
1836
1942
|
acc.value += nullable;
|
|
@@ -2405,12 +2511,14 @@ function resolveDynamicRef(anchorName, context, imports = []) {
|
|
|
2405
2511
|
if (!scopeEntry) return {
|
|
2406
2512
|
schema: {},
|
|
2407
2513
|
imports,
|
|
2408
|
-
resolvedTypeName: "unknown"
|
|
2514
|
+
resolvedTypeName: "unknown",
|
|
2515
|
+
schemaName: void 0
|
|
2409
2516
|
};
|
|
2410
2517
|
if (scopeEntry.isParameter) return {
|
|
2411
2518
|
schema: {},
|
|
2412
2519
|
imports,
|
|
2413
|
-
resolvedTypeName: scopeEntry.name
|
|
2520
|
+
resolvedTypeName: scopeEntry.name,
|
|
2521
|
+
schemaName: void 0
|
|
2414
2522
|
};
|
|
2415
2523
|
const resolvedTypeName = scopeEntry.name;
|
|
2416
2524
|
const schemaRef = `#/components/schemas/${encodeJsonPointerSegment(scopeEntry.schemaName)}`;
|
|
@@ -2419,13 +2527,15 @@ function resolveDynamicRef(anchorName, context, imports = []) {
|
|
|
2419
2527
|
return {
|
|
2420
2528
|
schema: resolvedSchema,
|
|
2421
2529
|
imports: resolvedImports,
|
|
2422
|
-
resolvedTypeName
|
|
2530
|
+
resolvedTypeName,
|
|
2531
|
+
schemaName: scopeEntry.schemaName
|
|
2423
2532
|
};
|
|
2424
2533
|
} catch {
|
|
2425
2534
|
return {
|
|
2426
2535
|
schema: {},
|
|
2427
2536
|
imports,
|
|
2428
|
-
resolvedTypeName: "unknown"
|
|
2537
|
+
resolvedTypeName: "unknown",
|
|
2538
|
+
schemaName: void 0
|
|
2429
2539
|
};
|
|
2430
2540
|
}
|
|
2431
2541
|
}
|
|
@@ -3323,6 +3433,8 @@ function buildBody(filteredBodyTypes, requestBody, operationName, context) {
|
|
|
3323
3433
|
const definition = filteredBodyTypes.map(({ value }) => value).join(" | ");
|
|
3324
3434
|
const nonReadonlyDefinition = filteredBodyTypes.some((x) => x.hasReadonlyProps) && definition && context.output.override.preserveReadonlyRequestBodies !== "preserve" ? `NonReadonly<${definition}>` : definition;
|
|
3325
3435
|
let implementation = generalJSTypesWithArray.includes(definition.toLowerCase()) || filteredBodyTypes.length > 1 ? camel(operationName) + context.output.override.components.requestBodies.suffix : camel(definition);
|
|
3436
|
+
const overrideName = getRequestBodyExtensionName(requestBody, context);
|
|
3437
|
+
if (overrideName) implementation = camel(overrideName);
|
|
3326
3438
|
let isOptional = false;
|
|
3327
3439
|
if (implementation) {
|
|
3328
3440
|
implementation = sanitize(implementation, {
|
|
@@ -3376,6 +3488,14 @@ function getBodiesByContentType({ requestBody, operationName, context, contentTy
|
|
|
3376
3488
|
};
|
|
3377
3489
|
});
|
|
3378
3490
|
}
|
|
3491
|
+
function getRequestBodyExtensionName(requestBody, context) {
|
|
3492
|
+
let value;
|
|
3493
|
+
if (isReference(requestBody)) {
|
|
3494
|
+
const { schema } = resolveRef(requestBody, context);
|
|
3495
|
+
value = schema?.["x-codegen-request-body-name"];
|
|
3496
|
+
} else value = requestBody?.["x-codegen-request-body-name"];
|
|
3497
|
+
return typeof value === "string" ? value : void 0;
|
|
3498
|
+
}
|
|
3379
3499
|
const CONTENT_TYPE_SUFFIX_MAP = {
|
|
3380
3500
|
"application/json": "Json",
|
|
3381
3501
|
"multipart/form-data": "FormData",
|
|
@@ -3407,7 +3527,7 @@ function resolveDiscriminators(schemas, context) {
|
|
|
3407
3527
|
} catch {
|
|
3408
3528
|
subTypeSchema = transformedSchemas[mappingValue];
|
|
3409
3529
|
}
|
|
3410
|
-
if (isBoolean$1(subTypeSchema) || propertyName === void 0) continue;
|
|
3530
|
+
if (!subTypeSchema || isBoolean$1(subTypeSchema) || propertyName === void 0) continue;
|
|
3411
3531
|
const property = subTypeSchema.properties?.[propertyName];
|
|
3412
3532
|
if (isBoolean$1(property)) continue;
|
|
3413
3533
|
const schemaProperty = property && !isReference(property) ? property : void 0;
|
|
@@ -3440,9 +3560,13 @@ function resolveDiscriminators(schemas, context) {
|
|
|
3440
3560
|
}
|
|
3441
3561
|
for (const [parentName, parentSchema] of Object.entries(transformedSchemas)) {
|
|
3442
3562
|
if (isBoolean$1(parentSchema)) continue;
|
|
3443
|
-
|
|
3444
|
-
|
|
3563
|
+
const variants = parentSchema.oneOf ?? parentSchema.anyOf;
|
|
3564
|
+
if (!variants || !parentSchema.discriminator) continue;
|
|
3565
|
+
const { propertyName, mapping } = parentSchema.discriminator;
|
|
3445
3566
|
if (!propertyName) continue;
|
|
3567
|
+
const mappedRefs = mapping ? Object.values(mapping) : [];
|
|
3568
|
+
const variantArrayRefs = variants.filter((item) => isReference(item) && typeof item.$ref === "string").map((item) => item.$ref);
|
|
3569
|
+
const variantRefs = [...new Set([...mappedRefs, ...variantArrayRefs])];
|
|
3446
3570
|
const parentProperties = parentSchema.properties;
|
|
3447
3571
|
const parentRequired = parentSchema.required;
|
|
3448
3572
|
const inheritableProps = {};
|
|
@@ -3451,7 +3575,7 @@ function resolveDiscriminators(schemas, context) {
|
|
|
3451
3575
|
}
|
|
3452
3576
|
const inheritableRequired = parentRequired?.filter((key) => key !== propertyName);
|
|
3453
3577
|
const hasInheritableProps = Object.keys(inheritableProps).length > 0;
|
|
3454
|
-
for (const mappingValue of
|
|
3578
|
+
for (const mappingValue of variantRefs) {
|
|
3455
3579
|
let variantSchema;
|
|
3456
3580
|
try {
|
|
3457
3581
|
const { originalName } = getRefInfo(mappingValue, context);
|
|
@@ -3957,6 +4081,8 @@ function getSchemasPath(context) {
|
|
|
3957
4081
|
}
|
|
3958
4082
|
function getSchemaImportPath(refName, context) {
|
|
3959
4083
|
if (context.output.factoryMethods?.mode === "single") return;
|
|
4084
|
+
const importPathBase = getSchemasImportPath(context.output.schemas);
|
|
4085
|
+
if (importPathBase) return joinSafe(importPathBase, conventionName(refName, context.output.namingConvention));
|
|
3960
4086
|
let outputDir = context.output.factoryMethods?.outputDirectory;
|
|
3961
4087
|
let schemasPath = getSchemasPath(context);
|
|
3962
4088
|
if (context.output.workspace) {
|
|
@@ -4041,14 +4167,17 @@ function hasCircularReference(target, sourceName, context, visited = /* @__PURE_
|
|
|
4041
4167
|
function buildPayload(target, context, parents, imports) {
|
|
4042
4168
|
if (isReference$1(target)) return buildRefPayload(target, context, parents, imports);
|
|
4043
4169
|
const schema = target;
|
|
4044
|
-
|
|
4045
|
-
if (schema.
|
|
4046
|
-
if (schema.
|
|
4170
|
+
const payloads = [];
|
|
4171
|
+
if (schema.allOf) payloads.push(buildAllOfPayload(getSchemas(schema.allOf) ?? [], context, parents, imports));
|
|
4172
|
+
else if (schema.oneOf) payloads.push(buildFirstOfPayload(getSchemas(schema.oneOf) ?? [], context, parents, imports));
|
|
4173
|
+
else if (schema.anyOf) payloads.push(buildFirstOfPayload(getSchemas(schema.anyOf) ?? [], context, parents, imports));
|
|
4174
|
+
if (Object.keys(getProperties(schema)).length > 0) payloads.push(buildObjectPayload(schema, context, parents, imports));
|
|
4175
|
+
if (payloads.length > 0) return payloads.length === 1 ? payloads[0] : `Object.assign({}, ${payloads.join(", ")})`;
|
|
4047
4176
|
const { constValue } = getExtendedProps(schema);
|
|
4048
4177
|
if (constValue !== void 0) return formatValue(constValue);
|
|
4049
4178
|
if (schema.default !== void 0) return buildDefaultPayload(schema, context);
|
|
4050
4179
|
const schemaType = inferSchemaType(schema);
|
|
4051
|
-
if (schemaType === "object"
|
|
4180
|
+
if (schemaType === "object") return "{}";
|
|
4052
4181
|
if (schemaType === "array") return buildArrayPayload(schema, context, parents, imports);
|
|
4053
4182
|
return buildPrimitivePayload(schema, schemaType, context);
|
|
4054
4183
|
}
|
|
@@ -4081,10 +4210,11 @@ function buildRefPayload(schema, context, parents, imports) {
|
|
|
4081
4210
|
}
|
|
4082
4211
|
function resolveImportPath(mode, refName, context) {
|
|
4083
4212
|
const baseName = conventionName(refName, context.output.namingConvention);
|
|
4213
|
+
const pkgBase = getSchemasImportPath(context.output.schemas);
|
|
4084
4214
|
switch (mode) {
|
|
4085
|
-
case "split": return `./${baseName}.factory`;
|
|
4086
|
-
case "single-split": return `./${conventionName("factoryMethods", context.output.namingConvention)}`;
|
|
4087
|
-
case "single": return `./${baseName}`;
|
|
4215
|
+
case "split": return pkgBase ? joinSafe(pkgBase, `${baseName}.factory`) : `./${baseName}.factory`;
|
|
4216
|
+
case "single-split": return pkgBase ? joinSafe(pkgBase, conventionName("factoryMethods", context.output.namingConvention)) : `./${conventionName("factoryMethods", context.output.namingConvention)}`;
|
|
4217
|
+
case "single": return pkgBase ? joinSafe(pkgBase, baseName) : `./${baseName}`;
|
|
4088
4218
|
}
|
|
4089
4219
|
}
|
|
4090
4220
|
function buildAllOfPayload(allOf, context, parents, imports) {
|
|
@@ -4414,15 +4544,27 @@ function parseFile(file, name) {
|
|
|
4414
4544
|
ecmaVersion: "latest",
|
|
4415
4545
|
sourceType: "module"
|
|
4416
4546
|
});
|
|
4417
|
-
const
|
|
4418
|
-
|
|
4547
|
+
const foundExport = ast.body.filter((x) => x.type === "ExportNamedDeclaration").map((declaration) => ({
|
|
4548
|
+
declaration,
|
|
4549
|
+
specifier: declaration.specifiers.find((specifier) => specifier.exported.type === "Identifier" && specifier.exported.name === name && specifier.local.type === "Identifier")
|
|
4550
|
+
})).find((item) => item.specifier);
|
|
4551
|
+
const foundSpecifier = foundExport?.specifier;
|
|
4552
|
+
if (foundExport && foundSpecifier && "name" in foundSpecifier.local) {
|
|
4419
4553
|
const exportedFuncName = foundSpecifier.local.name;
|
|
4420
|
-
|
|
4554
|
+
const mutatorInfo = parseFunction(ast, exportedFuncName);
|
|
4555
|
+
if (mutatorInfo) return mutatorInfo;
|
|
4556
|
+
if (foundExport.declaration.source || isImportedBinding(ast, exportedFuncName)) return standardMutatorInfo();
|
|
4421
4557
|
}
|
|
4422
4558
|
} catch {
|
|
4423
4559
|
return;
|
|
4424
4560
|
}
|
|
4425
4561
|
}
|
|
4562
|
+
function isImportedBinding(ast, name) {
|
|
4563
|
+
return ast.body.some((node) => {
|
|
4564
|
+
if (node.type !== "ImportDeclaration") return false;
|
|
4565
|
+
return node.specifiers.some((specifier) => "name" in specifier.local && specifier.local.name === name);
|
|
4566
|
+
});
|
|
4567
|
+
}
|
|
4426
4568
|
function standardMutatorInfo() {
|
|
4427
4569
|
return { numberOfParams: 1 };
|
|
4428
4570
|
}
|
|
@@ -5602,11 +5744,21 @@ async function writeSchemas({ schemaPath, schemas, target, namingConvention, fil
|
|
|
5602
5744
|
}
|
|
5603
5745
|
}
|
|
5604
5746
|
//#endregion
|
|
5747
|
+
//#region src/writers/finalize-mock-implementation.ts
|
|
5748
|
+
function getFinalizeMockImplementationOptions(output, mockOutputs) {
|
|
5749
|
+
const strictSchemaTypeNames = [...new Set((Array.isArray(mockOutputs) ? mockOutputs : [mockOutputs]).flatMap((mockOutput) => mockOutput.strictMockSchemaTypeNames ?? []))];
|
|
5750
|
+
return {
|
|
5751
|
+
mockOptions: output.override.mock,
|
|
5752
|
+
strictSchemaTypeNames: strictSchemaTypeNames.length > 0 ? strictSchemaTypeNames : void 0
|
|
5753
|
+
};
|
|
5754
|
+
}
|
|
5755
|
+
//#endregion
|
|
5605
5756
|
//#region src/writers/generate-imports-for-builder.ts
|
|
5606
5757
|
function generateImportsForBuilder(output, imports, relativeSchemasPath) {
|
|
5758
|
+
const isPackageImport = isObject(output.schemas) && !!output.schemas.importPath;
|
|
5607
5759
|
const isZodSchemaOutput = isObject(output.schemas) && output.schemas.type === "zod";
|
|
5608
5760
|
const schemaFactoryImports = imports.filter((i) => i.schemaFactory);
|
|
5609
|
-
const schemaFactoryImportExtension = getImportExtension(output.fileExtension, output.tsconfig);
|
|
5761
|
+
const schemaFactoryImportExtension = isPackageImport ? "" : getImportExtension(output.fileExtension, output.tsconfig);
|
|
5610
5762
|
const schemaFactoryDeps = schemaFactoryImports.length > 0 ? [{
|
|
5611
5763
|
exports: uniqueBy(schemaFactoryImports, (entry) => `${entry.name}|${entry.alias ?? ""}`),
|
|
5612
5764
|
dependency: joinSafe(relativeSchemasPath, `index.faker${schemaFactoryImportExtension}`)
|
|
@@ -5623,7 +5775,7 @@ function generateImportsForBuilder(output, imports, relativeSchemasPath) {
|
|
|
5623
5775
|
else {
|
|
5624
5776
|
const importsByDependency = /* @__PURE__ */ new Map();
|
|
5625
5777
|
for (const schemaImport of imports.filter((i) => !i.importPath)) {
|
|
5626
|
-
const dependency = joinSafe(relativeSchemasPath, `${conventionName(isZodSchemaOutput ? schemaImport.name : schemaImport.schemaName ?? schemaImport.name, output.namingConvention)}${isZodSchemaOutput ? ".zod" : ""}${getImportExtension(output.fileExtension, output.tsconfig)}`);
|
|
5778
|
+
const dependency = joinSafe(relativeSchemasPath, `${conventionName(isZodSchemaOutput ? schemaImport.name : schemaImport.schemaName ?? schemaImport.name, output.namingConvention)}${isZodSchemaOutput ? ".zod" : ""}${isPackageImport ? "" : getImportExtension(output.fileExtension, output.tsconfig)}`);
|
|
5627
5779
|
if (!importsByDependency.has(dependency)) importsByDependency.set(dependency, []);
|
|
5628
5780
|
importsByDependency.get(dependency)?.push(schemaImport);
|
|
5629
5781
|
}
|
|
@@ -5675,7 +5827,8 @@ function flattenMockOutput$1(full) {
|
|
|
5675
5827
|
return {
|
|
5676
5828
|
type: full.type,
|
|
5677
5829
|
implementation: full.implementation.function + full.implementation.handler,
|
|
5678
|
-
imports: full.imports
|
|
5830
|
+
imports: full.imports,
|
|
5831
|
+
strictMockSchemaTypeNames: full.strictMockSchemaTypeNames
|
|
5679
5832
|
};
|
|
5680
5833
|
}
|
|
5681
5834
|
function generateTarget(builder, options) {
|
|
@@ -5710,6 +5863,7 @@ function generateTarget(builder, options) {
|
|
|
5710
5863
|
target.mockOutputs.push(acc);
|
|
5711
5864
|
}
|
|
5712
5865
|
acc.imports.push(...opMock.imports);
|
|
5866
|
+
if (opMock.strictMockSchemaTypeNames?.length) acc.strictMockSchemaTypeNames = [...new Set([...acc.strictMockSchemaTypeNames ?? [], ...opMock.strictMockSchemaTypeNames])];
|
|
5713
5867
|
acc.implementation.function += opMock.implementation.function;
|
|
5714
5868
|
acc.implementation.handler += opMock.implementation.handler;
|
|
5715
5869
|
if (opMock.implementation.handlerName) {
|
|
@@ -5814,9 +5968,11 @@ async function writeSingleMode({ builder, output, projectName, header, needSchem
|
|
|
5814
5968
|
const { imports, mockOutputs: rawMockOutputs, implementation, mutators, clientMutators, formData, formUrlEncoded, paramsSerializer, paramsFilter, fetchReviver } = generateTarget(builder, output);
|
|
5815
5969
|
const mockOutputs = collapseInlineMockOutputs(rawMockOutputs);
|
|
5816
5970
|
const implementationMock = mockOutputs.map((m) => m.implementation).join("\n\n");
|
|
5971
|
+
const finalizedImplementationMock = builder.finalizeMockImplementation ? builder.finalizeMockImplementation(implementationMock, getFinalizeMockImplementationOptions(output, mockOutputs)) : implementationMock;
|
|
5817
5972
|
const importsMock = mockOutputs.flatMap((m) => m.imports);
|
|
5818
5973
|
let data = header;
|
|
5819
|
-
const
|
|
5974
|
+
const schemaCustomImportPath = getSchemasImportPath(output.schemas);
|
|
5975
|
+
const schemasPath = output.schemas ? schemaCustomImportPath ?? getRelativeImportPath(path, getFileInfo(isString(output.schemas) ? output.schemas : output.schemas.path, { extension: output.fileExtension }).dirname) : void 0;
|
|
5820
5976
|
const isAllowSyntheticDefaultImports = isSyntheticDefaultImportsAllow(output.tsconfig);
|
|
5821
5977
|
const normalizedImports = imports.filter((imp) => {
|
|
5822
5978
|
const searchWords = [imp.alias, imp.name].filter((part) => Boolean(part?.length)).map((part) => escapeRegExp(part)).join("|");
|
|
@@ -5877,7 +6033,7 @@ async function writeSingleMode({ builder, output, projectName, header, needSchem
|
|
|
5877
6033
|
data += `${implementation.trim()}\n`;
|
|
5878
6034
|
if (mockOutputs.length > 0) {
|
|
5879
6035
|
data += "\n\n";
|
|
5880
|
-
data +=
|
|
6036
|
+
data += finalizedImplementationMock;
|
|
5881
6037
|
}
|
|
5882
6038
|
await writeGeneratedFile(path, data);
|
|
5883
6039
|
return [path];
|
|
@@ -5896,7 +6052,8 @@ async function writeSplitMode({ builder, output, projectName, header, needSchema
|
|
|
5896
6052
|
});
|
|
5897
6053
|
const { imports, implementation, mockOutputs, mutators, clientMutators, formData, formUrlEncoded, paramsSerializer, paramsFilter, fetchReviver } = generateTarget(builder, output);
|
|
5898
6054
|
let implementationData = header;
|
|
5899
|
-
const
|
|
6055
|
+
const schemaCustomImportPath = getSchemasImportPath(output.schemas);
|
|
6056
|
+
const relativeSchemasPath = output.schemas ? schemaCustomImportPath ?? getRelativeImportPath(targetPath, getFileInfo(isString(output.schemas) ? output.schemas : output.schemas.path, { extension: output.fileExtension }).dirname) : "./" + filename + ".schemas" + extension.replace(/\.ts$/, "");
|
|
5900
6057
|
const isAllowSyntheticDefaultImports = isSyntheticDefaultImportsAllow(output.tsconfig);
|
|
5901
6058
|
const importsForBuilder = generateImportsForBuilder(output, imports, relativeSchemasPath);
|
|
5902
6059
|
implementationData += builder.imports({
|
|
@@ -5937,28 +6094,42 @@ async function writeSplitMode({ builder, output, projectName, header, needSchema
|
|
|
5937
6094
|
const implementationPath = nodePath.join(dirname, implementationFilename);
|
|
5938
6095
|
await writeGeneratedFile(implementationPath, implementationData);
|
|
5939
6096
|
const mockPaths = [];
|
|
6097
|
+
const writtenMockExtensions = /* @__PURE__ */ new Set();
|
|
5940
6098
|
for (const mockOutput of mockOutputs) {
|
|
5941
6099
|
const entry = output.mock.generators.find((g) => !isFunction(g) && g.type === mockOutput.type);
|
|
5942
6100
|
if (!entry) continue;
|
|
5943
6101
|
const importsMockForBuilder = generateImportsForBuilder(output, mockOutput.imports, relativeSchemasPath);
|
|
5944
6102
|
let mockData = header;
|
|
6103
|
+
const finalizedMockImplementation = builder.finalizeMockImplementation ? builder.finalizeMockImplementation(mockOutput.implementation, getFinalizeMockImplementationOptions(output, mockOutput)) : mockOutput.implementation;
|
|
5945
6104
|
mockData += builder.importsMock({
|
|
5946
|
-
implementation:
|
|
6105
|
+
implementation: finalizedMockImplementation,
|
|
5947
6106
|
imports: importsMockForBuilder,
|
|
5948
6107
|
projectName,
|
|
5949
6108
|
hasSchemaDir: !!output.schemas,
|
|
5950
6109
|
isAllowSyntheticDefaultImports,
|
|
5951
6110
|
options: entry
|
|
5952
6111
|
});
|
|
5953
|
-
mockData += `\n${
|
|
5954
|
-
const
|
|
6112
|
+
mockData += `\n${finalizedMockImplementation}`;
|
|
6113
|
+
const mockExtension = getMockFileExtensionByTypeName(entry);
|
|
6114
|
+
const mockPath = nodePath.join(dirname, filename + "." + mockExtension + extension);
|
|
5955
6115
|
await writeGeneratedFile(mockPath, mockData);
|
|
5956
6116
|
mockPaths.push(mockPath);
|
|
6117
|
+
writtenMockExtensions.add(mockExtension);
|
|
6118
|
+
}
|
|
6119
|
+
const indexMockPaths = [];
|
|
6120
|
+
if (output.mock.indexMockFiles) {
|
|
6121
|
+
const importExtension = getImportExtension(output.fileExtension, output.tsconfig);
|
|
6122
|
+
for (const mockExtension of writtenMockExtensions) {
|
|
6123
|
+
const indexMockPath = nodePath.join(dirname, `index.${mockExtension}${extension}`);
|
|
6124
|
+
await writeGeneratedFile(indexMockPath, `export * from './${filename}.${mockExtension}${importExtension}'\n`);
|
|
6125
|
+
indexMockPaths.push(indexMockPath);
|
|
6126
|
+
}
|
|
5957
6127
|
}
|
|
5958
6128
|
return [
|
|
5959
6129
|
implementationPath,
|
|
5960
6130
|
...schemasPath ? [schemasPath] : [],
|
|
5961
|
-
...mockPaths
|
|
6131
|
+
...mockPaths,
|
|
6132
|
+
...indexMockPaths
|
|
5962
6133
|
];
|
|
5963
6134
|
} catch (error) {
|
|
5964
6135
|
throw new Error(`Oups... 🍻. An Error occurred while splitting => ${String(error)}`, { cause: error });
|
|
@@ -5993,7 +6164,8 @@ function flattenMockOutput(full) {
|
|
|
5993
6164
|
return {
|
|
5994
6165
|
type: full.type,
|
|
5995
6166
|
implementation: full.implementation.function + full.implementation.handler,
|
|
5996
|
-
imports: full.imports
|
|
6167
|
+
imports: full.imports,
|
|
6168
|
+
strictMockSchemaTypeNames: full.strictMockSchemaTypeNames
|
|
5997
6169
|
};
|
|
5998
6170
|
}
|
|
5999
6171
|
function mergeOperationMockOutputs(accMockOutputs, opMockOutputs) {
|
|
@@ -6009,6 +6181,7 @@ function mergeOperationMockOutputs(accMockOutputs, opMockOutputs) {
|
|
|
6009
6181
|
result.push(acc);
|
|
6010
6182
|
}
|
|
6011
6183
|
acc.imports.push(...op.imports);
|
|
6184
|
+
if (op.strictMockSchemaTypeNames?.length) acc.strictMockSchemaTypeNames = [...new Set([...acc.strictMockSchemaTypeNames ?? [], ...op.strictMockSchemaTypeNames])];
|
|
6012
6185
|
acc.implementation.function += op.implementation.function;
|
|
6013
6186
|
acc.implementation.handler += op.implementation.handler;
|
|
6014
6187
|
if (op.implementation.handlerName) {
|
|
@@ -6157,7 +6330,8 @@ async function writeSplitTagsMode({ builder, output, projectName, header, needSc
|
|
|
6157
6330
|
const { imports, implementation, mockOutputs, mutators, clientMutators, formData, fetchReviver, formUrlEncoded, paramsSerializer, paramsFilter } = target;
|
|
6158
6331
|
let implementationData = header;
|
|
6159
6332
|
const importerPath = nodePath.join(dirname, tag, tag + extension);
|
|
6160
|
-
const
|
|
6333
|
+
const schemaCustomImportPath = getSchemasImportPath(output.schemas);
|
|
6334
|
+
const relativeSchemasPath = output.schemas ? schemaCustomImportPath ?? getRelativeImportPath(importerPath, getFileInfo(isString(output.schemas) ? output.schemas : output.schemas.path, { extension: output.fileExtension }).dirname) : "../" + filename + ".schemas" + extension.replace(/\.ts$/, "");
|
|
6161
6335
|
const tagNames = new Set(tagEntries.map(([t]) => t));
|
|
6162
6336
|
const serviceSuffix = OutputClient.ANGULAR === output.client ? ".service" : "";
|
|
6163
6337
|
const importsForBuilder = generateImportsForBuilder(output, imports.map((imp) => {
|
|
@@ -6237,16 +6411,17 @@ async function writeSplitTagsMode({ builder, output, projectName, header, needSc
|
|
|
6237
6411
|
const entry = output.mock.generators.find((g) => !isFunction(g) && g.type === mockOutput.type);
|
|
6238
6412
|
if (!entry) continue;
|
|
6239
6413
|
const importsMockForBuilder = generateImportsForBuilder(output, mockOutput.imports, relativeSchemasPath);
|
|
6414
|
+
const finalizedMockImplementation = builder.finalizeMockImplementation ? builder.finalizeMockImplementation(mockOutput.implementation, getFinalizeMockImplementationOptions(output, mockOutput)) : mockOutput.implementation;
|
|
6240
6415
|
let mockData = header;
|
|
6241
6416
|
mockData += builder.importsMock({
|
|
6242
|
-
implementation:
|
|
6417
|
+
implementation: finalizedMockImplementation,
|
|
6243
6418
|
imports: importsMockForBuilder,
|
|
6244
6419
|
projectName,
|
|
6245
6420
|
hasSchemaDir: !!output.schemas,
|
|
6246
6421
|
isAllowSyntheticDefaultImports,
|
|
6247
6422
|
options: entry
|
|
6248
6423
|
});
|
|
6249
|
-
mockData += `\n${
|
|
6424
|
+
mockData += `\n${finalizedMockImplementation}`;
|
|
6250
6425
|
const mockPath = nodePath.join(dirname, tag, tag + "." + getMockFileExtensionByTypeName(entry) + extension);
|
|
6251
6426
|
await writeGeneratedFile(mockPath, mockData);
|
|
6252
6427
|
mockPaths.push(mockPath);
|
|
@@ -6287,8 +6462,10 @@ async function writeTagsMode({ builder, output, projectName, header, needSchema,
|
|
|
6287
6462
|
const mockOutputs = collapseInlineMockOutputs(rawMockOutputs);
|
|
6288
6463
|
const importsMock = mockOutputs.flatMap((m) => m.imports);
|
|
6289
6464
|
const implementationMock = mockOutputs.map((m) => m.implementation).join("\n\n");
|
|
6465
|
+
const finalizedImplementationMock = builder.finalizeMockImplementation ? builder.finalizeMockImplementation(implementationMock, getFinalizeMockImplementationOptions(output, mockOutputs)) : implementationMock;
|
|
6290
6466
|
let data = header;
|
|
6291
|
-
const
|
|
6467
|
+
const schemaCustomImportPath = getSchemasImportPath(output.schemas);
|
|
6468
|
+
const schemasPathRelative = output.schemas ? schemaCustomImportPath ?? getRelativeImportPath(targetPath, getFileInfo(isString(output.schemas) ? output.schemas : output.schemas.path, { extension: output.fileExtension }).dirname) : "./" + filename + ".schemas" + extension.replace(/\.ts$/, "");
|
|
6292
6469
|
const normalizedImports = imports.filter((imp) => {
|
|
6293
6470
|
const searchWords = [imp.alias, imp.name].filter((part) => Boolean(part?.length)).map((part) => escapeRegExp(part)).join("|");
|
|
6294
6471
|
if (!searchWords) return false;
|
|
@@ -6349,7 +6526,7 @@ async function writeTagsMode({ builder, output, projectName, header, needSchema,
|
|
|
6349
6526
|
data += implementation;
|
|
6350
6527
|
if (mockOutputs.length > 0) {
|
|
6351
6528
|
data += "\n\n";
|
|
6352
|
-
data +=
|
|
6529
|
+
data += finalizedImplementationMock;
|
|
6353
6530
|
}
|
|
6354
6531
|
const implementationPath = nodePath.join(dirname, `${kebab(tag)}${extension}`);
|
|
6355
6532
|
await writeGeneratedFile(implementationPath, data);
|
|
@@ -6360,6 +6537,6 @@ async function writeTagsMode({ builder, output, projectName, header, needSchema,
|
|
|
6360
6537
|
}))).flat();
|
|
6361
6538
|
}
|
|
6362
6539
|
//#endregion
|
|
6363
|
-
export { BODY_TYPE_NAME, DefaultTag, EnumGeneration, ErrorWithTag, FormDataArrayHandling, GetterPropType, LogLevels, NAMED_COMPONENT_SECTIONS, NamingConvention, OutputClient, OutputHttpClient, OutputMockType, OutputMode, PropertySortOrder, RefComponentSuffix, SchemaType, SupportedFormatter, TEMPLATE_TAG_REGEX, URL_REGEX, VERBS_WITH_BODY, Verbs, addDependency, asyncReduce, buildAngularParamsFilterExpression, buildDynamicScope, camel, collectReferencedComponents, combineSchemas, compareVersions, conventionName, count, createDebugger, createLogger, createSuccessMessage, createTypeAliasIfNeeded, dedupeUnionType, dynamicAnchorToParamName, dynamicAnchorsToUniqueParamNames, dynamicImport, escape, escapeRegExp, extractBoundAliasInfo, filterByContentType, filteredVerbs, fixCrossDirectoryImports, fixRegularSchemaImports, generalJSTypes, generalJSTypesWithArray, generateAxiosOptions, generateBodyMutatorConfig, generateBodyOptions, generateComponentDefinition, generateDependencyImports, generateFactory, generateFormDataAndUrlEncodedFunction, generateImports, generateModelInline, generateModelsInline, generateMutator, generateMutatorConfig, generateMutatorImports, generateMutatorRequestOptions, generateOptions, generateParameterDefinition, generateQueryParamsAxiosConfig, generateSchemasDefinition, generateTarget, generateTargetForTags, generateVerbImports, generateVerbOptions, generateVerbsOptions, getAngularFilteredParamsCallExpression, getAngularFilteredParamsExpression, getAngularFilteredParamsHelperBody, getArray, getBaseUrlRuntimeImports, getBodiesByContentType, getBody, getCombinedEnumValue, getDefaultContentType, getDynamicAnchorName, getEnum, getEnumDescriptions, getEnumImplementation, getEnumNames, getEnumUnionFromSchema, getExtension, getFileInfo, getFormDataFieldFileType, getFullRoute, getImportExtension, getIsBodyVerb, getKey, getMockFileExtensionByTypeName, getNumberWord, getObject, getOperationId, getOrvalGeneratedTypes, getParameters, getParams, getParamsInPath, getPropertySafe, getProps, getQueryParams, getRefInfo, getResReqTypes, getResponse, getResponseTypeCategory, getRoute, getRouteAsArray, getScalar, getSuccessResponseType, getTypedResponse, getWarningCount, isBinaryContentType, isBinaryScalarSchema, isBoolean, isComponentRef, isDirectory, isDynamicReference, isFakerMock, isFunction, isModule, isMswMock, isNullish, isNumber, isNumeric, isObject, isReference, isSchema, isString, isStringLike, isSyntheticDefaultImportsAllow, isUrl, isVerb, isVerbose, jsDoc, jsStringEscape, kebab, keyValuePairsToJsDoc, log, logError, logVerbose, logWarning, makeRouteSafe, mergeDeep, mismatchArgsMessage, pascal, removeFilesAndEmptyFolders, resetWarnings, resolveDiscriminators, resolveDynamicRef, resolveExampleRefs, resolveInstalledVersion, resolveInstalledVersions, resolveObject, resolveRef, resolveValue, sanitize, setVerbose, snake, sortByPriority, splitSchemasByType, startMessage, stringify, toObjectString, path_exports as upath, upper, wrapRouteParameters, writeGeneratedFile, writeModelInline, writeModelsInline, writeSchema, writeSchemas, writeSingleMode, writeSplitMode, writeSplitTagsMode, writeTagsMode };
|
|
6540
|
+
export { BODY_TYPE_NAME, DefaultTag, EnumGeneration, ErrorWithTag, FormDataArrayHandling, GetterPropType, LogLevels, NAMED_COMPONENT_SECTIONS, NamingConvention, OutputClient, OutputHttpClient, OutputMockType, OutputMode, PropertySortOrder, RefComponentSuffix, SchemaType, SupportedFormatter, TEMPLATE_TAG_REGEX, URL_REGEX, VERBS_WITH_BODY, Verbs, addDependency, asyncReduce, buildAngularParamsFilterExpression, buildDynamicScope, camel, collectReferencedComponents, combineSchemas, compareVersions, conventionName, count, createDebugger, createLogger, createSuccessMessage, createTypeAliasIfNeeded, dedupeUnionType, dynamicAnchorToParamName, dynamicAnchorsToUniqueParamNames, dynamicImport, escape, escapeRegExp, extractBoundAliasInfo, filterByContentType, filteredVerbs, fixCrossDirectoryImports, fixRegularSchemaImports, generalJSTypes, generalJSTypesWithArray, generateAxiosOptions, generateBodyMutatorConfig, generateBodyOptions, generateComponentDefinition, generateDependencyImports, generateFactory, generateFormDataAndUrlEncodedFunction, generateImports, generateModelInline, generateModelsInline, generateMutator, generateMutatorConfig, generateMutatorImports, generateMutatorRequestOptions, generateOptions, generateParameterDefinition, generateQueryParamsAxiosConfig, generateSchemasDefinition, generateTarget, generateTargetForTags, generateVerbImports, generateVerbOptions, generateVerbsOptions, getAngularFilteredParamsCallExpression, getAngularFilteredParamsExpression, getAngularFilteredParamsHelperBody, getArray, getBaseUrlRuntimeImports, getBodiesByContentType, getBody, getCombinedEnumValue, getDefaultContentType, getDynamicAnchorName, getEnum, getEnumDescriptions, getEnumImplementation, getEnumNames, getEnumUnionFromSchema, getExtension, getFileInfo, getFormDataFieldFileType, getFullRoute, getImportExtension, getIsBodyVerb, getKey, getMockFileExtensionByTypeName, getNumberWord, getObject, getOperationId, getOrvalGeneratedTypes, getParameters, getParams, getParamsInPath, getPropertySafe, getProps, getQueryParams, getRefInfo, getResReqTypes, getResponse, getResponseTypeCategory, getRoute, getRouteAsArray, getScalar, getSchemasImportPath, getSuccessResponseType, getTypedResponse, getWarningCount, isBinaryContentType, isBinaryScalarSchema, isBoolean, isComponentRef, isDirectory, isDynamicReference, isFakerMock, isFunction, isModule, isMswMock, isNullish, isNumber, isNumeric, isObject, isReference, isSchema, isString, isStringLike, isSyntheticDefaultImportsAllow, isUrl, isVerb, isVerbose, jsDoc, jsStringEscape, jsStringLiteralEscape, kebab, keyValuePairsToJsDoc, log, logError, logVerbose, logWarning, makeRouteSafe, mergeDeep, mismatchArgsMessage, pascal, removeFilesAndEmptyFolders, resetWarnings, resolveDiscriminators, resolveDynamicRef, resolveExampleRefs, resolveInstalledVersion, resolveInstalledVersions, resolveObject, resolveRef, resolveValue, sanitize, setVerbose, snake, sortByPriority, splitSchemasByType, startMessage, stringify, toObjectString, path_exports as upath, upper, wrapRouteParameters, writeGeneratedFile, writeModelInline, writeModelsInline, writeSchema, writeSchemas, writeSingleMode, writeSplitMode, writeSplitTagsMode, writeTagsMode };
|
|
6364
6541
|
|
|
6365
6542
|
//# sourceMappingURL=index.mjs.map
|