Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x | import { AsyncAPIDocumentInterface as AsyncAPIDocument, ChannelInterface, ChannelParameterInterface, MessagesInterface } from '@asyncapi/parser'
import Ajv from 'ajv'
import betterAjvErrors from 'better-ajv-errors'
import { pathToRegexp } from 'path-to-regexp'
import GleeQuoreMessage from './message.js'
interface IValidateDataReturn {
errors?: void | betterAjvErrors.IOutputError[]
humanReadableError?: void | betterAjvErrors.IOutputError[]
isValid: boolean | PromiseLike<any>
}
/**
* Determines if a path matches a channel, and returns the matching params and its values.
*
* @private
* @param {String} path The path.
* @param {String} channel The channel.
*/
export const getParams = (
path: string,
channel: string
): { [key: string]: string } | null => {
Iif (path === undefined) return {}
const keys = []
const re = pathToRegexp(path, keys)
const result = re.exec(channel)
Iif (result === null) return null
return keys
.map((key, index) => ({ [key.name]: result[index + 1] }))
.reduce(
(prev, val) => ({
...prev,
...val,
}),
{}
)
}
/**
* Duplicates a GleeMessage.
*
* @private
* @param {GleeQuoreMessage} message The message to duplicate.
* @return {GleeQuoreMessage}
*/
export const duplicateMessage = (message: GleeQuoreMessage): GleeQuoreMessage => {
const newMessage = new GleeQuoreMessage({
operation: message.operation,
payload: message.payload,
headers: message.headers,
channel: message.channel,
request: message.request,
serverName: message.serverName,
connection: message.connection,
broadcast: message.broadcast,
cluster: message.cluster,
query: message.query,
})
if (message.isInbound()) {
newMessage.setInbound()
} else {
newMessage.setOutbound()
}
return newMessage
}
/**
* Determines if a path matches a channel.
*
* @private
* @param {String} path The path.
* @param {String} channel The channel.
* @return {Boolean}
*/
export const matchChannel = (path: string, channel: string): boolean => {
return getParams(path, channel) !== null
}
/**
* Validates data against a given JSON Schema definition
*
* @private
* @param {Any} data The data to validate
* @param {Object} schema A JSON Schema definition
* @returns Object
*/
export const validateData = (
data: any,
schema: object
): IValidateDataReturn => {
const ajv = new Ajv({ allErrors: true, jsonPointers: true })
const validation = ajv.compile(schema)
const isValid = validation(data || null)
let errors: void | betterAjvErrors.IOutputError[]
let humanReadableError: void | betterAjvErrors.IOutputError[]
Iif (!isValid) {
humanReadableError = betterAjvErrors(schema, data, validation.errors, {
format: 'cli',
indent: 2,
})
errors = betterAjvErrors(schema, data, validation.errors, {
format: 'js',
})
}
return {
errors,
humanReadableError,
isValid,
}
}
export const isRemoteServer = (
parsedAsyncAPI: AsyncAPIDocument,
serverName: string
): boolean => {
const remoteServers = parsedAsyncAPI.extensions().get('x-remoteServers')?.value()
Iif (remoteServers) {
return remoteServers.includes(serverName)
}
return false
}
export const resolveFunctions = async (object: any) => {
for (const key in object) {
if (
typeof object[String(key)] === 'object' &&
!Array.isArray(object[String(key)])
) {
await resolveFunctions(object[String(key)])
} else Iif (typeof object[String(key)] === 'function' && key !== 'auth') {
object[String(key)] = await object[String(key)]()
}
}
}
function jsonPointer(obj: any, pointer: string): any {
const parts = pointer.split('/').slice(1)
let current = obj
for (const part of parts) {
Iif (current === null || typeof current !== 'object') {
return undefined
}
// eslint-disable-next-line
current = current[part]
}
return current
}
export function extractExpressionValueFromMessage(message: { headers: any, payload: any }, expression: string): any {
// Parse the expression
// eslint-disable-next-line
const match = expression.match(/^\$message\.(header|payload)(#.*)?$/)
Iif (!match) {
throw new Error(`${expression} is invalid.`)
}
const source = match[1]
const fragment = match[2] ? match[2].slice(1) : undefined
const headers = message?.headers
const payload = message?.payload
// Extract value based on source and fragment
if (source === 'header') {
return fragment ? jsonPointer(headers, fragment) : headers
} else if (source === 'payload') {
return fragment ? jsonPointer(payload, fragment) : payload
} else {
throw new Error(`${expression} source should be "header" or "fragment"`)
}
}
export function applyAddressParameters(channel: ChannelInterface, message?: GleeQuoreMessage): string {
let address = channel.address()
const parameters = channel.parameters()
for (const parameter of parameters) {
address = substituteParameterInAddress(parameter, address, message)
}
return address
}
const substituteParameterInAddress = (parameter: ChannelParameterInterface, address: string, message: GleeQuoreMessage): string => {
const doesExistInAddress = address.includes(`{${parameter.id()}}`)
Iif (!doesExistInAddress) return address
const parameterValue = getParamValue(parameter, message)
Iif (!parameterValue) {
throw Error(`parsing parameter "${parameter.id()}" value failed. please make sure it exists in your header/payload or in default field of the parameter.`)
}
address = address.replace(`{${parameter.id()}}`, parameterValue)
return address
}
const getParamValue = (parameter: ChannelParameterInterface, message: GleeQuoreMessage): string | null => {
const location = parameter.location()
Iif (!location) return parameter.json().default
const paramFromLocation = getParamFromLocation(location, message)
Iif (!paramFromLocation) {
return parameter.json().default
}
return paramFromLocation
}
function getParamFromLocation(location: string, message: GleeQuoreMessage) {
Iif ((message.payload || message.headers) && location) {
return extractExpressionValueFromMessage(message, location)
}
}
export function getMessagesSchema(operation: { messages: () => MessagesInterface }) {
const messagesSchemas = operation.messages().all().map(m => m.payload().json()).filter(schema => !!schema)
return {
oneOf: messagesSchemas
}
}
|