@dfinity/zod-schemas 3.1.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +4 -4
- package/dist/option.d.ts +34 -0
- package/dist/result.d.ts +19 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,8 +31,60 @@ The library implements following features:
|
|
|
31
31
|
|
|
32
32
|
### :toolbox: Functions
|
|
33
33
|
|
|
34
|
+
- [inferOptionSchema](#gear-inferoptionschema)
|
|
35
|
+
- [inferNullishSchema](#gear-infernullishschema)
|
|
36
|
+
- [inferNullableSchema](#gear-infernullableschema)
|
|
37
|
+
- [inferResultSchema](#gear-inferresultschema)
|
|
34
38
|
- [createUrlSchema](#gear-createurlschema)
|
|
35
39
|
|
|
40
|
+
#### :gear: inferOptionSchema
|
|
41
|
+
|
|
42
|
+
| Function | Type |
|
|
43
|
+
| ------------------- | ---------------------------------------------------- |
|
|
44
|
+
| `inferOptionSchema` | `<T extends z.ZodType>(schema: T) => ZodOptional<T>` |
|
|
45
|
+
|
|
46
|
+
References:
|
|
47
|
+
|
|
48
|
+
- `Option`
|
|
49
|
+
|
|
50
|
+
[:link: Source](https://github.com/dfinity/icp-js-canisters/tree/main/packages/zod-schemas/src/option.ts#L4)
|
|
51
|
+
|
|
52
|
+
#### :gear: inferNullishSchema
|
|
53
|
+
|
|
54
|
+
| Function | Type |
|
|
55
|
+
| -------------------- | ----------------------------------------------------------------- |
|
|
56
|
+
| `inferNullishSchema` | `<T extends z.ZodType>(schema: T) => ZodOptional<ZodNullable<T>>` |
|
|
57
|
+
|
|
58
|
+
References:
|
|
59
|
+
|
|
60
|
+
- `Nullable`
|
|
61
|
+
|
|
62
|
+
[:link: Source](https://github.com/dfinity/icp-js-canisters/tree/main/packages/zod-schemas/src/option.ts#L8)
|
|
63
|
+
|
|
64
|
+
#### :gear: inferNullableSchema
|
|
65
|
+
|
|
66
|
+
| Function | Type |
|
|
67
|
+
| --------------------- | ---------------------------------------------------- |
|
|
68
|
+
| `inferNullableSchema` | `<T extends z.ZodType>(schema: T) => ZodNullable<T>` |
|
|
69
|
+
|
|
70
|
+
References:
|
|
71
|
+
|
|
72
|
+
- `Nullish`
|
|
73
|
+
|
|
74
|
+
[:link: Source](https://github.com/dfinity/icp-js-canisters/tree/main/packages/zod-schemas/src/option.ts#L12)
|
|
75
|
+
|
|
76
|
+
#### :gear: inferResultSchema
|
|
77
|
+
|
|
78
|
+
| Function | Type |
|
|
79
|
+
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
80
|
+
| `inferResultSchema` | `<T extends z.ZodType>(schema: T) => ZodDiscriminatedUnion<[ZodObject<{ status: ZodLiteral<"success">; result: T; }, $strict>, ZodObject<{ status: ZodLiteral<"error">; err: ZodOptional<...>; }, $strict>]>` |
|
|
81
|
+
|
|
82
|
+
References:
|
|
83
|
+
|
|
84
|
+
- `Result`
|
|
85
|
+
|
|
86
|
+
[:link: Source](https://github.com/dfinity/icp-js-canisters/tree/main/packages/zod-schemas/src/result.ts#L4)
|
|
87
|
+
|
|
36
88
|
#### :gear: createUrlSchema
|
|
37
89
|
|
|
38
90
|
Creates a Zod schema for validating URLs. By default, it validates that the URL protocol is HTTPS and allow usage of HTTP only locally.
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as a from"zod";var o=(t=>(t.PrincipalText="PrincipalText",t.Principal="Principal",t.Uint8Array="Uint8Array",t.Url="Url",t))(o||{});var x=a.instanceof(Uint8Array).meta({id:"Uint8Array"});var z=r=>r.optional(),d=r=>r.nullish(),h=r=>r.nullable();import{Principal as p}from"@icp-sdk/core/principal";import*as n from"zod";var R=n.string().refine(r=>{try{return p.fromText(r),!0}catch{return!1}},{error:"Invalid textual representation of a Principal."}).meta({id:"PrincipalText"}),b=n.custom().refine(r=>p.isPrincipal(r),{error:"Invalid Principal.",abort:!0}).transform(r=>p.from(r)).meta({id:"Principal"});import*as e from"zod";var w=r=>e.discriminatedUnion("status",[e.strictObject({status:e.literal("success"),result:r}),e.strictObject({status:e.literal("error"),err:e.unknown().optional()})]);import*as c from"zod";var f=({additionalProtocols:r=[],allowHttpLocally:l=!0})=>c.url().refine(s=>{try{let i=[...new Set(["https:",...r])],{protocol:t,hostname:m}=new URL(s);return l&&["localhost","127.0.0.1"].includes(m)?["http:",...i].includes(t):i.includes(t)}catch{return!1}},{error:"Invalid URL."}),L=f({}).meta({id:"Url"});export{b as PrincipalSchema,R as PrincipalTextSchema,x as Uint8ArraySchema,L as UrlSchema,o as ZodSchemaId,f as createUrlSchema,h as inferNullableSchema,d as inferNullishSchema,z as inferOptionSchema,w as inferResultSchema};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/arrays.ts", "../src/schema-id.ts", "../src/principal.ts", "../src/url.ts"],
|
|
4
|
-
"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 { 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\";\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"],
|
|
5
|
-
"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,
|
|
6
|
-
"names": ["z", "ZodSchemaId", "Uint8ArraySchema", "Principal", "z", "PrincipalTextSchema", "principal", "Principal", "PrincipalSchema", "value", "z", "createUrlSchema", "additionalProtocols", "allowHttpLocally", "url", "protocols", "protocol", "hostname", "UrlSchema"]
|
|
3
|
+
"sources": ["../src/arrays.ts", "../src/schema-id.ts", "../src/option.ts", "../src/principal.ts", "../src/result.ts", "../src/url.ts"],
|
|
4
|
+
"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 = createU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,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",
|
|
6
|
+
"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"]
|
|
7
7
|
}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as topLevelCreateRequire } from 'module';
|
|
2
2
|
const require = topLevelCreateRequire(import.meta.url);
|
|
3
|
-
import*as
|
|
3
|
+
import*as a from"zod";var o=(t=>(t.PrincipalText="PrincipalText",t.Principal="Principal",t.Uint8Array="Uint8Array",t.Url="Url",t))(o||{});var x=a.instanceof(Uint8Array).meta({id:"Uint8Array"});var z=r=>r.optional(),d=r=>r.nullish(),h=r=>r.nullable();import{Principal as p}from"@icp-sdk/core/principal";import*as n from"zod";var R=n.string().refine(r=>{try{return p.fromText(r),!0}catch{return!1}},{error:"Invalid textual representation of a Principal."}).meta({id:"PrincipalText"}),b=n.custom().refine(r=>p.isPrincipal(r),{error:"Invalid Principal.",abort:!0}).transform(r=>p.from(r)).meta({id:"Principal"});import*as e from"zod";var w=r=>e.discriminatedUnion("status",[e.strictObject({status:e.literal("success"),result:r}),e.strictObject({status:e.literal("error"),err:e.unknown().optional()})]);import*as c from"zod";var f=({additionalProtocols:r=[],allowHttpLocally:l=!0})=>c.url().refine(s=>{try{let i=[...new Set(["https:",...r])],{protocol:t,hostname:m}=new URL(s);return l&&["localhost","127.0.0.1"].includes(m)?["http:",...i].includes(t):i.includes(t)}catch{return!1}},{error:"Invalid URL."}),L=f({}).meta({id:"Url"});export{b as PrincipalSchema,R as PrincipalTextSchema,x as Uint8ArraySchema,L as UrlSchema,o as ZodSchemaId,f as createUrlSchema,h as inferNullableSchema,d as inferNullishSchema,z as inferOptionSchema,w as inferResultSchema};
|
|
4
4
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/arrays.ts", "../src/schema-id.ts", "../src/principal.ts", "../src/url.ts"],
|
|
4
|
-
"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 { 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\";\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"],
|
|
5
|
-
"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,
|
|
6
|
-
"names": ["z", "ZodSchemaId", "Uint8ArraySchema", "Principal", "z", "PrincipalTextSchema", "principal", "Principal", "PrincipalSchema", "value", "z", "createUrlSchema", "additionalProtocols", "allowHttpLocally", "url", "protocols", "protocol", "hostname", "UrlSchema"]
|
|
3
|
+
"sources": ["../src/arrays.ts", "../src/schema-id.ts", "../src/option.ts", "../src/principal.ts", "../src/result.ts", "../src/url.ts"],
|
|
4
|
+
"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"],
|
|
5
|
+
"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,E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,CAAE,QAAoB,CAAC",
|
|
6
|
+
"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"]
|
|
7
7
|
}
|
package/dist/option.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { z } from "zod";
|
|
2
|
+
/** @see {@link Option} */
|
|
3
|
+
export declare const inferOptionSchema: <T extends z.ZodType>(schema: T) => z.ZodOptional<T>;
|
|
4
|
+
/** @see {@link Nullable} */
|
|
5
|
+
export declare const inferNullishSchema: <T extends z.ZodType>(schema: T) => z.ZodOptional<z.ZodNullable<T>>;
|
|
6
|
+
/** @see {@link Nullish} */
|
|
7
|
+
export declare const inferNullableSchema: <T extends z.ZodType>(schema: T) => z.ZodNullable<T>;
|
|
8
|
+
/**
|
|
9
|
+
* Represents a value that may be `undefined`.
|
|
10
|
+
*
|
|
11
|
+
* @template T - The type of the wrapped value.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* type MaybeString = Option<string>; // string | undefined
|
|
15
|
+
*/
|
|
16
|
+
export type Option<T> = z.infer<ReturnType<typeof inferOptionSchema<z.ZodType<T>>>>;
|
|
17
|
+
/**
|
|
18
|
+
* Represents a value that may be `null`.
|
|
19
|
+
*
|
|
20
|
+
* @template T - The type of the wrapped value.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* type MaybeString = Nullable<string>; // string | null
|
|
24
|
+
*/
|
|
25
|
+
export type Nullable<T> = z.infer<ReturnType<typeof inferNullableSchema<z.ZodType<T>>>>;
|
|
26
|
+
/**
|
|
27
|
+
* Represents a value that may be `null` or `undefined`.
|
|
28
|
+
*
|
|
29
|
+
* @template T - The type of the wrapped value.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* type MaybeString = Nullish<string>; // string | null | undefined
|
|
33
|
+
*/
|
|
34
|
+
export type Nullish<T> = z.infer<ReturnType<typeof inferNullishSchema<z.ZodType<T>>>>;
|
package/dist/result.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
/** @see {@link Result} */
|
|
3
|
+
export declare const inferResultSchema: <T extends z.ZodType>(schema: T) => z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
4
|
+
status: z.ZodLiteral<"success">;
|
|
5
|
+
result: T;
|
|
6
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
7
|
+
status: z.ZodLiteral<"error">;
|
|
8
|
+
err: z.ZodOptional<z.ZodUnknown>;
|
|
9
|
+
}, z.core.$strict>]>;
|
|
10
|
+
/**
|
|
11
|
+
* Represents a result type with a success or error state.
|
|
12
|
+
*
|
|
13
|
+
* @template T - The type of the success `result` value.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* type StringResult = Result<string>;
|
|
17
|
+
* // { status: "success"; result: string } | { status: "error"; err?: unknown }
|
|
18
|
+
*/
|
|
19
|
+
export type Result<T> = z.infer<ReturnType<typeof inferResultSchema<z.ZodType<T>>>>;
|
package/package.json
CHANGED