UNPKG

@conform-to/zod

Version:

Conform helpers for integrating with Zod

72 lines (67 loc) 2.37 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var dom = require('@conform-to/dom'); var core = require('zod/v4/core'); var coercion = require('./coercion.js'); function getError(zodError, formatError) { var result = {}; for (var issue of zodError.issues) { var name = dom.formatPaths(issue.path.map(path => { if (typeof path === 'symbol') { throw new Error('@conform-to/zod does not support symbol paths. Please use a string or number instead.'); } return path; })); switch (issue.message) { case conformZodMessage.VALIDATION_UNDEFINED: return null; case conformZodMessage.VALIDATION_SKIPPED: result[name] = null; break; default: { var _issues = result[name]; if (_issues !== null) { if (_issues) { result[name] = _issues.concat(issue); } else { result[name] = [issue]; } } break; } } } return Object.entries(result).reduce((result, _ref) => { var [name, issues] = _ref; result[name] = issues ? formatError(issues) : null; return result; }, {}); } function parseWithZod(payload, options) { return dom.parse(payload, { resolve(payload, intent) { var error = options.error; var baseSchema = typeof options.schema === 'function' ? options.schema(intent) : options.schema; var schema = !options.disableAutoCoercion ? coercion.coerceFormValue(baseSchema) : baseSchema; var resolveSubmission = result => { var _options$formatError; return { value: result.success ? result.data : undefined, error: !result.success ? getError(result.error, (_options$formatError = options.formatError) !== null && _options$formatError !== void 0 ? _options$formatError : issues => issues.map(issue => issue.message)) : undefined }; }; return options.async ? core.safeParseAsync(schema, payload, { error }).then(result => resolveSubmission(result)) : resolveSubmission(core.safeParse(schema, payload, { error })); } }); } var conformZodMessage = { VALIDATION_SKIPPED: '__skipped__', VALIDATION_UNDEFINED: '__undefined__' }; exports.conformZodMessage = conformZodMessage; exports.parseWithZod = parseWithZod;