@kubb/swagger-ts 1.15.0-canary.20231112T135108 → 2.0.0-alpha.10

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,43 +1,71 @@
1
1
  import { createRequire } from 'module';
2
- import pathParser from 'path';
3
- import { createPlugin, getDependedPlugins, getPathMode, renderTemplate, getRelativePath, timeout, SchemaGenerator, getUniqueName, nameSorter, combineCodes } from '@kubb/core';
4
- import { pluginName as pluginName$1, resolve as resolve$1, isReference, OasBuilder, ImportsGenerator, OperationGenerator as OperationGenerator$1, useResolve as useResolve$1 } from '@kubb/swagger';
2
+ import path from 'path';
3
+ import { createPlugin, PluginManager, FileManager, SchemaGenerator } from '@kubb/core';
4
+ import { renderTemplate, getRelativePath, transformers, getUniqueName } from '@kubb/core/utils';
5
+ import { pluginName as pluginName$1, OasBuilder, ImportsGenerator, OperationGenerator as OperationGenerator$1, resolve } from '@kubb/swagger';
5
6
  import { camelCase, camelCaseTransformMerge, pascalCase, pascalCaseTransformMerge } from 'change-case';
6
- import { createTypeAliasDeclaration, modifiers, createOmitDeclaration, appendJSDocToNode, createUnionDeclaration, createPropertySignature, createIndexSignature, createIntersectionDeclaration, createEnumDeclaration, createTupleDeclaration, print, createImportDeclaration } from '@kubb/parser';
7
- import ts from 'typescript';
7
+ import { print } from '@kubb/parser';
8
+ import * as factory from '@kubb/parser/factory';
9
+ import { refsSorter, isReference } from '@kubb/swagger/utils';
8
10
 
9
11
  createRequire(import.meta.url);
10
- var { factory } = ts;
11
- var keywordTypeNodes = {
12
- any: factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),
13
- number: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
14
- integer: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
15
- object: factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword),
16
- string: factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
17
- boolean: factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword),
18
- undefined: factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
19
- null: factory.createLiteralTypeNode(factory.createToken(ts.SyntaxKind.NullKeyword))
12
+
13
+ var __accessCheck = (obj, member, msg) => {
14
+ if (!member.has(obj))
15
+ throw TypeError("Cannot " + msg);
20
16
  };
21
- function resolve(props) {
22
- return resolve$1({ ...props, pluginName });
23
- }
24
-
25
- // src/generators/TypeGenerator.ts
26
- var { factory: factory2 } = ts;
27
- var TypeGenerator = class _TypeGenerator extends SchemaGenerator {
28
- // Collect the types of all referenced schemas so we can export them later
29
- static usedEnumNames = {};
30
- refs = {};
31
- extraNodes = [];
32
- aliases = [];
33
- // Keep track of already used type aliases
34
- usedAliasNames = {};
35
- caseOptions = {
36
- delimiter: "",
37
- stripRegexp: /[^A-Z0-9$]/gi
38
- };
39
- constructor(options = { withJSDocs: true, resolveName: ({ name }) => name, enumType: "asConst", dateType: "string", optionalType: "questionToken" }) {
17
+ var __privateGet = (obj, member, getter) => {
18
+ __accessCheck(obj, member, "read from private field");
19
+ return getter ? getter.call(obj) : member.get(obj);
20
+ };
21
+ var __privateAdd = (obj, member, value) => {
22
+ if (member.has(obj))
23
+ throw TypeError("Cannot add the same private member more than once");
24
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
25
+ };
26
+ var __privateMethod = (obj, member, method) => {
27
+ __accessCheck(obj, member, "access private method");
28
+ return method;
29
+ };
30
+ var _usedAliasNames, _caseOptions, _getTypeFromSchema, getTypeFromSchema_fn, _getTypeFromProperties, getTypeFromProperties_fn, _getRefAlias, getRefAlias_fn, _getBaseTypeFromSchema, getBaseTypeFromSchema_fn;
31
+ var TypeGenerator = class extends SchemaGenerator {
32
+ constructor(options = {
33
+ usedEnumNames: {},
34
+ withJSDocs: true,
35
+ resolveName: ({ name }) => name,
36
+ enumType: "asConst",
37
+ dateType: "string",
38
+ optionalType: "questionToken"
39
+ }) {
40
40
  super(options);
41
+ /**
42
+ * Creates a type node from a given schema.
43
+ * Delegates to getBaseTypeFromSchema internally and
44
+ * optionally adds a union with null.
45
+ */
46
+ __privateAdd(this, _getTypeFromSchema);
47
+ /**
48
+ * Recursively creates a type literal with the given props.
49
+ */
50
+ __privateAdd(this, _getTypeFromProperties);
51
+ /**
52
+ * Create a type alias for the schema referenced by the given ReferenceObject
53
+ */
54
+ __privateAdd(this, _getRefAlias);
55
+ /**
56
+ * This is the very core of the OpenAPI to TS conversion - it takes a
57
+ * schema and returns the appropriate type.
58
+ */
59
+ __privateAdd(this, _getBaseTypeFromSchema);
60
+ this.refs = {};
61
+ this.extraNodes = [];
62
+ this.aliases = [];
63
+ // Keep track of already used type aliases
64
+ __privateAdd(this, _usedAliasNames, {});
65
+ __privateAdd(this, _caseOptions, {
66
+ delimiter: "",
67
+ stripRegexp: /[^A-Z0-9$]/gi
68
+ });
41
69
  return this;
42
70
  }
43
71
  build({
@@ -47,18 +75,18 @@ var TypeGenerator = class _TypeGenerator extends SchemaGenerator {
47
75
  keysToOmit
48
76
  }) {
49
77
  const nodes = [];
50
- const type = this.#getTypeFromSchema(schema, baseName);
78
+ const type = __privateMethod(this, _getTypeFromSchema, getTypeFromSchema_fn).call(this, schema, baseName);
51
79
  if (!type) {
52
80
  return this.extraNodes;
53
81
  }
54
- const node = createTypeAliasDeclaration({
55
- modifiers: [modifiers.export],
56
- name: this.options.resolveName({ name: baseName, pluginName }) || baseName,
57
- type: keysToOmit?.length ? createOmitDeclaration({ keys: keysToOmit, type, nonNullable: true }) : type
82
+ const node = factory.createTypeAliasDeclaration({
83
+ modifiers: [factory.modifiers.export],
84
+ name: this.options.resolveName({ name: baseName }) || baseName,
85
+ type: keysToOmit?.length ? factory.createOmitDeclaration({ keys: keysToOmit, type, nonNullable: true }) : type
58
86
  });
59
87
  if (description) {
60
88
  nodes.push(
61
- appendJSDocToNode({
89
+ factory.appendJSDocToNode({
62
90
  node,
63
91
  comments: [`@description ${description}`]
64
92
  })
@@ -73,232 +101,211 @@ var TypeGenerator = class _TypeGenerator extends SchemaGenerator {
73
101
  );
74
102
  return [...this.extraNodes, ...filterdNodes];
75
103
  }
76
- /**
77
- * Creates a type node from a given schema.
78
- * Delegates to getBaseTypeFromSchema internally and
79
- * optionally adds a union with null.
80
- */
81
- #getTypeFromSchema(schema, name) {
82
- const type = this.#getBaseTypeFromSchema(schema, name);
104
+ };
105
+ _usedAliasNames = new WeakMap();
106
+ _caseOptions = new WeakMap();
107
+ _getTypeFromSchema = new WeakSet();
108
+ getTypeFromSchema_fn = function(schema, name) {
109
+ const type = __privateMethod(this, _getBaseTypeFromSchema, getBaseTypeFromSchema_fn).call(this, schema, name);
110
+ if (!type) {
111
+ return null;
112
+ }
113
+ if (schema && !schema.nullable) {
114
+ return type;
115
+ }
116
+ return factory.createUnionDeclaration({ nodes: [type, factory.keywordTypeNodes.null] });
117
+ };
118
+ _getTypeFromProperties = new WeakSet();
119
+ getTypeFromProperties_fn = function(baseSchema, baseName) {
120
+ const { optionalType } = this.options;
121
+ const properties = baseSchema?.properties || {};
122
+ const required = baseSchema?.required;
123
+ const additionalProperties = baseSchema?.additionalProperties;
124
+ const members = Object.keys(properties).map((name) => {
125
+ const schema = properties[name];
126
+ const isRequired = required && required.includes(name);
127
+ let type = __privateMethod(this, _getTypeFromSchema, getTypeFromSchema_fn).call(this, schema, this.options.resolveName({ name: `${baseName || ""} ${name}` }));
83
128
  if (!type) {
84
129
  return null;
85
130
  }
86
- if (schema && !schema.nullable) {
87
- return type;
131
+ if (!isRequired && ["undefined", "questionTokenAndUndefined"].includes(optionalType)) {
132
+ type = factory.createUnionDeclaration({ nodes: [type, factory.keywordTypeNodes.undefined] });
88
133
  }
89
- return createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] });
90
- }
91
- /**
92
- * Recursively creates a type literal with the given props.
93
- */
94
- #getTypeFromProperties(baseSchema, baseName) {
95
- const { optionalType } = this.options;
96
- const properties = baseSchema?.properties || {};
97
- const required = baseSchema?.required;
98
- const additionalProperties = baseSchema?.additionalProperties;
99
- const members = Object.keys(properties).map((name) => {
100
- const schema = properties[name];
101
- const isRequired = required && required.includes(name);
102
- let type = this.#getTypeFromSchema(schema, this.options.resolveName({ name: `${baseName || ""} ${name}`, pluginName }));
103
- if (!type) {
104
- return null;
105
- }
106
- if (!isRequired && ["undefined", "questionTokenAndUndefined"].includes(optionalType)) {
107
- type = createUnionDeclaration({ nodes: [type, keywordTypeNodes.undefined] });
108
- }
109
- const propertySignature = createPropertySignature({
110
- questionToken: ["questionToken", "questionTokenAndUndefined"].includes(optionalType) && !isRequired,
111
- name,
112
- type,
113
- readOnly: schema.readOnly
114
- });
115
- if (this.options.withJSDocs) {
116
- return appendJSDocToNode({
117
- node: propertySignature,
118
- comments: [
119
- schema.description ? `@description ${schema.description}` : void 0,
120
- schema.type ? `@type ${schema.type}${isRequired ? "" : " | undefined"} ${schema.format || ""}` : void 0,
121
- schema.example ? `@example ${schema.example}` : void 0,
122
- schema.deprecated ? `@deprecated` : void 0,
123
- schema.default !== void 0 && typeof schema.default === "string" ? `@default '${schema.default}'` : void 0,
124
- schema.default !== void 0 && typeof schema.default !== "string" ? `@default ${schema.default}` : void 0
125
- ].filter(Boolean)
126
- });
127
- }
128
- return propertySignature;
134
+ const propertySignature = factory.createPropertySignature({
135
+ questionToken: ["questionToken", "questionTokenAndUndefined"].includes(optionalType) && !isRequired,
136
+ name,
137
+ type,
138
+ readOnly: schema.readOnly
129
139
  });
130
- if (additionalProperties) {
131
- const type = additionalProperties === true ? keywordTypeNodes.any : this.#getTypeFromSchema(additionalProperties);
132
- if (type) {
133
- members.push(createIndexSignature(type));
134
- }
135
- }
136
- return factory2.createTypeLiteralNode(members.filter(Boolean));
137
- }
138
- /**
139
- * Create a type alias for the schema referenced by the given ReferenceObject
140
- */
141
- #getRefAlias(obj, baseName) {
142
- const { $ref } = obj;
143
- let ref = this.refs[$ref];
144
- if (ref) {
145
- return factory2.createTypeReferenceNode(ref.propertyName, void 0);
146
- }
147
- const originalName = getUniqueName($ref.replace(/.+\//, ""), this.usedAliasNames);
148
- const propertyName = this.options.resolveName({ name: originalName, pluginName }) || originalName;
149
- ref = this.refs[$ref] = {
150
- propertyName,
151
- originalName
152
- };
153
- return factory2.createTypeReferenceNode(ref.propertyName, void 0);
154
- }
155
- /**
156
- * This is the very core of the OpenAPI to TS conversion - it takes a
157
- * schema and returns the appropriate type.
158
- */
159
- #getBaseTypeFromSchema(schema, baseName) {
160
- if (!schema) {
161
- return keywordTypeNodes.any;
140
+ if (this.options.withJSDocs) {
141
+ return factory.appendJSDocToNode({
142
+ node: propertySignature,
143
+ comments: [
144
+ schema.description ? `@description ${schema.description}` : void 0,
145
+ schema.type ? `@type ${schema.type}${isRequired ? "" : " | undefined"} ${schema.format || ""}` : void 0,
146
+ schema.example ? `@example ${schema.example}` : void 0,
147
+ schema.deprecated ? `@deprecated` : void 0,
148
+ schema.default !== void 0 && typeof schema.default === "string" ? `@default '${schema.default}'` : void 0,
149
+ schema.default !== void 0 && typeof schema.default !== "string" ? `@default ${schema.default}` : void 0
150
+ ].filter(Boolean)
151
+ });
162
152
  }
163
- if (isReference(schema)) {
164
- return this.#getRefAlias(schema, baseName);
153
+ return propertySignature;
154
+ });
155
+ if (additionalProperties) {
156
+ const type = additionalProperties === true ? factory.keywordTypeNodes.any : __privateMethod(this, _getTypeFromSchema, getTypeFromSchema_fn).call(this, additionalProperties);
157
+ if (type) {
158
+ members.push(factory.createIndexSignature(type));
165
159
  }
166
- if (schema.oneOf) {
167
- const schemaWithoutOneOf = { ...schema, oneOf: void 0 };
168
- const union = createUnionDeclaration({
169
- withParentheses: true,
170
- nodes: schema.oneOf.map((item) => {
171
- return this.#getBaseTypeFromSchema(item);
172
- }).filter((item) => {
173
- return item && item !== keywordTypeNodes.any;
174
- })
160
+ }
161
+ return factory.createTypeLiteralNode(members.filter(Boolean));
162
+ };
163
+ _getRefAlias = new WeakSet();
164
+ getRefAlias_fn = function(obj, _baseName) {
165
+ const { $ref } = obj;
166
+ let ref = this.refs[$ref];
167
+ if (ref) {
168
+ return factory.createTypeReferenceNode(ref.propertyName, void 0);
169
+ }
170
+ const originalName = getUniqueName($ref.replace(/.+\//, ""), __privateGet(this, _usedAliasNames));
171
+ const propertyName = this.options.resolveName({ name: originalName }) || originalName;
172
+ ref = this.refs[$ref] = {
173
+ propertyName,
174
+ originalName
175
+ };
176
+ return factory.createTypeReferenceNode(ref.propertyName, void 0);
177
+ };
178
+ _getBaseTypeFromSchema = new WeakSet();
179
+ getBaseTypeFromSchema_fn = function(schema, baseName) {
180
+ if (!schema) {
181
+ return factory.keywordTypeNodes.any;
182
+ }
183
+ if (isReference(schema)) {
184
+ return __privateMethod(this, _getRefAlias, getRefAlias_fn).call(this, schema, baseName);
185
+ }
186
+ if (schema.oneOf) {
187
+ const schemaWithoutOneOf = { ...schema, oneOf: void 0 };
188
+ const union = factory.createUnionDeclaration({
189
+ withParentheses: true,
190
+ nodes: schema.oneOf.map((item) => {
191
+ return __privateMethod(this, _getBaseTypeFromSchema, getBaseTypeFromSchema_fn).call(this, item);
192
+ }).filter((item) => {
193
+ return item && item !== factory.keywordTypeNodes.any;
194
+ })
195
+ });
196
+ if (schemaWithoutOneOf.properties) {
197
+ return factory.createIntersectionDeclaration({
198
+ nodes: [__privateMethod(this, _getBaseTypeFromSchema, getBaseTypeFromSchema_fn).call(this, schemaWithoutOneOf, baseName), union].filter(Boolean)
175
199
  });
176
- if (schemaWithoutOneOf.properties) {
177
- return createIntersectionDeclaration({
178
- nodes: [this.#getBaseTypeFromSchema(schemaWithoutOneOf, baseName), union].filter(Boolean)
179
- });
180
- }
181
- return union;
182
200
  }
183
- if (schema.anyOf) {
184
- const schemaWithoutAnyOf = { ...schema, anyOf: void 0 };
185
- const union = createUnionDeclaration({
186
- withParentheses: true,
187
- nodes: schema.anyOf.map((item) => {
188
- return this.#getBaseTypeFromSchema(item);
189
- }).filter((item) => {
190
- return item && item !== keywordTypeNodes.any;
191
- })
201
+ return union;
202
+ }
203
+ if (schema.anyOf) {
204
+ const schemaWithoutAnyOf = { ...schema, anyOf: void 0 };
205
+ const union = factory.createUnionDeclaration({
206
+ withParentheses: true,
207
+ nodes: schema.anyOf.map((item) => {
208
+ return __privateMethod(this, _getBaseTypeFromSchema, getBaseTypeFromSchema_fn).call(this, item);
209
+ }).filter((item) => {
210
+ return item && item !== factory.keywordTypeNodes.any;
211
+ })
212
+ });
213
+ if (schemaWithoutAnyOf.properties) {
214
+ return factory.createIntersectionDeclaration({
215
+ nodes: [__privateMethod(this, _getBaseTypeFromSchema, getBaseTypeFromSchema_fn).call(this, schemaWithoutAnyOf, baseName), union].filter(Boolean)
192
216
  });
193
- if (schemaWithoutAnyOf.properties) {
194
- return createIntersectionDeclaration({
195
- nodes: [this.#getBaseTypeFromSchema(schemaWithoutAnyOf, baseName), union].filter(Boolean)
196
- });
197
- }
198
- return union;
199
217
  }
200
- if (schema.allOf) {
201
- const schemaWithoutAllOf = { ...schema, allOf: void 0 };
202
- const and = createIntersectionDeclaration({
203
- withParentheses: true,
204
- nodes: schema.allOf.map((item) => {
205
- return this.#getBaseTypeFromSchema(item);
206
- }).filter((item) => {
207
- return item && item !== keywordTypeNodes.any;
208
- })
218
+ return union;
219
+ }
220
+ if (schema.allOf) {
221
+ const schemaWithoutAllOf = { ...schema, allOf: void 0 };
222
+ const and = factory.createIntersectionDeclaration({
223
+ withParentheses: true,
224
+ nodes: schema.allOf.map((item) => {
225
+ return __privateMethod(this, _getBaseTypeFromSchema, getBaseTypeFromSchema_fn).call(this, item);
226
+ }).filter((item) => {
227
+ return item && item !== factory.keywordTypeNodes.any;
228
+ })
229
+ });
230
+ if (schemaWithoutAllOf.properties) {
231
+ return factory.createIntersectionDeclaration({
232
+ nodes: [__privateMethod(this, _getBaseTypeFromSchema, getBaseTypeFromSchema_fn).call(this, schemaWithoutAllOf, baseName), and].filter(Boolean)
209
233
  });
210
- if (schemaWithoutAllOf.properties) {
211
- return createIntersectionDeclaration({
212
- nodes: [this.#getBaseTypeFromSchema(schemaWithoutAllOf, baseName), and].filter(Boolean)
213
- });
214
- }
215
- return and;
216
- }
217
- if (schema.enum && baseName) {
218
- const enumName = getUniqueName(baseName, _TypeGenerator.usedEnumNames);
219
- let enums = [...new Set(schema.enum)].map((key) => [key, key]);
220
- if ("x-enumNames" in schema) {
221
- enums = [...new Set(schema["x-enumNames"])].map((key, index) => {
222
- return [key, schema.enum?.[index]];
223
- });
224
- }
225
- this.extraNodes.push(
226
- ...createEnumDeclaration({
227
- name: camelCase(enumName, this.caseOptions),
228
- typeName: this.options.resolveName({ name: enumName, pluginName }),
229
- enums,
230
- type: this.options.enumType
231
- })
232
- );
233
- return factory2.createTypeReferenceNode(this.options.resolveName({ name: enumName, pluginName }), void 0);
234
234
  }
235
- if (schema.enum) {
236
- return createUnionDeclaration({
237
- nodes: schema.enum.map((name) => {
238
- return factory2.createLiteralTypeNode(typeof name === "number" ? factory2.createNumericLiteral(name) : factory2.createStringLiteral(`${name}`));
239
- })
235
+ return and;
236
+ }
237
+ if (schema.enum && baseName) {
238
+ const enumName = getUniqueName(baseName, this.options.usedEnumNames);
239
+ let enums = [...new Set(schema.enum)].map((key) => [key, key]);
240
+ if ("x-enumNames" in schema) {
241
+ enums = [...new Set(schema["x-enumNames"])].map((key, index) => {
242
+ return [key, schema.enum?.[index]];
240
243
  });
241
244
  }
242
- if ("items" in schema) {
243
- const node = this.#getTypeFromSchema(schema.items, baseName);
244
- if (node) {
245
- return factory2.createArrayTypeNode(node);
246
- }
245
+ this.extraNodes.push(
246
+ ...factory.createEnumDeclaration({
247
+ name: camelCase(enumName, __privateGet(this, _caseOptions)),
248
+ typeName: this.options.resolveName({ name: enumName }),
249
+ enums,
250
+ type: this.options.enumType
251
+ })
252
+ );
253
+ return factory.createTypeReferenceNode(this.options.resolveName({ name: enumName }), void 0);
254
+ }
255
+ if (schema.enum) {
256
+ return factory.createUnionDeclaration({
257
+ nodes: schema.enum.map((name) => {
258
+ return factory.createLiteralTypeNode(typeof name === "number" ? factory.createNumericLiteral(name) : factory.createStringLiteral(`${name}`));
259
+ })
260
+ });
261
+ }
262
+ if ("items" in schema) {
263
+ const node = __privateMethod(this, _getTypeFromSchema, getTypeFromSchema_fn).call(this, schema.items, baseName);
264
+ if (node) {
265
+ return factory.createArrayTypeNode(node);
247
266
  }
248
- if ("prefixItems" in schema) {
249
- const prefixItems = schema.prefixItems;
250
- return createTupleDeclaration({
251
- nodes: prefixItems.map((item) => {
252
- return this.#getBaseTypeFromSchema(item, void 0);
253
- })
267
+ }
268
+ if ("prefixItems" in schema) {
269
+ const prefixItems = schema.prefixItems;
270
+ return factory.createTupleDeclaration({
271
+ nodes: prefixItems.map((item) => {
272
+ return __privateMethod(this, _getBaseTypeFromSchema, getBaseTypeFromSchema_fn).call(this, item, void 0);
273
+ })
274
+ });
275
+ }
276
+ if (schema.properties || schema.additionalProperties) {
277
+ return __privateMethod(this, _getTypeFromProperties, getTypeFromProperties_fn).call(this, schema, baseName);
278
+ }
279
+ if (schema.type) {
280
+ if (Array.isArray(schema.type)) {
281
+ const [type, nullable] = schema.type;
282
+ return factory.createUnionDeclaration({
283
+ nodes: [
284
+ __privateMethod(this, _getBaseTypeFromSchema, getBaseTypeFromSchema_fn).call(this, {
285
+ ...schema,
286
+ type
287
+ }, baseName),
288
+ nullable ? factory.createLiteralTypeNode(factory.createNull()) : void 0
289
+ ].filter(Boolean)
254
290
  });
255
291
  }
256
- if (schema.properties || schema.additionalProperties) {
257
- return this.#getTypeFromProperties(schema, baseName);
292
+ if (this.options.dateType === "date" && ["date", "date-time"].some((item) => item === schema.format)) {
293
+ return factory.createTypeReferenceNode(factory.createIdentifier("Date"));
258
294
  }
259
- if (schema.type) {
260
- if (Array.isArray(schema.type)) {
261
- const [type, nullable] = schema.type;
262
- return createUnionDeclaration({
263
- nodes: [
264
- this.#getBaseTypeFromSchema(
265
- {
266
- ...schema,
267
- type
268
- },
269
- baseName
270
- ),
271
- nullable ? factory2.createLiteralTypeNode(factory2.createNull()) : void 0
272
- ].filter(Boolean)
273
- });
274
- }
275
- if (this.options.dateType === "date" && ["date", "date-time"].some((item) => item === schema.format)) {
276
- return factory2.createTypeReferenceNode(factory2.createIdentifier("Date"));
277
- }
278
- if (schema.type in keywordTypeNodes) {
279
- return keywordTypeNodes[schema.type];
280
- }
295
+ if (schema.type in factory.keywordTypeNodes) {
296
+ return factory.keywordTypeNodes[schema.type];
281
297
  }
282
- if (schema.format === "binary") {
283
- return factory2.createTypeReferenceNode("Blob", []);
284
- }
285
- if ("const" in schema && schema["const"] !== void 0 && typeof schema["const"] === "string") {
286
- return factory2.createLiteralTypeNode(factory2.createStringLiteral(schema["const"]));
287
- }
288
- return keywordTypeNodes.any;
289
298
  }
299
+ if (schema.format === "binary") {
300
+ return factory.createTypeReferenceNode("Blob", []);
301
+ }
302
+ if ("const" in schema && schema["const"] !== void 0 && typeof schema["const"] === "string") {
303
+ return factory.createLiteralTypeNode(factory.createStringLiteral(schema["const"]));
304
+ }
305
+ return factory.keywordTypeNodes.any;
290
306
  };
291
307
 
292
308
  // src/builders/TypeBuilder.ts
293
- function refsSorter(a, b) {
294
- if (Object.keys(a.import.refs)?.length < Object.keys(b.import.refs)?.length) {
295
- return -1;
296
- }
297
- if (Object.keys(a.import.refs)?.length > Object.keys(b.import.refs)?.length) {
298
- return 1;
299
- }
300
- return 0;
301
- }
302
309
  var TypeBuilder = class extends OasBuilder {
303
310
  configure(options) {
304
311
  if (options) {
@@ -311,8 +318,9 @@ var TypeBuilder = class extends OasBuilder {
311
318
  }
312
319
  print(name) {
313
320
  const codes = [];
314
- const generated = this.items.filter((operationSchema) => name ? operationSchema.name === name : true).sort(nameSorter).map((operationSchema) => {
321
+ const generated = this.items.filter((operationSchema) => name ? operationSchema.name === name : true).sort(transformers.nameSorter).map((operationSchema) => {
315
322
  const generator = new TypeGenerator({
323
+ usedEnumNames: this.options.usedEnumNames,
316
324
  withJSDocs: this.options.withJSDocs,
317
325
  resolveName: this.options.resolveName,
318
326
  enumType: this.options.enumType,
@@ -341,7 +349,7 @@ var TypeBuilder = class extends OasBuilder {
341
349
  const importMeta = importsGenerator.build(generated.map((item) => item.import));
342
350
  if (importMeta) {
343
351
  const nodes = importMeta.map((item) => {
344
- return createImportDeclaration({
352
+ return factory.createImportDeclaration({
345
353
  name: [{ propertyName: item.ref.propertyName }],
346
354
  path: item.path,
347
355
  isTypeOnly: true
@@ -350,78 +358,87 @@ var TypeBuilder = class extends OasBuilder {
350
358
  codes.unshift(print(nodes));
351
359
  }
352
360
  }
353
- return combineCodes(codes);
361
+ return transformers.combineCodes(codes);
354
362
  }
355
363
  };
364
+ var _printCombinedSchema, printCombinedSchema_fn;
356
365
  var OperationGenerator = class extends OperationGenerator$1 {
366
+ constructor() {
367
+ super(...arguments);
368
+ __privateAdd(this, _printCombinedSchema);
369
+ }
357
370
  resolve(operation) {
358
- const { pluginManager } = this.context;
359
- return resolve$1({
371
+ const { pluginManager, plugin } = this.context;
372
+ return resolve({
360
373
  operation,
361
374
  resolveName: pluginManager.resolveName,
362
375
  resolvePath: pluginManager.resolvePath,
363
- pluginName
376
+ pluginKey: plugin?.key
364
377
  });
365
378
  }
366
379
  async all() {
367
380
  return null;
368
381
  }
369
382
  async get(operation, schemas, options) {
370
- const { mode, enumType, dateType, optionalType } = options;
371
- const { pluginManager } = this.context;
383
+ const { mode, enumType, dateType, optionalType, usedEnumNames } = options;
384
+ const { pluginManager, plugin } = this.context;
372
385
  const type = this.resolve(operation);
373
386
  const fileResolver = (name) => {
374
- const root = pluginManager.resolvePath({ baseName: type.baseName, pluginName, options: { tag: operation.getTags()[0]?.name } });
387
+ const root = pluginManager.resolvePath({ baseName: type.baseName, pluginKey: plugin?.key, options: { tag: operation.getTags()[0]?.name } });
375
388
  const resolvedTypeId = pluginManager.resolvePath({
376
389
  baseName: `${name}.ts`,
377
- pluginName
390
+ pluginKey: plugin?.key
378
391
  });
379
392
  return getRelativePath(root, resolvedTypeId);
380
393
  };
381
394
  const source = new TypeBuilder({
395
+ usedEnumNames,
382
396
  fileResolver: mode === "file" ? void 0 : fileResolver,
383
397
  withJSDocs: true,
384
- resolveName: pluginManager.resolveName,
398
+ resolveName: (params) => pluginManager.resolveName({ ...params, pluginKey: plugin?.key }),
385
399
  enumType,
386
400
  optionalType,
387
401
  dateType
388
402
  }).add(schemas.pathParams).add(schemas.queryParams).add(schemas.headerParams).add(schemas.response).add(schemas.errors).configure().print();
403
+ const combinedSchemaSource = __privateMethod(this, _printCombinedSchema, printCombinedSchema_fn).call(this, type.name, operation, schemas);
389
404
  return {
390
405
  path: type.path,
391
406
  baseName: type.baseName,
392
- source,
407
+ source: [source, combinedSchemaSource].join("\n"),
393
408
  meta: {
394
- pluginName,
409
+ pluginKey: plugin.key,
395
410
  tag: operation.getTags()[0]?.name
396
411
  }
397
412
  };
398
413
  }
399
414
  async post(operation, schemas, options) {
400
- const { mode, enumType, dateType, optionalType } = options;
401
- const { pluginManager } = this.context;
415
+ const { mode, enumType, dateType, optionalType, usedEnumNames } = options;
416
+ const { pluginManager, plugin } = this.context;
402
417
  const type = this.resolve(operation);
403
418
  const fileResolver = (name) => {
404
- const root = pluginManager.resolvePath({ baseName: type.baseName, pluginName, options: { tag: operation.getTags()[0]?.name } });
419
+ const root = pluginManager.resolvePath({ baseName: type.baseName, pluginKey: plugin?.key, options: { tag: operation.getTags()[0]?.name } });
405
420
  const resolvedTypeId = pluginManager.resolvePath({
406
421
  baseName: `${name}.ts`,
407
- pluginName
422
+ pluginKey: plugin?.key
408
423
  });
409
424
  return getRelativePath(root, resolvedTypeId);
410
425
  };
411
426
  const source = new TypeBuilder({
427
+ usedEnumNames,
412
428
  fileResolver: mode === "file" ? void 0 : fileResolver,
413
429
  withJSDocs: true,
414
- resolveName: pluginManager.resolveName,
430
+ resolveName: (params) => pluginManager.resolveName({ ...params, pluginKey: plugin?.key }),
415
431
  enumType,
416
432
  optionalType,
417
433
  dateType
418
434
  }).add(schemas.pathParams).add(schemas.queryParams).add(schemas.headerParams).add(schemas.request).add(schemas.response).add(schemas.errors).configure().print();
435
+ const combinedSchemaSource = __privateMethod(this, _printCombinedSchema, printCombinedSchema_fn).call(this, type.name, operation, schemas);
419
436
  return {
420
437
  path: type.path,
421
438
  baseName: type.baseName,
422
- source,
439
+ source: [source, combinedSchemaSource].join("\n"),
423
440
  meta: {
424
- pluginName,
441
+ pluginKey: plugin.key,
425
442
  tag: operation.getTags()[0]?.name
426
443
  }
427
444
  };
@@ -436,67 +453,133 @@ var OperationGenerator = class extends OperationGenerator$1 {
436
453
  return this.post(operation, schemas, options);
437
454
  }
438
455
  };
456
+ _printCombinedSchema = new WeakSet();
457
+ printCombinedSchema_fn = function(name, operation, schemas) {
458
+ const properties = {
459
+ "response": factory.createTypeReferenceNode(
460
+ factory.createIdentifier(schemas.response.name),
461
+ void 0
462
+ )
463
+ };
464
+ if (schemas.request) {
465
+ properties["request"] = factory.createTypeReferenceNode(
466
+ factory.createIdentifier(schemas.request.name),
467
+ void 0
468
+ );
469
+ }
470
+ if (schemas.pathParams) {
471
+ properties["pathParams"] = factory.createTypeReferenceNode(
472
+ factory.createIdentifier(schemas.pathParams.name),
473
+ void 0
474
+ );
475
+ }
476
+ if (schemas.queryParams) {
477
+ properties["queryParams"] = factory.createTypeReferenceNode(
478
+ factory.createIdentifier(schemas.queryParams.name),
479
+ void 0
480
+ );
481
+ }
482
+ if (schemas.headerParams) {
483
+ properties["headerParams"] = factory.createTypeReferenceNode(
484
+ factory.createIdentifier(schemas.headerParams.name),
485
+ void 0
486
+ );
487
+ }
488
+ if (schemas.errors) {
489
+ properties["errors"] = factory.createUnionDeclaration({
490
+ nodes: schemas.errors.map((error) => {
491
+ return factory.createTypeReferenceNode(
492
+ factory.createIdentifier(error.name),
493
+ void 0
494
+ );
495
+ })
496
+ });
497
+ }
498
+ const namespaceNode = factory.createNamespaceDeclaration({
499
+ name: operation.method === "get" ? `${name}Query` : `${name}Mutation`,
500
+ statements: Object.keys(properties).map((key) => {
501
+ const type = properties[key];
502
+ if (!type) {
503
+ return void 0;
504
+ }
505
+ return factory.createTypeAliasDeclaration({
506
+ modifiers: [factory.modifiers.export],
507
+ name: pascalCase(key),
508
+ type
509
+ });
510
+ }).filter(Boolean)
511
+ });
512
+ return print(namespaceNode);
513
+ };
439
514
 
440
515
  // src/plugin.ts
441
516
  var pluginName = "swagger-ts";
517
+ var pluginKey = ["schema", pluginName];
442
518
  var definePlugin = createPlugin((options) => {
443
519
  const {
444
520
  output = "types",
445
- groupBy,
446
- skipBy = [],
447
- overrideBy = [],
521
+ group,
522
+ exclude = [],
523
+ include,
524
+ override = [],
448
525
  enumType = "asConst",
449
526
  dateType = "string",
450
527
  optionalType = "questionToken",
451
- transformers = {}
528
+ transformers: transformers2 = {},
529
+ exportAs
452
530
  } = options;
453
- const template = groupBy?.output ? groupBy.output : `${output}/{{tag}}Controller`;
531
+ const template = group?.output ? group.output : `${output}/{{tag}}Controller`;
454
532
  let pluginsOptions;
455
533
  return {
456
534
  name: pluginName,
457
535
  options,
458
536
  kind: "schema",
459
537
  validate(plugins) {
460
- pluginsOptions = getDependedPlugins(plugins, [pluginName$1]);
538
+ pluginsOptions = PluginManager.getDependedPlugins(plugins, [pluginName$1]);
461
539
  return true;
462
540
  },
463
541
  resolvePath(baseName, directory, options2) {
464
- const root = pathParser.resolve(this.config.root, this.config.output.path);
465
- const mode = getPathMode(pathParser.resolve(root, output));
542
+ const root = path.resolve(this.config.root, this.config.output.path);
543
+ const mode = FileManager.getMode(path.resolve(root, output));
466
544
  if (mode === "file") {
467
- return pathParser.resolve(root, output);
545
+ return path.resolve(root, output);
468
546
  }
469
- if (options2?.tag && groupBy?.type === "tag") {
547
+ if (options2?.tag && group?.type === "tag") {
470
548
  const tag = camelCase(options2.tag, { delimiter: "", transform: camelCaseTransformMerge });
471
- return pathParser.resolve(root, renderTemplate(template, { tag }), baseName);
549
+ return path.resolve(root, renderTemplate(template, { tag }), baseName);
472
550
  }
473
- return pathParser.resolve(root, output, baseName);
551
+ return path.resolve(root, output, baseName);
474
552
  },
475
- resolveName(name) {
553
+ resolveName(name, type) {
476
554
  const resolvedName = pascalCase(name, { delimiter: "", stripRegexp: /[^A-Z0-9$]/gi, transform: pascalCaseTransformMerge });
477
- return transformers?.name?.(resolvedName) || resolvedName;
555
+ if (type) {
556
+ return transformers2?.name?.(resolvedName, type) || resolvedName;
557
+ }
558
+ return resolvedName;
478
559
  },
479
- async writeFile(source, path) {
480
- if (!path.endsWith(".ts") || !source) {
560
+ async writeFile(source, writePath) {
561
+ if (!writePath.endsWith(".ts") || !source) {
481
562
  return;
482
563
  }
483
- await this.fileManager.write(source, path);
564
+ return this.fileManager.write(source, writePath);
484
565
  },
485
566
  async buildStart() {
486
567
  const [swaggerPlugin] = pluginsOptions;
487
568
  const oas = await swaggerPlugin.api.getOas();
488
569
  const schemas = await swaggerPlugin.api.getSchemas();
489
- const root = pathParser.resolve(this.config.root, this.config.output.path);
490
- const mode = getPathMode(pathParser.resolve(root, output));
570
+ const root = path.resolve(this.config.root, this.config.output.path);
571
+ const mode = FileManager.getMode(path.resolve(root, output));
572
+ const usedEnumNames = {};
491
573
  if (mode === "directory") {
492
574
  const builder = await new TypeBuilder({
493
- resolveName: (params) => this.resolveName({ pluginName, ...params }),
575
+ usedEnumNames,
576
+ resolveName: (params) => this.resolveName({ pluginKey: this.plugin.key, ...params }),
494
577
  fileResolver: (name) => {
495
578
  const resolvedTypeId = this.resolvePath({
496
579
  baseName: `${name}.ts`,
497
- pluginName
580
+ pluginKey: this.plugin.key
498
581
  });
499
- const root2 = this.resolvePath({ baseName: ``, pluginName });
582
+ const root2 = this.resolvePath({ baseName: ``, pluginKey: this.plugin.key });
500
583
  return getRelativePath(root2, resolvedTypeId);
501
584
  },
502
585
  withJSDocs: true,
@@ -511,16 +594,16 @@ var definePlugin = createPlugin((options) => {
511
594
  });
512
595
  });
513
596
  const mapFolderSchema = async ([name]) => {
514
- const path = this.resolvePath({ baseName: `${this.resolveName({ name, pluginName })}.ts`, pluginName });
515
- if (!path) {
597
+ const resolvedPath = this.resolvePath({ baseName: `${this.resolveName({ name, pluginKey: this.plugin.key })}.ts`, pluginKey: this.plugin.key });
598
+ if (!resolvedPath) {
516
599
  return null;
517
600
  }
518
601
  return this.addFile({
519
- path,
520
- baseName: `${this.resolveName({ name, pluginName })}.ts`,
602
+ path: resolvedPath,
603
+ baseName: `${this.resolveName({ name, pluginKey: this.plugin.key })}.ts`,
521
604
  source: builder.print(name),
522
605
  meta: {
523
- pluginName
606
+ pluginKey: this.plugin.key
524
607
  }
525
608
  });
526
609
  };
@@ -529,7 +612,8 @@ var definePlugin = createPlugin((options) => {
529
612
  }
530
613
  if (mode === "file") {
531
614
  const builder = new TypeBuilder({
532
- resolveName: (params) => this.resolveName({ pluginName, ...params }),
615
+ usedEnumNames,
616
+ resolveName: (params) => this.resolveName({ pluginKey: this.plugin.key, ...params }),
533
617
  withJSDocs: true,
534
618
  enumType,
535
619
  dateType,
@@ -541,17 +625,18 @@ var definePlugin = createPlugin((options) => {
541
625
  name
542
626
  });
543
627
  });
544
- const path = this.resolvePath({ baseName: "", pluginName });
545
- if (!path) {
628
+ const resolvedPath = this.resolvePath({ baseName: "", pluginKey: this.plugin.key });
629
+ if (!resolvedPath) {
546
630
  return;
547
631
  }
548
632
  await this.addFile({
549
- path,
550
- baseName: `${this.resolveName({ name: output, pluginName })}.ts`,
633
+ path: resolvedPath,
634
+ baseName: output,
551
635
  source: builder.print(),
552
636
  meta: {
553
- pluginName
554
- }
637
+ pluginKey: this.plugin.key
638
+ },
639
+ validate: false
555
640
  });
556
641
  }
557
642
  const operationGenerator = new OperationGenerator(
@@ -559,14 +644,17 @@ var definePlugin = createPlugin((options) => {
559
644
  mode,
560
645
  enumType,
561
646
  dateType,
562
- optionalType
647
+ optionalType,
648
+ usedEnumNames
563
649
  },
564
650
  {
565
651
  oas,
566
652
  pluginManager: this.pluginManager,
653
+ plugin: this.plugin,
567
654
  contentType: swaggerPlugin.api.contentType,
568
- skipBy,
569
- overrideBy
655
+ exclude,
656
+ include,
657
+ override
570
658
  }
571
659
  );
572
660
  const files = await operationGenerator.build();
@@ -576,21 +664,38 @@ var definePlugin = createPlugin((options) => {
576
664
  if (this.config.output.write === false) {
577
665
  return;
578
666
  }
579
- while (this.fileManager.isExecuting) {
580
- await timeout(100);
581
- }
582
- const root = pathParser.resolve(this.config.root, this.config.output.path);
583
- await this.fileManager.addIndexes(root, ".ts");
667
+ const root = path.resolve(this.config.root, this.config.output.path);
668
+ await this.fileManager.addIndexes({
669
+ root,
670
+ extName: ".ts",
671
+ meta: { pluginKey: this.plugin.key },
672
+ options: {
673
+ map: (file) => {
674
+ return {
675
+ ...file,
676
+ exports: file.exports?.map((item) => {
677
+ if (exportAs) {
678
+ return {
679
+ ...item,
680
+ name: exportAs,
681
+ asAlias: !!exportAs
682
+ };
683
+ }
684
+ return item;
685
+ })
686
+ };
687
+ },
688
+ output,
689
+ isTypeOnly: true
690
+ }
691
+ });
584
692
  }
585
693
  };
586
694
  });
587
- function useResolve(props = {}) {
588
- return useResolve$1({ pluginName, ...props });
589
- }
590
695
 
591
696
  // src/index.ts
592
697
  var src_default = definePlugin;
593
698
 
594
- export { OperationGenerator, TypeBuilder, TypeGenerator, src_default as default, definePlugin, keywordTypeNodes, pluginName, resolve, useResolve };
699
+ export { src_default as default, definePlugin, pluginKey, pluginName };
595
700
  //# sourceMappingURL=out.js.map
596
701
  //# sourceMappingURL=index.js.map