@kubb/plugin-msw 3.0.0-alpha.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.
@@ -0,0 +1,66 @@
1
+ import { OperationGenerator as Generator } from '@kubb/plugin-oas'
2
+ import { Oas } from '@kubb/plugin-oas/components'
3
+ import { App, createRoot } from '@kubb/react'
4
+
5
+ import { Mock } from './components/Mock.tsx'
6
+ import { Operations } from './components/Operations.tsx'
7
+
8
+ import type { Operation } from '@kubb/oas'
9
+ import type { OperationMethodResult, OperationsByMethod } from '@kubb/plugin-oas'
10
+ import type { FileMeta, PluginMsw } from './types.ts'
11
+
12
+ export class OperationGenerator extends Generator<PluginMsw['resolvedOptions'], PluginMsw> {
13
+ async all(operations: Operation[], operationsByMethod: OperationsByMethod): OperationMethodResult<FileMeta> {
14
+ const { oas, pluginManager, plugin, mode } = this.context
15
+
16
+ const root = createRoot({
17
+ logger: pluginManager.logger,
18
+ })
19
+
20
+ const templates = {
21
+ operations: Operations.templates,
22
+ mock: Mock.templates,
23
+ ...this.options.templates,
24
+ }
25
+
26
+ root.render(
27
+ <App pluginManager={pluginManager} plugin={plugin} mode={mode}>
28
+ <Oas oas={oas} operations={operations} generator={this}>
29
+ {templates?.operations && <Operations.File templates={templates.operations} />}
30
+ </Oas>
31
+ </App>,
32
+ )
33
+
34
+ return root.files
35
+ }
36
+
37
+ async operation(operation: Operation, options: PluginMsw['resolvedOptions']): OperationMethodResult<FileMeta> {
38
+ const { oas, pluginManager, plugin, mode } = this.context
39
+
40
+ const root = createRoot({
41
+ logger: pluginManager.logger,
42
+ })
43
+
44
+ const templates = {
45
+ handlers: Operations.templates,
46
+ mock: Mock.templates,
47
+ ...options.templates,
48
+ }
49
+
50
+ if (!templates?.mock) {
51
+ return []
52
+ }
53
+
54
+ root.render(
55
+ <App pluginManager={pluginManager} plugin={{ ...plugin, options }} mode={mode}>
56
+ <Oas oas={oas} operations={[operation]} generator={this}>
57
+ <Oas.Operation operation={operation}>
58
+ <Mock.File templates={templates.mock} />
59
+ </Oas.Operation>
60
+ </Oas>
61
+ </App>,
62
+ )
63
+
64
+ return root.files
65
+ }
66
+ }
@@ -0,0 +1,113 @@
1
+ import { PackageManager } from '@kubb/core'
2
+ import { URLPath } from '@kubb/core/utils'
3
+ import { Parser, File, useApp } from '@kubb/react'
4
+ import { pluginFakerName } from '@kubb/plugin-faker'
5
+ import { useOperation, useOperationManager } from '@kubb/plugin-oas/hooks'
6
+
7
+ import type { HttpMethod } from '@kubb/oas'
8
+ import type { ReactNode } from 'react'
9
+ import type { FileMeta, PluginMsw } from '../types.ts'
10
+
11
+ type TemplateProps = {
12
+ /**
13
+ * Name of the function
14
+ */
15
+ name: string
16
+ /**
17
+ * Method of the current operation, see useOperation.
18
+ */
19
+ method: HttpMethod
20
+ /**
21
+ * Path of the mock
22
+ */
23
+ path: URLPath
24
+ /**
25
+ * Name of the import for the mock(this is a function).
26
+ * @example createPet
27
+ */
28
+ responseName: string
29
+ }
30
+
31
+ function Template({ name, method, path, responseName }: TemplateProps): ReactNode {
32
+ return (
33
+ <>
34
+ {`
35
+ export const ${name} = http.${method}('*${path.toURLPath()}', function handler(info) {
36
+ return new Response(JSON.stringify(${responseName}()), {
37
+ headers: {
38
+ 'Content-Type': 'application/json',
39
+ },
40
+ })
41
+ })
42
+ `}
43
+ </>
44
+ )
45
+ }
46
+
47
+ const defaultTemplates = { default: Template } as const
48
+
49
+ type Props = {
50
+ /**
51
+ * This will make it possible to override the default behaviour.
52
+ */
53
+ Template?: React.ComponentType<React.ComponentProps<typeof Template>>
54
+ }
55
+
56
+ export function Mock({ Template = defaultTemplates.default }: Props): ReactNode {
57
+ const { pluginManager } = useApp<PluginMsw>()
58
+ const { getSchemas, getName } = useOperationManager()
59
+ const operation = useOperation()
60
+
61
+ const schemas = getSchemas(operation)
62
+ const name = getName(operation, { type: 'function' })
63
+ const responseName = pluginManager.resolveName({
64
+ pluginKey: [pluginFakerName],
65
+ name: schemas.response.name,
66
+ type: 'type',
67
+ })
68
+
69
+ return <Template name={name} responseName={responseName} method={operation.method} path={new URLPath(operation.path)} />
70
+ }
71
+
72
+ type FileProps = {
73
+ /**
74
+ * This will make it possible to override the default behaviour.
75
+ */
76
+ templates?: typeof defaultTemplates
77
+ }
78
+
79
+ Mock.File = function ({ templates = defaultTemplates }: FileProps): ReactNode {
80
+ const {
81
+ pluginManager,
82
+ plugin: {
83
+ options: { extName },
84
+ },
85
+ } = useApp<PluginMsw>()
86
+ const { getSchemas, getFile } = useOperationManager()
87
+ const operation = useOperation()
88
+
89
+ const schemas = getSchemas(operation)
90
+ const file = getFile(operation)
91
+ const fileFaker = getFile(operation, { pluginKey: [pluginFakerName] })
92
+ const responseName = pluginManager.resolveName({
93
+ pluginKey: [pluginFakerName],
94
+ name: schemas.response.name,
95
+ type: 'function',
96
+ })
97
+
98
+ const Template = templates.default
99
+
100
+ return (
101
+ <Parser language="typescript">
102
+ <File<FileMeta> baseName={file.baseName} path={file.path} meta={file.meta}>
103
+ <File.Import name={['http']} path={'msw'} />
104
+ {fileFaker && responseName && <File.Import extName={extName} name={[responseName]} root={file.path} path={fileFaker.path} />}
105
+ <File.Source>
106
+ <Mock Template={Template} />
107
+ </File.Source>
108
+ </File>
109
+ </Parser>
110
+ )
111
+ }
112
+
113
+ Mock.templates = defaultTemplates
@@ -0,0 +1,96 @@
1
+ import { Parser, File, useApp } from '@kubb/react'
2
+ import { useOperationManager, useOperations } from '@kubb/plugin-oas/hooks'
3
+
4
+ import type { KubbNode } from '@kubb/react'
5
+ import type { ReactNode } from 'react'
6
+ import type { FileMeta, PluginMsw } from '../types.ts'
7
+
8
+ type TemplateProps = {
9
+ /**
10
+ * Name of the function
11
+ */
12
+ name: string
13
+ handlers: string[]
14
+ }
15
+
16
+ function Template({ name, handlers }: TemplateProps): ReactNode {
17
+ return <>{`export const ${name} = ${JSON.stringify(handlers).replaceAll(`"`, '')} as const`}</>
18
+ }
19
+
20
+ type ParserTemplateProps = {
21
+ children?: React.ReactNode
22
+ }
23
+
24
+ function RootTemplate({ children }: ParserTemplateProps) {
25
+ const {
26
+ pluginManager,
27
+ plugin: { key: pluginKey },
28
+ } = useApp<PluginMsw>()
29
+
30
+ const { getName, getFile } = useOperationManager()
31
+
32
+ const file = pluginManager.getFile({ name: 'handlers', extName: '.ts', pluginKey })
33
+ const operations = useOperations()
34
+
35
+ const imports = operations
36
+ .map((operation) => {
37
+ const operationFile = getFile(operation, { pluginKey })
38
+ const operationName = getName(operation, { pluginKey, type: 'function' })
39
+
40
+ return <File.Import key={operationFile.path} name={[operationName]} root={file.path} path={operationFile.path} />
41
+ })
42
+ .filter(Boolean)
43
+
44
+ return (
45
+ <Parser language="typescript">
46
+ <File<FileMeta> baseName={file.baseName} path={file.path} meta={file.meta}>
47
+ {imports}
48
+ <File.Source>{children}</File.Source>
49
+ </File>
50
+ </Parser>
51
+ )
52
+ }
53
+
54
+ const defaultTemplates = { default: Template, root: RootTemplate } as const
55
+
56
+ type Templates = Partial<typeof defaultTemplates>
57
+
58
+ type Props = {
59
+ /**
60
+ * This will make it possible to override the default behaviour.
61
+ */
62
+ Template?: React.ComponentType<React.ComponentProps<typeof Template>>
63
+ }
64
+
65
+ export function Operations({ Template = defaultTemplates.default }: Props): ReactNode {
66
+ const {
67
+ plugin: { key: pluginKey },
68
+ } = useApp<PluginMsw>()
69
+
70
+ const operations = useOperations()
71
+ const { getName } = useOperationManager()
72
+
73
+ return <Template name="handlers" handlers={operations.map((operation) => getName(operation, { type: 'function', pluginKey }))} />
74
+ }
75
+
76
+ type FileProps = {
77
+ /**
78
+ * This will make it possible to override the default behaviour.
79
+ */
80
+ templates?: Templates
81
+ }
82
+
83
+ Operations.File = function (props: FileProps): KubbNode {
84
+ const templates = { ...defaultTemplates, ...props.templates }
85
+
86
+ const Template = templates.default
87
+ const RootTemplate = templates.root
88
+
89
+ return (
90
+ <RootTemplate>
91
+ <Operations Template={Template} />
92
+ </RootTemplate>
93
+ )
94
+ }
95
+
96
+ Operations.templates = defaultTemplates
@@ -0,0 +1,7 @@
1
+ export const createPets = http.post('*/pets', function handler(info) {
2
+ return new Response(JSON.stringify(CreatePetsMutationResponse()), {
3
+ headers: {
4
+ 'Content-Type': 'application/json',
5
+ },
6
+ })
7
+ })
@@ -0,0 +1,7 @@
1
+ export const showPetById = http.get('*/pets/:petId', function handler(info) {
2
+ return new Response(JSON.stringify(ShowPetByIdQueryResponse()), {
3
+ headers: {
4
+ 'Content-Type': 'application/json',
5
+ },
6
+ })
7
+ })
@@ -0,0 +1,2 @@
1
+ export { Mock } from './Mock.tsx'
2
+ export { Operations } from './Operations.tsx'
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { pluginMsw, pluginMswName } from './plugin.ts'
2
+ export type { PluginMsw } from './types.ts'
package/src/plugin.ts ADDED
@@ -0,0 +1,123 @@
1
+ import path from 'node:path'
2
+
3
+ import { FileManager, PluginManager, createPlugin } from '@kubb/core'
4
+ import { camelCase } from '@kubb/core/transformers'
5
+ import { renderTemplate } from '@kubb/core/utils'
6
+ import { pluginOasName } from '@kubb/plugin-oas'
7
+ import { getGroupedByTagFiles } from '@kubb/plugin-oas/utils'
8
+ import { pluginFakerName } from '@kubb/plugin-faker'
9
+ import { pluginTsName } from '@kubb/plugin-ts'
10
+
11
+ import { OperationGenerator } from './OperationGenerator.tsx'
12
+ import { Mock, Operations } from './components/index.ts'
13
+
14
+ import type { Plugin } from '@kubb/core'
15
+ import type { PluginOas as SwaggerPluginOptions } from '@kubb/plugin-oas'
16
+ import type { PluginMsw } from './types.ts'
17
+
18
+ export const pluginMswName = 'plugin-msw' satisfies PluginMsw['name']
19
+
20
+ export const pluginMsw = createPlugin<PluginMsw>((options) => {
21
+ const { output = { path: 'handlers' }, group, exclude = [], include, override = [], transformers = {}, templates } = options
22
+ const template = group?.output ? group.output : `${output.path}/{{tag}}Controller`
23
+
24
+ return {
25
+ name: pluginMswName,
26
+ options: {
27
+ extName: output.extName,
28
+ templates: {
29
+ operations: Operations.templates,
30
+ mock: Mock.templates,
31
+ ...templates,
32
+ },
33
+ },
34
+ pre: [pluginOasName, pluginTsName, pluginFakerName],
35
+ resolvePath(baseName, pathMode, options) {
36
+ const root = path.resolve(this.config.root, this.config.output.path)
37
+ const mode = pathMode ?? FileManager.getMode(path.resolve(root, output.path))
38
+
39
+ if (mode === 'single') {
40
+ /**
41
+ * when output is a file then we will always append to the same file(output file), see fileManager.addOrAppend
42
+ * Other plugins then need to call addOrAppend instead of just add from the fileManager class
43
+ */
44
+ return path.resolve(root, output.path)
45
+ }
46
+
47
+ if (options?.tag && group?.type === 'tag') {
48
+ const tag = camelCase(options.tag)
49
+
50
+ return path.resolve(root, renderTemplate(template, { tag }), baseName)
51
+ }
52
+
53
+ return path.resolve(root, output.path, baseName)
54
+ },
55
+ resolveName(name, type) {
56
+ const resolvedName = camelCase(name, {
57
+ suffix: type ? 'handler' : undefined,
58
+ isFile: type === 'file',
59
+ })
60
+ if (type) {
61
+ return transformers?.name?.(resolvedName, type) || resolvedName
62
+ }
63
+
64
+ return resolvedName
65
+ },
66
+ async writeFile(path, source) {
67
+ if (!path.endsWith('.ts') || !source) {
68
+ return
69
+ }
70
+
71
+ return this.fileManager.write(path, source, { sanity: false })
72
+ },
73
+ async buildStart() {
74
+ const [swaggerPlugin]: [Plugin<SwaggerPluginOptions>] = PluginManager.getDependedPlugins<SwaggerPluginOptions>(this.plugins, [pluginOasName])
75
+
76
+ const oas = await swaggerPlugin.api.getOas()
77
+ const root = path.resolve(this.config.root, this.config.output.path)
78
+ const mode = FileManager.getMode(path.resolve(root, output.path))
79
+
80
+ const operationGenerator = new OperationGenerator(this.plugin.options, {
81
+ oas,
82
+ pluginManager: this.pluginManager,
83
+ plugin: this.plugin,
84
+ contentType: swaggerPlugin.api.contentType,
85
+ exclude,
86
+ include,
87
+ override,
88
+ mode,
89
+ })
90
+
91
+ const files = await operationGenerator.build()
92
+ await this.addFile(...files)
93
+ },
94
+ async buildEnd() {
95
+ if (this.config.output.write === false) {
96
+ return
97
+ }
98
+
99
+ const root = path.resolve(this.config.root, this.config.output.path)
100
+
101
+ if (group?.type === 'tag') {
102
+ const rootFiles = await getGroupedByTagFiles({
103
+ logger: this.logger,
104
+ files: this.fileManager.files,
105
+ plugin: this.plugin,
106
+ template,
107
+ exportAs: group.exportAs || '{{tag}}Handlers',
108
+ root,
109
+ output,
110
+ })
111
+
112
+ await this.addFile(...rootFiles)
113
+ }
114
+
115
+ await this.fileManager.addIndexes({
116
+ root,
117
+ output,
118
+ meta: { pluginKey: this.plugin.key },
119
+ logger: this.logger,
120
+ })
121
+ },
122
+ }
123
+ })
package/src/types.ts ADDED
@@ -0,0 +1,95 @@
1
+ import type { Plugin, PluginFactoryOptions, ResolveNameParams } from '@kubb/core'
2
+ import type * as KubbFile from '@kubb/fs/types'
3
+
4
+ import type { Exclude, Include, Override, ResolvePathOptions } from '@kubb/plugin-oas'
5
+ import type { Mock, Operations } from './components/index.ts'
6
+
7
+ type Templates = {
8
+ operations?: typeof Operations.templates | false
9
+ mock?: typeof Mock.templates | false
10
+ }
11
+
12
+ export type Options = {
13
+ output?: {
14
+ /**
15
+ * Relative path to save the MSW mocks.
16
+ * When output is a file it will save all models inside that file else it will create a file per schema item.
17
+ * @default 'mocks'
18
+ */
19
+ path: string
20
+ /**
21
+ * Name to be used for the `export * as {{exportAs}} from './'`
22
+ */
23
+ exportAs?: string
24
+ /**
25
+ * Add an extension to the generated imports and exports, default it will not use an extension
26
+ */
27
+ extName?: KubbFile.Extname
28
+ /**
29
+ * Define what needs to exported, here you can also disable the export of barrel files
30
+ * @default `'barrel'`
31
+ */
32
+ exportType?: 'barrel' | 'barrelNamed' | false
33
+ }
34
+ /**
35
+ * Group the MSW mocks based on the provided name.
36
+ */
37
+ group?: {
38
+ /**
39
+ * Tag will group based on the operation tag inside the Swagger file
40
+ */
41
+ type: 'tag'
42
+ /**
43
+ * Relative path to save the grouped MSW mocks.
44
+ *
45
+ * `{{tag}}` will be replaced by the current tagName.
46
+ * @example `${output}/{{tag}}Controller` => `mocks/PetController`
47
+ * @default `${output}/{{tag}}Controller`
48
+ */
49
+ output?: string
50
+ /**
51
+ * Name to be used for the `export * as {{exportAs}} from './`
52
+ * @default `"{{tag}}Handlers"`
53
+ */
54
+ exportAs?: string
55
+ }
56
+ /**
57
+ * Array containing exclude parameters to exclude/skip tags/operations/methods/paths.
58
+ */
59
+ exclude?: Array<Exclude>
60
+ /**
61
+ * Array containing include parameters to include tags/operations/methods/paths.
62
+ */
63
+ include?: Array<Include>
64
+ /**
65
+ * Array containing override parameters to override `options` based on tags/operations/methods/paths.
66
+ */
67
+ override?: Array<Override<ResolvedOptions>>
68
+ transformers?: {
69
+ /**
70
+ * Customize the names based on the type that is provided by the plugin.
71
+ */
72
+ name?: (name: ResolveNameParams['name'], type?: ResolveNameParams['type']) => string
73
+ }
74
+ /**
75
+ * Make it possible to override one of the templates
76
+ */
77
+ templates?: Partial<Templates>
78
+ }
79
+ type ResolvedOptions = {
80
+ extName: KubbFile.Extname | undefined
81
+ templates: NonNullable<Templates>
82
+ }
83
+
84
+ export type FileMeta = {
85
+ pluginKey?: Plugin['key']
86
+ tag?: string
87
+ }
88
+
89
+ export type PluginMsw = PluginFactoryOptions<'plugin-msw', Options, ResolvedOptions, never, ResolvePathOptions>
90
+
91
+ declare module '@kubb/core' {
92
+ export interface _Register {
93
+ ['@kubb/plugin-msw']: PluginMsw
94
+ }
95
+ }