fix(base-driver): Tune capabilities array parsing (#21044)

This commit is contained in:
Mykola Mokhnach
2025-02-25 20:58:54 +01:00
committed by GitHub
parent ca8590221e
commit 594bc04c03
2 changed files with 11 additions and 5 deletions

View File

@@ -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<String>} 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}'`);
}
/**

View File

@@ -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();
});
});