@veloxts/validation 0.1.0 → 0.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 CHANGED
@@ -1,5 +1,7 @@
1
1
  # @veloxts/validation
2
2
 
3
+ > **Alpha Release** - This framework is in early development. APIs may change between versions. Not recommended for production use yet.
4
+
3
5
  Type-safe validation using Zod schemas for the VeloxTS framework.
4
6
 
5
7
  ## Installation
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veloxts/validation",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Zod integration and validation middleware for VeloxTS framework",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -13,7 +13,7 @@
13
13
  },
14
14
  "dependencies": {
15
15
  "zod": "3.24.4",
16
- "@veloxts/core": "0.1.0"
16
+ "@veloxts/core": "0.2.0"
17
17
  },
18
18
  "devDependencies": {
19
19
  "typescript": "5.9.3",
package/dist/index.d.ts DELETED
@@ -1,35 +0,0 @@
1
- /**
2
- * @veloxts/validation - Zod integration for runtime validation
3
- *
4
- * Provides Zod-based validation with automatic type inference for
5
- * procedure inputs/outputs and request validation.
6
- *
7
- * @example
8
- * ```typescript
9
- * import { z, parse, InferOutput } from '@veloxts/validation';
10
- *
11
- * const UserSchema = z.object({
12
- * id: z.string().uuid(),
13
- * name: z.string().min(1),
14
- * email: z.string().email(),
15
- * });
16
- *
17
- * type User = InferOutput<typeof UserSchema>;
18
- *
19
- * const user = parse(UserSchema, data);
20
- * // user is typed as User
21
- * ```
22
- *
23
- * @module @veloxts/validation
24
- */
25
- export { ZodError, type ZodType, type ZodTypeDef, z } from 'zod';
26
- export declare const VALIDATION_VERSION: "0.1.0";
27
- export type { AnySchema, AnyZodSchema, InferInput, InferOutput, NoInput, ResolveInput, ResolveOutput, SafeParseError, SafeParseResult, SafeParseSuccess, Schema, SchemaLike, UnknownOutput, ValidationIssue, } from './types.js';
28
- export { isSchema, isZodSchema, wrapSchema } from './types.js';
29
- export type { Validator } from './middleware.js';
30
- export { assertSchema, createTypeGuard, createValidator, formatZodErrors, parse, parseAll, safeParse, safeValidate, validate, validateAll, zodErrorToValidationError, } from './middleware.js';
31
- export type { BaseEntity, IdParam, TimestampFields } from './schemas/common.js';
32
- export { baseEntitySchema, booleanStringSchema, createIdSchema, datetimeSchema, emailSchema, idParamSchema, integerStringSchema, makePartial, nonEmptyStringSchema, numberStringSchema, omitFields, partialExcept, pickFields, timestampFieldsSchema, urlSchema, uuidSchema, } from './schemas/common.js';
33
- export type { CursorPaginatedResponse, CursorPaginationInput, CursorPaginationMeta, PaginatedResponse, PaginationInput, PaginationMeta, } from './schemas/pagination.js';
34
- export { calculateOffset, calculatePaginationMeta, createCursorPaginatedResponseSchema, createPaginatedResponse, createPaginatedResponseSchema, createPaginationSchema, cursorPaginationSchema, PAGINATION_DEFAULTS, paginationInputSchema, } from './schemas/pagination.js';
35
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAIH,OAAO,EAAE,QAAQ,EAAE,KAAK,OAAO,EAAE,KAAK,UAAU,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGjE,eAAO,MAAM,kBAAkB,EAAG,OAAgB,CAAC;AAMnD,YAAY,EAEV,SAAS,EACT,YAAY,EACZ,UAAU,EACV,WAAW,EACX,OAAO,EACP,YAAY,EACZ,aAAa,EAEb,cAAc,EACd,eAAe,EACf,gBAAgB,EAChB,MAAM,EACN,UAAU,EACV,aAAa,EACb,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAU/D,YAAY,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAGjD,OAAO,EACL,YAAY,EACZ,eAAe,EACf,eAAe,EACf,eAAe,EACf,KAAK,EACL,QAAQ,EACR,SAAS,EACT,YAAY,EACZ,QAAQ,EACR,WAAW,EACX,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAMzB,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAChF,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,WAAW,EACX,aAAa,EACb,mBAAmB,EACnB,WAAW,EACX,oBAAoB,EACpB,kBAAkB,EAClB,UAAU,EACV,aAAa,EACb,UAAU,EACV,qBAAqB,EACrB,SAAS,EACT,UAAU,GACX,MAAM,qBAAqB,CAAC;AAM7B,YAAY,EACV,uBAAuB,EACvB,qBAAqB,EACrB,oBAAoB,EACpB,iBAAiB,EACjB,eAAe,EACf,cAAc,GACf,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,mCAAmC,EACnC,uBAAuB,EACvB,6BAA6B,EAC7B,sBAAsB,EACtB,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,yBAAyB,CAAC"}
package/dist/index.js DELETED
@@ -1,36 +0,0 @@
1
- /**
2
- * @veloxts/validation - Zod integration for runtime validation
3
- *
4
- * Provides Zod-based validation with automatic type inference for
5
- * procedure inputs/outputs and request validation.
6
- *
7
- * @example
8
- * ```typescript
9
- * import { z, parse, InferOutput } from '@veloxts/validation';
10
- *
11
- * const UserSchema = z.object({
12
- * id: z.string().uuid(),
13
- * name: z.string().min(1),
14
- * email: z.string().email(),
15
- * });
16
- *
17
- * type User = InferOutput<typeof UserSchema>;
18
- *
19
- * const user = parse(UserSchema, data);
20
- * // user is typed as User
21
- * ```
22
- *
23
- * @module @veloxts/validation
24
- */
25
- // Re-export Zod for convenience
26
- // Users can import { z } from '@veloxts/validation' instead of installing zod separately
27
- export { ZodError, z } from 'zod';
28
- // Version constant
29
- export const VALIDATION_VERSION = '0.1.0';
30
- export { isSchema, isZodSchema, wrapSchema } from './types.js';
31
- // Primary API - parse functions (Zod naming convention)
32
- // Deprecated aliases for backwards compatibility
33
- export { assertSchema, createTypeGuard, createValidator, formatZodErrors, parse, parseAll, safeParse, safeValidate, validate, validateAll, zodErrorToValidationError, } from './middleware.js';
34
- export { baseEntitySchema, booleanStringSchema, createIdSchema, datetimeSchema, emailSchema, idParamSchema, integerStringSchema, makePartial, nonEmptyStringSchema, numberStringSchema, omitFields, partialExcept, pickFields, timestampFieldsSchema, urlSchema, uuidSchema, } from './schemas/common.js';
35
- export { calculateOffset, calculatePaginationMeta, createCursorPaginatedResponseSchema, createPaginatedResponse, createPaginatedResponseSchema, createPaginationSchema, cursorPaginationSchema, PAGINATION_DEFAULTS, paginationInputSchema, } from './schemas/pagination.js';
36
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,gCAAgC;AAChC,yFAAyF;AACzF,OAAO,EAAE,QAAQ,EAAiC,CAAC,EAAE,MAAM,KAAK,CAAC;AAEjE,mBAAmB;AACnB,MAAM,CAAC,MAAM,kBAAkB,GAAG,OAAgB,CAAC;AAwBnD,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAW/D,wDAAwD;AACxD,iDAAiD;AACjD,OAAO,EACL,YAAY,EACZ,eAAe,EACf,eAAe,EACf,eAAe,EACf,KAAK,EACL,QAAQ,EACR,SAAS,EACT,YAAY,EACZ,QAAQ,EACR,WAAW,EACX,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAOzB,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,WAAW,EACX,aAAa,EACb,mBAAmB,EACnB,WAAW,EACX,oBAAoB,EACpB,kBAAkB,EAClB,UAAU,EACV,aAAa,EACb,UAAU,EACV,qBAAqB,EACrB,SAAS,EACT,UAAU,GACX,MAAM,qBAAqB,CAAC;AAc7B,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,mCAAmC,EACnC,uBAAuB,EACvB,6BAA6B,EAC7B,sBAAsB,EACtB,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,yBAAyB,CAAC"}
@@ -1,174 +0,0 @@
1
- /**
2
- * Validation middleware for VeloxTS procedures and routes
3
- *
4
- * Provides middleware utilities for validating request data
5
- * with proper error handling and type inference.
6
- *
7
- * @module middleware
8
- */
9
- import { ValidationError } from '@veloxts/core';
10
- import { ZodError, type ZodType, type ZodTypeDef } from 'zod';
11
- import type { AnySchema, AnyZodSchema, SafeParseResult } from './types.js';
12
- /**
13
- * Transforms Zod validation issues into a field-error map
14
- *
15
- * @param issues - Array of Zod validation issues
16
- * @returns Record mapping field paths to error messages
17
- */
18
- export declare function formatZodErrors(issues: readonly {
19
- path: readonly (string | number)[];
20
- message: string;
21
- }[]): Record<string, string>;
22
- /**
23
- * Transforms a ZodError into a VeloxTSValidationError
24
- *
25
- * @param error - ZodError from failed validation
26
- * @param customMessage - Optional custom error message
27
- * @returns ValidationError with field-specific errors
28
- */
29
- export declare function zodErrorToValidationError(error: ZodError, customMessage?: string): ValidationError;
30
- /**
31
- * Parses and validates data against a schema, throwing ValidationError on failure
32
- *
33
- * Follows Zod's naming convention for consistency with the ecosystem.
34
- *
35
- * @template T - The validated output type
36
- * @param schema - Zod schema or Schema wrapper
37
- * @param data - Data to validate
38
- * @param errorMessage - Optional custom error message
39
- * @returns Validated data with proper type
40
- * @throws ValidationError if validation fails
41
- *
42
- * @example
43
- * ```typescript
44
- * const UserSchema = z.object({ name: z.string(), email: z.string().email() });
45
- *
46
- * const user = parse(UserSchema, request.body);
47
- * // user is typed as { name: string; email: string }
48
- * ```
49
- */
50
- export declare function parse<T>(schema: ZodType<T, ZodTypeDef, unknown> | AnySchema, data: unknown, errorMessage?: string): T;
51
- /**
52
- * @deprecated Use `parse` instead. This alias will be removed in v1.0.
53
- */
54
- export declare const validate: typeof parse;
55
- /**
56
- * Safely parses data without throwing
57
- *
58
- * Follows Zod's naming convention for consistency with the ecosystem.
59
- *
60
- * @template T - The validated output type
61
- * @param schema - Zod schema or Schema wrapper
62
- * @param data - Data to validate
63
- * @returns Safe parse result with success discriminator
64
- *
65
- * @example
66
- * ```typescript
67
- * const result = safeParse(UserSchema, request.body);
68
- * if (result.success) {
69
- * console.log(result.data.name);
70
- * } else {
71
- * console.log(result.error);
72
- * }
73
- * ```
74
- */
75
- export declare function safeParse<T>(schema: ZodType<T, ZodTypeDef, unknown> | AnySchema, data: unknown): SafeParseResult<T>;
76
- /**
77
- * @deprecated Use `safeParse` instead. This alias will be removed in v1.0.
78
- */
79
- export declare const safeValidate: typeof safeParse;
80
- /**
81
- * Creates a reusable validator function from a schema
82
- *
83
- * @template TOutput - The validated output type
84
- * @template TInput - The input type (defaults to unknown)
85
- * @param schema - Zod schema for validation
86
- * @returns Object with parse and safeParse methods
87
- *
88
- * @example
89
- * ```typescript
90
- * const userValidator = createValidator(UserSchema);
91
- *
92
- * // In a handler
93
- * const user = userValidator.parse(request.body);
94
- * ```
95
- */
96
- export declare function createValidator<TOutput, TInput = unknown>(schema: ZodType<TOutput, ZodTypeDef, TInput>): Validator<TOutput>;
97
- /**
98
- * Validator interface for type-safe validation
99
- */
100
- export interface Validator<T> {
101
- /** Parses data, throwing ValidationError on failure */
102
- parse(data: unknown): T;
103
- /** Safely parses data without throwing */
104
- safeParse(data: unknown): SafeParseResult<T>;
105
- /** @deprecated Use `parse` instead */
106
- validate(data: unknown): T;
107
- /** @deprecated Use `safeParse` instead */
108
- safeValidate(data: unknown): SafeParseResult<T>;
109
- /** The underlying Zod schema */
110
- schema: AnyZodSchema;
111
- }
112
- /**
113
- * Parses multiple data sources at once
114
- *
115
- * Useful for validating body, query, and params together.
116
- *
117
- * @param validations - Object mapping names to schema/data pairs
118
- * @returns Object with validated data for each key
119
- * @throws ValidationError with combined errors if any validation fails
120
- *
121
- * @example
122
- * ```typescript
123
- * const { body, query, params } = parseAll({
124
- * body: [CreateUserSchema, request.body],
125
- * query: [PaginationSchema, request.query],
126
- * params: [IdParamSchema, request.params],
127
- * });
128
- * ```
129
- */
130
- export declare function parseAll<T extends Record<string, [AnyZodSchema, unknown]>>(validations: T): {
131
- [K in keyof T]: T[K][0] extends ZodType<infer O, ZodTypeDef, unknown> ? O : never;
132
- };
133
- /**
134
- * @deprecated Use `parseAll` instead. This alias will be removed in v1.0.
135
- */
136
- export declare const validateAll: typeof parseAll;
137
- /**
138
- * Creates a type guard from a Zod schema
139
- *
140
- * @template T - The validated type
141
- * @param schema - Zod schema to use for checking
142
- * @returns Type predicate function
143
- *
144
- * @example
145
- * ```typescript
146
- * const isUser = createTypeGuard(UserSchema);
147
- *
148
- * if (isUser(data)) {
149
- * // data is typed as User
150
- * console.log(data.name);
151
- * }
152
- * ```
153
- */
154
- export declare function createTypeGuard<T>(schema: ZodType<T, ZodTypeDef, unknown>): (value: unknown) => value is T;
155
- /**
156
- * Asserts that a value matches a schema, narrowing the type
157
- *
158
- * @template T - The validated type
159
- * @param schema - Zod schema to validate against
160
- * @param value - Value to assert
161
- * @param errorMessage - Optional custom error message
162
- * @throws ValidationError if assertion fails
163
- *
164
- * @example
165
- * ```typescript
166
- * function processUser(data: unknown) {
167
- * assertSchema(UserSchema, data);
168
- * // data is now typed as User
169
- * console.log(data.name);
170
- * }
171
- * ```
172
- */
173
- export declare function assertSchema<T>(schema: ZodType<T, ZodTypeDef, unknown>, value: unknown, errorMessage?: string): asserts value is T;
174
- //# sourceMappingURL=middleware.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACh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leware for VeloxTS procedures and routes
3
- *
4
- * Provides middleware utilities for validating request data
5
- * with proper error handling and type inference.
6
- *
7
- * @module middleware
8
- */
9
- import { ValidationError } from '@veloxts/core';
10
- import { ZodError } from 'zod';
11
- import { isSchema, isZodSchema } from './types.js';
12
- // ============================================================================
13
- // Error Transformation
14
- // ============================================================================
15
- /**
16
- * Transforms Zod validation issues into a field-error map
17
- *
18
- * @param issues - Array of Zod validation issues
19
- * @returns Record mapping field paths to error messages
20
- */
21
- export function formatZodErrors(issues) {
22
- const fields = {};
23
- for (const issue of issues) {
24
- const path = issue.path.join('.') || '_root';
25
- // Only keep the first error for each field
26
- if (!(path in fields)) {
27
- fields[path] = issue.message;
28
- }
29
- }
30
- return fields;
31
- }
32
- /**
33
- * Transforms a ZodError into a VeloxTSValidationError
34
- *
35
- * @param error - ZodError from failed validation
36
- * @param customMessage - Optional custom error message
37
- * @returns ValidationError with field-specific errors
38
- */
39
- export function zodErrorToValidationError(error, customMessage) {
40
- const fields = formatZodErrors(error.issues);
41
- const message = customMessage ?? 'Validation failed';
42
- return new ValidationError(message, fields);
43
- }
44
- // ============================================================================
45
- // Validation Functions
46
- // ============================================================================
47
- /**
48
- * Parses and validates data against a schema, throwing ValidationError on failure
49
- *
50
- * Follows Zod's naming convention for consistency with the ecosystem.
51
- *
52
- * @template T - The validated output type
53
- * @param schema - Zod schema or Schema wrapper
54
- * @param data - Data to validate
55
- * @param errorMessage - Optional custom error message
56
- * @returns Validated data with proper type
57
- * @throws ValidationError if validation fails
58
- *
59
- * @example
60
- * ```typescript
61
- * const UserSchema = z.object({ name: z.string(), email: z.string().email() });
62
- *
63
- * const user = parse(UserSchema, request.body);
64
- * // user is typed as { name: string; email: string }
65
- * ```
66
- */
67
- export function parse(schema, data, errorMessage) {
68
- try {
69
- if (isSchema(schema)) {
70
- const result = schema.safeParse(data);
71
- if (result.success) {
72
- return result.data;
73
- }
74
- throw new ValidationError(errorMessage ?? 'Validation failed', formatZodErrors(result.error));
75
- }
76
- if (isZodSchema(schema)) {
77
- return schema.parse(data);
78
- }
79
- throw new Error('Invalid schema provided to parse()');
80
- }
81
- catch (error) {
82
- if (error instanceof ValidationError) {
83
- throw error;
84
- }
85
- if (error instanceof ZodError) {
86
- throw zodErrorToValidationError(error, errorMessage);
87
- }
88
- throw error;
89
- }
90
- }
91
- /**
92
- * @deprecated Use `parse` instead. This alias will be removed in v1.0.
93
- */
94
- export const validate = parse;
95
- /**
96
- * Safely parses data without throwing
97
- *
98
- * Follows Zod's naming convention for consistency with the ecosystem.
99
- *
100
- * @template T - The validated output type
101
- * @param schema - Zod schema or Schema wrapper
102
- * @param data - Data to validate
103
- * @returns Safe parse result with success discriminator
104
- *
105
- * @example
106
- * ```typescript
107
- * const result = safeParse(UserSchema, request.body);
108
- * if (result.success) {
109
- * console.log(result.data.name);
110
- * } else {
111
- * console.log(result.error);
112
- * }
113
- * ```
114
- */
115
- export function safeParse(schema, data) {
116
- if (isSchema(schema)) {
117
- return schema.safeParse(data);
118
- }
119
- if (isZodSchema(schema)) {
120
- const zodSchema = schema;
121
- const result = zodSchema.safeParse(data);
122
- if (result.success) {
123
- return { success: true, data: result.data };
124
- }
125
- return {
126
- success: false,
127
- error: result.error.issues.map((issue) => ({
128
- path: issue.path,
129
- message: issue.message,
130
- code: issue.code,
131
- })),
132
- };
133
- }
134
- return {
135
- success: false,
136
- error: [{ path: [], message: 'Invalid schema provided', code: 'custom' }],
137
- };
138
- }
139
- /**
140
- * @deprecated Use `safeParse` instead. This alias will be removed in v1.0.
141
- */
142
- export const safeValidate = safeParse;
143
- // ============================================================================
144
- // Schema Validators
145
- // ============================================================================
146
- /**
147
- * Creates a reusable validator function from a schema
148
- *
149
- * @template TOutput - The validated output type
150
- * @template TInput - The input type (defaults to unknown)
151
- * @param schema - Zod schema for validation
152
- * @returns Object with parse and safeParse methods
153
- *
154
- * @example
155
- * ```typescript
156
- * const userValidator = createValidator(UserSchema);
157
- *
158
- * // In a handler
159
- * const user = userValidator.parse(request.body);
160
- * ```
161
- */
162
- export function createValidator(schema) {
163
- return {
164
- parse(data) {
165
- return parse(schema, data);
166
- },
167
- safeParse(data) {
168
- return safeParse(schema, data);
169
- },
170
- // Deprecated aliases
171
- validate(data) {
172
- return parse(schema, data);
173
- },
174
- safeValidate(data) {
175
- return safeParse(schema, data);
176
- },
177
- schema,
178
- };
179
- }
180
- // ============================================================================
181
- // Request Validation Helpers
182
- // ============================================================================
183
- /**
184
- * Parses multiple data sources at once
185
- *
186
- * Useful for validating body, query, and params together.
187
- *
188
- * @param validations - Object mapping names to schema/data pairs
189
- * @returns Object with validated data for each key
190
- * @throws ValidationError with combined errors if any validation fails
191
- *
192
- * @example
193
- * ```typescript
194
- * const { body, query, params } = parseAll({
195
- * body: [CreateUserSchema, request.body],
196
- * query: [PaginationSchema, request.query],
197
- * params: [IdParamSchema, request.params],
198
- * });
199
- * ```
200
- */
201
- export function parseAll(validations) {
202
- const results = {};
203
- const allErrors = {};
204
- for (const [key, [schema, data]] of Object.entries(validations)) {
205
- const result = safeParse(schema, data);
206
- if (result.success) {
207
- results[key] = result.data;
208
- }
209
- else {
210
- for (const issue of result.error) {
211
- const path = issue.path.length > 0 ? `${key}.${issue.path.join('.')}` : key;
212
- if (!(path in allErrors)) {
213
- allErrors[path] = issue.message;
214
- }
215
- }
216
- }
217
- }
218
- if (Object.keys(allErrors).length > 0) {
219
- throw new ValidationError('Validation failed', allErrors);
220
- }
221
- return results;
222
- }
223
- /**
224
- * @deprecated Use `parseAll` instead. This alias will be removed in v1.0.
225
- */
226
- export const validateAll = parseAll;
227
- // ============================================================================
228
- // Type Guards
229
- // ============================================================================
230
- /**
231
- * Creates a type guard from a Zod schema
232
- *
233
- * @template T - The validated type
234
- * @param schema - Zod schema to use for checking
235
- * @returns Type predicate function
236
- *
237
- * @example
238
- * ```typescript
239
- * const isUser = createTypeGuard(UserSchema);
240
- *
241
- * if (isUser(data)) {
242
- * // data is typed as User
243
- * console.log(data.name);
244
- * }
245
- * ```
246
- */
247
- export function createTypeGuard(schema) {
248
- return (value) => {
249
- const result = schema.safeParse(value);
250
- return result.success;
251
- };
252
- }
253
- /**
254
- * Asserts that a value matches a schema, narrowing the type
255
- *
256
- * @template T - The validated type
257
- * @param schema - Zod schema to validate against
258
- * @param value - Value to assert
259
- * @param errorMessage - Optional custom error message
260
- * @throws ValidationError if assertion fails
261
- *
262
- * @example
263
- * ```typescript
264
- * function processUser(data: unknown) {
265
- * assertSchema(UserSchema, data);
266
- * // data is now typed as User
267
- * console.log(data.name);
268
- * }
269
- * ```
270
- */
271
- export function assertSchema(schema, value, errorMessage) {
272
- validate(schema, value, errorMessage);
273
- }
274
- //# sourceMappingURL=middleware.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAiC,MAAM,KAAK,CAAC;AAG9D,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEnD,+EAA+E;AAC/E,uBAAuB;AACvB,+EAA+E;AAE/E;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAC7B,MAA0E;IAE1E,MAAM,MAAM,GAA2B,EAAE,CAAC;IAE1C,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC;QAC7C,2CAA2C;QAC3C,IAAI,CAAC,CAAC,IAAI,IAAI,MAAM,CAAC,EAAE,CAAC;YACtB,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC;QAC/B,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CACvC,KAAe,EACf,aA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