Commit eda25aee authored by Sachinda 's avatar Sachinda

remove node

parent ba869fcb
Pipeline #8698 canceled with stages
build: components index.js
@component build --dev
components:
@component install --dev
clean:
rm -fr build components template.js
test:
open test/index.html
.PHONY: clean test
# type
Type assertions aka less-broken `typeof`.
## Example
```js
var type = require('type');
var obj = new Date;
if (type(obj) == 'date') ...
```
## API
```js
type(new Date) == 'date'
type({}) == 'object'
type(null) == 'null'
type(undefined) == 'undefined'
type("hey") == 'string'
type(true) == 'boolean'
type(false) == 'boolean'
type(12) == 'number'
type(type) == 'function'
type(/asdf/) == 'regexp'
type((function(){ return arguments })()) == 'arguments'
type([]) == 'array'
type(document.createElement('div')) == 'element'
type(NaN) == 'nan'
type(new Error('Ups! Something wrong...')) == 'error'
type(new Buffer) == 'buffer'
```
## License
MIT
{
"name": "type",
"description": "Cross-browser type assertions (less broken typeof)",
"version": "1.1.0",
"keywords": ["typeof", "type", "utility"],
"dependencies": {},
"development": {
"component/assert": "*"
},
"scripts": [
"index.js"
]
}
/**
* toString ref.
*/
var toString = Object.prototype.toString;
/**
* Return the type of `val`.
*
* @param {Mixed} val
* @return {String}
* @api public
*/
module.exports = function(val){
switch (toString.call(val)) {
case '[object Date]': return 'date';
case '[object RegExp]': return 'regexp';
case '[object Arguments]': return 'arguments';
case '[object Array]': return 'array';
case '[object Error]': return 'error';
}
if (val === null) return 'null';
if (val === undefined) return 'undefined';
if (val !== val) return 'nan';
if (val && val.nodeType === 1) return 'element';
if (isBuffer(val)) return 'buffer';
val = val.valueOf
? val.valueOf()
: Object.prototype.valueOf.apply(val);
return typeof val;
};
// code borrowed from https://github.com/feross/is-buffer/blob/master/index.js
function isBuffer(obj) {
return !!(obj != null &&
(obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor)
(obj.constructor &&
typeof obj.constructor.isBuffer === 'function' &&
obj.constructor.isBuffer(obj))
))
}
{
"_from": "component-type@1.2.1",
"_id": "component-type@1.2.1",
"_inBundle": false,
"_integrity": "sha1-ikeQFwAjjk/DIml3EjAibyS0Fak=",
"_location": "/component-type",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "component-type@1.2.1",
"name": "component-type",
"escapedName": "component-type",
"rawSpec": "1.2.1",
"saveSpec": null,
"fetchSpec": "1.2.1"
},
"_requiredBy": [
"/validate"
],
"_resolved": "https://registry.npmjs.org/component-type/-/component-type-1.2.1.tgz",
"_shasum": "8a47901700238e4fc32269771230226f24b415a9",
"_spec": "component-type@1.2.1",
"_where": "/private/var/www/db/coutch_db_create/node_modules/validate",
"bugs": {
"url": "https://github.com/component/type/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Cross-browser type assertions (less broken typeof)",
"homepage": "https://github.com/component/type#readme",
"keywords": [
"typeof",
"type",
"utility"
],
"license": "MIT",
"main": "index.js",
"name": "component-type",
"repository": {
"type": "git",
"url": "git+https://github.com/component/type.git"
},
"version": "1.2.1"
}
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="mocha.js"></script>
<script>mocha.setup('bdd')</script>
<script src="../build/build.js"></script>
<script src="tests.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
\ No newline at end of file
@charset "utf-8";
body {
font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
padding: 60px 50px;
}
#mocha ul, #mocha li {
margin: 0;
padding: 0;
}
#mocha ul {
list-style: none;
}
#mocha h1, #mocha h2 {
margin: 0;
}
#mocha h1 {
margin-top: 15px;
font-size: 1em;
font-weight: 200;
}
#mocha h1 a {
text-decoration: none;
color: inherit;
}
#mocha h1 a:hover {
text-decoration: underline;
}
#mocha .suite .suite h1 {
margin-top: 0;
font-size: .8em;
}
.hidden {
display: none;
}
#mocha h2 {
font-size: 12px;
font-weight: normal;
cursor: pointer;
}
#mocha .suite {
margin-left: 15px;
}
#mocha .test {
margin-left: 15px;
overflow: hidden;
}
#mocha .test.pending:hover h2::after {
content: '(pending)';
font-family: arial;
}
#mocha .test.pass.medium .duration {
background: #C09853;
}
#mocha .test.pass.slow .duration {
background: #B94A48;
}
#mocha .test.pass::before {
content: '✓';
font-size: 12px;
display: block;
float: left;
margin-right: 5px;
color: #00d6b2;
}
#mocha .test.pass .duration {
font-size: 9px;
margin-left: 5px;
padding: 2px 5px;
color: white;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
}
#mocha .test.pass.fast .duration {
display: none;
}
#mocha .test.pending {
color: #0b97c4;
}
#mocha .test.pending::before {
content: '◦';
color: #0b97c4;
}
#mocha .test.fail {
color: #c00;
}
#mocha .test.fail pre {
color: black;
}
#mocha .test.fail::before {
content: '✖';
font-size: 12px;
display: block;
float: left;
margin-right: 5px;
color: #c00;
}
#mocha .test pre.error {
color: #c00;
max-height: 300px;
overflow: auto;
}
#mocha .test pre {
display: block;
float: left;
clear: left;
font: 12px/1.5 monaco, monospace;
margin: 5px;
padding: 15px;
border: 1px solid #eee;
border-bottom-color: #ddd;
-webkit-border-radius: 3px;
-webkit-box-shadow: 0 1px 3px #eee;
-moz-border-radius: 3px;
-moz-box-shadow: 0 1px 3px #eee;
}
#mocha .test h2 {
position: relative;
}
#mocha .test a.replay {
position: absolute;
top: 3px;
right: 0;
text-decoration: none;
vertical-align: middle;
display: block;
width: 15px;
height: 15px;
line-height: 15px;
text-align: center;
background: #eee;
font-size: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
-webkit-transition: opacity 200ms;
-moz-transition: opacity 200ms;
transition: opacity 200ms;
opacity: 0.3;
color: #888;
}
#mocha .test:hover a.replay {
opacity: 1;
}
#mocha-report.pass .test.fail {
display: none;
}
#mocha-report.fail .test.pass {
display: none;
}
#mocha-error {
color: #c00;
font-size: 1.5 em;
font-weight: 100;
letter-spacing: 1px;
}
#mocha-stats {
position: fixed;
top: 15px;
right: 10px;
font-size: 12px;
margin: 0;
color: #888;
}
#mocha-stats .progress {
float: right;
padding-top: 0;
}
#mocha-stats em {
color: black;
}
#mocha-stats a {
text-decoration: none;
color: inherit;
}
#mocha-stats a:hover {
border-bottom: 1px solid #eee;
}
#mocha-stats li {
display: inline-block;
margin: 0 5px;
list-style: none;
padding-top: 11px;
}
code .comment { color: #ddd }
code .init { color: #2F6FAD }
code .string { color: #5890AD }
code .keyword { color: #8A6343 }
code .number { color: #2F6FAD }
This diff is collapsed.
var type = require('type')
, assert = require('component-assert');
describe('type', function(){
it('should match objects', function(){
function Foo(){}
assert('object' === type({}));
assert('object' === type(new Foo));
});
it('should match numbers', function(){
assert('number' === type(12));
assert('number' === type(1.0));
assert('number' === type(-5));
assert('number' === type(new Number(123)));
assert('number' === type(Infinity));
});
it('should match NaN', function () {
assert('nan' === type(NaN));
});
it('should match strings', function(){
assert('string' === type("test"));
assert('string' === type(new String('whoop')));
});
it('should match dates', function(){
assert('date' === type(new Date));
});
it('should match booleans', function(){
assert('boolean' === type(true));
assert('boolean' === type(false));
assert('boolean' === type(new Boolean(true)));
});
it('should match null', function(){
assert('null' === type(null));
});
it('should match undefined', function(){
assert('undefined' === type());
assert('undefined' === type(undefined));
});
it('should match arrays', function(){
assert('array' === type([]));
assert('array' === type(new Array()));
});
it('should match regexps', function(){
assert('regexp' === type(/asdf/));
assert('regexp' === type(new RegExp('weee')));
});
it('should match functions', function(){
assert('function' === type(function(){}));
});
it('should match arguments', function(){
assert('arguments' === type(arguments));
});
it('should match elements', function(){
assert('element' === type(document.createElement('div')));
});
it('should match errors', function(){
assert('error' === type(new Error('Ups!')));
});
it('should match buffers', function(){
var b = {};
assert('object' === type(b));
if (window.Buffer) {
var val = new Buffer(4);
assert('buffer' === type(val));
}
});
});
# dot
Get and set object properties with dot notation
## Installation
$ component install eivindfjeldstad/dot
## API
### dot.set(object, path, value)
```js
dot.set(obj, 'cool.aid', 'rocks');
assert(obj.cool.aid === 'rocks');
```
### dot.get(object, path)
```js
var value = dot.get(obj, 'cool.aid');
assert(value === 'rocks');
```
## License
MIT
{
"name": "dot",
"repo": "eivindfjeldstad/dot",
"description": "Get and set object properties with dot notation",
"version": "0.0.1",
"keywords": [],
"dependencies": {},
"development": {},
"license": "MIT",
"main": "index.js",
"scripts": [
"index.js"
]
}
\ No newline at end of file
/**
* Set given `path`
*
* @param {Object} obj
* @param {String} path
* @param {Mixed} val
* @api public
*/
exports.set = function (obj, path, val) {
var segs = path.split('.');
var attr = segs.pop();
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
obj[seg] = obj[seg] || {};
obj = obj[seg];
}
obj[attr] = val;
};
/**
* Get given `path`
*
* @param {Object} obj
* @param {String} path
* @return {Mixed}
* @api public
*/
exports.get = function (obj, path) {
var segs = path.split('.');
var attr = segs.pop();
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if (!obj[seg]) return;
obj = obj[seg];
}
return obj[attr];
};
\ No newline at end of file
{
"_from": "eivindfjeldstad-dot@0.0.1",
"_id": "eivindfjeldstad-dot@0.0.1",
"_inBundle": false,
"_integrity": "sha1-IvyXa/rzBuCDmjHbjoITSA+vuJM=",
"_location": "/eivindfjeldstad-dot",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "eivindfjeldstad-dot@0.0.1",
"name": "eivindfjeldstad-dot",
"escapedName": "eivindfjeldstad-dot",
"rawSpec": "0.0.1",
"saveSpec": null,
"fetchSpec": "0.0.1"
},
"_requiredBy": [
"/validate"
],
"_resolved": "https://registry.npmjs.org/eivindfjeldstad-dot/-/eivindfjeldstad-dot-0.0.1.tgz",
"_shasum": "22fc976bfaf306e0839a31db8e8213480fafb893",
"_spec": "eivindfjeldstad-dot@0.0.1",
"_where": "/private/var/www/db/coutch_db_create/node_modules/validate",
"bugs": {
"url": "https://github.com/eivindfjeldstad/dot/issues"
},
"bundleDependencies": false,
"deprecated": "Use @eivifj/dot instead",
"description": "Get and set object properties with dot notation",
"directories": {
"test": "test"
},
"homepage": "https://github.com/eivindfjeldstad/dot",
"keywords": [
"dot",
"notation",
"properties",
"object",
"path"
],
"license": "MIT",
"main": "index.js",
"name": "eivindfjeldstad-dot",
"repository": {
"type": "git",
"url": "git+https://github.com/eivindfjeldstad/dot.git"
},
"scripts": {
"test": "node test"
},
"version": "0.0.1"
}
var assert = require('assert');
var dot = require('..');
var tests = module.exports = {
'test set': function () {
var obj = {};
dot.set(obj, 'cool.aid', 'rocks');
assert(obj.cool.aid === 'rocks');
},
'test get': function () {
var obj = {};
obj.cool = {};
obj.cool.aid = 'rocks';
var value = dot.get(obj, 'cool.aid');
assert(value === 'rocks');
}
}
for (var t in tests) {
tests[t]();
}
console.log('All tests passed!');
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2014 object-hash contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This diff is collapsed.
This diff is collapsed.
{
"_from": "object-hash",
"_id": "object-hash@2.0.3",
"_inBundle": false,
"_integrity": "sha512-JPKn0GMu+Fa3zt3Bmr66JhokJU5BaNBIh4ZeTlaCBzrBsOeXzwcKKAK1tbLiPKgvwmPXsDvvLHoWh5Bm7ofIYg==",
"_location": "/object-hash",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "object-hash",
"name": "object-hash",
"escapedName": "object-hash",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.0.3.tgz",
"_shasum": "d12db044e03cd2ca3d77c0570d87225b02e1e6ea",
"_spec": "object-hash",
"_where": "/private/var/www/db/coutch_db_create",
"author": {
"name": "Scott Puleo",
"email": "puleos@gmail.com"
},
"browser": "./dist/object_hash.js",
"bugs": {
"url": "https://github.com/puleos/object-hash/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Generate hashes from javascript objects in node and the browser.",
"devDependencies": {
"browserify": "^16.2.3",
"gulp": "^4.0.0",
"gulp-browserify": "^0.5.1",
"gulp-coveralls": "^0.1.4",
"gulp-exec": "^3.0.1",
"gulp-istanbul": "^1.1.3",
"gulp-jshint": "^2.0.0",
"gulp-mocha": "^5.0.0",
"gulp-rename": "^1.2.0",
"gulp-replace": "^1.0.0",
"gulp-uglify": "^3.0.0",
"jshint": "^2.8.0",
"jshint-stylish": "^2.1.0",
"karma": "^4.2.0",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"mocha": "^6.2.0"
},
"engines": {
"node": ">= 6"
},
"files": [
"index.js",
"dist/object_hash.js"
],
"homepage": "https://github.com/puleos/object-hash",
"keywords": [
"object",
"hash",
"sha1",
"md5"
],
"license": "MIT",
"main": "./index.js",
"name": "object-hash",
"repository": {
"type": "git",
"url": "git+https://github.com/puleos/object-hash.git"
},
"scripts": {
"prepublish": "gulp dist",
"test": "node ./node_modules/.bin/mocha test"
},
"version": "2.0.3"
}
# object-hash
Generate hashes from objects and values in node and the browser. Uses node.js
crypto module for hashing. Supports SHA1 and many others (depending on the platform)
as well as custom streams (e.g. CRC32).
[![NPM](https://nodei.co/npm/object-hash.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/object-hash)
[![Travis CI](https://secure.travis-ci.org/puleos/object-hash.png?branch=master)](https://secure.travis-ci.org/puleos/object-hash?branch=master)
[![Coverage Status](https://coveralls.io/repos/puleos/object-hash/badge.svg?branch=master&service=github)](https://coveralls.io/github/puleos/object-hash?branch=master)
* Hash values of any type.
* Supports a keys only option for grouping similar objects with different values.
```js
var hash = require('object-hash');
hash({foo: 'bar'}) // => '67b69634f9880a282c14a0f0cb7ba20cf5d677e9'
hash([1, 2, 2.718, 3.14159]) // => '136b9b88375971dff9f1af09d7356e3e04281951'
```
## Versioning Disclaimer
Starting with version `1.1.8` (released April 2017), new versions will consider
the exact returned hash part of the API contract, i.e. changes that will affect
hash values will be considered `semver-major`. Previous versions may violate
that expectation.
For more information, see [this discussion](https://github.com/puleos/object-hash/issues/30).
## hash(value, options);
Generate a hash from any object or type. Defaults to sha1 with hex encoding.
* `algorithm` hash algo to be used: 'sha1', 'md5'. default: sha1
* This supports the algorithms returned by `crypto.getHashes()`. Note that the default of SHA-1 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired.
* `excludeValues` {true|false} hash object keys, values ignored. default: false
* `encoding` hash encoding, supports 'buffer', 'hex', 'binary', 'base64'. default: hex
* `ignoreUnknown` {true|*false} ignore unknown object types. default: false
* `replacer` optional function that replaces values before hashing. default: accept all values
* `respectFunctionProperties` {true|false} Whether properties on functions are considered when hashing. default: true
* `respectFunctionNames` {true|false} consider `name` property of functions for hashing. default: true
* `respectType` {true|false} Whether special type attributes (`.prototype`, `.__proto__`, `.constructor`)
are hashed. default: true
* `unorderedArrays` {true|false} Sort all arrays using before hashing. Note that this affects *all* collections,
i.e. including typed arrays, Sets, Maps, etc. default: false
* `unorderedSets` {true|false} Sort `Set` and `Map` instances before hashing, i.e. make
`hash(new Set([1, 2])) == hash(new Set([2, 1]))` return `true`. default: true
* `unorderedObjects` {true|false} Sort objects before hashing, i.e. make `hash({ x: 1, y: 2 }) === hash({ y: 2, x: 1 })`. default: true
* `excludeKeys` optional function for exclude specific key(s) from hashing, if returns true then exclude from hash. default: include all keys
## hash.sha1(value);
Hash using the sha1 algorithm.
Note that SHA-1 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired.
*Sugar method, equivalent to hash(value, {algorithm: 'sha1'})*
## hash.keys(value);
Hash object keys using the sha1 algorithm, values ignored.
*Sugar method, equivalent to hash(value, {excludeValues: true})*
## hash.MD5(value);
Hash using the md5 algorithm.
Note that the MD5 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired.
*Sugar method, equivalent to hash(value, {algorithm: 'md5'})*
## hash.keysMD5(value);
Hash object keys using the md5 algorithm, values ignored.
Note that the MD5 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired.
*Sugar method, equivalent to hash(value, {algorithm: 'md5', excludeValues: true})*
## hash.writeToStream(value, [options,] stream):
Write the information that would otherwise have been hashed to a stream, e.g.:
```js
hash.writeToStream({foo: 'bar', a: 42}, {respectType: false}, process.stdout)
// => e.g. 'object:a:number:42foo:string:bar'
```
## Installation
node:
```js
npm install object-hash
```
browser: */dist/object_hash.js*
```
<script src="object_hash.js" type="text/javascript"></script>
<script>
var hash = objectHash.sha1({foo:'bar'});
console.log(hash); // e003c89cdf35cdf46d8239b4692436364b7259f9
</script>
```
## Example usage
```js
var hash = require('object-hash');
var peter = {name: 'Peter', stapler: false, friends: ['Joanna', 'Michael', 'Samir'] };
var michael = {name: 'Michael', stapler: false, friends: ['Peter', 'Samir'] };
var bob = {name: 'Bob', stapler: true, friends: [] };
/***
* sha1 hex encoding (default)
*/
hash(peter);
// 14fa461bf4b98155e82adc86532938553b4d33a9
hash(michael);
// 4b2b30e27699979ce46714253bc2213010db039c
hash(bob);
// 38d96106bc8ef3d8bd369b99bb6972702c9826d5
/***
* hash object keys, values ignored
*/
hash(peter, { excludeValues: true });
// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c
hash(michael, { excludeValues: true });
// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c
hash.keys(bob);
// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c
/***
* hash object, ignore specific key(s)
*/
hash(peter, { excludeKeys: function(key) {
if ( key === 'friends') {
return true;
}
return false;
}
});
// 66b7d7e64871aa9fda1bdc8e88a28df797648d80
/***
* md5 base64 encoding
*/
hash(peter, { algorithm: 'md5', encoding: 'base64' });
// 6rkWaaDiG3NynWw4svGH7g==
hash(michael, { algorithm: 'md5', encoding: 'base64' });
// djXaWpuWVJeOF8Sb6SFFNg==
hash(bob, { algorithm: 'md5', encoding: 'base64' });
// lFzkw/IJ8/12jZI0rQeS3w==
```
## Legacy Browser Support
IE <= 8 and Opera <= 11 support dropped in version 0.3.0. If you require
legacy browser support you must either use an ES5 shim or use version 0.2.5
of this module.
## Development
```
git clone https://github.com/puleos/object-hash
```
## Node Docker Wrapper
If you want to stand this up in a docker container, you should take at look
at the [![node-object-hash](https://github.com/bean5/node-object-hash)](https://github.com/bean5/node-object-hash) project.
### gulp tasks
* `gulp watch` (default) watch files, test and lint on change/add
* `gulp test` unit tests
* `gulp karma` browser unit tests
* `gulp lint` jshint
* `gulp dist` create browser version in /dist
## License
MIT
## Changelog
### v2.0.0
Only Node.js versions `>= 6.0.0` are being tested in CI now.
No other breaking changes were introduced.
node_modules
\ No newline at end of file
test:
@./node_modules/.bin/mocha \
--reporter spec \
--bail
.PHONY: test
\ No newline at end of file
{
"name": "typecast",
"repo": "eivindfjeldstad/typecast",
"description": "Simple typecasting",
"version": "0.0.1",
"license": "MIT",
"main": "index.js",
"scripts": [
"index.js"
]
}
\ No newline at end of file
module.exports = typecast;
/**
* Cast given `val` to `type`
*
* @param {Mixed} val
* @param {String} type
* @api public
*/
function typecast (val, type) {
var fn = typecast[type];
if (typeof fn != 'function') throw new Error('cannot cast to ' + type);
return fn(val);
}
/**
* Cast `val` to `String`
*
* @param {Mixed} val
* @api public
*/
typecast.string = function (val) {
return val.toString();
};
/**
* Cast `val` to `Number`
*
* @param {Mixed} val
* @api public
*/
typecast.number = function (val) {
var num = parseFloat(val);
return isNaN(num)
? null
: num;
};
/**
* Cast `val` to a`Date`
*
* @param {Mixed} val
* @api public
*/
typecast.date = function (val) {
var date = new Date(val);
return isNaN(date.valueOf())
? null
: date;
};
/**
* Cast `val` to `Array`
*
* @param {Mixed} val
* @api public
*/
typecast.array = function (val) {
if (val instanceof Array) return val;
var arr = val.toString().split(',');
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].trim();
}
return arr;
};
/**
* Cast `val` to `Boolean`
*
* @param {Mixed} val
* @api public
*/
typecast.boolean = function (val) {
return !! val && val !== 'false';
};
\ No newline at end of file
{
"_from": "typecast@0.0.1",
"_id": "typecast@0.0.1",
"_inBundle": false,
"_integrity": "sha1-//t13La98d744pO2tuiT1sHtGd4=",
"_location": "/typecast",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "typecast@0.0.1",
"name": "typecast",
"escapedName": "typecast",
"rawSpec": "0.0.1",
"saveSpec": null,
"fetchSpec": "0.0.1"
},
"_requiredBy": [
"/validate"
],
"_resolved": "https://registry.npmjs.org/typecast/-/typecast-0.0.1.tgz",
"_shasum": "fffb75dcb6bdf1def8e293b6b6e893d6c1ed19de",
"_spec": "typecast@0.0.1",
"_where": "/private/var/www/db/coutch_db_create/node_modules/validate",
"bugs": {
"url": "https://github.com/eivindfjeldstad/typecast/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Simple typecasting",
"devDependencies": {
"mocha": "~1.17.0"
},
"homepage": "https://github.com/eivindfjeldstad/typecast#readme",
"license": "MIT",
"name": "typecast",
"repository": {
"type": "git",
"url": "git+https://github.com/eivindfjeldstad/typecast.git"
},
"version": "0.0.1"
}
#typecast
Simple typecasting in javascript.
##Example
```js
var typecast = require('typecast');
typecast(123, 'string') // => '123'
typecast('123', 'number') // => 123
typecast('a, b, c', 'array') // => ['a', 'b', 'c']
typecast('false', 'boolean') // => false
```
##API
###typecast(val, type)
Cast given `val` to `type`
###.string(val)
Cast `val` to `String`
###.number(val)
Cast `val` to `Number`
###.array(val)
Cast `val` to `Array`
###.boolean(val)
Cast `val` to `Boolean`
##Licence
MIT
\ No newline at end of file
var typecast = require('./');
var assert = require('assert');
describe('.string()', function () {
it('should return a string', function () {
assert(typecast.string(2) === '2');
assert(typeof typecast.string({}) == 'string');
})
})
describe('.number()', function () {
it('should return a number', function () {
assert(typecast.number('123') === 123);
})
it('should return null if typecasting fails', function () {
assert(typecast.number('abc') === null);
})
})
describe('.date()', function () {
it('should return a date', function () {
assert(typecast.date('2010 10 01').valueOf() === 1285884000000);
})
it('should return null if typecasting fails', function () {
assert(typecast.date('abc') === null);
})
})
describe('.array()', function () {
it('should return an array', function () {
var arr = [1, 2, 3];
assert(typecast.array(arr) === arr);
assert(typecast.array(1) instanceof Array);
assert(typecast.array('a, b, c').length == 3);
assert(typecast.array('a, b, c')[1] === 'b');
})
})
describe('.boolean()', function () {
it('should return a boolean', function () {
assert(typecast.boolean('abc') === true);
assert(typecast.boolean(0) === false);
assert(typecast.boolean('false') === false);
})
})
describe('typecast()', function () {
it('should work', function () {
assert(typecast(123, 'string') === '123');
});
it('should throw when given an invalid type', function () {
var err;
try {
typecast(1, 'invalid');
} catch (e) {
err = e;
}
assert(err);
});
});
\ No newline at end of file
MIT License
Copyright (c) 2018 Eivind Fjeldstad
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
/**
* Custom errors.
*
* @private
*/
var ValidationError =
/*#__PURE__*/
function (_Error) {
_inherits(ValidationError, _Error);
function ValidationError(message, path) {
var _this;
_classCallCheck(this, ValidationError);
_this = _possibleConstructorReturn(this, _getPrototypeOf(ValidationError).call(this, message));
defineProp(_assertThisInitialized(_this), 'path', path);
defineProp(_assertThisInitialized(_this), 'expose', true);
defineProp(_assertThisInitialized(_this), 'status', 400);
if (Error.captureStackTrace) {
Error.captureStackTrace(_assertThisInitialized(_this), ValidationError);
}
return _this;
}
return ValidationError;
}(_wrapNativeSuper(Error));
exports["default"] = ValidationError;
var defineProp = function defineProp(obj, prop, val) {
Object.defineProperty(obj, prop, {
enumerable: false,
configurable: true,
writable: true,
value: val
});
};
module.exports = exports.default;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
/**
* Default error messages.
*
* @private
*/
var Messages = {
// Type message
type: function type(prop, ctx, _type) {
if (typeof _type == 'function') {
_type = _type.name;
}
return "".concat(prop, " must be of type ").concat(_type, ".");
},
// Required message
required: function required(prop) {
return "".concat(prop, " is required.");
},
// Match message
match: function match(prop, ctx, regexp) {
return "".concat(prop, " must match ").concat(regexp, ".");
},
// Length message
length: function length(prop, ctx, len) {
if (typeof len == 'number') {
return "".concat(prop, " must have a length of ").concat(len, ".");
}
var min = len.min,
max = len.max;
if (min && max) {
return "".concat(prop, " must have a length between ").concat(min, " and ").concat(max, ".");
}
if (max) {
return "".concat(prop, " must have a maximum length of ").concat(max, ".");
}
if (min) {
return "".concat(prop, " must have a minimum length of ").concat(min, ".");
}
},
// Size message
size: function size(prop, ctx, _size) {
if (typeof _size == 'number') {
return "".concat(prop, " must have a size of ").concat(_size, ".");
}
var min = _size.min,
max = _size.max;
if (min !== undefined && max !== undefined) {
return "".concat(prop, " must be between ").concat(min, " and ").concat(max, ".");
}
if (max !== undefined) {
return "".concat(prop, " must be less than ").concat(max, ".");
}
if (min !== undefined) {
return "".concat(prop, " must be greater than ").concat(min, ".");
}
},
// Enum message
"enum": function _enum(prop, ctx, enums) {
var copy = enums.slice();
var last = copy.pop();
return "".concat(prop, " must be either ").concat(copy.join(', '), " or ").concat(last, ".");
},
// Default message
"default": function _default(prop) {
return "Validation failed for ".concat(prop, ".");
}
};
var _default2 = Messages;
exports["default"] = _default2;
module.exports = exports.default;
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.assign = assign;
exports.walk = walk;
exports.join = join;
var _eivindfjeldstadDot = _interopRequireDefault(require("eivindfjeldstad-dot"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Assign given key and value (or object) to given object
*
* @private
*/
function assign(key, val, obj) {
if (typeof key == 'string') {
obj[key] = val;
return;
}
Object.keys(key).forEach(function (k) {
return obj[k] = key[k];
});
}
/**
* Walk path
*
* @private
*/
function walk(path, obj, callback) {
var parts = path.split(/\.\$(?=\.|$)/);
var first = parts.shift();
var arr = _eivindfjeldstadDot["default"].get(obj, first);
if (!parts.length) {
return callback(first, arr);
}
if (!Array.isArray(arr)) {
return;
}
for (var i = 0; i < arr.length; i++) {
var current = join(i, first);
var next = current + parts.join('.$');
walk(next, obj, callback);
}
}
/**
* Join `path` with `prefix`
*
* @private
*/
function join(path, prefix) {
return prefix ? "".concat(prefix, ".").concat(path) : path;
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _componentType = _interopRequireDefault(require("component-type"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Default validators.
*
* @private
*/
var Validators = {
/**
* Validates presence.
*
* @param {Mixed} value - the value being validated
* @param {Object} ctx - the object being validated
* @param {Bolean} required
* @return {Boolean}
*/
required: function required(value, ctx, _required) {
if (_required === false) return true;
return value != null && value !== '';
},
/**
* Validates type.
*
* @param {Mixed} value - the value being validated
* @param {Object} ctx - the object being validated
* @param {String|Function} name name of the type or a constructor
* @return {Boolean}
*/
type: function type(value, ctx, name) {
if (value == null) return true;
if (typeof name == 'function') {
return value.constructor === name;
}
return (0, _componentType["default"])(value) === name;
},
/**
* Validates length.
*
* @param {String} value the string being validated
* @param {Object} ctx the object being validated
* @param {Object|Number} rules object with .min and/or .max props or a number
* @param {Number} [rules.min] - minimum length
* @param {Number} [rules.max] - maximum length
* @return {Boolean}
*/
length: function length(value, ctx, len) {
if (value == null) return true;
if (typeof len == 'number') {
return value.length === len;
}
var min = len.min,
max = len.max;
if (min && value.length < min) return false;
if (max && value.length > max) return false;
return true;
},
/**
* Validates size.
*
* @param {Number} value the number being validated
* @param {Object} ctx the object being validated
* @param {Object|Number} size object with .min and/or .max props or a number
* @param {String|Number} [size.min] - minimum size
* @param {String|Number} [size.max] - maximum size
* @return {Boolean}
*/
size: function size(value, ctx, _size) {
if (value == null) return true;
if (typeof _size == 'number') {
return value === _size;
}
var min = _size.min,
max = _size.max;
if (parseInt(min) != null && value < min) return false;
if (parseInt(max) != null && value > max) return false;
return true;
},
/**
* Validates enums.
*
* @param {String} value the string being validated
* @param {Object} ctx the object being validated
* @param {Array} enums array with allowed values
* @return {Boolean}
*/
"enum": function _enum(value, ctx, enums) {
if (value == null) return true;
return enums.includes(value);
},
/**
* Validates against given `regexp`.
*
* @param {String} value the string beign validated
* @param {Object} ctx the object being validated
* @param {RegExp} regexp the regexp to validate against
* @return {Boolean}
*/
match: function match(value, ctx, regexp) {
if (value == null) return true;
return regexp.test(value);
}
};
var _default = Validators;
exports["default"] = _default;
module.exports = exports.default;
\ No newline at end of file
type Type = Function | string
interface PropertyDefinition {
type?: Type;
required?: boolean;
length?: number | { min?: number; max?: number };
size?: number | { min?: number; max?: number };
enum?: string[];
each?: Rule;
elements?: Rule[];
match?: RegExp;
use?: { [key: string]: ValidationFunction };
message?: string | MessageFunction | { [key: string]: string | MessageFunction };
schema?: Schema;
properties?: SchemaDefinition;
}
type Rule = Type
| PropertyDefinition
| SchemaDefinition
| Schema
| RuleArray
// Remove when ts 3.7 is released
interface RuleArray extends Array<Rule> {}
interface SchemaDefinition {
[key: string]: Rule
}
interface ValidationFunction {
(value: any, ctx: object, ...args: any): boolean;
}
interface TypecastFunction {
(value: any): unknown;
}
interface MessageFunction {
(path: string, ctx: object, ...args: any): string;
}
interface ValidationOptions {
typecast?: boolean;
strip?: boolean;
}
export class ValidationError {
constructor(message: string, path: string);
path: string;
status: number;
expose: boolean;
}
export default class Schema {
constructor(definition?: SchemaDefinition, options?: ValidationOptions);
path(path: string, rules?: Rule): Property;
assert(target: { [key: string]: any }, options?: ValidationOptions): void;
validate(target: { [key: string]: any }, options?: ValidationOptions): ValidationError[];
message(validator: string, message: string | MessageFunction): Schema;
message(messages: { [validator: string]: string | MessageFunction }): Schema;
validator(name: string, fn: ValidationFunction): Schema;
validator(validators: { [name: string]: ValidationFunction }): Schema;
typecaster(name: string, fn: TypecastFunction): Schema;
typecaster(typecasters: { [name: string]: TypecastFunction }): Schema;
}
declare class Property {
constructor(name: string, schema: Schema);
message(messages: (string | MessageFunction) | { [validator: string]: string | MessageFunction }): Property;
schema(schema: Schema): Property;
use(fns: { [name: string]: ValidationFunction }): Property;
required(bool?: boolean): Property;
type(type: Type): Property;
string(): Property;
number(): Property;
array(): Property;
date(): Property;
length(rule: number | { min?: number; max?: number }): Property;
size(rule: number | { min?: number; max?: number }): Property;
enum(enums: string[]): Property;
match(regexp: RegExp): Property;
each(rules: Rule): Property;
elements(arr: Rule[]): Property;
properties(props: SchemaDefinition): Property;
path(path: string, rules?: Rule): Schema;
typecast<T>(value: any): T;
validate(value: any, ctx: object, path: string): ValidationError | null;
}
\ No newline at end of file
{
"_from": "validate",
"_id": "validate@5.1.0",
"_inBundle": false,
"_integrity": "sha512-Y+vJv+xR3XsaQM8W1rQvwc6is/sgCUBv3lvNKc2DZ1HcVcEWAaHVSFB5uoxkQnw2riUq77Rg5nv1u8YuuSu/Zw==",
"_location": "/validate",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "validate",
"name": "validate",
"escapedName": "validate",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/validate/-/validate-5.1.0.tgz",
"_shasum": "12d685e346067646cba491b27994ad98b6319fce",
"_spec": "validate",
"_where": "/private/var/www/db/coutch_db_create",
"author": {
"name": "Eivind Fjeldstad"
},
"bugs": {
"url": "https://github.com/eivindfjeldstad/validate/issues"
},
"bundleDependencies": false,
"dependencies": {
"component-type": "1.2.1",
"eivindfjeldstad-dot": "0.0.1",
"typecast": "0.0.1"
},
"deprecated": false,
"description": "Validate object properties in javascript.",
"devDependencies": {
"@babel/cli": "^7.6.0",
"@babel/core": "^7.6.0",
"@babel/preset-env": "^7.6.0",
"babel-jest": "^24.9.0",
"babel-plugin-add-module-exports": "^1.0.2",
"documentation": "^12.1.2",
"eslint": "^6.4.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-node": "^10.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"jest": "^24.9.0"
},
"engines": {
"node": ">=7.6"
},
"files": [
"build",
"index.d.ts"
],
"homepage": "https://github.com/eivindfjeldstad/validate#readme",
"jest": {
"testMatch": [
"**/test/**/*.js"
],
"coverageReporters": [
"text-summary",
"lcov"
],
"bail": true,
"testEnvironment": "node"
},
"keywords": [
"validation",
"validate",
"valid",
"object"
],
"license": "MIT",
"main": "build/schema.js",
"name": "validate",
"repository": {
"type": "git",
"url": "git+https://github.com/eivindfjeldstad/validate.git"
},
"scripts": {
"build": "babel -d build src",
"docs": "documentation readme ./src/*.js --section=API",
"lint": "eslint src test",
"prepublish": "npm run build",
"test": "jest",
"test-cov": "jest --coverage --runInBand --forceExit"
},
"version": "5.1.0"
}
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment