@kubb/plugin-swr 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.
package/dist/index.js ADDED
@@ -0,0 +1,180 @@
1
+ import {
2
+ Mutation,
3
+ Query,
4
+ QueryOptions
5
+ } from "./chunk-ECJ346AA.js";
6
+
7
+ // src/plugin.ts
8
+ import path from "path";
9
+ import { FileManager, PluginManager, createPlugin } from "@kubb/core";
10
+ import { camelCase, pascalCase } from "@kubb/core/transformers";
11
+ import { renderTemplate } from "@kubb/core/utils";
12
+ import { pluginOasName } from "@kubb/plugin-oas";
13
+ import { getGroupedByTagFiles } from "@kubb/plugin-oas/utils";
14
+ import { pluginTsName } from "@kubb/plugin-ts";
15
+ import { pluginZodName } from "@kubb/plugin-zod";
16
+
17
+ // src/OperationGenerator.tsx
18
+ import { OperationGenerator as Generator } from "@kubb/plugin-oas";
19
+ import { Oas } from "@kubb/plugin-oas/components";
20
+ import { App, createRoot } from "@kubb/react";
21
+ import { jsx } from "@kubb/react/jsx-runtime";
22
+ var OperationGenerator = class extends Generator {
23
+ async get(operation, options) {
24
+ const { oas, pluginManager, plugin, mode } = this.context;
25
+ const root = createRoot({
26
+ logger: pluginManager.logger
27
+ });
28
+ if (!options.templates?.query || !options.templates?.queryOptions) {
29
+ return [];
30
+ }
31
+ root.render(
32
+ /* @__PURE__ */ jsx(App, { pluginManager, plugin: { ...plugin, options }, mode, children: /* @__PURE__ */ jsx(Oas, { oas, operations: [operation], generator: this, children: /* @__PURE__ */ jsx(Oas.Operation, { operation, children: /* @__PURE__ */ jsx(
33
+ Query.File,
34
+ {
35
+ templates: {
36
+ query: options.templates.query,
37
+ queryOptions: options.templates.queryOptions
38
+ }
39
+ }
40
+ ) }) }) })
41
+ );
42
+ return root.files;
43
+ }
44
+ async post(operation, options) {
45
+ const { oas, pluginManager, plugin, mode } = this.context;
46
+ const root = createRoot({
47
+ logger: pluginManager.logger
48
+ });
49
+ if (!options.templates?.mutation) {
50
+ return [];
51
+ }
52
+ root.render(
53
+ /* @__PURE__ */ jsx(App, { pluginManager, plugin: { ...plugin, options }, mode, children: /* @__PURE__ */ jsx(Oas, { oas, operations: [operation], generator: this, children: /* @__PURE__ */ jsx(Oas.Operation, { operation, children: /* @__PURE__ */ jsx(Mutation.File, { templates: options.templates.mutation }) }) }) })
54
+ );
55
+ return root.files;
56
+ }
57
+ async put(operation, options) {
58
+ return this.post(operation, options);
59
+ }
60
+ async patch(operation, options) {
61
+ return this.post(operation, options);
62
+ }
63
+ async delete(operation, options) {
64
+ return this.post(operation, options);
65
+ }
66
+ };
67
+
68
+ // src/plugin.ts
69
+ var pluginSwrName = "plugin-swr";
70
+ var pluginSwr = createPlugin((options) => {
71
+ const { output = { path: "hooks" }, group, exclude = [], include, override = [], parser, transformers = {}, templates, dataReturnType = "data" } = options;
72
+ const template = group?.output ? group.output : `${output.path}/{{tag}}SWRController`;
73
+ return {
74
+ name: pluginSwrName,
75
+ options: {
76
+ extName: output.extName,
77
+ templates: {
78
+ mutation: Mutation.templates,
79
+ query: Query.templates,
80
+ queryOptions: QueryOptions.templates,
81
+ ...templates
82
+ },
83
+ client: {
84
+ importPath: "@kubb/plugin-client/client",
85
+ ...options.client
86
+ },
87
+ dataReturnType,
88
+ parser
89
+ },
90
+ pre: [pluginOasName, pluginTsName, parser === "zod" ? pluginZodName : void 0].filter(Boolean),
91
+ resolvePath(baseName, pathMode, options2) {
92
+ const root = path.resolve(this.config.root, this.config.output.path);
93
+ const mode = pathMode ?? FileManager.getMode(path.resolve(root, output.path));
94
+ if (mode === "single") {
95
+ return path.resolve(root, output.path);
96
+ }
97
+ if (options2?.tag && group?.type === "tag") {
98
+ const tag = camelCase(options2.tag);
99
+ return path.resolve(root, renderTemplate(template, { tag }), baseName);
100
+ }
101
+ return path.resolve(root, output.path, baseName);
102
+ },
103
+ resolveName(name, type) {
104
+ let resolvedName = camelCase(name);
105
+ if (type === "file" || type === "function") {
106
+ resolvedName = camelCase(name, {
107
+ prefix: "use",
108
+ isFile: type === "file"
109
+ });
110
+ }
111
+ if (type === "type") {
112
+ resolvedName = pascalCase(name);
113
+ }
114
+ if (type) {
115
+ return transformers?.name?.(resolvedName, type) || resolvedName;
116
+ }
117
+ return resolvedName;
118
+ },
119
+ async buildStart() {
120
+ const [swaggerPlugin] = PluginManager.getDependedPlugins(this.plugins, [pluginOasName]);
121
+ const oas = await swaggerPlugin.api.getOas();
122
+ const root = path.resolve(this.config.root, this.config.output.path);
123
+ const mode = FileManager.getMode(path.resolve(root, output.path));
124
+ const operationGenerator = new OperationGenerator(this.plugin.options, {
125
+ oas,
126
+ pluginManager: this.pluginManager,
127
+ plugin: this.plugin,
128
+ contentType: swaggerPlugin.api.contentType,
129
+ exclude,
130
+ include,
131
+ override,
132
+ mode
133
+ });
134
+ const files = await operationGenerator.build();
135
+ await this.addFile(...files);
136
+ },
137
+ async writeFile(path2, source) {
138
+ if (!path2.endsWith(".ts") || !source) {
139
+ return;
140
+ }
141
+ return this.fileManager.write(path2, source, { sanity: false });
142
+ },
143
+ async buildEnd() {
144
+ if (this.config.output.write === false) {
145
+ return;
146
+ }
147
+ const root = path.resolve(this.config.root, this.config.output.path);
148
+ if (group?.type === "tag") {
149
+ const rootFiles = await getGroupedByTagFiles({
150
+ logger: this.logger,
151
+ files: this.fileManager.files,
152
+ plugin: this.plugin,
153
+ template,
154
+ exportAs: group.exportAs || "{{tag}}SWRHooks",
155
+ root,
156
+ output
157
+ });
158
+ await this.addFile(...rootFiles);
159
+ }
160
+ await this.fileManager.addIndexes({
161
+ root,
162
+ output,
163
+ meta: { pluginKey: this.plugin.key },
164
+ logger: this.logger
165
+ });
166
+ }
167
+ };
168
+ });
169
+
170
+ // src/index.ts
171
+ var definePluginDefault = pluginSwr;
172
+ var definePlugin = pluginSwr;
173
+ var src_default = definePluginDefault;
174
+ export {
175
+ src_default as default,
176
+ definePlugin,
177
+ pluginSwr,
178
+ pluginSwrName
179
+ };
180
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugin.ts","../src/OperationGenerator.tsx","../src/index.ts"],"sourcesContent":["import path from 'node:path'\n\nimport { FileManager, PluginManager, createPlugin } from '@kubb/core'\nimport { camelCase, pascalCase } from '@kubb/core/transformers'\nimport { renderTemplate } from '@kubb/core/utils'\nimport { pluginOasName } from '@kubb/plugin-oas'\nimport { getGroupedByTagFiles } from '@kubb/plugin-oas/utils'\nimport { pluginTsName } from '@kubb/plugin-ts'\nimport { pluginZodName } from '@kubb/plugin-zod'\n\nimport { OperationGenerator } from './OperationGenerator.tsx'\nimport { Mutation, Query, QueryOptions } from './components/index.ts'\n\nimport type { Plugin } from '@kubb/core'\nimport type { PluginOas as SwaggerPluginOptions } from '@kubb/plugin-oas'\nimport type { PluginSwr } from './types.ts'\n\nexport const pluginSwrName = 'plugin-swr' satisfies PluginSwr['name']\n\nexport const pluginSwr = createPlugin<PluginSwr>((options) => {\n const { output = { path: 'hooks' }, group, exclude = [], include, override = [], parser, transformers = {}, templates, dataReturnType = 'data' } = options\n const template = group?.output ? group.output : `${output.path}/{{tag}}SWRController`\n\n return {\n name: pluginSwrName,\n options: {\n extName: output.extName,\n templates: {\n mutation: Mutation.templates,\n query: Query.templates,\n queryOptions: QueryOptions.templates,\n ...templates,\n },\n client: {\n importPath: '@kubb/plugin-client/client',\n ...options.client,\n },\n dataReturnType,\n parser,\n },\n pre: [pluginOasName, pluginTsName, parser === 'zod' ? pluginZodName : undefined].filter(Boolean),\n resolvePath(baseName, pathMode, options) {\n const root = path.resolve(this.config.root, this.config.output.path)\n const mode = pathMode ?? FileManager.getMode(path.resolve(root, output.path))\n\n if (mode === 'single') {\n /**\n * when output is a file then we will always append to the same file(output file), see fileManager.addOrAppend\n * Other plugins then need to call addOrAppend instead of just add from the fileManager class\n */\n return path.resolve(root, output.path)\n }\n\n if (options?.tag && group?.type === 'tag') {\n const tag = camelCase(options.tag)\n\n return path.resolve(root, renderTemplate(template, { tag }), baseName)\n }\n\n return path.resolve(root, output.path, baseName)\n },\n resolveName(name, type) {\n let resolvedName = camelCase(name)\n\n if (type === 'file' || type === 'function') {\n resolvedName = camelCase(name, {\n prefix: 'use',\n isFile: type === 'file',\n })\n }\n\n if (type === 'type') {\n resolvedName = pascalCase(name)\n }\n\n if (type) {\n return transformers?.name?.(resolvedName, type) || resolvedName\n }\n\n return resolvedName\n },\n async buildStart() {\n const [swaggerPlugin]: [Plugin<SwaggerPluginOptions>] = PluginManager.getDependedPlugins<SwaggerPluginOptions>(this.plugins, [pluginOasName])\n\n const oas = await swaggerPlugin.api.getOas()\n const root = path.resolve(this.config.root, this.config.output.path)\n const mode = FileManager.getMode(path.resolve(root, output.path))\n\n const operationGenerator = new OperationGenerator(this.plugin.options, {\n oas,\n pluginManager: this.pluginManager,\n plugin: this.plugin,\n contentType: swaggerPlugin.api.contentType,\n exclude,\n include,\n override,\n mode,\n })\n\n const files = await operationGenerator.build()\n await this.addFile(...files)\n },\n async writeFile(path, source) {\n if (!path.endsWith('.ts') || !source) {\n return\n }\n\n return this.fileManager.write(path, source, { sanity: false })\n },\n async buildEnd() {\n if (this.config.output.write === false) {\n return\n }\n\n const root = path.resolve(this.config.root, this.config.output.path)\n\n if (group?.type === 'tag') {\n const rootFiles = await getGroupedByTagFiles({\n logger: this.logger,\n files: this.fileManager.files,\n plugin: this.plugin,\n template,\n exportAs: group.exportAs || '{{tag}}SWRHooks',\n root,\n output,\n })\n\n await this.addFile(...rootFiles)\n }\n\n await this.fileManager.addIndexes({\n root,\n output,\n meta: { pluginKey: this.plugin.key },\n logger: this.logger,\n })\n },\n }\n})\n","import { OperationGenerator as Generator } from '@kubb/plugin-oas'\nimport { Oas } from '@kubb/plugin-oas/components'\nimport { App, createRoot } from '@kubb/react'\n\nimport { Mutation } from './components/Mutation.tsx'\nimport { Query } from './components/Query.tsx'\n\nimport type { Operation } from '@kubb/oas'\nimport type { OperationMethodResult } from '@kubb/plugin-oas'\nimport type { FileMeta, PluginSwr } from './types.ts'\n\nexport class OperationGenerator extends Generator<PluginSwr['resolvedOptions'], PluginSwr, FileMeta> {\n async get(operation: Operation, options: PluginSwr['resolvedOptions']): OperationMethodResult<FileMeta> {\n const { oas, pluginManager, plugin, mode } = this.context\n\n const root = createRoot({\n logger: pluginManager.logger,\n })\n\n if (!options.templates?.query || !options.templates?.queryOptions) {\n return []\n }\n\n root.render(\n <App pluginManager={pluginManager} plugin={{ ...plugin, options }} mode={mode}>\n <Oas oas={oas} operations={[operation]} generator={this}>\n <Oas.Operation operation={operation}>\n <Query.File\n templates={{\n query: options.templates.query,\n queryOptions: options.templates.queryOptions,\n }}\n />\n </Oas.Operation>\n </Oas>\n </App>,\n )\n\n return root.files\n }\n\n async post(operation: Operation, options: PluginSwr['resolvedOptions']): OperationMethodResult<FileMeta> {\n const { oas, pluginManager, plugin, mode } = this.context\n\n const root = createRoot({\n logger: pluginManager.logger,\n })\n\n if (!options.templates?.mutation) {\n return []\n }\n\n root.render(\n <App pluginManager={pluginManager} plugin={{ ...plugin, options }} mode={mode}>\n <Oas oas={oas} operations={[operation]} generator={this}>\n <Oas.Operation operation={operation}>\n <Mutation.File templates={options.templates.mutation} />\n </Oas.Operation>\n </Oas>\n </App>,\n )\n\n return root.files\n }\n\n async put(operation: Operation, options: PluginSwr['resolvedOptions']): OperationMethodResult<FileMeta> {\n return this.post(operation, options)\n }\n async patch(operation: Operation, options: PluginSwr['resolvedOptions']): OperationMethodResult<FileMeta> {\n return this.post(operation, options)\n }\n async delete(operation: Operation, options: PluginSwr['resolvedOptions']): OperationMethodResult<FileMeta> {\n return this.post(operation, options)\n }\n}\n","import { pluginSwr } from './plugin.ts'\n\nexport { pluginSwr, pluginSwrName } from './plugin.ts'\nexport type { PluginSwr } from './types.ts'\n\n/**\n * @deprecated Use `import { pluginSwr } from '@kubb/plugin-swr'` instead\n */\nconst definePluginDefault = pluginSwr\n/**\n * @deprecated Use `import { pluginSwr } from '@kubb/plugin-swr'` instead\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A,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AAED,YAAM,QAAQ,MAAM,mBAAmB,MAAM;AAC7C,YAAM,KAAK,QAAQ,GAAG,KAAK;AAAA,IAC7B;AAAA,IACA,MAAM,UAAUC,OAAM,QAAQ;AAC5B,UAAI,CAACA,MAAK,SAAS,KAAK,KAAK,CAAC,QAAQ;AACpC;AAAA,MACF;AAEA,aAAO,KAAK,YAAY,MAAMA,OAAM,QAAQ,EAAE,QAAQ,MAAM,CAAC;AAAA,IAC/D;AAAA,IACA,MAAM,WAAW;AACf,UAAI,KAAK,OAAO,OAAO,UAAU,OAAO;AACtC;AAAA,MACF;AAEA,YAAM,OAAO,KAAK,QAAQ,KAAK,OAAO,MAAM,KAAK,OAAO,OAAO,IAAI;AAEnE,UAAI,OAAO,SAAS,OAAO;AACzB,cAAM,YAAY,MAAM,qBAAqB;AAAA,UAC3C,QAAQ,KAAK;AAAA,UACb,OAAO,KAAK,YAAY;AAAA,UACxB,QAAQ,KAAK;AAAA,UACb;AAAA,UACA,UAAU,MAAM,YAAY;AAAA,UAC5B;AAAA,UACA;AAAA,QACF,CAAC;AAED,cAAM,KAAK,QAAQ,GAAG,SAAS;AAAA,MACjC;AAEA,YAAM,KAAK,YAAY,WAAW;AAAA,QAChC;AAAA,QACA;AAAA,QACA,MAAM,EAAE,WAAW,KAAK,OAAO,IAAI;AAAA,QACnC,QAAQ,KAAK;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AACF,CAAC;;;AElID,IAAM,sBAAsB;AAIrB,IAAM,eAAe;AAE5B,IAAO,cAAQ;","names":["options","path"]}
package/package.json ADDED
@@ -0,0 +1,98 @@
1
+ {
2
+ "name": "@kubb/plugin-swr",
3
+ "version": "3.0.0-alpha.0",
4
+ "description": "Generator plugin-swr",
5
+ "keywords": [
6
+ "typescript",
7
+ "plugins",
8
+ "kubb",
9
+ "codegen",
10
+ "swagger",
11
+ "openapi",
12
+ "swr",
13
+ "vercel",
14
+ "nextjs",
15
+ "next",
16
+ "axios"
17
+ ],
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git://github.com/kubb-labs/kubb.git",
21
+ "directory": "packages/plugin-swr"
22
+ },
23
+ "license": "MIT",
24
+ "author": "Stijn Van Hulle <stijn@stijnvanhulle.be",
25
+ "sideEffects": false,
26
+ "type": "module",
27
+ "exports": {
28
+ ".": {
29
+ "import": "./dist/index.js",
30
+ "require": "./dist/index.cjs",
31
+ "default": "./dist/index.cjs"
32
+ },
33
+ "./components": {
34
+ "import": "./dist/components.js",
35
+ "require": "./dist/components.cjs",
36
+ "default": "./dist/components.cjs"
37
+ },
38
+ "./package.json": "./package.json",
39
+ "./*": "./*"
40
+ },
41
+ "main": "dist/index.cjs",
42
+ "module": "dist/index.js",
43
+ "types": "./dist/index.d.ts",
44
+ "typesVersions": {
45
+ "*": {
46
+ "components": [
47
+ "./dist/components.d.ts"
48
+ ]
49
+ }
50
+ },
51
+ "files": [
52
+ "src",
53
+ "dist",
54
+ "!/**/**.test.**",
55
+ "!/**/__tests__/**"
56
+ ],
57
+ "dependencies": {
58
+ "@kubb/core": "3.0.0-alpha.0",
59
+ "@kubb/fs": "3.0.0-alpha.0",
60
+ "@kubb/oas": "3.0.0-alpha.0",
61
+ "@kubb/parser-ts": "3.0.0-alpha.0",
62
+ "@kubb/plugin-client": "3.0.0-alpha.0",
63
+ "@kubb/plugin-oas": "3.0.0-alpha.0",
64
+ "@kubb/plugin-ts": "3.0.0-alpha.0",
65
+ "@kubb/react": "3.0.0-alpha.0",
66
+ "@kubb/plugin-zod": "3.0.0-alpha.0"
67
+ },
68
+ "devDependencies": {
69
+ "@types/react": "^18.3.3",
70
+ "react": "^18.3.1",
71
+ "tsup": "^8.2.4",
72
+ "typescript": "^5.5.4",
73
+ "@kubb/config-biome": "3.0.0-alpha.0",
74
+ "@kubb/config-ts": "3.0.0-alpha.0",
75
+ "@kubb/config-tsup": "3.0.0-alpha.0"
76
+ },
77
+ "peerDependencies": {
78
+ "@kubb/react": "3.0.0-alpha.0"
79
+ },
80
+ "engines": {
81
+ "node": ">=20"
82
+ },
83
+ "publishConfig": {
84
+ "access": "public",
85
+ "registry": "https://registry.npmjs.org/"
86
+ },
87
+ "scripts": {
88
+ "build": "tsup",
89
+ "clean": "rimraf ./dist",
90
+ "lint": "bun biome lint .",
91
+ "lint:fix": "bun biome lint --apply-unsafe .",
92
+ "release": "pnpm publish --no-git-check",
93
+ "release:canary": "bash ../../.github/canary.sh && node ../../scripts/build.js canary && pnpm publish --no-git-check",
94
+ "start": "tsup --watch",
95
+ "test": "vitest --passWithNoTests",
96
+ "typecheck": "tsc -p ./tsconfig.json --noEmit --emitDeclarationOnly false"
97
+ }
98
+ }
@@ -0,0 +1,75 @@
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 { Mutation } from './components/Mutation.tsx'
6
+ import { Query } from './components/Query.tsx'
7
+
8
+ import type { Operation } from '@kubb/oas'
9
+ import type { OperationMethodResult } from '@kubb/plugin-oas'
10
+ import type { FileMeta, PluginSwr } from './types.ts'
11
+
12
+ export class OperationGenerator extends Generator<PluginSwr['resolvedOptions'], PluginSwr, FileMeta> {
13
+ async get(operation: Operation, options: PluginSwr['resolvedOptions']): OperationMethodResult<FileMeta> {
14
+ const { oas, pluginManager, plugin, mode } = this.context
15
+
16
+ const root = createRoot({
17
+ logger: pluginManager.logger,
18
+ })
19
+
20
+ if (!options.templates?.query || !options.templates?.queryOptions) {
21
+ return []
22
+ }
23
+
24
+ root.render(
25
+ <App pluginManager={pluginManager} plugin={{ ...plugin, options }} mode={mode}>
26
+ <Oas oas={oas} operations={[operation]} generator={this}>
27
+ <Oas.Operation operation={operation}>
28
+ <Query.File
29
+ templates={{
30
+ query: options.templates.query,
31
+ queryOptions: options.templates.queryOptions,
32
+ }}
33
+ />
34
+ </Oas.Operation>
35
+ </Oas>
36
+ </App>,
37
+ )
38
+
39
+ return root.files
40
+ }
41
+
42
+ async post(operation: Operation, options: PluginSwr['resolvedOptions']): OperationMethodResult<FileMeta> {
43
+ const { oas, pluginManager, plugin, mode } = this.context
44
+
45
+ const root = createRoot({
46
+ logger: pluginManager.logger,
47
+ })
48
+
49
+ if (!options.templates?.mutation) {
50
+ return []
51
+ }
52
+
53
+ root.render(
54
+ <App pluginManager={pluginManager} plugin={{ ...plugin, options }} mode={mode}>
55
+ <Oas oas={oas} operations={[operation]} generator={this}>
56
+ <Oas.Operation operation={operation}>
57
+ <Mutation.File templates={options.templates.mutation} />
58
+ </Oas.Operation>
59
+ </Oas>
60
+ </App>,
61
+ )
62
+
63
+ return root.files
64
+ }
65
+
66
+ async put(operation: Operation, options: PluginSwr['resolvedOptions']): OperationMethodResult<FileMeta> {
67
+ return this.post(operation, options)
68
+ }
69
+ async patch(operation: Operation, options: PluginSwr['resolvedOptions']): OperationMethodResult<FileMeta> {
70
+ return this.post(operation, options)
71
+ }
72
+ async delete(operation: Operation, options: PluginSwr['resolvedOptions']): OperationMethodResult<FileMeta> {
73
+ return this.post(operation, options)
74
+ }
75
+ }
@@ -0,0 +1,252 @@
1
+ import transformers from '@kubb/core/transformers'
2
+ import { FunctionParams, URLPath } from '@kubb/core/utils'
3
+ import { Parser, File, Function, useApp } from '@kubb/react'
4
+ import { pluginTsName } from '@kubb/plugin-ts'
5
+ import { useOperation, useOperationManager } from '@kubb/plugin-oas/hooks'
6
+ import { getASTParams, getComments } from '@kubb/plugin-oas/utils'
7
+
8
+ import { SchemaType } from './SchemaType.tsx'
9
+
10
+ import type { HttpMethod } from '@kubb/oas'
11
+ import type { ReactNode } from 'react'
12
+ import type { FileMeta, PluginSwr } from '../types.ts'
13
+
14
+ type TemplateProps = {
15
+ /**
16
+ * Name of the function
17
+ */
18
+ name: string
19
+ /**
20
+ * Parameters/options/props that need to be used
21
+ */
22
+ params: string
23
+ /**
24
+ * Generics that needs to be added for TypeScript
25
+ */
26
+ generics?: string
27
+ /**
28
+ * ReturnType(see async for adding Promise type)
29
+ */
30
+ returnType?: string
31
+ /**
32
+ * Options for JSdocs
33
+ */
34
+ JSDoc?: {
35
+ comments: string[]
36
+ }
37
+ hook: {
38
+ name: string
39
+ generics?: string
40
+ }
41
+ client: {
42
+ method: HttpMethod
43
+ generics: string
44
+ withQueryParams: boolean
45
+ withPathParams: boolean
46
+ withData: boolean
47
+ withHeaders: boolean
48
+ path: URLPath
49
+ }
50
+ dataReturnType: NonNullable<PluginSwr['options']['dataReturnType']>
51
+ }
52
+
53
+ function Template({ name, generics, returnType, params, JSDoc, client, hook, dataReturnType }: TemplateProps): ReactNode {
54
+ const clientOptions = [
55
+ `method: "${client.method}"`,
56
+ 'url',
57
+ client.withQueryParams ? 'params' : undefined,
58
+ client.withData ? 'data' : undefined,
59
+ client.withHeaders ? 'headers: { ...headers, ...clientOptions.headers }' : undefined,
60
+ '...clientOptions',
61
+ ].filter(Boolean)
62
+
63
+ const resolvedClientOptions = `${transformers.createIndent(4)}${clientOptions.join(`,\n${transformers.createIndent(4)}`)}`
64
+ if (client.withQueryParams) {
65
+ return (
66
+ <Function export name={name} generics={generics} returnType={returnType} params={params} JSDoc={JSDoc}>
67
+ {`
68
+ const { mutation: mutationOptions, client: clientOptions = {}, shouldFetch = true } = options ?? {}
69
+
70
+ const url = ${client.path.template} as const
71
+ return ${hook.name}<${hook.generics}>(
72
+ shouldFetch ? [url, params]: null,
73
+ async (_url${client.withData ? ', { arg: data }' : ''}) => {
74
+ const res = await client<${client.generics}>({
75
+ ${resolvedClientOptions}
76
+ })
77
+
78
+ return ${dataReturnType === 'data' ? 'res.data' : 'res'}
79
+ },
80
+ mutationOptions
81
+ )
82
+ `}
83
+ </Function>
84
+ )
85
+ }
86
+ return (
87
+ <Function export name={name} generics={generics} returnType={returnType} params={params} JSDoc={JSDoc}>
88
+ {`
89
+ const { mutation: mutationOptions, client: clientOptions = {}, shouldFetch = true } = options ?? {}
90
+
91
+ const url = ${client.path.template} as const
92
+ return ${hook.name}<${hook.generics}>(
93
+ shouldFetch ? url : null,
94
+ async (_url${client.withData ? ', { arg: data }' : ''}) => {
95
+ const res = await client<${client.generics}>({
96
+ ${resolvedClientOptions}
97
+ })
98
+
99
+ return ${dataReturnType === 'data' ? 'res.data' : 'res'}
100
+ },
101
+ mutationOptions
102
+ )
103
+ `}
104
+ </Function>
105
+ )
106
+ }
107
+
108
+ const defaultTemplates = {
109
+ default: Template,
110
+ } as const
111
+
112
+ type Props = {
113
+ factory: {
114
+ name: string
115
+ }
116
+ /**
117
+ * This will make it possible to override the default behaviour.
118
+ */
119
+ Template?: React.ComponentType<TemplateProps>
120
+ }
121
+
122
+ export function Mutation({ factory, Template = defaultTemplates.default }: Props): ReactNode {
123
+ const {
124
+ plugin: {
125
+ options: { dataReturnType },
126
+ },
127
+ } = useApp<PluginSwr>()
128
+ const { getSchemas, getName } = useOperationManager()
129
+ const operation = useOperation()
130
+
131
+ const name = getName(operation, { type: 'function' })
132
+ const schemas = getSchemas(operation, { pluginKey: [pluginTsName], type: 'type' })
133
+
134
+ const params = new FunctionParams()
135
+ const client = {
136
+ method: operation.method,
137
+ path: new URLPath(operation.path),
138
+ generics: [`${factory.name}["data"]`, `${factory.name}["error"]`, schemas.request?.name ? `${factory.name}["request"]` : ''].filter(Boolean).join(', '),
139
+ withQueryParams: !!schemas.queryParams?.name,
140
+ withData: !!schemas.request?.name,
141
+ withPathParams: !!schemas.pathParams?.name,
142
+ withHeaders: !!schemas.headerParams?.name,
143
+ }
144
+
145
+ const resultGenerics = [`${factory.name}["response"]`, `${factory.name}["error"]`]
146
+
147
+ params.add([
148
+ ...getASTParams(schemas.pathParams, { typed: true }),
149
+ {
150
+ name: 'params',
151
+ type: `${factory.name}['queryParams']`,
152
+ enabled: client.withQueryParams,
153
+ required: false,
154
+ },
155
+ {
156
+ name: 'headers',
157
+ type: `${factory.name}['headerParams']`,
158
+ enabled: client.withHeaders,
159
+ required: false,
160
+ },
161
+ {
162
+ name: 'options',
163
+ required: false,
164
+ type: `{
165
+ mutation?: SWRMutationConfiguration<${resultGenerics.join(', ')}>,
166
+ client?: ${factory.name}['client']['parameters'],
167
+ shouldFetch?: boolean,
168
+ }`,
169
+ default: '{}',
170
+ },
171
+ ])
172
+
173
+ const hook = {
174
+ name: 'useSWRMutation',
175
+ generics: [...resultGenerics, client.withQueryParams ? '[typeof url, typeof params] | null' : 'typeof url | null'].join(', '),
176
+ }
177
+
178
+ return (
179
+ <Template
180
+ name={name}
181
+ JSDoc={{ comments: getComments(operation) }}
182
+ client={client}
183
+ hook={hook}
184
+ params={params.toString()}
185
+ returnType={`SWRMutationResponse<${resultGenerics.join(', ')}>`}
186
+ dataReturnType={dataReturnType}
187
+ />
188
+ )
189
+ }
190
+
191
+ type FileProps = {
192
+ /**
193
+ * This will make it possible to override the default behaviour.
194
+ */
195
+ templates?: typeof defaultTemplates
196
+ }
197
+
198
+ Mutation.File = function ({ templates = defaultTemplates }: FileProps): ReactNode {
199
+ const {
200
+ plugin: {
201
+ options: {
202
+ extName,
203
+ client: { importPath },
204
+ },
205
+ },
206
+ } = useApp<PluginSwr>()
207
+
208
+ const { getSchemas, getFile, getName } = useOperationManager()
209
+ const operation = useOperation()
210
+
211
+ const schemas = getSchemas(operation, { pluginKey: [pluginTsName], type: 'type' })
212
+ const file = getFile(operation)
213
+ const fileType = getFile(operation, { pluginKey: [pluginTsName] })
214
+ const factoryName = getName(operation, { type: 'type' })
215
+
216
+ const Template = templates.default
217
+ const factory = {
218
+ name: factoryName,
219
+ }
220
+
221
+ return (
222
+ <Parser language="typescript">
223
+ <File<FileMeta> baseName={file.baseName} path={file.path} meta={file.meta}>
224
+ <File.Import name="useSWRMutation" path="swr/mutation" />
225
+ <File.Import name={['SWRMutationConfiguration', 'SWRMutationResponse']} path="swr/mutation" isTypeOnly />
226
+ <File.Import name={'client'} path={importPath} />
227
+ <File.Import name={['ResponseConfig']} path={importPath} isTypeOnly />
228
+ <File.Import
229
+ extName={extName}
230
+ name={[
231
+ schemas.request?.name,
232
+ schemas.response.name,
233
+ schemas.pathParams?.name,
234
+ schemas.queryParams?.name,
235
+ schemas.headerParams?.name,
236
+ ...(schemas.errors?.map((error) => error.name) || []),
237
+ ].filter(Boolean)}
238
+ root={file.path}
239
+ path={fileType.path}
240
+ isTypeOnly
241
+ />
242
+
243
+ <File.Source>
244
+ <SchemaType factory={factory} />
245
+ <Mutation Template={Template} factory={factory} />
246
+ </File.Source>
247
+ </File>
248
+ </Parser>
249
+ )
250
+ }
251
+
252
+ Mutation.templates = defaultTemplates