Suite of AT Protocol TypeScript libraries built on web standards
1import { CID } from "multiformats/cid";
2import { z } from "zod";
3import type { Def } from "./check.ts";
4
5const cidSchema = z.unknown().transform((obj, ctx): CID => {
6 const cid = CID.asCID(obj);
7
8 if (cid == null) {
9 ctx.addIssue({
10 code: "custom",
11 message: "Not a valid CID",
12 });
13 return z.NEVER;
14 }
15
16 return cid;
17});
18
19const carHeader: z.ZodObject<{ version: z.ZodLiteral<1>; roots: z.ZodArray }> =
20 z.object({
21 version: z.literal(1),
22 roots: z.array(cidSchema),
23 });
24export type CarHeader = z.infer<typeof carHeader>;
25
26export const schema: Record<string, z.ZodTypeAny> = {
27 cid: cidSchema,
28 carHeader,
29 bytes: z.instanceof(Uint8Array),
30 string: z.string(),
31 array: z.array(z.unknown()),
32 map: z.record(z.string(), z.unknown()),
33 unknown: z.unknown(),
34};
35
36export const def = {
37 cid: {
38 name: "cid",
39 schema: schema.cid,
40 } as Def<CID>,
41 carHeader: {
42 name: "CAR header",
43 schema: schema.carHeader,
44 } as Def<CarHeader>,
45 bytes: {
46 name: "bytes",
47 schema: schema.bytes,
48 } as Def<Uint8Array>,
49 string: {
50 name: "string",
51 schema: schema.string,
52 } as Def<string>,
53 map: {
54 name: "map",
55 schema: schema.map,
56 } as Def<Record<string, unknown>>,
57 unknown: {
58 name: "unknown",
59 schema: schema.unknown,
60 } as Def<unknown>,
61};
62
63export type ArrayEl<A> = A extends readonly (infer T)[] ? T : never;
64
65export type NotEmptyArray<T> = [T, ...T[]];