alepha 0.20.4 → 0.20.6
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/dist/api/audits/index.d.ts +391 -359
- package/dist/api/audits/index.d.ts.map +1 -1
- package/dist/api/audits/index.js +23 -1
- package/dist/api/audits/index.js.map +1 -1
- package/dist/api/files/index.d.ts +18 -0
- package/dist/api/files/index.d.ts.map +1 -1
- package/dist/api/files/index.js +51 -0
- package/dist/api/files/index.js.map +1 -1
- package/dist/api/jobs/index.browser.js +33 -14
- package/dist/api/jobs/index.browser.js.map +1 -1
- package/dist/api/jobs/index.d.ts +452 -155
- package/dist/api/jobs/index.d.ts.map +1 -1
- package/dist/api/jobs/index.js +474 -159
- package/dist/api/jobs/index.js.map +1 -1
- package/dist/api/keys/index.d.ts +32 -4
- package/dist/api/keys/index.d.ts.map +1 -1
- package/dist/api/keys/index.js +53 -0
- package/dist/api/keys/index.js.map +1 -1
- package/dist/api/notifications/index.d.ts +29 -1
- package/dist/api/notifications/index.d.ts.map +1 -1
- package/dist/api/notifications/index.js +55 -13
- package/dist/api/notifications/index.js.map +1 -1
- package/dist/api/organizations/index.js.map +1 -1
- package/dist/api/parameters/index.d.ts +15 -0
- package/dist/api/parameters/index.d.ts.map +1 -1
- package/dist/api/parameters/index.js +37 -0
- package/dist/api/parameters/index.js.map +1 -1
- package/dist/api/payments/index.js.map +1 -1
- package/dist/api/users/index.d.ts +150 -9
- package/dist/api/users/index.d.ts.map +1 -1
- package/dist/api/users/index.js +237 -28
- package/dist/api/users/index.js.map +1 -1
- package/dist/api/verifications/index.d.ts +3 -3
- package/dist/api/verifications/index.js.map +1 -1
- package/dist/batch/index.js.map +1 -1
- package/dist/bin/index.js +0 -0
- package/dist/bucket/index.d.ts +18 -0
- package/dist/bucket/index.d.ts.map +1 -1
- package/dist/bucket/index.js +47 -0
- package/dist/bucket/index.js.map +1 -1
- package/dist/bucket/index.workerd.js +24 -0
- package/dist/bucket/index.workerd.js.map +1 -1
- package/dist/cache/core/index.d.ts +20 -3
- package/dist/cache/core/index.d.ts.map +1 -1
- package/dist/cache/core/index.js.map +1 -1
- package/dist/cache/core/index.workerd.js.map +1 -1
- package/dist/cache/database/index.d.ts +155 -0
- package/dist/cache/database/index.d.ts.map +1 -0
- package/dist/cache/database/index.js +266 -0
- package/dist/cache/database/index.js.map +1 -0
- package/dist/cache/redis/index.js.map +1 -1
- package/dist/captcha/index.js.map +1 -1
- package/dist/cli/config/index.js.map +1 -1
- package/dist/cli/core/index.d.ts +35 -5
- package/dist/cli/core/index.d.ts.map +1 -1
- package/dist/cli/core/index.js +85 -6
- package/dist/cli/core/index.js.map +1 -1
- package/dist/cli/devtools/index.js.map +1 -1
- package/dist/cli/platform/index.js +1 -1
- package/dist/cli/platform/index.js.map +1 -1
- package/dist/cli/vendor/index.js.map +1 -1
- package/dist/command/index.js.map +1 -1
- package/dist/core/index.browser.js.map +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.native.js.map +1 -1
- package/dist/core/index.workerd.js.map +1 -1
- package/dist/crypto/index.browser.js.map +1 -1
- package/dist/crypto/index.js.map +1 -1
- package/dist/datetime/index.js.map +1 -1
- package/dist/email/brevo/index.js.map +1 -1
- package/dist/email/core/index.js.map +1 -1
- package/dist/email/core/index.workerd.js.map +1 -1
- package/dist/email/smtp/index.js.map +1 -1
- package/dist/fake/index.js.map +1 -1
- package/dist/lock/core/index.js.map +1 -1
- package/dist/lock/redis/index.js.map +1 -1
- package/dist/logger/index.js.map +1 -1
- package/dist/mcp/index.js.map +1 -1
- package/dist/orm/core/index.browser.js.map +1 -1
- package/dist/orm/core/index.bun.js.map +1 -1
- package/dist/orm/core/index.js.map +1 -1
- package/dist/orm/postgres/index.bun.js.map +1 -1
- package/dist/orm/postgres/index.js.map +1 -1
- package/dist/queue/core/index.js.map +1 -1
- package/dist/queue/core/index.workerd.js.map +1 -1
- package/dist/queue/redis/index.js.map +1 -1
- package/dist/react/auth/index.browser.js.map +1 -1
- package/dist/react/auth/index.js.map +1 -1
- package/dist/react/core/index.js.map +1 -1
- package/dist/react/form/index.js +2 -0
- package/dist/react/form/index.js.map +1 -1
- package/dist/react/head/index.browser.js.map +1 -1
- package/dist/react/head/index.js.map +1 -1
- package/dist/react/i18n/index.js.map +1 -1
- package/dist/react/intro/index.js.map +1 -1
- package/dist/react/router/index.browser.js.map +1 -1
- package/dist/react/router/index.js.map +1 -1
- package/dist/react/testing/index.js.map +1 -1
- package/dist/react/ui/index.js.map +1 -1
- package/dist/react/websocket/index.js.map +1 -1
- package/dist/redis/index.bun.js.map +1 -1
- package/dist/redis/index.js.map +1 -1
- package/dist/retry/index.js.map +1 -1
- package/dist/router/index.js.map +1 -1
- package/dist/scheduler/index.d.ts +22 -0
- package/dist/scheduler/index.d.ts.map +1 -1
- package/dist/scheduler/index.js +12 -0
- package/dist/scheduler/index.js.map +1 -1
- package/dist/scheduler/index.workerd.js +12 -0
- package/dist/scheduler/index.workerd.js.map +1 -1
- package/dist/security/index.browser.js.map +1 -1
- package/dist/security/index.js.map +1 -1
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/cookies/index.browser.js.map +1 -1
- package/dist/server/cookies/index.js.map +1 -1
- package/dist/server/core/index.browser.js.map +1 -1
- package/dist/server/core/index.js.map +1 -1
- package/dist/server/cors/index.js.map +1 -1
- package/dist/server/etag/index.js.map +1 -1
- package/dist/server/health/index.js.map +1 -1
- package/dist/server/links/index.browser.js.map +1 -1
- package/dist/server/links/index.js.map +1 -1
- package/dist/server/metrics/index.js.map +1 -1
- package/dist/server/proxy/index.js.map +1 -1
- package/dist/server/rate-limit/index.js.map +1 -1
- package/dist/server/static/index.js.map +1 -1
- package/dist/server/swagger/index.js.map +1 -1
- package/dist/sms/index.js.map +1 -1
- package/dist/system/index.browser.js.map +1 -1
- package/dist/system/index.js.map +1 -1
- package/dist/system/index.workerd.js.map +1 -1
- package/dist/topic/core/index.js.map +1 -1
- package/dist/topic/redis/index.js.map +1 -1
- package/dist/websocket/index.browser.js +4 -0
- package/dist/websocket/index.browser.js.map +1 -1
- package/dist/websocket/index.js +10 -0
- package/dist/websocket/index.js.map +1 -1
- package/package.json +282 -272
- package/src/api/audits/controllers/AdminAuditController.ts +29 -0
- package/src/api/files/controllers/FileController.ts +24 -0
- package/src/api/files/services/FileService.ts +41 -0
- package/src/api/jobs/__tests__/$job.spec.ts +427 -2
- package/src/api/jobs/entities/jobExecutionEntity.ts +3 -3
- package/src/api/jobs/index.ts +47 -10
- package/src/api/jobs/primitives/$job.ts +22 -9
- package/src/api/jobs/providers/DirectJobDispatcher.ts +71 -0
- package/src/api/jobs/providers/JobDispatcher.ts +49 -0
- package/src/api/jobs/providers/JobProvider.ts +365 -142
- package/src/api/jobs/providers/JobQueueProvider.ts +43 -18
- package/src/api/jobs/schemas/jobConfigAtom.ts +4 -3
- package/src/api/jobs/schemas/jobExecutionResourceSchema.ts +11 -0
- package/src/api/jobs/schemas/jobRegistrationSchema.ts +4 -2
- package/src/api/jobs/services/JobService.ts +21 -11
- package/src/api/keys/controllers/AdminApiKeyController.ts +23 -0
- package/src/api/keys/services/ApiKeyService.ts +42 -0
- package/src/api/notifications/__tests__/AlephaApiNotifications.spec.ts +63 -0
- package/src/api/notifications/controllers/AdminNotificationController.ts +48 -1
- package/src/api/notifications/index.ts +13 -3
- package/src/api/notifications/jobs/NotificationJobs.ts +0 -6
- package/src/api/parameters/controllers/AdminParameterController.ts +26 -0
- package/src/api/parameters/services/ParameterProvider.ts +18 -0
- package/src/api/users/__tests__/Registration-emailMode.spec.ts +203 -0
- package/src/api/users/__tests__/UsernameSlugger.spec.ts +138 -0
- package/src/api/users/atoms/realmAuthSettingsAtom.ts +41 -3
- package/src/api/users/controllers/AdminSessionController.ts +29 -0
- package/src/api/users/controllers/AdminUserController.ts +32 -0
- package/src/api/users/index.ts +3 -0
- package/src/api/users/services/CredentialService.ts +5 -0
- package/src/api/users/services/RegistrationService.ts +49 -1
- package/src/api/users/services/SessionCrudService.ts +16 -0
- package/src/api/users/services/SessionService.ts +17 -59
- package/src/api/users/services/UsernameSlugger.ts +195 -0
- package/src/bucket/primitives/$bucket.ts +21 -0
- package/src/bucket/providers/CloudflareR2Provider.ts +15 -0
- package/src/bucket/providers/FileStorageProvider.ts +9 -0
- package/src/bucket/providers/LocalFileStorageProvider.ts +14 -0
- package/src/bucket/providers/MemoryFileStorageProvider.ts +9 -0
- package/src/bucket/providers/NodeS3BucketProvider.ts +35 -0
- package/src/cache/core/primitives/$cache.ts +20 -3
- package/src/cache/database/__tests__/DatabaseCacheProvider.behavior.spec.ts +203 -0
- package/src/cache/database/__tests__/DatabaseCacheProvider.spec.ts +110 -0
- package/src/cache/database/entities/cacheEntries.ts +55 -0
- package/src/cache/database/index.ts +36 -0
- package/src/cache/database/providers/DatabaseCacheProvider.ts +348 -0
- package/src/cli/core/services/ProjectScaffolder.ts +0 -2
- package/src/cli/core/tasks/BuildCloudflareTask.ts +17 -3
- package/src/cli/core/tasks/BuildSitemapTask.ts +7 -0
- package/src/cli/core/tasks/BuildVercelTask.ts +82 -3
- package/src/cli/platform/__tests__/detectResources.spec.ts +96 -0
- package/src/cli/platform/commands/platform.ts +7 -1
- package/src/scheduler/index.ts +14 -0
- package/src/scheduler/providers/CronProvider.ts +13 -0
package/dist/mcp/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/mcp/helpers/jsonrpc.ts","../../src/mcp/errors/McpError.ts","../../src/mcp/providers/McpServerProvider.ts","../../src/mcp/primitives/$prompt.ts","../../src/mcp/primitives/$resource.ts","../../src/mcp/primitives/$tool.ts","../../src/mcp/transports/StreamableHttpMcpTransport.ts","../../src/mcp/index.ts"],"sourcesContent":["import { AlephaError } from \"alepha\";\nimport type {\n JsonRpcError,\n JsonRpcNotification,\n JsonRpcRequest,\n JsonRpcResponse,\n} from \"../interfaces/McpTypes.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport const JSONRPC_VERSION = \"2.0\" as const;\n\n/**\n * The latest MCP protocol revision Alepha targets.\n * See {@link SUPPORTED_PROTOCOL_VERSIONS} for the full negotiation list.\n */\nexport const MCP_PROTOCOL_VERSION = \"2025-11-25\" as const;\n\n/**\n * Protocol versions Alepha will accept during `initialize` negotiation,\n * highest preference first. The server echoes back whichever version the\n * client requested if it appears here, otherwise picks the first entry.\n */\nexport const SUPPORTED_PROTOCOL_VERSIONS = [\n \"2025-11-25\",\n \"2025-06-18\",\n \"2025-03-26\",\n \"2024-11-05\",\n] as const;\n\nexport type SupportedProtocolVersion =\n (typeof SUPPORTED_PROTOCOL_VERSIONS)[number];\n\nexport const isSupportedProtocolVersion = (\n v: unknown,\n): v is SupportedProtocolVersion =>\n typeof v === \"string\" &&\n (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(v);\n\nexport const JsonRpcErrorCodes = {\n PARSE_ERROR: -32700,\n INVALID_REQUEST: -32600,\n METHOD_NOT_FOUND: -32601,\n INVALID_PARAMS: -32602,\n INTERNAL_ERROR: -32603,\n} as const;\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Response Builders\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function createResponse(\n id: string | number,\n result: unknown,\n): JsonRpcResponse {\n return {\n jsonrpc: JSONRPC_VERSION,\n id,\n result,\n };\n}\n\nexport function createErrorResponse(\n id: string | number,\n error: JsonRpcError,\n): JsonRpcResponse {\n return {\n jsonrpc: JSONRPC_VERSION,\n id,\n error,\n };\n}\n\nexport function createNotification(\n method: string,\n params?: Record<string, unknown>,\n): JsonRpcNotification {\n return {\n jsonrpc: JSONRPC_VERSION,\n method,\n params,\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Error Builders\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function createParseError(message = \"Parse error\"): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.PARSE_ERROR,\n message,\n };\n}\n\nexport function createInvalidRequestError(\n message = \"Invalid request\",\n): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INVALID_REQUEST,\n message,\n };\n}\n\nexport function createMethodNotFoundError(method: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.METHOD_NOT_FOUND,\n message: `Method not found: ${method}`,\n };\n}\n\nexport function createInvalidParamsError(message: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INVALID_PARAMS,\n message,\n };\n}\n\nexport function createInternalError(message: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INTERNAL_ERROR,\n message,\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Message Parsing\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function parseMessage(data: string): JsonRpcRequest {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(data);\n } catch {\n throw new JsonRpcParseError(\"Invalid JSON\");\n }\n\n if (!isValidJsonRpcRequest(parsed)) {\n throw new JsonRpcParseError(\"Invalid JSON-RPC request\");\n }\n\n return parsed;\n}\n\nexport function isValidJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n if (obj.jsonrpc !== JSONRPC_VERSION) {\n return false;\n }\n\n if (typeof obj.method !== \"string\") {\n return false;\n }\n\n if (\n obj.id !== undefined &&\n typeof obj.id !== \"string\" &&\n typeof obj.id !== \"number\"\n ) {\n return false;\n }\n\n if (obj.params !== undefined && typeof obj.params !== \"object\") {\n return false;\n }\n\n return true;\n}\n\nexport function isNotification(request: JsonRpcRequest): boolean {\n return request.id === undefined;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class JsonRpcParseError extends AlephaError {\n name = \"JsonRpcParseError\";\n}\n","import { JsonRpcErrorCodes } from \"../helpers/jsonrpc.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * MCP-specific error codes (application-specific codes in the -32000 to -32099 range).\n */\nexport const McpErrorCodes = {\n UNAUTHORIZED: -32001,\n FORBIDDEN: -32003,\n} as const;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpError extends Error {\n name = \"McpError\";\n code: number;\n\n constructor(\n message: string,\n code: number = JsonRpcErrorCodes.INTERNAL_ERROR,\n ) {\n super(message);\n this.code = code;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpMethodNotFoundError extends McpError {\n name = \"McpMethodNotFoundError\";\n\n constructor(method: string) {\n super(`Method not found: ${method}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpToolNotFoundError extends McpError {\n name = \"McpToolNotFoundError\";\n tool: string;\n\n constructor(tool: string) {\n super(`Tool not found: ${tool}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.tool = tool;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpResourceNotFoundError extends McpError {\n name = \"McpResourceNotFoundError\";\n uri: string;\n\n constructor(uri: string) {\n super(`Resource not found: ${uri}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.uri = uri;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpPromptNotFoundError extends McpError {\n name = \"McpPromptNotFoundError\";\n prompt: string;\n\n constructor(prompt: string) {\n super(`Prompt not found: ${prompt}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.prompt = prompt;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpInvalidParamsError extends McpError {\n name = \"McpInvalidParamsError\";\n\n constructor(message: string) {\n super(message, JsonRpcErrorCodes.INVALID_PARAMS);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpUnauthorizedError extends McpError {\n name = \"McpUnauthorizedError\";\n\n constructor(message = \"Unauthorized\") {\n super(message, McpErrorCodes.UNAUTHORIZED);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpForbiddenError extends McpError {\n name = \"McpForbiddenError\";\n\n constructor(message = \"Forbidden\") {\n super(message, McpErrorCodes.FORBIDDEN);\n }\n}\n","import { $inject, Alepha, TypeBoxError } from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport {\n McpError,\n McpMethodNotFoundError,\n McpPromptNotFoundError,\n McpResourceNotFoundError,\n McpToolNotFoundError,\n} from \"../errors/McpError.ts\";\nimport {\n createErrorResponse,\n createInternalError,\n createResponse,\n isSupportedProtocolVersion,\n MCP_PROTOCOL_VERSION,\n SUPPORTED_PROTOCOL_VERSIONS,\n} from \"../helpers/jsonrpc.ts\";\nimport type {\n JsonRpcRequest,\n JsonRpcResponse,\n McpCapabilities,\n McpContext,\n McpInitializeResult,\n McpPromptDescriptor,\n McpPromptGetResult,\n McpPromptMessage,\n McpResourceContent,\n McpResourceDescriptor,\n McpResourceReadResult,\n McpServerInfo,\n McpToolCallResult,\n McpToolDescriptor,\n} from \"../interfaces/McpTypes.ts\";\nimport type { PromptPrimitive } from \"../primitives/$prompt.ts\";\nimport type { ResourcePrimitive } from \"../primitives/$resource.ts\";\nimport type { ToolPrimitive } from \"../primitives/$tool.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Core MCP server provider that handles protocol messages.\n *\n * This provider maintains registries of tools, resources, and prompts,\n * and routes incoming JSON-RPC requests to the appropriate handlers.\n *\n * It is transport-agnostic - actual communication is handled by\n * transport providers like StdioMcpTransport or SseMcpTransport.\n */\nexport class McpServerProvider {\n protected readonly log = $logger();\n protected readonly alepha = $inject(Alepha);\n\n protected readonly tools = new Map<string, ToolPrimitive<any>>();\n protected readonly resources = new Map<string, ResourcePrimitive>();\n protected readonly prompts = new Map<string, PromptPrimitive<any>>();\n\n protected initialized = false;\n\n /**\n * Protocol version negotiated with the client during `initialize`.\n * Used by transports to validate the `MCP-Protocol-Version` header on\n * subsequent HTTP requests (per spec 2025-06-18+).\n */\n public negotiatedVersion: string = MCP_PROTOCOL_VERSION;\n\n /**\n * Server identity returned during `initialize`. Consumers may override\n * fields directly (e.g. `mcpServer.serverInfo = { name: \"roadmap-mcp\",\n * version: \"0.20.3\", description: \"...\" }`) — the `description` field\n * is supported per spec 2025-11-25 (minor change #2).\n */\n public serverInfo: McpServerInfo = {\n name: \"alepha-mcp\",\n version: \"1.0.0\",\n };\n\n // -----------------------------------------------------------------------------------------------------------------\n // Registration Methods\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Register a tool with the MCP server.\n */\n public registerTool(tool: ToolPrimitive<any>): void {\n this.log.trace(`Registering MCP tool: ${tool.name}`);\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Register a resource with the MCP server.\n */\n public registerResource(resource: ResourcePrimitive): void {\n this.log.trace(`Registering MCP resource: ${resource.uri}`);\n this.resources.set(resource.uri, resource);\n }\n\n /**\n * Register a prompt with the MCP server.\n */\n public registerPrompt(prompt: PromptPrimitive<any>): void {\n this.log.trace(`Registering MCP prompt: ${prompt.name}`);\n this.prompts.set(prompt.name, prompt);\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Getters\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Get the server capabilities based on registered primitives.\n */\n public getCapabilities(): McpCapabilities {\n return {\n tools: this.tools.size > 0 ? {} : undefined,\n resources: this.resources.size > 0 ? {} : undefined,\n prompts: this.prompts.size > 0 ? {} : undefined,\n };\n }\n\n /**\n * Get all registered tools.\n */\n public getTools(): ToolPrimitive<any>[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get all registered resources.\n */\n public getResources(): ResourcePrimitive[] {\n return Array.from(this.resources.values());\n }\n\n /**\n * Get all registered prompts.\n */\n public getPrompts(): PromptPrimitive<any>[] {\n return Array.from(this.prompts.values());\n }\n\n /**\n * Get a tool by name.\n */\n public getTool(name: string): ToolPrimitive<any> | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Get a resource by URI.\n */\n public getResource(uri: string): ResourcePrimitive | undefined {\n return this.resources.get(uri);\n }\n\n /**\n * Get a prompt by name.\n */\n public getPrompt(name: string): PromptPrimitive<any> | undefined {\n return this.prompts.get(name);\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Message Handling\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Handle an incoming JSON-RPC request.\n *\n * @param request - The parsed JSON-RPC request\n * @param context - Optional context from the transport layer (headers, auth, etc.)\n * @returns The JSON-RPC response, or null for notifications\n */\n public async handleMessage(\n request: JsonRpcRequest,\n context?: McpContext,\n ): Promise<JsonRpcResponse | null> {\n const id = request.id;\n\n // Notifications have no id and expect no response\n if (id === undefined) {\n await this.handleNotification(request);\n return null;\n }\n\n try {\n const result = await this.handleRequest(request, context);\n return createResponse(id, result);\n } catch (error) {\n this.log.error(\"MCP request failed\", error);\n // Preserve error code from McpError instances\n if (error instanceof McpError) {\n return createErrorResponse(id, {\n code: error.code,\n message: error.message,\n });\n }\n return createErrorResponse(\n id,\n createInternalError((error as Error).message),\n );\n }\n }\n\n /**\n * Handle a JSON-RPC request that expects a response.\n */\n protected async handleRequest(\n request: JsonRpcRequest,\n context?: McpContext,\n ): Promise<unknown> {\n const { method, params = {} } = request;\n\n switch (method) {\n case \"initialize\":\n return this.handleInitialize(params);\n case \"ping\":\n return this.handlePing();\n case \"tools/list\":\n return this.handleToolsList();\n case \"tools/call\":\n return this.handleToolsCall(params, context);\n case \"resources/list\":\n return this.handleResourcesList();\n case \"resources/read\":\n return this.handleResourcesRead(params, context);\n case \"prompts/list\":\n return this.handlePromptsList();\n case \"prompts/get\":\n return this.handlePromptsGet(params, context);\n default:\n throw new McpMethodNotFoundError(method);\n }\n }\n\n /**\n * Handle a notification (no response expected).\n */\n protected async handleNotification(request: JsonRpcRequest): Promise<void> {\n const { method } = request;\n\n switch (method) {\n case \"notifications/initialized\":\n this.log.debug(\"MCP client initialized\");\n break;\n case \"notifications/cancelled\":\n this.log.debug(\"MCP request cancelled\", request.params);\n break;\n default:\n this.log.debug(`Unknown MCP notification: ${method}`);\n }\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Protocol Handlers\n // -----------------------------------------------------------------------------------------------------------------\n\n protected handleInitialize(\n params: Record<string, unknown>,\n ): McpInitializeResult {\n const requested = params.protocolVersion;\n // Echo the client's version when supported, otherwise reply with our\n // preferred version (highest entry in SUPPORTED_PROTOCOL_VERSIONS).\n // The client can then decide to retry, downgrade, or disconnect.\n const negotiated = isSupportedProtocolVersion(requested)\n ? requested\n : SUPPORTED_PROTOCOL_VERSIONS[0];\n\n this.log.info(\"MCP client initializing\", {\n clientInfo: params.clientInfo,\n requestedProtocolVersion: requested,\n negotiatedProtocolVersion: negotiated,\n });\n\n this.initialized = true;\n this.negotiatedVersion = negotiated;\n\n return {\n protocolVersion: negotiated,\n capabilities: this.getCapabilities(),\n serverInfo: this.serverInfo,\n };\n }\n\n protected handlePing(): Record<string, never> {\n return {};\n }\n\n protected handleToolsList(): { tools: McpToolDescriptor[] } {\n return {\n tools: Array.from(this.tools.values()).map((t) => t.toDescriptor()),\n };\n }\n\n protected async handleToolsCall(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpToolCallResult> {\n const name = params.name as string;\n const args = (params.arguments ?? {}) as Record<string, unknown>;\n\n const tool = this.tools.get(name);\n if (!tool) {\n // McpToolNotFoundError is intentionally a JSON-RPC protocol error,\n // not a tool execution error — see SEP-1303 (only validation/runtime\n // failures of an existing tool are reported via isError: true).\n throw new McpToolNotFoundError(name);\n }\n\n try {\n const result = await tool.execute(args, context);\n\n const callResult: McpToolCallResult = {\n content: [\n {\n type: \"text\",\n text:\n typeof result === \"string\"\n ? result\n : JSON.stringify(result ?? null),\n },\n ],\n };\n\n // Spec 2025-06-18: when the tool declares an outputSchema, the server\n // MUST populate `structuredContent` with the validated result. The\n // text-stringified `content` block remains as a back-compat fallback.\n if (tool.hasOutputSchema() && result !== undefined) {\n callResult.structuredContent = result;\n }\n\n return callResult;\n } catch (error) {\n // Spec 2025-11-25 / SEP-1303: input-validation failures (and other\n // tool-runtime errors) are returned as Tool Execution Errors, not\n // JSON-RPC protocol errors, so the model can self-correct.\n // For TypeBox validation errors we surface the failing path so the\n // model knows which argument was malformed.\n if (error instanceof TypeBoxError) {\n const path = error.value?.path || \"/\";\n const message = error.value?.message || error.message;\n return {\n content: [\n {\n type: \"text\",\n text: `Validation error at ${path}: ${message}`,\n },\n ],\n structuredContent: {\n errors: [{ path, message }],\n },\n isError: true,\n };\n }\n\n return {\n content: [\n {\n type: \"text\",\n text: `Error: ${(error as Error).message}`,\n },\n ],\n isError: true,\n };\n }\n }\n\n protected handleResourcesList(): { resources: McpResourceDescriptor[] } {\n return {\n resources: Array.from(this.resources.values()).map((r) =>\n r.toDescriptor(),\n ),\n };\n }\n\n protected async handleResourcesRead(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpResourceReadResult> {\n const uri = params.uri as string;\n\n const resource = this.resources.get(uri);\n if (!resource) {\n throw new McpResourceNotFoundError(uri);\n }\n\n const content = await resource.read(context);\n\n const resourceContent: McpResourceContent = {\n uri,\n mimeType: resource.mimeType,\n };\n\n if (content.text !== undefined) {\n resourceContent.text = content.text;\n }\n\n if (content.blob !== undefined) {\n // Convert binary to base64 for transport\n resourceContent.blob = Buffer.from(content.blob).toString(\"base64\");\n }\n\n return {\n contents: [resourceContent],\n };\n }\n\n protected handlePromptsList(): { prompts: McpPromptDescriptor[] } {\n return {\n prompts: Array.from(this.prompts.values()).map((p) => p.toDescriptor()),\n };\n }\n\n protected async handlePromptsGet(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpPromptGetResult> {\n const name = params.name as string;\n const args = (params.arguments ?? {}) as Record<string, string>;\n\n const prompt = this.prompts.get(name);\n if (!prompt) {\n throw new McpPromptNotFoundError(name);\n }\n\n const messages = await prompt.get(args, context);\n\n const mcpMessages: McpPromptMessage[] = messages.map((msg) => ({\n role: msg.role,\n content: {\n type: \"text\" as const,\n text: msg.content,\n },\n }));\n\n return {\n description: prompt.description,\n messages: mcpMessages,\n };\n }\n}\n","import {\n $inject,\n type Async,\n createPrimitive,\n KIND,\n Primitive,\n type Static,\n type TObject,\n t,\n} from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpPromptArgument,\n McpPromptDescriptor,\n PromptHandlerArgs,\n PromptMessage,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP prompt primitive for defining reusable prompt templates.\n *\n * Prompts allow you to define templated messages that can be filled in\n * with arguments at runtime. They're useful for creating consistent\n * interaction patterns.\n *\n * @example\n * ```ts\n * class Prompts {\n * greeting = $prompt({\n * description: \"Generate a personalized greeting\",\n * args: t.object({\n * name: t.text({ description: \"Name of the person to greet\" }),\n * style: t.optional(t.enum([\"formal\", \"casual\"])),\n * }),\n * handler: async ({ args }) => [\n * {\n * role: \"user\",\n * content: args.style === \"formal\"\n * ? `Please greet ${args.name} in a formal manner.`\n * : `Say hi to ${args.name}!`,\n * },\n * ],\n * });\n *\n * codeReview = $prompt({\n * description: \"Request a code review\",\n * args: t.object({\n * code: t.text({ description: \"The code to review\" }),\n * language: t.text({ description: \"Programming language\" }),\n * }),\n * handler: async ({ args }) => [\n * {\n * role: \"user\",\n * content: `Please review this ${args.language} code:\\n\\n${args.code}`,\n * },\n * ],\n * });\n * }\n * ```\n */\nexport const $prompt = <T extends TObject>(\n options: PromptPrimitiveOptions<T>,\n): PromptPrimitive<T> => {\n return createPrimitive(PromptPrimitive<T>, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface PromptPrimitiveOptions<T extends TObject> {\n /**\n * The name of the prompt.\n *\n * If not provided, defaults to the property key where the prompt is declared.\n *\n * @example \"greeting\"\n * @example \"code-review\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier.\n */\n title?: string;\n\n /**\n * Description of what this prompt does.\n *\n * Helps users understand the purpose of the prompt.\n *\n * @example \"Generate a personalized greeting message\"\n */\n description?: string;\n\n /**\n * Optional icons surfaced in client UIs (spec 2025-11-25 / SEP-973).\n */\n icons?: McpIcon[];\n\n /**\n * TypeBox schema defining the prompt arguments.\n *\n * Each property in the schema becomes an argument that can be\n * filled in when the prompt is used.\n */\n args?: T;\n\n /**\n * Handler function that generates the prompt messages.\n *\n * Receives the validated arguments and returns an array of messages.\n *\n * @param args - Object containing validated arguments\n * @returns Array of prompt messages\n */\n handler: (args: PromptHandlerArgs<T>) => Async<PromptMessage[]>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class PromptPrimitive<T extends TObject> extends Primitive<\n PromptPrimitiveOptions<T>\n> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the prompt.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the description of the prompt.\n */\n public get description(): string | undefined {\n return this.options.description;\n }\n\n protected onInit(): void {\n this.mcpServer.registerPrompt(this);\n }\n\n /**\n * Get the prompt messages with the given arguments.\n *\n * @param rawArgs - Raw arguments to validate and pass to the handler\n * @param context - Optional context from the transport layer\n * @returns Array of prompt messages\n */\n public async get(\n rawArgs: unknown,\n context?: McpContext,\n ): Promise<PromptMessage[]> {\n let args = (rawArgs ?? {}) as Static<T>;\n\n if (this.options.args) {\n args = this.alepha.codec.decode(this.options.args, rawArgs ?? {});\n }\n\n return this.options.handler({ args, context });\n }\n\n /**\n * Convert the prompt to an MCP prompt descriptor for protocol messages.\n */\n public toDescriptor(): McpPromptDescriptor {\n const descriptor: McpPromptDescriptor = {\n name: this.name,\n description: this.description,\n arguments: this.options.args\n ? this.schemaToArguments(this.options.args)\n : [],\n };\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n return descriptor;\n }\n\n /**\n * Convert a TypeBox schema to an array of prompt arguments.\n */\n protected schemaToArguments(schema: TObject): McpPromptArgument[] {\n const args: McpPromptArgument[] = [];\n\n for (const [name, propSchema] of Object.entries(schema.properties)) {\n const prop = propSchema as Record<string, unknown>;\n args.push({\n name,\n description: prop.description as string | undefined,\n required: !t.schema.isOptional(propSchema),\n });\n }\n\n return args;\n }\n}\n\n$prompt[KIND] = PromptPrimitive;\n","import { $inject, createPrimitive, KIND, Primitive } from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpResourceDescriptor,\n ResourceContent,\n ResourceHandler,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP resource primitive for exposing read-only data.\n *\n * Resources represent any kind of data that an LLM might want to read,\n * such as files, database records, API responses, or computed data.\n *\n * **Key Features**\n * - URI-based identification for resources\n * - Support for text and binary content\n * - MIME type specification\n * - Lazy loading via handler function\n *\n * @example\n * ```ts\n * class ProjectResources {\n * readme = $resource({\n * uri: \"file:///readme\",\n * description: \"Project README file\",\n * mimeType: \"text/markdown\",\n * handler: async () => ({\n * text: await fs.readFile(\"README.md\", \"utf-8\"),\n * }),\n * });\n *\n * config = $resource({\n * uri: \"config://app\",\n * name: \"Application Configuration\",\n * mimeType: \"application/json\",\n * handler: async () => ({\n * text: JSON.stringify(this.configService.getConfig()),\n * }),\n * });\n * }\n * ```\n */\nexport const $resource = (\n options: ResourcePrimitiveOptions,\n): ResourcePrimitive => {\n return createPrimitive(ResourcePrimitive, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ResourcePrimitiveOptions {\n /**\n * The URI that identifies this resource.\n *\n * URIs should follow a consistent scheme for your application.\n * Common patterns:\n * - `file:///path/to/file` - File system resources\n * - `db://table/id` - Database records\n * - `api://endpoint` - API responses\n * - `config://name` - Configuration values\n *\n * @example \"file:///readme.md\"\n * @example \"db://users/123\"\n */\n uri: string;\n\n /**\n * Human-readable name for the resource.\n *\n * If not provided, defaults to the property key where the resource is declared.\n *\n * @example \"Project README\"\n * @example \"User Profile\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier.\n */\n title?: string;\n\n /**\n * Optional icons surfaced in client UIs (spec 2025-11-25 / SEP-973).\n */\n icons?: McpIcon[];\n\n /**\n * Description of what this resource contains.\n *\n * Helps the LLM understand the purpose and content of the resource.\n *\n * @example \"The main README file for the project\"\n */\n description?: string;\n\n /**\n * MIME type of the resource content.\n *\n * Helps clients understand how to interpret the content.\n *\n * @default \"text/plain\"\n * @example \"text/markdown\"\n * @example \"application/json\"\n */\n mimeType?: string;\n\n /**\n * Handler function that returns the resource content.\n *\n * Called when the resource is read. Can return text or binary content.\n *\n * @returns Resource content with either `text` or `blob` property\n */\n handler: ResourceHandler;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class ResourcePrimitive extends Primitive<ResourcePrimitiveOptions> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the resource.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the URI of the resource.\n */\n public get uri(): string {\n return this.options.uri;\n }\n\n /**\n * Returns the description of the resource.\n */\n public get description(): string | undefined {\n return this.options.description;\n }\n\n /**\n * Returns the MIME type of the resource.\n */\n public get mimeType(): string {\n return this.options.mimeType ?? \"text/plain\";\n }\n\n protected onInit(): void {\n this.mcpServer.registerResource(this);\n }\n\n /**\n * Read the resource content.\n *\n * @param context - Optional context from the transport layer\n * @returns The resource content\n */\n public async read(context?: McpContext): Promise<ResourceContent> {\n return this.options.handler({ context });\n }\n\n /**\n * Convert the resource to an MCP resource descriptor for protocol messages.\n */\n public toDescriptor(): McpResourceDescriptor {\n const descriptor: McpResourceDescriptor = {\n uri: this.uri,\n name: this.name,\n description: this.description,\n mimeType: this.mimeType,\n };\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n return descriptor;\n }\n}\n\n$resource[KIND] = ResourcePrimitive;\n","import {\n $inject,\n type Async,\n createPrimitive,\n KIND,\n Primitive,\n type TObject,\n type TSchema,\n t,\n} from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpJsonSchema,\n McpToolAnnotations,\n McpToolDescriptor,\n ToolHandlerArgs,\n ToolHandlerResult,\n ToolPrimitiveSchema,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP tool primitive for defining callable functions.\n *\n * Tools are the primary way for LLMs to interact with external systems through MCP.\n * Each tool has a name, description, typed parameters, and a handler function.\n *\n * **Key Features**\n * - Full TypeScript inference for parameters and results\n * - Automatic schema validation using TypeBox\n * - JSON Schema generation for MCP protocol\n * - Integration with MCP server provider\n *\n * @example\n * ```ts\n * class CalculatorTools {\n * add = $tool({\n * description: \"Add two numbers together\",\n * schema: {\n * params: t.object({\n * a: t.number(),\n * b: t.number(),\n * }),\n * result: t.number(),\n * },\n * handler: async ({ params }) => {\n * return params.a + params.b;\n * },\n * });\n *\n * greet = $tool({\n * description: \"Generate a greeting message\",\n * schema: {\n * params: t.object({\n * name: t.text(),\n * }),\n * result: t.text(),\n * },\n * handler: async ({ params }) => {\n * return `Hello, ${params.name}!`;\n * },\n * });\n * }\n * ```\n */\nexport const $tool = <T extends ToolPrimitiveSchema>(\n options: ToolPrimitiveOptions<T>,\n): ToolPrimitive<T> => {\n return createPrimitive(ToolPrimitive<T>, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ToolPrimitiveOptions<T extends ToolPrimitiveSchema> {\n /**\n * The name of the tool.\n *\n * If not provided, defaults to the property key where the tool is declared.\n * Names should be descriptive and use kebab-case or snake_case.\n *\n * @example \"calculate-sum\"\n * @example \"get_weather\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier. Clients use `title` in\n * tool palettes / picker UIs.\n *\n * @example \"Search Lore\"\n */\n title?: string;\n\n /**\n * A human-readable description of what the tool does.\n *\n * This description is sent to the LLM to help it understand\n * when and how to use the tool. Be clear and specific.\n *\n * @example \"Calculate the sum of two numbers\"\n * @example \"Retrieve current weather data for a given location\"\n */\n description: string;\n\n /**\n * Behavior hints (spec 2025-03-26+). Clients use these to gate UI prompts\n * (e.g. require confirmation before a tool with `destructiveHint: true`).\n * None are guarantees — they are heuristics for the client, not the model.\n */\n annotations?: McpToolAnnotations;\n\n /**\n * Icons surfaced in client tool palettes / picker UIs (spec 2025-11-25).\n */\n icons?: McpIcon[];\n\n /**\n * TypeBox schema defining the tool's parameters and result type.\n *\n * - **params**: TObject schema for input parameters (optional)\n * - **result**: TSchema for the return value (optional)\n *\n * Schemas provide:\n * - Type inference for handler function\n * - Runtime validation of inputs\n * - JSON Schema generation for MCP protocol\n */\n schema?: T;\n\n /**\n * The handler function that executes when the tool is called.\n *\n * Receives validated parameters and returns the result.\n * Errors thrown here are caught and returned as MCP errors.\n *\n * @param args - Object containing validated params\n * @returns The tool result (can be async)\n */\n handler: (args: ToolHandlerArgs<T>) => Async<ToolHandlerResult<T>>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class ToolPrimitive<T extends ToolPrimitiveSchema> extends Primitive<\n ToolPrimitiveOptions<T>\n> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the tool.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the description of the tool.\n */\n public get description(): string {\n return this.options.description;\n }\n\n /**\n * Whether the tool declared a result schema. When true, `tools/call`\n * responses include `structuredContent` populated with the validated\n * result (spec 2025-06-18).\n */\n public hasOutputSchema(): boolean {\n return !!this.options.schema?.result;\n }\n\n protected onInit(): void {\n this.mcpServer.registerTool(this);\n }\n\n /**\n * Execute the tool with the given parameters.\n *\n * @param params - Raw parameters to validate and pass to the handler\n * @param context - Optional context from the transport layer\n * @returns The tool result\n */\n public async execute(\n params: unknown,\n context?: McpContext,\n ): Promise<ToolHandlerResult<T>> {\n let validatedParams: any = params ?? {};\n\n // Validate params using alepha.codec if schema provided\n if (this.options.schema?.params) {\n validatedParams = this.alepha.codec.decode(\n this.options.schema.params,\n validatedParams,\n );\n }\n\n const result = await this.options.handler({\n params: validatedParams,\n context,\n });\n\n // Validate and encode result if schema provided\n if (this.options.schema?.result && result !== undefined) {\n return this.alepha.codec.encode(\n this.options.schema.result,\n result,\n ) as ToolHandlerResult<T>;\n }\n\n return result as ToolHandlerResult<T>;\n }\n\n /**\n * Convert the tool to an MCP tool descriptor for protocol messages.\n *\n * Emits the spec 2025-11-25 surface: `title`, `annotations`, `icons`,\n * and (when `schema.result` is defined) `outputSchema` so the server\n * can populate `structuredContent` on call results.\n */\n public toDescriptor(): McpToolDescriptor {\n const inputSchema: McpJsonSchema = this.options.schema?.params\n ? this.schemaToJsonSchema(this.options.schema.params)\n : { type: \"object\", properties: {}, required: [] };\n\n const descriptor: McpToolDescriptor = {\n name: this.name,\n description: this.description,\n inputSchema,\n };\n\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.annotations)\n descriptor.annotations = this.options.annotations;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n\n // Output schema is emitted when the tool declares `schema.result`,\n // unlocking structured content on tools/call responses.\n if (this.options.schema?.result) {\n const out = this.propertyToJsonSchema(this.options.schema.result);\n // The result schema may be a primitive — wrap so the descriptor\n // value is always a JSON Schema object with `type`.\n descriptor.outputSchema = (\n typeof out === \"object\" && out !== null && \"type\" in out\n ? out\n : { type: \"object\", properties: {}, required: [] }\n ) as McpJsonSchema;\n }\n\n return descriptor;\n }\n\n /**\n * Convert a TypeBox schema to JSON Schema format.\n *\n * Emits the 2020-12 dialect annotation at the root (spec 2025-11-25 /\n * SEP-1613 — JSON Schema 2020-12 is the default dialect for MCP).\n * The TypeBox shapes Alepha emits today are already 2020-12-compatible;\n * this is just the dialect declaration.\n */\n protected schemaToJsonSchema(\n schema: TObject,\n options?: { root?: boolean },\n ): McpJsonSchema {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n properties[key] = this.propertyToJsonSchema(propSchema as TSchema);\n\n // Check if property is required (not optional)\n if (!t.schema.isOptional(propSchema as TSchema)) {\n required.push(key);\n }\n }\n\n const result: McpJsonSchema = {\n type: \"object\",\n properties,\n required,\n };\n\n // Annotate the dialect on the root schema only (avoid noise on nested\n // sub-schemas where MCP doesn't expect $schema).\n if (options?.root !== false) {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n\n return result;\n }\n\n /**\n * Convert a single property schema to JSON Schema format.\n */\n protected propertyToJsonSchema(schema: TSchema): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n // Check for description on all types\n if (\"description\" in schema) {\n result.description = schema.description;\n }\n\n if (t.schema.isString(schema)) {\n result.type = \"string\";\n if (\"minLength\" in schema) result.minLength = schema.minLength;\n if (\"maxLength\" in schema) result.maxLength = schema.maxLength;\n if (\"pattern\" in schema) result.pattern = schema.pattern;\n if (\"enum\" in schema) result.enum = schema.enum;\n } else if (t.schema.isNumber(schema)) {\n result.type = \"number\";\n if (\"minimum\" in schema) result.minimum = schema.minimum;\n if (\"maximum\" in schema) result.maximum = schema.maximum;\n } else if (t.schema.isInteger(schema)) {\n result.type = \"integer\";\n if (\"minimum\" in schema) result.minimum = schema.minimum;\n if (\"maximum\" in schema) result.maximum = schema.maximum;\n } else if (t.schema.isBoolean(schema)) {\n result.type = \"boolean\";\n } else if (t.schema.isArray(schema)) {\n result.type = \"array\";\n if (\"items\" in schema) {\n result.items = this.propertyToJsonSchema(schema.items as TSchema);\n }\n } else if (t.schema.isObject(schema)) {\n Object.assign(result, this.schemaToJsonSchema(schema, { root: false }));\n } else if (t.schema.isUnsafe(schema) || t.schema.isOptional(schema)) {\n // Handle Unsafe types (like t.enum) and optional wrappers by checking the underlying type property\n const schemaAny = schema as { type?: string; enum?: unknown[] };\n if (schemaAny.type === \"string\") {\n result.type = \"string\";\n if (\"enum\" in schema) result.enum = schema.enum;\n if (\"pattern\" in schema) result.pattern = schema.pattern;\n } else if (schemaAny.type === \"number\") {\n result.type = \"number\";\n } else if (schemaAny.type === \"integer\") {\n result.type = \"integer\";\n } else if (schemaAny.type === \"boolean\") {\n result.type = \"boolean\";\n } else if (schemaAny.type === \"array\") {\n result.type = \"array\";\n } else if (schemaAny.type === \"object\") {\n result.type = \"object\";\n } else {\n // Fallback\n result.type = \"string\";\n }\n } else {\n // Fallback for other types\n result.type = \"string\";\n }\n\n return result;\n }\n}\n\n$tool[KIND] = ToolPrimitive;\n","import { $atom, $inject, $state, t } from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport { $route } from \"alepha/server\";\nimport {\n createErrorResponse,\n createParseError,\n JsonRpcParseError,\n parseMessage,\n} from \"../helpers/jsonrpc.ts\";\nimport type { McpContext } from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport const mcpStreamableHttpOptions = $atom({\n name: \"alepha.mcp.streamableHttp.options\",\n description: \"Configuration options for the MCP Streamable HTTP transport.\",\n schema: t.object({\n /**\n * Path for the MCP endpoint. Single endpoint for both requests and\n * (optional) server-streamed responses, per spec 2025-03-26+.\n */\n path: t.text({ default: \"/mcp\" }),\n /**\n * Allow-list of `Origin` header values accepted on incoming requests.\n * Empty array (default) means \"allow any\". When set, browser-originated\n * requests with a non-matching `Origin` are rejected with 403 Forbidden,\n * blocking DNS-rebinding attacks against localhost MCP servers.\n *\n * Server-to-server callers (no `Origin` header) are always allowed.\n *\n * Spec 2025-11-25, PR #1439.\n */\n allowedOrigins: t.array(t.text(), { default: [] }),\n }),\n default: {\n path: \"/mcp\",\n allowedOrigins: [],\n },\n});\n\n// Backward-compat alias for the legacy atom name. Prefer\n// `mcpStreamableHttpOptions` going forward; this re-export keeps existing\n// consumer imports compiling and will be removed once they migrate.\nexport const mcpSseOptions = mcpStreamableHttpOptions;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Streamable HTTP transport for MCP communication.\n *\n * Implements the 2025-03-26+ Streamable HTTP transport: a single `/mcp`\n * endpoint that accepts JSON-RPC over POST and returns either\n * `application/json` (single response, the default) or\n * `text/event-stream` (when the server wants to stream multiple messages).\n *\n * Designed for serverless deployment (Cloudflare Workers, etc.) — there is\n * no long-lived GET stream. GET on the endpoint returns 405 Method Not\n * Allowed; clients that want server-initiated push must rely on the POST\n * response stream when the server upgrades to SSE for that particular call.\n *\n * Spec compliance:\n * - 2025-06-18: validates `MCP-Protocol-Version` header on every request\n * after `initialize` against the version negotiated and stored on\n * `McpServerProvider`.\n * - 2025-11-25: rejects requests with a non-allow-listed `Origin` header\n * (PR #1439). See {@link mcpStreamableHttpOptions.allowedOrigins}.\n *\n * @example\n * ```ts\n * import { Alepha, run } from \"alepha\";\n * import { AlephaServer } from \"alepha/server\";\n * import { AlephaMcp, StreamableHttpMcpTransport } from \"alepha/mcp\";\n *\n * class MyTools {\n * // ... tool definitions\n * }\n *\n * run(\n * Alepha.create()\n * .with(AlephaServer)\n * .with(AlephaMcp)\n * .with(StreamableHttpMcpTransport)\n * .with(MyTools)\n * );\n * ```\n */\nexport class StreamableHttpMcpTransport {\n protected readonly log = $logger();\n protected readonly options = $state(mcpStreamableHttpOptions);\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * GET on the MCP endpoint is not supported in this transport. Returning\n * 405 (rather than serving the legacy two-endpoint SSE pattern) is the\n * spec-allowed response for servers that don't offer server-initiated\n * push outside of an active POST.\n */\n notAllowed = $route({\n method: \"GET\",\n path: this.options.path,\n handler: (request) => {\n request.reply.status = 405;\n request.reply.headers.allow = \"POST\";\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: \"Method Not Allowed. Use POST for MCP messages.\",\n });\n },\n });\n\n /**\n * POST endpoint for client-to-server JSON-RPC messages.\n * Returns `application/json` for single responses; tools that need to\n * stream progress would upgrade to `text/event-stream` (deferred until a\n * concrete need exists).\n */\n message = $route({\n method: \"POST\",\n path: this.options.path,\n schema: {\n body: t.json(),\n },\n handler: async (request) => {\n try {\n // Origin allow-list check (spec 2025-11-25 / PR #1439).\n const originRaw = request.headers.origin;\n const origin = Array.isArray(originRaw) ? originRaw[0] : originRaw;\n if (\n origin &&\n this.options.allowedOrigins.length > 0 &&\n !this.options.allowedOrigins.includes(origin)\n ) {\n this.log.warn(\"Rejected MCP request with non-allowed Origin\", {\n origin,\n allowed: this.options.allowedOrigins,\n });\n request.reply.status = 403;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: \"Forbidden: Origin not allowed\",\n });\n return;\n }\n\n const body =\n typeof request.body === \"string\"\n ? request.body\n : JSON.stringify(request.body);\n\n this.log.debug(\"MCP request body\", {\n body,\n bodyType: typeof request.body,\n });\n\n const rpcRequest = parseMessage(body);\n\n // Build context from request headers\n const headers = { ...request.headers } as Record<\n string,\n string | string[] | undefined\n >;\n\n // Spec 2025-06-18+: every HTTP request after `initialize` MUST carry\n // an `MCP-Protocol-Version` header matching the negotiated version.\n // Reject mismatches with 400 so the client doesn't silently drift.\n if (rpcRequest.method !== \"initialize\") {\n const headerRaw = headers[\"mcp-protocol-version\"];\n const headerVersion = Array.isArray(headerRaw)\n ? headerRaw[0]\n : headerRaw;\n if (\n headerVersion &&\n headerVersion !== this.mcpServer.negotiatedVersion\n ) {\n this.log.warn(\"MCP-Protocol-Version header mismatch\", {\n header: headerVersion,\n negotiated: this.mcpServer.negotiatedVersion,\n });\n request.reply.status = 400;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: `MCP-Protocol-Version mismatch: expected ${this.mcpServer.negotiatedVersion}, got ${headerVersion}`,\n });\n return;\n }\n }\n\n const context: McpContext = { headers };\n\n const response = await this.mcpServer.handleMessage(\n rpcRequest,\n context,\n );\n\n if (response) {\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify(response);\n } else {\n request.reply.status = 204;\n }\n } catch (error) {\n if (error instanceof JsonRpcParseError) {\n request.reply.status = 400;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify(\n createErrorResponse(0, createParseError(error.message)),\n );\n } else {\n this.log.error(\"Failed to process MCP message\", error);\n request.reply.status = 500;\n request.reply.body = JSON.stringify({\n error: (error as Error).message,\n });\n }\n }\n },\n });\n}\n\n/**\n * @deprecated Use {@link StreamableHttpMcpTransport}. The 2024-11-05\n * two-endpoint HTTP+SSE pattern was replaced by Streamable HTTP in spec\n * 2025-03-26. This alias is preserved for one release to ease migration.\n */\nexport const SseMcpTransport = StreamableHttpMcpTransport;\n","import { $module } from \"alepha\";\nimport { $prompt } from \"./primitives/$prompt.ts\";\nimport { $resource } from \"./primitives/$resource.ts\";\nimport { $tool } from \"./primitives/$tool.ts\";\nimport { McpServerProvider } from \"./providers/McpServerProvider.ts\";\nimport { StreamableHttpMcpTransport } from \"./transports/StreamableHttpMcpTransport.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport {\n McpError,\n McpErrorCodes,\n McpForbiddenError,\n McpInvalidParamsError,\n McpMethodNotFoundError,\n McpPromptNotFoundError,\n McpResourceNotFoundError,\n McpToolNotFoundError,\n McpUnauthorizedError,\n} from \"./errors/McpError.ts\";\nexport {\n createErrorResponse,\n createInternalError,\n createInvalidParamsError,\n createInvalidRequestError,\n createMethodNotFoundError,\n createNotification,\n createParseError,\n createResponse,\n isNotification,\n isSupportedProtocolVersion,\n isValidJsonRpcRequest,\n JSONRPC_VERSION,\n JsonRpcErrorCodes,\n JsonRpcParseError,\n MCP_PROTOCOL_VERSION,\n parseMessage,\n SUPPORTED_PROTOCOL_VERSIONS,\n type SupportedProtocolVersion,\n} from \"./helpers/jsonrpc.ts\";\nexport type {\n JsonRpcError,\n JsonRpcNotification,\n // JSON-RPC types\n JsonRpcRequest,\n JsonRpcResponse,\n // MCP protocol types\n McpCapabilities,\n McpClientInfo,\n McpContent,\n // Context type for auth/headers\n McpContext,\n McpInitializeParams,\n McpInitializeResult,\n McpJsonSchema,\n McpPromptArgument,\n McpPromptContent,\n // Prompt types\n McpPromptDescriptor,\n McpPromptGetParams,\n McpPromptGetResult,\n McpPromptMessage,\n McpResourceContent,\n // Resource types\n McpResourceDescriptor,\n McpResourceReadParams,\n McpResourceReadResult,\n McpServerInfo,\n McpToolCallParams,\n McpToolCallResult,\n // Tool types\n McpToolDescriptor,\n PromptHandler,\n PromptHandlerArgs,\n PromptMessage,\n ResourceContent,\n ResourceHandler,\n ResourceHandlerArgs,\n ToolHandler,\n ToolHandlerArgs,\n ToolHandlerResult,\n // Handler types\n ToolPrimitiveSchema,\n} from \"./interfaces/McpTypes.ts\";\nexport type { PromptPrimitiveOptions } from \"./primitives/$prompt.ts\";\nexport { $prompt, PromptPrimitive } from \"./primitives/$prompt.ts\";\nexport type { ResourcePrimitiveOptions } from \"./primitives/$resource.ts\";\nexport { $resource, ResourcePrimitive } from \"./primitives/$resource.ts\";\nexport type { ToolPrimitiveOptions } from \"./primitives/$tool.ts\";\nexport { $tool, ToolPrimitive } from \"./primitives/$tool.ts\";\nexport { McpServerProvider } from \"./providers/McpServerProvider.ts\";\nexport {\n mcpSseOptions,\n mcpStreamableHttpOptions,\n SseMcpTransport,\n StreamableHttpMcpTransport,\n} from \"./transports/StreamableHttpMcpTransport.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Model Context Protocol for AI tool integration.\n *\n * **Features:**\n * - MCP resource definitions\n * - MCP tool definitions\n * - MCP prompt definitions\n * - JSON-RPC protocol\n * - Streamable HTTP transport (spec 2025-03-26+)\n *\n * @module alepha.mcp\n */\nexport const AlephaMcp = $module({\n name: \"alepha.mcp\",\n primitives: [$tool, $resource, $prompt],\n services: [McpServerProvider],\n // Transports are opt-in — user wires the one(s) they need via alepha.with(StreamableHttpMcpTransport).\n variants: [StreamableHttpMcpTransport],\n});\n"],"mappings":";;;;AAYA,MAAa,kBAAkB;;;;;AAM/B,MAAa,uBAAuB;;;;;;AAOpC,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;CACD;AAKD,MAAa,8BACX,MAEA,OAAO,MAAM,YACZ,4BAAkD,SAAS,EAAE;AAEhE,MAAa,oBAAoB;CAC/B,aAAa;CACb,iBAAiB;CACjB,kBAAkB;CAClB,gBAAgB;CAChB,gBAAgB;CACjB;AAMD,SAAgB,eACd,IACA,QACiB;AACjB,QAAO;EACL,SAAA;EACA;EACA;EACD;;AAGH,SAAgB,oBACd,IACA,OACiB;AACjB,QAAO;EACL,SAAA;EACA;EACA;EACD;;AAGH,SAAgB,mBACd,QACA,QACqB;AACrB,QAAO;EACL,SAAA;EACA;EACA;EACD;;AAOH,SAAgB,iBAAiB,UAAU,eAA6B;AACtE,QAAO;EACL,MAAM,kBAAkB;EACxB;EACD;;AAGH,SAAgB,0BACd,UAAU,mBACI;AACd,QAAO;EACL,MAAM,kBAAkB;EACxB;EACD;;AAGH,SAAgB,0BAA0B,QAA8B;AACtE,QAAO;EACL,MAAM,kBAAkB;EACxB,SAAS,qBAAqB;EAC/B;;AAGH,SAAgB,yBAAyB,SAA+B;AACtE,QAAO;EACL,MAAM,kBAAkB;EACxB;EACD;;AAGH,SAAgB,oBAAoB,SAA+B;AACjE,QAAO;EACL,MAAM,kBAAkB;EACxB;EACD;;AAOH,SAAgB,aAAa,MAA8B;CACzD,IAAI;AAEJ,KAAI;AACF,WAAS,KAAK,MAAM,KAAK;SACnB;AACN,QAAM,IAAI,kBAAkB,eAAe;;AAG7C,KAAI,CAAC,sBAAsB,OAAO,CAChC,OAAM,IAAI,kBAAkB,2BAA2B;AAGzD,QAAO;;AAGT,SAAgB,sBAAsB,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,IAAI,MAAM,iCAAiC,MAAM;AACtD,aAAQ,MAAM,SAAS;AACvB,aAAQ,MAAM,OAAO,KAAK,UAAU,EAClC,OAAQ,MAAgB,SACzB,CAAC;;;;EAIT,CAAC;;;;;;;AAQJ,MAAa,kBAAkB;;;;;;;;;;;;;;;ACjH/B,MAAa,YAAY,QAAQ;CAC/B,MAAM;CACN,YAAY;EAAC;EAAO;EAAW;EAAQ;CACvC,UAAU,CAAC,kBAAkB;CAE7B,UAAU,CAAC,2BAA2B;CACvC,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/mcp/helpers/jsonrpc.ts","../../src/mcp/errors/McpError.ts","../../src/mcp/providers/McpServerProvider.ts","../../src/mcp/primitives/$prompt.ts","../../src/mcp/primitives/$resource.ts","../../src/mcp/primitives/$tool.ts","../../src/mcp/transports/StreamableHttpMcpTransport.ts","../../src/mcp/index.ts"],"sourcesContent":["import { AlephaError } from \"alepha\";\nimport type {\n JsonRpcError,\n JsonRpcNotification,\n JsonRpcRequest,\n JsonRpcResponse,\n} from \"../interfaces/McpTypes.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport const JSONRPC_VERSION = \"2.0\" as const;\n\n/**\n * The latest MCP protocol revision Alepha targets.\n * See {@link SUPPORTED_PROTOCOL_VERSIONS} for the full negotiation list.\n */\nexport const MCP_PROTOCOL_VERSION = \"2025-11-25\" as const;\n\n/**\n * Protocol versions Alepha will accept during `initialize` negotiation,\n * highest preference first. The server echoes back whichever version the\n * client requested if it appears here, otherwise picks the first entry.\n */\nexport const SUPPORTED_PROTOCOL_VERSIONS = [\n \"2025-11-25\",\n \"2025-06-18\",\n \"2025-03-26\",\n \"2024-11-05\",\n] as const;\n\nexport type SupportedProtocolVersion =\n (typeof SUPPORTED_PROTOCOL_VERSIONS)[number];\n\nexport const isSupportedProtocolVersion = (\n v: unknown,\n): v is SupportedProtocolVersion =>\n typeof v === \"string\" &&\n (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(v);\n\nexport const JsonRpcErrorCodes = {\n PARSE_ERROR: -32700,\n INVALID_REQUEST: -32600,\n METHOD_NOT_FOUND: -32601,\n INVALID_PARAMS: -32602,\n INTERNAL_ERROR: -32603,\n} as const;\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Response Builders\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function createResponse(\n id: string | number,\n result: unknown,\n): JsonRpcResponse {\n return {\n jsonrpc: JSONRPC_VERSION,\n id,\n result,\n };\n}\n\nexport function createErrorResponse(\n id: string | number,\n error: JsonRpcError,\n): JsonRpcResponse {\n return {\n jsonrpc: JSONRPC_VERSION,\n id,\n error,\n };\n}\n\nexport function createNotification(\n method: string,\n params?: Record<string, unknown>,\n): JsonRpcNotification {\n return {\n jsonrpc: JSONRPC_VERSION,\n method,\n params,\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Error Builders\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function createParseError(message = \"Parse error\"): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.PARSE_ERROR,\n message,\n };\n}\n\nexport function createInvalidRequestError(\n message = \"Invalid request\",\n): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INVALID_REQUEST,\n message,\n };\n}\n\nexport function createMethodNotFoundError(method: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.METHOD_NOT_FOUND,\n message: `Method not found: ${method}`,\n };\n}\n\nexport function createInvalidParamsError(message: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INVALID_PARAMS,\n message,\n };\n}\n\nexport function createInternalError(message: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INTERNAL_ERROR,\n message,\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Message Parsing\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function parseMessage(data: string): JsonRpcRequest {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(data);\n } catch {\n throw new JsonRpcParseError(\"Invalid JSON\");\n }\n\n if (!isValidJsonRpcRequest(parsed)) {\n throw new JsonRpcParseError(\"Invalid JSON-RPC request\");\n }\n\n return parsed;\n}\n\nexport function isValidJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n if (obj.jsonrpc !== JSONRPC_VERSION) {\n return false;\n }\n\n if (typeof obj.method !== \"string\") {\n return false;\n }\n\n if (\n obj.id !== undefined &&\n typeof obj.id !== \"string\" &&\n typeof obj.id !== \"number\"\n ) {\n return false;\n }\n\n if (obj.params !== undefined && typeof obj.params !== \"object\") {\n return false;\n }\n\n return true;\n}\n\nexport function isNotification(request: JsonRpcRequest): boolean {\n return request.id === undefined;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class JsonRpcParseError extends AlephaError {\n name = \"JsonRpcParseError\";\n}\n","import { JsonRpcErrorCodes } from \"../helpers/jsonrpc.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * MCP-specific error codes (application-specific codes in the -32000 to -32099 range).\n */\nexport const McpErrorCodes = {\n UNAUTHORIZED: -32001,\n FORBIDDEN: -32003,\n} as const;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpError extends Error {\n name = \"McpError\";\n code: number;\n\n constructor(\n message: string,\n code: number = JsonRpcErrorCodes.INTERNAL_ERROR,\n ) {\n super(message);\n this.code = code;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpMethodNotFoundError extends McpError {\n name = \"McpMethodNotFoundError\";\n\n constructor(method: string) {\n super(`Method not found: ${method}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpToolNotFoundError extends McpError {\n name = \"McpToolNotFoundError\";\n tool: string;\n\n constructor(tool: string) {\n super(`Tool not found: ${tool}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.tool = tool;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpResourceNotFoundError extends McpError {\n name = \"McpResourceNotFoundError\";\n uri: string;\n\n constructor(uri: string) {\n super(`Resource not found: ${uri}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.uri = uri;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpPromptNotFoundError extends McpError {\n name = \"McpPromptNotFoundError\";\n prompt: string;\n\n constructor(prompt: string) {\n super(`Prompt not found: ${prompt}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.prompt = prompt;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpInvalidParamsError extends McpError {\n name = \"McpInvalidParamsError\";\n\n constructor(message: string) {\n super(message, JsonRpcErrorCodes.INVALID_PARAMS);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpUnauthorizedError extends McpError {\n name = \"McpUnauthorizedError\";\n\n constructor(message = \"Unauthorized\") {\n super(message, McpErrorCodes.UNAUTHORIZED);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpForbiddenError extends McpError {\n name = \"McpForbiddenError\";\n\n constructor(message = \"Forbidden\") {\n super(message, McpErrorCodes.FORBIDDEN);\n }\n}\n","import { $inject, Alepha, TypeBoxError } from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport {\n McpError,\n McpMethodNotFoundError,\n McpPromptNotFoundError,\n McpResourceNotFoundError,\n McpToolNotFoundError,\n} from \"../errors/McpError.ts\";\nimport {\n createErrorResponse,\n createInternalError,\n createResponse,\n isSupportedProtocolVersion,\n MCP_PROTOCOL_VERSION,\n SUPPORTED_PROTOCOL_VERSIONS,\n} from \"../helpers/jsonrpc.ts\";\nimport type {\n JsonRpcRequest,\n JsonRpcResponse,\n McpCapabilities,\n McpContext,\n McpInitializeResult,\n McpPromptDescriptor,\n McpPromptGetResult,\n McpPromptMessage,\n McpResourceContent,\n McpResourceDescriptor,\n McpResourceReadResult,\n McpServerInfo,\n McpToolCallResult,\n McpToolDescriptor,\n} from \"../interfaces/McpTypes.ts\";\nimport type { PromptPrimitive } from \"../primitives/$prompt.ts\";\nimport type { ResourcePrimitive } from \"../primitives/$resource.ts\";\nimport type { ToolPrimitive } from \"../primitives/$tool.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Core MCP server provider that handles protocol messages.\n *\n * This provider maintains registries of tools, resources, and prompts,\n * and routes incoming JSON-RPC requests to the appropriate handlers.\n *\n * It is transport-agnostic - actual communication is handled by\n * transport providers like StdioMcpTransport or SseMcpTransport.\n */\nexport class McpServerProvider {\n protected readonly log = $logger();\n protected readonly alepha = $inject(Alepha);\n\n protected readonly tools = new Map<string, ToolPrimitive<any>>();\n protected readonly resources = new Map<string, ResourcePrimitive>();\n protected readonly prompts = new Map<string, PromptPrimitive<any>>();\n\n protected initialized = false;\n\n /**\n * Protocol version negotiated with the client during `initialize`.\n * Used by transports to validate the `MCP-Protocol-Version` header on\n * subsequent HTTP requests (per spec 2025-06-18+).\n */\n public negotiatedVersion: string = MCP_PROTOCOL_VERSION;\n\n /**\n * Server identity returned during `initialize`. Consumers may override\n * fields directly (e.g. `mcpServer.serverInfo = { name: \"roadmap-mcp\",\n * version: \"0.20.3\", description: \"...\" }`) — the `description` field\n * is supported per spec 2025-11-25 (minor change #2).\n */\n public serverInfo: McpServerInfo = {\n name: \"alepha-mcp\",\n version: \"1.0.0\",\n };\n\n // -----------------------------------------------------------------------------------------------------------------\n // Registration Methods\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Register a tool with the MCP server.\n */\n public registerTool(tool: ToolPrimitive<any>): void {\n this.log.trace(`Registering MCP tool: ${tool.name}`);\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Register a resource with the MCP server.\n */\n public registerResource(resource: ResourcePrimitive): void {\n this.log.trace(`Registering MCP resource: ${resource.uri}`);\n this.resources.set(resource.uri, resource);\n }\n\n /**\n * Register a prompt with the MCP server.\n */\n public registerPrompt(prompt: PromptPrimitive<any>): void {\n this.log.trace(`Registering MCP prompt: ${prompt.name}`);\n this.prompts.set(prompt.name, prompt);\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Getters\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Get the server capabilities based on registered primitives.\n */\n public getCapabilities(): McpCapabilities {\n return {\n tools: this.tools.size > 0 ? {} : undefined,\n resources: this.resources.size > 0 ? {} : undefined,\n prompts: this.prompts.size > 0 ? {} : undefined,\n };\n }\n\n /**\n * Get all registered tools.\n */\n public getTools(): ToolPrimitive<any>[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get all registered resources.\n */\n public getResources(): ResourcePrimitive[] {\n return Array.from(this.resources.values());\n }\n\n /**\n * Get all registered prompts.\n */\n public getPrompts(): PromptPrimitive<any>[] {\n return Array.from(this.prompts.values());\n }\n\n /**\n * Get a tool by name.\n */\n public getTool(name: string): ToolPrimitive<any> | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Get a resource by URI.\n */\n public getResource(uri: string): ResourcePrimitive | undefined {\n return this.resources.get(uri);\n }\n\n /**\n * Get a prompt by name.\n */\n public getPrompt(name: string): PromptPrimitive<any> | undefined {\n return this.prompts.get(name);\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Message Handling\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Handle an incoming JSON-RPC request.\n *\n * @param request - The parsed JSON-RPC request\n * @param context - Optional context from the transport layer (headers, auth, etc.)\n * @returns The JSON-RPC response, or null for notifications\n */\n public async handleMessage(\n request: JsonRpcRequest,\n context?: McpContext,\n ): Promise<JsonRpcResponse | null> {\n const id = request.id;\n\n // Notifications have no id and expect no response\n if (id === undefined) {\n await this.handleNotification(request);\n return null;\n }\n\n try {\n const result = await this.handleRequest(request, context);\n return createResponse(id, result);\n } catch (error) {\n this.log.error(\"MCP request failed\", error);\n // Preserve error code from McpError instances\n if (error instanceof McpError) {\n return createErrorResponse(id, {\n code: error.code,\n message: error.message,\n });\n }\n return createErrorResponse(\n id,\n createInternalError((error as Error).message),\n );\n }\n }\n\n /**\n * Handle a JSON-RPC request that expects a response.\n */\n protected async handleRequest(\n request: JsonRpcRequest,\n context?: McpContext,\n ): Promise<unknown> {\n const { method, params = {} } = request;\n\n switch (method) {\n case \"initialize\":\n return this.handleInitialize(params);\n case \"ping\":\n return this.handlePing();\n case \"tools/list\":\n return this.handleToolsList();\n case \"tools/call\":\n return this.handleToolsCall(params, context);\n case \"resources/list\":\n return this.handleResourcesList();\n case \"resources/read\":\n return this.handleResourcesRead(params, context);\n case \"prompts/list\":\n return this.handlePromptsList();\n case \"prompts/get\":\n return this.handlePromptsGet(params, context);\n default:\n throw new McpMethodNotFoundError(method);\n }\n }\n\n /**\n * Handle a notification (no response expected).\n */\n protected async handleNotification(request: JsonRpcRequest): Promise<void> {\n const { method } = request;\n\n switch (method) {\n case \"notifications/initialized\":\n this.log.debug(\"MCP client initialized\");\n break;\n case \"notifications/cancelled\":\n this.log.debug(\"MCP request cancelled\", request.params);\n break;\n default:\n this.log.debug(`Unknown MCP notification: ${method}`);\n }\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Protocol Handlers\n // -----------------------------------------------------------------------------------------------------------------\n\n protected handleInitialize(\n params: Record<string, unknown>,\n ): McpInitializeResult {\n const requested = params.protocolVersion;\n // Echo the client's version when supported, otherwise reply with our\n // preferred version (highest entry in SUPPORTED_PROTOCOL_VERSIONS).\n // The client can then decide to retry, downgrade, or disconnect.\n const negotiated = isSupportedProtocolVersion(requested)\n ? requested\n : SUPPORTED_PROTOCOL_VERSIONS[0];\n\n this.log.info(\"MCP client initializing\", {\n clientInfo: params.clientInfo,\n requestedProtocolVersion: requested,\n negotiatedProtocolVersion: negotiated,\n });\n\n this.initialized = true;\n this.negotiatedVersion = negotiated;\n\n return {\n protocolVersion: negotiated,\n capabilities: this.getCapabilities(),\n serverInfo: this.serverInfo,\n };\n }\n\n protected handlePing(): Record<string, never> {\n return {};\n }\n\n protected handleToolsList(): { tools: McpToolDescriptor[] } {\n return {\n tools: Array.from(this.tools.values()).map((t) => t.toDescriptor()),\n };\n }\n\n protected async handleToolsCall(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpToolCallResult> {\n const name = params.name as string;\n const args = (params.arguments ?? {}) as Record<string, unknown>;\n\n const tool = this.tools.get(name);\n if (!tool) {\n // McpToolNotFoundError is intentionally a JSON-RPC protocol error,\n // not a tool execution error — see SEP-1303 (only validation/runtime\n // failures of an existing tool are reported via isError: true).\n throw new McpToolNotFoundError(name);\n }\n\n try {\n const result = await tool.execute(args, context);\n\n const callResult: McpToolCallResult = {\n content: [\n {\n type: \"text\",\n text:\n typeof result === \"string\"\n ? result\n : JSON.stringify(result ?? null),\n },\n ],\n };\n\n // Spec 2025-06-18: when the tool declares an outputSchema, the server\n // MUST populate `structuredContent` with the validated result. The\n // text-stringified `content` block remains as a back-compat fallback.\n if (tool.hasOutputSchema() && result !== undefined) {\n callResult.structuredContent = result;\n }\n\n return callResult;\n } catch (error) {\n // Spec 2025-11-25 / SEP-1303: input-validation failures (and other\n // tool-runtime errors) are returned as Tool Execution Errors, not\n // JSON-RPC protocol errors, so the model can self-correct.\n // For TypeBox validation errors we surface the failing path so the\n // model knows which argument was malformed.\n if (error instanceof TypeBoxError) {\n const path = error.value?.path || \"/\";\n const message = error.value?.message || error.message;\n return {\n content: [\n {\n type: \"text\",\n text: `Validation error at ${path}: ${message}`,\n },\n ],\n structuredContent: {\n errors: [{ path, message }],\n },\n isError: true,\n };\n }\n\n return {\n content: [\n {\n type: \"text\",\n text: `Error: ${(error as Error).message}`,\n },\n ],\n isError: true,\n };\n }\n }\n\n protected handleResourcesList(): { resources: McpResourceDescriptor[] } {\n return {\n resources: Array.from(this.resources.values()).map((r) =>\n r.toDescriptor(),\n ),\n };\n }\n\n protected async handleResourcesRead(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpResourceReadResult> {\n const uri = params.uri as string;\n\n const resource = this.resources.get(uri);\n if (!resource) {\n throw new McpResourceNotFoundError(uri);\n }\n\n const content = await resource.read(context);\n\n const resourceContent: McpResourceContent = {\n uri,\n mimeType: resource.mimeType,\n };\n\n if (content.text !== undefined) {\n resourceContent.text = content.text;\n }\n\n if (content.blob !== undefined) {\n // Convert binary to base64 for transport\n resourceContent.blob = Buffer.from(content.blob).toString(\"base64\");\n }\n\n return {\n contents: [resourceContent],\n };\n }\n\n protected handlePromptsList(): { prompts: McpPromptDescriptor[] } {\n return {\n prompts: Array.from(this.prompts.values()).map((p) => p.toDescriptor()),\n };\n }\n\n protected async handlePromptsGet(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpPromptGetResult> {\n const name = params.name as string;\n const args = (params.arguments ?? {}) as Record<string, string>;\n\n const prompt = this.prompts.get(name);\n if (!prompt) {\n throw new McpPromptNotFoundError(name);\n }\n\n const messages = await prompt.get(args, context);\n\n const mcpMessages: McpPromptMessage[] = messages.map((msg) => ({\n role: msg.role,\n content: {\n type: \"text\" as const,\n text: msg.content,\n },\n }));\n\n return {\n description: prompt.description,\n messages: mcpMessages,\n };\n }\n}\n","import {\n $inject,\n type Async,\n createPrimitive,\n KIND,\n Primitive,\n type Static,\n type TObject,\n t,\n} from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpPromptArgument,\n McpPromptDescriptor,\n PromptHandlerArgs,\n PromptMessage,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP prompt primitive for defining reusable prompt templates.\n *\n * Prompts allow you to define templated messages that can be filled in\n * with arguments at runtime. They're useful for creating consistent\n * interaction patterns.\n *\n * @example\n * ```ts\n * class Prompts {\n * greeting = $prompt({\n * description: \"Generate a personalized greeting\",\n * args: t.object({\n * name: t.text({ description: \"Name of the person to greet\" }),\n * style: t.optional(t.enum([\"formal\", \"casual\"])),\n * }),\n * handler: async ({ args }) => [\n * {\n * role: \"user\",\n * content: args.style === \"formal\"\n * ? `Please greet ${args.name} in a formal manner.`\n * : `Say hi to ${args.name}!`,\n * },\n * ],\n * });\n *\n * codeReview = $prompt({\n * description: \"Request a code review\",\n * args: t.object({\n * code: t.text({ description: \"The code to review\" }),\n * language: t.text({ description: \"Programming language\" }),\n * }),\n * handler: async ({ args }) => [\n * {\n * role: \"user\",\n * content: `Please review this ${args.language} code:\\n\\n${args.code}`,\n * },\n * ],\n * });\n * }\n * ```\n */\nexport const $prompt = <T extends TObject>(\n options: PromptPrimitiveOptions<T>,\n): PromptPrimitive<T> => {\n return createPrimitive(PromptPrimitive<T>, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface PromptPrimitiveOptions<T extends TObject> {\n /**\n * The name of the prompt.\n *\n * If not provided, defaults to the property key where the prompt is declared.\n *\n * @example \"greeting\"\n * @example \"code-review\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier.\n */\n title?: string;\n\n /**\n * Description of what this prompt does.\n *\n * Helps users understand the purpose of the prompt.\n *\n * @example \"Generate a personalized greeting message\"\n */\n description?: string;\n\n /**\n * Optional icons surfaced in client UIs (spec 2025-11-25 / SEP-973).\n */\n icons?: McpIcon[];\n\n /**\n * TypeBox schema defining the prompt arguments.\n *\n * Each property in the schema becomes an argument that can be\n * filled in when the prompt is used.\n */\n args?: T;\n\n /**\n * Handler function that generates the prompt messages.\n *\n * Receives the validated arguments and returns an array of messages.\n *\n * @param args - Object containing validated arguments\n * @returns Array of prompt messages\n */\n handler: (args: PromptHandlerArgs<T>) => Async<PromptMessage[]>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class PromptPrimitive<T extends TObject> extends Primitive<\n PromptPrimitiveOptions<T>\n> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the prompt.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the description of the prompt.\n */\n public get description(): string | undefined {\n return this.options.description;\n }\n\n protected onInit(): void {\n this.mcpServer.registerPrompt(this);\n }\n\n /**\n * Get the prompt messages with the given arguments.\n *\n * @param rawArgs - Raw arguments to validate and pass to the handler\n * @param context - Optional context from the transport layer\n * @returns Array of prompt messages\n */\n public async get(\n rawArgs: unknown,\n context?: McpContext,\n ): Promise<PromptMessage[]> {\n let args = (rawArgs ?? {}) as Static<T>;\n\n if (this.options.args) {\n args = this.alepha.codec.decode(this.options.args, rawArgs ?? {});\n }\n\n return this.options.handler({ args, context });\n }\n\n /**\n * Convert the prompt to an MCP prompt descriptor for protocol messages.\n */\n public toDescriptor(): McpPromptDescriptor {\n const descriptor: McpPromptDescriptor = {\n name: this.name,\n description: this.description,\n arguments: this.options.args\n ? this.schemaToArguments(this.options.args)\n : [],\n };\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n return descriptor;\n }\n\n /**\n * Convert a TypeBox schema to an array of prompt arguments.\n */\n protected schemaToArguments(schema: TObject): McpPromptArgument[] {\n const args: McpPromptArgument[] = [];\n\n for (const [name, propSchema] of Object.entries(schema.properties)) {\n const prop = propSchema as Record<string, unknown>;\n args.push({\n name,\n description: prop.description as string | undefined,\n required: !t.schema.isOptional(propSchema),\n });\n }\n\n return args;\n }\n}\n\n$prompt[KIND] = PromptPrimitive;\n","import { $inject, createPrimitive, KIND, Primitive } from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpResourceDescriptor,\n ResourceContent,\n ResourceHandler,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP resource primitive for exposing read-only data.\n *\n * Resources represent any kind of data that an LLM might want to read,\n * such as files, database records, API responses, or computed data.\n *\n * **Key Features**\n * - URI-based identification for resources\n * - Support for text and binary content\n * - MIME type specification\n * - Lazy loading via handler function\n *\n * @example\n * ```ts\n * class ProjectResources {\n * readme = $resource({\n * uri: \"file:///readme\",\n * description: \"Project README file\",\n * mimeType: \"text/markdown\",\n * handler: async () => ({\n * text: await fs.readFile(\"README.md\", \"utf-8\"),\n * }),\n * });\n *\n * config = $resource({\n * uri: \"config://app\",\n * name: \"Application Configuration\",\n * mimeType: \"application/json\",\n * handler: async () => ({\n * text: JSON.stringify(this.configService.getConfig()),\n * }),\n * });\n * }\n * ```\n */\nexport const $resource = (\n options: ResourcePrimitiveOptions,\n): ResourcePrimitive => {\n return createPrimitive(ResourcePrimitive, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ResourcePrimitiveOptions {\n /**\n * The URI that identifies this resource.\n *\n * URIs should follow a consistent scheme for your application.\n * Common patterns:\n * - `file:///path/to/file` - File system resources\n * - `db://table/id` - Database records\n * - `api://endpoint` - API responses\n * - `config://name` - Configuration values\n *\n * @example \"file:///readme.md\"\n * @example \"db://users/123\"\n */\n uri: string;\n\n /**\n * Human-readable name for the resource.\n *\n * If not provided, defaults to the property key where the resource is declared.\n *\n * @example \"Project README\"\n * @example \"User Profile\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier.\n */\n title?: string;\n\n /**\n * Optional icons surfaced in client UIs (spec 2025-11-25 / SEP-973).\n */\n icons?: McpIcon[];\n\n /**\n * Description of what this resource contains.\n *\n * Helps the LLM understand the purpose and content of the resource.\n *\n * @example \"The main README file for the project\"\n */\n description?: string;\n\n /**\n * MIME type of the resource content.\n *\n * Helps clients understand how to interpret the content.\n *\n * @default \"text/plain\"\n * @example \"text/markdown\"\n * @example \"application/json\"\n */\n mimeType?: string;\n\n /**\n * Handler function that returns the resource content.\n *\n * Called when the resource is read. Can return text or binary content.\n *\n * @returns Resource content with either `text` or `blob` property\n */\n handler: ResourceHandler;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class ResourcePrimitive extends Primitive<ResourcePrimitiveOptions> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the resource.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the URI of the resource.\n */\n public get uri(): string {\n return this.options.uri;\n }\n\n /**\n * Returns the description of the resource.\n */\n public get description(): string | undefined {\n return this.options.description;\n }\n\n /**\n * Returns the MIME type of the resource.\n */\n public get mimeType(): string {\n return this.options.mimeType ?? \"text/plain\";\n }\n\n protected onInit(): void {\n this.mcpServer.registerResource(this);\n }\n\n /**\n * Read the resource content.\n *\n * @param context - Optional context from the transport layer\n * @returns The resource content\n */\n public async read(context?: McpContext): Promise<ResourceContent> {\n return this.options.handler({ context });\n }\n\n /**\n * Convert the resource to an MCP resource descriptor for protocol messages.\n */\n public toDescriptor(): McpResourceDescriptor {\n const descriptor: McpResourceDescriptor = {\n uri: this.uri,\n name: this.name,\n description: this.description,\n mimeType: this.mimeType,\n };\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n return descriptor;\n }\n}\n\n$resource[KIND] = ResourcePrimitive;\n","import {\n $inject,\n type Async,\n createPrimitive,\n KIND,\n Primitive,\n type TObject,\n type TSchema,\n t,\n} from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpJsonSchema,\n McpToolAnnotations,\n McpToolDescriptor,\n ToolHandlerArgs,\n ToolHandlerResult,\n ToolPrimitiveSchema,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP tool primitive for defining callable functions.\n *\n * Tools are the primary way for LLMs to interact with external systems through MCP.\n * Each tool has a name, description, typed parameters, and a handler function.\n *\n * **Key Features**\n * - Full TypeScript inference for parameters and results\n * - Automatic schema validation using TypeBox\n * - JSON Schema generation for MCP protocol\n * - Integration with MCP server provider\n *\n * @example\n * ```ts\n * class CalculatorTools {\n * add = $tool({\n * description: \"Add two numbers together\",\n * schema: {\n * params: t.object({\n * a: t.number(),\n * b: t.number(),\n * }),\n * result: t.number(),\n * },\n * handler: async ({ params }) => {\n * return params.a + params.b;\n * },\n * });\n *\n * greet = $tool({\n * description: \"Generate a greeting message\",\n * schema: {\n * params: t.object({\n * name: t.text(),\n * }),\n * result: t.text(),\n * },\n * handler: async ({ params }) => {\n * return `Hello, ${params.name}!`;\n * },\n * });\n * }\n * ```\n */\nexport const $tool = <T extends ToolPrimitiveSchema>(\n options: ToolPrimitiveOptions<T>,\n): ToolPrimitive<T> => {\n return createPrimitive(ToolPrimitive<T>, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ToolPrimitiveOptions<T extends ToolPrimitiveSchema> {\n /**\n * The name of the tool.\n *\n * If not provided, defaults to the property key where the tool is declared.\n * Names should be descriptive and use kebab-case or snake_case.\n *\n * @example \"calculate-sum\"\n * @example \"get_weather\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier. Clients use `title` in\n * tool palettes / picker UIs.\n *\n * @example \"Search Lore\"\n */\n title?: string;\n\n /**\n * A human-readable description of what the tool does.\n *\n * This description is sent to the LLM to help it understand\n * when and how to use the tool. Be clear and specific.\n *\n * @example \"Calculate the sum of two numbers\"\n * @example \"Retrieve current weather data for a given location\"\n */\n description: string;\n\n /**\n * Behavior hints (spec 2025-03-26+). Clients use these to gate UI prompts\n * (e.g. require confirmation before a tool with `destructiveHint: true`).\n * None are guarantees — they are heuristics for the client, not the model.\n */\n annotations?: McpToolAnnotations;\n\n /**\n * Icons surfaced in client tool palettes / picker UIs (spec 2025-11-25).\n */\n icons?: McpIcon[];\n\n /**\n * TypeBox schema defining the tool's parameters and result type.\n *\n * - **params**: TObject schema for input parameters (optional)\n * - **result**: TSchema for the return value (optional)\n *\n * Schemas provide:\n * - Type inference for handler function\n * - Runtime validation of inputs\n * - JSON Schema generation for MCP protocol\n */\n schema?: T;\n\n /**\n * The handler function that executes when the tool is called.\n *\n * Receives validated parameters and returns the result.\n * Errors thrown here are caught and returned as MCP errors.\n *\n * @param args - Object containing validated params\n * @returns The tool result (can be async)\n */\n handler: (args: ToolHandlerArgs<T>) => Async<ToolHandlerResult<T>>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class ToolPrimitive<T extends ToolPrimitiveSchema> extends Primitive<\n ToolPrimitiveOptions<T>\n> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the tool.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the description of the tool.\n */\n public get description(): string {\n return this.options.description;\n }\n\n /**\n * Whether the tool declared a result schema. When true, `tools/call`\n * responses include `structuredContent` populated with the validated\n * result (spec 2025-06-18).\n */\n public hasOutputSchema(): boolean {\n return !!this.options.schema?.result;\n }\n\n protected onInit(): void {\n this.mcpServer.registerTool(this);\n }\n\n /**\n * Execute the tool with the given parameters.\n *\n * @param params - Raw parameters to validate and pass to the handler\n * @param context - Optional context from the transport layer\n * @returns The tool result\n */\n public async execute(\n params: unknown,\n context?: McpContext,\n ): Promise<ToolHandlerResult<T>> {\n let validatedParams: any = params ?? {};\n\n // Validate params using alepha.codec if schema provided\n if (this.options.schema?.params) {\n validatedParams = this.alepha.codec.decode(\n this.options.schema.params,\n validatedParams,\n );\n }\n\n const result = await this.options.handler({\n params: validatedParams,\n context,\n });\n\n // Validate and encode result if schema provided\n if (this.options.schema?.result && result !== undefined) {\n return this.alepha.codec.encode(\n this.options.schema.result,\n result,\n ) as ToolHandlerResult<T>;\n }\n\n return result as ToolHandlerResult<T>;\n }\n\n /**\n * Convert the tool to an MCP tool descriptor for protocol messages.\n *\n * Emits the spec 2025-11-25 surface: `title`, `annotations`, `icons`,\n * and (when `schema.result` is defined) `outputSchema` so the server\n * can populate `structuredContent` on call results.\n */\n public toDescriptor(): McpToolDescriptor {\n const inputSchema: McpJsonSchema = this.options.schema?.params\n ? this.schemaToJsonSchema(this.options.schema.params)\n : { type: \"object\", properties: {}, required: [] };\n\n const descriptor: McpToolDescriptor = {\n name: this.name,\n description: this.description,\n inputSchema,\n };\n\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.annotations)\n descriptor.annotations = this.options.annotations;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n\n // Output schema is emitted when the tool declares `schema.result`,\n // unlocking structured content on tools/call responses.\n if (this.options.schema?.result) {\n const out = this.propertyToJsonSchema(this.options.schema.result);\n // The result schema may be a primitive — wrap so the descriptor\n // value is always a JSON Schema object with `type`.\n descriptor.outputSchema = (\n typeof out === \"object\" && out !== null && \"type\" in out\n ? out\n : { type: \"object\", properties: {}, required: [] }\n ) as McpJsonSchema;\n }\n\n return descriptor;\n }\n\n /**\n * Convert a TypeBox schema to JSON Schema format.\n *\n * Emits the 2020-12 dialect annotation at the root (spec 2025-11-25 /\n * SEP-1613 — JSON Schema 2020-12 is the default dialect for MCP).\n * The TypeBox shapes Alepha emits today are already 2020-12-compatible;\n * this is just the dialect declaration.\n */\n protected schemaToJsonSchema(\n schema: TObject,\n options?: { root?: boolean },\n ): McpJsonSchema {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n properties[key] = this.propertyToJsonSchema(propSchema as TSchema);\n\n // Check if property is required (not optional)\n if (!t.schema.isOptional(propSchema as TSchema)) {\n required.push(key);\n }\n }\n\n const result: McpJsonSchema = {\n type: \"object\",\n properties,\n required,\n };\n\n // Annotate the dialect on the root schema only (avoid noise on nested\n // sub-schemas where MCP doesn't expect $schema).\n if (options?.root !== false) {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n\n return result;\n }\n\n /**\n * Convert a single property schema to JSON Schema format.\n */\n protected propertyToJsonSchema(schema: TSchema): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n // Check for description on all types\n if (\"description\" in schema) {\n result.description = schema.description;\n }\n\n if (t.schema.isString(schema)) {\n result.type = \"string\";\n if (\"minLength\" in schema) result.minLength = schema.minLength;\n if (\"maxLength\" in schema) result.maxLength = schema.maxLength;\n if (\"pattern\" in schema) result.pattern = schema.pattern;\n if (\"enum\" in schema) result.enum = schema.enum;\n } else if (t.schema.isNumber(schema)) {\n result.type = \"number\";\n if (\"minimum\" in schema) result.minimum = schema.minimum;\n if (\"maximum\" in schema) result.maximum = schema.maximum;\n } else if (t.schema.isInteger(schema)) {\n result.type = \"integer\";\n if (\"minimum\" in schema) result.minimum = schema.minimum;\n if (\"maximum\" in schema) result.maximum = schema.maximum;\n } else if (t.schema.isBoolean(schema)) {\n result.type = \"boolean\";\n } else if (t.schema.isArray(schema)) {\n result.type = \"array\";\n if (\"items\" in schema) {\n result.items = this.propertyToJsonSchema(schema.items as TSchema);\n }\n } else if (t.schema.isObject(schema)) {\n Object.assign(result, this.schemaToJsonSchema(schema, { root: false }));\n } else if (t.schema.isUnsafe(schema) || t.schema.isOptional(schema)) {\n // Handle Unsafe types (like t.enum) and optional wrappers by checking the underlying type property\n const schemaAny = schema as { type?: string; enum?: unknown[] };\n if (schemaAny.type === \"string\") {\n result.type = \"string\";\n if (\"enum\" in schema) result.enum = schema.enum;\n if (\"pattern\" in schema) result.pattern = schema.pattern;\n } else if (schemaAny.type === \"number\") {\n result.type = \"number\";\n } else if (schemaAny.type === \"integer\") {\n result.type = \"integer\";\n } else if (schemaAny.type === \"boolean\") {\n result.type = \"boolean\";\n } else if (schemaAny.type === \"array\") {\n result.type = \"array\";\n } else if (schemaAny.type === \"object\") {\n result.type = \"object\";\n } else {\n // Fallback\n result.type = \"string\";\n }\n } else {\n // Fallback for other types\n result.type = \"string\";\n }\n\n return result;\n }\n}\n\n$tool[KIND] = ToolPrimitive;\n","import { $atom, $inject, $state, t } from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport { $route } from \"alepha/server\";\nimport {\n createErrorResponse,\n createParseError,\n JsonRpcParseError,\n parseMessage,\n} from \"../helpers/jsonrpc.ts\";\nimport type { McpContext } from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport const mcpStreamableHttpOptions = $atom({\n name: \"alepha.mcp.streamableHttp.options\",\n description: \"Configuration options for the MCP Streamable HTTP transport.\",\n schema: t.object({\n /**\n * Path for the MCP endpoint. Single endpoint for both requests and\n * (optional) server-streamed responses, per spec 2025-03-26+.\n */\n path: t.text({ default: \"/mcp\" }),\n /**\n * Allow-list of `Origin` header values accepted on incoming requests.\n * Empty array (default) means \"allow any\". When set, browser-originated\n * requests with a non-matching `Origin` are rejected with 403 Forbidden,\n * blocking DNS-rebinding attacks against localhost MCP servers.\n *\n * Server-to-server callers (no `Origin` header) are always allowed.\n *\n * Spec 2025-11-25, PR #1439.\n */\n allowedOrigins: t.array(t.text(), { default: [] }),\n }),\n default: {\n path: \"/mcp\",\n allowedOrigins: [],\n },\n});\n\n// Backward-compat alias for the legacy atom name. Prefer\n// `mcpStreamableHttpOptions` going forward; this re-export keeps existing\n// consumer imports compiling and will be removed once they migrate.\nexport const mcpSseOptions = mcpStreamableHttpOptions;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Streamable HTTP transport for MCP communication.\n *\n * Implements the 2025-03-26+ Streamable HTTP transport: a single `/mcp`\n * endpoint that accepts JSON-RPC over POST and returns either\n * `application/json` (single response, the default) or\n * `text/event-stream` (when the server wants to stream multiple messages).\n *\n * Designed for serverless deployment (Cloudflare Workers, etc.) — there is\n * no long-lived GET stream. GET on the endpoint returns 405 Method Not\n * Allowed; clients that want server-initiated push must rely on the POST\n * response stream when the server upgrades to SSE for that particular call.\n *\n * Spec compliance:\n * - 2025-06-18: validates `MCP-Protocol-Version` header on every request\n * after `initialize` against the version negotiated and stored on\n * `McpServerProvider`.\n * - 2025-11-25: rejects requests with a non-allow-listed `Origin` header\n * (PR #1439). See {@link mcpStreamableHttpOptions.allowedOrigins}.\n *\n * @example\n * ```ts\n * import { Alepha, run } from \"alepha\";\n * import { AlephaServer } from \"alepha/server\";\n * import { AlephaMcp, StreamableHttpMcpTransport } from \"alepha/mcp\";\n *\n * class MyTools {\n * // ... tool definitions\n * }\n *\n * run(\n * Alepha.create()\n * .with(AlephaServer)\n * .with(AlephaMcp)\n * .with(StreamableHttpMcpTransport)\n * .with(MyTools)\n * );\n * ```\n */\nexport class StreamableHttpMcpTransport {\n protected readonly log = $logger();\n protected readonly options = $state(mcpStreamableHttpOptions);\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * GET on the MCP endpoint is not supported in this transport. Returning\n * 405 (rather than serving the legacy two-endpoint SSE pattern) is the\n * spec-allowed response for servers that don't offer server-initiated\n * push outside of an active POST.\n */\n notAllowed = $route({\n method: \"GET\",\n path: this.options.path,\n handler: (request) => {\n request.reply.status = 405;\n request.reply.headers.allow = \"POST\";\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: \"Method Not Allowed. Use POST for MCP messages.\",\n });\n },\n });\n\n /**\n * POST endpoint for client-to-server JSON-RPC messages.\n * Returns `application/json` for single responses; tools that need to\n * stream progress would upgrade to `text/event-stream` (deferred until a\n * concrete need exists).\n */\n message = $route({\n method: \"POST\",\n path: this.options.path,\n schema: {\n body: t.json(),\n },\n handler: async (request) => {\n try {\n // Origin allow-list check (spec 2025-11-25 / PR #1439).\n const originRaw = request.headers.origin;\n const origin = Array.isArray(originRaw) ? originRaw[0] : originRaw;\n if (\n origin &&\n this.options.allowedOrigins.length > 0 &&\n !this.options.allowedOrigins.includes(origin)\n ) {\n this.log.warn(\"Rejected MCP request with non-allowed Origin\", {\n origin,\n allowed: this.options.allowedOrigins,\n });\n request.reply.status = 403;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: \"Forbidden: Origin not allowed\",\n });\n return;\n }\n\n const body =\n typeof request.body === \"string\"\n ? request.body\n : JSON.stringify(request.body);\n\n this.log.debug(\"MCP request body\", {\n body,\n bodyType: typeof request.body,\n });\n\n const rpcRequest = parseMessage(body);\n\n // Build context from request headers\n const headers = { ...request.headers } as Record<\n string,\n string | string[] | undefined\n >;\n\n // Spec 2025-06-18+: every HTTP request after `initialize` MUST carry\n // an `MCP-Protocol-Version` header matching the negotiated version.\n // Reject mismatches with 400 so the client doesn't silently drift.\n if (rpcRequest.method !== \"initialize\") {\n const headerRaw = headers[\"mcp-protocol-version\"];\n const headerVersion = Array.isArray(headerRaw)\n ? headerRaw[0]\n : headerRaw;\n if (\n headerVersion &&\n headerVersion !== this.mcpServer.negotiatedVersion\n ) {\n this.log.warn(\"MCP-Protocol-Version header mismatch\", {\n header: headerVersion,\n negotiated: this.mcpServer.negotiatedVersion,\n });\n request.reply.status = 400;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: `MCP-Protocol-Version mismatch: expected ${this.mcpServer.negotiatedVersion}, got ${headerVersion}`,\n });\n return;\n }\n }\n\n const context: McpContext = { headers };\n\n const response = await this.mcpServer.handleMessage(\n rpcRequest,\n context,\n );\n\n if (response) {\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify(response);\n } else {\n request.reply.status = 204;\n }\n } catch (error) {\n if (error instanceof JsonRpcParseError) {\n request.reply.status = 400;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify(\n createErrorResponse(0, createParseError(error.message)),\n );\n } else {\n this.log.error(\"Failed to process MCP message\", error);\n request.reply.status = 500;\n request.reply.body = JSON.stringify({\n error: (error as Error).message,\n });\n }\n }\n },\n });\n}\n\n/**\n * @deprecated Use {@link StreamableHttpMcpTransport}. The 2024-11-05\n * two-endpoint HTTP+SSE pattern was replaced by Streamable HTTP in spec\n * 2025-03-26. This alias is preserved for one release to ease migration.\n */\nexport const SseMcpTransport = StreamableHttpMcpTransport;\n","import { $module } from \"alepha\";\nimport { $prompt } from \"./primitives/$prompt.ts\";\nimport { $resource } from \"./primitives/$resource.ts\";\nimport { $tool } from \"./primitives/$tool.ts\";\nimport { McpServerProvider } from \"./providers/McpServerProvider.ts\";\nimport { StreamableHttpMcpTransport } from \"./transports/StreamableHttpMcpTransport.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport {\n McpError,\n McpErrorCodes,\n McpForbiddenError,\n McpInvalidParamsError,\n McpMethodNotFoundError,\n McpPromptNotFoundError,\n McpResourceNotFoundError,\n McpToolNotFoundError,\n McpUnauthorizedError,\n} from \"./errors/McpError.ts\";\nexport {\n createErrorResponse,\n createInternalError,\n createInvalidParamsError,\n createInvalidRequestError,\n createMethodNotFoundError,\n createNotification,\n createParseError,\n createResponse,\n isNotification,\n isSupportedProtocolVersion,\n isValidJsonRpcRequest,\n JSONRPC_VERSION,\n JsonRpcErrorCodes,\n JsonRpcParseError,\n MCP_PROTOCOL_VERSION,\n parseMessage,\n SUPPORTED_PROTOCOL_VERSIONS,\n type SupportedProtocolVersion,\n} from \"./helpers/jsonrpc.ts\";\nexport type {\n JsonRpcError,\n JsonRpcNotification,\n // JSON-RPC types\n JsonRpcRequest,\n JsonRpcResponse,\n // MCP protocol types\n McpCapabilities,\n McpClientInfo,\n McpContent,\n // Context type for auth/headers\n McpContext,\n McpInitializeParams,\n McpInitializeResult,\n McpJsonSchema,\n McpPromptArgument,\n McpPromptContent,\n // Prompt types\n McpPromptDescriptor,\n McpPromptGetParams,\n McpPromptGetResult,\n McpPromptMessage,\n McpResourceContent,\n // Resource types\n McpResourceDescriptor,\n McpResourceReadParams,\n McpResourceReadResult,\n McpServerInfo,\n McpToolCallParams,\n McpToolCallResult,\n // Tool types\n McpToolDescriptor,\n PromptHandler,\n PromptHandlerArgs,\n PromptMessage,\n ResourceContent,\n ResourceHandler,\n ResourceHandlerArgs,\n ToolHandler,\n ToolHandlerArgs,\n ToolHandlerResult,\n // Handler types\n ToolPrimitiveSchema,\n} from \"./interfaces/McpTypes.ts\";\nexport type { PromptPrimitiveOptions } from \"./primitives/$prompt.ts\";\nexport { $prompt, PromptPrimitive } from \"./primitives/$prompt.ts\";\nexport type { ResourcePrimitiveOptions } from \"./primitives/$resource.ts\";\nexport { $resource, ResourcePrimitive } from \"./primitives/$resource.ts\";\nexport type { ToolPrimitiveOptions } from \"./primitives/$tool.ts\";\nexport { $tool, ToolPrimitive } from \"./primitives/$tool.ts\";\nexport { McpServerProvider } from \"./providers/McpServerProvider.ts\";\nexport {\n mcpSseOptions,\n mcpStreamableHttpOptions,\n SseMcpTransport,\n StreamableHttpMcpTransport,\n} from \"./transports/StreamableHttpMcpTransport.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Model Context Protocol for AI tool integration.\n *\n * **Features:**\n * - MCP resource definitions\n * - MCP tool definitions\n * - MCP prompt definitions\n * - JSON-RPC protocol\n * - Streamable HTTP transport (spec 2025-03-26+)\n *\n * @module alepha.mcp\n */\nexport const AlephaMcp = $module({\n name: \"alepha.mcp\",\n primitives: [$tool, $resource, $prompt],\n services: [McpServerProvider],\n // Transports are opt-in — user wires the one(s) they need via alepha.with(StreamableHttpMcpTransport).\n variants: [StreamableHttpMcpTransport],\n});\n"],"mappings":";;;;AAYA,MAAa,kBAAkB;;;;;AAM/B,MAAa,uBAAuB;;;;;;AAOpC,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;CACD;AAKD,MAAa,8BACX,MAEA,OAAO,MAAM,YACZ,4BAAkD,SAAS,EAAE;AAEhE,MAAa,oBAAoB;CAC/B,aAAa;CACb,iBAAiB;CACjB,kBAAkB;CAClB,gBAAgB;CAChB,gBAAgB;CACjB;AAMD,SAAgB,eACd,IACA,QACiB;CACjB,OAAO;EACL,SAAA;EACA;EACA;EACD;;AAGH,SAAgB,oBACd,IACA,O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DbColumnNotFoundError.ts","../../../src/orm/core/errors/DbConnectionError.ts","../../../src/orm/core/errors/DbDeadlockError.ts","../../../src/orm/core/errors/DbEntityNotFoundError.ts","../../../src/orm/core/errors/DbForeignKeyError.ts","../../../src/orm/core/errors/DbNotNullError.ts","../../../src/orm/core/errors/DbTableNotFoundError.ts","../../../src/orm/core/helpers/pgAttr.ts","../../../src/orm/core/constants/PG_SYMBOLS.ts","../../../src/orm/core/schemas/insertSchema.ts","../../../src/orm/core/schemas/updateSchema.ts","../../../src/orm/core/primitives/$entity.ts","../../../src/orm/core/providers/DatabaseTypeProvider.ts","../../../src/orm/core/schemas/legacyIdSchema.ts","../../../src/orm/core/index.browser.ts"],"sourcesContent":["import { AlephaError } from \"alepha\";\n\nexport class DbError extends AlephaError {\n name = \"DbError\";\n\n constructor(message: string, cause?: unknown) {\n super(message, { cause });\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a column does not exist.\n *\n * This typically happens when:\n * - Column name is misspelled\n * - Migrations haven't been run\n * - Using wrong schema version\n */\nexport class DbColumnNotFoundError extends DbError {\n readonly name = \"DbColumnNotFoundError\";\n readonly status = 500;\n\n /**\n * The column that was not found.\n */\n readonly column?: string;\n\n /**\n * The table where the column was expected.\n */\n readonly table?: string;\n\n constructor(\n message: string,\n cause?: unknown,\n options?: { column?: string; table?: string },\n ) {\n super(message, cause);\n this.column = options?.column;\n this.table = options?.table;\n }\n\n /**\n * Parse a database column not found error and create a DbColumnNotFoundError.\n * Supports both PostgreSQL and SQLite error formats.\n */\n static fromDatabaseError(error: Error): DbColumnNotFoundError {\n const message = error.message;\n\n // PostgreSQL format:\n // 'column \"foo\" does not exist'\n // 'column \"foo\" of relation \"users\" does not exist'\n const pgMatch = message.match(\n /column \"([^\"]+)\"(?: of relation \"([^\"]+)\")? does not exist/,\n );\n\n if (pgMatch) {\n const column = pgMatch[1];\n const table = pgMatch[2];\n const msg = table\n ? `Column '${column}' does not exist in table '${table}'`\n : `Column '${column}' does not exist`;\n return new DbColumnNotFoundError(msg, error, { column, table });\n }\n\n // SQLite format:\n // 'no such column: foo'\n // 'no such column: users.foo'\n const sqliteMatch = message.match(/no such column: (?:(\\S+)\\.)?(\\S+)/);\n\n if (sqliteMatch) {\n const table = sqliteMatch[1];\n const column = sqliteMatch[2];\n const msg = table\n ? `Column '${column}' does not exist in table '${table}'`\n : `Column '${column}' does not exist`;\n return new DbColumnNotFoundError(msg, error, { column, table });\n }\n\n return new DbColumnNotFoundError(\"Column does not exist\", error);\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a database connection fails.\n *\n * This can happen due to:\n * - Connection refused (server not running)\n * - Connection timeout\n * - Authentication failure\n * - Network issues\n * - Database file not found (SQLite)\n */\nexport class DbConnectionError extends DbError {\n readonly name = \"DbConnectionError\";\n readonly status = 503;\n\n /**\n * The type of connection error.\n */\n readonly errorType?:\n | \"refused\"\n | \"timeout\"\n | \"auth\"\n | \"not_found\"\n | \"locked\"\n | \"unknown\";\n\n /**\n * Whether this error is retryable.\n * Connection errors are often transient and can be retried.\n */\n readonly retryable: boolean;\n\n constructor(\n message: string,\n cause?: unknown,\n options?: {\n errorType?: DbConnectionError[\"errorType\"];\n retryable?: boolean;\n },\n ) {\n super(message, cause);\n this.errorType = options?.errorType;\n this.retryable = options?.retryable ?? true;\n }\n\n /**\n * Parse a database connection error message and create a DbConnectionError.\n * Supports both PostgreSQL and SQLite error formats.\n */\n static fromDatabaseError(error: Error): DbConnectionError {\n const message = error.message.toLowerCase();\n\n // Connection refused\n if (\n message.includes(\"connection refused\") ||\n message.includes(\"econnrefused\") ||\n message.includes(\"could not connect\")\n ) {\n return new DbConnectionError(\n \"Database connection refused. Is the server running?\",\n error,\n { errorType: \"refused\", retryable: true },\n );\n }\n\n // Timeout\n if (\n message.includes(\"timeout\") ||\n message.includes(\"timed out\") ||\n message.includes(\"etimedout\")\n ) {\n return new DbConnectionError(\"Database connection timed out\", error, {\n errorType: \"timeout\",\n retryable: true,\n });\n }\n\n // Authentication\n if (\n message.includes(\"password authentication failed\") ||\n message.includes(\"authentication failed\") ||\n message.includes(\"access denied\")\n ) {\n return new DbConnectionError(\n \"Database authentication failed. Check credentials.\",\n error,\n { errorType: \"auth\", retryable: false },\n );\n }\n\n // SQLite file not found\n if (\n message.includes(\"unable to open database\") ||\n message.includes(\"no such file\") ||\n message.includes(\"enoent\")\n ) {\n return new DbConnectionError(\"Database file not found\", error, {\n errorType: \"not_found\",\n retryable: false,\n });\n }\n\n // SQLite database locked\n if (message.includes(\"database is locked\")) {\n return new DbConnectionError(\n \"Database is locked by another process\",\n error,\n { errorType: \"locked\", retryable: true },\n );\n }\n\n return new DbConnectionError(\"Failed to connect to database\", error, {\n errorType: \"unknown\",\n retryable: true,\n });\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a deadlock is detected.\n *\n * This happens when two or more transactions are waiting for each other\n * to release locks. The database automatically aborts one transaction\n * to resolve the deadlock.\n *\n * This error is useful for implementing retry logic.\n */\nexport class DbDeadlockError extends DbError {\n readonly name = \"DbDeadlockError\";\n readonly status = 409;\n\n /**\n * Whether this error is retryable.\n * Deadlocks are typically safe to retry.\n */\n readonly retryable = true;\n\n /**\n * Parse a database deadlock error message and create a DbDeadlockError.\n * Supports PostgreSQL. SQLite doesn't have true deadlocks (uses SQLITE_BUSY instead).\n */\n static fromDatabaseError(error: Error): DbDeadlockError {\n return new DbDeadlockError(\n \"Transaction deadlock detected. Please retry the operation.\",\n error,\n );\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\nexport class DbEntityNotFoundError extends DbError {\n readonly name = \"DbEntityNotFoundError\";\n readonly status = 404;\n\n constructor(entityName: string) {\n super(`Entity from '${entityName}' was not found`);\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a foreign key constraint is violated.\n *\n * This typically happens when trying to delete an entity that is\n * referenced by another entity.\n */\nexport class DbForeignKeyError extends DbError {\n readonly name = \"DbForeignKeyError\";\n readonly status = 409;\n\n /**\n * The table that references the entity being deleted.\n */\n readonly referencingTable?: string;\n\n /**\n * The constraint name that was violated.\n */\n readonly constraintName?: string;\n\n constructor(\n message: string,\n cause?: unknown,\n options?: { referencingTable?: string; constraintName?: string },\n ) {\n super(message, cause);\n this.referencingTable = options?.referencingTable;\n this.constraintName = options?.constraintName;\n }\n\n /**\n * Parse a database foreign key error message and create a DbForeignKeyError.\n * Supports both PostgreSQL and SQLite error formats.\n */\n static fromDatabaseError(error: Error, tableName: string): DbForeignKeyError {\n const message = error.message;\n\n // PostgreSQL format:\n // 'violates foreign key constraint \"reporting_alert_query_id_fk\" on table \"reporting_alert\"'\n const pgMatch = message.match(\n /violates foreign key constraint \"([^\"]+)\" on table \"([^\"]+)\"/,\n );\n\n if (pgMatch) {\n const constraintName = pgMatch[1];\n const referencingTable = pgMatch[2];\n\n return new DbForeignKeyError(\n `Cannot delete ${tableName}: it is referenced by ${referencingTable}`,\n error,\n { referencingTable, constraintName },\n );\n }\n\n // SQLite format:\n // 'FOREIGN KEY constraint failed' (no table name available)\n return new DbForeignKeyError(\n `Cannot delete ${tableName}: it is referenced by another entity`,\n error,\n );\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a NOT NULL constraint is violated.\n *\n * This happens when inserting or updating a NULL value into a column\n * that has a NOT NULL constraint.\n */\nexport class DbNotNullError extends DbError {\n readonly name = \"DbNotNullError\";\n readonly status = 400;\n\n /**\n * The column that violated the NOT NULL constraint.\n */\n readonly column?: string;\n\n /**\n * The table containing the column.\n */\n readonly table?: string;\n\n constructor(\n message: string,\n cause?: unknown,\n options?: { column?: string; table?: string },\n ) {\n super(message, cause);\n this.column = options?.column;\n this.table = options?.table;\n }\n\n /**\n * Parse a database NOT NULL error message and create a DbNotNullError.\n * Supports both PostgreSQL and SQLite error formats.\n */\n static fromDatabaseError(error: Error, tableName: string): DbNotNullError {\n const message = error.message;\n\n // PostgreSQL format:\n // 'null value in column \"email\" of relation \"users\" violates not-null constraint'\n const pgMatch = message.match(\n /null value in column \"([^\"]+)\" of relation \"([^\"]+)\" violates not-null constraint/,\n );\n\n if (pgMatch) {\n const column = pgMatch[1];\n const table = pgMatch[2];\n return new DbNotNullError(\n `Column '${column}' in '${table}' cannot be null`,\n error,\n { column, table },\n );\n }\n\n // SQLite format:\n // 'NOT NULL constraint failed: users.email'\n const sqliteMatch = message.match(\n /NOT NULL constraint failed: ([^.]+)\\.(\\S+)/,\n );\n\n if (sqliteMatch) {\n const table = sqliteMatch[1];\n const column = sqliteMatch[2];\n return new DbNotNullError(\n `Column '${column}' in '${table}' cannot be null`,\n error,\n { column, table },\n );\n }\n\n return new DbNotNullError(\n `A required field in '${tableName}' cannot be null`,\n error,\n );\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a table does not exist.\n *\n * This typically happens when:\n * - Migrations haven't been run\n * - Table name is misspelled\n * - Wrong database/schema is being used\n */\nexport class DbTableNotFoundError extends DbError {\n readonly name = \"DbTableNotFoundError\";\n readonly status = 500;\n\n /**\n * The table that was not found.\n */\n readonly table?: string;\n\n constructor(message: string, cause?: unknown, options?: { table?: string }) {\n super(message, cause);\n this.table = options?.table;\n }\n\n /**\n * Parse a database table not found error and create a DbTableNotFoundError.\n * Supports both PostgreSQL and SQLite error formats.\n */\n static fromDatabaseError(error: Error): DbTableNotFoundError {\n const message = error.message;\n\n // PostgreSQL format:\n // 'relation \"users\" does not exist'\n const pgMatch = message.match(/relation \"([^\"]+)\" does not exist/);\n\n if (pgMatch) {\n const table = pgMatch[1];\n return new DbTableNotFoundError(\n `Table '${table}' does not exist. Have you run migrations?`,\n error,\n { table },\n );\n }\n\n // SQLite format:\n // 'no such table: users'\n const sqliteMatch = message.match(/no such table: (\\S+)/);\n\n if (sqliteMatch) {\n const table = sqliteMatch[1];\n return new DbTableNotFoundError(\n `Table '${table}' does not exist. Have you run migrations?`,\n error,\n { table },\n );\n }\n\n return new DbTableNotFoundError(\n \"Table does not exist. Have you run migrations?\",\n error,\n );\n }\n}\n","import type { TObject, TSchema } from \"alepha\";\nimport type { PgSymbolKeys, PgSymbols } from \"../constants/PG_SYMBOLS.ts\";\n\n/**\n * Decorates a typebox schema with a Postgres attribute.\n *\n * > It's just a fancy way to add Symbols to a field.\n *\n * @example\n * ```ts\n * import { t } from \"alepha\";\n * import { PG_UPDATED_AT } from \"../constants/PG_SYMBOLS\";\n *\n * export const updatedAtSchema = pgAttr(\n * t.datetime(), PG_UPDATED_AT,\n * );\n * ```\n */\nexport const pgAttr = <T extends TSchema, Attr extends PgSymbolKeys>(\n type: T,\n attr: Attr,\n value?: PgSymbols[Attr],\n): PgAttr<T, Attr> => {\n Object.assign(type, { [attr]: value ?? {} });\n return type as PgAttr<T, Attr>;\n};\n\n/**\n * Retrieves the fields of a schema that have a specific attribute.\n */\nexport const getAttrFields = (\n schema: TObject,\n name: PgSymbolKeys,\n): PgAttrField[] => {\n const fields: Array<PgAttrField> = [];\n\n for (const key of Object.keys(schema.properties)) {\n const value = schema.properties[key];\n if (name in value) {\n fields.push({\n type: value as TSchema,\n key: key,\n data: (value as any)[name],\n });\n }\n }\n\n return fields;\n};\n\n/**\n * Type representation.\n */\nexport type PgAttr<T extends TSchema, TAttr extends PgSymbolKeys> = T & {\n [K in TAttr]: PgSymbols[K];\n};\n\nexport interface PgAttrField {\n key: string;\n type: TSchema;\n data: any;\n nested?: any[];\n one?: boolean;\n}\n","import type { SQL } from \"drizzle-orm\";\nimport type {\n PgSequenceOptions,\n UpdateDeleteAction,\n} from \"drizzle-orm/pg-core\";\nimport type { EntityPrimitive } from \"../primitives/$entity.ts\";\n\nexport const PG_DEFAULT = Symbol.for(\"Alepha.Postgres.Default\");\nexport const PG_PRIMARY_KEY = Symbol.for(\"Alepha.Postgres.PrimaryKey\");\nexport const PG_CREATED_AT = Symbol.for(\"Alepha.Postgres.CreatedAt\");\nexport const PG_UPDATED_AT = Symbol.for(\"Alepha.Postgres.UpdatedAt\");\nexport const PG_DELETED_AT = Symbol.for(\"Alepha.Postgres.DeletedAt\");\nexport const PG_VERSION = Symbol.for(\"Alepha.Postgres.Version\");\nexport const PG_IDENTITY = Symbol.for(\"Alepha.Postgres.Identity\");\nexport const PG_ENUM = Symbol.for(\"Alepha.Postgres.Enum\");\nexport const PG_REF = Symbol.for(\"Alepha.Postgres.Ref\");\nexport const PG_GENERATED = Symbol.for(\"Alepha.Postgres.Generated\");\nexport const PG_ORGANIZATION = Symbol.for(\"Alepha.Postgres.Organization\");\n\n/**\n * @deprecated Use `PG_IDENTITY` instead.\n */\nexport const PG_SERIAL = Symbol.for(\"Alepha.Postgres.Serial\");\n\nexport type PgDefault = typeof PG_DEFAULT;\nexport type PgRef = typeof PG_REF;\nexport type PgPrimaryKey = typeof PG_PRIMARY_KEY;\n\nexport type PgSymbols = {\n [PG_DEFAULT]: {};\n [PG_PRIMARY_KEY]: {};\n [PG_CREATED_AT]: {};\n [PG_UPDATED_AT]: {};\n [PG_DELETED_AT]: {};\n [PG_VERSION]: {};\n [PG_IDENTITY]: PgIdentityOptions;\n [PG_REF]: PgRefOptions;\n [PG_ENUM]: PgEnumOptions;\n [PG_GENERATED]: PgGeneratedOptions;\n [PG_ORGANIZATION]: {};\n\n /**\n * @deprecated Use `PG_IDENTITY` instead.\n */\n [PG_SERIAL]: {};\n};\n\nexport type PgSymbolKeys = keyof PgSymbols;\n\nexport type PgIdentityOptions = {\n mode: \"always\" | \"byDefault\";\n} & PgSequenceOptions & {\n name?: string;\n };\n\nexport interface PgEnumOptions {\n name?: string;\n description?: string;\n}\n\nexport interface PgGeneratedOptions {\n /**\n * SQL expression for the generated column.\n */\n expression: SQL;\n\n /**\n * Storage mode for the generated column.\n * - `\"stored\"` — value is computed on write and stored on disk (default for PostgreSQL).\n * - `\"virtual\"` — value is computed on read (default for SQLite).\n */\n mode?: \"stored\" | \"virtual\";\n}\n\nexport interface PgRefOptions {\n ref: () => {\n name: string;\n entity: EntityPrimitive;\n };\n actions?: {\n onUpdate?: UpdateDeleteAction;\n onDelete?: UpdateDeleteAction;\n };\n}\n","import type { TObject, TOptional } from \"alepha\";\nimport { t } from \"alepha\";\nimport { PG_DEFAULT, PG_GENERATED } from \"../constants/PG_SYMBOLS.ts\";\n\n/**\n * Transforms a TObject schema for insert operations.\n * All default properties at the root level are made optional.\n * Generated columns are excluded entirely.\n *\n * @example\n * Before: { name: string; age: number(default=0); fullName: generated }\n * After: { name: string; age?: number; }\n */\nexport type TObjectInsert<T extends TObject> = TObject<{\n [K in keyof T[\"properties\"] as T[\"properties\"][K] extends {\n [PG_GENERATED]: any;\n }\n ? never\n : K]: T[\"properties\"][K] extends\n | { [PG_DEFAULT]: any }\n | { \"~optional\": true }\n ? TOptional<T[\"properties\"][K]>\n : T[\"properties\"][K];\n}>;\n\nexport const insertSchema = <T extends TObject>(obj: T): TObjectInsert<T> => {\n const newProperties: Record<string, any> = {};\n\n for (const key in obj.properties) {\n const prop = obj.properties[key];\n\n // Skip generated columns — they are computed by the database\n if (PG_GENERATED in prop) {\n continue;\n }\n\n if (PG_DEFAULT in prop) {\n newProperties[key] = t.optional(prop);\n } else {\n newProperties[key] = prop;\n }\n }\n\n return t.object(\n newProperties,\n \"options\" in obj && typeof obj.options === \"object\"\n ? { ...obj.options }\n : {},\n ) as TObjectInsert<T>;\n};\n","import {\n type TNull,\n type TObject,\n type TOptional,\n type TUnion,\n t,\n} from \"alepha\";\nimport { PG_GENERATED } from \"../constants/PG_SYMBOLS.ts\";\n\n/**\n * Transforms a TObject schema for update operations.\n * All optional properties at the root level are made nullable (i.e., `T | null`).\n * Generated columns are excluded entirely.\n *\n * @example\n * Before: { name?: string; age: number; fullName: generated }\n * After: { name?: string | null; age: number; }\n */\nexport type TObjectUpdate<T extends TObject> = TObject<{\n [K in keyof T[\"properties\"] as T[\"properties\"][K] extends {\n [PG_GENERATED]: any;\n }\n ? never\n : K]: T[\"properties\"][K] extends TOptional<infer U>\n ? TOptional<TUnion<[U, TNull]>>\n : T[\"properties\"][K];\n}>;\n\nexport const updateSchema = <T extends TObject>(\n schema: T,\n): TObjectUpdate<T> => {\n const newProperties: Record<string, any> = {};\n\n for (const key in schema.properties) {\n const prop = schema.properties[key];\n\n // Skip generated columns — they are computed by the database\n if (PG_GENERATED in prop) {\n continue;\n }\n\n if (t.schema.isOptional(prop)) {\n newProperties[key] = t.optional(t.union([prop, t.null()]));\n } else {\n newProperties[key] = prop;\n }\n }\n\n return t.object(\n newProperties,\n \"options\" in schema && typeof schema.options === \"object\"\n ? { ...schema.options }\n : {},\n ) as TObjectUpdate<T>;\n};\n","import { KIND, type Static, type TObject } from \"alepha\";\nimport type { BuildExtraConfigColumns, SQL } from \"drizzle-orm\";\nimport type {\n PgColumn,\n PgColumnBuilderBase,\n PgTableExtraConfigValue,\n} from \"drizzle-orm/pg-core\";\nimport { insertSchema, type TObjectInsert } from \"../schemas/insertSchema.ts\";\nimport { type TObjectUpdate, updateSchema } from \"../schemas/updateSchema.ts\";\n\n/**\n * Creates a database entity primitive that defines table structure using TypeBox schemas.\n *\n * @example\n * ```ts\n * import { t } from \"alepha\";\n * import { $entity } from \"alepha/orm\";\n *\n * const userEntity = $entity({\n * name: \"users\",\n * schema: t.object({\n * id: pg.primaryKey(),\n * name: t.text(),\n * email: t.email(),\n * }),\n * });\n * ```\n */\nexport const $entity = <TSchema extends TObject>(\n options: EntityPrimitiveOptions<TSchema>,\n): EntityPrimitive<TSchema> => {\n return new EntityPrimitive<TSchema>(options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface EntityPrimitiveOptions<\n T extends TObject,\n Keys = keyof Static<T>,\n> {\n /**\n * The database table name that will be created for this entity.\n * If not provided, name will be inferred from the $repository variable name.\n */\n name: string;\n\n /**\n * TypeBox schema defining the table structure and column types.\n */\n schema: T;\n\n /**\n * Database indexes to create for query optimization.\n */\n indexes?: (\n | Keys\n | {\n /**\n * Single column to index.\n */\n column: Keys;\n /**\n * Whether this should be a unique index (enforces uniqueness constraint).\n */\n unique?: boolean;\n /**\n * Custom name for the index. If not provided, generates name automatically.\n */\n name?: string;\n /**\n * Partial index condition. Only rows matching this SQL expression are indexed.\n */\n where?: SQL;\n }\n | {\n /**\n * Multiple columns for composite index (order matters for query optimization).\n */\n columns: Keys[];\n /**\n * Whether this should be a unique index (enforces uniqueness constraint).\n */\n unique?: boolean;\n /**\n * Custom name for the index. If not provided, generates name automatically.\n */\n name?: string;\n /**\n * Partial index condition. Only rows matching this SQL expression are indexed.\n */\n where?: SQL;\n }\n | {\n /**\n * SQL expressions for expression-based indexes.\n *\n * Can include column references and SQL functions like `LOWER()`, `UPPER()`, etc.\n * Columns and expressions can be mixed together.\n *\n * @example\n * ```ts\n * // Case-insensitive unique username per realm\n * indexes: [{\n * expressions: (self) => [self.realm, sql`LOWER(${self.username})`],\n * unique: true,\n * name: \"users_realm_username_lower_idx\",\n * }]\n * ```\n */\n expressions: (self: Record<Keys & string, any>) => (SQL | any)[];\n /**\n * Whether this should be a unique index (enforces uniqueness constraint).\n */\n unique?: boolean;\n /**\n * Custom name for the index. If not provided, generates name automatically.\n */\n name: string;\n /**\n * Partial index condition. Only rows matching this SQL expression are indexed.\n */\n where?: SQL;\n }\n )[];\n\n /**\n * Foreign key constraints to maintain referential integrity.\n */\n foreignKeys?: Array<{\n /**\n * Optional name for the foreign key constraint.\n */\n name?: string;\n /**\n * Local columns that reference the foreign table.\n */\n columns: Array<keyof Static<T>>;\n /**\n * Referenced columns in the foreign table.\n * Must be EntityColumn references from other entities.\n */\n foreignColumns: Array<() => EntityColumn<any>>;\n }>;\n\n /**\n * Additional table constraints for data validation.\n *\n * Constraints enforce business rules at the database level, providing\n * an additional layer of data integrity beyond application validation.\n *\n * **Constraint Types**:\n * - **Unique constraints**: Prevent duplicate values across columns\n * - **Check constraints**: Enforce custom validation rules with SQL expressions\n *\n * @example\n * ```ts\n * constraints: [\n * {\n * name: \"unique_user_email\",\n * columns: [\"email\"],\n * unique: true\n * },\n * {\n * name: \"valid_age_range\",\n * columns: [\"age\"],\n * check: sql`age >= 0 AND age <= 150`\n * },\n * {\n * name: \"unique_user_username_per_tenant\",\n * columns: [\"tenantId\", \"username\"],\n * unique: true\n * }\n * ]\n * ```\n */\n constraints?: Array<{\n /**\n * Columns involved in this constraint.\n */\n columns: Array<keyof Static<T>>;\n /**\n * Optional name for the constraint.\n */\n name?: string;\n /**\n * Whether this is a unique constraint.\n */\n unique?: boolean | {} /* options */;\n /**\n * SQL expression for check constraint validation.\n */\n check?: SQL;\n }>;\n\n /**\n * Advanced Drizzle ORM configuration for complex table setups.\n */\n config?: (\n self: BuildExtraConfigColumns<string, FromSchema<T>, \"pg\">,\n ) => PgTableExtraConfigValue[];\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class EntityPrimitive<T extends TObject = TObject> {\n public readonly options: EntityPrimitiveOptions<T>;\n\n constructor(options: EntityPrimitiveOptions<T>) {\n this.options = options;\n }\n\n alias(alias: string): this {\n const aliased = new EntityPrimitive<T>(this.options);\n return new Proxy(aliased, {\n get(target, prop, receiver) {\n if (prop === \"$alias\") {\n return alias;\n }\n return Reflect.get(target, prop, receiver);\n },\n }) as this;\n }\n\n get cols(): EntityColumns<T> {\n const cols: Partial<EntityColumns<T>> = {};\n for (const key of Object.keys(this.schema.properties) as Array<\n keyof T[\"properties\"]\n >) {\n cols[key] = {\n name: key as string,\n entity: this,\n };\n }\n\n return cols as EntityColumns<T>;\n }\n\n get name(): string {\n return this.options.name;\n }\n\n get schema(): T {\n return this.options.schema;\n }\n\n get insertSchema(): TObjectInsert<T> {\n return insertSchema(this.options.schema);\n }\n\n get updateSchema(): TObjectUpdate<T> {\n return updateSchema(this.options.schema);\n }\n}\n\n$entity[KIND] = EntityPrimitive;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Convert a schema to columns.\n */\nexport type FromSchema<T extends TObject> = {\n [key in keyof T[\"properties\"]]: PgColumnBuilderBase;\n};\n\nexport type SchemaToTableConfig<T extends TObject> = {\n name: string;\n schema: string | undefined;\n columns: {\n [key in keyof T[\"properties\"]]: PgColumn;\n };\n dialect: string;\n};\n\nexport type EntityColumn<T extends TObject> = {\n name: string;\n entity: EntityPrimitive<T>;\n};\n\nexport type EntityColumns<T extends TObject> = {\n [key in keyof T[\"properties\"]]: EntityColumn<T>;\n};\n","import {\n AlephaError,\n pageSchema,\n type Static,\n type TBigInt,\n type TInteger,\n type TNumber,\n type TNumberOptions,\n type TObject,\n type TObjectOptions,\n type TPage,\n type TSchema,\n type TString,\n type TStringOptions,\n t,\n} from \"alepha\";\nimport type { UpdateDeleteAction } from \"drizzle-orm/pg-core/foreign-keys\";\nimport {\n PG_CREATED_AT,\n PG_DEFAULT,\n PG_DELETED_AT,\n PG_IDENTITY,\n PG_ORGANIZATION,\n PG_PRIMARY_KEY,\n PG_REF,\n PG_UPDATED_AT,\n PG_VERSION,\n type PgDefault,\n type PgIdentityOptions,\n type PgPrimaryKey,\n type PgRef,\n} from \"../constants/PG_SYMBOLS.ts\";\nimport type { PgAttr } from \"../helpers/pgAttr.ts\";\nimport { pgAttr } from \"../helpers/pgAttr.ts\";\n\nexport class DatabaseTypeProvider {\n public readonly attr = pgAttr;\n\n /**\n * Creates a primary key with an identity column.\n */\n public readonly identityPrimaryKey = (\n identity?: PgIdentityOptions,\n options?: TNumberOptions,\n ) =>\n pgAttr(\n pgAttr(pgAttr(t.integer(options), PG_PRIMARY_KEY), PG_IDENTITY, identity),\n PG_DEFAULT,\n );\n\n /**\n * Creates a primary key with a big identity column. (default)\n */\n public readonly bigIdentityPrimaryKey = (\n identity?: PgIdentityOptions,\n options?: TNumberOptions,\n ) =>\n pgAttr(\n pgAttr(pgAttr(t.int64(options), PG_PRIMARY_KEY), PG_IDENTITY, identity),\n PG_DEFAULT,\n );\n\n /**\n * Creates a primary key with a UUID column.\n */\n public readonly uuidPrimaryKey = () =>\n pgAttr(pgAttr(t.uuid(), PG_PRIMARY_KEY), PG_DEFAULT);\n\n /**\n * Creates a primary key for a given type. Supports:\n * - `t.integer()` -> PG INT (default)\n * - `t.bigint()` -> PG BIGINT\n * - `t.uuid()` -> PG UUID\n */\n public primaryKey(): PgAttr<PgAttr<TInteger, PgPrimaryKey>, PgDefault>;\n public primaryKey(\n type: TString,\n options?: TStringOptions,\n ): PgAttr<PgAttr<TString, PgPrimaryKey>, PgDefault>;\n public primaryKey(\n type: TInteger,\n options?: TNumberOptions,\n identity?: PgIdentityOptions,\n ): PgAttr<PgAttr<TInteger, PgPrimaryKey>, PgDefault>;\n public primaryKey(\n type: TNumber,\n options?: TNumberOptions,\n identity?: PgIdentityOptions,\n ): PgAttr<PgAttr<TNumber, PgPrimaryKey>, PgDefault>;\n public primaryKey(\n type: TBigInt,\n options?: TNumberOptions,\n identity?: PgIdentityOptions,\n ): PgAttr<PgAttr<TBigInt, PgPrimaryKey>, PgDefault>;\n public primaryKey(\n type?: TSchema,\n options?: TNumberOptions | TStringOptions,\n identity?: PgIdentityOptions,\n ): PgAttr<PgAttr<TSchema, PgPrimaryKey>, PgDefault> {\n if (!type || t.schema.isInteger(type)) {\n return pgAttr(\n pgAttr(\n pgAttr(t.integer(options), PG_PRIMARY_KEY),\n PG_IDENTITY,\n identity,\n ),\n PG_DEFAULT,\n );\n }\n\n if (t.schema.isString(type) && type.format === \"uuid\") {\n return pgAttr(pgAttr(t.uuid(), PG_PRIMARY_KEY), PG_DEFAULT);\n }\n\n if (t.schema.isNumber(type) && type.format === \"int64\") {\n return pgAttr(\n pgAttr(\n pgAttr(t.number(options), PG_PRIMARY_KEY),\n PG_IDENTITY,\n identity,\n ),\n PG_DEFAULT,\n );\n }\n\n if (t.schema.isBigInt(type)) {\n return pgAttr(\n pgAttr(\n pgAttr(t.bigint(options), PG_PRIMARY_KEY),\n PG_IDENTITY,\n identity,\n ),\n PG_DEFAULT,\n );\n }\n\n throw new AlephaError(`Unsupported type for primary key: ${type}`);\n }\n\n /**\n * Wrap a schema with \"default\" attribute.\n * This is used to set a default value for a column in the database.\n */\n public readonly default = <T extends TSchema>(\n type: T,\n value?: Static<T>,\n ): PgAttr<T, PgDefault> => {\n if (value != null) {\n Object.assign(type, { default: value });\n }\n\n return this.attr(type, PG_DEFAULT);\n };\n\n /**\n * Creates a column 'version'.\n *\n * This is used to track the version of a row in the database.\n *\n * You can use it for optimistic concurrency control (OCC) with {@link RepositoryPrimitive#save}.\n *\n * @see {@link RepositoryPrimitive#save}\n * @see {@link PgVersionMismatchError}\n */\n public readonly version = (options: TNumberOptions = {}) =>\n this.default(pgAttr(t.integer(options), PG_VERSION), 0);\n\n /**\n * Creates a column Created At. So just a datetime column with a default value of the current timestamp.\n */\n public readonly createdAt = (options?: TStringOptions) =>\n pgAttr(pgAttr(t.datetime(options), PG_CREATED_AT), PG_DEFAULT);\n\n /**\n * Creates a column Updated At. Like createdAt, but it is updated on every update of the row.\n */\n public readonly updatedAt = (options?: TStringOptions) =>\n pgAttr(pgAttr(t.datetime(options), PG_UPDATED_AT), PG_DEFAULT);\n\n /**\n * Creates a column Deleted At for soft delete functionality.\n * This is used to mark rows as deleted without actually removing them from the database.\n * The column is nullable - NULL means not deleted, timestamp means deleted.\n */\n public readonly deletedAt = (options?: TStringOptions) =>\n pgAttr(t.optional(t.datetime(options)), PG_DELETED_AT);\n\n /**\n * Creates an organization column for multi-tenant row scoping.\n *\n * When present, queries are automatically filtered by the current user's organization.\n * Rows with `null` organization are considered global and visible to everyone.\n * On create, the column is auto-stamped with the current user's organization.\n */\n public readonly organization = () =>\n pgAttr(t.optional(t.uuid()), PG_ORGANIZATION);\n\n /**\n * Creates a reference to another table or schema. Basically a foreign key.\n */\n public readonly ref = <T extends TSchema>(\n type: T,\n ref: () => any,\n actions?: {\n onUpdate?: UpdateDeleteAction;\n onDelete?: UpdateDeleteAction;\n },\n ): PgAttr<T, PgRef> => {\n // If actions are not provided, set default onDelete based on type\n const finalActions = actions ?? {\n onDelete: t.schema.isOptional(type) ? \"set null\" : \"cascade\",\n };\n\n return this.attr(type, PG_REF, {\n ref,\n actions: finalActions,\n });\n };\n\n // -------------------------------------------------------------------------------------------------------------------\n\n /**\n * Creates a page schema for a given object schema.\n * It's used by {@link Repository#paginate} method.\n */\n public readonly page = <T extends TObject>(\n resource: T,\n options?: TObjectOptions,\n ): TPage<T> => {\n return pageSchema(resource, options);\n };\n}\n\n/**\n * Wrapper of TypeProvider (`t`) for database types.\n *\n * Use `db` for improve TypeBox schema definitions with database-specific attributes.\n *\n * @example\n * ```ts\n * import { t } from \"alepha\";\n * import { db } from \"alepha/orm\";\n *\n * const userSchema = t.object({\n * id: db.primaryKey(t.uuid()),\n * email: t.email(),\n * createdAt: db.createdAt(),\n * });\n * ```\n */\nexport const db = new DatabaseTypeProvider();\n","import { t } from \"alepha\";\nimport {\n PG_DEFAULT,\n PG_PRIMARY_KEY,\n PG_SERIAL,\n} from \"../constants/PG_SYMBOLS.ts\";\nimport { pgAttr } from \"../helpers/pgAttr.ts\";\n\n/**\n * @deprecated Use `pg.primaryKey()` instead.\n */\nexport const legacyIdSchema = pgAttr(\n pgAttr(pgAttr(t.integer(), PG_PRIMARY_KEY), PG_SERIAL),\n PG_DEFAULT,\n);\n","import { $module } from \"alepha\";\nimport { AlephaDateTime } from \"alepha/datetime\";\n\nexport * from \"./index.shared.ts\";\n\nexport const AlephaOrm = $module({\n name: \"alepha.orm\",\n primitives: [],\n services: [AlephaDateTime],\n});\n"],"mappings":";;;;AAEA,IAAa,UAAb,cAA6B,YAAY;CACvC,OAAO;CAEP,YAAY,SAAiB,OAAiB;AAC5C,QAAM,SAAS,EAAE,OAAO,CAAC;;;;;;;;;;;;;ACI7B,IAAa,wBAAb,MAAa,8BAA8B,QAAQ;CACjD,OAAgB;CAChB,SAAkB;;;;CAKlB;;;;CAKA;CAEA,YACE,SACA,OACA,SACA;AACA,QAAM,SAAS,MAAM;AACrB,OAAK,SAAS,SAAS;AACvB,OAAK,QAAQ,SAAS;;;;;;CAOxB,OAAO,kBAAkB,OAAqC;EAC5D,MAAM,UAAU,MAAM;EAKt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EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,gBAAgB;;;;CAK/C,OACE,MACA,KACA,YAIqB;EAErB,MAAM,eAAe,WAAW,EAC9B,UAAU,EAAE,OAAO,WAAW,KAAK,GAAG,aAAa,WACpD;AAED,SAAO,KAAK,KAAK,MAAM,QAAQ;GAC7B;GACA,SAAS;GACV,CAAC;;;;;;CASJ,QACE,UACA,YACa;AACb,SAAOA,aAAW,UAAU,QAAQ;;;;;;;;;;;;;;;;;;;;AAqBxC,MAAa,KAAK,IAAI,sBAAsB;;;;;;AC/O5C,MAAa,iBAAiB,OAC5B,OAAO,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,UAAU,EACtD,WACD;;;ACTD,MAAa,YAAY,QAAQ;CAC/B,MAAM;CACN,YAAY,EAAE;CACd,UAAU,CAAC,eAAe;CAC3B,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.browser.js","names":["pageSchema"],"sources":["../../../src/orm/core/errors/DbError.ts","../../../src/orm/core/errors/DbColumnNotFoundError.ts","../../../src/orm/core/errors/DbConnectionError.ts","../../../src/orm/core/errors/DbDeadlockError.ts","../../../src/orm/core/errors/DbEntityNotFoundError.ts","../../../src/orm/core/errors/DbForeignKeyError.ts","../../../src/orm/core/errors/DbNotNullError.ts","../../../src/orm/core/errors/DbTableNotFoundError.ts","../../../src/orm/core/helpers/pgAttr.ts","../../../src/orm/core/constants/PG_SYMBOLS.ts","../../../src/orm/core/schemas/insertSchema.ts","../../../src/orm/core/schemas/updateSchema.ts","../../../src/orm/core/primitives/$entity.ts","../../../src/orm/core/providers/DatabaseTypeProvider.ts","../../../src/orm/core/schemas/legacyIdSchema.ts","../../../src/orm/core/index.browser.ts"],"sourcesContent":["import { AlephaError } from \"alepha\";\n\nexport class DbError extends AlephaError {\n name = \"DbError\";\n\n constructor(message: string, cause?: unknown) {\n super(message, { cause });\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a column does not exist.\n *\n * This typically happens when:\n * - Column name is misspelled\n * - Migrations haven't been run\n * - Using wrong schema version\n */\nexport class DbColumnNotFoundError extends DbError {\n readonly name = \"DbColumnNotFoundError\";\n readonly status = 500;\n\n /**\n * The column that was not found.\n */\n readonly column?: string;\n\n /**\n * The table where the column was expected.\n */\n readonly table?: string;\n\n constructor(\n message: string,\n cause?: unknown,\n options?: { column?: string; table?: string },\n ) {\n super(message, cause);\n this.column = options?.column;\n this.table = options?.table;\n }\n\n /**\n * Parse a database column not found error and create a DbColumnNotFoundError.\n * Supports both PostgreSQL and SQLite error formats.\n */\n static fromDatabaseError(error: Error): DbColumnNotFoundError {\n const message = error.message;\n\n // PostgreSQL format:\n // 'column \"foo\" does not exist'\n // 'column \"foo\" of relation \"users\" does not exist'\n const pgMatch = message.match(\n /column \"([^\"]+)\"(?: of relation \"([^\"]+)\")? does not exist/,\n );\n\n if (pgMatch) {\n const column = pgMatch[1];\n const table = pgMatch[2];\n const msg = table\n ? `Column '${column}' does not exist in table '${table}'`\n : `Column '${column}' does not exist`;\n return new DbColumnNotFoundError(msg, error, { column, table });\n }\n\n // SQLite format:\n // 'no such column: foo'\n // 'no such column: users.foo'\n const sqliteMatch = message.match(/no such column: (?:(\\S+)\\.)?(\\S+)/);\n\n if (sqliteMatch) {\n const table = sqliteMatch[1];\n const column = sqliteMatch[2];\n const msg = table\n ? `Column '${column}' does not exist in table '${table}'`\n : `Column '${column}' does not exist`;\n return new DbColumnNotFoundError(msg, error, { column, table });\n }\n\n return new DbColumnNotFoundError(\"Column does not exist\", error);\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a database connection fails.\n *\n * This can happen due to:\n * - Connection refused (server not running)\n * - Connection timeout\n * - Authentication failure\n * - Network issues\n * - Database file not found (SQLite)\n */\nexport class DbConnectionError extends DbError {\n readonly name = \"DbConnectionError\";\n readonly status = 503;\n\n /**\n * The type of connection error.\n */\n readonly errorType?:\n | \"refused\"\n | \"timeout\"\n | \"auth\"\n | \"not_found\"\n | \"locked\"\n | \"unknown\";\n\n /**\n * Whether this error is retryable.\n * Connection errors are often transient and can be retried.\n */\n readonly retryable: boolean;\n\n constructor(\n message: string,\n cause?: unknown,\n options?: {\n errorType?: DbConnectionError[\"errorType\"];\n retryable?: boolean;\n },\n ) {\n super(message, cause);\n this.errorType = options?.errorType;\n this.retryable = options?.retryable ?? true;\n }\n\n /**\n * Parse a database connection error message and create a DbConnectionError.\n * Supports both PostgreSQL and SQLite error formats.\n */\n static fromDatabaseError(error: Error): DbConnectionError {\n const message = error.message.toLowerCase();\n\n // Connection refused\n if (\n message.includes(\"connection refused\") ||\n message.includes(\"econnrefused\") ||\n message.includes(\"could not connect\")\n ) {\n return new DbConnectionError(\n \"Database connection refused. Is the server running?\",\n error,\n { errorType: \"refused\", retryable: true },\n );\n }\n\n // Timeout\n if (\n message.includes(\"timeout\") ||\n message.includes(\"timed out\") ||\n message.includes(\"etimedout\")\n ) {\n return new DbConnectionError(\"Database connection timed out\", error, {\n errorType: \"timeout\",\n retryable: true,\n });\n }\n\n // Authentication\n if (\n message.includes(\"password authentication failed\") ||\n message.includes(\"authentication failed\") ||\n message.includes(\"access denied\")\n ) {\n return new DbConnectionError(\n \"Database authentication failed. Check credentials.\",\n error,\n { errorType: \"auth\", retryable: false },\n );\n }\n\n // SQLite file not found\n if (\n message.includes(\"unable to open database\") ||\n message.includes(\"no such file\") ||\n message.includes(\"enoent\")\n ) {\n return new DbConnectionError(\"Database file not found\", error, {\n errorType: \"not_found\",\n retryable: false,\n });\n }\n\n // SQLite database locked\n if (message.includes(\"database is locked\")) {\n return new DbConnectionError(\n \"Database is locked by another process\",\n error,\n { errorType: \"locked\", retryable: true },\n );\n }\n\n return new DbConnectionError(\"Failed to connect to database\", error, {\n errorType: \"unknown\",\n retryable: true,\n });\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a deadlock is detected.\n *\n * This happens when two or more transactions are waiting for each other\n * to release locks. The database automatically aborts one transaction\n * to resolve the deadlock.\n *\n * This error is useful for implementing retry logic.\n */\nexport class DbDeadlockError extends DbError {\n readonly name = \"DbDeadlockError\";\n readonly status = 409;\n\n /**\n * Whether this error is retryable.\n * Deadlocks are typically safe to retry.\n */\n readonly retryable = true;\n\n /**\n * Parse a database deadlock error message and create a DbDeadlockError.\n * Supports PostgreSQL. SQLite doesn't have true deadlocks (uses SQLITE_BUSY instead).\n */\n static fromDatabaseError(error: Error): DbDeadlockError {\n return new DbDeadlockError(\n \"Transaction deadlock detected. Please retry the operation.\",\n error,\n );\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\nexport class DbEntityNotFoundError extends DbError {\n readonly name = \"DbEntityNotFoundError\";\n readonly status = 404;\n\n constructor(entityName: string) {\n super(`Entity from '${entityName}' was not found`);\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a foreign key constraint is violated.\n *\n * This typically happens when trying to delete an entity that is\n * referenced by another entity.\n */\nexport class DbForeignKeyError extends DbError {\n readonly name = \"DbForeignKeyError\";\n readonly status = 409;\n\n /**\n * The table that references the entity being deleted.\n */\n readonly referencingTable?: string;\n\n /**\n * The constraint name that was violated.\n */\n readonly constraintName?: string;\n\n constructor(\n message: string,\n cause?: unknown,\n options?: { referencingTable?: string; constraintName?: string },\n ) {\n super(message, cause);\n this.referencingTable = options?.referencingTable;\n this.constraintName = options?.constraintName;\n }\n\n /**\n * Parse a database foreign key error message and create a DbForeignKeyError.\n * Supports both PostgreSQL and SQLite error formats.\n */\n static fromDatabaseError(error: Error, tableName: string): DbForeignKeyError {\n const message = error.message;\n\n // PostgreSQL format:\n // 'violates foreign key constraint \"reporting_alert_query_id_fk\" on table \"reporting_alert\"'\n const pgMatch = message.match(\n /violates foreign key constraint \"([^\"]+)\" on table \"([^\"]+)\"/,\n );\n\n if (pgMatch) {\n const constraintName = pgMatch[1];\n const referencingTable = pgMatch[2];\n\n return new DbForeignKeyError(\n `Cannot delete ${tableName}: it is referenced by ${referencingTable}`,\n error,\n { referencingTable, constraintName },\n );\n }\n\n // SQLite format:\n // 'FOREIGN KEY constraint failed' (no table name available)\n return new DbForeignKeyError(\n `Cannot delete ${tableName}: it is referenced by another entity`,\n error,\n );\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a NOT NULL constraint is violated.\n *\n * This happens when inserting or updating a NULL value into a column\n * that has a NOT NULL constraint.\n */\nexport class DbNotNullError extends DbError {\n readonly name = \"DbNotNullError\";\n readonly status = 400;\n\n /**\n * The column that violated the NOT NULL constraint.\n */\n readonly column?: string;\n\n /**\n * The table containing the column.\n */\n readonly table?: string;\n\n constructor(\n message: string,\n cause?: unknown,\n options?: { column?: string; table?: string },\n ) {\n super(message, cause);\n this.column = options?.column;\n this.table = options?.table;\n }\n\n /**\n * Parse a database NOT NULL error message and create a DbNotNullError.\n * Supports both PostgreSQL and SQLite error formats.\n */\n static fromDatabaseError(error: Error, tableName: string): DbNotNullError {\n const message = error.message;\n\n // PostgreSQL format:\n // 'null value in column \"email\" of relation \"users\" violates not-null constraint'\n const pgMatch = message.match(\n /null value in column \"([^\"]+)\" of relation \"([^\"]+)\" violates not-null constraint/,\n );\n\n if (pgMatch) {\n const column = pgMatch[1];\n const table = pgMatch[2];\n return new DbNotNullError(\n `Column '${column}' in '${table}' cannot be null`,\n error,\n { column, table },\n );\n }\n\n // SQLite format:\n // 'NOT NULL constraint failed: users.email'\n const sqliteMatch = message.match(\n /NOT NULL constraint failed: ([^.]+)\\.(\\S+)/,\n );\n\n if (sqliteMatch) {\n const table = sqliteMatch[1];\n const column = sqliteMatch[2];\n return new DbNotNullError(\n `Column '${column}' in '${table}' cannot be null`,\n error,\n { column, table },\n );\n }\n\n return new DbNotNullError(\n `A required field in '${tableName}' cannot be null`,\n error,\n );\n }\n}\n","import { DbError } from \"./DbError.ts\";\n\n/**\n * Error thrown when a table does not exist.\n *\n * This typically happens when:\n * - Migrations haven't been run\n * - Table name is misspelled\n * - Wrong database/schema is being used\n */\nexport class DbTableNotFoundError extends DbError {\n readonly name = \"DbTableNotFoundError\";\n readonly status = 500;\n\n /**\n * The table that was not found.\n */\n readonly table?: string;\n\n constructor(message: string, cause?: unknown, options?: { table?: string }) {\n super(message, cause);\n this.table = options?.table;\n }\n\n /**\n * Parse a database table not found error and create a DbTableNotFoundError.\n * Supports both PostgreSQL and SQLite error formats.\n */\n static fromDatabaseError(error: Error): DbTableNotFoundError {\n const message = error.message;\n\n // PostgreSQL format:\n // 'relation \"users\" does not exist'\n const pgMatch = message.match(/relation \"([^\"]+)\" does not exist/);\n\n if (pgMatch) {\n const table = pgMatch[1];\n return new DbTableNotFoundError(\n `Table '${table}' does not exist. Have you run migrations?`,\n error,\n { table },\n );\n }\n\n // SQLite format:\n // 'no such table: users'\n const sqliteMatch = message.match(/no such table: (\\S+)/);\n\n if (sqliteMatch) {\n const table = sqliteMatch[1];\n return new DbTableNotFoundError(\n `Table '${table}' does not exist. Have you run migrations?`,\n error,\n { table },\n );\n }\n\n return new DbTableNotFoundError(\n \"Table does not exist. Have you run migrations?\",\n error,\n );\n }\n}\n","import type { TObject, TSchema } from \"alepha\";\nimport type { PgSymbolKeys, PgSymbols } from \"../constants/PG_SYMBOLS.ts\";\n\n/**\n * Decorates a typebox schema with a Postgres attribute.\n *\n * > It's just a fancy way to add Symbols to a field.\n *\n * @example\n * ```ts\n * import { t } from \"alepha\";\n * import { PG_UPDATED_AT } from \"../constants/PG_SYMBOLS\";\n *\n * export const updatedAtSchema = pgAttr(\n * t.datetime(), PG_UPDATED_AT,\n * );\n * ```\n */\nexport const pgAttr = <T extends TSchema, Attr extends PgSymbolKeys>(\n type: T,\n attr: Attr,\n value?: PgSymbols[Attr],\n): PgAttr<T, Attr> => {\n Object.assign(type, { [attr]: value ?? {} });\n return type as PgAttr<T, Attr>;\n};\n\n/**\n * Retrieves the fields of a schema that have a specific attribute.\n */\nexport const getAttrFields = (\n schema: TObject,\n name: PgSymbolKeys,\n): PgAttrField[] => {\n const fields: Array<PgAttrField> = [];\n\n for (const key of Object.keys(schema.properties)) {\n const value = schema.properties[key];\n if (name in value) {\n fields.push({\n type: value as TSchema,\n key: key,\n data: (value as any)[name],\n });\n }\n }\n\n return fields;\n};\n\n/**\n * Type representation.\n */\nexport type PgAttr<T extends TSchema, TAttr extends PgSymbolKeys> = T & {\n [K in TAttr]: PgSymbols[K];\n};\n\nexport interface PgAttrField {\n key: string;\n type: TSchema;\n data: any;\n nested?: any[];\n one?: boolean;\n}\n","import type { SQL } from \"drizzle-orm\";\nimport type {\n PgSequenceOptions,\n UpdateDeleteAction,\n} from \"drizzle-orm/pg-core\";\nimport type { EntityPrimitive } from \"../primitives/$entity.ts\";\n\nexport const PG_DEFAULT = Symbol.for(\"Alepha.Postgres.Default\");\nexport const PG_PRIMARY_KEY = Symbol.for(\"Alepha.Postgres.PrimaryKey\");\nexport const PG_CREATED_AT = Symbol.for(\"Alepha.Postgres.CreatedAt\");\nexport const PG_UPDATED_AT = Symbol.for(\"Alepha.Postgres.UpdatedAt\");\nexport const PG_DELETED_AT = Symbol.for(\"Alepha.Postgres.DeletedAt\");\nexport const PG_VERSION = Symbol.for(\"Alepha.Postgres.Version\");\nexport const PG_IDENTITY = Symbol.for(\"Alepha.Postgres.Identity\");\nexport const PG_ENUM = Symbol.for(\"Alepha.Postgres.Enum\");\nexport const PG_REF = Symbol.for(\"Alepha.Postgres.Ref\");\nexport const PG_GENERATED = Symbol.for(\"Alepha.Postgres.Generated\");\nexport const PG_ORGANIZATION = Symbol.for(\"Alepha.Postgres.Organization\");\n\n/**\n * @deprecated Use `PG_IDENTITY` instead.\n */\nexport const PG_SERIAL = Symbol.for(\"Alepha.Postgres.Serial\");\n\nexport type PgDefault = typeof PG_DEFAULT;\nexport type PgRef = typeof PG_REF;\nexport type PgPrimaryKey = typeof PG_PRIMARY_KEY;\n\nexport type PgSymbols = {\n [PG_DEFAULT]: {};\n [PG_PRIMARY_KEY]: {};\n [PG_CREATED_AT]: {};\n [PG_UPDATED_AT]: {};\n [PG_DELETED_AT]: {};\n [PG_VERSION]: {};\n [PG_IDENTITY]: PgIdentityOptions;\n [PG_REF]: PgRefOptions;\n [PG_ENUM]: PgEnumOptions;\n [PG_GENERATED]: PgGeneratedOptions;\n [PG_ORGANIZATION]: {};\n\n /**\n * @deprecated Use `PG_IDENTITY` instead.\n */\n [PG_SERIAL]: {};\n};\n\nexport type PgSymbolKeys = keyof PgSymbols;\n\nexport type PgIdentityOptions = {\n mode: \"always\" | \"byDefault\";\n} & PgSequenceOptions & {\n name?: string;\n };\n\nexport interface PgEnumOptions {\n name?: string;\n description?: string;\n}\n\nexport interface PgGeneratedOptions {\n /**\n * SQL expression for the generated column.\n */\n expression: SQL;\n\n /**\n * Storage mode for the generated column.\n * - `\"stored\"` — value is computed on write and stored on disk (default for PostgreSQL).\n * - `\"virtual\"` — value is computed on read (default for SQLite).\n */\n mode?: \"stored\" | \"virtual\";\n}\n\nexport interface PgRefOptions {\n ref: () => {\n name: string;\n entity: EntityPrimitive;\n };\n actions?: {\n onUpdate?: UpdateDeleteAction;\n onDelete?: UpdateDeleteAction;\n };\n}\n","import type { TObject, TOptional } from \"alepha\";\nimport { t } from \"alepha\";\nimport { PG_DEFAULT, PG_GENERATED } from \"../constants/PG_SYMBOLS.ts\";\n\n/**\n * Transforms a TObject schema for insert operations.\n * All default properties at the root level are made optional.\n * Generated columns are excluded entirely.\n *\n * @example\n * Before: { name: string; age: number(default=0); fullName: generated }\n * After: { name: string; age?: number; }\n */\nexport type TObjectInsert<T extends TObject> = TObject<{\n [K in keyof T[\"properties\"] as T[\"properties\"][K] extends {\n [PG_GENERATED]: any;\n }\n ? never\n : K]: T[\"properties\"][K] extends\n | { [PG_DEFAULT]: any }\n | { \"~optional\": true }\n ? TOptional<T[\"properties\"][K]>\n : T[\"properties\"][K];\n}>;\n\nexport const insertSchema = <T extends TObject>(obj: T): TObjectInsert<T> => {\n const newProperties: Record<string, any> = {};\n\n for (const key in obj.properties) {\n const prop = obj.properties[key];\n\n // Skip generated columns — they are computed by the database\n if (PG_GENERATED in prop) {\n continue;\n }\n\n if (PG_DEFAULT in prop) {\n newProperties[key] = t.optional(prop);\n } else {\n newProperties[key] = prop;\n }\n }\n\n return t.object(\n newProperties,\n \"options\" in obj && typeof obj.options === \"object\"\n ? { ...obj.options }\n : {},\n ) as TObjectInsert<T>;\n};\n","import {\n type TNull,\n type TObject,\n type TOptional,\n type TUnion,\n t,\n} from \"alepha\";\nimport { PG_GENERATED } from \"../constants/PG_SYMBOLS.ts\";\n\n/**\n * Transforms a TObject schema for update operations.\n * All optional properties at the root level are made nullable (i.e., `T | null`).\n * Generated columns are excluded entirely.\n *\n * @example\n * Before: { name?: string; age: number; fullName: generated }\n * After: { name?: string | null; age: number; }\n */\nexport type TObjectUpdate<T extends TObject> = TObject<{\n [K in keyof T[\"properties\"] as T[\"properties\"][K] extends {\n [PG_GENERATED]: any;\n }\n ? never\n : K]: T[\"properties\"][K] extends TOptional<infer U>\n ? TOptional<TUnion<[U, TNull]>>\n : T[\"properties\"][K];\n}>;\n\nexport const updateSchema = <T extends TObject>(\n schema: T,\n): TObjectUpdate<T> => {\n const newProperties: Record<string, any> = {};\n\n for (const key in schema.properties) {\n const prop = schema.properties[key];\n\n // Skip generated columns — they are computed by the database\n if (PG_GENERATED in prop) {\n continue;\n }\n\n if (t.schema.isOptional(prop)) {\n newProperties[key] = t.optional(t.union([prop, t.null()]));\n } else {\n newProperties[key] = prop;\n }\n }\n\n return t.object(\n newProperties,\n \"options\" in schema && typeof schema.options === \"object\"\n ? { ...schema.options }\n : {},\n ) as TObjectUpdate<T>;\n};\n","import { KIND, type Static, type TObject } from \"alepha\";\nimport type { BuildExtraConfigColumns, SQL } from \"drizzle-orm\";\nimport type {\n PgColumn,\n PgColumnBuilderBase,\n PgTableExtraConfigValue,\n} from \"drizzle-orm/pg-core\";\nimport { insertSchema, type TObjectInsert } from \"../schemas/insertSchema.ts\";\nimport { type TObjectUpdate, updateSchema } from \"../schemas/updateSchema.ts\";\n\n/**\n * Creates a database entity primitive that defines table structure using TypeBox schemas.\n *\n * @example\n * ```ts\n * import { t } from \"alepha\";\n * import { $entity } from \"alepha/orm\";\n *\n * const userEntity = $entity({\n * name: \"users\",\n * schema: t.object({\n * id: pg.primaryKey(),\n * name: t.text(),\n * email: t.email(),\n * }),\n * });\n * ```\n */\nexport const $entity = <TSchema extends TObject>(\n options: EntityPrimitiveOptions<TSchema>,\n): EntityPrimitive<TSchema> => {\n return new EntityPrimitive<TSchema>(options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface EntityPrimitiveOptions<\n T extends TObject,\n Keys = keyof Static<T>,\n> {\n /**\n * The database table name that will be created for this entity.\n * If not provided, name will be inferred from the $repository variable name.\n */\n name: string;\n\n /**\n * TypeBox schema defining the table structure and column types.\n */\n schema: T;\n\n /**\n * Database indexes to create for query optimization.\n */\n indexes?: (\n | Keys\n | {\n /**\n * Single column to index.\n */\n column: Keys;\n /**\n * Whether this should be a unique index (enforces uniqueness constraint).\n */\n unique?: boolean;\n /**\n * Custom name for the index. If not provided, generates name automatically.\n */\n name?: string;\n /**\n * Partial index condition. Only rows matching this SQL expression are indexed.\n */\n where?: SQL;\n }\n | {\n /**\n * Multiple columns for composite index (order matters for query optimization).\n */\n columns: Keys[];\n /**\n * Whether this should be a unique index (enforces uniqueness constraint).\n */\n unique?: boolean;\n /**\n * Custom name for the index. If not provided, generates name automatically.\n */\n name?: string;\n /**\n * Partial index condition. Only rows matching this SQL expression are indexed.\n */\n where?: SQL;\n }\n | {\n /**\n * SQL expressions for expression-based indexes.\n *\n * Can include column references and SQL functions like `LOWER()`, `UPPER()`, etc.\n * Columns and expressions can be mixed together.\n *\n * @example\n * ```ts\n * // Case-insensitive unique username per realm\n * indexes: [{\n * expressions: (self) => [self.realm, sql`LOWER(${self.username})`],\n * unique: true,\n * name: \"users_realm_username_lower_idx\",\n * }]\n * ```\n */\n expressions: (self: Record<Keys & string, any>) => (SQL | any)[];\n /**\n * Whether this should be a unique index (enforces uniqueness constraint).\n */\n unique?: boolean;\n /**\n * Custom name for the index. If not provided, generates name automatically.\n */\n name: string;\n /**\n * Partial index condition. Only rows matching this SQL expression are indexed.\n */\n where?: SQL;\n }\n )[];\n\n /**\n * Foreign key constraints to maintain referential integrity.\n */\n foreignKeys?: Array<{\n /**\n * Optional name for the foreign key constraint.\n */\n name?: string;\n /**\n * Local columns that reference the foreign table.\n */\n columns: Array<keyof Static<T>>;\n /**\n * Referenced columns in the foreign table.\n * Must be EntityColumn references from other entities.\n */\n foreignColumns: Array<() => EntityColumn<any>>;\n }>;\n\n /**\n * Additional table constraints for data validation.\n *\n * Constraints enforce business rules at the database level, providing\n * an additional layer of data integrity beyond application validation.\n *\n * **Constraint Types**:\n * - **Unique constraints**: Prevent duplicate values across columns\n * - **Check constraints**: Enforce custom validation rules with SQL expressions\n *\n * @example\n * ```ts\n * constraints: [\n * {\n * name: \"unique_user_email\",\n * columns: [\"email\"],\n * unique: true\n * },\n * {\n * name: \"valid_age_range\",\n * columns: [\"age\"],\n * check: sql`age >= 0 AND age <= 150`\n * },\n * {\n * name: \"unique_user_username_per_tenant\",\n * columns: [\"tenantId\", \"username\"],\n * unique: true\n * }\n * ]\n * ```\n */\n constraints?: Array<{\n /**\n * Columns involved in this constraint.\n */\n columns: Array<keyof Static<T>>;\n /**\n * Optional name for the constraint.\n */\n name?: string;\n /**\n * Whether this is a unique constraint.\n */\n unique?: boolean | {} /* options */;\n /**\n * SQL expression for check constraint validation.\n */\n check?: SQL;\n }>;\n\n /**\n * Advanced Drizzle ORM configuration for complex table setups.\n */\n config?: (\n self: BuildExtraConfigColumns<string, FromSchema<T>, \"pg\">,\n ) => PgTableExtraConfigValue[];\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class EntityPrimitive<T extends TObject = TObject> {\n public readonly options: EntityPrimitiveOptions<T>;\n\n constructor(options: EntityPrimitiveOptions<T>) {\n this.options = options;\n }\n\n alias(alias: string): this {\n const aliased = new EntityPrimitive<T>(this.options);\n return new Proxy(aliased, {\n get(target, prop, receiver) {\n if (prop === \"$alias\") {\n return alias;\n }\n return Reflect.get(target, prop, receiver);\n },\n }) as this;\n }\n\n get cols(): EntityColumns<T> {\n const cols: Partial<EntityColumns<T>> = {};\n for (const key of Object.keys(this.schema.properties) as Array<\n keyof T[\"properties\"]\n >) {\n cols[key] = {\n name: key as string,\n entity: this,\n };\n }\n\n return cols as EntityColumns<T>;\n }\n\n get name(): string {\n return this.options.name;\n }\n\n get schema(): T {\n return this.options.schema;\n }\n\n get insertSchema(): TObjectInsert<T> {\n return insertSchema(this.options.schema);\n }\n\n get updateSchema(): TObjectUpdate<T> {\n return updateSchema(this.options.schema);\n }\n}\n\n$entity[KIND] = EntityPrimitive;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Convert a schema to columns.\n */\nexport type FromSchema<T extends TObject> = {\n [key in keyof T[\"properties\"]]: PgColumnBuilderBase;\n};\n\nexport type SchemaToTableConfig<T extends TObject> = {\n name: string;\n schema: string | undefined;\n columns: {\n [key in keyof T[\"properties\"]]: PgColumn;\n };\n dialect: string;\n};\n\nexport type EntityColumn<T extends TObject> = {\n name: string;\n entity: EntityPrimitive<T>;\n};\n\nexport type EntityColumns<T extends TObject> = {\n [key in keyof T[\"properties\"]]: EntityColumn<T>;\n};\n","import {\n AlephaError,\n pageSchema,\n type Static,\n type TBigInt,\n type TInteger,\n type TNumber,\n type TNumberOptions,\n type TObject,\n type TObjectOptions,\n type TPage,\n type TSchema,\n type TString,\n type TStringOptions,\n t,\n} from \"alepha\";\nimport type { UpdateDeleteAction } from \"drizzle-orm/pg-core/foreign-keys\";\nimport {\n PG_CREATED_AT,\n PG_DEFAULT,\n PG_DELETED_AT,\n PG_IDENTITY,\n PG_ORGANIZATION,\n PG_PRIMARY_KEY,\n PG_REF,\n PG_UPDATED_AT,\n PG_VERSION,\n type PgDefault,\n type PgIdentityOptions,\n type PgPrimaryKey,\n type PgRef,\n} from \"../constants/PG_SYMBOLS.ts\";\nimport type { PgAttr } from \"../helpers/pgAttr.ts\";\nimport { pgAttr } from \"../helpers/pgAttr.ts\";\n\nexport class DatabaseTypeProvider {\n public readonly attr = pgAttr;\n\n /**\n * Creates a primary key with an identity column.\n */\n public readonly identityPrimaryKey = (\n identity?: PgIdentityOptions,\n options?: TNumberOptions,\n ) =>\n pgAttr(\n pgAttr(pgAttr(t.integer(options), PG_PRIMARY_KEY), PG_IDENTITY, identity),\n PG_DEFAULT,\n );\n\n /**\n * Creates a primary key with a big identity column. (default)\n */\n public readonly bigIdentityPrimaryKey = (\n identity?: PgIdentityOptions,\n options?: TNumberOptions,\n ) =>\n pgAttr(\n pgAttr(pgAttr(t.int64(options), PG_PRIMARY_KEY), PG_IDENTITY, identity),\n PG_DEFAULT,\n );\n\n /**\n * Creates a primary key with a UUID column.\n */\n public readonly uuidPrimaryKey = () =>\n pgAttr(pgAttr(t.uuid(), PG_PRIMARY_KEY), PG_DEFAULT);\n\n /**\n * Creates a primary key for a given type. Supports:\n * - `t.integer()` -> PG INT (default)\n * - `t.bigint()` -> PG BIGINT\n * - `t.uuid()` -> PG UUID\n */\n public primaryKey(): PgAttr<PgAttr<TInteger, PgPrimaryKey>, PgDefault>;\n public primaryKey(\n type: TString,\n options?: TStringOptions,\n ): PgAttr<PgAttr<TString, PgPrimaryKey>, PgDefault>;\n public primaryKey(\n type: TInteger,\n options?: TNumberOptions,\n identity?: PgIdentityOptions,\n ): PgAttr<PgAttr<TInteger, PgPrimaryKey>, PgDefault>;\n public primaryKey(\n type: TNumber,\n options?: TNumberOptions,\n identity?: PgIdentityOptions,\n ): PgAttr<PgAttr<TNumber, PgPrimaryKey>, PgDefault>;\n public primaryKey(\n type: TBigInt,\n options?: TNumberOptions,\n identity?: PgIdentityOptions,\n ): PgAttr<PgAttr<TBigInt, PgPrimaryKey>, PgDefault>;\n public primaryKey(\n type?: TSchema,\n options?: TNumberOptions | TStringOptions,\n identity?: PgIdentityOptions,\n ): PgAttr<PgAttr<TSchema, PgPrimaryKey>, PgDefault> {\n if (!type || t.schema.isInteger(type)) {\n return pgAttr(\n pgAttr(\n pgAttr(t.integer(options), PG_PRIMARY_KEY),\n PG_IDENTITY,\n identity,\n ),\n PG_DEFAULT,\n );\n }\n\n if (t.schema.isString(type) && type.format === \"uuid\") {\n return pgAttr(pgAttr(t.uuid(), PG_PRIMARY_KEY), PG_DEFAULT);\n }\n\n if (t.schema.isNumber(type) && type.format === \"int64\") {\n return pgAttr(\n pgAttr(\n pgAttr(t.number(options), PG_PRIMARY_KEY),\n PG_IDENTITY,\n identity,\n ),\n PG_DEFAULT,\n );\n }\n\n if (t.schema.isBigInt(type)) {\n return pgAttr(\n pgAttr(\n pgAttr(t.bigint(options), PG_PRIMARY_KEY),\n PG_IDENTITY,\n identity,\n ),\n PG_DEFAULT,\n );\n }\n\n throw new AlephaError(`Unsupported type for primary key: ${type}`);\n }\n\n /**\n * Wrap a schema with \"default\" attribute.\n * This is used to set a default value for a column in the database.\n */\n public readonly default = <T extends TSchema>(\n type: T,\n value?: Static<T>,\n ): PgAttr<T, PgDefault> => {\n if (value != null) {\n Object.assign(type, { default: value });\n }\n\n return this.attr(type, PG_DEFAULT);\n };\n\n /**\n * Creates a column 'version'.\n *\n * This is used to track the version of a row in the database.\n *\n * You can use it for optimistic concurrency control (OCC) with {@link RepositoryPrimitive#save}.\n *\n * @see {@link RepositoryPrimitive#save}\n * @see {@link PgVersionMismatchError}\n */\n public readonly version = (options: TNumberOptions = {}) =>\n this.default(pgAttr(t.integer(options), PG_VERSION), 0);\n\n /**\n * Creates a column Created At. So just a datetime column with a default value of the current timestamp.\n */\n public readonly createdAt = (options?: TStringOptions) =>\n pgAttr(pgAttr(t.datetime(options), PG_CREATED_AT), PG_DEFAULT);\n\n /**\n * Creates a column Updated At. Like createdAt, but it is updated on every update of the row.\n */\n public readonly updatedAt = (options?: TStringOptions) =>\n pgAttr(pgAttr(t.datetime(options), PG_UPDATED_AT), PG_DEFAULT);\n\n /**\n * Creates a column Deleted At for soft delete functionality.\n * This is used to mark rows as deleted without actually removing them from the database.\n * The column is nullable - NULL means not deleted, timestamp means deleted.\n */\n public readonly deletedAt = (options?: TStringOptions) =>\n pgAttr(t.optional(t.datetime(options)), PG_DELETED_AT);\n\n /**\n * Creates an organization column for multi-tenant row scoping.\n *\n * When present, queries are automatically filtered by the current user's organization.\n * Rows with `null` organization are considered global and visible to everyone.\n * On create, the column is auto-stamped with the current user's organization.\n */\n public readonly organization = () =>\n pgAttr(t.optional(t.uuid()), PG_ORGANIZATION);\n\n /**\n * Creates a reference to another table or schema. Basically a foreign key.\n */\n public readonly ref = <T extends TSchema>(\n type: T,\n ref: () => any,\n actions?: {\n onUpdate?: UpdateDeleteAction;\n onDelete?: UpdateDeleteAction;\n },\n ): PgAttr<T, PgRef> => {\n // If actions are not provided, set default onDelete based on type\n const finalActions = actions ?? {\n onDelete: t.schema.isOptional(type) ? \"set null\" : \"cascade\",\n };\n\n return this.attr(type, PG_REF, {\n ref,\n actions: finalActions,\n });\n };\n\n // -------------------------------------------------------------------------------------------------------------------\n\n /**\n * Creates a page schema for a given object schema.\n * It's used by {@link Repository#paginate} method.\n */\n public readonly page = <T extends TObject>(\n resource: T,\n options?: TObjectOptions,\n ): TPage<T> => {\n return pageSchema(resource, options);\n };\n}\n\n/**\n * Wrapper of TypeProvider (`t`) for database types.\n *\n * Use `db` for improve TypeBox schema definitions with database-specific attributes.\n *\n * @example\n * ```ts\n * import { t } from \"alepha\";\n * import { db } from \"alepha/orm\";\n *\n * const userSchema = t.object({\n * id: db.primaryKey(t.uuid()),\n * email: t.email(),\n * createdAt: db.createdAt(),\n * });\n * ```\n */\nexport const db = new DatabaseTypeProvider();\n","import { t } from \"alepha\";\nimport {\n PG_DEFAULT,\n PG_PRIMARY_KEY,\n PG_SERIAL,\n} from \"../constants/PG_SYMBOLS.ts\";\nimport { pgAttr } from \"../helpers/pgAttr.ts\";\n\n/**\n * @deprecated Use `pg.primaryKey()` instead.\n */\nexport const legacyIdSchema = pgAttr(\n pgAttr(pgAttr(t.integer(), PG_PRIMARY_KEY), PG_SERIAL),\n PG_DEFAULT,\n);\n","import { $module } from \"alepha\";\nimport { AlephaDateTime } from \"alepha/datetime\";\n\nexport * from \"./index.shared.ts\";\n\nexport const AlephaOrm = $module({\n name: \"alepha.orm\",\n primitives: [],\n services: [AlephaDateTime],\n});\n"],"mappings":";;;;AAEA,IAAa,UAAb,cAA6B,YAAY;CACvC,OAAO;CAEP,YAAY,SAAiB,OAAiB;EAC5C,MAAM,SAAS,EAAE,OAAO,CAAC;;;;;;;;;;;;;ACI7B,IAAa,wBAAb,MAAa,8BAA8B,QAAQ;CACjD,OAAgB;CAChB,SAAkB;;;;CAKlB;;;;CAKA;CAEA,YACE,SACA,OACA,SACA;EACA,MAAM,SAAS,MAAM;EACrB,KAAK,SAAS,SAAS;EACvB,KAAK,QAAQ,SAAS;;;;;;CAOxB,OAAO,kBAAkB,OAAqC;EAC5D,MAAM,UAAU,MAAM;EAKtB,MAAM,UAAU,QAAQ,MACtB,6DACD;EAED,IAAI,SAAS;GACX,MAAM,SAAS,QAAQ;GACvB,MAAM,QAAQ,QAAQ;GAItB,OAAO,IAAI,sBAHC,QACR,WAAW,OAAO,6BAA6B,MAAM,KACrD,WAAW,OAAO,mBACgB,OAAO;IAAE;IAAQ;IAAO,CAAC;;EAMjE,MAAM,cAAc,QAAQ,MAAM,oCAAoC;EAEtE,IAAI,aAAa;GACf,MAAM,QAAQ,YAAY;GAC1B,MAAM,SAAS,YAAY;GAI3B,OAAO,IAAI,sBAHC,QACR,WAAW,OAAO,6BAA6B,MAAM,KACrD,WAAW,OAAO,mBACgB,OAAO;IAAE;IAAQ;IAAO,CAAC;;EAGjE,OAAO,IAAI,sBAAsB,yBAAyB,MAAM;;;;;;;;;;;;;;;AC3DpE,IAAa,oBAAb,MAAa,0BAA0B,QAAQ;CAC7C,OAAgB;CAChB,SAAkB;;;;CAKlB;;;;;CAYA;CAEA,YACE,SACA,OACA,S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