import { registerDecorator, ValidatorConstraint, type ValidationArguments, type ValidatorConstraintInterface, } from 'class-validator'; // JSON Schema (and the course contract) measure string lengths in Unicode code // points, while String.prototype.length counts UTF-16 units: one emoji outside // the BMP is two units. `@Length` therefore accepted an 11-emoji password // (22 units) and rejected 4000 emoji (8000 units), so these fields use an // explicit code-point validator instead. @ValidatorConstraint({ name: 'codePointLength', async: false }) class CodePointLengthConstraint implements ValidatorConstraintInterface { validate(value: unknown, args: ValidationArguments): boolean { const [min, max] = args.constraints as [number, number]; if (typeof value !== 'string') return false; const length = [...value].length; return length >= min && length <= max; } defaultMessage(args: ValidationArguments): string { const [min, max] = args.constraints as [number, number]; return `${args.property} must be between ${min} and ${max} code points`; } } export function CodePointLength(min: number, max: number): PropertyDecorator { return (target, propertyKey) => { registerDecorator({ name: 'codePointLength', target: target.constructor, propertyName: String(propertyKey), constraints: [min, max], validator: CodePointLengthConstraint, }); }; }