Comparing version 0.6.1 to 0.6.3
## Changelog | ||
### v0.6.3 | ||
* Add support for `build({ additionalProperties: 'always'})` (#60) | ||
* Add `error.additionalProperties` that specify forbidden property keys (#54) | ||
* Add support for NetSuite (#63) | ||
* Fix schema validation gives a false positive when the type keyword does not specify a valid type string (#52) | ||
* Fix validation error with arrays and oneOf (#55) | ||
* Fix validation error when using the additionalProperties keyword (#56) | ||
* Fix requiredMessage doesnt work when referencing external schema files (#51) | ||
### v0.6.1 | ||
@@ -4,0 +14,0 @@ |
115
dist/jsen.js
/* | ||
* jsen | ||
* https://github.com/bugventure/jsen | ||
* v0.6.3 | ||
* | ||
@@ -174,2 +175,3 @@ * Copyright (c) 2016 Veli Pehlivanov <bugventure@gmail.com> | ||
REGEX_ESCAPE_EXPR = /[\/]/g, | ||
STR_ESCAPE_EXPR = /(")/gim, | ||
VALID_IDENTIFIER_EXPR = /^[a-z_$][0-9a-z]*$/gi, | ||
@@ -200,2 +202,6 @@ INVALID_SCHEMA = 'jsen: invalid schema object', | ||
function encodeStr(str) { | ||
return '"' + str.replace(STR_ESCAPE_EXPR, '\\$1') + '"'; | ||
} | ||
function appendToPath(path, key) { | ||
@@ -206,6 +212,10 @@ VALID_IDENTIFIER_EXPR.lastIndex = 0; | ||
path + '.' + key : | ||
path + '["' + key + '"]'; | ||
path + '[' + encodeStr(key) + ']'; | ||
} | ||
function type(obj) { | ||
if (obj === undefined) { | ||
return 'undefined'; | ||
} | ||
var str = Object.prototype.toString.call(obj); | ||
@@ -286,3 +296,3 @@ return str.substr(8, str.length - 9).toLowerCase(); | ||
if (enumType === 'string') { | ||
clauses.push(context.path + ' === "' + value + '"'); | ||
clauses.push(context.path + ' === ' + encodeStr(value)); | ||
} | ||
@@ -429,3 +439,3 @@ else { | ||
if (type(context.schema.items) === 'object') { | ||
context.code('for (' + index + '; ' + index + ' < ' + context.path + '.length; ' + index + '++) {'); | ||
context.code('for (' + index + ' = 0; ' + index + ' < ' + context.path + '.length; ' + index + '++) {'); | ||
@@ -546,3 +556,3 @@ context.validate(context.path + '[' + index + ']', context.schema.items, context.noFailFast); | ||
context.code('for (' + n + '; ' + n + ' < ' + keys + '.length; ' + n + '++) {') | ||
context.code('for (' + n + ' = 0; ' + n + ' < ' + keys + '.length; ' + n + '++) {') | ||
(key + ' = ' + keys + '[' + n + ']') | ||
@@ -562,3 +572,3 @@ | ||
context.code((i ? 'else ' : '') + 'if (' + key + ' === "' + propKey + '") {'); | ||
context.code((i ? 'else ' : '') + 'if (' + key + ' === ' + encodeStr(propKey) + ') {'); | ||
@@ -595,3 +605,3 @@ if (addPropsCheck) { | ||
// do not allow additional properties | ||
context.error('additionalProperties'); | ||
context.error('additionalProperties', undefined, key); | ||
} | ||
@@ -693,2 +703,3 @@ else { | ||
context.code(initialCount + ' = errors.length'); | ||
context.code(matching + ' = 0'); | ||
@@ -891,13 +902,15 @@ for (; i < context.schema.oneOf.length; i++) { | ||
for (key in def) { | ||
if (!(key in schema.properties) && | ||
(schema.additionalProperties === false || | ||
(additional === false && !schema.additionalProperties))) { | ||
if (additional !== 'always') { | ||
for (key in def) { | ||
if (!(key in schema.properties) && | ||
(schema.additionalProperties === false || | ||
(additional === false && !schema.additionalProperties))) { | ||
if (parentMarker) { | ||
parentMarker.mark(def, key); | ||
if (parentMarker) { | ||
parentMarker.mark(def, key); | ||
} | ||
else { | ||
delete def[key]; | ||
} | ||
} | ||
else { | ||
delete def[key]; | ||
} | ||
} | ||
@@ -997,2 +1010,3 @@ } | ||
var context, | ||
encodedFormat, | ||
cachedRef, | ||
@@ -1007,54 +1021,33 @@ pathExp, | ||
function error(keyword, key) { | ||
var varid, | ||
errorPath = path, | ||
message = (key && schema.properties && schema.properties[key] && schema.properties[key].requiredMessage) || | ||
schema.invalidMessage; | ||
function error(keyword, key, additional) { | ||
var errorPath = path, | ||
res = key && schema.properties && schema.properties[key] ? | ||
resolver.resolve(schema.properties[key]) : null, | ||
message = res ? res.requiredMessage : schema.invalidMessage; | ||
if (!message) { | ||
message = key && schema.properties && schema.properties[key] && schema.properties[key].messages && | ||
schema.properties[key].messages[keyword] || | ||
schema.messages && schema.messages[keyword]; | ||
message = (res && res.messages && res.messages[keyword]) || | ||
(schema.messages && schema.messages[keyword]); | ||
} | ||
if (path.indexOf('[') > -1) { | ||
// create error objects dynamically when path contains indexed property expressions | ||
errorPath = getPathExpression(path); | ||
errorPath = path.indexOf('[') > -1 ? getPathExpression(path) : encodeStr(errorPath.substr(5)); | ||
if (key) { | ||
errorPath = errorPath ? errorPath + ' + ".' + key + '"' : key; | ||
} | ||
if (key) { | ||
errorPath = errorPath !== '""' ? errorPath + ' + ".' + key + '"' : encodeStr(key); | ||
} | ||
code('errors.push({') | ||
('path: ' + errorPath + ', ') | ||
('keyword: "' + keyword + '"' + (message ? ',' : '')); | ||
code('errors.push({'); | ||
if (message) { | ||
code('message: "' + message + '"'); | ||
} | ||
if (message) { | ||
code('message: ' + encodeStr(message) + ','); | ||
} | ||
code('})'); | ||
if (additional) { | ||
code('additionalProperties: ' + additional + ','); | ||
} | ||
else { | ||
// generate faster code when no indexed properties in the path | ||
varid = id(); | ||
errorPath = errorPath.substr(5); | ||
code('path: ' + errorPath + ', ') | ||
('keyword: ' + encodeStr(keyword)) | ||
('})'); | ||
if (key) { | ||
errorPath = errorPath ? errorPath + '.' + key : key; | ||
} | ||
refs[varid] = { | ||
path: errorPath, | ||
keyword: keyword | ||
}; | ||
if (message) { | ||
refs[varid].message = message; | ||
} | ||
code('errors.push(refs.' + varid + ')'); | ||
} | ||
if (!noFailFast && !options.greedy) { | ||
@@ -1132,3 +1125,5 @@ code('return (validate.errors = errors) && false'); | ||
code('if (!formats["' + schema.format + '"](' + context.path + ', schemas["' + schema.format + '"])) {'); | ||
encodedFormat = encodeStr(schema.format); | ||
code('if (!formats[' + encodedFormat + '](' + context.path + ', schemas[' + encodedFormat + '])) {'); | ||
error('format'); | ||
@@ -1194,6 +1189,3 @@ code('}'); | ||
"simpleTypes": { | ||
"anyOf": [ | ||
{ "enum": [ "array", "boolean", "integer", "null", "number", "object", "string", "any" ] }, | ||
{ "type": "string" } | ||
] | ||
"enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ] | ||
}, | ||
@@ -1330,3 +1322,2 @@ "stringArray": { | ||
} | ||
},{}],7:[function(require,module,exports){ | ||
@@ -1333,0 +1324,0 @@ 'use strict'; |
/* | ||
* jsen | ||
* https://github.com/bugventure/jsen | ||
* v0.6.3 | ||
* | ||
@@ -9,2 +10,2 @@ * Copyright (c) 2016 Veli Pehlivanov <bugventure@gmail.com> | ||
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.jsen=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){b.exports=a("./lib/jsen.js")},{"./lib/jsen.js":5}],2:[function(a,b,c){"use strict";function d(a){var b=Object.prototype.toString.call(a);return b.substr(8,b.length-9).toLowerCase()}function e(a,b){var c,d,e=Object.keys(a).sort(),g=Object.keys(b).sort();if(!f(e,g))return!1;for(c=0;c<e.length;c++)if(d=e[c],!f(a[d],b[d]))return!1;return!0}function f(a,b){var c,g=typeof a,h=typeof b;if("object"===g&&(g=d(a)),"object"===h&&(h=d(b)),g!==h)return!1;if("object"===g)return e(a,b);if("regexp"===g)return a.toString()===b.toString();if("array"===g){if(a.length!==b.length)return!1;for(c=0;c<a.length;c++)if(!f(a[c],b[c]))return!1;return!0}return a===b}b.exports=f},{}],3:[function(a,b,c){"use strict";var d={};d["date-time"]=/(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/,d.uri=/^([a-zA-Z][a-zA-Z0-9+-.]*:){0,1}\/\/[^\s]*$/,d.email=/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,d.ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,d.ipv6=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|[fF][eE]80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::([fF]{4}(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,d.hostname=/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$/,b.exports=d},{}],4:[function(a,b,c){"use strict";b.exports=function(){var a=arguments[0]||"",b=[].join.call([].slice.call(arguments,1),", "),c="",d="",e=1,f=" ",g="{[",h="}]",i=function(){return new Array(e+1).join(f)},j=function(a){c+=i()+a+"\n"},k=function(a){var b=a[0],c=a[a.length-1];return h.indexOf(b)>-1&&g.indexOf(c)>-1?(e--,j(a),e++):g.indexOf(c)>-1?(j(a),e++):h.indexOf(b)>-1?(e--,j(a)):j(a),k};return k.def=function(a,b){return d+=i()+"var "+a+(void 0!==b?" = "+b:"")+"\n",k},k.toSource=function(){return"function "+a+"("+b+") {\n"+d+"\n"+c+"\n}"},k.compile=function(a){var b="return ("+k.toSource()+")",c=a||{},d=Object.keys(c),e=d.map(function(a){return c[a]});return Function.apply(null,d.concat(b)).apply(null,e)},k}},{}],5:[function(a,b,c){(function(c){"use strict";function d(a){var b=a instanceof RegExp?a.toString():new RegExp(a).toString();return u?(b=b.substr(1,b.length-2),b="/"+b.replace(q,"\\$&")+"/"):b}function e(a,b){return r.lastIndex=0,r.test(b)?a+"."+b:a+'["'+b+'"]'}function f(a){var b=Object.prototype.toString.call(a);return b.substr(8,b.length-9).toLowerCase()}function g(a){return(0|a)===a}function h(a){var b,c,d=Object.keys(a),e=[],f={};for(c=0;c<d.length;c++)b=B[d[c]],b&&(b.type?(f[b.type]||(f[b.type]=[]),f[b.type].push(b)):e.push(b));return e.concat(Object.keys(f).reduce(function(a,b){return a.concat(f[b])},[]))}function i(a){var b=a.replace(p,"$1");return isNaN(+b)?'"'===b[0]?'[\\"'+b.substr(1,b.length-2)+'\\"]':'." + '+b+' + "':"."+b}function j(a){return'"'+a.replace(o,i).substr(5)+'"'}function k(a){var b,c,d=a,e=f(a);if("object"===e){d={};for(b in a)d[b]=k(a[b])}else if("array"===e)for(d=[],c=0;c<a.length;c++)d[c]=k(a[c]);else{if("regexp"===e)return new RegExp(a);if("date"===e)return new Date(a.toJSON())}return d}function l(){this.objects=[],this.properties=[]}function m(a,b,c,d,e){var g,h,i,j,n;if("object"!==f(a))return b;if(a=d.resolve(a),void 0===b&&a.hasOwnProperty("default")&&(b=k(a["default"])),g=f(b),"object"===g&&"object"===f(a.properties)){for(i in a.properties)h=m(a.properties[i],b[i],c,d),void 0!==h&&(b[i]=h);for(i in b)i in a.properties||a.additionalProperties!==!1&&(c!==!1||a.additionalProperties)||(e?e.mark(b,i):delete b[i])}else if("array"===g&&a.items){if("array"===f(a.items))for(j=0;j<a.items.length;j++)h=m(a.items[j],b[j],c,d),(void 0!==h||j<b.length)&&(b[j]=h);else if(b.length)for(j=0;j<b.length;j++)b[j]=m(a.items,b[j],c,d)}else if("array"===f(a.allOf)&&a.allOf.length){for(n=new l,j=0;j<a.allOf.length;j++)b=m(a.allOf[j],b,c,d,n);n.deleteDuplicates(),n.dispose()}return b}function n(a,b){function c(a){var b,c=l.resolve(a),d=a.$ref,f=p[d];return f||(f=p[d]={key:o(),func:function(a){return b(a)}},b=e(c),Object.defineProperty(f.func,"errors",{get:function(){return b.errors}}),q[f.key]=f.func),"refs."+f.key}function e(a){function e(a){var b=o();return i.def(b,a),b}function f(a,g,k){function l(c,d){var e,f=a,h=d&&g.properties&&g.properties[d]&&g.properties[d].requiredMessage||g.invalidMessage;h||(h=d&&g.properties&&g.properties[d]&&g.properties[d].messages&&g.properties[d].messages[c]||g.messages&&g.messages[c]),a.indexOf("[")>-1?(f=j(a),d&&(f=f?f+' + ".'+d+'"':d),i("errors.push({")("path: "+f+", ")('keyword: "'+c+'"'+(h?",":"")),h&&i('message: "'+h+'"'),i("})")):(e=o(),f=f.substr(5),d&&(f=f?f+"."+d:d),q[e]={path:f,keyword:c},h&&(q[e].message=h),i("errors.push(refs."+e+")")),k||b.greedy||i("return (validate.errors = errors) && false")}var m,n,p,s,t,u,v,w,x;if(void 0!==g.$ref)return n=c(g),p=j(a),s=e(0),void i("if (!"+n+"("+a+")) {")("if ("+n+".errors) {")("errors.push.apply(errors, "+n+".errors)")("for ("+s+" = 0; "+s+" < "+n+".errors.length; "+s+"++) {")("if ("+n+".errors["+s+"].path) {")("errors[errors.length - "+n+".errors.length + "+s+"].path = "+p+' + "." + '+n+".errors["+s+"].path")("} else {")("errors[errors.length - "+n+".errors.length + "+s+"].path = "+p)("}")("}")("}")("}");for(m={path:a,schema:g,code:i,declare:e,validate:f,error:l,noFailFast:k},v=h(g),x=0;x<v.length;x++)w=v[x],w.type&&t!==w.type&&(t&&i("}"),t=w.type,i("if ("+A[w.type](a)+") {")),w(m);t&&i("}"),g.format&&b.formats&&(u=b.formats[g.format],u&&("string"==typeof u||u instanceof RegExp?(i("if (!("+d(u)+").test("+m.path+")) {"),l("format"),i("}")):"function"==typeof u&&((r.formats||(r.formats={}))[g.format]=u,(r.schemas||(r.schemas={}))[g.format]=g,i('if (!formats["'+g.format+'"]('+m.path+', schemas["'+g.format+'"])) {'),l("format"),i("}"))))}var i=v("validate","data")("var errors = []");return f("data",a),i("return (validate.errors = errors) && errors.length === 0"),g=i.compile(r),g.errors=[],g.build=function(b,c){return m(a,c&&c.copy===!1?b:k(b),c&&c.additionalProperties,l)},g}if("object"!==f(a))throw new Error(s);b=b||{};var g,i=b.missing$Ref||!1,l=new y(a,b.schemas,i),n=0,o=function(){return"i"+n++},p={},q={errors:[]},r={equal:w,unique:x,refs:q};return e(a)}var o=/\[.+?\]/g,p=/\[?(.*?)?\]/,q=/[\/]/g,r=/^[a-z_$][0-9a-z]*$/gi,s="jsen: invalid schema object",t="object"==typeof window&&!!window.navigator,u="object"==typeof c&&"v0"===c.version.split(".")[0],v=a("./func.js"),w=a("./equal.js"),x=a("./unique.js"),y=a("./resolver.js"),z=a("./formats.js"),A={},B={};A["null"]=function(a){return a+" === null"},A["boolean"]=function(a){return"typeof "+a+' === "boolean"'},A.string=function(a){return"typeof "+a+' === "string"'},A.number=function(a){return"typeof "+a+' === "number"'},A.integer=function(a){return"typeof "+a+' === "number" && !('+a+" % 1)"},A.array=function(a){return a+" !== undefined && Array.isArray("+a+")"},A.object=function(a){return a+" !== undefined && typeof "+a+' === "object" && '+a+" !== null && !Array.isArray("+a+")"},A.date=function(a){return a+" !== undefined && "+a+" instanceof Date"},B.type=function(a){if(a.schema.type){var b=Array.isArray(a.schema.type)?a.schema.type:[a.schema.type],c=b.map(function(b){return A[b]?A[b](a.path)||"true":"true"}).join(" || ");c&&(a.code("if (!("+c+")) {"),a.error("type"),a.code("}"))}},B["enum"]=function(a){var b,c,d,e=a.schema["enum"],f=[];if(Array.isArray(e)){for(d=0;d<e.length;d++)b=e[d],c=typeof b,null===b||["boolean","number","string"].indexOf(c)>-1?"string"===c?f.push(a.path+' === "'+b+'"'):f.push(a.path+" === "+b):f.push("equal("+a.path+", "+JSON.stringify(b)+")");a.code("if (!("+f.join(" || ")+")) {"),a.error("enum"),a.code("}")}},B.minimum=function(a){"number"==typeof a.schema.minimum&&(a.code("if ("+a.path+" < "+a.schema.minimum+") {"),a.error("minimum"),a.code("}"))},B.exclusiveMinimum=function(a){a.schema.exclusiveMinimum===!0&&"number"==typeof a.schema.minimum&&(a.code("if ("+a.path+" === "+a.schema.minimum+") {"),a.error("exclusiveMinimum"),a.code("}"))},B.maximum=function(a){"number"==typeof a.schema.maximum&&(a.code("if ("+a.path+" > "+a.schema.maximum+") {"),a.error("maximum"),a.code("}"))},B.exclusiveMaximum=function(a){a.schema.exclusiveMaximum===!0&&"number"==typeof a.schema.maximum&&(a.code("if ("+a.path+" === "+a.schema.maximum+") {"),a.error("exclusiveMaximum"),a.code("}"))},B.multipleOf=function(a){if("number"==typeof a.schema.multipleOf){var b=a.schema.multipleOf,c=b.toString().length-b.toFixed(0).length-1,d=c>0?Math.pow(10,c):1,e=a.path;c>0?a.code("if (+(Math.round(("+e+" * "+d+') + "e+" + '+c+') + "e-" + '+c+") % "+b*d+" !== 0) {"):a.code("if ((("+e+" * "+d+") % "+b*d+") !== 0) {"),a.error("multipleOf"),a.code("}")}},B.minLength=function(a){g(a.schema.minLength)&&(a.code("if ("+a.path+".length < "+a.schema.minLength+") {"),a.error("minLength"),a.code("}"))},B.maxLength=function(a){g(a.schema.maxLength)&&(a.code("if ("+a.path+".length > "+a.schema.maxLength+") {"),a.error("maxLength"),a.code("}"))},B.pattern=function(a){var b="string"==typeof a.schema.pattern?new RegExp(a.schema.pattern):a.schema.pattern;"regexp"===f(b)&&(a.code("if (!("+d(b)+").test("+a.path+")) {"),a.error("pattern"),a.code("}"))},B.format=function(a){"string"==typeof a.schema.format&&z[a.schema.format]&&(a.code("if (!("+z[a.schema.format]+").test("+a.path+")) {"),a.error("format"),a.code("}"))},B.minItems=function(a){g(a.schema.minItems)&&(a.code("if ("+a.path+".length < "+a.schema.minItems+") {"),a.error("minItems"),a.code("}"))},B.maxItems=function(a){g(a.schema.maxItems)&&(a.code("if ("+a.path+".length > "+a.schema.maxItems+") {"),a.error("maxItems"),a.code("}"))},B.additionalItems=function(a){a.schema.additionalItems===!1&&Array.isArray(a.schema.items)&&(a.code("if ("+a.path+".length > "+a.schema.items.length+") {"),a.error("additionalItems"),a.code("}"))},B.uniqueItems=function(a){a.schema.uniqueItems&&(a.code("if (unique("+a.path+").length !== "+a.path+".length) {"),a.error("uniqueItems"),a.code("}"))},B.items=function(a){var b=a.declare(0),c=0;if("object"===f(a.schema.items))a.code("for ("+b+"; "+b+" < "+a.path+".length; "+b+"++) {"),a.validate(a.path+"["+b+"]",a.schema.items,a.noFailFast),a.code("}");else if(Array.isArray(a.schema.items)){for(;c<a.schema.items.length;c++)a.code("if ("+a.path+".length - 1 >= "+c+") {"),a.validate(a.path+"["+c+"]",a.schema.items[c],a.noFailFast),a.code("}");"object"===f(a.schema.additionalItems)&&(a.code("for ("+b+" = "+c+"; "+b+" < "+a.path+".length; "+b+"++) {"),a.validate(a.path+"["+b+"]",a.schema.additionalItems,a.noFailFast),a.code("}"))}},B.maxProperties=function(a){g(a.schema.maxProperties)&&(a.code("if (Object.keys("+a.path+").length > "+a.schema.maxProperties+") {"),a.error("maxProperties"),a.code("}"))},B.minProperties=function(a){g(a.schema.minProperties)&&(a.code("if (Object.keys("+a.path+").length < "+a.schema.minProperties+") {"),a.error("minProperties"),a.code("}"))},B.required=function(a){if(Array.isArray(a.schema.required))for(var b=0;b<a.schema.required.length;b++)a.code("if ("+e(a.path,a.schema.required[b])+" === undefined) {"),a.error("required",a.schema.required[b]),a.code("}")},B.properties=function(a){if(!a.validatedProperties){var b,c,d,g=a.schema.properties,h="object"===f(g)?Object.keys(g):[],i=a.schema.patternProperties,j="object"===f(i)?Object.keys(i):[],k=a.schema.additionalProperties,l=k===!1||"object"===f(k);if(h.length&&!j.length&&!l){for(c=0;c<h.length;c++)b=h[c],d=e(a.path,b),a.code("if ("+d+" !== undefined) {"),a.validate(d,g[b],a.noFailFast),a.code("}");a.validatedProperties=!0}}},B.patternProperties=B.additionalProperties=function(a){if(!a.validatedProperties){var b,c,g,h,i,j,k,l=a.schema.properties,m="object"===f(l)?Object.keys(l):[],n=a.schema.patternProperties,o="object"===f(n)?Object.keys(n):[],p=a.schema.additionalProperties,q=p===!1||"object"===f(p);if(m.length||o.length||q){for(b=a.declare("[]"),c=a.declare('""'),g=a.declare(0),q&&(h=a.declare(!1)),a.code(b+" = Object.keys("+a.path+")"),a.code("for ("+g+"; "+g+" < "+b+".length; "+g+"++) {")(c+" = "+b+"["+g+"]")("if ("+a.path+"["+c+"] === undefined) {")("continue")("}"),q&&a.code(h+" = false"),k=0;k<m.length;k++)i=m[k],a.code((k?"else ":"")+"if ("+c+' === "'+i+'") {'),q&&a.code(h+" = true"),a.validate(e(a.path,i),l[i],a.noFailFast),a.code("}");for(k=0;k<o.length;k++)j=o[k],a.code("if (("+d(j)+").test("+c+")) {"),q&&a.code(h+" = true"),a.validate(a.path+"["+c+"]",n[j],a.noFailFast),a.code("}");q&&(a.code("if (!"+h+") {"),p===!1?a.error("additionalProperties"):a.validate(a.path+"["+c+"]",p,a.noFailFast),a.code("}")),a.code("}"),a.validatedProperties=!0}}},B.dependencies=function(a){if("object"===f(a.schema.dependencies)){var b,c,d=0;for(b in a.schema.dependencies){if(c=a.schema.dependencies[b],a.code("if ("+e(a.path,b)+" !== undefined) {"),"object"===f(c))a.validate(a.path,c,a.noFailFast);else for(d;d<c.length;d++)a.code("if ("+e(a.path,c[d])+" === undefined) {"),a.error("dependencies",c[d]),a.code("}");a.code("}")}}},B.allOf=function(a){if(Array.isArray(a.schema.allOf))for(var b=0;b<a.schema.allOf.length;b++)a.validate(a.path,a.schema.allOf[b],a.noFailFast)},B.anyOf=function(a){if(Array.isArray(a.schema.anyOf)){var b=a.declare(0),c=a.declare(0),d=a.declare(!1),e=0;for(a.code(c+" = errors.length");e<a.schema.anyOf.length;e++)a.code("if (!"+d+") {"),a.code(b+" = errors.length"),a.validate(a.path,a.schema.anyOf[e],!0),a.code(d+" = errors.length === "+b)("}");a.code("if (!"+d+") {"),a.error("anyOf"),a.code("} else {")("errors.length = "+c)("}")}},B.oneOf=function(a){if(Array.isArray(a.schema.oneOf)){var b=a.declare(0),c=a.declare(0),d=a.declare(0),e=0;for(a.code(c+" = errors.length");e<a.schema.oneOf.length;e++)a.code(d+" = errors.length"),a.validate(a.path,a.schema.oneOf[e],!0),a.code("if (errors.length === "+d+") {")(b+"++")("}");a.code("if ("+b+" !== 1) {"),a.error("oneOf"),a.code("} else {")("errors.length = "+c)("}")}},B.not=function(a){if("object"===f(a.schema.not)){var b=a.declare(0);a.code(b+" = errors.length"),a.validate(a.path,a.schema.not,!0),a.code("if (errors.length === "+b+") {"),a.error("not"),a.code("} else {")("errors.length = "+b)("}")}},["minimum","exclusiveMinimum","maximum","exclusiveMaximum","multipleOf"].forEach(function(a){B[a].type="number"}),["minLength","maxLength","pattern","format"].forEach(function(a){B[a].type="string"}),["minItems","maxItems","additionalItems","uniqueItems","items"].forEach(function(a){B[a].type="array"}),["maxProperties","minProperties","required","properties","patternProperties","additionalProperties","dependencies"].forEach(function(a){B[a].type="object"}),l.prototype.mark=function(a,b){var c,d=this.objects.indexOf(a);return 0>d?(this.objects.push(a),c={},c[b]=1,void this.properties.push(c)):(c=this.properties[d],void(c[b]=c[b]?c[b]+1:1))},l.prototype.deleteDuplicates=function(){var a,b;for(b=0;b<this.properties.length;b++)for(a in this.properties[b])this.properties[b][a]>1&&delete this.objects[b][a]},l.prototype.dispose=function(){this.objects.length=0,this.properties.length=0},n.browser=t,n.clone=k,n.equal=w,n.unique=x,n.resolve=y.resolvePointer,b.exports=n}).call(this,a("_process"))},{"./equal.js":2,"./formats.js":3,"./func.js":4,"./resolver.js":7,"./unique.js":8,_process:9}],6:[function(a,b,c){b.exports={id:"http://json-schema.org/draft-04/schema#",$schema:"http://json-schema.org/draft-04/schema#",description:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},positiveInteger:{type:"integer",minimum:0},positiveIntegerDefault0:{allOf:[{$ref:"#/definitions/positiveInteger"},{"default":0}]},simpleTypes:{anyOf:[{"enum":["array","boolean","integer","null","number","object","string","any"]},{type:"string"}]},stringArray:{type:"array",items:{type:"string"},minItems:1,uniqueItems:!0}},type:"object",properties:{id:{type:"string",format:"uri"},$schema:{type:"string",format:"uri"},title:{type:"string"},description:{type:"string"},"default":{},multipleOf:{type:"number",minimum:0,exclusiveMinimum:!0},maximum:{type:"number"},exclusiveMaximum:{type:"boolean","default":!1},minimum:{type:"number"},exclusiveMinimum:{type:"boolean","default":!1},maxLength:{$ref:"#/definitions/positiveInteger"},minLength:{$ref:"#/definitions/positiveIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{anyOf:[{type:"boolean"},{$ref:"#"}],"default":{}},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],"default":{}},maxItems:{$ref:"#/definitions/positiveInteger"},minItems:{$ref:"#/definitions/positiveIntegerDefault0"},uniqueItems:{type:"boolean","default":!1},maxProperties:{$ref:"#/definitions/positiveInteger"},minProperties:{$ref:"#/definitions/positiveIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#"}],"default":{}},definitions:{type:"object",additionalProperties:{$ref:"#"},"default":{}},properties:{type:"object",additionalProperties:{$ref:"#"},"default":{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},"default":{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},"enum":{type:"array",minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},dependencies:{exclusiveMaximum:["maximum"],exclusiveMinimum:["minimum"]},"default":{}}},{}],7:[function(a,b,c){"use strict";function d(a,b){if(!b.length)return a;var c,e=b.shift();return a&&"object"==typeof a&&a.hasOwnProperty(e)&&(c=a[e]),b.length?c&&"object"==typeof c?d(c,b):void 0:c}function e(a){var b,c=a.indexOf("#");return 0!==c?[a]:(a=a.substr(c+1))?(b=a.split("/").map(function(a){return decodeURIComponent(a).replace(/~1/g,"/").replace(/~0/g,"~")}),"/"===a[0]&&b.shift(),b):[]}function f(a,b){return a&&"object"==typeof a?a.id===b?a:Object.keys(a).reduce(function(c,d){return c||f(a[d],b)},void 0):void 0}function g(a){var b,c,d=Object.keys(a),e={};for(c=0;c<d.length;c++)b=d[c],e[b]=new h(a[b]);return e}function h(a,b,c){this.rootSchema=a,this.resolvedRootSchema=null,this.cache={},this.missing$Ref=c,this.resolvers=b&&"object"==typeof b?g(b):null}var i=a("./metaschema.json"),j="jsen: invalid schema reference";h.prototype.resolveRef=function(a){var b,c,g,h=new Error(j+" "+a),k=this.rootSchema,l=this.resolvedRootSchema;if(!a||"string"!=typeof a)throw h;if(a===i.id&&(g=i),void 0===g&&l&&(g=f(l,a)),void 0===g&&(g=f(k,a)),void 0===g&&(c=e(a),l&&(g=d(l,c.slice(0))),void 0===g&&(g=d(k,c.slice(0)))),void 0===g&&c.length&&this.resolvers&&(b=d(this.resolvers,c),b&&(g=b.resolve(b.rootSchema))),void 0===g||"object"!=typeof g){if(!this.missing$Ref)throw h;g={}}return this.cache[a]===g?g:(this.cache[a]=g,void 0!==g.$ref&&(g=this.cache[a]=this.resolveRef(g.$ref)),g)},h.prototype.resolve=function(a){if(!a||"object"!=typeof a)return a;var b=a.$ref,c=this.cache[b];return void 0===b?a:void 0!==c?c:(c=this.resolveRef(b),a===this.rootSchema&&a!==c&&(this.resolvedRootSchema=c),c)},h.resolvePointer=function(a,b){return d(a,e(b))},b.exports=h},{"./metaschema.json":6}],8:[function(a,b,c){"use strict";function d(a,b,c){for(var d=0,e=a.length;e>d;d++)if(c(a[d],b))return d;return-1}var e=a("./equal.js");b.exports=function(a){return a.filter(function(a,b,c){return d(c,a,e)===b})},b.exports.findIndex=d},{"./equal.js":2}],9:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}]},{},[1])(1)}); | ||
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.jsen=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){b.exports=a("./lib/jsen.js")},{"./lib/jsen.js":5}],2:[function(a,b,c){"use strict";function d(a){var b=Object.prototype.toString.call(a);return b.substr(8,b.length-9).toLowerCase()}function e(a,b){var c,d,e=Object.keys(a).sort(),g=Object.keys(b).sort();if(!f(e,g))return!1;for(c=0;c<e.length;c++)if(d=e[c],!f(a[d],b[d]))return!1;return!0}function f(a,b){var c,g=typeof a,h=typeof b;if("object"===g&&(g=d(a)),"object"===h&&(h=d(b)),g!==h)return!1;if("object"===g)return e(a,b);if("regexp"===g)return a.toString()===b.toString();if("array"===g){if(a.length!==b.length)return!1;for(c=0;c<a.length;c++)if(!f(a[c],b[c]))return!1;return!0}return a===b}b.exports=f},{}],3:[function(a,b,c){"use strict";var d={};d["date-time"]=/(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/,d.uri=/^([a-zA-Z][a-zA-Z0-9+-.]*:){0,1}\/\/[^\s]*$/,d.email=/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,d.ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,d.ipv6=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|[fF][eE]80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::([fF]{4}(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,d.hostname=/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$/,b.exports=d},{}],4:[function(a,b,c){"use strict";b.exports=function(){var a=arguments[0]||"",b=[].join.call([].slice.call(arguments,1),", "),c="",d="",e=1,f=" ",g="{[",h="}]",i=function(){return new Array(e+1).join(f)},j=function(a){c+=i()+a+"\n"},k=function(a){var b=a[0],c=a[a.length-1];return h.indexOf(b)>-1&&g.indexOf(c)>-1?(e--,j(a),e++):g.indexOf(c)>-1?(j(a),e++):h.indexOf(b)>-1?(e--,j(a)):j(a),k};return k.def=function(a,b){return d+=i()+"var "+a+(void 0!==b?" = "+b:"")+"\n",k},k.toSource=function(){return"function "+a+"("+b+") {\n"+d+"\n"+c+"\n}"},k.compile=function(a){var b="return ("+k.toSource()+")",c=a||{},d=Object.keys(c),e=d.map(function(a){return c[a]});return Function.apply(null,d.concat(b)).apply(null,e)},k}},{}],5:[function(a,b,c){(function(c){"use strict";function d(a){var b=a instanceof RegExp?a.toString():new RegExp(a).toString();return w?(b=b.substr(1,b.length-2),b="/"+b.replace(r,"\\$&")+"/"):b}function e(a){return'"'+a.replace(s,"\\$1")+'"'}function f(a,b){return t.lastIndex=0,t.test(b)?a+"."+b:a+"["+e(b)+"]"}function g(a){if(void 0===a)return"undefined";var b=Object.prototype.toString.call(a);return b.substr(8,b.length-9).toLowerCase()}function h(a){return(0|a)===a}function i(a){var b,c,d=Object.keys(a),e=[],f={};for(c=0;c<d.length;c++)b=D[d[c]],b&&(b.type?(f[b.type]||(f[b.type]=[]),f[b.type].push(b)):e.push(b));return e.concat(Object.keys(f).reduce(function(a,b){return a.concat(f[b])},[]))}function j(a){var b=a.replace(q,"$1");return isNaN(+b)?'"'===b[0]?'[\\"'+b.substr(1,b.length-2)+'\\"]':'." + '+b+' + "':"."+b}function k(a){return'"'+a.replace(p,j).substr(5)+'"'}function l(a){var b,c,d=a,e=g(a);if("object"===e){d={};for(b in a)d[b]=l(a[b])}else if("array"===e)for(d=[],c=0;c<a.length;c++)d[c]=l(a[c]);else{if("regexp"===e)return new RegExp(a);if("date"===e)return new Date(a.toJSON())}return d}function m(){this.objects=[],this.properties=[]}function n(a,b,c,d,e){var f,h,i,j,k;if("object"!==g(a))return b;if(a=d.resolve(a),void 0===b&&a.hasOwnProperty("default")&&(b=l(a["default"])),f=g(b),"object"===f&&"object"===g(a.properties)){for(i in a.properties)h=n(a.properties[i],b[i],c,d),void 0!==h&&(b[i]=h);if("always"!==c)for(i in b)i in a.properties||a.additionalProperties!==!1&&(c!==!1||a.additionalProperties)||(e?e.mark(b,i):delete b[i])}else if("array"===f&&a.items){if("array"===g(a.items))for(j=0;j<a.items.length;j++)h=n(a.items[j],b[j],c,d),(void 0!==h||j<b.length)&&(b[j]=h);else if(b.length)for(j=0;j<b.length;j++)b[j]=n(a.items,b[j],c,d)}else if("array"===g(a.allOf)&&a.allOf.length){for(k=new m,j=0;j<a.allOf.length;j++)b=n(a.allOf[j],b,c,d,k);k.deleteDuplicates(),k.dispose()}return b}function o(a,b){function c(a){var b,c=m.resolve(a),d=a.$ref,e=q[d];return e||(e=q[d]={key:p(),func:function(a){return b(a)}},b=f(c),Object.defineProperty(e.func,"errors",{get:function(){return b.errors}}),r[e.key]=e.func),"refs."+e.key}function f(a){function f(a){var b=p();return j.def(b,a),b}function g(a,h,l){function n(c,d,f){var g=a,i=d&&h.properties&&h.properties[d]?m.resolve(h.properties[d]):null,n=i?i.requiredMessage:h.invalidMessage;n||(n=i&&i.messages&&i.messages[c]||h.messages&&h.messages[c]),g=a.indexOf("[")>-1?k(a):e(g.substr(5)),d&&(g='""'!==g?g+' + ".'+d+'"':e(d)),j("errors.push({"),n&&j("message: "+e(n)+","),f&&j("additionalProperties: "+f+","),j("path: "+g+", ")("keyword: "+e(c))("})"),l||b.greedy||j("return (validate.errors = errors) && false")}var o,p,q,r,t,u,v,w,x,y;if(void 0!==h.$ref)return q=c(h),r=k(a),t=f(0),void j("if (!"+q+"("+a+")) {")("if ("+q+".errors) {")("errors.push.apply(errors, "+q+".errors)")("for ("+t+" = 0; "+t+" < "+q+".errors.length; "+t+"++) {")("if ("+q+".errors["+t+"].path) {")("errors[errors.length - "+q+".errors.length + "+t+"].path = "+r+' + "." + '+q+".errors["+t+"].path")("} else {")("errors[errors.length - "+q+".errors.length + "+t+"].path = "+r)("}")("}")("}")("}");for(o={path:a,schema:h,code:j,declare:f,validate:g,error:n,noFailFast:l},w=i(h),y=0;y<w.length;y++)x=w[y],x.type&&u!==x.type&&(u&&j("}"),u=x.type,j("if ("+C[x.type](a)+") {")),x(o);u&&j("}"),h.format&&b.formats&&(v=b.formats[h.format],v&&("string"==typeof v||v instanceof RegExp?(j("if (!("+d(v)+").test("+o.path+")) {"),n("format"),j("}")):"function"==typeof v&&((s.formats||(s.formats={}))[h.format]=v,(s.schemas||(s.schemas={}))[h.format]=h,p=e(h.format),j("if (!formats["+p+"]("+o.path+", schemas["+p+"])) {"),n("format"),j("}"))))}var j=x("validate","data")("var errors = []");return g("data",a),j("return (validate.errors = errors) && errors.length === 0"),h=j.compile(s),h.errors=[],h.build=function(b,c){return n(a,c&&c.copy===!1?b:l(b),c&&c.additionalProperties,m)},h}if("object"!==g(a))throw new Error(u);b=b||{};var h,j=b.missing$Ref||!1,m=new A(a,b.schemas,j),o=0,p=function(){return"i"+o++},q={},r={errors:[]},s={equal:y,unique:z,refs:r};return f(a)}var p=/\[.+?\]/g,q=/\[?(.*?)?\]/,r=/[\/]/g,s=/(")/gim,t=/^[a-z_$][0-9a-z]*$/gi,u="jsen: invalid schema object",v="object"==typeof window&&!!window.navigator,w="object"==typeof c&&"v0"===c.version.split(".")[0],x=a("./func.js"),y=a("./equal.js"),z=a("./unique.js"),A=a("./resolver.js"),B=a("./formats.js"),C={},D={};C["null"]=function(a){return a+" === null"},C["boolean"]=function(a){return"typeof "+a+' === "boolean"'},C.string=function(a){return"typeof "+a+' === "string"'},C.number=function(a){return"typeof "+a+' === "number"'},C.integer=function(a){return"typeof "+a+' === "number" && !('+a+" % 1)"},C.array=function(a){return a+" !== undefined && Array.isArray("+a+")"},C.object=function(a){return a+" !== undefined && typeof "+a+' === "object" && '+a+" !== null && !Array.isArray("+a+")"},C.date=function(a){return a+" !== undefined && "+a+" instanceof Date"},D.type=function(a){if(a.schema.type){var b=Array.isArray(a.schema.type)?a.schema.type:[a.schema.type],c=b.map(function(b){return C[b]?C[b](a.path)||"true":"true"}).join(" || ");c&&(a.code("if (!("+c+")) {"),a.error("type"),a.code("}"))}},D["enum"]=function(a){var b,c,d,f=a.schema["enum"],g=[];if(Array.isArray(f)){for(d=0;d<f.length;d++)b=f[d],c=typeof b,null===b||["boolean","number","string"].indexOf(c)>-1?"string"===c?g.push(a.path+" === "+e(b)):g.push(a.path+" === "+b):g.push("equal("+a.path+", "+JSON.stringify(b)+")");a.code("if (!("+g.join(" || ")+")) {"),a.error("enum"),a.code("}")}},D.minimum=function(a){"number"==typeof a.schema.minimum&&(a.code("if ("+a.path+" < "+a.schema.minimum+") {"),a.error("minimum"),a.code("}"))},D.exclusiveMinimum=function(a){a.schema.exclusiveMinimum===!0&&"number"==typeof a.schema.minimum&&(a.code("if ("+a.path+" === "+a.schema.minimum+") {"),a.error("exclusiveMinimum"),a.code("}"))},D.maximum=function(a){"number"==typeof a.schema.maximum&&(a.code("if ("+a.path+" > "+a.schema.maximum+") {"),a.error("maximum"),a.code("}"))},D.exclusiveMaximum=function(a){a.schema.exclusiveMaximum===!0&&"number"==typeof a.schema.maximum&&(a.code("if ("+a.path+" === "+a.schema.maximum+") {"),a.error("exclusiveMaximum"),a.code("}"))},D.multipleOf=function(a){if("number"==typeof a.schema.multipleOf){var b=a.schema.multipleOf,c=b.toString().length-b.toFixed(0).length-1,d=c>0?Math.pow(10,c):1,e=a.path;c>0?a.code("if (+(Math.round(("+e+" * "+d+') + "e+" + '+c+') + "e-" + '+c+") % "+b*d+" !== 0) {"):a.code("if ((("+e+" * "+d+") % "+b*d+") !== 0) {"),a.error("multipleOf"),a.code("}")}},D.minLength=function(a){h(a.schema.minLength)&&(a.code("if ("+a.path+".length < "+a.schema.minLength+") {"),a.error("minLength"),a.code("}"))},D.maxLength=function(a){h(a.schema.maxLength)&&(a.code("if ("+a.path+".length > "+a.schema.maxLength+") {"),a.error("maxLength"),a.code("}"))},D.pattern=function(a){var b="string"==typeof a.schema.pattern?new RegExp(a.schema.pattern):a.schema.pattern;"regexp"===g(b)&&(a.code("if (!("+d(b)+").test("+a.path+")) {"),a.error("pattern"),a.code("}"))},D.format=function(a){"string"==typeof a.schema.format&&B[a.schema.format]&&(a.code("if (!("+B[a.schema.format]+").test("+a.path+")) {"),a.error("format"),a.code("}"))},D.minItems=function(a){h(a.schema.minItems)&&(a.code("if ("+a.path+".length < "+a.schema.minItems+") {"),a.error("minItems"),a.code("}"))},D.maxItems=function(a){h(a.schema.maxItems)&&(a.code("if ("+a.path+".length > "+a.schema.maxItems+") {"),a.error("maxItems"),a.code("}"))},D.additionalItems=function(a){a.schema.additionalItems===!1&&Array.isArray(a.schema.items)&&(a.code("if ("+a.path+".length > "+a.schema.items.length+") {"),a.error("additionalItems"),a.code("}"))},D.uniqueItems=function(a){a.schema.uniqueItems&&(a.code("if (unique("+a.path+").length !== "+a.path+".length) {"),a.error("uniqueItems"),a.code("}"))},D.items=function(a){var b=a.declare(0),c=0;if("object"===g(a.schema.items))a.code("for ("+b+" = 0; "+b+" < "+a.path+".length; "+b+"++) {"),a.validate(a.path+"["+b+"]",a.schema.items,a.noFailFast),a.code("}");else if(Array.isArray(a.schema.items)){for(;c<a.schema.items.length;c++)a.code("if ("+a.path+".length - 1 >= "+c+") {"),a.validate(a.path+"["+c+"]",a.schema.items[c],a.noFailFast),a.code("}");"object"===g(a.schema.additionalItems)&&(a.code("for ("+b+" = "+c+"; "+b+" < "+a.path+".length; "+b+"++) {"),a.validate(a.path+"["+b+"]",a.schema.additionalItems,a.noFailFast),a.code("}"))}},D.maxProperties=function(a){h(a.schema.maxProperties)&&(a.code("if (Object.keys("+a.path+").length > "+a.schema.maxProperties+") {"),a.error("maxProperties"),a.code("}"))},D.minProperties=function(a){h(a.schema.minProperties)&&(a.code("if (Object.keys("+a.path+").length < "+a.schema.minProperties+") {"),a.error("minProperties"),a.code("}"))},D.required=function(a){if(Array.isArray(a.schema.required))for(var b=0;b<a.schema.required.length;b++)a.code("if ("+f(a.path,a.schema.required[b])+" === undefined) {"),a.error("required",a.schema.required[b]),a.code("}")},D.properties=function(a){if(!a.validatedProperties){var b,c,d,e=a.schema.properties,h="object"===g(e)?Object.keys(e):[],i=a.schema.patternProperties,j="object"===g(i)?Object.keys(i):[],k=a.schema.additionalProperties,l=k===!1||"object"===g(k);if(h.length&&!j.length&&!l){for(c=0;c<h.length;c++)b=h[c],d=f(a.path,b),a.code("if ("+d+" !== undefined) {"),a.validate(d,e[b],a.noFailFast),a.code("}");a.validatedProperties=!0}}},D.patternProperties=D.additionalProperties=function(a){if(!a.validatedProperties){var b,c,h,i,j,k,l,m=a.schema.properties,n="object"===g(m)?Object.keys(m):[],o=a.schema.patternProperties,p="object"===g(o)?Object.keys(o):[],q=a.schema.additionalProperties,r=q===!1||"object"===g(q);if(n.length||p.length||r){for(b=a.declare("[]"),c=a.declare('""'),h=a.declare(0),r&&(i=a.declare(!1)),a.code(b+" = Object.keys("+a.path+")"),a.code("for ("+h+" = 0; "+h+" < "+b+".length; "+h+"++) {")(c+" = "+b+"["+h+"]")("if ("+a.path+"["+c+"] === undefined) {")("continue")("}"),r&&a.code(i+" = false"),l=0;l<n.length;l++)j=n[l],a.code((l?"else ":"")+"if ("+c+" === "+e(j)+") {"),r&&a.code(i+" = true"),a.validate(f(a.path,j),m[j],a.noFailFast),a.code("}");for(l=0;l<p.length;l++)k=p[l],a.code("if (("+d(k)+").test("+c+")) {"),r&&a.code(i+" = true"),a.validate(a.path+"["+c+"]",o[k],a.noFailFast),a.code("}");r&&(a.code("if (!"+i+") {"),q===!1?a.error("additionalProperties",void 0,c):a.validate(a.path+"["+c+"]",q,a.noFailFast),a.code("}")),a.code("}"),a.validatedProperties=!0}}},D.dependencies=function(a){if("object"===g(a.schema.dependencies)){var b,c,d=0;for(b in a.schema.dependencies){if(c=a.schema.dependencies[b],a.code("if ("+f(a.path,b)+" !== undefined) {"),"object"===g(c))a.validate(a.path,c,a.noFailFast);else for(d;d<c.length;d++)a.code("if ("+f(a.path,c[d])+" === undefined) {"),a.error("dependencies",c[d]),a.code("}");a.code("}")}}},D.allOf=function(a){if(Array.isArray(a.schema.allOf))for(var b=0;b<a.schema.allOf.length;b++)a.validate(a.path,a.schema.allOf[b],a.noFailFast)},D.anyOf=function(a){if(Array.isArray(a.schema.anyOf)){var b=a.declare(0),c=a.declare(0),d=a.declare(!1),e=0;for(a.code(c+" = errors.length");e<a.schema.anyOf.length;e++)a.code("if (!"+d+") {"),a.code(b+" = errors.length"),a.validate(a.path,a.schema.anyOf[e],!0),a.code(d+" = errors.length === "+b)("}");a.code("if (!"+d+") {"),a.error("anyOf"),a.code("} else {")("errors.length = "+c)("}")}},D.oneOf=function(a){if(Array.isArray(a.schema.oneOf)){var b=a.declare(0),c=a.declare(0),d=a.declare(0),e=0;for(a.code(c+" = errors.length"),a.code(b+" = 0");e<a.schema.oneOf.length;e++)a.code(d+" = errors.length"),a.validate(a.path,a.schema.oneOf[e],!0),a.code("if (errors.length === "+d+") {")(b+"++")("}");a.code("if ("+b+" !== 1) {"),a.error("oneOf"),a.code("} else {")("errors.length = "+c)("}")}},D.not=function(a){if("object"===g(a.schema.not)){var b=a.declare(0);a.code(b+" = errors.length"),a.validate(a.path,a.schema.not,!0),a.code("if (errors.length === "+b+") {"),a.error("not"),a.code("} else {")("errors.length = "+b)("}")}},["minimum","exclusiveMinimum","maximum","exclusiveMaximum","multipleOf"].forEach(function(a){D[a].type="number"}),["minLength","maxLength","pattern","format"].forEach(function(a){D[a].type="string"}),["minItems","maxItems","additionalItems","uniqueItems","items"].forEach(function(a){D[a].type="array"}),["maxProperties","minProperties","required","properties","patternProperties","additionalProperties","dependencies"].forEach(function(a){D[a].type="object"}),m.prototype.mark=function(a,b){var c,d=this.objects.indexOf(a);return 0>d?(this.objects.push(a),c={},c[b]=1,void this.properties.push(c)):(c=this.properties[d],void(c[b]=c[b]?c[b]+1:1))},m.prototype.deleteDuplicates=function(){var a,b;for(b=0;b<this.properties.length;b++)for(a in this.properties[b])this.properties[b][a]>1&&delete this.objects[b][a]},m.prototype.dispose=function(){this.objects.length=0,this.properties.length=0},o.browser=v,o.clone=l,o.equal=y,o.unique=z,o.resolve=A.resolvePointer,b.exports=o}).call(this,a("_process"))},{"./equal.js":2,"./formats.js":3,"./func.js":4,"./resolver.js":7,"./unique.js":8,_process:9}],6:[function(a,b,c){b.exports={id:"http://json-schema.org/draft-04/schema#",$schema:"http://json-schema.org/draft-04/schema#",description:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},positiveInteger:{type:"integer",minimum:0},positiveIntegerDefault0:{allOf:[{$ref:"#/definitions/positiveInteger"},{"default":0}]},simpleTypes:{"enum":["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},minItems:1,uniqueItems:!0}},type:"object",properties:{id:{type:"string",format:"uri"},$schema:{type:"string",format:"uri"},title:{type:"string"},description:{type:"string"},"default":{},multipleOf:{type:"number",minimum:0,exclusiveMinimum:!0},maximum:{type:"number"},exclusiveMaximum:{type:"boolean","default":!1},minimum:{type:"number"},exclusiveMinimum:{type:"boolean","default":!1},maxLength:{$ref:"#/definitions/positiveInteger"},minLength:{$ref:"#/definitions/positiveIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{anyOf:[{type:"boolean"},{$ref:"#"}],"default":{}},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],"default":{}},maxItems:{$ref:"#/definitions/positiveInteger"},minItems:{$ref:"#/definitions/positiveIntegerDefault0"},uniqueItems:{type:"boolean","default":!1},maxProperties:{$ref:"#/definitions/positiveInteger"},minProperties:{$ref:"#/definitions/positiveIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#"}],"default":{}},definitions:{type:"object",additionalProperties:{$ref:"#"},"default":{}},properties:{type:"object",additionalProperties:{$ref:"#"},"default":{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},"default":{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},"enum":{type:"array",minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},dependencies:{exclusiveMaximum:["maximum"],exclusiveMinimum:["minimum"]},"default":{}}},{}],7:[function(a,b,c){"use strict";function d(a,b){if(!b.length)return a;var c,e=b.shift();return a&&"object"==typeof a&&a.hasOwnProperty(e)&&(c=a[e]),b.length?c&&"object"==typeof c?d(c,b):void 0:c}function e(a){var b,c=a.indexOf("#");return 0!==c?[a]:(a=a.substr(c+1))?(b=a.split("/").map(function(a){return decodeURIComponent(a).replace(/~1/g,"/").replace(/~0/g,"~")}),"/"===a[0]&&b.shift(),b):[]}function f(a,b){return a&&"object"==typeof a?a.id===b?a:Object.keys(a).reduce(function(c,d){return c||f(a[d],b)},void 0):void 0}function g(a){var b,c,d=Object.keys(a),e={};for(c=0;c<d.length;c++)b=d[c],e[b]=new h(a[b]);return e}function h(a,b,c){this.rootSchema=a,this.resolvedRootSchema=null,this.cache={},this.missing$Ref=c,this.resolvers=b&&"object"==typeof b?g(b):null}var i=a("./metaschema.json"),j="jsen: invalid schema reference";h.prototype.resolveRef=function(a){var b,c,g,h=new Error(j+" "+a),k=this.rootSchema,l=this.resolvedRootSchema;if(!a||"string"!=typeof a)throw h;if(a===i.id&&(g=i),void 0===g&&l&&(g=f(l,a)),void 0===g&&(g=f(k,a)),void 0===g&&(c=e(a),l&&(g=d(l,c.slice(0))),void 0===g&&(g=d(k,c.slice(0)))),void 0===g&&c.length&&this.resolvers&&(b=d(this.resolvers,c),b&&(g=b.resolve(b.rootSchema))),void 0===g||"object"!=typeof g){if(!this.missing$Ref)throw h;g={}}return this.cache[a]===g?g:(this.cache[a]=g,void 0!==g.$ref&&(g=this.cache[a]=this.resolveRef(g.$ref)),g)},h.prototype.resolve=function(a){if(!a||"object"!=typeof a)return a;var b=a.$ref,c=this.cache[b];return void 0===b?a:void 0!==c?c:(c=this.resolveRef(b),a===this.rootSchema&&a!==c&&(this.resolvedRootSchema=c),c)},h.resolvePointer=function(a,b){return d(a,e(b))},b.exports=h},{"./metaschema.json":6}],8:[function(a,b,c){"use strict";function d(a,b,c){for(var d=0,e=a.length;e>d;d++)if(c(a[d],b))return d;return-1}var e=a("./equal.js");b.exports=function(a){return a.filter(function(a,b,c){return d(c,a,e)===b})},b.exports.findIndex=d},{"./equal.js":2}],9:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}]},{},[1])(1)}); |
108
lib/jsen.js
@@ -6,2 +6,3 @@ 'use strict'; | ||
REGEX_ESCAPE_EXPR = /[\/]/g, | ||
STR_ESCAPE_EXPR = /(")/gim, | ||
VALID_IDENTIFIER_EXPR = /^[a-z_$][0-9a-z]*$/gi, | ||
@@ -32,2 +33,6 @@ INVALID_SCHEMA = 'jsen: invalid schema object', | ||
function encodeStr(str) { | ||
return '"' + str.replace(STR_ESCAPE_EXPR, '\\$1') + '"'; | ||
} | ||
function appendToPath(path, key) { | ||
@@ -38,6 +43,10 @@ VALID_IDENTIFIER_EXPR.lastIndex = 0; | ||
path + '.' + key : | ||
path + '["' + key + '"]'; | ||
path + '[' + encodeStr(key) + ']'; | ||
} | ||
function type(obj) { | ||
if (obj === undefined) { | ||
return 'undefined'; | ||
} | ||
var str = Object.prototype.toString.call(obj); | ||
@@ -118,3 +127,3 @@ return str.substr(8, str.length - 9).toLowerCase(); | ||
if (enumType === 'string') { | ||
clauses.push(context.path + ' === "' + value + '"'); | ||
clauses.push(context.path + ' === ' + encodeStr(value)); | ||
} | ||
@@ -261,3 +270,3 @@ else { | ||
if (type(context.schema.items) === 'object') { | ||
context.code('for (' + index + '; ' + index + ' < ' + context.path + '.length; ' + index + '++) {'); | ||
context.code('for (' + index + ' = 0; ' + index + ' < ' + context.path + '.length; ' + index + '++) {'); | ||
@@ -378,3 +387,3 @@ context.validate(context.path + '[' + index + ']', context.schema.items, context.noFailFast); | ||
context.code('for (' + n + '; ' + n + ' < ' + keys + '.length; ' + n + '++) {') | ||
context.code('for (' + n + ' = 0; ' + n + ' < ' + keys + '.length; ' + n + '++) {') | ||
(key + ' = ' + keys + '[' + n + ']') | ||
@@ -394,3 +403,3 @@ | ||
context.code((i ? 'else ' : '') + 'if (' + key + ' === "' + propKey + '") {'); | ||
context.code((i ? 'else ' : '') + 'if (' + key + ' === ' + encodeStr(propKey) + ') {'); | ||
@@ -427,3 +436,3 @@ if (addPropsCheck) { | ||
// do not allow additional properties | ||
context.error('additionalProperties'); | ||
context.error('additionalProperties', undefined, key); | ||
} | ||
@@ -525,2 +534,3 @@ else { | ||
context.code(initialCount + ' = errors.length'); | ||
context.code(matching + ' = 0'); | ||
@@ -723,13 +733,15 @@ for (; i < context.schema.oneOf.length; i++) { | ||
for (key in def) { | ||
if (!(key in schema.properties) && | ||
(schema.additionalProperties === false || | ||
(additional === false && !schema.additionalProperties))) { | ||
if (additional !== 'always') { | ||
for (key in def) { | ||
if (!(key in schema.properties) && | ||
(schema.additionalProperties === false || | ||
(additional === false && !schema.additionalProperties))) { | ||
if (parentMarker) { | ||
parentMarker.mark(def, key); | ||
if (parentMarker) { | ||
parentMarker.mark(def, key); | ||
} | ||
else { | ||
delete def[key]; | ||
} | ||
} | ||
else { | ||
delete def[key]; | ||
} | ||
} | ||
@@ -829,2 +841,3 @@ } | ||
var context, | ||
encodedFormat, | ||
cachedRef, | ||
@@ -839,54 +852,33 @@ pathExp, | ||
function error(keyword, key) { | ||
var varid, | ||
errorPath = path, | ||
message = (key && schema.properties && schema.properties[key] && schema.properties[key].requiredMessage) || | ||
schema.invalidMessage; | ||
function error(keyword, key, additional) { | ||
var errorPath = path, | ||
res = key && schema.properties && schema.properties[key] ? | ||
resolver.resolve(schema.properties[key]) : null, | ||
message = res ? res.requiredMessage : schema.invalidMessage; | ||
if (!message) { | ||
message = key && schema.properties && schema.properties[key] && schema.properties[key].messages && | ||
schema.properties[key].messages[keyword] || | ||
schema.messages && schema.messages[keyword]; | ||
message = (res && res.messages && res.messages[keyword]) || | ||
(schema.messages && schema.messages[keyword]); | ||
} | ||
if (path.indexOf('[') > -1) { | ||
// create error objects dynamically when path contains indexed property expressions | ||
errorPath = getPathExpression(path); | ||
errorPath = path.indexOf('[') > -1 ? getPathExpression(path) : encodeStr(errorPath.substr(5)); | ||
if (key) { | ||
errorPath = errorPath ? errorPath + ' + ".' + key + '"' : key; | ||
} | ||
if (key) { | ||
errorPath = errorPath !== '""' ? errorPath + ' + ".' + key + '"' : encodeStr(key); | ||
} | ||
code('errors.push({') | ||
('path: ' + errorPath + ', ') | ||
('keyword: "' + keyword + '"' + (message ? ',' : '')); | ||
code('errors.push({'); | ||
if (message) { | ||
code('message: "' + message + '"'); | ||
} | ||
if (message) { | ||
code('message: ' + encodeStr(message) + ','); | ||
} | ||
code('})'); | ||
if (additional) { | ||
code('additionalProperties: ' + additional + ','); | ||
} | ||
else { | ||
// generate faster code when no indexed properties in the path | ||
varid = id(); | ||
errorPath = errorPath.substr(5); | ||
code('path: ' + errorPath + ', ') | ||
('keyword: ' + encodeStr(keyword)) | ||
('})'); | ||
if (key) { | ||
errorPath = errorPath ? errorPath + '.' + key : key; | ||
} | ||
refs[varid] = { | ||
path: errorPath, | ||
keyword: keyword | ||
}; | ||
if (message) { | ||
refs[varid].message = message; | ||
} | ||
code('errors.push(refs.' + varid + ')'); | ||
} | ||
if (!noFailFast && !options.greedy) { | ||
@@ -964,3 +956,5 @@ code('return (validate.errors = errors) && false'); | ||
code('if (!formats["' + schema.format + '"](' + context.path + ', schemas["' + schema.format + '"])) {'); | ||
encodedFormat = encodeStr(schema.format); | ||
code('if (!formats[' + encodedFormat + '](' + context.path + ', schemas[' + encodedFormat + '])) {'); | ||
error('format'); | ||
@@ -967,0 +961,0 @@ code('}'); |
@@ -19,6 +19,3 @@ { | ||
"simpleTypes": { | ||
"anyOf": [ | ||
{ "enum": [ "array", "boolean", "integer", "null", "number", "object", "string", "any" ] }, | ||
{ "type": "string" } | ||
] | ||
"enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ] | ||
}, | ||
@@ -154,2 +151,2 @@ "stringArray": { | ||
"default": {} | ||
} | ||
} |
{ | ||
"name": "jsen", | ||
"version": "0.6.1", | ||
"version": "0.6.3", | ||
"description": "JSON-Schema validator built for speed", | ||
@@ -22,3 +22,3 @@ "author": "Veli Pehlivanov <bugventure@gmail.com>", | ||
"test": "./node_modules/.bin/mocha", | ||
"build": "cat ./lib/header > ./dist/jsen.js && ./node_modules/.bin/browserify index.js -s jsen >> ./dist/jsen.js && ./node_modules/.bin/uglify -s ./dist/jsen.js -o ./dist/jsen.min.temp && cp ./lib/header ./dist/jsen.min.js && cat ./dist/jsen.min.temp >> ./dist/jsen.min.js && rm ./dist/jsen.min.temp", | ||
"build": "sed -e \"s/##VERSION##/v$npm_package_version/g\" ./lib/header > ./dist/jsen.js && ./node_modules/.bin/browserify index.js -s jsen >> ./dist/jsen.js && ./node_modules/.bin/uglify -s ./dist/jsen.js -o ./dist/jsen.min.temp && sed -e \"s/##VERSION##/v$npm_package_version/g\" ./lib/header > ./dist/jsen.min.js && cat ./dist/jsen.min.temp >> ./dist/jsen.min.js && rm ./dist/jsen.min.temp", | ||
"coverage": "./node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage" | ||
@@ -25,0 +25,0 @@ }, |
@@ -248,2 +248,22 @@ JSEN | ||
When the `additionalProperties` keyword fails validation, the respective error object contains a key by the same name, specifying the property name that was found in the validated object, but was fobidden in the schema: | ||
```javascript | ||
var schema = { | ||
properties: { foo: {} }, | ||
additionalProperties: false | ||
} | ||
var validate = jsen(schema); | ||
validate({ foo: 'foo', bar: 'bar' }); // false | ||
console.log(validate.errors); | ||
/* Output: | ||
[ { path: '', | ||
keyword: 'additionalProperties', | ||
additionalProperties: 'bar' } ] | ||
*/ | ||
``` | ||
The errors array is replaced on every call of the validator function. You can safely modify the array without affecting successive validation runs. | ||
@@ -499,2 +519,18 @@ | ||
In some scenarios, you may want to disallow additional properties in the schema, but still keep them when gathering default values with `build()`. This may be required, for example, when you want to explicitly fail validation and display a message to the user, listing any excessive properties that are forbidden by the schema. Setting `{ additionalProperties: 'always' }` will prevent the `build()` function from removing any properties in the initial object. | ||
```javascript | ||
var schema = { | ||
additionalProperties: false, | ||
properties: { | ||
foo: {} | ||
} | ||
}; | ||
var initial = { foo: 1, bar: 2 }; | ||
var validate = jsen(schema); | ||
var withDefaults = validate.build(initial, { additionalProperties: 'always' }); | ||
// withDefaults has both 'foo' and 'bar' keys | ||
``` | ||
## In-Browser Usage | ||
@@ -507,4 +543,4 @@ | ||
``` | ||
//cdn.rawgit.com/bugventure/jsen/v0.6.1/dist/jsen.js | ||
//cdn.rawgit.com/bugventure/jsen/v0.6.1/dist/jsen.min.js | ||
//cdn.rawgit.com/bugventure/jsen/v0.6.3/dist/jsen.js | ||
//cdn.rawgit.com/bugventure/jsen/v0.6.3/dist/jsen.min.js | ||
``` | ||
@@ -511,0 +547,0 @@ |
@@ -721,3 +721,17 @@ 'use strict'; | ||
}); | ||
it('"always" takes precedence over schema.additionalProperties', function () { | ||
var schema = { | ||
additionalProperties: false, | ||
properties: { | ||
foo: {} | ||
} | ||
}, | ||
initial = { foo: 1, bar: 2 }, | ||
expected = { foo: 1, bar: 2 }, | ||
validate = jsen(schema); | ||
assert.deepEqual(validate.build(initial, { additionalProperties: 'always' }), expected); | ||
}); | ||
}); | ||
}); |
@@ -364,2 +364,46 @@ 'use strict'; | ||
}); | ||
it('adds additionalProperties to object', function () { | ||
var schema = { | ||
type: 'object', | ||
properties: { | ||
a: { | ||
type: 'object', | ||
properties: { | ||
foo: {} | ||
}, | ||
additionalProperties: false | ||
} | ||
} | ||
}, | ||
data = { | ||
a: { | ||
foo: 'foo', | ||
bar: 'bar', | ||
baz: 'baz' | ||
} | ||
}, | ||
validate = jsen(schema), | ||
valid = validate(data); | ||
assert(!valid); | ||
assert.strictEqual(validate.errors.length, 1); | ||
assert.strictEqual(validate.errors[0].path, 'a'); | ||
assert.strictEqual(validate.errors[0].keyword, 'additionalProperties'); | ||
assert.strictEqual(validate.errors[0].additionalProperties, 'bar'); | ||
validate = jsen(schema, { greedy: true }); | ||
valid = validate(data); | ||
assert(!valid); | ||
assert.strictEqual(validate.errors.length, 2); | ||
assert.strictEqual(validate.errors[0].path, 'a'); | ||
assert.strictEqual(validate.errors[0].keyword, 'additionalProperties'); | ||
assert.strictEqual(validate.errors[0].additionalProperties, 'bar'); | ||
assert.strictEqual(validate.errors[1].path, 'a'); | ||
assert.strictEqual(validate.errors[1].keyword, 'additionalProperties'); | ||
assert.strictEqual(validate.errors[1].additionalProperties, 'baz'); | ||
assert.notStrictEqual(validate.errors[0], validate.errors[1]); | ||
}); | ||
}); | ||
@@ -366,0 +410,0 @@ |
@@ -176,2 +176,147 @@ 'use strict'; | ||
}); | ||
it('Fix requiredMessage doesn\'t work with external schema', function () { | ||
var personSchema = { | ||
$schema: 'http://json-schema.org/draft-04/schema#', | ||
type: 'object', | ||
properties: { | ||
name: { | ||
$ref: '#/name' | ||
} | ||
}, | ||
required: ['name'] | ||
}, | ||
definitions = { | ||
$schema: 'http://json-schema.org/draft-04/schema#', | ||
name: { | ||
type: 'string', | ||
maxLength: 100, | ||
pattern: '^[a-zA-Z]+$', | ||
invalidMessage: 'Error: Name is invalid - must be <= 100 in length and contain alphabetic characters only', | ||
requiredMessage: 'Error: Missing name' | ||
} | ||
}, | ||
validate = jsen(personSchema, { schemas: definitions }), | ||
valid = validate({}); | ||
assert(!valid); | ||
assert.strictEqual(validate.errors[0].message, definitions.name.requiredMessage); | ||
valid = validate({ name: '123' }); | ||
assert(!valid); | ||
assert.strictEqual(validate.errors[0].message, definitions.name.invalidMessage); | ||
}); | ||
it('Fix validation error when usign additionalProperties (#56)', function () { | ||
var schema = { | ||
$schema: 'http://json-schema.org/draft-04/schema#', | ||
type: 'object', | ||
additionalProperties: { | ||
type: 'object', | ||
properties: { | ||
label: { | ||
type: 'string' | ||
} | ||
}, | ||
additionalProperties: false | ||
} | ||
}, | ||
data = { | ||
one: { label: '1' }, | ||
two: { number: '2' } | ||
}, | ||
validate = jsen(schema); | ||
assert(!validate(data)); | ||
data = { | ||
one: { number: '1' }, | ||
two: { label: '2' } | ||
}; | ||
assert(!validate(data)); | ||
}); | ||
it('Fix validation error with arrays and oneOf (#55)', function () { | ||
var schema = { | ||
$schema: 'http://json-schema.org/draft-04/schema#', | ||
type: 'object', | ||
definitions: { | ||
array_of_elements: { | ||
properties: { | ||
the_array: { | ||
type: 'array', | ||
items: { | ||
oneOf: [ | ||
{ $ref: '#/definitions/element_of_type_one' }, | ||
{ $ref: '#/definitions/element_of_type_two' } | ||
] | ||
} | ||
} | ||
} | ||
}, | ||
element_of_type_one: { | ||
type: 'object', | ||
properties: { | ||
type: { | ||
enum: ['one'] | ||
} | ||
} | ||
}, | ||
element_of_type_two: { | ||
type: 'object', | ||
properties: { | ||
type: { | ||
enum: ['two'] | ||
} | ||
} | ||
} | ||
}, | ||
$ref: '#/definitions/array_of_elements' | ||
}, | ||
data = { | ||
the_array: [ | ||
{ type: 'two' }, | ||
{ type: 'one' } | ||
] | ||
}, | ||
validate = jsen(schema); | ||
assert(validate(data)); | ||
}); | ||
it('Fix validation error with arrays and oneOf no.2 (#55)', function () { | ||
var schema = { | ||
definitions: { | ||
myObjectDef: { | ||
type: 'number' | ||
} | ||
}, | ||
type: 'array', | ||
items: { | ||
oneOf: [ | ||
{ $ref: '#/definitions/myObjectDef' }, | ||
{ type: 'string' } | ||
] | ||
} | ||
}, | ||
data = [ | ||
123, | ||
'abc' | ||
], | ||
validate = jsen(schema); | ||
assert(validate(data)); | ||
}); | ||
it('Fix schema validation gives a false positive when the type keyword does not specify a valid type string (#52)', function () { | ||
var schema = { | ||
properties:{ | ||
foo: { type: 'bar' } | ||
} | ||
}, | ||
validateSchema = jsen({ $ref: 'http://json-schema.org/draft-04/schema#' }); | ||
assert(!validateSchema(schema)); | ||
}); | ||
}); |
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
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
278773
6038
614