Suite of AT Protocol TypeScript libraries built on web standards
1import {
2 Schema,
3 type ValidationResult,
4 type ValidatorContext,
5} from "../validation.ts";
6import { asUint8Array } from "../data/uint8array.ts";
7
8export type BytesSchemaOptions = {
9 minLength?: number;
10 maxLength?: number;
11};
12
13export class BytesSchema extends Schema<Uint8Array> {
14 constructor(readonly options: BytesSchemaOptions = {}) {
15 super();
16 }
17
18 validateInContext(
19 input: unknown,
20 ctx: ValidatorContext,
21 ): ValidationResult<Uint8Array> {
22 const bytes = asUint8Array(input);
23 if (!bytes) {
24 return ctx.issueInvalidType(input, "bytes");
25 }
26
27 const { minLength } = this.options;
28 if (minLength != null && bytes.length < minLength) {
29 return ctx.issueTooSmall(bytes, "bytes", minLength, bytes.length);
30 }
31
32 const { maxLength } = this.options;
33 if (maxLength != null && bytes.length > maxLength) {
34 return ctx.issueTooBig(bytes, "bytes", maxLength, bytes.length);
35 }
36
37 return ctx.success(bytes);
38 }
39}