← Public packages
@kentcdodds/photo-portfolio
A fast, photo-first portfolio site you update by chatting with your agent: galleries, about, contact, and one-step rollback.
Files
import * as s from 'remix/data-schema'
type InputIssue = {
message: string
path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>
}
/**
* Parse agent input strictly and throw one readable error listing every issue
* (`path: message`), so a mistyped key never turns into a silent no-op.
*/
export function parseInput<output>(
schema: s.Schema<unknown, output>,
raw: unknown,
label: string,
): output {
const result = s.parseSafe(schema, raw ?? {})
if (result.success) return result.value
const lines = result.issues.map((issue: InputIssue) => {
const path = (issue.path ?? [])
.map((part: PropertyKey | { key: PropertyKey }) =>
typeof part === 'object' ? String(part.key) : String(part),
)
.join('.')
return path ? `${path}: ${issue.message}` : issue.message
})
throw new Error(`Invalid ${label} input. ${lines.join('; ')}`)
}
export function isHttpUrl(value: string) {
try {
const url = new URL(value)
return url.protocol === 'https:' || url.protocol === 'http:'
} catch {
return false
}
}
export function isEmail(value: string) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
}
export function isHexColor(value: string) {
return /^#[0-9a-fA-F]{6}$/.test(value)
}
/** Non-empty trimmed text with a length cap. */
export function text(max: number) {
return s
.string()
.refine((value: string) => value.trim().length > 0, 'must not be empty')
.refine(
(value: string) => value.length <= max,
`must be at most ${max} characters`,
)
}
/** Possibly-empty text with a length cap. */
export function longText(max: number) {
return s
.string()
.refine(
(value: string) => value.length <= max,
`must be at most ${max} characters`,
)
}
export function httpUrl() {
return s.string().refine(isHttpUrl, 'must be an http(s) URL')
}
export function strictObject<shape extends Record<string, s.Schema<any, any>>>(
shape: shape,
) {
return s.object(shape, { unknownKeys: 'error' })
}