UNPKG

veffect

Version:

powerful TypeScript validation library built on the robust foundation of Effect combining exceptional type safety, high performance, and developer experience. Taking inspiration from Effect's functional principles, VEffect delivers a balanced approach tha

264 lines (263 loc) 13.2 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.interface_ = interface_; exports.interface = interface_; /** * Interface schema implementation - inspired by Zod 4's approach but with Effect style * This allows more precise control over key vs value optionality and supports recursive types */ const E = __importStar(require("../internal/effect")); const EffectMod = __importStar(require("effect/Effect")); const validator_1 = require("../validator"); const errors_1 = require("../errors"); /** * Create an interface schema with explicit control over key optionality * Keys with a ? suffix are treated as optional keys (not values) * * @example * ```ts * // Key optional (property can be omitted) * const userSchema = interface({ * "name?": string(), * age: number() * }); * // type is { name?: string; age: number } * * // Value optional (property must exist but can be undefined) * const configSchema = interface({ * name: string(), * timeout: number().optional() * }); * // type is { name: string; timeout: number | undefined } * ``` */ function interface_(properties) { const schema = { _tag: 'InterfaceSchema', properties, // Refinement implementation refine: (refinement, message) => { return { ...schema, toValidator: () => (0, validator_1.createEffectValidator)((input, options) => { const baseValidator = schema.toValidator(); return E.pipe(baseValidator.validate(input, options), E.flatMap(value => { try { const result = refinement(value); if (result instanceof Promise) { // For async refinements, we'll create a handler for them return EffectMod.tryPromise({ try: async () => { try { const passes = await result; if (passes) { return value; } else { throw new errors_1.CustomValidationError(typeof message === 'function' ? message(value) : message || 'Failed refinement', options === null || options === void 0 ? void 0 : options.path); } } catch (error) { if (error && typeof error === 'object' && '_tag' in error) { throw error; // Already ValidationError } throw new errors_1.CustomValidationError(error instanceof Error ? error.message : 'Error in async refinement', options === null || options === void 0 ? void 0 : options.path); } }, catch: (error) => { if (error && typeof error === 'object' && '_tag' in error) { return error; } return new errors_1.CustomValidationError(error instanceof Error ? error.message : 'Error in async refinement', options === null || options === void 0 ? void 0 : options.path); } }); } // For synchronous refinements return result ? E.succeed(value) : E.fail(new errors_1.CustomValidationError(typeof message === 'function' ? message(value) : message || 'Failed refinement', options === null || options === void 0 ? void 0 : options.path)); } catch (error) { if (error && typeof error === 'object' && '_tag' in error) { return E.fail(error); } return E.fail(new errors_1.CustomValidationError(error instanceof Error ? error.message : 'Error in refinement', options === null || options === void 0 ? void 0 : options.path)); } })); }) }; }, // Transform implementation transform: (transformer) => { return { _tag: 'TransformedSchema', toValidator: () => (0, validator_1.createEffectValidator)((input, options) => { return E.pipe(schema.toValidator().validate(input, options), E.map(value => transformer(value))); }) }; }, // Default value implementation default: (defaultValue) => { return { ...schema, toValidator: () => (0, validator_1.createEffectValidator)((input, options) => { if (input === undefined) { const value = typeof defaultValue === 'function' ? defaultValue() : defaultValue; return E.succeed(value); } return schema.toValidator().validate(input, options); }) }; }, // Nullable implementation nullable: () => { return { ...schema, toValidator: () => (0, validator_1.createEffectValidator)((input, options) => { if (input === null) { return E.succeed(null); } return schema.toValidator().validate(input, options); }) }; }, // Optional implementation optional: () => { return { _tag: 'OptionalSchema', toValidator: () => (0, validator_1.createEffectValidator)((input, options) => { if (input === undefined) { return E.succeed(undefined); } return schema.toValidator().validate(input, options); }) }; }, // Nullish implementation nullish: () => { return { _tag: 'NullishSchema', toValidator: () => (0, validator_1.createEffectValidator)((input, options) => { if (input === null || input === undefined) { return E.succeed(input); } return schema.toValidator().validate(input, options); }) }; }, toValidator: () => (0, validator_1.createEffectValidator)((input, options) => { if (typeof input !== 'object' || input === null || Array.isArray(input)) { return E.fail(new errors_1.TypeValidationError('Value must be an object', 'object', typeof input, options === null || options === void 0 ? void 0 : options.path)); } // Process keys and identify which ones are optional const requiredProperties = {}; const optionalProperties = {}; // First pass: categorize properties as required or optional for (const key in properties) { if (Object.prototype.hasOwnProperty.call(properties, key)) { // The key is optional if it ends with ? and is not a literal key containing ? // (In a literal key with a ?, the ? would need to be escaped as \?) if (key.endsWith('?')) { // Check if this is an optional property marker or just a key with ? in it // We determine this based on if the property name ends with ? but doesn't have a literal ? // in the property name (which would be escaped as \?) // This logic treats "name?" as optional property "name" // But treats "exists\?" as required property "exists?" // If the ? is escaped with a \, it's a literal ? in the key name const isLiteralQuestionMark = key.length > 1 && key[key.length - 2] === '\\'; if (!isLiteralQuestionMark) { // This is a key with optional property marker const baseKey = key.slice(0, -1); // Remove trailing ? optionalProperties[baseKey] = properties[key]; } else { // This is a key with a literal ? in the name const actualKey = key.slice(0, -2) + '?'; // Replace \? with ? requiredProperties[actualKey] = properties[key]; } } else { // This is a regular required property requiredProperties[key] = properties[key]; } } } // Check for missing required properties const missingKeys = []; for (const key in requiredProperties) { if (!(key in input)) { missingKeys.push(key); } } if (missingKeys.length > 0) { return E.fail(new errors_1.ObjectValidationError(`Missing required properties: ${missingKeys.join(', ')}`, missingKeys.map(key => ({ _tag: 'MissingPropertyError', message: `Missing required property: ${key}`, path: (options === null || options === void 0 ? void 0 : options.path) ? [...options.path, key] : [key], })), options === null || options === void 0 ? void 0 : options.path)); } const validationResults = []; // Validate required properties for (const key in requiredProperties) { const path = (options === null || options === void 0 ? void 0 : options.path) ? [...options.path, key] : [key]; const validator = requiredProperties[key].toValidator(); validationResults.push(E.map(validator.validate(input[key], { ...options, path }), validValue => [key, validValue])); } // Validate optional properties if present for (const key in optionalProperties) { if (key in input) { const path = (options === null || options === void 0 ? void 0 : options.path) ? [...options.path, key] : [key]; const validator = optionalProperties[key].toValidator(); validationResults.push(E.map(validator.validate(input[key], { ...options, path }), validValue => [key, validValue])); } } return E.pipe(E.all(validationResults, { concurrency: (options === null || options === void 0 ? void 0 : options.stopOnFirstError) ? 1 : 'unbounded' }), E.map(entries => { const result = {}; for (const [key, value] of entries) { result[key] = value; } return result; })); }) }; return schema; }