auto-request
Version:
通过Yapi JSON Schema生成接口Axios或Taro接口
1,188 lines (1,161 loc) • 1.59 MB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var fs = require('fs');
var prettier = require('prettier');
var readline = require('readline');
var jsonSchemaToTypescript = require('json-schema-to-typescript');
var path$1 = require('path');
var require$$0$1 = require('tty');
var require$$1 = require('util');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
var prettier__namespace = /*#__PURE__*/_interopNamespace(prettier);
var readline__namespace = /*#__PURE__*/_interopNamespace(readline);
var path__namespace = /*#__PURE__*/_interopNamespace(path$1);
var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
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;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var MethodsType;
(function (MethodsType) {
MethodsType["Get"] = "get";
MethodsType["Post"] = "post";
MethodsType["Delete"] = "delete";
MethodsType["Put"] = "put";
})(MethodsType || (MethodsType = {}));
var _a;
var ErrorType;
(function (ErrorType) {
ErrorType["PathParams"] = "path-total-error";
ErrorType["SchemaError"] = "schema-error";
ErrorType["PathError"] = "path-error";
ErrorType["Debug"] = "debug";
})(ErrorType || (ErrorType = {}));
var ErrorTypeDesc = (_a = {},
_a[ErrorType.PathParams] = '路径参数数量匹配不上文档',
_a[ErrorType.SchemaError] = '接口参数解析出问题',
_a[ErrorType.PathError] = '路径参数类型没写为path',
_a[ErrorType.Debug] = 'debug数据',
_a);
var Store = /** @class */ (function () {
function Store() {
this.errorUrl = [];
this.isTypeScript = true;
this.errorPath = '';
this.filename = '';
this.logFilename = '';
}
Store.prototype.pushError = function (data) {
this.errorUrl.push(data);
};
Store.prototype.print = function () {
var errTypeHash = this.errorUrl.reduce(function (pre, next) {
if (!pre[next.errorType]) {
pre[next.errorType] = [];
}
pre[next.errorType].push(__assign(__assign({}, next), { errorType: ErrorTypeDesc[next.errorType] }));
return pre;
}, {});
return JSON.stringify(errTypeHash);
};
Store.prototype.getFileType = function () {
if (this.isTypeScript) {
return '.ts';
}
return '.js';
};
return Store;
}());
var store = new Store();
// import { MethodsType, GetSchema } from './../define';
// 生成ts的schema
var handleRenderApiTsFileFeature = function (apis) {
var init = {
title: 'Api',
type: 'object',
properties: {},
definitions: {},
additionalProperties: false,
preDefine: ''
};
return apis.reduce(function (pre, next) {
try {
[next.generatorDefineParams()].forEach(function (item) {
var propertiesKey = item.propertiesKey, definitionsKey = item.definitionsKey, key = item.key;
if (!key) {
return;
}
pre['properties'][key] = propertiesKey;
pre['definitions'][key] = definitionsKey;
});
// get是没有data的 post的情况下 存在实例全局对象里面在下面的函数一起处理
next.generatorDefineData();
next.generatorDefineResponse().forEach(function (item) {
var propertiesKey = item.propertiesKey, definitionsKey = item.definitionsKey, key = item.key;
if (!key) {
return;
}
pre['properties'][key] = propertiesKey;
pre['definitions'][key] = definitionsKey;
});
}
catch (err) {
next.debugPrint(next.description, '【handleRenderApiTsFileFeature】' + err.toString());
}
return pre;
}, init);
};
// 返回接口定义名字的import列表
var wapperPreFixDefineName = function (helpers) {
return helpers.reduce(function (pre, next) {
var params = next.getMethodPreDefineParams();
if (params) {
pre.push(params);
}
var data = next.renderGetMethodDefineData();
if (data) {
pre.push(data);
}
var response = next.getMethodsDefineResponse();
if (response) {
pre.push(response);
}
return pre;
}, []);
};
// 返回接口泛型参数
var wapperMethodPreInteface = function (helpers) {
var p = [];
var params = helpers.getMethodPreDefineParams();
if (params) {
p.push("P extends ".concat(params));
}
var data = helpers.renderGetMethodDefineData();
if (data) {
p.push("D extends ".concat(data));
}
var response = helpers.getMethodsDefineResponse();
if (response) {
p.push("S = AxiosResponse < ".concat(response, " > "));
}
return p;
};
var wapperPreImportDefine = function (defines) {
return "\n import { \n".concat(defines, "\n\n } from './").concat(store.filename, ".define';\n ");
};
var initArray = function (arrs) {
if (Array.isArray(arrs)) {
return arrs;
}
return [];
};
var camelcase = require('camelcase');
var pascalCase = function (str) {
return camelcase(str, { pascalCase: true });
};
var clone$2 = require('clone');
var pascalCaseReplaceString = function (str, pascalCase) {
if (pascalCase === void 0) { pascalCase = true; }
return camelcase(str.replace(/[\/|\{|\}|\?\$]/g, ''), { pascalCase: pascalCase });
};
var renderMethodArgs = function (args) {
return initArray(args)
.filter(function (item) { return item; })
.join(',');
};
var formatUrl = function (parameters, url) {
if (parameters === void 0) { parameters = []; }
var pathParams = initArray(parameters).filter(function (paramsItem) { return paramsItem["in"] === 'path'; });
return pathParams.reduce(function (pre, _a) {
var name = _a.name;
return pre.replace("{".concat(name.trim(), "}"), "${".concat(name.trim(), "}"));
}, url);
};
var createMethodsName = function (url, method, parameters) {
if (parameters === void 0) { parameters = []; }
return pascalCaseReplaceString("".concat(formatUrl(parameters, url)).concat(pascalCase(method)));
};
var createMethodsNameCamelCase = function (url, method, parameters) {
if (parameters === void 0) { parameters = []; }
return "".concat(method.toLocaleLowerCase()).concat(pascalCaseReplaceString("".concat(formatUrl(parameters, url))));
};
var formatParamtersItemType = function (type) {
if (type === 'integer') {
return 'number';
}
return 'string';
};
// 获取parameters中path的参数
var renderRenderParametersPaths = function (parmeters, isTypeScript) {
if (isTypeScript === void 0) { isTypeScript = true; }
return initArray(parmeters)
.reduce(function (pre, next) {
if (next["in"] === 'path') {
if (isTypeScript) {
pre.push("".concat(next.name, ": ").concat(formatParamtersItemType(next.type)));
return pre;
}
pre.push("".concat(next.name));
return pre;
}
return pre;
}, [])
.join(',');
};
var getParameterPath = function (parmeters, isTypeScript) {
return initArray(parmeters).reduce(function (pre, next) {
if (next["in"] === 'path') {
pre.push(next);
return pre;
}
return pre;
}, []);
};
var getParameterData = function (parmeters, isTypeScript) {
return initArray(parmeters).reduce(function (pre, next) {
if (next["in"] === 'body') {
pre.push(next);
return pre;
}
return pre;
}, []);
};
var getParameterParams = function (parmeters, isTypeScript) {
return initArray(parmeters).reduce(function (pre, next) {
if (next["in"] === 'query') {
pre.push(next);
return pre;
}
return pre;
}, []);
};
// 渲染模板头部
var getTemplatePrefix = function () {
return "\n import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'\n \n\n ";
};
var wapperDefineName = function (methName, mode) {
if (mode === 'params') {
return "".concat(methName, "RequsetParams");
}
if (mode === 'data') {
return "".concat(methName, "RequsetData");
}
return "".concat(methName, "Response");
};
var Helper = /** @class */ (function () {
function Helper(uri, method, params) {
this.getApiInteraces = [];
this.renderOptionsStr = {
params: '',
data: ''
};
this.uri = uri;
this.method = method;
this.sourceSchema = params;
this.description = params.description;
this.summary = params.summary;
}
Helper.prototype.getUrl = function () {
return formatUrl(this.sourceSchema.parameters, this.uri);
};
Helper.prototype.getMethodsName = function () {
return createMethodsName(this.uri, this.method);
};
Helper.prototype.getMethodsNameCamelCase = function () {
return createMethodsNameCamelCase(this.uri, this.method);
};
Helper.prototype.getMethodPrePath = function () {
var getPaths = renderRenderParametersPaths(this.sourceSchema.parameters, store.isTypeScript);
this.__vaildateGetMethodPrePath(getParameterPath(this.sourceSchema.parameters, store.isTypeScript));
return getPaths ? "".concat(getPaths) : '';
};
Helper.prototype.getMethodPreParams = function () {
var getParams = getParameterParams(this.sourceSchema.parameters, store.isTypeScript);
if (getParams.length === 0) {
return '';
}
this.renderOptionsStr.params = 'params';
if (store.isTypeScript) {
return "params: P";
}
return 'params';
};
Helper.prototype.getMethodOption = function () {
if (store.isTypeScript) {
return "options:AxiosRequestConfig = {}";
}
return "options = {}";
};
// 获取params的ts定义名字
Helper.prototype.getMethodPreDefineParams = function () {
if (!this.getMethodPreParams()) {
return;
}
return wapperDefineName(this.getMethodsName(), 'params');
};
// 校验path参数是否有有问题
Helper.prototype.__vaildateGetMethodPrePath = function (getParams) {
var getUrlParams = initArray(this.uri.match(/\{\w+\}/g));
var getUrlParamsTotal = getUrlParams.length;
var parameters = getParams.length;
if (getUrlParamsTotal === 0 && parameters === 0) {
return;
}
// 检查定义的path参数和url上的参数数量是否一致
if (getUrlParamsTotal !== parameters) {
store.pushError({
url: this.uri,
desc: this.description,
method: this.method,
errorType: ErrorType.PathParams
});
}
// 检测路径参数类型是否匹配
var errMsg = [];
getUrlParams.forEach(function (key) {
var target = getParams.find(function (item) { return String(key).indexOf(item.name) > -1; });
if (target && target["in"] !== 'path') {
errMsg.push("".concat(key, "\u7684in\u7C7B\u578B\u4E3A").concat(target["in"], ", \u5E94\u8BE5\u6539\u4E3Apath"));
}
});
if (errMsg.length > 0) {
store.pushError({
url: this.uri,
desc: this.description,
method: this.method,
errMsg: errMsg.join(','),
errorType: ErrorType.PathError
});
}
};
Helper.prototype.debugPrint = function (desc, errMsg) {
if (errMsg === void 0) { errMsg = ''; }
if (this.description === desc) {
store.pushError({
errorType: ErrorType.Debug,
url: this.uri,
method: this.method,
desc: this.description,
errMsg: errMsg
});
}
};
// 查找方法中所有params参数
Helper.prototype.getMethodParams = function () { };
// 查找方法中所有data参数
Helper.prototype.getMethodData = function () {
return getParameterData(this.sourceSchema.parameters, store.isTypeScript);
};
Helper.prototype.renderGetMethodData = function () {
if (this.getMethodData().length === 0) {
return '';
}
this.renderOptionsStr.data = 'data';
if (store.isTypeScript) {
return "data: D";
}
return "data";
};
// 获取data的ts定义名字
Helper.prototype.renderGetMethodDefineData = function () {
if (this.method === MethodsType.Get) {
return;
}
if (!this.renderGetMethodData()) {
return;
}
return wapperDefineName(this.getMethodsName(), 'data');
};
// 获取接口返回的ts定义名字
Helper.prototype.getMethodsDefineResponse = function () {
return wapperDefineName(this.getMethodsName(), 'response');
};
// 获取返回对象的ts定义名字
Helper.prototype.renderTsDefineResFeature = function () {
if (!this.sourceSchema.responses['200']) {
return [];
}
return [];
};
Helper.prototype.renderTsDefineReqFeature = function () {
var _a = this.sourceSchema.parameters, parameters = _a === void 0 ? [] : _a;
var reqParams = initArray(parameters).filter(function (params) { return params["in"] === 'body'; });
if (reqParams.length === 0) {
return [];
}
return [];
};
// 处理query data的函数
Helper.prototype.generatorDefineParams = function () {
var querys = initArray(this.sourceSchema.parameters).filter(function (parameterItem) { return parameterItem["in"] === 'query'; });
var properties = querys.reduce(function (pre, next) {
var name = next.name, type = next.type, description = next.description;
pre[name] = {
type: type,
description: description
};
return pre;
}, {});
var required = initArray(querys)
.filter(function (item) { return item.required; })
.map(function (item) { return item.name; });
var key = this.getMethodPreDefineParams();
if (!key) {
return {
key: key,
propertiesKey: {},
definitionsKey: {}
};
}
return {
key: key,
propertiesKey: {
$ref: "#/definitions/".concat(key)
},
definitionsKey: {
title: key,
type: 'object',
additionalProperties: false,
properties: properties,
description: this.description,
required: required
}
};
};
// 处理response的函数
Helper.prototype.formatProperties = function (title, itemSchema) {
try {
var deepItemSchema_1 = clone$2(itemSchema);
// if (!deepItemSchema.properties && deepItemSchema['$ref']) {
// const innerTitle = `${title}${pascalCase('items')}`;
// return {
// [title]:`#/definitions/${title}`
// }
// }
var properties = Object.keys(deepItemSchema_1.properties).reduce(function (pre, next) {
var data = deepItemSchema_1.properties[next];
var innerTitle = "".concat(title).concat(pascalCase(next));
if (['object'].includes(data.type)) {
pre[next] = {};
pre[next]['$ref'] = "#/definitions/".concat(innerTitle);
return pre;
}
if (['array'].includes(data.type)) {
pre[next] = {};
pre[next]['items'] = {};
pre[next]['items']['$ref'] = "#/definitions/".concat(innerTitle);
return pre;
}
pre[next] = {};
pre[next] = clone$2(data);
return pre;
}, {});
return properties;
}
catch (err) {
return {};
}
};
Helper.prototype.setTypeObjToInstances = function (preName, key, itemSchema) {
var _this = this;
try {
if (!key) {
// 没有key就是root节点
// 先把这个接口的response根节点写入
if (itemSchema.type === 'object') {
var rootTitle_1 = "".concat(preName);
var rootProperties = this.formatProperties(rootTitle_1, itemSchema);
var apiInstance = {
key: rootTitle_1,
propertiesKey: {
$ref: "#/definitions/".concat(rootTitle_1)
},
definitionsKey: {
title: rootTitle_1,
type: itemSchema.type,
properties: rootProperties,
additionalProperties: false,
required: initArray(itemSchema.required)
}
};
this.getApiInteraces.push(apiInstance);
return;
}
if (itemSchema.type === 'array') {
var rootTitle_2 = "".concat(preName);
var rootProperties = this.formatProperties(rootTitle_2, itemSchema.items);
var apiInstance = {
key: rootTitle_2,
propertiesKey: {
items: {
$ref: "#/definitions/".concat(rootTitle_2)
}
},
definitionsKey: {
title: rootTitle_2,
type: itemSchema.type,
properties: rootProperties,
additionalProperties: false,
required: initArray(itemSchema.required)
}
};
this.getApiInteraces.push(apiInstance);
return;
}
}
// 剩下就是有key的
var rootTitle_3 = "".concat(preName).concat(pascalCase(key));
if (key === 'children') {
}
if (itemSchema.type === 'array') {
var apiInstance = {
key: rootTitle_3,
propertiesKey: {
items: {
$ref: "#/definitions/".concat(rootTitle_3)
}
},
definitionsKey: {
title: rootTitle_3,
type: itemSchema.items.type,
properties: this.formatProperties(rootTitle_3, itemSchema.items),
additionalProperties: false,
required: initArray(itemSchema.required)
}
};
this.getApiInteraces.push(apiInstance);
return;
}
if (itemSchema.type === 'object') {
var apiInstance = {
key: rootTitle_3,
propertiesKey: {
$ref: "#/definitions/".concat(rootTitle_3)
},
definitionsKey: {
title: rootTitle_3,
type: itemSchema.type,
properties: this.formatProperties(rootTitle_3, itemSchema),
additionalProperties: false,
required: initArray(itemSchema.required)
}
};
this.getApiInteraces.push(apiInstance);
return;
}
(function () {
var apiInstance = {
key: rootTitle_3,
propertiesKey: {
$ref: "#/definitions/".concat(rootTitle_3)
},
definitionsKey: {
title: rootTitle_3,
type: itemSchema.type,
additionalProperties: false,
required: initArray(itemSchema.required)
}
};
_this.getApiInteraces.push(apiInstance);
})();
}
catch (err) {
var rootTitle = "".concat(preName).concat(pascalCase(key));
if (itemSchema.type === 'array') {
var apiInstance = {
key: rootTitle,
propertiesKey: {
items: {
$ref: "#/definitions/".concat(rootTitle)
}
},
definitionsKey: {
title: rootTitle,
additionalProperties: true
}
};
this.getApiInteraces.push(apiInstance);
}
store.pushError({
url: this.uri,
method: this.method,
errorType: ErrorType.SchemaError,
desc: this.description,
errMsg: 'setTypeObjToInstances ' + rootTitle + ' ' + err.toString()
});
}
};
Helper.prototype.setTypeNotProperties = function (preName, key, itemSchema) {
var rootTitle = "".concat(preName).concat(pascalCase(key));
var apiInstance = {
key: rootTitle,
propertiesKey: {},
definitionsKey: {
title: rootTitle,
type: itemSchema.type,
additionalProperties: true,
required: []
}
};
this.getApiInteraces.push(apiInstance);
};
Helper.prototype.setTypeNotProperToArrRef = function (preName, key, itemSchema) {
var rootTitle = "".concat(preName).concat(pascalCase(key));
var apiInstance = {
key: rootTitle,
propertiesKey: __assign({}, itemSchema.items),
definitionsKey: {
title: rootTitle,
type: itemSchema.type,
additionalProperties: true,
required: []
}
};
this.getApiInteraces.push(apiInstance);
};
Helper.prototype.generatorDeepDefine = function (preName, key, itemSchema) {
var _this = this;
if (itemSchema.type === 'object') {
// 有key说明不是跟response
var rootTitle_4 = "".concat(preName).concat(pascalCase(key));
if (key && !itemSchema.properties) {
this.setTypeNotProperties(preName, key, itemSchema);
return;
}
if (key && itemSchema.properties) {
this.setTypeObjToInstances(preName, key, itemSchema);
// TODO
}
// 深度递归找出里面需要另外设置ref的数据
Object.keys(itemSchema.properties).forEach(function (itemKey) {
var data = itemSchema.properties[itemKey];
if (['object'].includes(data.type)) {
_this.generatorDeepDefine(rootTitle_4, itemKey, clone$2(data));
}
else if (['array'].includes(data.type)) {
_this.generatorDeepDefine(rootTitle_4, itemKey, clone$2(data));
}
});
}
if (itemSchema.type === 'array') {
this.setTypeObjToInstances(preName, key, itemSchema);
if (!itemSchema.items) {
return;
}
if (!key && !itemSchema.items.properties) {
this.setTypeNotProperToArrRef(preName, key, itemSchema);
return;
// 根节点数组的情况
}
if (!itemSchema.items.properties) {
this.setTypeNotProperties(preName, key, itemSchema);
return;
}
var rootTitle_5 = "".concat(preName).concat(pascalCase(key));
if (itemSchema.items.type === 'object') {
Object.keys(clone$2(itemSchema.items.properties)).forEach(function (itemKey) {
var data = itemSchema.items.properties[itemKey];
if (['object', 'array'].includes(data.type)) {
_this.generatorDeepDefine(rootTitle_5, itemKey, clone$2(data));
}
});
}
else if (itemSchema.items.type === 'array') {
var data = itemSchema.items;
this.generatorDeepDefine(rootTitle_5, 'item', clone$2(data));
}
else ;
}
};
Helper.prototype.generatorDefineData = function () {
return {
key: '',
propertiesKey: {},
definitionsKey: {}
};
};
Helper.prototype.generatorDefineResponse = function () {
var key = this.getMethodsDefineResponse();
var response = this.sourceSchema.responses['200'];
if (!response) {
// 没有200就直接返回空
return this.getApiInteraces;
}
var resSchema = response.schema;
if (!resSchema) {
var emptyInfof = {
key: key,
propertiesKey: {
$ref: "#/definitions/".concat(key)
},
definitionsKey: {
title: key,
type: 'object',
additionalProperties: true,
description: this.description
}
};
this.getApiInteraces.push(emptyInfof);
return this.getApiInteraces;
}
// 先把根节点的response设置好
this.setTypeObjToInstances(key, '', resSchema);
// 编辑response对象
if (resSchema.type === 'array') {
this.generatorDeepDefine(key, '', resSchema.items);
}
else {
this.generatorDeepDefine(key, '', resSchema);
}
return this.getApiInteraces;
};
return Helper;
}());
require('clone');
var GetHelper = /** @class */ (function (_super) {
__extends(GetHelper, _super);
// 待处理的数据
function GetHelper(uri, method, params) {
return _super.call(this, uri, method, params) || this;
}
// get是没有data的
GetHelper.prototype.generatorDefineData = function () {
return {
key: '',
propertiesKey: {},
definitionsKey: {}
};
};
return GetHelper;
}(Helper));
var useGetMethdos = function (uri, method, params, response) {
var instance = new Helper(uri, method, params);
var innerRenderCallback = function () {
var args = renderMethodArgs([
instance.getMethodPrePath(),
instance.getMethodPreParams(),
instance.getMethodOption(),
]);
var requestArgs = renderMethodArgs([
"url: `".concat(instance.getUrl(), "`"),
"method: '".concat(instance.method, "'"),
"".concat(instance.renderOptionsStr.data),
"".concat(instance.renderOptionsStr.params),
"...options",
]);
var preInterface = renderMethodArgs(wapperMethodPreInteface(instance));
var summary = instance.description === instance.summary ? '' : "\n@summary ".concat(instance.summary);
if (store.isTypeScript) {
return "\n /***\n * @description ".concat(instance.description, "\n * ").concat(summary, "\n **/\n export const ").concat(instance.getMethodsName(), " = <").concat(preInterface, ">(").concat(args, "):Promise<S> => {\n return axios.request({").concat(requestArgs, "})\n }\n\n ");
}
return "\n /***\n * @description ".concat(instance.description, "\n * ").concat(summary, "\n **/\n export const ").concat(instance.getMethodsName(), " = (").concat(args, ") => {\n return axios.request({").concat(requestArgs, "})\n }\n\n ");
};
// 渲染模板方法,可以通过传入使用自定义的方法
var renderTemplate = function (renderCallback) {
if (typeof renderCallback === 'function') {
return renderCallback.call(instance);
}
return innerRenderCallback();
};
return {
instance: instance,
renderTemplate: renderTemplate
};
};
var PostHelper = /** @class */ (function (_super) {
__extends(PostHelper, _super);
// 待处理的数据
function PostHelper(uri, method, params) {
return _super.call(this, uri, method, params) || this;
}
// get是没有data的
PostHelper.prototype.generatorDefineData = function () {
var _a;
var key = this.renderGetMethodDefineData();
if (!key) {
return {
key: '',
propertiesKey: {},
definitionsKey: {}
};
}
var bodySchema = this.sourceSchema.parameters.find(function (item) { return item["in"] === 'body'; });
if (!bodySchema) {
return {
key: '',
propertiesKey: {},
definitionsKey: {}
};
}
// 先把根节点的response设置好
if (((_a = bodySchema.schema) === null || _a === void 0 ? void 0 : _a.type) !== 'array') {
this.setTypeObjToInstances(key, '', bodySchema.schema);
}
// 编辑response对象
this.generatorDeepDefine(key, '', bodySchema.schema);
// post的情况会在处理response的时候顺带处理
return {
key: '',
propertiesKey: {},
definitionsKey: {}
};
};
return PostHelper;
}(Helper));
var usePostMethdos = function (uri, method, params) {
var instance = new Helper(uri, method, params);
var innerRenderCallback = function () {
var args = renderMethodArgs([
instance.getMethodPrePath(),
instance.getMethodPreParams(),
instance.renderGetMethodData(),
instance.getMethodOption(),
]);
var requestArgs = renderMethodArgs([
"url: `".concat(instance.getUrl(), "`"),
"method: '".concat(instance.method, "'"),
"".concat(instance.renderOptionsStr.data),
"".concat(instance.renderOptionsStr.params),
"...options",
]);
var preInterface = renderMethodArgs(wapperMethodPreInteface(instance));
if (store.isTypeScript) {
return "\n /***\n * @description ".concat(instance.description, "\n **/\n export const ").concat(instance.getMethodsName(), " = <").concat(preInterface, ">( ").concat(args, " ):Promise<S> => {\n return axios.request({").concat(requestArgs, "})\n }\n\n ");
}
return "\n /***\n * @description ".concat(instance.description, "\n **/\n export const ").concat(instance.getMethodsName(), " = ( ").concat(args, " ) => {\n return axios.request({").concat(requestArgs, "})\n }\n\n ");
};
// 渲染模板方法,可以通过传入使用自定义的方法
var renderTemplate = function (renderCallback) {
if (typeof renderCallback === 'function') {
return renderCallback.call(instance);
}
return innerRenderCallback();
};
return {
instance: instance,
renderTemplate: renderTemplate
};
};
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var lib$7 = {};
var hasRequiredLib$7;
function requireLib$7 () {
if (hasRequiredLib$7) return lib$7;
hasRequiredLib$7 = 1;
Object.defineProperty(lib$7, '__esModule', {
value: true
});
function _objectWithoutPropertiesLoose(r, e) {
if (null == r) return {};
var t = {};
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
if (-1 !== e.indexOf(n)) continue;
t[n] = r[n];
}
return t;
}
class Position {
constructor(line, col, index) {
this.line = void 0;
this.column = void 0;
this.index = void 0;
this.line = line;
this.column = col;
this.index = index;
}
}
class SourceLocation {
constructor(start, end) {
this.start = void 0;
this.end = void 0;
this.filename = void 0;
this.identifierName = void 0;
this.start = start;
this.end = end;
}
}
function createPositionWithColumnOffset(position, columnOffset) {
const {
line,
column,
index
} = position;
return new Position(line, column + columnOffset, index + columnOffset);
}
const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED";
var ModuleErrors = {
ImportMetaOutsideModule: {
message: `import.meta may appear only with 'sourceType: "module"'`,
code
},
ImportOutsideModule: {
message: `'import' and 'export' may appear only with 'sourceType: "module"'`,
code
}
};
const NodeDescriptions = {
ArrayPattern: "array destructuring pattern",
AssignmentExpression: "assignment expression",
AssignmentPattern: "assignment expression",
ArrowFunctionExpression: "arrow function expression",
ConditionalExpression: "conditional expression",
CatchClause: "catch clause",
ForOfStatement: "for-of statement",
ForInStatement: "for-in statement",
ForStatement: "for-loop",
FormalParameters: "function parameter list",
Identifier: "identifier",
ImportSpecifier: "import specifier",
ImportDefaultSpecifier: "import default specifier",
ImportNamespaceSpecifier: "import namespace specifier",
ObjectPattern: "object destructuring pattern",
ParenthesizedExpression: "parenthesized expression",
RestElement: "rest element",
UpdateExpression: {
true: "prefix operation",
false: "postfix operation"
},
VariableDeclarator: "variable declaration",
YieldExpression: "yield expression"
};
const toNodeDescription = node => node.type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[`${node.prefix}`] : NodeDescriptions[node.type];
var StandardErrors = {
AccessorIsGenerator: ({
kind
}) => `A ${kind}ter cannot be a generator.`,
ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.",
AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
AwaitNotInAsyncFunction: "'await' is only allowed within async functions.",
BadGetterArity: "A 'get' accessor must not have any formal parameters.",
BadSetterArity: "A 'set' accessor must have exactly one formal parameter.",
BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.",
ConstructorClassField: "Classes may not have a field named 'constructor'.",
ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
ConstructorIsAccessor: "Class constructor may not be an accessor.",
ConstructorIsAsync: "Constructor can't be an async function.",
ConstructorIsGenerator: "Constructor can't be a generator.",
DeclarationMissingInitializer: ({
kind
}) => `Missing initializer in ${kind} declaration.`,
DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",
DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",
DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",
DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",
DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
DecoratorStaticBlock: "Decorators can't be used with a static block.",
DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.',
DeletePrivateField: "Deleting a private field is not allowed.",
DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
DuplicateConstructor: "Duplicate constructor in the same class.",
DuplicateDefaultExport: "Only one default export allowed per module.",
DuplicateExport: ({
exportName
}) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`,
DuplicateProto: "Redefinition of __proto__ property.",
DuplicateRegExpFlags: "Duplicate regular expression flag.",
DynamicImportPhaseRequiresImportExpressions: ({
phase
}) => `'import.${phase}(...)' can only be parsed when using the 'createImportExpressions' option.`,
ElementAfterRest: "Rest element must be last element.",
EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
ExportBindingIsString: ({
localName,
exportName
}) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`,
ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
ForInOfLoopInitializer: ({
type
}) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`,
ForInUsing: "For-in loop may not start with 'using' declaration.",
ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
IllegalBreakContinue: ({
type
}) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`,
IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
IllegalReturn: "'return' outside of function.",
ImportAttributesUseAssert: "The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.",
ImportBindingIsString: ({
importName
}) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`,
ImportCallArity: `\`import()\` requires exactly one or two arguments.`,
ImportCallNotNewExpression: "Cannot use new with import(...).",
ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.",
ImportReflectionHasAssertion: "`import module x` cannot have assertions.",
ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.',
IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.",
InvalidBigIntLiteral: "Invalid BigIntLiteral.",
InvalidCodePoint: "Code point out of bounds.",
InvalidCoverInitializedName: "Invalid shorthand property initializer.",
InvalidDecimal: "Invalid decimal.",
InvalidDigit: ({
radix
}) => `Expected number in radix ${radix}.`,
InvalidEscapeSequence: "Bad character escape sequence.",
InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
InvalidEscapedReservedWord: ({
reservedWord
}) => `Escape sequence in keyword ${reservedWord}.`,
InvalidIdentifier: ({
identifierName
}) => `Invalid identifier ${identifierName}.`,
InvalidLhs: ({
ancestor
}) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,
InvalidLhsBinding: ({
ancestor
}) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,
InvalidLhsOptionalChaining: ({
ancestor
}) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`,
InvalidNumber: "Invalid number.",
InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
InvalidOrUnexpectedToken: ({
unexpected
}) => `Unexpected character '${unexpected}'.`,
InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
InvalidPrivateFieldResolution: ({
identifierName
}) => `Private name #${identifierName} is not defined.`,
InvalidPropertyBindingPattern: "Binding member expression.",
InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
LabelRedeclaration: ({
labelName
}) => `Label '${labelName}' is already declared.`,
LetInLexicalBinding: "'let' is disallowed as a lexically bound name.",
LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
MalformedRegExpFlags: "Invalid regular expression flag.",
MissingClassName: "A class name is required.",
MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
MissingSemicolon: "Missing semicolon.",
MissingPlugin: ({
missingPlugin
}) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
MissingOneOfPlugins: ({
missingPlugin
}) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
ModuleAttributesWithDuplicateKeys: ({
key
}) => `Duplicate key "${key}" is not allowed in module attributes.`,
ModuleExportNameHasLoneSurrogate: ({
surrogateCharCode
}) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`,
ModuleExportUndefined: ({
localName
}) => `Export '${localName}' is not defined.`,
MultipleDefaultsInSwitch: "Multiple default clauses.",
NewlineAfterThrow: "Illegal newline after throw.",
NoCatchOrFinally: "Missing catch or finally clause.",
NumberIdentifier: "Identifier directly after number.",
NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
ParamDupe: "Argument name clash.",
PatternHasAccessor: "Object pattern can't contain getter or setter.",
PatternHasMethod: "Object pattern can't contain methods.",
PrivateInExpectedIn: ({