UNPKG

@open-formulieren/formio-builder

Version:

An opinionated Formio webform builder for Open Forms

66 lines (65 loc) 2.41 kB
import { z } from 'zod'; import { buildCommonSchema } from '../../registry/validation'; // Reference: formio's file component translateScalars method, but without the weird // units that don't make sense for files... const TRANSFORMATIONS = { B: Math.pow(1024, 0), KB: Math.pow(1024, 1), MB: Math.pow(1024, 2), GB: Math.pow(1024, 3), }; const getSizeInBytes = (filesize) => { const match = /^(\d+)\s*(B|KB|MB|GB)?$/i.exec(filesize); if (match === null) { return null; } const size = parseInt(match[1], 10); const unit = (match[2] || 'B').toUpperCase(); return size * TRANSFORMATIONS[unit]; }; const imgSize = z.number().int().positive(); const ofSchema = z.object({ image: z .object({ resize: z .object({ apply: z.boolean().optional(), width: imgSize.optional(), height: imgSize.optional(), }) .optional(), }) .optional(), }); const buildFileMaxSizeSchema = (intl, builderContext) => { var _a; const { serverUploadLimit } = builderContext; const serverLimitInBytes = (_a = getSizeInBytes(serverUploadLimit)) !== null && _a !== void 0 ? _a : Number.MAX_SAFE_INTEGER; return z .string() .transform((val, ctx) => { const sizeInBytes = getSizeInBytes(val); if (sizeInBytes === null) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: intl.formatMessage({ id: "QW32Dd", defaultMessage: [{ type: 0, value: "Specify a positive, non-zero file size without decimals, e.g. 10MB." }] }), }); return z.NEVER; } return sizeInBytes; }) .refine(value => value <= serverLimitInBytes, { message: intl.formatMessage({ id: "5/jkH9", defaultMessage: [{ type: 0, value: "Specify a file size less than or equal to the server upload limit." }] }), }); }; const buildFileSchema = (intl, builderContext) => z.object({ of: ofSchema.optional(), maxNumberOfFiles: z.union([z.null(), z.number().int().positive().optional()]), fileMaxSize: buildFileMaxSizeSchema(intl, builderContext).optional(), }); const schema = ({ intl, builderContext }) => { const common = buildCommonSchema(intl); const fileSpecific = buildFileSchema(intl, builderContext); return common.and(fileSpecific); }; export default schema;