UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

56 lines 2.28 kB
import _Object$hasOwn from "core-js-pure/stable/object/has-own.js"; import * as z from 'zod'; export function extractZodSubSchema(root, pointer) { if (!pointer) return root; const normalized = pointer.startsWith('#') ? pointer.slice(1) : pointer; if (normalized === '/' || normalized === '') return root; const parts = normalized.split('/').slice(1).map(decodePointerSegment); let cur = root; for (const part of parts) { cur = unwrap(cur); if (cur instanceof z.ZodObject) { const shape = cur.shape; if (!_Object$hasOwn(shape, part)) { throw new Error(`Key '${part}' not found in object shape`); } cur = shape[part]; continue; } if (cur instanceof z.ZodArray) { cur = cur.element; continue; } if (cur instanceof z.ZodTuple) { const idx = Number(part); const items = cur.def.items; if (!Array.isArray(items)) { throw new Error('Tuple items are unavailable for traversal'); } if (!Number.isInteger(idx) || idx < 0 || idx >= items.length) { throw new Error(`Tuple index out of range: ${part}`); } cur = items[idx]; continue; } if (cur instanceof z.ZodRecord) { cur = cur.valueType; continue; } if (cur instanceof z.ZodUnion || cur instanceof z.ZodDiscriminatedUnion) { throw new Error('Pointer into union is ambiguous. Choose a branch explicitly.'); } if (cur instanceof z.ZodIntersection) { throw new Error('Pointer into intersection is ambiguous. Decide how to traverse.'); } const typeName = cur.type || cur.constructor.name; throw new Error(`Unsupported traversal at '${part}' for schema type '${typeName}'`); } return cur; } export function unwrap(t) { return t instanceof z.ZodOptional || t instanceof z.ZodNullable || t instanceof z.ZodDefault || t instanceof z.ZodCatch || t instanceof z.ZodNonOptional || t instanceof z.ZodPrefault || t instanceof z.ZodSuccess || t instanceof z.ZodReadonly || t instanceof z.ZodLazy || t instanceof z.ZodPromise ? unwrap(t.unwrap()) : t instanceof z.ZodPipe ? unwrap(t.out) : t; } export function decodePointerSegment(seg) { return seg.replace(/~1/g, '/').replace(/~0/g, '~'); } //# sourceMappingURL=extractZodSubSchema.js.map