@adaas/a-utils 0.1.11 → 0.1.12

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.
package/README.md CHANGED
@@ -59,45 +59,73 @@ const channel = new A_Channel();
59
59
 
60
60
  ### A-Command
61
61
 
62
- A powerful command execution system that provides structured command patterns with lifecycle management, status tracking, and serialization capabilities.
62
+ A powerful command execution system that provides structured command patterns with lifecycle management, event handling, status tracking, and serialization capabilities.
63
63
 
64
- **Basic Usage:**
64
+ > 📚 **[Complete A-Command Documentation](./src/lib/A-Command/README.md)** - Comprehensive guide with examples, API reference, and advanced usage patterns.
65
+
66
+ **Quick Start:**
65
67
  ```typescript
66
68
  import { A_Command } from '@adaas/a-utils';
69
+ import { A_Context } from '@adaas/a-concept';
67
70
 
68
- // Create a command
69
- const command = new A_Command({});
71
+ // Create and execute a simple command
72
+ const command = new A_Command({ action: 'greet', name: 'World' });
73
+ A_Context.root.register(command);
70
74
 
71
- // Execute the command
72
75
  await command.execute();
73
76
 
74
77
  console.log(command.status); // 'COMPLETED'
75
78
  console.log(command.duration); // Execution time in ms
76
79
  ```
77
80
 
78
- **Advanced Usage:**
81
+ **Advanced Example:**
79
82
  ```typescript
80
- // Command with custom logic
81
- class CustomCommand extends A_Command {
82
- async execute() {
83
- // Your custom command logic here
84
- return await super.execute();
83
+ // Typed command with custom logic
84
+ interface UserCreateParams {
85
+ name: string;
86
+ email: string;
87
+ }
88
+
89
+ interface UserCreateResult {
90
+ userId: string;
91
+ createdAt: string;
92
+ }
93
+
94
+ class CreateUserCommand extends A_Command<UserCreateParams, UserCreateResult> {}
95
+
96
+ // Custom execution logic using components
97
+ class UserProcessor extends A_Component {
98
+ @A_Feature.Extend({ scope: [CreateUserCommand] })
99
+ async execute(@A_Inject(A_Memory) memory: A_Memory<UserCreateResult>) {
100
+ // Your business logic here
101
+ await memory.set('userId', 'user-123');
102
+ await memory.set('createdAt', new Date().toISOString());
85
103
  }
86
104
  }
87
105
 
88
- // Serialization
89
- const command = new A_Command({});
90
- await command.execute();
106
+ // Execute with event handling
107
+ const command = new CreateUserCommand({
108
+ name: 'John Doe',
109
+ email: 'john@example.com'
110
+ });
111
+
112
+ command.on('complete', (cmd) => {
113
+ console.log('User created:', cmd.result);
114
+ });
91
115
 
92
- const serialized = command.toJSON();
93
- const deserializedCommand = new A_Command(serialized);
116
+ A_Context.root.register(UserProcessor);
117
+ A_Context.root.register(command);
118
+ await command.execute();
94
119
  ```
95
120
 
96
- **Features:**
97
- - Command execution with lifecycle management
98
- - Status tracking (INITIALIZED, PROCESSING, COMPLETED, FAILED)
99
- - Built-in timing and duration tracking
100
- - JSON serialization/deserialization
121
+ **Key Features:**
122
+ - **Complete Lifecycle Management** - Automatic progression through init → compile → execute → complete/fail
123
+ - **Event-Driven Architecture** - Subscribe to lifecycle events and custom events
124
+ - ✅ **State Persistence** - Full serialization/deserialization support
125
+ - **Type Safety** - Full TypeScript support with generic types
126
+ - ✅ **Error Handling** - Comprehensive error capture and management
127
+ - ✅ **Execution Tracking** - Built-in timing and duration tracking
128
+ - ✅ **Component Integration** - Extensible through A-Component architecture
101
129
  - Scope integration with dependency injection
102
130
  - Memory management integration
103
131
 
@@ -284,13 +312,15 @@ const manifest = new A_Manifest([
284
312
 
285
313
  ### A-Memory
286
314
 
287
- A type-safe memory management system for storing intermediate values and tracking errors during complex operations.
315
+ A type-safe memory management system for storing intermediate values and tracking errors during complex operations. Fully integrated with A-Command for state management.
316
+
317
+ > 💡 **Note:** A-Memory is automatically used by A-Command for result and error storage. See [A-Command Documentation](./src/lib/A-Command/README.md) for integration examples.
288
318
 
289
319
  **Basic Usage:**
290
320
  ```typescript
291
321
  import { A_Memory } from '@adaas/a-utils';
292
322
 
293
- // Create memory instance
323
+ // Create typed memory instance
294
324
  const memory = new A_Memory<{
295
325
  userId: string;
296
326
  userData: any;
@@ -299,16 +329,19 @@ const memory = new A_Memory<{
299
329
  userId: '12345'
300
330
  });
301
331
 
302
- // Store values
303
- memory.set('userData', { name: 'John', email: 'john@example.com' });
304
- memory.set('processedData', processUserData(memory.get('userData')));
332
+ // Store and retrieve values
333
+ await memory.set('userData', { name: 'John', email: 'john@example.com' });
334
+ await memory.set('processedData', processUserData(memory.get('userData')));
335
+
336
+ // Access values with type safety
337
+ const userId = memory.get('userId'); // string | undefined
338
+ const userData = memory.get('userData'); // any | undefined
305
339
 
306
340
  // Check prerequisites
307
341
  const hasRequired = await memory.verifyPrerequisites(['userId', 'userData']);
308
342
  console.log(hasRequired); // true
309
343
 
310
- // Access values
311
- const userId = memory.get('userId');
344
+ // Serialize all data
312
345
  const allData = memory.toJSON();
313
346
  ```
314
347
 
@@ -318,20 +351,42 @@ import { A_Error } from '@adaas/a-concept';
318
351
 
319
352
  const memory = new A_Memory();
320
353
 
321
- // Errors are automatically tracked
354
+ // Add errors during processing
322
355
  try {
323
356
  // Some operation that might fail
324
- throw new A_Error('Something went wrong');
357
+ throw new Error('Something went wrong');
325
358
  } catch (error) {
326
- memory.addError(error);
359
+ await memory.error(new A_Error({
360
+ title: 'Operation Failed',
361
+ message: error.message
362
+ }));
327
363
  }
328
364
 
329
365
  // Check for errors
330
366
  if (memory.Errors) {
331
- console.log('Errors occurred:', memory.Errors);
367
+ console.log('Errors occurred:', Array.from(memory.Errors));
332
368
  }
333
369
  ```
334
370
 
371
+ **Integration with A-Command:**
372
+ ```typescript
373
+ // A-Memory is automatically used by A-Command
374
+ class DataProcessor extends A_Component {
375
+ @A_Feature.Extend({ scope: [MyCommand] })
376
+ async execute(@A_Inject(A_Memory) memory: A_Memory<ResultType>) {
377
+ // Store intermediate results
378
+ await memory.set('step1', 'completed');
379
+ await memory.set('step2', { data: 'processed' });
380
+
381
+ // Access stored values
382
+ const step1Result = memory.get('step1');
383
+
384
+ // Results automatically become command.result
385
+ }
386
+ }
387
+ ```
388
+ ```
389
+
335
390
  **Features:**
336
391
  - Type-safe value storage
337
392
  - Prerequisite verification
package/dist/index.d.mts CHANGED
@@ -33,7 +33,11 @@ declare enum A_TYPES__CommandMetaKey {
33
33
  ABSTRACTIONS = "a-command-abstractions"
34
34
  }
35
35
  declare enum A_CONSTANTS__A_Command_Status {
36
+ CREATED = "CREATED",
37
+ INITIALIZATION = "INITIALIZATION",
36
38
  INITIALIZED = "INITIALIZED",
39
+ COMPILATION = "COMPILATION",
40
+ COMPILED = "COMPILED",
37
41
  IN_PROGRESS = "IN_PROGRESS",
38
42
  COMPLETED = "COMPLETED",
39
43
  FAILED = "FAILED"
@@ -58,11 +62,11 @@ type A_TYPES__Command_Constructor<T = A_Command> = new (...args: any[]) => T;
58
62
  /**
59
63
  * Command initialization type
60
64
  */
61
- type A_TYPES__Command_Init = any;
65
+ type A_TYPES__Command_Init = Record<string, any>;
62
66
  /**
63
67
  * Command serialized type
64
68
  */
65
- type A_TYPES__Command_Serialized<ResultType extends Record<string, any> = Record<string, any>> = {
69
+ type A_TYPES__Command_Serialized<ParamsType extends Record<string, any> = Record<string, any>, ResultType extends Record<string, any> = Record<string, any>> = {
66
70
  /**
67
71
  * Unique code of the command
68
72
  */
@@ -71,6 +75,10 @@ type A_TYPES__Command_Serialized<ResultType extends Record<string, any> = Record
71
75
  * Current status of the command
72
76
  */
73
77
  status: A_CONSTANTS__A_Command_Status;
78
+ /**
79
+ * Parameters used to invoke the command
80
+ */
81
+ params: ParamsType;
74
82
  /**
75
83
  * The time when the command was created
76
84
  */
@@ -121,7 +129,7 @@ type A_TYPES__CommandMeta = {
121
129
  }>;
122
130
  };
123
131
 
124
- declare class A_Command<InvokeType extends A_TYPES__Command_Init = A_TYPES__Command_Init, ResultType extends Record<string, any> = Record<string, any>, LifecycleEvents extends string = A_CONSTANTS__A_Command_Event> extends A_Entity<InvokeType, A_TYPES__Command_Serialized<ResultType>> {
132
+ declare class A_Command<InvokeType extends A_TYPES__Command_Init = A_TYPES__Command_Init, ResultType extends Record<string, any> = Record<string, any>, LifecycleEvents extends string | A_CONSTANTS__A_Command_Event = A_CONSTANTS__A_Command_Event> extends A_Entity<InvokeType, A_TYPES__Command_Serialized<InvokeType, ResultType>> {
125
133
  /**
126
134
  * Command Identifier that corresponds to the class name
127
135
  */
@@ -195,7 +203,7 @@ declare class A_Command<InvokeType extends A_TYPES__Command_Init = A_TYPES__Comm
195
203
  /**
196
204
  * Command invocation parameters
197
205
  */
198
- params: InvokeType | A_TYPES__Command_Serialized<ResultType> | string);
206
+ params: InvokeType | A_TYPES__Command_Serialized<InvokeType, ResultType> | string);
199
207
  init(): Promise<void>;
200
208
  compile(): Promise<void>;
201
209
  /**
@@ -243,13 +251,13 @@ declare class A_Command<InvokeType extends A_TYPES__Command_Init = A_TYPES__Comm
243
251
  *
244
252
  * @param serialized
245
253
  */
246
- fromJSON(serialized: A_TYPES__Command_Serialized<ResultType>): void;
254
+ fromJSON(serialized: A_TYPES__Command_Serialized<InvokeType, ResultType>): void;
247
255
  /**
248
256
  * Converts the Command instance to a plain object
249
257
  *
250
258
  * @returns
251
259
  */
252
- toJSON(): A_TYPES__Command_Serialized<ResultType>;
260
+ toJSON(): A_TYPES__Command_Serialized<InvokeType, ResultType>;
253
261
  }
254
262
 
255
263
  declare class A_CommandError extends A_Error {
@@ -768,6 +776,17 @@ declare class A_Memory<_MemoryType extends Record<string, any> = Record<string,
768
776
  * @param error
769
777
  */
770
778
  error(error: A_Error): Promise<void>;
779
+ /**
780
+ * Retrieves a value from the context memory
781
+ *
782
+ * @param key
783
+ * @returns
784
+ */
785
+ get<K extends keyof _MemoryType>(
786
+ /**
787
+ * Key to retrieve the value for
788
+ */
789
+ key: K): _MemoryType[K] | undefined;
771
790
  /**
772
791
  * Saves a value in the context memory
773
792
  *
package/dist/index.d.ts CHANGED
@@ -33,7 +33,11 @@ declare enum A_TYPES__CommandMetaKey {
33
33
  ABSTRACTIONS = "a-command-abstractions"
34
34
  }
35
35
  declare enum A_CONSTANTS__A_Command_Status {
36
+ CREATED = "CREATED",
37
+ INITIALIZATION = "INITIALIZATION",
36
38
  INITIALIZED = "INITIALIZED",
39
+ COMPILATION = "COMPILATION",
40
+ COMPILED = "COMPILED",
37
41
  IN_PROGRESS = "IN_PROGRESS",
38
42
  COMPLETED = "COMPLETED",
39
43
  FAILED = "FAILED"
@@ -58,11 +62,11 @@ type A_TYPES__Command_Constructor<T = A_Command> = new (...args: any[]) => T;
58
62
  /**
59
63
  * Command initialization type
60
64
  */
61
- type A_TYPES__Command_Init = any;
65
+ type A_TYPES__Command_Init = Record<string, any>;
62
66
  /**
63
67
  * Command serialized type
64
68
  */
65
- type A_TYPES__Command_Serialized<ResultType extends Record<string, any> = Record<string, any>> = {
69
+ type A_TYPES__Command_Serialized<ParamsType extends Record<string, any> = Record<string, any>, ResultType extends Record<string, any> = Record<string, any>> = {
66
70
  /**
67
71
  * Unique code of the command
68
72
  */
@@ -71,6 +75,10 @@ type A_TYPES__Command_Serialized<ResultType extends Record<string, any> = Record
71
75
  * Current status of the command
72
76
  */
73
77
  status: A_CONSTANTS__A_Command_Status;
78
+ /**
79
+ * Parameters used to invoke the command
80
+ */
81
+ params: ParamsType;
74
82
  /**
75
83
  * The time when the command was created
76
84
  */
@@ -121,7 +129,7 @@ type A_TYPES__CommandMeta = {
121
129
  }>;
122
130
  };
123
131
 
124
- declare class A_Command<InvokeType extends A_TYPES__Command_Init = A_TYPES__Command_Init, ResultType extends Record<string, any> = Record<string, any>, LifecycleEvents extends string = A_CONSTANTS__A_Command_Event> extends A_Entity<InvokeType, A_TYPES__Command_Serialized<ResultType>> {
132
+ declare class A_Command<InvokeType extends A_TYPES__Command_Init = A_TYPES__Command_Init, ResultType extends Record<string, any> = Record<string, any>, LifecycleEvents extends string | A_CONSTANTS__A_Command_Event = A_CONSTANTS__A_Command_Event> extends A_Entity<InvokeType, A_TYPES__Command_Serialized<InvokeType, ResultType>> {
125
133
  /**
126
134
  * Command Identifier that corresponds to the class name
127
135
  */
@@ -195,7 +203,7 @@ declare class A_Command<InvokeType extends A_TYPES__Command_Init = A_TYPES__Comm
195
203
  /**
196
204
  * Command invocation parameters
197
205
  */
198
- params: InvokeType | A_TYPES__Command_Serialized<ResultType> | string);
206
+ params: InvokeType | A_TYPES__Command_Serialized<InvokeType, ResultType> | string);
199
207
  init(): Promise<void>;
200
208
  compile(): Promise<void>;
201
209
  /**
@@ -243,13 +251,13 @@ declare class A_Command<InvokeType extends A_TYPES__Command_Init = A_TYPES__Comm
243
251
  *
244
252
  * @param serialized
245
253
  */
246
- fromJSON(serialized: A_TYPES__Command_Serialized<ResultType>): void;
254
+ fromJSON(serialized: A_TYPES__Command_Serialized<InvokeType, ResultType>): void;
247
255
  /**
248
256
  * Converts the Command instance to a plain object
249
257
  *
250
258
  * @returns
251
259
  */
252
- toJSON(): A_TYPES__Command_Serialized<ResultType>;
260
+ toJSON(): A_TYPES__Command_Serialized<InvokeType, ResultType>;
253
261
  }
254
262
 
255
263
  declare class A_CommandError extends A_Error {
@@ -768,6 +776,17 @@ declare class A_Memory<_MemoryType extends Record<string, any> = Record<string,
768
776
  * @param error
769
777
  */
770
778
  error(error: A_Error): Promise<void>;
779
+ /**
780
+ * Retrieves a value from the context memory
781
+ *
782
+ * @param key
783
+ * @returns
784
+ */
785
+ get<K extends keyof _MemoryType>(
786
+ /**
787
+ * Key to retrieve the value for
788
+ */
789
+ key: K): _MemoryType[K] | undefined;
771
790
  /**
772
791
  * Saves a value in the context memory
773
792
  *
package/dist/index.js CHANGED
@@ -92,7 +92,11 @@ var A_TYPES__CommandMetaKey = /* @__PURE__ */ ((A_TYPES__CommandMetaKey2) => {
92
92
  return A_TYPES__CommandMetaKey2;
93
93
  })(A_TYPES__CommandMetaKey || {});
94
94
  var A_CONSTANTS__A_Command_Status = /* @__PURE__ */ ((A_CONSTANTS__A_Command_Status2) => {
95
+ A_CONSTANTS__A_Command_Status2["CREATED"] = "CREATED";
96
+ A_CONSTANTS__A_Command_Status2["INITIALIZATION"] = "INITIALIZATION";
95
97
  A_CONSTANTS__A_Command_Status2["INITIALIZED"] = "INITIALIZED";
98
+ A_CONSTANTS__A_Command_Status2["COMPILATION"] = "COMPILATION";
99
+ A_CONSTANTS__A_Command_Status2["COMPILED"] = "COMPILED";
96
100
  A_CONSTANTS__A_Command_Status2["IN_PROGRESS"] = "IN_PROGRESS";
97
101
  A_CONSTANTS__A_Command_Status2["COMPLETED"] = "COMPLETED";
98
102
  A_CONSTANTS__A_Command_Status2["FAILED"] = "FAILED";
@@ -137,6 +141,15 @@ var A_Memory = class extends aConcept.A_Fragment {
137
141
  async error(error) {
138
142
  this._errors.add(error);
139
143
  }
144
+ /**
145
+ * Retrieves a value from the context memory
146
+ *
147
+ * @param key
148
+ * @returns
149
+ */
150
+ get(key) {
151
+ return this._memory.get(key);
152
+ }
140
153
  /**
141
154
  * Saves a value in the context memory
142
155
  *
@@ -275,18 +288,27 @@ var A_Command = class extends aConcept.A_Entity {
275
288
  // --------------------------------------------------------------------------
276
289
  // should create a new Task in DB with basic records
277
290
  async init() {
278
- this._status = "IN_PROGRESS" /* IN_PROGRESS */;
291
+ if (this._status !== "CREATED" /* CREATED */) {
292
+ return;
293
+ }
294
+ this._status = "INITIALIZATION" /* INITIALIZATION */;
279
295
  this._startTime = /* @__PURE__ */ new Date();
280
296
  if (!this.scope.isInheritedFrom(aConcept.A_Context.scope(this))) {
281
297
  this.scope.inherit(aConcept.A_Context.scope(this));
282
298
  }
283
299
  this.emit("init");
284
- return await this.call("init", this.scope);
300
+ await this.call("init", this.scope);
301
+ this._status = "INITIALIZED" /* INITIALIZED */;
285
302
  }
286
303
  // Should compile everything before execution
287
304
  async compile() {
305
+ if (this._status !== "INITIALIZED" /* INITIALIZED */) {
306
+ return;
307
+ }
308
+ this._status = "COMPILATION" /* COMPILATION */;
288
309
  this.emit("compile");
289
- return await this.call("compile", this.scope);
310
+ await this.call("compile", this.scope);
311
+ this._status = "COMPILED" /* COMPILED */;
290
312
  }
291
313
  /**
292
314
  * Executes the command logic.
@@ -295,8 +317,10 @@ var A_Command = class extends aConcept.A_Entity {
295
317
  try {
296
318
  await this.init();
297
319
  await this.compile();
298
- this.emit("execute");
299
- await this.call("execute", this.scope);
320
+ if (this._status === "COMPILED" /* COMPILED */) {
321
+ this.emit("execute");
322
+ await this.call("execute", this.scope);
323
+ }
300
324
  await this.complete();
301
325
  } catch (error) {
302
326
  await this.fail();
@@ -371,7 +395,7 @@ var A_Command = class extends aConcept.A_Entity {
371
395
  this._executionScope = new aConcept.A_Scope();
372
396
  this._executionScope.register(new A_Memory());
373
397
  this._params = newEntity;
374
- this._status = "INITIALIZED" /* INITIALIZED */;
398
+ this._status = "CREATED" /* CREATED */;
375
399
  }
376
400
  /**
377
401
  * Allows to convert serialized data to Command instance
@@ -397,7 +421,8 @@ var A_Command = class extends aConcept.A_Entity {
397
421
  memory.error(new aConcept.A_Error(err));
398
422
  });
399
423
  }
400
- this._status = serialized.status || "INITIALIZED" /* INITIALIZED */;
424
+ this._params = serialized.params;
425
+ this._status = serialized.status || "CREATED" /* CREATED */;
401
426
  }
402
427
  /**
403
428
  * Converts the Command instance to a plain object
@@ -409,6 +434,7 @@ var A_Command = class extends aConcept.A_Entity {
409
434
  ...super.toJSON(),
410
435
  code: this.code,
411
436
  status: this._status,
437
+ params: this._params,
412
438
  startedAt: this._startTime ? this._startTime.toISOString() : void 0,
413
439
  endedAt: this._endTime ? this._endTime.toISOString() : void 0,
414
440
  duration: this.duration,