api-farmer 0.0.16 → 0.0.18

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 varletjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -56,32 +56,6 @@ npx af
56
56
 
57
57
  Some simple usage examples can be found [here](fixtures)
58
58
 
59
- ### Custom EJS Template
60
-
61
- Create `api-farmer.ejs` in the project root, which will replace the `preset` template.
62
- The template format can refer to the preset template listed below:
63
-
64
- - [Axle](templates/axle.ejs)
65
- - [Axios](templates/axios.ejs)
66
-
67
- See the bottom of the document for template variable definitions.
68
-
69
- ### Status Code Strategy
70
-
71
- `smart`: find a valid status code between [`200`, `299`] that is closest to `200` <br>
72
- `loose`: all success status codes are `200` <br>
73
- `strict`: `Restful API` recommends using different successful http status codes for different methods, such as `get: 200`, `post: 201`, etc. <br>
74
-
75
- ```ts
76
- // api-farmer.config.ts
77
- import { defineConfig } from 'api-farmer'
78
-
79
- export default defineConfig({
80
- // 'strict' or 'loose' or 'smart', defaults 'smart'
81
- statusCodeStrategy: 'strict',
82
- })
83
- ```
84
-
85
59
  ### Transformer API
86
60
 
87
61
  You can use the Transformer API to further define template variables, which will override the default transformation rules.
@@ -112,16 +86,28 @@ export default defineConfig({
112
86
  })
113
87
  ```
114
88
 
89
+ ### Custom EJS Template
90
+
91
+ Create `api-farmer.ejs` in the project root, which will replace the `preset` template.
92
+ The template format can refer to the preset template listed below:
93
+
94
+ - [Axle](templates/axle.ejs)
95
+ - [Axios](templates/axios.ejs)
96
+
97
+ See the bottom of the document for template variable definitions.
98
+
115
99
  ### Configuration Options
116
100
 
117
101
  ```ts
118
102
  export interface Config {
119
103
  /**
120
104
  * The path to the OpenAPI/Swagger schema file.
105
+ * @default './schema.json'
121
106
  */
122
107
  input?: string
123
108
  /**
124
109
  * The path to the output directory.
110
+ * @default './src/apis/generated'
125
111
  */
126
112
  output?: string
127
113
  /**
@@ -130,43 +116,38 @@ export interface Config {
130
116
  base?: string
131
117
  /**
132
118
  * The filename of the generated openapi types file.
119
+ * @default '_types.ts'
133
120
  */
134
121
  typesFilename?: string
135
- /**
136
- * The transformer api options, used to override the default transformation rules.
137
- */
138
- transformer?: Partial<Transformer>
139
122
  /**
140
123
  * Whether to generate TypeScript code.
124
+ * @default true
141
125
  */
142
126
  ts?: boolean
127
+ /**
128
+ * Whether to generate only types.
129
+ * @default false
130
+ */
131
+ typesOnly?: boolean
143
132
  /**
144
133
  * Whether to override the existing files, or an array of filenames to override.
134
+ * @default true
145
135
  */
146
136
  overrides?: boolean | string[]
147
137
  /**
148
138
  * The preset ejs template to use.
139
+ * @default 'axle'
149
140
  */
150
141
  preset?: Preset
151
142
  /**
152
- * The status code strategy to use.
153
- * loose: all success status codes are 200,
154
- * strict: use the openapi recommended success status codes.
155
- * smart: find a valid status code between [200, 299] that is closest to 200
143
+ * Defines which return status codes will be typed
144
+ * @default (status) => status >= 200 && status < 300
156
145
  */
157
- statusCodeStrategy?: StatusCodeStrategy
146
+ validateStatus?: (status: number) => boolean
158
147
  /**
159
- * The status codes to override the default status codes.
148
+ * The transformer api options, used to override the default transformation rules.
160
149
  */
161
- statusCodes?: {
162
- get?: number
163
- post?: number
164
- put?: number
165
- delete?: number
166
- patch?: number
167
- options?: number
168
- head?: number
169
- }
150
+ transformer?: Partial<Transformer>
170
151
  }
171
152
  ```
172
153
 
@@ -186,6 +167,10 @@ export interface ApiModuleTemplateData {
186
167
  * Whether to generate ts code
187
168
  */
188
169
  ts: boolean
170
+ /**
171
+ * Whether to generate only types.
172
+ */
173
+ typesOnly?: boolean
189
174
  }
190
175
 
191
176
  export interface ApiModule {
@@ -1,13 +1,12 @@
1
1
  import {
2
2
  CWD,
3
3
  SUPPORTED_HTTP_METHODS,
4
- createStatusCodesByStrategy,
5
- doStatusCodeStrategy,
4
+ getValidResponseMetadataItems,
6
5
  hasQueryParameter,
7
6
  isRequiredRequestBody,
8
7
  readSchema,
9
8
  readTemplateFile
10
- } from "./chunk-LYOTF4II.js";
9
+ } from "./chunk-SKKHIIUE.js";
11
10
  import {
12
11
  __export
13
12
  } from "./chunk-6OIOYGN7.js";
@@ -22804,10 +22803,9 @@ function transformTypeResponseBody({
22804
22803
  }
22805
22804
  function transformTypeResponseBodyValue({
22806
22805
  type: type2,
22807
- statusCode,
22808
- mime
22806
+ responseMetadataItems
22809
22807
  }) {
22810
- return `${type2}['responses']['${statusCode}']['content']['${mime}']`;
22808
+ return responseMetadataItems.map(({ status, mime }) => `${type2}['responses']['${status}']['content']['${mime}']`).join(" | ");
22811
22809
  }
22812
22810
  function createTransformer() {
22813
22811
  return {
@@ -22829,7 +22827,7 @@ function createTransformer() {
22829
22827
 
22830
22828
  // src/generate.ts
22831
22829
  function transformPayloads(pathItems, options8) {
22832
- const { transformer, path: path13, base, statusCodeStrategy, statusCodes } = options8;
22830
+ const { transformer, path: path13, base, validateStatus } = options8;
22833
22831
  return Object.entries(pathItems).filter(([key2]) => SUPPORTED_HTTP_METHODS.includes(key2)).reduce((payloads, [method, operation]) => {
22834
22832
  const url2 = transformer.url({ path: path13, base });
22835
22833
  const args = { path: path13, base, url: url2, method, operation };
@@ -22848,13 +22846,9 @@ function transformPayloads(pathItems, options8) {
22848
22846
  entity,
22849
22847
  required: isRequiredRequestBody(operation.requestBody)
22850
22848
  }) : "undefined";
22851
- const { mime, statusCode } = doStatusCodeStrategy(
22852
- operation,
22853
- statusCodes[method] ?? 200,
22854
- statusCodeStrategy
22855
- );
22856
22849
  const typeResponseBody = transformer.typeResponseBody({ ...args, type: type2, verb, entity });
22857
- const typeResponseBodyValue = mime && statusCode ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, statusCode, mime }) : "undefined";
22850
+ const responseMetadataItems = getValidResponseMetadataItems(operation, validateStatus);
22851
+ const typeResponseBodyValue = responseMetadataItems.length > 0 ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, responseMetadataItems }) : "undefined";
22858
22852
  payloads.push({
22859
22853
  fn,
22860
22854
  url: url2,
@@ -22874,14 +22868,16 @@ function transformPayloads(pathItems, options8) {
22874
22868
  }, []);
22875
22869
  }
22876
22870
  function partitionApiModules(schema2, options8) {
22877
- const { base, transformer } = options8;
22871
+ const { base, transformer, validateStatus } = options8;
22878
22872
  const schemaPaths = schema2.paths ?? {};
22879
22873
  const schemaPathKeys = base ? Object.keys(schemaPaths).map((key2) => key2.replace(base, "")) : Object.keys(schemaPaths);
22880
22874
  const keyToPaths = groupBy(schemaPathKeys, (key2) => key2.split("/")[1]);
22881
22875
  const apiModules = Object.entries(keyToPaths).reduce((apiModules2, [name, paths]) => {
22882
22876
  const payloads = paths.reduce((payloads2, path13) => {
22883
22877
  const pathItems = schemaPaths[path13];
22884
- payloads2.push(...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer }));
22878
+ payloads2.push(
22879
+ ...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer, validateStatus })
22880
+ );
22885
22881
  return payloads2;
22886
22882
  }, []);
22887
22883
  apiModules2.push({ name: transformer.moduleName({ name }), payloads });
@@ -22890,7 +22886,7 @@ function partitionApiModules(schema2, options8) {
22890
22886
  return apiModules;
22891
22887
  }
22892
22888
  function renderApiModules(apiModules, options8) {
22893
- const { output, ts, overrides, preset } = options8;
22889
+ const { output, ts, typesOnly, overrides, preset } = options8;
22894
22890
  const templateFile = readTemplateFile(preset);
22895
22891
  const typesFilename = options8.typesFilename.replace(".ts", "");
22896
22892
  return Promise.all(
@@ -22899,7 +22895,8 @@ function renderApiModules(apiModules, options8) {
22899
22895
  const data = {
22900
22896
  apiModule,
22901
22897
  typesFilename,
22902
- ts
22898
+ ts,
22899
+ typesOnly
22903
22900
  };
22904
22901
  src_default.format(ejs.render(templateFile, data), {
22905
22902
  parser: "typescript",
@@ -22935,18 +22932,15 @@ async function generate(userOptions = {}) {
22935
22932
  const {
22936
22933
  base,
22937
22934
  ts = true,
22935
+ typesOnly = false,
22938
22936
  overrides = true,
22939
22937
  preset = "axle",
22940
- statusCodeStrategy = "smart",
22941
22938
  input = "./schema.json",
22942
22939
  output = "./src/apis/generated",
22943
22940
  typesFilename = "_types.ts",
22941
+ validateStatus = (status) => status >= 200 && status < 300,
22944
22942
  transformer = {}
22945
22943
  } = options8;
22946
- const statusCodes = {
22947
- ...createStatusCodesByStrategy(statusCodeStrategy),
22948
- ...options8.statusCodes ?? {}
22949
- };
22950
22944
  const mergedTransformer = { ...createTransformer(), ...transformer };
22951
22945
  const schema2 = await readSchema(input);
22952
22946
  logger.info("Generating API modules...");
@@ -22954,12 +22948,11 @@ async function generate(userOptions = {}) {
22954
22948
  await generateTypes(schema2, output, typesFilename);
22955
22949
  }
22956
22950
  const apiModules = partitionApiModules(schema2, {
22957
- statusCodes,
22958
- statusCodeStrategy,
22959
22951
  base,
22960
- transformer: mergedTransformer
22952
+ transformer: mergedTransformer,
22953
+ validateStatus
22961
22954
  });
22962
- await renderApiModules(apiModules, { output, typesFilename, ts, overrides, preset });
22955
+ await renderApiModules(apiModules, { output, typesFilename, ts, typesOnly, overrides, preset });
22963
22956
  logger.success("Done");
22964
22957
  }
22965
22958
 
@@ -68,24 +68,18 @@ function getCliVersion() {
68
68
  function isRequiredRequestBody(value) {
69
69
  return "required" in value && value.required === true;
70
70
  }
71
- function doStatusCodeStrategy(operation, statusCode, strategy) {
72
- if (strategy === "smart") {
73
- const responses = operation.responses ?? {};
74
- const codeKey = Object.keys(responses).sort((a, b) => Number(a) - Number(b)).find((codeKey2) => Number(codeKey2) >= 200 && Number(codeKey2) <= 299);
75
- if (!codeKey) {
76
- return {
77
- statusCode: void 0,
78
- mime: void 0
79
- };
80
- }
81
- statusCode = Number(codeKey);
82
- }
83
- const content = operation.responses?.[statusCode]?.content;
84
- const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
85
- return {
86
- statusCode,
87
- mime
88
- };
71
+ function getValidResponseMetadataItems(operation, validateStatus) {
72
+ const responses = operation.responses ?? {};
73
+ const validStatusResults = Object.keys(responses).sort((a, b) => Number(a) - Number(b)).filter((key) => validateStatus(Number(key))).map(Number);
74
+ const results = validStatusResults.map((status) => {
75
+ const content = operation.responses?.[status]?.content;
76
+ const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
77
+ return {
78
+ status,
79
+ mime
80
+ };
81
+ }).filter((result) => result.mime);
82
+ return results;
89
83
  }
90
84
 
91
85
  export {
@@ -97,5 +91,5 @@ export {
97
91
  hasQueryParameter,
98
92
  getCliVersion,
99
93
  isRequiredRequestBody,
100
- doStatusCodeStrategy
94
+ getValidResponseMetadataItems
101
95
  };
package/dist/cli.cjs CHANGED
@@ -55,37 +55,6 @@ var init_constants = __esm({
55
55
  });
56
56
 
57
57
  // src/utils.ts
58
- function createStatusCodesByStrategy(strategy) {
59
- return {
60
- strict: {
61
- get: 200,
62
- post: 201,
63
- put: 200,
64
- delete: 204,
65
- patch: 200,
66
- options: 204,
67
- head: 200
68
- },
69
- loose: {
70
- get: 200,
71
- post: 200,
72
- put: 200,
73
- delete: 200,
74
- patch: 200,
75
- options: 200,
76
- head: 200
77
- },
78
- smart: {
79
- get: 200,
80
- post: 200,
81
- put: 200,
82
- delete: 200,
83
- patch: 200,
84
- options: 200,
85
- head: 200
86
- }
87
- }[strategy];
88
- }
89
58
  async function readSchema(input) {
90
59
  const isYaml = input.endsWith(".yaml");
91
60
  const path13 = (0, import_path2.resolve)(CWD, input);
@@ -109,24 +78,18 @@ function getCliVersion() {
109
78
  function isRequiredRequestBody(value) {
110
79
  return "required" in value && value.required === true;
111
80
  }
112
- function doStatusCodeStrategy(operation, statusCode, strategy) {
113
- if (strategy === "smart") {
114
- const responses = operation.responses ?? {};
115
- const codeKey = Object.keys(responses).sort((a5, b8) => Number(a5) - Number(b8)).find((codeKey2) => Number(codeKey2) >= 200 && Number(codeKey2) <= 299);
116
- if (!codeKey) {
117
- return {
118
- statusCode: void 0,
119
- mime: void 0
120
- };
121
- }
122
- statusCode = Number(codeKey);
123
- }
124
- const content = operation.responses?.[statusCode]?.content;
125
- const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
126
- return {
127
- statusCode,
128
- mime
129
- };
81
+ function getValidResponseMetadataItems(operation, validateStatus) {
82
+ const responses = operation.responses ?? {};
83
+ const validStatusResults = Object.keys(responses).sort((a5, b8) => Number(a5) - Number(b8)).filter((key2) => validateStatus(Number(key2))).map(Number);
84
+ const results = validStatusResults.map((status) => {
85
+ const content = operation.responses?.[status]?.content;
86
+ const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
87
+ return {
88
+ status,
89
+ mime
90
+ };
91
+ }).filter((result) => result.mime);
92
+ return results;
130
93
  }
131
94
  var import_path2, import_fs_extra, import_swagger2openapi, import_yaml;
132
95
  var init_utils = __esm({
@@ -102088,10 +102051,9 @@ function transformTypeResponseBody({
102088
102051
  }
102089
102052
  function transformTypeResponseBodyValue({
102090
102053
  type: type2,
102091
- statusCode,
102092
- mime
102054
+ responseMetadataItems
102093
102055
  }) {
102094
- return `${type2}['responses']['${statusCode}']['content']['${mime}']`;
102056
+ return responseMetadataItems.map(({ status, mime }) => `${type2}['responses']['${status}']['content']['${mime}']`).join(" | ");
102095
102057
  }
102096
102058
  function createTransformer() {
102097
102059
  return {
@@ -102130,7 +102092,7 @@ __export(generate_exports, {
102130
102092
  transformPayloads: () => transformPayloads
102131
102093
  });
102132
102094
  function transformPayloads(pathItems, options8) {
102133
- const { transformer, path: path13, base, statusCodeStrategy, statusCodes } = options8;
102095
+ const { transformer, path: path13, base, validateStatus } = options8;
102134
102096
  return Object.entries(pathItems).filter(([key2]) => SUPPORTED_HTTP_METHODS.includes(key2)).reduce((payloads, [method, operation]) => {
102135
102097
  const url2 = transformer.url({ path: path13, base });
102136
102098
  const args = { path: path13, base, url: url2, method, operation };
@@ -102149,13 +102111,9 @@ function transformPayloads(pathItems, options8) {
102149
102111
  entity,
102150
102112
  required: isRequiredRequestBody(operation.requestBody)
102151
102113
  }) : "undefined";
102152
- const { mime, statusCode } = doStatusCodeStrategy(
102153
- operation,
102154
- statusCodes[method] ?? 200,
102155
- statusCodeStrategy
102156
- );
102157
102114
  const typeResponseBody = transformer.typeResponseBody({ ...args, type: type2, verb, entity });
102158
- const typeResponseBodyValue = mime && statusCode ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, statusCode, mime }) : "undefined";
102115
+ const responseMetadataItems = getValidResponseMetadataItems(operation, validateStatus);
102116
+ const typeResponseBodyValue = responseMetadataItems.length > 0 ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, responseMetadataItems }) : "undefined";
102159
102117
  payloads.push({
102160
102118
  fn: fn8,
102161
102119
  url: url2,
@@ -102175,14 +102133,16 @@ function transformPayloads(pathItems, options8) {
102175
102133
  }, []);
102176
102134
  }
102177
102135
  function partitionApiModules(schema2, options8) {
102178
- const { base, transformer } = options8;
102136
+ const { base, transformer, validateStatus } = options8;
102179
102137
  const schemaPaths = schema2.paths ?? {};
102180
102138
  const schemaPathKeys = base ? Object.keys(schemaPaths).map((key2) => key2.replace(base, "")) : Object.keys(schemaPaths);
102181
102139
  const keyToPaths = (0, import_rattail2.groupBy)(schemaPathKeys, (key2) => key2.split("/")[1]);
102182
102140
  const apiModules = Object.entries(keyToPaths).reduce((apiModules2, [name, paths]) => {
102183
102141
  const payloads = paths.reduce((payloads2, path13) => {
102184
102142
  const pathItems = schemaPaths[path13];
102185
- payloads2.push(...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer }));
102143
+ payloads2.push(
102144
+ ...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer, validateStatus })
102145
+ );
102186
102146
  return payloads2;
102187
102147
  }, []);
102188
102148
  apiModules2.push({ name: transformer.moduleName({ name }), payloads });
@@ -102191,7 +102151,7 @@ function partitionApiModules(schema2, options8) {
102191
102151
  return apiModules;
102192
102152
  }
102193
102153
  function renderApiModules(apiModules, options8) {
102194
- const { output, ts: ts9, overrides, preset } = options8;
102154
+ const { output, ts: ts9, typesOnly, overrides, preset } = options8;
102195
102155
  const templateFile = readTemplateFile(preset);
102196
102156
  const typesFilename = options8.typesFilename.replace(".ts", "");
102197
102157
  return Promise.all(
@@ -102200,7 +102160,8 @@ function renderApiModules(apiModules, options8) {
102200
102160
  const data = {
102201
102161
  apiModule,
102202
102162
  typesFilename,
102203
- ts: ts9
102163
+ ts: ts9,
102164
+ typesOnly
102204
102165
  };
102205
102166
  src_default.format(import_ejs.default.render(templateFile, data), {
102206
102167
  parser: "typescript",
@@ -102236,18 +102197,15 @@ async function generate(userOptions = {}) {
102236
102197
  const {
102237
102198
  base,
102238
102199
  ts: ts9 = true,
102200
+ typesOnly = false,
102239
102201
  overrides = true,
102240
102202
  preset = "axle",
102241
- statusCodeStrategy = "smart",
102242
102203
  input = "./schema.json",
102243
102204
  output = "./src/apis/generated",
102244
102205
  typesFilename = "_types.ts",
102206
+ validateStatus = (status) => status >= 200 && status < 300,
102245
102207
  transformer = {}
102246
102208
  } = options8;
102247
- const statusCodes = {
102248
- ...createStatusCodesByStrategy(statusCodeStrategy),
102249
- ...options8.statusCodes ?? {}
102250
- };
102251
102209
  const mergedTransformer = { ...createTransformer(), ...transformer };
102252
102210
  const schema2 = await readSchema(input);
102253
102211
  import_rslog.logger.info("Generating API modules...");
@@ -102255,12 +102213,11 @@ async function generate(userOptions = {}) {
102255
102213
  await generateTypes(schema2, output, typesFilename);
102256
102214
  }
102257
102215
  const apiModules = partitionApiModules(schema2, {
102258
- statusCodes,
102259
- statusCodeStrategy,
102260
102216
  base,
102261
- transformer: mergedTransformer
102217
+ transformer: mergedTransformer,
102218
+ validateStatus
102262
102219
  });
102263
- await renderApiModules(apiModules, { output, typesFilename, ts: ts9, overrides, preset });
102220
+ await renderApiModules(apiModules, { output, typesFilename, ts: ts9, typesOnly, overrides, preset });
102264
102221
  import_rslog.logger.success("Done");
102265
102222
  }
102266
102223
  var import_path14, import_ejs, import_fs_extra2, import_openapi_typescript, import_rattail2, import_rslog;
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  getCliVersion
4
- } from "./chunk-LYOTF4II.js";
4
+ } from "./chunk-SKKHIIUE.js";
5
5
  import "./chunk-6OIOYGN7.js";
6
6
 
7
7
  // src/cli.ts
@@ -9,7 +9,7 @@ import { Command } from "commander";
9
9
  var program = new Command();
10
10
  program.version(getCliVersion());
11
11
  program.action(async () => {
12
- const { generate } = await import("./generate-RJ23AKV7.js");
12
+ const { generate } = await import("./generate-IJGTBA2I.js");
13
13
  return generate();
14
14
  });
15
15
  program.parse();
@@ -4,8 +4,8 @@ import {
4
4
  partitionApiModules,
5
5
  renderApiModules,
6
6
  transformPayloads
7
- } from "./chunk-VAAFC73D.js";
8
- import "./chunk-LYOTF4II.js";
7
+ } from "./chunk-K46PCBCF.js";
8
+ import "./chunk-SKKHIIUE.js";
9
9
  import "./chunk-6OIOYGN7.js";
10
10
  export {
11
11
  generate,
package/dist/index.cjs CHANGED
@@ -79228,11 +79228,11 @@ __export(index_exports, {
79228
79228
  createStatusCodesByStrategy: () => createStatusCodesByStrategy,
79229
79229
  createTransformer: () => createTransformer,
79230
79230
  defineConfig: () => defineConfig,
79231
- doStatusCodeStrategy: () => doStatusCodeStrategy,
79232
79231
  generate: () => generate,
79233
79232
  generateTypes: () => generateTypes,
79234
79233
  getCliVersion: () => getCliVersion,
79235
79234
  getConfig: () => getConfig,
79235
+ getValidResponseMetadataItems: () => getValidResponseMetadataItems,
79236
79236
  hasQueryParameter: () => hasQueryParameter,
79237
79237
  isRequiredRequestBody: () => isRequiredRequestBody,
79238
79238
  partitionApiModules: () => partitionApiModules,
@@ -79328,10 +79328,9 @@ function transformTypeResponseBody({
79328
79328
  }
79329
79329
  function transformTypeResponseBodyValue({
79330
79330
  type: type2,
79331
- statusCode,
79332
- mime
79331
+ responseMetadataItems
79333
79332
  }) {
79334
- return `${type2}['responses']['${statusCode}']['content']['${mime}']`;
79333
+ return responseMetadataItems.map(({ status, mime }) => `${type2}['responses']['${status}']['content']['${mime}']`).join(" | ");
79335
79334
  }
79336
79335
  function createTransformer() {
79337
79336
  return {
@@ -102146,29 +102145,23 @@ function getCliVersion() {
102146
102145
  function isRequiredRequestBody(value) {
102147
102146
  return "required" in value && value.required === true;
102148
102147
  }
102149
- function doStatusCodeStrategy(operation, statusCode, strategy) {
102150
- if (strategy === "smart") {
102151
- const responses = operation.responses ?? {};
102152
- const codeKey = Object.keys(responses).sort((a5, b8) => Number(a5) - Number(b8)).find((codeKey2) => Number(codeKey2) >= 200 && Number(codeKey2) <= 299);
102153
- if (!codeKey) {
102154
- return {
102155
- statusCode: void 0,
102156
- mime: void 0
102157
- };
102158
- }
102159
- statusCode = Number(codeKey);
102160
- }
102161
- const content = operation.responses?.[statusCode]?.content;
102162
- const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
102163
- return {
102164
- statusCode,
102165
- mime
102166
- };
102148
+ function getValidResponseMetadataItems(operation, validateStatus) {
102149
+ const responses = operation.responses ?? {};
102150
+ const validStatusResults = Object.keys(responses).sort((a5, b8) => Number(a5) - Number(b8)).filter((key2) => validateStatus(Number(key2))).map(Number);
102151
+ const results = validStatusResults.map((status) => {
102152
+ const content = operation.responses?.[status]?.content;
102153
+ const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
102154
+ return {
102155
+ status,
102156
+ mime
102157
+ };
102158
+ }).filter((result) => result.mime);
102159
+ return results;
102167
102160
  }
102168
102161
 
102169
102162
  // src/generate.ts
102170
102163
  function transformPayloads(pathItems, options8) {
102171
- const { transformer, path: path13, base, statusCodeStrategy, statusCodes } = options8;
102164
+ const { transformer, path: path13, base, validateStatus } = options8;
102172
102165
  return Object.entries(pathItems).filter(([key2]) => SUPPORTED_HTTP_METHODS.includes(key2)).reduce((payloads, [method, operation]) => {
102173
102166
  const url2 = transformer.url({ path: path13, base });
102174
102167
  const args = { path: path13, base, url: url2, method, operation };
@@ -102187,13 +102180,9 @@ function transformPayloads(pathItems, options8) {
102187
102180
  entity,
102188
102181
  required: isRequiredRequestBody(operation.requestBody)
102189
102182
  }) : "undefined";
102190
- const { mime, statusCode } = doStatusCodeStrategy(
102191
- operation,
102192
- statusCodes[method] ?? 200,
102193
- statusCodeStrategy
102194
- );
102195
102183
  const typeResponseBody = transformer.typeResponseBody({ ...args, type: type2, verb, entity });
102196
- const typeResponseBodyValue = mime && statusCode ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, statusCode, mime }) : "undefined";
102184
+ const responseMetadataItems = getValidResponseMetadataItems(operation, validateStatus);
102185
+ const typeResponseBodyValue = responseMetadataItems.length > 0 ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, responseMetadataItems }) : "undefined";
102197
102186
  payloads.push({
102198
102187
  fn: fn8,
102199
102188
  url: url2,
@@ -102213,14 +102202,16 @@ function transformPayloads(pathItems, options8) {
102213
102202
  }, []);
102214
102203
  }
102215
102204
  function partitionApiModules(schema2, options8) {
102216
- const { base, transformer } = options8;
102205
+ const { base, transformer, validateStatus } = options8;
102217
102206
  const schemaPaths = schema2.paths ?? {};
102218
102207
  const schemaPathKeys = base ? Object.keys(schemaPaths).map((key2) => key2.replace(base, "")) : Object.keys(schemaPaths);
102219
102208
  const keyToPaths = (0, import_rattail2.groupBy)(schemaPathKeys, (key2) => key2.split("/")[1]);
102220
102209
  const apiModules = Object.entries(keyToPaths).reduce((apiModules2, [name, paths]) => {
102221
102210
  const payloads = paths.reduce((payloads2, path13) => {
102222
102211
  const pathItems = schemaPaths[path13];
102223
- payloads2.push(...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer }));
102212
+ payloads2.push(
102213
+ ...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer, validateStatus })
102214
+ );
102224
102215
  return payloads2;
102225
102216
  }, []);
102226
102217
  apiModules2.push({ name: transformer.moduleName({ name }), payloads });
@@ -102229,7 +102220,7 @@ function partitionApiModules(schema2, options8) {
102229
102220
  return apiModules;
102230
102221
  }
102231
102222
  function renderApiModules(apiModules, options8) {
102232
- const { output, ts: ts9, overrides, preset } = options8;
102223
+ const { output, ts: ts9, typesOnly, overrides, preset } = options8;
102233
102224
  const templateFile = readTemplateFile(preset);
102234
102225
  const typesFilename = options8.typesFilename.replace(".ts", "");
102235
102226
  return Promise.all(
@@ -102238,7 +102229,8 @@ function renderApiModules(apiModules, options8) {
102238
102229
  const data = {
102239
102230
  apiModule,
102240
102231
  typesFilename,
102241
- ts: ts9
102232
+ ts: ts9,
102233
+ typesOnly
102242
102234
  };
102243
102235
  src_default.format(import_ejs.default.render(templateFile, data), {
102244
102236
  parser: "typescript",
@@ -102274,18 +102266,15 @@ async function generate(userOptions = {}) {
102274
102266
  const {
102275
102267
  base,
102276
102268
  ts: ts9 = true,
102269
+ typesOnly = false,
102277
102270
  overrides = true,
102278
102271
  preset = "axle",
102279
- statusCodeStrategy = "smart",
102280
102272
  input = "./schema.json",
102281
102273
  output = "./src/apis/generated",
102282
102274
  typesFilename = "_types.ts",
102275
+ validateStatus = (status) => status >= 200 && status < 300,
102283
102276
  transformer = {}
102284
102277
  } = options8;
102285
- const statusCodes = {
102286
- ...createStatusCodesByStrategy(statusCodeStrategy),
102287
- ...options8.statusCodes ?? {}
102288
- };
102289
102278
  const mergedTransformer = { ...createTransformer(), ...transformer };
102290
102279
  const schema2 = await readSchema(input);
102291
102280
  import_rslog.logger.info("Generating API modules...");
@@ -102293,12 +102282,11 @@ async function generate(userOptions = {}) {
102293
102282
  await generateTypes(schema2, output, typesFilename);
102294
102283
  }
102295
102284
  const apiModules = partitionApiModules(schema2, {
102296
- statusCodes,
102297
- statusCodeStrategy,
102298
102285
  base,
102299
- transformer: mergedTransformer
102286
+ transformer: mergedTransformer,
102287
+ validateStatus
102300
102288
  });
102301
- await renderApiModules(apiModules, { output, typesFilename, ts: ts9, overrides, preset });
102289
+ await renderApiModules(apiModules, { output, typesFilename, ts: ts9, typesOnly, overrides, preset });
102302
102290
  import_rslog.logger.success("Done");
102303
102291
  }
102304
102292
 
@@ -102309,11 +102297,11 @@ var import_pluralize2 = __toESM(require("pluralize"), 1);
102309
102297
  createStatusCodesByStrategy,
102310
102298
  createTransformer,
102311
102299
  defineConfig,
102312
- doStatusCodeStrategy,
102313
102300
  generate,
102314
102301
  generateTypes,
102315
102302
  getCliVersion,
102316
102303
  getConfig,
102304
+ getValidResponseMetadataItems,
102317
102305
  hasQueryParameter,
102318
102306
  isRequiredRequestBody,
102319
102307
  partitionApiModules,
package/dist/index.d.cts CHANGED
@@ -1,6 +1,53 @@
1
- import { OperationObject, OpenAPI3, RequestBodyObject, ReferenceObject } from 'openapi-typescript';
1
+ import { OpenAPI3, OperationObject, RequestBodyObject, ReferenceObject } from 'openapi-typescript';
2
2
  export { default as pluralize } from 'pluralize';
3
3
 
4
+ type Preset = 'axle' | 'axios';
5
+ type StatusCodeStrategy = 'strict' | 'loose' | 'smart';
6
+ interface StatusCodes {
7
+ get?: number;
8
+ post?: number;
9
+ put?: number;
10
+ delete?: number;
11
+ patch?: number;
12
+ options?: number;
13
+ head?: number;
14
+ }
15
+ declare function createStatusCodesByStrategy(strategy: StatusCodeStrategy): {
16
+ get: number;
17
+ post: number;
18
+ put: number;
19
+ delete: number;
20
+ patch: number;
21
+ options: number;
22
+ head: number;
23
+ } | {
24
+ get: number;
25
+ post: number;
26
+ put: number;
27
+ delete: number;
28
+ patch: number;
29
+ options: number;
30
+ head: number;
31
+ } | {
32
+ get: number;
33
+ post: number;
34
+ put: number;
35
+ delete: number;
36
+ patch: number;
37
+ options: number;
38
+ head: number;
39
+ };
40
+ declare function readSchema(input: string): Promise<OpenAPI3>;
41
+ declare function readTemplateFile(preset?: Preset): string;
42
+ declare function hasQueryParameter(operation: OperationObject): boolean;
43
+ declare function getCliVersion(): any;
44
+ declare function isRequiredRequestBody(value: RequestBodyObject | ReferenceObject): boolean;
45
+ type ResponseMetadataItem = {
46
+ status: number;
47
+ mime: string;
48
+ };
49
+ declare function getValidResponseMetadataItems(operation: OperationObject, validateStatus: (status: number) => boolean): ResponseMetadataItem[];
50
+
4
51
  type TransformerBaseArgs = {
5
52
  path: string;
6
53
  base: string | undefined;
@@ -57,12 +104,11 @@ declare function transformTypeResponseBody({ type, }: {
57
104
  verb: string;
58
105
  entity: string;
59
106
  } & TransformerBaseArgs): string;
60
- declare function transformTypeResponseBodyValue({ type, statusCode, mime, }: {
107
+ declare function transformTypeResponseBodyValue({ type, responseMetadataItems, }: {
61
108
  type: string;
62
109
  verb: string;
63
110
  entity: string;
64
- statusCode: number;
65
- mime: string;
111
+ responseMetadataItems: ResponseMetadataItem[];
66
112
  } & TransformerBaseArgs): string;
67
113
  interface Transformer {
68
114
  moduleName: typeof transformModuleName;
@@ -81,55 +127,6 @@ interface Transformer {
81
127
  }
82
128
  declare function createTransformer(): Transformer;
83
129
 
84
- type Preset = 'axle' | 'axios';
85
- type StatusCodeStrategy = 'strict' | 'loose' | 'smart';
86
- interface StatusCodes {
87
- get?: number;
88
- post?: number;
89
- put?: number;
90
- delete?: number;
91
- patch?: number;
92
- options?: number;
93
- head?: number;
94
- }
95
- declare function createStatusCodesByStrategy(strategy: StatusCodeStrategy): {
96
- get: number;
97
- post: number;
98
- put: number;
99
- delete: number;
100
- patch: number;
101
- options: number;
102
- head: number;
103
- } | {
104
- get: number;
105
- post: number;
106
- put: number;
107
- delete: number;
108
- patch: number;
109
- options: number;
110
- head: number;
111
- } | {
112
- get: number;
113
- post: number;
114
- put: number;
115
- delete: number;
116
- patch: number;
117
- options: number;
118
- head: number;
119
- };
120
- declare function readSchema(input: string): Promise<OpenAPI3>;
121
- declare function readTemplateFile(preset?: Preset): string;
122
- declare function hasQueryParameter(operation: OperationObject): boolean;
123
- declare function getCliVersion(): any;
124
- declare function isRequiredRequestBody(value: RequestBodyObject | ReferenceObject): boolean;
125
- declare function doStatusCodeStrategy(operation: OperationObject, statusCode: number, strategy: StatusCodeStrategy): {
126
- statusCode: undefined;
127
- mime: undefined;
128
- } | {
129
- statusCode: number;
130
- mime: string | undefined;
131
- };
132
-
133
130
  interface ApiModuleTemplateData {
134
131
  /**
135
132
  * API module metadata
@@ -143,6 +140,10 @@ interface ApiModuleTemplateData {
143
140
  * Whether to generate ts code
144
141
  */
145
142
  ts: boolean;
143
+ /**
144
+ * Whether to generate only types
145
+ */
146
+ typesOnly: boolean;
146
147
  }
147
148
  interface ApiModule {
148
149
  /**
@@ -211,10 +212,12 @@ interface ApiModulePayload {
211
212
  interface GenerateOptions {
212
213
  /**
213
214
  * The path to the OpenAPI/Swagger schema file.
215
+ * @default './schema.json'
214
216
  */
215
217
  input?: string;
216
218
  /**
217
219
  * The path to the output directory.
220
+ * @default './src/apis/generated'
218
221
  */
219
222
  output?: string;
220
223
  /**
@@ -223,61 +226,55 @@ interface GenerateOptions {
223
226
  base?: string;
224
227
  /**
225
228
  * The filename of the generated openapi types file.
229
+ * @default '_types.ts'
226
230
  */
227
231
  typesFilename?: string;
228
- /**
229
- * The transformer api options, used to override the default transformation rules.
230
- */
231
- transformer?: Partial<Transformer>;
232
232
  /**
233
233
  * Whether to generate TypeScript code.
234
+ * @default true
234
235
  */
235
236
  ts?: boolean;
237
+ /**
238
+ * Whether to generate only types.
239
+ * @default false
240
+ */
241
+ typesOnly?: boolean;
236
242
  /**
237
243
  * Whether to override the existing files, or an array of filenames to override.
244
+ * @default true
238
245
  */
239
246
  overrides?: boolean | string[];
240
247
  /**
241
248
  * The preset ejs template to use.
249
+ * @default 'axle'
242
250
  */
243
251
  preset?: Preset;
244
252
  /**
245
- * The status code strategy to use.
246
- * loose: all success status codes are 200,
247
- * strict: use the openapi recommended success status codes.
248
- * smart: find a valid status code between [200, 299] that is closest to 200
253
+ * Defines which return status codes will be typed
254
+ * @default (status) => status >= 200 && status < 300
249
255
  */
250
- statusCodeStrategy?: StatusCodeStrategy;
256
+ validateStatus?: (status: number) => boolean;
251
257
  /**
252
- * The status codes to override the default status codes.
258
+ * The transformer api options, used to override the default transformation rules.
253
259
  */
254
- statusCodes?: {
255
- get?: number;
256
- post?: number;
257
- put?: number;
258
- delete?: number;
259
- patch?: number;
260
- options?: number;
261
- head?: number;
262
- };
260
+ transformer?: Partial<Transformer>;
263
261
  }
264
262
  declare function transformPayloads(pathItems: Record<string, OperationObject>, options: {
265
263
  path: string;
266
- statusCodeStrategy: StatusCodeStrategy;
267
- statusCodes: StatusCodes;
268
264
  transformer: Transformer;
269
265
  base: string | undefined;
266
+ validateStatus: (status: number) => boolean;
270
267
  }): ApiModulePayload[];
271
268
  declare function partitionApiModules(schema: OpenAPI3, options: {
272
269
  transformer: Transformer;
273
- statusCodeStrategy: StatusCodeStrategy;
274
- statusCodes: StatusCodes;
275
270
  base: string | undefined;
271
+ validateStatus: (status: number) => boolean;
276
272
  }): ApiModule[];
277
273
  declare function renderApiModules(apiModules: ApiModule[], options: {
278
274
  output: string;
279
275
  typesFilename: string;
280
276
  ts: boolean;
277
+ typesOnly: boolean;
281
278
  overrides: boolean | string[];
282
279
  preset: Preset;
283
280
  }): Promise<unknown[]>;
@@ -288,4 +285,4 @@ type Config = GenerateOptions;
288
285
  declare function defineConfig(config: Config): GenerateOptions;
289
286
  declare function getConfig(): Promise<Config>;
290
287
 
291
- export { type ApiModule, type ApiModulePayload, type ApiModuleTemplateData, type Config, type GenerateOptions, type Preset, type StatusCodeStrategy, type StatusCodes, type Transformer, type TransformerBaseArgs, createStatusCodesByStrategy, createTransformer, defineConfig, doStatusCodeStrategy, generate, generateTypes, getCliVersion, getConfig, hasQueryParameter, isRequiredRequestBody, partitionApiModules, readSchema, readTemplateFile, renderApiModules, transformEntity, transformFn, transformModuleName, transformPayloads, transformType, transformTypeQuery, transformTypeQueryValue, transformTypeRequestBody, transformTypeRequestBodyValue, transformTypeResponseBody, transformTypeResponseBodyValue, transformTypeValue, transformUrl, transformVerb };
288
+ export { type ApiModule, type ApiModulePayload, type ApiModuleTemplateData, type Config, type GenerateOptions, type Preset, type ResponseMetadataItem, type StatusCodeStrategy, type StatusCodes, type Transformer, type TransformerBaseArgs, createStatusCodesByStrategy, createTransformer, defineConfig, generate, generateTypes, getCliVersion, getConfig, getValidResponseMetadataItems, hasQueryParameter, isRequiredRequestBody, partitionApiModules, readSchema, readTemplateFile, renderApiModules, transformEntity, transformFn, transformModuleName, transformPayloads, transformType, transformTypeQuery, transformTypeQueryValue, transformTypeRequestBody, transformTypeRequestBodyValue, transformTypeResponseBody, transformTypeResponseBodyValue, transformTypeValue, transformUrl, transformVerb };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,53 @@
1
- import { OperationObject, OpenAPI3, RequestBodyObject, ReferenceObject } from 'openapi-typescript';
1
+ import { OpenAPI3, OperationObject, RequestBodyObject, ReferenceObject } from 'openapi-typescript';
2
2
  export { default as pluralize } from 'pluralize';
3
3
 
4
+ type Preset = 'axle' | 'axios';
5
+ type StatusCodeStrategy = 'strict' | 'loose' | 'smart';
6
+ interface StatusCodes {
7
+ get?: number;
8
+ post?: number;
9
+ put?: number;
10
+ delete?: number;
11
+ patch?: number;
12
+ options?: number;
13
+ head?: number;
14
+ }
15
+ declare function createStatusCodesByStrategy(strategy: StatusCodeStrategy): {
16
+ get: number;
17
+ post: number;
18
+ put: number;
19
+ delete: number;
20
+ patch: number;
21
+ options: number;
22
+ head: number;
23
+ } | {
24
+ get: number;
25
+ post: number;
26
+ put: number;
27
+ delete: number;
28
+ patch: number;
29
+ options: number;
30
+ head: number;
31
+ } | {
32
+ get: number;
33
+ post: number;
34
+ put: number;
35
+ delete: number;
36
+ patch: number;
37
+ options: number;
38
+ head: number;
39
+ };
40
+ declare function readSchema(input: string): Promise<OpenAPI3>;
41
+ declare function readTemplateFile(preset?: Preset): string;
42
+ declare function hasQueryParameter(operation: OperationObject): boolean;
43
+ declare function getCliVersion(): any;
44
+ declare function isRequiredRequestBody(value: RequestBodyObject | ReferenceObject): boolean;
45
+ type ResponseMetadataItem = {
46
+ status: number;
47
+ mime: string;
48
+ };
49
+ declare function getValidResponseMetadataItems(operation: OperationObject, validateStatus: (status: number) => boolean): ResponseMetadataItem[];
50
+
4
51
  type TransformerBaseArgs = {
5
52
  path: string;
6
53
  base: string | undefined;
@@ -57,12 +104,11 @@ declare function transformTypeResponseBody({ type, }: {
57
104
  verb: string;
58
105
  entity: string;
59
106
  } & TransformerBaseArgs): string;
60
- declare function transformTypeResponseBodyValue({ type, statusCode, mime, }: {
107
+ declare function transformTypeResponseBodyValue({ type, responseMetadataItems, }: {
61
108
  type: string;
62
109
  verb: string;
63
110
  entity: string;
64
- statusCode: number;
65
- mime: string;
111
+ responseMetadataItems: ResponseMetadataItem[];
66
112
  } & TransformerBaseArgs): string;
67
113
  interface Transformer {
68
114
  moduleName: typeof transformModuleName;
@@ -81,55 +127,6 @@ interface Transformer {
81
127
  }
82
128
  declare function createTransformer(): Transformer;
83
129
 
84
- type Preset = 'axle' | 'axios';
85
- type StatusCodeStrategy = 'strict' | 'loose' | 'smart';
86
- interface StatusCodes {
87
- get?: number;
88
- post?: number;
89
- put?: number;
90
- delete?: number;
91
- patch?: number;
92
- options?: number;
93
- head?: number;
94
- }
95
- declare function createStatusCodesByStrategy(strategy: StatusCodeStrategy): {
96
- get: number;
97
- post: number;
98
- put: number;
99
- delete: number;
100
- patch: number;
101
- options: number;
102
- head: number;
103
- } | {
104
- get: number;
105
- post: number;
106
- put: number;
107
- delete: number;
108
- patch: number;
109
- options: number;
110
- head: number;
111
- } | {
112
- get: number;
113
- post: number;
114
- put: number;
115
- delete: number;
116
- patch: number;
117
- options: number;
118
- head: number;
119
- };
120
- declare function readSchema(input: string): Promise<OpenAPI3>;
121
- declare function readTemplateFile(preset?: Preset): string;
122
- declare function hasQueryParameter(operation: OperationObject): boolean;
123
- declare function getCliVersion(): any;
124
- declare function isRequiredRequestBody(value: RequestBodyObject | ReferenceObject): boolean;
125
- declare function doStatusCodeStrategy(operation: OperationObject, statusCode: number, strategy: StatusCodeStrategy): {
126
- statusCode: undefined;
127
- mime: undefined;
128
- } | {
129
- statusCode: number;
130
- mime: string | undefined;
131
- };
132
-
133
130
  interface ApiModuleTemplateData {
134
131
  /**
135
132
  * API module metadata
@@ -143,6 +140,10 @@ interface ApiModuleTemplateData {
143
140
  * Whether to generate ts code
144
141
  */
145
142
  ts: boolean;
143
+ /**
144
+ * Whether to generate only types
145
+ */
146
+ typesOnly: boolean;
146
147
  }
147
148
  interface ApiModule {
148
149
  /**
@@ -211,10 +212,12 @@ interface ApiModulePayload {
211
212
  interface GenerateOptions {
212
213
  /**
213
214
  * The path to the OpenAPI/Swagger schema file.
215
+ * @default './schema.json'
214
216
  */
215
217
  input?: string;
216
218
  /**
217
219
  * The path to the output directory.
220
+ * @default './src/apis/generated'
218
221
  */
219
222
  output?: string;
220
223
  /**
@@ -223,61 +226,55 @@ interface GenerateOptions {
223
226
  base?: string;
224
227
  /**
225
228
  * The filename of the generated openapi types file.
229
+ * @default '_types.ts'
226
230
  */
227
231
  typesFilename?: string;
228
- /**
229
- * The transformer api options, used to override the default transformation rules.
230
- */
231
- transformer?: Partial<Transformer>;
232
232
  /**
233
233
  * Whether to generate TypeScript code.
234
+ * @default true
234
235
  */
235
236
  ts?: boolean;
237
+ /**
238
+ * Whether to generate only types.
239
+ * @default false
240
+ */
241
+ typesOnly?: boolean;
236
242
  /**
237
243
  * Whether to override the existing files, or an array of filenames to override.
244
+ * @default true
238
245
  */
239
246
  overrides?: boolean | string[];
240
247
  /**
241
248
  * The preset ejs template to use.
249
+ * @default 'axle'
242
250
  */
243
251
  preset?: Preset;
244
252
  /**
245
- * The status code strategy to use.
246
- * loose: all success status codes are 200,
247
- * strict: use the openapi recommended success status codes.
248
- * smart: find a valid status code between [200, 299] that is closest to 200
253
+ * Defines which return status codes will be typed
254
+ * @default (status) => status >= 200 && status < 300
249
255
  */
250
- statusCodeStrategy?: StatusCodeStrategy;
256
+ validateStatus?: (status: number) => boolean;
251
257
  /**
252
- * The status codes to override the default status codes.
258
+ * The transformer api options, used to override the default transformation rules.
253
259
  */
254
- statusCodes?: {
255
- get?: number;
256
- post?: number;
257
- put?: number;
258
- delete?: number;
259
- patch?: number;
260
- options?: number;
261
- head?: number;
262
- };
260
+ transformer?: Partial<Transformer>;
263
261
  }
264
262
  declare function transformPayloads(pathItems: Record<string, OperationObject>, options: {
265
263
  path: string;
266
- statusCodeStrategy: StatusCodeStrategy;
267
- statusCodes: StatusCodes;
268
264
  transformer: Transformer;
269
265
  base: string | undefined;
266
+ validateStatus: (status: number) => boolean;
270
267
  }): ApiModulePayload[];
271
268
  declare function partitionApiModules(schema: OpenAPI3, options: {
272
269
  transformer: Transformer;
273
- statusCodeStrategy: StatusCodeStrategy;
274
- statusCodes: StatusCodes;
275
270
  base: string | undefined;
271
+ validateStatus: (status: number) => boolean;
276
272
  }): ApiModule[];
277
273
  declare function renderApiModules(apiModules: ApiModule[], options: {
278
274
  output: string;
279
275
  typesFilename: string;
280
276
  ts: boolean;
277
+ typesOnly: boolean;
281
278
  overrides: boolean | string[];
282
279
  preset: Preset;
283
280
  }): Promise<unknown[]>;
@@ -288,4 +285,4 @@ type Config = GenerateOptions;
288
285
  declare function defineConfig(config: Config): GenerateOptions;
289
286
  declare function getConfig(): Promise<Config>;
290
287
 
291
- export { type ApiModule, type ApiModulePayload, type ApiModuleTemplateData, type Config, type GenerateOptions, type Preset, type StatusCodeStrategy, type StatusCodes, type Transformer, type TransformerBaseArgs, createStatusCodesByStrategy, createTransformer, defineConfig, doStatusCodeStrategy, generate, generateTypes, getCliVersion, getConfig, hasQueryParameter, isRequiredRequestBody, partitionApiModules, readSchema, readTemplateFile, renderApiModules, transformEntity, transformFn, transformModuleName, transformPayloads, transformType, transformTypeQuery, transformTypeQueryValue, transformTypeRequestBody, transformTypeRequestBodyValue, transformTypeResponseBody, transformTypeResponseBodyValue, transformTypeValue, transformUrl, transformVerb };
288
+ export { type ApiModule, type ApiModulePayload, type ApiModuleTemplateData, type Config, type GenerateOptions, type Preset, type ResponseMetadataItem, type StatusCodeStrategy, type StatusCodes, type Transformer, type TransformerBaseArgs, createStatusCodesByStrategy, createTransformer, defineConfig, generate, generateTypes, getCliVersion, getConfig, getValidResponseMetadataItems, hasQueryParameter, isRequiredRequestBody, partitionApiModules, readSchema, readTemplateFile, renderApiModules, transformEntity, transformFn, transformModuleName, transformPayloads, transformType, transformTypeQuery, transformTypeQueryValue, transformTypeRequestBody, transformTypeRequestBodyValue, transformTypeResponseBody, transformTypeResponseBodyValue, transformTypeValue, transformUrl, transformVerb };
package/dist/index.js CHANGED
@@ -20,16 +20,16 @@ import {
20
20
  transformTypeValue,
21
21
  transformUrl,
22
22
  transformVerb
23
- } from "./chunk-VAAFC73D.js";
23
+ } from "./chunk-K46PCBCF.js";
24
24
  import {
25
25
  createStatusCodesByStrategy,
26
- doStatusCodeStrategy,
27
26
  getCliVersion,
27
+ getValidResponseMetadataItems,
28
28
  hasQueryParameter,
29
29
  isRequiredRequestBody,
30
30
  readSchema,
31
31
  readTemplateFile
32
- } from "./chunk-LYOTF4II.js";
32
+ } from "./chunk-SKKHIIUE.js";
33
33
  import "./chunk-6OIOYGN7.js";
34
34
 
35
35
  // src/index.ts
@@ -38,11 +38,11 @@ export {
38
38
  createStatusCodesByStrategy,
39
39
  createTransformer,
40
40
  defineConfig,
41
- doStatusCodeStrategy,
42
41
  generate,
43
42
  generateTypes,
44
43
  getCliVersion,
45
44
  getConfig,
45
+ getValidResponseMetadataItems,
46
46
  hasQueryParameter,
47
47
  isRequiredRequestBody,
48
48
  partitionApiModules,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "api-farmer",
3
- "version": "0.0.16",
3
+ "version": "0.0.18",
4
4
  "description": "API module generation tool based on Openapi3/Swagger2.",
5
5
  "keywords": [
6
6
  "cli",
@@ -1,7 +1,8 @@
1
- <% if (ts) { %> import { type AxiosRequestConfig } from 'axios' <% } %>
2
- import { request } from '@/request'
1
+ <% if (ts && !typesOnly) { %> import { type AxiosRequestConfig } from 'axios' <% } %>
2
+ <% if (!typesOnly) { %> import { request } from '@/request' <% } %>
3
3
  <% if (ts) { %> import { type paths } from './<%- typesFilename %>' <% } %>
4
4
 
5
+ <% if (!typesOnly) { %>
5
6
  <% apiModule.payloads.forEach(payload => { %> -%>
6
7
  export const <%- payload.fn %> = (config<% if (ts) { %>: AxiosRequestConfig<<%- payload.typeRequestBody %>> <% } %>)
7
8
  => request<% if (ts) { %><any, <%- payload.typeResponseBody %>><% } %>({
@@ -11,6 +12,7 @@ export const <%- payload.fn %> = (config<% if (ts) { %>: AxiosRequestConfig<<%-
11
12
  })
12
13
 
13
14
  <% }) %>
15
+ <% } %>
14
16
 
15
17
  <% if (ts) { %>
16
18
  <% apiModule.payloads.forEach(payload => { %> -%>
@@ -1,6 +1,7 @@
1
- import { api } from '@/request'
1
+ <% if (!typesOnly) { %> import { api } from '@/request' <% } %>
2
2
  <% if (ts) { %> import { type paths } from './<%- typesFilename %>' <% } %>
3
3
 
4
+ <% if (!typesOnly) { %>
4
5
  <% apiModule.payloads.forEach(payload => { %> -%>
5
6
  export const <%- payload.fn %> = api
6
7
  <% if (ts) { %>
@@ -14,6 +15,7 @@ export const <%- payload.fn %> = api
14
15
  ('<%- payload.url %>', '<%- payload.method %>')
15
16
 
16
17
  <% }) %>
18
+ <% } %>
17
19
 
18
20
  <% if (ts) { %>
19
21
  <% apiModule.payloads.forEach(payload => { %> -%>