polyn
Version:
polyn is a collection of Node and browser compatible JavaScript utilities that focus on polymorphism
3 lines (2 loc) • 20.6 kB
JavaScript
/*! polyn 2019-11-09 */
!function(){"use strict";function i(e){return(console.warn||console.log)(e.message,e),e}if(!window)return i(new Error("[POLYN] Unable to define module: UNKNOWN RUNTIME"));window.polyn=window.polyn||{},window.polyn.addModule=function(e,n,r){var t,o;if(Array.isArray(n))for(t=0;t<n.length;t+=1)if(!polyn[n[t]])return i(new Error("[POLYN] Unable to define module: LOADED OUT OF ORDER"));o=new r(polyn),Object.defineProperty(polyn,e,{get:function(){return o},set:function(){return i(new Error("[POLYN] polyn modules are read-only"))},enumerable:!0,configurable:!1})}}(),function(){"use strict";var o="[POLYN] EXCEPTION WARNING: You should always pass an Error to Exception, to preserve your stack trace",i={onWarning:function(e){console.log(e)}};function e(e,n,r){var t=function(e,n){if("object"==typeof e)return e;var r=n;return"string"==typeof n?(i.onWarning(o),r=new Error(n)):n||(i.onWarning(o),r=new Error("UNKNOWN")),r}(e,n);return{type:function(e){return"string"==typeof e?e:"Exception"}(e),error:t,messages:function(e,n){var r=[];return Array.isArray(n)?r=n:n?r.push(n):!n&&e&&e.message&&r.push(e.message),r}(t,r),isException:!0}}"undefined"!=typeof module&&module.exports?module.exports=e:window&&window.polyn?window.polyn.addModule("Exception",null,function(){return e}):console.log(new Error("[POLYN] Unable to define module: UNKNOWN RUNTIME or POLYN NOT DEFINED")),e.configure=function(e){"function"==typeof(e=e||{}).onWarning&&(i.onWarning=e.onWarning)}}(),function(){"use strict";var e=n();function n(){function a(e,n){!0===n&&"undefined"!=typeof process&&"function"==typeof process.nextTick?process.nextTick(e):setTimeout(e,0)}return{runAsync:a,waterfall:function(o,n,i){var e=-1;n="function"==typeof n?(i=r(n||t),{blocking:!1}):(i=r(i||t),n||{});if(!Array.isArray(o))return i(new Error("The first argument to waterfall must be an array of functions"));if(!o.length)return i();function u(){!function(r,t){!function(e){n.blocking?e():a(e,!0)}(function(){try{var e=t[0],n=function(e){var n,r=[];for(n in e)e.hasOwnProperty(n)&&r.push(e[n]);return r.shift(),r}(t);if(e)return i.apply(null,[e].concat(n));if(r===o.length)return i.apply(null,[null].concat(n));n.push(function(n){return function(){if(null===n)throw new Error("Callback was already called.");var e=n;n=null,e.apply(this,arguments)}}(u)),o[r].apply(null,n)}catch(e){return i.apply(null,[e])}})}(e+=1,arguments)}u()}}}function r(n){return function(){if(null!==n){var e=n;n=null,e.apply(this,arguments)}}}function t(){}"undefined"!=typeof module&&module.exports?module.exports=e:window&&window.polyn?window.polyn.addModule("async",null,n):console.log(new Error("[POLYN] Unable to define module: UNKNOWN RUNTIME or POLYN NOT DEFINED"))}(),function(){"use strict";var STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,ARGUMENT_NAMES=/([^\s,]+)/g,FUNCTION_TEMPLATE="newFunc = function ({{args}}) { return that.apply(that, arguments); }",locale={errorTypes:{invalidArgumentException:"InvalidArgumentException"},errors:{cannotCopyFunction:"Valid values for the function argument are a function, null, or undefined"}};function Factory(e){return new ObjectHelper(e.async)}function ObjectHelper(async){var self={};function setReadOnlyProperty(e,n,r,t){var o="the {{name}} property is read-only".replace(/{{name}}/,n);Object.defineProperty(e,n,{get:function(){return r},set:function(){if("function"==typeof t)return t(o);var e=new Error(o);return console.log(e),e},enumerable:!0,configurable:!1})}function copyValue(e){if(!e)return e;try{return isDate(e)?new Date(e):isFunction(e)?copyFunction(e):isRegex(e)?new RegExp(e):isObject(e)&&!Array.isArray(e)?syncCloneObject(e,!0):JSON.parse(JSON.stringify(e))}catch(e){return{type:locale.errorTypes.invalidArgumentException,error:e,messages:[e.message],isException:!0}}}function copyFunction(func){var newFunc,that,prop;if(func&&"function"!=typeof func)return{type:locale.errorTypes.invalidArgumentException,error:new Error(locale.errors.cannotCopyFunction),messages:[locale.errors.cannotCopyFunction],isException:!0};if(!func)return func;for(prop in that=func.__clonedFrom||func,eval(FUNCTION_TEMPLATE.replace(/{{args}}/,getArgumentNames(func).join(", "))),that)that.hasOwnProperty(prop)&&(newFunc[prop]=copyValue(that[prop]));return newFunc.__clonedFrom=that,newFunc}function getArgumentNames(n,r){if("function"!=typeof r)return syncGetArgumentNames(n);async.runAsync(function(){var e=syncGetArgumentNames(n);e.isException?r(e):r(null,e)})}function syncGetArgumentNames(e){var n,r;return e&&"function"!=typeof e?{type:locale.errorTypes.invalidArgumentException,error:new Error(locale.errors.cannotCopyFunction),messages:[locale.errors.cannotCopyFunction],isException:!0}:e?(null===(r=(n=e.toString().replace(STRIP_COMMENTS,"")).slice(n.indexOf("(")+1,n.indexOf(")")).match(ARGUMENT_NAMES))&&(r=[]),r):[]}function cloneObject(n,r,t){if("function"!=typeof t)return syncCloneObject(n,r);async.runAsync(function(){var e=syncCloneObject(n,r);e.isException?t(e):t(null,e)})}function syncCloneObject(e,n){var r,t={};for(r in void 0===n&&(n=!0),e)if(e.hasOwnProperty(r)&&(n&&isObject(e[r])&&!isDate(e[r])?t[r]=syncCloneObject(e[r]):n||!isObject(e[r])||isDate(e[r])?t[r]=copyValue(e[r],t):t[r]=null,t[r]&&t[r].isException))return t[r];return t}function merge(n,r,t){if("function"!=typeof t)return syncMerge(n,r);async.runAsync(function(){var e=syncMerge(n,r);e.isException?t(e):t(null,e)})}function syncMerge(e,n){var r,t=syncCloneObject(e);for(r in n)n.hasOwnProperty(r)&&(isObject(n[r])&&!isDate(n[r])?t[r]=merge(e[r],n[r]):t[r]=n[r]);return t}function isDate(e){return"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)}function isFunction(e){return"function"==typeof e}function isObject(e){return"object"==typeof e}function isRegex(e){return e&&e instanceof RegExp}return setReadOnlyProperty(self,"setReadOnlyProperty",setReadOnlyProperty),setReadOnlyProperty(self,"copyValue",copyValue),setReadOnlyProperty(self,"cloneObject",cloneObject),setReadOnlyProperty(self,"merge",merge),setReadOnlyProperty(self,"getArgumentNames",getArgumentNames),self}"undefined"!=typeof module&&module.exports?module.exports=new Factory({async:require("./async.js")}):window&&window.polyn?window.polyn.addModule("objectHelper",["async"],Factory):console.log(new Error("[POLYN] Unable to define module: UNKNOWN RUNTIME or POLYN NOT DEFINED"))}(),function(){"use strict";function e(){var r,e={createUid:void 0,createGuid:void 0};return r=function(e){return e.replace(/[xy]/g,function(e){var n=16*Math.random()|0;return("x"===e?n:3&n|8).toString(16)})},e.createUid=function(e){var n;return e=e||12,n=new Array(e+1).join("x"),r(n)},e.createGuid=function(){return r("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx")},e}"undefined"!=typeof module&&module.exports?module.exports=new e:window&&window.polyn?window.polyn.addModule("id",null,e):console.log(new Error("[POLYN] Unable to define module: UNKNOWN RUNTIME or POLYN NOT DEFINED"))}(),function(){"use strict";function e(){var e,n,r={getType:void 0,defined:void 0,nullOrUndefined:void 0,function:void 0,object:void 0,array:void 0,string:void 0,bool:void 0,boolean:void 0,date:void 0,datetime:void 0,regexp:void 0,number:void 0,nullOrWhitespace:void 0,money:void 0,decimal:void 0,Window:void 0,ObjectID:void 0,not:{defined:void 0,function:void 0,object:void 0,array:void 0,string:void 0,bool:void 0,boolean:void 0,date:void 0,datetime:void 0,regexp:void 0,number:void 0,nullOrWhitespace:void 0,money:void 0,decimal:void 0,Window:void 0,ObjectID:void 0}},t={},o=["Boolean","Number","String","Function","Array","Date","RegExp","Object"];for(e=0;e<o.length;e+=1)t["[object "+(n=o[e])+"]"]=n.toLowerCase();return r.getType=function(e){return void 0===e?"undefined":null===e?String(e):"object"==typeof e||"function"==typeof e?t[Object.prototype.toString.call(e)]||"object":typeof e},r.defined=function(e){try{return"undefined"!==r.getType(e)}catch(e){return!1}},r.not.defined=function(e){return!1===r.defined(e)},r.nullOrUndefined=function(e){return r.not.defined(e)||null===e},r.not.nullOrWhitespace=function(e){return void 0!==e&&null!==typeof e&&!r.not.string(e)&&/([^\s])/.test(e)},r.nullOrWhitespace=function(e){return!1===r.not.nullOrWhitespace(e)},r.function=function(e){return"function"===r.getType(e)},r.not.function=function(e){return!1===r.function(e)},r.object=function(e){return"object"===r.getType(e)},r.not.object=function(e){return!1===r.object(e)},r.array=function(e){return"array"===r.getType(e)},r.not.array=function(e){return!1===r.array(e)},r.string=function(e){return"string"===r.getType(e)},r.not.string=function(e){return!1===r.string(e)},r.bool=function(e){return"boolean"===r.getType(e)},r.not.bool=function(e){return!1===r.boolean(e)},r.boolean=function(e){return"boolean"===r.getType(e)},r.not.boolean=function(e){return!1===r.boolean(e)},r.datetime=function(e){return"date"===r.getType(e)&&r.function(e.getTime)&&!isNaN(e.getTime())},r.not.datetime=function(e){return!1===r.datetime(e)},r.date=r.datetime,r.not.date=r.not.datetime,r.regexp=function(e){return"regexp"===r.getType(e)},r.not.regexp=function(e){return!1===r.regexp(e)},r.number=function(e){return"number"===r.getType(e)},r.not.number=function(e){return!1===r.number(e)},r.money=function(e){return r.defined(e)&&/^(?:-)?[0-9]\d*(?:\.\d{0,2})?$/.test(e.toString())},r.not.money=function(e){return!1===r.money(e)},r.decimal=function(e,n){return!r.not.number(e)&&(!(n||!r.number(e))||!(!e||+(+e||0).toFixed(n)!=+e))},r.not.decimal=function(e){return!1===r.decimal(e)},r.Window=function(e){return r.defined(Window)&&e instanceof Window},r.not.Window=function(e){return!1===r.Window(e)},r.ObjectID=function(e){return r.defined(e)&&"ObjectID"===e._bsontype},r.not.ObjectID=function(e){return!1===r.ObjectID(e)},r}"undefined"!=typeof module&&module.exports?module.exports=new e:window&&window.polyn?window.polyn.addModule("is",null,e):console.log(new Error("[POLYN] Unable to define module: UNKNOWN RUNTIME or POLYN NOT DEFINED"))}(),function(){"use strict";function e(e){return new n(e.async,e.id,e.is,e.Exception,e.objectHelper)}function n(i,u,a,c,l){var s,t,r,e,o,p,d,f,y,m,g,b,v,w,O,n,E,x,N,h,j={},P={v20161119:new Date("2016-11-19"),v20161120:new Date("2016-11-20")},T={errorTypes:{invalidArgumentException:"InvalidArgumentException",readOnlyViolation:"ReadOnlyViolation"},errors:{requiresImplementation:"An implementation is required to create a new instance of an interface",requiresProperty:"This implementation does not satisfy blueprint, {{blueprint}}. It should have the property, {{property}}, with type, {{type}}.",requiresArguments:"This implementation does not satisfy blueprint, {{blueprint}}. The function, {{property}}, is missing arguments",missingConstructorArgument:"An object literal is required when constructing a Blueprint",missingSignaturesMatchBlueprintArgument:"The `blueprint` argument is required",missingSignaturesMatchImplementationArgument:"The `implementation` argument is required",missingSignaturesMatchCallbackArgument:"The `callback` argument is required",configurationCompatibilityIsNotValid:"The date you tried to set the Blueprint compatibility to is not valid",validatePropertyInvalidArgs:"To validate a single property, you must provide the blueprint, and the property name",validatePropertyNoBlueprintValue:"The {{property}} property does not exist on the blueprint",validatePropertyFailed:"An error occurred while validating the property"}};return t=function(r,t,o){r=v(r),e(r,t,function(e,n){e||w(r,t),"function"==typeof o&&o(e,n)})},r=function(e,n){var r;return e=v(e),(r=o(e,n)).result&&w(e,n),r},e=function(n,r,t){i.runAsync(function(){var e=o(n,r);e.result?t(null,!0):t(e.errors,!1)})},o=function(e,n){var r,t=[];if(O(e,n))return{errors:null,result:!0};for(r in n.props)n.props.hasOwnProperty(r)&&p(n.__blueprintId,e,r,n.props[r],t);return 0<t.length?{errors:t,result:!1}:{errors:null,result:!0}},p=function(e,n,r,t,o){a.string(t)?f(e,n,r,t,o):a.regexp(t)?b(e,n,r,t,o):a.object(t)&&d(e,n,r,t,t.type,o)},d=function(e,n,r,t,o,i){if(!1!==t.required||!a.not.defined(n[r])&&null!==n[r])if(a.function(t.validate))t.validate(n[r],i,n);else switch(o){case"blueprint":g(t.blueprint,n,r,i);break;case"function":f(e,n,r,o,i),t.args&&y(e,n,r,t.args,i);break;case"decimal":m(e,n,r,t.places,i);break;case"expression":b(e,n,r,t.expression,i);break;default:f(e,n,r,o,i)}},f=function(e,n,r,t,o){a.function(a.not[t])&&a.not[t](n[r])&&o.push(E(T.errors.requiresProperty,e,r,t))},y=function(e,n,r,t,o){var i;if(!(a.array(t)&&0<t.length&&a.function(n[r])&&n[r].length===t.length)){try{i=t.join(", ")}catch(e){i=t.toString()}o.push(E(T.errors.requiresArguments,e,r,i))}},m=function(e,n,r,t,o){a.not.decimal(n[r],t)&&o.push(E(T.errors.requiresProperty,e,r,"decimal with "+t+" places"))},function(e,n,r,t){a.function(a.not.boolean)&&a.not.boolean(n[r])&&t.push(E(T.errors.requiresProperty,e,r,"boolean"))},g=function(e,n,r,t){var o,i=e.syncSignatureMatches(n[r]);if(!i.result)for(o=0;o<i.errors.length;o+=1)t.push(i.errors[o])},b=function(e,n,r,t,o){!1===t.test(n[r])&&o.push(E(T.errors.requiresProperty,e,r,t.toString()))},v=function(e){if(j.rememberValidation)try{e[j.memoryPropertName]=e[j.memoryPropertName]||{}}catch(e){}return e},w=function(e,n){if(j.rememberValidation)try{e[j.memoryPropertName][n.__blueprintId]=!0}catch(e){}return e},O=function(e,n){return e[j.memoryPropertName]&&e[j.memoryPropertName][n.__blueprintId]},function(e,n){return n<e},n=function(e,n){return e<n},E=function(e,n,r,t){return e.replace(/{{blueprint}}/gi,n).replace(/{{property}}/gi,r).replace(/{{type}}/gi,t)},x=function(e,n,r){l.setReadOnlyProperty(e,n,r,function(){var e=new c(T.errorTypes.readOnlyViolation,new Error(n+" is read-only"));return j.onError(e),e})},(s=function(e){var n,t={},r={},o=!1;for(n in e=e||{})if(e.hasOwnProperty(n))if("__blueprintId"===n)x(t,"__blueprintId",e.__blueprintId);else if(s.isValidatableProperty(e[n]))x(r,n,e[n]);else{o=!0;var i=new c(T.errorTypes.invalidArgumentException,new Error(n+" is not validatable by Blueprint"));j.onError(i)}return a.not.string(t.__blueprintId)&&x(t,"__blueprintId",u.createUid(8)),x(t,"props",r),x(t,"validate",function(e,n){return s.validate(t,e,n)}),x(t,"validateProperty",function(e,n,r){return s.validateProperty(t,e,n,r)}),x(t,"signatureMatches",function(e,n){return s.validate(t,e,n)}),x(t,"syncSignatureMatches",function(e){return s.syncValidate(t,e)}),x(t,"inherits",function(e){return s.syncMerge([t,e])}),x(t,"hasInvalidProperties",o),x(t,"getSchema",function(){return l.cloneObject(e)}),t}).validate=function(e,n,r){if(a.not.function(r))return s.syncValidate(e,n);i.runAsync(function(){t(n,e,r)})},s.syncValidate=function(e,n){return a.not.defined(e)?{errors:[T.errors.missingSignaturesMatchBlueprintArgument],result:!1}:a.not.defined(n)?{errors:[T.errors.missingSignaturesMatchImplementationArgument],result:!1}:r(n,e)},s.validateProperty=function(n,r,t,o){if(a.not.function(o))return s.syncValidateProperty(n,r,t);i.runAsync(function(){var e=s.syncValidateProperty(n,r,t);if(!e)return o([T.errors.validatePropertyFailed],!1);o(e.errors,e.result)})},s.syncValidateProperty=function(e,n,r){var t,o={},i=[];return a.not.defined(e)||a.not.string(n)?{errors:[T.errors.validatePropertyInvalidArgs],result:!1}:(t=e.props&&e.props[n]||e[n],a.not.defined(t)?{errors:[T.errors.validatePropertyNoBlueprintValue.replace(/{{property}}/,n)],result:!1}:(o[n]=r,p(e.__blueprintId,o,n,t,i),{errors:0===i.length?null:i,result:0===i.length}))},s.merge=function(e,n){if("function"!=typeof n)return s.syncMerge(e);i.runAsync(function(){n(null,s.syncMerge(e))})},s.syncMerge=function(e){var n,r,t=!0;if(!Array.isArray(e))return null;for(n=e.shift();t=t&&e.shift();)for(r in t.props)t.props.hasOwnProperty(r)&&(n.props[r]=n.props[r]||t.props[r]);return n},N=function(e){if(a.string(e.compatibility))try{j.compatibility=new Date(e.compatibility)}catch(e){j.compatibility=new Date("2016-11-19"),console.log(T.errors.configurationCompatibilityIsNotValid)}else a.date(e.compatibility)?j.compatibility=e.compatibility:j.compatibility=new Date("2016-11-19")},h=function(){n(P.v20161119,j.compatibility)?(j.rememberValidation=!1,j.memoryPropertName="__blueprints"):(j.rememberValidation=!0,j.memoryPropertName="__interfaces"),j.onError=function(e){console.log(e)}},s.types=["array","blueprint","bool","boolean","date","datetime","decimal","expression","function","money","nullOrWhitespace","number","object","regexp","string","ObjectID"],s.isValidatableProperty=function(e){return!!e&&!!(e.__blueprintId||a.string(e)&&-1<s.types.indexOf(e)||a.string(e.type)&&-1<s.types.indexOf(e.type)||a.regexp(e)||a.function(e.validate))},s.configure=function(e){return N(e=e||{}),h(),a.defined(e.rememberValidation)&&(j.rememberValidation=e.rememberValidation),a.function(e.onError)&&(j.onError=e.onError),l.copyValue(j)},s.configure(),s}"undefined"!=typeof module&&module.exports?module.exports=e({async:require("./async.js"),id:require("./id.js"),is:require("./is.js"),Exception:require("./Exception.js"),objectHelper:require("./objectHelper.js")}):window&&window.polyn?window.polyn.addModule("Blueprint",["async","id","is","Exception","objectHelper"],e):console.log(new Error("[POLYN] Unable to define module: UNKNOWN RUNTIME or POLYN NOT DEFINED"))}(),function(){"use strict";var b={errorTypes:{invalidArgumentException:"InvalidArgumentException",readOnlyViolation:"ReadOnlyViolation"},errors:{initialValidationFailed:"The argument passed to the constructor is not valid",validatePropertyInvalidArgs:"To validate a property, you must provide the instance, and property name"}};function e(e){return new n(e.Blueprint,e.Exception,e.objectHelper,e.is,e.async)}function n(l,t,s,p,i){var d={onError:function(e){console.log(e)}};function n(u){var a,e,c={};if(!u)return new m(new Error("A schema object, and values are required"));for(e in u)u.hasOwnProperty(e)&&"__skipValidation"!==e&&("__skipValdation"===e&&(c.__skipValidation=u.skipValdation),!p.object(u[e])||l.isValidatableProperty(u[e])||u[e].__immutableCtor?c[e]=u[e]:c[e]=new n(u[e]),c[e].__immutableCtor&&(o[e.substring(0,1).toUpperCase()+e.substring(1)]=c[e]));function o(e){var n,r,t,o={};if(e=e||{},!0!==u.__skipValidation&&!l.validate(a,e).result){var i=new m(new Error(b.errors.initialValidationFailed),l.validate(a,e).errors);return d.onError(i),i}try{for(n in c)c.hasOwnProperty(n)&&"__blueprintId"!==n&&(p.nullOrUndefined(e[n])?(r=o,t=n,s.setReadOnlyProperty(r,t,null,y(t))):f(o,c,e,n));Object.freeze(o)}catch(e){return new m(e)}return o}return a=new l(c),r(o,"merge",function(e,n,r){var t;if("function"!=typeof r)return g(o,e,n,function(e,n){t=e||n}),t;i.runAsync(function(){g(o,e,n,r)})}),r(o,"toObject",function(e,n){return s.cloneObject(e,!0,n)}),r(o,"validate",function(e,n){return l.validate(a,e,n)}),r(o,"validateProperty",function(e,n,r){if(!e&&p.function(r))r([b.errors.validatePropertyInvalidArgs],!1);else if(!e)return{errors:[b.errors.validatePropertyInvalidArgs],result:!1};return l.validateProperty(a,n,e[n],r)}),r(o,"log",function(e){e?console.log(o.toObject(e)):console.log(null)}),r(o,"getSchema",function(e){return s.cloneObject(u,!0,e)}),r(o,"blueprint",a),r(o,"__immutableCtor",!0),o}function f(e,n,r,t){var o,i;n[t].__immutableCtor&&p.function(n[t])?(o=n[t],e[t]=new o(r[t])):!function(e){return"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)}(r[t])?(s.setReadOnlyProperty(e,t,s.copyValue(r[t]),y(t)),Array.isArray(r[t])&&Object.freeze(e[t])):(i=new Date(r[t]),Object.defineProperty(e,t,{get:function(){return new Date(i)},enumerable:!0,configurable:!1}),Object.freeze(e[t]))}function y(n){return function(){var e=new t(b.errorTypes.readOnlyViolation,new Error("Cannot set `"+n+"`. This object is immutable"));return d.onError(e),e}}function m(e,n){return new t(b.errorTypes.invalidArgumentException,e,n)}function r(e,n,r){s.setReadOnlyProperty(e,n,r,function(){var e=new t(b.errorTypes.readOnlyViolation,new Error(n+" is read-only"));return d.onError(e),e})}function g(e,n,r,t){var o,i=s.merge(n,r);return i.isException?t(i):(o=new e(i)).isException?t(o):t(null,o)}return n.configure=function(e){e=e||{},p.function(e.onError)&&(d.onError=e.onError)},n}"undefined"!=typeof module&&module.exports?module.exports=e({Blueprint:require("./Blueprint.js"),Exception:require("./Exception.js"),objectHelper:require("./objectHelper.js"),is:require("./is.js"),async:require("./async.js")}):window&&window.polyn?window.polyn.addModule("Immutable",["async","Blueprint","is","Exception","objectHelper"],e):console.log(new Error("[POLYN] Unable to define module: UNKNOWN RUNTIME or POLYN NOT DEFINED"))}();