@adaas/a-utils 0.1.17 → 0.1.19

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.
Files changed (47) hide show
  1. package/dist/index.d.mts +964 -354
  2. package/dist/index.d.ts +964 -354
  3. package/dist/index.js +1426 -714
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +1426 -714
  6. package/dist/index.mjs.map +1 -1
  7. package/examples/A-Channel-examples.ts +13 -11
  8. package/examples/A-Command-examples-2.ts +429 -0
  9. package/examples/A-Command-examples.ts +487 -202
  10. package/examples/A-StateMachine-examples.ts +609 -0
  11. package/package.json +3 -2
  12. package/src/index.ts +1 -2
  13. package/src/lib/A-Channel/A-Channel.component.ts +14 -74
  14. package/src/lib/A-Channel/A-Channel.error.ts +5 -5
  15. package/src/lib/A-Channel/A-Channel.types.ts +2 -10
  16. package/src/lib/A-Channel/A-ChannelRequest.context.ts +25 -74
  17. package/src/lib/A-Command/A-Command.constants.ts +78 -23
  18. package/src/lib/A-Command/A-Command.entity.ts +447 -119
  19. package/src/lib/A-Command/A-Command.error.ts +11 -0
  20. package/src/lib/A-Command/A-Command.types.ts +96 -20
  21. package/src/lib/A-Command/A-CommandExecution.context.ts +0 -0
  22. package/src/lib/A-Command/README.md +164 -68
  23. package/src/lib/A-Config/A-Config.container.ts +2 -2
  24. package/src/lib/A-Config/A-Config.context.ts +19 -5
  25. package/src/lib/A-Config/components/ConfigReader.component.ts +1 -1
  26. package/src/lib/A-Logger/A-Logger.component.ts +211 -35
  27. package/src/lib/A-Logger/A-Logger.constants.ts +50 -10
  28. package/src/lib/A-Logger/A-Logger.env.ts +17 -1
  29. package/src/lib/A-Memory/A-Memory.component.ts +440 -0
  30. package/src/lib/A-Memory/A-Memory.constants.ts +49 -0
  31. package/src/lib/A-Memory/A-Memory.context.ts +14 -118
  32. package/src/lib/A-Memory/A-Memory.error.ts +21 -0
  33. package/src/lib/A-Memory/A-Memory.types.ts +21 -0
  34. package/src/lib/A-Operation/A-Operation.context.ts +58 -0
  35. package/src/lib/A-Operation/A-Operation.types.ts +47 -0
  36. package/src/lib/A-StateMachine/A-StateMachine.component.ts +258 -0
  37. package/src/lib/A-StateMachine/A-StateMachine.constants.ts +18 -0
  38. package/src/lib/A-StateMachine/A-StateMachine.error.ts +10 -0
  39. package/src/lib/A-StateMachine/A-StateMachine.types.ts +20 -0
  40. package/src/lib/A-StateMachine/A-StateMachineTransition.context.ts +41 -0
  41. package/src/lib/A-StateMachine/README.md +391 -0
  42. package/tests/A-Channel.test.ts +17 -14
  43. package/tests/A-Command.test.ts +548 -460
  44. package/tests/A-Logger.test.ts +8 -4
  45. package/tests/A-Memory.test.ts +151 -115
  46. package/tests/A-Schedule.test.ts +2 -2
  47. package/tests/A-StateMachine.test.ts +760 -0
@@ -28,7 +28,6 @@ async function basicChannelExample() {
28
28
  });
29
29
 
30
30
  console.log('Request params:', response.params);
31
- console.log('Request status:', response.status);
32
31
  }
33
32
 
34
33
  // Example 2: HTTP Client Channel
@@ -94,7 +93,7 @@ class HttpProcessor extends A_Component {
94
93
  }
95
94
  };
96
95
 
97
- (context as any)._result = mockResponse;
96
+ context.succeed(mockResponse);
98
97
  }
99
98
 
100
99
  @A_Feature.Extend({ scope: [HttpChannel] })
@@ -338,7 +337,7 @@ class DatabaseProcessor extends A_Component {
338
337
  throw new Error(`Unsupported operation: ${operation}`);
339
338
  }
340
339
 
341
- (context as any)._result = result;
340
+ context.succeed(result);
342
341
  }
343
342
 
344
343
  @A_Feature.Extend({ scope: [DatabaseChannel] })
@@ -445,7 +444,7 @@ class RobustProcessor extends A_Component {
445
444
  const currentRetries = this.retryCount.get(requestId) || 0;
446
445
  const maxRetries = 3;
447
446
 
448
- console.log(`Error occurred (attempt ${currentRetries + 1}/${maxRetries + 1}):`, context.failed);
447
+ console.log(`Error occurred (attempt ${currentRetries + 1}/${maxRetries + 1}):`, context.error?.message);
449
448
 
450
449
  if (currentRetries < maxRetries) {
451
450
  this.retryCount.set(requestId, currentRetries + 1);
@@ -476,13 +475,16 @@ async function errorHandlingExample() {
476
475
  console.log('Success result:', successResult.data);
477
476
 
478
477
  // Test failing operation
479
- const failResult = await robustChannel.request({
480
- operation: 'process-data',
481
- shouldFail: true
482
- });
483
-
484
- console.log('Fail result status:', failResult.status);
485
- console.log('Failed:', failResult.failed);
478
+ try {
479
+ const failResult = await robustChannel.request({
480
+ operation: 'process-data',
481
+ shouldFail: true
482
+ });
483
+
484
+ console.log('Fail result status:', failResult.status);
485
+ } catch (error) {
486
+ console.log('Request failed as expected:', (error as Error).message);
487
+ }
486
488
  }
487
489
 
488
490
  // Run all examples
@@ -0,0 +1,429 @@
1
+ // ============================================================================
2
+ // ====================== A-Command Feature-Driven Example ==================
3
+ // ============================================================================
4
+
5
+ /**
6
+ * Advanced Command Processing with Feature Templates
7
+ *
8
+ * This example demonstrates how to use A_Command with feature-driven architecture
9
+ * where command execution is configured through templates that map specific
10
+ * result properties to component handlers.
11
+ *
12
+ * Key Concepts Demonstrated:
13
+ * - Feature-driven command definition with @A_Feature.Define()
14
+ * - Template-based execution mapping components to result properties
15
+ * - Component-based handler system for modular processing
16
+ * - Automated command lifecycle with result compilation
17
+ * - Container-based command execution with scope management
18
+ */
19
+
20
+ import { A_Component, A_Concept, A_Container, A_Feature, A_Inject } from "@adaas/a-concept";
21
+ import { A_StateMachine } from "@adaas/a-utils/lib/A-StateMachine/A-StateMachine.component";
22
+ import { A_Command, A_CommandFeatures, A_Logger, A_Memory } from "src";
23
+
24
+ // ============================================================================
25
+ // ====================== Command Type Definitions ===========================
26
+ // ============================================================================
27
+
28
+ /**
29
+ * Command Input Parameters
30
+ *
31
+ * Defines the shape of data required to execute the CustomCommand.
32
+ * In this example, we need an item identifier to process.
33
+ */
34
+ type CustomCommandParams = { itemId: string };
35
+
36
+ /**
37
+ * Command Result Structure
38
+ *
39
+ * Defines the expected output structure of the command execution.
40
+ * The feature template will map these properties to specific component handlers.
41
+ */
42
+ type CustomCommandResult = { itemName: string; itemPrice: number };
43
+
44
+
45
+ // ============================================================================
46
+ // ====================== Feature-Driven Command Definition =================
47
+ // ============================================================================
48
+
49
+ /**
50
+ * CustomCommand - Feature-Template Based Command
51
+ *
52
+ * This command demonstrates advanced feature-driven architecture where:
53
+ *
54
+ * 1. TEMPLATE MAPPING: Each result property is mapped to a specific component and handler
55
+ * 2. AUTOMATED EXECUTION: The framework automatically calls the mapped handlers
56
+ * 3. RESULT COMPILATION: Handler outputs are automatically compiled into the result object
57
+ * 4. MODULAR PROCESSING: Each aspect of the command is handled by specialized components
58
+ *
59
+ * Architecture Flow:
60
+ * 1. Command is executed via [A_CommandFeatures.onExecute]
61
+ * 2. Framework processes the feature template
62
+ * 3. For each template entry, the specified component handler is called
63
+ * 4. Handler results are mapped back to the corresponding result properties
64
+ * 5. Final result object is compiled with all property values
65
+ *
66
+ * Template Configuration:
67
+ * - itemName → ComponentA.log1() : Handles item name resolution
68
+ * - itemPrice → ComponentB.log2() : Handles item price calculation
69
+ */
70
+ class CustomCommand extends A_Command<CustomCommandParams, CustomCommandResult> {
71
+
72
+ /**
73
+ * Feature Template Definition
74
+ *
75
+ * The @A_Feature.Define decorator configures how command execution
76
+ * is mapped to component handlers. Each template entry defines:
77
+ *
78
+ * @param name - The result property name that will receive the handler output
79
+ * @param component - The component class name that contains the handler
80
+ * @param handler - The method name within the component to execute
81
+ *
82
+ * Execution Flow:
83
+ * 1. Framework resolves ComponentA from scope
84
+ * 2. Calls ComponentA.log1() → result mapped to result.itemName
85
+ * 3. Framework resolves ComponentB from scope
86
+ * 4. Calls ComponentB.log2() → result mapped to result.itemPrice
87
+ * 5. Final result object: { itemName: ..., itemPrice: ... }
88
+ */
89
+ @A_Feature.Define({
90
+ template: [
91
+ {
92
+ name: 'itemName', // Maps handler result to result.itemName
93
+ component: 'ComponentA', // Resolve ComponentA from scope
94
+ handler: 'log1' // Call ComponentA.log1() method
95
+ },
96
+ {
97
+ name: 'itemPrice', // Maps handler result to result.itemPrice
98
+ component: 'ComponentB', // Resolve ComponentB from scope
99
+ handler: 'log2' // Call ComponentB.log2() method
100
+ }
101
+ ]
102
+ })
103
+ /**
104
+ * Command Execution Entry Point
105
+ *
106
+ * This method is called when command.execute() is invoked.
107
+ * The feature template processing happens automatically
108
+ * after this method completes.
109
+ *
110
+ * Execution Order:
111
+ * 1. This onExecute method runs first
112
+ * 2. Feature template processing executes component handlers
113
+ * 3. Results are compiled into the command result
114
+ * 4. Command status transitions to COMPLETED
115
+ */
116
+ protected async [A_CommandFeatures.onExecute](
117
+ @A_Inject(A_Logger) logger: A_Logger
118
+ ): Promise<void> {
119
+ logger.info("🚀 Executing CustomCommand with params:", this.params);
120
+ logger.info(" ItemId to process:", this.params.itemId);
121
+ logger.info(" Template will now process component handlers...");
122
+ }
123
+ }
124
+
125
+
126
+ // ============================================================================
127
+ // ====================== Specialized Component Handlers ====================
128
+ // ============================================================================
129
+
130
+ /**
131
+ * ComponentA - Item Name Resolution Handler
132
+ *
133
+ * Specialized component responsible for resolving item names.
134
+ * In a real-world scenario, this might:
135
+ * - Query a database for item details
136
+ * - Call an external API for product information
137
+ * - Apply business logic for name formatting
138
+ * - Cache results for performance optimization
139
+ *
140
+ * The log1() method will be automatically called by the command
141
+ * feature template and its result will be mapped to result.itemName.
142
+ */
143
+ class ComponentA extends A_Component {
144
+
145
+ /**
146
+ * Item Name Resolution Handler
147
+ *
148
+ * This method is called automatically by the CustomCommand feature template.
149
+ * The return value (if any) will be mapped to the 'itemName' property
150
+ * in the command result.
151
+ *
152
+ * @returns The resolved item name (currently just logging, but could return actual data)
153
+ */
154
+ log1(
155
+ @A_Inject(A_Logger) logger: A_Logger
156
+ ) {
157
+ logger.info("📦 ComponentA.log1() - Processing item name resolution");
158
+ logger.info(" Simulating item name lookup...");
159
+
160
+ // In a real implementation, this might return:
161
+ // return await this.itemService.getItemName(itemId);
162
+
163
+ // For demo purposes, we'll just log the action
164
+ logger.info(" ✅ Item name resolved");
165
+ }
166
+
167
+ }
168
+
169
+ /**
170
+ * ComponentB - Item Price Calculation Handler
171
+ *
172
+ * Specialized component responsible for calculating item prices.
173
+ * In a real-world scenario, this might:
174
+ * - Apply pricing rules and discounts
175
+ * - Calculate taxes and fees
176
+ * - Handle currency conversion
177
+ * - Integrate with pricing engines
178
+ *
179
+ * The log2() method will be automatically called by the command
180
+ * feature template and its result will be mapped to result.itemPrice.
181
+ */
182
+ class ComponentB extends A_Component {
183
+
184
+ /**
185
+ * Item Price Calculation Handler
186
+ *
187
+ * This method is called automatically by the CustomCommand feature template.
188
+ * The return value (if any) will be mapped to the 'itemPrice' property
189
+ * in the command result.
190
+ *
191
+ * @returns The calculated item price (currently just logging, but could return actual data)
192
+ */
193
+ log2(
194
+ @A_Inject(A_Logger) logger: A_Logger
195
+ ) {
196
+ logger.info("💰 ComponentB.log2() - Processing item price calculation");
197
+ logger.info(" Simulating price calculation logic...");
198
+
199
+ // In a real implementation, this might return:
200
+ // return await this.priceEngine.calculatePrice(itemId, context);
201
+
202
+ // For demo purposes, we'll just log the action
203
+ logger.info(" ✅ Item price calculated");
204
+ }
205
+ }
206
+
207
+
208
+ // ============================================================================
209
+ // ====================== Command Processing Container =======================
210
+ // ============================================================================
211
+
212
+ /**
213
+ * CommandProcessor - Execution Environment Container
214
+ *
215
+ * This container provides the execution environment for feature-driven commands.
216
+ * It acts as the orchestrator that:
217
+ *
218
+ * 1. SCOPE MANAGEMENT: Provides dependency injection scope for commands and components
219
+ * 2. COMMAND LIFECYCLE: Manages command creation, registration, and execution
220
+ * 3. RESULT HANDLING: Processes and logs command execution results
221
+ * 4. COMPONENT RESOLUTION: Ensures all required components are available for feature templates
222
+ *
223
+ * The @A_Concept.Start() decorator ensures this processing logic runs
224
+ * automatically when the concept starts up.
225
+ */
226
+ class CommandProcessor extends A_Container {
227
+
228
+ /**
229
+ * Container Startup and Command Execution
230
+ *
231
+ * This method demonstrates the complete lifecycle of feature-driven command execution:
232
+ *
233
+ * 1. COMMAND CREATION: Instantiate command with specific parameters
234
+ * 2. SCOPE REGISTRATION: Register command in container scope for DI
235
+ * 3. FEATURE EXECUTION: Execute command with automatic template processing
236
+ * 4. RESULT ANALYSIS: Examine and log the final command state and results
237
+ *
238
+ * Execution Flow:
239
+ * 1. CustomCommand created with itemId: '999'
240
+ * 2. Command registered in container scope
241
+ * 3. command.execute() triggers:
242
+ * - CustomCommand[A_CommandFeatures.onExecute]() runs
243
+ * - Feature template processes component handlers
244
+ * - ComponentA.log1() called → mapped to result.itemName
245
+ * - ComponentB.log2() called → mapped to result.itemPrice
246
+ * - Final result compiled and command status updated
247
+ * 4. Final state logged with complete command information
248
+ */
249
+ @A_Concept.Start()
250
+ protected async start(
251
+ @A_Inject(A_Logger) logger: A_Logger
252
+ ) {
253
+ logger.info('🎬 CommandProcessor starting - initializing feature-driven command execution');
254
+
255
+ // ====================================================================
256
+ // ====================== Command Creation ==========================
257
+ // ====================================================================
258
+
259
+ /**
260
+ * Create Feature-Driven Command Instance
261
+ *
262
+ * Instantiate the CustomCommand with specific parameters.
263
+ * The itemId will be available throughout the command execution
264
+ * and can be used by component handlers for processing.
265
+ */
266
+ const command = new CustomCommand({ itemId: '999' });
267
+ logger.info(`📝 Created CustomCommand: ${command.id}`);
268
+ logger.info(` Parameters: itemId = ${command.params.itemId}`);
269
+ logger.info(` Initial status: ${command.status}`);
270
+
271
+ // ====================================================================
272
+ // ====================== Scope Registration ========================
273
+ // ====================================================================
274
+
275
+ /**
276
+ * Register Command in Container Scope
277
+ *
278
+ * This makes the command available for dependency injection
279
+ * and ensures it can interact with other components in the container.
280
+ */
281
+ this.scope.register(command);
282
+ logger.info('🔗 Command registered in CommandProcessor scope');
283
+
284
+ // ====================================================================
285
+ // ====================== Feature-Driven Execution ==================
286
+ // ====================================================================
287
+
288
+ /**
289
+ * Execute Command with Feature Template Processing
290
+ *
291
+ * This triggers the complete command execution pipeline:
292
+ * 1. Command onExecute method runs
293
+ * 2. Feature template is processed
294
+ * 3. Component handlers are called automatically
295
+ * 4. Results are compiled into the command result object
296
+ * 5. Command status transitions to COMPLETED
297
+ */
298
+ logger.info('⚡ Executing feature-driven command...');
299
+ await command.execute();
300
+ logger.info('✅ Command execution completed');
301
+
302
+ // ====================================================================
303
+ // ====================== Result Analysis ===========================
304
+ // ====================================================================
305
+
306
+ /**
307
+ * Analyze Command Execution Results
308
+ *
309
+ * After execution, the command contains:
310
+ * - Updated status (should be COMPLETED)
311
+ * - Compiled result object with mapped component handler outputs
312
+ * - Complete execution history and state information
313
+ */
314
+ logger.info('📊 Command Execution Analysis:');
315
+ logger.info(` Final status: ${command.status}`);
316
+ logger.info(' Complete command state:', command.toJSON());
317
+ logger.info('🎉 Feature-driven command processing demonstration completed!');
318
+ }
319
+ }
320
+
321
+
322
+
323
+ // ============================================================================
324
+ // ====================== Application Architecture Setup =====================
325
+ // ============================================================================
326
+
327
+ /**
328
+ * Feature-Driven Command Processing Application
329
+ *
330
+ * This application demonstrates a complete feature-driven command architecture
331
+ * where commands are executed through configurable templates that map
332
+ * result properties to specialized component handlers.
333
+ *
334
+ * Architecture Components:
335
+ * - A_Concept: Main application architecture container
336
+ * - CommandProcessor: Execution environment for feature-driven commands
337
+ * - CustomCommand: Feature-template configured command implementation
338
+ * - ComponentA/B: Specialized handlers for different result properties
339
+ *
340
+ * Execution Flow:
341
+ * 1. Concept loads all containers and dependencies
342
+ * 2. CommandProcessor starts and creates command instances
343
+ * 3. Commands execute with automatic feature template processing
344
+ * 4. Component handlers are called and results are compiled
345
+ * 5. Final results are logged and analyzed
346
+ */
347
+ (async () => {
348
+ console.log('🚀 Starting Feature-Driven Command Processing Application');
349
+
350
+ // ========================================================================
351
+ // ====================== Concept Architecture Definition ================
352
+ // ========================================================================
353
+
354
+ /**
355
+ * Application Architecture Configuration
356
+ *
357
+ * Defines the complete application architecture with:
358
+ * - CommandProcessor container for command execution environment
359
+ * - All required components for feature template processing
360
+ * - Dependency injection configuration for seamless component resolution
361
+ *
362
+ * Container Components:
363
+ * - A_Logger: Provides scoped logging throughout the application
364
+ * - CustomCommand: The feature-driven command implementation
365
+ * - ComponentA: Handler for itemName resolution
366
+ * - ComponentB: Handler for itemPrice calculation
367
+ * - A_Memory: Memory management for state persistence
368
+ */
369
+ const concept = new A_Concept({
370
+ containers: [
371
+ new CommandProcessor({
372
+ name: 'Command Executor',
373
+ components: [
374
+ A_Logger, // Scoped logging system
375
+ CustomCommand, // Feature-driven command class
376
+ ComponentA, // Item name resolution handler
377
+ ComponentB, // Item price calculation handler
378
+ A_Memory, // Memory management system
379
+ ],
380
+ })
381
+ ],
382
+ components: [
383
+ A_Logger, // Global logger for the concept
384
+ A_Memory // Global memory management
385
+ ],
386
+ });
387
+
388
+ const logger = concept.scope.resolve(A_Logger)!;
389
+
390
+ logger.info('🏗️ Application architecture configured');
391
+ logger.info(' - CommandProcessor container with feature-driven components');
392
+ logger.info(' - Component handlers for modular command processing');
393
+ logger.info(' - Integrated logging and memory management');
394
+
395
+ // ========================================================================
396
+ // ====================== System Initialization ==========================
397
+ // ========================================================================
398
+
399
+ /**
400
+ * Load Application Architecture
401
+ *
402
+ * Initialize all containers, resolve dependencies, and prepare
403
+ * the system for command execution. This ensures all components
404
+ * are properly registered and available for feature template processing.
405
+ */
406
+ logger.info('⚡ Loading application architecture...');
407
+ await concept.load();
408
+ logger.info('✅ Architecture loaded - all components ready');
409
+
410
+ // ========================================================================
411
+ // ====================== Application Execution ===========================
412
+ // ========================================================================
413
+
414
+ /**
415
+ * Start Command Processing
416
+ *
417
+ * Trigger the CommandProcessor @A_Concept.Start() method which will:
418
+ * 1. Create CustomCommand instances
419
+ * 2. Execute feature-driven command processing
420
+ * 3. Demonstrate template-based component handler execution
421
+ * 4. Log complete results and analysis
422
+ */
423
+ logger.info('🎬 Starting command processing demonstration...');
424
+ await concept.start();
425
+
426
+ logger.info('🏁 Application execution completed successfully!');
427
+ logger.info('Review the logs above to see the feature-driven command processing flow.');
428
+
429
+ })();