syntropylog 0.9.19 → 0.10.0
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/CHANGELOG.md +18 -0
- package/README.md +8 -18
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +76 -1278
- package/dist/index.mjs +1 -1
- package/dist/testing/index.cjs +1 -107
- package/dist/testing/index.d.ts +8 -581
- package/dist/testing/index.mjs +2 -107
- package/dist/types/SyntropyLog.d.ts +0 -2
- package/dist/types/config/Result.d.ts +38 -0
- package/dist/types/config/config.validator.d.ts +17 -0
- package/dist/types/config/validators.d.ts +23 -0
- package/dist/types/config.d.ts +3 -25
- package/dist/types/config.schema.d.ts +53 -1232
- package/dist/types/core/LifecycleManager.d.ts +0 -3
- package/dist/types/internal-types.d.ts +0 -48
- package/dist/types/logger/Logger.d.ts +3 -2
- package/dist/types/logger/transports/ConsoleTransport.d.ts +1 -1
- package/dist/types/logger/transports/Transport.d.ts +2 -2
- package/dist/types/masking/MaskingEngine.d.ts +5 -10
- package/dist/types/serialization/SerializationManager.d.ts +4 -1
- package/dist/types/serialization/SerializationPipeline.d.ts +13 -2
- package/dist/types/serialization/pipeline/HygieneStep.d.ts +2 -2
- package/dist/types/serialization/pipeline/SanitizationStep.d.ts +1 -1
- package/dist/types/serialization/pipeline/SerializationStep.d.ts +5 -1
- package/dist/types/serialization/pipeline/TimeoutStep.d.ts +1 -1
- package/dist/types/serialization/types.d.ts +2 -2
- package/dist/types/testing/index.d.ts +0 -1
- package/dist/types/type-exports.d.ts +0 -1
- package/dist/types/types.d.ts +2 -2
- package/package.json +5 -18
- package/dist/types/redis/BeaconRedis.d.ts +0 -266
- package/dist/types/redis/BeaconRedisMock.d.ts +0 -181
- package/dist/types/redis/IBeaconRedis.d.ts +0 -447
- package/dist/types/redis/RedisCommandExecutor.d.ts +0 -310
- package/dist/types/redis/RedisConnectionManager.d.ts +0 -108
- package/dist/types/redis/RedisManager.d.ts +0 -28
- package/dist/types/redis/index.d.ts +0 -5
- package/dist/types/redis/redis.types.d.ts +0 -43
- package/dist/types/redis/redisCommandLogging.d.ts +0 -38
- package/dist/types/testing/BeaconRedisMock.d.ts +0 -61
- package/dist/types/utils/createFailingClient.d.ts +0 -19
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- refactor: replace valibot with zero-dependency ROP config validator.
|
|
8
|
+
This change significantly reduces the bundle size by eliminating the valibot dependency (~30kB raw reduction) and introduces a robust, functional configuration validation system with 100% test coverage.
|
|
9
|
+
|
|
10
|
+
## 0.9.20
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- Optimization and Security Refactor:
|
|
15
|
+
- Migrated configuration validation from Zod to Valibot to significantly reduce bundle size.
|
|
16
|
+
- Removed `ConcurrencyLimiter` and `logConcurrencyLimit` to simplify pipeline processing and eliminate async bottlenecks.
|
|
17
|
+
- Restored `optionalChalk` implementation for built-in visual console transports.
|
|
18
|
+
- Achieved 100% global test coverage.
|
|
19
|
+
- Implemented ReDoS (Catastrophic Backtracking) defenses in `MaskingEngine` with synchronous length limits on property keys.
|
|
20
|
+
|
|
3
21
|
## 0.9.19
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -16,8 +16,8 @@
|
|
|
16
16
|
<a href="https://www.npmjs.com/package/syntropylog"><img src="https://img.shields.io/npm/v/syntropylog.svg" alt="NPM Version"></a>
|
|
17
17
|
<a href="https://github.com/Syntropysoft/SyntropyLog/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/syntropylog.svg" alt="License"></a>
|
|
18
18
|
<a href="https://github.com/Syntropysoft/SyntropyLog/actions/workflows/ci.yaml"><img src="https://github.com/Syntropysoft/SyntropyLog/actions/workflows/ci.yaml/badge.svg" alt="CI Status"></a>
|
|
19
|
-
<a href="#"><img src="https://img.shields.io/badge/coverage-
|
|
20
|
-
<a href="#"><img src="https://img.shields.io/badge/status-v0.
|
|
19
|
+
<a href="#"><img src="https://img.shields.io/badge/coverage-95.13%25-brightgreen" alt="Test Coverage"></a>
|
|
20
|
+
<a href="#"><img src="https://img.shields.io/badge/status-v0.10.0-brightgreen.svg" alt="Version 0.10.0"></a>
|
|
21
21
|
<a href="https://socket.dev/npm/package/syntropylog"><img src="https://socket.dev/api/badge/npm/package/syntropylog" alt="Socket Badge"></a>
|
|
22
22
|
</p>
|
|
23
23
|
|
|
@@ -57,7 +57,7 @@ We ship with `sideEffects: false` and ESM so bundlers (Vite, Rollup, webpack, es
|
|
|
57
57
|
|
|
58
58
|
Traditional loggers (and even modern ones) share a common weakness: **serialization is a blocking operation**. If you log a massive, deeply nested, or circular object, the Node.js Event Loop stops. Your API stops responding. Your service might even crash with a `TypeError`.
|
|
59
59
|
|
|
60
|
-
SyntropyLog v0.
|
|
60
|
+
SyntropyLog v0.10.0 introduces the **Log Resilience Engine**, making your application immune to "Death by Log":
|
|
61
61
|
|
|
62
62
|
1. **Event Loop Protection**: Every serialization step is wrapped in a mandatory timeout (default: **50ms**). If serialization takes too long, it is aborted via `Promise.race`, and a safe subset of the data is logged instead. Your app keeps running.
|
|
63
63
|
2. **Circular Reference Immunity**: Built-in hygiene automatically detects and neutralizes circular references. No more `TypeError: Converting circular structure to JSON`.
|
|
@@ -447,7 +447,10 @@ await syntropyLog.init({
|
|
|
447
447
|
|
|
448
448
|
> **Silent Observer guarantee**: if the masking engine fails for any reason, it returns the original object and the application keeps running — it never throws.
|
|
449
449
|
|
|
450
|
-
**Performance**: Built-in rules use synchronous regex matching (safe, known patterns). Custom rules
|
|
450
|
+
**Performance**: Built-in rules use synchronous regex matching (safe, known patterns). Custom rules use the same synchronous engine for maximum speed.
|
|
451
|
+
|
|
452
|
+
> ⚠️ **Security Warning (Custom Rules)**
|
|
453
|
+
> Node.js regular expressions execute synchronously on the main thread. To prevent Event Loop blocking, SyntropyLog automatically skips evaluating any JSON keys longer than 256 characters. However, when writing **Custom Masking Rules**, it is your responsibility to write optimized, ReDoS-safe regular expressions. A catastrophic backtracking pattern in a custom rule could temporarily freeze your application if triggered by a specifically crafted payload.
|
|
451
454
|
|
|
452
455
|
---
|
|
453
456
|
|
|
@@ -601,20 +604,7 @@ const dbTransport = new UniversalAdapter({
|
|
|
601
604
|
|
|
602
605
|
---
|
|
603
606
|
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
SyntropyLog goes deep. Explore our specialized guides:
|
|
607
|
-
|
|
608
|
-
| | Guide | Description |
|
|
609
|
-
| :--- | :--- | :--- |
|
|
610
|
-
| 🔧 | [Master Configuration](./docs/configuration.md) | Every option explained: `loggingMatrix`, `serializers`, masking, context. |
|
|
611
|
-
| 💾 | [Universal Persistence](./docs/persistence.md) | Map logs to any DB (SQL/NoSQL) with pure JSON, zero dependencies. |
|
|
612
|
-
| 🧬 | [Serialization & Resiliency](./docs/serialization.md) | Circular reference protection, automated timeouts, and the Safe Pipeline. |
|
|
613
|
-
| ⚙️ | [Middleware & Frameworks](./docs/middleware.md) | Integration patterns for Express, NestJS, and more via Universal Contracts. |
|
|
614
|
-
| 🏢 | [Enterprise Patterns](./docs/enterprise.md) | Scalable architectures, ELK, Kubernetes, and compliance. |
|
|
615
|
-
| 🧪 | [Testing Strategy](./docs/testing.md) | Zero-boilerplate mocking with `SyntropyLogMock`. |
|
|
616
|
-
| 🎭 | [Core Philosophy](./docs/philosophy.md) | The "Silent Observer" principle and error handling strategy. |
|
|
617
|
-
| 📦 | [Examples](https://github.com/Syntropysoft/syntropylog-examples) | Real integrations with Express, Redis, Kafka, and more. |
|
|
607
|
+
---
|
|
618
608
|
|
|
619
609
|
---
|
|
620
610
|
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("events"),t=require("zod"),i=require("node:async_hooks"),n=require("crypto"),r=require("node:util"),s=require("flatted"),a=require("redis");function o(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(i){if("default"!==i){var n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return e[i]}})}}),t.default=e,Object.freeze(t)}var c=o(r);const l={audit:70,fatal:60,error:50,warn:40,info:30,debug:20,trace:10,silent:0};class u{constructor(e={}){this.level=e.level??"info",this.name=e.name??this.constructor.name,this.formatter=e?.formatter,this.sanitizationEngine=e?.sanitizationEngine}isLevelEnabled(e){return l[e]>=l[this.level]}async flush(){return Promise.resolve()}}var h;!function(e){e.CREDIT_CARD="credit_card",e.SSN="ssn",e.EMAIL="email",e.PHONE="phone",e.PASSWORD="password",e.TOKEN="token",e.CUSTOM="custom"}(h||(h={}));class g{constructor(e){if(this.rules=[],this.initialized=!1,this.maskChar=e?.maskChar||"*",this.preserveLength=e?.preserveLength??!0,this.regexTimeoutMs=e?.regexTimeoutMs??100,!1!==e?.enableDefaultRules&&this.addDefaultRules(),e?.rules)for(const t of e.rules)this.addRule(t)}addDefaultRules(){const e=[{pattern:/credit_card|card_number|payment_number/i,strategy:h.CREDIT_CARD,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/ssn|social_security|security_number/i,strategy:h.SSN,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/email/i,strategy:h.EMAIL,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/phone|phone_number|mobile_number/i,strategy:h.PHONE,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/password|pass|pwd|secret/i,strategy:h.PASSWORD,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/token|api_key|auth_token|jwt|bearer/i,strategy:h.TOKEN,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0}];for(const t of e)this.addRule(t)}addRule(e){"string"==typeof e.pattern?e._compiledPattern=new RegExp(e.pattern,"i"):e._compiledPattern=e.pattern,e.preserveLength=e.preserveLength??this.preserveLength,e.maskChar=e.maskChar??this.maskChar,this.rules.push(e)}async process(e){this.initialized||(this.initialized=!0);try{const t=new WeakSet;return await this.applyMaskingRules(e,t)}catch{return{...g.buildSafeFallbackFromMeta(e),_maskingFailed:!0,_maskingFailedMessage:g.MASKING_FAILED_MESSAGE}}}static buildSafeFallbackFromMeta(e){const t={},i=["level","timestamp","message","service"];for(const n of i)n in e&&void 0!==e[n]&&(t[n]=e[n]);return t}async applyMaskingRules(e,t){if(null===e||"object"!=typeof e)return e;if(t.has(e))return e;if(t.add(e),Array.isArray(e))return Promise.all(e.map(e=>this.applyMaskingRules(e,t)));const i=e,n={...i};for(const e in i)if(Object.prototype.hasOwnProperty.call(i,e)){const r=i[e];if("string"==typeof r)for(const t of this.rules){let i=!1;if(t._compiledPattern&&(i=t._isDefaultRule?t._compiledPattern.test(e):await this.testRegexWithTimeout(t._compiledPattern,e)),i){n[e]=this.applyStrategy(r,t);break}}else"object"==typeof r&&null!==r&&(n[e]=await this.applyMaskingRules(r,t))}return n}applyStrategy(e,t){if(t.strategy===h.CUSTOM&&t.customMask)return t.customMask(e);switch(t.strategy){case h.CREDIT_CARD:return this.maskCreditCard(e,t);case h.SSN:return this.maskSSN(e,t);case h.EMAIL:return this.maskEmail(e,t);case h.PHONE:return this.maskPhone(e,t);case h.PASSWORD:return this.maskPassword(e,t);case h.TOKEN:return this.maskToken(e,t);default:return this.maskDefault(e,t)}}maskCreditCard(e,t){const i=e.replace(/\D/g,"");return t.preserveLength?e.replace(/\d/g,(n,r)=>e.substring(0,r).replace(/\D/g,"").length<i.length-4?t.maskChar:n):`${t.maskChar.repeat(4)}-${t.maskChar.repeat(4)}-${t.maskChar.repeat(4)}-${i.slice(-4)}`}maskSSN(e,t){const i=e.replace(/\D/g,"");return t.preserveLength?e.replace(/\d/g,(n,r)=>e.substring(0,r).replace(/\D/g,"").length<i.length-4?t.maskChar:n):`***-**-${i.slice(-4)}`}maskEmail(e,t){const i=e.indexOf("@");if(i>0){const n=e.substring(0,i),r=e.substring(i);if(t.preserveLength){return(n.length>1?n.charAt(0)+t.maskChar.repeat(n.length-1):t.maskChar.repeat(n.length))+r}return`${n.charAt(0)}***${r}`}return this.maskDefault(e,t)}maskPhone(e,t){const i=e.replace(/\D/g,"");return t.preserveLength?e.replace(/\d/g,(n,r)=>e.substring(0,r).replace(/\D/g,"").length<i.length-4?t.maskChar:n):`${t.maskChar.repeat(3)}-${t.maskChar.repeat(3)}-${i.slice(-4)}`}maskPassword(e,t){return t.maskChar.repeat(e.length)}maskToken(e,t){return t.preserveLength?e.substring(0,4)+t.maskChar.repeat(e.length-9)+e.substring(e.length-5):e.length>8?e.substring(0,4)+"..."+e.substring(e.length-5):t.maskChar.repeat(e.length)}maskDefault(e,t){return t.preserveLength?t.maskChar.repeat(e.length):t.maskChar.repeat(Math.min(e.length,8))}getStats(){return{initialized:this.initialized,totalRules:this.rules.length,defaultRules:this.rules.filter(e=>[h.CREDIT_CARD,h.SSN,h.EMAIL,h.PHONE,h.PASSWORD,h.TOKEN].includes(e.strategy)).length,customRules:this.rules.filter(e=>e.strategy===h.CUSTOM).length,strategies:this.rules.map(e=>e.strategy)}}isInitialized(){return this.initialized}testRegexWithTimeout(e,t){const i=this.regexTimeoutMs;let n;const r=new Promise(e=>{n=setTimeout(()=>{console.warn(`[SyntropyLog] Masking rule regex timed out (${i}ms); key skipped. Consider using a simpler pattern.`),e(!1)},i)}),s=new Promise(i=>{try{i(e.test(t))}catch{i(!1)}}).then(e=>(clearTimeout(n),e));return Promise.race([s,r])}shutdown(){this.rules=[],this.initialized=!1}}g.MASKING_FAILED_MESSAGE="[SyntropyLog] Masking could not be applied (e.g. timeout or error); payload redacted for safety.";const d=t.z.object({transport:t.z.instanceof(u),env:t.z.union([t.z.string(),t.z.array(t.z.string())]).optional()}),m=t.z.union([t.z.instanceof(u),d]),p=t.z.object({name:t.z.string().optional(),level:t.z.enum(["audit","fatal","error","warn","info","debug","trace","silent"]).optional(),serviceName:t.z.string().optional(),environment:t.z.string().optional(),transportList:t.z.record(t.z.string(),t.z.instanceof(u)).optional(),env:t.z.record(t.z.string(),t.z.array(t.z.string())).optional(),transports:t.z.union([t.z.array(m),t.z.record(t.z.string(),t.z.array(m))]).optional(),serializerTimeoutMs:t.z.number().int().positive().default(50),prettyPrint:t.z.object({enabled:t.z.boolean().optional().default(!1)}).optional()}).optional(),f=t.z.object({maxRetries:t.z.number().int().positive().optional(),retryDelay:t.z.number().int().positive().optional()}).optional(),y=t.z.discriminatedUnion("mode",[t.z.object({mode:t.z.literal("single"),instanceName:t.z.string(),url:t.z.string().url(),retryOptions:f,logging:t.z.object({onSuccess:t.z.enum(["trace","debug","info"]).default("debug"),onError:t.z.enum(["warn","error","fatal"]).default("error"),logCommandValues:t.z.boolean().default(!0),logReturnValue:t.z.boolean().default(!1)}).optional()}),t.z.object({mode:t.z.literal("sentinel"),instanceName:t.z.string(),name:t.z.string(),sentinels:t.z.array(t.z.object({host:t.z.string(),port:t.z.number()})),sentinelPassword:t.z.string().optional(),retryOptions:f,logging:t.z.object({onSuccess:t.z.enum(["trace","debug","info"]).default("debug"),onError:t.z.enum(["warn","error","fatal"]).default("error"),logCommandValues:t.z.boolean().default(!0),logReturnValue:t.z.boolean().default(!1)}).optional()}),t.z.object({mode:t.z.literal("cluster"),instanceName:t.z.string(),rootNodes:t.z.array(t.z.object({host:t.z.string(),port:t.z.number()})),logging:t.z.object({onSuccess:t.z.enum(["trace","debug","info"]).default("debug"),onError:t.z.enum(["warn","error","fatal"]).default("error"),logCommandValues:t.z.boolean().default(!0),logReturnValue:t.z.boolean().default(!1)}).optional()})]),x=t.z.object({instances:t.z.array(y),default:t.z.string().optional()}).optional(),S=t.z.object({rules:t.z.array(t.z.object({pattern:t.z.union([t.z.string(),t.z.instanceof(RegExp)]),strategy:t.z.nativeEnum(h),preserveLength:t.z.boolean().optional(),maskChar:t.z.string().optional(),customMask:t.z.function(t.z.tuple([t.z.string()]),t.z.string()).optional()})).optional(),maskChar:t.z.string().optional(),preserveLength:t.z.boolean().optional(),enableDefaultRules:t.z.boolean().optional(),regexTimeoutMs:t.z.number().int().positive().default(100)}).optional(),z=t.z.object({default:t.z.array(t.z.string()).optional(),trace:t.z.array(t.z.string()).optional(),debug:t.z.array(t.z.string()).optional(),info:t.z.array(t.z.string()).optional(),warn:t.z.array(t.z.string()).optional(),error:t.z.array(t.z.string()).optional(),fatal:t.z.array(t.z.string()).optional()}).optional(),b=t.z.object({logger:p,loggingMatrix:z,redis:x,masking:S,context:t.z.object({correlationIdHeader:t.z.string().optional(),transactionIdHeader:t.z.string().optional()}).optional(),shutdownTimeout:t.z.number().describe("The maximum time in ms to wait for a graceful shutdown.").int().positive().optional()});class w{constructor(e){this.storage=new i.AsyncLocalStorage,this.correlationIdHeader="x-correlation-id",this.transactionIdHeader="x-trace-id",this.storage=new i.AsyncLocalStorage,this.loggingMatrix=e}configure(e){e.correlationIdHeader&&(this.correlationIdHeader=e.correlationIdHeader),e.transactionIdHeader&&(this.transactionIdHeader=e.transactionIdHeader)}reconfigureLoggingMatrix(e){this.loggingMatrix=e}run(e){return new Promise((t,i)=>{const n=this.storage.getStore(),r=new Map(n?.data);this.storage.run({data:r},async()=>{try{await Promise.resolve(e()),t()}catch(e){i(e)}})})}get(e){return this.storage.getStore()?.data.get(e)}getAll(){const e=this.storage.getStore();return e?Object.fromEntries(e.data.entries()):{}}set(e,t){const i=this.storage.getStore();i&&i.data.set(e,t)}getCorrelationId(){let e=this.get(this.correlationIdHeader)||this.get("correlationId");return e&&"string"==typeof e||(e=n.randomUUID(),this.set(this.correlationIdHeader,e)),e}setCorrelationId(e){this.set(this.correlationIdHeader,e)}getTransactionId(){return this.get("transactionId")}setTransactionId(e){this.set("transactionId",e)}getCorrelationIdHeaderName(){return this.correlationIdHeader}getTransactionIdHeaderName(){return this.transactionIdHeader}getTraceContextHeaders(){const e={};if(!this.storage.getStore())return e;const t=this.getCorrelationId(),i=this.getTransactionId();return t&&(e[this.getCorrelationIdHeaderName()]=t),i&&(e[this.getTransactionIdHeaderName()]=i),e}getFilteredContext(e){const t=this.getAll();if(!this.loggingMatrix){const e={...t},i=this.get(this.correlationIdHeader),n=this.get("correlationId");return!i&&n&&(e[this.correlationIdHeader]=n),e}const i=this.loggingMatrix[e]??this.loggingMatrix.default;if(!i)return{};const n={correlationId:[this.correlationIdHeader,"correlationId"],transactionId:[this.transactionIdHeader,"transactionId"],userId:["userId"],serviceName:["serviceName"],operation:["operation"],errorCode:["errorCode"],tenantId:["tenantId"],paymentId:["paymentId"],orderId:["orderId"],processorId:["processorId"],eventType:["eventType"]};if(i.includes("*")){const e={};for(const[i,r]of Object.entries(t)){let t=i;for(const[e,r]of Object.entries(n))if(r.includes(i)){t=e;break}e[t]=r}return e}const r={};for(const e of i){const i=n[e]||[e];for(const n of i)if(Object.prototype.hasOwnProperty.call(t,n)){r[e]=t[n];break}!Object.prototype.hasOwnProperty.call(r,e)&&Object.prototype.hasOwnProperty.call(t,e)&&(r[e]=t[e])}return r}}class v{constructor(e,t,i,n={}){this.pendingRouting=null,this.name=e,this.transports=t,this.dependencies=i,this.bindings=n.bindings??{},this.level=n.level??"info"}override(...e){return this.pendingRouting={override:e},this}add(...e){const t=this.pendingRouting,i=[...t&&"add"in t?t.add??[]:[],...e],n=t&&"remove"in t?t.remove??[]:void 0;return this.pendingRouting=n?.length?{add:i,remove:n}:{add:i},this}remove(...e){const t=this.pendingRouting,i=[...t&&"remove"in t?t.remove??[]:[],...e],n=t&&"add"in t?t.add??[]:void 0;return this.pendingRouting=n?.length?{add:n,remove:i}:{remove:i},this}getEffectiveTransports(){const e=this.pendingRouting;return this.pendingRouting=null,function(e,t,i){if(!t||!i)return e;if("override"in i)return i.override.map(e=>t.get(e)).filter(e=>null!=e);let n=[...e];if(i.add?.length)for(const e of i.add){const i=t.get(e);i&&n.push(i)}if(i.remove?.length){const e=new Set(i.remove);n=n.filter(t=>!e.has(t.name))}return n}(this.transports,this.dependencies.transportPool,e)}async _log(e,...t){if("silent"===e)return;const i=this.level;if(!function(e,t){return"silent"!==e&&("audit"===e||l[e]>=l[t])}(e,i))return;const{message:n,metadata:r}=function(e){let t,i={};if(0===e.length)t="";else if("object"!=typeof e[0]||null===e[0]||Array.isArray(e[0])){t=e[0]||"";const i=e.slice(1);t&&i.length>0&&(t=c.format(t,...i))}else{i=e[0],t=e[1]||"";const n=e.slice(2);t&&n.length>0&&(t=c.format(t,...n))}return{message:t||"",metadata:i}}(t),s={...this.dependencies.contextManager.getFilteredContext(e),...this.bindings,level:e,timestamp:(new Date).toISOString(),service:this.name,message:n,...r},a=(await this.dependencies.serializationManager.serialize(s,{depth:0,maxDepth:10,sensitiveFields:[],sanitize:!0})).data,o=await this.dependencies.maskingEngine.process(a),u=this.getEffectiveTransports();await Promise.all(u.map(t=>t.isLevelEnabled(e)?t.log(o):Promise.resolve()))}info(...e){return this._log("info",...e)}warn(...e){return this._log("warn",...e)}error(...e){return this._log("error",...e)}debug(...e){return this._log("debug",...e)}trace(...e){return this._log("trace",...e)}audit(...e){return this._log("audit",...e)}fatal(...e){return this._log("fatal",...e)}setLevel(e){this.level=e}child(e){return new v(this.name,this.transports,this.dependencies,{level:this.level,bindings:{...this.bindings,...e}})}withSource(e){return this.child({source:e})}withRetention(e){return this.child({retention:e})}withTransactionId(e){return this.child({transactionId:e})}}var C;exports.SerializationComplexity=void 0,(C=exports.SerializationComplexity||(exports.SerializationComplexity={})).SIMPLE="simple",C.COMPLEX="complex",C.CRITICAL="critical";class E{constructor(){this.defaultSensitiveFields=["password","token","secret","key","auth","authorization","api_key","apikey","private_key","privatekey","credential","credential_id","credentialid","access_token","accesstoken","refresh_token","refreshtoken","session_id","sessionid"],this.defaultMaxDepth=10}sanitize(e,t={}){const i=t.sensitiveFields||this.defaultSensitiveFields,n=t.maxDepth||this.defaultMaxDepth,r=t.currentDepth||0;if(r>=n)return"[MAX_DEPTH_REACHED]";if(null==e)return e;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e,i)=>this.sanitize(e,{...t,currentDepth:r+1}));if("object"==typeof e){const n={};for(const[s,a]of Object.entries(e)){const e=s.toLowerCase(),o=i.some(t=>e.includes(t.toLowerCase()));n[s]=o?"[REDACTED]":this.sanitize(a,{...t,currentDepth:r+1})}return n}return e}}const R="pipeline",k="unknown";class M{constructor(){this.steps=[],this.timeoutStrategies=new Map,this.metrics=null,this.sanitizer=new E,this.initializeDefaultStrategies()}addStep(e){this.steps.push(e)}addTimeoutStrategy(e){this.timeoutStrategies.set(e.getStrategyName(),e)}async process(e,t){const i=Date.now(),n=t?.serializationContext?.timeoutMs??50;this.metrics={stepDurations:{},totalDuration:0,operationTimeout:0,timeoutStrategy:k};let r=e;try{for(const e of this.steps){const i=Date.now();let s;const a=new Promise((t,i)=>{s=setTimeout(()=>i(new Error(`Timeout in step '${e.name}' (> ${n}ms)`)),n)});try{const i=e.execute(r,t);r=await Promise.race([i,a])}finally{clearTimeout(s)}this.metrics.stepDurations[e.name]=Date.now()-i}const e=this.selectTimeoutStrategy(r),s=e.calculateTimeout(r);return this.metrics.operationTimeout=s,this.metrics.timeoutStrategy=e.getStrategyName(),this.metrics.totalDuration=Date.now()-i,M.buildSuccessResult(r,t.sanitizeSensitiveData,this.metrics,s,e.getStrategyName())}catch(e){return this.metrics.totalDuration=Date.now()-i,M.buildErrorResult(r,e,this.metrics)}}getMetrics(){return this.metrics}static buildSuccessResult(e,t,i,n,r){const s=e,a=s.serializer??R,o=s.serializationComplexity??exports.SerializationComplexity.SIMPLE;return{success:!0,data:e,serializer:a,duration:i.totalDuration,complexity:o,sanitized:t,metadata:{stepDurations:i.stepDurations,operationTimeout:n,timeoutStrategy:r,serializer:a,complexity:o}}}static buildErrorResult(e,t,i){const n=t?.serializer??R;return{success:!1,data:e,serializer:n,duration:i.totalDuration,complexity:exports.SerializationComplexity.SIMPLE,sanitized:!1,error:t instanceof Error?t.message:String(t),metadata:{stepDurations:i.stepDurations,operationTimeout:0,timeoutStrategy:k,serializer:n,complexity:exports.SerializationComplexity.SIMPLE}}}selectTimeoutStrategy(e){const t=this.timeoutStrategies.get("default");if(null==t)throw new Error("SerializationPipeline: default timeout strategy is required");return t}initializeDefaultStrategies(){this.addTimeoutStrategy(new D)}}class D{calculateTimeout(e){return 5e3}getStrategyName(){return"default"}}class T{constructor(e=[]){this.name="serialization",this.serializers=[],this.serializers=e}addSerializer(e){const t=this.serializers.findIndex(t=>t.priority<e.priority);-1===t?this.serializers.push(e):this.serializers.splice(t,0,e)}async execute(e,t){const i=Date.now(),n=this.findSerializer(e);if(!n)return e;try{const r=await n.serialize(e,t.serializationContext),s=Date.now()-i;return{..."object"==typeof r.data&&null!==r.data?r.data:{},serializationDuration:s,serializer:n.name,serializationComplexity:r.complexity||r.metadata?.complexity||null}}catch(e){throw e instanceof Error&&!e.serializer&&(e.serializer=n.name),e}}findSerializer(e){for(const t of this.serializers)if(t.canSerialize(e))return t;return null}getRegisteredSerializers(){return this.serializers.map(e=>e.name)}}class P{constructor(){this.name="hygiene"}async execute(e,t){if(null===e||"object"!=typeof e)return e;try{if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack,...e};const t=s.stringify(e);return s.parse(t)}catch(e){return`[HYGIENE_ERROR: ${e instanceof Error?e.message:String(e)}]`}}}function I(e,t,i,n){const r={..."object"==typeof e&&null!==e?e:{},sanitizationDuration:t,sanitized:i};return void 0!==n&&(r.sanitizationError=n),r}class L{constructor(e){this.name="sanitization",this.sanitizer=e??new E}async execute(e,t){const i=Date.now(),n=()=>Date.now()-i;if(!t.sanitizeSensitiveData)return I(e,n(),!1);try{return I(this.sanitizer.sanitize(e,t.sanitizationContext),n(),!0)}catch(t){return I(e,n(),!1,function(e){return e instanceof Error?e.message:String(e)}(t))}}}class A{constructor(e){this.name="timeout",this.timeoutStrategies=new Map,this.timeoutStrategies=e}async execute(e,t){const i=Date.now();try{const t=this.selectTimeoutStrategy(e),n=t?.calculateTimeout(e)??3e3;return function(e,t,i,n){return{..."object"==typeof e&&null!==e?e:{},timeoutDuration:t,operationTimeout:i,timeoutStrategy:n?.getStrategyName()??"default",timeoutApplied:null!=n}}(e,Date.now()-i,n,t)}catch(t){return function(e,t,i){return{..."object"==typeof e&&null!==e?e:{},timeoutDuration:t,operationTimeout:3e3,timeoutStrategy:"default",timeoutApplied:!1,timeoutError:i instanceof Error?i.message:"Timeout error"}}(e,Date.now()-i,t)}}selectTimeoutStrategy(e){return this.timeoutStrategies.get("default")??null}}class _{constructor(e={}){this.config={timeoutMs:e.timeoutMs||5e3,enableMetrics:e.enableMetrics??!0,sanitizeSensitiveData:e.sanitizeSensitiveData??!0,sanitizationContext:{sensitiveFields:e.sanitizationContext?.sensitiveFields||["password","token","secret","key","auth","credential","api_key","private_key","connection_string","wallet_location"],redactPatterns:e.sanitizationContext?.redactPatterns||[/password\s*=\s*['"][^'"]*['"]/gi,/user\s*=\s*['"][^'"]*['"]/gi,/token\s*=\s*['"][^'"]*['"]/gi,/secret\s*=\s*['"][^'"]*['"]/gi],maxStringLength:e.sanitizationContext?.maxStringLength||300,enableDeepSanitization:e.sanitizationContext?.enableDeepSanitization??!0}},this.metrics={totalSerializations:0,successfulSerializations:0,failedSerializations:0,totalSerializationDuration:0,totalOperationTimeout:0,maxSerializationDuration:0,minSerializationDuration:0,complexityDistribution:{low:0,medium:0,high:0},serializerDistribution:{},timeoutStrategyDistribution:{}},this.pipeline=new M,this.serializationStep=new T,this.hygieneStep=new P,this.sanitizationStep=new L,this.timeoutStep=new A(this.pipeline.timeoutStrategies),this.pipeline.addStep(this.serializationStep),this.pipeline.addStep(this.hygieneStep),this.pipeline.addStep(this.sanitizationStep),this.pipeline.addStep(this.timeoutStep)}register(e){this.serializationStep.addSerializer(e)}async serialize(e,t={depth:0,maxDepth:10,sensitiveFields:[],sanitize:!0}){const i=Date.now(),n={serializationContext:t,sanitizeSensitiveData:this.config.sanitizeSensitiveData,sanitizationContext:this.config.sanitizationContext,enableMetrics:this.config.enableMetrics},r=await this.pipeline.process(e,n);return this.config.enableMetrics&&this.updateMetrics(r,Date.now()-i),r}updateMetrics(e,t){if(this.metrics.totalSerializations++,e.success){this.metrics.successfulSerializations++;const t=(e.metadata.stepDurations?.serialization||0)+(e.metadata.stepDurations?.hygiene||0);this.metrics.totalSerializationDuration+=t,this.metrics.maxSerializationDuration=Math.max(this.metrics.maxSerializationDuration,t),this.metrics.minSerializationDuration=0===this.metrics.minSerializationDuration?t:Math.min(this.metrics.minSerializationDuration,t);const i=e.metadata.operationTimeout||0;this.metrics.totalOperationTimeout+=i;const n=e.complexity||exports.SerializationComplexity.SIMPLE;n===exports.SerializationComplexity.SIMPLE?this.metrics.complexityDistribution.low++:n===exports.SerializationComplexity.COMPLEX?this.metrics.complexityDistribution.medium++:n===exports.SerializationComplexity.CRITICAL&&this.metrics.complexityDistribution.high++;const r=e.serializer||"unknown";this.metrics.serializerDistribution[r]=(this.metrics.serializerDistribution[r]||0)+1;const s=e.metadata.timeoutStrategy||"unknown";this.metrics.timeoutStrategyDistribution[s]=(this.metrics.timeoutStrategyDistribution[s]||0)+1}else this.metrics.failedSerializations++}getMetrics(){return{totalSerializations:this.metrics.totalSerializations,successfulSerializations:this.metrics.successfulSerializations,failedSerializations:this.metrics.failedSerializations,averageSerializationDuration:this.metrics.totalSerializations>0?this.metrics.totalSerializationDuration/this.metrics.totalSerializations:0,averageOperationTimeout:this.metrics.successfulSerializations>0?this.metrics.totalOperationTimeout/this.metrics.successfulSerializations:0,maxSerializationDuration:this.metrics.maxSerializationDuration,minSerializationDuration:this.metrics.minSerializationDuration,complexityDistribution:{...this.metrics.complexityDistribution},serializerDistribution:{...this.metrics.serializerDistribution},timeoutStrategyDistribution:{...this.metrics.timeoutStrategyDistribution}}}resetMetrics(){this.metrics={totalSerializations:0,successfulSerializations:0,failedSerializations:0,totalSerializationDuration:0,totalOperationTimeout:0,maxSerializationDuration:0,minSerializationDuration:0,complexityDistribution:{low:0,medium:0,high:0},serializerDistribution:{},timeoutStrategyDistribution:{}}}getRegisteredSerializers(){return this.serializationStep.getRegisteredSerializers()}getPipelineMetrics(){return this.pipeline.getMetrics()}}class O extends u{constructor(e){super(e)}async log(e){if(!this.isLevelEnabled(e.level))return;const t=this.formatter?this.formatter.format(e):e,i=JSON.stringify(t);switch(e.level){case"fatal":case"error":console.error(i);break;case"warn":console.warn(i);break;default:console.log(i)}}}class j{constructor(e){this.ansiRegex=/[\x1b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,this.maskingEngine=e}async process(e){let t=this.sanitizeRecursively(e);return this.maskingEngine&&(t=await this.maskingEngine.process(t)),t}sanitizeRecursively(e){if("string"==typeof e)return e.replace(this.ansiRegex,"");if(Array.isArray(e))return e.map(e=>this.sanitizeRecursively(e));if("object"==typeof e&&null!==e&&e.constructor===Object){const t={},i=e;for(const e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=this.sanitizeRecursively(i[e]));return t}return e}}function N(e,t){const i=[];for(const n of e)if(n instanceof u)i.push(n);else if(n&&"object"==typeof n&&"transport"in n){const e=null==n.env?null:Array.isArray(n.env)?n.env:[n.env];(null===e||e.includes(t))&&i.push(n.transport)}else n&&"object"==typeof n&&i.push(n);return i}class ${constructor(e,t,i){this.loggerPool=new Map,this.MAX_POOL_SIZE=1e3,this.contextManager=t,this.syntropyLogInstance=i,e.context&&this.contextManager.configure(e.context);const n=(e=>{const t=e.logger?.environment??"development",i=e.logger?.transportList&&Object.keys(e.logger.transportList).length>0,n=e.logger?.env&&Object.keys(e.logger.env).length>0;if(i&&n&&e.logger?.transportList&&e.logger?.env){const i=new Map(Object.entries(e.logger.transportList));return{transports:{default:(e.logger.env[t]??[]).map(e=>i.get(e)).filter(e=>null!=e)},transportPool:i}}if(e.logger?.transports){const i=e.logger.transports,n=new Map,r=e=>{const t=e instanceof u?e:e&&"object"==typeof e&&"transport"in e?e.transport:e,i=t.name??t.constructor?.name??`transport-${n.size}`;return n.set(i,t),t};let s;if(Array.isArray(i))i.forEach(r),s={default:N(i,t)};else{const e=i;s={};for(const[i,n]of Object.entries(e))n.forEach(r),s[i]=N(n,t)}return{transports:s,transportPool:n}}{const e=new j,t=new O({sanitizationEngine:e,name:"console"});return{transports:{default:[t]},transportPool:new Map([["console",t]])}}})(e);this.transports=n.transports,this.transportPool=n.transportPool,this.globalLogLevel=e.logger?.level??"info",this.serviceName=e.logger?.serviceName??"unknown-service",this.serializationManager=new _({timeoutMs:e.logger?.serializerTimeoutMs,sanitizeSensitiveData:!1!==e.masking?.enableDefaultRules}),this.maskingEngine=new g({rules:e.masking?.rules,maskChar:e.masking?.maskChar,preserveLength:e.masking?.preserveLength,enableDefaultRules:!1!==e.masking?.enableDefaultRules,regexTimeoutMs:e.masking?.regexTimeoutMs})}getLogger(e="default",t){const i=((e,t)=>{if(!t||0===Object.keys(t).length)return e;const i=Object.keys(t).sort().reduce((e,i)=>(e[i]=t[i],e),{});try{return`${e}:${JSON.stringify(i)}`}catch{return`${e}:${Object.keys(i).sort().join(",")}`}})(e,t);if(this.loggerPool.has(i)){const e=this.loggerPool.get(i);return this.loggerPool.delete(i),this.loggerPool.set(i,e),e}const n="default"===e?this.serviceName:e,r={contextManager:this.contextManager,serializationManager:this.serializationManager,maskingEngine:this.maskingEngine,syntropyLogInstance:this.syntropyLogInstance,transportPool:this.transportPool},s=this.transports[e]??this.transports.default,a=new v(n,s,r,{bindings:t});if(a.level=this.globalLogLevel,this.loggerPool.size>=this.MAX_POOL_SIZE){const e=this.loggerPool.keys().next().value;void 0!==e&&this.loggerPool.delete(e)}return this.loggerPool.set(i,a),a}async flushAllTransports(){const e=Object.values(this.transports).flat(),t=Array.from(new Set(e)).map(e=>e.flush().catch(t=>{console.error(`Error flushing transport ${e.constructor.name}:`,t)}));await Promise.allSettled(t)}async shutdown(){try{await this.flushAllTransports(),this.loggerPool.clear();const e=Object.values(this.transports).flat(),t=Array.from(new Set(e)).map(e=>"function"==typeof e.shutdown?e.shutdown().catch(t=>{console.error(`Error shutting down transport ${e.constructor.name}:`,t)}):Promise.resolve());await Promise.allSettled(t)}catch(e){console.error("Error during LoggerFactory shutdown:",e)}}}const H="[CONFIG_MASKED]",G=["password","token","secret","apikey","credential","pass","key","accesstoken","refreshtoken","clientsecret","sentinelpassword","sasl"];function F(e){if(e instanceof u)return e;if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>F(e));const t={},i=G.map(e=>e.toLowerCase());for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const r=n.toLowerCase(),s=e[n];i.includes(r)?t[n]=H:(r.includes("url")||r.includes("uri"))&&"string"==typeof s?t[n]=s.replace(/(?<=:\/\/)[^:]+:[^@]+@/,`${H}@`):"object"!=typeof s||null===s||s instanceof RegExp?t[n]=s:t[n]=F(s)}return t}function B(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack||null}:String(e)}class U extends e.EventEmitter{constructor(e){super(),this.state="NOT_INITIALIZED",this.logger=null,this.trackedProcesses=new Set,this.syntropyFacade=e,this.config={},this.serializationManager=new _({}),this.maskingEngine=new g({})}getState(){return this.state}async init(e){if("NOT_INITIALIZED"===this.state){this.state="INITIALIZING";try{const t=F(b.parse(e));this.config=t,this.contextManager=new w(this.config.loggingMatrix),this.config.context&&this.contextManager.configure(this.config.context),this.serializationManager=new _({timeoutMs:this.config.logger?.serializerTimeoutMs,sanitizeSensitiveData:!1!==this.config.masking?.enableDefaultRules}),this.maskingEngine=new g({rules:this.config.masking?.rules,maskChar:this.config.masking?.maskChar,preserveLength:this.config.masking?.preserveLength,enableDefaultRules:!1!==this.config.masking?.enableDefaultRules,regexTimeoutMs:this.config.masking?.regexTimeoutMs}),this.loggerFactory=new $(this.config,this.contextManager,this.syntropyFacade);const i=this.loggerFactory.getLogger("syntropylog-main");if(this.logger=i,this.config.redis)try{const{RedisManager:e}=await Promise.resolve().then(function(){return re});this.redisManager=new e(this.config.redis,i.withSource("redis-manager"),this.contextManager),this.redisManager.init()}catch(e){i.error("Failed to initialize Redis manager. Make sure redis package is installed.",{error:B(e)})}i.info("SyntropyLog framework initialized successfully."),this.state="READY",this.emit("ready")}catch(e){throw this.state="ERROR",this.emit("error",e),e instanceof t.ZodError?console.error("[SyntropyLog] Configuration validation failed:",e.issues):console.error("[SyntropyLog] Failed to initialize framework:",e),e}}else this.logger?.warn(`LifecycleManager.init() called while in state '${this.state}'. Ignoring subsequent call.`)}async shutdown(){if(this.logger?.info(`🔄 LifecycleManager.shutdown() called. Current state: ${this.state}`),"READY"===this.state){this.state="SHUTTING_DOWN",this.emit("shutting_down"),this.logger?.info("🔄 State changed to SHUTTING_DOWN");try{this.logger?.info("Shutting down SyntropyLog framework..."),this.maskingEngine?.shutdown?.();const e=[];this.redisManager&&e.push(this.redisManager.shutdown()),e.push(this.terminateExternalProcesses()),this.logger?.info(`📋 Executing ${e.length} shutdown steps...`),await Promise.allSettled(e),await(this.logger?.info("✅ Shutdown steps completed")),await(this.logger?.info("All managers have been shut down.")),await(this.logger?.info("✅ State changed to SHUTDOWN")),await(this.loggerFactory?.shutdown?.()),"SHUTTING_DOWN"===this.state&&this.emit("transports_drained"),this.state="SHUTDOWN",this.emit("shutdown")}catch(e){this.state="ERROR",this.emit("error",e),this.logger?.error("❌ Error during shutdown:",{error:B(e)}),await(this.loggerFactory?.shutdown?.()),"ERROR"===this.state&&this.emit("transports_drained")}}else this.logger?.warn(`❌ Cannot perform shutdown. Current state: ${this.state}`)}registerChildProcess(e){this.trackedProcesses.add(e),e.on("exit",()=>{this.trackedProcesses.delete(e)})}async terminateExternalProcesses(){try{if(0===this.trackedProcesses.size)return void this.logger?.info("No tracked external processes to terminate");this.logger?.info(`Terminating ${this.trackedProcesses.size} external processes...`);const e=Array.from(this.trackedProcesses).map(e=>(async(e,t)=>{if(!e.connected&&null!==e.exitCode)return;const i=e.pid;t?.debug(`Sending SIGTERM to process ${i}...`),e.kill("SIGTERM");const n=new Promise(t=>{const i=()=>{t(),e.removeListener("exit",i)};e.on("exit",i)}),r=new Promise(e=>setTimeout(e,5e3));await Promise.race([n,r]),null===e.exitCode?(t?.warn(`Process ${i} did not exit after SIGTERM, sending SIGKILL...`),e.kill("SIGKILL")):t?.debug(`Process ${i} exited gracefully`)})(e,this.logger));await Promise.allSettled(e),this.trackedProcesses.clear(),this.logger?.info("✅ All external processes terminated")}catch(e){this.logger?.warn("Error terminating external processes:",{error:B(e)})}}ensureReady(){if("READY"!==this.state)throw new Error(`SyntropyLog is not ready. Current state: '${this.state}'. Ensure init() has completed successfully by listening for the 'ready' event.`)}}function V(e,t){if(null==e)throw new Error(t)}class W extends e.EventEmitter{constructor(){super(),this.lifecycleManager=new U(this),this.lifecycleManager.on("ready",()=>this.emit("ready")),this.lifecycleManager.on("error",e=>this.emit("error",e)),this.lifecycleManager.on("shutting_down",()=>this.emit("shutting_down")),this.lifecycleManager.on("transports_drained",()=>this.emit("transports_drained")),this.lifecycleManager.on("shutdown",()=>this.emit("shutdown"))}static getInstance(){return W.instance||(W.instance=new W),W.instance}static resetInstance(){W.instance=void 0}getState(){return this.lifecycleManager.getState()}async init(e){return this.lifecycleManager.init(e)}async shutdown(){return this.lifecycleManager.shutdown()}getLogger(e="default",t){return V(this.lifecycleManager.loggerFactory,"Logger Factory not available."),this.lifecycleManager.loggerFactory.getLogger(e,t)}async getRedis(e){return this.lifecycleManager.ensureReady(),V(this.lifecycleManager.redisManager,"Redis manager not available. Make sure Redis is configured and redis package is installed."),this.lifecycleManager.redisManager.getInstance(e)}getContextManager(){return this.lifecycleManager.ensureReady(),this.lifecycleManager.contextManager}getConfig(){return this.lifecycleManager.ensureReady(),this.lifecycleManager.config}getFilteredContext(e){return this.lifecycleManager.ensureReady(),this.lifecycleManager.contextManager.getFilteredContext(e)}reconfigureLoggingMatrix(e){this.lifecycleManager.ensureReady(),this.lifecycleManager.contextManager.reconfigureLoggingMatrix(e)}getMasker(){return V(this.lifecycleManager.maskingEngine,"MaskingEngine not available."),this.lifecycleManager.maskingEngine}getSerializer(){return V(this.lifecycleManager.serializationManager,"SerializationManager not available."),this.lifecycleManager.serializationManager}_resetForTesting(){this.lifecycleManager.removeAllListeners(),Object.assign(this,{lifecycleManager:new U(this)}),this.removeAllListeners(),this.lifecycleManager.on("ready",()=>this.emit("ready")),this.lifecycleManager.on("error",e=>this.emit("error",e)),this.lifecycleManager.on("shutting_down",()=>this.emit("shutting_down")),this.lifecycleManager.on("shutdown",()=>this.emit("shutdown"))}}const K=W.getInstance();function q(e){const t=t=>function(e,t){return 0===t.length?e:`[${t.join(";")}m${e}[0m`}(t,e),i=t=>q([...e,t]);return Object.defineProperty(t,"white",{get:()=>i(37),enumerable:!0}),Object.defineProperty(t,"bold",{get:()=>i(1),enumerable:!0}),Object.defineProperty(t,"red",{get:()=>i(31),enumerable:!0}),Object.defineProperty(t,"bgRed",{get:()=>i(41),enumerable:!0}),Object.defineProperty(t,"yellow",{get:()=>i(33),enumerable:!0}),Object.defineProperty(t,"cyan",{get:()=>i(36),enumerable:!0}),Object.defineProperty(t,"green",{get:()=>i(32),enumerable:!0}),Object.defineProperty(t,"gray",{get:()=>i(90),enumerable:!0}),Object.defineProperty(t,"magenta",{get:()=>i(35),enumerable:!0}),Object.defineProperty(t,"blue",{get:()=>i(34),enumerable:!0}),Object.defineProperty(t,"bgWhite",{get:()=>i(47),enumerable:!0}),Object.defineProperty(t,"dim",{get:()=>i(2),enumerable:!0}),t}let Z=null;function X(){if(null!==Z)return Z;const e=void 0!==process.env.NO_COLOR&&""!==process.env.NO_COLOR&&"0"!==process.env.NO_COLOR,t="boolean"==typeof process.stdout?.isTTY&&process.stdout.isTTY;if(e||!t){const e=e=>e;e.white=e,e.bold=e,e.red=e,e.bgRed=e,e.yellow=e,e.cyan=e,e.green=e,e.gray=e,e.magenta=e,e.blue=e,e.bgWhite=e,e.dim=e,Z=e}else Z=q([]);return Z}class Y extends u{constructor(e){super(e),this.chalk=X()}async log(e){if(!this.isLevelEnabled(e.level))return;const t=this.formatter?this.formatter.format(e):e,i=this.formatLogString(t);this.getConsoleMethod(t.level)(i)}getConsoleMethod(e){switch(e){case"fatal":case"error":return console.error;case"warn":return console.warn;default:return console.log}}}function Q(e){return"function"==typeof e.ping&&!("commands"in e)}const J=e=>{switch(e.mode){case"single":case"sentinel":{const t=(e=>t=>{const i="retryOptions"in e?e.retryOptions:void 0;return t>(i?.maxRetries??10)?new Error("Exceeded the maximum number of Redis connection retries."):Math.min(50*t,i?.retryDelay??2e3)})(e);if("single"===e.mode)return a.createClient({url:e.url,socket:{reconnectStrategy:t}});{const i={sentinels:e.sentinels,name:e.name,sentinelPassword:e.sentinelPassword,socket:{reconnectStrategy:t}};return a.createClient(i)}}case"cluster":{const t={rootNodes:e.rootNodes.map(e=>({socket:{host:e.host,port:e.port}}))};return a.createCluster(t)}default:throw new Error(`Unsupported Redis mode: "${e.mode}"`)}};class ee{constructor(e,t){this.connectionPromise=null,this.connectionResolve=null,this.connectionReject=null,this.isConnectedAndReadyState=!1,this.isQuitState=!1,this.logger=t,this.instanceName=e.instanceName,this.client=J(e),this.setupListeners()}setupListeners(){this.client.on("connect",()=>this.logger.info(`[${this.instanceName}] Connecting to Redis...`)),this.client.on("ready",()=>{this.logger.info(`[${this.instanceName}] ✅ Redis is operational and ready to accept commands.`),this.isConnectedAndReadyState=!0,this.connectionResolve&&(this.connectionResolve(),this.connectionResolve=null,this.connectionReject=null)}),this.client.on("end",()=>{this.logger.warn(`[${this.instanceName}] Connection closed.`),this.isConnectedAndReadyState=!1}),this.client.on("error",e=>{this.logger.error(`[${this.instanceName}] Client error.`,{error:e}),this.connectionReject&&(this.connectionReject(e),this.connectionPromise=null,this.connectionResolve=null,this.connectionReject=null)}),this.client.on("reconnecting",()=>{this.logger.info(`[${this.instanceName}] Reconnecting...`)})}connect(){return this.isQuitState?Promise.reject(new Error("Client has been quit and cannot be reconnected.")):this.isReady()?Promise.resolve():(this.connectionPromise||(this.logger.info("Attempting to connect..."),this.connectionPromise=new Promise((e,t)=>{this.connectionResolve=e,this.connectionReject=t,this.client.connect().catch(e=>{this.logger.error("Immediate connection attempt failed.",{error:e}),this.connectionReject&&(this.connectionReject(e),this.connectionPromise=null,this.connectionResolve=null,this.connectionReject=null)})})),this.connectionPromise)}ensureReady(){return this.isQuitState?Promise.reject(new Error("Client has been quit. Cannot execute commands.")):(this.isReady()||this.connectionPromise||this.logger.debug("ensureReady: Client not open, initiating connect."),this.connect())}async disconnect(){if(this.isQuitState)this.logger.info("Quit already called. No action taken.");else if(this.connectionReject&&(this.connectionReject(new Error("Connection aborted due to disconnect call.")),this.connectionPromise=null,this.connectionResolve=null,this.connectionReject=null),this.isQuitState=!0,this.isConnectedAndReadyState=!1,this.client.isOpen){this.logger.info("Attempting to quit client.");try{"function"==typeof this.client.removeAllListeners&&this.client.removeAllListeners(),await this.client.quit()}catch(e){throw this.logger.error("Error during client.quit().",{error:e}),e}}else"function"==typeof this.client.removeAllListeners&&this.client.removeAllListeners(),this.logger.info("Client was not open. Quit operation effectively complete.")}getNativeClient(){return this.client}isReady(){return this.isConnectedAndReadyState}async isHealthy(){if(this.isQuitState||!this.isReady())return!1;try{const e=await this.ping();return this.logger.debug(`PING response: ${e}`),"PONG"===e}catch(e){return this.logger.error("PING failed during health check.",{error:e}),!1}}isQuit(){return this.isQuitState}async ping(e){return await this.ensureReady(),Q(this.client)?this.client.ping(e):Promise.resolve(e||"PONG")}async info(e){return await this.ensureReady(),Q(this.client)?this.client.info(e):Promise.resolve("# INFO command is not supported in cluster mode.")}async exists(e){return await this.ensureReady(),this.client.exists(e)}async get(e){return await this.ensureReady(),this.client.get(e)}async set(e,t,i){if(await this.ensureReady(),i)return this.client.setEx(e,i,t);return await this.client.set(e,t)||"OK"}async del(e){return await this.ensureReady(),this.client.del(e)}}class te{constructor(e,t){this.nativeTx=e,this.beacon=t}get(e){return this.nativeTx.get(e),this}set(e,t,i){const n=i?{EX:i}:void 0;return this.nativeTx.set(e,t,n),this}del(e){return this.nativeTx.del(e),this}exists(e){return this.nativeTx.exists(e),this}expire(e,t){return this.nativeTx.expire(e,t),this}ttl(e){return this.nativeTx.ttl(e),this}incr(e){return this.nativeTx.incr(e),this}decr(e){return this.nativeTx.decr(e),this}incrBy(e,t){return this.nativeTx.incrBy(e,t),this}decrBy(e,t){return this.nativeTx.decrBy(e,t),this}hGet(e,t){return this.nativeTx.hGet(e,t),this}hSet(e,t,i){return"string"==typeof t?this.nativeTx.hSet(e,t,i):this.nativeTx.hSet(e,t),this}hGetAll(e){return this.nativeTx.hGetAll(e),this}hDel(e,t){return this.nativeTx.hDel(e,t),this}hExists(e,t){return this.nativeTx.hExists(e,t),this}hIncrBy(e,t,i){return this.nativeTx.hIncrBy(e,t,i),this}lPush(e,t){return this.nativeTx.lPush(e,t),this}rPush(e,t){return this.nativeTx.rPush(e,t),this}lPop(e){return this.nativeTx.lPop(e),this}rPop(e){return this.nativeTx.rPop(e),this}lRange(e,t,i){return this.nativeTx.lRange(e,t,i),this}lLen(e){return this.nativeTx.lLen(e),this}lTrim(e,t,i){return this.nativeTx.lTrim(e,t,i),this}sAdd(e,t){return this.nativeTx.sAdd(e,t),this}sMembers(e){return this.nativeTx.sMembers(e),this}sIsMember(e,t){return this.nativeTx.sIsMember(e,t),this}sRem(e,t){return this.nativeTx.sRem(e,t),this}sCard(e){return this.nativeTx.sCard(e),this}zAdd(e,t,i){return Array.isArray(t)?this.nativeTx.zAdd(e,t):this.nativeTx.zAdd(e,{score:t,value:i}),this}zRange(e,t,i,n){return this.nativeTx.zRange(e,t,i,n),this}zRangeWithScores(e,t,i,n){return this.nativeTx.zRangeWithScores(e,t,i,n),this}zRem(e,t){return this.nativeTx.zRem(e,t),this}zCard(e){return this.nativeTx.zCard(e),this}zScore(e,t){return this.nativeTx.zScore(e,t),this}ping(e){return this.nativeTx.ping(e),this}info(e){return this.nativeTx.info(e),this}executeScript(e,t,i){throw new Error("executeScript is not supported inside a Redis transaction (MULTI/EXEC).")}exec(){return this.beacon.runTransactionExec(()=>this.nativeTx.exec())}discard(){return this.beacon.runTransactionDiscard(()=>this.nativeTx.discard())}}class ie{constructor(e,t,i,n){this.config=e,this.logger=n,this.connectionManager=t,this.commandExecutor=i}getInstanceName(){return this.config.instanceName}async connect(){return this.connectionManager.ensureReady()}async quit(){return this.connectionManager.disconnect()}updateConfig(e){this.logger.info({newConfig:e},"Dynamically updating Redis instance configuration..."),Object.assign(this.config,e)}multi(){const e=this.commandExecutor.multi();return new te(e,this)}runTransactionExec(e){return this._executeCommand("MULTI/EXEC",e)}runTransactionDiscard(e){return this._executeCommand("DISCARD",e)}async _executeCommand(e,t,...i){const n=Date.now(),r=this.logger.withSource("redis");try{await this.connectionManager.ensureReady();const a=await t(),o=Date.now()-n,c=null==(s=this.config.logging)||null==s.onSuccess?"debug":s.onSuccess,l=function(e,t,i,n,r,s){const a={command:e,instance:t,durationMs:i};return!0===s?.logCommandValues&&(a.params=n),!0===s?.logReturnValue&&(a.result=r),a}(e,this.getInstanceName(),o,i,a,this.config.logging);return r[c](l,`Redis command [${e}] executed successfully.`),a}catch(t){const s=Date.now()-n,a=function(e){return null==e||null==e.onError?"error":e.onError}(this.config.logging),o=function(e,t,i,n,r,s){const a={command:e,instance:t,durationMs:i,err:B(n)};return!0===s?.logCommandValues&&(a.params=r),a}(e,this.getInstanceName(),s,t,i,this.config.logging);throw r[a](o,`Redis command [${e}] failed.`),t}var s}async get(e){return this._executeCommand("GET",()=>this.commandExecutor.get(e),e)}async set(e,t,i){const n=i?{EX:i}:void 0;return this._executeCommand("SET",()=>this.commandExecutor.set(e,t,n),e,t,i)}async del(e){return this._executeCommand("DEL",()=>this.commandExecutor.del(e),e)}async exists(e){return this._executeCommand("EXISTS",()=>this.commandExecutor.exists(e),e)}async expire(e,t){return this._executeCommand("EXPIRE",()=>this.commandExecutor.expire(e,t),e,t)}async ttl(e){return this._executeCommand("TTL",()=>this.commandExecutor.ttl(e),e)}async incr(e){return this._executeCommand("INCR",()=>this.commandExecutor.incr(e),e)}async decr(e){return this._executeCommand("DECR",()=>this.commandExecutor.decr(e),e)}async incrBy(e,t){return this._executeCommand("INCRBY",()=>this.commandExecutor.incrBy(e,t),e,t)}async decrBy(e,t){return this._executeCommand("DECRBY",()=>this.commandExecutor.decrBy(e,t),e,t)}async hGet(e,t){return this._executeCommand("HGET",async()=>await this.commandExecutor.hGet(e,t)??null,e,t)}async hSet(e,t,i){return"string"==typeof t?this._executeCommand("HSET",()=>this.commandExecutor.hSet(e,t,i),e,t,i):this._executeCommand("HSET",()=>this.commandExecutor.hSet(e,t),e,t)}async hGetAll(e){return this._executeCommand("HGETALL",()=>this.commandExecutor.hGetAll(e),e)}async hDel(e,t){return this._executeCommand("HDEL",()=>this.commandExecutor.hDel(e,t),e,t)}async hExists(e,t){return this._executeCommand("HEXISTS",()=>this.commandExecutor.hExists(e,t),e,t)}async hIncrBy(e,t,i){return this._executeCommand("HINCRBY",()=>this.commandExecutor.hIncrBy(e,t,i),e,t,i)}async lPush(e,t){return this._executeCommand("LPUSH",()=>this.commandExecutor.lPush(e,t),e,t)}async rPush(e,t){return this._executeCommand("RPUSH",()=>this.commandExecutor.rPush(e,t),e,t)}async lPop(e){return this._executeCommand("LPOP",()=>this.commandExecutor.lPop(e),e)}async rPop(e){return this._executeCommand("RPOP",()=>this.commandExecutor.rPop(e),e)}async lRange(e,t,i){return this._executeCommand("LRANGE",()=>this.commandExecutor.lRange(e,t,i),e,t,i)}async lLen(e){return this._executeCommand("LLEN",()=>this.commandExecutor.lLen(e),e)}async lTrim(e,t,i){return this._executeCommand("LTRIM",()=>this.commandExecutor.lTrim(e,t,i),e,t,i)}async sAdd(e,t){return this._executeCommand("SADD",()=>this.commandExecutor.sAdd(e,t),e,t)}async sMembers(e){return this._executeCommand("SMEMBERS",()=>this.commandExecutor.sMembers(e),e)}async sIsMember(e,t){return this._executeCommand("SISMEMBER",()=>this.commandExecutor.sIsMember(e,t),e,t)}async sRem(e,t){return this._executeCommand("SREM",()=>this.commandExecutor.sRem(e,t),e,t)}async sCard(e){return this._executeCommand("SCARD",()=>this.commandExecutor.sCard(e),e)}async zAdd(e,t,i){return Array.isArray(t)?this._executeCommand("ZADD",()=>this.commandExecutor.zAdd(e,t),e,t):this._executeCommand("ZADD",()=>this.commandExecutor.zAdd(e,t,i),e,t,i)}async zRange(e,t,i,n){return this._executeCommand("ZRANGE",()=>this.commandExecutor.zRange(e,t,i,n),e,t,i,n)}async zRangeWithScores(e,t,i,n){return this._executeCommand("ZRANGE_WITHSCORES",()=>this.commandExecutor.zRangeWithScores(e,t,i,n),e,t,i,n)}async zRem(e,t){return this._executeCommand("ZREM",()=>this.commandExecutor.zRem(e,t),e,t)}async zCard(e){return this._executeCommand("ZCARD",()=>this.commandExecutor.zCard(e),e)}async zScore(e,t){return this._executeCommand("ZSCORE",()=>this.commandExecutor.zScore(e,t),e,t)}async ping(e){return this._executeCommand("PING",()=>this.connectionManager.ping(e),e)}async info(e){return this._executeCommand("INFO",()=>this.connectionManager.info(e),e)}async executeScript(e,t,i){return this._executeCommand("SCRIPT_EXEC",()=>this.commandExecutor.executeScript(e,t,i),e,t,i)}async subscribe(e,t){return this._executeCommand("SUBSCRIBE",()=>this.commandExecutor.subscribe(e,t),e)}async unsubscribe(e){return this._executeCommand("UNSUBSCRIBE",()=>this.commandExecutor.unsubscribe(e),e)}async publish(e,t){return this._executeCommand("PUBLISH",()=>this.commandExecutor.publish(e,t),e)}async scan(e,t){return this._executeCommand("SCAN",()=>this.commandExecutor.scan(e,t),e)}async keys(e){return this._executeCommand("KEYS",()=>this.commandExecutor.keys(e),e)}}class ne{constructor(e){this.client=e}multi(){return this.client.multi()}get(e){return this.client.get(e)}set(e,t,i){return this.client.set(e,t,i)}del(e){return this.client.del(e)}exists(e){return this.client.exists(e)}async expire(e,t){return this.client.expire(e,t)}ttl(e){return this.client.ttl(e)}incr(e){return this.client.incr(e)}decr(e){return this.client.decr(e)}incrBy(e,t){return this.client.incrBy(e,t)}decrBy(e,t){return this.client.decrBy(e,t)}async hGet(e,t){return await this.client.hGet(e,t)??void 0}hSet(e,t,i){return"string"==typeof t?this.client.hSet(e,t,i):this.client.hSet(e,t)}hGetAll(e){return this.client.hGetAll(e)}hDel(e,t){return this.client.hDel(e,t)}async hExists(e,t){return this.client.hExists(e,t)}hIncrBy(e,t,i){return this.client.hIncrBy(e,t,i)}lPush(e,t){return this.client.lPush(e,t)}rPush(e,t){return this.client.rPush(e,t)}lPop(e){return this.client.lPop(e)}rPop(e){return this.client.rPop(e)}lRange(e,t,i){return this.client.lRange(e,t,i)}lLen(e){return this.client.lLen(e)}lTrim(e,t,i){return this.client.lTrim(e,t,i)}sAdd(e,t){return this.client.sAdd(e,t)}sMembers(e){return this.client.sMembers(e)}async sIsMember(e,t){return this.client.sIsMember(e,t)}sRem(e,t){return this.client.sRem(e,t)}sCard(e){return this.client.sCard(e)}zAdd(e,t,i){return Array.isArray(t)?this.client.zAdd(e,t):this.client.zAdd(e,{score:t,value:i})}zRange(e,t,i,n){return this.client.zRange(e,t,i,n)}zRangeWithScores(e,t,i,n){return this.client.zRangeWithScores(e,t,i,n)}zRem(e,t){return this.client.zRem(e,t)}zCard(e){return this.client.zCard(e)}zScore(e,t){return this.client.zScore(e,t)}async executeScript(e,t,i){return await this.client.sendCommand(["EVAL",e,t.length.toString(),...t,...i])}subscribe(e,t){return this.client.subscribe(e,t)}unsubscribe(e){return e?this.client.unsubscribe(e):this.client.unsubscribe()}publish(e,t){return this.client.publish(e,t)}async scan(e,t){const i=await this.client.scan(e,t);return{cursor:i.cursor,keys:i.keys}}keys(e){return this.client.keys(e)}}var re=Object.freeze({__proto__:null,RedisManager:class{constructor(e,t,i){this.instances=new Map,this.config=e,this.logger=t.child({module:"RedisManager"}),this.contextManager=i}init(){if(this.logger.trace("Initializing RedisManager..."),!this.config||!this.config.instances||0===this.config.instances.length)return void this.logger.trace("No Redis instances to initialize.");const e=()=>{if(!this.config||!this.config.instances||0===this.config.instances.length)throw new Error("Redis configuration is invalid: no instances configured. Please provide at least one Redis instance.")},t=()=>{if(this.config.default){if(!this.config.instances.some(e=>e.instanceName===this.config.default))throw new Error(`Redis configuration error: default instance "${this.config.default}" not found in configured instances. Available instances: ${this.config.instances.map(e=>e.instanceName).join(", ")}`)}},i=()=>{for(const e of this.config.instances){const t=new ee(e,this.logger),i=new ne(t.getNativeClient()),n=new ie(e,t,i,this.logger);this.instances.set(e.instanceName,n),e.instanceName===this.config.default&&(this.defaultInstance=n)}},n=()=>{if(!this.defaultInstance&&this.instances.size>0){const e=this.instances.values().next().value;this.defaultInstance=e}};try{e(),t(),i(),n()}catch(e){throw this.logger.error("RedisManager initialization failed",{error:e instanceof Error?e.message:String(e)}),e}}getInstance(e){const t=e??this.defaultInstance?.getInstanceName();if(!t)throw new Error("A specific instance name was not provided and no default Redis instance is configured.");const i=this.instances.get(t);if(!i)throw new Error(`Redis instance with name "${t}" was not found. Please check that the name is spelled correctly in your configuration and code.`);return i}async shutdown(){this.logger.info("Closing all Redis connections...");const e=Array.from(this.instances.values()).map(e=>e.quit());await Promise.allSettled(e),this.instances.clear(),this.defaultInstance=void 0,this.logger.info("All Redis connections have been closed.")}}});exports.AdapterTransport=class extends u{constructor(e){if(!e.adapter)throw new Error("AdapterTransport requires a valid adapter implementation.");super(e),this.adapter=e.adapter}async log(e){if(!this.isLevelEnabled(e.level))return;const t=this.formatter?this.formatter.format(e):e;await this.adapter.log(t)}async flush(){"function"==typeof this.adapter.flush&&await this.adapter.flush()}async shutdown(){"function"==typeof this.adapter.shutdown&&await this.adapter.shutdown()}},exports.ClassicConsoleTransport=class extends Y{constructor(e){super(e),this.levelColorMap={fatal:this.chalk.bgRed.white.bold,error:this.chalk.red.bold,warn:this.chalk.yellow.bold,info:this.chalk.cyan.bold,audit:this.chalk.white.bold,debug:this.chalk.green,trace:this.chalk.gray}}formatTimestamp(e){const t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`}formatLogString(e){const{timestamp:t,level:i,service:n,message:r,context:s,...a}=e,o=this.levelColorMap[i]||this.chalk.white,c=this.formatTimestamp(t),l=o(i.toUpperCase().padEnd(5)),u=this.chalk.magenta(`[${n}]`),h={...s||{},...a,message:r},g=Object.keys(h);let d="";g.length>0&&(d=this.chalk.dim(" ["+g.map(e=>`${e}=${JSON.stringify(h[e])}`).join(" ")+"]"));return`${c} ${l} ${u}${d}`}},exports.ColorfulConsoleTransport=class extends Y{constructor(e){var t;super(e),this.levelStyleMap={trace:{level:(t=this.chalk).gray.bold,message:t.gray,metaKey:t.gray.dim,metaValue:t.gray},debug:{level:t.cyan.bold,message:t.cyan,metaKey:t.cyan.dim,metaValue:t.cyan},info:{level:t.green.bold,message:t.green,metaKey:t.green.dim,metaValue:t.green},warn:{level:t.yellow.bold,message:t.yellow,metaKey:t.yellow.dim,metaValue:t.yellow},error:{level:t.red.bold,message:t.red,metaKey:t.red.dim,metaValue:t.red},fatal:{level:t.red.bgWhite.bold,message:t.red.bold,metaKey:t.red.dim,metaValue:t.red},audit:{level:t.magenta.bold,message:t.magenta,metaKey:t.magenta.dim,metaValue:t.magenta}}}formatLogString(e){return((e,t,i)=>{const{timestamp:n,level:r,service:s,message:a,...o}=e,c=i[r]??{level:t.white.bold,message:t.white,metaKey:t.gray,metaValue:t.white},l=c.metaKey(new Date(n).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})),u=r.toUpperCase().padEnd(8),h=c.level(u),g=s?c.metaValue(`(${s})`):"";let d=`${l} ${h}`;g&&(d+=` ${g}`),d+=` ${c.message(a??"")}`;const m=Object.keys(o);if(m.length>0){const e=m.map(e=>{const t=o[e],i="object"==typeof t&&null!==t?JSON.stringify(t):String(t);return`${c.metaKey(e)}=${c.metaValue(i)}`});d+=`\n ${t.dim("└─")} ${e.join(" ")}`}return d})(e,this.chalk,this.levelStyleMap)}},exports.CompactConsoleTransport=class extends Y{constructor(e){super(e),this.levelColorMap={fatal:this.chalk.bgRed.white.bold,error:this.chalk.red.bold,warn:this.chalk.yellow.bold,info:this.chalk.cyan.bold,audit:this.chalk.white.bold,debug:this.chalk.green,trace:this.chalk.gray}}formatLogString(e){const{timestamp:t,level:i,service:n,message:r,...s}=e,a=this.levelColorMap[i]||this.chalk.white;let o=`${this.chalk.gray(new Date(t).toLocaleTimeString())} ${a(`[${i.toUpperCase()}]`)} ${this.chalk.blue(`(${n})`)}: ${r||""}`;const c=Object.keys(s);if(c.length>0){const e=c.map(e=>{const t=s[e],i="object"==typeof t&&null!==t?JSON.stringify(t):String(t);return`${this.chalk.dim(e)}=${this.chalk.gray(i)}`}).join(" ");o+=`\n ${this.chalk.dim("└─")} ${e}`}return o}},exports.ConsoleTransport=O,exports.PrettyConsoleTransport=class extends Y{constructor(e){var t;super(e),this.levelColorMap={fatal:(t=this.chalk).bgRed.white.bold,error:t.red.bold,warn:t.yellow.bold,info:t.blue.bold,audit:t.white.bold,debug:t.green,trace:t.gray}}formatLogString(e){return((e,t,i)=>{const{timestamp:n,level:r,service:s,message:a,...o}=e,c=i[r]||t.white;let l=`${t.gray(new Date(n).toLocaleTimeString())} ${c(`[${r.toUpperCase()}]`)} ${t.cyan(`(${s})`)}: ${a||""}`;Object.keys(o).length>0&&(l+=`\n${t.gray(JSON.stringify(o,null,2))}`);return l})(e,this.chalk,this.levelColorMap)}},exports.SanitizationEngine=j,exports.SerializationManager=_,exports.SpyTransport=class extends u{constructor(e){super(e),this.entries=[]}async log(e){this.entries.push(e)}getEntries(){return[...this.entries]}findEntries(e){return"function"==typeof e?this.entries.filter(e):this.entries.filter(t=>Object.keys(e).every(i=>{const n=i;return e[n]===t[n]}))}clear(){this.entries=[]}getFirstEntry(){return this.entries[0]}getLastEntry(){return this.entries[this.entries.length-1]}},exports.SyntropyLog=W,exports.Transport=u,exports.UniversalAdapter=class{constructor(e){if("function"!=typeof e.executor)throw new Error("UniversalAdapter requires an executor function.");this.executor=e.executor}async log(e){try{await this.executor(e)}catch(e){console.error(`UniversalAdapter execution failed: ${e instanceof Error?e.message:String(e)}`)}}},exports.UniversalLogFormatter=class{constructor(e){this.mapping=e.mapping,this.includeAllIn=e.includeAllIn}format(e){const t={};for(const[i,n]of Object.entries(this.mapping))t[i]=this.resolveValue(n,e);if(this.includeAllIn){const i=e.bindings??{},n=e.metadata??{};t[this.includeAllIn]={..."object"==typeof i&&null!==i?i:{},..."object"==typeof n&&null!==n?n:{}}}return t}resolveValue(e,t){if("object"==typeof e&&!Array.isArray(e)&&"value"in e){const t=e;return t.value??t.fallback}const i=Array.isArray(e)?e:[e];for(const e of i){if("object"==typeof e&&null!==e&&"value"in e){const t=e;return t.value??t.fallback}if("string"==typeof e){const i=this.getValueByPath(e,t);if(null!=i)return i}}}getValueByPath(e,t){if("message"===e)return t.message;if("level"===e)return t.level;if("timestamp"===e)return t.timestamp;const i=e.split(".");let n=t;for(const e of i){if(null===n||"object"!=typeof n)return;if(n===t&&!Object.prototype.hasOwnProperty.call(t,e)){const i=t,r=i.bindings?.[e];if(void 0!==r){n=r;continue}const s=i.metadata?.[e];if(void 0!==s){n=s;continue}}n=n[e]}return n}},exports.syntropyLog=K;
|
|
1
|
+
"use strict";var e=require("events"),t=require("node:async_hooks"),r=require("crypto");function i(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var s=i(require("node:util"));const n=e=>({ok:!0,value:e}),a=(...e)=>({ok:!1,errors:e}),o=e=>t=>null==t?n(void 0):e(t),l=e=>t=>{if(!Array.isArray(t))return a("must be an array");const r=[],i=[];for(let s=0;s<t.length;s++){const n=e(t[s]);n.ok?r.push(n.value):i.push(...n.errors.map(e=>`[${s}]: ${String(e)}`))}return i.length>0?{ok:!1,errors:i}:n(r)},c=e=>t=>{if(null===t||"object"!=typeof t||Array.isArray(t))return a("must be an object");const r=t,i={...r},s=[];for(const t of Object.keys(e)){const n=(0,e[t])(r[t]);n.ok?i[t]=n.value:s.push(...n.errors.map(e=>`${t}: ${String(e)}`))}return s.length>0?{ok:!1,errors:s}:n(i)},u=e=>"string"==typeof e?n(e):a("expected string, got "+typeof e),g=e=>"boolean"==typeof e?n(e):a("expected boolean, got "+typeof e),h=e=>{const t=(e=>"number"!=typeof e||Number.isNaN(e)?a("expected number, got "+typeof e):n(e))(e);return t.ok?!Number.isInteger(t.value)||t.value<1?a(`must be a positive integer (>= 1), got ${t.value}`):n(t.value):t},d=e=>t=>e.includes(t)?n(t):a(`must be one of [${e.join(", ")}], got ${String(t)}`),m=e=>t=>{const r=(e=>null===e||"object"!=typeof e||Array.isArray(e)?a("expected object, got "+(null===e?"null":typeof e)):n(e))(t);if(!r.ok)return r;const i={},s=[];for(const[t,n]of Object.entries(r.value)){const r=e(n);r.ok?i[t]=r.value:s.push(...r.errors.map(e=>`${t}: ${e}`))}return s.length?{ok:!1,errors:s}:n(i)},p={audit:70,fatal:60,error:50,warn:40,info:30,debug:20,trace:10,silent:0};class f{constructor(e={}){this.level=e.level??"info",this.name=e.name??this.constructor.name,this.formatter=e?.formatter,this.sanitizationEngine=e?.sanitizationEngine}isLevelEnabled(e){return p[e]>=p[this.level]}async flush(){return Promise.resolve()}}var y;!function(e){e.CREDIT_CARD="credit_card",e.SSN="ssn",e.EMAIL="email",e.PHONE="phone",e.PASSWORD="password",e.TOKEN="token",e.CUSTOM="custom"}(y||(y={}));class S{constructor(e){if(this.rules=[],this.initialized=!1,this.maskChar=e?.maskChar||"*",this.preserveLength=e?.preserveLength??!0,this.regexTimeoutMs=e?.regexTimeoutMs??100,!1!==e?.enableDefaultRules&&this.addDefaultRules(),e?.rules)for(const t of e.rules)this.addRule(t)}addDefaultRules(){const e=[{pattern:/credit_card|card_number|payment_number/i,strategy:y.CREDIT_CARD,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/ssn|social_security|security_number/i,strategy:y.SSN,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/email/i,strategy:y.EMAIL,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/phone|phone_number|mobile_number/i,strategy:y.PHONE,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/password|pass|pwd|secret/i,strategy:y.PASSWORD,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/token|api_key|auth_token|jwt|bearer/i,strategy:y.TOKEN,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0}];for(const t of e)this.addRule(t)}addRule(e){"string"==typeof e.pattern?e._compiledPattern=new RegExp(e.pattern,"i"):e._compiledPattern=e.pattern,e.preserveLength=e.preserveLength??this.preserveLength,e.maskChar=e.maskChar??this.maskChar,this.rules.push(e)}process(e){this.initialized||(this.initialized=!0);try{const t=new WeakSet;return this.applyMaskingRules(e,t)}catch{return{...S.buildSafeFallbackFromMeta(e),_maskingFailed:!0,_maskingFailedMessage:S.MASKING_FAILED_MESSAGE}}}static buildSafeFallbackFromMeta(e){const t={},r=["level","timestamp","message","service"];for(const i of r)i in e&&void 0!==e[i]&&(t[i]=e[i]);return t}applyMaskingRules(e,t){if(null===e||"object"!=typeof e)return e;if(t.has(e))return e;if(t.add(e),Array.isArray(e)){let r=!1;const i=new Array(e.length);for(let s=0;s<e.length;s++){const n=this.applyMaskingRules(e[s],t);i[s]=n,n!==e[s]&&(r=!0)}return r?i:e}const r=e;for(const e in r){if(!Object.prototype.hasOwnProperty.call(r,e))continue;const i=r[e];if("string"==typeof i)for(const t of this.rules){let s=!1;if(t._compiledPattern&&(s=t._isDefaultRule?t._compiledPattern.test(e):this.testRegexWithTimeout(t._compiledPattern,e)),s){r[e]=this.applyStrategy(i,t);break}}else if("object"==typeof i&&null!==i){const s=this.applyMaskingRules(i,t);s!==i&&(r[e]=s)}}return r}applyStrategy(e,t){if(t.strategy===y.CUSTOM&&t.customMask)return t.customMask(e);switch(t.strategy){case y.CREDIT_CARD:return this.maskCreditCard(e,t);case y.SSN:return this.maskSSN(e,t);case y.EMAIL:return this.maskEmail(e,t);case y.PHONE:return this.maskPhone(e,t);case y.PASSWORD:return this.maskPassword(e,t);case y.TOKEN:return this.maskToken(e,t);default:return this.maskDefault(e,t)}}maskCreditCard(e,t){const r=e.replace(/\D/g,"");return t.preserveLength?e.replace(/\d/g,(i,s)=>e.substring(0,s).replace(/\D/g,"").length<r.length-4?t.maskChar:i):`${t.maskChar.repeat(4)}-${t.maskChar.repeat(4)}-${t.maskChar.repeat(4)}-${r.slice(-4)}`}maskSSN(e,t){const r=e.replace(/\D/g,"");return t.preserveLength?e.replace(/\d/g,(i,s)=>e.substring(0,s).replace(/\D/g,"").length<r.length-4?t.maskChar:i):`***-**-${r.slice(-4)}`}maskEmail(e,t){const r=e.indexOf("@");if(r>0){const i=e.substring(0,r),s=e.substring(r);if(t.preserveLength){return(i.length>1?i.charAt(0)+t.maskChar.repeat(i.length-1):t.maskChar.repeat(i.length))+s}return`${i.charAt(0)}***${s}`}return this.maskDefault(e,t)}maskPhone(e,t){const r=e.replace(/\D/g,"");return t.preserveLength?e.replace(/\d/g,(i,s)=>e.substring(0,s).replace(/\D/g,"").length<r.length-4?t.maskChar:i):`${t.maskChar.repeat(3)}-${t.maskChar.repeat(3)}-${r.slice(-4)}`}maskPassword(e,t){return t.maskChar.repeat(e.length)}maskToken(e,t){return t.preserveLength?e.substring(0,4)+t.maskChar.repeat(e.length-9)+e.substring(e.length-5):e.length>8?e.substring(0,4)+"..."+e.substring(e.length-5):t.maskChar.repeat(e.length)}maskDefault(e,t){return t.preserveLength?t.maskChar.repeat(e.length):t.maskChar.repeat(Math.min(e.length,8))}getStats(){return{initialized:this.initialized,totalRules:this.rules.length,defaultRules:this.rules.filter(e=>[y.CREDIT_CARD,y.SSN,y.EMAIL,y.PHONE,y.PASSWORD,y.TOKEN].includes(e.strategy)).length,customRules:this.rules.filter(e=>e.strategy===y.CUSTOM).length,strategies:this.rules.map(e=>e.strategy)}}isInitialized(){return this.initialized}testRegexWithTimeout(e,t){if(t.length>256)return!1;try{return e.test(t)}catch{return!1}}shutdown(){this.rules=[],this.initialized=!1}}S.MASKING_FAILED_MESSAGE="[SyntropyLog] Masking could not be applied (e.g. timeout or error); payload redacted for safety.";class b extends Error{constructor(e){super(`[SyntropyLog] Configuration validation failed:\n${e.map(e=>` • ${e}`).join("\n")}`),this.name="ConfigValidationError",this.issues=e}}const v=d(["audit","fatal","error","warn","info","debug","trace","silent"]),w=e=>e instanceof f?n(e):a("must be an instance of Transport"),k=e=>{const t=w(e);return t.ok?t:c({transport:w,env:o(e=>"string"==typeof e||Array.isArray(e)?n(e):a("env must be a string or string[]"))})(e)},x=c({pattern:e=>"string"==typeof e||e instanceof RegExp?n(e):a("expected string or RegExp, got "+typeof e),strategy:d(Object.values(y)),preserveLength:o(g),maskChar:o(u),customMask:o(e=>"function"==typeof e?n(e):a("expected function, got "+typeof e))}),z=c({name:o(u),level:o(v),serviceName:o(u),environment:o(u),transportList:o(m(w)),env:o(m(l(u))),transports:o(e=>{if(Array.isArray(e)){const t=l(k)(e);return t.ok?n(t.value):t}return null!==e&&"object"==typeof e?n(e):a("transports must be an array or a record of arrays")}),serializerTimeoutMs:o(h),prettyPrint:o(c({enabled:o(g)}))}),D=c({rules:o(l(x)),maskChar:o(u),preserveLength:o(g),enableDefaultRules:o(g),regexTimeoutMs:o(h)}),M=c({default:o(l(u)),trace:o(l(u)),debug:o(l(u)),info:o(l(u)),warn:o(l(u)),error:o(l(u)),fatal:o(l(u))}),C=c({correlationIdHeader:o(u),transactionIdHeader:o(u)}),E=c({logger:o(z),loggingMatrix:o(M),masking:o(D),context:o(C),shutdownTimeout:o(h)});const O=Object.freeze({});class I{constructor(e){this.storage=new t.AsyncLocalStorage,this.correlationIdHeader="x-correlation-id",this.transactionIdHeader="x-trace-id",this.storage=new t.AsyncLocalStorage,this.loggingMatrix=e}configure(e){e.correlationIdHeader&&(this.correlationIdHeader=e.correlationIdHeader),e.transactionIdHeader&&(this.transactionIdHeader=e.transactionIdHeader)}reconfigureLoggingMatrix(e){this.loggingMatrix=e}run(e){return new Promise((t,r)=>{const i=this.storage.getStore(),s=new Map(i?.data);this.storage.run({data:s},async()=>{try{await Promise.resolve(e()),t()}catch(e){r(e)}})})}get(e){return this.storage.getStore()?.data.get(e)}getAll(){const e=this.storage.getStore();return e?Object.fromEntries(e.data.entries()):{}}set(e,t){const r=this.storage.getStore();r&&r.data.set(e,t)}getCorrelationId(){let e=this.get(this.correlationIdHeader)||this.get("correlationId");return e&&"string"==typeof e||(e=r.randomUUID(),this.set(this.correlationIdHeader,e)),e}setCorrelationId(e){this.set(this.correlationIdHeader,e)}getTransactionId(){return this.get("transactionId")}setTransactionId(e){this.set("transactionId",e)}getCorrelationIdHeaderName(){return this.correlationIdHeader}getTransactionIdHeaderName(){return this.transactionIdHeader}getTraceContextHeaders(){const e={};if(!this.storage.getStore())return e;const t=this.getCorrelationId(),r=this.getTransactionId();return t&&(e[this.getCorrelationIdHeaderName()]=t),r&&(e[this.getTransactionIdHeaderName()]=r),e}getFilteredContext(e){const t=this.getAll();if(!this.loggingMatrix){const e=Object.keys(t).length,r=this.get(this.correlationIdHeader),i=this.get("correlationId");if(0===e&&!r&&!i)return O;const s={};return Object.assign(s,t),!r&&i&&(s[this.correlationIdHeader]=i),s}const r=this.loggingMatrix[e]??this.loggingMatrix.default;if(!r)return O;const i={correlationId:[this.correlationIdHeader,"correlationId"],transactionId:[this.transactionIdHeader,"transactionId"],userId:["userId"],serviceName:["serviceName"],operation:["operation"],errorCode:["errorCode"],tenantId:["tenantId"],paymentId:["paymentId"],orderId:["orderId"],processorId:["processorId"],eventType:["eventType"]};if(r.includes("*")){const e={};for(const[r,s]of Object.entries(t)){let t=r;for(const[e,s]of Object.entries(i))if(s.includes(r)){t=e;break}e[t]=s}return e}const s={};for(const e of r){const r=i[e]||[e];for(const i of r)if(Object.prototype.hasOwnProperty.call(t,i)){s[e]=t[i];break}!Object.prototype.hasOwnProperty.call(s,e)&&Object.prototype.hasOwnProperty.call(t,e)&&(s[e]=t[e])}return s}}const L={depth:0,maxDepth:10,sensitiveFields:[],sanitize:!0};class R{constructor(e,t,r,i={}){this.pendingRouting=null,this.name=e,this.transports=t,this.dependencies=r,this.bindings=i.bindings??{},this.level=i.level??"info"}override(...e){return this.pendingRouting={override:e},this}add(...e){const t=this.pendingRouting,r=[...t&&"add"in t?t.add??[]:[],...e],i=t&&"remove"in t?t.remove??[]:void 0;return this.pendingRouting=i?.length?{add:r,remove:i}:{add:r},this}remove(...e){const t=this.pendingRouting,r=[...t&&"remove"in t?t.remove??[]:[],...e],i=t&&"add"in t?t.add??[]:void 0;return this.pendingRouting=i?.length?{add:i,remove:r}:{remove:r},this}captureEffectiveTransports(){const e=this.pendingRouting;return this.pendingRouting=null,function(e,t,r){if(!t||!r)return e;if("override"in r)return r.override.map(e=>t.get(e)).filter(e=>null!=e);let i=[...e];if(r.add?.length)for(const e of r.add){const r=t.get(e);r&&i.push(r)}if(r.remove?.length){const e=new Set(r.remove);i=i.filter(t=>!e.has(t.name))}return i}(this.transports,this.dependencies.transportPool,e)}async _log(e,...t){if("silent"===e)return;if(!function(e,t){return"silent"!==e&&("audit"===e||p[e]>=p[t])}(e,this.level))return;const r=this.captureEffectiveTransports();try{const{message:i,metadata:n}=function(e){let t,r={};if(0===e.length)t="";else if("object"!=typeof e[0]||null===e[0]||Array.isArray(e[0])){t=e[0]||"";const r=e.slice(1);t&&r.length>0&&(t=s.format(t,...r))}else{r=e[0],t=e[1]||"";const i=e.slice(2);t&&i.length>0&&(t=s.format(t,...i))}return{message:t||"",metadata:r}}(t),a=this.dependencies.contextManager.getFilteredContext(e),o={level:e,timestamp:(new Date).toISOString(),service:this.name,message:i};Object.assign(o,a,this.bindings,n);const l=this.dependencies.serializationManager.serialize(o,L).data,c=this.dependencies.maskingEngine.process(l);for(const t of r)t.isLevelEnabled(e)&&t.log(c)}catch{}}info(...e){return this._log("info",...e)}warn(...e){return this._log("warn",...e)}error(...e){return this._log("error",...e)}debug(...e){return this._log("debug",...e)}trace(...e){return this._log("trace",...e)}audit(...e){return this._log("audit",...e)}fatal(...e){return this._log("fatal",...e)}setLevel(e){this.level=e}child(e){return new R(this.name,this.transports,this.dependencies,{level:this.level,bindings:{...this.bindings,...e}})}withSource(e){return this.child({source:e})}withRetention(e){return this.child({retention:e})}withTransactionId(e){return this.child({transactionId:e})}}var T;exports.SerializationComplexity=void 0,(T=exports.SerializationComplexity||(exports.SerializationComplexity={})).SIMPLE="simple",T.COMPLEX="complex",T.CRITICAL="critical";class P{constructor(){this.defaultSensitiveFields=["password","token","secret","key","auth","authorization","api_key","apikey","private_key","privatekey","credential","credential_id","credentialid","access_token","accesstoken","refresh_token","refreshtoken","session_id","sessionid"],this.defaultMaxDepth=10}sanitize(e,t={}){const r=t.sensitiveFields||this.defaultSensitiveFields,i=t.maxDepth||this.defaultMaxDepth,s=t.currentDepth||0;if(s>=i)return"[MAX_DEPTH_REACHED]";if(null==e)return e;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e)){const t={sensitiveFields:r,maxDepth:i,currentDepth:s+1};for(let r=0;r<e.length;r++){const i=this.sanitize(e[r],t);i!==e[r]&&(e[r]=i)}return e}if("object"==typeof e){const t=e;for(const e of Object.keys(t)){const n=e.toLowerCase();if(r.some(e=>n.includes(e.toLowerCase())))t[e]="[REDACTED]";else{const n=this.sanitize(t[e],{sensitiveFields:r,maxDepth:i,currentDepth:s+1});n!==t[e]&&(t[e]=n)}}return e}return e}}const A="pipeline",j="unknown";class ${constructor(){this.steps=[],this.timeoutStrategies=new Map,this.metrics=null,this.sanitizer=new P,this.initializeDefaultStrategies()}addStep(e){this.steps.push(e)}addTimeoutStrategy(e){this.timeoutStrategies.set(e.getStrategyName(),e)}process(e,t){const r=Date.now();this.metrics={stepDurations:{},totalDuration:0,operationTimeout:0,timeoutStrategy:j};let i=e;try{for(const e of this.steps){const r=Date.now();i=e.execute(i,t),this.metrics.stepDurations[e.name]=Date.now()-r}const e=this.selectTimeoutStrategy(i),s=e.calculateTimeout(i);return this.metrics.operationTimeout=s,this.metrics.timeoutStrategy=e.getStrategyName(),this.metrics.totalDuration=Date.now()-r,$.buildSuccessResult(i,t.sanitizeSensitiveData,this.metrics,s,e.getStrategyName())}catch(e){return this.metrics.totalDuration=Date.now()-r,$.buildErrorResult(i,e,this.metrics)}}getMetrics(){return this.metrics}static buildSuccessResult(e,t,r,i,s){const n=e,a=n.serializer??A,o=n.serializationComplexity??exports.SerializationComplexity.SIMPLE;return{success:!0,data:e,serializer:a,duration:r.totalDuration,complexity:o,sanitized:t,metadata:{stepDurations:r.stepDurations,operationTimeout:i,timeoutStrategy:s,serializer:a,complexity:o}}}static buildErrorResult(e,t,r){const i=t?.serializer??A;return{success:!1,data:e,serializer:i,duration:r.totalDuration,complexity:exports.SerializationComplexity.SIMPLE,sanitized:!1,error:t instanceof Error?t.message:String(t),metadata:{stepDurations:r.stepDurations,operationTimeout:0,timeoutStrategy:j,serializer:i,complexity:exports.SerializationComplexity.SIMPLE}}}selectTimeoutStrategy(e){const t=this.timeoutStrategies.get("default");if(null==t)throw new Error("SerializationPipeline: default timeout strategy is required");return t}initializeDefaultStrategies(){this.addTimeoutStrategy(new _)}}class _{calculateTimeout(e){return 5e3}getStrategyName(){return"default"}}class N{constructor(e=[]){this.name="serialization",this.serializers=[],this.serializers=e}addSerializer(e){const t=this.serializers.findIndex(t=>t.priority<e.priority);-1===t?this.serializers.push(e):this.serializers.splice(t,0,e)}execute(e,t){const r=Date.now(),i=this.findSerializer(e);if(!i)return e;try{const s=i.serialize(e,t.serializationContext),n=Date.now()-r,a="object"==typeof s.data&&null!==s.data?s.data:{};return a.serializationDuration=n,a.serializer=i.name,a.serializationComplexity=s.complexity||s.metadata?.complexity||null,a}catch(e){throw e instanceof Error&&!e.serializer&&(e.serializer=i.name),e}}findSerializer(e){for(const t of this.serializers)if(t.canSerialize(e))return t;return null}getRegisteredSerializers(){return this.serializers.map(e=>e.name)}}function H(e,t){if(null===e||"object"!=typeof e)return e;if(t.has(e))return"[Circular]";if(t.add(e),Array.isArray(e)){let r=!1;const i=new Array(e.length);for(let s=0;s<e.length;s++){const n=H(e[s],t);i[s]=n,n!==e[s]&&(r=!0)}return t.delete(e),r?i:e}for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const i=e[r],s=H(i,t);s!==i&&(e[r]=s)}return t.delete(e),e}class F{constructor(){this.name="hygiene"}execute(e,t){if(null===e||"object"!=typeof e)return e;try{if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack,...e};try{return JSON.stringify(e),e}catch{let t;try{t=H(e,new WeakSet)}catch(e){let t;try{t=e instanceof Error?e.message:String(e)}catch{t="unknown"}return`[HYGIENE_ERROR: ${t}]`}return t}}catch(e){let t;try{t=e instanceof Error?e.message:String(e)}catch{t="unknown"}return`[HYGIENE_ERROR: ${t}]`}}}function K(e,t,r,i){if("object"==typeof e&&null!==e){const s=e;return s.sanitizationDuration=t,s.sanitized=r,void 0!==i&&(s.sanitizationError=i),e}return{sanitizationDuration:t,sanitized:r,...void 0!==i&&{sanitizationError:i}}}class U{constructor(e){this.name="sanitization",this.sanitizer=e??new P}execute(e,t){const r=Date.now(),i=()=>Date.now()-r;if(!t.sanitizeSensitiveData)return K(e,i(),!1);try{return K(this.sanitizer.sanitize(e,t.sanitizationContext),i(),!0)}catch(t){return K(e,i(),!1,function(e){return e instanceof Error?e.message:String(e)}(t))}}}const G=3e3;class W{constructor(e){this.name="timeout",this.timeoutStrategies=new Map,this.timeoutStrategies=e}execute(e,t){const r=Date.now();try{const t=this.selectTimeoutStrategy(e),i=t?.calculateTimeout(e)??G;return function(e,t,r,i){if("object"==typeof e&&null!==e){const s=e;return s.timeoutDuration=t,s.operationTimeout=r,s.timeoutStrategy=i?.getStrategyName()??"default",s.timeoutApplied=null!=i,e}return{timeoutDuration:t,operationTimeout:r,timeoutStrategy:i?.getStrategyName()??"default",timeoutApplied:null!=i}}(e,Date.now()-r,i,t)}catch(t){return function(e,t,r){if("object"==typeof e&&null!==e){const i=e;return i.timeoutDuration=t,i.operationTimeout=G,i.timeoutStrategy="default",i.timeoutApplied=!1,i.timeoutError=r instanceof Error?r.message:"Timeout error",e}return{timeoutDuration:t,operationTimeout:G,timeoutStrategy:"default",timeoutApplied:!1,timeoutError:r instanceof Error?r.message:"Timeout error"}}(e,Date.now()-r,t)}}selectTimeoutStrategy(e){return this.timeoutStrategies.get("default")??null}}class V{constructor(e={}){this.config={timeoutMs:e.timeoutMs||5e3,enableMetrics:e.enableMetrics??!0,sanitizeSensitiveData:e.sanitizeSensitiveData??!0,sanitizationContext:{sensitiveFields:e.sanitizationContext?.sensitiveFields||["password","token","secret","key","auth","credential","api_key","private_key","connection_string","wallet_location"],redactPatterns:e.sanitizationContext?.redactPatterns||[/password\s*=\s*['"][^'"]*['"]/gi,/user\s*=\s*['"][^'"]*['"]/gi,/token\s*=\s*['"][^'"]*['"]/gi,/secret\s*=\s*['"][^'"]*['"]/gi],maxStringLength:e.sanitizationContext?.maxStringLength||300,enableDeepSanitization:e.sanitizationContext?.enableDeepSanitization??!0}},this.metrics={totalSerializations:0,successfulSerializations:0,failedSerializations:0,totalSerializationDuration:0,totalOperationTimeout:0,maxSerializationDuration:0,minSerializationDuration:0,complexityDistribution:{low:0,medium:0,high:0},serializerDistribution:{},timeoutStrategyDistribution:{}},this.pipeline=new $,this.serializationStep=new N,this.hygieneStep=new F,this.sanitizationStep=new U,this.timeoutStep=new W(this.pipeline.timeoutStrategies),this.pipeline.addStep(this.serializationStep),this.pipeline.addStep(this.hygieneStep),this.pipeline.addStep(this.sanitizationStep),this.pipeline.addStep(this.timeoutStep)}register(e){this.serializationStep.addSerializer(e)}serialize(e,t={depth:0,maxDepth:10,sensitiveFields:[],sanitize:!0}){const r=Date.now(),i={serializationContext:t,sanitizeSensitiveData:this.config.sanitizeSensitiveData,sanitizationContext:this.config.sanitizationContext,enableMetrics:this.config.enableMetrics},s=this.pipeline.process(e,i);return this.config.enableMetrics&&this.updateMetrics(s,Date.now()-r),s}updateMetrics(e,t){if(this.metrics.totalSerializations++,e.success){this.metrics.successfulSerializations++;const t=(e.metadata.stepDurations?.serialization||0)+(e.metadata.stepDurations?.hygiene||0);this.metrics.totalSerializationDuration+=t,this.metrics.maxSerializationDuration=Math.max(this.metrics.maxSerializationDuration,t),this.metrics.minSerializationDuration=0===this.metrics.minSerializationDuration?t:Math.min(this.metrics.minSerializationDuration,t);const r=e.metadata.operationTimeout||0;this.metrics.totalOperationTimeout+=r;const i=e.complexity||exports.SerializationComplexity.SIMPLE;i===exports.SerializationComplexity.SIMPLE?this.metrics.complexityDistribution.low++:i===exports.SerializationComplexity.COMPLEX?this.metrics.complexityDistribution.medium++:i===exports.SerializationComplexity.CRITICAL&&this.metrics.complexityDistribution.high++;const s=e.serializer||"unknown";this.metrics.serializerDistribution[s]=(this.metrics.serializerDistribution[s]||0)+1;const n=e.metadata.timeoutStrategy||"unknown";this.metrics.timeoutStrategyDistribution[n]=(this.metrics.timeoutStrategyDistribution[n]||0)+1}else this.metrics.failedSerializations++}getMetrics(){return{totalSerializations:this.metrics.totalSerializations,successfulSerializations:this.metrics.successfulSerializations,failedSerializations:this.metrics.failedSerializations,averageSerializationDuration:this.metrics.totalSerializations>0?this.metrics.totalSerializationDuration/this.metrics.totalSerializations:0,averageOperationTimeout:this.metrics.successfulSerializations>0?this.metrics.totalOperationTimeout/this.metrics.successfulSerializations:0,maxSerializationDuration:this.metrics.maxSerializationDuration,minSerializationDuration:this.metrics.minSerializationDuration,complexityDistribution:{...this.metrics.complexityDistribution},serializerDistribution:{...this.metrics.serializerDistribution},timeoutStrategyDistribution:{...this.metrics.timeoutStrategyDistribution}}}resetMetrics(){this.metrics={totalSerializations:0,successfulSerializations:0,failedSerializations:0,totalSerializationDuration:0,totalOperationTimeout:0,maxSerializationDuration:0,minSerializationDuration:0,complexityDistribution:{low:0,medium:0,high:0},serializerDistribution:{},timeoutStrategyDistribution:{}}}getRegisteredSerializers(){return this.serializationStep.getRegisteredSerializers()}getPipelineMetrics(){return this.pipeline.getMetrics()}}class q extends f{constructor(e){super(e)}log(e){if(!this.isLevelEnabled(e.level))return;const t=this.formatter?this.formatter.format(e):e,r=JSON.stringify(t);switch(e.level){case"fatal":case"error":console.error(r);break;case"warn":console.warn(r);break;default:console.log(r)}}}class Y{constructor(e){this.ansiRegex=/[\x1b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,this.maskingEngine=e}async process(e){let t=this.sanitizeRecursively(e);return this.maskingEngine&&(t=this.maskingEngine.process(t)),t}sanitizeRecursively(e){if("string"==typeof e)return e.replace(this.ansiRegex,"");if(Array.isArray(e))return e.map(e=>this.sanitizeRecursively(e));if("object"==typeof e&&null!==e&&e.constructor===Object){const t={},r=e;for(const e in r)Object.prototype.hasOwnProperty.call(r,e)&&(t[e]=this.sanitizeRecursively(r[e]));return t}return e}}function J(e,t){const r=[];for(const i of e)if(i instanceof f)r.push(i);else if(i&&"object"==typeof i&&"transport"in i){const e=null==i.env?null:Array.isArray(i.env)?i.env:[i.env];(null===e||e.includes(t))&&r.push(i.transport)}else i&&"object"==typeof i&&r.push(i);return r}class Z{constructor(e,t,r){this.loggerPool=new Map,this.MAX_POOL_SIZE=1e3,this.contextManager=t,this.syntropyLogInstance=r,e.context&&this.contextManager.configure(e.context);const i=(e=>{const t=e.logger?.environment??"development",r=e.logger?.transportList&&Object.keys(e.logger.transportList).length>0,i=e.logger?.env&&Object.keys(e.logger.env).length>0;if(r&&i&&e.logger?.transportList&&e.logger?.env){const r=new Map(Object.entries(e.logger.transportList));return{transports:{default:(e.logger.env[t]??[]).map(e=>r.get(e)).filter(e=>null!=e)},transportPool:r}}if(e.logger?.transports){const r=e.logger.transports,i=new Map,s=e=>{const t=e instanceof f?e:e&&"object"==typeof e&&"transport"in e?e.transport:e,r=t.name??t.constructor?.name??`transport-${i.size}`;return i.set(r,t),t};let n;if(Array.isArray(r))r.forEach(s),n={default:J(r,t)};else{const e=r;n={};for(const[r,i]of Object.entries(e))i.forEach(s),n[r]=J(i,t)}return{transports:n,transportPool:i}}{const e=new Y,t=new q({sanitizationEngine:e,name:"console"});return{transports:{default:[t]},transportPool:new Map([["console",t]])}}})(e);this.transports=i.transports,this.transportPool=i.transportPool,this.globalLogLevel=e.logger?.level??"info",this.serviceName=e.logger?.serviceName??"unknown-service",this.serializationManager=new V({timeoutMs:e.logger?.serializerTimeoutMs,sanitizeSensitiveData:!1!==e.masking?.enableDefaultRules}),this.maskingEngine=new S({rules:e.masking?.rules,maskChar:e.masking?.maskChar,preserveLength:e.masking?.preserveLength,enableDefaultRules:!1!==e.masking?.enableDefaultRules,regexTimeoutMs:e.masking?.regexTimeoutMs})}getLogger(e="default",t){const r=((e,t)=>{if(!t||0===Object.keys(t).length)return e;const r=Object.keys(t).sort().reduce((e,r)=>(e[r]=t[r],e),{});try{return`${e}:${JSON.stringify(r)}`}catch{return`${e}:${Object.keys(r).sort().join(",")}`}})(e,t);if(this.loggerPool.has(r)){const e=this.loggerPool.get(r);return this.loggerPool.delete(r),this.loggerPool.set(r,e),e}const i="default"===e?this.serviceName:e,s={contextManager:this.contextManager,serializationManager:this.serializationManager,maskingEngine:this.maskingEngine,syntropyLogInstance:this.syntropyLogInstance,transportPool:this.transportPool},n=this.transports[e]??this.transports.default,a=new R(i,n,s,{bindings:t});if(a.level=this.globalLogLevel,this.loggerPool.size>=this.MAX_POOL_SIZE){const e=this.loggerPool.keys().next().value;void 0!==e&&this.loggerPool.delete(e)}return this.loggerPool.set(r,a),a}async flushAllTransports(){const e=Object.values(this.transports).flat(),t=Array.from(new Set(e)).map(e=>e.flush().catch(t=>{console.error(`Error flushing transport ${e.constructor.name}:`,t)}));await Promise.allSettled(t)}async shutdown(){try{await this.flushAllTransports(),this.loggerPool.clear();const e=Object.values(this.transports).flat(),t=Array.from(new Set(e)).map(e=>"function"==typeof e.shutdown?e.shutdown().catch(t=>{console.error(`Error shutting down transport ${e.constructor.name}:`,t)}):Promise.resolve());await Promise.allSettled(t)}catch(e){console.error("Error during LoggerFactory shutdown:",e)}}}const X="[CONFIG_MASKED]",B=["password","token","secret","apikey","credential","pass","key","accesstoken","refreshtoken","clientsecret","sentinelpassword","sasl"];function Q(e){if(e instanceof f)return e;if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Q(e));const t={},r=B.map(e=>e.toLowerCase());for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const s=i.toLowerCase(),n=e[i];r.includes(s)?t[i]=X:(s.includes("url")||s.includes("uri"))&&"string"==typeof n?t[i]=n.replace(/(?<=:\/\/)[^:]+:[^@]+@/,`${X}@`):"object"!=typeof n||null===n||n instanceof RegExp?t[i]=n:t[i]=Q(n)}return t}function ee(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack||null}:String(e)}class te extends e.EventEmitter{constructor(e){super(),this.state="NOT_INITIALIZED",this.logger=null,this.trackedProcesses=new Set,this.syntropyFacade=e,this.config={},this.serializationManager=new V({}),this.maskingEngine=new S({})}getState(){return this.state}async init(e){if("NOT_INITIALIZED"===this.state){this.state="INITIALIZING";try{const t=Q(function(e){const t=E(e);if(!t.ok)throw new b(t.errors);return t.value}(e));this.config=t,this.contextManager=new I(this.config.loggingMatrix),this.config.context&&this.contextManager.configure(this.config.context),this.serializationManager=new V({timeoutMs:this.config.logger?.serializerTimeoutMs,sanitizeSensitiveData:!1!==this.config.masking?.enableDefaultRules}),this.maskingEngine=new S({rules:this.config.masking?.rules,maskChar:this.config.masking?.maskChar,preserveLength:this.config.masking?.preserveLength,enableDefaultRules:!1!==this.config.masking?.enableDefaultRules,regexTimeoutMs:this.config.masking?.regexTimeoutMs}),this.loggerFactory=new Z(this.config,this.contextManager,this.syntropyFacade);const r=this.loggerFactory.getLogger("syntropylog-main");this.logger=r,r.info("SyntropyLog framework initialized successfully."),this.state="READY",this.emit("ready")}catch(e){throw this.state="ERROR",this.emit("error",e),e instanceof b?console.error("[SyntropyLog] Configuration validation failed:",e.issues):console.error("[SyntropyLog] Failed to initialize framework:",e),e}}else this.logger?.warn(`LifecycleManager.init() called while in state '${this.state}'. Ignoring subsequent call.`)}async shutdown(){if(this.logger?.info(`🔄 LifecycleManager.shutdown() called. Current state: ${this.state}`),"READY"===this.state){this.state="SHUTTING_DOWN",this.emit("shutting_down"),this.logger?.info("🔄 State changed to SHUTTING_DOWN");try{this.logger?.info("Shutting down SyntropyLog framework..."),this.maskingEngine?.shutdown?.();const e=[];e.push(this.terminateExternalProcesses()),this.logger?.info(`📋 Executing ${e.length} shutdown steps...`),await Promise.allSettled(e),await(this.logger?.info("✅ Shutdown steps completed")),await(this.logger?.info("All managers have been shut down.")),await(this.logger?.info("✅ State changed to SHUTDOWN")),await(this.loggerFactory?.shutdown?.()),"SHUTTING_DOWN"===this.state&&this.emit("transports_drained"),this.state="SHUTDOWN",this.emit("shutdown")}catch(e){this.state="ERROR",this.emit("error",e),this.logger?.error("❌ Error during shutdown:",{error:ee(e)}),await(this.loggerFactory?.shutdown?.()),"ERROR"===this.state&&this.emit("transports_drained")}}else this.logger?.warn(`❌ Cannot perform shutdown. Current state: ${this.state}`)}registerChildProcess(e){this.trackedProcesses.add(e),e.on("exit",()=>{this.trackedProcesses.delete(e)})}async terminateExternalProcesses(){try{if(0===this.trackedProcesses.size)return void this.logger?.info("No tracked external processes to terminate");this.logger?.info(`Terminating ${this.trackedProcesses.size} external processes...`);const e=Array.from(this.trackedProcesses).map(e=>(async(e,t)=>{if(!e.connected&&null!==e.exitCode)return;const r=e.pid;t?.debug(`Sending SIGTERM to process ${r}...`),e.kill("SIGTERM");const i=new Promise(t=>{const r=()=>{t(),e.removeListener("exit",r)};e.on("exit",r)}),s=new Promise(e=>setTimeout(e,5e3));await Promise.race([i,s]),null===e.exitCode?(t?.warn(`Process ${r} did not exit after SIGTERM, sending SIGKILL...`),e.kill("SIGKILL")):t?.debug(`Process ${r} exited gracefully`)})(e,this.logger));await Promise.allSettled(e),this.trackedProcesses.clear(),this.logger?.info("✅ All external processes terminated")}catch(e){this.logger?.warn("Error terminating external processes:",{error:ee(e)})}}ensureReady(){if("READY"!==this.state)throw new Error(`SyntropyLog is not ready. Current state: '${this.state}'. Ensure init() has completed successfully by listening for the 'ready' event.`)}}function re(e,t){if(null==e)throw new Error(t)}class ie extends e.EventEmitter{constructor(){super(),this.lifecycleManager=new te(this),this.lifecycleManager.on("ready",()=>this.emit("ready")),this.lifecycleManager.on("error",e=>this.emit("error",e)),this.lifecycleManager.on("shutting_down",()=>this.emit("shutting_down")),this.lifecycleManager.on("transports_drained",()=>this.emit("transports_drained")),this.lifecycleManager.on("shutdown",()=>this.emit("shutdown"))}static getInstance(){return ie.instance||(ie.instance=new ie),ie.instance}static resetInstance(){ie.instance=void 0}getState(){return this.lifecycleManager.getState()}async init(e){return this.lifecycleManager.init(e)}async shutdown(){return this.lifecycleManager.shutdown()}getLogger(e="default",t){return re(this.lifecycleManager.loggerFactory,"Logger Factory not available."),this.lifecycleManager.loggerFactory.getLogger(e,t)}getContextManager(){return this.lifecycleManager.ensureReady(),this.lifecycleManager.contextManager}getConfig(){return this.lifecycleManager.ensureReady(),this.lifecycleManager.config}getFilteredContext(e){return this.lifecycleManager.ensureReady(),this.lifecycleManager.contextManager.getFilteredContext(e)}reconfigureLoggingMatrix(e){this.lifecycleManager.ensureReady(),this.lifecycleManager.contextManager.reconfigureLoggingMatrix(e)}getMasker(){return re(this.lifecycleManager.maskingEngine,"MaskingEngine not available."),this.lifecycleManager.maskingEngine}getSerializer(){return re(this.lifecycleManager.serializationManager,"SerializationManager not available."),this.lifecycleManager.serializationManager}_resetForTesting(){this.lifecycleManager.removeAllListeners(),Object.assign(this,{lifecycleManager:new te(this)}),this.removeAllListeners(),this.lifecycleManager.on("ready",()=>this.emit("ready")),this.lifecycleManager.on("error",e=>this.emit("error",e)),this.lifecycleManager.on("shutting_down",()=>this.emit("shutting_down")),this.lifecycleManager.on("shutdown",()=>this.emit("shutdown"))}}const se=ie.getInstance();function ne(e){const t=t=>function(e,t){return 0===t.length?e:`[${t.join(";")}m${e}[0m`}(t,e),r=t=>ne([...e,t]);return Object.defineProperty(t,"white",{get:()=>r(37),enumerable:!0}),Object.defineProperty(t,"bold",{get:()=>r(1),enumerable:!0}),Object.defineProperty(t,"red",{get:()=>r(31),enumerable:!0}),Object.defineProperty(t,"bgRed",{get:()=>r(41),enumerable:!0}),Object.defineProperty(t,"yellow",{get:()=>r(33),enumerable:!0}),Object.defineProperty(t,"cyan",{get:()=>r(36),enumerable:!0}),Object.defineProperty(t,"green",{get:()=>r(32),enumerable:!0}),Object.defineProperty(t,"gray",{get:()=>r(90),enumerable:!0}),Object.defineProperty(t,"magenta",{get:()=>r(35),enumerable:!0}),Object.defineProperty(t,"blue",{get:()=>r(34),enumerable:!0}),Object.defineProperty(t,"bgWhite",{get:()=>r(47),enumerable:!0}),Object.defineProperty(t,"dim",{get:()=>r(2),enumerable:!0}),t}let ae=null;function oe(){if(null!==ae)return ae;const e=void 0!==process.env.NO_COLOR&&""!==process.env.NO_COLOR&&"0"!==process.env.NO_COLOR,t="boolean"==typeof process.stdout?.isTTY&&process.stdout.isTTY;if(e||!t){const e=e=>e;e.white=e,e.bold=e,e.red=e,e.bgRed=e,e.yellow=e,e.cyan=e,e.green=e,e.gray=e,e.magenta=e,e.blue=e,e.bgWhite=e,e.dim=e,ae=e}else ae=ne([]);return ae}class le extends f{constructor(e){super(e),this.chalk=oe()}async log(e){if(!this.isLevelEnabled(e.level))return;const t=this.formatter?this.formatter.format(e):e,r=this.formatLogString(t);this.getConsoleMethod(t.level)(r)}getConsoleMethod(e){switch(e){case"fatal":case"error":return console.error;case"warn":return console.warn;default:return console.log}}}exports.AdapterTransport=class extends f{constructor(e){if(!e.adapter)throw new Error("AdapterTransport requires a valid adapter implementation.");super(e),this.adapter=e.adapter}async log(e){if(!this.isLevelEnabled(e.level))return;const t=this.formatter?this.formatter.format(e):e;await this.adapter.log(t)}async flush(){"function"==typeof this.adapter.flush&&await this.adapter.flush()}async shutdown(){"function"==typeof this.adapter.shutdown&&await this.adapter.shutdown()}},exports.ClassicConsoleTransport=class extends le{constructor(e){super(e),this.levelColorMap={fatal:this.chalk.bgRed.white.bold,error:this.chalk.red.bold,warn:this.chalk.yellow.bold,info:this.chalk.cyan.bold,audit:this.chalk.white.bold,debug:this.chalk.green,trace:this.chalk.gray}}formatTimestamp(e){const t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`}formatLogString(e){const{timestamp:t,level:r,service:i,message:s,context:n,...a}=e,o=this.levelColorMap[r]||this.chalk.white,l=this.formatTimestamp(t),c=o(r.toUpperCase().padEnd(5)),u=this.chalk.magenta(`[${i}]`),g={...n||{},...a,message:s},h=Object.keys(g);let d="";h.length>0&&(d=this.chalk.dim(" ["+h.map(e=>`${e}=${JSON.stringify(g[e])}`).join(" ")+"]"));return`${l} ${c} ${u}${d}`}},exports.ColorfulConsoleTransport=class extends le{constructor(e){var t;super(e),this.levelStyleMap={trace:{level:(t=this.chalk).gray.bold,message:t.gray,metaKey:t.gray.dim,metaValue:t.gray},debug:{level:t.cyan.bold,message:t.cyan,metaKey:t.cyan.dim,metaValue:t.cyan},info:{level:t.green.bold,message:t.green,metaKey:t.green.dim,metaValue:t.green},warn:{level:t.yellow.bold,message:t.yellow,metaKey:t.yellow.dim,metaValue:t.yellow},error:{level:t.red.bold,message:t.red,metaKey:t.red.dim,metaValue:t.red},fatal:{level:t.red.bgWhite.bold,message:t.red.bold,metaKey:t.red.dim,metaValue:t.red},audit:{level:t.magenta.bold,message:t.magenta,metaKey:t.magenta.dim,metaValue:t.magenta}}}formatLogString(e){return((e,t,r)=>{const{timestamp:i,level:s,service:n,message:a,...o}=e,l=r[s]??{level:t.white.bold,message:t.white,metaKey:t.gray,metaValue:t.white},c=l.metaKey(new Date(i).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})),u=s.toUpperCase().padEnd(8),g=l.level(u),h=n?l.metaValue(`(${n})`):"";let d=`${c} ${g}`;h&&(d+=` ${h}`),d+=` ${l.message(a??"")}`;const m=Object.keys(o);if(m.length>0){const e=m.map(e=>{const t=o[e],r="object"==typeof t&&null!==t?JSON.stringify(t):String(t);return`${l.metaKey(e)}=${l.metaValue(r)}`});d+=`\n ${t.dim("└─")} ${e.join(" ")}`}return d})(e,this.chalk,this.levelStyleMap)}},exports.CompactConsoleTransport=class extends le{constructor(e){super(e),this.levelColorMap={fatal:this.chalk.bgRed.white.bold,error:this.chalk.red.bold,warn:this.chalk.yellow.bold,info:this.chalk.cyan.bold,audit:this.chalk.white.bold,debug:this.chalk.green,trace:this.chalk.gray}}formatLogString(e){const{timestamp:t,level:r,service:i,message:s,...n}=e,a=this.levelColorMap[r]||this.chalk.white;let o=`${this.chalk.gray(new Date(t).toLocaleTimeString())} ${a(`[${r.toUpperCase()}]`)} ${this.chalk.blue(`(${i})`)}: ${s||""}`;const l=Object.keys(n);if(l.length>0){const e=l.map(e=>{const t=n[e],r="object"==typeof t&&null!==t?JSON.stringify(t):String(t);return`${this.chalk.dim(e)}=${this.chalk.gray(r)}`}).join(" ");o+=`\n ${this.chalk.dim("└─")} ${e}`}return o}},exports.ConsoleTransport=q,exports.PrettyConsoleTransport=class extends le{constructor(e){var t;super(e),this.levelColorMap={fatal:(t=this.chalk).bgRed.white.bold,error:t.red.bold,warn:t.yellow.bold,info:t.blue.bold,audit:t.white.bold,debug:t.green,trace:t.gray}}formatLogString(e){return((e,t,r)=>{const{timestamp:i,level:s,service:n,message:a,...o}=e,l=r[s]||t.white;let c=`${t.gray(new Date(i).toLocaleTimeString())} ${l(`[${s.toUpperCase()}]`)} ${t.cyan(`(${n})`)}: ${a||""}`;Object.keys(o).length>0&&(c+=`\n${t.gray(JSON.stringify(o,null,2))}`);return c})(e,this.chalk,this.levelColorMap)}},exports.SanitizationEngine=Y,exports.SerializationManager=V,exports.SpyTransport=class extends f{constructor(e){super(e),this.entries=[]}async log(e){this.entries.push(e)}getEntries(){return[...this.entries]}findEntries(e){return"function"==typeof e?this.entries.filter(e):this.entries.filter(t=>Object.keys(e).every(r=>{const i=r;return e[i]===t[i]}))}clear(){this.entries=[]}getFirstEntry(){return this.entries[0]}getLastEntry(){return this.entries[this.entries.length-1]}},exports.SyntropyLog=ie,exports.Transport=f,exports.UniversalAdapter=class{constructor(e){if("function"!=typeof e.executor)throw new Error("UniversalAdapter requires an executor function.");this.executor=e.executor}async log(e){try{await this.executor(e)}catch(e){console.error(`UniversalAdapter execution failed: ${e instanceof Error?e.message:String(e)}`)}}},exports.UniversalLogFormatter=class{constructor(e){this.mapping=e.mapping,this.includeAllIn=e.includeAllIn}format(e){const t={};for(const[r,i]of Object.entries(this.mapping))t[r]=this.resolveValue(i,e);if(this.includeAllIn){const r=e.bindings??{},i=e.metadata??{};t[this.includeAllIn]={..."object"==typeof r&&null!==r?r:{},..."object"==typeof i&&null!==i?i:{}}}return t}resolveValue(e,t){if("object"==typeof e&&!Array.isArray(e)&&"value"in e){const t=e;return t.value??t.fallback}const r=Array.isArray(e)?e:[e];for(const e of r){if("object"==typeof e&&null!==e&&"value"in e){const t=e;return t.value??t.fallback}if("string"==typeof e){const r=this.getValueByPath(e,t);if(null!=r)return r}}}getValueByPath(e,t){if("message"===e)return t.message;if("level"===e)return t.level;if("timestamp"===e)return t.timestamp;const r=e.split(".");let i=t;for(const e of r){if(null===i||"object"!=typeof i)return;if(i===t&&!Object.prototype.hasOwnProperty.call(t,e)){const r=t,s=r.bindings?.[e];if(void 0!==s){i=s;continue}const n=r.metadata?.[e];if(void 0!==n){i=n;continue}}i=i[e]}return i}},exports.syntropyLog=se;
|