@delta-base/server
Version:
Server SDK for delta-base
1,243 lines (1,232 loc) • 42.1 kB
TypeScript
import { Event, ReadEvent, StreamPosition, EventStore as EventStore$2, AggregateStreamOptions, AggregateStreamResult, ReadStreamOptions, ReadStreamResult, AppendToStreamOptions, AppendToStreamResult } from '@delta-base/toolkit';
export { AggregateStreamOptions, AggregateStreamResult, AppendToStreamOptions, AppendToStreamResult, AuthenticationError, AuthorizationError, DeltaBaseError, DeltaBaseErrorTypes, Event, EventStoreAlreadyExistsError, EventStoreNotFoundError, ExpectedStreamVersion, GlobalPosition, InternalServerError, InvalidSubscriptionConfigError, NotFoundError, RateLimitError, ReadEvent, ReadStreamOptions, ReadStreamResult, SerializationError, StorageError, StreamNotFoundError, StreamPosition, StreamVersionConflictError, SubscriptionNotFoundError, TimeoutError, ValidationError, ValidationErrors, VersionConflictError, assertNotEmptyString, assertPositiveNumber, assertUnsignedBigInt, isAuthenticationError, isAuthorizationError, isDeltaBaseError, isEventStoreAlreadyExistsError, isEventStoreNotFoundError, isInternalServerError, isInvalidSubscriptionConfigError, isNotFoundError, isNumber, isRateLimitError, isSerializationError, isStorageError, isStreamNotFoundError, isStreamVersionConflictError, isString, isSubscriptionNotFoundError, isTimeoutError, isValidationError, isVersionConflictError } from '@delta-base/toolkit';
interface HttpClientConfig {
baseUrl: string;
apiKey?: string;
headers?: Record<string, string>;
}
declare class HttpClient {
private baseUrl;
private apiKey?;
private customHeaders?;
constructor(config: HttpClientConfig);
/**
* Perform a GET request
*/
get<T>(path: string, params?: Record<string, string>): Promise<T>;
/**
* Perform a POST request
*/
post<T>(path: string, body?: Record<string, unknown>): Promise<T>;
/**
* Perform a PUT request
*/
put<T>(path: string, body?: Record<string, unknown>): Promise<T>;
/**
* Perform a DELETE request
*/
delete<T>(path: string): Promise<T>;
/**
* Get common headers for all requests
*/
private getHeaders;
/**
* Handle API response and convert to typed errors
*/
private handleResponse;
/**
* Create a typed error based on status code and response body
*/
private createTypedError;
/**
* Type guard for version conflict error responses
*/
private isVersionConflictError;
/**
* Type guard for validation error responses
*/
private isValidationError;
/**
* Type guard for general error responses
*/
private isGeneralError;
}
/**
* EventBus API client for managing event subscriptions
*/
/**
* Available subscriber types for event subscriptions
*/
declare enum SubscriberType {
DurableObject = "durable_object",
Webhook = "webhook",
Queue = "queue",
CloudflareWorkflow = "cloudflare_workflow",
WebSocket = "websocket"
}
/**
* Subscription status values
*/
declare enum SubscriptionStatus {
Active = "ACTIVE",
Suspended = "SUSPENDED",
Error = "ERROR",
Initializing = "INITIALIZING",
Deleted = "DELETED"
}
/**
* Retry policy configuration for subscribers
*/
interface RetryPolicy {
/**
* Maximum number of delivery attempts before giving up
*/
maxAttempts: number;
/**
* How many minutes to wait between retry attempts
*/
backoffMinutes: number;
}
/**
* Base configuration shared by all subscriber types
*/
interface BaseSubscriberConfig {
/**
* Configuration for retry behavior
*/
retryPolicy?: RetryPolicy;
}
/**
* Configuration for webhook subscribers
*/
interface WebhookConfig extends BaseSubscriberConfig {
/**
* The URL that will receive HTTP POST requests with events
*/
url: string;
/**
* Custom headers to include in the webhook request
*/
headers?: Record<string, string>;
/**
* Timeout in milliseconds for the webhook request
*/
timeoutMs?: number;
}
/**
* Union type for all subscriber configurations
*/
type SubscriberConfig = {
type: SubscriberType.Webhook;
config: WebhookConfig;
};
/**
* Type of initial position for subscriptions
*/
type InitialPosition = 'latest' | 'earliest';
/**
* Event filter pattern for subscriptions
*/
type EventFilterPattern = string | string[];
/**
* Status details for a subscription
*/
interface SubscriptionStatusDetails {
/**
* Last error message if the subscription is in an error state
*/
lastError?: string;
/**
* When the last error occurred
*/
lastErrorAt?: string;
/**
* Number of retries that have been attempted
*/
retryCount?: number;
/**
* When the next retry will be attempted
*/
nextRetryAt?: string;
}
/**
* Complete subscription information
*/
interface Subscription {
/**
* Unique identifier for this subscription
*/
subscriptionId: string;
/**
* Current status of the subscription
*/
status: SubscriptionStatus;
/**
* Additional details about the current status
*/
statusDetails?: SubscriptionStatusDetails;
/**
* The event store this subscription is connected to
*/
eventStoreId: string;
/**
* The event pattern this subscription is filtering on
*/
eventFilter: string;
/**
* The ID of the subscriber
*/
subscriberId: string;
/**
* Type of subscriber receiving events
*/
subscriberType: SubscriberType;
/**
* When this subscription was created
*/
createdAt: string;
/**
* When this subscription was last updated
*/
updatedAt: string;
/**
* The global position of the last successfully delivered event
*/
lastProcessedEventGlobalPosition?: number;
/**
* Whether this is an existing subscription that was found instead of creating a new one
*/
isExistingSubscription?: boolean;
/**
* Human-readable message about the subscription operation
*/
message?: string;
}
/**
* Options for creating a subscription
*/
interface SubscribeOptions {
/**
* Pattern(s) determining which events to receive
*/
eventFilter: EventFilterPattern;
/**
* Optional custom ID for this subscription. If not provided, one will be generated.
*/
subscriberId?: string;
/**
* Configuration for the subscriber that will receive events
*/
subscriber: SubscriberConfig;
/**
* The position in the message stream from which a consumer starts consuming messages
* when there is no prior checkpoint. Defaults to latest.
*/
initialPosition?: InitialPosition;
}
/**
* Options for listing subscriptions
*/
interface ListSubscriptionsOptions {
/**
* Filter results by subscriber type
*/
subscriberType?: SubscriberType;
/**
* Filter results by event filter pattern
*/
eventFilter?: string;
/**
* Maximum number of results to return
*/
limit?: number;
/**
* Number of results to skip
*/
offset?: number;
}
/**
* Response from listing subscriptions
*/
interface ListSubscriptionsResponse {
/**
* Array of subscription details
*/
subscriptions: Subscription[];
/**
* Total number of subscriptions matching the query
*/
totalCount: number;
}
/**
* Type for received events from a subscription
*/
interface SubscriptionEvent {
/**
* Unique identifier for the event
*/
id: string;
/**
* Type of the event
*/
type: string;
/**
* Event data payload
*/
data: Record<string, unknown>;
/**
* Optional metadata associated with the event
*/
metadata?: Record<string, unknown>;
}
/**
* EventBus client for managing subscriptions to an event store
*/
declare class EventBus {
private http;
private eventStoreName;
/**
* Create a new EventBus client for a specific event store
*
* @param http - The HTTP client used for API requests
* @param eventStoreName - The name of the event store to manage subscriptions for
*/
constructor(http: HttpClient, eventStoreName: string);
/**
* Subscribe to events from this event store
*
* @param options - Configuration for the subscription
* @returns The created subscription information
* @throws {InvalidSubscriptionConfigError} When subscription configuration is invalid
* @throws {EventStoreNotFoundError} When the event store doesn't exist
* @throws {ValidationError} When request validation fails
* @throws {AuthenticationError} When authentication fails
*
* @example
* ```typescript
* import {
* isInvalidSubscriptionConfigError,
* isEventStoreNotFoundError
* } from '@delta-base/server';
*
* try {
* const subscription = await eventBus.subscribe({
* eventFilter: 'user.*',
* subscriber: {
* type: SubscriberType.Webhook,
* config: {
* url: 'https://example.com/webhook',
* headers: { 'X-API-Key': 'secret' },
* retryPolicy: {
* maxAttempts: 3,
* backoffMinutes: 5
* }
* }
* }
* });
*
* // Check if this is an existing subscription
* if (subscription.isExistingSubscription) {
* console.log('Found existing subscription:', subscription.message);
* } else {
* console.log('Created new subscription:', subscription.message);
* }
* } catch (error) {
* if (isInvalidSubscriptionConfigError(error)) {
* console.log(`Invalid configuration: ${error.configError}`);
* // Handle invalid subscription config
* } else if (isEventStoreNotFoundError(error)) {
* console.log(`Event store '${error.eventStoreId}' not found`);
* // Handle missing event store
* } else {
* throw error; // Re-throw unknown errors
* }
* }
* ```
*/
subscribe(options: SubscribeOptions): Promise<Subscription>;
/**
* Create a webhook subscription
*
* @param eventFilter - Pattern determining which events to receive
* @param url - The URL that will receive HTTP POST requests with events
* @param options - Additional configuration options
* @returns The created subscription information
*
* @example
* ```typescript
* // Subscribe to all user events
* const subscription = await eventBus.subscribeWebhook(
* 'user.*',
* 'https://example.com/webhook',
* {
* headers: { 'X-API-Key': 'secret' },
* retryPolicy: {
* maxAttempts: 3,
* backoffMinutes: 5
* }
* }
* );
*
* // Check if this is an existing subscription with the same configuration
* if (subscription.isExistingSubscription) {
* console.log('Reusing existing subscription:', subscription.message);
* } else {
* console.log('Created new subscription:', subscription.message);
* }
* ```
*/
subscribeWebhook(eventFilter: EventFilterPattern, url: string, options?: Omit<WebhookConfig, 'url'> & {
subscriberId?: string;
initialPosition?: InitialPosition;
}): Promise<Subscription>;
/**
* Get details about a specific subscription
*
* @param subscriptionId - ID of the subscription to retrieve
* @returns Subscription details
*
* @example
* ```typescript
* const subscription = await eventBus.getSubscription('sub_123456');
* console.log(subscription.status); // 'ACTIVE'
* ```
*/
getSubscription(subscriptionId: string): Promise<Subscription>;
/**
* List all subscriptions for this event store
*
* @param options - Optional filtering and pagination parameters
* @returns List of subscriptions and total count
*
* @example
* ```typescript
* // List all webhook subscriptions
* const { subscriptions, totalCount } = await eventBus.listSubscriptions({
* subscriberType: SubscriberType.Webhook,
* limit: 20,
* offset: 0
* });
* ```
*/
listSubscriptions(options?: ListSubscriptionsOptions): Promise<ListSubscriptionsResponse>;
/**
* Unsubscribe from events (delete a subscription)
*
* @param subscriptionId - ID of the subscription to delete
* @returns Success message
*
* @example
* ```typescript
* const result = await eventBus.unsubscribe('sub_123456');
* console.log(result.success); // true
* ```
*/
unsubscribe(subscriptionId: string): Promise<{
success: boolean;
message: string;
}>;
/**
* Map API subscription response to Subscription type
*
* @param response - The API response to map
* @returns Mapped subscription
* @private
*/
private mapSubscriptionResponse;
}
/**
* EventStore API client for interacting with event streams
*/
/**
* Stream information returned from a query
*/
interface StreamInfo {
streamId: string;
streamPosition: StreamPosition;
streamType: string;
streamMetadata: Record<string, unknown>;
isArchived: boolean;
lastArchivedPosition: StreamPosition;
createdAt: string;
updatedAt: string;
}
/**
* Query parameters for filtering events
*/
interface QueryEventsOptions {
streamId?: string;
type?: string | string[];
eventId?: string;
transactionId?: string;
fromPosition?: number;
toPosition?: number;
fromDate?: string;
toDate?: string;
phase?: number;
includeArchived?: boolean;
limit?: number;
offset?: number;
sortBy?: 'globalPosition' | 'createdAt' | 'streamPosition';
sortDirection?: 'asc' | 'desc';
includeCount?: boolean;
}
/**
* Query parameters for filtering streams
*/
interface QueryStreamsOptions {
streamId?: string;
streamType?: string | string[];
streamIdPattern?: string;
minPosition?: number;
maxPosition?: number;
fromDate?: string;
toDate?: string;
includeArchived?: boolean;
includeMetadata?: boolean;
limit?: number;
offset?: number;
sortBy?: 'streamPosition' | 'createdAt' | 'updatedAt' | 'streamId';
sortDirection?: 'asc' | 'desc';
includeCount?: boolean;
}
/**
* Result of a query events operation
*/
interface QueryEventsResult<EventType extends Event = Event> {
events: ReadEvent<EventType>[];
pagination: {
limit: number;
offset: number;
total?: number;
hasMore: boolean;
};
}
/**
* Result of a query streams operation
*/
interface QueryStreamsResult {
streams: StreamInfo[];
pagination: {
limit: number;
offset: number;
total?: number;
hasMore: boolean;
};
}
/**
* Implementation of the EventStore interface for DeltaBase
*/
declare class EventStore$1 implements EventStore$2 {
private http;
private eventStoreName;
/**
* Creates a new EventStore client instance
*
* @param http - The HTTP client to use for API requests
* @param eventStoreName - The name of the event store to interact with
*/
constructor(http: HttpClient, eventStoreName: string);
/**
* Aggregate events from a stream and compute a state
*
* @param streamId - The ID of the stream to aggregate events from
* @param options - Configuration options for the aggregation process
* @param options.initialState - Function that returns the initial state
* @param options.evolve - Function that applies an event to the current state
* @param options.read - Optional read options to control which events to include
* @returns Promise resolving to the aggregation result with the computed state and stream metadata
*
* @example
* ```typescript
* // Define your state type and event types
* type UserState = { email: string, isVerified: boolean };
* type UserEvent =
* | { type: 'user.created', data: { email: string } }
* | { type: 'user.verified', data: { verifiedAt: string } };
*
* // Aggregate the stream into a state
* const result = await eventStore.aggregateStream<UserState, UserEvent>(
* 'user-123',
* {
* initialState: () => ({ email: '', isVerified: false }),
* evolve: (state, event) => {
* switch (event.type) {
* case 'user.created':
* return { ...state, email: event.data.email };
* case 'user.verified':
* return { ...state, isVerified: true };
* default:
* return state;
* }
* },
* read: { from: 0 }
* }
* );
* ```
*/
aggregateStream<State, EventType extends Event>(streamId: string, options: AggregateStreamOptions<State, EventType>): Promise<AggregateStreamResult<State>>;
/**
* Read events from a stream
*
* @param streamId - The ID of the stream to read events from
* @param options - The options for reading events
* @param options.from - Optional starting position to read from
* @param options.to - Optional ending position to read to
* @param options.maxCount - Optional maximum number of events to read
* @param options.expectedStreamVersion - Optional expected version for optimistic concurrency
* @returns Promise resolving to the read result containing events and stream metadata
*
* @example
* ```typescript
* // Read all events from a stream
* const result = await eventStore.readStream('user-123');
*
* // Read events with a specific starting position
* const result = await eventStore.readStream('user-123', { from: 5 });
*
* // Read a specific range of events
* const result = await eventStore.readStream('user-123', { from: 5, to: 10 });
*
* // Read a limited number of events
* const result = await eventStore.readStream('user-123', { maxCount: 100 });
* ```
*/
readStream<EventType extends Event>(streamId: string, options?: ReadStreamOptions): Promise<ReadStreamResult<EventType>>;
/**
* Append events to a stream
*
* @param streamId - The ID of the stream to append events to
* @param events - Array of events to append to the stream
* @param options - Optional parameters for the append operation
* @param options.expectedStreamVersion - Optional expected version for optimistic concurrency
* @returns Promise resolving to the append result with the next expected version
* @throws {VersionConflictError} When expectedStreamVersion doesn't match current stream version
* @throws {ValidationError} When request validation fails
* @throws {EventStoreNotFoundError} When the event store doesn't exist
* @throws {AuthenticationError} When authentication fails
*
* @example
* ```typescript
* import {
* isVersionConflictError,
* isValidationError
* } from '@delta-base/server';
*
* try {
* // Append with optimistic concurrency control
* await eventStore.appendToStream(
* 'user-123',
* [{
* type: 'user.updated',
* data: { email: 'updated@example.com' }
* }],
* { expectedStreamVersion: 0n }
* );
* } catch (error) {
* if (isVersionConflictError(error)) {
* console.log(`Version conflict: expected ${error.expectedVersion}, got ${error.currentVersion}`);
* // Handle concurrency conflict
* } else if (isValidationError(error)) {
* console.log('Validation errors:', error.validationErrors);
* // Handle validation failures
* } else {
* throw error; // Re-throw unknown errors
* }
* }
* ```
*/
appendToStream<EventType extends Event>(streamId: string, events: EventType[], options?: AppendToStreamOptions): Promise<AppendToStreamResult>;
/**
* Query events with flexible filtering options
*
* @param options - Query parameters for filtering events
* @param options.streamId - Optional stream ID to filter by
* @param options.type - Optional event type(s) to filter by
* @param options.eventId - Optional specific event ID to retrieve
* @param options.transactionId - Optional transaction ID to filter by
* @param options.fromPosition - Optional starting global position
* @param options.toPosition - Optional ending global position
* @param options.fromDate - Optional starting date for time-based filtering
* @param options.toDate - Optional ending date for time-based filtering
* @param options.phase - Optional event phase to filter by
* @param options.includeArchived - Whether to include archived events
* @param options.limit - Maximum number of events to return
* @param options.offset - Number of events to skip
* @param options.sortBy - Field to sort results by
* @param options.sortDirection - Direction to sort results
* @param options.includeCount - Whether to include total count in results
* @returns Promise resolving to the query result with events and pagination info
*
* @example
* ```typescript
* // Query all events of a specific type
* const result = await eventStore.queryEvents({
* type: 'user.created'
* });
*
* // Query events with pagination
* const result = await eventStore.queryEvents({
* limit: 20,
* offset: 40,
* includeCount: true
* });
*
* // Query events within a time range
* const result = await eventStore.queryEvents({
* fromDate: '2023-01-01T00:00:00Z',
* toDate: '2023-01-31T23:59:59Z'
* });
* ```
*/
queryEvents<EventType extends Event = Event>(options?: QueryEventsOptions): Promise<QueryEventsResult<EventType>>;
/**
* Query events for a specific stream with filtering options
*
* @param streamId - The ID of the stream to query events from
* @param options - Query parameters for filtering events
* @param options.type - Optional event type(s) to filter by
* @param options.eventId - Optional specific event ID to retrieve
* @param options.transactionId - Optional transaction ID to filter by
* @param options.fromPosition - Optional starting global position
* @param options.toPosition - Optional ending global position
* @param options.fromDate - Optional starting date for time-based filtering
* @param options.toDate - Optional ending date for time-based filtering
* @param options.phase - Optional event phase to filter by
* @param options.includeArchived - Whether to include archived events
* @param options.limit - Maximum number of events to return
* @param options.offset - Number of events to skip
* @param options.sortBy - Field to sort results by
* @param options.sortDirection - Direction to sort results
* @param options.includeCount - Whether to include total count in results
* @returns Promise resolving to the query result with events and pagination info
*
* @example
* ```typescript
* // Query events for a specific stream
* const result = await eventStore.queryStreamEvents('user-123', {
* type: 'user.updated'
* });
* ```
*/
queryStreamEvents<EventType extends Event = Event>(streamId: string, options?: Omit<QueryEventsOptions, 'streamId'>): Promise<QueryEventsResult<EventType>>;
/**
* Query streams with filtering options
*
* @param options - Query parameters for filtering streams
* @param options.streamId - Optional specific stream ID to retrieve
* @param options.streamType - Optional stream type(s) to filter by
* @param options.streamIdPattern - Optional pattern to match stream IDs
* @param options.minPosition - Optional minimum stream position
* @param options.maxPosition - Optional maximum stream position
* @param options.fromDate - Optional starting date for time-based filtering
* @param options.toDate - Optional ending date for time-based filtering
* @param options.includeArchived - Whether to include archived streams
* @param options.includeMetadata - Whether to include stream metadata
* @param options.limit - Maximum number of streams to return
* @param options.offset - Number of streams to skip
* @param options.sortBy - Field to sort results by
* @param options.sortDirection - Direction to sort results
* @param options.includeCount - Whether to include total count in results
* @returns Promise resolving to the query result with streams and pagination info
*
* @example
* ```typescript
* // Query all streams
* const result = await eventStore.queryStreams();
*
* // Query streams by type
* const result = await eventStore.queryStreams({
* streamType: 'user'
* });
*
* // Query streams with a pattern match
* const result = await eventStore.queryStreams({
* streamIdPattern: 'user-%'
* });
* ```
*/
queryStreams(options?: QueryStreamsOptions): Promise<QueryStreamsResult>;
/**
* Query streams of a specific type with filtering options
*
* @param streamType - The stream type to filter by
* @param options - Query parameters for filtering streams
* @param options.streamId - Optional specific stream ID to retrieve
* @param options.streamIdPattern - Optional pattern to match stream IDs
* @param options.minPosition - Optional minimum stream position
* @param options.maxPosition - Optional maximum stream position
* @param options.fromDate - Optional starting date for time-based filtering
* @param options.toDate - Optional ending date for time-based filtering
* @param options.includeArchived - Whether to include archived streams
* @param options.includeMetadata - Whether to include stream metadata
* @param options.limit - Maximum number of streams to return
* @param options.offset - Number of streams to skip
* @param options.sortBy - Field to sort results by
* @param options.sortDirection - Direction to sort results
* @param options.includeCount - Whether to include total count in results
* @returns Promise resolving to the query result with streams and pagination info
*
* @example
* ```typescript
* // Query all user streams
* const result = await eventStore.queryStreamsByType('user');
*
* // Query user streams with pagination
* const result = await eventStore.queryStreamsByType('user', {
* limit: 20,
* offset: 0
* });
* ```
*/
queryStreamsByType(streamType: string, options?: Omit<QueryStreamsOptions, 'streamType'>): Promise<QueryStreamsResult>;
/**
* Get a list of stream IDs in an event store
*
* @param options - Optional parameters for listing streams
* @param options.limit - Maximum number of stream IDs to return
* @param options.offset - Number of stream IDs to skip
* @param options.pattern - Pattern to match stream IDs (e.g., 'user-*')
* @returns Promise resolving to an object containing stream IDs and total count
*
* @example
* ```typescript
* // List all streams
* const { streams, total } = await eventStore.listStreams();
*
* // List streams with pagination
* const { streams, total } = await eventStore.listStreams({
* limit: 50,
* offset: 100
* });
*
* // List streams matching a pattern
* const { streams, total } = await eventStore.listStreams({
* pattern: 'user-*'
* });
* ```
*/
listStreams(options?: {
limit?: number;
offset?: number;
pattern?: string;
}): Promise<{
streams: string[];
total: number;
}>;
}
/**
* Management API client for interacting with Delta-Base event stores.
*
* This client provides operations for creating, listing, retrieving, updating,
* and deleting event stores in the DeltaBase platform.
*/
/**
* Event store information returned from the Management API.
* Contains basic information about an event store.
*/
interface EventStore {
/**
* Unique identifier for the event store
*/
id: string;
/**
* Display name of the event store
*/
name: string;
/**
* Optional description of the event store's purpose or contents
*/
description?: string;
/**
* Optional cloud region where the event store is located
*/
region?: string;
/**
* ISO timestamp of when the event store was created
*/
createdAt: string;
/**
* ISO timestamp of when the event store was last updated
*/
updatedAt: string;
/**
* Current status of the event store
*/
status: 'active' | 'suspended' | 'deleted';
}
/**
* Response from listing event stores.
* Contains an array of event stores and their total count.
*/
interface EventStoreListResponse {
/**
* Array of event stores returned from the listing operation
*/
eventStores: EventStore[];
/**
* Total number of event stores available (for pagination)
*/
totalCount: number;
}
/**
* Detailed event store information including usage statistics and settings.
* Extends the basic EventStore interface with additional details.
*/
interface EventStoreDetailsResponse extends EventStore {
/**
* Usage statistics for the event store
*/
statistics?: {
/**
* Total number of event streams stored
*/
totalStreams: number;
/**
* Total number of events stored
*/
totalEvents: number;
/**
* Storage size in bytes used by the event store
*/
databaseSizeBytes: number;
/**
* ISO timestamp of the oldest event in the store, if available
*/
oldestEventTimestamp?: string;
/**
* ISO timestamp of the newest event in the store, if available
*/
newestEventTimestamp?: string;
};
/**
* Configuration settings for the event store
*/
settings?: {
/**
* Number of days events are retained before automatic deletion
*/
retentionPeriodDays: number;
/**
* Maximum size in bytes allowed per event stream
*/
maxStreamSizeBytes: number;
};
}
/**
* Options for creating a new event store.
*/
interface CreateEventStoreOptions {
/**
* Display name of the event store (required) - should be between 3 and 64 characters long and can only contain lowercase letters, numbers, and hyphens
*/
name: string;
/**
* Optional description of the event store's purpose or contents
*/
description?: string;
/**
* Optional cloud region where the event store should be created
*/
region?: string;
/**
* Optional configuration settings for the event store
*/
settings?: {
/**
* Number of days to retain events before automatic deletion
*/
retentionPeriodDays?: number;
/**
* Maximum size in bytes allowed per event stream
*/
maxStreamSizeBytes?: number;
};
}
/**
* Management client for creating and managing event stores.
*
* Provides operations for the lifecycle of event stores including:
* - Creating new event stores
* - Listing available event stores
* - Getting details about specific event stores
* - Updating event store settings
* - Deleting event stores
*/
declare class ManagementClient {
private http;
/**
* Creates a new ManagementClient instance.
*
* @param http - The HTTP client to use for API requests
*/
constructor(http: HttpClient);
/**
* Creates a new event store in the DeltaBase platform.
*
* @param options - Configuration for the new event store
* @returns Promise resolving to the created event store information
* @throws {EventStoreAlreadyExistsError} When an event store with the same name exists
* @throws {ValidationError} When request validation fails
* @throws {AuthenticationError} When authentication fails
* @throws {InternalServerError} When the server encounters an error
*
* @example
* ```typescript
* import {
* isEventStoreAlreadyExistsError,
* isValidationError
* } from '@delta-base/server';
*
* try {
* const eventStore = await managementClient.createEventStore({
* name: 'orders-production',
* description: 'Production event store for order events',
* settings: {
* retentionPeriodDays: 90,
* maxStreamSizeBytes: 1073741824 // 1GB
* }
* });
* } catch (error) {
* if (isEventStoreAlreadyExistsError(error)) {
* console.log(`Event store '${error.name}' already exists`);
* // Handle existing event store
* } else if (isValidationError(error)) {
* console.log('Validation errors:', error.validationErrors);
* // Handle validation failures
* } else {
* throw error; // Re-throw unknown errors
* }
* }
* ```
*/
createEventStore(options: CreateEventStoreOptions): Promise<EventStore>;
/**
* Retrieves a list of all event stores accessible to the current user.
*
* @returns Promise resolving to a list of event stores and total count
*
* @example
* ```typescript
* // Get all available event stores
* const { eventStores, totalCount } = await managementClient.listEventStores();
*
* // Display event store names
* eventStores.forEach(store => {
* console.log(`${store.name} (${store.id}): ${store.status}`);
* });
* ```
*/
listEventStores(): Promise<EventStoreListResponse>;
/**
* Retrieves detailed information about a specific event store.
*
* @param eventStoreName - Name of the event store to retrieve
* @returns Promise resolving to detailed information about the event store
*
* @example
* ```typescript
* // Get details for a specific event store
* const eventStore = await managementClient.getEventStore('es_12345');
*
* // Access statistics
* if (eventStore.statistics) {
* console.log(`Total events: ${eventStore.statistics.totalEvents}`);
* console.log(`Storage used: ${eventStore.statistics.databaseSizeBytes} bytes`);
* }
* ```
*/
getEventStore(eventStoreName: string): Promise<EventStoreDetailsResponse>;
/**
* Permanently deletes an event store and all its data.
*
* This operation cannot be undone. All event streams, events, and
* subscriptions associated with this event store will be deleted.
*
* @param eventStoreName - Name of the event store to delete
* @returns Promise that resolves when the deletion is complete
*
* @example
* ```typescript
* // Delete an event store
* await managementClient.deleteEventStore('es_12345');
* ```
*/
deleteEventStore(eventStoreName: string): Promise<void>;
/**
* Updates settings for an existing event store.
*
* @param eventStoreName - ID of the event store to update
* @param settings - New settings for the event store
* @param settings.description - Optional new description for the event store
* @param settings.retentionPeriodDays - Optional new retention period in days
* @param settings.maxStreamSizeBytes - Optional new maximum stream size in bytes
* @returns Promise resolving to the updated event store information
*
* @example
* ```typescript
* // Update event store description
* const updated = await managementClient.updateEventStore('es_12345', {
* description: 'Updated description for this event store'
* });
*
* // Update event store retention settings
* const updated = await managementClient.updateEventStore('es_12345', {
* retentionPeriodDays: 180, // Keep events for 6 months
* maxStreamSizeBytes: 536870912 // 512MB per stream
* });
* ```
*/
updateEventStore(eventStoreName: string, settings: {
description?: string;
retentionPeriodDays?: number;
maxStreamSizeBytes?: number;
}): Promise<EventStore>;
}
/**
* Configuration options for the DeltaBase client.
*/
interface DeltaBaseConfig {
/**
* Base URL of the Delta-Base API.
* For production use the default URL. For local development,
* specify your local server address.
* @default 'http://localhost:8787'
*/
baseUrl?: string;
/**
* API key for authentication with the Delta-Base platform.
* Required for all API operations. You can obtain this from
* your Delta-Base dashboard.
*/
apiKey?: string;
/**
* Custom headers to include with all requests.
* Useful for internal service authentication or other custom headers.
*/
headers?: Record<string, string>;
}
/**
* DeltaBase client for interacting with the Delta-Base platform.
*
* This is the main entry point for the SDK that provides access to:
* - Management operations (create/delete event stores)
* - Event store operations (append/read events)
* - Event bus functionality (subscriptions and real-time updates)
*
* @example
* ```typescript
* // Initialize the client
* const client = new DeltaBase({
* apiKey: "your-api-key"
* });
*
* // Access various functionality
* const management = client.getManagement();
* const eventStore = client.getEventStore("my-store");
* const eventBus = client.getEventBus("my-store");
* ```
*/
declare class DeltaBase {
private http;
/**
* Creates a new DeltaBase client instance.
*
* @param config - Configuration options for connecting to the Delta-Base platform
* @throws {Error} If neither apiKey nor headers are provided in the configuration
*
* @example
* ```typescript
* // Create with API key (standard authentication)
* const client = new DeltaBase({ apiKey: "your-api-key" });
*
* // Create with custom URL (production)
* const prodClient = new DeltaBase({
* baseUrl: "https://api.delta-base.com",
* apiKey: "your-api-key"
* });
*
* // Create with custom headers (internal service authentication)
* const internalClient = new DeltaBase({
* baseUrl: "https://api.delta-base.com",
* headers: {
* 'X-Deltabase-Internal-Service': 'auth-service',
* 'X-Deltabase-Internal-Token': 'internal-token'
* }
* });
* ```
*/
constructor(config: DeltaBaseConfig);
/**
* Get a ManagementClient for managing event stores
*
* @returns A ManagementClient instance for creating and managing event stores
* @example
* ```typescript
* const management = client.getManagement();
* const eventStore = await management.createEventStore({
* name: "my-event-store"
* });
* ```
*/
getManagement(): ManagementClient;
/**
* Get an EventStore client for a specific event store
*
* @param eventStoreName The name of the event store to connect to
* @returns An EventStore client instance configured for the specified event store
* @example
* ```typescript
* const eventStore = client.getEventStore("my-event-store");
* await eventStore.appendToStream("user-123", [
* { type: "UserCreated", data: { userId: "123", name: "John" } }
* ]);
* ```
*/
getEventStore(eventStoreName: string): EventStore$1;
/**
* Get an EventBus client for a specific event store
*
* @param eventStoreName The name of the event store to manage subscriptions for
* @returns An EventBus client instance configured for the specified event store
* @example
* ```typescript
* const eventBus = client.getEventBus("my-event-store");
* const subscription = await eventBus.createSubscription({
* name: "user-events",
* eventFilter: "user.*"
* });
* ```
*/
getEventBus(eventStoreName: string): EventBus;
}
interface EventStoreConfig {
name: string;
description?: string;
settings?: {
retentionPeriodDays?: number;
maxStreamSizeBytes?: number;
};
subscriptions: SubscriptionConfig[];
}
interface SubscriptionConfig {
id: string;
eventFilter: string | string[];
subscriberType: 'webhook';
webhook?: {
url: string;
headers?: Record<string, string>;
timeoutMs?: number;
retryPolicy?: {
maxAttempts: number;
backoffMinutes: number;
};
};
initialPosition?: 'latest' | 'earliest';
}
interface InfrastructureConfig {
eventStores: EventStoreConfig[];
apiKey?: string;
apiUrl?: string;
}
export { type CreateEventStoreOptions, DeltaBase, type DeltaBaseConfig, EventBus, EventStore$1 as EventStore, type EventStoreConfig, type EventStoreDetailsResponse, type EventStore as EventStoreInfo, type EventStoreListResponse, HttpClient, type HttpClientConfig, type InfrastructureConfig, type ListSubscriptionsOptions, type ListSubscriptionsResponse, ManagementClient, type QueryEventsOptions, type QueryEventsResult, type QueryStreamsOptions, type QueryStreamsResult, type RetryPolicy, type StreamInfo, type SubscribeOptions, SubscriberType, type Subscription, type SubscriptionConfig, type SubscriptionEvent, SubscriptionStatus, type WebhookConfig };