yapi-to-typescript2 1.0.1 → 1.0.2

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.
@@ -1,1111 +1,714 @@
1
- import _createForOfIteratorHelperLoose from "@babel/runtime/helpers/esm/createForOfIteratorHelperLoose";
2
- import _taggedTemplateLiteralLoose from "@babel/runtime/helpers/esm/taggedTemplateLiteralLoose";
3
- import _extends from "@babel/runtime/helpers/esm/extends";
4
- import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
5
-
6
- var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7, _templateObject8, _templateObject9, _templateObject10, _templateObject11, _templateObject12, _templateObject13;
7
-
8
- import _regeneratorRuntime from "@babel/runtime/regenerator";
1
+ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
2
+ if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
3
+ return cooked;
4
+ };
5
+ var __assign = (this && this.__assign) || function () {
6
+ __assign = Object.assign || function(t) {
7
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
8
+ s = arguments[i];
9
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
10
+ t[p] = s[p];
11
+ }
12
+ return t;
13
+ };
14
+ return __assign.apply(this, arguments);
15
+ };
16
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
+ return new (P || (P = Promise))(function (resolve, reject) {
19
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
23
+ });
24
+ };
25
+ var __generator = (this && this.__generator) || function (thisArg, body) {
26
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
27
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
28
+ function verb(n) { return function (v) { return step([n, v]); }; }
29
+ function step(op) {
30
+ if (f) throw new TypeError("Generator is already executing.");
31
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
32
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
33
+ if (y = 0, t) op = [op[0] & 2, t.value];
34
+ switch (op[0]) {
35
+ case 0: case 1: t = op; break;
36
+ case 4: _.label++; return { value: op[1], done: false };
37
+ case 5: _.label++; y = op[1]; op = [0]; continue;
38
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
39
+ default:
40
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
41
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
42
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
43
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
44
+ if (t[2]) _.ops.pop();
45
+ _.trys.pop(); continue;
46
+ }
47
+ op = body.call(thisArg, _);
48
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
49
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
50
+ }
51
+ };
52
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
53
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
54
+ if (ar || !(i in from)) {
55
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
56
+ ar[i] = from[i];
57
+ }
58
+ }
59
+ return to.concat(ar || Array.prototype.slice.call(from));
60
+ };
9
61
  import * as changeCase from 'change-case';
10
62
  import dayjs from 'dayjs';
11
63
  import fs from 'fs-extra';
12
64
  import path from 'path';
13
- import { castArray, cloneDeepFast, dedent, groupBy, isEmpty, isFunction, last, memoize, noop, omit, uniq, values } from 'vtils';
14
- import { Method, QueryStringArrayFormat, RequestBodyType } from './types';
65
+ import { castArray, cloneDeepFast, dedent, groupBy, isEmpty, isFunction, last, memoize, noop, omit, uniq, values, } from 'vtils';
66
+ import { Method, QueryStringArrayFormat, RequestBodyType, } from './types';
15
67
  import { exec } from 'child_process';
16
- import { getCachedPrettierOptions, getNormalizedRelativePath, getPrettier, getRequestDataJsonSchema, getResponseDataJsonSchema, httpGet, jsonSchemaToType, sortByWeights, throwError } from './utils';
68
+ import { getCachedPrettierOptions, getNormalizedRelativePath, getPrettier, getRequestDataJsonSchema, getResponseDataJsonSchema, httpGet, jsonSchemaToType, sortByWeights, throwError, } from './utils';
17
69
  import { SwaggerToYApiServer } from './SwaggerToYApiServer';
18
-
19
70
  /**
20
71
  * @see https://webpack.js.org/guides/tree-shaking/#mark-a-function-call-as-side-effect-free
21
72
  * @see https://terser.org/docs/api-reference.html#annotations
22
73
  */
23
74
  var COMPRESSOR_TREE_SHAKING_ANNOTATION = '/*#__PURE__*/';
24
- export var Generator = /*#__PURE__*/function () {
25
- /** 配置 */
26
- function Generator(config, options) {
27
- var _this = this;
28
-
29
- if (options === void 0) {
30
- options = {
31
- cwd: process.cwd()
32
- };
33
- }
34
-
35
- this.options = options;
36
- this.config = [];
37
- this.disposes = [];
38
- this.fetchProject = memoize( /*#__PURE__*/function () {
39
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref) {
40
- var serverUrl, token, projectInfo, basePath;
41
- return _regeneratorRuntime.wrap(function _callee$(_context) {
42
- while (1) {
43
- switch (_context.prev = _context.next) {
44
- case 0:
45
- serverUrl = _ref.serverUrl, token = _ref.token;
46
- _context.next = 3;
47
- return _this.fetchApi(serverUrl + "/api/project/get", {
48
- token: token
49
- });
50
-
51
- case 3:
52
- projectInfo = _context.sent;
53
- basePath = ("/" + (projectInfo.basepath || '/')).replace(/\/+$/, '').replace(/^\/+/, '/');
54
- projectInfo.basepath = basePath; // 实现项目在 YApi 上的地址
55
-
56
- projectInfo._url = serverUrl + "/project/" + projectInfo._id + "/interface/api";
57
- return _context.abrupt("return", projectInfo);
58
-
59
- case 8:
60
- case "end":
61
- return _context.stop();
62
- }
63
- }
64
- }, _callee);
65
- }));
66
-
67
- return function (_x) {
68
- return _ref2.apply(this, arguments);
69
- };
70
- }(), function (_ref3) {
71
- var serverUrl = _ref3.serverUrl,
72
- token = _ref3.token;
73
- return serverUrl + "|" + token;
74
- });
75
- this.fetchExport = memoize( /*#__PURE__*/function () {
76
- var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref4) {
77
- var serverUrl, token, projectInfo, categoryList;
78
- return _regeneratorRuntime.wrap(function _callee2$(_context2) {
79
- while (1) {
80
- switch (_context2.prev = _context2.next) {
81
- case 0:
82
- serverUrl = _ref4.serverUrl, token = _ref4.token;
83
- _context2.next = 3;
84
- return _this.fetchProject({
85
- serverUrl: serverUrl,
86
- token: token
87
- });
88
-
89
- case 3:
90
- projectInfo = _context2.sent;
91
- _context2.next = 6;
92
- return _this.fetchApi(serverUrl + "/api/plugin/export", {
93
- type: 'json',
94
- status: 'all',
95
- isWiki: 'false',
96
- token: token
97
- });
98
-
99
- case 6:
100
- categoryList = _context2.sent;
101
- return _context2.abrupt("return", categoryList.map(function (cat) {
102
- var _cat$list, _cat$list$, _cat$list2, _cat$list2$;
103
-
104
- var projectId = ((_cat$list = cat.list) == null ? void 0 : (_cat$list$ = _cat$list[0]) == null ? void 0 : _cat$list$.project_id) || 0;
105
- var catId = ((_cat$list2 = cat.list) == null ? void 0 : (_cat$list2$ = _cat$list2[0]) == null ? void 0 : _cat$list2$.catid) || 0; // 实现分类在 YApi 上的地址
106
-
107
- // 实现分类在 YApi 上的地址
108
- cat._url = serverUrl + "/project/" + projectId + "/interface/api/cat_" + catId;
109
- cat.list = (cat.list || []).map(function (item) {
110
- var interfaceId = item._id; // 实现接口在 YApi 上的地址
111
-
112
- // 实现接口在 YApi 上的地址
113
- item._url = serverUrl + "/project/" + projectId + "/interface/api/" + interfaceId;
114
- item.path = "" + projectInfo.basepath + item.path;
115
- return item;
116
- });
117
- return cat;
118
- }));
119
-
120
- case 8:
121
- case "end":
122
- return _context2.stop();
123
- }
124
- }
125
- }, _callee2);
126
- }));
127
-
128
- return function (_x2) {
129
- return _ref5.apply(this, arguments);
130
- };
131
- }(), function (_ref6) {
132
- var serverUrl = _ref6.serverUrl,
133
- token = _ref6.token;
134
- return serverUrl + "|" + token;
135
- });
136
- // config 可能是对象或数组,统一为数组
137
- this.config = castArray(config);
138
- }
139
-
140
- var _proto = Generator.prototype;
141
-
142
- _proto.prepare = /*#__PURE__*/function () {
143
- var _prepare = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
144
- var _this2 = this;
145
-
146
- return _regeneratorRuntime.wrap(function _callee4$(_context4) {
147
- while (1) {
148
- switch (_context4.prev = _context4.next) {
149
- case 0:
150
- _context4.next = 2;
151
- return Promise.all( // config 可能是对象或数组,统一为数组
152
- this.config.map( /*#__PURE__*/function () {
153
- var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(item) {
154
- var swaggerToYApiServer;
155
- return _regeneratorRuntime.wrap(function _callee3$(_context3) {
156
- while (1) {
157
- switch (_context3.prev = _context3.next) {
158
- case 0:
159
- if (!(item.serverType === 'swagger')) {
160
- _context3.next = 6;
161
- break;
162
- }
163
-
164
- swaggerToYApiServer = new SwaggerToYApiServer({
165
- swaggerJsonUrl: item.serverUrl
166
- });
167
- _context3.next = 4;
168
- return swaggerToYApiServer.start();
169
-
170
- case 4:
171
- item.serverUrl = _context3.sent;
172
-
173
- _this2.disposes.push(function () {
174
- return swaggerToYApiServer.stop();
175
- });
176
-
177
- case 6:
178
- if (item.serverUrl) {
179
- // 去除地址后面的 /
180
- // fix: https://github.com/fjc0k/yapi-to-typescript/issues/22
181
- item.serverUrl = item.serverUrl.replace(/\/+$/, '');
182
- }
183
-
184
- return _context3.abrupt("return", item);
185
-
186
- case 8:
187
- case "end":
188
- return _context3.stop();
189
- }
75
+ var Generator = /** @class */ (function () {
76
+ function Generator(config, options) {
77
+ if (options === void 0) { options = { cwd: process.cwd() }; }
78
+ var _this = this;
79
+ this.options = options;
80
+ /** 配置 */
81
+ this.config = [];
82
+ this.disposes = [];
83
+ this.fetchProject = memoize(function (_a) {
84
+ var serverUrl = _a.serverUrl, token = _a.token;
85
+ return __awaiter(_this, void 0, void 0, function () {
86
+ var projectInfo, basePath;
87
+ return __generator(this, function (_b) {
88
+ switch (_b.label) {
89
+ case 0: return [4 /*yield*/, this.fetchApi("".concat(serverUrl, "/api/project/get"), {
90
+ token: token,
91
+ })];
92
+ case 1:
93
+ projectInfo = _b.sent();
94
+ basePath = "/".concat(projectInfo.basepath || '/')
95
+ .replace(/\/+$/, '')
96
+ .replace(/^\/+/, '/');
97
+ projectInfo.basepath = basePath;
98
+ // 实现项目在 YApi 上的地址
99
+ projectInfo._url = "".concat(serverUrl, "/project/").concat(projectInfo._id, "/interface/api");
100
+ return [2 /*return*/, projectInfo];
190
101
  }
191
- }, _callee3);
192
- }));
193
-
194
- return function (_x3) {
195
- return _ref7.apply(this, arguments);
196
- };
197
- }()));
198
-
199
- case 2:
200
- this.config = _context4.sent;
201
-
202
- case 3:
203
- case "end":
204
- return _context4.stop();
205
- }
206
- }
207
- }, _callee4, this);
208
- }));
209
-
210
- function prepare() {
211
- return _prepare.apply(this, arguments);
212
- }
213
-
214
- return prepare;
215
- }();
216
-
217
- _proto.generate = /*#__PURE__*/function () {
218
- var _generate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10() {
219
- var _this3 = this;
220
-
221
- var outputFileList;
222
- return _regeneratorRuntime.wrap(function _callee10$(_context10) {
223
- while (1) {
224
- switch (_context10.prev = _context10.next) {
225
- case 0:
226
- outputFileList = Object.create(null);
227
- _context10.next = 3;
228
- return Promise.all(this.config.map( /*#__PURE__*/function () {
229
- var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(serverConfig, serverIndex) {
230
- var projects;
231
- return _regeneratorRuntime.wrap(function _callee9$(_context9) {
232
- while (1) {
233
- switch (_context9.prev = _context9.next) {
234
- case 0:
235
- projects = serverConfig.projects.reduce(function (projects, project) {
236
- projects.push.apply(projects, castArray(project.token).map(function (token) {
237
- return _extends({}, project, {
238
- token: token
239
- });
240
- }));
241
- return projects;
242
- }, []);
243
- return _context9.abrupt("return", Promise.all(projects.map( /*#__PURE__*/function () {
244
- var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(projectConfig, projectIndex) {
245
- var projectInfo;
246
- return _regeneratorRuntime.wrap(function _callee8$(_context8) {
247
- while (1) {
248
- switch (_context8.prev = _context8.next) {
249
- case 0:
250
- _context8.next = 2;
251
- return _this3.fetchProjectInfo(_extends({}, serverConfig, projectConfig));
252
-
253
- case 2:
254
- projectInfo = _context8.sent;
255
- _context8.next = 5;
256
- return Promise.all(projectConfig.categories.map( /*#__PURE__*/function () {
257
- var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(categoryConfig, categoryIndex) {
258
- var categoryIds, _categoryIds, excludedCategoryIds, codes, _iterator, _step, _outputFileList$group, groupedCodes;
259
-
260
- return _regeneratorRuntime.wrap(function _callee7$(_context7) {
261
- while (1) {
262
- switch (_context7.prev = _context7.next) {
263
- case 0:
264
- // 分类处理
265
- // 数组化
266
- categoryIds = castArray(categoryConfig.id); // 全部分类
267
-
268
- // 全部分类
269
- if (categoryIds.includes(0)) {
270
- (_categoryIds = categoryIds).push.apply(_categoryIds, projectInfo.cats.map(function (cat) {
271
- return cat._id;
272
- }));
273
- } // 唯一化
274
-
275
-
276
- // 唯一化
277
- categoryIds = uniq(categoryIds); // 去掉被排除的分类
278
-
279
- // 去掉被排除的分类
280
- excludedCategoryIds = categoryIds.filter(function (id) {
281
- return id < 0;
282
- }).map(Math.abs);
283
- categoryIds = categoryIds.filter(function (id) {
284
- return !excludedCategoryIds.includes(Math.abs(id));
285
- }); // 删除不存在的分类
286
-
287
- // 删除不存在的分类
288
- categoryIds = categoryIds.filter(function (id) {
289
- return !!projectInfo.cats.find(function (cat) {
290
- return cat._id === id;
291
- });
292
- }); // 顺序化
293
-
294
- // 顺序化
295
- categoryIds = categoryIds.sort();
296
- _context7.next = 9;
297
- return Promise.all(categoryIds.map( /*#__PURE__*/function () {
298
- var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(id, categoryIndex2) {
299
- var syntheticalConfig, interfaceList, interfaceCodes, groupedInterfaceCodes;
300
- return _regeneratorRuntime.wrap(function _callee6$(_context6) {
301
- while (1) {
302
- switch (_context6.prev = _context6.next) {
303
- case 0:
304
- categoryConfig = _extends({}, categoryConfig, {
305
- id: id
306
- });
307
- syntheticalConfig = _extends({}, serverConfig, projectConfig, categoryConfig, {
308
- mockUrl: projectInfo.getMockUrl()
309
- });
310
- syntheticalConfig.target = syntheticalConfig.target || 'typescript';
311
- syntheticalConfig.devUrl = projectInfo.getDevUrl(syntheticalConfig.devEnvName);
312
- syntheticalConfig.prodUrl = projectInfo.getProdUrl(syntheticalConfig.prodEnvName); // 接口列表
313
-
314
- _context6.next = 7;
315
- return _this3.fetchInterfaceList(syntheticalConfig);
316
-
317
- case 7:
318
- interfaceList = _context6.sent;
319
- interfaceList = interfaceList.map(function (interfaceInfo) {
320
- // 实现 _project 字段
321
- interfaceInfo._project = omit(projectInfo, ['cats', 'getMockUrl', 'getDevUrl', 'getProdUrl']); // 预处理
322
-
323
- // 预处理
324
- var _interfaceInfo = isFunction(syntheticalConfig.preproccessInterface) ? syntheticalConfig.preproccessInterface(cloneDeepFast(interfaceInfo), changeCase, syntheticalConfig) : interfaceInfo;
325
-
326
- return _interfaceInfo;
327
- }).filter(Boolean);
328
- interfaceList.sort(function (a, b) {
329
- return a._id - b._id;
330
- });
331
- _context6.next = 12;
332
- return Promise.all(interfaceList.map( /*#__PURE__*/function () {
333
- var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(interfaceInfo) {
334
- var outputFilePath, categoryUID, code, weights;
335
- return _regeneratorRuntime.wrap(function _callee5$(_context5) {
336
- while (1) {
337
- switch (_context5.prev = _context5.next) {
338
- case 0:
339
- outputFilePath = path.resolve(_this3.options.cwd, typeof syntheticalConfig.outputFilePath === 'function' ? syntheticalConfig.outputFilePath(interfaceInfo, changeCase) : syntheticalConfig.outputFilePath);
340
- categoryUID = "_" + serverIndex + "_" + projectIndex + "_" + categoryIndex + "_" + categoryIndex2;
341
- _context5.next = 4;
342
- return _this3.generateInterfaceCode(syntheticalConfig, interfaceInfo, categoryUID);
343
-
344
- case 4:
345
- code = _context5.sent;
346
- weights = [serverIndex, projectIndex, categoryIndex, categoryIndex2];
347
- return _context5.abrupt("return", {
348
- categoryUID: categoryUID,
349
- outputFilePath: outputFilePath,
350
- weights: weights,
351
- code: code
352
- });
353
-
354
- case 7:
355
- case "end":
356
- return _context5.stop();
357
- }
358
- }
359
- }, _callee5);
360
- }));
361
-
362
- return function (_x12) {
363
- return _ref12.apply(this, arguments);
364
- };
365
- }()));
366
-
367
- case 12:
368
- interfaceCodes = _context6.sent;
369
- groupedInterfaceCodes = groupBy(interfaceCodes, function (item) {
370
- return item.outputFilePath;
371
- });
372
- return _context6.abrupt("return", Object.keys(groupedInterfaceCodes).map(function (outputFilePath) {
373
- var categoryCode = [].concat(uniq(sortByWeights(groupedInterfaceCodes[outputFilePath]).map(function (item) {
374
- return item.categoryUID;
375
- })).map(function (categoryUID) {
376
- return syntheticalConfig.typesOnly ? '' : dedent(_templateObject || (_templateObject = _taggedTemplateLiteralLoose(["\n const mockUrl", " = ", " as any\n const devUrl", " = ", " as any\n const prodUrl", " = ", " as any\n const dataKey", " = ", " as any\n "])), categoryUID, JSON.stringify(syntheticalConfig.mockUrl), categoryUID, JSON.stringify(syntheticalConfig.devUrl), categoryUID, JSON.stringify(syntheticalConfig.prodUrl), categoryUID, JSON.stringify(syntheticalConfig.dataKey));
377
- }), sortByWeights(groupedInterfaceCodes[outputFilePath]).map(function (item) {
378
- return item.code;
379
- })).filter(Boolean).join('\n\n');
380
-
381
- if (!outputFileList[outputFilePath]) {
382
- outputFileList[outputFilePath] = {
383
- syntheticalConfig: syntheticalConfig,
384
- content: [],
385
- requestFunctionFilePath: syntheticalConfig.requestFunctionFilePath ? path.resolve(_this3.options.cwd, syntheticalConfig.requestFunctionFilePath) : path.join(path.dirname(outputFilePath), 'request.ts'),
386
- requestHookMakerFilePath: syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled ? syntheticalConfig.reactHooks.requestHookMakerFilePath ? path.resolve(_this3.options.cwd, syntheticalConfig.reactHooks.requestHookMakerFilePath) : path.join(path.dirname(outputFilePath), 'makeRequestHook.ts') : ''
387
- };
388
- }
389
-
390
- return {
391
- outputFilePath: outputFilePath,
392
- code: categoryCode,
393
- weights: last(sortByWeights(groupedInterfaceCodes[outputFilePath])).weights
394
- };
395
- }));
396
-
397
- case 15:
398
- case "end":
399
- return _context6.stop();
400
- }
401
- }
402
- }, _callee6);
403
- }));
404
-
405
- return function (_x10, _x11) {
406
- return _ref11.apply(this, arguments);
407
- };
408
- }()));
409
-
410
- case 9:
411
- codes = _context7.sent.flat();
412
-
413
- for (_iterator = _createForOfIteratorHelperLoose(values(groupBy(codes, function (item) {
414
- return item.outputFilePath;
415
- }))); !(_step = _iterator()).done;) {
416
- groupedCodes = _step.value;
417
- sortByWeights(groupedCodes);
418
-
419
- (_outputFileList$group = outputFileList[groupedCodes[0].outputFilePath].content).push.apply(_outputFileList$group, groupedCodes.map(function (item) {
420
- return item.code;
421
- }));
422
- }
423
-
424
- case 11:
425
- case "end":
426
- return _context7.stop();
427
- }
428
- }
429
- }, _callee7);
430
- }));
431
-
432
- return function (_x8, _x9) {
433
- return _ref10.apply(this, arguments);
434
- };
435
- }()));
436
-
437
- case 5:
438
- case "end":
439
- return _context8.stop();
440
- }
441
- }
442
- }, _callee8);
443
- }));
444
-
445
- return function (_x6, _x7) {
446
- return _ref9.apply(this, arguments);
447
- };
448
- }())));
449
-
102
+ });
103
+ });
104
+ }, function (_a) {
105
+ var serverUrl = _a.serverUrl, token = _a.token;
106
+ return "".concat(serverUrl, "|").concat(token);
107
+ });
108
+ this.fetchExport = memoize(function (_a) {
109
+ var serverUrl = _a.serverUrl, token = _a.token;
110
+ return __awaiter(_this, void 0, void 0, function () {
111
+ var projectInfo, categoryList;
112
+ return __generator(this, function (_b) {
113
+ switch (_b.label) {
114
+ case 0: return [4 /*yield*/, this.fetchProject({ serverUrl: serverUrl, token: token })];
115
+ case 1:
116
+ projectInfo = _b.sent();
117
+ return [4 /*yield*/, this.fetchApi("".concat(serverUrl, "/api/plugin/export"), {
118
+ type: 'json',
119
+ status: 'all',
120
+ isWiki: 'false',
121
+ token: token,
122
+ })];
450
123
  case 2:
451
- case "end":
452
- return _context9.stop();
453
- }
454
- }
455
- }, _callee9);
456
- }));
457
-
458
- return function (_x4, _x5) {
459
- return _ref8.apply(this, arguments);
460
- };
461
- }()));
462
-
463
- case 3:
464
- return _context10.abrupt("return", outputFileList);
465
-
466
- case 4:
467
- case "end":
468
- return _context10.stop();
469
- }
470
- }
471
- }, _callee10, this);
472
- }));
473
-
474
- function generate() {
475
- return _generate.apply(this, arguments);
476
- }
477
-
478
- return generate;
479
- }();
480
-
481
- _proto.write = /*#__PURE__*/function () {
482
- var _write = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(outputFileList) {
483
- var _this4 = this;
484
-
485
- return _regeneratorRuntime.wrap(function _callee12$(_context12) {
486
- while (1) {
487
- switch (_context12.prev = _context12.next) {
488
- case 0:
489
- return _context12.abrupt("return", Promise.all(Object.keys(outputFileList).map( /*#__PURE__*/function () {
490
- var _ref13 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(outputFilePath) {
491
- var _outputFileList$outpu, content, requestFunctionFilePath, requestHookMakerFilePath, syntheticalConfig, rawRequestFunctionFilePath, rawRequestHookMakerFilePath, rawOutputContent, prettier, prettyOutputContent, outputContent;
492
-
493
- return _regeneratorRuntime.wrap(function _callee11$(_context11) {
494
- while (1) {
495
- switch (_context11.prev = _context11.next) {
496
- case 0:
497
- _outputFileList$outpu = outputFileList[outputFilePath], content = _outputFileList$outpu.content, requestFunctionFilePath = _outputFileList$outpu.requestFunctionFilePath, requestHookMakerFilePath = _outputFileList$outpu.requestHookMakerFilePath, syntheticalConfig = _outputFileList$outpu.syntheticalConfig;
498
- rawRequestFunctionFilePath = requestFunctionFilePath;
499
- rawRequestHookMakerFilePath = requestHookMakerFilePath; // 支持 .jsx? 后缀
500
-
501
- // 支持 .jsx? 后缀
502
- outputFilePath = outputFilePath.replace(/\.js(x)?$/, '.ts$1');
503
- requestFunctionFilePath = requestFunctionFilePath.replace(/\.js(x)?$/, '.ts$1');
504
- requestHookMakerFilePath = requestHookMakerFilePath.replace(/\.js(x)?$/, '.ts$1');
505
-
506
- if (syntheticalConfig.typesOnly) {
507
- _context11.next = 20;
508
- break;
509
- }
510
-
511
- _context11.next = 9;
512
- return fs.pathExists(rawRequestFunctionFilePath);
513
-
514
- case 9:
515
- if (_context11.sent) {
516
- _context11.next = 12;
517
- break;
518
- }
519
-
520
- _context11.next = 12;
521
- return fs.outputFile(requestFunctionFilePath, dedent(_templateObject2 || (_templateObject2 = _taggedTemplateLiteralLoose(["\n import type { RequestFunctionParams } from 'yapi-to-typescript'\n\n export interface RequestOptions {\n /**\n * \u4F7F\u7528\u7684\u670D\u52A1\u5668\u3002\n *\n * - `prod`: \u751F\u4EA7\u670D\u52A1\u5668\n * - `dev`: \u6D4B\u8BD5\u670D\u52A1\u5668\n * - `mock`: \u6A21\u62DF\u670D\u52A1\u5668\n *\n * @default prod\n */\n server?: 'prod' | 'dev' | 'mock',\n }\n\n export default function request<TResponseData>(\n payload: RequestFunctionParams,\n options: RequestOptions = {\n server: 'prod',\n },\n ): Promise<TResponseData> {\n return new Promise<TResponseData>((resolve, reject) => {\n // \u57FA\u672C\u5730\u5740\n const baseUrl = options.server === 'mock'\n ? payload.mockUrl\n : options.server === 'dev'\n ? payload.devUrl\n : payload.prodUrl\n\n // \u8BF7\u6C42\u5730\u5740\n const url = `${baseUrl}${payload.path}`\n\n // \u5177\u4F53\u8BF7\u6C42\u903B\u8F91\n })\n }\n "], ["\n import type { RequestFunctionParams } from 'yapi-to-typescript'\n\n export interface RequestOptions {\n /**\n * \u4F7F\u7528\u7684\u670D\u52A1\u5668\u3002\n *\n * - \\`prod\\`: \u751F\u4EA7\u670D\u52A1\u5668\n * - \\`dev\\`: \u6D4B\u8BD5\u670D\u52A1\u5668\n * - \\`mock\\`: \u6A21\u62DF\u670D\u52A1\u5668\n *\n * @default prod\n */\n server?: 'prod' | 'dev' | 'mock',\n }\n\n export default function request<TResponseData>(\n payload: RequestFunctionParams,\n options: RequestOptions = {\n server: 'prod',\n },\n ): Promise<TResponseData> {\n return new Promise<TResponseData>((resolve, reject) => {\n // \u57FA\u672C\u5730\u5740\n const baseUrl = options.server === 'mock'\n ? payload.mockUrl\n : options.server === 'dev'\n ? payload.devUrl\n : payload.prodUrl\n\n // \u8BF7\u6C42\u5730\u5740\n const url = \\`\\${baseUrl}\\${payload.path}\\`\n\n // \u5177\u4F53\u8BF7\u6C42\u903B\u8F91\n })\n }\n "]))));
522
-
523
- case 12:
524
- _context11.t0 = syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled;
525
-
526
- if (!_context11.t0) {
527
- _context11.next = 17;
528
- break;
529
- }
530
-
531
- _context11.next = 16;
532
- return fs.pathExists(rawRequestHookMakerFilePath);
533
-
534
- case 16:
535
- _context11.t0 = !_context11.sent;
536
-
537
- case 17:
538
- if (!_context11.t0) {
539
- _context11.next = 20;
540
- break;
541
- }
542
-
543
- _context11.next = 20;
544
- return fs.outputFile(requestHookMakerFilePath, dedent(_templateObject3 || (_templateObject3 = _taggedTemplateLiteralLoose(["\n import { useState, useEffect } from 'react'\n import type { RequestConfig } from 'yapi-to-typescript'\n import type { Request } from ", "\n import baseRequest from ", "\n\n export default function makeRequestHook<TRequestData, TRequestConfig extends RequestConfig, TRequestResult extends ReturnType<typeof baseRequest>>(request: Request<TRequestData, TRequestConfig, TRequestResult>) {\n type Data = TRequestResult extends Promise<infer R> ? R : TRequestResult\n return function useRequest(requestData: TRequestData) {\n // \u4E00\u4E2A\u7B80\u5355\u7684 Hook \u5B9E\u73B0\uFF0C\u5B9E\u9645\u9879\u76EE\u53EF\u7ED3\u5408\u5176\u4ED6\u5E93\u4F7F\u7528\uFF0C\u6BD4\u5982\uFF1A\n // @umijs/hooks \u7684 useRequest (https://github.com/umijs/hooks)\n // swr (https://github.com/zeit/swr)\n\n const [loading, setLoading] = useState(true)\n const [data, setData] = useState<Data>()\n\n useEffect(() => {\n request(requestData).then(data => {\n setLoading(false)\n setData(data as any)\n })\n }, [JSON.stringify(requestData)])\n\n return {\n loading,\n data,\n }\n }\n }\n "])), JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, outputFilePath)), JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, requestFunctionFilePath))));
545
-
546
- case 20:
547
- // 始终写入主文件
548
- rawOutputContent = dedent(_templateObject4 || (_templateObject4 = _taggedTemplateLiteralLoose(["\n /* tslint:disable */\n /* eslint-disable */\n\n /* \u8BE5\u6587\u4EF6\u7531 yapi-to-typescript \u81EA\u52A8\u751F\u6210\uFF0C\u8BF7\u52FF\u76F4\u63A5\u4FEE\u6539\uFF01\uFF01\uFF01 */\n\n ", "\n "])), syntheticalConfig.typesOnly ? dedent(_templateObject5 || (_templateObject5 = _taggedTemplateLiteralLoose(["\n // @ts-ignore\n type FileData = File\n\n ", "\n "])), content.join('\n\n').trim()) : dedent(_templateObject6 || (_templateObject6 = _taggedTemplateLiteralLoose(["\n // @ts-ignore\n // prettier-ignore\n import { QueryStringArrayFormat, Method, RequestBodyType, ResponseBodyType, FileData, prepare } from 'yapi-to-typescript'\n // @ts-ignore\n // prettier-ignore\n import type { RequestConfig, RequestFunctionRestArgs } from 'yapi-to-typescript'\n // @ts-ignore\n import request from ", "\n ", "\n\n type UserRequestRestArgs = RequestFunctionRestArgs<typeof request>\n\n // Request: \u76EE\u524D React Hooks \u529F\u80FD\u6709\u7528\u5230\n export type Request<TRequestData, TRequestConfig extends RequestConfig, TRequestResult> = (\n TRequestConfig['requestDataOptional'] extends true\n ? (requestData?: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult\n : (requestData: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult\n ) & {\n requestConfig: TRequestConfig\n }\n\n ", "\n "])), JSON.stringify(getNormalizedRelativePath(outputFilePath, requestFunctionFilePath)), !syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? '' : dedent(_templateObject7 || (_templateObject7 = _taggedTemplateLiteralLoose(["\n // @ts-ignore\n import makeRequestHook from ", "\n "])), JSON.stringify(getNormalizedRelativePath(outputFilePath, requestHookMakerFilePath))), content.join('\n\n').trim())); // ref: https://prettier.io/docs/en/options.html
549
-
550
- _context11.next = 23;
551
- return getPrettier(_this4.options.cwd);
552
-
553
- case 23:
554
- prettier = _context11.sent;
555
- _context11.t1 = prettier;
556
- _context11.t2 = rawOutputContent;
557
- _context11.t3 = _extends;
558
- _context11.t4 = {};
559
- _context11.next = 30;
560
- return getCachedPrettierOptions();
561
-
562
- case 30:
563
- _context11.t5 = _context11.sent;
564
- _context11.t6 = {
565
- filepath: outputFilePath
566
- };
567
- _context11.t7 = (0, _context11.t3)(_context11.t4, _context11.t5, _context11.t6);
568
- _context11.next = 35;
569
- return _context11.t1.format.call(_context11.t1, _context11.t2, _context11.t7);
570
-
571
- case 35:
572
- prettyOutputContent = _context11.sent;
573
- outputContent = dedent(_templateObject8 || (_templateObject8 = _taggedTemplateLiteralLoose(["\n /* prettier-ignore-start */\n ", "\n /* prettier-ignore-end */\n "])), prettyOutputContent) + "\n";
574
- _context11.next = 39;
575
- return fs.outputFile(outputFilePath, outputContent);
576
-
577
- case 39:
578
- if (!(syntheticalConfig.target === 'javascript')) {
579
- _context11.next = 44;
580
- break;
581
- }
582
-
583
- _context11.next = 42;
584
- return _this4.tsc(outputFilePath);
585
-
586
- case 42:
587
- _context11.next = 44;
588
- return Promise.all([fs.remove(requestFunctionFilePath).catch(noop), fs.remove(requestHookMakerFilePath).catch(noop), fs.remove(outputFilePath).catch(noop)]);
589
-
590
- case 44:
591
- case "end":
592
- return _context11.stop();
593
- }
124
+ categoryList = _b.sent();
125
+ return [2 /*return*/, categoryList.map(function (cat) {
126
+ var _a, _b, _c, _d;
127
+ var projectId = ((_b = (_a = cat.list) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.project_id) || 0;
128
+ var catId = ((_d = (_c = cat.list) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.catid) || 0;
129
+ // 实现分类在 YApi 上的地址
130
+ cat._url = "".concat(serverUrl, "/project/").concat(projectId, "/interface/api/cat_").concat(catId);
131
+ cat.list = (cat.list || []).map(function (item) {
132
+ var interfaceId = item._id;
133
+ // 实现接口在 YApi 上的地址
134
+ item._url = "".concat(serverUrl, "/project/").concat(projectId, "/interface/api/").concat(interfaceId);
135
+ item.path = "".concat(projectInfo.basepath).concat(item.path);
136
+ return item;
137
+ });
138
+ return cat;
139
+ })];
594
140
  }
595
- }, _callee11);
596
- }));
597
-
598
- return function (_x14) {
599
- return _ref13.apply(this, arguments);
600
- };
601
- }())));
602
-
603
- case 1:
604
- case "end":
605
- return _context12.stop();
606
- }
607
- }
608
- }, _callee12);
609
- }));
610
-
611
- function write(_x13) {
612
- return _write.apply(this, arguments);
613
- }
614
-
615
- return write;
616
- }();
617
-
618
- _proto.tsc = /*#__PURE__*/function () {
619
- var _tsc = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(file) {
620
- var _this5 = this;
621
-
622
- return _regeneratorRuntime.wrap(function _callee13$(_context13) {
623
- while (1) {
624
- switch (_context13.prev = _context13.next) {
625
- case 0:
626
- return _context13.abrupt("return", new Promise(function (resolve) {
627
- // add this to fix bug that not-generator-file-on-window
628
- var command = "" + (require('os').platform() === 'win32' ? 'node ' : '') + JSON.stringify(require.resolve("typescript/bin/tsc"));
629
- exec(command + " --target ES2019 --module ESNext --jsx preserve --declaration --esModuleInterop " + JSON.stringify(file), {
630
- cwd: _this5.options.cwd,
631
- env: process.env
632
- }, function () {
633
- return resolve();
634
141
  });
635
- }));
636
-
637
- case 1:
638
- case "end":
639
- return _context13.stop();
640
- }
641
- }
642
- }, _callee13);
643
- }));
644
-
645
- function tsc(_x15) {
646
- return _tsc.apply(this, arguments);
142
+ });
143
+ }, function (_a) {
144
+ var serverUrl = _a.serverUrl, token = _a.token;
145
+ return "".concat(serverUrl, "|").concat(token);
146
+ });
147
+ // config 可能是对象或数组,统一为数组
148
+ this.config = castArray(config);
647
149
  }
648
-
649
- return tsc;
650
- }();
651
-
652
- _proto.fetchApi = /*#__PURE__*/function () {
653
- var _fetchApi = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(url, query) {
654
- var res;
655
- return _regeneratorRuntime.wrap(function _callee14$(_context14) {
656
- while (1) {
657
- switch (_context14.prev = _context14.next) {
658
- case 0:
659
- _context14.next = 2;
660
- return httpGet(url, query);
661
-
662
- case 2:
663
- res = _context14.sent;
664
-
665
- /* istanbul ignore next */
666
- if (res && res.errcode) {
667
- throwError(res.errmsg + " [\u8BF7\u6C42\u5730\u5740: " + url + "] [\u8BF7\u6C42\u53C2\u6570: " + new URLSearchParams(query).toString() + "]");
668
- }
669
-
670
- return _context14.abrupt("return", res.data || res);
671
-
672
- case 5:
673
- case "end":
674
- return _context14.stop();
675
- }
676
- }
677
- }, _callee14);
678
- }));
679
-
680
- function fetchApi(_x16, _x17) {
681
- return _fetchApi.apply(this, arguments);
682
- }
683
-
684
- return fetchApi;
685
- }();
686
-
687
- /** 获取分类的接口列表 */
688
- _proto.fetchInterfaceList =
689
- /*#__PURE__*/
690
- function () {
691
- var _fetchInterfaceList = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(_ref14) {
692
- var serverUrl, token, id, category;
693
- return _regeneratorRuntime.wrap(function _callee15$(_context15) {
694
- while (1) {
695
- switch (_context15.prev = _context15.next) {
696
- case 0:
697
- serverUrl = _ref14.serverUrl, token = _ref14.token, id = _ref14.id;
698
- _context15.next = 3;
699
- return this.fetchExport({
700
- serverUrl: serverUrl,
701
- token: token
702
- });
703
-
704
- case 3:
705
- _context15.t0 = _context15.sent;
706
-
707
- if (_context15.t0) {
708
- _context15.next = 6;
709
- break;
710
- }
711
-
712
- _context15.t0 = [];
713
-
714
- case 6:
715
- category = _context15.t0.find(function (cat) {
716
- return !isEmpty(cat) && !isEmpty(cat.list) && cat.list[0].catid === id;
717
- });
718
-
719
- if (category) {
720
- category.list.forEach(function (interfaceInfo) {
721
- // 实现 _category 字段
722
- interfaceInfo._category = omit(category, ['list']);
723
- });
724
- }
725
-
726
- return _context15.abrupt("return", category ? category.list : []);
727
-
728
- case 9:
729
- case "end":
730
- return _context15.stop();
731
- }
732
- }
733
- }, _callee15, this);
734
- }));
735
-
736
- function fetchInterfaceList(_x18) {
737
- return _fetchInterfaceList.apply(this, arguments);
738
- }
739
-
740
- return fetchInterfaceList;
741
- }()
742
- /** 获取项目信息 */
743
- ;
744
-
745
- _proto.fetchProjectInfo =
746
- /*#__PURE__*/
747
- function () {
748
- var _fetchProjectInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee16(syntheticalConfig) {
749
- var projectInfo, projectCats;
750
- return _regeneratorRuntime.wrap(function _callee16$(_context16) {
751
- while (1) {
752
- switch (_context16.prev = _context16.next) {
753
- case 0:
754
- _context16.next = 2;
755
- return this.fetchProject(syntheticalConfig);
756
-
757
- case 2:
758
- projectInfo = _context16.sent;
759
- _context16.next = 5;
760
- return this.fetchApi(syntheticalConfig.serverUrl + "/api/interface/getCatMenu", {
761
- token: syntheticalConfig.token,
762
- project_id: projectInfo._id
763
- });
764
-
765
- case 5:
766
- projectCats = _context16.sent;
767
- return _context16.abrupt("return", _extends({}, projectInfo, {
768
- cats: projectCats,
769
- getMockUrl: function getMockUrl() {
770
- return syntheticalConfig.serverUrl + "/mock/" + projectInfo._id;
771
- },
772
- getDevUrl: function getDevUrl(devEnvName) {
773
- var env = projectInfo.env.find(function (e) {
774
- return e.name === devEnvName;
775
- });
776
- return env && env.domain
777
- /* istanbul ignore next */
778
- || '';
779
- },
780
- getProdUrl: function getProdUrl(prodEnvName) {
781
- var env = projectInfo.env.find(function (e) {
782
- return e.name === prodEnvName;
783
- });
784
- return env && env.domain
785
- /* istanbul ignore next */
786
- || '';
150
+ Generator.prototype.prepare = function () {
151
+ return __awaiter(this, void 0, void 0, function () {
152
+ var _a;
153
+ var _this = this;
154
+ return __generator(this, function (_b) {
155
+ switch (_b.label) {
156
+ case 0:
157
+ _a = this;
158
+ return [4 /*yield*/, Promise.all(
159
+ // config 可能是对象或数组,统一为数组
160
+ this.config.map(function (item) { return __awaiter(_this, void 0, void 0, function () {
161
+ var swaggerToYApiServer_1, _a;
162
+ return __generator(this, function (_b) {
163
+ switch (_b.label) {
164
+ case 0:
165
+ if (!(item.serverType === 'swagger')) return [3 /*break*/, 2];
166
+ swaggerToYApiServer_1 = new SwaggerToYApiServer({
167
+ swaggerJsonUrl: item.serverUrl,
168
+ });
169
+ _a = item;
170
+ return [4 /*yield*/, swaggerToYApiServer_1.start()];
171
+ case 1:
172
+ _a.serverUrl = _b.sent();
173
+ this.disposes.push(function () { return swaggerToYApiServer_1.stop(); });
174
+ _b.label = 2;
175
+ case 2:
176
+ if (item.serverUrl) {
177
+ // 去除地址后面的 /
178
+ // fix: https://github.com/fjc0k/yapi-to-typescript/issues/22
179
+ item.serverUrl = item.serverUrl.replace(/\/+$/, '');
180
+ }
181
+ return [2 /*return*/, item];
182
+ }
183
+ });
184
+ }); }))];
185
+ case 1:
186
+ _a.config = _b.sent();
187
+ return [2 /*return*/];
787
188
  }
788
- }));
789
-
790
- case 7:
791
- case "end":
792
- return _context16.stop();
793
- }
794
- }
795
- }, _callee16, this);
796
- }));
797
-
798
- function fetchProjectInfo(_x19) {
799
- return _fetchProjectInfo.apply(this, arguments);
800
- }
801
-
802
- return fetchProjectInfo;
803
- }()
804
- /** 生成接口代码 */
805
- ;
806
-
807
- _proto.generateInterfaceCode =
808
- /*#__PURE__*/
809
- function () {
810
- var _generateInterfaceCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee17(syntheticalConfig, interfaceInfo, categoryUID) {
811
- var _syntheticalConfig$js, _syntheticalConfig$js2, _syntheticalConfig$js3, _syntheticalConfig$js4;
812
-
813
- var extendedInterfaceInfo, requestFunctionName, requestConfigName, requestConfigTypeName, requestDataTypeName, responseDataTypeName, requestDataJsonSchema, requestDataType, responseDataJsonSchema, responseDataType, isRequestDataOptional, requestHookName, paramNames, paramNamesLiteral, paramNameType, queryNames, queryNamesLiteral, queryNameType, genComment, requestFunctionExtraInfo;
814
- return _regeneratorRuntime.wrap(function _callee17$(_context17) {
815
- while (1) {
816
- switch (_context17.prev = _context17.next) {
817
- case 0:
818
- extendedInterfaceInfo = _extends({}, interfaceInfo, {
819
- parsedPath: path.parse(interfaceInfo.path)
820
- });
821
-
822
- if (!isFunction(syntheticalConfig.getRequestFunctionName)) {
823
- _context17.next = 7;
824
- break;
825
- }
826
-
827
- _context17.next = 4;
828
- return syntheticalConfig.getRequestFunctionName(extendedInterfaceInfo, changeCase);
829
-
830
- case 4:
831
- _context17.t0 = _context17.sent;
832
- _context17.next = 8;
833
- break;
834
-
835
- case 7:
836
- _context17.t0 = changeCase.camelCase(extendedInterfaceInfo.parsedPath.name);
837
-
838
- case 8:
839
- requestFunctionName = _context17.t0;
840
- requestConfigName = changeCase.camelCase(requestFunctionName + "RequestConfig");
841
- requestConfigTypeName = changeCase.pascalCase(requestConfigName);
842
-
843
- if (!isFunction(syntheticalConfig.getRequestDataTypeName)) {
844
- _context17.next = 17;
845
- break;
846
- }
847
-
848
- _context17.next = 14;
849
- return syntheticalConfig.getRequestDataTypeName(extendedInterfaceInfo, changeCase);
850
-
851
- case 14:
852
- _context17.t1 = _context17.sent;
853
- _context17.next = 18;
854
- break;
855
-
856
- case 17:
857
- _context17.t1 = changeCase.pascalCase(requestFunctionName + "Request");
858
-
859
- case 18:
860
- requestDataTypeName = _context17.t1;
861
-
862
- if (!isFunction(syntheticalConfig.getResponseDataTypeName)) {
863
- _context17.next = 25;
864
- break;
865
- }
866
-
867
- _context17.next = 22;
868
- return syntheticalConfig.getResponseDataTypeName(extendedInterfaceInfo, changeCase);
869
-
870
- case 22:
871
- _context17.t2 = _context17.sent;
872
- _context17.next = 26;
873
- break;
874
-
875
- case 25:
876
- _context17.t2 = changeCase.pascalCase(requestFunctionName + "Response");
877
-
878
- case 26:
879
- responseDataTypeName = _context17.t2;
880
- requestDataJsonSchema = getRequestDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {});
881
- _context17.next = 30;
882
- return jsonSchemaToType(requestDataJsonSchema, requestDataTypeName);
883
-
884
- case 30:
885
- requestDataType = _context17.sent;
886
- responseDataJsonSchema = getResponseDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {}, syntheticalConfig.dataKey);
887
- _context17.next = 34;
888
- return jsonSchemaToType(responseDataJsonSchema, responseDataTypeName);
889
-
890
- case 34:
891
- responseDataType = _context17.sent;
892
- isRequestDataOptional = /(\{\}|any)$/.test(requestDataType);
893
-
894
- if (!(syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled)) {
895
- _context17.next = 47;
896
- break;
897
- }
898
-
899
- if (!isFunction(syntheticalConfig.reactHooks.getRequestHookName)) {
900
- _context17.next = 43;
901
- break;
902
- }
903
-
904
- _context17.next = 40;
905
- return syntheticalConfig.reactHooks.getRequestHookName(extendedInterfaceInfo, changeCase);
906
-
907
- case 40:
908
- _context17.t4 = _context17.sent;
909
- _context17.next = 44;
910
- break;
911
-
912
- case 43:
913
- _context17.t4 = "use" + changeCase.pascalCase(requestFunctionName);
914
-
915
- case 44:
916
- _context17.t3 = _context17.t4;
917
- _context17.next = 48;
918
- break;
919
-
920
- case 47:
921
- _context17.t3 = '';
922
-
923
- case 48:
924
- requestHookName = _context17.t3;
925
- // 支持路径参数
926
- paramNames = (extendedInterfaceInfo.req_params
927
- /* istanbul ignore next */
928
- || []).map(function (item) {
929
- return item.name;
930
- });
931
- paramNamesLiteral = JSON.stringify(paramNames);
932
- paramNameType = paramNames.length === 0 ? 'string' : "'" + paramNames.join("' | '") + "'"; // 支持查询参数
933
-
934
- queryNames = (extendedInterfaceInfo.req_query
935
- /* istanbul ignore next */
936
- || []).map(function (item) {
937
- return item.name;
938
- });
939
- queryNamesLiteral = JSON.stringify(queryNames);
940
- queryNameType = queryNames.length === 0 ? 'string' : "'" + queryNames.join("' | '") + "'"; // 接口注释
941
-
942
- genComment = function genComment(genTitle) {
943
- var _ref15 = _extends({}, syntheticalConfig.comment, syntheticalConfig.serverType === 'swagger' ? {
944
- tag: false,
945
- updateTime: false,
946
- link: false
947
- } : {}),
948
- _ref15$enabled = _ref15.enabled,
949
- isEnabled = _ref15$enabled === void 0 ? true : _ref15$enabled,
950
- _ref15$title = _ref15.title,
951
- hasTitle = _ref15$title === void 0 ? true : _ref15$title,
952
- _ref15$category = _ref15.category,
953
- hasCategory = _ref15$category === void 0 ? true : _ref15$category,
954
- _ref15$tag = _ref15.tag,
955
- hasTag = _ref15$tag === void 0 ? true : _ref15$tag,
956
- _ref15$requestHeader = _ref15.requestHeader,
957
- hasRequestHeader = _ref15$requestHeader === void 0 ? true : _ref15$requestHeader,
958
- _ref15$updateTime = _ref15.updateTime,
959
- hasUpdateTime = _ref15$updateTime === void 0 ? true : _ref15$updateTime,
960
- _ref15$link = _ref15.link,
961
- hasLink = _ref15$link === void 0 ? true : _ref15$link,
962
- extraTags = _ref15.extraTags;
963
-
964
- if (!isEnabled) {
965
- return '';
966
- } // 转义标题中的 /
967
-
968
-
969
- var escapedTitle = String(extendedInterfaceInfo.title).replace(/\//g, '\\/');
970
- var description = hasLink ? "[" + escapedTitle + "\u2197](" + extendedInterfaceInfo._url + ")" : escapedTitle;
971
- var summary = [hasCategory && {
972
- label: '分类',
973
- value: hasLink ? "[" + extendedInterfaceInfo._category.name + "\u2197](" + extendedInterfaceInfo._category._url + ")" : extendedInterfaceInfo._category.name
974
- }, hasTag && {
975
- label: '标签',
976
- value: extendedInterfaceInfo.tag.map(function (tag) {
977
- return "`" + tag + "`";
978
- })
979
- }, hasRequestHeader && {
980
- label: '请求头',
981
- value: "`" + extendedInterfaceInfo.method.toUpperCase() + " " + extendedInterfaceInfo.path + "`"
982
- }, hasUpdateTime && {
983
- label: '更新时间',
984
- value: process.env.JEST_WORKER_ID // 测试时使用 unix 时间戳
985
- ? String(extendedInterfaceInfo.up_time) :
986
- /* istanbul ignore next */
987
- "`" + dayjs(extendedInterfaceInfo.up_time * 1000).format('YYYY-MM-DD HH:mm:ss') + "`"
988
- }];
989
-
990
- if (typeof extraTags === 'function') {
991
- var tags = extraTags(extendedInterfaceInfo);
992
-
993
- for (var _iterator2 = _createForOfIteratorHelperLoose(tags), _step2; !(_step2 = _iterator2()).done;) {
994
- var tag = _step2.value;
995
- ;
996
- (tag.position === 'start' ? summary.unshift : summary.push).call(summary, {
997
- label: tag.name,
998
- value: tag.value
999
- });
1000
- }
189
+ });
190
+ });
191
+ };
192
+ Generator.prototype.generate = function () {
193
+ return __awaiter(this, void 0, void 0, function () {
194
+ var outputFileList;
195
+ var _this = this;
196
+ return __generator(this, function (_a) {
197
+ switch (_a.label) {
198
+ case 0:
199
+ outputFileList = Object.create(null);
200
+ return [4 /*yield*/, Promise.all(this.config.map(function (serverConfig, serverIndex) { return __awaiter(_this, void 0, void 0, function () {
201
+ var projects;
202
+ var _this = this;
203
+ return __generator(this, function (_a) {
204
+ projects = serverConfig.projects.reduce(function (projects, project) {
205
+ projects.push.apply(projects, castArray(project.token).map(function (token) { return (__assign(__assign({}, project), { token: token })); }));
206
+ return projects;
207
+ }, []);
208
+ return [2 /*return*/, Promise.all(projects.map(function (projectConfig, projectIndex) { return __awaiter(_this, void 0, void 0, function () {
209
+ var projectInfo;
210
+ var _this = this;
211
+ return __generator(this, function (_a) {
212
+ switch (_a.label) {
213
+ case 0: return [4 /*yield*/, this.fetchProjectInfo(__assign(__assign({}, serverConfig), projectConfig))];
214
+ case 1:
215
+ projectInfo = _a.sent();
216
+ return [4 /*yield*/, Promise.all(projectConfig.categories.map(function (categoryConfig, categoryIndex) { return __awaiter(_this, void 0, void 0, function () {
217
+ var categoryIds, excludedCategoryIds, codes, _i, _a, groupedCodes;
218
+ var _b;
219
+ var _this = this;
220
+ return __generator(this, function (_c) {
221
+ switch (_c.label) {
222
+ case 0:
223
+ categoryIds = castArray(categoryConfig.id);
224
+ // 全部分类
225
+ if (categoryIds.includes(0)) {
226
+ categoryIds.push.apply(categoryIds, projectInfo.cats.map(function (cat) { return cat._id; }));
227
+ }
228
+ // 唯一化
229
+ categoryIds = uniq(categoryIds);
230
+ excludedCategoryIds = categoryIds
231
+ .filter(function (id) { return id < 0; })
232
+ .map(Math.abs);
233
+ categoryIds = categoryIds.filter(function (id) { return !excludedCategoryIds.includes(Math.abs(id)); });
234
+ // 删除不存在的分类
235
+ categoryIds = categoryIds.filter(function (id) { return !!projectInfo.cats.find(function (cat) { return cat._id === id; }); });
236
+ // 顺序化
237
+ categoryIds = categoryIds.sort();
238
+ return [4 /*yield*/, Promise.all(categoryIds.map(function (id, categoryIndex2) { return __awaiter(_this, void 0, void 0, function () {
239
+ var syntheticalConfig, interfaceList, interfaceCodes, groupedInterfaceCodes;
240
+ var _this = this;
241
+ return __generator(this, function (_a) {
242
+ switch (_a.label) {
243
+ case 0:
244
+ categoryConfig = __assign(__assign({}, categoryConfig), { id: id });
245
+ syntheticalConfig = __assign(__assign(__assign(__assign({}, serverConfig), projectConfig), categoryConfig), { mockUrl: projectInfo.getMockUrl() });
246
+ syntheticalConfig.target =
247
+ syntheticalConfig.target || 'typescript';
248
+ syntheticalConfig.devUrl = projectInfo.getDevUrl(syntheticalConfig.devEnvName);
249
+ syntheticalConfig.prodUrl = projectInfo.getProdUrl(syntheticalConfig.prodEnvName);
250
+ return [4 /*yield*/, this.fetchInterfaceList(syntheticalConfig)];
251
+ case 1:
252
+ interfaceList = _a.sent();
253
+ interfaceList = interfaceList
254
+ .map(function (interfaceInfo) {
255
+ // 实现 _project 字段
256
+ interfaceInfo._project = omit(projectInfo, [
257
+ 'cats',
258
+ 'getMockUrl',
259
+ 'getDevUrl',
260
+ 'getProdUrl',
261
+ ]);
262
+ // 预处理
263
+ var _interfaceInfo = isFunction(syntheticalConfig.preproccessInterface)
264
+ ? syntheticalConfig.preproccessInterface(cloneDeepFast(interfaceInfo), changeCase, syntheticalConfig)
265
+ : interfaceInfo;
266
+ return _interfaceInfo;
267
+ })
268
+ .filter(Boolean);
269
+ interfaceList.sort(function (a, b) { return a._id - b._id; });
270
+ return [4 /*yield*/, Promise.all(interfaceList.map(function (interfaceInfo) { return __awaiter(_this, void 0, void 0, function () {
271
+ var outputFilePath, categoryUID, code, weights;
272
+ return __generator(this, function (_a) {
273
+ switch (_a.label) {
274
+ case 0:
275
+ outputFilePath = path.resolve(this.options.cwd, typeof syntheticalConfig.outputFilePath ===
276
+ 'function'
277
+ ? syntheticalConfig.outputFilePath(interfaceInfo, changeCase)
278
+ : syntheticalConfig.outputFilePath);
279
+ categoryUID = "_".concat(serverIndex, "_").concat(projectIndex, "_").concat(categoryIndex, "_").concat(categoryIndex2);
280
+ return [4 /*yield*/, this.generateInterfaceCode(syntheticalConfig, interfaceInfo, categoryUID)];
281
+ case 1:
282
+ code = _a.sent();
283
+ weights = [
284
+ serverIndex,
285
+ projectIndex,
286
+ categoryIndex,
287
+ categoryIndex2,
288
+ ];
289
+ return [2 /*return*/, {
290
+ categoryUID: categoryUID,
291
+ outputFilePath: outputFilePath,
292
+ weights: weights,
293
+ code: code,
294
+ }];
295
+ }
296
+ });
297
+ }); }))];
298
+ case 2:
299
+ interfaceCodes = _a.sent();
300
+ groupedInterfaceCodes = groupBy(interfaceCodes, function (item) { return item.outputFilePath; });
301
+ return [2 /*return*/, Object.keys(groupedInterfaceCodes).map(function (outputFilePath) {
302
+ var categoryCode = __spreadArray(__spreadArray([], uniq(sortByWeights(groupedInterfaceCodes[outputFilePath]).map(function (item) { return item.categoryUID; })).map(function (categoryUID) {
303
+ return syntheticalConfig.typesOnly
304
+ ? ''
305
+ : dedent(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n const mockUrl", " = ", " as any\n const devUrl", " = ", " as any\n const prodUrl", " = ", " as any\n const dataKey", " = ", " as any\n "], ["\n const mockUrl", " = ", " as any\n const devUrl", " = ", " as any\n const prodUrl", " = ", " as any\n const dataKey", " = ", " as any\n "])), categoryUID, JSON.stringify(syntheticalConfig.mockUrl), categoryUID, JSON.stringify(syntheticalConfig.devUrl), categoryUID, JSON.stringify(syntheticalConfig.prodUrl), categoryUID, JSON.stringify(syntheticalConfig.dataKey));
306
+ }), true), sortByWeights(groupedInterfaceCodes[outputFilePath]).map(function (item) { return item.code; }), true).filter(Boolean)
307
+ .join('\n\n');
308
+ if (!outputFileList[outputFilePath]) {
309
+ outputFileList[outputFilePath] = {
310
+ syntheticalConfig: syntheticalConfig,
311
+ content: [],
312
+ requestFunctionFilePath: syntheticalConfig.requestFunctionFilePath
313
+ ? path.resolve(_this.options.cwd, syntheticalConfig.requestFunctionFilePath)
314
+ : path.join(path.dirname(outputFilePath), 'request.ts'),
315
+ requestHookMakerFilePath: syntheticalConfig.reactHooks &&
316
+ syntheticalConfig.reactHooks.enabled
317
+ ? syntheticalConfig.reactHooks
318
+ .requestHookMakerFilePath
319
+ ? path.resolve(_this.options.cwd, syntheticalConfig.reactHooks
320
+ .requestHookMakerFilePath)
321
+ : path.join(path.dirname(outputFilePath), 'makeRequestHook.ts')
322
+ : '',
323
+ };
324
+ }
325
+ return {
326
+ outputFilePath: outputFilePath,
327
+ code: categoryCode,
328
+ weights: last(sortByWeights(groupedInterfaceCodes[outputFilePath])).weights,
329
+ };
330
+ })];
331
+ }
332
+ });
333
+ }); }))];
334
+ case 1:
335
+ codes = (_c.sent()).flat();
336
+ for (_i = 0, _a = values(groupBy(codes, function (item) { return item.outputFilePath; })); _i < _a.length; _i++) {
337
+ groupedCodes = _a[_i];
338
+ sortByWeights(groupedCodes);
339
+ (_b = outputFileList[groupedCodes[0].outputFilePath].content).push.apply(_b, groupedCodes.map(function (item) { return item.code; }));
340
+ }
341
+ return [2 /*return*/];
342
+ }
343
+ });
344
+ }); }))];
345
+ case 2:
346
+ _a.sent();
347
+ return [2 /*return*/];
348
+ }
349
+ });
350
+ }); }))];
351
+ });
352
+ }); }))];
353
+ case 1:
354
+ _a.sent();
355
+ return [2 /*return*/, outputFileList];
1001
356
  }
1002
-
1003
- var titleComment = hasTitle ? dedent(_templateObject9 || (_templateObject9 = _taggedTemplateLiteralLoose(["\n * ", "\n *\n "])), genTitle(description)) : '';
1004
- var extraComment = summary.filter(function (item) {
1005
- return typeof item !== 'boolean' && !isEmpty(item.value);
1006
- }).map(function (item) {
1007
- var _item = item;
1008
- return "* @" + _item.label + " " + castArray(_item.value).join(', ');
1009
- }).join('\n');
1010
- return dedent(_templateObject10 || (_templateObject10 = _taggedTemplateLiteralLoose(["\n /**\n ", "\n */\n "])), [titleComment, extraComment].filter(Boolean).join('\n'));
1011
- }; // 请求参数额外信息
1012
-
1013
-
1014
- if (!(typeof syntheticalConfig.setRequestFunctionExtraInfo === 'function')) {
1015
- _context17.next = 62;
1016
- break;
1017
- }
1018
-
1019
- _context17.next = 59;
1020
- return syntheticalConfig.setRequestFunctionExtraInfo(extendedInterfaceInfo, changeCase);
1021
-
1022
- case 59:
1023
- _context17.t5 = _context17.sent;
1024
- _context17.next = 63;
1025
- break;
1026
-
1027
- case 62:
1028
- _context17.t5 = {};
1029
-
1030
- case 63:
1031
- requestFunctionExtraInfo = _context17.t5;
1032
- return _context17.abrupt("return", dedent(_templateObject11 || (_templateObject11 = _taggedTemplateLiteralLoose(["\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n "])), genComment(function (title) {
1033
- return "\u63A5\u53E3 " + title + " \u7684 **\u8BF7\u6C42\u7C7B\u578B**";
1034
- }), requestDataType.trim(), genComment(function (title) {
1035
- return "\u63A5\u53E3 " + title + " \u7684 **\u8FD4\u56DE\u7C7B\u578B**";
1036
- }), responseDataType.trim(), syntheticalConfig.typesOnly ? '' : dedent(_templateObject12 || (_templateObject12 = _taggedTemplateLiteralLoose(["\n ", "\n type ", " = Readonly<RequestConfig<\n ", ",\n ", ",\n ", ",\n ", ",\n ", ",\n ", ",\n ", ",\n ", "\n >>\n\n ", "\n const ", ": ", " = ", " {\n mockUrl: mockUrl", ",\n devUrl: devUrl", ",\n prodUrl: prodUrl", ",\n path: ", ",\n method: Method.", ",\n requestHeaders: ", ",\n requestBodyType: RequestBodyType.", ",\n responseBodyType: ResponseBodyType.", ",\n dataKey: dataKey", ",\n paramNames: ", ",\n queryNames: ", ",\n requestDataOptional: ", ",\n requestDataJsonSchema: ", ",\n responseDataJsonSchema: ", ",\n requestFunctionName: ", ",\n queryStringArrayFormat: QueryStringArrayFormat.", ",\n extraInfo: ", ",\n }\n\n ", "\n export const ", " = ", " (\n requestData", ": ", ",\n ...args: UserRequestRestArgs\n ) => {\n return request<", ">(\n prepare(", ", requestData),\n ...args,\n )\n }\n\n ", ".requestConfig = ", "\n\n ", "\n "])), genComment(function (title) {
1037
- return "\u63A5\u53E3 " + title + " \u7684 **\u8BF7\u6C42\u914D\u7F6E\u7684\u7C7B\u578B**";
1038
- }), requestConfigTypeName, JSON.stringify(syntheticalConfig.mockUrl), JSON.stringify(syntheticalConfig.devUrl), JSON.stringify(syntheticalConfig.prodUrl), JSON.stringify(extendedInterfaceInfo.path), JSON.stringify(syntheticalConfig.dataKey) || 'undefined', paramNameType, queryNameType, JSON.stringify(isRequestDataOptional), genComment(function (title) {
1039
- return "\u63A5\u53E3 " + title + " \u7684 **\u8BF7\u6C42\u914D\u7F6E**";
1040
- }), requestConfigName, requestConfigTypeName, COMPRESSOR_TREE_SHAKING_ANNOTATION, categoryUID, categoryUID, categoryUID, JSON.stringify(extendedInterfaceInfo.path), extendedInterfaceInfo.method, JSON.stringify((extendedInterfaceInfo.req_headers || []).filter(function (item) {
1041
- return item.name.toLowerCase() !== 'content-type';
1042
- }).reduce(function (res, item) {
1043
- res[item.name] = item.value;
1044
- return res;
1045
- }, {})), extendedInterfaceInfo.method === Method.GET ? RequestBodyType.query : extendedInterfaceInfo.req_body_type
1046
- /* istanbul ignore next */
1047
- || RequestBodyType.none, extendedInterfaceInfo.res_body_type, categoryUID, paramNamesLiteral, queryNamesLiteral, JSON.stringify(isRequestDataOptional), JSON.stringify((_syntheticalConfig$js = syntheticalConfig.jsonSchema) != null && _syntheticalConfig$js.enabled && ((_syntheticalConfig$js2 = syntheticalConfig.jsonSchema) == null ? void 0 : _syntheticalConfig$js2.requestData) !== false ? requestDataJsonSchema : {}), JSON.stringify((_syntheticalConfig$js3 = syntheticalConfig.jsonSchema) != null && _syntheticalConfig$js3.enabled && ((_syntheticalConfig$js4 = syntheticalConfig.jsonSchema) == null ? void 0 : _syntheticalConfig$js4.responseData) !== false ? responseDataJsonSchema : {}), JSON.stringify(requestFunctionName), syntheticalConfig.queryStringArrayFormat || QueryStringArrayFormat.brackets, JSON.stringify(requestFunctionExtraInfo), genComment(function (title) {
1048
- return "\u63A5\u53E3 " + title + " \u7684 **\u8BF7\u6C42\u51FD\u6570**";
1049
- }), requestFunctionName, COMPRESSOR_TREE_SHAKING_ANNOTATION, isRequestDataOptional ? '?' : '', requestDataTypeName, responseDataTypeName, requestConfigName, requestFunctionName, requestConfigName, !syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? '' : dedent(_templateObject13 || (_templateObject13 = _taggedTemplateLiteralLoose(["\n ", "\n export const ", " = ", " makeRequestHook<", ", ", ", ReturnType<typeof ", ">>(", ")\n "])), genComment(function (title) {
1050
- return "\u63A5\u53E3 " + title + " \u7684 **React Hook**";
1051
- }), requestHookName, COMPRESSOR_TREE_SHAKING_ANNOTATION, requestDataTypeName, requestConfigTypeName, requestFunctionName, requestFunctionName))));
1052
-
1053
- case 65:
1054
- case "end":
1055
- return _context17.stop();
1056
- }
1057
- }
1058
- }, _callee17);
1059
- }));
1060
-
1061
- function generateInterfaceCode(_x20, _x21, _x22) {
1062
- return _generateInterfaceCode.apply(this, arguments);
1063
- }
1064
-
1065
- return generateInterfaceCode;
1066
- }();
1067
-
1068
- _proto.destroy = /*#__PURE__*/function () {
1069
- var _destroy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee19() {
1070
- return _regeneratorRuntime.wrap(function _callee19$(_context19) {
1071
- while (1) {
1072
- switch (_context19.prev = _context19.next) {
1073
- case 0:
1074
- return _context19.abrupt("return", Promise.all(this.disposes.map( /*#__PURE__*/function () {
1075
- var _ref16 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(dispose) {
1076
- return _regeneratorRuntime.wrap(function _callee18$(_context18) {
1077
- while (1) {
1078
- switch (_context18.prev = _context18.next) {
1079
- case 0:
1080
- return _context18.abrupt("return", dispose());
1081
-
1082
- case 1:
1083
- case "end":
1084
- return _context18.stop();
1085
- }
1086
- }
1087
- }, _callee18);
1088
- }));
1089
-
1090
- return function (_x23) {
1091
- return _ref16.apply(this, arguments);
1092
- };
1093
- }())));
1094
-
1095
- case 1:
1096
- case "end":
1097
- return _context19.stop();
1098
- }
1099
- }
1100
- }, _callee19, this);
1101
- }));
1102
-
1103
- function destroy() {
1104
- return _destroy.apply(this, arguments);
1105
- }
1106
-
1107
- return destroy;
1108
- }();
1109
-
1110
- return Generator;
1111
- }();
357
+ });
358
+ });
359
+ };
360
+ Generator.prototype.write = function (outputFileList) {
361
+ return __awaiter(this, void 0, void 0, function () {
362
+ var _this = this;
363
+ return __generator(this, function (_a) {
364
+ return [2 /*return*/, Promise.all(Object.keys(outputFileList).map(function (outputFilePath) { return __awaiter(_this, void 0, void 0, function () {
365
+ var _a,
366
+ // eslint-disable-next-line prefer-const
367
+ content, requestFunctionFilePath, requestHookMakerFilePath,
368
+ // eslint-disable-next-line prefer-const
369
+ syntheticalConfig, rawRequestFunctionFilePath, rawRequestHookMakerFilePath, _b, rawOutputContent, prettier, prettyOutputContent, _c, _d, _e, _f, outputContent;
370
+ return __generator(this, function (_g) {
371
+ switch (_g.label) {
372
+ case 0:
373
+ _a = outputFileList[outputFilePath], content = _a.content, requestFunctionFilePath = _a.requestFunctionFilePath, requestHookMakerFilePath = _a.requestHookMakerFilePath, syntheticalConfig = _a.syntheticalConfig;
374
+ rawRequestFunctionFilePath = requestFunctionFilePath;
375
+ rawRequestHookMakerFilePath = requestHookMakerFilePath;
376
+ // 支持 .jsx? 后缀
377
+ outputFilePath = outputFilePath.replace(/\.js(x)?$/, '.ts$1');
378
+ requestFunctionFilePath = requestFunctionFilePath.replace(/\.js(x)?$/, '.ts$1');
379
+ requestHookMakerFilePath = requestHookMakerFilePath.replace(/\.js(x)?$/, '.ts$1');
380
+ if (!!syntheticalConfig.typesOnly) return [3 /*break*/, 7];
381
+ return [4 /*yield*/, fs.pathExists(rawRequestFunctionFilePath)];
382
+ case 1:
383
+ if (!!(_g.sent())) return [3 /*break*/, 3];
384
+ return [4 /*yield*/, fs.outputFile(requestFunctionFilePath, dedent(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n import type { RequestFunctionParams } from 'yapi-to-typescript2'\n\n export interface RequestOptions {\n /**\n * \u4F7F\u7528\u7684\u670D\u52A1\u5668\u3002\n *\n * - `prod`: \u751F\u4EA7\u670D\u52A1\u5668\n * - `dev`: \u6D4B\u8BD5\u670D\u52A1\u5668\n * - `mock`: \u6A21\u62DF\u670D\u52A1\u5668\n *\n * @default prod\n */\n server?: 'prod' | 'dev' | 'mock',\n }\n\n export default function request<TResponseData>(\n payload: RequestFunctionParams,\n options: RequestOptions = {\n server: 'prod',\n },\n ): Promise<TResponseData> {\n return new Promise<TResponseData>((resolve, reject) => {\n // \u57FA\u672C\u5730\u5740\n const baseUrl = options.server === 'mock'\n ? payload.mockUrl\n : options.server === 'dev'\n ? payload.devUrl\n : payload.prodUrl\n\n // \u8BF7\u6C42\u5730\u5740\n const url = `${baseUrl}${payload.path}`\n\n // \u5177\u4F53\u8BF7\u6C42\u903B\u8F91\n })\n }\n "], ["\n import type { RequestFunctionParams } from 'yapi-to-typescript2'\n\n export interface RequestOptions {\n /**\n * \u4F7F\u7528\u7684\u670D\u52A1\u5668\u3002\n *\n * - \\`prod\\`: \u751F\u4EA7\u670D\u52A1\u5668\n * - \\`dev\\`: \u6D4B\u8BD5\u670D\u52A1\u5668\n * - \\`mock\\`: \u6A21\u62DF\u670D\u52A1\u5668\n *\n * @default prod\n */\n server?: 'prod' | 'dev' | 'mock',\n }\n\n export default function request<TResponseData>(\n payload: RequestFunctionParams,\n options: RequestOptions = {\n server: 'prod',\n },\n ): Promise<TResponseData> {\n return new Promise<TResponseData>((resolve, reject) => {\n // \u57FA\u672C\u5730\u5740\n const baseUrl = options.server === 'mock'\n ? payload.mockUrl\n : options.server === 'dev'\n ? payload.devUrl\n : payload.prodUrl\n\n // \u8BF7\u6C42\u5730\u5740\n const url = \\`\\${baseUrl}\\${payload.path}\\`\n\n // \u5177\u4F53\u8BF7\u6C42\u903B\u8F91\n })\n }\n "]))))];
385
+ case 2:
386
+ _g.sent();
387
+ _g.label = 3;
388
+ case 3:
389
+ _b = syntheticalConfig.reactHooks &&
390
+ syntheticalConfig.reactHooks.enabled;
391
+ if (!_b) return [3 /*break*/, 5];
392
+ return [4 /*yield*/, fs.pathExists(rawRequestHookMakerFilePath)];
393
+ case 4:
394
+ _b = !(_g.sent());
395
+ _g.label = 5;
396
+ case 5:
397
+ if (!_b) return [3 /*break*/, 7];
398
+ return [4 /*yield*/, fs.outputFile(requestHookMakerFilePath, dedent(templateObject_3 || (templateObject_3 = __makeTemplateObject(["\n import { useState, useEffect } from 'react'\n import type { RequestConfig } from 'yapi-to-typescript2'\n import type { Request } from ", "\n import baseRequest from ", "\n\n export default function makeRequestHook<TRequestData, TRequestConfig extends RequestConfig, TRequestResult extends ReturnType<typeof baseRequest>>(request: Request<TRequestData, TRequestConfig, TRequestResult>) {\n type Data = TRequestResult extends Promise<infer R> ? R : TRequestResult\n return function useRequest(requestData: TRequestData) {\n // \u4E00\u4E2A\u7B80\u5355\u7684 Hook \u5B9E\u73B0\uFF0C\u5B9E\u9645\u9879\u76EE\u53EF\u7ED3\u5408\u5176\u4ED6\u5E93\u4F7F\u7528\uFF0C\u6BD4\u5982\uFF1A\n // @umijs/hooks \u7684 useRequest (https://github.com/umijs/hooks)\n // swr (https://github.com/zeit/swr)\n\n const [loading, setLoading] = useState(true)\n const [data, setData] = useState<Data>()\n\n useEffect(() => {\n request(requestData).then(data => {\n setLoading(false)\n setData(data as any)\n })\n }, [JSON.stringify(requestData)])\n\n return {\n loading,\n data,\n }\n }\n }\n "], ["\n import { useState, useEffect } from 'react'\n import type { RequestConfig } from 'yapi-to-typescript2'\n import type { Request } from ", "\n import baseRequest from ", "\n\n export default function makeRequestHook<TRequestData, TRequestConfig extends RequestConfig, TRequestResult extends ReturnType<typeof baseRequest>>(request: Request<TRequestData, TRequestConfig, TRequestResult>) {\n type Data = TRequestResult extends Promise<infer R> ? R : TRequestResult\n return function useRequest(requestData: TRequestData) {\n // \u4E00\u4E2A\u7B80\u5355\u7684 Hook \u5B9E\u73B0\uFF0C\u5B9E\u9645\u9879\u76EE\u53EF\u7ED3\u5408\u5176\u4ED6\u5E93\u4F7F\u7528\uFF0C\u6BD4\u5982\uFF1A\n // @umijs/hooks \u7684 useRequest (https://github.com/umijs/hooks)\n // swr (https://github.com/zeit/swr)\n\n const [loading, setLoading] = useState(true)\n const [data, setData] = useState<Data>()\n\n useEffect(() => {\n request(requestData).then(data => {\n setLoading(false)\n setData(data as any)\n })\n }, [JSON.stringify(requestData)])\n\n return {\n loading,\n data,\n }\n }\n }\n "])), JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, outputFilePath)), JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, requestFunctionFilePath))))];
399
+ case 6:
400
+ _g.sent();
401
+ _g.label = 7;
402
+ case 7:
403
+ rawOutputContent = dedent(templateObject_7 || (templateObject_7 = __makeTemplateObject(["\n /* tslint:disable */\n /* eslint-disable */\n\n /* \u8BE5\u6587\u4EF6\u7531 yapi-to-typescript2 \u81EA\u52A8\u751F\u6210\uFF0C\u8BF7\u52FF\u76F4\u63A5\u4FEE\u6539\uFF01\uFF01\uFF01 */\n\n ", "\n "], ["\n /* tslint:disable */\n /* eslint-disable */\n\n /* \u8BE5\u6587\u4EF6\u7531 yapi-to-typescript2 \u81EA\u52A8\u751F\u6210\uFF0C\u8BF7\u52FF\u76F4\u63A5\u4FEE\u6539\uFF01\uFF01\uFF01 */\n\n ", "\n "
404
+ // ref: https://prettier.io/docs/en/options.html
405
+ ])), syntheticalConfig.typesOnly
406
+ ? dedent(templateObject_4 || (templateObject_4 = __makeTemplateObject(["\n // @ts-ignore\n type FileData = File\n\n ", "\n "], ["\n // @ts-ignore\n type FileData = File\n\n ", "\n "])), content.join('\n\n').trim()) : dedent(templateObject_6 || (templateObject_6 = __makeTemplateObject(["\n // @ts-ignore\n // prettier-ignore\n import { QueryStringArrayFormat, Method, RequestBodyType, ResponseBodyType, FileData, prepare } from 'yapi-to-typescript2'\n // @ts-ignore\n // prettier-ignore\n import type { RequestConfig, RequestFunctionRestArgs } from 'yapi-to-typescript2'\n // @ts-ignore\n import request from ", "\n ", "\n\n type UserRequestRestArgs = RequestFunctionRestArgs<typeof request>\n\n // Request: \u76EE\u524D React Hooks \u529F\u80FD\u6709\u7528\u5230\n export type Request<TRequestData, TRequestConfig extends RequestConfig, TRequestResult> = (\n TRequestConfig['requestDataOptional'] extends true\n ? (requestData?: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult\n : (requestData: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult\n ) & {\n requestConfig: TRequestConfig\n }\n\n ", "\n "], ["\n // @ts-ignore\n // prettier-ignore\n import { QueryStringArrayFormat, Method, RequestBodyType, ResponseBodyType, FileData, prepare } from 'yapi-to-typescript2'\n // @ts-ignore\n // prettier-ignore\n import type { RequestConfig, RequestFunctionRestArgs } from 'yapi-to-typescript2'\n // @ts-ignore\n import request from ", "\n ", "\n\n type UserRequestRestArgs = RequestFunctionRestArgs<typeof request>\n\n // Request: \u76EE\u524D React Hooks \u529F\u80FD\u6709\u7528\u5230\n export type Request<TRequestData, TRequestConfig extends RequestConfig, TRequestResult> = (\n TRequestConfig['requestDataOptional'] extends true\n ? (requestData?: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult\n : (requestData: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult\n ) & {\n requestConfig: TRequestConfig\n }\n\n ", "\n "])), JSON.stringify(getNormalizedRelativePath(outputFilePath, requestFunctionFilePath)), !syntheticalConfig.reactHooks ||
407
+ !syntheticalConfig.reactHooks.enabled
408
+ ? ''
409
+ : dedent(templateObject_5 || (templateObject_5 = __makeTemplateObject(["\n // @ts-ignore\n import makeRequestHook from ", "\n "], ["\n // @ts-ignore\n import makeRequestHook from ", "\n "])), JSON.stringify(getNormalizedRelativePath(outputFilePath, requestHookMakerFilePath))), content.join('\n\n').trim()));
410
+ return [4 /*yield*/, getPrettier(this.options.cwd)
411
+ // 此处需用 await 以兼容 Prettier 3
412
+ ];
413
+ case 8:
414
+ prettier = _g.sent();
415
+ _d = (_c = prettier).format;
416
+ _e = [rawOutputContent];
417
+ _f = [{}];
418
+ return [4 /*yield*/, getCachedPrettierOptions()];
419
+ case 9: return [4 /*yield*/, _d.apply(_c, _e.concat([__assign.apply(void 0, [__assign.apply(void 0, _f.concat([(_g.sent())])), { filepath: outputFilePath }])]))];
420
+ case 10:
421
+ prettyOutputContent = _g.sent();
422
+ outputContent = "".concat(dedent(templateObject_8 || (templateObject_8 = __makeTemplateObject(["\n /* prettier-ignore-start */\n ", "\n /* prettier-ignore-end */\n "], ["\n /* prettier-ignore-start */\n ", "\n /* prettier-ignore-end */\n "])), prettyOutputContent), "\n");
423
+ return [4 /*yield*/, fs.outputFile(outputFilePath, outputContent)
424
+ // 如果要生成 JavaScript 代码,
425
+ // 则先对主文件进行 tsc 编译,主文件引用到的其他文件也会被编译,
426
+ // 然后,删除原始的 .tsx? 文件。
427
+ ];
428
+ case 11:
429
+ _g.sent();
430
+ if (!(syntheticalConfig.target === 'javascript')) return [3 /*break*/, 14];
431
+ return [4 /*yield*/, this.tsc(outputFilePath)];
432
+ case 12:
433
+ _g.sent();
434
+ return [4 /*yield*/, Promise.all([
435
+ fs.remove(requestFunctionFilePath).catch(noop),
436
+ fs.remove(requestHookMakerFilePath).catch(noop),
437
+ fs.remove(outputFilePath).catch(noop),
438
+ ])];
439
+ case 13:
440
+ _g.sent();
441
+ _g.label = 14;
442
+ case 14: return [2 /*return*/];
443
+ }
444
+ });
445
+ }); }))];
446
+ });
447
+ });
448
+ };
449
+ Generator.prototype.tsc = function (file) {
450
+ return __awaiter(this, void 0, void 0, function () {
451
+ var _this = this;
452
+ return __generator(this, function (_a) {
453
+ return [2 /*return*/, new Promise(function (resolve) {
454
+ // add this to fix bug that not-generator-file-on-window
455
+ var command = "".concat(require('os').platform() === 'win32' ? 'node ' : '').concat(JSON.stringify(require.resolve("typescript/bin/tsc")));
456
+ exec("".concat(command, " --target ES2019 --module ESNext --jsx preserve --declaration --esModuleInterop ").concat(JSON.stringify(file)), {
457
+ cwd: _this.options.cwd,
458
+ env: process.env,
459
+ }, function () { return resolve(); });
460
+ })];
461
+ });
462
+ });
463
+ };
464
+ Generator.prototype.fetchApi = function (url, query) {
465
+ return __awaiter(this, void 0, void 0, function () {
466
+ var res;
467
+ return __generator(this, function (_a) {
468
+ switch (_a.label) {
469
+ case 0: return [4 /*yield*/, httpGet(url, query)
470
+ /* istanbul ignore next */
471
+ ];
472
+ case 1:
473
+ res = _a.sent();
474
+ /* istanbul ignore next */
475
+ if (res && res.errcode) {
476
+ throwError("".concat(res.errmsg, " [\u8BF7\u6C42\u5730\u5740: ").concat(url, "] [\u8BF7\u6C42\u53C2\u6570: ").concat(new URLSearchParams(query).toString(), "]"));
477
+ }
478
+ return [2 /*return*/, res.data || res];
479
+ }
480
+ });
481
+ });
482
+ };
483
+ /** 获取分类的接口列表 */
484
+ Generator.prototype.fetchInterfaceList = function (_a) {
485
+ var serverUrl = _a.serverUrl, token = _a.token, id = _a.id;
486
+ return __awaiter(this, void 0, void 0, function () {
487
+ var category;
488
+ return __generator(this, function (_b) {
489
+ switch (_b.label) {
490
+ case 0: return [4 /*yield*/, this.fetchExport({ serverUrl: serverUrl, token: token })];
491
+ case 1:
492
+ category = ((_b.sent()) || []).find(function (cat) { return !isEmpty(cat) && !isEmpty(cat.list) && cat.list[0].catid === id; });
493
+ if (category) {
494
+ category.list.forEach(function (interfaceInfo) {
495
+ // 实现 _category 字段
496
+ interfaceInfo._category = omit(category, ['list']);
497
+ });
498
+ }
499
+ return [2 /*return*/, category ? category.list : []];
500
+ }
501
+ });
502
+ });
503
+ };
504
+ /** 获取项目信息 */
505
+ Generator.prototype.fetchProjectInfo = function (syntheticalConfig) {
506
+ return __awaiter(this, void 0, void 0, function () {
507
+ var projectInfo, projectCats;
508
+ return __generator(this, function (_a) {
509
+ switch (_a.label) {
510
+ case 0: return [4 /*yield*/, this.fetchProject(syntheticalConfig)];
511
+ case 1:
512
+ projectInfo = _a.sent();
513
+ return [4 /*yield*/, this.fetchApi("".concat(syntheticalConfig.serverUrl, "/api/interface/getCatMenu"), {
514
+ token: syntheticalConfig.token,
515
+ project_id: projectInfo._id,
516
+ })];
517
+ case 2:
518
+ projectCats = _a.sent();
519
+ return [2 /*return*/, __assign(__assign({}, projectInfo), { cats: projectCats, getMockUrl: function () {
520
+ return "".concat(syntheticalConfig.serverUrl, "/mock/").concat(projectInfo._id);
521
+ }, getDevUrl: function (devEnvName) {
522
+ var env = projectInfo.env.find(function (e) { return e.name === devEnvName; });
523
+ return (env && env.domain) /* istanbul ignore next */ || '';
524
+ }, getProdUrl: function (prodEnvName) {
525
+ var env = projectInfo.env.find(function (e) { return e.name === prodEnvName; });
526
+ return (env && env.domain) /* istanbul ignore next */ || '';
527
+ } })];
528
+ }
529
+ });
530
+ });
531
+ };
532
+ /** 生成接口代码 */
533
+ Generator.prototype.generateInterfaceCode = function (syntheticalConfig, interfaceInfo, categoryUID) {
534
+ var _a, _b, _c, _d;
535
+ return __awaiter(this, void 0, void 0, function () {
536
+ var extendedInterfaceInfo, requestFunctionName, _e, requestConfigName, requestConfigTypeName, requestDataTypeName, _f, responseDataTypeName, _g, requestDataJsonSchema, requestDataType, responseDataJsonSchema, responseDataType, isRequestDataOptional, requestHookName, _h, _j, paramNames, paramNamesLiteral, paramNameType, queryNames, queryNamesLiteral, queryNameType, genComment, requestFunctionExtraInfo, _k;
537
+ return __generator(this, function (_l) {
538
+ switch (_l.label) {
539
+ case 0:
540
+ extendedInterfaceInfo = __assign(__assign({}, interfaceInfo), { parsedPath: path.parse(interfaceInfo.path) });
541
+ if (!isFunction(syntheticalConfig.getRequestFunctionName)) return [3 /*break*/, 2];
542
+ return [4 /*yield*/, syntheticalConfig.getRequestFunctionName(extendedInterfaceInfo, changeCase)];
543
+ case 1:
544
+ _e = _l.sent();
545
+ return [3 /*break*/, 3];
546
+ case 2:
547
+ _e = changeCase.camelCase(extendedInterfaceInfo.parsedPath.name);
548
+ _l.label = 3;
549
+ case 3:
550
+ requestFunctionName = _e;
551
+ requestConfigName = changeCase.camelCase("".concat(requestFunctionName, "RequestConfig"));
552
+ requestConfigTypeName = changeCase.pascalCase(requestConfigName);
553
+ if (!isFunction(syntheticalConfig.getRequestDataTypeName)) return [3 /*break*/, 5];
554
+ return [4 /*yield*/, syntheticalConfig.getRequestDataTypeName(extendedInterfaceInfo, changeCase)];
555
+ case 4:
556
+ _f = _l.sent();
557
+ return [3 /*break*/, 6];
558
+ case 5:
559
+ _f = changeCase.pascalCase("".concat(requestFunctionName, "Request"));
560
+ _l.label = 6;
561
+ case 6:
562
+ requestDataTypeName = _f;
563
+ if (!isFunction(syntheticalConfig.getResponseDataTypeName)) return [3 /*break*/, 8];
564
+ return [4 /*yield*/, syntheticalConfig.getResponseDataTypeName(extendedInterfaceInfo, changeCase)];
565
+ case 7:
566
+ _g = _l.sent();
567
+ return [3 /*break*/, 9];
568
+ case 8:
569
+ _g = changeCase.pascalCase("".concat(requestFunctionName, "Response"));
570
+ _l.label = 9;
571
+ case 9:
572
+ responseDataTypeName = _g;
573
+ requestDataJsonSchema = getRequestDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {});
574
+ return [4 /*yield*/, jsonSchemaToType(requestDataJsonSchema, requestDataTypeName)];
575
+ case 10:
576
+ requestDataType = _l.sent();
577
+ responseDataJsonSchema = getResponseDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {}, syntheticalConfig.dataKey);
578
+ return [4 /*yield*/, jsonSchemaToType(responseDataJsonSchema, responseDataTypeName)];
579
+ case 11:
580
+ responseDataType = _l.sent();
581
+ isRequestDataOptional = /(\{\}|any)$/s.test(requestDataType);
582
+ if (!(syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled)) return [3 /*break*/, 15];
583
+ if (!isFunction(syntheticalConfig.reactHooks.getRequestHookName)) return [3 /*break*/, 13];
584
+ return [4 /*yield*/, syntheticalConfig.reactHooks.getRequestHookName(extendedInterfaceInfo, changeCase)];
585
+ case 12:
586
+ _j = _l.sent();
587
+ return [3 /*break*/, 14];
588
+ case 13:
589
+ _j = "use".concat(changeCase.pascalCase(requestFunctionName));
590
+ _l.label = 14;
591
+ case 14:
592
+ _h = _j;
593
+ return [3 /*break*/, 16];
594
+ case 15:
595
+ _h = '';
596
+ _l.label = 16;
597
+ case 16:
598
+ requestHookName = _h;
599
+ paramNames = (extendedInterfaceInfo.req_params /* istanbul ignore next */ || []).map(function (item) { return item.name; });
600
+ paramNamesLiteral = JSON.stringify(paramNames);
601
+ paramNameType = paramNames.length === 0 ? 'string' : "'".concat(paramNames.join("' | '"), "'");
602
+ queryNames = (extendedInterfaceInfo.req_query /* istanbul ignore next */ || []).map(function (item) { return item.name; });
603
+ queryNamesLiteral = JSON.stringify(queryNames);
604
+ queryNameType = queryNames.length === 0 ? 'string' : "'".concat(queryNames.join("' | '"), "'");
605
+ genComment = function (genTitle) {
606
+ var _a = __assign(__assign({}, syntheticalConfig.comment), (syntheticalConfig.serverType === 'swagger'
607
+ ? {
608
+ tag: false,
609
+ updateTime: false,
610
+ link: false,
611
+ }
612
+ : {})), _b = _a.enabled, isEnabled = _b === void 0 ? true : _b, _c = _a.title, hasTitle = _c === void 0 ? true : _c, _d = _a.category, hasCategory = _d === void 0 ? true : _d, _e = _a.tag, hasTag = _e === void 0 ? true : _e, _f = _a.requestHeader, hasRequestHeader = _f === void 0 ? true : _f, _g = _a.updateTime, hasUpdateTime = _g === void 0 ? true : _g, _h = _a.link, hasLink = _h === void 0 ? true : _h, extraTags = _a.extraTags;
613
+ if (!isEnabled) {
614
+ return '';
615
+ }
616
+ // 转义标题中的 /
617
+ var escapedTitle = String(extendedInterfaceInfo.title).replace(/\//g, '\\/');
618
+ var description = hasLink
619
+ ? "[".concat(escapedTitle, "\u2197](").concat(extendedInterfaceInfo._url, ")")
620
+ : escapedTitle;
621
+ var summary = [
622
+ hasCategory && {
623
+ label: '分类',
624
+ value: hasLink
625
+ ? "[".concat(extendedInterfaceInfo._category.name, "\u2197](").concat(extendedInterfaceInfo._category._url, ")")
626
+ : extendedInterfaceInfo._category.name,
627
+ },
628
+ hasTag && {
629
+ label: '标签',
630
+ value: extendedInterfaceInfo.tag.map(function (tag) { return "`".concat(tag, "`"); }),
631
+ },
632
+ hasRequestHeader && {
633
+ label: '请求头',
634
+ value: "`".concat(extendedInterfaceInfo.method.toUpperCase(), " ").concat(extendedInterfaceInfo.path, "`"),
635
+ },
636
+ hasUpdateTime && {
637
+ label: '更新时间',
638
+ value: process.env.JEST_WORKER_ID // 测试时使用 unix 时间戳
639
+ ? String(extendedInterfaceInfo.up_time)
640
+ : /* istanbul ignore next */
641
+ "`".concat(dayjs(extendedInterfaceInfo.up_time * 1000).format('YYYY-MM-DD HH:mm:ss'), "`"),
642
+ },
643
+ ];
644
+ if (typeof extraTags === 'function') {
645
+ var tags = extraTags(extendedInterfaceInfo);
646
+ for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
647
+ var tag = tags_1[_i];
648
+ ;
649
+ (tag.position === 'start' ? summary.unshift : summary.push).call(summary, {
650
+ label: tag.name,
651
+ value: tag.value,
652
+ });
653
+ }
654
+ }
655
+ var titleComment = hasTitle
656
+ ? dedent(templateObject_9 || (templateObject_9 = __makeTemplateObject(["\n * ", "\n *\n "], ["\n * ", "\n *\n "])), genTitle(description)) : '';
657
+ var extraComment = summary
658
+ .filter(function (item) { return typeof item !== 'boolean' && !isEmpty(item.value); })
659
+ .map(function (item) {
660
+ var _item = item;
661
+ return "* @".concat(_item.label, " ").concat(castArray(_item.value).join(', '));
662
+ })
663
+ .join('\n');
664
+ return dedent(templateObject_10 || (templateObject_10 = __makeTemplateObject(["\n /**\n ", "\n */\n "], ["\n /**\n ", "\n */\n "])), [titleComment, extraComment].filter(Boolean).join('\n'));
665
+ };
666
+ if (!(typeof syntheticalConfig.setRequestFunctionExtraInfo === 'function')) return [3 /*break*/, 18];
667
+ return [4 /*yield*/, syntheticalConfig.setRequestFunctionExtraInfo(extendedInterfaceInfo, changeCase)];
668
+ case 17:
669
+ _k = _l.sent();
670
+ return [3 /*break*/, 19];
671
+ case 18:
672
+ _k = {};
673
+ _l.label = 19;
674
+ case 19:
675
+ requestFunctionExtraInfo = _k;
676
+ return [2 /*return*/, dedent(templateObject_13 || (templateObject_13 = __makeTemplateObject(["\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n "], ["\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n "])), genComment(function (title) { return "\u63A5\u53E3 ".concat(title, " \u7684 **\u8BF7\u6C42\u7C7B\u578B**"); }), requestDataType.trim(), genComment(function (title) { return "\u63A5\u53E3 ".concat(title, " \u7684 **\u8FD4\u56DE\u7C7B\u578B**"); }), responseDataType.trim(), syntheticalConfig.typesOnly
677
+ ? ''
678
+ : dedent(templateObject_12 || (templateObject_12 = __makeTemplateObject(["\n ", "\n type ", " = Readonly<RequestConfig<\n ", ",\n ", ",\n ", ",\n ", ",\n ", ",\n ", ",\n ", ",\n ", "\n >>\n\n ", "\n const ", ": ", " = ", " {\n mockUrl: mockUrl", ",\n devUrl: devUrl", ",\n prodUrl: prodUrl", ",\n path: ", ",\n method: Method.", ",\n requestHeaders: ", ",\n requestBodyType: RequestBodyType.", ",\n responseBodyType: ResponseBodyType.", ",\n dataKey: dataKey", ",\n paramNames: ", ",\n queryNames: ", ",\n requestDataOptional: ", ",\n requestDataJsonSchema: ", ",\n responseDataJsonSchema: ", ",\n requestFunctionName: ", ",\n queryStringArrayFormat: QueryStringArrayFormat.", ",\n extraInfo: ", ",\n }\n\n ", "\n export const ", " = ", " (\n requestData", ": ", ",\n ...args: UserRequestRestArgs\n ) => {\n return request<", ">(\n prepare(", ", requestData),\n ...args,\n )\n }\n\n ", ".requestConfig = ", "\n\n ", "\n "], ["\n ", "\n type ", " = Readonly<RequestConfig<\n ", ",\n ", ",\n ", ",\n ", ",\n ", ",\n ", ",\n ", ",\n ", "\n >>\n\n ", "\n const ", ": ", " = ", " {\n mockUrl: mockUrl", ",\n devUrl: devUrl", ",\n prodUrl: prodUrl", ",\n path: ", ",\n method: Method.", ",\n requestHeaders: ", ",\n requestBodyType: RequestBodyType.", ",\n responseBodyType: ResponseBodyType.", ",\n dataKey: dataKey", ",\n paramNames: ", ",\n queryNames: ", ",\n requestDataOptional: ", ",\n requestDataJsonSchema: ", ",\n responseDataJsonSchema: ", ",\n requestFunctionName: ", ",\n queryStringArrayFormat: QueryStringArrayFormat.", ",\n extraInfo: ", ",\n }\n\n ", "\n export const ", " = ", " (\n requestData", ": ", ",\n ...args: UserRequestRestArgs\n ) => {\n return request<", ">(\n prepare(", ", requestData),\n ...args,\n )\n }\n\n ", ".requestConfig = ", "\n\n ", "\n "])), genComment(function (title) { return "\u63A5\u53E3 ".concat(title, " \u7684 **\u8BF7\u6C42\u914D\u7F6E\u7684\u7C7B\u578B**"); }), requestConfigTypeName, JSON.stringify(syntheticalConfig.mockUrl), JSON.stringify(syntheticalConfig.devUrl), JSON.stringify(syntheticalConfig.prodUrl), JSON.stringify(extendedInterfaceInfo.path), JSON.stringify(syntheticalConfig.dataKey) || 'undefined', paramNameType, queryNameType, JSON.stringify(isRequestDataOptional), genComment(function (title) { return "\u63A5\u53E3 ".concat(title, " \u7684 **\u8BF7\u6C42\u914D\u7F6E**"); }), requestConfigName, requestConfigTypeName, COMPRESSOR_TREE_SHAKING_ANNOTATION, categoryUID, categoryUID, categoryUID, JSON.stringify(extendedInterfaceInfo.path), extendedInterfaceInfo.method, JSON.stringify((extendedInterfaceInfo.req_headers || [])
679
+ .filter(function (item) { return item.name.toLowerCase() !== 'content-type'; })
680
+ .reduce(function (res, item) {
681
+ res[item.name] = item.value;
682
+ return res;
683
+ }, {})), extendedInterfaceInfo.method === Method.GET
684
+ ? RequestBodyType.query
685
+ : extendedInterfaceInfo.req_body_type /* istanbul ignore next */ ||
686
+ RequestBodyType.none, extendedInterfaceInfo.res_body_type, categoryUID, paramNamesLiteral, queryNamesLiteral, JSON.stringify(isRequestDataOptional), JSON.stringify(((_a = syntheticalConfig.jsonSchema) === null || _a === void 0 ? void 0 : _a.enabled) &&
687
+ ((_b = syntheticalConfig.jsonSchema) === null || _b === void 0 ? void 0 : _b.requestData) !== false
688
+ ? requestDataJsonSchema
689
+ : {}), JSON.stringify(((_c = syntheticalConfig.jsonSchema) === null || _c === void 0 ? void 0 : _c.enabled) &&
690
+ ((_d = syntheticalConfig.jsonSchema) === null || _d === void 0 ? void 0 : _d.responseData) !== false
691
+ ? responseDataJsonSchema
692
+ : {}), JSON.stringify(requestFunctionName), syntheticalConfig.queryStringArrayFormat ||
693
+ QueryStringArrayFormat.brackets, JSON.stringify(requestFunctionExtraInfo), genComment(function (title) { return "\u63A5\u53E3 ".concat(title, " \u7684 **\u8BF7\u6C42\u51FD\u6570**"); }), requestFunctionName, COMPRESSOR_TREE_SHAKING_ANNOTATION, isRequestDataOptional ? '?' : '', requestDataTypeName, responseDataTypeName, requestConfigName, requestFunctionName, requestConfigName, !syntheticalConfig.reactHooks ||
694
+ !syntheticalConfig.reactHooks.enabled
695
+ ? ''
696
+ : dedent(templateObject_11 || (templateObject_11 = __makeTemplateObject(["\n ", "\n export const ", " = ", " makeRequestHook<", ", ", ", ReturnType<typeof ", ">>(", ")\n "], ["\n ", "\n export const ", " = ", " makeRequestHook<", ", ", ", ReturnType<typeof ", ">>(", ")\n "])), genComment(function (title) { return "\u63A5\u53E3 ".concat(title, " \u7684 **React Hook**"); }), requestHookName, COMPRESSOR_TREE_SHAKING_ANNOTATION, requestDataTypeName, requestConfigTypeName, requestFunctionName, requestFunctionName)))];
697
+ }
698
+ });
699
+ });
700
+ };
701
+ Generator.prototype.destroy = function () {
702
+ return __awaiter(this, void 0, void 0, function () {
703
+ var _this = this;
704
+ return __generator(this, function (_a) {
705
+ return [2 /*return*/, Promise.all(this.disposes.map(function (dispose) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
706
+ return [2 /*return*/, dispose()];
707
+ }); }); }))];
708
+ });
709
+ });
710
+ };
711
+ return Generator;
712
+ }());
713
+ export { Generator };
714
+ var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6, templateObject_7, templateObject_8, templateObject_9, templateObject_10, templateObject_11, templateObject_12, templateObject_13;