From 7102185730f13a3ca488240c9abc19d6ab68d239 Mon Sep 17 00:00:00 2001 From: Jonas Lagoni Date: Tue, 28 Jul 2020 10:21:01 +0200 Subject: [PATCH] feat: Add types for typescript (#116) --- .github/workflows/release.yml | 2 + lib/asyncapiSchemaFormatParser.js | 8 + lib/customValidators.js | 15 +- lib/errors/parser-error.js | 2 + lib/models/asyncapi.js | 45 ++- lib/models/base.js | 1 + lib/models/channel-parameter.js | 1 + lib/models/channel.js | 1 + lib/models/components.js | 1 + lib/models/contact.js | 1 + lib/models/correlation-id.js | 1 + lib/models/external-docs.js | 1 + lib/models/info.js | 3 +- lib/models/license.js | 1 + lib/models/message-trait.js | 1 + lib/models/message-traitable.js | 1 + lib/models/message.js | 1 + lib/models/oauth-flow.js | 1 + lib/models/operation-trait.js | 1 + lib/models/operation-traitable.js | 1 + lib/models/operation.js | 1 + lib/models/publish-operation.js | 1 + lib/models/schema.js | 1 + lib/models/security-scheme.js | 1 + lib/models/server-security-requirement.js | 1 + lib/models/server-variable.js | 1 + lib/models/server.js | 1 + lib/models/subscribe-operation.js | 1 + lib/models/tag.js | 1 + lib/parser.js | 5 +- lib/utils.js | 6 + package-lock.json | 31 ++ package.json | 3 + types.d.ts | 458 ++++++++++++++++++++++ 34 files changed, 578 insertions(+), 23 deletions(-) create mode 100644 types.d.ts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8b73d7eec..287c627e6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -22,6 +22,8 @@ jobs: run: npm test - name: Regenerate docs run: npm run docs + - name: Regenerate types + run: npm run types - name: Generate bundle.js for the browser run: npm run prepublishOnly - name: Get version from package.json before release step diff --git a/lib/asyncapiSchemaFormatParser.js b/lib/asyncapiSchemaFormatParser.js index f12fae7de..248c27329 100644 --- a/lib/asyncapiSchemaFormatParser.js +++ b/lib/asyncapiSchemaFormatParser.js @@ -8,6 +8,9 @@ module.exports = { getMimeTypes }; +/** + * @private + */ async function parse({ message, originalAsyncAPIDocument, fileFormat, parsedAsyncAPIDocument, pathToPayload }) { const ajv = new Ajv({ jsonPointers: true, @@ -27,6 +30,9 @@ async function parse({ message, originalAsyncAPIDocument, fileFormat, parsedAsyn }); } +/** + * @private + */ function getMimeTypes() { return [ 'application/vnd.aai.asyncapi;version=2.0.0', @@ -42,6 +48,7 @@ function getMimeTypes() { * To validate schema of the payload we just need a small portion of official AsyncAPI spec JSON Schema, the definition of the schema must be * a main part of the JSON Schema * + * @private * @param {Object} asyncapiSchema AsyncAPI specification JSON Schema * @returns {Object} valid JSON Schema document describing format of AsyncAPI-valid schema for message payload */ @@ -56,6 +63,7 @@ function preparePayloadSchema(asyncapiSchema) { * Errors from Ajv contain dataPath information about parameter relative to parsed payload message. * This function enriches dataPath with additional information on where is the parameter located in AsyncAPI document * + * @private * @param {Array} errors Ajv errors * @param {String} path Path to location of the payload schema in AsyncAPI Document * @returns {Array} same object as received in input but with modified datePath property so it contain full path relative to AsyncAPI document diff --git a/lib/customValidators.js b/lib/customValidators.js index 47eb7ae60..4fe266410 100644 --- a/lib/customValidators.js +++ b/lib/customValidators.js @@ -4,7 +4,7 @@ const validationError = 'validation-errors'; /** * Validates if variables provided in the url have corresponding variable object defined - * + * @private * @param {Object} parsedJSON parsed AsyncAPI document * @param {String} asyncapiYAMLorJSON AsyncAPI document in string * @param {String} initialFormat information of the document was oryginally JSON or YAML @@ -46,6 +46,7 @@ function validateServerVariables(parsedJSON, asyncapiYAMLorJSON, initialFormat) /** * Validates if parameters specified in the channel have corresponding parameters object defined * + * @private * @param {Object} parsedJSON parsed AsyncAPI document * @param {String} asyncapiYAMLorJSON AsyncAPI document in string * @param {String} initialFormat information of the document was oryginally JSON or YAML @@ -88,6 +89,7 @@ function validateChannelParams(parsedJSON, asyncapiYAMLorJSON, initialFormat) { /** * Validates if operationIds are duplicated in the document * + * @private * @param {Object} parsedJSON parsed AsyncAPI document * @param {String} asyncapiYAMLorJSON AsyncAPI document in string * @param {String} initialFormat information of the document was oryginally JSON or YAML @@ -136,10 +138,11 @@ function validateOperationId(parsedJSON, asyncapiYAMLorJSON, initialFormat, oper /** * Validates if server security is declared properly and the name has a corresponding security schema definition in components with the same name * + * @private * @param {Object} parsedJSON parsed AsyncAPI document * @param {String} asyncapiYAMLorJSON AsyncAPI document in string * @param {String} initialFormat information of the document was oryginally JSON or YAML - * @param {Array[String]} specialSecTypes list of security types that can have data in array + * @param {String[]} specialSecTypes list of security types that can have data in array * @returns {Boolean} true in case the document is valid, otherwise throws ParserError */ function validateServerSecurity(parsedJSON, asyncapiYAMLorJSON, initialFormat, specialSecTypes) { @@ -196,7 +199,7 @@ function validateServerSecurity(parsedJSON, asyncapiYAMLorJSON, initialFormat, s * @private * @param {String} securityName name of the server security element that you want to localize in the security schema object * @param {Object} components components object from the AsyncAPI document - * @returns {Array[String]} there are 2 elements in array, index 0 is the name of the security schema object and index 1 is it's type + * @returns {String[]} there are 2 elements in array, index 0 is the name of the security schema object and index 1 is it's type */ function findSecuritySchema(securityName, components) { const secSchemes = components && components.securitySchemes; @@ -217,10 +220,10 @@ function findSecuritySchema(securityName, components) { * Validates if given server security is a proper empty array when security type requires it * @private * @param {String} schemaType security type, like httpApiKey or userPassword - * @param {Array[String]} specialSecTypes list of special types that do not have to be an empty array + * @param {String[]} specialSecTypes list of special types that do not have to be an empty array * @param {Object} secObj server security object * @param {String} secName name os server security object - * @returns {Array[String]} there are 2 elements in array, index 0 is the name of the security schema object and index 1 is it's type + * @returns {String[]} there are 2 elements in array, index 0 is the name of the security schema object and index 1 is it's type */ function isSrvrSecProperArray(schemaType, specialSecTypes, secObj, secName) { if (!specialSecTypes.includes(schemaType)) { @@ -237,4 +240,4 @@ module.exports = { validateServerVariables, validateOperationId, validateServerSecurity -}; \ No newline at end of file +}; diff --git a/lib/errors/parser-error.js b/lib/errors/parser-error.js index 8881d00bb..d8b96f67a 100644 --- a/lib/errors/parser-error.js +++ b/lib/errors/parser-error.js @@ -13,6 +13,8 @@ const buildError = (from, to) => { /** * Represents an error while trying to parse an AsyncAPI document. + * @alias module:@asyncapi/parser#ParserError + * @extends Error */ class ParserError extends Error { /** diff --git a/lib/models/asyncapi.js b/lib/models/asyncapi.js index e839b5010..ffcfaf79b 100644 --- a/lib/models/asyncapi.js +++ b/lib/models/asyncapi.js @@ -12,7 +12,8 @@ const xParserCircle = 'x-parser-circular'; /** * Implements functions to deal with the AsyncAPI document. - * @class + * @class + * @alias module:@asyncapi/parser#AsyncAPIDocument * @extends Base * @returns {AsyncAPIDocument} */ @@ -146,7 +147,7 @@ class AsyncAPIDocument extends Base { } /** - * @returns {Map} + * @returns {Map} */ allMessages() { const messages = new Map(); @@ -177,7 +178,7 @@ class AsyncAPIDocument extends Base { } /** - * @returns {Map} + * @returns {Map} */ allSchemas() { const schemas = new Map(); @@ -204,6 +205,12 @@ class AsyncAPIDocument extends Base { } } +/** + * Assign message keys as message name to all the component messages. + * + * @private + * @param {AsyncAPIDocument} doc + */ function assignNameToComponentMessages(doc) { if (doc.hasComponents()) { for (const [key, m] of Object.entries(doc.components().messages())) { @@ -217,6 +224,7 @@ function assignNameToComponentMessages(doc) { /** * Assign parameter keys as uid for the parameter schema. * + * @private * @param {AsyncAPIDocument} doc */ function assignUidToParameterSchemas(doc) { @@ -231,6 +239,7 @@ function assignUidToParameterSchemas(doc) { /** * Assign uid to component schemas. * + * @private * @param {AsyncAPIDocument} doc */ function assignUidToComponentSchemas(doc) { @@ -244,6 +253,7 @@ function assignUidToComponentSchemas(doc) { /** * Assign anonymous names to nameless messages. * + * @private * @param {AsyncAPIDocument} doc */ function assignNameToAnonymousMessages(doc) { @@ -261,7 +271,8 @@ function assignNameToAnonymousMessages(doc) { /** * Add anonymous name to key if no name provided. * - * @param {messages} map of messages + * @private + * @param {Message} map of messages */ function addNameToKey(messages, number) { messages.forEach(m => { @@ -273,7 +284,7 @@ function addNameToKey(messages, number) { /** * Function that indicates that a circular reference was detected. - * + * @private * @param {Schema} schema schema that is currently accessed and need to be checked if it is a first time * @param {Array} seenObjects list of objects that were already seen during recursion */ @@ -284,18 +295,25 @@ function isCircular(schema, seenObjects) { /** * Mark schema as being a circular ref * + * @private * @param {Schema} schema schema that should be marked as circular */ function markCircular(schema) { schema.json()[String(xParserCircle)] = true; } + +/** + * Callback that is called foreach schema found + * @private + * @callback FoundSchemaCallback + * @param {Schema} schema found. +*/ /** * Recursively go through each schema and execute callback. * - * @param {Schema} schemaContent schema. - * @param {Function} callback(schema) - * the function that is called foreach schema found. - * schema {Schema}: the found schema. + * @private + * @param {Schema} schema found. + * @param {FoundSchemaCallback} callback */ function recursiveSchema(schemaContent, callback) { if (schemaContent === null) return; @@ -307,6 +325,7 @@ function recursiveSchema(schemaContent, callback) { /** * Schema crawler * + * @private * @param {Schema} schemaContent schema. * @param {Array} seenObj schema elements that crowler went through already. * @param {Function} callback(schema) @@ -345,10 +364,9 @@ function crawl(schema, seenObj, callback) { /** * Go through each channel and for each parameter, and message payload and headers recursively call the callback for each schema. * + * @private * @param {AsyncAPIDocument} doc - * @param {Function} callback(schema) - * the function that is called foreach schema found. - * schema {Schema}: the found schema. + * @param {FoundSchemaCallback} callback */ function schemaDocument(doc, callback) { if (doc.hasChannels()) { @@ -378,6 +396,7 @@ function schemaDocument(doc, callback) { /** * Gives schemas id to all anonymous schemas. * + * @private * @param {AsyncAPIDocument} doc */ function assignIdToAnonymousSchemas(doc) { @@ -393,6 +412,7 @@ function assignIdToAnonymousSchemas(doc) { /** * Recursively go through schema of object type and execute callback. * + * @private * @param {Schema} schema Object type. * @param {Array} seenObj schema elements that crawler went through already. * @param {Function} callback(schema) @@ -415,6 +435,7 @@ function recursiveSchemaObject(schema, seenObj, callback) { /** * Recursively go through schema of array type and execute callback. * + * @private * @param {Schema} schema Array type. * @param {Array} seenObj schema elements that crowler went through already. * @param {Function} callback(schema) diff --git a/lib/models/base.js b/lib/models/base.js index cd0e0511f..c5bc5f819 100644 --- a/lib/models/base.js +++ b/lib/models/base.js @@ -3,6 +3,7 @@ const ParserError = require('../errors/parser-error'); /** * Implements common functionality for all the models. * @class + * @alias module:@asyncapi/parser#Base * @returns {Base} */ class Base { diff --git a/lib/models/channel-parameter.js b/lib/models/channel-parameter.js index f621181a3..105ce9e1c 100644 --- a/lib/models/channel-parameter.js +++ b/lib/models/channel-parameter.js @@ -5,6 +5,7 @@ const Schema = require('./schema'); /** * Implements functions to deal with a ChannelParameter object. * @class + * @alias module:@asyncapi/parser#ChannelParameter * @extends Base * @returns {ChannelParameter} */ diff --git a/lib/models/channel.js b/lib/models/channel.js index d0290e10b..f2db677f6 100644 --- a/lib/models/channel.js +++ b/lib/models/channel.js @@ -7,6 +7,7 @@ const SubscribeOperation = require('./subscribe-operation'); /** * Implements functions to deal with a Channel object. * @class + * @alias module:@asyncapi/parser#Channel * @extends Base * @returns {Channel} */ diff --git a/lib/models/components.js b/lib/models/components.js index 3839ea80e..63b983ac9 100644 --- a/lib/models/components.js +++ b/lib/models/components.js @@ -11,6 +11,7 @@ const MessageTrait = require('./message-trait'); /** * Implements functions to deal with a Components object. * @class + * @alias module:@asyncapi/parser#Components * @extends Base * @returns {Components} */ diff --git a/lib/models/contact.js b/lib/models/contact.js index 612277baf..c94de06d8 100644 --- a/lib/models/contact.js +++ b/lib/models/contact.js @@ -4,6 +4,7 @@ const Base = require('./base'); /** * Implements functions to deal with the Contact object. * @class + * @alias module:@asyncapi/parser#Contact * @extends Base * @returns {Contact} */ diff --git a/lib/models/correlation-id.js b/lib/models/correlation-id.js index 95b82c476..5fb0dd4f3 100644 --- a/lib/models/correlation-id.js +++ b/lib/models/correlation-id.js @@ -4,6 +4,7 @@ const Base = require('./base'); /** * Implements functions to deal with a CorrelationId object. * @class + * @alias module:@asyncapi/parser#CorrelationId * @extends Base * @returns {CorrelationId} */ diff --git a/lib/models/external-docs.js b/lib/models/external-docs.js index 79aa4838f..7f14ca152 100644 --- a/lib/models/external-docs.js +++ b/lib/models/external-docs.js @@ -4,6 +4,7 @@ const Base = require('./base'); /** * Implements functions to deal with an ExternalDocs object. * @class + * @alias module:@asyncapi/parser#ExternalDocs * @extends Base * @returns {ExternalDocs} */ diff --git a/lib/models/info.js b/lib/models/info.js index 64ffa88ec..ce83523b2 100644 --- a/lib/models/info.js +++ b/lib/models/info.js @@ -5,7 +5,8 @@ const Contact = require('./contact'); /** * Implements functions to deal with the Info object. - * @class Info + * @class + * @alias module:@asyncapi/parser#Info * @extends Base * @returns {Info} */ diff --git a/lib/models/license.js b/lib/models/license.js index 1519665d7..ce8ac140b 100644 --- a/lib/models/license.js +++ b/lib/models/license.js @@ -4,6 +4,7 @@ const Base = require('./base'); /** * Implements functions to deal with the License object. * @class + * @alias module:@asyncapi/parser#License * @extends Base * @returns {License} */ diff --git a/lib/models/message-trait.js b/lib/models/message-trait.js index ae73f8ffb..077e79a7c 100644 --- a/lib/models/message-trait.js +++ b/lib/models/message-trait.js @@ -4,6 +4,7 @@ const MessageTraitable = require('./message-traitable'); /** * Implements functions to deal with a MessageTrait object. * @class + * @alias module:@asyncapi/parser#MessageTrait * @extends Base * @returns {MessageTrait} */ diff --git a/lib/models/message-traitable.js b/lib/models/message-traitable.js index 692eb236c..b22cd011c 100644 --- a/lib/models/message-traitable.js +++ b/lib/models/message-traitable.js @@ -8,6 +8,7 @@ const CorrelationId = require('./correlation-id'); /** * Implements functions to deal with a the common properties that Message and MessageTrait objects have. * @class + * @alias module:@asyncapi/parser#MessageTraitable * @extends Base * @returns {MessageTraitable} */ diff --git a/lib/models/message.js b/lib/models/message.js index 58a0a6522..9f15c10bf 100644 --- a/lib/models/message.js +++ b/lib/models/message.js @@ -4,6 +4,7 @@ const Schema = require('./schema'); /** * Implements functions to deal with a Message object. * @class + * @alias module:@asyncapi/parser#Message * @extends MessageTraitable * @returns {Message} */ diff --git a/lib/models/oauth-flow.js b/lib/models/oauth-flow.js index 594276dad..caf00ea49 100644 --- a/lib/models/oauth-flow.js +++ b/lib/models/oauth-flow.js @@ -4,6 +4,7 @@ const Base = require('./base'); /** * Implements functions to deal with a OAuthFlow object. * @class + * @alias module:@asyncapi/parser#OAuthFlow * @extends Base * @returns {OAuthFlow} */ diff --git a/lib/models/operation-trait.js b/lib/models/operation-trait.js index 5a4e60adf..1bbc82375 100644 --- a/lib/models/operation-trait.js +++ b/lib/models/operation-trait.js @@ -3,6 +3,7 @@ const OperationTraitable = require('./operation-traitable'); /** * Implements functions to deal with a OperationTrait object. * @class + * @alias module:@asyncapi/parser#OperationTrait * @extends OperationTraitable * @returns {OperationTrait} */ diff --git a/lib/models/operation-traitable.js b/lib/models/operation-traitable.js index 1c8d4e08b..693e1eb8d 100644 --- a/lib/models/operation-traitable.js +++ b/lib/models/operation-traitable.js @@ -6,6 +6,7 @@ const ExternalDocs = require('./external-docs'); /** * Implements functions to deal with the common properties Operation and OperationTrait object have. * @class + * @alias module:@asyncapi/parser#OperationTraitable * @extends Base * @returns {OperationTraitable} */ diff --git a/lib/models/operation.js b/lib/models/operation.js index 84bce3aa1..d0366d1af 100644 --- a/lib/models/operation.js +++ b/lib/models/operation.js @@ -4,6 +4,7 @@ const Message = require('./message'); /** * Implements functions to deal with an Operation object. * @class + * @alias module:@asyncapi/parser#Operation * @extends OperationTraitable * @returns {Operation} */ diff --git a/lib/models/publish-operation.js b/lib/models/publish-operation.js index ff53bc1ff..739c924a8 100644 --- a/lib/models/publish-operation.js +++ b/lib/models/publish-operation.js @@ -3,6 +3,7 @@ const Operation = require('./operation'); /** * Implements functions to deal with a PublishOperation object. * @class + * @alias module:@asyncapi/parser#PublishOperation * @extends Operation * @returns {PublishOperation} */ diff --git a/lib/models/schema.js b/lib/models/schema.js index 9a4ef348b..6d6fc0bfa 100644 --- a/lib/models/schema.js +++ b/lib/models/schema.js @@ -5,6 +5,7 @@ const ExternalDocs = require('./external-docs'); /** * Implements functions to deal with a Schema object. * @class + * @alias module:@asyncapi/parser#Schema * @extends Base * @returns {Schema} */ diff --git a/lib/models/security-scheme.js b/lib/models/security-scheme.js index 1d77dd7c3..b4f4dcf3e 100644 --- a/lib/models/security-scheme.js +++ b/lib/models/security-scheme.js @@ -5,6 +5,7 @@ const OAuthFlow = require('./oauth-flow'); /** * Implements functions to deal with a SecurityScheme object. * @class + * @alias module:@asyncapi/parser#SecurityScheme * @extends Base * @returns {SecurityScheme} */ diff --git a/lib/models/server-security-requirement.js b/lib/models/server-security-requirement.js index 669d584f9..ad5a2be4f 100644 --- a/lib/models/server-security-requirement.js +++ b/lib/models/server-security-requirement.js @@ -3,6 +3,7 @@ const Base = require('./base'); /** * Implements functions to deal with a ServerSecurityRequirement object. * @class + * @alias module:@asyncapi/parser#ServerSecurityRequirement * @extends Base * @returns {ServerSecurityRequirement} */ diff --git a/lib/models/server-variable.js b/lib/models/server-variable.js index ea8467dd4..8e6655b94 100644 --- a/lib/models/server-variable.js +++ b/lib/models/server-variable.js @@ -4,6 +4,7 @@ const Base = require('./base'); /** * Implements functions to deal with a ServerVariable object. * @class + * @alias module:@asyncapi/parser#ServerVariable * @extends Base * @returns {ServerVariable} */ diff --git a/lib/models/server.js b/lib/models/server.js index 47fe4b3d0..80387bc11 100644 --- a/lib/models/server.js +++ b/lib/models/server.js @@ -6,6 +6,7 @@ const ServerSecurityRequirement = require('./server-security-requirement'); /** * Implements functions to deal with a Server object. * @class + * @alias module:@asyncapi/parser#Server * @extends Base * @returns {Server} */ diff --git a/lib/models/subscribe-operation.js b/lib/models/subscribe-operation.js index 531c2662f..a265bab89 100644 --- a/lib/models/subscribe-operation.js +++ b/lib/models/subscribe-operation.js @@ -3,6 +3,7 @@ const Operation = require('./operation'); /** * Implements functions to deal with a SubscribeOperation object. * @class + * @alias module:@asyncapi/parser#SubscribeOperation * @extends Operation * @returns {SubscribeOperation} */ diff --git a/lib/models/tag.js b/lib/models/tag.js index 6443a4be6..37a7f84ed 100644 --- a/lib/models/tag.js +++ b/lib/models/tag.js @@ -5,6 +5,7 @@ const ExternalDocs = require('./external-docs'); /** * Implements functions to deal with a Tag object. * @class + * @alias module:@asyncapi/parser#Tag * @extends Base * @returns {Tag} */ diff --git a/lib/parser.js b/lib/parser.js index 394b0f938..48ced5656 100644 --- a/lib/parser.js +++ b/lib/parser.js @@ -18,7 +18,7 @@ const xParserCircle = 'x-parser-circular'; const refParser = new $RefParser; /** - * @module Parser + * @module @asyncapi/parser */ module.exports = { parse, @@ -31,7 +31,6 @@ module.exports = { /** * Parses and validate an AsyncAPI document from YAML or JSON. * - * @name module:Parser#parse * @param {String} asyncapiYAMLorJSON An AsyncAPI document in JSON or YAML format. * @param {Object} [options] Configuration options. * @param {String} [options.path] Path to the AsyncAPI document. It will be used to resolve relative references. Defaults to current working dir. @@ -117,7 +116,6 @@ async function parse(asyncapiYAMLorJSON, options = {}) { /** * Fetches an AsyncAPI document from the given URL and passes its content to the `parse` method. * - * @name module:Parser#parseFromUrl * @param {String} url URL where the AsyncAPI document is located. * @param {Object} [fetchOptions] Configuration to pass to the {@link https://developer.mozilla.org/en-US/docs/Web/API/Request|fetch} call. * @param {Object} [options] Configuration to pass to the {@link module:Parser#parse} method. @@ -208,7 +206,6 @@ async function validateAndConvertMessage(msg, originalAsyncAPIDocument, fileForm /** * Registers a new schema parser. Schema parsers are in charge of parsing and transforming payloads to AsyncAPI Schema format. * - * @name module:Parser#registerSchemaParser * @param {string[]} schemaFormats An array of schema formats the given schema parser is able to recognize and transform. * @param {Object} parserModule The schema parser module containing parse() and getMimeTypes() functions. */ diff --git a/lib/utils.js b/lib/utils.js index 591ee03aa..8b9817cd1 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -260,6 +260,8 @@ utils.improveAjvErrors = (errors, asyncapiYAMLorJSON, initialFormat) => { /** * It parses the string and returns an array with all values that are between curly braces, including braces + * @function parseUrlVariables + * @private */ utils.parseUrlVariables = str => { if (typeof str !== 'string') return; @@ -269,6 +271,8 @@ utils.parseUrlVariables = str => { /** * Returns an array of not existing properties in provided object with names specified in provided array + * @function getMissingProps + * @private */ utils.getMissingProps = (arr, obj) => { arr = arr.map(val => val.replace(/[{}]/g, '')); @@ -283,6 +287,8 @@ utils.getMissingProps = (arr, obj) => { /** * Returns array of errors messages compatible with validationErrors parameter from ParserError * + * @function groupValidationErrors + * @private * @param {String} root name of the root element in the AsyncAPI document, for example channels * @param {String} errorMessage the text of the custom error message that will follow the path that points the error * @param {Map} errorElements map of error elements cause the validation error might happen in many places in the document. diff --git a/package-lock.json b/package-lock.json index 1a49d647a..9fdd21e34 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3698,6 +3698,12 @@ "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", "dev": true }, + "in-publish": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/in-publish/-/in-publish-2.0.1.tgz", + "integrity": "sha512-oDM0kUSNFC31ShNxHKUyfZKy8ZeXZBWMjMdZHKLOk13uvT27VTL/QzRGfRUcevJhpkZAvlhPYuXkF7eNWrtyxQ==", + "dev": true + }, "indent-string": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-3.2.0.tgz", @@ -4215,6 +4221,16 @@ } } }, + "jsdoc-export-default-interop": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/jsdoc-export-default-interop/-/jsdoc-export-default-interop-0.3.1.tgz", + "integrity": "sha1-Ri+p+bSiqwag9NBiQUPQLlui0F8=", + "dev": true, + "requires": { + "in-publish": "^2.0.0", + "lodash": "^4.0.1" + } + }, "jsdoc-parse": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/jsdoc-parse/-/jsdoc-parse-4.0.1.tgz", @@ -10759,6 +10775,15 @@ "integrity": "sha1-n5up2e+odkw4dpi8v+sshI8RrbM=", "dev": true }, + "tsd-jsdoc": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tsd-jsdoc/-/tsd-jsdoc-2.5.0.tgz", + "integrity": "sha512-80fcJLAiUeerg4xPftp+iEEKWUjJjHk9AvcHwJqA8Zw0R4oASdu3kT/plE/Zj19QUTz8KupyOX25zStlNJjS9g==", + "dev": true, + "requires": { + "typescript": "^3.2.1" + } + }, "tty-browserify": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.1.tgz", @@ -10801,6 +10826,12 @@ "is-typedarray": "^1.0.0" } }, + "typescript": { + "version": "3.9.6", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.6.tgz", + "integrity": "sha512-Pspx3oKAPJtjNwE92YS05HQoY7z2SFyOpHo9MqJor3BXAGNaPUs83CuVp9VISFkSjyRfiTpmKuAYGJB7S7hOxw==", + "dev": true + }, "typical": { "version": "2.6.1", "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", diff --git a/package.json b/package.json index 4792d355f..02779c4f3 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,7 @@ "version": "0.27.1", "description": "JavaScript AsyncAPI parser.", "main": "lib/index.js", + "types": "types.d.ts", "directories": { "test": "test" }, @@ -10,6 +11,7 @@ "test": "nyc --reporter=html --reporter=text mocha --recursive", "bundle": "browserify lib/browser.js | uglifyjs > dist/bundle.js", "docs": "jsdoc2md lib/parser.js -f lib/**/*.js > API.md", + "types": "jsdoc -t node_modules/tsd-jsdoc/dist -r lib -d ./", "prepublishOnly": "npm run bundle", "release": "semantic-release", "get-version": "echo $npm_package_version", @@ -46,6 +48,7 @@ "mocha": "^6.1.4", "nyc": "^15.1.0", "semantic-release": "^17.0.4", + "tsd-jsdoc": "^2.5.0", "uglify-es": "^3.3.9" }, "dependencies": { diff --git a/types.d.ts b/types.d.ts new file mode 100644 index 000000000..4f4d50b54 --- /dev/null +++ b/types.d.ts @@ -0,0 +1,458 @@ +declare module "@asyncapi/parser" { + /** + * Instantiates an error + * @param definition.type - The type of the error. + * @param definition.title - The message of the error. + * @param [definition.detail] - A string containing more detailed information about the error. + * @param [definition.parsedJSON] - The resulting JSON after YAML transformation. Or the JSON object if the this was the initial format. + * @param [definition.validationErrors] - The errors resulting from the validation. For more information, see https://www.npmjs.com/package/better-ajv-errors. + * @param definition.validationErrors.title - A validation error message. + * @param definition.validationErrors.jsonPointer - The path to the field that contains the error. Uses JSON Pointer format. + * @param definition.validationErrors.startLine - The line where the error starts in the AsyncAPI document. + * @param definition.validationErrors.startColumn - The column where the error starts in the AsyncAPI document. + * @param definition.validationErrors.startOffset - The offset (starting from the beginning of the document) where the error starts in the AsyncAPI document. + * @param definition.validationErrors.endLine - The line where the error ends in the AsyncAPI document. + * @param definition.validationErrors.endColumn - The column where the error ends in the AsyncAPI document. + * @param definition.validationErrors.endOffset - The offset (starting from the beginning of the document) where the error ends in the AsyncAPI document. + * @param [definition.location] - Error location details after trying to parse an invalid JSON or YAML document. + * @param definition.location.startLine - The line of the YAML/JSON document where the error starts. + * @param definition.location.startColumn - The column of the YAML/JSON document where the error starts. + * @param definition.location.startOffset - The offset (starting from the beginning of the document) where the error starts in the YAML/JSON AsyncAPI document. + * @param [definition.refs] - Error details after trying to resolve $ref's. + * @param definition.refs.title - A validation error message. + * @param definition.refs.jsonPointer - The path to the field that contains the error. Uses JSON Pointer format. + * @param definition.refs.startLine - The line where the error starts in the AsyncAPI document. + * @param definition.refs.startColumn - The column where the error starts in the AsyncAPI document. + * @param definition.refs.startOffset - The offset (starting from the beginning of the document) where the error starts in the AsyncAPI document. + * @param definition.refs.endLine - The line where the error ends in the AsyncAPI document. + * @param definition.refs.endColumn - The column where the error ends in the AsyncAPI document. + * @param definition.refs.endOffset - The offset (starting from the beginning of the document) where the error ends in the AsyncAPI document. + */ + class ParserError extends Error { + constructor(definition: { + type: string; + title: string; + detail?: string; + parsedJSON?: any; + validationErrors?: { + title: string; + jsonPointer: string; + startLine: number; + startColumn: number; + startOffset: number; + endLine: number; + endColumn: number; + endOffset: number; + }[]; + location?: { + startLine: number; + startColumn: number; + startOffset: number; + }; + refs?: { + title: string; + jsonPointer: string; + startLine: number; + startColumn: number; + startOffset: number; + endLine: number; + endColumn: number; + endOffset: number; + }[]; + }); + /** + * Returns a JS object representation of the error. + */ + toJS(): void; + } + class AsyncAPIDocument extends Base { + version(): string; + info(): Info; + id(): string; + hasServers(): boolean; + servers(): { + [key: string]: Server; + }; + /** + * @param name - Name of the server. + */ + server(name: string): Server; + hasChannels(): boolean; + channels(): { + [key: string]: Channel; + }; + channelNames(): string[]; + /** + * @param name - Name of the channel. + */ + channel(name: string): Channel; + defaultContentType(): string; + hasComponents(): boolean; + components(): Components; + hasTags(): boolean; + tags(): Tag[]; + hasMessages(): boolean; + allMessages(): Map; + allSchemas(): Map; + hasCircular(): boolean; + } + class Base { + json(): any; + } + /** + * Implements functions to deal with a ChannelParameter object. + */ + class ChannelParameter extends Base { + description(): string; + location(): string; + schema(): Schema; + } + /** + * Implements functions to deal with a Channel object. + */ + class Channel extends Base { + description(): string; + parameters(): { + [key: string]: ChannelParameter; + }; + /** + * @param name - Name of the parameter. + */ + parameter(name: string): ChannelParameter; + hasParameters(): boolean; + publish(): PublishOperation; + subscribe(): SubscribeOperation; + hasPublish(): boolean; + hasSubscribe(): boolean; + bindings(): any; + /** + * @param name - Name of the binding. + */ + binding(name: string): any; + } + /** + * Implements functions to deal with a Components object. + */ + class Components extends Base { + messages(): { + [key: string]: Message; + }; + message(): Message; + schemas(): { + [key: string]: Schema; + }; + schema(): Schema; + securitySchemes(): { + [key: string]: SecurityScheme; + }; + securityScheme(): SecurityScheme; + parameters(): { + [key: string]: ChannelParameter; + }; + parameter(): ChannelParameter; + correlationIds(): { + [key: string]: CorrelationId; + }; + correlationId(): CorrelationId; + operationTraits(): { + [key: string]: OperationTrait; + }; + operationTrait(): OperationTrait; + messageTraits(): { + [key: string]: MessageTrait; + }; + messageTrait(): MessageTrait; + } + /** + * Implements functions to deal with the Contact object. + */ + class Contact extends Base { + name(): string; + url(): string; + email(): string; + } + /** + * Implements functions to deal with a CorrelationId object. + */ + class CorrelationId extends Base { + description(): string; + location(): string; + } + /** + * Implements functions to deal with an ExternalDocs object. + */ + class ExternalDocs extends Base { + description(): string; + url(): string; + } + /** + * Implements functions to deal with the Info object. + */ + class Info extends Base { + title(): string; + version(): string; + license(): License; + contact(): Contact; + } + /** + * Implements functions to deal with the License object. + */ + class License extends Base { + name(): string; + url(): string; + } + /** + * Implements functions to deal with a MessageTrait object. + */ + class MessageTrait extends Base { + } + /** + * Implements functions to deal with a the common properties that Message and MessageTrait objects have. + */ + class MessageTraitable extends Base { + headers(): Schema; + /** + * @param name - Name of the header. + */ + header(name: string): Schema; + correlationId(): CorrelationId; + schemaFormat(): string; + contentType(): string; + name(): string; + title(): string; + summary(): string; + description(): string; + externalDocs(): ExternalDocs; + hasTags(): boolean; + tags(): Tag[]; + bindings(): any; + /** + * @param name - Name of the binding. + */ + binding(name: string): any; + examples(): any[]; + } + /** + * Implements functions to deal with a Message object. + */ + class Message extends MessageTraitable { + uid(): string; + payload(): Schema; + originalPayload(): any; + originalSchemaFormat(): string; + } + /** + * Implements functions to deal with a OAuthFlow object. + */ + class OAuthFlow extends Base { + authorizationUrl(): string; + tokenUrl(): string; + refreshUrl(): string; + scopes(): { + [key: string]: string; + }; + } + /** + * Implements functions to deal with a OperationTrait object. + */ + class OperationTrait extends OperationTraitable { + } + /** + * Implements functions to deal with the common properties Operation and OperationTrait object have. + */ + class OperationTraitable extends Base { + id(): string; + summary(): string; + description(): string; + hasTags(): boolean; + tags(): Tag[]; + externalDocs(): ExternalDocs; + bindings(): any; + /** + * @param name - Name of the binding. + */ + binding(name: string): any; + } + /** + * Implements functions to deal with an Operation object. + */ + class Operation extends OperationTraitable { + hasMultipleMessages(): boolean; + messages(): Message[]; + message(): Message; + } + /** + * Implements functions to deal with a PublishOperation object. + */ + class PublishOperation extends Operation { + isPublish(): boolean; + isSubscribe(): boolean; + kind(): string; + } + /** + * Implements functions to deal with a Schema object. + */ + class Schema extends Base { + uid(): string; + $id(): string; + multipleOf(): number; + maximum(): number; + exclusiveMaximum(): number; + minimum(): number; + exclusiveMinimum(): number; + maxLength(): number; + minLength(): number; + pattern(): string; + maxItems(): number; + minItems(): number; + uniqueItems(): boolean; + maxProperties(): number; + minProperties(): number; + required(): string[]; + enum(): any[]; + type(): string | string[]; + allOf(): Schema[]; + oneOf(): Schema[]; + anyOf(): Schema[]; + not(): Schema; + items(): Schema | Schema[]; + properties(): { + [key: string]: Schema; + }; + additionalProperties(): boolean | Schema; + additionalItems(): Schema; + patternProperties(): { + [key: string]: Schema; + }; + const(): any; + contains(): Schema; + dependencies(): { + [key: string]: Schema | string[]; + }; + propertyNames(): Schema; + if(): Schema; + then(): Schema; + else(): Schema; + format(): string; + contentEncoding(): string; + contentMediaType(): string; + definitions(): { + [key: string]: Schema; + }; + description(): string; + title(): string; + default(): any; + deprecated(): boolean; + discriminator(): string; + externalDocs(): ExternalDocs; + readOnly(): boolean; + writeOnly(): boolean; + examples(): any[]; + isCircular(): boolean; + } + /** + * Implements functions to deal with a SecurityScheme object. + */ + class SecurityScheme extends Base { + type(): string; + description(): string; + name(): string; + in(): string; + scheme(): string; + bearerFormat(): string; + openIdConnectUrl(): string; + flows(): { + [key: string]: OAuthFlow; + }; + } + /** + * Implements functions to deal with a ServerSecurityRequirement object. + */ + class ServerSecurityRequirement extends Base { + } + /** + * Implements functions to deal with a ServerVariable object. + */ + class ServerVariable extends Base { + allowedValues(): any[]; + /** + * @param name - Name of the variable. + */ + allows(name: string): boolean; + hasAllowedValues(): boolean; + defaultValue(): string; + hasDefaultValue(): boolean; + description(): string; + examples(): string[]; + } + /** + * Implements functions to deal with a Server object. + */ + class Server extends Base { + description(): string; + url(): string; + protocol(): string; + protocolVersion(): string; + variables(): { + [key: string]: ServerVariable; + }; + /** + * @param name - Name of the server variable. + */ + variable(name: string): ServerVariable; + hasVariables(): boolean; + security(): ServerSecurityRequirement[]; + bindings(): any; + /** + * @param name - Name of the binding. + */ + binding(name: string): any; + } + /** + * Implements functions to deal with a SubscribeOperation object. + */ + class SubscribeOperation extends Operation { + isPublish(): boolean; + isSubscribe(): boolean; + kind(): string; + } + /** + * Implements functions to deal with a Tag object. + */ + class Tag extends Base { + name(): string; + description(): string; + externalDocs(): ExternalDocs; + } + /** + * Parses and validate an AsyncAPI document from YAML or JSON. + * @param asyncapiYAMLorJSON - An AsyncAPI document in JSON or YAML format. + * @param [options] - Configuration options. + * @param [options.path] - Path to the AsyncAPI document. It will be used to resolve relative references. Defaults to current working dir. + * @param [options.parse] - Options object to pass to {@link https://apidevtools.org/json-schema-ref-parser/docs/options.html|json-schema-ref-parser}. + * @param [options.resolve] - Options object to pass to {@link https://apidevtools.org/json-schema-ref-parser/docs/options.html|json-schema-ref-parser}. + * @param [options.applyTraits = true] - Whether to resolve and apply traits or not. + * @returns The parsed AsyncAPI document. + */ + function parse(asyncapiYAMLorJSON: string, options?: { + path?: string; + parse?: any; + resolve?: any; + applyTraits?: any; + }): Promise; + /** + * Fetches an AsyncAPI document from the given URL and passes its content to the `parse` method. + * @param url - URL where the AsyncAPI document is located. + * @param [fetchOptions] - Configuration to pass to the {@link https://developer.mozilla.org/en-US/docs/Web/API/Request|fetch} call. + * @param [options] - Configuration to pass to the {@link module:Parser#parse} method. + * @returns The parsed AsyncAPI document. + */ + function parseFromUrl(url: string, fetchOptions?: any, options?: any): Promise; + /** + * Registers a new schema parser. Schema parsers are in charge of parsing and transforming payloads to AsyncAPI Schema format. + * @param schemaFormats - An array of schema formats the given schema parser is able to recognize and transform. + * @param parserModule - The schema parser module containing parse() and getMimeTypes() functions. + */ + function registerSchemaParser(schemaFormats: string[], parserModule: any): void; +} +