update, text, response

This commit is contained in:
2025-11-02 11:09:14 +01:00
parent 14776c86b0
commit eed8a4ddcf
2794 changed files with 156786 additions and 129204 deletions

View File

@@ -1,172 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
### [2.7.2](https://github.com/medikoo/type/compare/v2.7.1...v2.7.2) (2022-08-05)
### Maintenance Improvements
- **TS:** Improve `ensure` options handling ([#8](https://github.com/medikoo/type/issues/8)) ([4a54066](https://github.com/medikoo/type/commit/4a54066d7b55cef14ac4aa25a6f070296a043a6f)) ([Marco](https://github.com/borracciaBlu))
### [2.7.1](https://github.com/medikoo/type/compare/v2.7.0...v2.7.1) (2022-08-04)
### Maintenance Improvements
- **TS:** Fix support for `isOptional` in `ensure` options ([#7](https://github.com/medikoo/type/issues/7)) ([320f89b](https://github.com/medikoo/type/commit/320f89b89237e3e0ceff5e26b67cb18bd52cb42d)) ([Marco](https://github.com/borracciaBlu))
## [2.7.0](https://github.com/medikoo/type/compare/v2.6.1...v2.7.0) (2022-08-03)
### Features
- `BigInt.coerce` and `BigInt.ensure` ([e49ad78](https://github.com/medikoo/type/commit/e49ad787bd3aa67b7aa9f7a8ea4cde22a08bebc5))
### [2.6.1](https://github.com/medikoo/type/compare/v2.6.0...v2.6.1) (2022-07-29)
### Maintenance Improvements
- Declare TS types ([#6](https://github.com/medikoo/type/issues/6)) ([6378e2c](https://github.com/medikoo/type/commit/6378e2c457670bcb8a9b898e0f2502ed5b942d44)) ([Marco](https://github.com/borracciaBlu))
## [2.6.0](https://github.com/medikoo/type/compare/v2.5.0...v2.6.0) (2022-02-02)
### Features
- `constructor` validation utils ([74b99bb](https://github.com/medikoo/type/commit/74b99bbf6be27083bf9a053961edb2a585ae3e77))
## [2.5.0](https://github.com/medikoo/type/compare/v2.4.0...v2.5.0) (2021-03-08)
### Features
- `errorCode` option for `ensure*` utils ([777a1f2](https://github.com/medikoo/type/commit/777a1f2c9fd76defcd24d3a30cce49491947fef7))
## [2.4.0](https://github.com/medikoo/type/compare/v2.3.0...v2.4.0) (2021-03-08)
### Features
- `set/is` and `set/ensure` utils ([083ec23](https://github.com/medikoo/type/commit/083ec2351718c310f316dcfd8c624a13201e227f))
## [2.3.0](https://github.com/medikoo/type/compare/v2.2.0...v2.3.0) (2021-02-16)
### Features
- `map/is` and `map/ensure` utils ([aafd1cb](https://github.com/medikoo/type/commit/aafd1cbd8c888fda98d39fd17e59f38b078d7bcf))
## [2.2.0](https://github.com/medikoo/type/compare/v2.1.0...v2.2.0) (2021-02-11)
### Features
- Support `ensureItem` option in `array/ensure` ([8f74973](https://github.com/medikoo/type/commit/8f749739df9bfebf44087093e09c8f7341a33a09))
## [2.1.0](https://github.com/medikoo/type/compare/v2.0.0...v2.1.0) (2020-08-21)
### Features
- `ensure` util for cumulated input validation ([814c5a8](https://github.com/medikoo/type/commit/814c5a801ecac23d06d8a5f4bcafc4763a04408c))
- Provide an alternative error message with `options.name` ([c7751c0](https://github.com/medikoo/type/commit/c7751c084ee4f3d3ed10500db0edde2ff00e03a1))
- Support `%n` (meaningful name) token in error message resolver ([b0f374e](https://github.com/medikoo/type/commit/b0f374e54345c714fe37a90887ecfe60577ce133))
- Support `min` validation for natural numbers ([e703512](https://github.com/medikoo/type/commit/e70351248818d3e113110106ad174b42c5fd9b25))
- Support custom Error constructors ([c6ecb90](https://github.com/medikoo/type/commit/c6ecb90e21c1c778210934204cbe393fb89ef2f6))
### Bug Fixes
- Fix typo in error message ([2735533](https://github.com/medikoo/type/commit/2735533de28d33dfa13222743698169c92d08c09))
## [2.0.0](https://github.com/medikoo/type/compare/v1.2.0...v2.0.0) (2019-10-10)
### Features
- `allowedKeys` option for plain-object/ensure ([f81e72e](https://github.com/medikoo/type/commit/f81e72e))
- `ensurePropertyValue` option for plain-object/ensure ([c5ff8fb](https://github.com/medikoo/type/commit/c5ff8fb))
- Replace `coerceItem` with `ensureItem` option in iterable/ensure ([721494f](https://github.com/medikoo/type/commit/721494f))
- Seclude lib/resolve-error-message ([12636d9](https://github.com/medikoo/type/commit/12636d9))
- Validate options.ensureItem in iterable/ensure ([78da6c1](https://github.com/medikoo/type/commit/78da6c1))
### BREAKING CHANGES
- iterable/ensure no longer supports `coerceItem` option. Instead `ensureItem` was introduced
## [1.2.0](https://github.com/medikoo/type/compare/v1.1.0...v1.2.0) (2019-09-20)
### Bug Fixes
- Improve error message so it's not confusing ([97cd6b9](https://github.com/medikoo/type/commit/97cd6b9))
### Features
- 'coerceItem' option for iterable/ensure ([0818860](https://github.com/medikoo/type/commit/0818860))
## [1.1.0](https://github.com/medikoo/type/compare/v1.0.3...v1.1.0) (2019-09-20)
### Features
- `denyEmpty` option for iterables validation ([301d071](https://github.com/medikoo/type/commit/301d071))
### [1.0.3](https://github.com/medikoo/type/compare/v1.0.2...v1.0.3) (2019-08-06)
### Bug Fixes
- Recognize custom built ES5 era errors ([6462fac](https://github.com/medikoo/type/commit/6462fac))
### [1.0.2](https://github.com/medikoo/type/compare/v1.0.1...v1.0.2) (2019-08-06)
### Bug Fixes
- Recognize host errors (e.g. DOMException) ([96ef399](https://github.com/medikoo/type/commit/96ef399))
## [1.0.1](https://github.com/medikoo/type/compare/v1.0.0...v1.0.1) (2019-04-08)
# 1.0.0 (2019-04-05)
### Bug Fixes
- ensure 'is' functions can't crash ([59ceb78](https://github.com/medikoo/type/commit/59ceb78))
### Features
- array-length/coerce ([af8ddec](https://github.com/medikoo/type/commit/af8ddec))
- array-length/ensure ([d313eb6](https://github.com/medikoo/type/commit/d313eb6))
- array-like/ensure ([45f1ddd](https://github.com/medikoo/type/commit/45f1ddd))
- array-like/is ([9a026a5](https://github.com/medikoo/type/commit/9a026a5))
- array/ensure ([9db1515](https://github.com/medikoo/type/commit/9db1515))
- array/is ([9672839](https://github.com/medikoo/type/commit/9672839))
- date/ensure ([44e25a0](https://github.com/medikoo/type/commit/44e25a0))
- date/is ([0316558](https://github.com/medikoo/type/commit/0316558))
- ensure to not crash ([3998348](https://github.com/medikoo/type/commit/3998348))
- ensure/number ([134b5cb](https://github.com/medikoo/type/commit/134b5cb))
- error/ensure ([d5c8a30](https://github.com/medikoo/type/commit/d5c8a30))
- error/is-error ([4d6b899](https://github.com/medikoo/type/commit/4d6b899))
- finite/coerce ([accaad1](https://github.com/medikoo/type/commit/accaad1))
- finite/ensure ([51e4174](https://github.com/medikoo/type/commit/51e4174))
- function/ensure ([b624c9a](https://github.com/medikoo/type/commit/b624c9a))
- function/is ([dab8026](https://github.com/medikoo/type/commit/dab8026))
- integer/coerce ([89dea2e](https://github.com/medikoo/type/commit/89dea2e))
- integer/ensure ([44a7071](https://github.com/medikoo/type/commit/44a7071))
- iterable/ensure ([3d48841](https://github.com/medikoo/type/commit/3d48841))
- iterable/is ([cf09513](https://github.com/medikoo/type/commit/cf09513))
- lib/is-to-string-tag-supported ([c8c001d](https://github.com/medikoo/type/commit/c8c001d))
- natural-number/coerce ([d08fdd9](https://github.com/medikoo/type/commit/d08fdd9))
- natural-number/ensure ([6c24d12](https://github.com/medikoo/type/commit/6c24d12))
- number/coerce ([86ccf08](https://github.com/medikoo/type/commit/86ccf08))
- object/ensure ([a9e8eed](https://github.com/medikoo/type/commit/a9e8eed))
- object/is ([d2d7251](https://github.com/medikoo/type/commit/d2d7251))
- plain-function/ensure ([5186518](https://github.com/medikoo/type/commit/5186518))
- plain-function/is ([51bc791](https://github.com/medikoo/type/commit/51bc791))
- plain-object/ensure ([91cf5e5](https://github.com/medikoo/type/commit/91cf5e5))
- plain-object/is ([4dcf393](https://github.com/medikoo/type/commit/4dcf393))
- promise/ensure ([8d096a4](https://github.com/medikoo/type/commit/8d096a4))
- promise/is ([a00de02](https://github.com/medikoo/type/commit/a00de02))
- prototype/is ([b23bdcc](https://github.com/medikoo/type/commit/b23bdcc))
- reg-exp/ensure ([6f7bbcb](https://github.com/medikoo/type/commit/6f7bbcb))
- reg-exp/is ([9728519](https://github.com/medikoo/type/commit/9728519))
- safe-integer/coerce ([b8549c4](https://github.com/medikoo/type/commit/b8549c4))
- safe-integer/ensure ([a70ef3f](https://github.com/medikoo/type/commit/a70ef3f))
- string/coerce ([b25c71f](https://github.com/medikoo/type/commit/b25c71f))
- string/ensure ([b62577d](https://github.com/medikoo/type/commit/b62577d))
- support 'default' in resolveException ([e08332a](https://github.com/medikoo/type/commit/e08332a))
- switch config to ES3 based ([37606d9](https://github.com/medikoo/type/commit/37606d9))
- thenable/ensure ([6762c0d](https://github.com/medikoo/type/commit/6762c0d))
- thenable/is ([2711d70](https://github.com/medikoo/type/commit/2711d70))
- time-value/coerce ([27fd109](https://github.com/medikoo/type/commit/27fd109))
- time-value/ensure ([1f6a8ea](https://github.com/medikoo/type/commit/1f6a8ea))
- **string/coerce:** restrict toString acceptance ([2a87100](https://github.com/medikoo/type/commit/2a87100))
- value/ensure ([dd6d8cb](https://github.com/medikoo/type/commit/dd6d8cb))
- value/is ([fdf4763](https://github.com/medikoo/type/commit/fdf4763))

View File

@@ -1,15 +0,0 @@
ISC License
Copyright (c) 2019-2022, Mariusz Nowak, @medikoo, medikoo.com
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

View File

@@ -1,168 +0,0 @@
[![Build status][build-image]][build-url]
[![Tests coverage][cov-image]][cov-url]
[![npm version][npm-image]][npm-url]
# type
## Runtime validation and processing of JavaScript types
- Respects language nature and acknowledges its quirks
- Allows coercion in restricted forms (rejects clearly invalid input, normalizes permissible type deviations)
- No transpilation implied, written to work in all ECMAScript 3+ engines
## Use case
Validate arguments input in public API endpoints.
_For validation of more sophisticated input structures (as deeply nested configuration objects) it's recommended to consider more powerful schema based utlities (as [AJV](https://ajv.js.org/) or [@hapi/joi](https://hapi.dev/family/joi/))_
### Example usage
Bulletproof input arguments normalization and validation:
```javascript
const ensureString = require('type/string/ensure')
, ensureDate = require('type/date/ensure')
, ensureNaturalNumber = require('type/natural-number/ensure')
, isObject = require('type/object/is');
module.exports = (path, options = { min: 0 }) {
path = ensureString(path, { errorMessage: "%v is not a path" });
if (!isObject(options)) options = {};
const min = ensureNaturalNumber(options.min, { default: 0 })
, max = ensureNaturalNumber(options.max, { isOptional: true })
, startTime = ensureDate(options.startTime, { isOptional: true });
// ...logic
};
```
### Installation
```bash
npm install type
```
## Utilities
Aside of general [`ensure`](docs/ensure.md) validation util, following kind of utilities for recognized JavaScript types are provided:
##### `*/coerce`
Restricted coercion into primitive type. Returns coerced value or `null` if value is not coercible per rules.
##### `*/is`
Object type/kind confirmation, returns either `true` or `false`.
##### `*/ensure`
Value validation. Returns input value (in primitive cases possibly coerced) or if value doesn't meet the constraints throws `TypeError` .
Each `*/ensure` utility, accepts following options (eventually passed with second argument):
- `isOptional` - Makes `null` or `undefined` accepted as valid value. In such case instead of `TypeError` being thrown, `null` is returned.
- `default` - A value to be returned if `null` or `undefined` is passed as an input value.
- `errorMessage` - Custom error message. Following placeholders can be used:
- `%v` - To be replaced with short string representation of invalid value
- `%n` - To be replaced with meaninfgul name (to be passed with `name` option) of validated value. Not effective if `name` option is not present
- `errorCode` - Eventual error code to be exposed on `.code` error property
- `name` - Meaningful name for validated value, to be used in error message, assuming it contains `%n` placeholder
- `Error` - Alternative error constructor to be used (defaults to `TypeError`)
### Index
#### General utils:
- [`ensure`](docs/ensure.md)
#### Type specific utils:
- **Value**
- [`value/is`](docs/value.md#valueis)
- [`value/ensure`](docs/value.md#valueensure)
- **Object**
- [`object/is`](docs/object.md#objectis)
- [`object/ensure`](docs/object.md#objectensure)
- **Plain Object**
- [`plain-object/is`](docs/plain-object.md#plain-objectis)
- [`plain-object/ensure`](docs/plain-object.md#plain-objectensure)
- **String**
- [`string/coerce`](docs/string.md#stringcoerce)
- [`string/ensure`](docs/string.md#stringensure)
- **Number**
- [`number/coerce`](docs/number.md#numbercoerce)
- [`number/ensure`](docs/number.md#numberensure)
- **Finite Number**
- [`finite/coerce`](docs/finite.md#finitecoerce)
- [`finite/ensure`](docs/finite.md#finiteensure)
- **Integer Number**
- [`integer/coerce`](docs/integer.md#integercoerce)
- [`integer/ensure`](docs/integer.md#integerensure)
- **Safe Integer Number**
- [`safe-integer/coerce`](docs/safe-integer.md#safe-integercoerce)
- [`safe-integer/ensure`](docs/.md#safe-integerensure)
- **Natural Number**
- [`natural-number/coerce`](docs/natural-number.md#natural-numbercoerce)
- [`natural-number/ensure`](docs/natural-number.md#natural-numberensure)
- **Array Length**
- [`array-length/coerce`](docs/array-length.md#array-lengthcoerce)
- [`array-length/ensure`](docs/array-length.md#array-lengthensure)
- **Time Value**
- [`time-value/coerce`](docs/time-value.md#time-valuecoerce)
- [`time-value/ensure`](docs/time-value.md#time-valueensure)
- **BigInt**
- [`big-int/coerce`](docs/big-int.md#big-intcoerce)
- [`big-int/ensure`](docs/big-int.md#big-intensure)
- **Array Like**
- [`array-like/is`](docs/array-like.md#array-likeis)
- [`array-like/ensure`](docs/array-like.md#array-likeensure)
- **Array**
- [`array/is`](docs/array.md#arrayis)
- [`array/ensure`](docs/array.md#arrayensure)
- **Iterable**
- [`iterable/is`](docs/iterable.md#iterableis)
- [`iterable/ensure`](docs/iterable.md#iterableensure)
- **Set**
- [`set/is`](docs/set.md#setis)
- [`set/ensure`](docs/set.md#setensure)
- **Map**
- [`map/is`](docs/map.md#mapis)
- [`map/ensure`](docs/map.md#mapensure)
- **Date**
- [`date/is`](docs/date.md#dateis)
- [`date/ensure`](docs/date.md#dateensure)
- **Function**
- [`function/is`](docs/function.md#functionis)
- [`function/ensure`](docs/function.md#functionensure)
- **Constructor**
- [`constructor/is`](docs/constructor.md#plain-functionis)
- [`constructor/ensure`](docs/constructor.md#plain-functionensure)
- **Plain Function**
- [`plain-function/is`](docs/plain-function.md#plain-functionis)
- [`plain-function/ensure`](docs/plain-function.md#plain-functionensure)
- **Reg Exp**
- [`reg-exp/is`](docs/reg-exp.md#reg-expis)
- [`reg-exp/ensure`](docs/.md#reg-expensure)
- **Thenable**
- [`thenable/is`](docs/thenable.md#thenableis)
- [`thenable/ensure`](docs/thenable.md#thenableensure)
- **Promise**
- [`promise/is`](docs/promise.md#promiseis)
- [`promise/ensure`](docs/promise.md#promiseensure)
- **Error**
- [`error/is`](docs/error.md#erroris)
- [`error/ensure`](docs/error.md#errorensure)
- **Prototype**
- [`prototype/is`](docs/prototype.md#prototypeis)
### Tests
$ npm test
[build-image]: https://github.com/medikoo/type/workflows/Integrate/badge.svg
[build-url]: https://github.com/medikoo/type/actions?query=workflow%3AIntegrate
[cov-image]: https://img.shields.io/codecov/c/github/medikoo/type.svg
[cov-url]: https://codecov.io/gh/medikoo/type
[npm-image]: https://img.shields.io/npm/v/type.svg
[npm-url]: https://www.npmjs.com/package/type

View File

@@ -1,10 +0,0 @@
"use strict";
var coerceToSafeInteger = require("../safe-integer/coerce");
module.exports = function (value) {
value = coerceToSafeInteger(value);
if (!value) return value;
if (value < 0) return null;
return value;
};

View File

@@ -1,15 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, coerce = require("./coerce");
module.exports = function (value/*, options*/) {
var coerced = coerce(value);
if (coerced !== null) return coerced;
var options = arguments[1];
var errorMessage =
options && options.name
? "Expected an array length for %n, received %v"
: "%v is not an array length";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,14 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value/*, options*/) {
if (is(value, arguments[1])) return value;
var options = arguments[1];
var errorMessage =
options && options.name
? "Expected an array like for %n, received %v"
: "%v is not an array like";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,21 +0,0 @@
"use strict";
var coerceToArrayLength = require("../array-length/coerce")
, isObject = require("../object/is");
module.exports = function (value/*, options*/) {
if (!isObject(value)) {
var options = arguments[1];
if (isObject(options) && options.allowString && typeof value === "string") return true;
return false;
}
if (typeof value === "function") return false;
var length;
try { length = value.length; }
catch (error) { return false; }
if (coerceToArrayLength(length) === null) return false;
return true;
};

View File

@@ -1,43 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, resolveErrorMessage = require("../lib/resolve-error-message")
, toShortString = require("../lib/to-short-string")
, ensurePlainFunction = require("../plain-function/ensure")
, is = require("./is");
var objHasOwnProperty = Object.prototype.hasOwnProperty, invalidItemsLimit = 3;
module.exports = function (value /*, options*/) {
var options = arguments[1];
var mainErrorMessage =
options && options.name ? "Expected an array for %n, received %v" : "%v is not an array";
if (!is(value)) return resolveException(value, mainErrorMessage, options);
if (!options) return value;
var ensureItem = ensurePlainFunction(options.ensureItem, { isOptional: true });
if (ensureItem) {
var coercedValue = [], invalidItems;
for (var index = 0, length = value.length; index < length; ++index) {
if (!objHasOwnProperty.call(value, index)) continue;
var coercedItem;
try {
coercedItem = ensureItem(value[index]);
} catch (error) {
if (!invalidItems) invalidItems = [];
if (invalidItems.push(toShortString(value[index])) === invalidItemsLimit) break;
}
if (invalidItems) continue;
coercedValue[index] = coercedItem;
}
if (invalidItems) {
throw new TypeError(
resolveErrorMessage(mainErrorMessage, value, options) +
".\n Following items are invalid: " +
invalidItems.join(", ")
);
}
return coercedValue;
}
return value;
};

View File

@@ -1,27 +0,0 @@
"use strict";
var isPrototype = require("../prototype/is");
var isArray;
if (typeof Array.isArray === "function") {
isArray = Array.isArray;
} else {
var objectToString = Object.prototype.toString, objectTaggedString = objectToString.call([]);
isArray = function (value) { return objectToString.call(value) === objectTaggedString; };
}
module.exports = function (value) {
if (!isArray(value)) return false;
// Sanity check (reject objects which do not expose common Array interface)
if (!hasOwnProperty.call(value, "length")) return false;
try {
if (typeof value.length !== "number") return false;
if (typeof value.push !== "function") return false;
if (typeof value.splice !== "function") return false;
} catch (error) {
return false;
}
return !isPrototype(value);
};

View File

@@ -1,13 +0,0 @@
"use strict";
var isValue = require("../value/is");
// Sanity BigInt support check
BigInt(0);
module.exports = function (value) {
if (!isValue(value)) return null;
if (typeof value === "bigint") return value;
try { return BigInt(value); }
catch (error) { return null; }
};

View File

@@ -1,13 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, coerce = require("./coerce");
module.exports = function (value /*, options*/) {
var coerced = coerce(value);
if (coerced !== null) return coerced;
var options = arguments[1];
var errorMessage =
options && options.name ? "Expected bigint for %n, received %v" : "%v is not a bigint";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,14 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value /*, options*/) {
if (is(value)) return value;
var options = arguments[1];
var errorMessage =
options && options.name
? "Expected a constructor function for %n, received %v"
: "%v is not a constructor function";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,12 +0,0 @@
"use strict";
var isFunction = require("../function/is");
var constructorRe = /^\s*(?:class[\s{/}]|function[\s(])/
, functionToString = Function.prototype.toString;
module.exports = function (value) {
if (!isFunction(value)) return false;
if (!constructorRe.test(functionToString.call(value))) return false;
return true;
};

View File

@@ -1,12 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value/*, options*/) {
if (is(value)) return value;
var options = arguments[1];
var errorMessage =
options && options.name ? "Expected a date for %n, received %v" : "%v is not a date";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,26 +0,0 @@
"use strict";
var isPrototype = require("../prototype/is");
var dateValueOf = Date.prototype.valueOf;
module.exports = function (value) {
if (!value) return false;
try {
// Sanity check (reject objects which do not expose common Date interface)
if (typeof value.getFullYear !== "function") return false;
if (typeof value.getTimezoneOffset !== "function") return false;
if (typeof value.setFullYear !== "function") return false;
// Ensure its native Date object (has [[DateValue]] slot)
dateValueOf.call(value);
} catch (error) {
return false;
}
// Ensure it hosts valid date
if (isNaN(value)) return false;
return !isPrototype(value);
};

View File

@@ -1,27 +0,0 @@
# Array length
_number_ primitive that conforms as valid _array length_
## `array-length/coerce`
Follows [`safe-integer/coerce`](safe-integer.md#safe-integercoerce) but returns `null` in place of values which are below `0`
```javascript
const coerceToArrayLength = require("type/safe-integer/coerce");
coerceToArrayLength("12.95"); // 12
coerceToArrayLength(9007199254740992); // null
coerceToArrayLength(null); // null
```
## `array-length/ensure`
If given argument is an _array length_ coercible value (via [`array-length/coerce`](#array-lengthcoerce)) returns result number.
Otherwise `TypeError` is thrown.
```javascript
const ensureArrayLength = require("type/array-length/ensure");
ensureArrayLength(12.93); // "12"
ensureArrayLength(9007199254740992); // Thrown TypeError: 9007199254740992 is not a valid array length
```

View File

@@ -1,33 +0,0 @@
# Array Like
_Array-like_ value (any value with `length` property)
## `array-like/is`
Restricted _array-like_ confirmation. Returns true for every value that meets following contraints
- is an _object_ (or with `allowString` option, a _string_)
- is not a _function_
- Exposes `length` that meets [`array-length`](array-length.md#array-lengthcoerce) constraints
```javascript
const isArrayLike = require("type/array-like/is");
isArrayLike([]); // true
isArrayLike({}); // false
isArrayLike({ length: 0 }); // true
isArrayLike("foo"); // false
isArrayLike("foo", { allowString: true }); // true
```
## `array-like/ensure`
If given argument is an _array-like_, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensureArrayLike = require("type/array-like/ensure");
ensureArrayLike({ length: 0 }); // { length: 0 }
ensureArrayLike("foo", { allowString: true }); // "foo"
ensureArrayLike({}); // Thrown TypeError: null is not an iterable
```

View File

@@ -1,46 +0,0 @@
# Array
_Array_ instance
## `array/is`
Confirms if given object is a native array
```javascript
const isArray = require("type/array/is");
isArray([]); // true
isArray({}); // false
isArray("foo"); // false
```
## `array/ensure`
If given argument is an array, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensureArray = require("type/array/ensure");
ensureArray(["foo"]); // ["foo"]
ensureArray("foo"); // Thrown TypeError: foo is not an array
```
### Confirming on items
Items can be validated by passing `ensureItem` option. Note that in this case:
- A newly created instance of an array with coerced item values is returned
- Error message lists up to three items which are invalid
```javascript
const ensureString = require("type/string/ensure");
ensureArray([12], { ensureItem: ensureString }); // ["12"]
/*
Below invocation with crash with:
TypeError: 23, [object Object], [object Object] is not a valid array.
Following items are invalid: [object Object], [object Object]
*/
ensureArray([23, {}, {}], { ensureItem: ensureString });
```

View File

@@ -1,27 +0,0 @@
# BigInt
_bigint_ primitive
## `big-int/coerce`
BigInt coercion. If value can be coerced by `BigInt` its result is returned.
For all other values `null` is returned
```javascript
const coerceToBigInt = require("type/big-int/coerce");
coerceToBigInt(12); // 12n
coerceToBigInt(undefined); // null
```
## `big-int/ensure`
If given argument is a _bigint_ coercible value (via [`big-int/coerce`](#big-intcoerce)) returns result bigint.
Otherwise `TypeError` is thrown.
```javascript
const ensureBigInt = require("type/big-int/ensure");
ensureBigInt(12); // 12n
ensureBigInt(null); // Thrown TypeError: null is not a bigint
```

View File

@@ -1,28 +0,0 @@
# Constructor
A _Function_ instance that's a _constructor_ (either regular function or _class_)
## `constructor/is`
Confirms if given object is a constructor function\_
```javascript
const isConstructor = require("type/constructor/is");
isConstructor(function () {}); // true
isConstructor(() => {}); // false
isConstructor(class {}); // true
isConstructor("foo"); // false
```
## `constructor/ensure`
If given argument is a _constructor function_, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensureConstructor = require("type/constructor/ensure");
const fn = function () {};
ensureConstructor(fn); // fn
ensureConstructor(() => {}); // Thrown TypeError: () => {} is not a constructor function
```

View File

@@ -1,28 +0,0 @@
# Date
_Date_ instance
## `date/is`
Confirms if given object is a native date, and is not an _Invalid Date_
```javascript
const isDate = require("type/date/is");
isDate(new Date()); // true
isDate(new Date("Invalid date")); // false
isDate(Date.now()); // false
isDate("foo"); // false
```
## `date/ensure`
If given argument is a date object, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensureDate = require("type/date/ensure");
const date = new Date();
ensureDate(date); // date
ensureDate(123123); // Thrown TypeError: 123123 is not a date object
```

View File

@@ -1,40 +0,0 @@
# `ensure(validationDatum1[, ...validationDatumN[, options]])`
Provides a complete cumulated input validation for an API endpoint. Validates multiple input arguments and consolidates eventual errors into one.
## Arguments
### `validationDatum1[, ...validationDatumN]`
For each argument to be validated a `validationDatum` of following stucture should be defined:
```javascript
[argumentName, inputValue, ensureFunction, (options = {})];
```
- `argumentName` - Name of validated argument (used for meaningful error messaging)
- `inputValue` - An argument value as passed to function
- `ensureFunction` - An `ensureX` function with which argument should be validated (e.g. if we're after string, then we need [string/ensure](string.md#stringensure))
- `options` - Optional, extra options to be passed to `ensureX` function
### `[options]`
Eventual options be passed to underlying `ensureX` functions. If custom error constructor is passed with an `Error` option, then cumulated error is created with this constructor.
## Usage example
```javascript
const ensure = require("type/ensure");
const ensureString = require("type/string/ensure");
const ensureNaturalNumber = require("type/natural-number/ensure");
const resolveRepositoryIssue = (repoName, issueNumber) => {
// Validate input
[repoName, issueNumber] = ensure(
["repoName", repoName, ensureString],
["issueNumber", issueNumber, ensureNaturalNumber],
{ Error: UserError }
);
// ... logic
};
```

View File

@@ -1,26 +0,0 @@
# Error
_Error_ instance
## `error/is`
Confirms if given object is a native error object
```javascript
const isError = require("type/error/is");
isError(new Error()); // true
isError({ message: "Fake error" }); // false
```
## `error/ensure`
If given argument is an error object, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensureError = require("type/error/ensure");
const someError = new Error("Some error");
ensureError(someError); // someError
ensureError({ message: "Fake error" }); // Thrown TypeError: [object Object] is not an error object
```

View File

@@ -1,27 +0,0 @@
# Finite Number
Finite _number_ primitive
## `finite/coerce`
Follows [`number/coerce`](number.md#numbercoerce) additionally rejecting `Infinity` and `-Infinity` values (`null` is returned if given values coerces to them)
```javascript
const coerceToFinite = require("type/finite/coerce");
coerceToFinite("12"); // 12
coerceToFinite(Infinity); // null
coerceToFinite(null); // null
```
## `finite/ensure`
If given argument is a finite number coercible value (via [`finite/coerce`](#finitecoerce)) returns result number.
Otherwise `TypeError` is thrown.
```javascript
const ensureFinite = require("type/finite/ensure");
ensureFinite(12); // "12"
ensureFinite(null); // Thrown TypeError: null is not a finite number
```

View File

@@ -1,28 +0,0 @@
# Function
_Function_ instance
## `function/is`
Confirms if given object is a native function
```javascript
const isFunction = require("type/function/is");
isFunction(function () {}); // true
isFunction(() => {}); // true
isFunction(class {}); // true
isFunction("foo"); // false
```
## `function/ensure`
If given argument is a function object, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensureFunction = require("type/function/ensure");
const fn = function () {};
ensureFunction(fn); // fn
ensureFunction(/foo/); // Thrown TypeError: /foo/ is not a function
```

View File

@@ -1,27 +0,0 @@
# Integer Number
Integer _number_ primitive
## `integer/coerce`
Follows [`finite/coerce`](finite.md#finitecoerce) additionally stripping decimal part from the number
```javascript
const coerceToInteger = require("type/integer/coerce");
coerceToInteger("12.95"); // 12
coerceToInteger(Infinity); // null
coerceToInteger(null); // null
```
## `integer/ensure`
If given argument is an integer coercible value (via [`integer/coerce`](#integercoerce)) returns result number.
Otherwise `TypeError` is thrown.
```javascript
const ensureInteger = require("type/integer/ensure");
ensureInteger(12.93); // "12"
ensureInteger(null); // Thrown TypeError: null is not an integer
```

View File

@@ -1,65 +0,0 @@
# Iterable
Value which implements _iterable_ protocol
## `iterable/is`
Confirms if given object is an _iterable_ and is not a _string_ (unless `allowString` option is passed)
```javascript
const isIterable = require("type/iterable/is");
isIterable([]); // true
isIterable({}); // false
isIterable("foo"); // false
isIterable("foo", { allowString: true }); // true
```
Supports also `denyEmpty` option
```javascript
isIterable([], { denyEmpty: true }); // false
isIterable(["foo"], { denyEmpty: true }); // true
```
## `iterable/ensure`
If given argument is an _iterable_, it is returned back. Otherwise `TypeError` is thrown.
By default _string_ primitives are rejected unless `allowString` option is passed.
```javascript
const ensureIterable = require("type/iterable/ensure");
ensureIterable([]); // []
ensureIterable("foo", { allowString: true }); // "foo"
ensureIterable({}); // Thrown TypeError: null is not expected iterable
```
### Denying empty iterables
Pass `denyEmpty` option to require non empty iterables
```javascript
ensureIterable([], { denyEmpty: true }); // Thrown TypeError: [] is not expected iterable
```
### Confirming on items
Items can be validated by passing `ensureItem` option. Note that in this case:
- A newly created instance of array with coerced values is returned
- Error message lists up to three invalid items
```javascript
const ensureString = require("type/string/ensure");
ensureIterable(new Set(["foo", 12]), { ensureItem: ensureString }); // ["foo", "12"]
/*
Below invocation with crash with:
TypeError: [object Set] is not expected iterable value.
Following items are invalid:
- [object Object]
*/
ensureIterable(new Set(["foo", {}]), { ensureItem: ensureString });
```

View File

@@ -1,27 +0,0 @@
# Map
_Map_ instance
## `map/is`
Confirms if given object is a native _map_
```javascript
const isMap = require("type/map/is");
isMap(new Map()); // true
isMap(new Set()); // false
isMap({}); // false
```
## `map/ensure`
If given argument is a _map_, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensureMap = require("type/map/ensure");
const map = new Map();
ensureMap(map); // map
eensureMap({}); // Thrown TypeError: [object Object] is not a map
```

View File

@@ -1,27 +0,0 @@
# Natural Number
Natural _number_ primitive
## `natural-number/coerce`
Follows [`integer/coerce`](integer.md#integercoerce) but returns `null` for values below `0`
```javascript
const coerceToNaturalNumber = require("type/natural-number/coerce");
coerceToNaturalNumber("12.95"); // 12
coerceToNaturalNumber(-120); // null
coerceToNaturalNumber(null); // null
```
## `natural-number/ensure`
If given argument is a natural number coercible value (via [`natural-number/coerce`](#natural-numbercoerce)) returns result number.
Otherwise `TypeError` is thrown.
```javascript
const ensureNaturalNumber = require("type/natural-number/ensure");
ensureNaturalNumber(12.93); // "12"
ensureNaturalNumber(-230); // Thrown TypeError: null is not a natural number
```

View File

@@ -1,33 +0,0 @@
# Number
_number_ primitive
## `number/coerce`
Restricted number coercion. Returns number presentation for every value that follows below constraints
- is implicitly coercible to number
- is neither `null` nor `undefined`
- is not `NaN` and doesn't coerce to `NaN`
For all other values `null` is returned
```javascript
const coerceToNumber = require("type/number/coerce");
coerceToNumber("12"); // 12
coerceToNumber({}); // null
coerceToNumber(null); // null
```
## `number/ensure`
If given argument is a number coercible value (via [`number/coerce`](#numbercoerce)) returns result number.
Otherwise `TypeError` is thrown.
```javascript
const ensureNumber = require("type/number/ensure");
ensureNumber(12); // "12"
ensureNumber(null); // Thrown TypeError: null is not a number
```

View File

@@ -1,28 +0,0 @@
# Object
_Object_, any non-primitive value
## `object/is`
Confirms if passed value is an object
```javascript
const isObject = require("type/object/is");
isObject({}); // true
isObject(true); // false
isObject(null); // false
```
## `object/ensure`
If given argument is an object, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensureObject = require("type/object/ensure");
const obj = {};
ensureObject(obj); // obj
ensureString(null); // Thrown TypeError: null is not an object
```

View File

@@ -1,28 +0,0 @@
# Plain Function
A _Function_ instance that is not a _Class_
## `plain-function/is`
Confirms if given object is a _plain function_
```javascript
const isPlainFunction = require("type/plain-function/is");
isPlainFunction(function () {}); // true
isPlainFunction(() => {}); // true
isPlainFunction(class {}); // false
isPlainFunction("foo"); // false
```
## `plain-function/ensure`
If given argument is a _plain function_ object, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensurePlainFunction = require("type/function/ensure");
const fn = function () {};
ensurePlainFunction(fn); // fn
ensurePlainFunction(class {}); // Thrown TypeError: class is not a plain function
```

View File

@@ -1,69 +0,0 @@
# Plain Object
A _plain object_
- Inherits directly from `Object.prototype` or `null`
- Is not a constructor's `prototype` property
## `plain-object/is`
Confirms if given object is a _plain object_
```javascript
const isPlainObject = require("type/plain-object/is");
isPlainObject({}); // true
isPlainObject(Object.create(null)); // true
isPlainObject([]); // false
```
## `plain-object/ensure`
If given argument is a plain object it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensurePlainObject = require("type/plain-object/ensure");
ensurePlainObject({}); // {}
ensurePlainObject("foo"); // Thrown TypeError: foo is not a plain object
```
### Confirming on keys
Keys can be validated by passing `allowedKeys` option. Note that in this case:
- Error message lists up to three invalid keys
```javascript
const allowedKeys = ["foo"];
ensurePlainObject({}, { allowedKeys }); // {}
ensurePlainObject({ foo: "bar" }, { allowedKeys }); // { foo: 'bar' }
/*
Below invocation with crash with:
TypeError: [object Object] is not a valid plain object.
Following keys are unexpected: lorem, ipsum
*/
ensurePlainObject({ foo: "bar", lorem: 1, ipsum: 2 }, { allowedKeys });
```
### Confirming on property values
Property values can be validated by passing `ensurePropertyValue` option. Note that in this case:
- A newly created instance of plain object with coerced values is returned
- Error message lists up to three keys that contain invalid values
```javascript
const ensureString = require("type/string/ensure");
ensurePlainObject({ foo: 12 }, { ensurePropertyValue: ensureString }); // { foo: '12' }
/*
Below invocation with crash with:
TypeError: [object Object] is not a valid plain object.
Valuees for following keys are invalid: lorem, ipsum
*/
ensurePlainObject({ foo: 23, lorem: {}, ipsum: {} }, { ensurePropertyValue: ensureString });
```

View File

@@ -1,27 +0,0 @@
# Promise
_Promise_ instance
## `promise/is`
Confirms if given object is a native _promise_
```javascript
const isPromise = require("type/promise/is");
isPromise(Promise.resolve()); // true
isPromise({ then: () => {} }); // false
isPromise({}); // false
```
## `promise/ensure`
If given argument is a promise, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensurePromise = require("type/promise/ensure");
const promise = Promise.resolve();
ensurePromise(promise); // promise
eensurePromise({}); // Thrown TypeError: [object Object] is not a promise
```

View File

@@ -1,15 +0,0 @@
# Prototype
Some constructor's `prototype` property
## `prototype/is`
Confirms if given object serves as a _prototype_ property
```javascript
const isPrototype = require("type/prototype/is");
isPrototype({}); // false
isPrototype(Object.prototype); // true
isPrototype(Array.prototype); // true
```

View File

@@ -1,26 +0,0 @@
# RegExp
_RegExp_ instance
## `reg-exp/is`
Confirms if given object is a native regular expression object
```javascript
const isRegExp = require("type/reg-exp/is");
isRegExp(/foo/);
isRegExp({}); // false
isRegExp("foo"); // false
```
## `reg-exp/ensure`
If given argument is a regular expression object, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensureRegExp = require("type/reg-exp/ensure");
ensureRegExp(/foo/); // /foo/
ensureRegExp("foo"); // Thrown TypeError: null is not a regular expression object
```

View File

@@ -1,27 +0,0 @@
# Safe Integer Number
Safe integer _number_ primitive
## `safe-integer/coerce`
Follows [`integer/coerce`](integer.md#integercoerce) but returns `null` in place of values which are beyond `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER` range.
```javascript
const coerceToSafeInteger = require("type/safe-integer/coerce");
coerceToInteger("12.95"); // 12
coerceToInteger(9007199254740992); // null
coerceToInteger(null); // null
```
## `safe-integer/ensure`
If given argument is a safe integer coercible value (via [`safe-integer/coerce`](#safe-integercoerce)) returns result number.
Otherwise `TypeError` is thrown.
```javascript
const ensureSafeInteger = require("type/safe-integer/ensure");
ensureSafeInteger(12.93); // "12"
ensureSafeInteger(9007199254740992); // Thrown TypeError: null is not a safe integer
```

View File

@@ -1,27 +0,0 @@
# Set
_Set_ instance
## `set/is`
Confirms if given object is a native set\_
```javascript
const isSet = require("type/set/is");
isSet(new Set()); // true
isSet(new Map()); // false
isSet({}); // false
```
## `Set/ensure`
If given argument is a _set_, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensureSet = require("type/set/ensure");
const set = new Set();
ensureSet(set); // set
eensureSet({}); // Thrown TypeError: [object Object] is not a set
```

View File

@@ -1,32 +0,0 @@
# String
_string_ primitive
## `string/coerce`
Restricted string coercion. Returns string presentation for every value that follows below constraints
- is implicitly coercible to string
- is neither`null` nor `undefined`
- its `toString` method is not `Object.prototype.toString`
For all other values `null` is returned
```javascript
const coerceToString = require("type/string/coerce");
coerceToString(12); // "12"
coerceToString(undefined); // null
```
## `string/ensure`
If given argument is a string coercible value (via [`string/coerce`](#stringcoerce)) returns result string.
Otherwise `TypeError` is thrown.
```javascript
const ensureString = require("type/string/ensure");
ensureString(12); // "12"
ensureString(null); // Thrown TypeError: null is not a string
```

View File

@@ -1,27 +0,0 @@
# Thenable
_Thenable_ object (an object with `then` method)
## `thenable/is`
Confirms if given object is a _thenable_
```javascript
const isThenable = require("type/thenable/is");
isThenable(Promise.resolve()); // true
isThenable({ then: () => {} }); // true
isThenable({}); // false
```
## `thenable/ensure`
If given argument is a _thenable_ object, it is returned back. Otherwise `TypeError` is thrown.
```javascript
const ensureThenable = require("type/thenable/ensure");
const promise = Promise.resolve();
ensureThenable(promise); // promise
ensureThenable({}); // Thrown TypeError: [object Object] is not a thenable object
```

View File

@@ -1,27 +0,0 @@
# Time value
_number_ primitive which is a valid _time value_ (as used internally in _Date_ instances)
## `time-value/coerce`
Follows [`integer/coerce`](integer.md#integercoerce) but returns `null` in place of values which go beyond 100 000 0000 days from unix epoch
```javascript
const coerceToTimeValue = require("type/time-value/coerce");
coerceToTimeValue(12312312); // true
coerceToTimeValue(Number.MAX_SAFE_INTEGER); // false
coerceToTimeValue("foo"); // false
```
## `time-value/ensure`
If given argument is a _time value_ coercible value (via [`time-value/coerce`](#time-valuecoerce)) returns result number.
Otherwise `TypeError` is thrown.
```javascript
const ensureTimeValue = require("type/time-value/ensure");
ensureTimeValue(12.93); // "12"
ensureTimeValue(Number.MAX_SAFE_INTEGER); // Thrown TypeError: null is not a natural number
```

View File

@@ -1,27 +0,0 @@
# Value
_Value_, any value that's neither `null` nor `undefined` .
## `value/is`
Confirms whether passed argument is a _value_
```javascript
const isValue = require("type/value/is");
isValue({}); // true
isValue(null); // false
```
## `value/ensure`
Ensures if given argument is a _value_. If it's a value it is returned back, if not `TypeError` is thrown
```javascript
const ensureValue = require("type/value/ensure");
const obj = {};
ensureValue(obj); // obj
ensureValue(null); // Thrown TypeError: Cannot use null
```

View File

@@ -1,51 +0,0 @@
"use strict";
var isArray = require("./array/is")
, toShortString = require("./lib/to-short-string");
var objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;
var assign = function (target, source) {
for (var key in source) {
if (objPropertyIsEnumerable.call(source, key)) target[key] = source[key];
}
};
module.exports = function (validationDatum1/*, ...validationDatumN, options */) {
var validationData = [validationDatum1];
var globalOptions;
if (arguments.length > 1) {
var hasOptions = !isArray(arguments[arguments.length - 1]);
if (hasOptions) globalOptions = arguments[arguments.length - 1];
var lastDatumIndex = hasOptions ? arguments.length - 2 : arguments.length - 1;
for (var i = 1; i <= lastDatumIndex; ++i) validationData.push(arguments[i]);
}
var result = [], errors;
for (var j = 0; j < validationData.length; ++j) {
var validationDatum = validationData[j];
var options = { name: validationDatum[0] };
if (globalOptions) assign(options, globalOptions);
if (validationDatum[3]) assign(options, validationDatum[3]);
var resultItem;
if (typeof validationDatum[2] !== "function") {
throw new TypeError(toShortString(validationDatum[2]) + " is not a function");
}
try {
resultItem = validationDatum[2](validationDatum[1], options);
} catch (error) {
if (!errors) errors = [];
errors.push(error);
}
if (errors) continue;
result.push(resultItem);
}
if (!errors) return result;
if (errors.length === 1) throw errors[0];
var ErrorConstructor = (globalOptions && globalOptions.Error) || TypeError;
var errorMessage = "Approached following errors:";
for (var k = 0; k < errors.length; ++k) {
errorMessage += "\n - " + errors[k].message.split("\n").join("\n ");
}
throw new ErrorConstructor(errorMessage);
};

View File

@@ -1,12 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value/*, options*/) {
if (is(value)) return value;
var options = arguments[1];
var errorMessage =
options && options.name ? "Expected an error for %n, received %v" : "%v is not an error";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,45 +0,0 @@
"use strict";
var isPrototype = require("../prototype/is")
, isPlainObject = require("../plain-object/is");
var objectToString = Object.prototype.toString;
// Recognize host specific errors (e.g. DOMException)
var errorTaggedStringRe = /^\[object .*(?:Error|Exception)\]$/
, errorNameRe = /^[^\s]*(?:Error|Exception)$/;
module.exports = function (value) {
if (!value) return false;
var name;
// Sanity check (reject objects which do not expose common Error interface)
try {
name = value.name;
if (typeof name !== "string") return false;
if (typeof value.message !== "string") return false;
} catch (error) {
return false;
}
// Ensure its a native-like Error object
// (has [[ErrorData]] slot, or was created to resemble one)
// Note: It's not a 100% bulletproof check of confirming that as:
// - In ES2015+ string tag can be overriden via Symbol.toStringTag property
// - Host errors do not share native error tag. Still we rely on assumption that
// tag for each error will end either with `Error` or `Exception` string
// - In pre ES2015 era, no custom errors will share the error tag.
if (!errorTaggedStringRe.test(objectToString.call(value))) {
// Definitely not an ES2015 error instance, but could still be an error
// (created via e.g. CustomError.prototype = Object.create(Error.prototype))
try {
if (name !== value.constructor.name) return false;
} catch (error) {
return false;
}
if (!errorNameRe.test(name)) return false;
if (isPlainObject(value)) return false;
}
return !isPrototype(value);
};

View File

@@ -1,8 +0,0 @@
"use strict";
var coerceToNumber = require("../number/coerce");
module.exports = function (value) {
value = coerceToNumber(value);
return isFinite(value) ? value : null;
};

View File

@@ -1,15 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, coerce = require("./coerce");
module.exports = function (value/*, options*/) {
var coerced = coerce(value);
if (coerced !== null) return coerced;
var options = arguments[1];
var errorMessage =
options && options.name
? "Expected a finite number for %n, received %v"
: "%v is not a finite number";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,14 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value/*, options*/) {
if (is(value)) return value;
var options = arguments[1];
var errorMessage =
options && options.name
? "Expected a function for %n, received %v"
: "%v is not a function";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,19 +0,0 @@
"use strict";
var isPrototype = require("../prototype/is");
module.exports = function (value) {
if (typeof value !== "function") return false;
if (!hasOwnProperty.call(value, "length")) return false;
try {
if (typeof value.length !== "number") return false;
if (typeof value.call !== "function") return false;
if (typeof value.apply !== "function") return false;
} catch (error) {
return false;
}
return !isPrototype(value);
};

View File

@@ -1,11 +0,0 @@
"use strict";
var coerceToFinite = require("../finite/coerce");
var abs = Math.abs, floor = Math.floor;
module.exports = function (value) {
value = coerceToFinite(value);
if (!value) return value;
return (value > 0 ? 1 : -1) * floor(abs(value));
};

View File

@@ -1,15 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, coerce = require("./coerce");
module.exports = function (value/*, options*/) {
var coerced = coerce(value);
if (coerced !== null) return coerced;
var options = arguments[1];
var errorMessage =
options && options.name
? "Expected an integer for %n, received %v"
: "%v is not an integer";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,49 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, resolveErrorMessage = require("../lib/resolve-error-message")
, toShortString = require("../lib/to-short-string")
, ensurePlainFunction = require("../plain-function/ensure")
, is = require("./is");
var invalidItemsLimit = 3;
module.exports = function (value/*, options*/) {
var options = arguments[1];
var mainErrorMessage =
options && options.name
? "Expected an iterable for %n, received %v"
: "%v is not expected iterable";
if (!is(value, options)) return resolveException(value, mainErrorMessage, options);
if (!options) return value;
var ensureItem = ensurePlainFunction(options.ensureItem, { isOptional: true });
if (ensureItem) {
var coercedValue = [];
var iterator = value[Symbol.iterator]();
var item, invalidItems;
while (!(item = iterator.next()).done) {
var newItemValue;
try {
newItemValue = ensureItem(item.value);
} catch (error) {
if (!invalidItems) invalidItems = [];
if (invalidItems.push(item.value) === invalidItemsLimit) break;
}
if (invalidItems) continue;
coercedValue.push(newItemValue);
}
if (invalidItems) {
var errorMessage =
resolveErrorMessage(mainErrorMessage, value, options) +
".\n Following items are invalid:";
for (var i = 0; i < invalidItems.length; ++i) {
errorMessage += "\n - " + toShortString(invalidItems[i]);
}
throw new TypeError(errorMessage);
}
return coercedValue;
}
return value;
};

View File

@@ -1,32 +0,0 @@
// Polyfills friendly, therefore ES5 syntax
"use strict";
var isObject = require("../object/is");
var iteratorSymbol = Symbol.iterator;
if (!iteratorSymbol) {
throw new Error("Cannot initialize iterator/is due to Symbol.iterator not being implemented");
}
module.exports = function (value/*, options*/) {
var options = arguments[1];
if (!isObject(value)) {
if (!isObject(options) || !options.allowString || typeof value !== "string") return false;
}
try {
if (typeof value[iteratorSymbol] !== "function") return false;
} catch (error) {
return false;
}
if (!options) return true;
if (options.denyEmpty) {
try {
if (value[iteratorSymbol]().next().done) return false;
} catch (error) {
return false;
}
}
return true;
};

View File

@@ -1,12 +0,0 @@
"use strict";
var resolveException = require("../resolve-exception");
module.exports = function (value, coerced, options) {
if (coerced >= options.min) return coerced;
var errorMessage =
options && options.name
? "Expected %n to be greater or equal " + options.min + ", received %v"
: "%v is not greater or equal " + options.min;
return resolveException(value, errorMessage, options);
};

View File

@@ -1,3 +0,0 @@
"use strict";
module.exports = typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol";

View File

@@ -1,52 +0,0 @@
"use strict";
var stringCoerce = require("../string/coerce")
, toShortString = require("./to-short-string");
module.exports = function (errorMessage, value, inputOptions) {
if (inputOptions && inputOptions.errorMessage) {
errorMessage = stringCoerce(inputOptions.errorMessage);
}
var valueInsertIndex = errorMessage.indexOf("%v");
var valueToken = valueInsertIndex > -1 ? toShortString(value) : null;
if (inputOptions && inputOptions.name) {
var nameInsertIndex = errorMessage.indexOf("%n");
if (nameInsertIndex > -1) {
if (valueInsertIndex > -1) {
var firstToken, secondToken, firstInsertIndex, secondInsertIndex;
if (nameInsertIndex > valueInsertIndex) {
firstToken = valueToken;
firstInsertIndex = valueInsertIndex;
secondToken = inputOptions.name;
secondInsertIndex = nameInsertIndex;
} else {
firstToken = inputOptions.name;
firstInsertIndex = nameInsertIndex;
secondToken = valueToken;
secondInsertIndex = valueInsertIndex;
}
return (
errorMessage.slice(0, firstInsertIndex) +
firstToken +
errorMessage.slice(firstInsertIndex + 2, secondInsertIndex) +
secondToken +
errorMessage.slice(secondInsertIndex + 2)
);
}
return (
errorMessage.slice(0, nameInsertIndex) +
inputOptions.name +
errorMessage.slice(nameInsertIndex + 2)
);
}
}
if (valueInsertIndex > -1) {
return (
errorMessage.slice(0, valueInsertIndex) +
valueToken +
errorMessage.slice(valueInsertIndex + 2)
);
}
return errorMessage;
};

View File

@@ -1,15 +0,0 @@
"use strict";
var isValue = require("../value/is")
, resolveErrorMessage = require("./resolve-error-message");
module.exports = function (value, defaultMessage, inputOptions) {
if (inputOptions && !isValue(value)) {
if ("default" in inputOptions) return inputOptions["default"];
if (inputOptions.isOptional) return null;
}
var ErrorConstructor = (inputOptions && inputOptions.Error) || TypeError;
var error = new ErrorConstructor(resolveErrorMessage(defaultMessage, value, inputOptions));
if (inputOptions && inputOptions.errorCode) error.code = inputOptions.errorCode;
throw error;
};

View File

@@ -1,10 +0,0 @@
"use strict";
module.exports = function (value) {
try {
return value.toString();
} catch (error) {
try { return String(value); }
catch (error2) { return null; }
}
};

View File

@@ -1,29 +0,0 @@
"use strict";
var safeToString = require("./safe-to-string");
var reNewLine = /[\n\r\u2028\u2029]/g;
module.exports = function (value) {
var string = safeToString(value);
if (string === null) return "<Non-coercible to string value>";
// Trim if too long
if (string.length > 100) string = string.slice(0, 99) + "…";
// Replace eventual new lines
string = string.replace(reNewLine, function (char) {
switch (char) {
case "\n":
return "\\n";
case "\r":
return "\\r";
case "\u2028":
return "\\u2028";
case "\u2029":
return "\\u2029";
/* istanbul ignore next */
default:
throw new Error("Unexpected character");
}
});
return string;
};

View File

@@ -1,12 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value /*, options*/) {
if (is(value)) return value;
var options = arguments[1];
var errorMessage =
options && options.name ? "Expected a map for %n, received %v" : "%v is not a map";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,28 +0,0 @@
"use strict";
var isPrototype = require("../prototype/is");
// In theory we could rely on Symbol.toStringTag directly,
// still early native implementation (e.g. in FF) predated symbols
var objectToString = Object.prototype.toString, objectTaggedString = objectToString.call(new Map());
module.exports = function (value) {
if (!value) return false;
// Sanity check (reject objects which do not expose common Promise interface)
try {
if (typeof value.set !== "function") return false;
if (typeof value.get !== "function") return false;
if (typeof value.has !== "function") return false;
if (typeof value.clear !== "function") return false;
} catch (error) {
return false;
}
// Ensure its native Promise object (has [[MapData]] slot)
// Note: it's not 100% precise as string tag may be overriden
// and other objects could be hacked to expose it
if (objectToString.call(value) !== objectTaggedString) return false;
return !isPrototype(value);
};

View File

@@ -1,10 +0,0 @@
"use strict";
var coerceToInteger = require("../integer/coerce");
module.exports = function (value) {
value = coerceToInteger(value);
if (!value) return value;
if (value < 0) return null;
return value;
};

View File

@@ -1,21 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, ensureMin = require("../lib/ensure/min")
, coerce = require("./coerce");
module.exports = function (value/*, options*/) {
var coerced = coerce(value), options = arguments[1];
if (coerced !== null) {
if (options) {
if (options.min) ensureMin(value, coerced, options);
}
return coerced;
}
var errorMessage =
options && options.name
? "Expected a natural number for %n, received %v"
: "%v is not a natural number";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,14 +0,0 @@
"use strict";
var isValue = require("../value/is");
module.exports = function (value) {
if (!isValue(value)) return null;
try {
value = +value; // Ensure implicit coercion
} catch (error) {
return null;
}
if (isNaN(value)) return null;
return value;
};

View File

@@ -1,13 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, coerce = require("./coerce");
module.exports = function (value/*, options*/) {
var coerced = coerce(value);
if (coerced !== null) return coerced;
var options = arguments[1];
var errorMessage =
options && options.name ? "Expected a number for %n, received %v" : "%v is not a number";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,12 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value/*, options*/) {
if (is(value)) return value;
var options = arguments[1];
var errorMessage =
options && options.name ? "Expected an object for %n, received %v" : "%v is not an object";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,11 +0,0 @@
"use strict";
var isValue = require("../value/is");
// prettier-ignore
var possibleTypes = { "object": true, "function": true, "undefined": true /* document.all */ };
module.exports = function (value) {
if (!isValue(value)) return false;
return hasOwnProperty.call(possibleTypes, typeof value);
};

View File

@@ -1,120 +0,0 @@
{
"name": "type",
"version": "2.7.2",
"description": "Runtime validation and processing of JavaScript types",
"author": "Mariusz Nowak <medyk@medikoo.com> (https://www.medikoo.com/)",
"keywords": [
"type",
"coercion"
],
"repository": "medikoo/type",
"devDependencies": {
"chai": "^4.3.6",
"eslint": "^8.21.0",
"eslint-config-medikoo": "^4.1.2",
"git-list-updated": "^1.2.1",
"github-release-from-cc-changelog": "^2.3.0",
"husky": "^4.3.8",
"lint-staged": "^13.0.3",
"mocha": "^6.2.3",
"nyc": "^15.1.0",
"prettier-elastic": "^2.2.1"
},
"typesVersions": {
">=4": {
"*": [
"ts-types/*"
]
}
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.js": [
"eslint"
],
"*.{css,html,js,json,md,yaml,yml}": [
"prettier -c"
]
},
"eslintConfig": {
"extends": "medikoo/es3",
"root": true,
"globals": {
"BigInt": true,
"Map": true,
"Promise": true,
"Set": true,
"Symbol": true
},
"overrides": [
{
"files": "test/**/*.js",
"env": {
"mocha": true
},
"rules": {
"no-eval": "off",
"no-new-wrappers": "off"
}
},
{
"files": [
"string/coerce.js",
"number/coerce.js"
],
"rules": {
"no-implicit-coercion": "off"
}
},
{
"files": "plain-object/is.js",
"rules": {
"no-proto": "off"
}
}
]
},
"prettier": {
"printWidth": 100,
"tabWidth": 4,
"overrides": [
{
"files": [
"*.md",
"*.yml"
],
"options": {
"tabWidth": 2
}
}
]
},
"nyc": {
"all": true,
"exclude": [
".github",
"coverage/**",
"test/**",
"*.config.js"
],
"reporter": [
"lcov",
"html",
"text-summary"
]
},
"scripts": {
"coverage": "nyc npm test",
"lint:updated": "pipe-git-updated --base=main --ext=js -- eslint --ignore-pattern '!*'",
"prettier-check": "prettier -c --ignore-path .gitignore \"**/*.{css,html,js,json,md,yaml,yml}\"",
"prettier-check:updated": "pipe-git-updated --base=main --ext=css --ext=html --ext=js --ext=json --ext=md --ext=yaml --ext=yml -- prettier -c",
"prettify": "prettier --write --ignore-path .gitignore \"**/*.{css,html,js,json,md,yaml,yml}\"",
"prettify:updated": "pipe-git-updated ---base=main -ext=css --ext=html --ext=js --ext=json --ext=md --ext=yaml --ext=yml -- prettier --write",
"test": "mocha --recursive"
},
"license": "ISC"
}

View File

@@ -1,14 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value/*, options*/) {
if (is(value)) return value;
var options = arguments[1];
var errorMessage =
options && options.name
? "Expected a plain function for %n, received %v"
: "%v is not a plain function";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,11 +0,0 @@
"use strict";
var isFunction = require("../function/is");
var classRe = /^\s*class[\s{/}]/, functionToString = Function.prototype.toString;
module.exports = function (value) {
if (!isFunction(value)) return false;
if (classRe.test(functionToString.call(value))) return false;
return true;
};

View File

@@ -1,67 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, resolveErrorMessage = require("../lib/resolve-error-message")
, ensurePlainFunction = require("../plain-function/ensure")
, ensureArray = require("../array/ensure")
, is = require("./is");
var objHasOwnProperty = Object.prototype.hasOwnProperty, invalidItemsLimit = 3;
module.exports = function (value/*, options*/) {
var options = arguments[1];
var mainErrorMessage =
options && options.name
? "Expected a plain object for %n, received %v"
: "%v is not a plain object";
if (!is(value)) return resolveException(value, mainErrorMessage, options);
if (!options) return value;
var invalidKeys, key, errorMessage;
var allowedKeys = ensureArray(options.allowedKeys, { isOptional: true });
if (allowedKeys) {
for (key in value) {
if (!objHasOwnProperty.call(value, key)) continue;
if (allowedKeys.indexOf(key) > -1) continue;
if (!invalidKeys) invalidKeys = [];
if (invalidKeys.push(key) === invalidItemsLimit) break;
}
if (invalidKeys) {
errorMessage =
resolveErrorMessage(mainErrorMessage, value, options) +
".\n Following keys are unexpected: " +
invalidKeys.join(", ");
throw new TypeError(errorMessage);
}
}
var ensurePropertyValue = ensurePlainFunction(options.ensurePropertyValue, {
isOptional: true
});
if (ensurePropertyValue) {
var coercedValue = {};
for (key in value) {
if (!objHasOwnProperty.call(value, key)) continue;
var coercedPropertyValue;
try {
coercedPropertyValue = ensurePropertyValue(value[key]);
} catch (error) {
if (!invalidKeys) invalidKeys = [];
if (invalidKeys.push(key) === invalidItemsLimit) break;
}
if (invalidKeys) continue;
coercedValue[key] = coercedPropertyValue;
}
if (invalidKeys) {
errorMessage =
resolveErrorMessage(mainErrorMessage, value, options) +
".\n Values for following keys are invalid: " +
invalidKeys.join(", ");
throw new TypeError(errorMessage);
}
return coercedValue;
}
return value;
};

View File

@@ -1,28 +0,0 @@
"use strict";
var isObject = require("../object/is")
, isPrototype = require("../prototype/is");
var getPrototypeOf;
if (typeof Object.getPrototypeOf === "function") {
getPrototypeOf = Object.getPrototypeOf;
} else if ({}.__proto__ === Object.prototype) {
getPrototypeOf = function (object) { return object.__proto__; };
}
module.exports = function (value) {
if (!isObject(value)) return false;
var prototype;
if (getPrototypeOf) {
prototype = getPrototypeOf(value);
} else {
try {
var valueConstructor = value.constructor;
if (valueConstructor) prototype = valueConstructor.prototype;
} catch (error) {
return false;
}
}
if (prototype && !hasOwnProperty.call(prototype, "propertyIsEnumerable")) return false;
return !isPrototype(value);
};

View File

@@ -1,12 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value/*, options*/) {
if (is(value)) return value;
var options = arguments[1];
var errorMessage =
options && options.name ? "Expected a promise for %n, received %v" : "%v is not a promise";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,27 +0,0 @@
"use strict";
var isPrototype = require("../prototype/is");
// In theory we could rely on Symbol.toStringTag directly,
// still early native implementation (e.g. in FF) predated symbols
var objectToString = Object.prototype.toString
, objectTaggedString = objectToString.call(Promise.resolve());
module.exports = function (value) {
if (!value) return false;
// Sanity check (reject objects which do not expose common Promise interface)
try {
if (typeof value.then !== "function") return false;
if (typeof value["catch"] !== "function") return false;
} catch (error) {
return false;
}
// Ensure its native Promise object (has [[PromiseState]] slot)
// Note: it's not 100% precise as string tag may be overriden
// and other objects could be hacked to expose it
if (objectToString.call(value) !== objectTaggedString) return false;
return !isPrototype(value);
};

View File

@@ -1,13 +0,0 @@
"use strict";
var isObject = require("../object/is");
module.exports = function (value) {
if (!isObject(value)) return false;
try {
if (!value.constructor) return false;
return value.constructor.prototype === value;
} catch (error) {
return false;
}
};

View File

@@ -1,14 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value/*, options*/) {
if (is(value)) return value;
var options = arguments[1];
var errorMessage =
options && options.name
? "Expected a regular expression for %n, received %v"
: "%v is not a regular expression";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,37 +0,0 @@
"use strict";
var isToStringTagSupported = require("../lib/is-to-string-tag-supported")
, isPrototype = require("../prototype/is");
var regExpTest = RegExp.prototype.test
, objectToString = Object.prototype.toString
, objectTaggedString = objectToString.call(/a/);
module.exports = function (value) {
if (!value) return false;
// Sanity check (reject objects which do not expose common RegExp interface)
if (!hasOwnProperty.call(value, "lastIndex")) return false;
try {
if (typeof value.lastIndex !== "number") return false;
if (typeof value.test !== "function") return false;
if (typeof value.exec !== "function") return false;
} catch (error) {
return false;
}
// Ensure its native RegExp object (has [[RegExpMatcher]] slot)
if (isToStringTagSupported && typeof value[Symbol.toStringTag] === "string") {
// Edge case (possibly a regExp with custom Symbol.toStringTag)
try {
var lastIndex = value.lastIndex;
regExpTest.call(value, "");
if (value.lastIndex !== lastIndex) value.lastIndex = lastIndex;
return true;
} catch (error) {
return false;
}
}
if (objectToString.call(value) !== objectTaggedString) return false;
return !isPrototype(value);
};

View File

@@ -1,13 +0,0 @@
"use strict";
var coerceToInteger = require("../integer/coerce");
var MAX_SAFE_INTEGER = 9007199254740991, MIN_SAFE_INTEGER = -9007199254740991;
module.exports = function (value) {
value = coerceToInteger(value);
if (!value) return value;
if (value > MAX_SAFE_INTEGER) return null;
if (value < MIN_SAFE_INTEGER) return null;
return value;
};

View File

@@ -1,15 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, coerce = require("./coerce");
module.exports = function (value/*, options*/) {
var coerced = coerce(value);
if (coerced !== null) return coerced;
var options = arguments[1];
var errorMessage =
options && options.name
? "Expected a safe integer for %n, received %v"
: "%v is not a safe integer";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,12 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value /*, options*/) {
if (is(value)) return value;
var options = arguments[1];
var errorMessage =
options && options.name ? "Expected a set for %n, received %v" : "%v is not a set";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,27 +0,0 @@
"use strict";
var isPrototype = require("../prototype/is");
// In theory we could rely on Symbol.toStringTag directly,
// still early native implementation (e.g. in FF) predated symbols
var objectToString = Object.prototype.toString, objectTaggedString = objectToString.call(new Set());
module.exports = function (value) {
if (!value) return false;
// Sanity check (reject objects which do not expose common Set interface)
try {
if (typeof value.add !== "function") return false;
if (typeof value.has !== "function") return false;
if (typeof value.clear !== "function") return false;
} catch (error) {
return false;
}
// Ensure its native Set object (has [[SetData]] slot)
// Note: it's not 100% precise as string tag may be overriden
// and other objects could be hacked to expose it
if (objectToString.call(value) !== objectTaggedString) return false;
return !isPrototype(value);
};

View File

@@ -1,23 +0,0 @@
"use strict";
var isValue = require("../value/is")
, isObject = require("../object/is");
var objectToString = Object.prototype.toString;
module.exports = function (value) {
if (!isValue(value)) return null;
if (isObject(value)) {
// Reject Object.prototype.toString coercion
var valueToString = value.toString;
if (typeof valueToString !== "function") return null;
if (valueToString === objectToString) return null;
// Note: It can be object coming from other realm, still as there's no ES3 and CSP compliant
// way to resolve its realm's Object.prototype.toString it's left as not addressed edge case
}
try {
return "" + value; // Ensure implicit coercion
} catch (error) {
return null;
}
};

View File

@@ -1,13 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, coerce = require("./coerce");
module.exports = function (value/*, options*/) {
var coerced = coerce(value);
if (coerced !== null) return coerced;
var options = arguments[1];
var errorMessage =
options && options.name ? "Expected a string for %n, received %v" : "%v is not a string";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,14 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value/*, options*/) {
if (is(value)) return value;
var options = arguments[1];
var errorMessage =
options && options.name
? "Expected a thenable for %n, received %v"
: "%v is not a thenable";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,9 +0,0 @@
"use strict";
var isObject = require("../object/is");
module.exports = function (value) {
if (!isObject(value)) return false;
try { return typeof value.then === "function"; }
catch (error) { return false; }
};

View File

@@ -1,12 +0,0 @@
"use strict";
var coerceToInteger = require("../integer/coerce");
var abs = Math.abs;
module.exports = function (value) {
value = coerceToInteger(value);
if (!value) return value;
if (abs(value) > 8.64e15) return null;
return value;
};

View File

@@ -1,15 +0,0 @@
"use strict";
var resolveException = require("../lib/resolve-exception")
, coerce = require("./coerce");
module.exports = function (value/*, options*/) {
var coerced = coerce(value);
if (coerced !== null) return coerced;
var options = arguments[1];
var errorMessage =
options && options.name
? "Expected a time value for %n, received %v"
: "%v is not a time value";
return resolveException(value, errorMessage, options);
};

View File

@@ -1,2 +0,0 @@
declare function coerceToArrayLength(value: any): number | null;
export default coerceToArrayLength;

View File

@@ -1,7 +0,0 @@
import { EnsureBaseOptions, EnsureIsOptional, EnsureDefault } from '../ensure';
declare function ensureArrayLength(value: any, options?: EnsureBaseOptions): number;
declare function ensureArrayLength(value: any, options?: EnsureBaseOptions & EnsureIsOptional): number | null;
declare function ensureArrayLength(value: any, options?: EnsureBaseOptions & EnsureIsOptional & EnsureDefault<number>): number;
export default ensureArrayLength;

View File

@@ -1,11 +0,0 @@
import { EnsureBaseOptions, EnsureIsOptional, EnsureDefault } from '../ensure';
type LengthwiseObject = { length: number } & object;
type ArrayLikeEnsureOptions = { allowString?: boolean };
declare function ensureArrayLike<T>(value: any, options?: ArrayLikeEnsureOptions & EnsureBaseOptions): T[] | string | LengthwiseObject;
declare function ensureArrayLike<T>(value: any, options?: ArrayLikeEnsureOptions & EnsureBaseOptions & EnsureIsOptional): T[] | string | LengthwiseObject | null;
declare function ensureArrayLike<T>(value: any, options?: ArrayLikeEnsureOptions & EnsureBaseOptions & EnsureIsOptional & EnsureDefault<T[] | string | LengthwiseObject>): T[] | string | LengthwiseObject;
export default ensureArrayLike;

View File

@@ -1,2 +0,0 @@
declare function isArrayLike(value: any, options?: {allowString?: boolean}): boolean;
export default isArrayLike;

View File

@@ -1,10 +0,0 @@
import { EnsureFunction, EnsureBaseOptions, EnsureIsOptional, EnsureDefault } from '../ensure';
type EnsureArrayOptions = { ensureItem?: EnsureFunction };
declare function ensureArray<T>(value: any, options?: EnsureArrayOptions & EnsureBaseOptions): T[];
declare function ensureArray<T>(value: any, options?: EnsureArrayOptions & EnsureBaseOptions & EnsureIsOptional): T[] | null;
declare function ensureArray<T>(value: any, options?: EnsureArrayOptions & EnsureBaseOptions & EnsureIsOptional & EnsureDefault<T[]>): T[];
export default ensureArray;

View File

@@ -1,2 +0,0 @@
declare function isArray(value: any): boolean;
export default isArray;

View File

@@ -1,2 +0,0 @@
declare function coerceToBigInt(value: any): bigint | null;
export default coerceToBigInt;

View File

@@ -1,7 +0,0 @@
import { EnsureBaseOptions, EnsureIsOptional, EnsureDefault } from '../ensure';
declare function ensureBigInt(value: any, options?: EnsureBaseOptions): bigint;
declare function ensureBigInt(value: any, options?: EnsureBaseOptions & EnsureIsOptional): bigint | null;
declare function ensureBigInt(value: any, options?: EnsureBaseOptions & EnsureIsOptional & EnsureDefault<bigint>): bigint;
export default ensureBigInt;

View File

@@ -1,7 +0,0 @@
import { EnsureFunction, EnsureBaseOptions, EnsureIsOptional, EnsureDefault } from '../ensure';
declare function ensureConstructor(value: any, options?: EnsureBaseOptions): EnsureFunction | object;
declare function ensureConstructor(value: any, options?: EnsureBaseOptions & EnsureIsOptional): EnsureFunction | object | null;
declare function ensureConstructor(value: any, options?: EnsureBaseOptions & EnsureIsOptional & EnsureDefault<EnsureFunction | object>): EnsureFunction | object;
export default ensureConstructor;

View File

@@ -1,2 +0,0 @@
declare function isConstructor(value: any): boolean;
export default isConstructor;

View File

@@ -1,7 +0,0 @@
import { EnsureBaseOptions, EnsureIsOptional, EnsureDefault } from '../ensure';
declare function ensureDate(value: any, options?: EnsureBaseOptions): Date;
declare function ensureDate(value: any, options?: EnsureBaseOptions & EnsureIsOptional): Date | null;
declare function ensureDate(value: any, options?: EnsureBaseOptions & EnsureIsOptional & EnsureDefault<Date>): Date;
export default ensureDate;

View File

@@ -1,2 +0,0 @@
declare function isDate(value: any): boolean;
export default isDate;

View File

@@ -1,24 +0,0 @@
export type EnsureFunction = (...args: any[]) => any;
export interface EnsureBaseOptions {
name?: string;
errorMessage?: string;
errorCode?: number;
Error?: ErrorConstructor;
}
export interface EnsureIsOptional {
isOptional: boolean;
}
export interface EnsureDefault<T> {
default: T;
}
type EnsureOptions = EnsureBaseOptions & { isOptional?: boolean } & { default?: any };
type ValidationDatum = [argumentName: string, inputValue: any, ensureFunction: EnsureFunction, options?: object];
type ValidationDatumList = ValidationDatum[];
declare function ensure<T>(...args: [...ValidationDatumList, EnsureOptions]): T;
declare function ensure<T>(...args: [...ValidationDatumList]): T;
export default ensure;

Some files were not shown because too many files have changed in this diff Show More