@bernierllc/neverhub-adapter

中文文档
0.4.1发布于 2026/07/14MITTypeScriptCommonJS零依赖近 30 天下载 4397

Standardized adapter for integrating BernierLLC packages with NeverHub service discovery and event bus system

原始使用文档
文档目录23 节
  1. Installation
  2. Features
  3. Quick Start
  4. Basic Integration
  5. Event Publishing
  6. Event Subscription
  7. Service Discovery
  8. Configuration Management
  9. Health Checks and Metrics
  10. API Reference
  11. NeverHubAdapter Class
  12. Configuration
  13. Types
  14. Environment Detection
  15. Graceful Degradation
  16. Error Handling
  17. Advanced Usage
  18. Custom Configuration
  19. Environment-Specific Configuration
  20. Event Pattern Matching
  21. Utility Functions
  22. See Also
  23. License

@bernierllc/neverhub-adapter

Standardized adapter for integrating BernierLLC packages with NeverHub service discovery and event bus system.

Installation

npm install @bernierllc/neverhub-adapter

Features

  • Auto-Detection: Automatically detects if NeverHub is available in the environment
  • Service Registration: Register package capabilities and dependencies with service discovery
  • Event System: Publish/subscribe to events across packages in the ecosystem
  • Service Discovery: Find and use other packages dynamically
  • Health Monitoring: Report package health status and metrics
  • Configuration: Load configuration and connection strings from NeverHub
  • Graceful Degradation: Full functionality when NeverHub is unavailable

Quick Start

Basic Integration

import { NeverHubAdapter } from '@bernierllc/neverhub-adapter';

export class MyPackage {
  private neverhub?: NeverHubAdapter;

  async initialize(): Promise<void> {
    // Auto-detect NeverHub
    if (await NeverHubAdapter.detect()) {
      this.neverhub = new NeverHubAdapter();
      
      // Register with NeverHub
      await this.neverhub.register({
        type: 'my-package',
        name: '@bernierllc/my-package',
        version: '1.0.0',
        capabilities: [
          { type: 'data', name: 'processing', version: '1.0.0' }
        ],
        dependencies: ['logging']
      });
    }

    await this.initializeCore();
  }
}

Event Publishing

// Safe event publishing - works even when NeverHub is unavailable
await this.neverhub?.publishEvent({
  type: 'data.processed',
  data: { recordId: '123', status: 'success' },
  source: 'my-package'
});

Event Subscription

// Subscribe to events with pattern matching
const unsubscribe = await this.neverhub?.subscribe('user.*', async (event) => {
  console.log('User event received:', event);
});

// Clean up subscription when done
// unsubscribe?.();

Service Discovery

// Find services by capability
const services = await this.neverhub?.discover({
  capabilityTypes: ['logging']
});

if (services?.available.includes('structured-logging')) {
  const logger = await this.neverhub.getService('structured-logging');
  // Use the logger service
}

Configuration Management

// Load configuration with defaults
const config = await this.neverhub?.getConfiguration('my-package', {
  logging: { level: 'info' },
  retries: 3
});

// Get connection strings
const dbConnection = await this.neverhub?.getConnectionString('my-package', 'database');

Health Checks and Metrics

// Register health check
await this.neverhub?.registerHealthCheck('my-package', async () => {
  return {
    healthy: this.isOperational(),
    message: 'Service is running normally',
    metadata: { uptime: process.uptime() }
  };
});

// Report metrics
await this.neverhub?.reportMetric('my-package', {
  name: 'requests_total',
  value: 100,
  type: MetricType.COUNTER,
  labels: { status: 'success' }
});

API Reference

NeverHubAdapter Class

Static Methods

  • static detect(): Promise<boolean> - Detect if NeverHub is available

Instance Methods

Core Methods
  • initialize(): Promise<boolean> - Initialize the adapter
  • register(registration: PackageRegistration): Promise<void> - Register package
  • getState(): AdapterState - Get current adapter state
  • isAvailable(): boolean - Check if NeverHub is available
  • isInitialized(): boolean - Check if adapter is initialized
  • isRegistered(): boolean - Check if package is registered
Event Methods
  • publishEvent(event: Event): Promise<void> - Publish event
  • subscribe(pattern: string, handler: EventHandler): Promise<() => void> - Subscribe to events
Discovery Methods
  • discover(criteria: DiscoveryCriteria): Promise<ServiceDiscoveryResult> - Discover services
  • getService(serviceName: string): Promise<any> - Get specific service
Configuration Methods
  • getConfiguration(packageName: string, defaults?: any): Promise<any> - Get configuration
  • getConnectionString(packageName: string, connectionName: string): Promise<string | null> - Get connection string
  • getEnvironmentConfiguration(packageName: string, environment: string, defaults?: any): Promise<any> - Get environment-specific configuration
Health Methods
  • registerHealthCheck(packageName: string, checkFn: HealthCheckFunction): Promise<void> - Register health check
  • reportMetric(packageName: string, metric: Metric): Promise<void> - Report metric

Configuration

The adapter can be configured with environment variables:

  • NEVERHUB_API_URL - Custom NeverHub API URL
  • NEVERHUB_ENDPOINT - Alternative endpoint specification
  • NEVERHUB_HOST - Host-only specification (protocol will be added)

Or programmatically:

const adapter = new NeverHubAdapter({
  apiUrl: 'http://custom.neverhub.com:3001',
  timeout: 5000,
  maxRetries: 5,
  debug: true
});

Types

PackageRegistration

interface PackageRegistration {
  type: string;                    // Package type identifier
  name: string;                    // Full package name including scope
  version: string;                 // Semantic version
  dependencies: string[];          // List of dependency package names
  capabilities: Capability[];      // List of capabilities provided
  discoveryEnabled?: boolean;      // Whether discoverable by others
  discoverySubscriptions?: DiscoverySubscription[];
  webhookUrl?: string;            // Optional webhook URL
}

Event

interface Event {
  type: string;                   // Event type identifier
  data: any;                      // Event payload
  source?: string;                // Source package identifier
  timestamp?: string;             // Event timestamp (ISO string)
  metadata?: Record<string, any>; // Additional metadata
}

Capability

interface Capability {
  type: string;                   // Capability type (e.g., 'data', 'logging')
  name: string;                   // Specific capability name
  version: string;                // Version of the capability interface
  metadata?: Record<string, any>; // Additional metadata
}

Environment Detection

The adapter automatically detects NeverHub availability through:

  1. Environment Variables: Checks for NEVERHUB_API_URL, NEVERHUB_ENDPOINT, or NEVERHUB_HOST
  2. Default Endpoints: Tests http://localhost:3001 and http://neverhub:3001
  3. Health Check: Validates API availability at /api/health

Graceful Degradation

When NeverHub is not available, the adapter:

  • Returns default values for configuration requests
  • Silently ignores event publishing attempts
  • Returns empty results for service discovery
  • Logs warnings for debugging but never throws errors
  • Maintains full package functionality

Error Handling

The adapter is designed with graceful degradation as a core principle:

  • Never throws errors due to NeverHub unavailability
  • Logs warnings for debugging when operations fail
  • Returns sensible defaults when NeverHub data is unavailable
  • Maintains package functionality regardless of NeverHub state

Advanced Usage

Custom Configuration

const adapter = new NeverHubAdapter({
  apiUrl: 'http://my-neverhub.internal:3001',
  timeout: 10000,
  maxRetries: 5,
  debug: process.env.NODE_ENV === 'development'
});

Environment-Specific Configuration

const config = await adapter.getEnvironmentConfiguration(
  'my-package',
  process.env.NODE_ENV || 'development',
  { logging: { level: 'info' } }
);

Event Pattern Matching

The event system supports flexible pattern matching:

  • * - Matches any event type
  • user.* - Matches all user-related events
  • service.*.created - Matches creation events from any service
  • exact.match - Matches only the exact event type

Utility Functions

For advanced use cases, utility functions are exported:

import {
  detectNeverHub,
  publishEvent,
  discoverServices,
  validatePackageRegistration
} from '@bernierllc/neverhub-adapter';

See Also

This package integrates with other BernierLLC packages:

License

Copyright (c) 2025 Bernier LLC. All rights reserved.

版本与发布记录

@bernierllc/neverhub-adapter 共发布 9 个版本,首次发布于 2025/08/30;过去 12 个月发布了 8 个版本。

版本发布日期距今
0.4.1latest2026/07/143 个月前
0.4.02026/05/205 个月前
0.3.02026/05/205 个月前
0.2.02026/05/205 个月前
0.1.62026/03/107 个月前
0.1.52026/03/048 个月前

关于 @bernierllc/neverhub-adapter 的常见问题

@bernierllc/neverhub-adapter 是什么?

Standardized adapter for integrating BernierLLC packages with NeverHub service discovery and event bus system

如何安装 @bernierllc/neverhub-adapter?

在项目目录运行 npm install @bernierllc/neverhub-adapter,或使用 pnpm add / yarn add / bun add。

@bernierllc/neverhub-adapter 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@bernierllc/neverhub-adapter 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@bernierllc/neverhub-adapter 可以商用吗?

@bernierllc/neverhub-adapter 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@bernierllc/neverhub-adapter 的下载量有多少?

根据 npm 官方下载统计,@bernierllc/neverhub-adapter 在 2026/10/08 – 2026/11/06 这 30 天内被下载 4,397 次,日均约 147 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bernierllc/neverhub-adapter 还在维护吗?

最新版本 0.4.1 发布于 2026/07/14(3 个月前);至今共发布 9 个版本,其中过去 12 个月发布了 8 个;首次发布于 2025/08/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。