UNPKG

@swoft/platform-contracts

Version:

DDD-compliant dependency injection contracts for Swoft platform - Defines clean architecture boundaries

603 lines (595 loc) 23.5 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); // src/index.ts var index_exports = {}; __export(index_exports, { APPLICATION_CONTRACTS: () => APPLICATION_CONTRACTS, CONFIGURATION_CONTRACTS: () => CONFIGURATION_CONTRACTS, CONTRACTS: () => CONTRACTS, CONTRACT_METADATA: () => CONTRACT_METADATA, CQRS_CONTRACTS: () => CQRS_CONTRACTS, DI_CAS_SERVICE: () => DI_CAS_SERVICE, DI_DATABASE_NAME: () => DI_DATABASE_NAME, DI_DOCUMENTATION_REPOSITORY: () => DI_DOCUMENTATION_REPOSITORY, DI_MONGO_CLIENT: () => DI_MONGO_CLIENT, DI_MONGO_CONNECTION_STRING: () => DI_MONGO_CONNECTION_STRING, DI_SCHEMA_REPOSITORY: () => DI_SCHEMA_REPOSITORY, DI_SERVICE_MANAGER: () => DI_SERVICE_MANAGER, DOMAIN_CONTRACTS: () => DOMAIN_CONTRACTS, DOMAIN_SERVICE_CONTRACTS: () => DOMAIN_SERVICE_CONTRACTS, HealthCheckUtils: () => HealthCheckUtils, HealthNavigationPatterns: () => HealthNavigationPatterns, INFRASTRUCTURE_CONTRACTS: () => INFRASTRUCTURE_CONTRACTS, LOGGING_CONTRACTS: () => LOGGING_CONTRACTS, MCPSemanticStartupEnforcer: () => MCPSemanticStartupEnforcer, NAVIGATION_CONTRACTS: () => NAVIGATION_CONTRACTS, SECURITY_CONTRACTS: () => SECURITY_CONTRACTS, USE_CASE_CONTRACTS: () => USE_CASE_CONTRACTS, createSemanticEnforcer: () => createSemanticEnforcer }); module.exports = __toCommonJS(index_exports); // src/infrastructure/index.ts var INFRASTRUCTURE_CONTRACTS = { // Core MongoDB infrastructure MONGO_CLIENT: Symbol("Infrastructure.MongoDB.Client"), DATABASE_NAME: Symbol("Infrastructure.MongoDB.DatabaseName"), MONGO_CONNECTION_STRING: Symbol("Infrastructure.MongoDB.ConnectionString"), // Storage infrastructure CAS_STORAGE_PORT: Symbol("Infrastructure.Storage.CasStoragePort"), DISK_REGISTRY_PORT: Symbol("Infrastructure.Storage.DiskRegistryPort"), DISK_ADAPTER_RESOLVER: Symbol("Infrastructure.Storage.DiskAdapterResolver"), // External service infrastructure S3_CLIENT: Symbol("Infrastructure.AWS.S3Client"), SECRET_MANAGER: Symbol("Infrastructure.AWS.SecretsManager") }; // src/domain/index.ts var DOMAIN_CONTRACTS = { // Core domain repositories SCHEMA_REPOSITORY: Symbol("Domain.Repository.SchemaRepository"), BUSINESS_ACTION_REPOSITORY: Symbol("Domain.Repository.BusinessActionRepository"), // Knowledge domain repositories DOCUMENTATION_REPOSITORY: Symbol("Domain.Repository.DocumentationRepository"), // Runtime domain repositories ATOMIC_TASK_REPOSITORY: Symbol("Domain.Repository.AtomicTaskRepository"), // Collaboration domain repositories HANDOFF_REPOSITORY: Symbol("Domain.Repository.HandoffRepository"), MESSAGE_REPOSITORY: Symbol("Domain.Repository.MessageRepository") }; var DOMAIN_SERVICE_CONTRACTS = { // Knowledge domain services CONTENT_DISCOVERY_SERVICE: Symbol("Domain.Service.ContentDiscoveryService"), RELATIONSHIP_DISCOVERY_SERVICE: Symbol("Domain.Service.RelationshipDiscoveryService"), // Runtime domain services TASK_ORCHESTRATION_SERVICE: Symbol("Domain.Service.TaskOrchestrationService"), // Core domain services BUSINESS_ACTION_ORCHESTRATOR: Symbol("Domain.Service.BusinessActionOrchestrator") }; // src/application/index.ts var APPLICATION_CONTRACTS = { // Core application services CAS_SERVICE: Symbol("Application.Service.CasService"), CONTRACT_DISCOVERY_SERVICE: Symbol("Application.Service.ContractDiscoveryService"), SCHEMA_APPLICATION_SERVICE: Symbol("Application.Service.SchemaApplicationService"), // Knowledge application services DOCUMENTATION_APPLICATION_SERVICE: Symbol("Application.Service.DocumentationApplicationService"), // Runtime application services SERVICE_MANAGER: Symbol("Application.Service.ServiceManager"), SERVICE_REGISTRY: Symbol("Application.Service.ServiceRegistry"), TASK_ORCHESTRATOR: Symbol("Application.Service.TaskOrchestrator"), // Development application services SEEDER_MANAGER: Symbol("Application.Service.SeederManager"), VALIDATION_SERVICE: Symbol("Application.Service.ValidationService") }; var CQRS_CONTRACTS = { // Command processing COMMAND_BUS: Symbol("Application.CQRS.CommandBus"), COMMAND_HANDLER_REGISTRY: Symbol("Application.CQRS.CommandHandlerRegistry"), // Query processing QUERY_BUS: Symbol("Application.CQRS.QueryBus"), QUERY_HANDLER_REGISTRY: Symbol("Application.CQRS.QueryHandlerRegistry"), // Event processing EVENT_BUS: Symbol("Application.CQRS.EventBus"), EVENT_HANDLER_REGISTRY: Symbol("Application.CQRS.EventHandlerRegistry") }; var USE_CASE_CONTRACTS = { // Service management use cases START_SERVICE_USE_CASE: Symbol("Application.UseCase.StartService"), STOP_SERVICE_USE_CASE: Symbol("Application.UseCase.StopService"), LIST_SERVICES_USE_CASE: Symbol("Application.UseCase.ListServices"), // Documentation use cases CREATE_DOCUMENTATION_USE_CASE: Symbol("Application.UseCase.CreateDocumentation"), UPDATE_DOCUMENTATION_USE_CASE: Symbol("Application.UseCase.UpdateDocumentation"), PUBLISH_DOCUMENTATION_USE_CASE: Symbol("Application.UseCase.PublishDocumentation") }; // src/shared/MCPSemanticStartupEnforcer.ts var import_promises = require("fs/promises"); var import_path = require("path"); var _MCPSemanticStartupEnforcer = class _MCPSemanticStartupEnforcer { constructor(domainId, packageName) { __publicField(this, "domainId"); __publicField(this, "packageName"); __publicField(this, "semantics"); __publicField(this, "domainBoundary"); __publicField(this, "startupResult"); this.domainId = domainId; this.packageName = packageName; this.startupResult = { success: false, domainId, entityRelationships: 0, workflows: 0, customSemantics: 0, errors: [], warnings: [] }; } /** * Execute mandatory startup sequence * Throws on critical errors, preventing server startup */ async enforceStartup() { console.log(""); console.log("\u{1F680} ========================================"); console.log("\u{1F680} MCP Semantic Startup Protocol v1.0"); console.log(`\u{1F680} Domain: ${this.domainId}`); console.log(`\u{1F680} Package: ${this.packageName}`); console.log("\u{1F680} ========================================"); console.log(""); try { console.log("\u{1F4CD} Step 1: Loading Domain Boundary Map..."); await this.loadDomainBoundaryMap(); console.log("\u{1F4CD} Step 2: Loading Semantic Navigation..."); await this.loadSemanticNavigation(); console.log("\u{1F4CD} Step 3: Validating Semantic Understanding..."); await this.validateSemanticUnderstanding(); console.log("\u{1F4CD} Step 4: Semantic Navigation Summary..."); this.displaySemanticSummary(); this.startupResult.success = true; console.log(""); console.log("\u2705 ========================================"); console.log("\u2705 Semantic startup complete!"); console.log("\u2705 Ready to provide context-aware navigation"); console.log("\u2705 ========================================"); console.log(""); } catch (error) { this.startupResult.errors.push(error.message); console.error(""); console.error("\u274C ========================================"); console.error("\u274C FATAL: Semantic startup failed!"); console.error(`\u274C Error: ${error.message}`); console.error("\u274C Server CANNOT start without semantic context"); console.error("\u274C ========================================"); console.error(""); throw error; } return this.startupResult; } /** * Load and parse Domain Boundary Map */ async loadDomainBoundaryMap() { const workspace = process.env.SWOFT_TEAM_WORKSPACE || process.cwd(); const mapPath = (0, import_path.join)(workspace, "docs/architecture/DOMAIN-BOUNDARY-MAP.md"); try { const content = await (0, import_promises.readFile)(mapPath, "utf-8"); const domainInfo = this.parseDomainBoundaryMap(content); if (!domainInfo) { throw new Error(`Domain '${this.domainId}' not found in Domain Boundary Map. Expected format: DOM-XXX (e.g., DOM-001) or domain name (e.g., 'party-manager'). Check docs/architecture/DOMAIN-BOUNDARY-MAP.md for valid domains.`); } this.domainBoundary = domainInfo; console.log(` \u2705 Found domain ${domainInfo.domainRef}: ${domainInfo.domainId}`); console.log(` \u2705 Bounded contexts: ${domainInfo.boundedContexts.length}`); console.log(` \u2705 Published language terms: ${domainInfo.publishedLanguage.length}`); } catch (error) { throw new Error(`Failed to load Domain Boundary Map: ${error.message}`); } } /** * Parse domain boundary map markdown to extract domain info */ parseDomainBoundaryMap(content) { console.log(` \u{1F50D} Searching for domain: ${this.domainId}`); const lines = content.split("\n"); let currentDomain = null; let foundDomain = false; for (const line of lines) { const domainMatch = line.match(/^####\s+(DOM-\d+):\s+(.+)\s+Domain/); if (domainMatch) { const [, domainRef, domainName] = domainMatch; if (domainRef === this.domainId || domainName && domainName.toLowerCase().includes(this.domainId.toLowerCase().replace("-", " "))) { foundDomain = true; currentDomain = { domainRef, domainId: this.domainId, packageName: "", services: [], boundedContexts: [], publishedLanguage: [] }; } else { foundDomain = false; } } if (foundDomain && currentDomain) { if (line.includes("**Package**:")) { const packageMatch = line.match(/`([^`]+)`/); if (packageMatch) { currentDomain.packageName = packageMatch[1]; } } if (line.includes("**Bounded Contexts**:")) { const contextsMatch = line.match(/contexts?\s*\(([^)]+)\)/); if (contextsMatch && contextsMatch[1]) { currentDomain.boundedContexts = contextsMatch[1].split(",").map((c) => c.trim()); } } if (line.includes("**Published Language**:")) { const termsMatch = line.match(/:\s*(.+)$/); if (termsMatch && termsMatch[1]) { currentDomain.publishedLanguage = termsMatch[1].split(",").map((t) => t.trim()); } } if (line.includes("**Database**:")) { const dbMatch = line.match(/:\s*(.+)$/); if (dbMatch && dbMatch[1]) { currentDomain.database = dbMatch[1].trim(); } } } } return currentDomain; } /** * Load semantic navigation from domain package */ async loadSemanticNavigation() { try { const semanticExports = await this.tryLoadSemantics(); if (!semanticExports || !semanticExports.domainSemantics) { console.log(" \u26A0\uFE0F No semantic navigation found, creating minimal definition"); this.createMinimalSemantics(); return; } this.semantics = semanticExports.domainSemantics; if (this.semantics) { this.startupResult.entityRelationships = this.semantics.entityRelationships?.length || 0; this.startupResult.workflows = this.semantics.workflows?.length || 0; this.startupResult.customSemantics = this.semantics.customSemantics?.length || 0; } console.log(` \u2705 Loaded ${this.startupResult.entityRelationships} entity relationships`); console.log(` \u2705 Loaded ${this.startupResult.workflows} workflows`); console.log(` \u2705 Loaded ${this.startupResult.customSemantics} custom semantic patterns`); } catch (error) { this.startupResult.warnings.push(`Could not load semantic navigation: ${error.message}`); console.log(" \u26A0\uFE0F Using minimal semantic navigation"); this.createMinimalSemantics(); } } /** * Try to load semantics from various possible locations */ async tryLoadSemantics() { return null; } /** * Create minimal semantic navigation when none exists */ createMinimalSemantics() { this.semantics = { domainId: this.domainId, mcpServerId: `mcp-${this.domainId}`, entityRelationships: [], workflows: [], confidence: 0.5, lastUpdated: (/* @__PURE__ */ new Date()).toISOString() }; this.startupResult.warnings.push("Using minimal semantic navigation - domain should implement full semantics"); } /** * Validate the MCP server understands its semantic context */ async validateSemanticUnderstanding() { const validations = [ { name: "Domain Identity", check: /* @__PURE__ */ __name(() => this.domainBoundary !== null, "check"), error: "Domain not found in Domain Boundary Map" }, { name: "Semantic Navigation", check: /* @__PURE__ */ __name(() => this.semantics !== null, "check"), error: "No semantic navigation loaded" }, { name: "Published Language", check: /* @__PURE__ */ __name(() => (this.domainBoundary?.publishedLanguage?.length || 0) > 0, "check"), error: "No published language terms defined" } ]; for (const validation of validations) { if (!validation.check()) { throw new Error(`Validation failed for ${validation.name}: ${validation.error}`); } console.log(` \u2705 Validated: ${validation.name}`); } } /** * Display semantic navigation summary */ displaySemanticSummary() { console.log(""); console.log("\u{1F4CA} Semantic Navigation Summary:"); console.log("================================"); if (this.domainBoundary) { console.log(`Domain: ${this.domainBoundary.domainRef} - ${this.domainBoundary.domainId}`); console.log(`Package: ${this.domainBoundary.packageName}`); console.log(`Database: ${this.domainBoundary.database || "Not specified"}`); console.log(""); console.log("Published Language Terms:"); this.domainBoundary.publishedLanguage.forEach((term) => { console.log(` - ${term}`); }); } if (this.semantics && this.semantics.entityRelationships && this.semantics.entityRelationships.length > 0) { console.log(""); console.log("Entity Relationships:"); this.semantics.entityRelationships.slice(0, 3).forEach((rel) => { console.log(` - ${rel.sourceEntityType} ${rel.relationshipType} ${rel.targetEntityType}`); }); if (this.semantics.entityRelationships.length > 3) { console.log(` ... and ${this.semantics.entityRelationships.length - 3} more`); } } if (this.semantics && this.semantics.workflows && this.semantics.workflows.length > 0) { console.log(""); console.log("Available Workflows:"); this.semantics.workflows.slice(0, 3).forEach((wf) => { console.log(` - ${wf.name} (${wf.steps.length} steps)`); }); if (this.semantics.workflows.length > 3) { console.log(` ... and ${this.semantics.workflows.length - 3} more`); } } console.log("================================"); } /** * Get loaded semantic navigation for use by MCP server */ getSemantics() { return this.semantics; } /** * Get domain boundary information */ getDomainBoundary() { return this.domainBoundary; } }; __name(_MCPSemanticStartupEnforcer, "MCPSemanticStartupEnforcer"); var MCPSemanticStartupEnforcer = _MCPSemanticStartupEnforcer; function createSemanticEnforcer(domainId, packageName) { return new MCPSemanticStartupEnforcer(domainId, packageName); } __name(createSemanticEnforcer, "createSemanticEnforcer"); // src/shared/HealthCheck.ts var _HealthCheckUtils = class _HealthCheckUtils { /** * Create standard health response structure */ static createResponse(serviceName, version, domainChecks, domainDetails = {}, metrics) { return { status: "ok", service: serviceName, version, timestamp: (/* @__PURE__ */ new Date()).toISOString(), checks: { connectivity: { status: "connected", responseTime: "12ms" }, ...domainChecks, ...domainDetails }, metrics }; } /** * Create error response */ static createErrorResponse(serviceName, error) { return { status: "error", service: serviceName, timestamp: (/* @__PURE__ */ new Date()).toISOString(), checks: { connectivity: { status: "failed", error: error.message || String(error) } } }; } /** * Standard metrics collection */ static collectStandardMetrics() { return { uptime: process.uptime(), memory: process.memoryUsage(), timestamp: (/* @__PURE__ */ new Date()).toISOString() }; } }; __name(_HealthCheckUtils, "HealthCheckUtils"); var HealthCheckUtils = _HealthCheckUtils; var _HealthNavigationPatterns = class _HealthNavigationPatterns { /** * Common cross-MCP health navigation hints */ static getSystemHealthHints() { return [ { toolName: "health_check", description: "Check system-wide health status", relevanceContext: "if this service shows issues" } ]; } /** * Service recovery navigation hints */ static getRecoveryHints(serviceName) { return [ { toolName: "service_control", description: `Restart ${serviceName} if needed` }, { toolName: "logs", description: `View ${serviceName} logs for diagnostics` } ]; } }; __name(_HealthNavigationPatterns, "HealthNavigationPatterns"); var HealthNavigationPatterns = _HealthNavigationPatterns; // src/shared/index.ts var NAVIGATION_CONTRACTS = { // Core navigation services NAVIGATION_HINTS_PROVIDER: Symbol("Shared.Navigation.NavigationHintsProvider"), NAVIGATION_HINTS_BUILDER: Symbol("Shared.Navigation.NavigationHintsBuilder"), NAVIGATION_HINTS_FACTORY: Symbol("Shared.Navigation.NavigationHintsFactory"), // Cross-MCP navigation CROSS_MCP_NAVIGATOR: Symbol("Shared.Navigation.CrossMcpNavigator"), MCP_TOOL_REGISTRY: Symbol("Shared.Navigation.McpToolRegistry"), // Context awareness WORKFLOW_CONTEXT_PROVIDER: Symbol("Shared.Navigation.WorkflowContextProvider"), GIT_CONTEXT_PROVIDER: Symbol("Shared.Navigation.GitContextProvider"), // Navigation enhancement NAVIGATION_PROCESSOR: Symbol("Shared.Navigation.NavigationProcessor"), NAVIGATION_FILTER: Symbol("Shared.Navigation.NavigationFilter"), // Semantic navigation SEMANTIC_NAVIGATION_REGISTRY: Symbol("Shared.Navigation.SemanticNavigationRegistry"), SEMANTIC_HINTS_FACTORY: Symbol("Shared.Navigation.SemanticHintsFactory"), DOMAIN_SEMANTICS_PROVIDER: Symbol("Shared.Navigation.DomainSemanticsProvider") }; var LOGGING_CONTRACTS = { // Core logging LOGGER: Symbol("Shared.Logging.Logger"), BOUNDED_CONTEXT_LOGGER: Symbol("Shared.Logging.BoundedContextLogger"), LAYER_LOGGER: Symbol("Shared.Logging.LayerLogger"), // Performance monitoring PERFORMANCE_MONITOR: Symbol("Shared.Monitoring.PerformanceMonitor"), METRICS_COLLECTOR: Symbol("Shared.Monitoring.MetricsCollector"), // Health checks HEALTH_CHECK_SERVICE: Symbol("Shared.Health.HealthCheckService"), DISK_HEALTH_MONITOR: Symbol("Shared.Health.DiskHealthMonitor") }; var SECURITY_CONTRACTS = { // Authentication AUTHENTICATION_SERVICE: Symbol("Shared.Security.AuthenticationService"), TOKEN_VALIDATOR: Symbol("Shared.Security.TokenValidator"), // Authorization AUTHORIZATION_SERVICE: Symbol("Shared.Security.AuthorizationService"), PERMISSION_CHECKER: Symbol("Shared.Security.PermissionChecker"), // Audit AUDIT_LOGGER: Symbol("Shared.Security.AuditLogger"), SECURITY_EVENT_PUBLISHER: Symbol("Shared.Security.SecurityEventPublisher") }; var CONFIGURATION_CONTRACTS = { // Core configuration SERVER_CONFIG: Symbol("Shared.Config.ServerConfig"), DATABASE_CONFIG: Symbol("Shared.Config.DatabaseConfig"), // Environment-specific DEVELOPMENT_CONFIG: Symbol("Shared.Config.DevelopmentConfig"), PRODUCTION_CONFIG: Symbol("Shared.Config.ProductionConfig"), // Feature flags FEATURE_FLAG_SERVICE: Symbol("Shared.Config.FeatureFlagService"), ENVIRONMENT_DETECTOR: Symbol("Shared.Config.EnvironmentDetector") }; // src/ContractRegistry.ts var CONTRACTS = { // Infrastructure Layer (External dependencies) INFRASTRUCTURE: INFRASTRUCTURE_CONTRACTS, // Domain Layer (Business logic ports) DOMAIN: { REPOSITORIES: DOMAIN_CONTRACTS, SERVICES: DOMAIN_SERVICE_CONTRACTS }, // Application Layer (Use cases and orchestration) APPLICATION: { SERVICES: APPLICATION_CONTRACTS, CQRS: CQRS_CONTRACTS, USE_CASES: USE_CASE_CONTRACTS }, // Shared Layer (Cross-cutting concerns) SHARED: { LOGGING: LOGGING_CONTRACTS, SECURITY: SECURITY_CONTRACTS, CONFIGURATION: CONFIGURATION_CONTRACTS } }; var DI_MONGO_CLIENT = CONTRACTS.INFRASTRUCTURE.MONGO_CLIENT; var DI_DATABASE_NAME = CONTRACTS.INFRASTRUCTURE.DATABASE_NAME; var DI_MONGO_CONNECTION_STRING = CONTRACTS.INFRASTRUCTURE.MONGO_CONNECTION_STRING; var DI_SCHEMA_REPOSITORY = CONTRACTS.DOMAIN.REPOSITORIES.SCHEMA_REPOSITORY; var DI_DOCUMENTATION_REPOSITORY = CONTRACTS.DOMAIN.REPOSITORIES.DOCUMENTATION_REPOSITORY; var DI_CAS_SERVICE = CONTRACTS.APPLICATION.SERVICES.CAS_SERVICE; var DI_SERVICE_MANAGER = CONTRACTS.APPLICATION.SERVICES.SERVICE_MANAGER; var CONTRACT_METADATA = { version: "1.0.0", totalContracts: Object.keys(CONTRACTS).length, layers: [ "INFRASTRUCTURE", "DOMAIN", "APPLICATION", "SHARED" ], description: "DDD-compliant dependency injection contracts for Swoft platform" }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { APPLICATION_CONTRACTS, CONFIGURATION_CONTRACTS, CONTRACTS, CONTRACT_METADATA, CQRS_CONTRACTS, DI_CAS_SERVICE, DI_DATABASE_NAME, DI_DOCUMENTATION_REPOSITORY, DI_MONGO_CLIENT, DI_MONGO_CONNECTION_STRING, DI_SCHEMA_REPOSITORY, DI_SERVICE_MANAGER, DOMAIN_CONTRACTS, DOMAIN_SERVICE_CONTRACTS, HealthCheckUtils, HealthNavigationPatterns, INFRASTRUCTURE_CONTRACTS, LOGGING_CONTRACTS, MCPSemanticStartupEnforcer, NAVIGATION_CONTRACTS, SECURITY_CONTRACTS, USE_CASE_CONTRACTS, createSemanticEnforcer }); //# sourceMappingURL=index.js.map