UNPKG

@dexwox-labs/a2a-core

Version:

Core types, validation and telemetry for Google's Agent-to-Agent (A2A) protocol - shared foundation for client and server implementations

406 lines 13.2 kB
/** * @module Validators * @description Schema validation utilities for A2A protocol types * * This module provides schema definitions and validation functions for the A2A protocol. * It uses Zod for runtime type validation and provides helper functions for validating * various protocol objects. */ import { z } from 'zod'; import { type TaskTransition, type Message, type MessageSendConfiguration, type Task, type AgentCard, type PushNotificationConfig, type DiscoverRequest, type DiscoverResponse } from '../types/a2a-protocol'; /** * Validation functions for A2A protocol objects * * These functions validate objects against their respective schemas and return * a SafeParseReturnType that includes either the validated data or validation errors. */ /** * Validates a message object against the Message schema * * @param data - The data to validate * @returns A SafeParseReturnType containing either the validated Message or validation errors * * @example * ```typescript * const result = validateMessage({ * parts: [{ type: 'text', content: 'Hello, world!' }] * }); * * if (result.success) { * // Use the validated message * console.log('Valid message:', result.data); * } else { * // Handle validation errors * console.error('Invalid message:', result.error); * } * ``` */ export declare const validateMessage: (data: unknown) => z.SafeParseReturnType<unknown, Message>; /** * Validates a task object against the Task schema * * @param data - The data to validate * @returns A SafeParseReturnType containing either the validated Task or validation errors * * @example * ```typescript * const result = validateTask({ * id: '123e4567-e89b-12d3-a456-426614174000', * name: 'Process Data', * status: 'submitted', * createdAt: new Date().toISOString(), * updatedAt: new Date().toISOString() * }); * * if (result.success) { * // Use the validated task * console.log('Valid task:', result.data); * } else { * // Handle validation errors * console.error('Invalid task:', result.error); * } * ``` */ export declare const validateTask: (data: unknown) => z.SafeParseReturnType<unknown, Task>; /** * Validates an agent card object against the AgentCard schema * * @param data - The data to validate * @returns A SafeParseReturnType containing either the validated AgentCard or validation errors * * @example * ```typescript * const result = validateAgentCard({ * id: '123e4567-e89b-12d3-a456-426614174000', * name: 'Weather Agent', * capabilities: ['weather-forecasting', 'location-search'], * endpoint: 'https://example.com/agents/weather' * }); * * if (result.success) { * // Use the validated agent card * console.log('Valid agent card:', result.data); * } else { * // Handle validation errors * console.error('Invalid agent card:', result.error); * } * ``` */ export declare const validateAgentCard: (data: unknown) => z.SafeParseReturnType<unknown, AgentCard>; /** * Validates a push notification configuration against the PushNotificationConfig schema * * @param data - The data to validate * @returns A SafeParseReturnType containing either the validated PushNotificationConfig or validation errors * * @example * ```typescript * const result = validatePushNotificationConfig({ * enabled: true, * endpoint: 'https://example.com/webhooks/a2a', * authToken: 'secret-token', * events: ['taskCompleted', 'taskFailed'] * }); * * if (result.success) { * // Use the validated config * console.log('Valid push config:', result.data); * } else { * // Handle validation errors * console.error('Invalid push config:', result.error); * } * ``` */ export declare const validatePushNotificationConfig: (data: unknown) => z.SafeParseReturnType<unknown, PushNotificationConfig>; /** * Validates a discover request against the DiscoverRequest schema * * @param data - The data to validate * @returns A SafeParseReturnType containing either the validated DiscoverRequest or validation errors * * @example * ```typescript * const result = validateDiscoverRequest({ * id: '1', * method: 'discover', * params: { capability: 'weather-forecasting' }, * jsonrpc: '2.0' * }); * * if (result.success) { * // Use the validated request * console.log('Valid discover request:', result.data); * } else { * // Handle validation errors * console.error('Invalid discover request:', result.error); * } * ``` */ export declare const validateDiscoverRequest: (data: unknown) => z.SafeParseReturnType<unknown, DiscoverRequest>; /** * Validates a discover response against the DiscoverResponse schema * * @param data - The data to validate * @returns A SafeParseReturnType containing either the validated DiscoverResponse or validation errors * * @example * ```typescript * const result = validateDiscoverResponse({ * id: '1', * result: [ * { * id: '123e4567-e89b-12d3-a456-426614174000', * name: 'Weather Agent', * capabilities: ['weather-forecasting'], * endpoint: 'https://example.com/agents/weather' * } * ] * }); * * if (result.success) { * // Use the validated response * console.log('Valid discover response:', result.data); * } else { * // Handle validation errors * console.error('Invalid discover response:', result.error); * } * ``` */ export declare const validateDiscoverResponse: (data: unknown) => z.SafeParseReturnType<unknown, DiscoverResponse>; /** * Type guards for A2A protocol objects * * These functions check if an object conforms to a specific schema and narrow * its type if it does. They return a boolean indicating whether the object is * of the specified type. */ /** * Checks if the provided data is a valid Message * * @param data - The data to check * @returns True if the data is a valid Message, false otherwise * * @example * ```typescript * const data = { parts: [{ type: 'text', content: 'Hello' }] }; * * if (isMessage(data)) { * // TypeScript now knows that data is a Message * console.log('Message parts:', data.parts.length); * } * ``` */ export declare const isMessage: (data: unknown) => data is Message; /** * Checks if the provided data is a valid Task * * @param data - The data to check * @returns True if the data is a valid Task, false otherwise * * @example * ```typescript * const data = getTaskFromSomewhere(); * * if (isTask(data)) { * // TypeScript now knows that data is a Task * console.log('Task status:', data.status); * } * ``` */ export declare const isTask: (data: unknown) => data is Task; /** * Checks if the provided data is a valid AgentCard * * @param data - The data to check * @returns True if the data is a valid AgentCard, false otherwise * * @example * ```typescript * const data = getAgentFromSomewhere(); * * if (isAgentCard(data)) { * // TypeScript now knows that data is an AgentCard * console.log('Agent capabilities:', data.capabilities); * } * ``` */ export declare const isAgentCard: (data: unknown) => data is AgentCard; /** * Checks if the provided data is a valid PushNotificationConfig * * @param data - The data to check * @returns True if the data is a valid PushNotificationConfig, false otherwise * * @example * ```typescript * const data = getConfigFromSomewhere(); * * if (isPushNotificationConfig(data)) { * // TypeScript now knows that data is a PushNotificationConfig * console.log('Push notifications enabled:', data.enabled); * } * ``` */ export declare const isPushNotificationConfig: (data: unknown) => data is PushNotificationConfig; /** * Formats a Zod validation error into a human-readable string * * This function takes a Zod error object and converts it into a string * representation, with each issue formatted as "path: message" and joined * with semicolons. * * @param error - The Zod error to format * @returns A formatted error string * * @example * ```typescript * const result = validateTask(invalidTask); * * if (!result.success) { * const errorMessage = formatValidationError(result.error); * console.error('Validation failed:', errorMessage); * // Example output: "name: Required; status: Invalid enum value" * } * ``` */ export declare function formatValidationError(error: z.ZodError): string; /** * Decorator for validating method parameters against a schema * * This decorator can be applied to methods to automatically validate their * first parameter against the provided schema. If validation fails, an error * is thrown with details about the validation issues. * * @param schema - The Zod schema to validate against * @returns A method decorator function * * @example * ```typescript * class MessageService { * @validate(MessageSchema) * sendMessage(message: Message) { * // This code only runs if message passes validation * console.log('Sending message:', message); * } * } * * const service = new MessageService(); * * // This will throw an error because the message is invalid * service.sendMessage({ invalid: 'data' }); * ``` */ export declare function validate<T extends z.ZodTypeAny>(schema: T): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor; /** * Collection of all schema definitions for A2A protocol objects * * This object provides access to all the Zod schemas defined in this module, * allowing them to be used directly for validation or type inference. * * @example * ```typescript * // Use a schema directly for validation * const result = schemas.Message.safeParse(data); * * // Create a type from a schema * type MessageType = z.infer<typeof schemas.Message>; * ``` */ export declare const schemas: { Message: z.ZodType<Message, z.ZodTypeDef, Message>; Task: z.ZodType<Task, z.ZodTypeDef, Task>; AgentCard: z.ZodType<AgentCard, z.ZodTypeDef, AgentCard>; PushNotificationConfig: z.ZodType<PushNotificationConfig, z.ZodTypeDef, PushNotificationConfig>; DiscoverRequest: z.ZodType<DiscoverRequest, z.ZodTypeDef, DiscoverRequest>; DiscoverResponse: z.ZodType<DiscoverResponse, z.ZodTypeDef, DiscoverResponse>; MessagePart: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{ type: z.ZodLiteral<"text">; content: z.ZodString; format: z.ZodDefault<z.ZodEnum<["plain", "markdown"]>>; }, "strip", z.ZodTypeAny, { type: "text"; content: string; format: "plain" | "markdown"; }, { type: "text"; content: string; format?: "plain" | "markdown" | undefined; }>, z.ZodObject<{ type: z.ZodLiteral<"file">; content: z.ZodUnion<[z.ZodString, z.ZodType<Uint8Array<ArrayBuffer>, z.ZodTypeDef, Uint8Array<ArrayBuffer>>]>; mimeType: z.ZodString; name: z.ZodString; size: z.ZodOptional<z.ZodNumber>; }, "strip", z.ZodTypeAny, { type: "file"; content: string | Uint8Array<ArrayBuffer>; mimeType: string; name: string; size?: number | undefined; }, { type: "file"; content: string | Uint8Array<ArrayBuffer>; mimeType: string; name: string; size?: number | undefined; }>, z.ZodObject<{ type: z.ZodLiteral<"data">; content: z.ZodRecord<z.ZodString, z.ZodAny>; schema: z.ZodOptional<z.ZodString>; }, "strip", z.ZodTypeAny, { type: "data"; content: Record<string, any>; schema?: string | undefined; }, { type: "data"; content: Record<string, any>; schema?: string | undefined; }>, z.ZodObject<{ type: z.ZodLiteral<"heartbeat">; content: z.ZodString; format: z.ZodDefault<z.ZodLiteral<"plain">>; }, "strip", z.ZodTypeAny, { type: "heartbeat"; content: string; format: "plain"; }, { type: "heartbeat"; content: string; format?: "plain" | undefined; }>]>; Artifact: z.ZodObject<{ id: z.ZodString; type: z.ZodEnum<["text", "file", "data"]>; content: z.ZodRecord<z.ZodString, z.ZodAny>; createdAt: z.ZodString; updatedAt: z.ZodString; }, "strip", z.ZodTypeAny, { type: "data" | "text" | "file"; id: string; content: Record<string, any>; createdAt: string; updatedAt: string; }, { type: "data" | "text" | "file"; id: string; content: Record<string, any>; createdAt: string; updatedAt: string; }>; A2AError: z.ZodObject<{ code: z.ZodNumber; message: z.ZodString; data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>; }, "strip", z.ZodTypeAny, { code: number; message: string; data?: Record<string, any> | undefined; }, { code: number; message: string; data?: Record<string, any> | undefined; }>; TaskTransition: z.ZodType<TaskTransition, z.ZodTypeDef, TaskTransition>; MessageSendConfiguration: z.ZodType<MessageSendConfiguration, z.ZodTypeDef, MessageSendConfiguration>; }; //# sourceMappingURL=validators.d.ts.map