UNPKG

macoolka-type-model

Version:

`macoolka-type-model` is a library for define model in TypeScript. It easily build a type contain field and method to your Application. It provide a generation model for type and validition

415 lines 18 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(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); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildTs = exports.topologicalSort = void 0; var pipeable_1 = require("fp-ts/pipeable"); var A = __importStar(require("fp-ts/Array")); var O = __importStar(require("fp-ts/Option")); var E = __importStar(require("fp-ts/Either")); var utils_1 = require("./utils"); var constant_1 = require("../constant"); var macoolka_predicate_1 = require("macoolka-predicate"); var Ord = __importStar(require("fp-ts/Ord")); var Module_1 = require("../Module"); var topologicalSort_1 = __importDefault(require("macoolka-algorithms/lib/topologicalSort")); var graph_1 = require("../graph"); /** * topological sort IOType in MModule * @desczh * IOType 拓扑排序 * @since 0.2.0 */ var topologicalSort = function (ignoreNames) { return function (a) { var orders = []; orders = orders.concat(a.interfaces); orders = orders.concat(a.typealiases); var ordMoudle = function (names) { return ({ equals: function (a, b) { return a.name === b.name; }, compare: function (a, b) { var aIndex = (0, pipeable_1.pipe)(names, A.findIndex(function (name) { return name === a.name; }), O.getOrElse(function () { return -1; })); var bIndex = (0, pipeable_1.pipe)(names, A.findIndex(function (name) { return name === b.name; }), O.getOrElse(function () { return -1; })); return Ord.ordNumber.compare(bIndex, aIndex); } }); }; var valid = function (names) { return (0, pipeable_1.pipe)(orders, A.map(function (b) { return (0, pipeable_1.pipe)(names, A.findIndex(function (name) { return name === b.name; }), E.fromOption(function () { return (0, Module_1.typeNotFound)({ model: a.name, name: b.name }); })); }), A.lefts, function (a) { return a.length > 0 ? E.left(a.join('\n')) : E.right(names); }); }; return (0, pipeable_1.pipe)(a, (0, graph_1.buildGraph)(ignoreNames), E.map(topologicalSort_1.default), E.chain(function (a) { return (0, pipeable_1.pipe)(a.map(function (value) { return value.value; }), valid, E.map(function (names) { return (0, pipeable_1.pipe)(names, ordMoudle, A.sort, function (b) { return b(orders); }); })); })); }; }; exports.topologicalSort = topologicalSort; var _a = (0, utils_1.formatCode)({}), formatBlock = _a.formatBlock, formatItem = _a.formatItem, fold = _a.fold; /** * String scalar map to io name */ var stringRulesToTypeName = { maxLength: function (a) { return (0, pipeable_1.pipe)(O.fromNullable(a), O.map(function (a) { return "t.stringMaxLength(".concat(a, ")"); })); }, minLength: function (a) { return (0, pipeable_1.pipe)(O.fromNullable(a), O.map(function (a) { return "t.stringMinLength(".concat(a, ")"); })); }, match: function (a) { return (0, pipeable_1.pipe)(O.fromNullable(a), O.map(function (a) { return "t.stringMatch(".concat(new RegExp(a), ")"); })); } }; /** * number scalar map to io name */ var numberRules = { maximum: function (a) { return (0, pipeable_1.pipe)(O.fromNullable(a), O.map(function (a) { return "t.numberMaxValue(".concat(a, ")"); })); }, minimum: function (a) { return (0, pipeable_1.pipe)(O.fromNullable(a), O.map(function (a) { return "t.numberMinValue(".concat(a, ")"); })); } }; /** * Scalar to io name */ var rule = { number: function (numberScale) { return (0, pipeable_1.pipe)([ numberRules.maximum(numberScale.maximum), numberRules.minimum(numberScale.minimum) ], A.compact, concat('intersection', 't.string')); }, int: function (intScale) { return (0, pipeable_1.pipe)([ numberRules.maximum(intScale.maximum), numberRules.minimum(intScale.minimum) ], A.compact, concat('intersection', 't.int')); }, string: function (stringScale) { return (0, pipeable_1.pipe)([ stringRulesToTypeName.maxLength(stringScale.maxLength), stringRulesToTypeName.minLength(stringScale.minLength), stringRulesToTypeName.match(stringScale.pattern) ], A.compact, concat('intersection', 't.string')); } }; /** * Connect type with union or intersection * @param mode * @param empty */ var concat = function (mode, empty) { return function (as) { if (as.length === 0) { return empty; } else if (as.length === 1) { return as[0]; } else { return "t.".concat(mode, "([").concat(as.join(','), "])"); } }; }; /** * Convert string[] to enum format * @param values */ var getEnumValues = function (values) { var keys = values.reduce(function (b, a) { var _a; return (__assign(__assign({}, b), (_a = {}, _a[a] = '', _a))); }, {}); return values.length === 0 ? "t.never" : values.length === 1 ? "t.literal('".concat(values[0], "')") : "t.keyof(".concat(JSON.stringify(keys), ")"); // : `t.union([${values.map(value => `t.literal('${value}')`).join(' , ')}])` }; function intersection(indent, name) { return function (content) { return content.length > 1 ? formatBlock({ begin: "t.intersection([", end: (0, macoolka_predicate_1.notMaybe)(name) ? "],'".concat(name, "')") : '])', indent: indent, split: ',', content: content }) : content.length === 1 ? content[0] : 'never'; }; } function union(indent, name) { return function (content) { return formatBlock({ begin: "t.union([", end: (0, macoolka_predicate_1.notMaybe)(name) ? "],'".concat(name, "')") : '])', indent: indent, content: content, split: ',' }); }; } /** * Get io type name with field * @param a */ var getTypeName = function (a) { if ((0, macoolka_predicate_1.isString)(a)) { switch (a) { case 'int': return 't.int'; case 'datetime': return 't.dateFromISOString'; case 'json': return 't.record(t.string,t.any)'; default: return "t.".concat(a); } } var typename; switch (a._kind) { case 'kind': { typename = "t.literal('".concat(a.value, "')"); break; } case 'json': typename = 't.record(t.string,t.any)'; break; case 'type': typename = a.value; break; case 'datetime': typename = 't.dateFromISOString'; break; case 'int': typename = 't.int'; break; case 'typeUnion': var types = a.values.map(function (value) { return "".concat(value); }); typename = union(0)(types); // `t.union([${types}])` break; case 'typeIntersection': // const types = a.values.map(value => `${value}`) typename = intersection(0)(a.values.map(function (value) { return "".concat(value); })); // `t.union([${types}])` break; case 'enum': typename = getEnumValues(a.values); break; case 'string': typename = rule.string(a); break; case 'int': typename = rule.int(a); break; case 'number': typename = rule.number(a); break; default: typename = "t.".concat(a._kind); } var _isArray = a.isArray, isArrayRequired = a.isArrayRequired, defaultEmptyArray = a.defaultEmptyArray; var isArray = _isArray || isArrayRequired; var _type = isArray ? "t.array(".concat(typename, ")") : typename; var body = (0, pipeable_1.pipe)((!(0, macoolka_predicate_1.isString)(a)) && !(0, macoolka_predicate_1.isMaybe)(a.defaultValue) ? O.some(a.defaultValue) : O.none, O.map(function (value) { return (defaultEmptyArray === true && (isArray === true)) ? O.some([value]) : O.some(value); }), O.getOrElse(function () { return (defaultEmptyArray === true && (isArray === true)) ? O.some([]) : O.none; }), O.map(function (value) { return JSON.stringify(value); }), O.map(function (value) { return "t.withDefault(".concat(_type, ",").concat(value, ")"); }), O.getOrElse(function () { return _type; })); return body; }; /** * TSBuild instance with IO * @since 0.2.0 */ var buildTs = function (option) { if (option === void 0) { option = {}; } return function (schema) { var _a = option.header, header = _a === void 0 ? constant_1.headerTS : _a, _b = option.imports, imports = _b === void 0 ? constant_1.importsIO : _b, _c = option.showDesc, showDesc = _c === void 0 ? true : _c, _d = option.ignoreTypeNames, ignoreTypeNames = _d === void 0 ? [] : _d, _e = option.recursionNames, recursionNames = _e === void 0 ? [] : _e; function printTypeReference(i) { return function (_a) { var type = _a.type; return getTypeName(type); }; } /** * Get field Statement * @param i */ function printField(i) { return function (field) { var name = field.name; var content = "".concat(name, ":").concat(printTypeReference(i)(field), ","); return formatItem(i, showDesc)({ content: content, docs: field }); }; } /** * Get t.type or t.partial Statement * @param indent */ var printType = function (indent, typename) { return function (input) { var fields = input.fields, name = input.name; return formatBlock({ begin: formatItem(0, showDesc)({ content: "t.".concat(name, "({"), docs: input }), end: (0, macoolka_predicate_1.notMaybe)(typename) ? "},'".concat(typename, "')") : '})', indent: indent, content: fields.map(printField(indent + 1)) }); }; }; /** * Get t.intersection(t.type,t.partial) Statement * @param indent */ function printFields(indent) { return function (fields) { return (0, pipeable_1.pipe)(fields, A.partition(function (a) { return a.required === true || a.id === true; }), function (_a) { var left = _a.left, right = _a.right; if (left.length > 0 && right.length > 0) { var partial = printType(indent + 1)({ name: 'partial', fields: left, methods: [], implements: [], isExported: false, description: [], deprecated: false, help: [], since: "0.2.0", ignore: false, examples: [], reason: [], path: [], _kind: 'interface' }); var type = printType(indent + 1)({ name: 'type', fields: right, methods: [], implements: [], isExported: false, description: [], deprecated: false, help: [], since: "0.2.0", ignore: false, examples: [], reason: [], path: [], _kind: 'interface' }); return intersection(0)([type, partial]); } else if (left.length > 0) { var partial = printType(indent)({ name: 'partial', fields: left, methods: [], implements: [], isExported: false, description: [], deprecated: false, help: [], since: "0.2.0", ignore: false, examples: [], reason: [], path: [], _kind: 'interface' }); return "".concat(partial, " "); } else if (right.length > 0) { var type = printType(indent)({ _kind: 'interface', name: 'type', fields: right, methods: [], implements: [], help: [], since: "0.2.0", isExported: false, description: [], deprecated: false, ignore: false, examples: [], reason: [], path: [] }); return "".concat(type, " "); } else { var type = printType(indent)({ name: 'type', fields: right, methods: [], implements: [], isExported: false, description: [], deprecated: false, help: [], since: "0.2.0", ignore: false, examples: [], reason: [], path: [], _kind: 'interface' }); return "".concat(type, " "); } }); }; } function printTypeAlias(indent) { return function (typealias) { var _a = typealias.fields, fields = _a === void 0 ? [] : _a, name = typealias.name; var body = printTypeReference(indent)(typealias); var content = fields.length === 0 ? body : intersection(0, name)([body, printFields(indent)(fields)]); return formatItem(0, showDesc)({ content: printName(name, content), docs: typealias }); }; } var printName = function (name, content) { return recursionNames.includes(name) ? "export const ".concat(name, ":t.Type<").concat(name, "> = t.recursion('").concat(name, "',()=>").concat(content, ")") : "export const ".concat(name, " = ").concat(content); }; /** * Get t.intersection(t.type,t.partial) Statement * @param indent */ function printInterface(indent) { return function (input) { var _a = input.fields, fields = _a === void 0 ? [] : _a, name = input.name, _b = input.implements, impl = _b === void 0 ? [] : _b; var fieldsContent = printFields(indent)(fields); var content = printName(name, intersection(0, name)(__spreadArray(__spreadArray([], impl, true), [fieldsContent], false))); return formatItem(0, showDesc)({ content: content, docs: input }); }; } var printModule = function (indent) { return function (list) { var content = list.map(function (a) { return a._kind === 'interface' ? printInterface(indent)(a) : printTypeAlias(indent)(a); }); return formatBlock({ begin: '', end: '', indent: indent, content: content }); }; }; var indent = 0; var _list = (0, exports.topologicalSort)(ignoreTypeNames)(schema); return (0, pipeable_1.pipe)(_list, E.map(function (a) { return formatBlock({ begin: formatItem(indent, showDesc)({ content: fold(imports), docs: { description: header, deprecated: false, ignore: false, examples: [], reason: [], path: [], help: [], since: '0.2.0' } }), end: '', indent: indent, content: [printModule(indent)(a)] }); })); }; }; exports.buildTs = buildTs; exports.default = exports.buildTs; //# sourceMappingURL=IOBuild.js.map