@schema-hub/zod-error-formatter
Version:
Simple and easy-to-understand zod error messages
48 lines • 1.75 kB
JavaScript
import { isNonEmptyArray } from '../tuple/non-empty-array.js';
export const isNonEmptyPath = (isNonEmptyArray);
export function formatPath(path) {
return path.reduce((currentFormattedPath, item, index) => {
if (typeof item === 'number') {
return `${currentFormattedPath}[${item}]`;
}
if (index === 0) {
return item.toString();
}
return `${currentFormattedPath}.${item.toString()}`;
}, '');
}
function isIndexable(value) {
return typeof value === 'object' && value !== null;
}
function isMap(value) {
return value instanceof Map;
}
function determinePathItemKind(pathItem) {
return typeof pathItem === 'number' ? 'key' : 'property';
}
function findMapValueByPath(value, path) {
if (isNonEmptyPath(path)) {
const [mapEntryKey, ...remainingPath] = path;
const entry = value.get(mapEntryKey);
if (entry !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define -- recursion
return findValueByPath(entry, remainingPath);
}
return { found: false, pathItemKind: determinePathItemKind(mapEntryKey) };
}
return { found: true, value };
}
export function findValueByPath(value, path) {
if (isMap(value)) {
return findMapValueByPath(value, path);
}
if (isNonEmptyPath(path)) {
const [currentPathItem, ...remainingPath] = path;
if (isIndexable(value) && Object.hasOwn(value, currentPathItem)) {
return findValueByPath(value[currentPathItem], remainingPath);
}
return { found: false, pathItemKind: determinePathItemKind(currentPathItem) };
}
return { found: true, value };
}
//# sourceMappingURL=path.js.map