export class PathError extends Error { constructor( public readonly kind: "invalid_path", public readonly path: string, ) { super(`${kind}: ${path}`); }}type Step = { key: string } | { index: number };const isDigit = (c: string): boolean => c.length === 1 && c >= "0" && c <= "9";const isKeyChar = (c: string): boolean => c.length === 1 && c !== "." && c !== "[" && c !== "]";const parsePath = (path: string): Step[] | undefined => { const steps: Step[] = []; let i = 0; const readKey = (): boolean => { const start = i; while (i < path.length && isKeyChar(path.charAt(i))) i++; if (i === start) return false; steps.push({ key: path.slice(start, i) }); return true; }; if (path.length === 0) return undefined; while (i < path.length) { const c = path.charAt(i); if (c === "[") { i++; const start = i; while (i < path.length && isDigit(path.charAt(i))) i++; if (i === start || path.charAt(i) !== "]") return undefined; steps.push({ index: Number(path.slice(start, i)) }); i++; } else if (c === "." && steps.length > 0) { i++; if (!readKey()) return undefined; } else if (steps.length === 0) { if (!readKey()) return undefined; } else { return undefined; } } return steps;};/** Returns undefined when the value is absent. Throws PathError for an invalid path. */export function getPath(obj: unknown, path: string): unknown { const steps = parsePath(path); if (steps === undefined) throw new PathError("invalid_path", path); let cur: unknown = obj; for (const step of steps) { if ("key" in step) { if (typeof cur !== "object" || cur === null || Array.isArray(cur) || !Object.hasOwn(cur, step.key)) return undefined; cur = (cur as Record<string, unknown>)[step.key]; } else { if (!Array.isArray(cur) || step.index >= cur.length) return undefined; cur = cur[step.index]; } } return cur === null ? undefined : cur;}