From 8aadaf6c1c55cc050fe00ece3615c34040237aa3 Mon Sep 17 00:00:00 2001 From: Dami Oyeniyi Date: Tue, 17 Nov 2026 13:54:46 +0100 Subject: [PATCH] fix(shared): handle nullish input, undefined values, and prototypes safely in hasA11yProp (#5208) * fix(shared): handle nullish input and undefined values safely in hasA11yProp * Fix types --------- Co-authored-by: grzdev Co-authored-by: Eric --- packages/shared/src/utils/hasA11yProp.ts | 14 +++++++++++--- packages/shared/tests/hasA11yProp.spec.ts | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/utils/hasA11yProp.ts b/packages/shared/src/utils/hasA11yProp.ts index ad1cbdc78..1785a37fc 100644 --- a/packages/shared/src/utils/hasA11yProp.ts +++ b/packages/shared/src/utils/hasA11yProp.ts @@ -1,12 +1,20 @@ /** * Check if a component has an accessibility prop * - * @param {object} props + * @param {object} [props] * @returns {boolean} Whether the component has an accessibility prop */ -export const hasA11yProp = (props: object) => { +export const hasA11yProp = (props?: Record | null): boolean => { + if (props == null || typeof props !== 'object') { + return false; + } + for (const prop in props) { - if (prop.startsWith('aria-') || prop === 'role' || prop === 'title') { + if ( + Object.prototype.hasOwnProperty.call(props, prop) && + (prop.startsWith('aria-') || prop === 'role' || prop === 'title') && + props[prop] != null + ) { return true; } } diff --git a/packages/shared/tests/hasA11yProp.spec.ts b/packages/shared/tests/hasA11yProp.spec.ts index ea71ed047..b7f64d4b1 100644 --- a/packages/shared/tests/hasA11yProp.spec.ts +++ b/packages/shared/tests/hasA11yProp.spec.ts @@ -27,4 +27,25 @@ describe('hasA11yProp', () => { it('returns true if a11y prop is present among other props', () => { expect(hasA11yProp({ className: 'foo', 'aria-label': 'Close' })).toBe(true); }); + + it('returns false when props is null, undefined, or a non-object', () => { + expect(hasA11yProp(null)).toBe(false); + expect(hasA11yProp(undefined)).toBe(false); + expect(hasA11yProp()).toBe(false); + expect(hasA11yProp('not-an-object' as unknown as Record)).toBe(false); + expect(hasA11yProp(123 as unknown as Record)).toBe(false); + }); + + it('returns false when a11y props are explicitly undefined or null', () => { + expect(hasA11yProp({ 'aria-label': undefined })).toBe(false); + expect(hasA11yProp({ role: null })).toBe(false); + expect(hasA11yProp({ title: undefined, 'aria-hidden': null })).toBe(false); + }); + + it('ignores inherited properties on the prototype chain', () => { + const proto = { 'aria-label': 'Inherited' }; + const props = Object.create(proto); + props.className = 'icon'; + expect(hasA11yProp(props)).toBe(false); + }); });