@adaas/a-utils 0.1.13 → 0.1.15

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/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A_Feature, A_Inject, A_Scope, A_Concept, A_Container, A_Error, A_Component, A_Fragment, A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY, A_CommonHelper, A_FormatterHelper, A_Context, A_Entity, A_ScopeError, A_TypeGuards } from '@adaas/a-concept';
1
+ import { A_Inject, A_Scope, A_Feature, A_Concept, A_Container, A_Error, A_TypeGuards, A_Fragment, A_Component, A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY, A_CommonHelper, A_FormatterHelper, A_Context, A_IdentityHelper, A_Entity, A_ScopeError } from '@adaas/a-concept';
2
2
 
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -11,27 +11,346 @@ var __decorateClass = (decorators, target, key, kind) => {
11
11
  return result;
12
12
  };
13
13
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
14
+
15
+ // src/lib/A-Channel/A-Channel.constants.ts
16
+ var A_ChannelFeatures = /* @__PURE__ */ ((A_ChannelFeatures2) => {
17
+ A_ChannelFeatures2["onTimeout"] = "onTimeout";
18
+ A_ChannelFeatures2["onRetry"] = "onRetry";
19
+ A_ChannelFeatures2["onCircuitBreakerOpen"] = "onCircuitBreakerOpen";
20
+ A_ChannelFeatures2["onCache"] = "onCache";
21
+ A_ChannelFeatures2["onConnect"] = "onConnect";
22
+ A_ChannelFeatures2["onDisconnect"] = "onDisconnect";
23
+ A_ChannelFeatures2["onBeforeRequest"] = "onBeforeRequest";
24
+ A_ChannelFeatures2["onRequest"] = "onRequest";
25
+ A_ChannelFeatures2["onAfterRequest"] = "onAfterRequest";
26
+ A_ChannelFeatures2["onError"] = "onError";
27
+ A_ChannelFeatures2["onSend"] = "onSend";
28
+ A_ChannelFeatures2["onConsume"] = "onConsume";
29
+ return A_ChannelFeatures2;
30
+ })(A_ChannelFeatures || {});
31
+ var A_ChannelRequestStatuses = /* @__PURE__ */ ((A_ChannelRequestStatuses2) => {
32
+ A_ChannelRequestStatuses2["PENDING"] = "PENDING";
33
+ A_ChannelRequestStatuses2["SUCCESS"] = "SUCCESS";
34
+ A_ChannelRequestStatuses2["FAILED"] = "FAILED";
35
+ return A_ChannelRequestStatuses2;
36
+ })(A_ChannelRequestStatuses || {});
37
+
38
+ // src/lib/A-Channel/A-ChannelRequest.context.ts
39
+ var A_ChannelRequest = class extends A_Fragment {
40
+ constructor(params = {}) {
41
+ super();
42
+ this._errors = /* @__PURE__ */ new Set();
43
+ this._status = "PENDING" /* PENDING */;
44
+ this._params = params;
45
+ }
46
+ /**
47
+ * Returns the status of the request
48
+ */
49
+ get status() {
50
+ return this._status;
51
+ }
52
+ /**
53
+ * Returns the parameters of the request
54
+ */
55
+ get failed() {
56
+ return this._errors.size > 0;
57
+ }
58
+ /**
59
+ * Returns the Params of the Request
60
+ */
61
+ get params() {
62
+ return this._params;
63
+ }
64
+ /**
65
+ * Returns the Result of the Request
66
+ */
67
+ get data() {
68
+ return this._result;
69
+ }
70
+ get errors() {
71
+ return this._errors.size > 0 ? this._errors : void 0;
72
+ }
73
+ // ==========================================================
74
+ // ==================== Mutations ===========================
75
+ // ==========================================================
76
+ /**
77
+ * Adds an error to the context
78
+ *
79
+ * @param error
80
+ */
81
+ fail(error) {
82
+ this._status = "FAILED" /* FAILED */;
83
+ this._errors.add(error);
84
+ }
85
+ /**
86
+ * Sets the result of the request
87
+ *
88
+ * @param result
89
+ */
90
+ succeed(result) {
91
+ this._status = "SUCCESS" /* SUCCESS */;
92
+ this._result = result;
93
+ }
94
+ /**
95
+ * Serializes the context to a JSON object
96
+ *
97
+ * @returns
98
+ */
99
+ toJSON() {
100
+ return {
101
+ params: this._params,
102
+ result: this._result,
103
+ status: this._status,
104
+ errors: this.errors ? Array.from(this._errors).map((err) => err.toString()) : void 0
105
+ };
106
+ }
107
+ };
108
+
109
+ // src/lib/A-Channel/A-Channel.error.ts
14
110
  var A_ChannelError = class extends A_Error {
111
+ /**
112
+ * Channel Error allows to keep track of errors within a channel if something goes wrong
113
+ *
114
+ *
115
+ * @param originalError
116
+ * @param context
117
+ */
118
+ constructor(originalError, context) {
119
+ if (A_TypeGuards.isString(context))
120
+ super(originalError, context);
121
+ else
122
+ super(originalError);
123
+ if (context instanceof A_ChannelRequest)
124
+ this._context = context;
125
+ }
126
+ /***
127
+ * Returns Context of the error
128
+ */
129
+ get context() {
130
+ return this._context;
131
+ }
15
132
  };
133
+ // ==========================================================
134
+ // ==================== Error Types =========================
135
+ // ==========================================================
16
136
  A_ChannelError.MethodNotImplemented = "A-Channel Method Not Implemented";
17
137
 
138
+ // src/lib/A-Config/A-Config.constants.ts
139
+ var A_CONSTANTS__CONFIG_ENV_VARIABLES = {};
140
+ var A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY = [];
141
+
142
+ // src/lib/A-Config/A-Config.context.ts
143
+ var A_Config = class extends A_Fragment {
144
+ constructor(config) {
145
+ super({
146
+ name: "A_Config"
147
+ });
148
+ this.VARIABLES = /* @__PURE__ */ new Map();
149
+ this.DEFAULT_ALLOWED_TO_READ_PROPERTIES = [
150
+ ...A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY,
151
+ ...A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY
152
+ ];
153
+ this.config = A_CommonHelper.deepCloneAndMerge(config, {
154
+ strict: false,
155
+ defaults: {},
156
+ variables: A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY
157
+ });
158
+ this.CONFIG_PROPERTIES = this.config.variables ? this.config.variables : [];
159
+ this.config.variables.forEach((variable) => {
160
+ this.VARIABLES.set(
161
+ A_FormatterHelper.toUpperSnakeCase(variable),
162
+ this.config.defaults[variable]
163
+ );
164
+ });
165
+ }
166
+ /**
167
+ * This method is used to get the configuration property by name
168
+ *
169
+ * @param property
170
+ * @returns
171
+ */
172
+ get(property) {
173
+ if (this.CONFIG_PROPERTIES.includes(property) || this.DEFAULT_ALLOWED_TO_READ_PROPERTIES.includes(property) || !this.config.strict)
174
+ return this.VARIABLES.get(A_FormatterHelper.toUpperSnakeCase(property));
175
+ throw new Error("Property not exists or not allowed to read");
176
+ }
177
+ set(property, value) {
178
+ const array = Array.isArray(property) ? property : typeof property === "string" ? [{ property, value }] : Object.keys(property).map((key) => ({
179
+ property: key,
180
+ value: property[key]
181
+ }));
182
+ for (const { property: property2, value: value2 } of array) {
183
+ let targetValue = value2 ? value2 : this.config?.defaults ? this.config.defaults[property2] : void 0;
184
+ this.VARIABLES.set(A_FormatterHelper.toUpperSnakeCase(property2), targetValue);
185
+ }
186
+ }
187
+ };
188
+
189
+ // src/lib/A-Logger/A-Logger.component.ts
190
+ var A_Logger = class extends A_Component {
191
+ constructor(scope) {
192
+ super();
193
+ this.scope = scope;
194
+ this.colors = {
195
+ green: "32",
196
+ blue: "34",
197
+ red: "31",
198
+ yellow: "33",
199
+ gray: "90",
200
+ magenta: "35",
201
+ cyan: "36",
202
+ white: "37",
203
+ pink: "95"
204
+ };
205
+ this.config = this.scope.has(A_Config) ? this.scope.resolve(A_Config) : void 0;
206
+ }
207
+ get scopeLength() {
208
+ return this.scope.name.length;
209
+ }
210
+ compile(color, ...args) {
211
+ return [
212
+ `\x1B[${this.colors[color]}m[${this.scope.name}] |${this.getTime()}|`,
213
+ args.length > 1 ? `
214
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------` : "",
215
+ ...args.map((arg, i) => {
216
+ switch (true) {
217
+ case arg instanceof A_Error:
218
+ return this.compile_A_Error(arg);
219
+ case arg instanceof Error:
220
+ return this.compile_Error(arg);
221
+ case typeof arg === "object":
222
+ return JSON.stringify(arg, null, 2).replace(/\n/g, `
223
+ ${" ".repeat(this.scopeLength + 3)}| `);
224
+ default:
225
+ return String(
226
+ (i > 0 || args.length > 1 ? "\n" : "") + arg
227
+ ).replace(/\n/g, `
228
+ ${" ".repeat(this.scopeLength + 3)}| `);
229
+ }
230
+ }),
231
+ args.length > 1 ? `
232
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------\x1B[0m` : "\x1B[0m"
233
+ ];
234
+ }
235
+ get allowedToLog() {
236
+ return this.config ? this.config.get("CONFIG_VERBOSE") !== void 0 && this.config.get("CONFIG_VERBOSE") !== "false" && this.config.get("CONFIG_VERBOSE") !== false : true;
237
+ }
238
+ log(param1, ...args) {
239
+ if (!this.allowedToLog)
240
+ return;
241
+ if (typeof param1 === "string" && this.colors[param1]) {
242
+ console.log(...this.compile(param1, ...args));
243
+ return;
244
+ } else {
245
+ console.log(...this.compile("blue", param1, ...args));
246
+ }
247
+ }
248
+ warning(...args) {
249
+ if (!this.allowedToLog)
250
+ return;
251
+ console.log(...this.compile("yellow", ...args));
252
+ }
253
+ error(...args) {
254
+ if (this.config && this.config.get("CONFIG_IGNORE_ERRORS"))
255
+ return;
256
+ return console.log(...this.compile("red", ...args));
257
+ }
258
+ log_A_Error(error) {
259
+ const time = this.getTime();
260
+ console.log(`\x1B[31m[${this.scope.name}] |${time}| ERROR ${error.code}
261
+ ${" ".repeat(this.scopeLength + 3)}| ${error.message}
262
+ ${" ".repeat(this.scopeLength + 3)}| ${error.description}
263
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
264
+ ${" ".repeat(this.scopeLength + 3)}| ${error.stack?.split("\n").map((line, index) => index === 0 ? line : `${" ".repeat(this.scopeLength + 3)}| ${line}`).join("\n") || "No stack trace"}
265
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
266
+ \x1B[0m` + (error.originalError ? `\x1B[31m${" ".repeat(this.scopeLength + 3)}| Wrapped From ${error.originalError.message}
267
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
268
+ ${" ".repeat(this.scopeLength + 3)}| ${error.originalError.stack?.split("\n").map((line, index) => index === 0 ? line : `${" ".repeat(this.scopeLength + 3)}| ${line}`).join("\n") || "No stack trace"}
269
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
270
+ \x1B[0m` : "") + (error.link ? `\x1B[31m${" ".repeat(this.scopeLength + 3)}| Read in docs: ${error.link}
271
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
272
+ \x1B[0m` : ""));
273
+ }
274
+ compile_A_Error(error) {
275
+ this.getTime();
276
+ return `
277
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
278
+ ${" ".repeat(this.scopeLength + 3)}| Error: | ${error.code}
279
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
280
+ ${" ".repeat(this.scopeLength + 3)}|${" ".repeat(10)}| ${error.message}
281
+ ${" ".repeat(this.scopeLength + 3)}|${" ".repeat(10)}| ${error.description}
282
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
283
+ ${" ".repeat(this.scopeLength + 3)}| ${error.stack?.split("\n").map((line, index) => index === 0 ? line : `${" ".repeat(this.scopeLength + 3)}| ${line}`).join("\n") || "No stack trace"}
284
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------` + (error.originalError ? `${" ".repeat(this.scopeLength + 3)}| Wrapped From ${error.originalError.message}
285
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------
286
+ ${" ".repeat(this.scopeLength + 3)}| ${error.originalError.stack?.split("\n").map((line, index) => index === 0 ? line : `${" ".repeat(this.scopeLength + 3)}| ${line}`).join("\n") || "No stack trace"}
287
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------` : "") + (error.link ? `${" ".repeat(this.scopeLength + 3)}| Read in docs: ${error.link}
288
+ ${" ".repeat(this.scopeLength + 3)}|-------------------------------` : "");
289
+ }
290
+ compile_Error(error) {
291
+ return JSON.stringify({
292
+ name: error.name,
293
+ message: error.message,
294
+ stack: error.stack?.split("\n").map((line, index) => index === 0 ? line : `${" ".repeat(this.scopeLength + 3)}| ${line}`).join("\n")
295
+ }, null, 2).replace(/\n/g, `
296
+ ${" ".repeat(this.scopeLength + 3)}| `).replace(/\\n/g, "\n");
297
+ }
298
+ getTime() {
299
+ const now = /* @__PURE__ */ new Date();
300
+ const minutes = String(now.getMinutes()).padStart(2, "0");
301
+ const seconds = String(now.getSeconds()).padStart(2, "0");
302
+ const milliseconds = String(now.getMilliseconds()).padStart(4, "0");
303
+ return `${minutes}:${seconds}:${milliseconds}`;
304
+ }
305
+ };
306
+ A_Logger = __decorateClass([
307
+ __decorateParam(0, A_Inject(A_Scope))
308
+ ], A_Logger);
309
+
18
310
  // src/lib/A-Channel/A-Channel.component.ts
19
311
  var A_Channel = class extends A_Component {
312
+ /**
313
+ * Creates a new A_Channel instance.
314
+ *
315
+ * The channel must be registered with A_Context before use:
316
+ * ```typescript
317
+ * const channel = new A_Channel();
318
+ * A_Context.root.register(channel);
319
+ * ```
320
+ */
20
321
  constructor() {
21
- super(...arguments);
322
+ super();
22
323
  /**
23
- * Indicates whether the channel is processing requests
324
+ * Indicates whether the channel is currently processing requests.
325
+ * This flag is managed automatically during request/send operations.
326
+ *
327
+ * @readonly
24
328
  */
25
329
  this._processing = false;
330
+ /**
331
+ * Internal cache storage for channel-specific data.
332
+ * Can be used by custom implementations for caching responses,
333
+ * connection pools, or other channel-specific state.
334
+ *
335
+ * @protected
336
+ */
337
+ this._cache = /* @__PURE__ */ new Map();
26
338
  }
27
339
  /**
28
- * Indicates whether the channel is processing requests
29
- */
340
+ * Indicates whether the channel is currently processing requests.
341
+ *
342
+ * @returns {boolean} True if channel is processing, false otherwise
343
+ */
30
344
  get processing() {
31
345
  return this._processing;
32
346
  }
33
347
  /**
34
- * Indicates whether the channel is connected
348
+ * Promise that resolves when the channel is fully initialized.
349
+ *
350
+ * Automatically calls the onConnect lifecycle hook if not already called.
351
+ * This ensures the channel is ready for communication operations.
352
+ *
353
+ * @returns {Promise<void>} Promise that resolves when initialization is complete
35
354
  */
36
355
  get initialize() {
37
356
  if (!this._initialized) {
@@ -39,48 +358,259 @@ var A_Channel = class extends A_Component {
39
358
  }
40
359
  return this._initialized;
41
360
  }
361
+ async onConnect(...args) {
362
+ }
363
+ async onDisconnect(...args) {
364
+ }
365
+ async onBeforeRequest(...args) {
366
+ }
367
+ async onRequest(...args) {
368
+ }
369
+ async onAfterRequest(...args) {
370
+ }
371
+ async onError(...args) {
372
+ }
373
+ async onSend(...args) {
374
+ }
375
+ // ==========================================================
376
+ // ================= Public API Methods ===================
377
+ // ==========================================================
42
378
  /**
43
- * Initializes the channel before use
379
+ * Initializes the channel by calling the onConnect lifecycle hook.
380
+ *
381
+ * This method is called automatically when accessing the `initialize` property.
382
+ * You can also call it manually if needed.
383
+ *
384
+ * @returns {Promise<void>} Promise that resolves when connection is established
44
385
  */
45
386
  async connect() {
46
- throw new A_ChannelError(
47
- A_ChannelError.MethodNotImplemented,
48
- `The connect method is not implemented in ${this.constructor.name} channel. This method is required to initialize the channel before use. So please implement it in the derived class.`
49
- );
387
+ await this.call("onConnect" /* onConnect */);
50
388
  }
51
389
  /**
52
- * Allows to send a request through the channel
53
- *
54
- * @param req - The request parameters
55
- * @returns The response from the channel
390
+ * Disconnects the channel by calling the onDisconnect lifecycle hook.
391
+ *
392
+ * Use this method to properly cleanup resources when the channel is no longer needed.
393
+ *
394
+ * @returns {Promise<void>} Promise that resolves when cleanup is complete
395
+ */
396
+ async disconnect() {
397
+ await this.call("onDisconnect" /* onDisconnect */);
398
+ }
399
+ /**
400
+ * Sends a request and waits for a response (Request/Response pattern).
401
+ *
402
+ * This method follows the complete request lifecycle:
403
+ * 1. Ensures channel is initialized
404
+ * 2. Creates request scope and context
405
+ * 3. Calls onBeforeRequest hook
406
+ * 4. Calls onRequest hook (main processing)
407
+ * 5. Calls onAfterRequest hook
408
+ * 6. Returns the response context
409
+ *
410
+ * If any step fails, the onError hook is called and the error is captured
411
+ * in the returned context.
412
+ *
413
+ * @template _ParamsType The type of request parameters
414
+ * @template _ResultType The type of response data
415
+ * @param params The request parameters
416
+ * @returns {Promise<A_ChannelRequest<_ParamsType, _ResultType>>} Request context with response
417
+ *
418
+ * @example
419
+ * ```typescript
420
+ * // Basic usage
421
+ * const response = await channel.request({ action: 'getData', id: 123 });
422
+ *
423
+ * // Typed usage
424
+ * interface UserRequest { userId: string; }
425
+ * interface UserResponse { name: string; email: string; }
426
+ *
427
+ * const userResponse = await channel.request<UserRequest, UserResponse>({
428
+ * userId: 'user-123'
429
+ * });
430
+ *
431
+ * if (!userResponse.failed) {
432
+ * console.log('User:', userResponse.data.name);
433
+ * }
434
+ * ```
56
435
  */
57
436
  async request(params) {
58
- throw new A_ChannelError(
59
- A_ChannelError.MethodNotImplemented,
60
- `The request method is not implemented in ${this.constructor.name} channel.`
61
- );
437
+ await this.initialize;
438
+ this._processing = true;
439
+ const requestScope = new A_Scope({
440
+ name: `a-channel@scope:request:${A_IdentityHelper.generateTimeId()}`
441
+ });
442
+ const context = new A_ChannelRequest(params);
443
+ try {
444
+ requestScope.inherit(A_Context.scope(this));
445
+ requestScope.register(context);
446
+ await this.call("onBeforeRequest" /* onBeforeRequest */, requestScope);
447
+ await this.call("onRequest" /* onRequest */, requestScope);
448
+ await this.call("onAfterRequest" /* onAfterRequest */, requestScope);
449
+ this._processing = false;
450
+ return context;
451
+ } catch (error) {
452
+ this._processing = false;
453
+ const channelError = new A_ChannelError(error);
454
+ context.fail(channelError);
455
+ await this.call("onError" /* onError */, requestScope);
456
+ return context;
457
+ }
62
458
  }
63
459
  /**
64
- * Uses for Fire-and-Forget messaging through the channel
460
+ * Sends a fire-and-forget message (Send pattern).
461
+ *
462
+ * This method is used for one-way communication where no response is expected:
463
+ * - Event broadcasting
464
+ * - Notification sending
465
+ * - Message queuing
466
+ * - Logging operations
467
+ *
468
+ * The method follows this lifecycle:
469
+ * 1. Ensures channel is initialized
470
+ * 2. Creates send scope and context
471
+ * 3. Calls onSend hook
472
+ * 4. Completes without returning data
473
+ *
474
+ * If the operation fails, the onError hook is called but no error is thrown
475
+ * to the caller (fire-and-forget semantics).
65
476
  *
66
- * @param message - can be of any type depending on the channel implementation
477
+ * @template _ParamsType The type of message parameters
478
+ * @param message The message to send
479
+ * @returns {Promise<void>} Promise that resolves when send is complete
480
+ *
481
+ * @example
482
+ * ```typescript
483
+ * // Send notification
484
+ * await channel.send({
485
+ * type: 'user.login',
486
+ * userId: 'user-123',
487
+ * timestamp: new Date().toISOString()
488
+ * });
489
+ *
490
+ * // Send to message queue
491
+ * await channel.send({
492
+ * queue: 'email-queue',
493
+ * payload: {
494
+ * to: 'user@example.com',
495
+ * subject: 'Welcome!',
496
+ * body: 'Welcome to our service!'
497
+ * }
498
+ * });
499
+ * ```
67
500
  */
68
501
  async send(message) {
69
- throw new A_ChannelError(
70
- A_ChannelError.MethodNotImplemented,
71
- `The send method is not implemented in ${this.constructor.name} channel.`
72
- );
502
+ await this.initialize;
503
+ this._processing = true;
504
+ const requestScope = new A_Scope({
505
+ name: `a-channel@scope:send:${A_IdentityHelper.generateTimeId()}`
506
+ });
507
+ const context = new A_ChannelRequest(message);
508
+ try {
509
+ requestScope.inherit(A_Context.scope(this));
510
+ requestScope.register(context);
511
+ await this.call("onSend" /* onSend */, requestScope);
512
+ this._processing = false;
513
+ } catch (error) {
514
+ this._processing = false;
515
+ const channelError = new A_ChannelError(error);
516
+ context.fail(channelError);
517
+ await this.call("onError" /* onError */, requestScope);
518
+ }
519
+ }
520
+ /**
521
+ * @deprecated This method is deprecated and will be removed in future versions.
522
+ * Use request() or send() methods instead depending on your communication pattern.
523
+ *
524
+ * For request/response pattern: Use request()
525
+ * For fire-and-forget pattern: Use send()
526
+ * For consumer patterns: Implement custom consumer logic using request() in a loop
527
+ */
528
+ async consume() {
529
+ await this.initialize;
530
+ this._processing = true;
531
+ const requestScope = new A_Scope({ name: `a-channel@scope:consume:${A_IdentityHelper.generateTimeId()}` });
532
+ const context = new A_ChannelRequest();
533
+ try {
534
+ requestScope.inherit(A_Context.scope(this));
535
+ requestScope.register(context);
536
+ await this.call("onConsume" /* onConsume */, requestScope);
537
+ this._processing = false;
538
+ return context;
539
+ } catch (error) {
540
+ this._processing = false;
541
+ const channelError = new A_ChannelError(error);
542
+ context.fail(channelError);
543
+ await this.call("onError" /* onError */, requestScope);
544
+ return context;
545
+ }
73
546
  }
74
547
  };
75
548
  __decorateClass([
76
- A_Feature.Define()
77
- ], A_Channel.prototype, "connect", 1);
549
+ A_Feature.Extend({
550
+ name: "onConnect" /* onConnect */
551
+ })
552
+ ], A_Channel.prototype, "onConnect", 1);
553
+ __decorateClass([
554
+ A_Feature.Extend({
555
+ name: "onDisconnect" /* onDisconnect */
556
+ })
557
+ ], A_Channel.prototype, "onDisconnect", 1);
558
+ __decorateClass([
559
+ A_Feature.Extend({
560
+ name: "onBeforeRequest" /* onBeforeRequest */
561
+ })
562
+ ], A_Channel.prototype, "onBeforeRequest", 1);
563
+ __decorateClass([
564
+ A_Feature.Extend({
565
+ name: "onRequest" /* onRequest */
566
+ })
567
+ ], A_Channel.prototype, "onRequest", 1);
568
+ __decorateClass([
569
+ A_Feature.Extend({
570
+ name: "onAfterRequest" /* onAfterRequest */
571
+ })
572
+ ], A_Channel.prototype, "onAfterRequest", 1);
78
573
  __decorateClass([
79
- A_Feature.Define()
80
- ], A_Channel.prototype, "request", 1);
574
+ A_Feature.Extend({
575
+ name: "onError" /* onError */
576
+ })
577
+ ], A_Channel.prototype, "onError", 1);
81
578
  __decorateClass([
82
- A_Feature.Define()
83
- ], A_Channel.prototype, "send", 1);
579
+ A_Feature.Extend({
580
+ name: "onSend" /* onSend */
581
+ })
582
+ ], A_Channel.prototype, "onSend", 1);
583
+ var HttpChannel = class extends A_Channel {
584
+ };
585
+ var PollyspotChannel = class extends HttpChannel {
586
+ constructor() {
587
+ super();
588
+ this.baseUrl = "https://pollyspot.example.com";
589
+ }
590
+ };
591
+ var GlobalErrorhandler = class extends A_Component {
592
+ async handleError(context, logger, config) {
593
+ }
594
+ async anotherError(context, logger, config) {
595
+ }
596
+ };
597
+ __decorateClass([
598
+ A_Feature.Extend({
599
+ name: "onError" /* onError */,
600
+ scope: [PollyspotChannel]
601
+ }),
602
+ __decorateParam(0, A_Inject(A_ChannelRequest)),
603
+ __decorateParam(1, A_Inject(A_Logger)),
604
+ __decorateParam(2, A_Inject(A_Config))
605
+ ], GlobalErrorhandler.prototype, "handleError", 1);
606
+ __decorateClass([
607
+ A_Feature.Extend({
608
+ name: "onError" /* onError */
609
+ }),
610
+ __decorateParam(0, A_Inject(A_ChannelRequest)),
611
+ __decorateParam(1, A_Inject(A_Logger)),
612
+ __decorateParam(2, A_Inject(A_Config))
613
+ ], GlobalErrorhandler.prototype, "anotherError", 1);
84
614
 
85
615
  // src/lib/A-Command/A-Command.constants.ts
86
616
  var A_TYPES__CommandMetaKey = /* @__PURE__ */ ((A_TYPES__CommandMetaKey2) => {
@@ -471,176 +1001,6 @@ var A_Command = class extends A_Entity {
471
1001
  }
472
1002
  }
473
1003
  };
474
-
475
- // src/lib/A-Config/A-Config.constants.ts
476
- var A_CONSTANTS__CONFIG_ENV_VARIABLES = {};
477
- var A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY = [];
478
-
479
- // src/lib/A-Config/A-Config.context.ts
480
- var A_Config = class extends A_Fragment {
481
- constructor(config) {
482
- super({
483
- name: "A_Config"
484
- });
485
- this.VARIABLES = /* @__PURE__ */ new Map();
486
- this.DEFAULT_ALLOWED_TO_READ_PROPERTIES = [
487
- ...A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY,
488
- ...A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY
489
- ];
490
- this.config = A_CommonHelper.deepCloneAndMerge(config, {
491
- strict: false,
492
- defaults: {},
493
- variables: A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY
494
- });
495
- this.CONFIG_PROPERTIES = this.config.variables ? this.config.variables : [];
496
- this.config.variables.forEach((variable) => {
497
- this.VARIABLES.set(
498
- A_FormatterHelper.toUpperSnakeCase(variable),
499
- this.config.defaults[variable]
500
- );
501
- });
502
- }
503
- /**
504
- * This method is used to get the configuration property by name
505
- *
506
- * @param property
507
- * @returns
508
- */
509
- get(property) {
510
- if (this.CONFIG_PROPERTIES.includes(property) || this.DEFAULT_ALLOWED_TO_READ_PROPERTIES.includes(property) || !this.config.strict)
511
- return this.VARIABLES.get(A_FormatterHelper.toUpperSnakeCase(property));
512
- throw new Error("Property not exists or not allowed to read");
513
- }
514
- set(property, value) {
515
- const array = Array.isArray(property) ? property : typeof property === "string" ? [{ property, value }] : Object.keys(property).map((key) => ({
516
- property: key,
517
- value: property[key]
518
- }));
519
- for (const { property: property2, value: value2 } of array) {
520
- let targetValue = value2 ? value2 : this.config?.defaults ? this.config.defaults[property2] : void 0;
521
- this.VARIABLES.set(A_FormatterHelper.toUpperSnakeCase(property2), targetValue);
522
- }
523
- }
524
- };
525
- var A_Logger = class extends A_Component {
526
- constructor(scope) {
527
- super();
528
- this.scope = scope;
529
- this.colors = {
530
- green: "32",
531
- blue: "34",
532
- red: "31",
533
- yellow: "33",
534
- gray: "90",
535
- magenta: "35",
536
- cyan: "36",
537
- white: "37",
538
- pink: "95"
539
- };
540
- this.config = this.scope.has(A_Config) ? this.scope.resolve(A_Config) : void 0;
541
- }
542
- get scopeLength() {
543
- return this.scope.name.length;
544
- }
545
- compile(color, ...args) {
546
- return [
547
- `\x1B[${this.colors[color]}m[${this.scope.name}] |${this.getTime()}|`,
548
- args.length > 1 ? `
549
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------` : "",
550
- ...args.map((arg, i) => {
551
- switch (true) {
552
- case arg instanceof A_Error:
553
- return this.compile_A_Error(arg);
554
- case arg instanceof Error:
555
- return this.compile_Error(arg);
556
- case typeof arg === "object":
557
- return JSON.stringify(arg, null, 2).replace(/\n/g, `
558
- ${" ".repeat(this.scopeLength + 3)}| `);
559
- default:
560
- return String(
561
- (i > 0 || args.length > 1 ? "\n" : "") + arg
562
- ).replace(/\n/g, `
563
- ${" ".repeat(this.scopeLength + 3)}| `);
564
- }
565
- }),
566
- args.length > 1 ? `
567
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------\x1B[0m` : "\x1B[0m"
568
- ];
569
- }
570
- get allowedToLog() {
571
- return this.config ? this.config.get("CONFIG_VERBOSE") !== void 0 && this.config.get("CONFIG_VERBOSE") !== "false" && this.config.get("CONFIG_VERBOSE") !== false : true;
572
- }
573
- log(param1, ...args) {
574
- if (!this.allowedToLog)
575
- return;
576
- if (typeof param1 === "string" && this.colors[param1]) {
577
- console.log(...this.compile(param1, ...args));
578
- return;
579
- } else {
580
- console.log(...this.compile("blue", param1, ...args));
581
- }
582
- }
583
- warning(...args) {
584
- if (!this.allowedToLog)
585
- return;
586
- console.log(...this.compile("yellow", ...args));
587
- }
588
- error(...args) {
589
- if (this.config && this.config.get("CONFIG_IGNORE_ERRORS"))
590
- return;
591
- return console.log(...this.compile("red", ...args));
592
- }
593
- log_A_Error(error) {
594
- const time = this.getTime();
595
- console.log(`\x1B[31m[${this.scope.name}] |${time}| ERROR ${error.code}
596
- ${" ".repeat(this.scopeLength + 3)}| ${error.message}
597
- ${" ".repeat(this.scopeLength + 3)}| ${error.description}
598
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------
599
- ${" ".repeat(this.scopeLength + 3)}| ${error.stack?.split("\n").map((line, index) => index === 0 ? line : `${" ".repeat(this.scopeLength + 3)}| ${line}`).join("\n") || "No stack trace"}
600
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------
601
- \x1B[0m` + (error.originalError ? `\x1B[31m${" ".repeat(this.scopeLength + 3)}| Wrapped From ${error.originalError.message}
602
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------
603
- ${" ".repeat(this.scopeLength + 3)}| ${error.originalError.stack?.split("\n").map((line, index) => index === 0 ? line : `${" ".repeat(this.scopeLength + 3)}| ${line}`).join("\n") || "No stack trace"}
604
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------
605
- \x1B[0m` : "") + (error.link ? `\x1B[31m${" ".repeat(this.scopeLength + 3)}| Read in docs: ${error.link}
606
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------
607
- \x1B[0m` : ""));
608
- }
609
- compile_A_Error(error) {
610
- this.getTime();
611
- return `
612
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------
613
- ${" ".repeat(this.scopeLength + 3)}| Error: | ${error.code}
614
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------
615
- ${" ".repeat(this.scopeLength + 3)}|${" ".repeat(10)}| ${error.message}
616
- ${" ".repeat(this.scopeLength + 3)}|${" ".repeat(10)}| ${error.description}
617
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------
618
- ${" ".repeat(this.scopeLength + 3)}| ${error.stack?.split("\n").map((line, index) => index === 0 ? line : `${" ".repeat(this.scopeLength + 3)}| ${line}`).join("\n") || "No stack trace"}
619
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------` + (error.originalError ? `${" ".repeat(this.scopeLength + 3)}| Wrapped From ${error.originalError.message}
620
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------
621
- ${" ".repeat(this.scopeLength + 3)}| ${error.originalError.stack?.split("\n").map((line, index) => index === 0 ? line : `${" ".repeat(this.scopeLength + 3)}| ${line}`).join("\n") || "No stack trace"}
622
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------` : "") + (error.link ? `${" ".repeat(this.scopeLength + 3)}| Read in docs: ${error.link}
623
- ${" ".repeat(this.scopeLength + 3)}|-------------------------------` : "");
624
- }
625
- compile_Error(error) {
626
- return JSON.stringify({
627
- name: error.name,
628
- message: error.message,
629
- stack: error.stack?.split("\n").map((line, index) => index === 0 ? line : `${" ".repeat(this.scopeLength + 3)}| ${line}`).join("\n")
630
- }, null, 2).replace(/\n/g, `
631
- ${" ".repeat(this.scopeLength + 3)}| `).replace(/\\n/g, "\n");
632
- }
633
- getTime() {
634
- const now = /* @__PURE__ */ new Date();
635
- const minutes = String(now.getMinutes()).padStart(2, "0");
636
- const seconds = String(now.getSeconds()).padStart(2, "0");
637
- const milliseconds = String(now.getMilliseconds()).padStart(4, "0");
638
- return `${minutes}:${seconds}:${milliseconds}`;
639
- }
640
- };
641
- A_Logger = __decorateClass([
642
- __decorateParam(0, A_Inject(A_Scope))
643
- ], A_Logger);
644
1004
  var A_FSPolyfillClass = class {
645
1005
  constructor(logger) {
646
1006
  this.logger = logger;
@@ -1787,6 +2147,6 @@ var A_Schedule = class extends A_Component {
1787
2147
  }
1788
2148
  };
1789
2149
 
1790
- export { A_CONSTANTS_A_Command_Features, A_CONSTANTS__A_Command_Status, A_CONSTANTS__CONFIG_ENV_VARIABLES, A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY, A_Channel, A_ChannelError, A_Command, A_CommandError, A_Config, A_ConfigError, A_ConfigLoader, A_Deferred, A_Logger, A_Manifest, A_ManifestChecker, A_ManifestError, A_Memory, A_Polyfill, A_Schedule, A_ScheduleObject, A_TYPES__CommandMetaKey, A_TYPES__ConfigFeature, ConfigReader, ENVConfigReader, FileConfigReader };
2150
+ export { A_CONSTANTS_A_Command_Features, A_CONSTANTS__A_Command_Status, A_CONSTANTS__CONFIG_ENV_VARIABLES, A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY, A_Channel, A_ChannelError, A_ChannelFeatures, A_ChannelRequest, A_ChannelRequestStatuses, A_Command, A_CommandError, A_Config, A_ConfigError, A_ConfigLoader, A_Deferred, A_Logger, A_Manifest, A_ManifestChecker, A_ManifestError, A_Memory, A_Polyfill, A_Schedule, A_ScheduleObject, A_TYPES__CommandMetaKey, A_TYPES__ConfigFeature, ConfigReader, ENVConfigReader, FileConfigReader };
1791
2151
  //# sourceMappingURL=index.mjs.map
1792
2152
  //# sourceMappingURL=index.mjs.map