UNPKG

@dfinity/zod-schemas

Version:

A collection of reusable Zod schemas and validators for common data patterns in ICP applications

8 lines (7 loc) 8.71 kB
{ "version": 3, "sources": ["../src/arrays.ts", "../src/schema-id.ts", "../src/option.ts", "../src/principal.ts", "../src/result.ts", "../src/url.ts"], "sourcesContent": ["import * as z from \"zod\";\nimport { ZodSchemaId } from \"./schema-id\";\n\n/**\n * Zod schema to validate a value is a `Uint8Array` instance.\n *\n * @example\n * ```typescript\n * const result = Uint8ArraySchema.safeParse(new Uint8Array([1, 2, 3]));\n * console.log(result.success); // true or false\n * ```\n */\nexport const Uint8ArraySchema = z\n .instanceof(Uint8Array)\n .meta({ id: ZodSchemaId.Uint8Array });\n", "/**\n * Enum of metadata `id` values assigned to Zod schemas in this library.\n */\nexport enum ZodSchemaId {\n /** Metadata id for {@link PrincipalTextSchema}. */\n PrincipalText = \"PrincipalText\",\n /** Metadata id for {@link PrincipalSchema}. */\n Principal = \"Principal\",\n /** Metadata id for {@link Uint8ArraySchema}. */\n Uint8Array = \"Uint8Array\",\n /** Metadata id for {@link UrlSchema}. */\n Url = \"Url\",\n}\n", "import type { z } from \"zod\";\n\n/** @see {@link Option} */\nexport const inferOptionSchema = <T extends z.ZodType>(schema: T) =>\n schema.optional();\n\n/** @see {@link Nullable} */\nexport const inferNullishSchema = <T extends z.ZodType>(schema: T) =>\n schema.nullish();\n\n/** @see {@link Nullish} */\nexport const inferNullableSchema = <T extends z.ZodType>(schema: T) =>\n schema.nullable();\n\n/**\n * Represents a value that may be `undefined`.\n *\n * @template T - The type of the wrapped value.\n *\n * @example\n * type MaybeString = Option<string>; // string | undefined\n */\nexport type Option<T> = z.infer<\n ReturnType<typeof inferOptionSchema<z.ZodType<T>>>\n>;\n\n/**\n * Represents a value that may be `null`.\n *\n * @template T - The type of the wrapped value.\n *\n * @example\n * type MaybeString = Nullable<string>; // string | null\n */\nexport type Nullable<T> = z.infer<\n ReturnType<typeof inferNullableSchema<z.ZodType<T>>>\n>;\n\n/**\n * Represents a value that may be `null` or `undefined`.\n *\n * @template T - The type of the wrapped value.\n *\n * @example\n * type MaybeString = Nullish<string>; // string | null | undefined\n */\nexport type Nullish<T> = z.infer<\n ReturnType<typeof inferNullishSchema<z.ZodType<T>>>\n>;\n", "import { Principal } from \"@icp-sdk/core/principal\";\nimport * as z from \"zod\";\nimport { ZodSchemaId } from \"./schema-id\";\n\n/**\n * Zod schema to validate a string as a valid textual representation of a Principal.\n *\n * This schema checks if the provided string can be converted into a `Principal` instance.\n * If the conversion fails, validation will return an error message.\n *\n * @example\n * ```typescript\n * const result = PrincipalTextSchema.safeParse('aaaaa-aa');\n * console.log(result.success); // true or false\n * ```\n */\nexport const PrincipalTextSchema = z\n .string()\n .refine(\n (principal) => {\n try {\n Principal.fromText(principal);\n return true;\n } catch (_err: unknown) {\n return false;\n }\n },\n {\n error: \"Invalid textual representation of a Principal.\",\n },\n )\n .meta({ id: ZodSchemaId.PrincipalText });\n\nexport type PrincipalText = z.infer<typeof PrincipalTextSchema>;\n\n/**\n * Zod schema to validate and transform a value into a `Principal` instance.\n *\n * This schema checks if the provided value is an instance or an object representing\n * a `Principal` and transforms it into a valid `Principal` instance.\n *\n * @example\n * ```typescript\n * const result = PrincipalSchema.safeParse(Principal.fromText('aaaaa-aa'));\n * console.log(result.success); // true or false\n * ```\n */\nexport const PrincipalSchema = z\n .custom<Principal>()\n .refine((principal) => Principal.isPrincipal(principal), {\n error: \"Invalid Principal.\",\n abort: true,\n })\n .transform((value) => Principal.from(value))\n .meta({ id: ZodSchemaId.Principal });\n", "import * as z from \"zod\";\n\n/** @see {@link Result} */\nexport const inferResultSchema = <T extends z.ZodType>(schema: T) =>\n z.discriminatedUnion(\"status\", [\n z.strictObject({\n status: z.literal(\"success\"),\n result: schema,\n }),\n z.strictObject({\n status: z.literal(\"error\"),\n err: z.unknown().optional(),\n }),\n ]);\n\n/**\n * Represents a result type with a success or error state.\n *\n * @template T - The type of the success `result` value.\n *\n * @example\n * type StringResult = Result<string>;\n * // { status: \"success\"; result: string } | { status: \"error\"; err?: unknown }\n */\nexport type Result<T> = z.infer<\n ReturnType<typeof inferResultSchema<z.ZodType<T>>>\n>;\n", "import * as z from \"zod\";\nimport { ZodSchemaId } from \"./schema-id\";\n\n/**\n * A URL protocol as template literal type.\n * Example: \"https:\" or \"ftp:\"\n */\nexport type UrlProtocol = `${string}:`;\n\n/**\n * Creates a Zod schema for validating URLs. By default, it validates that the URL protocol is HTTPS and allow usage of HTTP only locally.\n *\n * @param {Object} options - Configuration options for the schema.\n * @param {UrlProtocol[]} [options.additionalProtocols=[]] - Additional protocols to allow (e.g., \"wss:\" or \"ftp:\"). \u26A0\uFE0F Usage of insecure protocols is discouraged.\n * @param {boolean} [options.allowHttpLocally=true] - Whether to allow HTTP for localhost and 127.0.0.1. Default: true.\n * @returns {z.ZodEffects<z.ZodString, string, string>} - The Zod schema with URL validation.\n *\n * @example\n * const schema = createUrlSchema({\n * additionalProtocols: [\"wss:\"],\n * allowHttpLocally: false\n * });\n *\n * schema.parse(\"https://example.com\"); // Valid\n * schema.parse(\"wss://example.com\"); // Valid\n * schema.parse(\"http://localhost\"); // Invalid if allowHttpLocally is false\n */\nexport const createUrlSchema = ({\n additionalProtocols = [],\n allowHttpLocally = true,\n}: {\n additionalProtocols?: UrlProtocol[];\n allowHttpLocally?: boolean;\n}): z.ZodURL =>\n z.url().refine(\n (url: string | URL): boolean => {\n try {\n const protocols = [...new Set([\"https:\", ...additionalProtocols])];\n\n const { protocol, hostname } = new URL(url);\n\n // We allow http for development locally\n if (allowHttpLocally && [\"localhost\", \"127.0.0.1\"].includes(hostname)) {\n return [\"http:\", ...protocols].includes(protocol);\n }\n\n return protocols.includes(protocol);\n } catch (_err: unknown) {\n return false;\n }\n },\n {\n error: \"Invalid URL.\",\n },\n );\n\n/**\n * Default URL schema that enforces HTTPS and allows HTTP locally.\n *\n * @constant {z.ZodEffects<z.ZodString, string, string>}\n * @example\n * UrlSchema.parse(\"https://example.com\"); // Valid\n * UrlSchema.parse(\"http://127.0.0.1\"); // Valid (localhost exception)\n */\nexport const UrlSchema = createUrlSchema({}).meta({ id: ZodSchemaId.Url });\n"], "mappings": ";;AAAA,UAAYA,MAAO,MCGZ,IAAKC,OAEVA,EAAA,cAAgB,gBAEhBA,EAAA,UAAY,YAEZA,EAAA,WAAa,aAEbA,EAAA,IAAM,MARIA,OAAA,IDSL,IAAMC,EACV,aAAW,UAAU,EACrB,KAAK,CAAE,eAA2B,CAAC,EEX/B,IAAMC,EAA0CC,GACrDA,EAAO,SAAS,EAGLC,EAA2CD,GACtDA,EAAO,QAAQ,EAGJE,EAA4CF,GACvDA,EAAO,SAAS,ECZlB,OAAS,aAAAG,MAAiB,0BAC1B,UAAYC,MAAO,MAeZ,IAAMC,EACV,SAAO,EACP,OACEC,GAAc,CACb,GAAI,CACF,OAAAC,EAAU,SAASD,CAAS,EACrB,EACT,MAAwB,CACtB,MAAO,EACT,CACF,EACA,CACE,MAAO,gDACT,CACF,EACC,KAAK,CAAE,kBAA8B,CAAC,EAgB5BE,EACV,SAAkB,EAClB,OAAQF,GAAcC,EAAU,YAAYD,CAAS,EAAG,CACvD,MAAO,qBACP,MAAO,EACT,CAAC,EACA,UAAWG,GAAUF,EAAU,KAAKE,CAAK,CAAC,EAC1C,KAAK,CAAE,cAA0B,CAAC,ECtDrC,UAAYC,MAAO,MAGZ,IAAMC,EAA0CC,GACnD,qBAAmB,SAAU,CAC3B,eAAa,CACb,OAAU,UAAQ,SAAS,EAC3B,OAAQA,CACV,CAAC,EACC,eAAa,CACb,OAAU,UAAQ,OAAO,EACzB,IAAO,UAAQ,EAAE,SAAS,CAC5B,CAAC,CACH,CAAC,ECbH,UAAYC,MAAO,MA2BZ,IAAMC,EAAkB,CAAC,CAC9B,oBAAAC,EAAsB,CAAC,EACvB,iBAAAC,EAAmB,EACrB,IAII,MAAI,EAAE,OACLC,GAA+B,CAC9B,GAAI,CACF,IAAMC,EAAY,CAAC,GAAG,IAAI,IAAI,CAAC,SAAU,GAAGH,CAAmB,CAAC,CAAC,EAE3D,CAAE,SAAAI,EAAU,SAAAC,CAAS,EAAI,IAAI,IAAIH,CAAG,EAG1C,OAAID,GAAoB,CAAC,YAAa,WAAW,EAAE,SAASI,CAAQ,EAC3D,CAAC,QAAS,GAAGF,CAAS,EAAE,SAASC,CAAQ,EAG3CD,EAAU,SAASC,CAAQ,CACpC,MAAwB,CACtB,MAAO,EACT,CACF,EACA,CACE,MAAO,cACT,CACF,EAUWE,EAAYP,EAAgB,CAAC,CAAC,EAAE,KAAK,CAAE,QAAoB,CAAC", "names": ["z", "ZodSchemaId", "Uint8ArraySchema", "inferOptionSchema", "schema", "inferNullishSchema", "inferNullableSchema", "Principal", "z", "PrincipalTextSchema", "principal", "Principal", "PrincipalSchema", "value", "z", "inferResultSchema", "schema", "z", "createUrlSchema", "additionalProtocols", "allowHttpLocally", "url", "protocols", "protocol", "hostname", "UrlSchema"] }