valibot: [v0.31.0-rc.5] The internal function `_stringify` has a problem

The internal function _stringify has a problem. It may happen that constructor is undefined, so when trying to access constructor.name an error is thrown because name cannot be accessed since constructor is `undefined.

https://github.com/fabian-hiller/valibot/blob/2bdb2c8cb2228cc9d11776a60ba7e380caaece97/library/src/utils/_stringify/_stringify.ts#L10-L20

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 23 (9 by maintainers)

Commits related to this issue

Most upvoted comments

This is fixed in v0.31.0-rc.6

Due to our small bundle size, Zods solution does not work for us. 🫤

My reply https://github.com/fabian-hiller/valibot/issues/608#issuecomment-2135423650 - Yes, I agree. I think input && typeof input === 'object' is the only check that cannot be manipulated by developers. It will always work as expected. But by doing so, specific object types will also get accepted (like Array, Date and so on), which is fine because technically specific objects still belong to the general object type. I would recommend using input && typeof input === 'object' as a temporary change until we can find a better solution.

I mean Object.getPrototypeOf(input).constructor and not Object.getPrototypeOf(input). You recommended to add a second ? to Object.getPrototypeOf(input)?.constructor?.name and I want to understand why do you think that this is necessary.

The first ? is useful in cases where Object.getPrototypeOf(input) is null but there are also cases where Object.getPrototypeOf(input) is an empty object {} so the first ? has no effect, therefore trying to access the name property of the constructor will throw error since the constructor property does not exist on an empty object {}. For this reason, it is necessary to use two ?.

function Empty() {}
Empty.prototype = Object.create(null);

const test2 = new Empty();

Object.getPrototypeOf(test2); // {}
Object.getPrototypeOf(test2)?.constructor; // undefiend
Object.getPrototypeOf(test2)?.constructor.name; // TypeError: Cannot read properties of undefined (reading 'name')
Object.getPrototypeOf(test2)?.constructor?.name; // undefined