@smartsamurai/krapi-sdk
Version:
KRAPI TypeScript SDK - Easy-to-use client SDK for connecting to self-hosted KRAPI servers (like Appwrite SDK)
1,461 lines (1,432 loc) • 262 kB
TypeScript
import { B as BaseHttpClient, A as ApiResponse, D as DatabaseConnection, L as Logger$1, P as Project$1, a as PaginatedResponse, b as DatabaseHealthStatus, c as AutoFixResult, S as SchemaValidationResult, M as MigrationResult, H as HealthHttpClient, d as HealthService, e as ApiResponse$1, f as SystemSettings$1, E as EmailConfig, g as SystemInfo, h as DatabaseHealth$1, i as AdminUser$1, j as ProjectUser$1, Q as QueryOptions, k as PaginatedResponse$1, l as ActivityLog$1, m as ApiKey$1, T as TestResult$1, n as ProjectStats, o as ProjectSettings$1, C as Collection, p as Document, F as FileInfo, q as StorageStats, r as EmailSendRequest, s as EmailTemplate, t as ChangelogEntry$1, u as CreateChangelogEntry, v as BackupMetadata$1, w as ModelCapabilities$1, x as ChatMessage$1, y as ChatResponse$1, z as Model$1, G as AdminHttpClient, I as EmailHttpClient, J as EmailService, K as SendEmailRequest, N as StorageHttpClient, O as StorageService, R as CollectionsHttpClient, U as CollectionsService, V as FieldType, W as FieldValidation, X as RelationConfig, Y as QueryOptions$1, Z as AuthHttpClient, _ as AuthService, $ as RetryConfig, a0 as CollectionTypeDefinition, a1 as CollectionTypeValidationResult, a2 as CollectionTypeAutoFixResult, a3 as CollectionTypeRegistry, a4 as ExpectedSchema, a5 as TableDefinition, a6 as DatabaseSDKConfig, a7 as Document$1, a8 as CreateDocumentRequest, a9 as FieldDefinition, aa as CollectionTypeIssue } from './client-C_QJhnar.js';
export { ag as AccessLevel, aD as AdminPermission, af as AdminRole, bo as AggregationRequest, bp as AggregationResponse, ao as ApiKeyAuthRequest, ap as ApiKeyAuthResponse, b4 as ApiKeyListOptions, b1 as ApiKeyScope, b2 as ApiKeyStatus, ac as BaseClient, bm as BulkDocumentRequest, bn as BulkDocumentResponse, bC as CacheHealth, aj as Client, aN as CollectionField, aO as CollectionIndex, bi as CollectionListOptions, bN as CollectionRouteHandler, bH as CollectionRouteParams, b8 as CollectionSchema, bd as CollectionSettings, bf as CollectionStats, bY as CollectionTypeAutoFixRule, bV as CollectionTypeConstraint, bT as CollectionTypeField, bZ as CollectionTypeFix, bU as CollectionTypeIndex, bW as CollectionTypeRelation, bS as CollectionTypeSchema, bX as CollectionTypeValidationRule, b$ as ConstraintDefinition, b3 as CreateApiKeyRequest, bg as CreateCollectionRequest, bu as CreateEmailTemplateRequest, b5 as CreateSessionRequest, aA as DatabaseHealthStatus, by as DatabaseIssue, bR as DeepPartial, as as DocumentFilter, bk as DocumentListOptions, at as DocumentQueryOptions, bO as DocumentRouteHandler, bI as DocumentRouteParams, bl as DocumentSearchRequest, bj as DocumentStatus, b_ as EmailAttachment, av as EmailConfig, bw as EmailListOptions, ax as EmailRequest, bv as EmailResponse, ay as EmailResult, aw as EmailTemplate, bt as EmailTemplateType, ae as Environment, bD as ExternalServiceHealth, bA as FieldMismatch, b9 as FieldOptions, aQ as FileAttachment, aJ as FileFilter, aF as FileFolder, bs as FileListOptions, bq as FileMetadata, aH as FilePermission, c2 as FileRecord, aP as FileRelation, bK as FileRouteParams, aG as FileVersion, aR as FilterCondition, az as HealthDiagnostics, bx as HealthStatus, bP as HttpConnection, ab as HttpSDKConfig, ba as IndexDefinition, aj as KrapiClient, ak as KrapiClientConfig, bQ as KrapiConnection, am as LoginRequest, an as LoginResponse, aS as PaginationOptions, aq as PasswordChangeRequest, ar as PasswordResetRequest, be as Permission, b7 as ProjectListOptions, aY as ProjectLoginRequest, bM as ProjectRouteHandler, bG as ProjectRouteParams, ai as ProjectScope, b6 as ProjectStatus, aX as RefreshResponse, c0 as RelationDefinition, bc as RelationshipDefinition, bF as RouteContext, bL as RouteHandler, bE as RouteParams, ad as SDKError, bz as SchemaMismatch, ah as Scope, aT as SearchOptions, aC as ServiceHealthStatus, al as Session, aV as SessionToken, c1 as SessionType, aW as SessionValidation, aU as SortOptions, bB as StorageHealth, aL as StorageQuota, aK as StorageStatistics, aE as StoredFile, aB as SystemHealthStatus, bh as UpdateCollectionRequest, au as UpdateDocumentRequest, br as UploadFileOptions, aI as UploadRequest, aZ as User, b0 as UserListOptions, a_ as UserProfile, bJ as UserRouteParams, a$ as UserStatus, bb as ValidationRule, ag as _AccessLevel, aD as _AdminPermission, af as _AdminRole, aN as _CollectionField, aO as _CollectionIndex, aQ as _FileAttachment, aP as _FileRelation, aR as _FilterCondition, ah as _Scope, aM as _Session } from './client-C_QJhnar.js';
import 'axios';
/**
* Testing HTTP Client for KRAPI SDK
*
* HTTP-based testing methods for frontend applications.
* Provides test project management, test execution, and data seeding.
*
* @module http-clients/testing-http-client
* @example
* const client = new TestingHttpClient({ baseUrl: 'https://api.example.com' });
* const testProject = await client.createTestProject({ name: 'test-project' });
*/
/**
* Testing HTTP Client
*
* HTTP client for testing operations.
*
* @class TestingHttpClient
* @extends {BaseHttpClient}
* @example
* const client = new TestingHttpClient({ baseUrl: 'https://api.example.com' });
* const results = await client.runTests();
*/
declare class TestingHttpClient extends BaseHttpClient {
createTestProject(options?: {
name?: string;
with_collections?: boolean;
with_documents?: boolean;
document_count?: number;
}): Promise<ApiResponse<Record<string, unknown>>>;
cleanup(projectId?: string): Promise<ApiResponse<{
success: boolean;
deleted: {
projects: number;
collections: number;
documents: number;
files: number;
users: number;
};
}>>;
runTests(testSuite?: string): Promise<ApiResponse<{
results: Array<{
suite: string;
tests: Array<{
name: string;
passed: boolean;
error?: string;
duration: number;
}>;
}>;
summary: {
total: number;
passed: number;
failed: number;
duration: number;
};
}>>;
seedData(projectId: string, seedType: string, options?: Record<string, unknown>): Promise<ApiResponse<{
success: boolean;
created: Record<string, number>;
}>>;
getTestProjects(): Promise<ApiResponse<Record<string, unknown>[]>>;
deleteTestProject(projectId: string): Promise<ApiResponse<{
success: boolean;
}>>;
resetTestData(projectId?: string): Promise<ApiResponse<{
success: boolean;
}>>;
runScenario(scenarioName: string, options?: Record<string, unknown>): Promise<ApiResponse<{
success: boolean;
results: Record<string, unknown>;
duration: number;
}>>;
getAvailableScenarios(): Promise<ApiResponse<string[]>>;
runPerformanceTest(testConfig: {
endpoint: string;
method: "GET" | "POST" | "PUT" | "DELETE";
iterations: number;
concurrent_users: number;
payload?: Record<string, unknown>;
}): Promise<ApiResponse<{
success: boolean;
results: {
total_requests: number;
successful_requests: number;
failed_requests: number;
average_response_time: number;
min_response_time: number;
max_response_time: number;
requests_per_second: number;
errors: Array<{
status: number;
message: string;
count: number;
}>;
};
duration: number;
}>>;
runLoadTest(testConfig: {
endpoint: string;
method: "GET" | "POST" | "PUT" | "DELETE";
duration_seconds: number;
users_per_second: number;
payload?: Record<string, unknown>;
}): Promise<ApiResponse<{
success: boolean;
results: {
total_requests: number;
successful_requests: number;
failed_requests: number;
average_response_time: number;
p95_response_time: number;
p99_response_time: number;
requests_per_second: number;
errors: Array<{
status: number;
message: string;
count: number;
}>;
};
duration: number;
}>>;
}
/**
* Testing Service for KRAPI SDK
*
* Provides testing utilities, health checks, and development helpers.
*/
interface TestResult {
name: string;
passed: boolean;
message: string;
duration: number;
details?: Record<string, unknown>;
}
interface TestSuite {
name: string;
tests: TestResult[];
totalPassed: number;
totalFailed: number;
duration: number;
success: boolean;
}
interface EndpointTestResult {
endpoint: string;
method: string;
status: number;
responseTime: number;
success: boolean;
error?: string;
}
/**
* Testing Service for KRAPI SDK
*
* Provides testing utilities, health checks, and development helpers.
*
* @class TestingService
* @example
* const testingService = new TestingService(dbConnection, logger);
* const testSuite = await testingService.runDatabaseTests();
*/
declare class TestingService {
private db;
private logger;
/**
* Create a new TestingService instance
*
* @param {DatabaseConnection} databaseConnection - Database connection
* @param {Logger} logger - Logger instance
*/
constructor(databaseConnection: DatabaseConnection, logger: Logger$1);
/**
* Run database tests
*
* Runs comprehensive database tests including connection, tables, performance, and data integrity.
*
* @returns {Promise<TestSuite>} Test suite results
*
* @example
* const testSuite = await testingService.runDatabaseTests();
* console.log(`Passed: ${testSuite.totalPassed}, Failed: ${testSuite.totalFailed}`);
*/
runDatabaseTests(): Promise<TestSuite>;
private testDatabaseConnection;
private testRequiredTables;
private testDatabasePerformance;
private testDataIntegrity;
testEndpoint(baseUrl: string, endpoint: string, method?: string, headers?: Record<string, string>, body?: unknown): Promise<EndpointTestResult>;
runFullTestSuite(): Promise<{
database: TestSuite;
summary: {
totalTests: number;
totalPassed: number;
totalFailed: number;
duration: number;
success: boolean;
};
}>;
generateTestData(projectId?: string): Promise<{
success: boolean;
created: {
collections: number;
documents: number;
users: number;
files: number;
};
}>;
cleanupTestData(projectId?: string): Promise<{
success: boolean;
deleted: number;
}>;
}
/**
* Testing Adapter
*
* Unifies TestingHttpClient and TestingService behind a common interface.
*/
type Mode$f = "client" | "server";
declare class TestingAdapter {
private mode;
private httpClient;
private service;
constructor(mode: Mode$f, httpClient?: TestingHttpClient, service?: TestingService);
createTestProject(options?: {
name?: string;
with_collections?: boolean;
with_documents?: boolean;
document_count?: number;
}): Promise<Project$1>;
cleanup(projectId?: string): Promise<{
success: boolean;
deleted: {
projects: number;
collections: number;
documents: number;
files: number;
users: number;
};
}>;
runTests(testSuite?: string): Promise<{
results: Array<{
suite: string;
tests: Array<{
name: string;
passed: boolean;
error?: string;
duration: number;
}>;
}>;
summary: {
total: number;
passed: number;
failed: number;
duration: number;
};
}>;
seedData(projectId: string, seedType: string, options?: Record<string, unknown>): Promise<{
success: boolean;
created: Record<string, number>;
}>;
}
interface ChangelogEntry {
id: string;
entity_type: string;
entity_id: string;
action: string;
changes: Record<string, unknown>;
user_id?: string;
timestamp: Date;
metadata?: Record<string, unknown>;
}
interface CreateChangelogEntryParams {
entity_type: string;
entity_id: string;
action: string;
changes: Record<string, unknown>;
user_id?: string;
metadata?: Record<string, unknown>;
}
interface ChangelogQueryOptions {
entity_type?: string;
entity_id?: string;
user_id?: string;
action?: string;
start_date?: Date;
end_date?: Date;
limit?: number;
offset?: number;
}
/**
* Service for managing changelog entries to track changes to entities
*
* @class ChangelogService
* @example
* const changelogService = new ChangelogService(dbConnection, logger);
* const entry = await changelogService.create({
* entity_type: 'project',
* entity_id: 'project-id',
* action: 'created',
* changes: { name: 'New Project' }
* });
*/
declare class ChangelogService {
private dbConnection;
private logger;
/**
* Create a new ChangelogService instance
*
* @param {DatabaseConnection} dbConnection - Database connection
* @param {Logger} logger - Logger instance
*/
constructor(dbConnection: DatabaseConnection, logger: Logger$1);
/**
* Create a new changelog entry
*
* @param {CreateChangelogEntryParams} params - Changelog entry parameters
* @param {string} params.entity_type - Entity type (e.g., 'project', 'collection')
* @param {string} params.entity_id - Entity ID
* @param {string} params.action - Action performed (e.g., 'created', 'updated', 'deleted')
* @param {Record<string, unknown>} params.changes - Changes made
* @param {string} [params.user_id] - User ID who performed the action
* @param {Record<string, unknown>} [params.metadata] - Additional metadata
* @returns {Promise<ChangelogEntry>} Created changelog entry
* @throws {Error} If creation fails
*
* @example
* const entry = await changelogService.create({
* entity_type: 'project',
* entity_id: 'project-id',
* action: 'updated',
* changes: { name: 'New Name' },
* user_id: 'user-id'
* });
*/
create(params: CreateChangelogEntryParams): Promise<ChangelogEntry>;
/**
* Get changelog entries by entity
*
* @param {string} entity_type - Entity type
* @param {string} entity_id - Entity ID
* @param {ChangelogQueryOptions} [options] - Query options
* @returns {Promise<ChangelogEntry[]>} Array of changelog entries
* @throws {Error} If query fails
*
* @example
* const entries = await changelogService.getByEntity('project', 'project-id', {
* limit: 10,
* action: 'created'
* });
*/
getByEntity(entity_type: string, entity_id: string, options?: ChangelogQueryOptions): Promise<ChangelogEntry[]>;
/**
* Get all changelog entries with filtering
*/
getAll(options?: ChangelogQueryOptions): Promise<ChangelogEntry[]>;
/**
* Delete changelog entries by entity
*/
deleteByEntity(entity_type: string, entity_id: string): Promise<number>;
/**
* Clear old changelog entries
*/
clearOldEntries(daysOld: number): Promise<number>;
}
/**
* Changelog HTTP Client for KRAPI SDK
*
* HTTP-based changelog methods for frontend applications.
* Provides changelog retrieval for projects, collections, and documents.
*
* @module http-clients/changelog-http-client
* @example
* const client = new ChangelogHttpClient({ baseUrl: 'https://api.example.com' });
* const changelog = await client.getProjectChangelog('project-id', { limit: 10 });
*/
/**
* Changelog HTTP Client
*
* HTTP client for changelog operations.
*
* @class ChangelogHttpClient
* @extends {BaseHttpClient}
* @example
* const client = new ChangelogHttpClient({ baseUrl: 'https://api.example.com' });
* const changelog = await client.getProjectChangelog('project-id');
*/
declare class ChangelogHttpClient extends BaseHttpClient {
getProjectChangelog(projectId: string, options?: {
limit?: number;
offset?: number;
action_type?: string;
user_id?: string;
start_date?: string;
end_date?: string;
collection_name?: string;
document_id?: string;
}): Promise<PaginatedResponse<{
id: string;
project_id: string;
user_id: string;
username: string;
action: string;
action_type: string;
entity_type: string;
entity_id: string;
entity_name: string;
old_values?: Record<string, unknown>;
new_values?: Record<string, unknown>;
metadata?: Record<string, unknown>;
ip_address?: string;
user_agent?: string;
created_at: string;
}>>;
getCollectionChangelog(projectId: string, collectionName: string, options?: {
limit?: number;
offset?: number;
action_type?: string;
user_id?: string;
start_date?: string;
end_date?: string;
document_id?: string;
}): Promise<PaginatedResponse<{
id: string;
project_id: string;
collection_name: string;
user_id: string;
username: string;
action: string;
action_type: string;
entity_type: string;
entity_id: string;
entity_name: string;
old_values?: Record<string, unknown>;
new_values?: Record<string, unknown>;
metadata?: Record<string, unknown>;
ip_address?: string;
user_agent?: string;
created_at: string;
}>>;
getDocumentChangelog(projectId: string, collectionName: string, documentId: string, options?: {
limit?: number;
offset?: number;
action_type?: string;
user_id?: string;
start_date?: string;
end_date?: string;
}): Promise<PaginatedResponse<{
id: string;
project_id: string;
collection_name: string;
document_id: string;
user_id: string;
username: string;
action: string;
action_type: string;
field_changes: Array<{
field_name: string;
old_value: unknown;
new_value: unknown;
}>;
metadata?: Record<string, unknown>;
ip_address?: string;
user_agent?: string;
created_at: string;
}>>;
getUserActivity(projectId: string, userId: string, options?: {
limit?: number;
offset?: number;
action_type?: string;
start_date?: string;
end_date?: string;
entity_type?: string;
}): Promise<PaginatedResponse<{
id: string;
project_id: string;
user_id: string;
username: string;
action: string;
action_type: string;
entity_type: string;
entity_id: string;
entity_name: string;
old_values?: Record<string, unknown>;
new_values?: Record<string, unknown>;
metadata?: Record<string, unknown>;
ip_address?: string;
user_agent?: string;
created_at: string;
}>>;
getSystemChangelog(options?: {
limit?: number;
offset?: number;
action_type?: string;
user_id?: string;
project_id?: string;
entity_type?: string;
start_date?: string;
end_date?: string;
}): Promise<PaginatedResponse<{
id: string;
project_id?: string;
user_id: string;
username: string;
action: string;
action_type: string;
entity_type: string;
entity_id: string;
entity_name: string;
old_values?: Record<string, unknown>;
new_values?: Record<string, unknown>;
metadata?: Record<string, unknown>;
ip_address?: string;
user_agent?: string;
created_at: string;
}>>;
getChangelogStatistics(projectId: string, options?: {
period: "hour" | "day" | "week" | "month";
start_date?: string;
end_date?: string;
group_by?: "action_type" | "entity_type" | "user_id";
}): Promise<ApiResponse<{
period: string;
start_date: string;
end_date: string;
total_entries: number;
entries_by_action_type: Record<string, number>;
entries_by_entity_type: Record<string, number>;
entries_by_user: Record<string, number>;
daily_activity: Array<{
date: string;
count: number;
action_types: Record<string, number>;
}>;
}>>;
exportChangelog(projectId: string, options?: {
format: "json" | "csv" | "xml";
start_date?: string;
end_date?: string;
action_type?: string;
user_id?: string;
entity_type?: string;
}): Promise<ApiResponse<{
success: boolean;
download_url: string;
expires_at: string;
file_size: number;
}>>;
purgeOldChangelog(options?: {
older_than_days: number;
project_id?: string;
action_type?: string;
entity_type?: string;
}): Promise<ApiResponse<{
success: boolean;
message: string;
purged_count: number;
freed_space: number;
}>>;
}
/**
* Changelog Adapter
*
* Unifies ChangelogHttpClient and ChangelogService behind a common interface.
*/
type Mode$e = "client" | "server";
declare class ChangelogAdapter {
private mode;
private httpClient;
private service;
constructor(mode: Mode$e, httpClient?: ChangelogHttpClient, service?: ChangelogService);
getProjectChangelog(projectId: string, options?: {
limit?: number;
offset?: number;
action_type?: string;
user_id?: string;
start_date?: string;
end_date?: string;
collection_name?: string;
document_id?: string;
}): Promise<unknown[]>;
getCollectionChangelog(projectId: string, collectionName: string, options?: {
limit?: number;
offset?: number;
action_type?: string;
user_id?: string;
start_date?: string;
end_date?: string;
document_id?: string;
}): Promise<unknown[]>;
getDocumentChangelog(projectId: string, collectionName: string, documentId: string, options?: {
limit?: number;
offset?: number;
action_type?: string;
user_id?: string;
start_date?: string;
end_date?: string;
}): Promise<unknown[]>;
getUserActivity(projectId: string, userId: string, options?: {
limit?: number;
offset?: number;
action_type?: string;
start_date?: string;
end_date?: string;
entity_type?: string;
}): Promise<unknown[]>;
getSystemChangelog(options?: {
limit?: number;
offset?: number;
action_type?: string;
user_id?: string;
project_id?: string;
entity_type?: string;
start_date?: string;
end_date?: string;
}): Promise<unknown[]>;
}
/**
* Activity Log Interface
*
* @interface ActivityLog
* @property {string} id - Log entry ID
* @property {string} [user_id] - User ID who performed the action
* @property {string} [project_id] - Project ID
* @property {string} action - Action performed
* @property {string} resource_type - Type of resource affected
* @property {string} [resource_id] - Resource ID
* @property {Record<string, unknown>} details - Action details
* @property {string} [ip_address] - IP address
* @property {string} [user_agent] - User agent
* @property {Date} timestamp - Action timestamp
* @property {"info" | "warning" | "error" | "critical"} severity - Log severity
* @property {Record<string, unknown>} [metadata] - Additional metadata
*/
interface ActivityLog {
id: string;
user_id?: string;
project_id?: string;
action: string;
resource_type: string;
resource_id?: string;
details: Record<string, unknown>;
ip_address?: string;
user_agent?: string;
timestamp: Date;
severity: "info" | "warning" | "error" | "critical";
metadata?: Record<string, unknown>;
}
/**
* Activity Query Interface
*
* @interface ActivityQuery
* @property {string} [user_id] - Filter by user ID
* @property {string} [project_id] - Filter by project ID
* @property {string} [action] - Filter by action
* @property {string} [resource_type] - Filter by resource type
* @property {string} [resource_id] - Filter by resource ID
* @property {string} [severity] - Filter by severity
* @property {Date} [start_date] - Start date filter
* @property {Date} [end_date] - End date filter
* @property {number} [limit] - Maximum number of results
* @property {number} [offset] - Number of results to skip
*/
interface ActivityQuery {
user_id?: string;
project_id?: string;
action?: string;
resource_type?: string;
resource_id?: string;
severity?: string;
start_date?: Date;
end_date?: Date;
limit?: number;
offset?: number;
}
/**
* Activity Logger Class
*
* Manages activity logging with database persistence.
* Provides methods for logging activities and querying activity logs.
*
* @class ActivityLogger
* @example
* const logger = new ActivityLogger(dbConnection, console);
* await logger.log({
* user_id: 'user-id',
* action: 'created',
* resource_type: 'document',
* details: {}
* });
*/
declare class ActivityLogger {
private dbConnection;
private logger;
private initialized;
constructor(dbConnection: {
query: (sql: string, params?: unknown[]) => Promise<{
rows?: unknown[];
}>;
}, logger?: Logger$1);
/**
* Initialize the activity_logs table
*/
private initializeActivityTable;
/**
* Ensure table is initialized before any operation
* Uses a timeout to prevent hanging
*/
private ensureInitialized;
/**
* Log an activity
*/
log(activity: Omit<ActivityLog, "id" | "timestamp" | "created_at">): Promise<ActivityLog>;
/**
* Query activity logs
*/
query(query: ActivityQuery): Promise<{
logs: ActivityLog[];
total: number;
}>;
/**
* Get recent activity for a user or project
*/
getRecentActivity(userId?: string, projectId?: string, limit?: number): Promise<ActivityLog[]>;
/**
* Get activity statistics
*/
getActivityStats(projectId?: string, days?: number): Promise<{
total_actions: number;
actions_by_type: Record<string, number>;
actions_by_severity: Record<string, number>;
actions_by_user: Record<string, number>;
}>;
/**
* Clean old activity logs
*/
cleanOldLogs(daysToKeep?: number): Promise<number>;
/**
* Cleanup old activity logs (alias for cleanOldLogs with different return format)
*
* @param daysToKeep - Number of days to keep (default: 90)
* @returns Cleanup result with success status and deleted count
*/
cleanup(daysToKeep?: number): Promise<{
success: boolean;
deleted_count: number;
}>;
}
/**
* Activity HTTP Client for KRAPI SDK
*
* HTTP-based activity logging for frontend applications.
* Provides activity logging, querying, and statistics.
*
* @module http-clients/activity-http-client
* @example
* const client = new ActivityHttpClient({ baseUrl: 'https://api.example.com' });
* await client.log({ action: 'created', resource_type: 'document' });
*/
/**
* Activity HTTP Client
*
* HTTP client for activity logging operations.
*
* @class ActivityHttpClient
* @extends {BaseHttpClient}
*/
declare class ActivityHttpClient extends BaseHttpClient {
/**
* Log an activity event
*
* @param {Omit<ActivityLog, "id" | "timestamp">} activityData - Activity data
* @returns {Promise<ApiResponse<ActivityLog>>} Created activity log
*/
log(activityData: Omit<ActivityLog, "id" | "timestamp">): Promise<ApiResponse<ActivityLog>>;
/**
* Query activity logs
*
* @param {ActivityQuery} query - Query parameters
* @returns {Promise<PaginatedResponse<ActivityLog>>} Activity logs with pagination
*/
query(query: ActivityQuery): Promise<ApiResponse<PaginatedResponse<ActivityLog>>>;
/**
* Get activity statistics
*
* @param {string} [projectId] - Optional project ID
* @param {number} [days=30] - Number of days to analyze
* @returns {Promise<ApiResponse<{ total_actions: number; actions_by_type: Record<string, number>; actions_by_severity: Record<string, number>; actions_by_user: Record<string, number> }>>} Activity statistics
*/
getStats(projectId?: string, days?: number): Promise<ApiResponse<{
total_actions: number;
actions_by_type: Record<string, number>;
actions_by_severity: Record<string, number>;
actions_by_user: Record<string, number>;
}>>;
/**
* Get recent activity
*
* @param {string} [userId] - Optional user ID
* @param {string} [projectId] - Optional project ID
* @param {number} [limit=50] - Maximum number of results
* @returns {Promise<ApiResponse<ActivityLog[]>>} Recent activity logs
*/
getRecent(userId?: string, projectId?: string, limit?: number): Promise<ApiResponse<ActivityLog[]>>;
/**
* Get user timeline
*
* @param {string} userId - User ID
* @param {Object} [options] - Query options
* @param {number} [options.limit] - Maximum number of results
* @param {number} [options.offset] - Number of results to skip
* @param {Date} [options.start_date] - Start date filter
* @param {Date} [options.end_date] - End date filter
* @returns {Promise<PaginatedResponse<ActivityLog>>} User activity timeline
*/
getUserTimeline(userId: string, options?: {
limit?: number;
offset?: number;
start_date?: Date;
end_date?: Date;
}): Promise<ApiResponse<PaginatedResponse<ActivityLog>>>;
/**
* Cleanup old activity logs
*
* @param {number} [daysToKeep=90] - Number of days to keep
* @returns {Promise<ApiResponse<{ success: boolean; deleted_count: number }>>} Cleanup result
*/
cleanup(daysToKeep?: number): Promise<ApiResponse<{
success: boolean;
deleted_count: number;
}>>;
}
/**
* Activity Adapter
*
* Unifies ActivityHttpClient and ActivityLogger behind a common interface.
*/
type Mode$d = "client" | "server";
declare class ActivityAdapter {
private mode;
private httpClient;
private logger;
constructor(mode: Mode$d, httpClient?: ActivityHttpClient, logger?: ActivityLogger);
log(activityData: Omit<ActivityLog, "id" | "timestamp">): Promise<ActivityLog>;
query(query: {
user_id?: string;
project_id?: string;
action?: string;
resource_type?: string;
resource_id?: string;
severity?: string;
start_date?: Date;
end_date?: Date;
limit?: number;
offset?: number;
}): Promise<ActivityLog[]>;
getStats(projectId?: string, days?: number): Promise<{
total_actions: number;
actions_by_type: Record<string, number>;
actions_by_severity: Record<string, number>;
actions_by_user: Record<string, number>;
}>;
getRecent(projectId?: string, limit?: number): Promise<ActivityLog[]>;
cleanup(daysToKeep?: number): Promise<{
success: boolean;
deleted_count: number;
}>;
}
/**
* MCP Service for BackendSDK
*
* Provides Model Context Protocol (MCP) functionality for AI model interactions.
* Supports chat operations, model capabilities, and model management.
*
* @module mcp-service
*/
interface ChatMessage {
role: "user" | "assistant" | "system";
content: string;
timestamp?: string;
}
interface ChatResponse {
message: string;
model: string;
usage?: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
finish_reason?: string;
}
interface ModelCapabilities {
models: string[];
features: string[];
max_tokens: number;
supports_streaming: boolean;
supports_functions: boolean;
}
interface Model {
id: string;
name: string;
provider: string;
capabilities: string[];
max_tokens: number;
is_available: boolean;
}
/**
* MCP Service for BackendSDK
*
* Provides MCP functionality for AI model interactions.
*
* @class MCPService
* @example
* const mcpService = new MCPService(dbConnection, logger);
* const response = await mcpService.chat('project-id', [{ role: 'user', content: 'Hello' }]);
*/
declare class MCPService {
private _dbConnection;
private logger;
constructor(_dbConnection: DatabaseConnection, logger?: Logger$1);
/**
* Get model capabilities
*
* @returns {Promise<ModelCapabilities>} Model capabilities
*/
getModelCapabilities(): Promise<ModelCapabilities>;
/**
* Send chat messages to MCP model
*
* @param {string} projectId - Project ID
* @param {ChatMessage[]} messages - Chat messages
* @returns {Promise<ChatResponse>} Chat response
*/
chat(projectId: string, messages: ChatMessage[]): Promise<ChatResponse>;
/**
* Send chat messages to MCP model (admin context)
*
* @param {ChatMessage[]} messages - Chat messages
* @returns {Promise<ChatResponse>} Chat response
*/
adminChat(messages: ChatMessage[]): Promise<ChatResponse>;
/**
* List available MCP models
*
* @returns {Promise<Model[]>} List of available models
*/
listModels(): Promise<Model[]>;
}
/**
* MCP HTTP Client for KRAPI SDK
*
* HTTP-based MCP operations for frontend applications.
* Provides MCP chat, model capabilities, and model management.
*
* @module http-clients/mcp-http-client
* @example
* const client = new MCPHttpClient({ baseUrl: 'https://api.example.com' });
* const capabilities = await client.getModelCapabilities();
*/
/**
* MCP HTTP Client
*
* HTTP client for MCP operations.
*
* @class MCPHttpClient
* @extends {BaseHttpClient}
*/
declare class MCPHttpClient extends BaseHttpClient {
/**
* Get model capabilities
*
* @returns {Promise<ApiResponse<ModelCapabilities>>} Model capabilities
*/
getModelCapabilities(): Promise<ApiResponse<ModelCapabilities>>;
/**
* Send chat messages to MCP model
*
* @param {string} projectId - Project ID
* @param {ChatMessage[]} messages - Chat messages
* @returns {Promise<ApiResponse<ChatResponse>>} Chat response
*/
chat(projectId: string, messages: ChatMessage[]): Promise<ApiResponse<ChatResponse>>;
/**
* Send chat messages to MCP model (admin context)
*
* @param {ChatMessage[]} messages - Chat messages
* @returns {Promise<ApiResponse<ChatResponse>>} Chat response
*/
adminChat(messages: ChatMessage[]): Promise<ApiResponse<ChatResponse>>;
/**
* List available MCP models
*
* @returns {Promise<ApiResponse<Model[]>>} List of available models
*/
listModels(): Promise<ApiResponse<Model[]>>;
}
/**
* MCP Adapter
*
* Unifies MCPHttpClient and MCPService behind a common interface.
*/
type Mode$c = "client" | "server";
declare class MCPAdapter {
private mode;
private httpClient;
private service;
constructor(mode: Mode$c, httpClient?: MCPHttpClient, service?: MCPService);
chat(projectId: string, messages: ChatMessage[]): Promise<ChatResponse>;
adminChat(messages: ChatMessage[]): Promise<ChatResponse>;
getModelCapabilities(): Promise<ModelCapabilities>;
listModels(): Promise<Model[]>;
}
/**
* Backup Backend Interface
*
* Defines the interface for backup backend implementations.
* This allows the SDK to work with different backup backends (file-based, Restic, etc.)
*
* @module services/backup/backup-backend.interface
*/
/**
* Backup snapshot information
*/
interface BackupSnapshot {
/** Short snapshot ID */
id: string;
/** Full snapshot ID (e.g., Restic snapshot ID) */
snapshot_id: string;
/** Backup type */
type: "project" | "system";
/** Project ID (for project backups) */
project_id?: string;
/** ISO timestamp */
created_at: string;
/** Total size in bytes */
size: number;
/** Unique data size after deduplication */
unique_size?: number;
/** Whether backup is encrypted */
encrypted: boolean;
/** Backup version */
version: string;
/** Backup description */
description?: string;
/** Backup tags */
tags?: string[];
/** Number of files in backup */
file_count?: number;
}
/**
* Backup statistics
*/
interface BackupStats {
/** Total size in bytes */
total_size: number;
/** Unique data size after deduplication */
unique_size: number;
/** Number of files */
file_count: number;
/** Compression ratio (if applicable) */
compression_ratio?: number;
}
/**
* Backup Backend Interface
*
* Implementations of this interface handle the actual backup storage and retrieval.
* The SDK's BackupService uses this interface to perform backup operations.
*/
interface BackupBackend {
/**
* Initialize backup repository
*
* @param password - Repository password
* @returns Promise that resolves when repository is initialized
*/
initializeRepository(password: string): Promise<void>;
/**
* Create system backup (all databases + files)
*
* @param options - Backup options
* @param options.description - Backup description
* @param options.password - Backup password
* @param options.tags - Backup tags
* @returns Promise resolving to backup snapshot
*/
createSystemBackup(options: {
description?: string;
password: string;
tags?: string[];
}): Promise<BackupSnapshot>;
/**
* Create project backup
*
* @param projectId - Project ID
* @param options - Backup options
* @param options.description - Backup description
* @param options.password - Backup password
* @param options.includeFiles - Whether to include files
* @param options.tags - Backup tags
* @returns Promise resolving to backup snapshot
*/
createProjectBackup(projectId: string, options: {
description?: string;
password: string;
includeFiles?: boolean;
tags?: string[];
}): Promise<BackupSnapshot>;
/**
* List backups
*
* @param password - Repository password
* @param options - List options
* @param options.projectId - Filter by project ID
* @param options.type - Filter by backup type
* @param options.limit - Maximum number of backups to return
* @returns Promise resolving to array of backup snapshots
*/
listBackups(password: string, options?: {
projectId?: string;
type?: "project" | "system";
limit?: number;
}): Promise<BackupSnapshot[]>;
/**
* Restore backup
*
* @param snapshotId - Snapshot ID to restore
* @param password - Repository password
* @param targetPath - Target path for restoration
* @param options - Restore options
* @param options.include - Paths to include (if applicable)
* @param options.exclude - Paths to exclude (if applicable)
* @returns Promise that resolves when restoration is complete
*/
restoreBackup(snapshotId: string, password: string, targetPath: string, options?: {
include?: string[];
exclude?: string[];
}): Promise<void>;
/**
* Delete backup
*
* @param snapshotId - Snapshot ID to delete
* @param password - Repository password
* @returns Promise that resolves when backup is deleted
*/
deleteBackup(snapshotId: string, password: string): Promise<void>;
/**
* Get backup statistics
*
* @param snapshotId - Snapshot ID
* @param password - Repository password
* @returns Promise resolving to backup statistics
*/
getBackupStats(snapshotId: string, password: string): Promise<BackupStats>;
}
/**
* Backup Service for BackendSDK
*
* Provides encrypted backup and restore functionality for KRAPI projects.
* Supports:
* - Individual project backups (encrypted)
* - System-wide backups (encrypted)
* - Backup versioning
* - Secure backup storage
*
* Uses a BackupBackend abstraction to support different backup storage implementations
* (file-based, Restic, etc.)
*/
interface BackupMetadata {
id: string;
project_id?: string;
type: "project" | "system";
created_at: string;
size: number;
encrypted: boolean;
version: string;
description?: string;
/** Restic snapshot ID (for Restic backend) */
snapshot_id?: string;
/** Unique data size after deduplication */
unique_size?: number;
/** Number of files in backup */
file_count?: number;
/** Backup tags */
tags?: string[];
}
interface BackupOptions {
projectId?: string;
description?: string;
password?: string;
includeFiles?: boolean;
compressionLevel?: number;
}
interface RestoreOptions {
password?: string;
overwrite?: boolean;
targetPath?: string;
targetProjectId?: string;
}
/**
* Backup Service for KRAPI
*
* Provides encrypted backup and restore functionality.
* Supports project backups and system-wide backups with encryption.
*
* @class BackupService
* @example
* const backupService = new BackupService(dbConnection, logger);
* const backup = await backupService.backupProject({ projectId: 'project-id', password: 'encryption-password' });
*/
declare class BackupService {
private dbConnection;
private logger;
private backend;
private dataPath;
/**
* Create a new BackupService instance
*
* @param dbConnection - Database connection
* @param logger - Logger instance
* @param backupBackend - Optional backup backend (defaults to FileBackupBackend)
* @param backupsDir - Backup directory path (for FileBackupBackend, default: data/backups)
* @param dataPath - Data directory path (default: data)
*/
constructor(dbConnection: DatabaseConnection, logger?: Logger$1, backupBackend?: BackupBackend, backupsDir?: string, dataPath?: string);
/**
* Convert BackupSnapshot to BackupMetadata
*/
private snapshotToMetadata;
/**
* Save backup metadata to database
*/
private saveBackupMetadata;
/**
* Get backup metadata from database
*/
private getBackupMetadata;
/**
* Delete backup metadata from database
*/
private deleteBackupMetadata;
/**
* Create encrypted backup of a project
*
* Creates an encrypted backup of a project's database and optionally files.
*
* @param options - Backup options
* @param options.projectId - Project ID (required)
* @param options.description - Backup description
* @param options.password - Encryption password (generated if not provided)
* @param options.includeFiles - Whether to include files in backup
* @returns Backup metadata with password
* @throws {Error} If project not found or backup fails
*
* @example
* const backup = await backupService.backupProject({
* projectId: 'project-id',
* description: 'Monthly backup',
* password: 'secure-password'
* });
*/
backupProject(options: BackupOptions): Promise<BackupMetadata & {
password: string;
}>;
/**
* Create system-wide backup (all projects + main database)
*
* @param options - Backup options
* @param options.description - Backup description
* @param options.password - Encryption password (generated if not provided)
* @returns Backup metadata with password
*/
backupSystem(options?: BackupOptions): Promise<BackupMetadata & {
password: string;
}>;
/**
* Restore project from encrypted backup
*
* @param backupId - Backup ID to restore
* @param options - Restore options
* @param options.password - Password required to restore encrypted backup
* @param options.overwrite - Whether to overwrite existing project
* @param options.targetPath - Target path for restoration (optional)
* @param options.targetProjectId - Target project ID (optional)
*/
restoreProject(backupId: string, options?: RestoreOptions): Promise<void>;
/**
* List all backups
*
* @param projectId - Optional project ID filter
* @param type - Optional backup type filter
* @returns Array of backup metadata
*/
listBackups(projectId?: string, type?: "project" | "system"): Promise<BackupMetadata[]>;
/**
* Get backup details
*
* @param backupId - Backup ID
* @param password - Backup password (optional, for stats)
* @returns Backup metadata
*/
getBackup(backupId: string, password?: string): Promise<BackupMetadata>;
/**
* Delete backup
*
* @param backupId - Backup ID to delete
* @param password - Backup password (required for some backends)
*/
deleteBackup(backupId: string, password?: string): Promise<void>;
/**
* Generate random password
*/
private generatePassword;
}
/**
* Backup HTTP Client for KRAPI SDK
*
* HTTP-based backup operations for frontend applications.
* Provides backup creation, listing, restoration, and deletion.
*
* @module http-clients/backup-http-client
* @example
* const client = new BackupHttpClient({ baseUrl: 'https://api.example.com' });
* const backup = await client.createProjectBackup('project-id', { password: 'encryption-key' });
*/
/**
* Backup HTTP Client
*
* HTTP client for backup operations.
*
* @class BackupHttpClient
* @extends {BaseHttpClient}
*/
declare class BackupHttpClient extends BaseHttpClient {
/**
* Create a project backup
*
* @param {string} projectId - Project ID
* @param {Object} [options] - Backup options
* @param {string} [options.description] - Backup description
* @param {string} [options.password] - Encryption password
* @returns {Promise<ApiResponse<BackupMetadata & { password: string }>>} Backup metadata with password
*/
createProjectBackup(projectId: string, options?: {
description?: string;
password?: string;
includeFiles?: boolean;
}): Promise<ApiResponse<BackupMetadata & {
password: string;
}>>;
/**
* Create a system backup
*
* @param {Object} [options] - Backup options
* @param {string} [options.description] - Backup description
* @param {string} [options.password] - Encryption password
* @returns {Promise<ApiResponse<BackupMetadata & { password: string }>>} Backup metadata with password
*/
createSystemBackup(options?: {
description?: string;
password?: string;
}): Promise<ApiResponse<BackupMetadata & {
password: string;
}>>;
/**
* List backups
*
* @param {Object} [options] - Query options
* @param {string} [options.type] - Backup type ('project' | 'system')
* @param {string} [options.projectId] - Project ID (for project backups)
* @param {number} [options.limit] - Maximum number of results
* @param {number} [options.offset] - Number of results to skip
* @returns {Promise<PaginatedResponse<BackupMetadata>>} List of backups
*/
list(options?: {
type?: "project" | "system";
projectId?: string;
limit?: number;
offset?: number;
}): Promise<PaginatedResponse<BackupMetadata>>;
/**
* Get backup details
*
* @param {string} backupId - Backup ID
* @returns {Promise<ApiResponse<BackupMetadata>>} Backup metadata
*/
getBackup(backupId: string): Promise<ApiResponse<BackupMetadata>>;
/**
* Delete a backup
*
* @param {string} backupId - Backup ID
* @returns {Promise<ApiResponse<{ success: boolean }>>} Delete result
*/
deleteBackup(backupId: string): Promise<ApiResponse<{
success: boolean;
}>>;
/**
* Restore from backup
*
* @param {string} backupId - Backup ID
* @param {Object} [options] - Restore options
* @param {string} [options.password] - Backup encryption password
* @param {string} [options.targetProjectId] - Target project ID (for project backups)
* @param {boolean} [options.overwrite] - Whether to overwrite existing data
* @returns {Promise<ApiResponse<{ success: boolean; message?: string }>>} Restore result
*/
restore(backupId: string, options?: {
password?: string;
targetProjectId?: string;
overwrite?: boolean;
}): Promise<ApiResponse<{
success: boolean;
message?: string;
}>>;
}
/**
* Backup Adapter
*
* Unifies BackupHttpClient and BackupService behind a common interface.
*/
type Mode$b = "client" | "server";
declare class BackupAdapter {
private mode;
private httpClient;
private service;
constructor(mode: Mode$b, httpClient?: BackupHttpClient, service?: BackupService);
createProject(projectId: string, options?: {
description?: string;
password?: string;
includeFiles?: boolean;
}): Promise<BackupMetadata>;
restorePr