Comparing version 2.0.0 to 2.1.0-beta.1
@@ -1,2 +0,2 @@ | ||
!function(e,r){"object"==typeof exports&&"object"==typeof module?module.exports=r():"function"==typeof define&&define.amd?define([],r):"object"==typeof exports?exports.Morphism=r():e.Morphism=r()}(this,function(){return function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)t.d(n,o,function(r){return e[r]}.bind(null,o));return n},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.p="",t(t.s=0)}([function(e,r,t){"use strict";function n(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,n)}return t}function o(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}t.r(r);var i=Symbol.for("SchemaOptions");function a(e){return h(e)&&e.hasOwnProperty("fn")&&e.hasOwnProperty("path")}function c(e){return l(e)}function u(e){return Array.isArray(e)&&e.every(c)}var s,p=(e,r)=>e.reduce((e,t)=>(b(e,t,g(r,t)),e),{});function f(e){return void 0===e}function h(e){var r=typeof e;return null!=e&&("object"===r||"function"===r)}function l(e){return"string"==typeof e||e instanceof String}function d(e){return"function"==typeof e}function y(e){if(Promise&&Promise.resolve)return Promise.resolve(e)==e;throw"Promise not supported in your environment"}function g(e,r){for(var t=(r=(r=r.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split("."),n=0,o=t.length;n<o;++n){var i=t[n];if(!(h(e)&&i in e))return;e=e[i]}return e}function m(e,r){return e.reduce((e,t,i)=>(function(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?n(t,!0).forEach(function(r){o(e,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):n(t).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))})}return e})({},e,{[t]:r[i]}),{})}function v(e,r){return"number"==typeof r&&Array.isArray(e)||function(e,r){return null!=e&&Object.prototype.hasOwnProperty.call(e,r)}(e,r)}function b(e,r,t,n){if("number"==typeof r&&(r=[r]),!r||0===r.length)return e;if("string"==typeof r)return b(e,r.split(".").map(P),t,n);var o=r[0],i=function(e,r){if(v(e,r))return e[r]}(e,o);return 1===r.length?(void 0!==i&&n||(e[o]=t),i):(void 0===i&&("number"==typeof r[1]?e[o]=[]:e[o]={}),b(e[o],r.slice(1),t,n))}function P(e){var r=parseInt(e);return r.toString()===e?r:e}function O(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,n)}return t}function j(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?O(t,!0).forEach(function(r){w(e,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):O(t).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))})}return e}function w(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function S(e,r){return r&&!function(e){for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r))return!1;return!0}(r)&&(e[i]=r),e}!function(e){e.Root="Root",e.Property="Property",e.ActionFunction="ActionFunction",e.ActionAggregator="ActionAggregator",e.ActionString="ActionString",e.ActionSelector="ActionSelector"}(s||(s={}));class A{constructor(e){this.schemaOptions=void 0,this.root=void 0,this.schema=void 0,this.schema=e,this.schemaOptions=A.getSchemaOptions(this.schema),this.root={data:{targetPropertyPath:"",propertyName:"MorphismTreeRoot",action:null,kind:s.Root},parent:null,children:[]},e&&this.parseSchema(e)}static getSchemaOptions(e){return j({},{class:{automapping:!0},undefinedValues:{strip:!1}},{},e?e[i]:void 0)}parseSchema(e,r,t){var n;(l(n=e)||d(n)||a(n)||u(n))&&r?(this.add({propertyName:r,action:e},t),t=t?"".concat(t,".").concat(r):r):(r&&(this.add({propertyName:r,action:null},t),t=t?"".concat(t,".").concat(r):r),Array.isArray(e)?e.forEach((e,r)=>{this.parseSchema(e,r.toString(),t)}):h(e)&&Object.keys(e).forEach(r=>{this.parseSchema(e[r],r,t)}))}*traverseBFS(){var e=[];for(e.push(this.root);e.length>0;){var r=e.shift();if(!r)return;for(var t=0,n=r.children.length;t<n;t++)e.push(r.children[t]);r.data.kind!==s.Root&&(yield r)}}add(e,r){var t=this.getActionKind(e.action);if(!t)throw new Error("The action specified for ".concat(e.propertyName," is not supported."));var n={data:j({},e,{kind:t,targetPropertyPath:""}),parent:null,children:[]};if(n.data.preparedAction=this.getPreparedAction(n.data),r)for(var o of this.traverseBFS())o.data.targetPropertyPath===r&&(n.parent=o,n.data.targetPropertyPath="".concat(o.data.targetPropertyPath,".").concat(n.data.propertyName),o.children.push(n));else n.parent=this.root,n.data.targetPropertyPath=n.data.propertyName,this.root.children.push(n)}getActionKind(e){return c(e)?s.ActionString:d(e)?s.ActionFunction:a(e)?s.ActionSelector:u(e)?s.ActionAggregator:null===e?s.Property:void 0}getPreparedAction(e){var{propertyName:r,action:t,kind:n}=e;if(c(t))return e=>{var{object:r}=e;return g(r,t)};if(d(t))return e=>{var{object:r,items:n,objectToCompute:o}=e;return t.call(void 0,r,n,o)};if(u(t))return e=>{var{object:r}=e;return p(t,r)};if(a(t))return e=>{var n,{object:o,items:i,objectToCompute:a}=e;try{var c;Array.isArray(t.path)?c=p(t.path,o):l(t.path)&&(c=g(o,t.path)),n=t.fn.call(void 0,c,o,i,a)}catch(e){throw e.message="Unable to set target property [".concat(r,"].\n \n An error occured when applying [").concat(t.fn.name,"] on property [").concat(t.path,"]\n \n Internal error: ").concat(e.message),e}return n};if(n===s.Property)return null;throw new Error("The action specified for ".concat(r," is not supported."))}}function M(e){return(r,t,n)=>{var o=n.value;return"function"==typeof o&&(n.value=function(){for(var r=arguments.length,t=new Array(r),n=0;n<r;n++)t[n]=arguments[n];var i=o.apply(this,t);return y(i)?Promise.resolve(i).then(r=>e(r)):e(i)}),n}}function _(e,r,t,n){var o=r.schemaOptions,i=[];for(var a of r.traverseBFS()){var{preparedAction:c,targetPropertyPath:u}=a.data;c&&i.push({targetPropertyPath:u,preparedAction:c({object:e,objectToCompute:n,items:t})})}return i.reduce((e,r)=>{var t=((e,r)=>f(r)?f(e)?void 0:e:r)(g(e,r.targetPropertyPath),r.preparedAction);return void 0===t?(o&&o.undefinedValues&&o.undefinedValues.strip?o.undefinedValues.default&&b(e,r.targetPropertyPath,o.undefinedValues.default(e,r.targetPropertyPath)):b(e,r.targetPropertyPath,t),e):(b(e,r.targetPropertyPath,t),e)},n)}function E(e,r){var t,n=A.getSchemaOptions(e);if(r&&n.class&&n.class.automapping){var o=function(e,r){var t=Object.keys(new e),n=m(t,t);return Object.assign(n,r)}(r,e);t=new A(o)}else t=new A(e);return function(e){if(!e)return e;if(Array.isArray(e))return e.map(n=>{if(r){var o=new r;return _(n,t,e,o)}return _(n,t,e,{})});var n=e;if(r){var o=new r;return _(n,t,[n],o)}return _(n,t,[n],{})}}function x(e,r,t){switch(arguments.length){case 1:return E(e);case 2:return E(e)(r);case 3:if(t)return null!==r?E(e,t)(r):E(e,t);throw new Error("When using morphism(schema, items, type), type should be defined but value received is ".concat(t))}}function T(e,r){return M(E(e,r))}function k(e){return M(E(e))}function D(e,r){return M(E(e,r))}t.d(r,"morph",function(){return T}),t.d(r,"toJSObject",function(){return k}),t.d(r,"toClassObject",function(){return D}),t.d(r,"morphism",function(){return x}),t.d(r,"createSchema",function(){return S}),t.d(r,"Schema",function(){}),t.d(r,"StrictSchema",function(){}),t.d(r,"SchemaOptions",function(){}),t.d(r,"Mapper",function(){}),t.d(r,"SCHEMA_OPTIONS_SYMBOL",function(){return i});var N=new class{constructor(e){this._registry=null,this._registry=e||{cache:new Map}}register(e,r){if(!e&&!r)throw new Error("type paramater is required when you register a mapping");if(this.exists(e))throw new Error("A mapper for ".concat(e.name," has already been registered"));var t;return t=x(r||{},null,e),this._registry.cache.set(e,t),t}map(e,r){if(!this.exists(e)){var t=this.register(e);if(void 0===r)return t}return this.getMapper(e)(r)}getMapper(e){return this._registry.cache.get(e)}setMapper(e,r){if(r){if(this.exists(e)){var t=x(r,null,e);return this._registry.cache.set(e,t),t}throw new Error("The type ".concat(e.name," is not registered. Register it using `Mophism.register(").concat(e.name,", schema)`"))}throw new Error("The schema must be an Object. Found ".concat(r))}deleteMapper(e){return this._registry.cache.delete(e)}exists(e){return this._registry.cache.has(e)}get mappers(){return this._registry.cache}},F=x;F.register=(e,r)=>N.register(e,r),F.map=(e,r)=>N.map(e,r),F.getMapper=e=>N.getMapper(e),F.setMapper=(e,r)=>N.setMapper(e,r),F.deleteMapper=e=>N.deleteMapper(e),F.mappers=N.mappers;var R=F;r.default=R}])}); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Morphism=t():e.Morphism=t()}(this,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var a=t[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)r.d(n,a,function(t){return e[t]}.bind(null,a));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=1)}([function(e,t){},function(e,t,r){"use strict";function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}r.r(t);var o=Symbol("SchemaOptions");function i(e){return l(e)&&(e.hasOwnProperty("fn")||e.hasOwnProperty("path"))}function c(e){return d(e)}function u(e){return Array.isArray(e)&&e.every(c)}var s=(e,t)=>e.reduce((e,r)=>(y(e,r,v(t,r)),e),{});function p(e){return void 0===e}function l(e){var t=typeof e;return null!=e&&("object"===t||"function"===t)}function d(e){return"string"==typeof e||e instanceof String}function h(e){return"function"==typeof e}function f(e){if(Promise&&Promise.resolve)return Promise.resolve(e)==e;throw new Error("Promise not supported in your environment")}function v(e,t){for(var r=(t=(t=t.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split("."),n=0,a=r.length;n<a;++n){var o=r[n];if(!(l(e)&&o in e))return;e=e[o]}return e}function m(e,t){return e.reduce((e,r,o)=>function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?n(Object(r),!0).forEach((function(t){a(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}({},e,{[r]:t[o]}),{})}function g(e,t){return"number"==typeof t&&Array.isArray(e)||function(e,t){return null!=e&&Object.prototype.hasOwnProperty.call(e,t)}(e,t)}function y(e,t,r,n){if("number"==typeof t&&(t=[t]),!t||0===t.length)return e;if("string"==typeof t)return y(e,t.split(".").map(b),r,n);var a=t[0],o=function(e,t){if(g(e,t))return e[t]}(e,a);return 1===t.length?(void 0!==o&&n||(e[a]=r),o):(void 0===o&&("number"==typeof t[1]?e[a]=[]:e[a]={}),y(e[a],t.slice(1),r,n))}function b(e){var t=parseInt(e);return t.toString()===e?t:e}function w(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}var x=Symbol("errors");class O extends Error{constructor(e){super("Invalid value supplied at property <".concat(e.targetProperty,">.")),this.targetProperty=void 0,this.innerError=void 0,this.innerError=e.innerError}}class P extends Error{constructor(e,t){super(),this.errors=void 0,this.reporter=void 0,this.target=void 0,this.errors=new Set,this.reporter=e,this.target=t}addError(e){this.errors.add(e);var t=this.reporter.report(this.target);t&&(this.message=t.join("\n"))}}function j(e){return e&&e[x]&&e[x].errors.size>0}function E(e){var{message:t,innerError:r}=e;return"".concat(t," Reason: ").concat(r.message)}class S{constructor(e=E){this.formatter=e}report(e){var t=this.extractErrors(e);return t?[...t.errors.values()].map(this.formatter):null}extractErrors(e){return j(e)?e[x]:null}}var A,M=new S;class V extends Error{constructor(e){super(e.expect),this.value=void 0,this.expect=void 0,this.value=e.value,this.expect=e.expect}}function _(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function R(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?_(Object(r),!0).forEach((function(t){T(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function T(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function N(e,t){return t&&!w(t)&&(e[o]=t),e}!function(e){e.Root="Root",e.Property="Property",e.ActionFunction="ActionFunction",e.ActionAggregator="ActionAggregator",e.ActionString="ActionString",e.ActionSelector="ActionSelector"}(A||(A={}));class D{constructor(e){this.schemaOptions=void 0,this.root=void 0,this.schema=void 0,this.schema=e,this.schemaOptions=D.getSchemaOptions(this.schema),this.root={data:{targetPropertyPath:"",propertyName:"MorphismTreeRoot",action:null,kind:A.Root},parent:null,children:[]},e&&this.parseSchema(e)}static getSchemaOptions(e){return R({},{class:{automapping:!0},undefinedValues:{strip:!1}},{},e?e[o]:void 0)}parseSchema(e,t,r){if((d(n=e)||h(n)||i(n)||u(n))&&t)this.add({propertyName:t,action:e},r),r=r?"".concat(r,".").concat(t):t;else{if(t){if(l(e)&&w(e))throw new Error("A value of a schema property can't be an empty object. Value ".concat(JSON.stringify(e)," found for property ").concat(t));this.add({propertyName:t,action:e},r),r=r?"".concat(r,".").concat(t):t}Array.isArray(e)?e.forEach((e,t)=>{this.parseSchema(e,t.toString(),r)}):l(e)&&Object.keys(e).forEach(t=>{this.parseSchema(e[t],t,r)})}var n}*traverseBFS(){var e=[];for(e.push(this.root);e.length>0;){var t=e.shift();if(t){for(var r=0,n=t.children.length;r<n;r++)e.push(t.children[r]);t.data.kind!==A.Root&&(yield t)}}}add(e,t){var r={data:R({},e,{kind:this.getActionKind(e),targetPropertyPath:""}),parent:null,children:[]};if(r.data.preparedAction=this.getPreparedAction(r.data),t)for(var n of this.traverseBFS())n.data.targetPropertyPath===t&&(r.parent=n,r.data.targetPropertyPath="".concat(n.data.targetPropertyPath,".").concat(r.data.propertyName),n.children.push(r));else r.parent=this.root,r.data.targetPropertyPath=r.data.propertyName,this.root.children.push(r)}getActionKind(e){if(c(e.action))return A.ActionString;if(h(e.action))return A.ActionFunction;if(i(e.action))return A.ActionSelector;if(u(e.action))return A.ActionAggregator;if(l(e.action))return A.Property;throw new Error("The action specified for ".concat(e.propertyName," is not supported."))}getPreparedAction(e){var{propertyName:t,action:r,kind:n}=e;return c(r)?e=>{var{object:t}=e;return v(t,r)}:h(r)?e=>{var{object:t,items:n,objectToCompute:a}=e;return r.call(void 0,t,n,a)}:u(r)?e=>{var{object:t}=e;return s(r,t)}:i(r)?e=>{var n,{object:a,items:o,objectToCompute:i}=e;if(r.path?Array.isArray(r.path)?n=s(r.path,a):d(r.path)&&(n=v(a,r.path)):n=a,r.fn)try{n=r.fn.call(void 0,n,a,o,i)}catch(e){throw e.message="Unable to set target property [".concat(t,"].\n \n An error occured when applying [").concat(r.fn.name,"] on property [").concat(r.path,"]\n \n Internal error: ").concat(e.message),e}if(r.validation){var c=r.validation({value:n});this.processValidationResult(c,t,i),n=c.value}return n}:n===A.Property?null:void 0}processValidationResult(e,t,r){if(e.error){var n=e.error;if(!(n instanceof V))throw n;this.addErrorToTarget(t,n,r)}}addErrorToTarget(e,t,r){var n=new O({targetProperty:e,innerError:t});j(r)?r[x].addError(n):(this.schemaOptions.validation&&this.schemaOptions.validation.reporter?r[x]=new P(this.schemaOptions.validation.reporter,r):r[x]=new P(M,r),r[x].addError(n))}}function k(e){return(t,r,n)=>{var a=n.value;return"function"==typeof a&&(n.value=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var o=a.apply(this,r);return f(o)?Promise.resolve(o).then(t=>e(t)):e(o)}),n}}class F{constructor(e){this.data=e,this.next=void 0,this.head=void 0,this.tail=void 0,this.next=null,this.head=this,this.tail=this}append(e){this.tail.next=new F(e),this.tail=this.tail.next}*values(){for(;null!==this.head;)yield this.head.data,this.head=this.head.next}}function q(e,t,r){return{name:e,expect:t,validate:e=>r.test(e.value)}}var C={get:(e,t)=>{if(t in e)return e[t];if(I.has(t))return I.get(t);throw new Error("The validator ".concat(t,"() does not exist. Did you forget to call Validation.addValidator(name, validator)"))}},I=new Map,B=new Proxy({addValidator:(e,t)=>{I.set(e,t)}},C);B.addValidator("string",(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=new F({name:"string",expect:e=>"Expected value to be a <string> but received <".concat(e.value,">"),validate:t=>!!d(t.value)||!!e.convert&&(t.value=String(t.value),!0)}),r=e=>{for(var r=e,n=t.values(),a=n.next(),o={};!r.error&&!a.done;){var i=a.value;if(i.name in o)throw new Error("Rule ".concat(i.name," has already been used"));o[i.name]=i,i.validate(r)||(r.error=new V({expect:d(i.expect)?i.expect:i.expect(r),value:r.value})),a=n.next()}return r},n={min:e=>(t.append({name:"min",expect:t=>"Expected value to be greater or equal than <".concat(e,"> but received <").concat(t.value,">"),validate:t=>t.value.length>=e}),a),max:e=>(t.append({name:"max",expect:t=>"Expected value to be less or equal than <".concat(e,"> but received <").concat(t.value,">"),validate:t=>t.value.length<=e}),a),size:e=>(t.append({name:"length",expect:t=>"Expected value to be length of <".concat(e,"> but received <").concat(t.value,">"),validate:t=>t.value.length===e}),a),regex:e=>{var r=q("regex",t=>"Expected value to match pattern: ".concat(e," but received <").concat(t.value,">"),e);return t.append(r),a},alphanum:()=>{var e=q("regex",e=>"Expected value to contain only alphanumeric characters but received <".concat(e.value,">"),/^[a-z0-9]+$/i);return t.append(e),a}},a=Object.assign(r,n);return a})),B.addValidator("number",(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=new F({name:"number",expect:e=>"Expected value to be a <number> but received <".concat(e.value,">"),validate:t=>e.convert?(t.value=+t.value,!isNaN(t.value)):"number"==typeof t.value}),r=e=>{for(var r=e,n=t.values(),a=n.next(),o={};!r.error&&!a.done;){var i=a.value;if(i.name in o)throw new Error("Rule ".concat(i.name," has already been used"));o[i.name]=i,i.validate(r)||(r.error=new V({expect:d(i.expect)?i.expect:i.expect(r),value:r.value})),a=n.next()}return r},n={min:e=>(t.append({name:"min",expect:"value to be greater or equal than ".concat(e),validate:t=>t.value>=e}),a),max:e=>(t.append({name:"max",expect:"value to be less or equal than ".concat(e),validate:t=>t.value<=e}),a)},a=Object.assign(r,n);return a})),B.addValidator("boolean",(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=new F({name:"boolean",expect:e=>"Expected value to be a <boolean> but received <".concat(e.value,">"),validate:t=>e.convert?"boolean"==typeof t.value?t.value:/true/i.test(t.value)?(t.value=!0,!0):!!/false/i.test(t.value)&&(t.value=!1,!0):"boolean"==typeof t.value}),r=e=>{for(var r=e,n=t.values(),a=n.next(),o={};!r.error&&!a.done;){var i=a.value;if(i.name in o)throw new Error("Rule ".concat(i.name," has already been used"));o[i.name]=i,i.validate(r)||(r.error=new V({expect:d(i.expect)?i.expect:i.expect(r),value:r.value})),a=n.next()}return r},n={},a=Object.assign(r,n);return a}));var z=r(0);function J(e,t,r,n){var a=t.schemaOptions,o=[];for(var i of t.traverseBFS()){var{preparedAction:c,targetPropertyPath:u}=i.data;c&&o.push({targetPropertyPath:u,preparedAction:c({object:e,objectToCompute:n,items:r})})}return o.reduce((e,t)=>{var r,n,o=(r=v(e,t.targetPropertyPath),p(n=t.preparedAction)?p(r)?void 0:r:n);return void 0===o?(a&&a.undefinedValues&&a.undefinedValues.strip?a.undefinedValues.default&&y(e,t.targetPropertyPath,a.undefinedValues.default(e,t.targetPropertyPath)):y(e,t.targetPropertyPath,o),K(a,e),e):(y(e,t.targetPropertyPath,o),K(a,e),e)},n)}function K(e,t){if(e&&e.validation&&e.validation.throw&&j(t)){var r;if(e.validation.reporter)r=e.validation.reporter.extractErrors(t);else r=M.extractErrors(t);if(r)throw r}}function $(e,t){var r,n=D.getSchemaOptions(e);if(t&&n.class&&n.class.automapping){var a=function(e,t){var r=Object.keys(new e),n=m(r,r);return Object.assign(n,t)}(t,e);r=new D(a)}else r=new D(e);return e=>{if(!e)return e;if(Array.isArray(e))return e.map(n=>{if(t){var a=new t;return J(n,r,e,a)}return J(n,r,e,{})});var n=e;if(t){var a=new t;return J(n,r,[n],a)}return J(n,r,[n],{})}}function H(e,t,r){switch(arguments.length){case 1:return $(e);case 2:return $(e)(t);case 3:if(r)return null!==t?$(e,r)(t):$(e,r);throw new Error("When using morphism(schema, items, type), type should be defined but value received is ".concat(r))}}function L(e,t){return k($(e,t))}function U(e){return k($(e))}function W(e,t){return k($(e,t))}r.d(t,"morph",(function(){return L})),r.d(t,"toJSObject",(function(){return U})),r.d(t,"toClassObject",(function(){return W})),r.d(t,"morphism",(function(){return H})),r.d(t,"createSchema",(function(){return N})),r.d(t,"Schema",(function(){})),r.d(t,"StrictSchema",(function(){})),r.d(t,"SchemaOptions",(function(){})),r.d(t,"Mapper",(function(){})),r.d(t,"SCHEMA_OPTIONS_SYMBOL",(function(){return o})),r.d(t,"Reporter",(function(){return S})),r.d(t,"reporter",(function(){return M})),r.d(t,"Formatter",(function(){})),r.d(t,"Validation",(function(){return B})),r.d(t,"Rule",(function(){return z.Rule})),r.d(t,"ValidatorError",(function(){return V})),r.d(t,"IValidation",(function(){}));var Y=new class{constructor(){this._registry=null,this._registry={cache:new Map}}register(e,t){if(!e&&!t)throw new Error("type paramater is required when you register a mapping");if(this.exists(e))throw new Error("A mapper for ".concat(e.name," has already been registered"));var r;return r=H(t||{},null,e),this._registry.cache.set(e,r),r}map(e,t){if(!this.exists(e)){var r=this.register(e);if(void 0===t)return r}return this.getMapper(e)(t)}getMapper(e){return this._registry.cache.get(e)}setMapper(e,t){if(t){if(this.exists(e)){var r=H(t,null,e);return this._registry.cache.set(e,r),r}throw new Error("The type ".concat(e.name," is not registered. Register it using `Mophism.register(").concat(e.name,", schema)`"))}throw new Error("The schema must be an Object. Found ".concat(t))}deleteMapper(e){return this._registry.cache.delete(e)}exists(e){return this._registry.cache.has(e)}get mappers(){return this._registry.cache}},G=H;G.register=(e,t)=>Y.register(e,t),G.map=(e,t)=>Y.map(e,t),G.getMapper=e=>Y.getMapper(e),G.setMapper=(e,t)=>Y.setMapper(e,t),G.deleteMapper=e=>Y.deleteMapper(e),G.mappers=Y.mappers;var Q=G;t.default=Q}])})); | ||
//# sourceMappingURL=morphism.map |
import { ActionSelector, ActionAggregator, ActionFunction } from './types'; | ||
/** | ||
* Symbol identifier used to store options on a Morphism schema. Using the `createSchema` helper to avoid using the symbol directly. | ||
* | ||
* @example | ||
* ```typescript | ||
* import { SCHEMA_OPTIONS_SYMBOL } from 'morphism'; | ||
* | ||
* const options: SchemaOptions = { class: { automapping: true }, undefinedValues: { strip: true } }; | ||
* const schema: Schema = { targetProperty: 'sourceProperty', [SCHEMA_OPTIONS_SYMBOL]: options } | ||
* ``` | ||
*/ | ||
export declare const SCHEMA_OPTIONS_SYMBOL: unique symbol; | ||
@@ -3,0 +15,0 @@ export declare function isActionSelector<S, R>(value: any): value is ActionSelector<S, R>; |
@@ -8,2 +8,6 @@ /** | ||
import { IMorphismRegistry } from './MorphismRegistry'; | ||
import { Reporter, reporter as defaultReporter, Formatter } from './validation/reporter'; | ||
import { Validation, IValidation } from './validation/Validation'; | ||
import { ValidatorError } from './validation/validators/ValidatorError'; | ||
import { Rule } from './validation/validators/types'; | ||
/** | ||
@@ -57,3 +61,3 @@ * Currying function that either outputs a mapping function or the transformed data. | ||
declare const Morphism: typeof morphism & IMorphismRegistry; | ||
export { morphism, createSchema, Schema, StrictSchema, SchemaOptions, Mapper, SCHEMA_OPTIONS_SYMBOL }; | ||
export { morphism, createSchema, Schema, StrictSchema, SchemaOptions, Mapper, SCHEMA_OPTIONS_SYMBOL, Reporter, defaultReporter as reporter, Formatter, Validation, Rule, ValidatorError, IValidation, }; | ||
export default Morphism; |
@@ -64,3 +64,3 @@ import { Constructable, Schema, Mapper } from './types'; | ||
*/ | ||
constructor(cache?: Map<any, any> | WeakMap<any, any>); | ||
constructor(); | ||
/** | ||
@@ -116,3 +116,3 @@ * Register a mapping schema for a Class. | ||
*/ | ||
readonly mappers: Map<any, any>; | ||
get mappers(): Map<any, any>; | ||
} |
import { Actions, Schema, StrictSchema } from './types'; | ||
import { Reporter } from './validation/reporter'; | ||
export declare enum NodeKind { | ||
@@ -35,10 +36,53 @@ Root = "Root", | ||
}>; | ||
/** | ||
* Options attached to a `Schema` or `StrictSchema` | ||
*/ | ||
export interface SchemaOptions<Target = any> { | ||
/** | ||
* Specify how to handle ES6 Class | ||
* @memberof SchemaOptions | ||
*/ | ||
class?: { | ||
/** | ||
* Specify wether ES6 Class fields should be automapped if names on source and target match | ||
* @default true | ||
* @type {boolean} | ||
*/ | ||
automapping: boolean; | ||
}; | ||
/** | ||
* Specify how to handle undefined values mapped during the transformations | ||
* @memberof SchemaOptions | ||
*/ | ||
undefinedValues?: { | ||
/** | ||
* Undefined values should be removed from the target | ||
* @default false | ||
* @type {boolean} | ||
*/ | ||
strip: boolean; | ||
/** | ||
* Optional callback to be executed for every undefined property on the Target | ||
* @function default | ||
*/ | ||
default?: (target: Target, propertyPath: string) => any; | ||
}; | ||
/** | ||
* Schema validation options | ||
* @memberof SchemaOptions | ||
*/ | ||
validation?: { | ||
/** | ||
* Should throw when property validation fails | ||
* @default false | ||
* @type {boolean} | ||
*/ | ||
throw: boolean; | ||
/** | ||
* Custom reporter to use when throw option is set to true | ||
* @default false | ||
* @type {boolean} | ||
*/ | ||
reporter?: Reporter; | ||
}; | ||
} | ||
@@ -59,7 +103,9 @@ /** | ||
private parseSchema; | ||
traverseBFS(): IterableIterator<SchemaNode<Target, Source>>; | ||
traverseBFS(): Generator<SchemaNode<Target, Source>, void, unknown>; | ||
add(data: AddNode<Target, Source>, targetPropertyPath?: string): void; | ||
getActionKind(action: Actions<Target, Source> | null): NodeKind.Property | NodeKind.ActionFunction | NodeKind.ActionAggregator | NodeKind.ActionString | NodeKind.ActionSelector | undefined; | ||
getPreparedAction(nodeData: SchemaNodeData<Target, Source>): PreparedAction | null; | ||
getActionKind(data: AddNode<Target, Source>): NodeKind.Property | NodeKind.ActionFunction | NodeKind.ActionAggregator | NodeKind.ActionString | NodeKind.ActionSelector; | ||
getPreparedAction(nodeData: SchemaNodeData<Target, Source>): PreparedAction | null | undefined; | ||
private processValidationResult; | ||
private addErrorToTarget; | ||
} | ||
export {}; |
@@ -1,2 +0,2 @@ | ||
import { SCHEMA_OPTIONS_SYMBOL, SchemaOptions } from './morphism'; | ||
import { SCHEMA_OPTIONS_SYMBOL, SchemaOptions, ValidatorError } from './morphism'; | ||
/** | ||
@@ -34,3 +34,3 @@ * A structure-preserving object from a source data towards a target data. | ||
export declare type StrictSchema<Target = any, Source = any> = { | ||
[destinationProperty in keyof Target]: ActionString<Source> | ActionFunction<Target, Source, Target[destinationProperty]> | ActionAggregator<Source> | ActionSelector<Source, Target[destinationProperty]> | StrictSchema<Target[destinationProperty], Source>; | ||
[destinationProperty in keyof Target]: ActionString<Source> | ActionFunction<Target, Source, Target[destinationProperty]> | ActionAggregator<Source> | ActionSelector<Source, Target> | StrictSchema<Target[destinationProperty], Source>; | ||
} & { | ||
@@ -40,3 +40,3 @@ [SCHEMA_OPTIONS_SYMBOL]?: SchemaOptions<Target>; | ||
export declare type Schema<Target = any, Source = any> = { | ||
[destinationProperty in keyof Target]?: ActionString<Source> | ActionFunction<Target, Source, Target[destinationProperty]> | ActionAggregator<Source> | ActionSelector<Source, Target[destinationProperty]> | Schema<Target[destinationProperty], Source>; | ||
[destinationProperty in keyof Target]?: ActionString<Source> | ActionFunction<Target, Source, Target[destinationProperty]> | ActionAggregator<Source> | ActionSelector<Source, Target> | Schema<Target[destinationProperty], Source>; | ||
} & { | ||
@@ -102,3 +102,3 @@ [SCHEMA_OPTIONS_SYMBOL]?: SchemaOptions<Target | any>; | ||
*/ | ||
export declare type ActionString<Source> = string; | ||
export declare type ActionString<Source> = string | keyof Source; | ||
/** | ||
@@ -150,6 +150,14 @@ * An Array of String that allows to perform a function over source property | ||
*/ | ||
export interface ActionSelector<Source = object, R = any> { | ||
path: ActionString<Source> | ActionAggregator<Source>; | ||
fn: (fieldValue: any, object: Source, items: Source, objectToCompute: R) => R; | ||
export interface ActionSelector<Source = object, Target = any> { | ||
path?: ActionString<Source> | ActionAggregator<Source>; | ||
fn?: (fieldValue: any, object: Source, items: Source, objectToCompute: Target) => Target; | ||
validation?: ValidateFunction; | ||
} | ||
export interface ValidatorValidateResult { | ||
value: any; | ||
error?: ValidatorError; | ||
} | ||
export declare type ValidateFunction = (input: { | ||
value: any; | ||
}) => ValidatorValidateResult; | ||
export interface Constructable<T> { | ||
@@ -161,5 +169,11 @@ new (...args: any[]): T; | ||
export declare type ResultItem<TSchema extends Schema> = DestinationFromSchema<TSchema>; | ||
/** | ||
* Function to map an Input source towards a Target. Input can be a single object, or a collection of objects | ||
* @function | ||
* @typeparam TSchema Schema | ||
* @typeparam TResult Result Type | ||
*/ | ||
export interface Mapper<TSchema extends Schema | StrictSchema, TResult = ResultItem<TSchema>> { | ||
(data: SourceFromSchema<TSchema>[]): TResult[]; | ||
(data: SourceFromSchema<TSchema>): TResult; | ||
(data?: SourceFromSchema<TSchema>[] | null): TResult[]; | ||
(data?: SourceFromSchema<TSchema> | null): TResult; | ||
} |
{ | ||
"name": "morphism", | ||
"version": "2.0.0", | ||
"version": "2.1.0-beta.1", | ||
"description": "Do not repeat anymore your objects transformations.", | ||
@@ -12,11 +12,13 @@ "homepage": "https://github.com/nobrainr/morphism", | ||
"build:js": "TS_NODE_PROJECT=\"tsconfig.webpack.json\" webpack --mode=production", | ||
"watch:js": "npm run build:js -- -w --display \"errors-only\"", | ||
"watch:js": "yarn run build:js -w --display \"errors-only\"", | ||
"build:types": "tsc -p tsconfig.prod.json --emitDeclarationOnly", | ||
"watch:types": "npm run build:types -- -w >/dev/null", | ||
"watch:types": "yarn run build:types -w >/dev/null", | ||
"test": "jest", | ||
"test:types": "tsc --emitDeclarationOnly", | ||
"test:coverage": "npm run test -- --coverage", | ||
"test:coverage": "yarn run test --coverage", | ||
"semantic-release": "semantic-release", | ||
"docs": "typedoc", | ||
"docs:deploy": "now ./docs/typedoc -A ../../now.json --public --team $TEAM_NAME --token $NOW_TOKEN && now alias --team $TEAM_NAME --token $NOW_TOKEN" | ||
"docs:deploy": "now ./docs/typedoc -A ../../now.json --public --team $TEAM_NAME --token $NOW_TOKEN && now alias --team $TEAM_NAME --token $NOW_TOKEN", | ||
"analyze-bundle:dev": "WEBPACK_ANALYZE=true TS_NODE_PROJECT=\"tsconfig.webpack.json\" webpack", | ||
"analyze-bundle:prod": "WEBPACK_ANALYZE=true TS_NODE_PROJECT=\"tsconfig.webpack.json\" webpack --mode=production" | ||
}, | ||
@@ -26,3 +28,7 @@ "release": { | ||
"master", | ||
"next" | ||
"next", | ||
{ | ||
"name": "beta", | ||
"prerelease": true | ||
} | ||
] | ||
@@ -55,19 +61,25 @@ }, | ||
"devDependencies": { | ||
"@babel/core": "7.5.5", | ||
"@babel/plugin-proposal-class-properties": "^7.5.5", | ||
"@babel/plugin-proposal-decorators": "^7.4.4", | ||
"@babel/plugin-proposal-object-rest-spread": "^7.5.5", | ||
"@babel/preset-env": "7.5.5", | ||
"@babel/preset-typescript": "^7.3.3", | ||
"@types/jest": "24.0.15", | ||
"@types/node": "^12.0.0", | ||
"@babel/core": "7.7.0", | ||
"@babel/plugin-proposal-class-properties": "^7.7.0", | ||
"@babel/plugin-proposal-decorators": "^7.7.0", | ||
"@babel/plugin-proposal-object-rest-spread": "^7.6.2", | ||
"@babel/preset-env": "7.7.0", | ||
"@babel/preset-typescript": "^7.7.0", | ||
"@hapi/joi": "^16.1.7", | ||
"@types/hapi__joi": "^16.0.1", | ||
"@types/jest": "24.0.25", | ||
"@types/node": "^13.1.0", | ||
"@types/validator": "^10.11.3", | ||
"@types/webpack": "^4.4.27", | ||
"@types/webpack-bundle-analyzer": "^2.13.3", | ||
"babel-loader": "^8.0.5", | ||
"fork-ts-checker-webpack-plugin": "^1.0.1", | ||
"fork-ts-checker-webpack-plugin": "^4.0.1", | ||
"jest": "24.7.1", | ||
"nodemon": "^1.18.11", | ||
"nodemon-webpack-plugin": "^4.0.8", | ||
"now": "^15.6.2", | ||
"lint-staged": "^9.4.3", | ||
"nodemon": "^2.0.0", | ||
"nodemon-webpack-plugin": "^4.2.2", | ||
"now": "^16.7.2", | ||
"npm-run-all": "^4.1.5", | ||
"semantic-release": "^16.0.0-beta.22", | ||
"prettier": "1.19.1", | ||
"semantic-release": "^16.0.3", | ||
"source-map-loader": "^0.2.4", | ||
@@ -77,7 +89,9 @@ "ts-node": "^8.0.3", | ||
"tslint-loader": "^3.6.0", | ||
"typedoc": "^0.15.0", | ||
"typedoc-plugin-external-module-name": "^2.0.0", | ||
"typedoc": "^0.16.0", | ||
"typedoc-plugin-external-module-name": "^3.0.0", | ||
"typedoc-plugin-internal-external": "^2.0.1", | ||
"typescript": "^3.4.2", | ||
"webpack": "4.38.0", | ||
"typescript": "^3.7.2", | ||
"validator": "^11.1.0", | ||
"webpack": "4.41.5", | ||
"webpack-bundle-analyzer": "^3.5.2", | ||
"webpack-cli": "^3.3.0" | ||
@@ -92,3 +106,14 @@ }, | ||
"repository": "nobrainr/morphism", | ||
"license": "MIT" | ||
"license": "MIT", | ||
"husky": { | ||
"hooks": { | ||
"pre-commit": "lint-staged" | ||
} | ||
}, | ||
"lint-staged": { | ||
"*.{ts,js,css,json,md}": [ | ||
"prettier --write", | ||
"git add" | ||
] | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
124599
21
694
35
14289
1