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.
package/lib/cjs/utils.js CHANGED
@@ -1,86 +1,101 @@
1
1
  "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
-
5
- exports.__esModule = true;
6
- exports.getCachedPrettierOptions = void 0;
7
- exports.getNormalizedRelativePath = getNormalizedRelativePath;
8
- exports.getPrettier = getPrettier;
9
- exports.getPrettierOptions = getPrettierOptions;
10
- exports.getRequestDataJsonSchema = getRequestDataJsonSchema;
11
- exports.getResponseDataJsonSchema = getResponseDataJsonSchema;
12
- exports.httpGet = httpGet;
13
- exports.isGetLikeMethod = isGetLikeMethod;
14
- exports.isPostLikeMethod = isPostLikeMethod;
15
- exports.jsonSchemaStringToJsonSchema = jsonSchemaStringToJsonSchema;
16
- exports.jsonSchemaToJSTTJsonSchema = jsonSchemaToJSTTJsonSchema;
17
- exports.jsonSchemaToType = jsonSchemaToType;
18
- exports.jsonToJsonSchema = jsonToJsonSchema;
19
- exports.mockjsTemplateToJsonSchema = mockjsTemplateToJsonSchema;
20
- exports.processJsonSchema = processJsonSchema;
21
- exports.propDefinitionsToJsonSchema = propDefinitionsToJsonSchema;
22
- exports.reachJsonSchema = reachJsonSchema;
23
- exports.sortByWeights = sortByWeights;
24
- exports.throwError = throwError;
25
- exports.toUnixPath = toUnixPath;
26
- exports.traverseJsonSchema = traverseJsonSchema;
27
-
28
- var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
29
-
30
- var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
31
-
32
- var _createForOfIteratorHelperLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/createForOfIteratorHelperLoose"));
33
-
34
- var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
35
-
36
- var _fsExtra = _interopRequireDefault(require("fs-extra"));
37
-
38
- var _json = _interopRequireDefault(require("json5"));
39
-
40
- var _nodeFetch = _interopRequireDefault(require("node-fetch"));
41
-
42
- var _path = _interopRequireDefault(require("path"));
43
-
44
- var _prettier = _interopRequireDefault(require("prettier"));
45
-
46
- var _proxyAgent = _interopRequireDefault(require("proxy-agent"));
47
-
48
- var _toJsonSchema = _interopRequireDefault(require("to-json-schema"));
49
-
50
- var _vtils = require("vtils");
51
-
52
- var _jsonSchemaToTypescript = require("json-schema-to-typescript");
53
-
54
- var _helpers = require("./helpers");
55
-
56
- var _types = require("./types");
57
-
58
- var _url2 = require("url");
59
-
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
+ 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;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
50
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
51
+ if (ar || !(i in from)) {
52
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
53
+ ar[i] = from[i];
54
+ }
55
+ }
56
+ return to.concat(ar || Array.prototype.slice.call(from));
57
+ };
58
+ var __importDefault = (this && this.__importDefault) || function (mod) {
59
+ return (mod && mod.__esModule) ? mod : { "default": mod };
60
+ };
61
+ Object.defineProperty(exports, "__esModule", { value: true });
62
+ exports.httpGet = exports.getCachedPrettierOptions = exports.getPrettierOptions = exports.getPrettier = exports.isPostLikeMethod = exports.isGetLikeMethod = exports.sortByWeights = exports.reachJsonSchema = exports.getResponseDataJsonSchema = exports.getRequestDataJsonSchema = exports.jsonSchemaToType = exports.propDefinitionsToJsonSchema = exports.mockjsTemplateToJsonSchema = exports.jsonToJsonSchema = exports.jsonSchemaStringToJsonSchema = exports.jsonSchemaToJSTTJsonSchema = exports.processJsonSchema = exports.traverseJsonSchema = exports.getNormalizedRelativePath = exports.toUnixPath = exports.throwError = void 0;
63
+ var fs_extra_1 = __importDefault(require("fs-extra"));
64
+ var json5_1 = __importDefault(require("json5"));
65
+ var node_fetch_1 = __importDefault(require("node-fetch"));
66
+ var path_1 = __importDefault(require("path"));
67
+ var prettier_1 = __importDefault(require("prettier"));
68
+ var proxy_agent_1 = __importDefault(require("proxy-agent"));
69
+ var to_json_schema_1 = __importDefault(require("to-json-schema"));
70
+ var vtils_1 = require("vtils");
71
+ var json_schema_to_typescript_1 = require("json-schema-to-typescript");
72
+ var helpers_1 = require("./helpers");
73
+ var types_1 = require("./types");
74
+ var url_1 = require("url");
60
75
  /**
61
76
  * 抛出错误。
62
77
  *
63
78
  * @param msg 错误信息
64
79
  */
65
80
  function throwError() {
66
- for (var _len = arguments.length, msg = new Array(_len), _key = 0; _key < _len; _key++) {
67
- msg[_key] = arguments[_key];
68
- }
69
-
70
- /* istanbul ignore next */
71
- throw new Error(msg.join(''));
81
+ var msg = [];
82
+ for (var _i = 0; _i < arguments.length; _i++) {
83
+ msg[_i] = arguments[_i];
84
+ }
85
+ /* istanbul ignore next */
86
+ throw new Error(msg.join(''));
72
87
  }
88
+ exports.throwError = throwError;
73
89
  /**
74
90
  * 将路径统一为 unix 风格的路径。
75
91
  *
76
92
  * @param path 路径
77
93
  * @returns unix 风格的路径
78
94
  */
79
-
80
-
81
95
  function toUnixPath(path) {
82
- return path.replace(/[/\\]+/g, '/');
96
+ return path.replace(/[/\\]+/g, '/');
83
97
  }
98
+ exports.toUnixPath = toUnixPath;
84
99
  /**
85
100
  * 获得规范化的相对路径。
86
101
  *
@@ -88,319 +103,267 @@ function toUnixPath(path) {
88
103
  * @param to 去向路径
89
104
  * @returns 相对路径
90
105
  */
91
-
92
-
93
106
  function getNormalizedRelativePath(from, to) {
94
- return toUnixPath(_path.default.relative(_path.default.dirname(from), to)).replace(/^(?=[^.])/, './').replace(/\.(ts|js)x?$/i, '');
107
+ return toUnixPath(path_1.default.relative(path_1.default.dirname(from), to))
108
+ .replace(/^(?=[^.])/, './')
109
+ .replace(/\.(ts|js)x?$/i, '');
95
110
  }
111
+ exports.getNormalizedRelativePath = getNormalizedRelativePath;
96
112
  /**
97
113
  * 原地遍历 JSONSchema。
98
114
  */
99
-
100
-
101
115
  function traverseJsonSchema(jsonSchema, cb, currentPath) {
102
- if (currentPath === void 0) {
103
- currentPath = [];
104
- }
105
-
106
- /* istanbul ignore if */
107
- if (!(0, _vtils.isObject)(jsonSchema)) return jsonSchema; // Mock.toJSONSchema 产生的 properties 为数组,然而 JSONSchema4 的 properties 为对象
108
-
109
- if ((0, _vtils.isArray)(jsonSchema.properties)) {
110
- jsonSchema.properties = jsonSchema.properties.reduce(function (props, js) {
111
- props[js.name] = js;
112
- return props;
113
- }, {});
114
- } // 处理传入的 JSONSchema
115
-
116
-
117
- cb(jsonSchema, currentPath); // 继续处理对象的子元素
118
-
119
- if (jsonSchema.properties) {
120
- (0, _vtils.forOwn)(jsonSchema.properties, function (item, key) {
121
- return traverseJsonSchema(item, cb, [].concat(currentPath, [key]));
122
- });
123
- } // 继续处理数组的子元素
124
-
125
-
126
- if (jsonSchema.items) {
127
- (0, _vtils.castArray)(jsonSchema.items).forEach(function (item, index) {
128
- return traverseJsonSchema(item, cb, [].concat(currentPath, [index]));
129
- });
130
- } // 处理 oneOf
131
-
132
-
133
- if (jsonSchema.oneOf) {
134
- jsonSchema.oneOf.forEach(function (item) {
135
- return traverseJsonSchema(item, cb, currentPath);
136
- });
137
- } // 处理 anyOf
138
-
139
-
140
- if (jsonSchema.anyOf) {
141
- jsonSchema.anyOf.forEach(function (item) {
142
- return traverseJsonSchema(item, cb, currentPath);
143
- });
144
- } // 处理 allOf
145
-
146
-
147
- if (jsonSchema.allOf) {
148
- jsonSchema.allOf.forEach(function (item) {
149
- return traverseJsonSchema(item, cb, currentPath);
150
- });
151
- }
152
-
153
- return jsonSchema;
116
+ if (currentPath === void 0) { currentPath = []; }
117
+ /* istanbul ignore if */
118
+ if (!(0, vtils_1.isObject)(jsonSchema))
119
+ return jsonSchema;
120
+ // Mock.toJSONSchema 产生的 properties 为数组,然而 JSONSchema4 的 properties 为对象
121
+ if ((0, vtils_1.isArray)(jsonSchema.properties)) {
122
+ jsonSchema.properties = jsonSchema.properties.reduce(function (props, js) {
123
+ props[js.name] = js;
124
+ return props;
125
+ }, {});
126
+ }
127
+ // 处理传入的 JSONSchema
128
+ cb(jsonSchema, currentPath);
129
+ // 继续处理对象的子元素
130
+ if (jsonSchema.properties) {
131
+ (0, vtils_1.forOwn)(jsonSchema.properties, function (item, key) {
132
+ return traverseJsonSchema(item, cb, __spreadArray(__spreadArray([], currentPath, true), [key], false));
133
+ });
134
+ }
135
+ // 继续处理数组的子元素
136
+ if (jsonSchema.items) {
137
+ (0, vtils_1.castArray)(jsonSchema.items).forEach(function (item, index) {
138
+ return traverseJsonSchema(item, cb, __spreadArray(__spreadArray([], currentPath, true), [index], false));
139
+ });
140
+ }
141
+ // 处理 oneOf
142
+ if (jsonSchema.oneOf) {
143
+ jsonSchema.oneOf.forEach(function (item) { return traverseJsonSchema(item, cb, currentPath); });
144
+ }
145
+ // 处理 anyOf
146
+ if (jsonSchema.anyOf) {
147
+ jsonSchema.anyOf.forEach(function (item) { return traverseJsonSchema(item, cb, currentPath); });
148
+ }
149
+ // 处理 allOf
150
+ if (jsonSchema.allOf) {
151
+ jsonSchema.allOf.forEach(function (item) { return traverseJsonSchema(item, cb, currentPath); });
152
+ }
153
+ return jsonSchema;
154
154
  }
155
+ exports.traverseJsonSchema = traverseJsonSchema;
155
156
  /**
156
157
  * 原地处理 JSONSchema。
157
158
  *
158
159
  * @param jsonSchema 待处理的 JSONSchema
159
160
  * @returns 处理后的 JSONSchema
160
161
  */
161
-
162
-
163
162
  function processJsonSchema(jsonSchema, customTypeMapping) {
164
- return traverseJsonSchema(jsonSchema, function (jsonSchema) {
165
- // 删除通过 swagger 导入时未剔除的 ref
166
- delete jsonSchema.$ref;
167
- delete jsonSchema.$$ref; // 数组只取第一个判断类型
168
-
169
- if (jsonSchema.type === 'array' && Array.isArray(jsonSchema.items) && jsonSchema.items.length) {
170
- jsonSchema.items = jsonSchema.items[0];
171
- } // 处理类型名称为标准的 JSONSchema 类型名称
172
-
173
-
174
- if (jsonSchema.type) {
175
- // 类型映射表,键都为小写
176
- var typeMapping = (0, _extends2.default)({
177
- byte: 'integer',
178
- short: 'integer',
179
- int: 'integer',
180
- long: 'integer',
181
- float: 'number',
182
- double: 'number',
183
- bigdecimal: 'number',
184
- char: 'string',
185
- void: 'null'
186
- }, (0, _vtils.mapKeys)(customTypeMapping, function (_, key) {
187
- return key.toLowerCase();
188
- }));
189
- var isMultiple = Array.isArray(jsonSchema.type);
190
- var types = (0, _vtils.castArray)(jsonSchema.type).map(function (type) {
191
- // 所有类型转成小写,如:String -> string
192
- type = type.toLowerCase(); // 映射为标准的 JSONSchema 类型
193
-
194
- type = typeMapping[type] || type;
195
- return type;
196
- });
197
- jsonSchema.type = isMultiple ? types : types[0];
198
- } // 移除字段名称首尾空格
199
-
200
-
201
- if (jsonSchema.properties) {
202
- (0, _vtils.forOwn)(jsonSchema.properties, function (_, prop) {
203
- var propDef = jsonSchema.properties[prop];
204
- delete jsonSchema.properties[prop];
205
- jsonSchema.properties[prop.trim()] = propDef;
206
- });
207
-
208
- if (Array.isArray(jsonSchema.required)) {
209
- jsonSchema.required = jsonSchema.required.map(function (prop) {
210
- return prop.trim();
211
- });
212
- }
213
- }
214
-
215
- return jsonSchema;
216
- });
163
+ return traverseJsonSchema(jsonSchema, function (jsonSchema) {
164
+ // 删除通过 swagger 导入时未剔除的 ref
165
+ delete jsonSchema.$ref;
166
+ delete jsonSchema.$$ref;
167
+ // 数组只取第一个判断类型
168
+ if (jsonSchema.type === 'array' &&
169
+ Array.isArray(jsonSchema.items) &&
170
+ jsonSchema.items.length) {
171
+ jsonSchema.items = jsonSchema.items[0];
172
+ }
173
+ // 处理类型名称为标准的 JSONSchema 类型名称
174
+ if (jsonSchema.type) {
175
+ // 类型映射表,键都为小写
176
+ var typeMapping_1 = __assign({ byte: 'integer', short: 'integer', int: 'integer', long: 'integer', float: 'number', double: 'number', bigdecimal: 'number', char: 'string', void: 'null' }, (0, vtils_1.mapKeys)(customTypeMapping, function (_, key) { return key.toLowerCase(); }));
177
+ var isMultiple = Array.isArray(jsonSchema.type);
178
+ var types = (0, vtils_1.castArray)(jsonSchema.type).map(function (type) {
179
+ // 所有类型转成小写,如:String -> string
180
+ type = type.toLowerCase();
181
+ // 映射为标准的 JSONSchema 类型
182
+ type = typeMapping_1[type] || type;
183
+ return type;
184
+ });
185
+ jsonSchema.type = isMultiple ? types : types[0];
186
+ }
187
+ // 移除字段名称首尾空格
188
+ if (jsonSchema.properties) {
189
+ (0, vtils_1.forOwn)(jsonSchema.properties, function (_, prop) {
190
+ var propDef = jsonSchema.properties[prop];
191
+ delete jsonSchema.properties[prop];
192
+ jsonSchema.properties[prop.trim()] = propDef;
193
+ });
194
+ if (Array.isArray(jsonSchema.required)) {
195
+ jsonSchema.required = jsonSchema.required.map(function (prop) { return prop.trim(); });
196
+ }
197
+ }
198
+ return jsonSchema;
199
+ });
217
200
  }
201
+ exports.processJsonSchema = processJsonSchema;
218
202
  /**
219
203
  * 获取适用于 JSTT 的 JSONSchema。
220
204
  *
221
205
  * @param jsonSchema 待处理的 JSONSchema
222
206
  * @returns 适用于 JSTT 的 JSONSchema
223
207
  */
224
-
225
-
226
208
  function jsonSchemaToJSTTJsonSchema(jsonSchema, typeName) {
227
- if (jsonSchema) {
228
- // 去除最外层的 description 以防止 JSTT 提取它作为类型的注释
229
- delete jsonSchema.description;
230
- }
231
-
232
- return traverseJsonSchema(jsonSchema, function (jsonSchema, currentPath) {
233
- // 支持类型引用
234
- var refValue = // YApi 低版本不支持配置 title,可以在 description 里配置
235
- jsonSchema.title == null ? jsonSchema.description : jsonSchema.title;
236
-
237
- if (refValue != null && refValue.startsWith('&')) {
238
- var typeRelativePath = refValue.substring(1);
239
- var typeAbsolutePath = toUnixPath(_path.default.resolve(_path.default.dirname(("/" + currentPath.join('/')).replace(/\/{2,}/g, '/')), typeRelativePath).replace(/^[a-z]+:/i, ''));
240
- var typeAbsolutePathArr = typeAbsolutePath.split('/').filter(Boolean);
241
- var tsTypeLeft = '';
242
- var tsTypeRight = typeName;
243
-
244
- for (var _iterator = (0, _createForOfIteratorHelperLoose2.default)(typeAbsolutePathArr), _step; !(_step = _iterator()).done;) {
245
- var key = _step.value;
246
- tsTypeLeft += 'NonNullable<';
247
- tsTypeRight += "[" + JSON.stringify(key) + "]>";
248
- }
249
-
250
- var tsType = "" + tsTypeLeft + tsTypeRight;
251
- jsonSchema.tsType = tsType;
252
- } // 去除 title 和 id,防止 json-schema-to-typescript 提取它们作为接口名
253
-
254
-
255
- delete jsonSchema.title;
256
- delete jsonSchema.id; // 忽略数组长度限制
257
-
258
- delete jsonSchema.minItems;
259
- delete jsonSchema.maxItems;
260
-
261
- if (jsonSchema.type === 'object') {
262
- // additionalProperties 设为 false
263
- jsonSchema.additionalProperties = false;
264
- } // 删除 default,防止 json-schema-to-typescript 根据它推测类型
265
-
266
-
267
- delete jsonSchema.default;
268
- return jsonSchema;
269
- });
209
+ if (jsonSchema) {
210
+ // 去除最外层的 description 以防止 JSTT 提取它作为类型的注释
211
+ delete jsonSchema.description;
212
+ }
213
+ return traverseJsonSchema(jsonSchema, function (jsonSchema, currentPath) {
214
+ // 支持类型引用
215
+ var refValue =
216
+ // YApi 低版本不支持配置 title,可以在 description 里配置
217
+ jsonSchema.title == null ? jsonSchema.description : jsonSchema.title;
218
+ if (refValue === null || refValue === void 0 ? void 0 : refValue.startsWith('&')) {
219
+ var typeRelativePath = refValue.substring(1);
220
+ var typeAbsolutePath = toUnixPath(path_1.default
221
+ .resolve(path_1.default.dirname("/".concat(currentPath.join('/')).replace(/\/{2,}/g, '/')), typeRelativePath)
222
+ .replace(/^[a-z]+:/i, ''));
223
+ var typeAbsolutePathArr = typeAbsolutePath.split('/').filter(Boolean);
224
+ var tsTypeLeft = '';
225
+ var tsTypeRight = typeName;
226
+ for (var _i = 0, typeAbsolutePathArr_1 = typeAbsolutePathArr; _i < typeAbsolutePathArr_1.length; _i++) {
227
+ var key = typeAbsolutePathArr_1[_i];
228
+ tsTypeLeft += 'NonNullable<';
229
+ tsTypeRight += "[".concat(JSON.stringify(key), "]>");
230
+ }
231
+ var tsType = "".concat(tsTypeLeft).concat(tsTypeRight);
232
+ jsonSchema.tsType = tsType;
233
+ }
234
+ // 去除 title 和 id,防止 json-schema-to-typescript 提取它们作为接口名
235
+ delete jsonSchema.title;
236
+ delete jsonSchema.id;
237
+ // 忽略数组长度限制
238
+ delete jsonSchema.minItems;
239
+ delete jsonSchema.maxItems;
240
+ if (jsonSchema.type === 'object') {
241
+ // 将 additionalProperties 设为 false
242
+ jsonSchema.additionalProperties = false;
243
+ }
244
+ // 删除 default,防止 json-schema-to-typescript 根据它推测类型
245
+ delete jsonSchema.default;
246
+ return jsonSchema;
247
+ });
270
248
  }
249
+ exports.jsonSchemaToJSTTJsonSchema = jsonSchemaToJSTTJsonSchema;
271
250
  /**
272
251
  * 将 JSONSchema 字符串转为 JSONSchema 对象。
273
252
  *
274
253
  * @param str 要转换的 JSONSchema 字符串
275
254
  * @returns 转换后的 JSONSchema 对象
276
255
  */
277
-
278
-
279
256
  function jsonSchemaStringToJsonSchema(str, customTypeMapping) {
280
- return processJsonSchema(JSON.parse(str), customTypeMapping);
257
+ return processJsonSchema(JSON.parse(str), customTypeMapping);
281
258
  }
259
+ exports.jsonSchemaStringToJsonSchema = jsonSchemaStringToJsonSchema;
282
260
  /**
283
261
  * 获得 JSON 数据的 JSONSchema 对象。
284
262
  *
285
263
  * @param json JSON 数据
286
264
  * @returns JSONSchema 对象
287
265
  */
288
-
289
-
290
266
  function jsonToJsonSchema(json, customTypeMapping) {
291
- var schema = (0, _toJsonSchema.default)(json, {
292
- required: false,
293
- arrays: {
294
- mode: 'first'
295
- },
296
- objects: {
297
- additionalProperties: false
298
- },
299
- strings: {
300
- detectFormat: false
301
- },
302
- postProcessFnc: function postProcessFnc(type, schema, value) {
303
- if (!schema.description && !!value && type !== 'object') {
304
- schema.description = JSON.stringify(value);
305
- }
306
-
307
- return schema;
308
- }
309
- });
310
- delete schema.description;
311
- return processJsonSchema(schema, customTypeMapping);
267
+ var schema = (0, to_json_schema_1.default)(json, {
268
+ required: false,
269
+ arrays: {
270
+ mode: 'first',
271
+ },
272
+ objects: {
273
+ additionalProperties: false,
274
+ },
275
+ strings: {
276
+ detectFormat: false,
277
+ },
278
+ postProcessFnc: function (type, schema, value) {
279
+ if (!schema.description && !!value && type !== 'object') {
280
+ schema.description = JSON.stringify(value);
281
+ }
282
+ return schema;
283
+ },
284
+ });
285
+ delete schema.description;
286
+ return processJsonSchema(schema, customTypeMapping);
312
287
  }
288
+ exports.jsonToJsonSchema = jsonToJsonSchema;
313
289
  /**
314
290
  * 获得 mockjs 模板的 JSONSchema 对象。
315
291
  *
316
292
  * @param template mockjs 模板
317
293
  * @returns JSONSchema 对象
318
294
  */
319
-
320
-
321
295
  function mockjsTemplateToJsonSchema(template, customTypeMapping) {
322
- var actions = []; // https://github.com/nuysoft/Mock/blob/refactoring/src/mock/constant.js#L27
323
-
324
- var keyRe = /(.+)\|(?:\+(\d+)|([+-]?\d+-?[+-]?\d*)?(?:\.(\d+-?\d*))?)/; // https://github.com/nuysoft/Mock/wiki/Mock.Random
325
-
326
- var numberPatterns = ['natural', 'integer', 'float', 'range', 'increment'];
327
- var boolPatterns = ['boolean', 'bool'];
328
-
329
- var normalizeValue = function normalizeValue(value) {
330
- if (typeof value === 'string' && value.startsWith('@')) {
331
- var pattern = value.slice(1);
332
-
333
- if (numberPatterns.some(function (p) {
334
- return pattern.startsWith(p);
335
- })) {
336
- return 1;
337
- }
338
-
339
- if (boolPatterns.some(function (p) {
340
- return pattern.startsWith(p);
341
- })) {
342
- return true;
343
- }
344
- }
345
-
346
- return value;
347
- };
348
-
349
- (0, _vtils.traverse)(template, function (value, key, parent) {
350
- if (typeof key === 'string') {
351
- actions.push(function () {
352
- delete parent[key];
353
- parent[// https://github.com/nuysoft/Mock/blob/refactoring/src/mock/schema/schema.js#L16
354
- key.replace(keyRe, '$1')] = normalizeValue(value);
355
- });
356
- }
357
- });
358
- actions.forEach(function (action) {
359
- return action();
360
- });
361
- return jsonToJsonSchema(template, customTypeMapping);
296
+ var actions = [];
297
+ // https://github.com/nuysoft/Mock/blob/refactoring/src/mock/constant.js#L27
298
+ var keyRe = /(.+)\|(?:\+(\d+)|([+-]?\d+-?[+-]?\d*)?(?:\.(\d+-?\d*))?)/;
299
+ // https://github.com/nuysoft/Mock/wiki/Mock.Random
300
+ var numberPatterns = [
301
+ 'natural',
302
+ 'integer',
303
+ 'float',
304
+ 'range',
305
+ 'increment',
306
+ ];
307
+ var boolPatterns = ['boolean', 'bool'];
308
+ var normalizeValue = function (value) {
309
+ if (typeof value === 'string' && value.startsWith('@')) {
310
+ var pattern_1 = value.slice(1);
311
+ if (numberPatterns.some(function (p) { return pattern_1.startsWith(p); })) {
312
+ return 1;
313
+ }
314
+ if (boolPatterns.some(function (p) { return pattern_1.startsWith(p); })) {
315
+ return true;
316
+ }
317
+ }
318
+ return value;
319
+ };
320
+ (0, vtils_1.traverse)(template, function (value, key, parent) {
321
+ if (typeof key === 'string') {
322
+ actions.push(function () {
323
+ delete parent[key];
324
+ parent[
325
+ // https://github.com/nuysoft/Mock/blob/refactoring/src/mock/schema/schema.js#L16
326
+ key.replace(keyRe, '$1')] = normalizeValue(value);
327
+ });
328
+ }
329
+ });
330
+ actions.forEach(function (action) { return action(); });
331
+ return jsonToJsonSchema(template, customTypeMapping);
362
332
  }
333
+ exports.mockjsTemplateToJsonSchema = mockjsTemplateToJsonSchema;
363
334
  /**
364
335
  * 获得属性定义列表的 JSONSchema 对象。
365
336
  *
366
337
  * @param propDefinitions 属性定义列表
367
338
  * @returns JSONSchema 对象
368
339
  */
369
-
370
-
371
340
  function propDefinitionsToJsonSchema(propDefinitions, customTypeMapping) {
372
- return processJsonSchema({
373
- type: 'object',
374
- required: propDefinitions.reduce(function (res, prop) {
375
- if (prop.required) {
376
- res.push(prop.name);
377
- }
378
-
379
- return res;
380
- }, []),
381
- properties: propDefinitions.reduce(function (res, prop) {
382
- res[prop.name] = (0, _extends2.default)({
383
- type: prop.type,
384
- description: prop.comment
385
- }, prop.type === 'file' ? {
386
- tsType: _helpers.FileData.name
387
- } : {});
388
- return res;
389
- }, {})
390
- }, customTypeMapping);
341
+ return processJsonSchema({
342
+ type: 'object',
343
+ required: propDefinitions.reduce(function (res, prop) {
344
+ if (prop.required) {
345
+ res.push(prop.name);
346
+ }
347
+ return res;
348
+ }, []),
349
+ properties: propDefinitions.reduce(function (res, prop) {
350
+ res[prop.name] = __assign({ type: prop.type, description: prop.comment }, (prop.type === 'file' ? { tsType: helpers_1.FileData.name } : {}));
351
+ return res;
352
+ }, {}),
353
+ }, customTypeMapping);
391
354
  }
392
-
355
+ exports.propDefinitionsToJsonSchema = propDefinitionsToJsonSchema;
393
356
  var JSTTOptions = {
394
- bannerComment: '',
395
- style: {
396
- bracketSpacing: false,
397
- printWidth: 120,
398
- semi: true,
399
- singleQuote: true,
400
- tabWidth: 2,
401
- trailingComma: 'none',
402
- useTabs: false
403
- }
357
+ bannerComment: '',
358
+ style: {
359
+ bracketSpacing: false,
360
+ printWidth: 120,
361
+ semi: true,
362
+ singleQuote: true,
363
+ tabWidth: 2,
364
+ trailingComma: 'none',
365
+ useTabs: false,
366
+ },
404
367
  };
405
368
  /**
406
369
  * 根据 JSONSchema 对象生产 TypeScript 类型定义。
@@ -409,358 +372,240 @@ var JSTTOptions = {
409
372
  * @param typeName 类型名称
410
373
  * @returns TypeScript 类型定义
411
374
  */
412
-
413
- function jsonSchemaToType(_x, _x2) {
414
- return _jsonSchemaToType.apply(this, arguments);
415
- }
416
-
417
- function _jsonSchemaToType() {
418
- _jsonSchemaToType = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(jsonSchema, typeName) {
419
- var fakeTypeName, code;
420
- return _regenerator.default.wrap(function _callee$(_context) {
421
- while (1) {
422
- switch (_context.prev = _context.next) {
423
- case 0:
424
- if (!(0, _vtils.isEmpty)(jsonSchema)) {
425
- _context.next = 2;
426
- break;
427
- }
428
-
429
- return _context.abrupt("return", "export interface " + typeName + " {}");
430
-
431
- case 2:
432
- if (!jsonSchema.__is_any__) {
433
- _context.next = 5;
434
- break;
375
+ function jsonSchemaToType(jsonSchema, typeName) {
376
+ return __awaiter(this, void 0, void 0, function () {
377
+ var fakeTypeName, code;
378
+ return __generator(this, function (_a) {
379
+ switch (_a.label) {
380
+ case 0:
381
+ if ((0, vtils_1.isEmpty)(jsonSchema)) {
382
+ return [2 /*return*/, "export interface ".concat(typeName, " {}")];
383
+ }
384
+ if (jsonSchema.__is_any__) {
385
+ delete jsonSchema.__is_any__;
386
+ return [2 /*return*/, "export type ".concat(typeName, " = any")];
387
+ }
388
+ fakeTypeName = 'THISISAFAKETYPENAME';
389
+ return [4 /*yield*/, (0, json_schema_to_typescript_1.compile)(jsonSchemaToJSTTJsonSchema((0, vtils_1.cloneDeepFast)(jsonSchema), typeName), fakeTypeName, JSTTOptions)];
390
+ case 1:
391
+ code = _a.sent();
392
+ return [2 /*return*/, code.replace(fakeTypeName, typeName).trim()];
435
393
  }
436
-
437
- delete jsonSchema.__is_any__;
438
- return _context.abrupt("return", "export type " + typeName + " = any");
439
-
440
- case 5:
441
- // JSTT 会转换 typeName,因此传入一个全大写的假 typeName,生成代码后再替换回真正的 typeName
442
- fakeTypeName = 'THISISAFAKETYPENAME';
443
- _context.next = 8;
444
- return (0, _jsonSchemaToTypescript.compile)(jsonSchemaToJSTTJsonSchema((0, _vtils.cloneDeepFast)(jsonSchema), typeName), fakeTypeName, JSTTOptions);
445
-
446
- case 8:
447
- code = _context.sent;
448
- return _context.abrupt("return", code.replace(fakeTypeName, typeName).trim());
449
-
450
- case 10:
451
- case "end":
452
- return _context.stop();
453
- }
454
- }
455
- }, _callee);
456
- }));
457
- return _jsonSchemaToType.apply(this, arguments);
394
+ });
395
+ });
458
396
  }
459
-
397
+ exports.jsonSchemaToType = jsonSchemaToType;
460
398
  function getRequestDataJsonSchema(interfaceInfo, customTypeMapping) {
461
- var jsonSchema; // 处理表单数据(仅 POST 类接口)
462
-
463
- if (isPostLikeMethod(interfaceInfo.method)) {
464
- switch (interfaceInfo.req_body_type) {
465
- case _types.RequestBodyType.form:
466
- jsonSchema = propDefinitionsToJsonSchema(interfaceInfo.req_body_form.map(function (item) {
467
- return {
468
- name: item.name,
469
- required: item.required === _types.Required.true,
470
- type: item.type === _types.RequestFormItemType.file ? 'file' : 'string',
471
- comment: item.desc
472
- };
473
- }), customTypeMapping);
474
- break;
475
-
476
- case _types.RequestBodyType.json:
477
- if (interfaceInfo.req_body_other) {
478
- jsonSchema = interfaceInfo.req_body_is_json_schema ? jsonSchemaStringToJsonSchema(interfaceInfo.req_body_other, customTypeMapping) : jsonToJsonSchema(_json.default.parse(interfaceInfo.req_body_other), customTypeMapping);
399
+ var jsonSchema;
400
+ // 处理表单数据(仅 POST 类接口)
401
+ if (isPostLikeMethod(interfaceInfo.method)) {
402
+ switch (interfaceInfo.req_body_type) {
403
+ case types_1.RequestBodyType.form:
404
+ jsonSchema = propDefinitionsToJsonSchema(interfaceInfo.req_body_form.map(function (item) { return ({
405
+ name: item.name,
406
+ required: item.required === types_1.Required.true,
407
+ type: (item.type === types_1.RequestFormItemType.file
408
+ ? 'file'
409
+ : 'string'),
410
+ comment: item.desc,
411
+ }); }), customTypeMapping);
412
+ break;
413
+ case types_1.RequestBodyType.json:
414
+ if (interfaceInfo.req_body_other) {
415
+ jsonSchema = interfaceInfo.req_body_is_json_schema
416
+ ? jsonSchemaStringToJsonSchema(interfaceInfo.req_body_other, customTypeMapping)
417
+ : jsonToJsonSchema(json5_1.default.parse(interfaceInfo.req_body_other), customTypeMapping);
418
+ }
419
+ break;
420
+ default:
421
+ /* istanbul ignore next */
422
+ break;
479
423
  }
480
-
481
- break;
482
-
483
- default:
484
- /* istanbul ignore next */
485
- break;
486
424
  }
487
- } // 处理查询数据
488
-
489
-
490
- if ((0, _vtils.isArray)(interfaceInfo.req_query) && interfaceInfo.req_query.length) {
491
- var queryJsonSchema = propDefinitionsToJsonSchema(interfaceInfo.req_query.map(function (item) {
492
- return {
493
- name: item.name,
494
- required: item.required === _types.Required.true,
495
- type: item.type || 'string',
496
- comment: item.desc
497
- };
498
- }), customTypeMapping);
499
- /* istanbul ignore else */
500
-
501
- if (jsonSchema) {
502
- jsonSchema.properties = (0, _extends2.default)({}, jsonSchema.properties, queryJsonSchema.properties);
503
- jsonSchema.required = [].concat(Array.isArray(jsonSchema.required) ? jsonSchema.required : [], Array.isArray(queryJsonSchema.required) ? queryJsonSchema.required : []);
504
- } else {
505
- jsonSchema = queryJsonSchema;
425
+ // 处理查询数据
426
+ if ((0, vtils_1.isArray)(interfaceInfo.req_query) && interfaceInfo.req_query.length) {
427
+ var queryJsonSchema = propDefinitionsToJsonSchema(interfaceInfo.req_query.map(function (item) { return ({
428
+ name: item.name,
429
+ required: item.required === types_1.Required.true,
430
+ type: item.type || 'string',
431
+ comment: item.desc,
432
+ }); }), customTypeMapping);
433
+ /* istanbul ignore else */
434
+ if (jsonSchema) {
435
+ jsonSchema.properties = __assign(__assign({}, jsonSchema.properties), queryJsonSchema.properties);
436
+ jsonSchema.required = __spreadArray(__spreadArray([], (Array.isArray(jsonSchema.required) ? jsonSchema.required : []), true), (Array.isArray(queryJsonSchema.required)
437
+ ? queryJsonSchema.required
438
+ : []), true);
439
+ }
440
+ else {
441
+ jsonSchema = queryJsonSchema;
442
+ }
506
443
  }
507
- } // 处理路径参数
508
-
509
-
510
- if ((0, _vtils.isArray)(interfaceInfo.req_params) && interfaceInfo.req_params.length) {
511
- var paramsJsonSchema = propDefinitionsToJsonSchema(interfaceInfo.req_params.map(function (item) {
512
- return {
513
- name: item.name,
514
- required: true,
515
- type: item.type || 'string',
516
- comment: item.desc
517
- };
518
- }), customTypeMapping);
519
- /* istanbul ignore else */
520
-
521
- if (jsonSchema) {
522
- jsonSchema.properties = (0, _extends2.default)({}, jsonSchema.properties, paramsJsonSchema.properties);
523
- jsonSchema.required = [].concat(Array.isArray(jsonSchema.required) ? jsonSchema.required : [], Array.isArray(paramsJsonSchema.required) ? paramsJsonSchema.required : []);
524
- } else {
525
- jsonSchema = paramsJsonSchema;
444
+ // 处理路径参数
445
+ if ((0, vtils_1.isArray)(interfaceInfo.req_params) && interfaceInfo.req_params.length) {
446
+ var paramsJsonSchema = propDefinitionsToJsonSchema(interfaceInfo.req_params.map(function (item) { return ({
447
+ name: item.name,
448
+ required: true,
449
+ type: item.type || 'string',
450
+ comment: item.desc,
451
+ }); }), customTypeMapping);
452
+ /* istanbul ignore else */
453
+ if (jsonSchema) {
454
+ jsonSchema.properties = __assign(__assign({}, jsonSchema.properties), paramsJsonSchema.properties);
455
+ jsonSchema.required = __spreadArray(__spreadArray([], (Array.isArray(jsonSchema.required) ? jsonSchema.required : []), true), (Array.isArray(paramsJsonSchema.required)
456
+ ? paramsJsonSchema.required
457
+ : []), true);
458
+ }
459
+ else {
460
+ jsonSchema = paramsJsonSchema;
461
+ }
526
462
  }
527
- }
528
-
529
- return jsonSchema || {};
463
+ return jsonSchema || {};
530
464
  }
531
-
465
+ exports.getRequestDataJsonSchema = getRequestDataJsonSchema;
532
466
  function getResponseDataJsonSchema(interfaceInfo, customTypeMapping, dataKey) {
533
- var jsonSchema = {};
534
-
535
- switch (interfaceInfo.res_body_type) {
536
- case _types.ResponseBodyType.json:
537
- if (interfaceInfo.res_body) {
538
- jsonSchema = interfaceInfo.res_body_is_json_schema ? jsonSchemaStringToJsonSchema(interfaceInfo.res_body, customTypeMapping) : mockjsTemplateToJsonSchema(_json.default.parse(interfaceInfo.res_body), customTypeMapping);
539
- }
540
-
541
- break;
542
-
543
- default:
544
- jsonSchema = {
545
- __is_any__: true
546
- };
547
- break;
548
- }
549
-
550
- if (dataKey && jsonSchema) {
551
- jsonSchema = reachJsonSchema(jsonSchema, dataKey);
552
- }
553
-
554
- return jsonSchema;
467
+ var jsonSchema = {};
468
+ switch (interfaceInfo.res_body_type) {
469
+ case types_1.ResponseBodyType.json:
470
+ if (interfaceInfo.res_body) {
471
+ jsonSchema = interfaceInfo.res_body_is_json_schema
472
+ ? jsonSchemaStringToJsonSchema(interfaceInfo.res_body, customTypeMapping)
473
+ : mockjsTemplateToJsonSchema(json5_1.default.parse(interfaceInfo.res_body), customTypeMapping);
474
+ }
475
+ break;
476
+ default:
477
+ jsonSchema = { __is_any__: true };
478
+ break;
479
+ }
480
+ if (dataKey && jsonSchema) {
481
+ jsonSchema = reachJsonSchema(jsonSchema, dataKey);
482
+ }
483
+ return jsonSchema;
555
484
  }
556
-
485
+ exports.getResponseDataJsonSchema = getResponseDataJsonSchema;
557
486
  function reachJsonSchema(jsonSchema, path) {
558
- var last = jsonSchema;
559
-
560
- for (var _iterator2 = (0, _createForOfIteratorHelperLoose2.default)((0, _vtils.castArray)(path)), _step2; !(_step2 = _iterator2()).done;) {
561
- var _last$properties;
562
-
563
- var segment = _step2.value;
564
-
565
- var _last = (_last$properties = last.properties) == null ? void 0 : _last$properties[segment];
566
-
567
- if (!_last) {
568
- return jsonSchema;
487
+ var _a;
488
+ var last = jsonSchema;
489
+ for (var _i = 0, _b = (0, vtils_1.castArray)(path); _i < _b.length; _i++) {
490
+ var segment = _b[_i];
491
+ var _last = (_a = last.properties) === null || _a === void 0 ? void 0 : _a[segment];
492
+ if (!_last) {
493
+ return jsonSchema;
494
+ }
495
+ last = _last;
569
496
  }
570
-
571
- last = _last;
572
- }
573
-
574
- return last;
497
+ return last;
575
498
  }
576
-
499
+ exports.reachJsonSchema = reachJsonSchema;
577
500
  function sortByWeights(list) {
578
- list.sort(function (a, b) {
579
- var _x$weights;
580
-
581
- var x = a.weights.length > b.weights.length ? b : a;
582
- var minLen = Math.min(a.weights.length, b.weights.length);
583
- var maxLen = Math.max(a.weights.length, b.weights.length);
584
-
585
- (_x$weights = x.weights).push.apply(_x$weights, new Array(maxLen - minLen).fill(0));
586
-
587
- var w = a.weights.reduce(function (w, _, i) {
588
- if (w === 0) {
589
- w = a.weights[i] - b.weights[i];
590
- }
591
-
592
- return w;
593
- }, 0);
594
- return w;
595
- });
596
- return list;
501
+ list.sort(function (a, b) {
502
+ var _a;
503
+ var x = a.weights.length > b.weights.length ? b : a;
504
+ var minLen = Math.min(a.weights.length, b.weights.length);
505
+ var maxLen = Math.max(a.weights.length, b.weights.length);
506
+ (_a = x.weights).push.apply(_a, new Array(maxLen - minLen).fill(0));
507
+ var w = a.weights.reduce(function (w, _, i) {
508
+ if (w === 0) {
509
+ w = a.weights[i] - b.weights[i];
510
+ }
511
+ return w;
512
+ }, 0);
513
+ return w;
514
+ });
515
+ return list;
597
516
  }
598
-
517
+ exports.sortByWeights = sortByWeights;
599
518
  function isGetLikeMethod(method) {
600
- return method === _types.Method.GET || method === _types.Method.OPTIONS || method === _types.Method.HEAD;
519
+ return (method === types_1.Method.GET || method === types_1.Method.OPTIONS || method === types_1.Method.HEAD);
601
520
  }
602
-
521
+ exports.isGetLikeMethod = isGetLikeMethod;
603
522
  function isPostLikeMethod(method) {
604
- return !isGetLikeMethod(method);
605
- }
606
-
607
- function getPrettier(_x3) {
608
- return _getPrettier.apply(this, arguments);
523
+ return !isGetLikeMethod(method);
609
524
  }
610
-
611
- function _getPrettier() {
612
- _getPrettier = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(cwd) {
613
- var projectPrettierPath;
614
- return _regenerator.default.wrap(function _callee2$(_context2) {
615
- while (1) {
616
- switch (_context2.prev = _context2.next) {
617
- case 0:
618
- projectPrettierPath = _path.default.join(cwd, 'node_modules/prettier');
619
- _context2.next = 3;
620
- return _fsExtra.default.pathExists(projectPrettierPath);
621
-
622
- case 3:
623
- if (!_context2.sent) {
624
- _context2.next = 5;
625
- break;
525
+ exports.isPostLikeMethod = isPostLikeMethod;
526
+ function getPrettier(cwd) {
527
+ return __awaiter(this, void 0, void 0, function () {
528
+ var projectPrettierPath;
529
+ return __generator(this, function (_a) {
530
+ switch (_a.label) {
531
+ case 0:
532
+ projectPrettierPath = path_1.default.join(cwd, 'node_modules/prettier');
533
+ return [4 /*yield*/, fs_extra_1.default.pathExists(projectPrettierPath)];
534
+ case 1:
535
+ if (_a.sent()) {
536
+ return [2 /*return*/, require(projectPrettierPath)];
537
+ }
538
+ return [2 /*return*/, require('prettier')];
626
539
  }
627
-
628
- return _context2.abrupt("return", require(projectPrettierPath));
629
-
630
- case 5:
631
- return _context2.abrupt("return", require('prettier'));
632
-
633
- case 6:
634
- case "end":
635
- return _context2.stop();
636
- }
637
- }
638
- }, _callee2);
639
- }));
640
- return _getPrettier.apply(this, arguments);
540
+ });
541
+ });
641
542
  }
642
-
543
+ exports.getPrettier = getPrettier;
643
544
  function getPrettierOptions() {
644
- return _getPrettierOptions.apply(this, arguments);
645
- }
646
-
647
- function _getPrettierOptions() {
648
- _getPrettierOptions = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee3() {
649
- var prettierOptions, _yield$run, prettierConfigPathErr, prettierConfigPath, _yield$run2, prettierConfigErr, prettierConfig;
650
-
651
- return _regenerator.default.wrap(function _callee3$(_context3) {
652
- while (1) {
653
- switch (_context3.prev = _context3.next) {
654
- case 0:
655
- prettierOptions = {
656
- parser: 'typescript',
657
- printWidth: 120,
658
- tabWidth: 2,
659
- singleQuote: true,
660
- semi: false,
661
- trailingComma: 'all',
662
- bracketSpacing: false,
663
- endOfLine: 'lf'
664
- }; // 测试时跳过本地配置的解析
665
-
666
- if (!process.env.JEST_WORKER_ID) {
667
- _context3.next = 3;
668
- break;
545
+ return __awaiter(this, void 0, void 0, function () {
546
+ var prettierOptions, _a, prettierConfigPathErr, prettierConfigPath, _b, prettierConfigErr, prettierConfig;
547
+ return __generator(this, function (_c) {
548
+ switch (_c.label) {
549
+ case 0:
550
+ prettierOptions = {
551
+ parser: 'typescript',
552
+ printWidth: 120,
553
+ tabWidth: 2,
554
+ singleQuote: true,
555
+ semi: false,
556
+ trailingComma: 'all',
557
+ bracketSpacing: false,
558
+ endOfLine: 'lf',
559
+ };
560
+ // 测试时跳过本地配置的解析
561
+ if (process.env.JEST_WORKER_ID) {
562
+ return [2 /*return*/, prettierOptions];
563
+ }
564
+ return [4 /*yield*/, (0, vtils_1.run)(function () {
565
+ return prettier_1.default.resolveConfigFile();
566
+ })];
567
+ case 1:
568
+ _a = _c.sent(), prettierConfigPathErr = _a[0], prettierConfigPath = _a[1];
569
+ if (prettierConfigPathErr || !prettierConfigPath) {
570
+ return [2 /*return*/, prettierOptions];
571
+ }
572
+ return [4 /*yield*/, (0, vtils_1.run)(function () {
573
+ return prettier_1.default.resolveConfig(prettierConfigPath);
574
+ })];
575
+ case 2:
576
+ _b = _c.sent(), prettierConfigErr = _b[0], prettierConfig = _b[1];
577
+ if (prettierConfigErr || !prettierConfig) {
578
+ return [2 /*return*/, prettierOptions];
579
+ }
580
+ return [2 /*return*/, __assign(__assign(__assign({}, prettierOptions), prettierConfig), { parser: 'typescript' })];
669
581
  }
670
-
671
- return _context3.abrupt("return", prettierOptions);
672
-
673
- case 3:
674
- _context3.next = 5;
675
- return (0, _vtils.run)(function () {
676
- return _prettier.default.resolveConfigFile();
677
- });
678
-
679
- case 5:
680
- _yield$run = _context3.sent;
681
- prettierConfigPathErr = _yield$run[0];
682
- prettierConfigPath = _yield$run[1];
683
-
684
- if (!(prettierConfigPathErr || !prettierConfigPath)) {
685
- _context3.next = 10;
686
- break;
687
- }
688
-
689
- return _context3.abrupt("return", prettierOptions);
690
-
691
- case 10:
692
- _context3.next = 12;
693
- return (0, _vtils.run)(function () {
694
- return _prettier.default.resolveConfig(prettierConfigPath);
695
- });
696
-
697
- case 12:
698
- _yield$run2 = _context3.sent;
699
- prettierConfigErr = _yield$run2[0];
700
- prettierConfig = _yield$run2[1];
701
-
702
- if (!(prettierConfigErr || !prettierConfig)) {
703
- _context3.next = 17;
704
- break;
705
- }
706
-
707
- return _context3.abrupt("return", prettierOptions);
708
-
709
- case 17:
710
- return _context3.abrupt("return", (0, _extends2.default)({}, prettierOptions, prettierConfig, {
711
- parser: 'typescript'
712
- }));
713
-
714
- case 18:
715
- case "end":
716
- return _context3.stop();
717
- }
718
- }
719
- }, _callee3);
720
- }));
721
- return _getPrettierOptions.apply(this, arguments);
722
- }
723
-
724
- var getCachedPrettierOptions = (0, _vtils.memoize)(getPrettierOptions);
725
- exports.getCachedPrettierOptions = getCachedPrettierOptions;
726
-
727
- function httpGet(_x4, _x5) {
728
- return _httpGet.apply(this, arguments);
582
+ });
583
+ });
729
584
  }
730
-
731
- function _httpGet() {
732
- _httpGet = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee4(url, query) {
733
- var _url, res;
734
-
735
- return _regenerator.default.wrap(function _callee4$(_context4) {
736
- while (1) {
737
- switch (_context4.prev = _context4.next) {
738
- case 0:
739
- _url = new _url2.URL(url);
740
-
741
- if (query) {
742
- Object.keys(query).forEach(function (key) {
743
- _url.searchParams.set(key, query[key]);
744
- });
585
+ exports.getPrettierOptions = getPrettierOptions;
586
+ exports.getCachedPrettierOptions = (0, vtils_1.memoize)(getPrettierOptions);
587
+ function httpGet(url, query) {
588
+ return __awaiter(this, void 0, void 0, function () {
589
+ var _url, res;
590
+ return __generator(this, function (_a) {
591
+ switch (_a.label) {
592
+ case 0:
593
+ _url = new url_1.URL(url);
594
+ if (query) {
595
+ Object.keys(query).forEach(function (key) {
596
+ _url.searchParams.set(key, query[key]);
597
+ });
598
+ }
599
+ url = _url.toString();
600
+ return [4 /*yield*/, (0, node_fetch_1.default)(url, {
601
+ method: 'GET',
602
+ agent: new proxy_agent_1.default(),
603
+ })];
604
+ case 1:
605
+ res = _a.sent();
606
+ return [2 /*return*/, res.json()];
745
607
  }
746
-
747
- url = _url.toString();
748
- _context4.next = 5;
749
- return (0, _nodeFetch.default)(url, {
750
- method: 'GET',
751
- agent: new _proxyAgent.default()
752
- });
753
-
754
- case 5:
755
- res = _context4.sent;
756
- return _context4.abrupt("return", res.json());
757
-
758
- case 7:
759
- case "end":
760
- return _context4.stop();
761
- }
762
- }
763
- }, _callee4);
764
- }));
765
- return _httpGet.apply(this, arguments);
766
- }
608
+ });
609
+ });
610
+ }
611
+ exports.httpGet = httpGet;