syntropylog 0.9.19 → 0.9.20
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 +11 -0
- package/README.md +4 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +72 -1201
- 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.d.ts +3 -18
- package/dist/types/config.schema.d.ts +49 -1169
- 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 +4 -16
- 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,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.20
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Optimization and Security Refactor:
|
|
8
|
+
- Migrated configuration validation from Zod to Valibot to significantly reduce bundle size.
|
|
9
|
+
- Removed `ConcurrencyLimiter` and `logConcurrencyLimit` to simplify pipeline processing and eliminate async bottlenecks.
|
|
10
|
+
- Restored `optionalChalk` implementation for built-in visual console transports.
|
|
11
|
+
- Achieved 100% global test coverage.
|
|
12
|
+
- Implemented ReDoS (Catastrophic Backtracking) defenses in `MaskingEngine` with synchronous length limits on property keys.
|
|
13
|
+
|
|
3
14
|
## 0.9.19
|
|
4
15
|
|
|
5
16
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -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
|
|
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("valibot"),i=require("node:async_hooks"),r=require("crypto"),s=require("node:util");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(i){if("default"!==i){var r=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return e[i]}})}}),t.default=e,Object.freeze(t)}var a=n(t),o=n(s);const l={audit:70,fatal:60,error:50,warn:40,info:30,debug:20,trace:10,silent:0};class c{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 u;!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"}(u||(u={}));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:u.CREDIT_CARD,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/ssn|social_security|security_number/i,strategy:u.SSN,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/email/i,strategy:u.EMAIL,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/phone|phone_number|mobile_number/i,strategy:u.PHONE,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/password|pass|pwd|secret/i,strategy:u.PASSWORD,preserveLength:!0,maskChar:this.maskChar,_isDefaultRule:!0},{pattern:/token|api_key|auth_token|jwt|bearer/i,strategy:u.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{...g.buildSafeFallbackFromMeta(e),_maskingFailed:!0,_maskingFailedMessage:g.MASKING_FAILED_MESSAGE}}}static buildSafeFallbackFromMeta(e){const t={},i=["level","timestamp","message","service"];for(const r of i)r in e&&void 0!==e[r]&&(t[r]=e[r]);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 i=!1;const r=new Array(e.length);for(let s=0;s<e.length;s++){const n=this.applyMaskingRules(e[s],t);r[s]=n,n!==e[s]&&(i=!0)}return i?r:e}const i=e;for(const e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;const r=i[e];if("string"==typeof r)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){i[e]=this.applyStrategy(r,t);break}}else if("object"==typeof r&&null!==r){const s=this.applyMaskingRules(r,t);s!==r&&(i[e]=s)}}return i}applyStrategy(e,t){if(t.strategy===u.CUSTOM&&t.customMask)return t.customMask(e);switch(t.strategy){case u.CREDIT_CARD:return this.maskCreditCard(e,t);case u.SSN:return this.maskSSN(e,t);case u.EMAIL:return this.maskEmail(e,t);case u.PHONE:return this.maskPhone(e,t);case u.PASSWORD:return this.maskPassword(e,t);case u.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,(r,s)=>e.substring(0,s).replace(/\D/g,"").length<i.length-4?t.maskChar:r):`${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,(r,s)=>e.substring(0,s).replace(/\D/g,"").length<i.length-4?t.maskChar:r):`***-**-${i.slice(-4)}`}maskEmail(e,t){const i=e.indexOf("@");if(i>0){const r=e.substring(0,i),s=e.substring(i);if(t.preserveLength){return(r.length>1?r.charAt(0)+t.maskChar.repeat(r.length-1):t.maskChar.repeat(r.length))+s}return`${r.charAt(0)}***${s}`}return this.maskDefault(e,t)}maskPhone(e,t){const i=e.replace(/\D/g,"");return t.preserveLength?e.replace(/\d/g,(r,s)=>e.substring(0,s).replace(/\D/g,"").length<i.length-4?t.maskChar:r):`${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=>[u.CREDIT_CARD,u.SSN,u.EMAIL,u.PHONE,u.PASSWORD,u.TOKEN].includes(e.strategy)).length,customRules:this.rules.filter(e=>e.strategy===u.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}}g.MASKING_FAILED_MESSAGE="[SyntropyLog] Masking could not be applied (e.g. timeout or error); payload redacted for safety.";const h=a.object({transport:a.custom(e=>e instanceof c,"Must be an instance of Transport"),env:a.optional(a.union([a.string(),a.array(a.string())]))}),d=a.union([a.custom(e=>e instanceof c,"Must be an instance of Transport"),h]),p=a.optional(a.object({name:a.optional(a.string()),level:a.optional(a.picklist(["audit","fatal","error","warn","info","debug","trace","silent"])),serviceName:a.optional(a.string()),environment:a.optional(a.string()),transportList:a.optional(a.record(a.string(),a.custom(e=>e instanceof c,"Must be an instance of Transport"))),env:a.optional(a.record(a.string(),a.array(a.string()))),transports:a.optional(a.union([a.array(d),a.record(a.string(),a.array(d))])),serializerTimeoutMs:a.optional(a.pipe(a.number(),a.integer(),a.minValue(1)),50),prettyPrint:a.optional(a.object({enabled:a.optional(a.boolean(),!1)}))})),m=a.optional(a.object({rules:a.optional(a.array(a.object({pattern:a.union([a.string(),a.instance(RegExp)]),strategy:a.enum(u),preserveLength:a.optional(a.boolean()),maskChar:a.optional(a.string()),customMask:a.optional(a.custom(e=>"function"==typeof e,"Must be a function"))}))),maskChar:a.optional(a.string()),preserveLength:a.optional(a.boolean()),enableDefaultRules:a.optional(a.boolean()),regexTimeoutMs:a.optional(a.pipe(a.number(),a.integer(),a.minValue(1)),100)})),f=a.optional(a.object({default:a.optional(a.array(a.string())),trace:a.optional(a.array(a.string())),debug:a.optional(a.array(a.string())),info:a.optional(a.array(a.string())),warn:a.optional(a.array(a.string())),error:a.optional(a.array(a.string())),fatal:a.optional(a.array(a.string()))})),y=a.object({logger:p,loggingMatrix:f,masking:m,context:a.optional(a.object({correlationIdHeader:a.optional(a.string()),transactionIdHeader:a.optional(a.string())})),shutdownTimeout:a.optional(a.pipe(a.number(),a.integer(),a.minValue(1),a.description("The maximum time in ms to wait for a graceful shutdown.")))}),S=Object.freeze({});class b{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 r=this.storage.getStore(),s=new Map(r?.data);this.storage.run({data:s},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=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(),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=Object.keys(t).length,i=this.get(this.correlationIdHeader),r=this.get("correlationId");if(0===e&&!i&&!r)return S;const s={};return Object.assign(s,t),!i&&r&&(s[this.correlationIdHeader]=r),s}const i=this.loggingMatrix[e]??this.loggingMatrix.default;if(!i)return S;const r={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,s]of Object.entries(t)){let t=i;for(const[e,s]of Object.entries(r))if(s.includes(i)){t=e;break}e[t]=s}return e}const s={};for(const e of i){const i=r[e]||[e];for(const r of i)if(Object.prototype.hasOwnProperty.call(t,r)){s[e]=t[r];break}!Object.prototype.hasOwnProperty.call(s,e)&&Object.prototype.hasOwnProperty.call(t,e)&&(s[e]=t[e])}return s}}const w={depth:0,maxDepth:10,sensitiveFields:[],sanitize:!0};class v{constructor(e,t,i,r={}){this.pendingRouting=null,this.name=e,this.transports=t,this.dependencies=i,this.bindings=r.bindings??{},this.level=r.level??"info"}override(...e){return this.pendingRouting={override:e},this}add(...e){const t=this.pendingRouting,i=[...t&&"add"in t?t.add??[]:[],...e],r=t&&"remove"in t?t.remove??[]:void 0;return this.pendingRouting=r?.length?{add:i,remove:r}:{add:i},this}remove(...e){const t=this.pendingRouting,i=[...t&&"remove"in t?t.remove??[]:[],...e],r=t&&"add"in t?t.add??[]:void 0;return this.pendingRouting=r?.length?{add:r,remove:i}:{remove:i},this}captureEffectiveTransports(){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 r=[...e];if(i.add?.length)for(const e of i.add){const i=t.get(e);i&&r.push(i)}if(i.remove?.length){const e=new Set(i.remove);r=r.filter(t=>!e.has(t.name))}return r}(this.transports,this.dependencies.transportPool,e)}async _log(e,...t){if("silent"===e)return;if(!function(e,t){return"silent"!==e&&("audit"===e||l[e]>=l[t])}(e,this.level))return;const i=this.captureEffectiveTransports();try{const{message:r,metadata:s}=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=o.format(t,...i))}else{i=e[0],t=e[1]||"";const r=e.slice(2);t&&r.length>0&&(t=o.format(t,...r))}return{message:t||"",metadata:i}}(t),n=this.dependencies.contextManager.getFilteredContext(e),a={level:e,timestamp:(new Date).toISOString(),service:this.name,message:r};Object.assign(a,n,this.bindings,s);const l=this.dependencies.serializationManager.serialize(a,w).data,c=this.dependencies.maskingEngine.process(l);for(const t of i)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 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 k;exports.SerializationComplexity=void 0,(k=exports.SerializationComplexity||(exports.SerializationComplexity={})).SIMPLE="simple",k.COMPLEX="complex",k.CRITICAL="critical";class z{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,r=t.maxDepth||this.defaultMaxDepth,s=t.currentDepth||0;if(s>=r)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:i,maxDepth:r,currentDepth:s+1};for(let i=0;i<e.length;i++){const r=this.sanitize(e[i],t);r!==e[i]&&(e[i]=r)}return e}if("object"==typeof e){const t=e;for(const e of Object.keys(t)){const n=e.toLowerCase();if(i.some(e=>n.includes(e.toLowerCase())))t[e]="[REDACTED]";else{const n=this.sanitize(t[e],{sensitiveFields:i,maxDepth:r,currentDepth:s+1});n!==t[e]&&(t[e]=n)}}return e}return e}}const x="pipeline",D="unknown";class M{constructor(){this.steps=[],this.timeoutStrategies=new Map,this.metrics=null,this.sanitizer=new z,this.initializeDefaultStrategies()}addStep(e){this.steps.push(e)}addTimeoutStrategy(e){this.timeoutStrategies.set(e.getStrategyName(),e)}process(e,t){const i=Date.now();this.metrics={stepDurations:{},totalDuration:0,operationTimeout:0,timeoutStrategy:D};let r=e;try{for(const e of this.steps){const i=Date.now();r=e.execute(r,t),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,r,s){const n=e,a=n.serializer??x,o=n.serializationComplexity??exports.SerializationComplexity.SIMPLE;return{success:!0,data:e,serializer:a,duration:i.totalDuration,complexity:o,sanitized:t,metadata:{stepDurations:i.stepDurations,operationTimeout:r,timeoutStrategy:s,serializer:a,complexity:o}}}static buildErrorResult(e,t,i){const r=t?.serializer??x;return{success:!1,data:e,serializer:r,duration:i.totalDuration,complexity:exports.SerializationComplexity.SIMPLE,sanitized:!1,error:t instanceof Error?t.message:String(t),metadata:{stepDurations:i.stepDurations,operationTimeout:0,timeoutStrategy:D,serializer:r,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 C)}}class C{calculateTimeout(e){return 5e3}getStrategyName(){return"default"}}class E{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 i=Date.now(),r=this.findSerializer(e);if(!r)return e;try{const s=r.serialize(e,t.serializationContext),n=Date.now()-i,a="object"==typeof s.data&&null!==s.data?s.data:{};return a.serializationDuration=n,a.serializer=r.name,a.serializationComplexity=s.complexity||s.metadata?.complexity||null,a}catch(e){throw e instanceof Error&&!e.serializer&&(e.serializer=r.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 O(e,t){if(null===e||"object"!=typeof e)return e;if(t.has(e))return"[Circular]";if(t.add(e),Array.isArray(e)){let i=!1;const r=new Array(e.length);for(let s=0;s<e.length;s++){const n=O(e[s],t);r[s]=n,n!==e[s]&&(i=!0)}return t.delete(e),i?r:e}for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const r=e[i],s=O(r,t);s!==r&&(e[i]=s)}return t.delete(e),e}class I{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=O(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 L(e,t,i,r){if("object"==typeof e&&null!==e){const s=e;return s.sanitizationDuration=t,s.sanitized=i,void 0!==r&&(s.sanitizationError=r),e}return{sanitizationDuration:t,sanitized:i,...void 0!==r&&{sanitizationError:r}}}class T{constructor(e){this.name="sanitization",this.sanitizer=e??new z}execute(e,t){const i=Date.now(),r=()=>Date.now()-i;if(!t.sanitizeSensitiveData)return L(e,r(),!1);try{return L(this.sanitizer.sanitize(e,t.sanitizationContext),r(),!0)}catch(t){return L(e,r(),!1,function(e){return e instanceof Error?e.message:String(e)}(t))}}}const R=3e3;class P{constructor(e){this.name="timeout",this.timeoutStrategies=new Map,this.timeoutStrategies=e}execute(e,t){const i=Date.now();try{const t=this.selectTimeoutStrategy(e),r=t?.calculateTimeout(e)??R;return function(e,t,i,r){if("object"==typeof e&&null!==e){const s=e;return s.timeoutDuration=t,s.operationTimeout=i,s.timeoutStrategy=r?.getStrategyName()??"default",s.timeoutApplied=null!=r,e}return{timeoutDuration:t,operationTimeout:i,timeoutStrategy:r?.getStrategyName()??"default",timeoutApplied:null!=r}}(e,Date.now()-i,r,t)}catch(t){return function(e,t,i){if("object"==typeof e&&null!==e){const r=e;return r.timeoutDuration=t,r.operationTimeout=R,r.timeoutStrategy="default",r.timeoutApplied=!1,r.timeoutError=i instanceof Error?i.message:"Timeout error",e}return{timeoutDuration:t,operationTimeout:R,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 j{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 E,this.hygieneStep=new I,this.sanitizationStep=new T,this.timeoutStep=new P(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 i=Date.now(),r={serializationContext:t,sanitizeSensitiveData:this.config.sanitizeSensitiveData,sanitizationContext:this.config.sanitizationContext,enableMetrics:this.config.enableMetrics},s=this.pipeline.process(e,r);return this.config.enableMetrics&&this.updateMetrics(s,Date.now()-i),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 i=e.metadata.operationTimeout||0;this.metrics.totalOperationTimeout+=i;const r=e.complexity||exports.SerializationComplexity.SIMPLE;r===exports.SerializationComplexity.SIMPLE?this.metrics.complexityDistribution.low++:r===exports.SerializationComplexity.COMPLEX?this.metrics.complexityDistribution.medium++:r===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 A extends c{constructor(e){super(e)}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 _{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={},i=e;for(const e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=this.sanitizeRecursively(i[e]));return t}return e}}function $(e,t){const i=[];for(const r of e)if(r instanceof c)i.push(r);else if(r&&"object"==typeof r&&"transport"in r){const e=null==r.env?null:Array.isArray(r.env)?r.env:[r.env];(null===e||e.includes(t))&&i.push(r.transport)}else r&&"object"==typeof r&&i.push(r);return i}class N{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 r=(e=>{const t=e.logger?.environment??"development",i=e.logger?.transportList&&Object.keys(e.logger.transportList).length>0,r=e.logger?.env&&Object.keys(e.logger.env).length>0;if(i&&r&&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,r=new Map,s=e=>{const t=e instanceof c?e:e&&"object"==typeof e&&"transport"in e?e.transport:e,i=t.name??t.constructor?.name??`transport-${r.size}`;return r.set(i,t),t};let n;if(Array.isArray(i))i.forEach(s),n={default:$(i,t)};else{const e=i;n={};for(const[i,r]of Object.entries(e))r.forEach(s),n[i]=$(r,t)}return{transports:n,transportPool:r}}{const e=new _,t=new A({sanitizationEngine:e,name:"console"});return{transports:{default:[t]},transportPool:new Map([["console",t]])}}})(e);this.transports=r.transports,this.transportPool=r.transportPool,this.globalLogLevel=e.logger?.level??"info",this.serviceName=e.logger?.serviceName??"unknown-service",this.serializationManager=new j({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 r="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 v(r,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(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]",F=["password","token","secret","apikey","credential","pass","key","accesstoken","refreshtoken","clientsecret","sentinelpassword","sasl"];function K(e){if(e instanceof c)return e;if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>K(e));const t={},i=F.map(e=>e.toLowerCase());for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const s=r.toLowerCase(),n=e[r];i.includes(s)?t[r]=H:(s.includes("url")||s.includes("uri"))&&"string"==typeof n?t[r]=n.replace(/(?<=:\/\/)[^:]+:[^@]+@/,`${H}@`):"object"!=typeof n||null===n||n instanceof RegExp?t[r]=n:t[r]=K(n)}return t}function U(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack||null}:String(e)}class V 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 j({}),this.maskingEngine=new g({})}getState(){return this.state}async init(e){if("NOT_INITIALIZED"===this.state){this.state="INITIALIZING";try{const i=K(t.parse(y,e));this.config=i,this.contextManager=new b(this.config.loggingMatrix),this.config.context&&this.contextManager.configure(this.config.context),this.serializationManager=new j({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 N(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 t.ValiError?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:U(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 r=new Promise(t=>{const i=()=>{t(),e.removeListener("exit",i)};e.on("exit",i)}),s=new Promise(e=>setTimeout(e,5e3));await Promise.race([r,s]),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:U(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 G(e,t){if(null==e)throw new Error(t)}class W extends e.EventEmitter{constructor(){super(),this.lifecycleManager=new V(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 G(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 G(this.lifecycleManager.maskingEngine,"MaskingEngine not available."),this.lifecycleManager.maskingEngine}getSerializer(){return G(this.lifecycleManager.serializationManager,"SerializationManager not available."),this.lifecycleManager.serializationManager}_resetForTesting(){this.lifecycleManager.removeAllListeners(),Object.assign(this,{lifecycleManager:new V(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 q=W.getInstance();function Y(e){const t=t=>function(e,t){return 0===t.length?e:`[${t.join(";")}m${e}[0m`}(t,e),i=t=>Y([...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 J=null;function Z(){if(null!==J)return J;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,J=e}else J=Y([]);return J}class X extends c{constructor(e){super(e),this.chalk=Z()}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}}}exports.AdapterTransport=class extends c{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 X{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:r,message:s,context:n,...a}=e,o=this.levelColorMap[i]||this.chalk.white,l=this.formatTimestamp(t),c=o(i.toUpperCase().padEnd(5)),u=this.chalk.magenta(`[${r}]`),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 X{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:r,level:s,service:n,message:a,...o}=e,l=i[s]??{level:t.white.bold,message:t.white,metaKey:t.gray,metaValue:t.white},c=l.metaKey(new Date(r).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 p=Object.keys(o);if(p.length>0){const e=p.map(e=>{const t=o[e],i="object"==typeof t&&null!==t?JSON.stringify(t):String(t);return`${l.metaKey(e)}=${l.metaValue(i)}`});d+=`\n ${t.dim("└─")} ${e.join(" ")}`}return d})(e,this.chalk,this.levelStyleMap)}},exports.CompactConsoleTransport=class extends X{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:r,message:s,...n}=e,a=this.levelColorMap[i]||this.chalk.white;let o=`${this.chalk.gray(new Date(t).toLocaleTimeString())} ${a(`[${i.toUpperCase()}]`)} ${this.chalk.blue(`(${r})`)}: ${s||""}`;const l=Object.keys(n);if(l.length>0){const e=l.map(e=>{const t=n[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=A,exports.PrettyConsoleTransport=class extends X{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:r,level:s,service:n,message:a,...o}=e,l=i[s]||t.white;let c=`${t.gray(new Date(r).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=_,exports.SerializationManager=j,exports.SpyTransport=class extends c{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 r=i;return e[r]===t[r]}))}clear(){this.entries=[]}getFirstEntry(){return this.entries[0]}getLastEntry(){return this.entries[this.entries.length-1]}},exports.SyntropyLog=W,exports.Transport=c,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,r]of Object.entries(this.mapping))t[i]=this.resolveValue(r,e);if(this.includeAllIn){const i=e.bindings??{},r=e.metadata??{};t[this.includeAllIn]={..."object"==typeof i&&null!==i?i:{},..."object"==typeof r&&null!==r?r:{}}}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 r=t;for(const e of i){if(null===r||"object"!=typeof r)return;if(r===t&&!Object.prototype.hasOwnProperty.call(t,e)){const i=t,s=i.bindings?.[e];if(void 0!==s){r=s;continue}const n=i.metadata?.[e];if(void 0!==n){r=n;continue}}r=r[e]}return r}},exports.syntropyLog=q;
|