UNPKG

@backland/schema

Version:

TypeScript schema declaration and validation library with static type inference

224 lines (223 loc) 9.16 kB
var _excluded = ["def", "defaultValue"]; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } import { inspectObject, simpleObjectClone } from '@backland/utils'; import { CircularDeps } from '../CircularDeps'; import { parseValidationError } from '../applyValidator'; import { arrayFieldParse } from './ArrayFieldParse'; import { createFieldTypeError, isFieldError } from './FieldTypeErrors'; import { $inferableKey } from './Infer'; export * from '../applyValidator'; export var FieldsTypeCache = new Map(); export class FieldType { get definition() { return this.asFinalFieldDef; } constructor(config) { _defineProperty(this, "typeName", void 0); _defineProperty(this, "type", void 0); _defineProperty(this, "def", void 0); _defineProperty(this, $inferableKey, void 0); _defineProperty(this, "composer", void 0); _defineProperty(this, "id", void 0); _defineProperty(this, "name", void 0); _defineProperty(this, "options", void 0); _defineProperty(this, "optional", void 0); _defineProperty(this, "list", void 0); _defineProperty(this, "defaultValue", void 0); _defineProperty(this, "description", void 0); _defineProperty(this, "hidden", void 0); _defineProperty(this, "describe", description => { this.description = description; return this; }); _defineProperty(this, "describeField", () => { return this.asFinalFieldDef; }); _defineProperty(this, "applyParser", _parser => { return (input, _options) => { var options = {}; if (typeof _options === 'function') { options = { customErrorMessage: _options }; } if (typeof _options === 'string') { options = { customErrorMessage: _options }; } if (typeof _options === 'object') { options = _options; } var { customErrorMessage: customMessage, includeHidden = true } = options; // keep it secret if (this.hidden && !includeHidden) return undefined; if (_parser.preParse) { input = _parser.preParse(input); } if ((input === undefined || input === null) && this.defaultValue !== undefined) { input = this.defaultValue; } if (this.type === 'null' && input === undefined) { return null; } if (this.type !== 'null' && input === null && this.optional) { return undefined; } if (input === undefined && this.optional) { return undefined; } if (input === undefined && !this.optional) { throw createFieldTypeError('requiredField'); } if (this.asFinalFieldDef.list) { return arrayFieldParse({ arrayOptions: {}, // since is the shot definition (list:true) there is no options input, parser: input => _parser.parse(input, options), parserOptions: options }); } try { return _parser.parse(input, options); } catch (originalError) { if (!customMessage && isFieldError(originalError)) { throw originalError; } throw parseValidationError(input, customMessage, originalError); } }; }); _defineProperty(this, "parse", void 0); _defineProperty(this, "__isFieldType", true); _defineProperty(this, "clone", () => { var _this$asFinalFieldDef = this.asFinalFieldDef, { def, defaultValue } = _this$asFinalFieldDef, rest = _objectWithoutProperties(_this$asFinalFieldDef, _excluded); var field; if (rest.type === 'literal') { field = _objectSpread(_objectSpread({}, simpleObjectClone(rest)), {}, { def, defaultValue }); } else { field = simpleObjectClone(rest); if (def !== undefined) { field.def = simpleObjectClone(def); } if (defaultValue !== undefined) { field.defaultValue = simpleObjectClone(def); } } return CircularDeps.fieldInstanceFromDef(field); }); var { name, id, def: _def, options: _options2 = {} } = config; this.id = id; this.typeName = name; this.type = name; this.options = _options2; var defKeys = _def ? Object.keys(_def).sort() : undefined; if (defKeys !== null && defKeys !== void 0 && defKeys.length) { this.def = _def; } if (id) { var existing = FieldsTypeCache.get(id); if (existing) { var _existing$defKeys; var existingKeys = (_existing$defKeys = existing.defKeys) === null || _existing$defKeys === void 0 ? void 0 : _existing$defKeys.join(', '); if (existing.fieldType.typeName !== this.typeName) { throw new Error("Field with id \"".concat(id, "\" already registered with different type:\n \"").concat(inspectObject({ old: existing.fieldType.asFinalFieldDef, current: this.asFinalFieldDef }, { depth: 2 }), "\"")); } if ((defKeys === null || defKeys === void 0 ? void 0 : defKeys.join(', ')) !== existingKeys) { throw new Error("Field with id \"".concat(id, "\" already registered with different fields:\n \"").concat(existingKeys, "\"")); } } FieldsTypeCache.set(id, { fieldType: this, defKeys }); } } validate(input) { try { this.parse(input); return true; } catch (e) { return false; } } is(input) { return this.validate(input); } toOptional() { // @ts-ignore this.optional = true; return this; } toRequired() { // @ts-ignore this.optional = false; return this; } toList(options) { // @ts-ignore this.list = true; if (options && typeof options === 'object') { this.options = _objectSpread(_objectSpread({}, this.options), options); } return this; } setDefaultValue(value) { // @ts-ignore this.defaultValue = value; return this; } get asFinalFieldDef() { var res = { def: this.def, defaultValue: this.defaultValue, description: this.description, hidden: this.hidden, list: this.list, optional: this.optional, type: this.type }; Object.entries(res).forEach(_ref => { var [k, v] = _ref; if (v === undefined || v === false) { delete res[k]; } }); return res; } static create() { throw new Error('not implemented in abstract class.'); } } export function isFieldInstance(t) { return (t === null || t === void 0 ? void 0 : t.__isFieldType) === true; } //# sourceMappingURL=FieldType.js.map