cloudevent
Advanced tools
Comparing version 0.7.0 to 0.8.0
# Change Log | ||
## [0.8.0](https://github.com/smartiniOnGitHub/cloudevent.js/releases/tag/0.8.0) (2021-03-26) | ||
Summary Changelog: | ||
- Implement the [v1.0.1 - CloudEvents Spec](https://github.com/cloudevents/spec/releases/tag/v1.0.1) | ||
but ensure compatibility with release 1.0 | ||
- Update requirements to Node.js 10 LTS (10.13.0 or later) | ||
- Update dependencies for the development environment | ||
- Generate documentation from sources with JSDoc, no more ESDoc | ||
- Fix: Manage in the right way optional values given as null (even extensions) | ||
- Fix: remove the unnecessary executable attribute from sources and some other file in the repo | ||
- Feature: add to CloudEvent an utility (static) method to dump validation results | ||
- Feature: ensure 'data' works in the right way with a string value | ||
and even with a boolean value, both with a non default datacontenttype (for example 'text/plain') | ||
- Feature: handle 'data' as array (it was previously forbidden) | ||
- Feature: update example and update/simplify README | ||
- Feature: update JSONBatch strict validation to consider even null/undefined items in the array | ||
- Feature: update to string representation including all mandatory attributes, | ||
and by using 'payload' instead of 'data' (shortened if more than 1024 chars) | ||
because it's more general | ||
## [0.7.0](https://github.com/smartiniOnGitHub/cloudevent.js/releases/tag/0.7.0) (2020-09-20) | ||
@@ -4,0 +23,0 @@ Summary Changelog: |
/* | ||
* Copyright 2018 the original author or authors. | ||
* Copyright 2018-2021 the original author or authors. | ||
* | ||
@@ -62,2 +62,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
const ceCommonOptionsStrict = { ...ceCommonOptions, strict: true } | ||
const ceCommonOptionsForTextData = { ...ceCommonOptions, datacontenttype: 'text/plain' } | ||
const ceCommonExtensions = { exampleextension: 'value' } | ||
@@ -71,2 +72,7 @@ const ceNamespace = 'com.github.smartiniOnGitHub.cloudeventjs.testevent-v1.0.0' | ||
// create a sample minimal instance good for normal validation but not for strict validation ... | ||
const ceMinimalBadSource = new CloudEvent('1', ceNamespace, 'source (bad)', null) | ||
assert(ceMinimalBadSource !== null) | ||
console.log(`ce dump (good but not for strict validation): ${T.dumpObject(ceMinimalBadSource, 'ceMinimalBadSource')}`) | ||
// create a sample minimal instance ... | ||
@@ -157,3 +163,4 @@ const ceMinimal = new CloudEvent('1', // id | ||
ceDataAsString, // data | ||
ceCommonOptions, // use common options | ||
// ceCommonOptions, // ok but not in strict validation | ||
ceCommonOptionsForTextData, // ok even in strict validation | ||
ceCommonExtensions | ||
@@ -164,2 +171,3 @@ ) | ||
assert(ceFullTextData.payload === ceDataAsString) // returned data is transformed | ||
console.log(`ce payload: '${ceFullTextData.payload}', length: ${ceFullTextData.payload.length}`) | ||
console.log(`ce dump: ${T.dumpObject(ceFullTextData, 'ceFullTextData')}`) | ||
@@ -179,2 +187,3 @@ console.log(`ce validation results on ceFullTextData (no strict validation) = ${CloudEvent.validateEvent(ceFullTextData)}`) | ||
assert(ceFullStrictBinaryData.payload === ceDataAsString) // returned data is transformed | ||
console.log(`ce payload: '${ceFullStrictBinaryData.payload}', length: ${ceFullStrictBinaryData.payload.length}`) | ||
console.log(`ce dump: ${T.dumpObject(ceFullStrictBinaryData, 'ceFullStrictBinaryData')}`) | ||
@@ -186,3 +195,8 @@ | ||
assert(!ceMinimalMandatoryUndefinedNoStrict.isValid()) | ||
// console.log(`DEBUG - ${CloudEvent.dumpValidationResults(ceMinimalBadSource, null, 'ceMinimalBadSource')}`) | ||
assert(ceMinimalBadSource.isValid()) | ||
// console.log(`DEBUG - ${CloudEvent.dumpValidationResults(ceMinimalBadSource, { strict: true }, 'ceMinimalBadSource')}`) | ||
assert(!ceMinimalBadSource.isValid({ strict: true })) | ||
assert(ceMinimal.isValid()) | ||
assert(ceMinimal.isValid({ strict: true })) | ||
assert(ceFull.isValid()) | ||
@@ -194,3 +208,3 @@ assert(ceFullStrict.isValid()) | ||
assert(ceFullTextData.isValid()) | ||
assert(!ceFullTextData.isValid({ strict: true })) | ||
assert(ceFullTextData.isValid({ strict: true })) | ||
assert(ceFullStrictBinaryData.isValid()) | ||
@@ -207,6 +221,8 @@ // the same, but using static method | ||
assert(CloudEvent.isValidEvent(ceFullTextData)) | ||
assert(!CloudEvent.isValidEvent(ceFullTextData, { strict: true })) | ||
assert(CloudEvent.isValidEvent(ceFullTextData, { strict: true })) | ||
assert(CloudEvent.isValidEvent(ceFullStrictBinaryData)) | ||
// console.log(`DEBUG - ${CloudEvent.dumpValidationResults(ceEmpty, null, 'ceEmpty')}`) | ||
assert(CloudEvent.validateEvent(ceEmpty).length === 3) | ||
assert(CloudEvent.validateEvent(ceEmpty, { strict: true }).length === 5) | ||
// console.log(`DEBUG - ${CloudEvent.dumpValidationResults(ceEmpty, { strict: true }, 'ceEmpty')}`) | ||
assert(CloudEvent.validateEvent(ceEmpty, { strict: true }).length === 4) | ||
assert(CloudEvent.validateEvent(ceMinimalMandatoryUndefinedNoStrict).length > 0) | ||
@@ -228,3 +244,3 @@ assert(CloudEvent.validateEvent(ceMinimal).length === 0) | ||
assert(CloudEvent.validateEvent(ceFullTextData, { strict: false }).length === 0) | ||
assert(CloudEvent.validateEvent(ceFullTextData, { strict: true }).length === 1) | ||
assert(CloudEvent.validateEvent(ceFullTextData, { strict: true }).length === 0) | ||
assert(CloudEvent.validateEvent(ceFullStrictBinaryData).length === 0) | ||
@@ -237,2 +253,3 @@ assert(CloudEvent.validateEvent(ceFullStrictBinaryData, { strict: false }).length === 0) | ||
console.log(`Validation output for ceEmpty (force strict mode to true) is: size: ${CloudEvent.validateEvent(ceEmpty, { strict: true }).length}, details:\n` + CloudEvent.validateEvent(ceEmpty, { strict: true })) | ||
console.log(`Validation output for ceEmpty, alternative way: ${CloudEvent.dumpValidationResults(ceEmpty, { strict: true }, 'ceEmpty')}`) | ||
@@ -268,2 +285,8 @@ // serialization examples | ||
console.log('Serialization output for ceFullStrictOtherContentType, details:\n' + ceFullStrictOtherContentTypeSerialized) | ||
const ceFullTextDataSerialized = CloudEvent.serializeEvent(ceFullTextData, { onlyValid: true }) | ||
assert(ceFullTextDataSerialized !== null) | ||
console.log('Serialization output for ceFullTextData, details:\n' + ceFullTextDataSerialized) | ||
const ceFullStrictBinaryDataSerialized = CloudEvent.serializeEvent(ceFullStrictBinaryData, { onlyValid: true }) | ||
assert(ceFullStrictBinaryDataSerialized !== null) | ||
console.log('Serialization output for ceFullStrictBinaryData, details:\n' + ceFullStrictBinaryDataSerialized) | ||
@@ -295,2 +318,14 @@ // then use (send/store/etc) serialized instances ... | ||
console.log(`ce dump: ${T.dumpObject(ceFullStrictOtherContentTypeDeserialized, 'ceFullStrictOtherContentTypeDeserialized')}`) | ||
const ceFullTextDataDeserialized = CloudEvent.deserializeEvent(ceFullTextDataSerialized, { onlyValid: true }) | ||
assert(ceFullTextDataDeserialized !== null) | ||
assert(ceFullTextDataDeserialized.isValid()) | ||
assert(!ceFullTextDataDeserialized.isStrict) | ||
assert(CloudEvent.isCloudEvent(ceFullTextDataDeserialized)) | ||
console.log(`ce dump: ${T.dumpObject(ceFullTextDataDeserialized, 'ceFullTextDataDeserialized')}`) | ||
const ceFullStrictBinaryDataDeserialized = CloudEvent.deserializeEvent(ceFullStrictBinaryDataSerialized, { onlyValid: true }) | ||
assert(ceFullStrictBinaryDataDeserialized !== null) | ||
assert(ceFullStrictBinaryDataDeserialized.isValid()) | ||
assert(ceFullStrictBinaryDataDeserialized.isStrict) | ||
assert(CloudEvent.isCloudEvent(ceFullStrictBinaryDataDeserialized)) | ||
console.log(`ce dump: ${T.dumpObject(ceFullStrictBinaryDataDeserialized, 'ceFullStrictBinaryDataDeserialized')}`) | ||
@@ -307,4 +342,6 @@ // then use (validate/send/store/etc) deserialized instances ... | ||
1234567890, // bad | ||
3.14159, // bad | ||
false, // bad | ||
true, // bad | ||
ceMinimalBadSource, // good but not for strict validation | ||
ceMinimal, | ||
@@ -317,3 +354,5 @@ ceFull, | ||
ceErrorStrict, | ||
ceFullStrictOtherContentType, | ||
ceFullStrictOtherContentType, // good, but to serialize/deserialize related options must be used | ||
ceFullTextData, | ||
ceFullStrictBinaryData, | ||
null, | ||
@@ -325,11 +364,16 @@ undefined | ||
console.log(`JSONBatch contains ${batch.length} items, but only some are valid CloudEvent instances, see related sample code:`) | ||
console.log(`${JSONBatch.getEvents(batch, { onlyValid: false, strict: false }).length} CloudEvent instances`) | ||
console.log(`${JSONBatch.getEvents(batch, { onlyValid: true, strict: true }).length} CloudEvent instances valid in strict mode`) | ||
console.log(`CloudEvent instances valid: ${JSONBatch.getEvents(batch, { onlyValid: true, strict: false }).length}`) | ||
console.log(`CloudEvent instances valid in strict mode: ${JSONBatch.getEvents(batch, { onlyValid: true, strict: true }).length}`) | ||
// sample validation, in normal and in strict mode | ||
assert(JSONBatch.validateBatch(batch, { strict: false }).length === 7) | ||
assert(JSONBatch.validateBatch(batch, { strict: true }).length === 8) | ||
console.log(`JSONBatch validation errors, num: ${JSONBatch.validateBatch(batch, { strict: false }).length}`) | ||
console.log(`JSONBatch validation errors in strict mode, num: ${JSONBatch.validateBatch(batch, { strict: true }).length}`) | ||
console.log(`JSONBatch validation errors in strict mode, details:\n${JSONBatch.validateBatch(batch, { strict: true })}\n`) | ||
assert(JSONBatch.validateBatch(batch, { strict: false }).length === 8) // expected validation errors | ||
assert(JSONBatch.validateBatch(batch, { strict: true }).length === 13) // expected validation errors | ||
// sample filtering of events | ||
assert(JSONBatch.getEvents(batch, { onlyValid: false, strict: false }).length === 5) // no filtering | ||
assert(JSONBatch.getEvents(batch, { onlyValid: true, strict: false }).length === 5) // only valid | ||
assert(JSONBatch.getEvents(batch, { onlyValid: true, strict: true }).length === 4) // only valid in strict mode | ||
// console.log(`DEBUG - JSONBatch.getEvents, num: ${JSONBatch.getEvents(batch, { onlyValid: true, strict: true }).length}`) | ||
assert(JSONBatch.getEvents(batch, { onlyValid: false, strict: false }).length === 8) // no filtering | ||
assert(JSONBatch.getEvents(batch, { onlyValid: false, strict: true }).length === 8) // no filtering (neither in strict mode) | ||
assert(JSONBatch.getEvents(batch, { onlyValid: true, strict: false }).length === 8) // only valid | ||
assert(JSONBatch.getEvents(batch, { onlyValid: true, strict: true }).length === 7) // only valid in strict mode | ||
console.log('JSONBatch events: get only valid instances, as a sample') | ||
@@ -346,3 +390,3 @@ const events = JSONBatch.getEvents(batch, { | ||
const ser = JSONBatch.serializeEvents(events, { prettyPrint: true, logError: true }) | ||
console.log(`JSONBatch events: serialized = \n${ser}\n`) | ||
console.log(`JSONBatch events serialized = \n${ser}\n`) | ||
const deser = JSONBatch.deserializeEvents(ser, { | ||
@@ -349,0 +393,0 @@ logError: true, |
{ | ||
"name": "cloudevent", | ||
"version": "0.7.0", | ||
"version": "0.8.0", | ||
"description": "JavaScript/Node.js implementation of the CloudEvents standard format", | ||
@@ -8,6 +8,10 @@ "main": "src/index", | ||
"dependency:log": "npm list > ./temp/dependencies.log", | ||
"docs": "npx esdoc", | ||
"docs:clean": "rm -rf ./docs/*", | ||
"docs:generate": "npx jsdoc -c .jsdoc.json -R README.md", | ||
"docs": "npm run docs:clean && npm run docs:generate", | ||
"example": "node example/nodejs-base", | ||
"example:debug": "node --inspect-brk example/nodejs-base", | ||
"lint": "standard \"./src/**/*.js\" \"./test/**/*.test.js\" \"./example/**/*.js\"", | ||
"lint": "npm run lint:standard", | ||
"lint:fix": "standard --fix", | ||
"lint:standard": "standard --verbose", | ||
"lint:log": "npm run lint > ./temp/lint-standard.log", | ||
@@ -18,2 +22,3 @@ "license-check": "npx legally", | ||
"license-checker:log": "npm run license-checker | tee ./temp/license-checker.log", | ||
"test:clean": "rm -rf .nyc_output/* ./coverage/*", | ||
"test:coverage": "npm run test:unit -- --cov --coverage-report=html", | ||
@@ -27,12 +32,9 @@ "test:unit": "tap -J --comments --no-esm --strict test/*.test.js", | ||
"devDependencies": { | ||
"esdoc": "^1.1.0", | ||
"esdoc-standard-plugin": "^1.0.0", | ||
"esdoc-ecmascript-proposal-plugin": "^1.0.0", | ||
"esdoc-node": "^1.0.5", | ||
"standard": "^14.3.4", | ||
"tap": "^14.10.8" | ||
"jsdoc": "^3.6.6", | ||
"standard": "^16.0.3", | ||
"tap": "^14.11.0" | ||
}, | ||
"peerDependencies": {}, | ||
"engines": { | ||
"node": ">=8.17.0" | ||
"node": ">=10.13.0" | ||
}, | ||
@@ -39,0 +41,0 @@ "homepage": "https://github.com/smartiniOnGitHub/cloudevent.js#readme", |
@@ -14,3 +14,3 @@ # cloudevent / cloudevent.js | ||
Current release implements the v1.0 of the CloudEvents Spec. | ||
Current release implements the v1.0.1 of the CloudEvents Spec. | ||
@@ -29,3 +29,5 @@ The purpose of this library is to create instances of CloudEvents in a simple way | ||
For changes and release notes, see [CHANGELOG](./CHANGELOG.md). | ||
## Usage | ||
@@ -38,5 +40,2 @@ | ||
// reference the library, not needed if using destructuring assignment, see below | ||
const CloudEventExports = require('cloudevent') | ||
// minimal, most common usage | ||
@@ -67,2 +66,3 @@ // const { CloudEvent } = require('cloudevent') | ||
const ceCommonOptionsStrict = { ...ceCommonOptions, strict: true } | ||
const ceCommonOptionsForTextData = { ...ceCommonOptions, datacontenttype: 'text/plain' } | ||
const ceCommonExtensions = { exampleextension: 'value' } | ||
@@ -76,2 +76,5 @@ const ceNamespace = 'com.github.smartiniOnGitHub.cloudeventjs.testevent-v1.0.0' | ||
// create a sample minimal instance good for normal validation but not for strict validation ... | ||
const ceMinimalBadSource = new CloudEvent('1', ceNamespace, 'source (bad)', null) | ||
// create a sample minimal instance ... | ||
@@ -81,6 +84,6 @@ const ceMinimal = new CloudEvent('1', // id | ||
'/', // source | ||
{} // data (empty) // optional, but useful the same in this sample usage | ||
{} // data (empty) // optional, even null is good is good in this case | ||
) | ||
// When creating some instances with an undefined mandatory argument (handled by defaults), | ||
// When creating instances with an undefined mandatory argument (handled by defaults), | ||
// but with strict flag disabled success is expected, otherwise with strict flag enabled a failure is expected ... | ||
@@ -97,2 +100,3 @@ // In JavaScript, null values are not handled as default values, only undefined values ... | ||
) | ||
// create a sample instance with strict mode (for validation) enabled ... | ||
const ceFullStrict = new CloudEvent('2/full-strict', | ||
@@ -105,5 +109,2 @@ ceNamespace, | ||
) | ||
assert(ceFullStrict.isStrict) | ||
assert(!ceFull.isStrict) // ensure common options object has not been changed when reusing some of its values for the second instance | ||
assert(!CloudEvent.isStrictEvent(ceFull)) // the same, but using static method | ||
// create an instance with a JSON string as data | ||
@@ -117,4 +118,2 @@ const ceFullStrictJSONTextData = new CloudEvent('2/full-strict-json-string-data', | ||
) | ||
assert(ceFullStrictJSONTextData !== null) | ||
assert(ceFullStrictJSONTextData.isStrict) | ||
// create an instance that wrap an Error | ||
@@ -135,6 +134,2 @@ const error = new Error('sample error') | ||
) | ||
assert(ceErrorStrict !== null) | ||
assert(ceErrorStrict.isStrict) | ||
assert(!ceErrorStrict.isStrict) // ensure common options object has not been changed when reusing some of its values for the second instance | ||
assert(!CloudEvent.isStrictEvent(ceErrorStrict)) // the same, but using static method | ||
// create an instance with a different content type | ||
@@ -148,5 +143,3 @@ const ceFullStrictOtherContentType = new CloudEvent('4/full-strict-other-content-type', | ||
) | ||
assert(ceFullStrictOtherContentType !== null) | ||
assert(ceFullStrictOtherContentType.isStrict) | ||
// create an instance with data as a string, but not strict (to validate it even in strict mode) | ||
// create an instance with data as a string, but not strict (to validate later in strict mode if needed) | ||
const ceFullTextData = new CloudEvent('5/no-strict-text-data', | ||
@@ -156,8 +149,7 @@ ceNamespace, | ||
ceDataAsString, // data | ||
ceCommonOptions, // use common options | ||
// ceCommonOptions, // ok but not in strict validation | ||
ceCommonOptionsForTextData, // ok even in strict validation | ||
ceCommonExtensions | ||
) | ||
assert(ceFullTextData !== null) | ||
assert(!ceFullTextData.isStrict) | ||
assert(ceFullTextData.payload === ceDataAsString) // returned data is transformed | ||
console.log(`cloudEvent payload: '${ceFullTextData.payload}', length: ${ceFullTextData.payload.length}`) | ||
// create an instance with data encoded in base64 | ||
@@ -171,5 +163,3 @@ const ceFullStrictBinaryData = new CloudEvent('6/full-strict-binary-data', | ||
) | ||
assert(ceFullStrictBinaryData !== null) | ||
assert(ceFullStrictBinaryData.isStrict) | ||
assert(ceFullStrictBinaryData.payload === ceDataAsString) // returned data is transformed | ||
console.log(`cloudEvent payload: '${ceFullStrictBinaryData.payload}', length: ${ceFullStrictBinaryData.payload.length}`) | ||
``` | ||
@@ -184,3 +174,6 @@ | ||
assert(!ceMinimalMandatoryUndefinedNoStrict.isValid()) | ||
assert(ceMinimalBadSource.isValid()) | ||
assert(!ceMinimalBadSource.isValid({ strict: true })) | ||
assert(ceMinimal.isValid()) | ||
assert(ceMinimal.isValid({ strict: true })) | ||
assert(ceFull.isValid()) | ||
@@ -190,8 +183,12 @@ assert(ceFullStrict.isValid()) | ||
assert(ceFullStrictOtherContentType.isValid()) | ||
assert(ceFullTextData.isValid()) | ||
assert(ceFullTextData.isValid({ strict: true })) | ||
assert(CloudEvent.isValidEvent(ceFullTextData, { strict: true })) | ||
assert(CloudEvent.isValidEvent(ceFullStrictBinaryData)) | ||
// etc ... | ||
console.log(`Validation on ceEmpty: isValid: ${ceEmpty.isValid()}`) | ||
console.log(`Validation output for ceEmpty, default strict mode is: size: ${CloudEvent.validateEvent(ceEmpty).length}, details:\n` + CloudEvent.validateEvent(ceEmpty)) | ||
console.log(`Validation output for ceEmpty, force strict mode to true is size: ${CloudEvent.validateEvent(ceEmpty, { strict: true }).length}, details:\n` + CloudEvent.validateEvent(ceEmpty, { strict: true })) | ||
console.log(`Validation output for ceEmpty, alternative way: ${CloudEvent.dumpValidationResults(ceEmpty, { strict: true }, 'ceEmpty')}`) | ||
``` | ||
@@ -220,2 +217,6 @@ | ||
console.log('Serialization output for ceFullStrictOtherContentType, details:\n' + ceFullStrictOtherContentTypeSerialized) | ||
const ceFullTextDataSerialized = CloudEvent.serializeEvent(ceFullTextData, { onlyValid: true }) | ||
console.log('Serialization output for ceFullTextData, details:\n' + ceFullTextDataSerialized) | ||
const ceFullStrictBinaryDataSerialized = CloudEvent.serializeEvent(ceFullStrictBinaryData, { onlyValid: true }) | ||
console.log('Serialization output for ceFullStrictBinaryData, details:\n' + ceFullStrictBinaryDataSerialized) | ||
@@ -233,9 +234,4 @@ // then use (send/store/etc) serialized instances ... | ||
const ceFullDeserialized = CloudEvent.deserializeEvent(ceFullSerialized) | ||
assert(ceFullDeserialized !== null) | ||
assert(ceFullDeserialized.isValid()) | ||
assert(!ceFullDeserialized.isStrict) | ||
assert(CloudEvent.isCloudEvent(ceFullDeserialized)) | ||
console.log(`cloudEvent dump: ${T.dumpObject(ceFullDeserialized, 'ceFullDeserialized')}`) | ||
const ceFullStrictDeserializedOnlyValid = CloudEvent.deserializeEvent(ceFullStrictSerialized, { onlyValid: true }) | ||
assert(ceFullStrictDeserializedOnlyValid !== null) | ||
console.log(`cloudEvent dump: ${T.dumpObject(ceFullStrictDeserializedOnlyValid, 'ceFullStrictDeserializedOnlyValid')}`) | ||
@@ -248,7 +244,7 @@ // non default contenttype | ||
}) | ||
assert(ceFullStrictOtherContentTypeDeserialized !== null) | ||
assert(ceFullStrictOtherContentTypeDeserialized.isValid()) | ||
assert(ceFullStrictOtherContentTypeDeserialized.isStrict) | ||
assert(CloudEvent.isCloudEvent(ceFullStrictOtherContentTypeDeserialized)) | ||
console.log(`cloudEvent dump: ${T.dumpObject(ceFullStrictOtherContentTypeDeserialized, 'ceFullStrictOtherContentTypeDeserialized')}`) | ||
const ceFullTextDataDeserialized = CloudEvent.deserializeEvent(ceFullTextDataSerialized, { onlyValid: true }) | ||
console.log(`ce dump: ${T.dumpObject(ceFullTextDataDeserialized, 'ceFullTextDataDeserialized')}`) | ||
const ceFullStrictBinaryDataDeserialized = CloudEvent.deserializeEvent(ceFullStrictBinaryDataSerialized, { onlyValid: true }) | ||
console.log(`ce dump: ${T.dumpObject(ceFullStrictBinaryDataDeserialized, 'ceFullStrictBinaryDataDeserialized')}`) | ||
@@ -259,3 +255,5 @@ // then use (validate/send/store/etc) deserialized instances ... | ||
Look into the [example](./example/) folder for more sample scripts that uses the library | ||
From previous code blocks, I remove most assert statements, to simplify | ||
code reading and usage; but for a deeper comprension and usage, | ||
look into the [example](./example/) folder for more sample scripts that uses the library | ||
(inline but it's the same using it from npm registry); | ||
@@ -267,5 +265,14 @@ you can find even examples for using JSONBatch objects (array of CloudEvent instances). | ||
Node.js 8 LTS (but recommended 8.17.0) or later. | ||
Node.js 10 LTS (but recommended 10.23.1) or later. | ||
## Sources | ||
Source code is all inside main repo: | ||
[cloudevent.js](https://github.com/smartiniOnGitHub/cloudevent.js/). | ||
Documentation generated from source code (library API): | ||
[here](https://smartiniongithub.github.io/cloudevent.js/). | ||
## Note | ||
@@ -278,5 +285,2 @@ | ||
You can find Code Documentation for the API of the library | ||
[here](https://smartiniongithub.github.io/cloudevent.js/). | ||
See the CloudEvents Specification [here](https://github.com/cloudevents/spec). | ||
@@ -301,2 +305,3 @@ | ||
so for example my strict extension now is 'strictvalidation' with a boolean value. | ||
Since v1.0.1 of the spec, some properties has been expanded/clarified. | ||
@@ -303,0 +308,0 @@ |
/* | ||
* Copyright 2018 the original author or authors. | ||
* Copyright 2018-2021 the original author or authors. | ||
* | ||
@@ -25,3 +25,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
* Get a reference to cloudevent Validator class. | ||
* | ||
* @private | ||
* @see Validator | ||
@@ -33,3 +33,3 @@ */ | ||
* Get a reference to cloudevent Transformer class. | ||
* | ||
* @private | ||
* @see Transformer | ||
@@ -52,9 +52,9 @@ */ | ||
* @param {object} [options={}] optional attributes of the event; some has default values chosen here: | ||
* time (timestamp/date, default now), | ||
* datainbase64 (string) base64 encoded value for the data (data attribute must not be present when this is defined), | ||
* datacontenttype (string, default 'application/json') is the content type of the data attribute, | ||
* dataschema (uri) optional, reference to the schema that data adheres to, | ||
* subject (string) optional, describes the subject of the event in the context of the event producer (identified by source), | ||
* strict (boolean, default false) tell if object instance will be validated in a more strict way | ||
* @param {object} extensions optional, contains extension properties (each extension as a key/value property, and no nested objects) but if given any object must contain at least 1 property | ||
* - time (timestamp/date, default now), | ||
* - datainbase64 (string) base64 encoded value for the data (data attribute must not be present when this is defined), | ||
* - datacontenttype (string, default 'application/json') is the content type of the data attribute, | ||
* - dataschema (uri) optional, reference to the schema that data adheres to, | ||
* - subject (string) optional, describes the subject of the event in the context of the event producer (identified by source), | ||
* - strict (boolean, default false) tell if object instance will be validated in a more strict way | ||
* @param {?object} extensions optional, contains extension properties (each extension as a key/value property, and no nested objects) but if given any object must contain at least 1 property | ||
* @throws {Error} if strict is true and id or type is undefined or null | ||
@@ -133,6 +133,7 @@ * @throws {Error} if data and data_base64 are defined | ||
* The MIME Type for the encoding of the data attribute, when serialized. | ||
* If null, default value will be set. | ||
* @type {string} | ||
* @private | ||
*/ | ||
this.datacontenttype = datacontenttype | ||
this.datacontenttype = (!V.isNull(datacontenttype)) ? datacontenttype : CloudEvent.datacontenttypeDefault() | ||
/** | ||
@@ -147,2 +148,3 @@ * The URI of the schema for event data, if any. | ||
* Copy the original object to avoid changing objects that could be shared. | ||
* If null, current timestamp will be set. | ||
* Note that here the object will be transformed into string when serialized. | ||
@@ -152,3 +154,3 @@ * @type {object} | ||
*/ | ||
this.time = new Date(time.valueOf()) | ||
this.time = (!V.isNull(time)) ? new Date(time.valueOf()) : new Date() | ||
/** | ||
@@ -359,4 +361,4 @@ * The subject of the event in the context of the event producer. | ||
* @param {object} [options={}] containing: | ||
* strict (boolean, default false) to validate it in a more strict way, | ||
* dataschemavalidator (function(data, dataschema) boolean, optional) a function to validate data of current CloudEvent instance with its dataschema | ||
* - strict (boolean, default false) to validate it in a more strict way, | ||
* - dataschemavalidator (function(data, dataschema) boolean, optional) a function to validate data of current CloudEvent instance with its dataschema | ||
* @return {object[]} an array of (non null) validation errors, or at least an empty array | ||
@@ -407,8 +409,10 @@ */ | ||
} else { | ||
ve.push(V.ensureIsObjectOrCollectionNotString(event.data, 'data')) | ||
ve.push(CloudEvent.ensureTypeOfDataIsRight(event)) | ||
} | ||
// end of default datacontenttype | ||
} else { | ||
// ensure data is a plain object or collection, or even a string in this case | ||
// ensure data is a plain object or collection, | ||
// or even a value (string or boolean or number) in this case | ||
// because in serialization/deserialization some validation can occur on the transformed object | ||
ve.push(V.ensureIsObjectOrCollectionOrString(event.data, 'data')) | ||
ve.push(CloudEvent.ensureTypeOfDataIsRight(event)) | ||
} | ||
@@ -419,3 +423,5 @@ } | ||
ve.push(V.ensureIsStringNotEmpty(event.datacontenttype, 'datacontenttype')) | ||
ve.push(V.ensureIsURI(event.dataschema, null, 'dataschema')) | ||
if (V.isDefinedAndNotNull(event.dataschema)) { | ||
ve.push(V.ensureIsURI(event.dataschema, null, 'dataschema')) | ||
} | ||
if (V.isFunction(dataschemavalidator)) { | ||
@@ -426,3 +432,3 @@ try { | ||
} catch (e) { | ||
ve.push(new Error('data does not respect the dataschema for the given validator')) | ||
ve.push(new Error(`data does not respect the dataschema '${event.dataschema}' for the given validator`)) | ||
} | ||
@@ -453,4 +459,4 @@ } | ||
* @param {object} [options={}] containing: | ||
* strict (boolean, default false) to validate it in a more strict way, | ||
* dataschemavalidator (function(data, dataschema) boolean, optional) a function to validate data of current CloudEvent instance with its dataschema | ||
* - strict (boolean, default false) to validate it in a more strict way, | ||
* - dataschemavalidator (function(data, dataschema) boolean, optional) a function to validate data of current CloudEvent instance with its dataschema | ||
* @return {boolean} true if valid, otherwise false | ||
@@ -487,6 +493,6 @@ */ | ||
* @param {object} [options={}] optional serialization attributes: | ||
* encoder (function, no default) a function that takes data and returns encoded data as a string, | ||
* encodedData (string, no default) already encoded data (but consistency with the datacontenttype is not checked), | ||
* onlyValid (boolean, default false) to serialize only if it's a valid instance, | ||
* onlyIfLessThan64KB (boolean, default false) to return the serialized string only if it's less than 64 KB, | ||
* - encoder (function, no default) a function that takes data and returns encoded data as a string, | ||
* - encodedData (string, no default) already encoded data (but consistency with the datacontenttype is not checked), | ||
* - onlyValid (boolean, default false) to serialize only if it's a valid instance, | ||
* - onlyIfLessThan64KB (boolean, default false) to return the serialized string only if it's less than 64 KB, | ||
* @return {string} the serialized event, as a string | ||
@@ -521,3 +527,7 @@ * @throws {Error} if event is undefined or null, or an option is undefined/null/wrong | ||
// encoder not defined, check encodedData | ||
if (!V.isDefinedAndNotNull(encodedData)) throw new Error(`Missing encoder function: use encoder function or already encoded data with the given data content type: '${event.datacontenttype}'.`) | ||
// but mandatory only for non-value data | ||
if (!V.isValue(event.data) && !V.isDefinedAndNotNull(encodedData)) throw new Error(`Missing encoder function: use encoder function or already encoded data with the given data content type: '${event.datacontenttype}'.`) | ||
if (V.isValue(event.data) && !V.isDefinedAndNotNull(encodedData)) { | ||
encodedData = `${event.data}` | ||
} | ||
} | ||
@@ -541,7 +551,7 @@ if (!V.isStringNotEmpty(encodedData)) throw new Error(`Missing or wrong encoded data: '${encodedData}' for the given data content type: '${event.datacontenttype}'.`) | ||
* @param {object} [options={}] optional deserialization attributes: | ||
* decoder (function, no default) a function that takes data and returns decoder data as a string, | ||
* decodedData (string, no default) already decoded data (but consistency with the datacontenttype is not checked), | ||
* onlyValid (boolean, default false) to deserialize only if it's a valid instance, | ||
* onlyIfLessThan64KB (boolean, default false) to return the deserialized string only if it's less than 64 KB, | ||
* timezoneOffset (number, default 0) to apply a different timezone offset | ||
* - decoder (function, no default) a function that takes data and returns decoder data as a string, | ||
* - decodedData (string, no default) already decoded data (but consistency with the datacontenttype is not checked), | ||
* - onlyValid (boolean, default false) to deserialize only if it's a valid instance, | ||
* - onlyIfLessThan64KB (boolean, default false) to return the deserialized string only if it's less than 64 KB, | ||
* - timezoneOffset (number, default 0) to apply a different timezone offset | ||
* @return {object} the deserialized event as a CloudEvent instance | ||
@@ -596,5 +606,9 @@ * @throws {Error} if ser is undefined or null, or an option is undefined/null/wrong | ||
// decoder not defined, so decodedData must be defined | ||
if (!V.isDefinedAndNotNull(decodedData)) throw new Error(`Missing decoder function: use decoder function or already decoded data with the given data content type: '${parsed.datacontenttype}'.`) | ||
// but mandatory only for non-value data | ||
if (!V.isValue(parsed.data) && !V.isDefinedAndNotNull(decodedData)) throw new Error(`Missing decoder function: use decoder function or already decoded data with the given data content type: '${parsed.datacontenttype}'.`) | ||
if (V.isValue(parsed.data) && !V.isDefinedAndNotNull(decodedData)) { | ||
decodedData = `${parsed.data}` | ||
} | ||
} | ||
if (!V.isObjectOrCollectionOrString(decodedData)) throw new Error(`Missing or wrong decoded data: '${decodedData}' for the given data content type: '${parsed.datacontenttype}'.`) | ||
if (!V.isObjectOrCollectionOrArrayOrValue(decodedData)) throw new Error(`Missing or wrong decoded data: '${decodedData}' for the given data content type: '${parsed.datacontenttype}'.`) | ||
// overwrite data with decodedData before returning it | ||
@@ -660,3 +674,3 @@ ce.data = decodedData | ||
if (V.isUndefined(value)) throw new Error('Extension value undefined') | ||
if (!V.isString(value) && !V.isBoolean(value) && !V.isNumber(value)) return false | ||
if (!V.isString(value) && !V.isBoolean(value) && !V.isNumber(value) && !V.isNull(value)) return false | ||
return true | ||
@@ -694,8 +708,8 @@ } | ||
source: { type: 'string', format: 'uri-reference' }, | ||
datacontenttype: { type: 'string' }, | ||
data: { type: ['object', 'string'] }, | ||
data_base64: { type: 'string' }, | ||
dataschema: { type: 'string', format: 'uri' }, | ||
// time: { type: 'string', format: 'date-time' }, | ||
subject: { type: 'string', minLength: 1 } | ||
datacontenttype: { type: ['string', 'null'], minLength: 1 }, | ||
data: { type: ['object', 'string', 'number', 'array', 'boolean', 'null'] }, | ||
data_base64: { type: ['string', 'null'], contentEncoding: 'base64' }, | ||
dataschema: { type: ['string', 'null'], format: 'uri', minLength: 1 }, | ||
time: { type: ['string', 'null'], format: 'date-time', minLength: 1 }, | ||
subject: { type: ['string', 'null'], minLength: 1 } | ||
}, | ||
@@ -708,2 +722,56 @@ required: ['specversion', 'id', 'type', 'source'], | ||
/** | ||
* Tell the type of data of the CloudEvent, | ||
* if it's right (depending even on related datacontenttype), | ||
* from the validator point of view. | ||
* | ||
* @static | ||
* @param {!object} ce the CloudEvent to validate | ||
* @param {object} [options={}] optional validation options | ||
* @param {string} [name='data'] the name to assign in the returned error string (if any), or 'data' as default value | ||
* @return {string|null} error message if the given data type is not right, otherwise null | ||
* @throws {TypeError} if event is not a CloudEvent instance or subclass | ||
* @throws {Error} if event is undefined or null | ||
*/ | ||
static ensureTypeOfDataIsRight (ce, options = {}, name = 'data') { | ||
if (!CloudEvent.isCloudEvent(ce)) throw new TypeError('The given event is not a CloudEvent instance') | ||
let ve | ||
if (V.isUndefinedOrNull(ce.data)) { | ||
ve = null // it's impossible to verify its type | ||
} else if (ce.datacontenttype === CloudEvent.datacontenttypeDefault()) { | ||
ve = V.ensureIsObjectOrCollectionOrArrayNotValue(ce.data, name) || null | ||
} else { | ||
// for example with: datacontenttype 'text/plain': | ||
// ensure data is a plain object or collection, | ||
// or even a string or boolean or number in this case | ||
// because in serialization/deserialization some validation can occur on the transformed object | ||
ve = V.ensureIsObjectOrCollectionOrArrayOrValue(ce.data, name) || null | ||
} | ||
return ve | ||
} | ||
/** | ||
* Utility function that return a dump of validation results | ||
* on the given CloudEvent. | ||
* | ||
* @static | ||
* @param {(?object)} ce the CloudEvent object to dump | ||
* @param {object} [options={}] optional validation options | ||
* @param {string} [name='noname'] the name to assign in the returned string, or 'noname' as default value | ||
* @return {string} the dump of the object or a message when obj is undefined/null/not a CloudEvent | ||
*/ | ||
static dumpValidationResults (ce, options = {}, name = 'noname') { | ||
if (V.isUndefined(ce)) { | ||
return `${name}: undefined` | ||
} else if (V.isNull(ce)) { | ||
return `${name}: null` | ||
} else if (CloudEvent.isCloudEvent(ce)) { | ||
const opts = (options == null) ? {} : options | ||
const ve = CloudEvent.validateEvent(ce, opts) | ||
return `${name}: ${JSON.stringify(ve.map((i) => i.message))}` | ||
} else { | ||
return `${name}: 'is not a CloudEvent, no validation possible'` | ||
} | ||
} | ||
/** | ||
* Serialize the current CloudEvent. | ||
@@ -714,4 +782,4 @@ * | ||
* @param {object} [options={}] optional serialization attributes: | ||
* encoder (function, default null) a function that takes data and returns encoded data, | ||
* encodedData (string, default null) already encoded data (but consistency with the datacontenttype is not checked), | ||
* - encoder (function, default null) a function that takes data and returns encoded data, | ||
* - encodedData (string, default null) already encoded data (but consistency with the datacontenttype is not checked), | ||
* @return {string} the serialized event, as a string | ||
@@ -729,4 +797,4 @@ */ | ||
* @param {object} [options={}] containing: | ||
* strict (boolean, default false) to validate it in a more strict way, | ||
* dataschemavalidator (function(data, dataschema) boolean, optional) a function to validate data of current CloudEvent instance with its dataschema | ||
* - strict (boolean, default false) to validate it in a more strict way, | ||
* - dataschemavalidator (function(data, dataschema) boolean, optional) a function to validate data of current CloudEvent instance with its dataschema | ||
* @return {object[]} an array of (non null) validation errors, or at least an empty array | ||
@@ -744,4 +812,4 @@ */ | ||
* @param {object} [options={}] containing: | ||
* strict (boolean, default false) to validate it in a more strict way, | ||
* dataschemavalidator (function(data, dataschema) boolean, optional) a function to validate data of current CloudEvent instance with its dataschema | ||
* - strict (boolean, default false) to validate it in a more strict way, | ||
* - dataschemavalidator (function(data, dataschema) boolean, optional) a function to validate data of current CloudEvent instance with its dataschema | ||
* @return {boolean} true if valid, otherwise false | ||
@@ -793,3 +861,3 @@ */ | ||
* | ||
* @type {(object|Map|Set|string)} | ||
* @type {(object|Map|Set|Array|string|boolean|number)} | ||
*/ | ||
@@ -805,2 +873,4 @@ get payload () { | ||
return this.data.slice() | ||
} else if (V.isArray(this.data)) { | ||
return this.data.map((i) => i) | ||
} else { | ||
@@ -810,5 +880,9 @@ return { ...this.data } | ||
} | ||
// end of this.isDatacontenttypeJSON | ||
} else if (V.isString(this.data)) { | ||
// handle an edge case: if data is a String, I need to clone in a different way ... | ||
return this.data.slice() | ||
} else if (V.isArray(this.data)) { | ||
return this.data.map((i) => i) | ||
} else if (V.isBoolean(this.data) || V.isNumber(this.data)) { | ||
return this.data | ||
} else { | ||
@@ -863,5 +937,9 @@ return { ...this.data } | ||
toString () { | ||
const dataDumped = T.dumpObject(this.data, 'data') | ||
const dataSummary = (dataDumped.length < 1024) ? dataDumped : (dataDumped.substr(0, 1019) + ' ...}') | ||
return `CloudEvent[specversion: ${this.specversion}, ${T.dumpObject(this.id, 'id')}, ${T.dumpObject(this.type, 'type')}, ${dataSummary}, ...]` | ||
const payload = this.payload | ||
const payloadDump = T.dumpObject(payload, 'payload') | ||
let payloadSummary = (payloadDump.length < 1024) ? payloadDump : (payloadDump.substr(0, 1020) + '...') | ||
if (V.isString(payload)) { | ||
payloadSummary = payloadSummary + '\'' | ||
} | ||
return `CloudEvent[specversion:${this.specversion}, id:'${this.id}', type:'${this.type}', source:'${this.source}', datacontenttype:'${this.datacontenttype}', ${payloadSummary}, ...]` | ||
} | ||
@@ -884,2 +962,4 @@ | ||
* | ||
* @readonly | ||
* @type {string[]} | ||
* @static | ||
@@ -886,0 +966,0 @@ */ |
/* | ||
* Copyright 2018 the original author or authors. | ||
* Copyright 2018-2021 the original author or authors. | ||
* | ||
@@ -19,5 +19,11 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
/** | ||
* index: | ||
* this module groups all functions/classes, to export in a simpler way. | ||
* @module cloudevent | ||
*/ | ||
/** | ||
* Get a reference to CloudEvent class definition. | ||
* | ||
* See {@link CloudEvent}. | ||
* @private | ||
*/ | ||
@@ -28,4 +34,4 @@ const cloudEventDefinition = require('./cloudevent') | ||
* Get a reference to JSONBatch class definition. | ||
* | ||
* See {@link JSONBatch}. | ||
* @private | ||
*/ | ||
@@ -36,4 +42,4 @@ const jsonBatchDefinition = require('./jsonbatch') | ||
* Get a reference to cloudevent class Validator. | ||
* | ||
* See {@link Validator}. | ||
* @private | ||
*/ | ||
@@ -44,4 +50,4 @@ const cloudEventValidator = require('./validator') | ||
* Get a reference to cloudevent class Transformer. | ||
* | ||
* See {@link Transformer}. | ||
* @private | ||
*/ | ||
@@ -51,6 +57,13 @@ const cloudEventTransformer = require('./transformer') | ||
module.exports = { | ||
/** CloudEvent class definition. */ | ||
CloudEvent: cloudEventDefinition, | ||
/** JSONBatch class definition. */ | ||
JSONBatch: jsonBatchDefinition, | ||
/** CloudEvent class Validator. */ | ||
CloudEventValidator: cloudEventValidator, | ||
/** CloudEvent class Transformer. */ | ||
CloudEventTransformer: cloudEventTransformer | ||
} |
/* | ||
* Copyright 2018 the original author or authors. | ||
* Copyright 2018-2021 the original author or authors. | ||
* | ||
@@ -26,4 +26,4 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
* Get a reference to cloudevent CloudEvent class. | ||
* | ||
* @see Validator | ||
* @private | ||
*/ | ||
@@ -34,4 +34,4 @@ const CloudEvent = require('./cloudevent') // get cloudevent from here | ||
* Get a reference to cloudevent Validator class. | ||
* | ||
* @see Validator | ||
* @private | ||
*/ | ||
@@ -48,6 +48,6 @@ const V = require('./validator') // get validator from here | ||
* Create a new instance of a JSONBatch object. | ||
* | ||
* Note that instancing is not allowed for this class because all its methods are static. | ||
* | ||
* @throws {Error} because instancing not allowed for this class | ||
* @throws {Error} instancing not allowed for this class | ||
* @hideconstructor | ||
*/ | ||
@@ -86,12 +86,12 @@ constructor () { | ||
if (V.isArray(batch)) { | ||
// additional validation on nested items (any not null item) | ||
const itemsValidation = batch.filter((i) => V.isDefinedAndNotNull(i) | ||
).map((i) => { | ||
const ceValidation = CloudEvent.validateEvent(i, { strict }) | ||
if (ceValidation.length > 0) { | ||
// return validation errors found | ||
return ceValidation | ||
batch.forEach((i, index) => { | ||
if (V.isDefinedAndNotNull(i) || strict === true) { | ||
// additional validation (and on all items) in strict mode | ||
const ceValidation = CloudEvent.validateEvent(i, { strict }) | ||
if (ceValidation.length > 0) { | ||
// append validation errors found | ||
ve.push(...ceValidation) | ||
} | ||
} | ||
}) | ||
ve.push(...itemsValidation) | ||
} else if (CloudEvent.isCloudEvent(batch)) { | ||
@@ -150,6 +150,7 @@ // validate the given (single) CloudEvent instance or subclass | ||
* @static | ||
* @generator | ||
* @param {!object} batch the JSONBatch to iterate | ||
* @param {object} [options={}] optional processing attributes: | ||
* onlyValid (boolean, default false) to extract only valid instances | ||
* strict (boolean, default false) to validate it in a more strict way | ||
* - onlyValid (boolean, default false) to extract only valid instances | ||
* - strict (boolean, default false) to validate it in a more strict way | ||
* @return {object} a CloudEvent (if any) | ||
@@ -186,4 +187,4 @@ * @throws {Error} if batch is undefined or null | ||
* @param {object} [options={}] optional processing attributes: | ||
* onlyValid (boolean, default false) to extract only valid instances | ||
* strict (boolean, default false) to validate it in a more strict way | ||
* - onlyValid (boolean, default false) to extract only valid instances | ||
* - strict (boolean, default false) to validate it in a more strict way | ||
* @return {object[]} processed events, as an array | ||
@@ -222,4 +223,4 @@ * @throws {Error} if batch is undefined or null, or an option is undefined/null/wrong | ||
* Additional options valid here: | ||
* logError (boolean, default false) to log to console serialization errors | ||
* throwError (boolean, default false) to throw serialization errors | ||
* - logError (boolean, default false) to log to console serialization errors | ||
* - throwError (boolean, default false) to throw serialization errors | ||
* @return {string} the serialized JSONBatch, as a string | ||
@@ -276,4 +277,4 @@ * @throws {Error} if batch is undefined or null, or an option is undefined/null/wrong | ||
* Additional options valid here: | ||
* logError (boolean, default false) to log to console deserialization errors | ||
* throwError (boolean, default false) to throw serialization errors | ||
* - logError (boolean, default false) to log to console deserialization errors | ||
* - throwError (boolean, default false) to throw serialization errors | ||
* @return {object[]} the deserialized batch as a JSONBatch (so a CloudEvent array instance) | ||
@@ -280,0 +281,0 @@ * @throws {Error} if ser is undefined or null, or an option is undefined/null/wrong |
/* | ||
* Copyright 2018 the original author or authors. | ||
* Copyright 2018-2021 the original author or authors. | ||
* | ||
@@ -25,11 +25,17 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
* Get a reference to cloudevent Validator class. | ||
* | ||
* See {@link Validator}. | ||
* @private | ||
*/ | ||
const V = require('./validator') // get validator from here | ||
/** Get the host name where this code is runninng */ | ||
/** | ||
* Get the host name where this code is runninng. | ||
* @private | ||
*/ | ||
const hostname = require('os').hostname() | ||
/** Get the process id (pid) where this code is runninng */ | ||
/** | ||
* Get the process id (pid) where this code is runninng. | ||
* @private | ||
*/ | ||
const pid = require('process').pid | ||
@@ -46,6 +52,6 @@ | ||
* Create a new instance of a Transformer object. | ||
* | ||
* Note that instancing is not allowed for this class because all its methods are static. | ||
* | ||
* @throws {Error} because instancing not allowed for this class | ||
* @throws {Error} instancing not allowed for this class | ||
* @hideconstructor | ||
*/ | ||
@@ -66,9 +72,9 @@ constructor () { | ||
if (V.isUndefined(obj)) { | ||
return `${name}: undefined` | ||
return `${name}:undefined` | ||
} else if (V.isNull(obj)) { | ||
return `${name}: null` | ||
return `${name}:null` | ||
} else if (V.isObject(obj) || V.isKeyedCollection(obj)) { | ||
return `${name}: ${JSON.stringify(obj)}` | ||
return `${name}:${JSON.stringify(obj)}` | ||
} else { | ||
return `${name}: '${obj.toString()}'` | ||
return `${name}:'${obj.toString()}'` | ||
} | ||
@@ -211,5 +217,5 @@ } | ||
* @param {object} [options={}] transformation options: | ||
* includeStackTrace flag (default false) to add the StackTrace into the object to return, | ||
* addStatus flag (default true) to add a 'status' attribute into the object to return, | ||
* addTimestamp flag (default false) to add the current 'timestamp' as attribute into the object to return, | ||
* - includeStackTrace flag (default false) to add the StackTrace into the object to return, | ||
* - addStatus flag (default true) to add a 'status' attribute into the object to return, | ||
* - addTimestamp flag (default false) to add the current 'timestamp' as attribute into the object to return, | ||
* @return {object} the object representation of the error | ||
@@ -302,2 +308,4 @@ * @throws {TypeError} if err is undefined or null, or is not an Error instance | ||
* | ||
* @readonly | ||
* @type {number} | ||
* @static | ||
@@ -304,0 +312,0 @@ */ |
/* | ||
* Copyright 2018 the original author or authors. | ||
* Copyright 2018-2021 the original author or authors. | ||
* | ||
@@ -23,2 +23,6 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
/** | ||
* Get a reference to Node.js url module. | ||
* @private | ||
*/ | ||
const url = require('url') | ||
@@ -35,6 +39,6 @@ | ||
* Create a new instance of a Validator object. | ||
* | ||
* Note that instancing is not allowed for this class because all its methods are static. | ||
* | ||
* @throws {Error} because instancing not allowed for this class | ||
* @throws {Error} instancing not allowed for this class | ||
* @hideconstructor | ||
*/ | ||
@@ -160,3 +164,3 @@ constructor () { | ||
static isDateFuture (arg) { | ||
return (Validator.isDateValid(arg) && arg.getTime() >= Date.now()) | ||
return (Validator.isDateValid(arg) && arg.getTime() > Date.now()) | ||
} | ||
@@ -187,2 +191,16 @@ | ||
/** | ||
* Tell if the given argument is a normal value | ||
* (string or boolean or number). | ||
* | ||
* @static | ||
* @param {?object} arg the object to check | ||
* @return {boolean} true if it's a string or boolean or number, false otherwise | ||
*/ | ||
static isValue (arg) { | ||
return (Validator.isDefinedAndNotNull(arg) && | ||
(Validator.isString(arg) || Validator.isBoolean(arg) || Validator.isNumber(arg)) | ||
) | ||
} | ||
/** | ||
* Tell if the given argument is a boolean. | ||
@@ -299,2 +317,16 @@ * | ||
/** | ||
* Tell if the given argument is a plain object or a keyed collection or an array. | ||
* | ||
* See {@link Validator.isObjectOrCollection}. | ||
* See {@link Validator.isArray}. | ||
* | ||
* @static | ||
* @param {?object} arg the object to check | ||
* @return {boolean} true if it's a plain object or a keyed collection or an array, false otherwise | ||
*/ | ||
static isObjectOrCollectionOrArray (arg) { | ||
return (Validator.isObjectOrCollection(arg) || Validator.isArray(arg)) | ||
} | ||
/** | ||
* Tell if the given argument is a plain object or a keyed collection, but not a string. | ||
@@ -313,2 +345,18 @@ * | ||
/** | ||
* Tell if the given argument is a plain object or a keyed collection or an array, | ||
* but not a value (string or boolean or number). | ||
* | ||
* See {@link Validator.isObjectOrCollection}. | ||
* See {@link Validator.isArray}. | ||
* See {@link Validator.isValue}. | ||
* | ||
* @static | ||
* @param {?object} arg the object to check | ||
* @return {boolean} true if it's a plain object or a keyed collection or an array but not a value (string or boolean or number), false otherwise | ||
*/ | ||
static isObjectOrCollectionOrArrayNotValue (arg) { | ||
return ((Validator.isObjectOrCollection(arg) || Validator.isArray(arg)) && !Validator.isValue(arg)) | ||
} | ||
/** | ||
* Tell if the given argument is a plain object or a keyed collection, or a string. | ||
@@ -327,2 +375,33 @@ * | ||
/** | ||
* Tell if the given argument is a plain object or a keyed collection, | ||
* or a value (string or boolean or number). | ||
* | ||
* See {@link Validator.isObjectOrCollection}. | ||
* See {@link Validator.isValuey}. | ||
* | ||
* @static | ||
* @param {?object} arg the object to check | ||
* @return {boolean} true if it's a plain object or a keyed collection or a value (string or boolean or number), false otherwise | ||
*/ | ||
static isObjectOrCollectionOrValue (arg) { | ||
return (Validator.isObjectOrCollection(arg) || Validator.isValue(arg)) | ||
} | ||
/** | ||
* Tell if the given argument is a plain object or a keyed collection or an array, | ||
* or a value (string or boolean or number). | ||
* | ||
* See {@link Validator.isObjectOrCollection}. | ||
* See {@link Validator.isArray}. | ||
* See {@link Validator.isValuey}. | ||
* | ||
* @static | ||
* @param {?object} arg the object to check | ||
* @return {boolean} true if it's a plain object or a keyed collection or an array or a value (string or boolean or number), false otherwise | ||
*/ | ||
static isObjectOrCollectionOrArrayOrValue (arg) { | ||
return (Validator.isObjectOrCollection(arg) || Validator.isArray(arg) || Validator.isValue(arg)) | ||
} | ||
/** | ||
* Tell if the given argument is a string representation of a version number. | ||
@@ -506,2 +585,18 @@ * | ||
/** | ||
* Ensure that the given argument is a value (string or boolean or number). | ||
* | ||
* See {@link Validator.isValue}. | ||
* | ||
* @static | ||
* @param {?object} arg the object to check | ||
* @param {string} [name='arg'] the name to use in generated error (or the value of first argument if not given) | ||
* @return {TypeError} if it's not a string or a boolean or a number, nothing otherwise | ||
*/ | ||
static ensureIsValue (arg, name = 'arg') { | ||
if (!Validator.isValue(arg)) { | ||
return new TypeError(`The argument '${name}' must be a value (string or boolean or number), instead got a '${typeof arg}'`) | ||
} | ||
} | ||
/** | ||
* Ensure that the given argument is a boolean. | ||
@@ -654,2 +749,18 @@ * | ||
/** | ||
* Ensure that the given argument is a plain object or a collection or an array. | ||
* | ||
* See {@link Validator.isObjectOrCollectionOrArray}. | ||
* | ||
* @static | ||
* @param {?object} arg the object to check | ||
* @param {string} [name='arg'] the name to use in generated error (or the value of first argument if not given) | ||
* @return {TypeError} if it's not a plain object nor a collection nor an array, nothing otherwise | ||
*/ | ||
static ensureIsObjectOrCollectionOrArray (arg, name = 'arg') { | ||
if (!Validator.isObjectOrCollectionOrArray(arg)) { | ||
return new TypeError(`The argument '${name}' must be an object or a collection and not an array, instead got a '${typeof arg}'`) | ||
} | ||
} | ||
/** | ||
* Ensure that the given argument is a plain object or a collection, not a string. | ||
@@ -671,2 +782,19 @@ * | ||
/** | ||
* Ensure that the given argument is a plain object or a collection or an array, | ||
* not a value (string or boolean or number). | ||
* | ||
* See {@link Validator.isObjectOrCollectionOrArrayNotValue}. | ||
* | ||
* @static | ||
* @param {?object} arg the object to check | ||
* @param {string} [name='arg'] the name to use in generated error (or the value of first argument if not given) | ||
* @return {TypeError} if it's not a plain object nor a collection or it's a value (string or boolean or number), nothing otherwise | ||
*/ | ||
static ensureIsObjectOrCollectionOrArrayNotValue (arg, name = 'arg') { | ||
if (!Validator.isObjectOrCollectionOrArrayNotValue(arg)) { | ||
return new TypeError(`The argument '${name}' must be an object or a collection or an array and not a value (string or boolean or number), instead got a '${typeof arg}'`) | ||
} | ||
} | ||
/** | ||
* Ensure that the given argument is a plain object or a collection, or a string. | ||
@@ -688,2 +816,36 @@ * | ||
/** | ||
* Ensure that the given argument is a plain object or a collection, | ||
* or a value (string or boolean or number). | ||
* | ||
* See {@link Validator.isObjectOrCollectionOrValue}. | ||
* | ||
* @static | ||
* @param {?object} arg the object to check | ||
* @param {string} [name='arg'] the name to use in generated error (or the value of first argument if not given) | ||
* @return {TypeError} if it's not a plain object nor a collection nor a value (string or boolean or number), nothing otherwise | ||
*/ | ||
static ensureIsObjectOrCollectionOrValue (arg, name = 'arg') { | ||
if (!Validator.isObjectOrCollectionOrValue(arg)) { | ||
return new TypeError(`The argument '${name}' must be an object or a collection or a value (string or boolean or number), instead got a '${typeof arg}'`) | ||
} | ||
} | ||
/** | ||
* Ensure that the given argument is a plain object or a collection or an array, | ||
* or a value (string or boolean or number). | ||
* | ||
* See {@link Validator.isObjectOrCollectionOrArrayOrValue}. | ||
* | ||
* @static | ||
* @param {?object} arg the object to check | ||
* @param {string} [name='arg'] the name to use in generated error (or the value of first argument if not given) | ||
* @return {TypeError} if it's not a plain object nor a collection nor a value (string or boolean or number), nothing otherwise | ||
*/ | ||
static ensureIsObjectOrCollectionOrArrayOrValue (arg, name = 'arg') { | ||
if (!Validator.isObjectOrCollectionOrArrayOrValue(arg)) { | ||
return new TypeError(`The argument '${name}' must be an object or a collection or an array or a value (string or boolean or number), instead got a '${typeof arg}'`) | ||
} | ||
} | ||
/** | ||
* Ensure that the given argument is a date. | ||
@@ -797,3 +959,3 @@ * | ||
if (!Validator.isURI(arg, base)) { | ||
return new Error(`The argument '${name}' must be an URI or URL string, and not '${arg}', '${base}'`) | ||
return new Error(`The argument '${name}' must be an URI or URL string and not ('${arg}', '${base}')`) | ||
} | ||
@@ -800,0 +962,0 @@ } |
162779
3
2984
301