@kubb/swagger-ts 2.0.0-alpha.1 → 2.0.0-alpha.11

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/src/plugin.ts ADDED
@@ -0,0 +1,229 @@
1
+ import path from 'node:path'
2
+
3
+ import { createPlugin, FileManager, PluginManager } from '@kubb/core'
4
+ import { getRelativePath, renderTemplate } from '@kubb/core/utils'
5
+ import { pluginName as swaggerPluginName } from '@kubb/swagger'
6
+
7
+ import { camelCase, camelCaseTransformMerge, pascalCase, pascalCaseTransformMerge } from 'change-case'
8
+
9
+ import { TypeBuilder } from './builders/index.ts'
10
+ import { OperationGenerator } from './generators/index.ts'
11
+
12
+ import type { KubbFile, KubbPlugin } from '@kubb/core'
13
+ import type { OpenAPIV3, PluginOptions as SwaggerPluginOptions } from '@kubb/swagger'
14
+ import type { PluginOptions } from './types.ts'
15
+
16
+ export const pluginName = 'swagger-ts' satisfies PluginOptions['name']
17
+ export const pluginKey: PluginOptions['key'] = ['schema', pluginName] satisfies PluginOptions['key']
18
+
19
+ export const definePlugin = createPlugin<PluginOptions>((options) => {
20
+ const {
21
+ output = 'types',
22
+ group,
23
+ exclude = [],
24
+ include,
25
+ override = [],
26
+ enumType = 'asConst',
27
+ dateType = 'string',
28
+ optionalType = 'questionToken',
29
+ transformers = {},
30
+ exportAs,
31
+ } = options
32
+ const template = group?.output ? group.output : `${output}/{{tag}}Controller`
33
+ let pluginsOptions: [KubbPlugin<SwaggerPluginOptions>]
34
+
35
+ return {
36
+ name: pluginName,
37
+ options,
38
+ kind: 'schema',
39
+ validate(plugins) {
40
+ pluginsOptions = PluginManager.getDependedPlugins<SwaggerPluginOptions>(plugins, [swaggerPluginName])
41
+
42
+ return true
43
+ },
44
+ resolvePath(baseName, directory, options) {
45
+ const root = path.resolve(this.config.root, this.config.output.path)
46
+ const mode = FileManager.getMode(path.resolve(root, output))
47
+
48
+ if (mode === 'file') {
49
+ /**
50
+ * when output is a file then we will always append to the same file(output file), see fileManager.addOrAppend
51
+ * Other plugins then need to call addOrAppend instead of just add from the fileManager class
52
+ */
53
+ return path.resolve(root, output)
54
+ }
55
+
56
+ if (options?.tag && group?.type === 'tag') {
57
+ const tag = camelCase(options.tag, { delimiter: '', transform: camelCaseTransformMerge })
58
+
59
+ return path.resolve(root, renderTemplate(template, { tag }), baseName)
60
+ }
61
+
62
+ return path.resolve(root, output, baseName)
63
+ },
64
+ resolveName(name, type) {
65
+ const resolvedName = pascalCase(name, { delimiter: '', stripRegexp: /[^A-Z0-9$]/gi, transform: pascalCaseTransformMerge })
66
+
67
+ if (type) {
68
+ return transformers?.name?.(resolvedName, type) || resolvedName
69
+ }
70
+
71
+ return resolvedName
72
+ },
73
+ async writeFile(source, writePath) {
74
+ if (!writePath.endsWith('.ts') || !source) {
75
+ return
76
+ }
77
+
78
+ return this.fileManager.write(source, writePath)
79
+ },
80
+ async buildStart() {
81
+ const [swaggerPlugin] = pluginsOptions
82
+
83
+ const oas = await swaggerPlugin.api.getOas()
84
+
85
+ const schemas = await swaggerPlugin.api.getSchemas()
86
+ const root = path.resolve(this.config.root, this.config.output.path)
87
+ const mode = FileManager.getMode(path.resolve(root, output))
88
+ // keep the used enumnames between TypeBuilder and OperationGenerator per plugin(pluginKey)
89
+ const usedEnumNames = {}
90
+
91
+ if (mode === 'directory') {
92
+ const builder = await new TypeBuilder({
93
+ usedEnumNames,
94
+ resolveName: (params) => this.resolveName({ pluginKey: this.plugin.key, ...params }),
95
+ fileResolver: (name) => {
96
+ const resolvedTypeId = this.resolvePath({
97
+ baseName: `${name}.ts`,
98
+ pluginKey: this.plugin.key,
99
+ })
100
+
101
+ const root = this.resolvePath({ baseName: ``, pluginKey: this.plugin.key })
102
+
103
+ return getRelativePath(root, resolvedTypeId)
104
+ },
105
+ withJSDocs: true,
106
+ enumType,
107
+ dateType,
108
+ optionalType,
109
+ }).configure()
110
+ Object.entries(schemas).forEach(([name, schema]: [string, OpenAPIV3.SchemaObject]) => {
111
+ // generate and pass through new code back to the core so it can be write to that file
112
+ return builder.add({
113
+ schema,
114
+ name,
115
+ })
116
+ })
117
+
118
+ const mapFolderSchema = async ([name]: [string, OpenAPIV3.SchemaObject]) => {
119
+ const resolvedPath = this.resolvePath({ baseName: `${this.resolveName({ name, pluginKey: this.plugin.key })}.ts`, pluginKey: this.plugin.key })
120
+
121
+ if (!resolvedPath) {
122
+ return null
123
+ }
124
+
125
+ return this.addFile({
126
+ path: resolvedPath,
127
+ baseName: `${this.resolveName({ name, pluginKey: this.plugin.key })}.ts`,
128
+ source: builder.print(name),
129
+ meta: {
130
+ pluginKey: this.plugin.key,
131
+ },
132
+ })
133
+ }
134
+
135
+ const promises = Object.entries(schemas).map(mapFolderSchema)
136
+
137
+ await Promise.all(promises)
138
+ }
139
+
140
+ if (mode === 'file') {
141
+ // outside the loop because we need to add files to just one instance to have the correct sorting, see refsSorter
142
+ const builder = new TypeBuilder({
143
+ usedEnumNames,
144
+ resolveName: (params) => this.resolveName({ pluginKey: this.plugin.key, ...params }),
145
+ withJSDocs: true,
146
+ enumType,
147
+ dateType,
148
+ optionalType,
149
+ }).configure()
150
+ Object.entries(schemas).forEach(([name, schema]: [string, OpenAPIV3.SchemaObject]) => {
151
+ // generate and pass through new code back to the core so it can be write to that file
152
+ return builder.add({
153
+ schema,
154
+ name,
155
+ })
156
+ })
157
+
158
+ const resolvedPath = this.resolvePath({ baseName: '', pluginKey: this.plugin.key })
159
+ if (!resolvedPath) {
160
+ return
161
+ }
162
+
163
+ await this.addFile({
164
+ path: resolvedPath,
165
+ baseName: output as KubbFile.BaseName,
166
+ source: builder.print(),
167
+ meta: {
168
+ pluginKey: this.plugin.key,
169
+ },
170
+ validate: false,
171
+ })
172
+ }
173
+
174
+ const operationGenerator = new OperationGenerator(
175
+ {
176
+ mode,
177
+ enumType,
178
+ dateType,
179
+ optionalType,
180
+ usedEnumNames,
181
+ },
182
+ {
183
+ oas,
184
+ pluginManager: this.pluginManager,
185
+ plugin: this.plugin,
186
+ contentType: swaggerPlugin.api.contentType,
187
+ exclude,
188
+ include,
189
+ override,
190
+ },
191
+ )
192
+
193
+ const files = await operationGenerator.build()
194
+ await this.addFile(...files)
195
+ },
196
+ async buildEnd() {
197
+ if (this.config.output.write === false) {
198
+ return
199
+ }
200
+
201
+ const root = path.resolve(this.config.root, this.config.output.path)
202
+
203
+ await this.fileManager.addIndexes({
204
+ root,
205
+ extName: '.ts',
206
+ meta: { pluginKey: this.plugin.key },
207
+ options: {
208
+ map: (file) => {
209
+ return {
210
+ ...file,
211
+ exports: file.exports?.map((item) => {
212
+ if (exportAs) {
213
+ return {
214
+ ...item,
215
+ name: exportAs,
216
+ asAlias: !!exportAs,
217
+ }
218
+ }
219
+ return item
220
+ }),
221
+ }
222
+ },
223
+ output,
224
+ isTypeOnly: true,
225
+ },
226
+ })
227
+ },
228
+ }
229
+ })
package/src/types.ts ADDED
@@ -0,0 +1,82 @@
1
+ import type { KubbPlugin, PluginFactoryOptions, ResolveNameParams } from '@kubb/core'
2
+ import type { Exclude, Include, Override, ResolvePathOptions } from '@kubb/swagger'
3
+
4
+ export type Options = {
5
+ /**
6
+ * Relative path to save the TypeScript types.
7
+ * When output is a file it will save all models inside that file else it will create a file per schema item.
8
+ * @default 'types'
9
+ */
10
+ output?: string
11
+ /**
12
+ * Group the TypeScript types based on the provided name.
13
+ */
14
+ group?: {
15
+ /**
16
+ * Tag will group based on the operation tag inside the Swagger file.
17
+ */
18
+ type: 'tag'
19
+ /**
20
+ * Relative path to save the grouped TypeScript Types.
21
+ *
22
+ * `{{tag}}` will be replaced by the current tagName.
23
+ * @example `${output}/{{tag}}Controller` => `models/PetController`
24
+ * @default `${output}/{{tag}}Controller`
25
+ */
26
+ output?: string
27
+ }
28
+ /**
29
+ * Name to be used for the `export * as {{exportAs}} from './`
30
+ */
31
+ exportAs?: string
32
+ /**
33
+ * Array containing exclude paramaters to exclude/skip tags/operations/methods/paths.
34
+ */
35
+ exclude?: Array<Exclude>
36
+ /**
37
+ * Array containing include paramaters to include tags/operations/methods/paths.
38
+ */
39
+ include?: Array<Include>
40
+ /**
41
+ * Array containing override paramaters to override `options` based on tags/operations/methods/paths.
42
+ */
43
+ override?: Array<Override<Options>>
44
+ /**
45
+ * Choose to use `enum` or `as const` for enums
46
+ * @default 'asConst'
47
+ */
48
+ enumType?: 'enum' | 'asConst' | 'asPascalConst'
49
+ /**
50
+ * Choose to use `date` or `datetime` as JavaScript `Date` instead of `string`.
51
+ * @default 'string'
52
+ */
53
+ dateType?: 'string' | 'date'
54
+ /**
55
+ * Choose what to use as mode for an optional value.
56
+ * @examples 'questionToken': type?: string
57
+ * @examples 'undefined': type: string | undefined
58
+ * @examples 'questionTokenAndUndefined': type?: string | undefined
59
+ * @default 'questionToken'
60
+ */
61
+ optionalType?: 'questionToken' | 'undefined' | 'questionTokenAndUndefined'
62
+ transformers?: {
63
+ /**
64
+ * Customize the names based on the type that is provided by the plugin.
65
+ */
66
+ name?: (name: ResolveNameParams['name'], type?: ResolveNameParams['type']) => string
67
+ }
68
+ }
69
+
70
+ export type FileMeta = {
71
+ pluginKey?: KubbPlugin['key']
72
+ name?: string
73
+ tag?: string
74
+ }
75
+
76
+ export type PluginOptions = PluginFactoryOptions<'swagger-ts', 'schema', Options, Options, never, ResolvePathOptions>
77
+
78
+ declare module '@kubb/core' {
79
+ export interface _Register {
80
+ ['@kubb/swagger-ts']: PluginOptions
81
+ }
82
+ }