66 lines
2.2 KiB
TypeScript
66 lines
2.2 KiB
TypeScript
import { z } from 'zod';
|
|
|
|
const codePointLength = (value: string): number => Array.from(value).length;
|
|
const validUnicode = (value: string): boolean => !/[\u0000\uD800-\uDFFF]/u.test(value);
|
|
const nonBlank = (value: string): boolean => value.trim().length > 0;
|
|
|
|
const boundedUnicodeString = (max: number, label: string) =>
|
|
z
|
|
.string()
|
|
.refine(validUnicode, 'Недопустимый символ')
|
|
.refine(nonBlank, `${label} не может состоять только из пробелов`)
|
|
.refine(
|
|
(value) => codePointLength(value) <= max,
|
|
`${label} слишком длинное`,
|
|
);
|
|
|
|
export const uuidSchema = z.string().uuid('Ожидался UUID').transform((id) => id.toLowerCase());
|
|
export const usernameSchema = z.string().regex(/^[a-z0-9_]{3,32}$/, 'Некорректный username');
|
|
export const passwordSchema = boundedUnicodeString(128, 'password')
|
|
.refine((value) => codePointLength(value) >= 12, 'password слишком короткий');
|
|
|
|
export const createUserSchema = z
|
|
.object({
|
|
username: usernameSchema,
|
|
password: passwordSchema,
|
|
display_name: boundedUnicodeString(100, 'display_name'),
|
|
})
|
|
.strict();
|
|
|
|
export const createChatSchema = z
|
|
.object({
|
|
title: boundedUnicodeString(100, 'title'),
|
|
member_ids: z
|
|
.array(uuidSchema)
|
|
.min(1)
|
|
.max(100)
|
|
.refine(
|
|
(ids) => new Set(ids).size === ids.length,
|
|
'member_ids содержит дубликаты',
|
|
),
|
|
})
|
|
.strict();
|
|
|
|
export const createMessageSchema = z
|
|
.object({
|
|
text: boundedUnicodeString(4000, 'text'),
|
|
})
|
|
.strict();
|
|
|
|
export const paginationSchema = z.object({
|
|
limit: z.number().int().min(1).max(100).default(50),
|
|
cursor: z.string().min(1).max(512).optional(),
|
|
});
|
|
|
|
export const cursorPayloadSchema = z
|
|
.object({
|
|
v: z.literal(1),
|
|
kind: z.enum(['chats', 'messages']),
|
|
resource: z.string().min(1),
|
|
created_at: z.string().datetime({ precision: 3 }),
|
|
id: uuidSchema,
|
|
})
|
|
.strict();
|
|
|
|
export type CursorPayload = z.infer<typeof cursorPayloadSchema>;
|