All files json-rpc-parse.js

96.3% Statements 104/108
90.27% Branches 102/113
100% Functions 19/19
96.3% Lines 104/108

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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 4871x   1x 1x                               1x                                                         1x                             1x                   62x 62x 62x 62x 62x             1x 1x                         900x 116x                             145x 127x 8x     119x       121x         121x 109x     121x                               112x 80x 72x 42x   68x 40x           40x 16x 14x       40x 40x 12x     40x                               68x 64x                             48x                           106x 105x                       101x 24x   101x       93x 93x   89x 25x 124x   25x     89x 89x 10x     89x                         37x                         31x                       27x                       21x                           20x 18x 17x                         101x                         79x 3x 3x     2x               77x 3x 1x   2x       5x 5x     1x 1x     5x         74x   73x 1x 1x     72x 32x 20x 9x           23x 12x         11x 3x                       8x                       40x 1x     39x       7x   32x 2x                 30x 7x   23x 12x   11x 9x   2x                       1x     17x     1x                            
((factory) => {
    // Define as CommonJS export:
    Eif (typeof require === 'function' && typeof exports === 'object') {
        module.exports = factory(); // eslint-disable-line
    }
    // Define as AMD:
    else if (typeof define === 'function' && define.amd) { // eslint-disable-line no-undef
        define([], factory); // eslint-disable-line no-undef
    }
    // Browser:
    else {
        window.JsonRPC = factory(); // eslint-disable-line no-undef
    }
})(() => {
    /**
     * List of errors
     *
     * @type {object}
     */
    const ERRORS = {
        // codes from -32000 to -32099 reserved for implementation-defined server-errors.
        INVALID_REQUEST: {
            code: -32600,
            message: 'Invalid Request'
        },
        METHOD_NOT_FOUND: {
            code: -32601,
            message: 'Method not found'
        },
        INVALID_PARAMS: {
            code: -32602,
            message: 'Invalid params'
        },
        INTERNAL_ERROR: {
            code: -32603,
            message: 'Internal error'
        },
        PARSE_ERROR: {
            code: -32700,
            message: 'Parse error'
        }
    };
 
    /**
     * List of supported message types
     *
     * @type {object}
     */
    const MESSAGE_TYPES = {
        REQUEST: 'request',
        INTERNAL_REQUEST: 'internal_request',
        NOTIFICATION: 'notification',
        INTERNAL_NOTIFICATION: 'internal_notification',
        RESPONSE: 'response',
        ERROR: 'error',
        BATCH: 'batch'
    };
 
    /**
     * Contains prefix of name of all messages for internal usage
     *
     * @type {string}
     */
    const INTERNAL_MESSAGE_PREFIX = 'rpc.';
 
    /**
     * Constructor of error object, that should be thrown from "parse" method
     *
     * @param {object} error
     *
     * @constructor
     */
    function ParserError(error) {
        this.name = 'ParserError';
        this.message = 'Failed to parse JSON-RPC message';
        this.rpcError = error;
        Eif (Error.captureStackTrace) {
            Error.captureStackTrace(this, ParserError);
        }
        else {
            this.stack = (new Error()).stack;
        }
    }
 
    ParserError.prototype = Object.create(Error.prototype);
    ParserError.prototype.constructor = ParserError;
 
    /**
     * Utility function for assertion
     *
     * @param {boolean} condition
     * @param {string} errorText
     *
     * @returns {void}
     *
     * @throws Error if condition is falsy
     */
    function assert(condition, errorText) {
        if (!condition) {
            throw new Error(errorText);
        }
    }
 
    /**
     * Utility function to create basic JSON-RPC message
     *
     * @param {number|string|undefined} id?
     * @param {object} messageData?
     *
     * @returns {object}
     *
     * @private
     */
    function _createMessage(id, messageData = null) {
        if (id !== undefined && id !== null) {
            if (typeof id === 'string') {
                assert(id.length > 0, 'ID of message is not defined');
            }
            else {
                assert(Number.isInteger(id), `ID should be a string or an integer number, "${typeof id}" given`);
            }
        }
 
        const message = {
            jsonrpc: '2.0',
            ...messageData
        };
 
        if (id !== undefined) {
            message.id = id;
        }
 
        return message;
    }
 
    /**
     * Create a JSON-RPC request object ( https://www.jsonrpc.org/specification#request_object )
     *
     * @param {number|string|undefined} id
     * @param {string} method
     * @param {object|array|undefined} params
     * @param {boolean} isInternal
     *
     * @returns {object}
     *
     * @private
     */
    function _createRequestObject(id, method, params, isInternal) {
        assert(typeof method === 'string', 'Method should be a string');
        assert(method.trim().length > 0, 'Method name should not be empty');
        if (!isInternal) {
            assert(method.indexOf(INTERNAL_MESSAGE_PREFIX) !== 0, `Invalid method name "${method}": only internal methods can be prefixed with "${INTERNAL_MESSAGE_PREFIX}"`);
        }
        if (params !== undefined && params !== null) {
            assert(
                Array.isArray(params) || typeof params === 'object',
                `Request parameters must be a structured value (an array or an object), "${typeof params}" given`
            );
        }
 
        if (isInternal) {
            if (method.indexOf(INTERNAL_MESSAGE_PREFIX) !== 0) {
                method = `${INTERNAL_MESSAGE_PREFIX}${method}`;
            }
        }
 
        let messageData = {method};
        if (params) {
            messageData.params = params;
        }
 
        return _createMessage(id, messageData);
    }
 
    /**
     * Utility function to create JSON-RPC request
     *
     * @param {number|string} id
     * @param {string} method
     * @param {object|array|undefined} params
     * @param {boolean} isInternal
     *
     * @returns {object}
     *
     * @private
     */
    function _createRequest(id, method, params, isInternal) {
        assert(id !== undefined && id !== null, 'ID of request is not defined');
        return _createRequestObject(id, method, params, isInternal);
    }
 
    /**
     * Utility function to create JSON-RPC notification
     *
     * @param {string} method
     * @param {object|array|undefined} params
     * @param {boolean} isInternal
     *
     * @returns {object}
     *
     * @private
     */
    function _createNotification(method, params, isInternal) {
        return _createRequestObject(undefined, method, params, isInternal);
    }
 
    /**
     * Utility function to create JSON-RPC response
     *
     * @param {number|string} id
     * @param {object} responseData
     *
     * @returns {object}
     *
     * @private
     */
    function _createResponse(id, responseData) {
        assert(id !== undefined, 'ID of response is not defined');
        return _createMessage(id, responseData);
    }
 
    /**
     * Creates a response error object ( https://www.jsonrpc.org/specification#error_object )
     *
     * @param {Number|{code: int, message: string?}} errorData - error code
     * @param {*} additionalData? - error details
     *
     * @return {Object}
     */
    function _createErrorObject(errorData, additionalData) {
        if (Number.isInteger(errorData)) {
            errorData = {code: errorData};
        }
        assert(
            typeof errorData === 'object' && errorData !== null && !Array.isArray(errorData),
            'Error code should be an integer number or object with "code" and "message" property'
        );
        assert(errorData.message === undefined || typeof errorData.message === 'string', 'Error message should be a string');
        assert(Number.isInteger(errorData.code), 'Error code should be an integer value');
 
        if (!errorData.message) {
            let errorInRegistry = Object.values(ERRORS).find(
                error => error.code === errorData.code
            );
            errorData.message = errorInRegistry ? errorInRegistry.message : 'Internal Server Error';
        }
 
        const errorObj = {...errorData};
        if (additionalData !== null && additionalData !== undefined) {
            errorObj.data = additionalData;
        }
 
        return errorObj;
    }
 
    /**
     * Creates new JSON-RPC request
     *
     * @param {number|string} id
     * @param {string} method
     * @param {object|array|undefined} params
     *
     * @returns {object}
     */
    function createRequest(id, method, params) {
        return _createRequest(id, method, params, false);
    }
 
    /**
     * Creates new internal JSON-RPC request
     *
     * @param {number|string} id
     * @param {string} method
     * @param {object|array|undefined} params
     *
     * @returns {object}
     */
    function createInternalRequest(id, method, params) {
        return _createRequest(id, method, params, true);
    }
 
    /**
     * Creates new JSON-RPC notification
     *
     * @param {string} method
     * @param {object|array|undefined} params
     *
     * @returns {object}
     */
    function createNotification(method, params) {
        return _createNotification(method, params, false);
    }
 
    /**
     * Creates new internal JSON-RPC notification
     *
     * @param {string} method
     * @param {object|array|undefined} params
     *
     * @returns {object}
     */
    function createInternalNotification(method, params) {
        return _createNotification(method, params, true);
    }
 
    /**
     * Creates JSON-RPC response
     *
     * @param {number|string} id
     * @param {*} result
     *
     * @returns {object}
     *
     * @private
     */
    function createResponse(id, result) {
        assert(id !== undefined && id !== null, 'Response ID is not defined');
        assert(result !== undefined, 'Response result is not defined');
        return _createResponse(id, {result});
    }
 
    /**
     * Creates JSON-RPC response with error
     *
     * @param {number|string} id
     * @param {number|{code: number, message: string?}} errorCode
     * @param {object} details?
     *
     * @returns {object}
     */
    function createError(id, errorCode, details) {
        return _createResponse(id, {error: _createErrorObject(errorCode, details)});
    }
 
    /**
     * Parses passed message
     *
     * @param {string|object|array} message - JSON string or object or array or requests (batch)
     *
     * @returns {Array|object}
     */
    function parseMessage(message) {
        let result;
        // Prase JSON string into object:
        if (typeof message === 'string') {
            try {
                message = JSON.parse(message);
            }
            catch (e) {
                throw new ParserError(createError(null, ERRORS.PARSE_ERROR));
            }
        }
 
 
        // If message is an array then it's a batch, so we need to parse every request in this
        // batch separately
        // (unless we already parsing a batch - in that case parse error should be returned):
        if (Array.isArray(message)) {
            if (message.length === 0) {
                throw new ParserError(createError(null, ERRORS.INVALID_REQUEST));
            }
            result = {
                type: MESSAGE_TYPES.BATCH,
                payload: message.map((request) => {
                    let msg;
                    try {
                        msg = parseMessage(request, false);
                    }
                    catch (e) {
                        Eif (e instanceof ParserError) {
                            msg = e;
                        }
                    }
                    return msg;
                })
            };
        }
        // If message is normal js object, so we need to validate it and determine it's type:
        else if (typeof message === 'object') {
            // The only supported version is JSON-RPC 2.0:
            if (message.jsonrpc !== '2.0') {
                let id = message.id || null;
                throw new ParserError(createError(id, ERRORS.INTERNAL_ERROR));
            }
 
            if (message.hasOwnProperty('method')) {
                if (message.hasOwnProperty('params')) {
                    if (typeof message.params !== 'object' || message.params === null) {
                        throw new ParserError(
                            createError(message.id || null, ERRORS.INVALID_REQUEST)
                        );
                    }
                }
 
                if (typeof message.method !== 'string' || message.method.trim().length === 0) {
                    throw new ParserError(
                        createError(message.id || null, ERRORS.INVALID_REQUEST)
                    );
                }
 
                if (message.id) {
                    result = {
                        type: message.method.indexOf(INTERNAL_MESSAGE_PREFIX) === 0
                            ? MESSAGE_TYPES.INTERNAL_REQUEST
                            : MESSAGE_TYPES.REQUEST,
                        payload: {
                            id: message.id,
                            method: message.method,
                            params: message.params
                        }
                    };
                }
                else {
                    result = {
                        type: message.method.indexOf(INTERNAL_MESSAGE_PREFIX) === 0
                            ? MESSAGE_TYPES.INTERNAL_NOTIFICATION
                            : MESSAGE_TYPES.NOTIFICATION,
                        payload: {
                            method: message.method,
                            params: message.params
                        }
                    };
                }
            }
            else {
                if (!message.id) {
                    throw new ParserError(createError(null, ERRORS.INVALID_REQUEST));
                }
 
                if (
                    (message.result && message.error) ||
                    (!message.result && !message.error)
                ) {
                    throw new ParserError(createError(message.id, ERRORS.INVALID_REQUEST));
                }
                else if (message.result) {
                    result = {
                        type: MESSAGE_TYPES.RESPONSE,
                        payload: {
                            id: message.id,
                            result: message.result
                        }
                    };
                }
                else {
                    if (typeof message.error !== 'object' || message.error === null || Array.isArray(message.error)) {
                        throw new ParserError(createError(message.id, ERRORS.INVALID_REQUEST));
                    }
                    if (!message.error.hasOwnProperty('code') || !Number.isInteger(message.error.code)) {
                        throw new ParserError(createError(message.id, ERRORS.INVALID_REQUEST));
                    }
                    if (!message.error.hasOwnProperty('message') || typeof message.error.message !== 'string') {
                        throw new ParserError(createError(message.id, ERRORS.INVALID_REQUEST));
                    }
                    result = {
                        type: MESSAGE_TYPES.ERROR,
                        payload: {
                            id: message.id,
                            error: message.error
                        }
                    };
                }
            }
        }
        // If message is not an array and is not an object - it is invalid, so return an error:
        else {
            throw new ParserError(createError(null, ERRORS.INVALID_REQUEST));
        }
 
        return result;
    }
 
    return {
        ERRORS,
        MESSAGE_TYPES,
        INTERNAL_MESSAGE_PREFIX,
        ParserError,
        createRequest,
        createInternalRequest,
        createNotification,
        createInternalNotification,
        createResponse,
        createError,
        parseMessage
    };
});