@tamyla/clodo-framework 4.3.2 → 4.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,526 @@
1
+ # API Reference
2
+
3
+ ## 📚 Core Classes and Functions
4
+
5
+ ### **Configuration System**
6
+
7
+ #### **FeatureFlagManager**
8
+ ```javascript
9
+ import { FeatureFlagManager } from '@tamyla/clodo-framework';
10
+
11
+ const featureManager = new FeatureFlagManager();
12
+ ```
13
+
14
+ **Methods:**
15
+ ```javascript
16
+ // Set domain context for feature resolution
17
+ setDomain(domainConfig: DomainConfig): void
18
+
19
+ // Check if a feature is enabled
20
+ isEnabled(featureName: string, defaultValue?: boolean): boolean
21
+
22
+ // Get all enabled features
23
+ getEnabledFeatures(): string[]
24
+
25
+ // Get all disabled features
26
+ getDisabledFeatures(): string[]
27
+
28
+ // Get all configured features with status
29
+ getAllFeatures(): Record<string, boolean>
30
+
31
+ // Set global feature override (for testing)
32
+ setGlobalOverride(featureName: string, enabled: boolean): void
33
+
34
+ // Remove global override
35
+ removeGlobalOverride(featureName: string): void
36
+
37
+ // Clear all global overrides
38
+ clearGlobalOverrides(): void
39
+
40
+ // Get detailed feature information
41
+ getFeatureInfo(featureName: string): FeatureInfo
42
+
43
+ // Create conditional handler based on feature
44
+ createToggle(featureName: string, enabledFn: Function, disabledFn?: Function): Function
45
+
46
+ // Add/remove event listeners
47
+ addListener(callback: Function): void
48
+ removeListener(callback: Function): void
49
+ ```
50
+
51
+ **Types:**
52
+ ```typescript
53
+ interface FeatureInfo {
54
+ name: string;
55
+ domainEnabled: boolean | null;
56
+ globalOverride: boolean | undefined;
57
+ effectiveEnabled: boolean;
58
+ hasOverride: boolean;
59
+ domain: string;
60
+ }
61
+ ```
62
+
63
+ #### **Domain Configuration Functions**
64
+ ```javascript
65
+ import {
66
+ createDomainConfigSchema,
67
+ validateDomainConfig,
68
+ mergeDomainConfigs,
69
+ createDomainRegistry,
70
+ getDomainFromEnv,
71
+ createEnvironmentConfig
72
+ } from '@tamyla/clodo-framework';
73
+ ```
74
+
75
+ **Functions:**
76
+ ```javascript
77
+ // Create base domain configuration template
78
+ createDomainConfigSchema(): DomainConfig
79
+
80
+ // Validate domain configuration
81
+ validateDomainConfig(config: DomainConfig): void // throws on invalid
82
+
83
+ // Merge base and service-specific configs
84
+ mergeDomainConfigs(baseConfig: DomainConfig, serviceConfig: DomainConfig): DomainConfig
85
+
86
+ // Create domain registry with lookup methods
87
+ createDomainRegistry(domainConfigs: Record<string, DomainConfig>): DomainRegistry
88
+
89
+ // Get domain config from environment variables
90
+ getDomainFromEnv(env: WorkerEnv, domainConfigs: Record<string, DomainConfig>): DomainConfig
91
+
92
+ // Create environment-specific configuration
93
+ createEnvironmentConfig(baseConfig: DomainConfig, environment?: string): DomainConfig
94
+ ```
95
+
96
+ **Types:**
97
+ ```typescript
98
+ interface DomainConfig {
99
+ name: string;
100
+ displayName: string;
101
+ accountId: string;
102
+ zoneId: string;
103
+ domains: {
104
+ production: string;
105
+ staging: string;
106
+ development: string;
107
+ };
108
+ services: Record<string, any>;
109
+ databases: Record<string, any>;
110
+ features: Record<string, boolean>;
111
+ settings: {
112
+ environment: string;
113
+ logLevel: string;
114
+ corsOrigins: string[];
115
+ };
116
+ }
117
+
118
+ interface DomainRegistry {
119
+ get(domainName: string): DomainConfig;
120
+ list(): string[];
121
+ validateAll(): void;
122
+ add(domainName: string, config: DomainConfig): void;
123
+ remove(domainName: string): void;
124
+ }
125
+ ```
126
+
127
+ ### **Data Services**
128
+
129
+ #### **GenericDataService**
130
+ ```javascript
131
+ import { GenericDataService } from '@tamyla/clodo-framework';
132
+
133
+ const userService = new GenericDataService(d1Client, 'users');
134
+ ```
135
+
136
+ **Constructor:**
137
+ ```javascript
138
+ new GenericDataService(d1Client: D1Database, modelName: string)
139
+ ```
140
+
141
+ **CRUD Methods:**
142
+ ```javascript
143
+ // Create new record
144
+ async create(data: Record<string, any>): Promise<Record<string, any>>
145
+
146
+ // Find record by ID
147
+ async findById(id: string): Promise<Record<string, any> | null>
148
+
149
+ // Find records by criteria
150
+ async find(criteria?: Record<string, any>, options?: QueryOptions): Promise<Record<string, any>[]>
151
+
152
+ // Find all records
153
+ async findAll(options?: QueryOptions): Promise<Record<string, any>[]>
154
+
155
+ // Update record
156
+ async update(id: string, updates: Record<string, any>): Promise<Record<string, any>>
157
+
158
+ // Delete record
159
+ async delete(id: string): Promise<boolean>
160
+
161
+ // Paginate results
162
+ async paginate(criteria?: Record<string, any>, pagination?: PaginationOptions): Promise<PaginatedResult>
163
+ ```
164
+
165
+ **Types:**
166
+ ```typescript
167
+ interface QueryOptions {
168
+ orderBy?: string;
169
+ orderDirection?: 'ASC' | 'DESC';
170
+ limit?: number;
171
+ offset?: number;
172
+ }
173
+
174
+ interface PaginationOptions {
175
+ page?: number;
176
+ limit?: number;
177
+ orderBy?: string;
178
+ orderDirection?: 'ASC' | 'DESC';
179
+ }
180
+
181
+ interface PaginatedResult {
182
+ data: Record<string, any>[];
183
+ pagination: {
184
+ page: number;
185
+ limit: number;
186
+ total: number;
187
+ totalPages: number;
188
+ hasNext: boolean;
189
+ hasPrev: boolean;
190
+ };
191
+ }
192
+ ```
193
+
194
+ #### **SchemaManager**
195
+ ```javascript
196
+ import { schemaManager } from '@tamyla/clodo-framework';
197
+ ```
198
+
199
+ **Methods:**
200
+ ```javascript
201
+ // Register a data model
202
+ registerModel(name: string, schema: ModelSchema): void
203
+
204
+ // Get registered model
205
+ getModel(name: string): ModelSchema | null
206
+
207
+ // Get all registered models
208
+ getAllModels(): Map<string, ModelSchema>
209
+
210
+ // Validate data against model schema
211
+ validateData(modelName: string, data: Record<string, any>): ValidationResult
212
+
213
+ // Generate SQL for operations
214
+ generateSQL(modelName: string, operation: 'create' | 'read' | 'update' | 'delete', data: any): SQLResult
215
+
216
+ // Generate table creation SQL
217
+ generateTableSQL(modelName: string): string
218
+
219
+ // Generate index creation SQL
220
+ generateIndexSQL(modelName: string): string[]
221
+ ```
222
+
223
+ **Types:**
224
+ ```typescript
225
+ interface ModelSchema {
226
+ tableName: string;
227
+ columns: Record<string, ColumnDefinition>;
228
+ indexes?: IndexDefinition[];
229
+ constraints?: ConstraintDefinition[];
230
+ }
231
+
232
+ interface ColumnDefinition {
233
+ type: 'string' | 'number' | 'boolean' | 'datetime' | 'json';
234
+ primaryKey?: boolean;
235
+ required?: boolean;
236
+ unique?: boolean;
237
+ default?: any;
238
+ auto?: boolean; // For timestamps
239
+ maxLength?: number;
240
+ minLength?: number;
241
+ }
242
+
243
+ interface ValidationResult {
244
+ valid: boolean;
245
+ data: Record<string, any>; // Cleaned/transformed data
246
+ errors: string[];
247
+ }
248
+
249
+ interface SQLResult {
250
+ sql: string;
251
+ params: any[];
252
+ }
253
+ ```
254
+
255
+ ### **Routing System**
256
+
257
+ #### **EnhancedRouter**
258
+ ```javascript
259
+ import { EnhancedRouter } from '@tamyla/clodo-framework';
260
+
261
+ const router = new EnhancedRouter(d1Client, options);
262
+ ```
263
+
264
+ **Constructor:**
265
+ ```javascript
266
+ new EnhancedRouter(d1Client: D1Database, options?: RouterOptions)
267
+ ```
268
+
269
+ **Methods:**
270
+ ```javascript
271
+ // Register custom route
272
+ registerRoute(method: string, path: string, handler: RouteHandler): void
273
+
274
+ // Handle incoming request
275
+ async handleRequest(method: string, path: string, request: Request): Promise<Response>
276
+
277
+ // Get registered routes (for debugging)
278
+ getRoutes(): Map<string, RouteHandler>
279
+ ```
280
+
281
+ **Types:**
282
+ ```typescript
283
+ interface RouterOptions {
284
+ requireAuth?: boolean;
285
+ allowPublicRead?: boolean;
286
+ customValidators?: Record<string, Function>;
287
+ hooks?: Record<string, Function>;
288
+ }
289
+
290
+ type RouteHandler = (request: Request, ...params: string[]) => Promise<Response>;
291
+ ```
292
+
293
+ #### **GenericRouteHandler**
294
+ ```javascript
295
+ import { GenericRouteHandler } from '@tamyla/clodo-framework';
296
+
297
+ const handler = new GenericRouteHandler(d1Client, 'users', options);
298
+ ```
299
+
300
+ **Constructor:**
301
+ ```javascript
302
+ new GenericRouteHandler(d1Client: D1Database, modelName: string, options?: HandlerOptions)
303
+ ```
304
+
305
+ **HTTP Handlers:**
306
+ ```javascript
307
+ // List all records - GET /api/model
308
+ async handleList(request: Request): Promise<Response>
309
+
310
+ // Create new record - POST /api/model
311
+ async handleCreate(request: Request): Promise<Response>
312
+
313
+ // Get single record - GET /api/model/:id
314
+ async handleGet(request: Request, id: string): Promise<Response>
315
+
316
+ // Update record - PATCH /api/model/:id
317
+ async handleUpdate(request: Request, id: string): Promise<Response>
318
+
319
+ // Delete record - DELETE /api/model/:id
320
+ async handleDelete(request: Request, id: string): Promise<Response>
321
+ ```
322
+
323
+ **Types:**
324
+ ```typescript
325
+ interface HandlerOptions {
326
+ requireAuth?: boolean;
327
+ allowPublicRead?: boolean;
328
+ customValidators?: Record<string, Function>;
329
+ hooks?: {
330
+ beforeCreate?: Function;
331
+ afterCreate?: Function;
332
+ beforeUpdate?: Function;
333
+ afterUpdate?: Function;
334
+ beforeDelete?: Function;
335
+ afterDelete?: Function;
336
+ };
337
+ }
338
+ ```
339
+
340
+ ### **Worker Integration**
341
+
342
+ #### **Service Initialization**
343
+ ```javascript
344
+ import { initializeService } from '@tamyla/clodo-framework';
345
+
346
+ const service = initializeService(env, domainConfigs);
347
+ ```
348
+
349
+ **Function:**
350
+ ```javascript
351
+ initializeService(
352
+ env: WorkerEnv,
353
+ domainConfigs: Record<string, DomainConfig>
354
+ ): ServiceContext
355
+ ```
356
+
357
+ **Types:**
358
+ ```typescript
359
+ interface ServiceContext {
360
+ domain: string;
361
+ environment: string;
362
+ features: string[];
363
+ config: DomainConfig;
364
+ env: WorkerEnv;
365
+ isProduction: boolean;
366
+ isStaging: boolean;
367
+ isDevelopment: boolean;
368
+ }
369
+
370
+ interface WorkerEnv {
371
+ DOMAIN_NAME?: string;
372
+ CF_DOMAIN_NAME?: string;
373
+ ENVIRONMENT?: string;
374
+ NODE_ENV?: string;
375
+ [key: string]: any;
376
+ }
377
+ ```
378
+
379
+ #### **Feature Guards**
380
+ ```javascript
381
+ import { createFeatureGuard } from '@tamyla/clodo-framework';
382
+
383
+ const guard = createFeatureGuard('featureName', options);
384
+ ```
385
+
386
+ **Function:**
387
+ ```javascript
388
+ createFeatureGuard(
389
+ featureName: string,
390
+ options?: FeatureGuardOptions
391
+ ): (handler: RouteHandler) => RouteHandler
392
+ ```
393
+
394
+ **Usage:**
395
+ ```javascript
396
+ // Wrap route handler with feature guard
397
+ const protectedHandler = createFeatureGuard('premiumFeatures')(
398
+ async (request, env, ctx) => {
399
+ // Handler only executes if feature is enabled
400
+ return new Response('Premium feature content');
401
+ }
402
+ );
403
+ ```
404
+
405
+ **Types:**
406
+ ```typescript
407
+ interface FeatureGuardOptions {
408
+ fallbackResponse?: Response;
409
+ required?: boolean;
410
+ logAccess?: boolean;
411
+ }
412
+ ```
413
+
414
+ ### **Module System**
415
+
416
+ #### **ModuleManager**
417
+ ```javascript
418
+ import { moduleManager } from '@tamyla/clodo-framework';
419
+ ```
420
+
421
+ **Methods:**
422
+ ```javascript
423
+ // Register custom module
424
+ registerModule(name: string, module: Module): void
425
+
426
+ // Get registered module
427
+ getModule(name: string): Module | null
428
+
429
+ // Execute lifecycle hooks
430
+ async executeHooks(hookName: string, context: HookContext): Promise<void>
431
+
432
+ // List registered modules
433
+ getModules(): Map<string, Module>
434
+ ```
435
+
436
+ **Types:**
437
+ ```typescript
438
+ interface Module {
439
+ name: string;
440
+ version?: string;
441
+ hooks?: Record<string, Function>;
442
+ initialize?: (context: any) => Promise<void>;
443
+ }
444
+
445
+ interface HookContext {
446
+ model?: string;
447
+ request?: Request;
448
+ data?: any;
449
+ result?: any;
450
+ [key: string]: any;
451
+ }
452
+ ```
453
+
454
+ ### **Utility Functions**
455
+
456
+ #### **Logging**
457
+ ```javascript
458
+ import { createLogger } from '@tamyla/clodo-framework';
459
+
460
+ const logger = createLogger('ServiceName');
461
+ ```
462
+
463
+ **Logger Methods:**
464
+ ```javascript
465
+ logger.debug(message: string, ...args: any[]): void
466
+ logger.info(message: string, ...args: any[]): void
467
+ logger.warn(message: string, ...args: any[]): void
468
+ logger.error(message: string, ...args: any[]): void
469
+ ```
470
+
471
+ #### **Validation Helpers**
472
+ ```javascript
473
+ import { validateRequired, deepMerge } from '@tamyla/clodo-framework';
474
+
475
+ // Validate required fields exist
476
+ validateRequired(object: any, requiredFields: string[]): void // throws on missing
477
+
478
+ // Deep merge objects
479
+ deepMerge(target: any, source: any): any
480
+ ```
481
+
482
+ ### **Constants**
483
+
484
+ #### **Common Features**
485
+ ```javascript
486
+ import { COMMON_FEATURES } from '@tamyla/clodo-framework';
487
+
488
+ // Pre-defined feature names
489
+ COMMON_FEATURES.AUTHENTICATION // 'authentication'
490
+ COMMON_FEATURES.AUTHORIZATION // 'authorization'
491
+ COMMON_FEATURES.LOGGING // 'logging'
492
+ COMMON_FEATURES.MONITORING // 'monitoring'
493
+ COMMON_FEATURES.ANALYTICS // 'analytics'
494
+ COMMON_FEATURES.CACHING // 'caching'
495
+ COMMON_FEATURES.RATE_LIMITING // 'rateLimiting'
496
+ COMMON_FEATURES.FILE_STORAGE // 'fileStorage'
497
+ COMMON_FEATURES.EMAIL_NOTIFICATIONS // 'emailNotifications'
498
+ COMMON_FEATURES.PUSH_NOTIFICATIONS // 'pushNotifications'
499
+ COMMON_FEATURES.SEARCH // 'search'
500
+ COMMON_FEATURES.FILTERING // 'filtering'
501
+ COMMON_FEATURES.SORTING // 'sorting'
502
+ COMMON_FEATURES.PAGINATION // 'pagination'
503
+ COMMON_FEATURES.EXPORT // 'export'
504
+ COMMON_FEATURES.IMPORT // 'import'
505
+ COMMON_FEATURES.BACKUP // 'backup'
506
+ COMMON_FEATURES.RESTORE // 'restore'
507
+ ```
508
+
509
+ ## 🔧 Framework Information
510
+
511
+ ```javascript
512
+ import { FRAMEWORK_VERSION, FRAMEWORK_NAME, initializeFramework } from '@tamyla/clodo-framework';
513
+
514
+ console.log(FRAMEWORK_NAME); // 'Clodo Framework'
515
+ console.log(FRAMEWORK_VERSION); // '1.0.0'
516
+
517
+ // Initialize framework with options
518
+ const framework = initializeFramework({
519
+ logLevel: 'debug',
520
+ enableMetrics: true
521
+ });
522
+ ```
523
+
524
+ ---
525
+
526
+ **Next**: [Configuration API Details](./configuration.md)