@usageflow/core
v0.5.0
Published
Core functionality for UsageFlow integrations
Readme
@usageflow/core
Core functionality for UsageFlow API tracking. This package provides the base implementation for tracking API usage across different Node.js frameworks.
Installation
npm install @usageflow/coreOverview
@usageflow/core is the foundational package that provides core functionality for UsageFlow integrations. It includes:
- Base
UsageFlowAPIclass for framework-agnostic usage tracking - WebSocket connection management with connection pooling
- Route pattern matching and ledger ID generation
- Request metadata collection and sanitization
- Configuration management and policy fetching
Usage
This package is typically used indirectly through framework-specific implementations:
- @usageflow/express for Express.js
- @usageflow/fastify for Fastify
- @usageflow/nestjs for NestJS
If you need to extend UsageFlow for a different framework, you can extend the UsageFlowAPI class:
import { UsageFlowAPI, UsageFlowAPIConfig } from '@usageflow/core';
class CustomFrameworkUsageFlowAPI extends UsageFlowAPI {
constructor(config: UsageFlowAPIConfig) {
super(config);
this.setWebServer('custom');
}
// Implement framework-specific methods
}API Reference
UsageFlowAPIConfig
interface UsageFlowAPIConfig {
apiKey: string; // Your UsageFlow API key
poolSize?: number; // Number of WebSocket connections (default: 5)
}UsageFlowAPI
Base class for all UsageFlow implementations.
Constructor
constructor(config: UsageFlowAPIConfig)Methods
setWebServer(webServer: 'express' | 'fastify' | 'nestjs'): void
Sets the web server type for route pattern extraction.
getApiKey(): string | null
Returns the configured API key.
getUsageflowUrl(): string
Returns the UsageFlow API URL.
getRoutePattern(request: UsageFlowRequest): string
Extracts the route pattern from a request object. Supports Express, Fastify, and NestJS.
guessLedgerId(request: UsageFlowRequest, overrideUrl?: string): string
Generates a ledger ID for tracking based on the request and configured policies.
createRoutesMap(routes: Route[]): RoutesMap
Converts an array of routes into a map for efficient lookup.
shouldSkipRoute(method: string, url: string, whitelistMap: RoutesMap): boolean
Checks if a route should be skipped based on the whitelist.
shouldMonitorRoute(method: string, url: string, routesMap: RoutesMap): boolean
Checks if a route should be monitored based on the routes map.
sanitizeHeaders(headers: Headers): Headers
Sanitizes sensitive information from headers (authorization tokens, API keys, etc.).
extractBearerToken(authHeader?: string): string | null
Extracts the bearer token from an Authorization header.
decodeJwtUnverified(token: string): Record<string, any> | null
Decodes a JWT token without verifying the signature.
allocationRequest(request: UsageFlowRequest, payload: RequestForAllocation, metadata: RequestMetadata): Promise<void>
Sends an allocation request via WebSocket.
useAllocationRequest(payload: RequestForAllocation): Promise<void>
Finalizes an allocation request.
destroy(): void
Cleans up resources including intervals and WebSocket connections.
UsageFlowSocketManager
Manages WebSocket connections with connection pooling.
Constructor
constructor(apiKey: string, poolSize?: number)Methods
connect(): Promise<void>
Establishes WebSocket connections in the pool.
sendAsync<T>(payload: UsageFlowSocketMessage): Promise<UsageFlowSocketResponse<T>>
Sends a message and waits for a response.
send(payload: UsageFlowSocketMessage): void
Sends a message without waiting for a response.
isConnected(): boolean
Checks if at least one WebSocket connection is active.
close(): void
Closes all WebSocket connections.
destroy(): void
Cleans up all resources.
Types
Route
interface Route {
method: string; // HTTP method or '*' for all methods
url: string; // URL pattern or '*' for all URLs
}RequestMetadata
interface RequestMetadata {
method: string;
url: string;
rawUrl: string;
clientIP: string;
userAgent?: string;
timestamp: string;
headers: Record<string, string>;
queryParams: Record<string, any> | null;
pathParams: Record<string, any> | null;
body?: any;
requestDuration?: number;
}UsageFlowConfig
interface UsageFlowConfig {
url: string;
method: string;
identityFieldName?: string;
identityFieldLocation?:
| 'path_params'
| 'query_params'
| 'body'
| 'bearer_token'
| 'headers';
}Requirements
- Node.js >= 18.0.0
- TypeScript >= 5.0.0 (for TypeScript projects)
Dependencies
axios: HTTP client for API requestsws: WebSocket client library
Development
# Install dependencies
npm install
# Build the package
npm run build
# Run tests
npm testLicense
MIT
Support
For issues, questions, or contributions, please visit our GitHub repository.
