├── .gitignore ├── LICENSE ├── README.md ├── docs ├── fonts │ ├── OpenSans-Bold-webfont.eot │ ├── OpenSans-Bold-webfont.svg │ ├── OpenSans-Bold-webfont.woff │ ├── OpenSans-BoldItalic-webfont.eot │ ├── OpenSans-BoldItalic-webfont.svg │ ├── OpenSans-BoldItalic-webfont.woff │ ├── OpenSans-Italic-webfont.eot │ ├── OpenSans-Italic-webfont.svg │ ├── OpenSans-Italic-webfont.woff │ ├── OpenSans-Light-webfont.eot │ ├── OpenSans-Light-webfont.svg │ ├── OpenSans-Light-webfont.woff │ ├── OpenSans-LightItalic-webfont.eot │ ├── OpenSans-LightItalic-webfont.svg │ ├── OpenSans-LightItalic-webfont.woff │ ├── OpenSans-Regular-webfont.eot │ ├── OpenSans-Regular-webfont.svg │ └── OpenSans-Regular-webfont.woff ├── index.html ├── is.__validationUnit.html ├── is.html ├── is.js.html ├── scripts │ ├── linenumber.js │ └── prettify │ │ ├── Apache-License-2.0.txt │ │ ├── lang-css.js │ │ └── prettify.js └── styles │ ├── jsdoc-default.css │ ├── prettify-jsdoc.css │ └── prettify-tomorrow.css ├── is.js ├── package-lock.json ├── package.json └── tests.js /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/windows,macos,linux,visualstudiocode,vscode,sublimetext,node 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=windows,macos,linux,visualstudiocode,vscode,sublimetext,node 4 | 5 | ### Linux ### 6 | *~ 7 | 8 | # temporary files which can be created if a process still has a handle open of a deleted file 9 | .fuse_hidden* 10 | 11 | # KDE directory preferences 12 | .directory 13 | 14 | # Linux trash folder which might appear on any partition or disk 15 | .Trash-* 16 | 17 | # .nfs files are created when an open file is removed but is still being accessed 18 | .nfs* 19 | 20 | ### macOS ### 21 | # General 22 | .DS_Store 23 | .AppleDouble 24 | .LSOverride 25 | 26 | # Icon must end with two \r 27 | Icon 28 | 29 | 30 | # Thumbnails 31 | ._* 32 | 33 | # Files that might appear in the root of a volume 34 | .DocumentRevisions-V100 35 | .fseventsd 36 | .Spotlight-V100 37 | .TemporaryItems 38 | .Trashes 39 | .VolumeIcon.icns 40 | .com.apple.timemachine.donotpresent 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | 49 | ### Node ### 50 | # Logs 51 | logs 52 | *.log 53 | npm-debug.log* 54 | yarn-debug.log* 55 | yarn-error.log* 56 | lerna-debug.log* 57 | 58 | # Diagnostic reports (https://nodejs.org/api/report.html) 59 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 60 | 61 | # Runtime data 62 | pids 63 | *.pid 64 | *.seed 65 | *.pid.lock 66 | 67 | # Directory for instrumented libs generated by jscoverage/JSCover 68 | lib-cov 69 | 70 | # Coverage directory used by tools like istanbul 71 | coverage 72 | *.lcov 73 | 74 | # nyc test coverage 75 | .nyc_output 76 | 77 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 78 | .grunt 79 | 80 | # Bower dependency directory (https://bower.io/) 81 | bower_components 82 | 83 | # node-waf configuration 84 | .lock-wscript 85 | 86 | # Compiled binary addons (https://nodejs.org/api/addons.html) 87 | build/Release 88 | 89 | # Dependency directories 90 | node_modules/ 91 | jspm_packages/ 92 | 93 | # TypeScript v1 declaration files 94 | typings/ 95 | 96 | # TypeScript cache 97 | *.tsbuildinfo 98 | 99 | # Optional npm cache directory 100 | .npm 101 | 102 | # Optional eslint cache 103 | .eslintcache 104 | 105 | # Optional stylelint cache 106 | .stylelintcache 107 | 108 | # Microbundle cache 109 | .rpt2_cache/ 110 | .rts2_cache_cjs/ 111 | .rts2_cache_es/ 112 | .rts2_cache_umd/ 113 | 114 | # Optional REPL history 115 | .node_repl_history 116 | 117 | # Output of 'npm pack' 118 | *.tgz 119 | 120 | # Yarn Integrity file 121 | .yarn-integrity 122 | 123 | # dotenv environment variables file 124 | .env 125 | .env.test 126 | .env*.local 127 | 128 | # parcel-bundler cache (https://parceljs.org/) 129 | .cache 130 | .parcel-cache 131 | 132 | # Next.js build output 133 | .next 134 | 135 | # Nuxt.js build / generate output 136 | .nuxt 137 | dist 138 | 139 | # Gatsby files 140 | .cache/ 141 | # Comment in the public line in if your project uses Gatsby and not Next.js 142 | # https://nextjs.org/blog/next-9-1#public-directory-support 143 | # public 144 | 145 | # vuepress build output 146 | .vuepress/dist 147 | 148 | # Serverless directories 149 | .serverless/ 150 | 151 | # FuseBox cache 152 | .fusebox/ 153 | 154 | # DynamoDB Local files 155 | .dynamodb/ 156 | 157 | # TernJS port file 158 | .tern-port 159 | 160 | # Stores VSCode versions used for testing VSCode extensions 161 | .vscode-test 162 | 163 | ### SublimeText ### 164 | # Cache files for Sublime Text 165 | *.tmlanguage.cache 166 | *.tmPreferences.cache 167 | *.stTheme.cache 168 | 169 | # Workspace files are user-specific 170 | *.sublime-workspace 171 | 172 | # Project files should be checked into the repository, unless a significant 173 | # proportion of contributors will probably not be using Sublime Text 174 | # *.sublime-project 175 | 176 | # SFTP configuration file 177 | sftp-config.json 178 | 179 | # Package control specific files 180 | Package Control.last-run 181 | Package Control.ca-list 182 | Package Control.ca-bundle 183 | Package Control.system-ca-bundle 184 | Package Control.cache/ 185 | Package Control.ca-certs/ 186 | Package Control.merged-ca-bundle 187 | Package Control.user-ca-bundle 188 | oscrypto-ca-bundle.crt 189 | bh_unicode_properties.cache 190 | 191 | # Sublime-github package stores a github token in this file 192 | # https://packagecontrol.io/packages/sublime-github 193 | GitHub.sublime-settings 194 | 195 | ### VisualStudioCode ### 196 | .vscode/* 197 | !.vscode/tasks.json 198 | !.vscode/launch.json 199 | *.code-workspace 200 | 201 | ### VisualStudioCode Patch ### 202 | # Ignore all local history of files 203 | .history 204 | .ionide 205 | 206 | ### vscode ### 207 | !.vscode/settings.json 208 | !.vscode/extensions.json 209 | 210 | ### Windows ### 211 | # Windows thumbnail cache files 212 | Thumbs.db 213 | Thumbs.db:encryptable 214 | ehthumbs.db 215 | ehthumbs_vista.db 216 | 217 | # Dump file 218 | *.stackdump 219 | 220 | # Folder config file 221 | [Dd]esktop.ini 222 | 223 | # Recycle Bin used on file shares 224 | $RECYCLE.BIN/ 225 | 226 | # Windows Installer files 227 | *.cab 228 | *.msi 229 | *.msix 230 | *.msm 231 | *.msp 232 | 233 | # Windows shortcuts 234 | *.lnk 235 | 236 | # End of https://www.toptal.com/developers/gitignore/api/windows,macos,linux,visualstudiocode,vscode,sublimetext,node 237 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Laszlo Boros 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Fluent JSON validator 2 | 3 | * [**GitHub repository**](https://github.com/Semmu/fluent-json-validator) 4 | * [**Online API docs**](https://semmu.github.io/fluent-json-validator) 5 | * [**NPM package site**](https://www.npmjs.com/package/fluent-json-validator) 6 | 7 | An easy-to-use, expressive, and composable JSON object validator, with a fluent builder pattern interface! 8 | 9 | ```javascript 10 | // this is what you want to validate: 11 | // coming from the user, read from a file, sent back by some API, etc. 12 | const person = { 13 | name: 'John Doe', 14 | age: 42, 15 | hobbies: ['eating', 'coding', 'sleeping'], 16 | favoriteNumberOrColor: 'green' 17 | }; 18 | 19 | // this is the structure you want your data to have: 20 | const personSchema = is.Object({ 21 | name: is.String(), 22 | nickname: is.optional().String(), 23 | // ^ nickname may be missing, but if not, it must be a string. 24 | age: is.Number().Which( 25 | age => age > 10 26 | // ^ age must be more than 10. 27 | ), 28 | hobbies: is.ArrayOf( 29 | is.String().Which( 30 | hobby => hobby !== 'illegal activities' 31 | // ^ hobbies can't include illegal activities! 32 | ) 33 | ), 34 | favoriteNumberOrColor: is.OneOf([is.Number(), is.String()]) 35 | }); 36 | 37 | // and this is how you check if it matches or not: 38 | personSchema.validate(person); // == true 39 | ``` 40 | 41 | 42 | ## Features 43 | 44 | * Lightweight, since it has **no dependencies!** 45 | * Has a **small and simple API**, only a handful of methods. 46 | * Can validate **primitive types, arrays** (`is.ArrayOf`) and even **variable types** (`is.OneOf`)! 47 | * Can validate **any arbitrary JSON object structure**, just mix'n'match the needed validators (`is.Object`)! 48 | * Schemas are **reusable and composable** for validating complex data structures painlessly! 49 | * Can be used for **formal**1 and **functional**1 validation as well (`is.Which`)! 50 | 51 | 1: I may be using slightly incorrect words, but by formal validation I mean _the subject has the desired structure_, and by functional validation I mean _the subject itself also satisfies additional arbitrary requirements_. 52 | 53 | 54 | ## Installation 55 | 56 | ```bash 57 | npm install fluent-json-validator 58 | ``` 59 | 60 | 61 | ## Usage / how-to / tutorial 62 | 63 | First, of course you need to import the library itself: 64 | 65 | ```javascript 66 | import { is } from 'fluent-json-validator' 67 | ``` 68 | 69 | Then you can create validators like this: 70 | 71 | ```javascript 72 | const stringValidator = is.String(); 73 | ``` 74 | 75 | These validators can then validate objects passed to them like this: 76 | 77 | ```javascript 78 | stringValidator.validate('some string') // true 79 | stringValidator.validate(42) // false 80 | ``` 81 | 82 | Of course this whole expression can be written on one single line if you prefer compact solutions: 83 | 84 | ```javascript 85 | is.String().validate('some string') // still true 86 | is.String().validate(42) // still false 87 | ``` 88 | 89 | If some data may not be present, you can use optional validators, which accept missing/undefined data: 90 | 91 | ```javascript 92 | const isOptionalNumber = is.optional().Number() // or is.Number().optional() 93 | 94 | isOptionalNumber.validate(42) // true 95 | isOptionalNumber.validate() // true 96 | isOptionalNumber.validate('NaN') // false 97 | ``` 98 | 99 | As for primitive data types, we have validators for strings, numbers and booleans: 100 | 101 | ```javascript 102 | const stringValidator = is.String() 103 | const numberValidator = is.Number() 104 | const boolValidator = is.Boolean() 105 | 106 | stringValidator.validate('more string') // true 107 | numberValidator.validate(42) // true 108 | boolValidator.validate(true) // true 109 | ``` 110 | 111 | And for complex/compound data types, i.e. objects, we have the object validator: 112 | 113 | ```javascript 114 | const objectValidator = is.Object({ 115 | someKey: is.String() 116 | }) 117 | ``` 118 | 119 | This object validator needs a parameter which describes the desired schema of the subject. It must contain the same properties as the subject you want to validate, and it must be made up of other validators. 120 | 121 | Using this is very similar to the primitive data type validators: 122 | 123 | ```javascript 124 | const someObject = { 125 | someKey: 'this is some string' 126 | } 127 | 128 | objectValidator.validate(someObject) // true 129 | 130 | const otherObject = { 131 | someKey: 42 132 | } 133 | 134 | objectValidator.validate(otherObject) // false 135 | ``` 136 | 137 | (Of course the above expressions can be written on one line as well. Excercise left for the reader.) 138 | 139 | For arrays, you can use the array validator: 140 | 141 | ```javascript 142 | const arrayValidator = is.ArrayOf(is.Number()) 143 | ``` 144 | 145 | This one also needs a parameter: a validator, which is going to check all the elements of the array, like this: 146 | 147 | ```javascript 148 | arrayValidator.validate([1, 2, 3]) // true 149 | arrayValidator.validate(['some', 'string']) // false 150 | arrayValidator.validate([1, 2, 'impostor']) // false 151 | ``` 152 | 153 | If you happen to have some data which could have different types, you can validate that as well: 154 | 155 | ```javascript 156 | const variableValidator = is.OneOf([is.String(), is.Number()]) 157 | ``` 158 | 159 | This validator needs an array of validators, and the subject will need to match against at least one of them. 160 | 161 | ```javascript 162 | variableValidator.validate('some string') // true 163 | variableValidator.validate(42) // also true 164 | variableValidator.validate(true) // false 165 | ``` 166 | 167 | Lastly, if you need to check for functional requirements, you can do that too: 168 | 169 | ```javascript 170 | const ageValidator = is.Number().Which(value => value >= 18) 171 | ``` 172 | 173 | It needs a lambda/function as a parameter, which will receive the subject to validate, and must return a boolean. 174 | 175 | Using it does not require anything special: 176 | 177 | ```javascript 178 | ageValidator.validate(18) // true 179 | ageValidator.validate(5) // false 180 | ``` 181 | 182 | And if you need to validate complex data structures, you can compose big validators from smaller ones, like: 183 | 184 | ```javascript 185 | const isPerson = is.Object({ 186 | name: is.String(), 187 | gender: is.optional().String(), 188 | age: is.Number() 189 | }) 190 | 191 | const isLocation = is.Object({ 192 | longitude: is.Number(), 193 | latitude: is.Number() 194 | }) 195 | 196 | // the compound validator. 197 | const isCompany = is.Object({ 198 | owner: isPerson, 199 | employees: is.ArrayOf(isPerson), 200 | location: isLocation 201 | }) 202 | 203 | isCompany.validate({ 204 | owner: { 205 | name: 'John Doe', 206 | gender: 'male', 207 | age: 42 208 | }, 209 | employees: [ 210 | { 211 | name: 'Some Dude', 212 | // note: gender is missing! 213 | age: 18 214 | }, { 215 | name: 'Another Individual', 216 | gender: 'mystery', 217 | age: 99 218 | } 219 | ], 220 | location: { 221 | longitude: 42, 222 | latitude: 3.14 223 | } 224 | }) // true 225 | ``` 226 | 227 | This is actually a very simple example compared to what you can do with this library. 228 | 229 | For example you can have an array of values, in which all of them must meet a functional requirement: 230 | 231 | ```javascript 232 | const diceRolls = is.ArrayOf(is.Number().Which(value => value > 0 && value < 7)) 233 | 234 | diceRolls.validate([1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]) // true 235 | diceRolls.validate([1, 6, 3]) // true 236 | diceRolls.validate([9]) // false 237 | diceRolls.validate(['over 9000']) // false 238 | ``` 239 | 240 | And also you can have a functional requirement which ensures e.g. cross-referencing in complex schemas: 241 | 242 | ```javascript 243 | const isFood = is.Object({ 244 | name: is.String(), 245 | calories: is.Number() 246 | }) 247 | 248 | const validator = is.Object({ 249 | foods: is.ArrayOf(isFood), 250 | favoriteFoodName: is.String() 251 | }).Which(obj => obj.foods.filter(food => food.name == obj.favoriteFoodName).length == 1) 252 | // ^ == there exists one and only one food which has the name of favoriteFoodName. 253 | 254 | console.log(validator.validate({ 255 | foods: [ 256 | { 257 | name: 'apple', 258 | calories: 52 259 | }, 260 | { 261 | name: 'pizza', 262 | calories: 266 263 | } 264 | ], 265 | favoriteFoodName: 'apple' 266 | })) // true 267 | ``` 268 | 269 | In this example above we have a list of foods (with names and calories), and a favorite food, which must exist in the said foods array. 270 | 271 | Also don't forget to check the [countless tests](./tests.js) for inspiration, especially the [complex ones](./tests.js#L285) at the end! 272 | 273 | 274 | ## API docs 275 | 276 | In the [`docs/`](docs/) folder and also hosted on [GitHub Pages](https://semmu.github.io/fluent-json-validator). (Don't forget to check the right sidebar of the site!) 277 | 278 | 279 | ## Testing 280 | 281 | Testcases are listed in [`tests.js`](./tests.js). Run them with 282 | ```bash 283 | npm test 284 | ``` 285 | 286 | 287 | ## Note about code quality (?) 288 | 289 | This project most probably does not follow the current Javascript standards and coding style embraced by the global community, thus some people may find the source code weird and/or outright hideous. As I'm not primarily a Javascript developer (and I don't intend to become one) the current implementation is a solution that I could come up with, which works and has the API that I dreamed of. 290 | 291 | If you have ideas how to improve the library internals (without breaking the public API) feel free to open an issue or PR to discuss it! I'm open for improvements and constructive criticism. 292 | 293 | 294 | ## But why? 295 | 296 | Because there is no other JSON object validator with a builder pattern interface like this one. Okay, there is actually [Superstruct](https://www.npmjs.com/package/superstruct), but I didn't know about it when I started developing this, and also it is much-much bigger with many features I personally don't need. 297 | 298 | So I created this library as a smaller alternative. 299 | 300 | 301 | ## License 302 | 303 | MIT 304 | -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Bold-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-Bold-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Bold-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-Bold-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-BoldItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-BoldItalic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-BoldItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-BoldItalic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Italic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-Italic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Italic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-Italic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Light-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-Light-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Light-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-Light-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-LightItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-LightItalic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-LightItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-LightItalic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Regular-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-Regular-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Regular-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Semmu/fluent-json-validator/3f0152bab4e512958f82f0e91fd9e84958768cf5/docs/fonts/OpenSans-Regular-webfont.woff -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Home 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Home

21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |

30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 |
46 |

Fluent JSON validator

47 | 52 |

An easy-to-use, expressive, and composable JSON object validator, with a fluent builder pattern interface!

53 |
// this is what you want to validate:
 54 | // coming from the user, read from a file, sent back by some API, etc.
 55 | const person = {
 56 |     name: 'John Doe',
 57 |     age: 42,
 58 |     hobbies: ['eating', 'coding', 'sleeping'],
 59 |     favoriteNumberOrColor: 'green'
 60 | };
 61 | 
 62 | // this is the structure you want your data to have:
 63 | const personSchema = is.Object({
 64 |     name: is.String(),
 65 |     nickname: is.optional().String(),
 66 |     // ^ nickname may be missing, but if not, it must be a string.
 67 |     age: is.Number().Which(
 68 |         age => age > 10
 69 |         // ^ age must be more than 10.
 70 |     ),
 71 |     hobbies: is.ArrayOf(
 72 |         is.String().Which(
 73 |             hobby => hobby !== 'illegal activities'
 74 |             // ^ hobbies can't include illegal activities!
 75 |         )
 76 |     ),
 77 |     favoriteNumberOrColor: is.OneOf([is.Number(), is.String()])
 78 | });
 79 | 
 80 | // and this is how you check if it matches or not:
 81 | personSchema.validate(person); // == true
 82 | 
83 |

Features

84 |
    85 |
  • Lightweight, since it has no dependencies!
  • 86 |
  • Has a small and simple API, only a handful of methods.
  • 87 |
  • Can validate primitive types, arrays (is.ArrayOf) and even variable types (is.OneOf)!
  • 88 |
  • Can validate any arbitrary JSON object structure, just mix'n'match the needed validators (is.Object)!
  • 89 |
  • Schemas are reusable and composable for validating complex data structures painlessly!
  • 90 |
  • Can be used for formal1 and functional1 validation as well (is.Which)!
  • 91 |
92 |

1: I may be using slightly incorrect words, but by formal validation I mean the subject has the desired structure, and by functional validation I mean the subject itself also satisfies additional arbitrary requirements.

93 |

Installation

94 |
npm install fluent-json-validator
 95 | 
96 |

Usage / how-to / tutorial

97 |

First, of course you need to import the library itself:

98 |
import { is } from 'fluent-json-validator'
 99 | 
100 |

Then you can create validators like this:

101 |
const stringValidator = is.String();
102 | 
103 |

These validators can then validate objects passed to them like this:

104 |
stringValidator.validate('some string') // true
105 | stringValidator.validate(42)            // false
106 | 
107 |

Of course this whole expression can be written on one single line if you prefer compact solutions:

108 |
is.String().validate('some string') // still true
109 | is.String().validate(42)            // still false
110 | 
111 |

If some data may not be present, you can use optional validators, which accept missing/undefined data:

112 |
const isOptionalNumber = is.optional().Number() // or is.Number().optional()
113 | 
114 | isOptionalNumber.validate(42)    // true
115 | isOptionalNumber.validate()      // true
116 | isOptionalNumber.validate('NaN') // false
117 | 
118 |

As for primitive data types, we have validators for strings, numbers and booleans:

119 |
const stringValidator = is.String()
120 | const numberValidator = is.Number()
121 | const boolValidator   = is.Boolean()
122 | 
123 | stringValidator.validate('more string') // true
124 | numberValidator.validate(42)            // true
125 | boolValidator.validate(true)            // true
126 | 
127 |

And for complex/compound data types, i.e. objects, we have the object validator:

128 |
const objectValidator = is.Object({
129 |     someKey: is.String()
130 | })
131 | 
132 |

This object validator needs a parameter which describes the desired schema of the subject. It must contain the same properties as the subject you want to validate, and it must be made up of other validators.

133 |

Using this is very similar to the primitive data type validators:

134 |
const someObject = {
135 |     someKey: 'this is some string'
136 | }
137 | 
138 | objectValidator.validate(someObject) // true
139 | 
140 | const otherObject = {
141 |     someKey: 42
142 | }
143 | 
144 | objectValidator.validate(otherObject) // false
145 | 
146 |

(Of course the above expressions can be written on one line as well. Excercise left for the reader.)

147 |

For arrays, you can use the array validator:

148 |
const arrayValidator = is.ArrayOf(is.Number())
149 | 
150 |

This one also needs a parameter: a validator, which is going to check all the elements of the array, like this:

151 |
arrayValidator.validate([1, 2, 3])          // true
152 | arrayValidator.validate(['some', 'string']) // false
153 | arrayValidator.validate([1, 2, 'impostor']) // false
154 | 
155 |

If you happen to have some data which could have different types, you can validate that as well:

156 |
const variableValidator = is.OneOf([is.String(), is.Number()])
157 | 
158 |

This validator needs an array of validators, and the subject will need to match against at least one of them.

159 |
variableValidator.validate('some string') // true
160 | variableValidator.validate(42)            // also true
161 | variableValidator.validate(true)          // false
162 | 
163 |

Lastly, if you need to check for functional requirements, you can do that too:

164 |
const ageValidator = is.Number().Which(value => value >= 18)
165 | 
166 |

It needs a lambda/function as a parameter, which will receive the subject to validate, and must return a boolean.

167 |

Using it does not require anything special:

168 |
ageValidator.validate(18) // true
169 | ageValidator.validate(5)  // false
170 | 
171 |

And if you need to validate complex data structures, you can compose big validators from smaller ones, like:

172 |
const isPerson = is.Object({
173 |     name:   is.String(),
174 |     gender: is.optional().String(),
175 |     age:    is.Number()
176 | })
177 | 
178 | const isLocation = is.Object({
179 |     longitude: is.Number(),
180 |     latitude:  is.Number()
181 | })
182 | 
183 | // the compound validator.
184 | const isCompany = is.Object({
185 |     owner:     isPerson,
186 |     employees: is.ArrayOf(isPerson),
187 |     location:  isLocation
188 | })
189 | 
190 | isCompany.validate({
191 |     owner: {
192 |         name:   'John Doe',
193 |         gender: 'male',
194 |         age:    42
195 |     },
196 |     employees: [
197 |         {
198 |             name: 'Some Dude',
199 |             // note: gender is missing!
200 |             age:  18
201 |         }, {
202 |             name:   'Another Individual',
203 |             gender: 'mystery',
204 |             age:    99
205 |         }
206 |     ],
207 |     location: {
208 |         longitude: 42,
209 |         latitude:  3.14
210 |     }
211 | }) // true
212 | 
213 |

This is actually a very simple example compared to what you can do with this library.

214 |

For example you can have an array of values, in which all of them must meet a functional requirement:

215 |
const diceRolls = is.ArrayOf(is.Number().Which(value => value > 0 && value < 7))
216 | 
217 | diceRolls.validate([1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]) // true
218 | diceRolls.validate([1, 6, 3])                         // true
219 | diceRolls.validate([9])                               // false
220 | diceRolls.validate(['over 9000'])                     // false
221 | 
222 |

And also you can have a functional requirement which ensures e.g. cross-referencing in complex schemas:

223 |
const isFood = is.Object({
224 |     name: is.String(),
225 |     calories: is.Number()
226 | })
227 | 
228 | const validator = is.Object({
229 |     foods: is.ArrayOf(isFood),
230 |     favoriteFoodName: is.String()
231 | }).Which(obj => obj.foods.filter(food => food.name == obj.favoriteFoodName).length == 1)
232 |          // ^ == there exists one and only one food which has the name of favoriteFoodName.
233 | 
234 | console.log(validator.validate({
235 |     foods: [
236 |         {
237 |             name: 'apple',
238 |             calories: 52
239 |         },
240 |         {
241 |             name: 'pizza',
242 |             calories: 266
243 |         }
244 |     ],
245 |     favoriteFoodName: 'apple'
246 | })) // true
247 | 
248 |

In this example above we have a list of foods (with names and calories), and a favorite food, which must exist in the said foods array.

249 |

Also don't forget to check the countless tests for inspiration, especially the complex ones at the end!

250 |

API docs

251 |

In the docs/ folder and also hosted on GitHub Pages. (Don't forget to check the right sidebar of the site!)

252 |

Testing

253 |

Testcases are listed in tests.js. Run them with

254 |
npm test
255 | 
256 |

Note about code quality (?)

257 |

This project most probably does not follow the current Javascript standards and coding style embraced by the global community, thus some people may find the source code weird and/or outright hideous. As I'm not primarily a Javascript developer (and I don't intend to become one) the current implementation is a solution that I could come up with, which works and has the API that I dreamed of.

258 |

If you have ideas how to improve the library internals (without breaking the public API) feel free to open an issue or PR to discuss it! I'm open for improvements and constructive criticism.

259 |

But why?

260 |

Because there is no other JSON object validator with a builder pattern interface like this one. Okay, there is actually Superstruct, but I didn't know about it when I started developing this, and also it is much-much bigger with many features I personally don't need.

261 |

So I created this library as a smaller alternative.

262 |

License

263 |

MIT

264 |
265 | 266 | 267 | 268 | 269 | 270 | 271 |
272 | 273 | 276 | 277 |
278 | 279 | 282 | 283 | 284 | 285 | 286 | -------------------------------------------------------------------------------- /docs/is.__validationUnit.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Class: __validationUnit 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Class: __validationUnit

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 |
30 | 31 |

32 | is.__validationUnit() → {Object}

33 | 34 | 35 |
36 | 37 |
38 |
39 | 40 | 41 | 42 | 43 | 44 | 45 |

new __validationUnit() → {Object}

46 | 47 | 48 | 49 | 50 | 51 | 52 |
53 | Function to return a new configurable validator. You don't need to call this directly! Use a factory method instead. 54 |
55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 |
69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 |
Source:
96 |
99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 |
107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 |
Returns:
123 | 124 | 125 |
126 | The new, unconfigured validator. 127 |
128 | 129 | 130 | 131 |
132 |
133 | Type 134 |
135 |
136 | 137 | Object 138 | 139 | 140 |
141 |
142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 |
151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 |

Methods

168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 |

ArrayOf(schema) → {is.__validationUnit}

176 | 177 | 178 | 179 | 180 | 181 | 182 |
183 | Set the validator to validate arrays. 184 |
185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 |
Parameters:
195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 |
NameTypeDescription
schema 223 | 224 | 225 | is.__validationUnit 226 | 227 | 228 | 229 | The validator which must validate every element of the array.
241 | 242 | 243 | 244 | 245 | 246 | 247 |
248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 |
Source:
275 |
278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 |
286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 |
Returns:
302 | 303 | 304 |
305 | The validator itself. 306 |
307 | 308 | 309 | 310 |
311 |
312 | Type 313 |
314 |
315 | 316 | is.__validationUnit 317 | 318 | 319 |
320 |
321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 |

Boolean() → {is.__validationUnit}

335 | 336 | 337 | 338 | 339 | 340 | 341 |
342 | Set the validator to validate booleans. 343 |
344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 |
358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 |
Source:
385 |
388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 |
396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 |
Returns:
412 | 413 | 414 |
415 | The validator itself. 416 |
417 | 418 | 419 | 420 |
421 |
422 | Type 423 |
424 |
425 | 426 | is.__validationUnit 427 | 428 | 429 |
430 |
431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 |

Number() → {is.__validationUnit}

445 | 446 | 447 | 448 | 449 | 450 | 451 |
452 | Set the validator to validate numbers. 453 |
454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 |
468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 |
Source:
495 |
498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 |
506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 |
Returns:
522 | 523 | 524 |
525 | The validator itself. 526 |
527 | 528 | 529 | 530 |
531 |
532 | Type 533 |
534 |
535 | 536 | is.__validationUnit 537 | 538 | 539 |
540 |
541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 |

Object(schemaObj) → {is.__validationUnit}

555 | 556 | 557 | 558 | 559 | 560 | 561 |
562 | Set the validator to validate objects. 563 |
564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 |
Parameters:
574 | 575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 |
NameTypeDescription
schemaObj 602 | 603 | 604 | Object 605 | 606 | 607 | 608 | The schema of the object to validate, made up of other validators.
620 | 621 | 622 | 623 | 624 | 625 | 626 |
627 | 628 | 629 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 |
Source:
654 |
657 | 658 | 659 | 660 | 661 | 662 | 663 | 664 |
665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 |
Returns:
681 | 682 | 683 |
684 | The validator itself. 685 |
686 | 687 | 688 | 689 |
690 |
691 | Type 692 |
693 |
694 | 695 | is.__validationUnit 696 | 697 | 698 |
699 |
700 | 701 | 702 | 703 | 704 | 705 | 706 | 707 | 708 | 709 | 710 | 711 | 712 | 713 |

OneOf(schemaArray) → {is.__validationUnit}

714 | 715 | 716 | 717 | 718 | 719 | 720 |
721 | Set the validator to validate a variable type. 722 |
723 | 724 | 725 | 726 | 727 | 728 | 729 | 730 | 731 | 732 |
Parameters:
733 | 734 | 735 | 736 | 737 | 738 | 739 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 754 | 755 | 756 | 757 | 758 | 759 | 760 | 768 | 769 | 770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 |
NameTypeDescription
schemaArray 761 | 762 | 763 | is.__validationUnit 764 | 765 | 766 | 767 | An array of other validators.
779 | 780 | 781 | 782 | 783 | 784 | 785 |
786 | 787 | 788 | 789 | 790 | 791 | 792 | 793 | 794 | 795 | 796 | 797 | 798 | 799 | 800 | 801 | 802 | 803 | 804 | 805 | 806 | 807 | 808 | 809 | 810 | 811 | 812 |
Source:
813 |
816 | 817 | 818 | 819 | 820 | 821 | 822 | 823 |
824 | 825 | 826 | 827 | 828 | 829 | 830 | 831 | 832 | 833 | 834 | 835 | 836 | 837 | 838 | 839 |
Returns:
840 | 841 | 842 |
843 | The validator itself. 844 |
845 | 846 | 847 | 848 |
849 |
850 | Type 851 |
852 |
853 | 854 | is.__validationUnit 855 | 856 | 857 |
858 |
859 | 860 | 861 | 862 | 863 | 864 | 865 | 866 | 867 | 868 | 869 | 870 | 871 | 872 |

optional() → {is.__validationUnit}

873 | 874 | 875 | 876 | 877 | 878 | 879 |
880 | Set the validator to optional, so it accepts missing values. 881 |
882 | 883 | 884 | 885 | 886 | 887 | 888 | 889 | 890 | 891 | 892 | 893 | 894 | 895 |
896 | 897 | 898 | 899 | 900 | 901 | 902 | 903 | 904 | 905 | 906 | 907 | 908 | 909 | 910 | 911 | 912 | 913 | 914 | 915 | 916 | 917 | 918 | 919 | 920 | 921 | 922 |
Source:
923 |
926 | 927 | 928 | 929 | 930 | 931 | 932 | 933 |
934 | 935 | 936 | 937 | 938 | 939 | 940 | 941 | 942 | 943 | 944 | 945 | 946 | 947 | 948 | 949 |
Returns:
950 | 951 | 952 |
953 | The validator itself. 954 |
955 | 956 | 957 | 958 |
959 |
960 | Type 961 |
962 |
963 | 964 | is.__validationUnit 965 | 966 | 967 |
968 |
969 | 970 | 971 | 972 | 973 | 974 | 975 | 976 | 977 | 978 | 979 | 980 | 981 | 982 |

String() → {is.__validationUnit}

983 | 984 | 985 | 986 | 987 | 988 | 989 |
990 | Set the validator to validate strings. 991 |
992 | 993 | 994 | 995 | 996 | 997 | 998 | 999 | 1000 | 1001 | 1002 | 1003 | 1004 | 1005 |
1006 | 1007 | 1008 | 1009 | 1010 | 1011 | 1012 | 1013 | 1014 | 1015 | 1016 | 1017 | 1018 | 1019 | 1020 | 1021 | 1022 | 1023 | 1024 | 1025 | 1026 | 1027 | 1028 | 1029 | 1030 | 1031 | 1032 |
Source:
1033 |
1036 | 1037 | 1038 | 1039 | 1040 | 1041 | 1042 | 1043 |
1044 | 1045 | 1046 | 1047 | 1048 | 1049 | 1050 | 1051 | 1052 | 1053 | 1054 | 1055 | 1056 | 1057 | 1058 | 1059 |
Returns:
1060 | 1061 | 1062 |
1063 | The validator itself. 1064 |
1065 | 1066 | 1067 | 1068 |
1069 |
1070 | Type 1071 |
1072 |
1073 | 1074 | is.__validationUnit 1075 | 1076 | 1077 |
1078 |
1079 | 1080 | 1081 | 1082 | 1083 | 1084 | 1085 | 1086 | 1087 | 1088 | 1089 | 1090 | 1091 | 1092 |

validate(subject) → {Boolean}

1093 | 1094 | 1095 | 1096 | 1097 | 1098 | 1099 |
1100 | Validate the subject against the set schema. 1101 |
1102 | 1103 | 1104 | 1105 | 1106 | 1107 | 1108 | 1109 | 1110 | 1111 |
Parameters:
1112 | 1113 | 1114 | 1115 | 1116 | 1117 | 1118 | 1119 | 1120 | 1121 | 1122 | 1123 | 1124 | 1125 | 1126 | 1127 | 1128 | 1129 | 1130 | 1131 | 1132 | 1133 | 1134 | 1135 | 1136 | 1137 | 1138 | 1139 | 1147 | 1148 | 1149 | 1150 | 1151 | 1152 | 1153 | 1154 | 1155 | 1156 | 1157 |
NameTypeDescription
subject 1140 | 1141 | 1142 | any 1143 | 1144 | 1145 | 1146 | The subject to validate.
1158 | 1159 | 1160 | 1161 | 1162 | 1163 | 1164 |
1165 | 1166 | 1167 | 1168 | 1169 | 1170 | 1171 | 1172 | 1173 | 1174 | 1175 | 1176 | 1177 | 1178 | 1179 | 1180 | 1181 | 1182 | 1183 | 1184 | 1185 | 1186 | 1187 | 1188 | 1189 | 1190 | 1191 |
Source:
1192 |
1195 | 1196 | 1197 | 1198 | 1199 | 1200 | 1201 | 1202 |
1203 | 1204 | 1205 | 1206 | 1207 | 1208 | 1209 | 1210 | 1211 | 1212 | 1213 | 1214 | 1215 | 1216 | 1217 | 1218 |
Returns:
1219 | 1220 | 1221 |
1222 | Validation result: true if the subject matches the schema, false otherwise. 1223 |
1224 | 1225 | 1226 | 1227 |
1228 |
1229 | Type 1230 |
1231 |
1232 | 1233 | Boolean 1234 | 1235 | 1236 |
1237 |
1238 | 1239 | 1240 | 1241 | 1242 | 1243 | 1244 | 1245 | 1246 | 1247 | 1248 | 1249 | 1250 | 1251 |

Which(lambda) → {is.__validationUnit}

1252 | 1253 | 1254 | 1255 | 1256 | 1257 | 1258 |
1259 | Add a new functional validation lambda to the validator. 1260 |
1261 | 1262 | 1263 | 1264 | 1265 | 1266 | 1267 | 1268 | 1269 | 1270 |
Parameters:
1271 | 1272 | 1273 | 1274 | 1275 | 1276 | 1277 | 1278 | 1279 | 1280 | 1281 | 1282 | 1283 | 1284 | 1285 | 1286 | 1287 | 1288 | 1289 | 1290 | 1291 | 1292 | 1293 | 1294 | 1295 | 1296 | 1297 | 1298 | 1306 | 1307 | 1308 | 1309 | 1310 | 1311 | 1312 | 1313 | 1314 | 1315 | 1316 |
NameTypeDescription
lambda 1299 | 1300 | 1301 | lambda 1302 | 1303 | 1304 | 1305 | The functional validator, which accesses the subject and returns true or false.
1317 | 1318 | 1319 | 1320 | 1321 | 1322 | 1323 |
1324 | 1325 | 1326 | 1327 | 1328 | 1329 | 1330 | 1331 | 1332 | 1333 | 1334 | 1335 | 1336 | 1337 | 1338 | 1339 | 1340 | 1341 | 1342 | 1343 | 1344 | 1345 | 1346 | 1347 | 1348 | 1349 | 1350 |
Source:
1351 |
1354 | 1355 | 1356 | 1357 | 1358 | 1359 | 1360 | 1361 |
1362 | 1363 | 1364 | 1365 | 1366 | 1367 | 1368 | 1369 | 1370 | 1371 | 1372 | 1373 | 1374 | 1375 | 1376 | 1377 |
Returns:
1378 | 1379 | 1380 |
1381 | The validator itself. 1382 |
1383 | 1384 | 1385 | 1386 |
1387 |
1388 | Type 1389 |
1390 |
1391 | 1392 | is.__validationUnit 1393 | 1394 | 1395 |
1396 |
1397 | 1398 | 1399 | 1400 | 1401 | 1402 | 1403 | 1404 | 1405 | 1406 | 1407 | 1408 | 1409 | 1410 |
1411 | 1412 |
1413 | 1414 | 1415 | 1416 | 1417 |
1418 | 1419 | 1422 | 1423 |
1424 | 1425 | 1428 | 1429 | 1430 | 1431 | 1432 | -------------------------------------------------------------------------------- /docs/is.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Namespace: is 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Namespace: is

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 |
30 | 31 |

is

32 | 33 | 34 |
35 | 36 |
37 |
38 | 39 | 40 |
Global constant & API entry point for Fluent JSON validator.
41 | 42 | 43 | 44 | 45 | 46 |
47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 |
Source:
74 |
77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 |
85 | 86 | 87 | 88 | 89 |
90 | 91 | 92 | 93 | 94 | 95 | 96 |

Classes

97 | 98 |
99 |
__validationUnit
100 |
101 |
102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 |

Methods

114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 |

(static) ArrayOf(schema) → {is.__validationUnit}

122 | 123 | 124 | 125 | 126 | 127 | 128 |
129 | Create an array validator. 130 |
131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 |
Parameters:
141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 |
NameTypeDescription
schema 169 | 170 | 171 | is.__validationUnit 172 | 173 | 174 | 175 | Any validator that the array elements must validate against.
187 | 188 | 189 | 190 | 191 | 192 | 193 |
194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 |
Source:
221 |
224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 |
232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 |
Returns:
248 | 249 | 250 |
251 | The new array validator. 252 |
253 | 254 | 255 | 256 |
257 |
258 | Type 259 |
260 |
261 | 262 | is.__validationUnit 263 | 264 | 265 |
266 |
267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 |

(static) Boolean() → {is.__validationUnit}

281 | 282 | 283 | 284 | 285 | 286 | 287 |
288 | Create a new boolean validator. 289 |
290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 |
304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 |
Source:
331 |
334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 |
342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 |
Returns:
358 | 359 | 360 |
361 | The new boolean validator. 362 |
363 | 364 | 365 | 366 |
367 |
368 | Type 369 |
370 |
371 | 372 | is.__validationUnit 373 | 374 | 375 |
376 |
377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 |

(static) Number() → {is.__validationUnit}

391 | 392 | 393 | 394 | 395 | 396 | 397 |
398 | Create a new number validator. 399 |
400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 |
414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 |
Source:
441 |
444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 |
452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 |
Returns:
468 | 469 | 470 |
471 | The new number validator. 472 |
473 | 474 | 475 | 476 |
477 |
478 | Type 479 |
480 |
481 | 482 | is.__validationUnit 483 | 484 | 485 |
486 |
487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 |

(static) Object(schemaObj) → {is.__validationUnit}

501 | 502 | 503 | 504 | 505 | 506 | 507 |
508 | Create an object validator. 509 |
510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 |
Parameters:
520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 |
NameTypeDescription
schemaObj 548 | 549 | 550 | Object 551 | 552 | 553 | 554 | The schema object, made up of other validators.
566 | 567 | 568 | 569 | 570 | 571 | 572 |
573 | 574 | 575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 |
Source:
600 |
603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 |
611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 |
Returns:
627 | 628 | 629 |
630 | The new object validator. 631 |
632 | 633 | 634 | 635 |
636 |
637 | Type 638 |
639 |
640 | 641 | is.__validationUnit 642 | 643 | 644 |
645 |
646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 |

(static) OneOf(schemaArray) → {is.__validationUnit}

660 | 661 | 662 | 663 | 664 | 665 | 666 |
667 | Create a variable type validator. 668 |
669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 |
Parameters:
679 | 680 | 681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 | 703 | 704 | 705 | 706 | 714 | 715 | 716 | 717 | 718 | 719 | 720 | 721 | 722 | 723 | 724 |
NameTypeDescription
schemaArray 707 | 708 | 709 | Array.<is.__validationUnit> 710 | 711 | 712 | 713 | Array of validator objects the subject must match against (at least one of them).
725 | 726 | 727 | 728 | 729 | 730 | 731 |
732 | 733 | 734 | 735 | 736 | 737 | 738 | 739 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 754 | 755 | 756 | 757 | 758 |
Source:
759 |
762 | 763 | 764 | 765 | 766 | 767 | 768 | 769 |
770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 780 | 781 | 782 | 783 | 784 | 785 |
Returns:
786 | 787 | 788 |
789 | The new variable type validator. 790 |
791 | 792 | 793 | 794 |
795 |
796 | Type 797 |
798 |
799 | 800 | is.__validationUnit 801 | 802 | 803 |
804 |
805 | 806 | 807 | 808 | 809 | 810 | 811 | 812 | 813 | 814 | 815 | 816 | 817 | 818 |

(static) optional() → {is.__validationUnit}

819 | 820 | 821 | 822 | 823 | 824 | 825 |
826 | Create a new validator object that is optional. 827 |
828 | 829 | 830 | 831 | 832 | 833 | 834 | 835 | 836 | 837 | 838 | 839 | 840 | 841 |
842 | 843 | 844 | 845 | 846 | 847 | 848 | 849 | 850 | 851 | 852 | 853 | 854 | 855 | 856 | 857 | 858 | 859 | 860 | 861 | 862 | 863 | 864 | 865 | 866 | 867 | 868 |
Source:
869 |
872 | 873 | 874 | 875 | 876 | 877 | 878 | 879 |
880 | 881 | 882 | 883 | 884 | 885 | 886 | 887 | 888 | 889 | 890 | 891 | 892 | 893 | 894 | 895 |
Returns:
896 | 897 | 898 |
899 | A new optional validator object. 900 |
901 | 902 | 903 | 904 |
905 |
906 | Type 907 |
908 |
909 | 910 | is.__validationUnit 911 | 912 | 913 |
914 |
915 | 916 | 917 | 918 | 919 | 920 | 921 | 922 | 923 | 924 | 925 | 926 | 927 | 928 |

(static) String() → {is.__validationUnit}

929 | 930 | 931 | 932 | 933 | 934 | 935 |
936 | Create a new string validator. 937 |
938 | 939 | 940 | 941 | 942 | 943 | 944 | 945 | 946 | 947 | 948 | 949 | 950 | 951 |
952 | 953 | 954 | 955 | 956 | 957 | 958 | 959 | 960 | 961 | 962 | 963 | 964 | 965 | 966 | 967 | 968 | 969 | 970 | 971 | 972 | 973 | 974 | 975 | 976 | 977 | 978 |
Source:
979 |
982 | 983 | 984 | 985 | 986 | 987 | 988 | 989 |
990 | 991 | 992 | 993 | 994 | 995 | 996 | 997 | 998 | 999 | 1000 | 1001 | 1002 | 1003 | 1004 | 1005 |
Returns:
1006 | 1007 | 1008 |
1009 | The new string validator. 1010 |
1011 | 1012 | 1013 | 1014 |
1015 |
1016 | Type 1017 |
1018 |
1019 | 1020 | is.__validationUnit 1021 | 1022 | 1023 |
1024 |
1025 | 1026 | 1027 | 1028 | 1029 | 1030 | 1031 | 1032 | 1033 | 1034 | 1035 | 1036 | 1037 | 1038 |

(static) Which(functionalValidator) → {is.__validationUnit}

1039 | 1040 | 1041 | 1042 | 1043 | 1044 | 1045 |
1046 | Create a new functional validator. 1047 |
1048 | 1049 | 1050 | 1051 | 1052 | 1053 | 1054 | 1055 | 1056 | 1057 |
Parameters:
1058 | 1059 | 1060 | 1061 | 1062 | 1063 | 1064 | 1065 | 1066 | 1067 | 1068 | 1069 | 1070 | 1071 | 1072 | 1073 | 1074 | 1075 | 1076 | 1077 | 1078 | 1079 | 1080 | 1081 | 1082 | 1083 | 1084 | 1085 | 1093 | 1094 | 1095 | 1096 | 1097 | 1098 | 1099 | 1100 | 1101 | 1102 | 1103 |
NameTypeDescription
functionalValidator 1086 | 1087 | 1088 | function 1089 | 1090 | 1091 | 1092 | The functional validator which checks the subject for functional requirements.
1104 | 1105 | 1106 | 1107 | 1108 | 1109 | 1110 |
1111 | 1112 | 1113 | 1114 | 1115 | 1116 | 1117 | 1118 | 1119 | 1120 | 1121 | 1122 | 1123 | 1124 | 1125 | 1126 | 1127 | 1128 | 1129 | 1130 | 1131 | 1132 | 1133 | 1134 | 1135 | 1136 | 1137 |
Source:
1138 |
1141 | 1142 | 1143 | 1144 | 1145 | 1146 | 1147 | 1148 |
1149 | 1150 | 1151 | 1152 | 1153 | 1154 | 1155 | 1156 | 1157 | 1158 | 1159 | 1160 | 1161 | 1162 | 1163 | 1164 |
Returns:
1165 | 1166 | 1167 |
1168 | The new functional validator. 1169 |
1170 | 1171 | 1172 | 1173 |
1174 |
1175 | Type 1176 |
1177 |
1178 | 1179 | is.__validationUnit 1180 | 1181 | 1182 |
1183 |
1184 | 1185 | 1186 | 1187 | 1188 | 1189 | 1190 | 1191 | 1192 | 1193 | 1194 | 1195 | 1196 | 1197 |
1198 | 1199 |
1200 | 1201 | 1202 | 1203 | 1204 |
1205 | 1206 | 1209 | 1210 |
1211 | 1212 | 1215 | 1216 | 1217 | 1218 | 1219 | -------------------------------------------------------------------------------- /docs/is.js.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Source: is.js 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Source: is.js

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 |
29 |
'use strict';
 30 | 
 31 | /**
 32 |  * Global constant & API entry point for Fluent JSON validator.
 33 |  *
 34 |  * @namespace  is
 35 |  * @type       {Object}
 36 |  */
 37 | const is = {
 38 | 
 39 |     /**
 40 |      * Function to return a new configurable validator. You don't need to call this directly! Use a factory method instead.
 41 |      *
 42 |      * @class   is.__validationUnit
 43 |      * @return  {Object}  The new, unconfigured validator.
 44 |      */
 45 |     __validationUnit: function() {
 46 | 
 47 |         this.__type = undefined;
 48 |         this.__required = true;
 49 |         this.__functionalValidators = [];
 50 |         this.__validateType = (subject) => {
 51 |             return false; // FIXME should this actually throw an exception?
 52 |         }
 53 | 
 54 |         /**
 55 |          * Validate the subject against the set schema.
 56 |          *
 57 |          * @param      {any}      subject   The subject to validate.
 58 |          * @return     {Boolean}            Validation result: true if the subject matches the schema, false otherwise.
 59 |          */
 60 |         this.validate = (subject) => {
 61 |             if (typeof subject === "undefined" && this.__type !== "array" && this.__type !== "various") {
 62 |                 return !this.__required;
 63 |             } else {
 64 |                 return this.__validateType(subject) &&
 65 |                        this.__functionalValidators.filter(functionalValidator => !functionalValidator(subject)).length == 0;
 66 |                        // ^ == there is no functional validator lambda which does not validate the subject.
 67 |             };
 68 |         };
 69 | 
 70 |         /**
 71 |          * Set the validator to optional, so it accepts missing values.
 72 |          *
 73 |          * @return     {is.__validationUnit}  The validator itself.
 74 |          */
 75 |         this.optional = function() {
 76 |             this.__required = false;
 77 |             return this;
 78 |         };
 79 | 
 80 |         /**
 81 |          * Add a new functional validation lambda to the validator.
 82 |          *
 83 |          * @param      {lambda}               lambda  The functional validator, which accesses the subject and returns true or false.
 84 |          * @return     {is.__validationUnit}          The validator itself.
 85 |          */
 86 |         this.Which = function(lambda) {
 87 |             this.__functionalValidators.push(lambda);
 88 |             return this;
 89 |         }
 90 | 
 91 |         /**
 92 |          * Set the validator to validate strings.
 93 |          *
 94 |          * @return     {is.__validationUnit}  The validator itself.
 95 |          */
 96 |         this.String = function() {
 97 |             this.__type = "string";
 98 |             this.__validateType = (value) => (
 99 |                 typeof value === "string"
100 |             );
101 |             return this;
102 |         };
103 | 
104 |         /**
105 |          * Set the validator to validate booleans.
106 |          *
107 |          * @return     {is.__validationUnit}  The validator itself.
108 |          */
109 |         this.Boolean = function() {
110 |             this.__type = "boolean";
111 |             this.__validateType = (value) => (
112 |                 typeof value === "boolean"
113 |             );
114 |             return this;
115 |         }
116 | 
117 |         /**
118 |          * Set the validator to validate numbers.
119 |          *
120 |          * @return     {is.__validationUnit}  The validator itself.
121 |          */
122 |         this.Number = function() {
123 |             this.__type = "number";
124 |             this.__validateType = (value) => (
125 |                 typeof value === "number"
126 |             );
127 |             return this;
128 |         };
129 | 
130 |         /**
131 |          * Set the validator to validate objects.
132 |          *
133 |          * @param      {Object}               schemaObj  The schema of the object to validate, made up of other validators.
134 |          * @return     {is.__validationUnit}             The validator itself.
135 |          */
136 |         this.Object = function(schemaObj) {
137 |             this.__type = "object";
138 |             this.__schemaObj = schemaObj || {};
139 |             this.__validateType = (value) => {
140 |                 if (typeof value !== "object") {
141 |                     return false;
142 |                 };
143 |                 for (const schemaKey in this.__schemaObj) {
144 |                     // here we iterate over the keys of the schema
145 |                     // and validate the corresponding properties of the value object.
146 |                     if (!schemaObj[schemaKey].validate(value[schemaKey])) {
147 |                         return false;
148 |                     };
149 |                 };
150 |                 return true;
151 |             };
152 |             return this;
153 |         };
154 | 
155 |         /**
156 |          * Set the validator to validate arrays.
157 |          *
158 |          * @param      {is.__validationUnit}  schema  The validator which must validate every element of the array.
159 |          * @return     {is.__validationUnit}          The validator itself.
160 |          */
161 |         this.ArrayOf = function(schema) {
162 |             this.__type = "array";
163 |             this.__schema = schema;
164 |             this.__validateType = (value) => {
165 |                 if (Array.isArray(value)) {
166 |                     return value.filter(e => !this.__schema.validate(e)).length == 0;
167 |                     // ^ == there is no item in the array which is not validated by the schema
168 |                 } else {
169 |                     return (!this.__required && typeof value === "undefined");
170 |                 };
171 |             };
172 |             return this;
173 |         };
174 | 
175 |         /**
176 |          * Set the validator to validate a variable type.
177 |          *
178 |          * @param      {is.__validationUnit}  schemaArray  An array of other validators.
179 |          * @return     {is.__validationUnit}               The validator itself.
180 |          */
181 |         this.OneOf = function(schemaArray) {
182 |             this.__type = "various";
183 |             this.__schemaArray = schemaArray;
184 |             this.__validateType = (value) => {
185 |                 if (!this.__required && typeof value === "undefined") {
186 |                     return true;
187 |                 } else {
188 |                     return this.__schemaArray.filter(schema => schema.validate(value)).length > 0;
189 |                     // ^ == there is at least one schema which validates the value
190 |                 };
191 |             };
192 |             return this;
193 |         }
194 | 
195 |         return this;
196 |     },
197 | };
198 | 
199 | /**
200 |  * Create a new validator object that is optional.
201 |  *
202 |  * @return     {is.__validationUnit}  A new optional validator object.
203 |  */
204 | is.optional = () => (new is.__validationUnit().optional());
205 | 
206 | /**
207 |  * Create a new functional validator.
208 |  *
209 |  * @param      {Function}             functionalValidator  The functional validator which checks the subject for functional requirements.
210 |  * @return     {is.__validationUnit}                       The new functional validator.
211 |  */
212 | is.Which = (functionalValidator) => (new is.__validationUnit().Which(functionalValidator));
213 | 
214 | /**
215 |  * Create a new string validator.
216 |  *
217 |  * @return     {is.__validationUnit}  The new string validator.
218 |  */
219 | is.String = () => (new is.__validationUnit().String());
220 | 
221 | /**
222 |  * Create a new boolean validator.
223 |  *
224 |  * @return     {is.__validationUnit}  The new boolean validator.
225 |  */
226 | is.Boolean = () => (new is.__validationUnit().Boolean());
227 | 
228 | /**
229 |  * Create a new number validator.
230 |  *
231 |  * @return     {is.__validationUnit}  The new number validator.
232 |  */
233 | is.Number = () => (new is.__validationUnit().Number());
234 | 
235 | /**
236 |  * Create an object validator.
237 |  *
238 |  * @param      {Object}               schemaObj  The schema object, made up of other validators.
239 |  * @return     {is.__validationUnit}             The new object validator.
240 |  */
241 | is.Object = (schemaObj) => (new is.__validationUnit().Object(schemaObj));
242 | 
243 | /**
244 |  * Create an array validator.
245 |  *
246 |  * @param      {is.__validationUnit}  schema  Any validator that the array elements must validate against.
247 |  * @return     {is.__validationUnit}          The new array validator.
248 |  */
249 | is.ArrayOf = (schema) => (new is.__validationUnit().ArrayOf(schema));
250 | 
251 | /**
252 |  * Create a variable type validator.
253 |  *
254 |  * @param      {is.__validationUnit[]}  schemaArray  Array of validator objects the subject must match against (at least one of them).
255 |  * @return     {is.__validationUnit}                 The new variable type validator.
256 |  */
257 | is.OneOf = (schemaArray) => (new is.__validationUnit().OneOf(schemaArray));
258 | 
259 | export { is };
260 | 
261 |
262 |
263 | 264 | 265 | 266 | 267 |
268 | 269 | 272 | 273 |
274 | 275 | 278 | 279 | 280 | 281 | 282 | 283 | -------------------------------------------------------------------------------- /docs/scripts/linenumber.js: -------------------------------------------------------------------------------- 1 | /*global document */ 2 | (() => { 3 | const source = document.getElementsByClassName('prettyprint source linenums'); 4 | let i = 0; 5 | let lineNumber = 0; 6 | let lineId; 7 | let lines; 8 | let totalLines; 9 | let anchorHash; 10 | 11 | if (source && source[0]) { 12 | anchorHash = document.location.hash.substring(1); 13 | lines = source[0].getElementsByTagName('li'); 14 | totalLines = lines.length; 15 | 16 | for (; i < totalLines; i++) { 17 | lineNumber++; 18 | lineId = `line${lineNumber}`; 19 | lines[i].id = lineId; 20 | if (lineId === anchorHash) { 21 | lines[i].className += ' selected'; 22 | } 23 | } 24 | } 25 | })(); 26 | -------------------------------------------------------------------------------- /docs/scripts/prettify/Apache-License-2.0.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /docs/scripts/prettify/lang-css.js: -------------------------------------------------------------------------------- 1 | PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n "]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", 2 | /^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); 3 | -------------------------------------------------------------------------------- /docs/scripts/prettify/prettify.js: -------------------------------------------------------------------------------- 1 | var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; 2 | (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= 3 | [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), 9 | l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, 10 | q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, 11 | q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, 12 | "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), 13 | a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} 14 | for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], 18 | "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], 19 | H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], 20 | J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ 21 | I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), 22 | ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", 23 | /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), 24 | ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", 25 | hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= 26 | !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p th:last-child { border-right: 1px solid #ddd; } 224 | 225 | .ancestors, .attribs { color: #999; } 226 | .ancestors a, .attribs a 227 | { 228 | color: #999 !important; 229 | text-decoration: none; 230 | } 231 | 232 | .clear 233 | { 234 | clear: both; 235 | } 236 | 237 | .important 238 | { 239 | font-weight: bold; 240 | color: #950B02; 241 | } 242 | 243 | .yes-def { 244 | text-indent: -1000px; 245 | } 246 | 247 | .type-signature { 248 | color: #aaa; 249 | } 250 | 251 | .name, .signature { 252 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 253 | } 254 | 255 | .details { margin-top: 14px; border-left: 2px solid #DDD; } 256 | .details dt { width: 120px; float: left; padding-left: 10px; padding-top: 6px; } 257 | .details dd { margin-left: 70px; } 258 | .details ul { margin: 0; } 259 | .details ul { list-style-type: none; } 260 | .details li { margin-left: 30px; padding-top: 6px; } 261 | .details pre.prettyprint { margin: 0 } 262 | .details .object-value { padding-top: 0; } 263 | 264 | .description { 265 | margin-bottom: 1em; 266 | margin-top: 1em; 267 | } 268 | 269 | .code-caption 270 | { 271 | font-style: italic; 272 | font-size: 107%; 273 | margin: 0; 274 | } 275 | 276 | .source 277 | { 278 | border: 1px solid #ddd; 279 | width: 80%; 280 | overflow: auto; 281 | } 282 | 283 | .prettyprint.source { 284 | width: inherit; 285 | } 286 | 287 | .source code 288 | { 289 | font-size: 100%; 290 | line-height: 18px; 291 | display: block; 292 | padding: 4px 12px; 293 | margin: 0; 294 | background-color: #fff; 295 | color: #4D4E53; 296 | } 297 | 298 | .prettyprint code span.line 299 | { 300 | display: inline-block; 301 | } 302 | 303 | .prettyprint.linenums 304 | { 305 | padding-left: 70px; 306 | -webkit-user-select: none; 307 | -moz-user-select: none; 308 | -ms-user-select: none; 309 | user-select: none; 310 | } 311 | 312 | .prettyprint.linenums ol 313 | { 314 | padding-left: 0; 315 | } 316 | 317 | .prettyprint.linenums li 318 | { 319 | border-left: 3px #ddd solid; 320 | } 321 | 322 | .prettyprint.linenums li.selected, 323 | .prettyprint.linenums li.selected * 324 | { 325 | background-color: lightyellow; 326 | } 327 | 328 | .prettyprint.linenums li * 329 | { 330 | -webkit-user-select: text; 331 | -moz-user-select: text; 332 | -ms-user-select: text; 333 | user-select: text; 334 | } 335 | 336 | .params .name, .props .name, .name code { 337 | color: #4D4E53; 338 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 339 | font-size: 100%; 340 | } 341 | 342 | .params td.description > p:first-child, 343 | .props td.description > p:first-child 344 | { 345 | margin-top: 0; 346 | padding-top: 0; 347 | } 348 | 349 | .params td.description > p:last-child, 350 | .props td.description > p:last-child 351 | { 352 | margin-bottom: 0; 353 | padding-bottom: 0; 354 | } 355 | 356 | .disabled { 357 | color: #454545; 358 | } 359 | -------------------------------------------------------------------------------- /docs/styles/prettify-jsdoc.css: -------------------------------------------------------------------------------- 1 | /* JSDoc prettify.js theme */ 2 | 3 | /* plain text */ 4 | .pln { 5 | color: #000000; 6 | font-weight: normal; 7 | font-style: normal; 8 | } 9 | 10 | /* string content */ 11 | .str { 12 | color: #006400; 13 | font-weight: normal; 14 | font-style: normal; 15 | } 16 | 17 | /* a keyword */ 18 | .kwd { 19 | color: #000000; 20 | font-weight: bold; 21 | font-style: normal; 22 | } 23 | 24 | /* a comment */ 25 | .com { 26 | font-weight: normal; 27 | font-style: italic; 28 | } 29 | 30 | /* a type name */ 31 | .typ { 32 | color: #000000; 33 | font-weight: normal; 34 | font-style: normal; 35 | } 36 | 37 | /* a literal value */ 38 | .lit { 39 | color: #006400; 40 | font-weight: normal; 41 | font-style: normal; 42 | } 43 | 44 | /* punctuation */ 45 | .pun { 46 | color: #000000; 47 | font-weight: bold; 48 | font-style: normal; 49 | } 50 | 51 | /* lisp open bracket */ 52 | .opn { 53 | color: #000000; 54 | font-weight: bold; 55 | font-style: normal; 56 | } 57 | 58 | /* lisp close bracket */ 59 | .clo { 60 | color: #000000; 61 | font-weight: bold; 62 | font-style: normal; 63 | } 64 | 65 | /* a markup tag name */ 66 | .tag { 67 | color: #006400; 68 | font-weight: normal; 69 | font-style: normal; 70 | } 71 | 72 | /* a markup attribute name */ 73 | .atn { 74 | color: #006400; 75 | font-weight: normal; 76 | font-style: normal; 77 | } 78 | 79 | /* a markup attribute value */ 80 | .atv { 81 | color: #006400; 82 | font-weight: normal; 83 | font-style: normal; 84 | } 85 | 86 | /* a declaration */ 87 | .dec { 88 | color: #000000; 89 | font-weight: bold; 90 | font-style: normal; 91 | } 92 | 93 | /* a variable name */ 94 | .var { 95 | color: #000000; 96 | font-weight: normal; 97 | font-style: normal; 98 | } 99 | 100 | /* a function name */ 101 | .fun { 102 | color: #000000; 103 | font-weight: bold; 104 | font-style: normal; 105 | } 106 | 107 | /* Specify class=linenums on a pre to get line numbering */ 108 | ol.linenums { 109 | margin-top: 0; 110 | margin-bottom: 0; 111 | } 112 | -------------------------------------------------------------------------------- /docs/styles/prettify-tomorrow.css: -------------------------------------------------------------------------------- 1 | /* Tomorrow Theme */ 2 | /* Original theme - https://github.com/chriskempson/tomorrow-theme */ 3 | /* Pretty printing styles. Used with prettify.js. */ 4 | /* SPAN elements with the classes below are added by prettyprint. */ 5 | /* plain text */ 6 | .pln { 7 | color: #4d4d4c; } 8 | 9 | @media screen { 10 | /* string content */ 11 | .str { 12 | color: #718c00; } 13 | 14 | /* a keyword */ 15 | .kwd { 16 | color: #8959a8; } 17 | 18 | /* a comment */ 19 | .com { 20 | color: #8e908c; } 21 | 22 | /* a type name */ 23 | .typ { 24 | color: #4271ae; } 25 | 26 | /* a literal value */ 27 | .lit { 28 | color: #f5871f; } 29 | 30 | /* punctuation */ 31 | .pun { 32 | color: #4d4d4c; } 33 | 34 | /* lisp open bracket */ 35 | .opn { 36 | color: #4d4d4c; } 37 | 38 | /* lisp close bracket */ 39 | .clo { 40 | color: #4d4d4c; } 41 | 42 | /* a markup tag name */ 43 | .tag { 44 | color: #c82829; } 45 | 46 | /* a markup attribute name */ 47 | .atn { 48 | color: #f5871f; } 49 | 50 | /* a markup attribute value */ 51 | .atv { 52 | color: #3e999f; } 53 | 54 | /* a declaration */ 55 | .dec { 56 | color: #f5871f; } 57 | 58 | /* a variable name */ 59 | .var { 60 | color: #c82829; } 61 | 62 | /* a function name */ 63 | .fun { 64 | color: #4271ae; } } 65 | /* Use higher contrast and text-weight for printable form. */ 66 | @media print, projection { 67 | .str { 68 | color: #060; } 69 | 70 | .kwd { 71 | color: #006; 72 | font-weight: bold; } 73 | 74 | .com { 75 | color: #600; 76 | font-style: italic; } 77 | 78 | .typ { 79 | color: #404; 80 | font-weight: bold; } 81 | 82 | .lit { 83 | color: #044; } 84 | 85 | .pun, .opn, .clo { 86 | color: #440; } 87 | 88 | .tag { 89 | color: #006; 90 | font-weight: bold; } 91 | 92 | .atn { 93 | color: #404; } 94 | 95 | .atv { 96 | color: #060; } } 97 | /* Style */ 98 | /* 99 | pre.prettyprint { 100 | background: white; 101 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 102 | font-size: 12px; 103 | line-height: 1.5; 104 | border: 1px solid #ccc; 105 | padding: 10px; } 106 | */ 107 | 108 | /* Specify class=linenums on a pre to get line numbering */ 109 | ol.linenums { 110 | margin-top: 0; 111 | margin-bottom: 0; } 112 | 113 | /* IE indents via margin-left */ 114 | li.L0, 115 | li.L1, 116 | li.L2, 117 | li.L3, 118 | li.L4, 119 | li.L5, 120 | li.L6, 121 | li.L7, 122 | li.L8, 123 | li.L9 { 124 | /* */ } 125 | 126 | /* Alternate shading for lines */ 127 | li.L1, 128 | li.L3, 129 | li.L5, 130 | li.L7, 131 | li.L9 { 132 | /* */ } 133 | -------------------------------------------------------------------------------- /is.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Global constant & API entry point for Fluent JSON validator. 5 | * 6 | * @namespace is 7 | * @type {Object} 8 | */ 9 | const is = { 10 | 11 | /** 12 | * Function to return a new configurable validator. You don't need to call this directly! Use a factory method instead. 13 | * 14 | * @class is.__validationUnit 15 | * @return {Object} The new, unconfigured validator. 16 | */ 17 | __validationUnit: function() { 18 | 19 | this.__type = undefined; 20 | this.__required = true; 21 | this.__functionalValidators = []; 22 | this.__validateType = (subject) => { 23 | return false; // FIXME should this actually throw an exception? 24 | } 25 | 26 | /** 27 | * Validate the subject against the set schema. 28 | * 29 | * @param {any} subject The subject to validate. 30 | * @return {Boolean} Validation result: true if the subject matches the schema, false otherwise. 31 | */ 32 | this.validate = (subject) => { 33 | if (typeof subject === "undefined" && this.__type !== "array" && this.__type !== "various") { 34 | return !this.__required; 35 | } else { 36 | return this.__validateType(subject) && 37 | this.__functionalValidators.filter(functionalValidator => !functionalValidator(subject)).length == 0; 38 | // ^ == there is no functional validator lambda which does not validate the subject. 39 | }; 40 | }; 41 | 42 | /** 43 | * Set the validator to optional, so it accepts missing values. 44 | * 45 | * @return {is.__validationUnit} The validator itself. 46 | */ 47 | this.optional = function() { 48 | this.__required = false; 49 | return this; 50 | }; 51 | 52 | /** 53 | * Add a new functional validation lambda to the validator. 54 | * 55 | * @param {lambda} lambda The functional validator, which accesses the subject and returns true or false. 56 | * @return {is.__validationUnit} The validator itself. 57 | */ 58 | this.Which = function(lambda) { 59 | this.__functionalValidators.push(lambda); 60 | return this; 61 | } 62 | 63 | /** 64 | * Set the validator to validate strings. 65 | * 66 | * @return {is.__validationUnit} The validator itself. 67 | */ 68 | this.String = function() { 69 | this.__type = "string"; 70 | this.__validateType = (value) => ( 71 | typeof value === "string" 72 | ); 73 | return this; 74 | }; 75 | 76 | /** 77 | * Set the validator to validate booleans. 78 | * 79 | * @return {is.__validationUnit} The validator itself. 80 | */ 81 | this.Boolean = function() { 82 | this.__type = "boolean"; 83 | this.__validateType = (value) => ( 84 | typeof value === "boolean" 85 | ); 86 | return this; 87 | } 88 | 89 | /** 90 | * Set the validator to validate numbers. 91 | * 92 | * @return {is.__validationUnit} The validator itself. 93 | */ 94 | this.Number = function() { 95 | this.__type = "number"; 96 | this.__validateType = (value) => ( 97 | typeof value === "number" 98 | ); 99 | return this; 100 | }; 101 | 102 | /** 103 | * Set the validator to validate objects. 104 | * 105 | * @param {Object} schemaObj The schema of the object to validate, made up of other validators. 106 | * @return {is.__validationUnit} The validator itself. 107 | */ 108 | this.Object = function(schemaObj) { 109 | this.__type = "object"; 110 | this.__schemaObj = schemaObj || {}; 111 | this.__validateType = (value) => { 112 | if (typeof value !== "object") { 113 | return false; 114 | }; 115 | for (const schemaKey in this.__schemaObj) { 116 | // here we iterate over the keys of the schema 117 | // and validate the corresponding properties of the value object. 118 | if (!schemaObj[schemaKey].validate(value[schemaKey])) { 119 | return false; 120 | }; 121 | }; 122 | return true; 123 | }; 124 | return this; 125 | }; 126 | 127 | /** 128 | * Set the validator to validate arrays. 129 | * 130 | * @param {is.__validationUnit} schema The validator which must validate every element of the array. 131 | * @return {is.__validationUnit} The validator itself. 132 | */ 133 | this.ArrayOf = function(schema) { 134 | this.__type = "array"; 135 | this.__schema = schema; 136 | this.__validateType = (value) => { 137 | if (Array.isArray(value)) { 138 | return value.filter(e => !this.__schema.validate(e)).length == 0; 139 | // ^ == there is no item in the array which is not validated by the schema 140 | } else { 141 | return (!this.__required && typeof value === "undefined"); 142 | }; 143 | }; 144 | return this; 145 | }; 146 | 147 | /** 148 | * Set the validator to validate a variable type. 149 | * 150 | * @param {is.__validationUnit} schemaArray An array of other validators. 151 | * @return {is.__validationUnit} The validator itself. 152 | */ 153 | this.OneOf = function(schemaArray) { 154 | this.__type = "various"; 155 | this.__schemaArray = schemaArray; 156 | this.__validateType = (value) => { 157 | if (!this.__required && typeof value === "undefined") { 158 | return true; 159 | } else { 160 | return this.__schemaArray.filter(schema => schema.validate(value)).length > 0; 161 | // ^ == there is at least one schema which validates the value 162 | }; 163 | }; 164 | return this; 165 | } 166 | 167 | return this; 168 | }, 169 | }; 170 | 171 | /** 172 | * Create a new validator object that is optional. 173 | * 174 | * @return {is.__validationUnit} A new optional validator object. 175 | */ 176 | is.optional = () => (new is.__validationUnit().optional()); 177 | 178 | /** 179 | * Create a new functional validator. 180 | * 181 | * @param {Function} functionalValidator The functional validator which checks the subject for functional requirements. 182 | * @return {is.__validationUnit} The new functional validator. 183 | */ 184 | is.Which = (functionalValidator) => (new is.__validationUnit().Which(functionalValidator)); 185 | 186 | /** 187 | * Create a new string validator. 188 | * 189 | * @return {is.__validationUnit} The new string validator. 190 | */ 191 | is.String = () => (new is.__validationUnit().String()); 192 | 193 | /** 194 | * Create a new boolean validator. 195 | * 196 | * @return {is.__validationUnit} The new boolean validator. 197 | */ 198 | is.Boolean = () => (new is.__validationUnit().Boolean()); 199 | 200 | /** 201 | * Create a new number validator. 202 | * 203 | * @return {is.__validationUnit} The new number validator. 204 | */ 205 | is.Number = () => (new is.__validationUnit().Number()); 206 | 207 | /** 208 | * Create an object validator. 209 | * 210 | * @param {Object} schemaObj The schema object, made up of other validators. 211 | * @return {is.__validationUnit} The new object validator. 212 | */ 213 | is.Object = (schemaObj) => (new is.__validationUnit().Object(schemaObj)); 214 | 215 | /** 216 | * Create an array validator. 217 | * 218 | * @param {is.__validationUnit} schema Any validator that the array elements must validate against. 219 | * @return {is.__validationUnit} The new array validator. 220 | */ 221 | is.ArrayOf = (schema) => (new is.__validationUnit().ArrayOf(schema)); 222 | 223 | /** 224 | * Create a variable type validator. 225 | * 226 | * @param {is.__validationUnit[]} schemaArray Array of validator objects the subject must match against (at least one of them). 227 | * @return {is.__validationUnit} The new variable type validator. 228 | */ 229 | is.OneOf = (schemaArray) => (new is.__validationUnit().OneOf(schemaArray)); 230 | 231 | export { is }; 232 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fluent-json-validator", 3 | "version": "0.3.2", 4 | "lockfileVersion": 2, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "version": "0.3.2", 9 | "license": "MIT", 10 | "devDependencies": { 11 | "jsdoc": "^3.6.6" 12 | } 13 | }, 14 | "node_modules/@babel/parser": { 15 | "version": "7.13.10", 16 | "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.13.10.tgz", 17 | "integrity": "sha512-0s7Mlrw9uTWkYua7xWr99Wpk2bnGa0ANleKfksYAES8LpWH4gW1OUr42vqKNf0us5UQNfru2wPqMqRITzq/SIQ==", 18 | "dev": true, 19 | "bin": { 20 | "parser": "bin/babel-parser.js" 21 | }, 22 | "engines": { 23 | "node": ">=6.0.0" 24 | } 25 | }, 26 | "node_modules/argparse": { 27 | "version": "1.0.10", 28 | "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", 29 | "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", 30 | "dev": true, 31 | "dependencies": { 32 | "sprintf-js": "~1.0.2" 33 | } 34 | }, 35 | "node_modules/bluebird": { 36 | "version": "3.7.2", 37 | "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", 38 | "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", 39 | "dev": true 40 | }, 41 | "node_modules/catharsis": { 42 | "version": "0.8.11", 43 | "resolved": "https://registry.npmjs.org/catharsis/-/catharsis-0.8.11.tgz", 44 | "integrity": "sha512-a+xUyMV7hD1BrDQA/3iPV7oc+6W26BgVJO05PGEoatMyIuPScQKsde6i3YorWX1qs+AZjnJ18NqdKoCtKiNh1g==", 45 | "dev": true, 46 | "dependencies": { 47 | "lodash": "^4.17.14" 48 | }, 49 | "engines": { 50 | "node": ">= 8" 51 | } 52 | }, 53 | "node_modules/entities": { 54 | "version": "2.0.3", 55 | "resolved": "https://registry.npmjs.org/entities/-/entities-2.0.3.tgz", 56 | "integrity": "sha512-MyoZ0jgnLvB2X3Lg5HqpFmn1kybDiIfEQmKzTb5apr51Rb+T3KdmMiqa70T+bhGnyv7bQ6WMj2QMHpGMmlrUYQ==", 57 | "dev": true 58 | }, 59 | "node_modules/escape-string-regexp": { 60 | "version": "2.0.0", 61 | "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", 62 | "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", 63 | "dev": true, 64 | "engines": { 65 | "node": ">=8" 66 | } 67 | }, 68 | "node_modules/graceful-fs": { 69 | "version": "4.2.6", 70 | "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.6.tgz", 71 | "integrity": "sha512-nTnJ528pbqxYanhpDYsi4Rd8MAeaBA67+RZ10CM1m3bTAVFEDcd5AuA4a6W5YkGZ1iNXHzZz8T6TBKLeBuNriQ==", 72 | "dev": true 73 | }, 74 | "node_modules/js2xmlparser": { 75 | "version": "4.0.1", 76 | "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.1.tgz", 77 | "integrity": "sha512-KrPTolcw6RocpYjdC7pL7v62e55q7qOMHvLX1UCLc5AAS8qeJ6nukarEJAF2KL2PZxlbGueEbINqZR2bDe/gUw==", 78 | "dev": true, 79 | "dependencies": { 80 | "xmlcreate": "^2.0.3" 81 | } 82 | }, 83 | "node_modules/jsdoc": { 84 | "version": "3.6.6", 85 | "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-3.6.6.tgz", 86 | "integrity": "sha512-znR99e1BHeyEkSvgDDpX0sTiTu+8aQyDl9DawrkOGZTTW8hv0deIFXx87114zJ7gRaDZKVQD/4tr1ifmJp9xhQ==", 87 | "dev": true, 88 | "dependencies": { 89 | "@babel/parser": "^7.9.4", 90 | "bluebird": "^3.7.2", 91 | "catharsis": "^0.8.11", 92 | "escape-string-regexp": "^2.0.0", 93 | "js2xmlparser": "^4.0.1", 94 | "klaw": "^3.0.0", 95 | "markdown-it": "^10.0.0", 96 | "markdown-it-anchor": "^5.2.7", 97 | "marked": "^0.8.2", 98 | "mkdirp": "^1.0.4", 99 | "requizzle": "^0.2.3", 100 | "strip-json-comments": "^3.1.0", 101 | "taffydb": "2.6.2", 102 | "underscore": "~1.10.2" 103 | }, 104 | "bin": { 105 | "jsdoc": "jsdoc.js" 106 | }, 107 | "engines": { 108 | "node": ">=8.15.0" 109 | } 110 | }, 111 | "node_modules/klaw": { 112 | "version": "3.0.0", 113 | "resolved": "https://registry.npmjs.org/klaw/-/klaw-3.0.0.tgz", 114 | "integrity": "sha512-0Fo5oir+O9jnXu5EefYbVK+mHMBeEVEy2cmctR1O1NECcCkPRreJKrS6Qt/j3KC2C148Dfo9i3pCmCMsdqGr0g==", 115 | "dev": true, 116 | "dependencies": { 117 | "graceful-fs": "^4.1.9" 118 | } 119 | }, 120 | "node_modules/linkify-it": { 121 | "version": "2.2.0", 122 | "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-2.2.0.tgz", 123 | "integrity": "sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw==", 124 | "dev": true, 125 | "dependencies": { 126 | "uc.micro": "^1.0.1" 127 | } 128 | }, 129 | "node_modules/lodash": { 130 | "version": "4.17.21", 131 | "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", 132 | "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", 133 | "dev": true 134 | }, 135 | "node_modules/markdown-it": { 136 | "version": "10.0.0", 137 | "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-10.0.0.tgz", 138 | "integrity": "sha512-YWOP1j7UbDNz+TumYP1kpwnP0aEa711cJjrAQrzd0UXlbJfc5aAq0F/PZHjiioqDC1NKgvIMX+o+9Bk7yuM2dg==", 139 | "dev": true, 140 | "dependencies": { 141 | "argparse": "^1.0.7", 142 | "entities": "~2.0.0", 143 | "linkify-it": "^2.0.0", 144 | "mdurl": "^1.0.1", 145 | "uc.micro": "^1.0.5" 146 | }, 147 | "bin": { 148 | "markdown-it": "bin/markdown-it.js" 149 | } 150 | }, 151 | "node_modules/markdown-it-anchor": { 152 | "version": "5.3.0", 153 | "resolved": "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-5.3.0.tgz", 154 | "integrity": "sha512-/V1MnLL/rgJ3jkMWo84UR+K+jF1cxNG1a+KwqeXqTIJ+jtA8aWSHuigx8lTzauiIjBDbwF3NcWQMotd0Dm39jA==", 155 | "dev": true, 156 | "peerDependencies": { 157 | "markdown-it": "*" 158 | } 159 | }, 160 | "node_modules/marked": { 161 | "version": "0.8.2", 162 | "resolved": "https://registry.npmjs.org/marked/-/marked-0.8.2.tgz", 163 | "integrity": "sha512-EGwzEeCcLniFX51DhTpmTom+dSA/MG/OBUDjnWtHbEnjAH180VzUeAw+oE4+Zv+CoYBWyRlYOTR0N8SO9R1PVw==", 164 | "dev": true, 165 | "bin": { 166 | "marked": "bin/marked" 167 | }, 168 | "engines": { 169 | "node": ">= 8.16.2" 170 | } 171 | }, 172 | "node_modules/mdurl": { 173 | "version": "1.0.1", 174 | "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-1.0.1.tgz", 175 | "integrity": "sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4=", 176 | "dev": true 177 | }, 178 | "node_modules/mkdirp": { 179 | "version": "1.0.4", 180 | "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", 181 | "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", 182 | "dev": true, 183 | "bin": { 184 | "mkdirp": "bin/cmd.js" 185 | }, 186 | "engines": { 187 | "node": ">=10" 188 | } 189 | }, 190 | "node_modules/requizzle": { 191 | "version": "0.2.3", 192 | "resolved": "https://registry.npmjs.org/requizzle/-/requizzle-0.2.3.tgz", 193 | "integrity": "sha512-YanoyJjykPxGHii0fZP0uUPEXpvqfBDxWV7s6GKAiiOsiqhX6vHNyW3Qzdmqp/iq/ExbhaGbVrjB4ruEVSM4GQ==", 194 | "dev": true, 195 | "dependencies": { 196 | "lodash": "^4.17.14" 197 | } 198 | }, 199 | "node_modules/sprintf-js": { 200 | "version": "1.0.3", 201 | "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", 202 | "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", 203 | "dev": true 204 | }, 205 | "node_modules/strip-json-comments": { 206 | "version": "3.1.1", 207 | "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", 208 | "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", 209 | "dev": true, 210 | "engines": { 211 | "node": ">=8" 212 | }, 213 | "funding": { 214 | "url": "https://github.com/sponsors/sindresorhus" 215 | } 216 | }, 217 | "node_modules/taffydb": { 218 | "version": "2.6.2", 219 | "resolved": "https://registry.npmjs.org/taffydb/-/taffydb-2.6.2.tgz", 220 | "integrity": "sha1-fLy2S1oUG2ou/CxdLGe04VCyomg=", 221 | "dev": true 222 | }, 223 | "node_modules/uc.micro": { 224 | "version": "1.0.6", 225 | "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz", 226 | "integrity": "sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==", 227 | "dev": true 228 | }, 229 | "node_modules/underscore": { 230 | "version": "1.10.2", 231 | "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.10.2.tgz", 232 | "integrity": "sha512-N4P+Q/BuyuEKFJ43B9gYuOj4TQUHXX+j2FqguVOpjkssLUUrnJofCcBccJSCoeturDoZU6GorDTHSvUDlSQbTg==", 233 | "dev": true 234 | }, 235 | "node_modules/xmlcreate": { 236 | "version": "2.0.3", 237 | "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.3.tgz", 238 | "integrity": "sha512-HgS+X6zAztGa9zIK3Y3LXuJes33Lz9x+YyTxgrkIdabu2vqcGOWwdfCpf1hWLRrd553wd4QCDf6BBO6FfdsRiQ==", 239 | "dev": true 240 | } 241 | }, 242 | "dependencies": { 243 | "@babel/parser": { 244 | "version": "7.13.10", 245 | "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.13.10.tgz", 246 | "integrity": "sha512-0s7Mlrw9uTWkYua7xWr99Wpk2bnGa0ANleKfksYAES8LpWH4gW1OUr42vqKNf0us5UQNfru2wPqMqRITzq/SIQ==", 247 | "dev": true 248 | }, 249 | "argparse": { 250 | "version": "1.0.10", 251 | "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", 252 | "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", 253 | "dev": true, 254 | "requires": { 255 | "sprintf-js": "~1.0.2" 256 | } 257 | }, 258 | "bluebird": { 259 | "version": "3.7.2", 260 | "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", 261 | "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", 262 | "dev": true 263 | }, 264 | "catharsis": { 265 | "version": "0.8.11", 266 | "resolved": "https://registry.npmjs.org/catharsis/-/catharsis-0.8.11.tgz", 267 | "integrity": "sha512-a+xUyMV7hD1BrDQA/3iPV7oc+6W26BgVJO05PGEoatMyIuPScQKsde6i3YorWX1qs+AZjnJ18NqdKoCtKiNh1g==", 268 | "dev": true, 269 | "requires": { 270 | "lodash": "^4.17.14" 271 | } 272 | }, 273 | "entities": { 274 | "version": "2.0.3", 275 | "resolved": "https://registry.npmjs.org/entities/-/entities-2.0.3.tgz", 276 | "integrity": "sha512-MyoZ0jgnLvB2X3Lg5HqpFmn1kybDiIfEQmKzTb5apr51Rb+T3KdmMiqa70T+bhGnyv7bQ6WMj2QMHpGMmlrUYQ==", 277 | "dev": true 278 | }, 279 | "escape-string-regexp": { 280 | "version": "2.0.0", 281 | "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", 282 | "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", 283 | "dev": true 284 | }, 285 | "graceful-fs": { 286 | "version": "4.2.6", 287 | "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.6.tgz", 288 | "integrity": "sha512-nTnJ528pbqxYanhpDYsi4Rd8MAeaBA67+RZ10CM1m3bTAVFEDcd5AuA4a6W5YkGZ1iNXHzZz8T6TBKLeBuNriQ==", 289 | "dev": true 290 | }, 291 | "js2xmlparser": { 292 | "version": "4.0.1", 293 | "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-4.0.1.tgz", 294 | "integrity": "sha512-KrPTolcw6RocpYjdC7pL7v62e55q7qOMHvLX1UCLc5AAS8qeJ6nukarEJAF2KL2PZxlbGueEbINqZR2bDe/gUw==", 295 | "dev": true, 296 | "requires": { 297 | "xmlcreate": "^2.0.3" 298 | } 299 | }, 300 | "jsdoc": { 301 | "version": "3.6.6", 302 | "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-3.6.6.tgz", 303 | "integrity": "sha512-znR99e1BHeyEkSvgDDpX0sTiTu+8aQyDl9DawrkOGZTTW8hv0deIFXx87114zJ7gRaDZKVQD/4tr1ifmJp9xhQ==", 304 | "dev": true, 305 | "requires": { 306 | "@babel/parser": "^7.9.4", 307 | "bluebird": "^3.7.2", 308 | "catharsis": "^0.8.11", 309 | "escape-string-regexp": "^2.0.0", 310 | "js2xmlparser": "^4.0.1", 311 | "klaw": "^3.0.0", 312 | "markdown-it": "^10.0.0", 313 | "markdown-it-anchor": "^5.2.7", 314 | "marked": "^0.8.2", 315 | "mkdirp": "^1.0.4", 316 | "requizzle": "^0.2.3", 317 | "strip-json-comments": "^3.1.0", 318 | "taffydb": "2.6.2", 319 | "underscore": "~1.10.2" 320 | } 321 | }, 322 | "klaw": { 323 | "version": "3.0.0", 324 | "resolved": "https://registry.npmjs.org/klaw/-/klaw-3.0.0.tgz", 325 | "integrity": "sha512-0Fo5oir+O9jnXu5EefYbVK+mHMBeEVEy2cmctR1O1NECcCkPRreJKrS6Qt/j3KC2C148Dfo9i3pCmCMsdqGr0g==", 326 | "dev": true, 327 | "requires": { 328 | "graceful-fs": "^4.1.9" 329 | } 330 | }, 331 | "linkify-it": { 332 | "version": "2.2.0", 333 | "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-2.2.0.tgz", 334 | "integrity": "sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw==", 335 | "dev": true, 336 | "requires": { 337 | "uc.micro": "^1.0.1" 338 | } 339 | }, 340 | "lodash": { 341 | "version": "4.17.21", 342 | "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", 343 | "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", 344 | "dev": true 345 | }, 346 | "markdown-it": { 347 | "version": "10.0.0", 348 | "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-10.0.0.tgz", 349 | "integrity": "sha512-YWOP1j7UbDNz+TumYP1kpwnP0aEa711cJjrAQrzd0UXlbJfc5aAq0F/PZHjiioqDC1NKgvIMX+o+9Bk7yuM2dg==", 350 | "dev": true, 351 | "requires": { 352 | "argparse": "^1.0.7", 353 | "entities": "~2.0.0", 354 | "linkify-it": "^2.0.0", 355 | "mdurl": "^1.0.1", 356 | "uc.micro": "^1.0.5" 357 | } 358 | }, 359 | "markdown-it-anchor": { 360 | "version": "5.3.0", 361 | "resolved": "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-5.3.0.tgz", 362 | "integrity": "sha512-/V1MnLL/rgJ3jkMWo84UR+K+jF1cxNG1a+KwqeXqTIJ+jtA8aWSHuigx8lTzauiIjBDbwF3NcWQMotd0Dm39jA==", 363 | "dev": true, 364 | "requires": {} 365 | }, 366 | "marked": { 367 | "version": "0.8.2", 368 | "resolved": "https://registry.npmjs.org/marked/-/marked-0.8.2.tgz", 369 | "integrity": "sha512-EGwzEeCcLniFX51DhTpmTom+dSA/MG/OBUDjnWtHbEnjAH180VzUeAw+oE4+Zv+CoYBWyRlYOTR0N8SO9R1PVw==", 370 | "dev": true 371 | }, 372 | "mdurl": { 373 | "version": "1.0.1", 374 | "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-1.0.1.tgz", 375 | "integrity": "sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4=", 376 | "dev": true 377 | }, 378 | "mkdirp": { 379 | "version": "1.0.4", 380 | "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", 381 | "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", 382 | "dev": true 383 | }, 384 | "requizzle": { 385 | "version": "0.2.3", 386 | "resolved": "https://registry.npmjs.org/requizzle/-/requizzle-0.2.3.tgz", 387 | "integrity": "sha512-YanoyJjykPxGHii0fZP0uUPEXpvqfBDxWV7s6GKAiiOsiqhX6vHNyW3Qzdmqp/iq/ExbhaGbVrjB4ruEVSM4GQ==", 388 | "dev": true, 389 | "requires": { 390 | "lodash": "^4.17.14" 391 | } 392 | }, 393 | "sprintf-js": { 394 | "version": "1.0.3", 395 | "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", 396 | "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", 397 | "dev": true 398 | }, 399 | "strip-json-comments": { 400 | "version": "3.1.1", 401 | "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", 402 | "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", 403 | "dev": true 404 | }, 405 | "taffydb": { 406 | "version": "2.6.2", 407 | "resolved": "https://registry.npmjs.org/taffydb/-/taffydb-2.6.2.tgz", 408 | "integrity": "sha1-fLy2S1oUG2ou/CxdLGe04VCyomg=", 409 | "dev": true 410 | }, 411 | "uc.micro": { 412 | "version": "1.0.6", 413 | "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz", 414 | "integrity": "sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==", 415 | "dev": true 416 | }, 417 | "underscore": { 418 | "version": "1.10.2", 419 | "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.10.2.tgz", 420 | "integrity": "sha512-N4P+Q/BuyuEKFJ43B9gYuOj4TQUHXX+j2FqguVOpjkssLUUrnJofCcBccJSCoeturDoZU6GorDTHSvUDlSQbTg==", 421 | "dev": true 422 | }, 423 | "xmlcreate": { 424 | "version": "2.0.3", 425 | "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.3.tgz", 426 | "integrity": "sha512-HgS+X6zAztGa9zIK3Y3LXuJes33Lz9x+YyTxgrkIdabu2vqcGOWwdfCpf1hWLRrd553wd4QCDf6BBO6FfdsRiQ==", 427 | "dev": true 428 | } 429 | } 430 | } 431 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fluent-json-validator", 3 | "version": "0.3.2", 4 | "description": "An easy-to-use, expressive, and composable JSON object validator, with a fluent builder pattern interface!", 5 | "type": "module", 6 | "main": "is.js", 7 | "scripts": { 8 | "start": "npm test", 9 | "test": "node tests.js", 10 | "jsdoc": "jsdoc --readme README.md -d docs/ is.js" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/Semmu/fluent-json-validator.git" 15 | }, 16 | "keywords": [ 17 | "json", 18 | "data", 19 | "structure", 20 | "object", 21 | "validator", 22 | "validate", 23 | "formal", 24 | "functional", 25 | "expressive", 26 | "fluent", 27 | "composable", 28 | "eloquent", 29 | "builder" 30 | ], 31 | "author": "Laszlo Boros (Semmu)", 32 | "license": "MIT", 33 | "bugs": { 34 | "url": "https://github.com/Semmu/fluent-json-validator/issues" 35 | }, 36 | "homepage": "https://github.com/Semmu/fluent-json-validator#readme", 37 | "devDependencies": { 38 | "jsdoc": "^3.6.6" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /tests.js: -------------------------------------------------------------------------------- 1 | import { is } from './is.js'; 2 | 3 | // this is the huge array containing all the testcases 4 | const testCases = [ 5 | { 6 | description: 'values are required by default', 7 | result: false === is.String().validate() && 8 | false === is.Number().validate() && 9 | false === is.Boolean().validate() && 10 | false === is.Object().validate() 11 | }, 12 | { 13 | description: 'optionals accept undefined', 14 | result: true === is.optional().String().validate() && 15 | true === is.optional().Number().validate() && 16 | true === is.optional().Boolean().validate() && 17 | true === is.optional().Object().validate() 18 | }, 19 | { 20 | description: 'types only accept correct inputs', 21 | result: false === is.String().validate() && 22 | true === is.String().validate('string') && 23 | false === is.String().validate(42) && 24 | false === is.String().validate(true) && 25 | false === is.String().validate({}) && 26 | 27 | false === is.Number().validate() && 28 | false === is.Number().validate('string') && 29 | true === is.Number().validate(42) && 30 | false === is.Number().validate(true) && 31 | false === is.Number().validate({}) && 32 | 33 | false === is.Boolean().validate() && 34 | false === is.Boolean().validate('string') && 35 | false === is.Boolean().validate(42) && 36 | true === is.Boolean().validate(true) && 37 | false === is.Boolean().validate({}) && 38 | 39 | false === is.Object().validate() && 40 | false === is.Object().validate('string') && 41 | false === is.Object().validate(42) && 42 | false === is.Object().validate(true) && 43 | true === is.Object().validate({}) 44 | }, 45 | { 46 | description: 'validating unknown type fails', 47 | result: false === is.Which(x => true).validate() && 48 | false === is.optional().Which(x => true).validate('anything') 49 | }, 50 | { 51 | description: 'functional requirements work', 52 | result: true === is.String().Which(str => str.length > 5).validate('more than 5 chars') && 53 | false === is.String().Which(str => str.length > 5).validate('less') && 54 | 55 | true === is.Number().Which(num => num > 42).validate(50) && 56 | false === is.Number().Which(num => num > 42).validate(0) && 57 | 58 | true === is.Boolean().Which(bln => bln).validate(true) && 59 | false === is.Boolean().Which(bln => bln).validate(false) && 60 | 61 | true === is.Object().Which(obj => 'key1' in obj ? 'key2' in obj : true).validate({}) && 62 | false === is.Object().Which(obj => 'key1' in obj ? 'key2' in obj : true).validate({key1: 'value1'}) && 63 | true === is.Object().Which(obj => 'key1' in obj ? 'key2' in obj : true).validate({key1: 'value1', key2: 'value2'}) 64 | }, 65 | { 66 | description: 'multiple simultaneous functional requirements work', 67 | result: true === is.Number().Which(num => num > 5).Which(num => num < 10).validate(8) && 68 | false === is.Number().Which(num => num > 5).Which(num => num < 10).validate(4) && 69 | false === is.Number().Which(num => num > 5).Which(num => num < 10).validate(11) 70 | }, 71 | { 72 | description: 'ArrayOf does not accept non-arrays', 73 | result: false === is.ArrayOf(is.String()).validate('not an array') && 74 | false === is.ArrayOf(is.Number()).validate(42) 75 | }, 76 | { 77 | description: 'ArrayOf accepts the correct values', 78 | result: true === is.ArrayOf(is.String()).validate(['array', 'of', 'strings']) && 79 | false === is.ArrayOf(is.String()).validate(['array', 'of', 42]) && 80 | false === is.ArrayOf(is.String()).validate(['array', 'of', undefined]) && 81 | 82 | true === is.ArrayOf(is.optional().String()).validate(['array', 'of', undefined]) 83 | }, 84 | { 85 | description: 'functional requirements of arrays and their elements work correctly', 86 | result: true === is.ArrayOf(is.String()).Which(arr => arr.length == 3).validate(['array', 'of', 'strings']) && 87 | false === is.ArrayOf(is.String()).Which(arr => arr.length == 3).validate(['array', 'of', 'more', 'strings']) && 88 | true === is.ArrayOf(is.String().Which(str => str == 'a')).validate(['a', 'a', 'a']) && 89 | false === is.ArrayOf(is.String().Which(str => str == 'a')).validate(['a', 'a', 'B!']) && 90 | 91 | true === is.ArrayOf(is.String().Which(str => str == 'a')).Which(arr => arr.length == 3).validate(['a', 'a', 'a']) && 92 | false === is.ArrayOf(is.String().Which(str => str == 'a')).Which(arr => arr.length == 3).validate(['a', 'a', 'a', 'a']) 93 | }, 94 | { 95 | description: 'optional ArrayOf works correctly', 96 | result: true === is.optional().ArrayOf(is.String()).validate() && 97 | true === is.optional().ArrayOf(is.String()).validate(['array', 'of', 'strings']) && 98 | false === is.optional().ArrayOf(is.String()).validate(['array', 'of', 42]) && 99 | true === is.optional().ArrayOf(is.optional().String()).validate(['array', 'of', undefined]) && 100 | false === is.optional().ArrayOf(is.optional().String()).validate(['array', 'of', 42]) 101 | }, 102 | { 103 | description: 'OneOf works correctly', 104 | result: false === is.OneOf([is.String()]).validate() && 105 | true === is.OneOf([is.String()]).validate('string') && 106 | false === is.OneOf([is.String()]).validate(42) && 107 | 108 | true === is.OneOf([is.String(), is.Number()]).validate('string') && 109 | true === is.OneOf([is.String(), is.Number()]).validate(42) && 110 | false === is.OneOf([is.String(), is.Number()]).validate({}) && 111 | true === is.OneOf([is.Object(), is.Number()]).validate({}) && 112 | false === is.OneOf([is.String(), is.Number()]).validate() 113 | }, 114 | { 115 | description: 'optional OneOf works correctly', 116 | result: true === is.optional().OneOf([is.Number(), is.String()]).validate() && 117 | true === is.optional().OneOf([is.Number(), is.String()]).validate(42) && 118 | true === is.optional().OneOf([is.Number(), is.String()]).validate('string') && 119 | false === is.optional().OneOf([is.Number(), is.String()]).validate({}) 120 | }, 121 | { 122 | description: 'OneOf mixed with optional types works correctly', 123 | result: true === is.OneOf([is.optional().String()]).validate() && 124 | true === is.OneOf([is.optional().String()]).validate('string') && 125 | false === is.OneOf([is.optional().String()]).validate(42) && 126 | 127 | true === is.OneOf([is.String(), is.optional().Number()]).validate() && 128 | true === is.OneOf([is.String(), is.optional().Number()]).validate('string') && 129 | true === is.OneOf([is.String(), is.optional().Number()]).validate(42) && 130 | false === is.OneOf([is.String(), is.optional().Number()]).validate({}) 131 | }, 132 | { 133 | description: 'ArrayOf OneOf works correctly', 134 | result: true === is.ArrayOf(is.OneOf([is.String()])).validate(['array', 'of', 'strings']) && 135 | false === is.ArrayOf(is.OneOf([is.String()])).validate(['array', undefined, 'string']) && 136 | 137 | true === is.ArrayOf(is.OneOf([is.optional().String()])).validate(['array', undefined, 'string']) && 138 | 139 | true === is.ArrayOf(is.OneOf([is.String(), is.Number()])).validate(['string', 42]) && 140 | false === is.ArrayOf(is.OneOf([is.String(), is.Number()])).validate(['string', 42, undefined]) && 141 | false === is.ArrayOf(is.OneOf([is.String(), is.Number()])).validate(['string', 42, {}]) && 142 | 143 | true === is.ArrayOf(is.OneOf([is.String(), is.optional().Number()])).validate(['string', 42, undefined]) && 144 | true === is.ArrayOf(is.OneOf([is.optional().String(), is.Number()])).validate(['string', 42, undefined]) && 145 | false === is.ArrayOf(is.OneOf([is.String(), is.optional().Number()])).validate(['string', 42, {}]) 146 | }, 147 | { 148 | description: 'simple Object validation works', 149 | result: true === is.Object({ 150 | str: is.String(), 151 | num: is.Number(), 152 | bln: is.Boolean(), 153 | obj: is.Object() 154 | }).validate({ 155 | str: 'string', 156 | num: 42, 157 | bln: false, 158 | obj: {} 159 | }) && 160 | false === is.Object({ 161 | str: is.String(), 162 | num: is.Number(), 163 | }).validate({ 164 | str: 'string', 165 | }) 166 | }, 167 | { 168 | description: 'Object validation with optional properties works', 169 | result: false === is.Object({ 170 | str: is.String(), 171 | num: is.Number(), 172 | }).validate({ 173 | str: 'string', 174 | }) && 175 | true === is.Object({ 176 | str: is.String(), 177 | num: is.optional().Number(), 178 | }).validate({ 179 | str: 'string', 180 | }) 181 | }, 182 | { 183 | description: 'Object having ArrayOf works', 184 | result: true === is.Object({ 185 | nums: is.ArrayOf(is.Number()) 186 | }).validate({ 187 | nums: [1, 2, 3] 188 | }) && 189 | true === is.Object({ 190 | nums: is.ArrayOf(is.optional().Number()) 191 | }).validate({ 192 | nums: [1, 2, undefined] 193 | }) && 194 | true === is.Object({ 195 | nums: is.ArrayOf(is.optional().Number()) 196 | }).validate({ 197 | nums: [undefined] 198 | }) && 199 | true === is.Object({ 200 | nums: is.ArrayOf(is.Number()) 201 | }).validate({ 202 | nums: [] 203 | }) && 204 | true === is.Object({ 205 | nums: is.ArrayOf(is.Number()) 206 | }).validate({ 207 | nums: [] 208 | }) && 209 | false === is.Object({ 210 | nums: is.ArrayOf(is.Number()) 211 | }).validate({ 212 | nums: undefined 213 | }) && 214 | false === is.Object({ 215 | nums: is.ArrayOf(is.Number()) 216 | }).validate({ 217 | nums: [undefined] 218 | }) && 219 | false === is.Object({ 220 | nums: is.ArrayOf(is.Number()) 221 | }).validate({ 222 | // actually empty object 223 | }) && 224 | true === is.Object({ 225 | nums: is.optional().ArrayOf(is.Number()) 226 | }).validate({ 227 | // actually empty object 228 | }) && 229 | false === is.Object({ 230 | nums: is.optional().ArrayOf(is.Number()) 231 | }).validate({ 232 | nums: 'it exists, but not an array of numbers' 233 | }) 234 | }, 235 | { 236 | description: 'Object having OneOf works', 237 | result: true === is.Object({ 238 | oneof: is.OneOf([is.String(), is.Number()]) 239 | }).validate({ 240 | oneof: 'string' 241 | }) && 242 | true === is.Object({ 243 | oneof: is.OneOf([is.String(), is.Number()]) 244 | }).validate({ 245 | oneof: 42 246 | }) && 247 | false === is.Object({ 248 | oneof: is.OneOf([is.String(), is.Number()]) 249 | }).validate({ 250 | oneof: {} 251 | }) && 252 | false === is.Object({ 253 | oneof: is.OneOf([is.String(), is.Number()]) 254 | }).validate({ 255 | // actually empty object 256 | }) && 257 | true === is.Object({ 258 | oneof: is.optional().OneOf([is.String(), is.Number()]) 259 | }).validate({ 260 | // actually empty object 261 | }) && 262 | false === is.Object({ 263 | oneof: is.optional().OneOf([is.String(), is.Number()]) 264 | }).validate({ 265 | oneof: [] 266 | }) 267 | } 268 | ]; 269 | 270 | const personSchema = is.Object({ 271 | name: is.String(), 272 | nickname: is.optional().String(), 273 | hometown: is.String(), 274 | age: is.Number().Which(age => age > 5), 275 | hobbies: is.optional().ArrayOf(is.String().Which(str => str !== 'illegal activites')), 276 | favoriteNumberOrColor: is.optional().OneOf([is.String(), is.Number()]), 277 | }); 278 | 279 | const locationSchema = is.Object({ 280 | name: is.String(), 281 | coordinates: is.ArrayOf(is.Number()), 282 | population: is.optional().Number(), 283 | }); 284 | 285 | const everythingSchema = is.Object({ 286 | people: is.ArrayOf(personSchema), 287 | locations: is.ArrayOf(locationSchema) 288 | }).Which(everything => ( 289 | // this is a functional way to say that the hometown of each person 290 | // exists in locations, a.k.a. no one has a hometown which is not 291 | // defined in locations. 292 | everything.people.filter(person => ( 293 | everything.locations.filter(locations => locations.name == person.hometown).length == 0 294 | )).length == 0 295 | )).Which(everything => ( 296 | // this is a super complicated but functional way to say that there are no location duplicates based on their name... 297 | // (why js doesn't have `unique`?) 298 | everything.locations.map(location => location.name).filter((location, i, array) => array.indexOf(location) == i).length == everything.locations.length 299 | )); 300 | 301 | testCases.push( 302 | { 303 | description: 'complex test: person validation works', 304 | result: true === personSchema.validate({ 305 | name: 'John Doe', 306 | nickname: 'johnny', 307 | hometown: 'Budapest', 308 | age: 42, 309 | }) && 310 | true === personSchema.validate({ 311 | name: 'John Doe', 312 | hometown: 'Budapest', 313 | age: 42, 314 | hobbies: ['eating', 'coding', 'sleeping'] 315 | }) && 316 | true === personSchema.validate({ 317 | name: 'John Doe', 318 | hometown: 'Budapest', 319 | age: 42, 320 | hobbies: ['eating', 'coding', 'sleeping'], 321 | favoriteNumberOrColor: 42 322 | }) && 323 | false === personSchema.validate({ 324 | name: 'John Doe', 325 | hometown: 'Budapest', 326 | age: 42, 327 | hobbies: ['eating', 'coding', 'sleeping'], 328 | favoriteNumberOrColor: ['you', 'dont', 'tell', 'me', 'what', 'to', 'do'] 329 | }) && 330 | false === personSchema.validate({ 331 | name: 'John Doe', 332 | hometown: 'Budapest', 333 | age: 42, 334 | hobbies: ['eating', 'illegal activites', 'sleeping'] 335 | }) && 336 | false === personSchema.validate({ 337 | name: 'John Doe Jr.', 338 | hometown: 'Budapest', 339 | age: 2 340 | }) && 341 | false === personSchema.validate({ 342 | hometown: 'Budapest', 343 | age: 42 344 | }) 345 | }, 346 | { 347 | description: 'complex test: location validation works', 348 | result: true === locationSchema.validate({ 349 | name: 'Budapest', 350 | coordinates: [47.49, 19.04], 351 | population: 1 352 | }) && 353 | true === locationSchema.validate({ 354 | name: 'Budapest', 355 | coordinates: [47.49, 19.04], 356 | }) && 357 | false === locationSchema.validate({ 358 | name: 'Budapest', 359 | population: 42 360 | }) && 361 | false === locationSchema.validate({ 362 | coordinates: [47.49, 19.04], 363 | population: 42 364 | }) 365 | }, 366 | { 367 | description: 'complex test: composite schema for people and location validation works, with cross-referencing functional validation', 368 | result: true === everythingSchema.validate({ 369 | people: [{ 370 | name: 'John Doe', 371 | hometown: 'Budapest', 372 | age: 42, 373 | hobbies: ['eating', 'coding', 'sleeping'] 374 | }], 375 | locations: [{ 376 | name: 'Budapest', 377 | coordinates: [47.49, 19.04], 378 | population: 1 379 | }] 380 | }) && 381 | false === everythingSchema.validate({ 382 | people: [{ 383 | name: 'John Doe', 384 | hometown: 'Budapest', 385 | age: 42, 386 | hobbies: ['eating', 'coding', 'sleeping'] 387 | }], 388 | locations: [] 389 | }) && 390 | false === everythingSchema.validate({ 391 | people: [{ 392 | name: 'John Doe', 393 | hometown: 'Budapest', 394 | age: 42, 395 | hobbies: ['eating', 'coding', 'sleeping'] 396 | }], 397 | locations: [{ 398 | name: 'Not Budapest', 399 | coordinates: [47.49, 19.04], 400 | population: 1 401 | }] 402 | }) && 403 | true === everythingSchema.validate({ 404 | people: [{ 405 | name: 'Johnny Bravo', 406 | hometown: 'Aron City', 407 | age: 42, 408 | hobbies: ['looking good', 'dating girls', 'flexing'] 409 | }, { 410 | name: 'John Doe', 411 | hometown: 'Budapest', 412 | age: 42, 413 | hobbies: ['eating', 'coding', 'sleeping'] 414 | }, { 415 | name: 'Ms. Janet Doe', 416 | hometown: 'Budapest', 417 | age: 40, 418 | hobbies: ['eating', 'coding', 'sleeping'] 419 | }], 420 | locations: [{ 421 | name: 'Budapest', 422 | coordinates: [47.49, 19.04], 423 | population: 1 424 | }, { 425 | name: 'Aron City', 426 | coordinates: [34.05, 118.24], 427 | }] 428 | }) && 429 | false === everythingSchema.validate({ 430 | people: [{ 431 | name: 'John Doe', 432 | hometown: 'Budapest', 433 | age: 42, 434 | hobbies: ['eating', 'coding', 'sleeping'] 435 | }], 436 | locations: [{ 437 | name: 'Budapest', 438 | coordinates: [47.49, 19.04], 439 | population: 1 440 | }, { 441 | name: 'Budapest', 442 | coordinates: [47.49, 19.04], 443 | population: 1 444 | }] 445 | }) 446 | } 447 | ); 448 | 449 | // struct to hold output coloring special chars 450 | const c = { 451 | reset: '\x1b[0m', 452 | bold: '\x1b[1m', 453 | red: '\x1b[31m', 454 | green: '\x1b[32m', 455 | }; 456 | 457 | // boolean to sign if we had any test failures 458 | let __hadErrors = false; 459 | 460 | // check and print testcase results 461 | const check = (result, description) => { 462 | if ((result) === true) { // result could be any expression and we want to be as strict as possible 463 | console.log(`${c.bold}${c.green}[+]${c.reset} ${description}`); 464 | } else { 465 | console.log(`${c.bold}${c.red}[-]${c.reset} ${description}`); 466 | __hadErrors = true; 467 | }; 468 | }; 469 | 470 | // we're starting the testing 471 | console.log(`${c.bold}[i] Running tests...${c.reset}`); 472 | 473 | // iterate over all the testcases and check them 474 | testCases.forEach(testCase => check(testCase.result, testCase.description)); 475 | 476 | // just an empty line after the testcases 477 | console.log(''); 478 | 479 | // print testing verdict 480 | if (!__hadErrors) { 481 | // if we had no errors, we celebrate 482 | console.log(`${c.bold}${c.green}ALL TESTS PASSED!${c.reset}`); 483 | } else { 484 | // if we had errors, we make sure it's visible 485 | console.log(`${c.bold}${c.red}SOME TESTS FAILED!${c.reset}`); 486 | 487 | // we set the exit code to 1 to signal failure 488 | process.exit(1); 489 | } --------------------------------------------------------------------------------