From 594bc04c03fb073cd7ad31d7e23f77fb8041b92e Mon Sep 17 00:00:00 2001 From: Mykola Mokhnach Date: Tue, 25 Feb 2025 20:58:54 +0100 Subject: [PATCH] fix(base-driver): Tune capabilities array parsing (#21044) --- packages/base-driver/lib/basedriver/helpers.js | 13 ++++++++----- .../test/unit/basedriver/helpers.spec.js | 3 +++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/base-driver/lib/basedriver/helpers.js b/packages/base-driver/lib/basedriver/helpers.js index 21e48c08f..933993fe0 100644 --- a/packages/base-driver/lib/basedriver/helpers.js +++ b/packages/base-driver/lib/basedriver/helpers.js @@ -376,26 +376,29 @@ export function duplicateKeys(input, firstKey, secondKey) { * Takes a desired capability and tries to JSON.parse it as an array, * and either returns the parsed array or a singleton array. * - * @param {string|Array} cap A desired capability + * @param {string[]} cap A desired capability */ export function parseCapsArray(cap) { if (_.isArray(cap)) { return cap; } - let parsedCaps; try { - parsedCaps = JSON.parse(cap); + const parsedCaps = JSON.parse(cap); if (_.isArray(parsedCaps)) { return parsedCaps; } } catch (e) { - logger.warn(`Failed to parse capability as JSON array: ${e.message}`); + const message = `Failed to parse capability as JSON array: ${e.message}`; + if (_.isString(cap) && _.startsWith(_.trimStart(cap), '[')) { + throw new TypeError(message); + } + logger.warn(message); } if (_.isString(cap)) { return [cap]; } - throw new Error(`must provide a string or JSON Array; received ${cap}`); + throw new TypeError(`Expected a string or a valid JSON array; received '${cap}'`); } /** diff --git a/packages/base-driver/test/unit/basedriver/helpers.spec.js b/packages/base-driver/test/unit/basedriver/helpers.spec.js index 1a5a6b4be..b301c9014 100644 --- a/packages/base-driver/test/unit/basedriver/helpers.spec.js +++ b/packages/base-driver/test/unit/basedriver/helpers.spec.js @@ -153,4 +153,7 @@ describe('parseCapsArray', function () { it('should return an array without change', function () { parseCapsArray(['a', 'b']).should.eql(['a', 'b']); }); + it('should fail if an invalid JSON array is provided', function () { + (() => parseCapsArray(`['*']`)).should.throw(); + }); });