@smartsamurai/krapi-sdk
Version:
KRAPI TypeScript SDK - Easy-to-use client SDK for connecting to self-hosted KRAPI servers (like Appwrite SDK)
340 lines (313 loc) • 9.9 kB
text/typescript
/**
* KRAPI TypeScript SDK
*
* A comprehensive, type-safe SDK for building KRAPI applications with perfect client/server parity.
*
* ## What is KRAPI?
*
* KRAPI is a self-hosted backend-as-a-service (BaaS) platform that provides:
* - Database management (projects, collections, documents)
* - User management and authentication
* - File storage
* - Email service
* - RESTful API access
*
* ## Main Interface (Recommended)
*
* The `krapi` singleton is the recommended way to use the SDK. It works seamlessly in both
* client and server environments with perfect API parity - the same code works everywhere!
*
* ### Client Mode (HTTP)
*
* Used by frontend applications, Next.js API routes, and external services.
* Makes HTTP requests to your KRAPI server.
*
* ```typescript
* import { krapi } from '@smartsamurai/krapi-sdk';
*
* // Connect to KRAPI server
* await krapi.connect({
* endpoint: 'http://localhost:3470', // Your KRAPI server URL
* apiKey: 'your-api-key' // Optional: For API key authentication
* });
*
* // Use the SDK - all methods make HTTP requests
* const projects = await krapi.projects.getAll();
* const project = await krapi.projects.create({ name: 'My Project' });
* ```
*
* ### Server Mode (Database)
*
* Used by backend services, Express routes, and internal services.
* Directly queries the database for maximum performance.
*
* ```typescript
* import { krapi } from '@smartsamurai/krapi-sdk';
* import { DatabaseConnection } from './your-database-setup';
*
* // Connect with direct database access
* await krapi.connect({
* database: databaseConnection, // Direct database connection
* logger: console // Optional: Custom logger
* });
*
* // Use the exact same methods - but queries database directly!
* const projects = await krapi.projects.getAll();
* const project = await krapi.projects.create({ name: 'My Project' });
* ```
*
* ## Perfect API Parity
*
* The same code works identically in both modes:
*
* ```typescript
* // This code works the same in client and server mode!
* const project = await krapi.projects.create({ name: 'My Project' });
* const collection = await krapi.collections.create(project.id, { name: 'tasks' });
* const document = await krapi.documents.create(project.id, 'tasks', { data: {...} });
* ```
*
* ## Authentication
*
* The SDK supports multiple authentication methods:
*
* ```typescript
* // API Key authentication
* await krapi.connect({ endpoint: '...', apiKey: 'your-api-key' });
*
* // Session token authentication
* const session = await krapi.auth.login('username', 'password');
* krapi.auth.setSessionToken(session.session_token);
*
* // Get current user
* const user = await krapi.auth.getCurrentUser();
* ```
*
* ## Error Handling
*
* The SDK provides detailed error information:
*
* ```typescript
* import { HttpError } from '@smartsamurai/krapi-sdk';
*
* try {
* const project = await krapi.projects.get('project-id');
* } catch (error) {
* if (error instanceof HttpError) {
* console.error('HTTP Status:', error.status);
* console.error('Error Message:', error.message);
* console.error('Request:', error.method, error.url);
* }
* }
* ```
*
* ## Alternative Interfaces
*
* - **KrapiClient**: Client-only SDK (from '@smartsamurai/krapi-sdk/client')
* - **Individual Services**: Import specific services for fine-grained control
*
* @module @smartsamurai/krapi-sdk
* @example Client Mode
* ```typescript
* import { krapi } from '@smartsamurai/krapi-sdk';
*
* await krapi.connect({
* endpoint: 'http://localhost:3470',
* apiKey: 'your-api-key'
* });
*
* const projects = await krapi.projects.getAll();
* const project = await krapi.projects.create({ name: 'My Project' });
* ```
*
* @example Server Mode
* ```typescript
* import { krapi } from '@smartsamurai/krapi-sdk';
*
* await krapi.connect({
* database: databaseConnection
* });
*
* const projects = await krapi.projects.getAll();
* const project = await krapi.projects.create({ name: 'My Project' });
* ```
*
* @example Authentication Flow
* ```typescript
* import { krapi } from '@smartsamurai/krapi-sdk';
*
* // Connect
* await krapi.connect({ endpoint: 'http://localhost:3470', apiKey: 'admin-key' });
*
* // Login
* const session = await krapi.auth.login('username', 'password');
*
* // Session token is automatically used for subsequent requests
* const user = await krapi.auth.getCurrentUser();
* const projects = await krapi.projects.getAll();
* ```
*/
// MAIN INTERFACE - PERFECT PLUG AND SOCKET DESIGN
export { krapi, KrapiWrapper } from "./krapi";
export type { KrapiConfig } from "./krapi";
export type { KrapiSocketInterface } from "./socket-interface";
// Export error classes for error handling
export { HttpError } from "./http-clients/http-error";
export { KrapiError, type ErrorCode } from "./core/krapi-error";
// Export core types and interfaces
export type {
DatabaseConnection,
Logger,
DatabaseSDKConfig,
HttpSDKConfig,
ApiResponse,
PaginatedResponse,
QueryOptions,
BaseClient,
SDKError,
Environment,
} from "./core";
export { FieldType } from "./core";
// LEGACY INTERFACES (for backward compatibility - DEPRECATED)
// Note: These are maintained for compatibility but krapi singleton is recommended
export { BackendSDK } from "./backend-sdk";
// Legacy unified client exports removed - use the new krapi singleton instead
// Note: FrontendSDK removed - use krapi singleton instead
// Export shared interfaces and types
export * from "./interfaces";
export * from "./types";
// Export key enums explicitly for better IDE support
export { AdminRole, AccessLevel, Scope, ProjectScope } from "./types";
// Export the main SDK class (krapi singleton is the default)
// Export all individual services (can be used directly)
export { AdminService } from "./admin-service";
export { AuthService } from "./auth-service";
export { ChangelogService } from "./changelog-service";
export { CollectionsSchemaManager } from "./collections-schema-manager";
export { CollectionsService } from "./collections-service";
export { CollectionsTypeManager } from "./collections-type-manager";
export { CollectionsTypeValidator } from "./collections-type-validator";
export { EmailService } from "./email-service";
export { HealthService } from "./health-service";
export { SQLiteSchemaInspector } from "./sqlite-schema-inspector";
export { ProjectsService } from "./projects-service";
export { StorageService } from "./storage-service";
export { SystemService } from "./system-service";
export { ActivityLogger } from "./activity-logger";
export { BackupService } from "./backup-service";
export { FileBackupBackend } from "./services/backup/file-backup-backend";
export type {
BackupBackend,
BackupSnapshot,
BackupStats,
} from "./services/backup/backup-backend.interface";
export { MetadataManager } from "./metadata-manager";
export { PerformanceMonitor } from "./performance-monitor";
export { UsersService } from "./users-service";
// Export unified client SDK (like Appwrite - easy to import!)
// Import with: import { KrapiClient } from '@smartsamurai/krapi-sdk/client'
// Or for convenience: import { KrapiClient } from '@smartsamurai/krapi-sdk'
export { KrapiClient, type KrapiClientConfig, type ApiResponse as ClientApiResponse } from "./client";
export { default as Client } from "./client";
// Also export from main entry point for convenience (can use '@smartsamurai/krapi-sdk' instead of '@smartsamurai/krapi-sdk/client')
// Export HTTP clients for granular frontend control
export { AuthHttpClient } from "./http-clients/auth-http-client";
export { ProjectsHttpClient } from "./http-clients/projects-http-client";
export { CollectionsHttpClient } from "./http-clients/collections-http-client";
export { BaseHttpClient } from "./http-clients/base-http-client";
// Export examples and utilities
export {
TaskManager as PlugSocketTaskManager,
clientExample,
serverExample,
sharedBusinessLogic,
demonstratePerfectFit,
} from "./plug-socket-example";
export {
SocketVerification,
runSocketVerification,
} from "./socket-verification";
export * from "./examples";
// Export service types
export type {
AdminUser,
ApiKey,
SystemStats,
DatabaseHealth,
DiagnosticResult,
} from "./admin-service";
export type {
ActivityLog,
ActivityQuery,
} from "./activity-logger";
export type {
CustomField,
CollectionMetadata,
MetadataQuery,
} from "./metadata-manager";
export type {
BackupMetadata,
BackupOptions,
RestoreOptions,
} from "./backup-service";
export type {
PerformanceMetric,
LoadTestResult,
QueryPerformance,
} from "./performance-monitor";
export type {
Session,
LoginRequest,
LoginResponse,
ApiKeyAuthRequest,
ApiKeyAuthResponse,
PasswordChangeRequest,
PasswordResetRequest,
} from "./auth-service";
export type {
DocumentFilter,
DocumentQueryOptions,
CreateDocumentRequest,
UpdateDocumentRequest,
} from "./collections-service";
export type {
EmailConfig,
EmailTemplate,
EmailRequest,
EmailResult,
} from "./email-service";
export type {
HealthDiagnostics,
DatabaseHealthStatus,
SystemHealthStatus,
ServiceHealthStatus,
} from "./health-service";
export type {
Project,
ProjectSettings,
ProjectStatistics,
ProjectApiKey,
CreateProjectRequest,
UpdateProjectRequest,
} from "./projects-service";
export type { ProjectStats, AdminPermission } from "./types";
export type {
StoredFile,
FileFolder,
FileVersion,
FilePermission,
UploadRequest,
FileFilter,
StorageStatistics,
StorageQuota,
} from "./storage-service";
export type {
ProjectUser,
UserRole,
UserSession,
UserActivity,
CreateUserRequest,
UpdateUserRequest,
UserFilter,
UserStatistics,
} from "./users-service";