Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@decaf-ts/logging

Package Overview
Dependencies
Maintainers
5
Versions
113
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@decaf-ts/logging - npm Package Compare versions

Comparing version
0.20.0
to
0.21.0
+1
-1
dist/logging.cjs

@@ -1,2 +0,2 @@

var e,t;e=this,t=function(e,t,r,n){"use strict";const o="ENV",s="__",i=["${","}"];var a;e.LogLevel=void 0,(a=e.LogLevel||(e.LogLevel={})).benchmark="benchmark",a.error="error",a.warn="warn",a.info="info",a.verbose="verbose",a.debug="debug",a.trace="trace",a.silly="silly";const c={benchmark:0,error:3,warn:6,info:9,verbose:12,debug:15,trace:18,silly:21};var l;e.LoggingMode=void 0,(l=e.LoggingMode||(e.LoggingMode={})).RAW="raw",l.JSON="json";const u={app:{},separator:{},class:{fg:34},id:{fg:36},stack:{},timestamp:{},message:{error:{fg:31}},method:{},logLevel:{benchmark:{fg:32,style:["bold"]},error:{fg:31,style:["bold"]},info:{fg:34,style:["bold"]},verbose:{fg:34,style:["bold"]},debug:{fg:33,style:["bold"]},trace:{fg:33,style:["bold"]},silly:{fg:33,style:["bold"]}}},g={env:"development",verbose:0,level:e.LogLevel.info,logLevel:!0,style:!1,filters:[],contextSeparator:".",separator:"-",timestamp:!0,timestampFormat:"HH:mm:ss.SSS",context:!0,meta:!0,format:e.LoggingMode.RAW,pattern:"{level} [{timestamp}] {app} {context} {separator} {message} {stack}",theme:u};class f{constructor(){this.descriptors=new Map}register(e){return this.descriptors.set(e.key,e),this}unregister(e){return this.descriptors.delete(e),this}get(e){return this.descriptors.get(e)}render(e,t){const r={},n=new Set;return t.forEach(t=>{if(n.has(t))return;n.add(t);const o=this.descriptors.get(t);if(!o)return;if(o.shouldInclude&&!o.shouldInclude(e))return;const s=o.render(e);if(void 0===s)return;const i=o.style?o.style(s,e):s;r[t]=i}),r}keys(){return Array.from(this.descriptors.keys())}}const p=new Map;function h(e){if(p.has(e))return p.get(e);const t=d(e||""),r=new Set,n=[];m(t,r,n);const o={pattern:e,segments:t,keys:n,includesMeta:r.has("meta")};return p.set(e,o),o}function y(e,t){return v(e.segments,t).text}function d(e){const t=[];let r=0;for(;r<e.length;){const n=e[r];if("["===n){const n=b(e,r,"[","]");if(-1===n){t.push({type:"literal",value:"["}),r++;continue}const o=e.slice(r+1,n);t.push({type:"optional",prefix:"[",suffix:"]",children:d(o)}),r=n+1;continue}if("{"===n){const n=e.indexOf("}",r+1);if(-1===n){t.push({type:"literal",value:"{"}),r++;continue}const o=e.slice(r+1,n).trim();t.push({type:"parameter",key:o}),r=n+1;continue}let o=r;for(;o<e.length&&"["!==e[o]&&"{"!==e[o];)o++;const s=e.slice(r,o);s.length&&t.push({type:"literal",value:s}),r=o}return t}function b(e,t,r,n){let o=0;for(let s=t;s<e.length;s++){const t=e[s];if(t===r)o++;else if(t===n&&(o--,0===o))return s}return-1}function m(e,t,r){for(const n of e)"parameter"===n.type&&(t.has(n.key)||(t.add(n.key),r.push(n.key))),"optional"===n.type&&m(n.children,t,r)}function v(e,t){const r=[];let n=!1;for(const o of e){const e=x(o,t);e.text.length&&r.push(e.text),n=n||e.hasValue}return{text:r.join(""),hasValue:n}}function x(e,t){if("literal"===e.type)return{text:e.value,hasValue:!1};if("parameter"===e.type){const r=t[e.key]??"";return{text:r,hasValue:r.length>0}}const r=v(e.children,t);return r.hasValue?{text:`${e.prefix}${r.text}${e.suffix}`,hasValue:!0}:{text:"",hasValue:!1}}const w=new f;w.register({key:"level",render(e){if(!1!==e.config.logLevel)return e.level.toUpperCase()},style:(e,t)=>t.applyTheme(e,"logLevel")}).register({key:"timestamp",shouldInclude:e=>!(!e.config.timestamp||!e.timestamp),render:e=>e.timestamp,style:(e,t)=>t.applyTheme(e,"timestamp")}).register({key:"app",shouldInclude:e=>!!e.app,render:e=>e.app,style:(e,t)=>t.applyTheme(e,"app")}).register({key:"context",shouldInclude:e=>!1!==e.config.context&&e.context.length>0,render(e){const t=e.config.contextSeparator||".";return e.context.join(t)},style:(e,t)=>t.applyTheme(e,"class")}).register({key:"separator",shouldInclude:e=>!!e.separator,render:e=>e.separator,style:(e,t)=>t.applyTheme(e,"separator")}).register({key:"message",render:e=>e.filteredMessage,style:(e,t)=>t.applyTheme(e,"message")}).register({key:"stack",shouldInclude:e=>!!e.stack,render:e=>e.stack,style:(e,t)=>t.applyTheme(e,"stack")}).register({key:"meta",shouldInclude:e=>!!e.metaString,render:e=>e.metaString}).register({key:"correlationId",shouldInclude:e=>!!e.correlationId,render:e=>e.correlationId,style:(e,t)=>t.applyTheme(e,"id")});const L=w;function E(e,t,r="g"){return Object.entries(t).forEach(([t,n])=>{const o=RegExp(k(t),r);e=e.replace(o,n)}),e}function O(e){return _(e).toUpperCase()}function _(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function k(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j(e,...t){if(t.length>1&&!t.every(e=>"string"==typeof e||"number"==typeof e))throw Error("Only string and number arguments are supported for multiple replacements.");if(1===t.length&&"object"==typeof t[0]){const r=t[0];return Object.entries(r).reduce((e,[t,r])=>e.replace(RegExp(`\\{${t}\\}`,"g"),()=>r),e)}return e.replace(/{(\d+)}/g,(e,r)=>void 0!==t[r]?t[r].toString():"undefined")}const A=j;function M(){return Object.getPrototypeOf(Object.getPrototypeOf(globalThis))!==Object.prototype}const P=Symbol("EnvironmentEmpty"),S=Symbol("EnvironmentModel"),R=/^[a-z][a-zA-Z0-9]*$/;class C extends r.ObjectAccumulator{static{this.factory=()=>new C}constructor(){super(),Object.defineProperty(this,S,{value:{},writable:!0,enumerable:!1,configurable:!1})}fromEnv(e){let t;return M()?t=globalThis[o]||{}:(t=globalThis.process.env,e=O(e)),this.parseEnvValue(t[e])}parseEnvValue(e){return C.parseRuntimeValue(e)}static parseRuntimeValue(e){if("string"!=typeof e)return e;if("true"===e)return!0;if("false"===e)return!1;const t=e.trim();return/^-?\d+(\.\d+)?$/.test(t)?Number(t):e}expand(e){Object.entries(e).forEach(([e,t])=>{C.mergeModel(this[S],e,t),Object.defineProperty(this,e,{get:()=>{const r=this.fromEnv(e);return void 0!==r?r:t&&"object"==typeof t?Array.isArray(t)?t:C.buildEnvProxy(t,[e]):""===t?P:t},set:e=>{t=e},configurable:!0,enumerable:!0})})}orThrow(){const e=this[S],t=e=>void 0!==e?this.parseEnvValue(e):void 0,r=(e,t=!1)=>C.missingEnvError(e,t),n=(e,o)=>{const s={get(s,i){if("string"!=typeof i)return;if(Array.isArray(e)&&"length"===i)return e.length;const a=[...o,i],{key:c,value:l}=C.readRuntimeForPath(a);if("string"==typeof l&&0===l.length)throw r(c,!0);const u=t(l);if(void 0!==u){if("string"==typeof u&&0===u.length)throw r(c,!0);return u}if(!e||!Object.prototype.hasOwnProperty.call(e,i))throw r(c);const g=e[i];if(void 0!==g){if(""===g)throw r(c);return g&&"object"==typeof g?n(g,a):g}},ownKeys:()=>e?Reflect.ownKeys(e):[],getOwnPropertyDescriptor(t,r){if(e)return Object.prototype.hasOwnProperty.call(e,r)?{enumerable:!0,configurable:!0}:void 0}};return new Proxy(Array.isArray(e)?[]:{},s)};return new Proxy(this,{get(o,s,i){if("string"!=typeof s)return Reflect.get(o,s,i);if(!Object.prototype.hasOwnProperty.call(e,s))return Reflect.get(o,s,i);const{key:a,value:c}=C.readRuntimeForPath([s]);if("string"==typeof c&&0===c.length)throw r(a,!0);const l=t(c);if(void 0!==l){if("string"==typeof l&&0===l.length)throw r(a,!0);return l}const u=e[s];if(u&&"object"==typeof u)return n(u,[s]);if(void 0===u)return Reflect.get(o,s,i);const g=Reflect.get(o,s);if(void 0===g||""===g)throw r(a,""===g);return g}})}static instance(...e){if(!C._instance){const t=C.factory(...e),r=new Proxy(t,{get(e,t,r){const n=Reflect.get(e,t,r);if(n!==P&&("string"!=typeof t||!Object.prototype.hasOwnProperty.call(e,t)||void 0!==n)){if(void 0!==n)return n;if("string"==typeof t){if("app"===t)return;return C.buildEnvProxy(void 0,[t])}return n}}});C._instance=r}return C._instance}accumulate(e){return super.accumulate(e),this}static accumulate(e){const t=C.instance();return Object.keys(t).forEach(e=>{const r=Object.getOwnPropertyDescriptor(t,e);r&&r.configurable&&r.enumerable&&Object.defineProperty(t,e,{...r,enumerable:!1})}),t.accumulate(e),t}static get(e){return C._instance.get(e)}static formatEnvSegment(e){return R.test(e)?O(e):e.toUpperCase()}static buildEnvKey(e){return e.map(e=>C.formatEnvSegment(e)).join(s)}static buildRawKey(e){return e.join(s)}static readRuntimeForPath(e){const t=C.buildEnvKey(e),r=C.buildRawKey(e),n=C.readRuntimeEnv(t);if(void 0!==n)return{key:t,value:n};if(r!==t){const e=C.readRuntimeEnv(r);if(void 0!==e)return{key:r,value:e}}return{key:t,value:void 0}}static buildEnvProxy(e,t){const r=e=>C.readRuntimeEnv(e),n=/^[0-9]+$/,o={get(o,s){if(s===Symbol.toPrimitive)return()=>C.buildEnvKey(t);if("toString"===s)return()=>C.buildEnvKey(t);if("valueOf"===s)return()=>C.buildEnvKey(t);if("symbol"==typeof s)return;if(Array.isArray(e)&&"length"===s)return e.length;const i=[...t,s],a=C.buildEnvKey(i),c=C.buildRawKey(i);let l=r(a);if(void 0===l&&c!==a&&(l=r(c)),void 0!==l)return C.parseRuntimeValue(l);const u=!!e&&Object.prototype.hasOwnProperty.call(e,s),g=u?e[s]:void 0;if(Array.isArray(e)&&(e=>"string"==typeof e&&n.test(e))(s)){if(!u)return;return g&&"object"==typeof g?C.buildEnvProxy(g,i):C.parseRuntimeValue(g)}return g&&"object"==typeof g?C.buildEnvProxy(g,i):u&&""===g||u&&void 0===g?void 0:u?C.parseRuntimeValue(g):C.buildEnvProxy(void 0,i)},ownKeys:()=>e?Reflect.ownKeys(e):[],getOwnPropertyDescriptor(t,r){if(e)return Object.prototype.hasOwnProperty.call(e,r)?{enumerable:!0,configurable:!0}:void 0}};return new Proxy(Array.isArray(e)?[]:{},o)}static keys(e=!0){return C.instance().keys().map(t=>e?O(t):t)}static mergeModel(e,t,r){if(e){if(r&&"object"==typeof r&&!Array.isArray(r)){const n=e[t],o=n&&"object"==typeof n&&!Array.isArray(n)?n:{};return e[t]=o,void Object.entries(r).forEach(([e,t])=>{C.mergeModel(o,e,t)})}e[t]=r}}static readRuntimeEnv(e){if(M()){const t=globalThis[o];return t?t[e]:void 0}return globalThis?.process?.env?.[e]}static missingEnvError(e,t){return Error(`Environment variable ${e} is required but was ${t?"an empty string":"undefined"}.`)}}const $=C.accumulate(Object.assign({app:void 0},g,{env:(M()&&globalThis[o]?globalThis[o].NODE_ENV:globalThis.process.env.NODE_ENV)||"development"}));function T(e){if("function"!=typeof e)return!1;try{const t=Function.prototype.toString.call(e);if(/^\s*class[\s{]/.test(t))return!0}catch{}const t=Object.getOwnPropertyDescriptor(e,"prototype");if(!t||!t.value)return!1;if(!1===t.writable)return!0;const r=e.prototype;return!!Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.getOwnPropertyNames(r).filter(e=>"constructor"!==e).length>0}function I(e){return"function"==typeof e&&!T(e)}function V(e){if(!I(e))return!1;const t=Object.getOwnPropertyDescriptor(e,"prototype");return!t||void 0===t.value}function N(e){if(null===e||"object"!=typeof e)return!1;const t=e.constructor;return!(!t||t===Object)&&T(t)}function F(e){if(null===e)return"null";if(void 0===e)return"undefined";if("string"==typeof e)return e;if(T(e))return e.name||"AnonymousClass";if(N(e)){const t=e.toString;if("function"==typeof t&&t!==Object.prototype.toString)try{const r=t.call(e);if("string"==typeof r&&r.length)return r}catch{}const r=e.constructor;return r&&r.name?r.name:"AnonymousInstance"}if(V(e)||I(e)){const t=e;return t.name?t.name:"anonymous"}if("object"==typeof e){const t=Object.prototype.toString.call(e),r=/^\[object ([^\]]+)\]$/.exec(t);return r?.[1]?r[1]:"Object"}return typeof e}const K=Symbol("MiniLoggerRootContext");class D{constructor(e,t,r=[]){this.conf=t,this.baseContext=Array.isArray(r)?[...r]:[],e&&this.baseContext.push(e),this.context=[...this.baseContext],this[K]=[...this.baseContext]}config(e){return this.conf&&e in this.conf?this.conf[e]:z.getConfig()[e]}for(e,t,...r){let n,o=t;const s=Array.isArray(this.context)?[...this.context]:"string"==typeof this.context&&this.context?[this.context]:[],i=this[K],a=Array.isArray(i)?[...i]:Array.isArray(this.baseContext)?[...this.baseContext]:[];"string"==typeof e?n=e:void 0!==e&&(T(e)||N(e)||I(e)?n=F(e):!o&&e&&"object"==typeof e&&(o=e));let c=n?[...s,n]:[...s];return new Proxy(this,{get:(e,t,r)=>{const n=Reflect.get(e,t,r);return"config"===t?new Proxy(this.config,{apply:(e,t,n)=>{const[s]=n;return o&&void 0!==s&&s in o?o[s]:Reflect.apply(e,r,n)},get:(e,t)=>o&&t in o?o[t]:Reflect.get(e,t,r)}):"clear"===t?()=>(c=[...a],o=void 0,r):"context"===t?c:"root"===t?[...a]:t===K?a:"for"===t?(...t)=>{const r=Array.isArray(e.context)?[...e.context]:"string"==typeof e.context&&e.context?[e.context]:[];e.context=[...c];try{return e.for.apply(e,t)}finally{e.context=r}}:n}})}getConfigSnapshot(){return{...z.getConfig(),...this.conf||{}}}getContextSegments(){return Array.isArray(this.context)?[...this.context]:"string"==typeof this.context&&this.context?[this.context]:[]}resolveFilters(e){const t=e.filters||[];return Array.isArray(t)?t.filter(e=>"object"==typeof e&&null!==e&&"function"==typeof e.filter):[]}applyFilters(e,t,r){const n=this.resolveFilters(r);return n.length?n.reduce((e,n)=>{try{const o=n.filter(r,e,[...t]);return"string"==typeof o?o:e}catch{return e}},e):e}createLog(e,t,r,n){const o=!!this.config("style"),s=this.config("separator"),i=z.getConfig().app,a=this.config("timestamp")?(new Date).toISOString():void 0,c=this.getConfigSnapshot(),l=this.getContextSegments(),u="string"==typeof t?t:t instanceof Error?t.message:t+"",g=this.applyFilters(u,l,c),f=this.config("meta")&&n?n:void 0,p=f?this.formatMeta(f):void 0,d=p?this.applyFilters(p,l,c):void 0,b=this.config("correlationId"),m=null!=b?b+"":void 0;let v,x;if(r||t instanceof Error){const n=r||t;n.stack&&(x="string"==typeof t?g:n.message,v=` | ${x} - Stack trace:\n${o?z.theme(n.stack,"stack",e):n.stack}`)}const w={config:c,level:e,context:l,timestamp:a,app:"string"==typeof i&&i.length?i:void 0,separator:s,correlationId:m,rawMessage:u,filteredMessage:g,meta:f,metaString:d,stack:v,stackLabel:x,applyTheme:(t,r)=>o?z.theme(t,r,e):t},E=this.config("pattern"),O=c.pattern||"",_=h(E.length?E:O),k=L.render(w,_.keys);switch(this.config("format")){case"json":{const e=L.render(w,L.keys()),t={};return Object.entries(e).forEach(([e,r])=>{"meta"!==e&&(t[e]=r)}),w.meta&&(t.meta=w.meta),JSON.stringify(t)}case"raw":{let e=this.normalizePatternSpacing(y(_,k));return!_.includesMeta&&d&&(e=e?`${e} ${d}`:d),e}default:throw Error("Unsupported logging format: "+this.config("format"))}}formatMeta(e){try{return JSON.stringify(e)}catch(t){return e+""}}normalizePatternSpacing(e){return e.replace(/[ \t]{2,}/g," ").replace(/^[ \t]+|[ \t]+$/g,"")}log(t,r,n,o){const s=this.config("level");if(c[t]>c[s])return;let i;switch(t){case e.LogLevel.benchmark:case e.LogLevel.info:case e.LogLevel.verbose:i=console.log;break;case e.LogLevel.debug:i=console.debug;break;case e.LogLevel.error:i=console.error;break;case e.LogLevel.trace:i=console.trace;break;case e.LogLevel.warn:i=console.warn;break;case e.LogLevel.silly:i=console.debug;break;default:throw Error("Invalid log level")}i(this.createLog(t,r,n,o))}benchmark(t,r){this.log(e.LogLevel.benchmark,t,void 0,r)}silly(t,r=0,n){const o="number"==typeof r?r:0,s="number"==typeof r?n:r;this.config("verbose")<o||this.log(e.LogLevel.silly,t,void 0,s)}verbose(t,r=0,n){const o="number"==typeof r?r:0,s="number"==typeof r?n:r;this.config("verbose")<o||this.log(e.LogLevel.verbose,t,void 0,s)}info(t,r){this.log(e.LogLevel.info,t,void 0,r)}debug(t,r){this.log(e.LogLevel.debug,t,void 0,r)}error(t,r,n){let o,s;r instanceof Error?(o=r,s=n):s=r,this.log(e.LogLevel.error,t,o,s)}warn(t,r){this.log(e.LogLevel.warn,t,void 0,r)}trace(t,r){this.log(e.LogLevel.trace,t,void 0,r)}setConfig(e){this.conf={...this.conf||{},...e}}get root(){return[...this.baseContext]}clear(){return this.context=[...this.baseContext],this}}class z{static{this._factory=(e,t)=>{const r="string"==typeof $.app?[$.app]:[];return new D(e,t,r)}}static{this._config=$}constructor(){}static setFactory(e){z._factory=e,this.global=void 0}static setConfig(e){Object.entries(e).forEach(([e,t])=>{this._config[e]=t})}static getConfig(){return this._config}static get(){return this.ensureRoot()}static verbose(e,t=0,r){return this.get().verbose(e,t,r)}static info(e,t){return this.get().info(e,t)}static trace(e,t){return this.get().trace(e,t)}static debug(e,t){return this.get().debug(e,t)}static benchmark(e,t){return this.get().benchmark(e,t)}static silly(e,t=0,r){return this.get().silly(e,t,r)}static warn(e,t){return this.get().warn(e,t)}static error(e,t,r){return this.get().error(e,t,r)}static for(e,t,...r){const n=void 0!==t?[e,t]:[e];return(this.global?this.global:this.ensureRoot(r)).for(...n)}static because(e,t){let r=this.ensureRoot().for(e,this._config);return t&&(r=r.for(t)),r}static baseContext(){const e=this._config.app;return"string"==typeof e&&e.length?[e]:[]}static attachRootContext(e){const t=e.root&&Array.isArray(e.root)?[...e.root]:this.baseContext();return(!e.context||Array.isArray(e.context)&&0===e.context.length)&&(e.context=[...t]),e[K]=[...t],e}static ensureRoot(e=[]){if(!this.global){const t=this._factory(void 0,void 0,...e);this.global=this.attachRootContext(t)}return this.global}static theme(r,n,o,s=u){if(!this._config.style)return r;const i=s[n];if(!i||!Object.keys(i).length)return r;let a=i;const c=Object.assign({},e.LogLevel);return Object.keys(i)[0]in c&&(a=i[o]||{}),Object.keys(a).reduce((e,r)=>{const n=a[r];return n?((e,r,n)=>{try{const o=e;let s=t.style(o);function i(e,r=!1){let i=r?s.background:s.foreground;if(!Array.isArray(e))return i.call(s,n);switch(e.length){case 1:return i=r?s.bgColor256:s.color256,i(e[0]);case 3:return i=r?s.bgRgb:s.rgb,s.rgb(e[0],e[1],e[2]);default:return t.style(o)}}function a(e){s="number"==typeof e?s.style(e):s[e]}switch(r){case"bg":case"fg":return i(n).text;case"style":return Array.isArray(n)?n.forEach(a):a(n),s.text;default:return o}}catch(c){return e}})(e,r,n):e},r)}static register(e){return L.register(e)}static unregister(e){return L.unregister(e)}}class U{get log(){return this._log||(this._log=z.for(this)),this._log}constructor(){}}class J extends U{get log(){return super.log.for(this,{filters:[]})}}const Z="undefined"!=typeof globalThis&&"function"==typeof globalThis.performance?.now?()=>globalThis.performance.now():"undefined"!=typeof process&&"function"==typeof process.hrtime?.bigint?()=>{const e=process.hrtime.bigint();return Number(e)/1e6}:()=>Date.now();function q(e){const t=0>e?"-":"",r=Math.abs(e),n=Math.floor(r/36e5),o=Math.floor(r%36e5/6e4),s=Math.floor(r%6e4/1e3),i=Math.floor(r%1e3),a=(e,t)=>e.toString().padStart(t,"0");return`${t}${a(n,2)}:${a(o,2)}:${a(s,2)}.${a(i,3)}`}function B(t=e.LogLevel.info,r=0,n=(...e)=>"called with "+e,o){return(e,s,i)=>{if(!i||"number"==typeof i)throw Error("Logging decoration only applies to methods");const a=e instanceof U?e.log.for(e[s]):z.for(e).for(e[s]),c=a[t].bind(a),l=i.value;return i.value=new Proxy(l,{apply(e,t,s){c(n(...s),r);try{const r=Reflect.apply(e,t,s);return r instanceof Promise?r.then(e=>(o&&c(o(void 0,e)),e)).catch(e=>{throw o&&a.error(o(e)),e}):(o&&c(o(void 0,r)),r)}catch(e){throw o&&a.error(o(e)),e}}}),i}}function W(){return(e,t,r)=>{if(!r)throw Error("final decorator can only be used on methods");return r?.configurable&&(r.configurable=!1),r}}class H extends J{constructor(e,t){super(),this.regexp=e,this.replacement=t}match(e){const t=this.regexp.exec(e);return this.regexp.lastIndex=0,t}filter(e,t,r){const n=this.log.for(this.filter);if(!this.match(t))return t;try{return t.replace(this.regexp,this.replacement)}catch(e){n.error("PatternFilter replacement error: "+e)}return""}}n.__decorate([W(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[String]),n.__metadata("design:returntype",void 0)],H.prototype,"match",null),e.BrowserEnvKey=o,e.DefaultLoggingConfig=g,e.DefaultPlaceholderWrappers=i,e.DefaultTheme=u,e.ENV_PATH_DELIMITER=s,e.Environment=C,e.LogFilter=J,e.LogParameterRegistry=f,e.LoggedClass=U,e.LoggedEnvironment=$,e.Logging=z,e.MiniLogger=D,e.NumericLogLevels=c,e.PACKAGE_NAME="@decaf-ts/logging",e.PatternFilter=H,e.ROOT_CONTEXT_SYMBOL=K,e.StopWatch=class{constructor(e=!1){this._startMs=null,this._elapsedMs=0,this._running=!1,this._laps=[],this._lastLapTotalMs=0,e&&this.start()}get running(){return this._running}get elapsedMs(){return this._running&&null!=this._startMs?this._elapsedMs+(Z()-this._startMs):this._elapsedMs}start(){return this._running||(this._running=!0,this._startMs=Z()),this}pause(){return this._running&&null!=this._startMs&&(this._elapsedMs+=Z()-this._startMs,this._startMs=null,this._running=!1),this}resume(){return this._running||(this._running=!0,this._startMs=Z()),this}stop(){return this.pause(),this._elapsedMs}reset(){const e=this._running;return this._startMs=e?Z():null,this._elapsedMs=0,this._laps=[],this._lastLapTotalMs=0,this}lap(e){const t=this.elapsedMs,r=t-this._lastLapTotalMs,n={index:this._laps.length,label:e,ms:r,totalMs:t};return this._laps.push(n),this._lastLapTotalMs=t,n}get laps(){return this._laps}toString(){return q(this.elapsedMs)}toJSON(){return{running:this._running,elapsedMs:this.elapsedMs,laps:this._laps.slice()}}},e.VERSION="0.19.0",e.benchmark=()=>(e,t,r)=>{if(!r||"number"==typeof r)throw Error("benchmark decoration only applies to methods");const n=e instanceof U?e.log.for(e[t]):z.for(e).for(e[t]),o=r.value;return r.value=new Proxy(o,{apply(e,t,r){const o=Z();try{const s=Reflect.apply(e,t,r);return s instanceof Promise?s.then(e=>(n.benchmark(`completed in ${Z()-o}ms`),e)).catch(e=>{throw n.benchmark(`failed in ${Z()-o}ms`),e}):(n.benchmark(`completed in ${Z()-o}ms`),s)}catch(e){throw n.benchmark(`failed in ${Z()-o}ms`),e}}}),r},e.compileLogPattern=h,e.debug=()=>B(e.LogLevel.debug,0,(...e)=>"called with "+e,(e,t)=>e?"Failed with: "+e:t?"Completed with "+JSON.stringify(t):"completed"),e.escapeRegExp=k,e.final=W,e.formatMs=q,e.getObjectName=F,e.info=()=>B(e.LogLevel.info),e.isBrowser=M,e.isClass=T,e.isFunction=I,e.isInstance=N,e.isMethod=V,e.log=B,e.logParameterRegistry=L,e.now=Z,e.padEnd=(e,t,r=" ")=>{if(1!==r.length)throw Error("Invalid character length for padding. must be one!");return e.padEnd(t,r)},e.patchPlaceholders=(e,t,r=i[0],n=i[1],o="g")=>E(e,Object.entries(t).reduce((e,[t,o])=>(e[`${r}${t}${n}`]=o,e),{}),o),e.patchString=E,e.renderPattern=y,e.sf=j,e.silly=()=>B(e.LogLevel.silly),e.stringFormat=A,e.toCamelCase=e=>e.replace(/(?:^\w|[A-Z]|\b\w)/g,(e,t)=>0===t?e.toLowerCase():e.toUpperCase()).replace(/\s+/g,""),e.toENVFormat=O,e.toKebabCase=e=>e.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase(),e.toPascalCase=e=>e.replace(/(?:^\w|[A-Z]|\b\w)/g,e=>e.toUpperCase()).replace(/\s+/g,""),e.toSnakeCase=_,e.trace=()=>B(e.LogLevel.trace),e.verbose=(t=0)=>(t||(t=0),B(e.LogLevel.verbose,t)),Object.keys(t).forEach(r=>{"default"===r||Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:()=>t[r]})})},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("styled-string-builder"),require("typed-object-accumulator"),require("tslib")):"function"==typeof define&&define.amd?define(["exports","styled-string-builder","typed-object-accumulator","tslib"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).logging={},e.styledStringBuilder,e.typedObjectAccumulator,e.tslib);
var e,t;e=this,t=function(e,t,r,n){"use strict";const o="ENV",s="__",i=["${","}"];var a;e.LogLevel=void 0,(a=e.LogLevel||(e.LogLevel={})).benchmark="benchmark",a.error="error",a.warn="warn",a.info="info",a.verbose="verbose",a.debug="debug",a.trace="trace",a.silly="silly";const c={benchmark:0,error:3,warn:6,info:9,verbose:12,debug:15,trace:18,silly:21};var l;e.LoggingMode=void 0,(l=e.LoggingMode||(e.LoggingMode={})).RAW="raw",l.JSON="json";const u={app:{},separator:{},class:{fg:34},id:{fg:36},stack:{},timestamp:{},message:{error:{fg:31}},method:{},logLevel:{benchmark:{fg:32,style:["bold"]},error:{fg:31,style:["bold"]},info:{fg:34,style:["bold"]},verbose:{fg:34,style:["bold"]},debug:{fg:33,style:["bold"]},trace:{fg:33,style:["bold"]},silly:{fg:33,style:["bold"]}}},g={env:"development",verbose:0,level:e.LogLevel.info,logLevel:!0,style:!1,filters:[],contextSeparator:".",separator:"-",timestamp:!0,timestampFormat:"HH:mm:ss.SSS",context:!0,meta:!0,format:e.LoggingMode.RAW,pattern:"{level} [{timestamp}] {app} {context} {separator} {message} {stack}",theme:u};class f{constructor(){this.descriptors=new Map}register(e){return this.descriptors.set(e.key,e),this}unregister(e){return this.descriptors.delete(e),this}get(e){return this.descriptors.get(e)}render(e,t){const r={},n=new Set;return t.forEach(t=>{if(n.has(t))return;n.add(t);const o=this.descriptors.get(t);if(!o)return;if(o.shouldInclude&&!o.shouldInclude(e))return;const s=o.render(e);if(void 0===s)return;const i=o.style?o.style(s,e):s;r[t]=i}),r}keys(){return Array.from(this.descriptors.keys())}}const p=new Map;function h(e){if(p.has(e))return p.get(e);const t=d(e||""),r=new Set,n=[];m(t,r,n);const o={pattern:e,segments:t,keys:n,includesMeta:r.has("meta")};return p.set(e,o),o}function y(e,t){return v(e.segments,t).text}function d(e){const t=[];let r=0;for(;r<e.length;){const n=e[r];if("["===n){const n=b(e,r,"[","]");if(-1===n){t.push({type:"literal",value:"["}),r++;continue}const o=e.slice(r+1,n);t.push({type:"optional",prefix:"[",suffix:"]",children:d(o)}),r=n+1;continue}if("{"===n){const n=e.indexOf("}",r+1);if(-1===n){t.push({type:"literal",value:"{"}),r++;continue}const o=e.slice(r+1,n).trim();t.push({type:"parameter",key:o}),r=n+1;continue}let o=r;for(;o<e.length&&"["!==e[o]&&"{"!==e[o];)o++;const s=e.slice(r,o);s.length&&t.push({type:"literal",value:s}),r=o}return t}function b(e,t,r,n){let o=0;for(let s=t;s<e.length;s++){const t=e[s];if(t===r)o++;else if(t===n&&(o--,0===o))return s}return-1}function m(e,t,r){for(const n of e)"parameter"===n.type&&(t.has(n.key)||(t.add(n.key),r.push(n.key))),"optional"===n.type&&m(n.children,t,r)}function v(e,t){const r=[];let n=!1;for(const o of e){const e=x(o,t);e.text.length&&r.push(e.text),n=n||e.hasValue}return{text:r.join(""),hasValue:n}}function x(e,t){if("literal"===e.type)return{text:e.value,hasValue:!1};if("parameter"===e.type){const r=t[e.key]??"";return{text:r,hasValue:r.length>0}}const r=v(e.children,t);return r.hasValue?{text:`${e.prefix}${r.text}${e.suffix}`,hasValue:!0}:{text:"",hasValue:!1}}const w=new f;w.register({key:"level",render(e){if(!1!==e.config.logLevel)return e.level.toUpperCase()},style:(e,t)=>t.applyTheme(e,"logLevel")}).register({key:"timestamp",shouldInclude:e=>!(!e.config.timestamp||!e.timestamp),render:e=>e.timestamp,style:(e,t)=>t.applyTheme(e,"timestamp")}).register({key:"app",shouldInclude:e=>!!e.app,render:e=>e.app,style:(e,t)=>t.applyTheme(e,"app")}).register({key:"context",shouldInclude:e=>!1!==e.config.context&&e.context.length>0,render(e){const t=e.config.contextSeparator||".";return e.context.join(t)},style:(e,t)=>t.applyTheme(e,"class")}).register({key:"separator",shouldInclude:e=>!!e.separator,render:e=>e.separator,style:(e,t)=>t.applyTheme(e,"separator")}).register({key:"message",render:e=>e.filteredMessage,style:(e,t)=>t.applyTheme(e,"message")}).register({key:"stack",shouldInclude:e=>!!e.stack,render:e=>e.stack,style:(e,t)=>t.applyTheme(e,"stack")}).register({key:"meta",shouldInclude:e=>!!e.metaString,render:e=>e.metaString}).register({key:"correlationId",shouldInclude:e=>!!e.correlationId,render:e=>e.correlationId,style:(e,t)=>t.applyTheme(e,"id")});const L=w;function E(e,t,r="g"){return Object.entries(t).forEach(([t,n])=>{const o=RegExp(k(t),r);e=e.replace(o,n)}),e}function O(e){return _(e).toUpperCase()}function _(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function k(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function j(e,...t){if(t.length>1&&!t.every(e=>"string"==typeof e||"number"==typeof e))throw Error("Only string and number arguments are supported for multiple replacements.");if(1===t.length&&"object"==typeof t[0]){const r=t[0];return Object.entries(r).reduce((e,[t,r])=>e.replace(RegExp(`\\{${t}\\}`,"g"),()=>r),e)}return e.replace(/{(\d+)}/g,(e,r)=>void 0!==t[r]?t[r].toString():"undefined")}const A=j;function M(){return Object.getPrototypeOf(Object.getPrototypeOf(globalThis))!==Object.prototype}const P=Symbol("EnvironmentEmpty"),S=Symbol("EnvironmentModel"),R=/^[a-z][a-zA-Z0-9]*$/;class C extends r.ObjectAccumulator{static{this.factory=()=>new C}constructor(){super(),Object.defineProperty(this,S,{value:{},writable:!0,enumerable:!1,configurable:!1})}fromEnv(e){let t;return M()?t=globalThis[o]||{}:(t=globalThis.process.env,e=O(e)),this.parseEnvValue(t[e])}parseEnvValue(e){return C.parseRuntimeValue(e)}static parseRuntimeValue(e){if("string"!=typeof e)return e;if("true"===e)return!0;if("false"===e)return!1;const t=e.trim();return/^-?\d+(\.\d+)?$/.test(t)?Number(t):e}expand(e){Object.entries(e).forEach(([e,t])=>{C.mergeModel(this[S],e,t),Object.defineProperty(this,e,{get:()=>{const r=this.fromEnv(e);return void 0!==r?r:t&&"object"==typeof t?Array.isArray(t)?t:C.buildEnvProxy(t,[e]):""===t?P:t},set:e=>{t=e},configurable:!0,enumerable:!0})})}orThrow(){const e=this[S],t=e=>void 0!==e?this.parseEnvValue(e):void 0,r=(e,t=!1)=>C.missingEnvError(e,t),n=(e,o)=>{const s={get(s,i){if("string"!=typeof i)return;if(Array.isArray(e)&&"length"===i)return e.length;const a=[...o,i],{key:c,value:l}=C.readRuntimeForPath(a);if("string"==typeof l&&0===l.length)throw r(c,!0);const u=t(l);if(void 0!==u){if("string"==typeof u&&0===u.length)throw r(c,!0);return u}if(!e||!Object.prototype.hasOwnProperty.call(e,i))throw r(c);const g=e[i];if(void 0!==g){if(""===g)throw r(c);return g&&"object"==typeof g?n(g,a):g}},ownKeys:()=>e?Reflect.ownKeys(e):[],getOwnPropertyDescriptor(t,r){if(e)return Object.prototype.hasOwnProperty.call(e,r)?{enumerable:!0,configurable:!0}:void 0}};return new Proxy(Array.isArray(e)?[]:{},s)};return new Proxy(this,{get(o,s,i){if("string"!=typeof s)return Reflect.get(o,s,i);if(!Object.prototype.hasOwnProperty.call(e,s))return Reflect.get(o,s,i);const{key:a,value:c}=C.readRuntimeForPath([s]);if("string"==typeof c&&0===c.length)throw r(a,!0);const l=t(c);if(void 0!==l){if("string"==typeof l&&0===l.length)throw r(a,!0);return l}const u=e[s];if(u&&"object"==typeof u)return n(u,[s]);if(void 0===u)return Reflect.get(o,s,i);const g=Reflect.get(o,s);if(void 0===g||""===g)throw r(a,""===g);return g}})}static instance(...e){if(!C._instance){const t=C.factory(...e),r=new Proxy(t,{get(e,t,r){const n=Reflect.get(e,t,r);if(n!==P&&("string"!=typeof t||!Object.prototype.hasOwnProperty.call(e,t)||void 0!==n)){if(void 0!==n)return n;if("string"==typeof t){if("app"===t)return;return C.buildEnvProxy(void 0,[t])}return n}}});C._instance=r}return C._instance}accumulate(e){return super.accumulate(e),this}static accumulate(e){const t=C.instance();return Object.keys(t).forEach(e=>{const r=Object.getOwnPropertyDescriptor(t,e);r&&r.configurable&&r.enumerable&&Object.defineProperty(t,e,{...r,enumerable:!1})}),t.accumulate(e),t}static get(e){return C._instance.get(e)}static formatEnvSegment(e){return R.test(e)?O(e):e.toUpperCase()}static buildEnvKey(e){return e.map(e=>C.formatEnvSegment(e)).join(s)}static buildRawKey(e){return e.join(s)}static readRuntimeForPath(e){const t=C.buildEnvKey(e),r=C.buildRawKey(e),n=C.readRuntimeEnv(t);if(void 0!==n)return{key:t,value:n};if(r!==t){const e=C.readRuntimeEnv(r);if(void 0!==e)return{key:r,value:e}}return{key:t,value:void 0}}static buildEnvProxy(e,t){const r=e=>C.readRuntimeEnv(e),n=/^[0-9]+$/,o={get(o,s){if(s===Symbol.toPrimitive)return()=>C.buildEnvKey(t);if("toString"===s)return()=>C.buildEnvKey(t);if("valueOf"===s)return()=>C.buildEnvKey(t);if("symbol"==typeof s)return;if(Array.isArray(e)&&"length"===s)return e.length;const i=[...t,s],a=C.buildEnvKey(i),c=C.buildRawKey(i);let l=r(a);if(void 0===l&&c!==a&&(l=r(c)),void 0!==l)return C.parseRuntimeValue(l);const u=!!e&&Object.prototype.hasOwnProperty.call(e,s),g=u?e[s]:void 0;if(Array.isArray(e)&&(e=>"string"==typeof e&&n.test(e))(s)){if(!u)return;return g&&"object"==typeof g?C.buildEnvProxy(g,i):C.parseRuntimeValue(g)}return g&&"object"==typeof g?C.buildEnvProxy(g,i):u&&""===g||u&&void 0===g?void 0:u?C.parseRuntimeValue(g):C.buildEnvProxy(void 0,i)},ownKeys:()=>e?Reflect.ownKeys(e):[],getOwnPropertyDescriptor(t,r){if(e)return Object.prototype.hasOwnProperty.call(e,r)?{enumerable:!0,configurable:!0}:void 0}};return new Proxy(Array.isArray(e)?[]:{},o)}static keys(e=!0){return C.instance().keys().map(t=>e?O(t):t)}static mergeModel(e,t,r){if(e){if(r&&"object"==typeof r&&!Array.isArray(r)){const n=e[t],o=n&&"object"==typeof n&&!Array.isArray(n)?n:{};return e[t]=o,void Object.entries(r).forEach(([e,t])=>{C.mergeModel(o,e,t)})}e[t]=r}}static readRuntimeEnv(e){if(M()){const t=globalThis[o];return t?t[e]:void 0}return globalThis?.process?.env?.[e]}static missingEnvError(e,t){return Error(`Environment variable ${e} is required but was ${t?"an empty string":"undefined"}.`)}}const $=C.accumulate(Object.assign({app:void 0},g,{env:(M()&&globalThis[o]?globalThis[o].NODE_ENV:globalThis.process.env.NODE_ENV)||"development"}));function T(e){if("function"!=typeof e)return!1;try{const t=Function.prototype.toString.call(e);if(/^\s*class[\s{]/.test(t))return!0}catch{}const t=Object.getOwnPropertyDescriptor(e,"prototype");if(!t||!t.value)return!1;if(!1===t.writable)return!0;const r=e.prototype;return!!Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.getOwnPropertyNames(r).filter(e=>"constructor"!==e).length>0}function I(e){return"function"==typeof e&&!T(e)}function V(e){if(!I(e))return!1;const t=Object.getOwnPropertyDescriptor(e,"prototype");return!t||void 0===t.value}function N(e){if(null===e||"object"!=typeof e)return!1;const t=e.constructor;return!(!t||t===Object)&&T(t)}function F(e){if(null===e)return"null";if(void 0===e)return"undefined";if("string"==typeof e)return e;if(T(e))return e.name||"AnonymousClass";if(N(e)){const t=e.toString;if("function"==typeof t&&t!==Object.prototype.toString)try{const r=t.call(e);if("string"==typeof r&&r.length)return r}catch{}const r=e.constructor;return r&&r.name?r.name:"AnonymousInstance"}if(V(e)||I(e)){const t=e;return t.name?t.name:"anonymous"}if("object"==typeof e){const t=Object.prototype.toString.call(e),r=/^\[object ([^\]]+)\]$/.exec(t);return r?.[1]?r[1]:"Object"}return typeof e}const K=Symbol("MiniLoggerRootContext");class D{constructor(e,t,r=[]){this.conf=t,this.baseContext=Array.isArray(r)?[...r]:[],e&&this.baseContext.push(e),this.context=[...this.baseContext],this[K]=[...this.baseContext]}config(e){return this.conf&&e in this.conf?this.conf[e]:z.getConfig()[e]}for(e,t,...r){let n,o=t;const s=Array.isArray(this.context)?[...this.context]:"string"==typeof this.context&&this.context?[this.context]:[],i=this[K],a=Array.isArray(i)?[...i]:Array.isArray(this.baseContext)?[...this.baseContext]:[];"string"==typeof e?n=e:void 0!==e&&(T(e)||N(e)||I(e)?n=F(e):!o&&e&&"object"==typeof e&&(o=e));let c=n?[...s,n]:[...s];return new Proxy(this,{get:(e,t,r)=>{const n=Reflect.get(e,t,r);return"config"===t?new Proxy(this.config,{apply:(e,t,n)=>{const[s]=n;return o&&void 0!==s&&s in o?o[s]:Reflect.apply(e,r,n)},get:(e,t)=>o&&t in o?o[t]:Reflect.get(e,t,r)}):"clear"===t?()=>(c=[...a],o=void 0,r):"context"===t?c:"root"===t?[...a]:t===K?a:"for"===t?(...t)=>{const r=Array.isArray(e.context)?[...e.context]:"string"==typeof e.context&&e.context?[e.context]:[];e.context=[...c];try{return e.for.apply(e,t)}finally{e.context=r}}:n}})}getConfigSnapshot(){return{...z.getConfig(),...this.conf||{}}}getContextSegments(){return Array.isArray(this.context)?[...this.context]:"string"==typeof this.context&&this.context?[this.context]:[]}resolveFilters(e){const t=e.filters||[];return Array.isArray(t)?t.filter(e=>"object"==typeof e&&null!==e&&"function"==typeof e.filter):[]}applyFilters(e,t,r){const n=this.resolveFilters(r);return n.length?n.reduce((e,n)=>{try{const o=n.filter(r,e,[...t]);return"string"==typeof o?o:e}catch{return e}},e):e}createLog(e,t,r,n){const o=!!this.config("style"),s=this.config("separator"),i=z.getConfig().app,a=this.config("timestamp")?(new Date).toISOString():void 0,c=this.getConfigSnapshot(),l=this.getContextSegments(),u="string"==typeof t?t:t instanceof Error?t.message:t+"",g=this.applyFilters(u,l,c),f=this.config("meta")&&n?n:void 0,p=f?this.formatMeta(f):void 0,d=p?this.applyFilters(p,l,c):void 0,b=this.config("correlationId"),m=null!=b?b+"":void 0;let v,x;if(r||t instanceof Error){const n=r||t;n.stack&&(x="string"==typeof t?g:n.message,v=` | ${x} - Stack trace:\n${o?z.theme(n.stack,"stack",e):n.stack}`)}const w={config:c,level:e,context:l,timestamp:a,app:"string"==typeof i&&i.length?i:void 0,separator:s,correlationId:m,rawMessage:u,filteredMessage:g,meta:f,metaString:d,stack:v,stackLabel:x,applyTheme:(t,r)=>o?z.theme(t,r,e):t},E=this.config("pattern"),O=c.pattern||"",_=h(E.length?E:O),k=L.render(w,_.keys);switch(this.config("format")){case"json":{const e=L.render(w,L.keys()),t={};return Object.entries(e).forEach(([e,r])=>{"meta"!==e&&(t[e]=r)}),w.meta&&(t.meta=w.meta),JSON.stringify(t)}case"raw":{let e=this.normalizePatternSpacing(y(_,k));return!_.includesMeta&&d&&(e=e?`${e} ${d}`:d),e}default:throw Error("Unsupported logging format: "+this.config("format"))}}formatMeta(e){try{return JSON.stringify(e)}catch(t){return e+""}}normalizePatternSpacing(e){return e.replace(/[ \t]{2,}/g," ").replace(/^[ \t]+|[ \t]+$/g,"")}log(t,r,n,o){const s=this.config("level");if(c[t]>c[s])return;let i;switch(t){case e.LogLevel.benchmark:case e.LogLevel.info:case e.LogLevel.verbose:i=console.log;break;case e.LogLevel.debug:i=console.debug;break;case e.LogLevel.error:i=console.error;break;case e.LogLevel.trace:i=console.trace;break;case e.LogLevel.warn:i=console.warn;break;case e.LogLevel.silly:i=console.debug;break;default:throw Error("Invalid log level")}i(this.createLog(t,r,n,o))}benchmark(t,r){this.log(e.LogLevel.benchmark,t,void 0,r)}silly(t,r=0,n){const o="number"==typeof r?r:0,s="number"==typeof r?n:r;this.config("verbose")<o||this.log(e.LogLevel.silly,t,void 0,s)}verbose(t,r=0,n){const o="number"==typeof r?r:0,s="number"==typeof r?n:r;this.config("verbose")<o||this.log(e.LogLevel.verbose,t,void 0,s)}info(t,r){this.log(e.LogLevel.info,t,void 0,r)}debug(t,r){this.log(e.LogLevel.debug,t,void 0,r)}error(t,r,n){let o,s;r instanceof Error?(o=r,s=n):s=r,this.log(e.LogLevel.error,t,o,s)}warn(t,r){this.log(e.LogLevel.warn,t,void 0,r)}trace(t,r){this.log(e.LogLevel.trace,t,void 0,r)}setConfig(e){this.conf={...this.conf||{},...e}}get root(){return[...this.baseContext]}clear(){return this.context=[...this.baseContext],this}}class z{static{this._factory=(e,t)=>{const r="string"==typeof $.app?[$.app]:[];return new D(e,t,r)}}static{this._config=$}constructor(){}static setFactory(e){z._factory=e,this.global=void 0}static setConfig(e){Object.entries(e).forEach(([e,t])=>{this._config[e]=t})}static getConfig(){return this._config}static get(){return this.ensureRoot()}static verbose(e,t=0,r){return this.get().verbose(e,t,r)}static info(e,t){return this.get().info(e,t)}static trace(e,t){return this.get().trace(e,t)}static debug(e,t){return this.get().debug(e,t)}static benchmark(e,t){return this.get().benchmark(e,t)}static silly(e,t=0,r){return this.get().silly(e,t,r)}static warn(e,t){return this.get().warn(e,t)}static error(e,t,r){return this.get().error(e,t,r)}static for(e,t,...r){const n=void 0!==t?[e,t]:[e];return(this.global?this.global:this.ensureRoot(r)).for(...n)}static because(e,t){let r=this.ensureRoot().for(e,this._config);return t&&(r=r.for(t)),r}static baseContext(){const e=this._config.app;return"string"==typeof e&&e.length?[e]:[]}static attachRootContext(e){const t=e.root&&Array.isArray(e.root)?[...e.root]:this.baseContext();return(!e.context||Array.isArray(e.context)&&0===e.context.length)&&(e.context=[...t]),e[K]=[...t],e}static ensureRoot(e=[]){if(!this.global){const t=this._factory(void 0,void 0,...e);this.global=this.attachRootContext(t)}return this.global}static theme(r,n,o,s=u){if(!this._config.style)return r;const i=s[n];if(!i||!Object.keys(i).length)return r;let a=i;const c=Object.assign({},e.LogLevel);return Object.keys(i)[0]in c&&(a=i[o]||{}),Object.keys(a).reduce((e,r)=>{const n=a[r];return n?((e,r,n)=>{try{const o=e;let s=t.style(o);function i(e,r=!1){let i=r?s.background:s.foreground;if(!Array.isArray(e))return i.call(s,n);switch(e.length){case 1:return i=r?s.bgColor256:s.color256,i(e[0]);case 3:return i=r?s.bgRgb:s.rgb,s.rgb(e[0],e[1],e[2]);default:return t.style(o)}}function a(e){s="number"==typeof e?s.style(e):s[e]}switch(r){case"bg":case"fg":return i(n).text;case"style":return Array.isArray(n)?n.forEach(a):a(n),s.text;default:return o}}catch(c){return e}})(e,r,n):e},r)}static register(e){return L.register(e)}static unregister(e){return L.unregister(e)}}class U{get log(){return this._log||(this._log=z.for(this)),this._log}constructor(){}}class J extends U{get log(){return super.log.for(this,{filters:[]})}}const Z="undefined"!=typeof globalThis&&"function"==typeof globalThis.performance?.now?()=>globalThis.performance.now():"undefined"!=typeof process&&"function"==typeof process.hrtime?.bigint?()=>{const e=process.hrtime.bigint();return Number(e)/1e6}:()=>Date.now();function q(e){const t=0>e?"-":"",r=Math.abs(e),n=Math.floor(r/36e5),o=Math.floor(r%36e5/6e4),s=Math.floor(r%6e4/1e3),i=Math.floor(r%1e3),a=(e,t)=>e.toString().padStart(t,"0");return`${t}${a(n,2)}:${a(o,2)}:${a(s,2)}.${a(i,3)}`}function B(t=e.LogLevel.info,r=0,n=(...e)=>"called with "+e,o){return(e,s,i)=>{if(!i||"number"==typeof i)throw Error("Logging decoration only applies to methods");const a=e instanceof U?e.log.for(e[s]):z.for(e).for(e[s]),c=a[t].bind(a),l=i.value;return i.value=new Proxy(l,{apply(e,t,s){c(n(...s),r);try{const r=Reflect.apply(e,t,s);return r instanceof Promise?r.then(e=>(o&&c(o(void 0,e)),e)).catch(e=>{throw o&&a.error(o(e)),e}):(o&&c(o(void 0,r)),r)}catch(e){throw o&&a.error(o(e)),e}}}),i}}function W(){return(e,t,r)=>{if(!r)throw Error("final decorator can only be used on methods");return r?.configurable&&(r.configurable=!1),r}}class H extends J{constructor(e,t){super(),this.regexp=e,this.replacement=t}match(e){const t=this.regexp.exec(e);return this.regexp.lastIndex=0,t}filter(e,t,r){const n=this.log.for(this.filter);if(!this.match(t))return t;try{return t.replace(this.regexp,this.replacement)}catch(e){n.error("PatternFilter replacement error: "+e)}return""}}n.__decorate([W(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[String]),n.__metadata("design:returntype",void 0)],H.prototype,"match",null),e.BrowserEnvKey=o,e.DefaultLoggingConfig=g,e.DefaultPlaceholderWrappers=i,e.DefaultTheme=u,e.ENV_PATH_DELIMITER=s,e.Environment=C,e.LogFilter=J,e.LogParameterRegistry=f,e.LoggedClass=U,e.LoggedEnvironment=$,e.Logging=z,e.MiniLogger=D,e.NumericLogLevels=c,e.PACKAGE_NAME="@decaf-ts/logging",e.PatternFilter=H,e.ROOT_CONTEXT_SYMBOL=K,e.StopWatch=class{constructor(e=!1){this._startMs=null,this._elapsedMs=0,this._running=!1,this._laps=[],this._lastLapTotalMs=0,e&&this.start()}get running(){return this._running}get elapsedMs(){return this._running&&null!=this._startMs?this._elapsedMs+(Z()-this._startMs):this._elapsedMs}start(){return this._running||(this._running=!0,this._startMs=Z()),this}pause(){return this._running&&null!=this._startMs&&(this._elapsedMs+=Z()-this._startMs,this._startMs=null,this._running=!1),this}resume(){return this._running||(this._running=!0,this._startMs=Z()),this}stop(){return this.pause(),this._elapsedMs}reset(){const e=this._running;return this._startMs=e?Z():null,this._elapsedMs=0,this._laps=[],this._lastLapTotalMs=0,this}lap(e){const t=this.elapsedMs,r=t-this._lastLapTotalMs,n={index:this._laps.length,label:e,ms:r,totalMs:t};return this._laps.push(n),this._lastLapTotalMs=t,n}get laps(){return this._laps}toString(){return q(this.elapsedMs)}toJSON(){return{running:this._running,elapsedMs:this.elapsedMs,laps:this._laps.slice()}}},e.VERSION="0.20.0",e.benchmark=()=>(e,t,r)=>{if(!r||"number"==typeof r)throw Error("benchmark decoration only applies to methods");const n=e instanceof U?e.log.for(e[t]):z.for(e).for(e[t]),o=r.value;return r.value=new Proxy(o,{apply(e,t,r){const o=Z();try{const s=Reflect.apply(e,t,r);return s instanceof Promise?s.then(e=>(n.benchmark(`completed in ${Z()-o}ms`),e)).catch(e=>{throw n.benchmark(`failed in ${Z()-o}ms`),e}):(n.benchmark(`completed in ${Z()-o}ms`),s)}catch(e){throw n.benchmark(`failed in ${Z()-o}ms`),e}}}),r},e.compileLogPattern=h,e.debug=()=>B(e.LogLevel.debug,0,(...e)=>"called with "+e,(e,t)=>e?"Failed with: "+e:t?"Completed with "+JSON.stringify(t):"completed"),e.escapeRegExp=k,e.final=W,e.formatMs=q,e.getObjectName=F,e.info=()=>B(e.LogLevel.info),e.isBrowser=M,e.isClass=T,e.isFunction=I,e.isInstance=N,e.isMethod=V,e.log=B,e.logParameterRegistry=L,e.now=Z,e.padEnd=(e,t,r=" ")=>{if(1!==r.length)throw Error("Invalid character length for padding. must be one!");return e.padEnd(t,r)},e.patchPlaceholders=(e,t,r=i[0],n=i[1],o="g")=>E(e,Object.entries(t).reduce((e,[t,o])=>(e[`${r}${t}${n}`]=o,e),{}),o),e.patchString=E,e.renderPattern=y,e.sf=j,e.silly=()=>B(e.LogLevel.silly),e.stringFormat=A,e.toCamelCase=e=>e.replace(/(?:^\w|[A-Z]|\b\w)/g,(e,t)=>0===t?e.toLowerCase():e.toUpperCase()).replace(/\s+/g,""),e.toENVFormat=O,e.toKebabCase=e=>e.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase(),e.toPascalCase=e=>e.replace(/(?:^\w|[A-Z]|\b\w)/g,e=>e.toUpperCase()).replace(/\s+/g,""),e.toSnakeCase=_,e.trace=()=>B(e.LogLevel.trace),e.verbose=(t=0)=>(t||(t=0),B(e.LogLevel.verbose,t)),Object.keys(t).forEach(r=>{"default"===r||Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:()=>t[r]})})},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("styled-string-builder"),require("typed-object-accumulator"),require("tslib")):"function"==typeof define&&define.amd?define(["exports","styled-string-builder","typed-object-accumulator","tslib"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).logging={},e.styledStringBuilder,e.typedObjectAccumulator,e.tslib);
//# sourceMappingURL=logging.cjs.map

@@ -43,3 +43,3 @@ "use strict";

*/
exports.VERSION = "0.19.0";
exports.VERSION = "0.20.0";
/**

@@ -46,0 +46,0 @@ * @description Current package version string.

@@ -26,3 +26,3 @@ /**

*/
export const VERSION = "0.19.0";
export const VERSION = "0.20.0";
/**

@@ -29,0 +29,0 @@ * @description Current package version string.

@@ -1,2 +0,2 @@

import { LoggingConfig, Theme } from "./types.cjs";
import { LoggingConfig, Theme } from "./types.d.cts";
/**

@@ -3,0 +3,0 @@ * @description The global key that is used to store environment variables in browser contexts.

@@ -1,2 +0,2 @@

import { LoggingConfig, Theme } from "./types.js";
import { LoggingConfig, Theme } from "./types.d.mts";
/**

@@ -3,0 +3,0 @@ * @description The global key that is used to store environment variables in browser contexts.

@@ -1,2 +0,2 @@

import { LogLevel } from "./constants.cjs";
import { LogLevel } from "./constants.d.cts";
export type ArgFormatFunction = (...args: any[]) => string;

@@ -3,0 +3,0 @@ export type ReturnFormatFunction = (e?: Error, result?: any) => string;

@@ -1,2 +0,2 @@

import { LogLevel } from "./constants.js";
import { LogLevel } from "./constants.d.mts";
export type ArgFormatFunction = (...args: any[]) => string;

@@ -3,0 +3,0 @@ export type ReturnFormatFunction = (e?: Error, result?: any) => string;

@@ -6,3 +6,3 @@ /**

*/
export * from "./LogFilter.cjs";
export * from "./PatternFilter.cjs";
export * from "./LogFilter.d.cts";
export * from "./PatternFilter.d.cts";

@@ -6,3 +6,3 @@ /**

*/
export * from "./LogFilter.js";
export * from "./PatternFilter.js";
export * from "./LogFilter.d.mts";
export * from "./PatternFilter.d.mts";

@@ -1,3 +0,3 @@

import { Logger, LoggingConfig, LoggingFilter } from "../types.cjs";
import { LoggedClass } from "../LoggedClass.cjs";
import { Logger, LoggingConfig, LoggingFilter } from "../types.d.cts";
import { LoggedClass } from "../LoggedClass.d.cts";
/**

@@ -4,0 +4,0 @@ * @description A base class for message filters that can be plugged into the logging pipeline.

@@ -1,3 +0,3 @@

import { Logger, LoggingConfig, LoggingFilter } from "../types.js";
import { LoggedClass } from "../LoggedClass.js";
import { Logger, LoggingConfig, LoggingFilter } from "../types.d.mts";
import { LoggedClass } from "../LoggedClass.d.mts";
/**

@@ -4,0 +4,0 @@ * @description A base class for message filters that can be plugged into the logging pipeline.

@@ -1,3 +0,3 @@

import { LogFilter } from "./LogFilter.cjs";
import { LoggingConfig } from "../types.cjs";
import { LogFilter } from "./LogFilter.d.cts";
import { LoggingConfig } from "../types.d.cts";
/**

@@ -4,0 +4,0 @@ * @description A replacement callback that is used to transform RegExp matches.

@@ -1,3 +0,3 @@

import { LogFilter } from "./LogFilter.js";
import { LoggingConfig } from "../types.js";
import { LogFilter } from "./LogFilter.d.mts";
import { LoggingConfig } from "../types.d.mts";
/**

@@ -4,0 +4,0 @@ * @description A replacement callback that is used to transform RegExp matches.

@@ -6,14 +6,14 @@ /**

*/
export * from "./filters/index.cjs";
export * from "./constants.cjs";
export * from "./decorators.cjs";
export * from "./environment.cjs";
export * from "./LoggedClass.cjs";
export * from "./logging.cjs";
export * from "./logParameters.cjs";
export * from "./text.cjs";
export * from "./time.cjs";
export * from "./types.cjs";
export * from "./web.cjs";
export * from "./utils.cjs";
export * from "./filters/index.d.cts";
export * from "./constants.d.cts";
export * from "./decorators.d.cts";
export * from "./environment.d.cts";
export * from "./LoggedClass.d.cts";
export * from "./logging.d.cts";
export * from "./logParameters.d.cts";
export * from "./text.d.cts";
export * from "./time.d.cts";
export * from "./types.d.cts";
export * from "./web.d.cts";
export * from "./utils.d.cts";
export * from "styled-string-builder";

@@ -20,0 +20,0 @@ /**

@@ -6,14 +6,14 @@ /**

*/
export * from "./filters/index.js";
export * from "./constants.js";
export * from "./decorators.js";
export * from "./environment.js";
export * from "./LoggedClass.js";
export * from "./logging.js";
export * from "./logParameters.js";
export * from "./text.js";
export * from "./time.js";
export * from "./types.js";
export * from "./web.js";
export * from "./utils.js";
export * from "./filters/index.d.mts";
export * from "./constants.d.mts";
export * from "./decorators.d.mts";
export * from "./environment.d.mts";
export * from "./LoggedClass.d.mts";
export * from "./logging.d.mts";
export * from "./logParameters.d.mts";
export * from "./text.d.mts";
export * from "./time.d.mts";
export * from "./types.d.mts";
export * from "./web.d.mts";
export * from "./utils.d.mts";
export * from "styled-string-builder";

@@ -20,0 +20,0 @@ /**

@@ -1,2 +0,2 @@

import { Logger } from "./types.cjs";
import { Logger } from "./types.d.cts";
/**

@@ -3,0 +3,0 @@ * @description A base class that provides a ready-to-use logger instance.

@@ -1,2 +0,2 @@

import { Logger } from "./types.js";
import { Logger } from "./types.d.mts";
/**

@@ -3,0 +3,0 @@ * @description A base class that provides a ready-to-use logger instance.

@@ -1,5 +0,5 @@

import { LoggerFactory, LoggingConfig, LoggingContext, LoggingFilter, LogMeta, StringLike, Theme, Logger } from "./types.cjs";
import { LogLevel } from "./constants.cjs";
import { LogParameterDescriptor } from "./logParameters.cjs";
import { LoggedEnvironment } from "./environment.cjs";
import { LoggerFactory, LoggingConfig, LoggingContext, LoggingFilter, LogMeta, StringLike, Theme, Logger } from "./types.d.cts";
import { LogLevel } from "./constants.d.cts";
import { LogParameterDescriptor } from "./logParameters.d.cts";
import { LoggedEnvironment } from "./environment.d.cts";
export declare const ROOT_CONTEXT_SYMBOL: unique symbol;

@@ -371,4 +371,4 @@ /**

static theme(text: string, type: keyof Theme | keyof LogLevel, loggerLevel: LogLevel, template?: Theme): string;
static register(descriptor: LogParameterDescriptor): import("./logParameters.cjs").LogParameterRegistry;
static unregister(key: string): import("./logParameters.cjs").LogParameterRegistry;
static register(descriptor: LogParameterDescriptor): import("./logParameters.d.cts").LogParameterRegistry;
static unregister(key: string): import("./logParameters.d.cts").LogParameterRegistry;
}

@@ -1,5 +0,5 @@

import { LoggerFactory, LoggingConfig, LoggingContext, LoggingFilter, LogMeta, StringLike, Theme, Logger } from "./types.js";
import { LogLevel } from "./constants.js";
import { LogParameterDescriptor } from "./logParameters.js";
import { LoggedEnvironment } from "./environment.js";
import { LoggerFactory, LoggingConfig, LoggingContext, LoggingFilter, LogMeta, StringLike, Theme, Logger } from "./types.d.mts";
import { LogLevel } from "./constants.d.mts";
import { LogParameterDescriptor } from "./logParameters.d.mts";
import { LoggedEnvironment } from "./environment.d.mts";
export declare const ROOT_CONTEXT_SYMBOL: unique symbol;

@@ -371,4 +371,4 @@ /**

static theme(text: string, type: keyof Theme | keyof LogLevel, loggerLevel: LogLevel, template?: Theme): string;
static register(descriptor: LogParameterDescriptor): import("./logParameters.js").LogParameterRegistry;
static unregister(key: string): import("./logParameters.js").LogParameterRegistry;
static register(descriptor: LogParameterDescriptor): import("./logParameters.d.mts").LogParameterRegistry;
static unregister(key: string): import("./logParameters.d.mts").LogParameterRegistry;
}

@@ -1,3 +0,3 @@

import { LogLevel } from "./constants.cjs";
import { LogMeta, LoggingConfig } from "./types.cjs";
import { LogLevel } from "./constants.d.cts";
import { LogMeta, LoggingConfig } from "./types.d.cts";
export type LogParameterPayload = {

@@ -4,0 +4,0 @@ config: LoggingConfig;

@@ -1,3 +0,3 @@

import { LogLevel } from "./constants.js";
import { LogMeta, LoggingConfig } from "./types.js";
import { LogLevel } from "./constants.d.mts";
import { LogMeta, LoggingConfig } from "./types.d.mts";
export type LogParameterPayload = {

@@ -4,0 +4,0 @@ config: LoggingConfig;

@@ -7,2 +7,2 @@ /**

*/
export * from "./pino.cjs";
export * from "./pino.d.cts";

@@ -7,2 +7,2 @@ /**

*/
export * from "./pino.js";
export * from "./pino.d.mts";
import { Logger as PinoBaseLogger } from "pino";
import { MiniLogger } from "../logging.cjs";
import { Logger, LoggerFactory, LogMeta, LoggingConfig, StringLike } from "../types.cjs";
import { LogLevel } from "../constants.cjs";
import { MiniLogger } from "../logging.d.cts";
import { Logger, LoggerFactory, LogMeta, LoggingConfig, StringLike } from "../types.d.cts";
import { LogLevel } from "../constants.d.cts";
/**

@@ -6,0 +6,0 @@ * @description A logger that is powered by the Pino logging library.

import { Logger as PinoBaseLogger } from "pino";
import { MiniLogger } from "../logging.js";
import { Logger, LoggerFactory, LogMeta, LoggingConfig, StringLike } from "../types.js";
import { LogLevel } from "../constants.js";
import { MiniLogger } from "../logging.d.mts";
import { Logger, LoggerFactory, LogMeta, LoggingConfig, StringLike } from "../types.d.mts";
import { LogLevel } from "../constants.d.mts";
/**

@@ -6,0 +6,0 @@ * @description A logger that is powered by the Pino logging library.

import { styles } from "styled-string-builder";
import { LoggingMode, LogLevel } from "./constants.cjs";
import { LoggingMode, LogLevel } from "./constants.d.cts";
/**

@@ -4,0 +4,0 @@ * @description A string-compatible value that can be accepted by the logging APIs.

import { styles } from "styled-string-builder";
import { LoggingMode, LogLevel } from "./constants.js";
import { LoggingMode, LogLevel } from "./constants.d.mts";
/**

@@ -4,0 +4,0 @@ * @description A string-compatible value that can be accepted by the logging APIs.

@@ -7,2 +7,2 @@ /**

*/
export * from "./winston.cjs";
export * from "./winston.d.cts";

@@ -7,2 +7,2 @@ /**

*/
export * from "./winston.js";
export * from "./winston.d.mts";
import winston from "winston";
import { Logger, LoggerFactory, LogMeta, LoggingConfig, StringLike } from "../types.cjs";
import { MiniLogger } from "../logging.cjs";
import { LogLevel } from "../constants.cjs";
import { Logger, LoggerFactory, LogMeta, LoggingConfig, StringLike } from "../types.d.cts";
import { MiniLogger } from "../logging.d.cts";
import { LogLevel } from "../constants.d.cts";
/**

@@ -6,0 +6,0 @@ * @description A logger implementation that uses Winston.

import winston from "winston";
import { Logger, LoggerFactory, LogMeta, LoggingConfig, StringLike } from "../types.js";
import { MiniLogger } from "../logging.js";
import { LogLevel } from "../constants.js";
import { Logger, LoggerFactory, LogMeta, LoggingConfig, StringLike } from "../types.d.mts";
import { MiniLogger } from "../logging.d.mts";
import { LogLevel } from "../constants.d.mts";
/**

@@ -6,0 +6,0 @@ * @description A logger implementation that uses Winston.

{
"name": "@decaf-ts/logging",
"version": "0.20.0",
"version": "0.21.0",
"description": "simple winston inspired wrapper for cross lib logging",

@@ -5,0 +5,0 @@ "type": "module",

import { LoggingConfig, Theme } from "./types";
/**
* @description The global key that is used to store environment variables in browser contexts.
* @summary This enables the logging environment helpers to locate serialized environment configuration on `globalThis`.
* @const {string} BrowserEnvKey
* @memberOf module:Logging
*/
export declare const BrowserEnvKey = "ENV";
/**
* @description The delimiter that is used for composing nested environment variable names.
* @summary This joins parent and child keys when mapping object paths to ENV strings.
* @const {string} ENV_PATH_DELIMITER
* @memberOf module:Logging
*/
export declare const ENV_PATH_DELIMITER = "__";
/**
* @description The default prefix and suffix that are used for template placeholders.
* @summary This provides wrapper strings that are applied when interpolating messages with {@link patchPlaceholders}.
* @const {string[]} DefaultPlaceholderWrappers
* @memberOf module:Logging
*/
export declare const DefaultPlaceholderWrappers: string[];
/**
* @description An enum for log levels.
* @summary Defines the different levels of logging for the application.
* @enum {string}
* @readonly
* @memberOf module:Logging
*/
export declare enum LogLevel {
/** @description Benchmark events that capture performance metrics. */
benchmark = "benchmark",
/** @description Error events that indicate failures requiring attention. */
error = "error",
/** @description Warning events that may indicate issues. */
warn = "warn",
/** @description Informational events describing normal operation. */
info = "info",
/** @description Verbose diagnostic information for detailed tracing. */
verbose = "verbose",
/** @description Debug or trace details aimed at developers. */
debug = "debug",
/** @description trace details aimed at developers */
trace = "trace",
/** @description Extremely chatty or playful log entries. */
silly = "silly"
}
/**
* @description The numeric values that are associated with log levels.
* @summary This provides a numeric representation of log levels for comparison and filtering.
* @typedef {object} NumericLogLevelsShape
* @property {number} benchmark - The numeric value for the benchmark level (0).
* @property {number} error - The numeric value for the error level (3).
* @property {number} warn - The numeric value for the warn level (6).
* @property {number} info - The numeric value for the info level (9).
* @property {number} verbose - The numeric value for the verbose level (12).
* @property {number} debug - The numeric value for the debug level (15).
* @property {number} trace - The numeric value for the trace level (18).
* @property {number} silly - The numeric value for the silly level (21).
* @memberOf module:Logging
*/
/**
* @description The numeric values that are associated with log levels.
* @summary This provides a numeric representation of log levels for comparison and filtering.
* @const {NumericLogLevelsShape} NumericLogLevels
* @memberOf module:Logging
*/
export declare const NumericLogLevels: {
benchmark: number;
error: number;
warn: number;
info: number;
verbose: number;
debug: number;
trace: number;
silly: number;
};
/**
* @description An enum for logging output modes.
* @summary Defines the different output formats for log messages.
* @enum {string}
* @readonly
* @memberOf module:Logging
*/
export declare enum LoggingMode {
/** Raw text format for human readability */
RAW = "raw",
/** JSON format for machine parsing */
JSON = "json"
}
/**
* @description The default theme for styling log output.
* @summary Defines the default color and style settings for various components of log messages.
* @const {Theme} DefaultTheme
* @memberOf module:Logging
*/
export declare const DefaultTheme: Theme;
/**
* @description The default configuration for logging.
* @summary Defines the default settings for the logging system, including verbosity, log level, styling, and timestamp format.
* @const {LoggingConfig} DefaultLoggingConfig
* @memberOf module:Logging
*/
export declare const DefaultLoggingConfig: LoggingConfig;
import { LogLevel } from "./constants";
export type ArgFormatFunction = (...args: any[]) => string;
export type ReturnFormatFunction = (e?: Error, result?: any) => string;
/**
* @description A method decorator for logging function calls.
* @summary This decorator wraps a class method to automatically log entry, exit, timing, and optional custom messages at a configurable {@link LogLevel}.
* @param {LogLevel} [level=LogLevel.info] - The log level to apply to the generated log statements.
* @param {number} [verbosity=0] - The verbosity threshold that is required for the entry log to appear.
* @param {ArgFormatFunction} [entryMessage] - A formatter that is invoked with the original method arguments to describe the invocation.
* @param {ReturnFormatFunction} [exitMessage] - An optional formatter that describes the outcome or failure of the call.
* @return {function(any, any, PropertyDescriptor): void} A method decorator proxy that injects logging behavior.
* @function log
* @mermaid
* sequenceDiagram
* participant Client
* participant Decorator as log decorator
* participant Method as Original Method
* participant Logger as Logging instance
*
* Client->>Decorator: call decorated method
* Decorator->>Logger: log method call
* Decorator->>Method: call original method
* alt result is Promise
* Method-->>Decorator: return Promise
* Decorator->>Decorator: attach then handler
* Note over Decorator: Promise resolves
* Decorator->>Logger: log benchmark (if enabled)
* Decorator-->>Client: return result
* else result is not Promise
* Method-->>Decorator: return result
* Decorator->>Logger: log benchmark (if enabled)
* Decorator-->>Client: return result
* end
* @category Method Decorators
*/
export declare function log(level?: LogLevel, verbosity?: number, entryMessage?: ArgFormatFunction, exitMessage?: ReturnFormatFunction): (target: any, propertyKey?: any, descriptor?: any) => any;
/**
* @description A method decorator that records execution time at the benchmark level.
* @summary This decorator wraps the target method to emit {@link Logger.benchmark} entries that capture completion time or failure latency.
* @return {function(any, any, PropertyDescriptor): void} A method decorator proxy that benchmarks the original implementation.
* @function benchmark
* @mermaid
* sequenceDiagram
* participant Caller
* participant Decorator as benchmark
* participant Method as Original Method
* Caller->>Decorator: invoke()
* Decorator->>Method: Reflect.apply(...)
* alt Promise result
* Method-->>Decorator: Promise
* Decorator->>Decorator: attach then()
* Decorator->>Decorator: log completion duration
* else Synchronous result
* Method-->>Decorator: value
* Decorator->>Decorator: log completion duration
* end
* Decorator-->>Caller: return result
* @category Method Decorators
*/
export declare function benchmark(): (target: any, propertyKey?: any, descriptor?: any) => any;
/**
* @description A method decorator for logging function calls with the debug level.
* @summary This is a convenience wrapper around {@link log} that logs using `LogLevel.debug`.
* @return {function(any, any, PropertyDescriptor): void} A debug-level logging decorator.
* @function debug
* @category Method Decorators
*/
export declare function debug(): (target: any, propertyKey?: any, descriptor?: any) => any;
/**
* @description A method decorator for logging function calls with the info level.
* @summary This is a convenience wrapper around {@link log} that logs using `LogLevel.info`.
* @return {function(any, any, PropertyDescriptor): void} An info-level logging decorator.
* @function info
* @category Method Decorators
*/
export declare function info(): (target: any, propertyKey?: any, descriptor?: any) => any;
/**
* @description A method decorator for logging function calls with the silly level.
* @summary This is a convenience wrapper around {@link log} that logs using `LogLevel.silly`.
* @return {function(any, any, PropertyDescriptor): void} A silly-level logging decorator.
* @function silly
* @category Method Decorators
*/
export declare function silly(): (target: any, propertyKey?: any, descriptor?: any) => any;
/**
* @description A method decorator for logging function calls with the trace level.
* @summary This is a convenience wrapper around {@link log} that logs using `LogLevel.trace`.
* @return {function(any, any, PropertyDescriptor): void} A trace-level logging decorator.
* @function trace
* @category Method Decorators
*/
export declare function trace(): (target: any, propertyKey?: any, descriptor?: any) => any;
/**
* @description A method decorator for logging function calls with the verbose level.
* @summary This is a convenience wrapper around {@link log} that logs using `LogLevel.verbose` with a configurable verbosity.
* @param {(number|boolean)} [verbosity=0] - The verbosity level for log filtering or a flag to enable benchmarking.
* @return {function(any, any, PropertyDescriptor): void} A verbose logging decorator.
* @function verbose
* @category Method Decorators
*/
export declare function verbose(verbosity?: number | boolean): (target: any, propertyKey?: any, descriptor?: any) => any;
/**
* @description Creates a decorator that makes a method non-configurable.
* @summary This decorator prevents overriding by marking the method descriptor as non-configurable. It will throw an error if it is applied to non-method targets.
* @return {function(object, any, PropertyDescriptor): (PropertyDescriptor|undefined)} A decorator that hardens the method descriptor.
* @function final
* @category Method Decorators
*/
export declare function final(): (target: object, propertyKey?: any, descriptor?: any) => any;
import { ObjectAccumulator } from "typed-object-accumulator";
/**
* @description A factory type for creating Environment instances.
* @summary This describes factories that construct {@link Environment} derivatives with custom initialization.
* @template T - The type of object the Environment will accumulate.
* @template E - The specific Environment type to be created, extending Environment<T>.
* @typedef {function(unknown[]): E} EnvironmentFactory
* @memberOf module:Logging
*/
export type EnvironmentFactory<T extends object, E extends Environment<T>> = (...args: unknown[]) => E;
export type EnvironmentInstance<T extends object = any> = Environment<T> & T & {
orThrow(): EnvironmentInstance<any>;
};
export type AccumulatedEnvironment<T extends object = any> = EnvironmentInstance<T> & ObjectAccumulator<T> & {
accumulate<V extends object>(value: V): AccumulatedEnvironment<T & V>;
};
export declare class Environment<T extends object> extends ObjectAccumulator<T> {
/**
* @static
* @protected
* @description A factory function for creating Environment instances.
* @summary Defines how new instances of the Environment class should be created.
* @return {Environment<any>} A new instance of the Environment class.
*/
protected static factory: EnvironmentFactory<any, any>;
/**
* @static
* @private
* @description The singleton instance of the Environment class.
* @type {Environment<any>}
*/
private static _instance;
protected constructor();
/**
* @description Retrieves a value from the runtime environment.
* @summary This method handles browser and Node.js environments by normalizing keys and parsing values.
* @param {string} k - The key to resolve from the environment.
* @return {unknown} The value that is resolved from the environment, or `undefined` if it is absent.
*/
protected fromEnv(k: string): unknown;
/**
* @description Converts stringified environment values into native types.
* @summary This method interprets booleans and numbers, while leaving other types unchanged.
* @param {unknown} val - The raw value that is retrieved from the environment.
* @return {unknown} The parsed value, converted to a boolean or number, or left as-is.
*/
protected parseEnvValue(val: unknown): unknown;
private static parseRuntimeValue;
/**
* @description Expands an object into the environment.
* @summary This method defines lazy properties that first consult runtime variables before falling back to seeded values.
* @template V - The type of the object being expanded.
* @param {V} value - The object to expose through environment getters and setters.
* @return {void}
*/
protected expand<V extends object>(value: V): void;
/**
* @description Returns a proxy that enforces required environment variables.
* @summary Accessing a property that resolves to `undefined` or an empty string when declared in the model will throw an error.
* @return {EnvironmentInstance<any>} A proxy of the environment that enforces required variables.
*/
orThrow(): EnvironmentInstance<any>;
/**
* @protected
* @static
* @description Retrieves or creates the singleton instance of the Environment class.
* @summary This method ensures that only one {@link Environment} instance is created, and wraps it in a proxy to compose ENV keys on demand.
* @template E
* @param {...unknown[]} args - Arguments that are forwarded to the factory when instantiating the singleton.
* @return {E} The singleton environment instance.
*/
protected static instance<E extends Environment<any>>(...args: unknown[]): E;
accumulate<V extends object>(value: V): AccumulatedEnvironment<T & V>;
/**
* @static
* @description Accumulates the given value into the environment.
* @summary This method adds new properties and hides raw descriptors to avoid leaking enumeration semantics.
* @template V
* @param {V} value - The object to merge into the environment.
* @return {AccumulatedEnvironment<any>} The updated environment reference.
*/
static accumulate<V extends object>(value: V): AccumulatedEnvironment<any>;
/**
* @description Retrieves a value using a dot-path key from the accumulated environment.
* @summary This method delegates to the singleton instance to access stored configuration.
* @param {string} key - The key to resolve from the environment store.
* @return {unknown} The stored value that corresponds to the provided key.
*/
static get(key: string): any;
private static formatEnvSegment;
private static buildEnvKey;
private static buildRawKey;
private static readRuntimeForPath;
/**
* @description Builds a proxy that composes environment keys for nested properties.
* @summary This allows chained property access to emit uppercase ENV identifiers, while honoring existing runtime overrides.
* @param {any} current - The seed model segment to use when projecting nested structures.
* @param {string[]} path - The accumulated path segments that lead to the proxy.
* @return {any} A proxy that resolves environment values or composes additional proxies for deeper paths.
*/
private static buildEnvProxy;
/**
* @static
* @description Retrieves the keys of the environment, optionally converting them to ENV format.
* @summary This method gets all keys in the environment, with an option to format them for environment variables.
* @param {boolean} [toEnv=true] - Whether to convert the keys to ENV format.
* @return {string[]} An array of keys from the environment.
*/
static keys(toEnv?: boolean): string[];
private static mergeModel;
private static readRuntimeEnv;
private static missingEnvError;
}
/**
* @description A singleton environment instance that is seeded with the default logging configuration.
* @summary This constant combines {@link DefaultLoggingConfig} with runtime environment variables to provide consistent logging defaults across platforms.
* @const {AccumulatedEnvironment<any>} LoggedEnvironment
* @memberOf module:Logging
*/
export declare const LoggedEnvironment: any;
/**
* @description Exports for the filters module.
* @summary This file exports all the necessary components for the filters functionality, including LogFilter and PatternFilter.
* @module logging/filters
*/
export * from "./LogFilter";
export * from "./PatternFilter";
import { Logger, LoggingConfig, LoggingFilter } from "../types";
import { LoggedClass } from "../LoggedClass";
/**
* @description A base class for message filters that can be plugged into the logging pipeline.
* @summary This class extends {@link LoggedClass} to supply a scoped logger, and defines the contract that is required by {@link LoggingFilter} implementers that transform or drop log messages before emission.
* @class LogFilter
* @example
* class RedactSecretsFilter extends LogFilter {
* filter(config: LoggingConfig, message: string): string {
* return message.replace(/secret/gi, "***");
* }
* }
*
* const filter = new RedactSecretsFilter();
* filter.filter({ ...DefaultLoggingConfig, verbose: 0 }, "secret token");
* @mermaid
* sequenceDiagram
* participant Logger
* participant Filter as LogFilter
* participant Impl as ConcreteFilter
* participant Output
* Logger->>Filter: filter(config, message, context)
* Filter->>Impl: delegate to subclass implementation
* Impl-->>Filter: transformed message
* Filter-->>Output: return filtered message
*/
export declare abstract class LogFilter extends LoggedClass implements LoggingFilter {
/**
* @description A scoped logger that excludes other filters from the chain.
* @summary This method returns a child logger that is dedicated to the filter, which prevents recursive filter invocation when emitting diagnostic messages.
* @return {Logger} A context-aware logger for the filter instance.
*/
get log(): Logger;
/**
* @description Transforms or suppresses a log message.
* @summary This method inspects the provided message and context to produce the value that will be forwarded to subsequent filters or emitters.
* @param {LoggingConfig} config - The active logging configuration.
* @param {string} message - The original log message payload.
* @param {string[]} context - The context values that are attached to the message.
* @return {string} The filtered message to pass to downstream processing.
*/
abstract filter(config: LoggingConfig, message: string, context: string[]): string;
}
import { LogFilter } from "./LogFilter";
import { LoggingConfig } from "../types";
/**
* @description A replacement callback that is used to transform RegExp matches.
* @summary This function receives the matched substring and additional capture arguments, and returns the replacement text that will be injected into the log message.
* @typedef {function(string, ...any): string} ReplacementFunction
* @memberOf module:Logging
*/
export type ReplacementFunction = (substring: string, ...args: any[]) => string;
/**
* @description A filter that patches log messages using regular expressions.
* @summary This class applies a configured {@link RegExp} and replacement strategy to redact, mask, or restructure log payloads before they are emitted.
* @param {RegExp} regexp - The expression to use for detecting sensitive or formatted text.
* @param {(string|ReplacementFunction)} replacement - The replacement string or a callback that is invoked for each match.
* @class PatternFilter
* @example
* const filter = new PatternFilter(/token=[^&]+/g, "token=***");
* const sanitized = filter.filter(config, "token=123&user=tom", []);
* // sanitized === "token=***&user=tom"
* @mermaid
* sequenceDiagram
* participant Logger
* participant Filter as PatternFilter
* participant RegExp
* Logger->>Filter: filter(config, message, context)
* Filter->>RegExp: execute match()
* alt match found
* RegExp-->>Filter: captures
* Filter->>RegExp: replace(message, replacement)
* RegExp-->>Filter: transformed message
* else no match
* RegExp-->>Filter: null
* end
* Filter-->>Logger: sanitized message
*/
export declare class PatternFilter extends LogFilter {
protected readonly regexp: RegExp;
protected readonly replacement: string | ReplacementFunction;
constructor(regexp: RegExp, replacement: string | ReplacementFunction);
/**
* @description Ensures deterministic RegExp matching.
* @summary This method runs the configured expression, then resets its state so that repeated invocations behave consistently.
* @param {string} message - The message to test for matches.
* @return {(RegExpExecArray|null)} The match result, or null if no match is found.
*/
protected match(message: string): RegExpExecArray | null;
/**
* @description Applies the replacement strategy to the incoming message.
* @summary This method executes {@link PatternFilter.match} and, when a match is found, replaces every occurrence using the configured replacement handler.
* @param {LoggingConfig} config - The active logging configuration (unused, but part of the filter contract).
* @param {string} message - The message to be sanitized.
* @param {string[]} context - The context entries that are associated with the log event.
* @return {string} The sanitized log message.
*/
filter(config: LoggingConfig, message: string, context: string[]): string;
}
/**
* @module Logging
* @description A comprehensive and versatile logging toolkit for both browser and Node.js environments.
* @summary This module provides a complete logging solution, exposing {@link Logging} and {@link MiniLogger} for runtime logging. It also includes decorators like {@link log} for method instrumentation, and various utilities such as {@link PatternFilter}, {@link StopWatch}, and {@link LoggedEnvironment} to help build configurable and theme-aware log pipelines.
*/
export * from "./filters";
export * from "./constants";
export * from "./decorators";
export * from "./environment";
export * from "./LoggedClass";
export * from "./logging";
export * from "./logParameters";
export * from "./text";
export * from "./time";
export * from "./types";
export * from "./web";
export * from "./utils";
export * from "styled-string-builder";
/**
* @description Current package version string.
* @summary Stores the package version for diagnostics and compatibility checks.
* @const VERSION
* @type {string}
* @memberOf module:Logging
*/
export declare const VERSION: string;
/**
* @description Current package version string.
* @summary Stores the package version for diagnostics and compatibility checks.
* @const PACKAGE_NAME
* @type {string}
* @memberOf module:Logging
*/
export declare const PACKAGE_NAME: string;
import { Logger } from "./types";
/**
* @description A base class that provides a ready-to-use logger instance.
* @summary This class supplies inheriting classes with a lazily created, context-aware {@link Logger} via the protected `log` getter. This promotes consistent, structured logging without the need for manual wiring.
* @class LoggedClass
* @example
* class UserService extends LoggedClass {
* create(user: User) {
* this.log.info(`Creating user ${user.id}`);
* }
* }
*
* const svc = new UserService();
* svc.create({ id: "42" });
* @mermaid
* sequenceDiagram
* participant Client
* participant Instance as Subclass Instance
* participant Getter as LoggedClass.log
* participant Logging as Logging
* participant Logger as Logger
*
* Client->>Instance: call someMethod()
* Instance->>Getter: access this.log
* Getter->>Logging: Logging.for(this)
* Logging-->>Getter: return Logger
* Getter-->>Instance: return Logger
* Instance->>Logger: info/debug/error(...)
*/
export declare abstract class LoggedClass {
private _log?;
/**
* @description Lazily provides a context-aware logger for the current instance.
* @summary This method calls {@link Logging.for} with the subclass instance to obtain a logger whose context matches the subclass name.
* @return {Logger} A logger that is bound to the subclass context.
*/
protected get log(): Logger;
protected constructor();
}
import { LoggerFactory, LoggingConfig, LoggingContext, LoggingFilter, LogMeta, StringLike, Theme, Logger } from "./types";
import { LogLevel } from "./constants";
import { LogParameterDescriptor } from "./logParameters";
import { LoggedEnvironment } from "./environment";
export declare const ROOT_CONTEXT_SYMBOL: unique symbol;
/**
* @description A minimal logger implementation.
* @summary MiniLogger is a lightweight logging class that implements the Logger interface. It provides basic logging functionality with support for different log levels, verbosity, context-aware logging, and customizable formatting.
* @param {string} [context] - The context (typically class name) this logger is associated with.
* @param {Partial<LoggingConfig>} [conf] - Optional configuration to override global settings.
* @param {string[]} [baseContext=[]] - The base context for the logger.
* @class MiniLogger
* @example
* // Create a new logger for a class
* const logger = new MiniLogger('MyClass');
*
* // Log messages at different levels
* logger.info('This is an info message');
* logger.debug('This is a debug message');
* logger.error('Something went wrong');
*
* // Create a child logger for a specific method
* const methodLogger = logger.for('myMethod');
* methodLogger.verbose('Detailed information', 2);
*
* // Log with custom configuration
* logger.for('specialMethod', { style: true }).info('Styled message');
*/
export declare class MiniLogger implements Logger {
protected conf?: Partial<LoggingConfig> | undefined;
protected context: string[];
protected baseContext: string[];
constructor(context?: string, conf?: Partial<LoggingConfig> | undefined, baseContext?: string[]);
protected config<K extends keyof LoggingConfig>(key: K): LoggingConfig[K];
for(config: Partial<LoggingConfig>): this;
for(method: string | ((...args: any[]) => any) | {
new (...args: any[]): any;
} | object): this;
for(method: string | ((...args: any[]) => any) | {
new (...args: any[]): any;
} | object | Partial<LoggingConfig>, config: Partial<LoggingConfig>, ...args: any[]): this;
protected getConfigSnapshot(): LoggingConfig;
protected getContextSegments(): string[];
protected resolveFilters(config: LoggingConfig): LoggingFilter[];
protected applyFilters(message: string, context: string[], config: LoggingConfig): string;
/**
* @description Creates a formatted log string.
* @summary Generates a log string with timestamp, colored log level, context, and message.
* @param {LogLevel} level - The log level for this message.
* @param {StringLike | Error} message - The message to log or an Error object.
* @param {Error} [error] - Optional error to extract stack trace to include in the log.
* @return {string} A formatted log string with all components.
*/
protected createLog(level: LogLevel, message: StringLike | Error, error?: Error, meta?: LogMeta): string;
private formatMeta;
protected normalizePatternSpacing(value: string): string;
/**
* @description Logs a message with the specified log level.
* @summary Checks if the message should be logged based on the current log level, then uses the appropriate console method to output the formatted log.
* @param {LogLevel} level - The log level of the message.
* @param {StringLike | Error} msg - The message to be logged or an Error object.
* @param {Error} [error] - Optional stack trace to include in the log.
* @return {void}
*/
protected log(level: LogLevel, msg: StringLike | Error, error?: Error, meta?: LogMeta): void;
/**
* @description Logs a message at the benchmark level.
* @summary Logs a message at the benchmark level if the current verbosity setting allows it.
* @param {StringLike} msg - The message to be logged.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
benchmark(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs a message at the silly level.
* @summary Logs a message at the silly level if the current verbosity setting allows it.
* @param {StringLike} msg - The message to be logged.
* @param {number} [verbosity=0] - The verbosity level of the message.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
silly(msg: StringLike, verbosityOrMeta?: number | LogMeta, meta?: LogMeta): void;
/**
* @description Logs a message at the verbose level.
* @summary Logs a message at the verbose level if the current verbosity setting allows it.
* @param {StringLike} msg - The message to be logged.
* @param {number} [verbosity=0] - The verbosity level of the message.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
verbose(msg: StringLike, verbosityOrMeta?: number | LogMeta, meta?: LogMeta): void;
/**
* @description Logs a message at the info level.
* @summary Logs a message at the info level for general application information.
* @param {StringLike} msg - The message to be logged.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
info(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs a message at the debug level.
* @summary Logs a message at the debug level for detailed troubleshooting information.
* @param {StringLike} msg - The message to be logged.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
debug(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs a message at the error level.
* @summary Logs a message at the error level for errors and exceptions.
* @param {StringLike | Error} msg - The message to be logged or an Error object.
* @param {Error|object} [e] - Optional error or metadata to include in the log.
* @param {object} [meta] - Optional metadata to include with the entry when an error is supplied.
* @return {void}
*/
error(msg: StringLike | Error, e?: Error | LogMeta, meta?: LogMeta): void;
/**
* @description Logs a message at the warning level.
* @summary Logs a message at the warning level for potential issues.
* @param {StringLike} msg - The message to be logged.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
warn(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs a message at the trace level.
* @summary Logs a message at the trace level for tracing code execution.
* @param {StringLike} msg - The message to be logged.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
trace(msg: StringLike, meta?: LogMeta): void;
/**
* @description Updates the logger configuration.
* @summary Merges the provided configuration with the existing configuration.
* @param {Partial<LoggingConfig>} config - The configuration options to apply.
* @return {void}
*/
setConfig(config: Partial<LoggingConfig>): void;
get root(): string[];
/**
* @description Clears any contextual overrides applied by `for`.
* @summary Returns the same logger instance so more contexts can be chained afterwards.
* @return {this} The same logger instance.
*/
clear(): this;
}
/**
* @description A static class for managing logging operations.
* @summary The Logging class provides a centralized logging mechanism with support for different log levels, verbosity, and styling. It uses a singleton pattern to maintain a global logger instance and allows creating specific loggers for different classes and methods.
* @class Logging
* @example
* // Set global configuration
* Logging.setConfig({ level: LogLevel.debug, style: true });
*
* // Get a logger for a specific class
* const logger = Logging.for('MyClass');
*
* // Log messages at different levels
* logger.info('Application started');
* logger.debug('Processing data...');
*
* // Log with context
* const methodLogger = Logging.for('MyClass.myMethod');
* methodLogger.verbose('Detailed operation information', 1);
*
* // Log errors
* try {
* // some operation
* } catch (error) {
* logger.error(error);
* }
* @mermaid
* classDiagram
* class Logger {
* <<interface>>
* +for(method, config, ...args)
* +silly(msg, verbosity)
* +verbose(msg, verbosity)
* +info(msg)
* +debug(msg)
* +error(msg)
* +setConfig(config)
* }
*
* class Logging {
* -global: Logger
* -_factory: LoggerFactory
* -_config: LoggingConfig
* +setFactory(factory)
* +setConfig(config)
* +getConfig()
* +get()
* +verbose(msg, verbosity)
* +info(msg)
* +debug(msg)
* +silly(msg)
* +error(msg)
* +for(object, config, ...args)
* +because(reason, id)
* +theme(text, type, loggerLevel, template)
* }
*
* class MiniLogger {
* +constructor(context, conf?)
* }
*
* Logging ..> Logger : creates
* Logging ..> MiniLogger : creates by default
*/
export declare class Logging {
/**
* @description The global logger instance.
* @summary A singleton instance of Logger used for global logging.
*/
private static global?;
/**
* @description Factory function for creating logger instances.
* @summary A function that creates new Logger instances. By default, it creates a MiniLogger.
*/
private static _factory;
private static _config;
private constructor();
/**
* @description Sets the factory function for creating logger instances.
* @summary Allows customizing how logger instances are created.
* @param {LoggerFactory} factory - The factory function to use for creating loggers.
* @return {void}
*/
static setFactory(factory: LoggerFactory): void;
/**
* @description Updates the global logging configuration.
* @summary Allows updating the global logging configuration with new settings.
* @param {Partial<LoggingConfig>} config - The configuration options to apply.
* @return {void}
*/
static setConfig(config: Partial<LoggingConfig>): void;
/**
* @description Gets a copy of the current global logging configuration.
* @summary Returns a copy of the current global logging configuration.
* @return {LoggingConfig} A copy of the current configuration.
*/
static getConfig(): typeof LoggedEnvironment;
/**
* @description Retrieves or creates the global logger instance.
* @summary Returns the existing global logger or creates a new one if it doesn't exist.
* @return {Logger} The global Logger instance.
*/
static get(): Logger;
/**
* @description Logs a verbose message.
* @summary Delegates the verbose logging to the global logger instance.
* @param {StringLike} msg - The message to be logged.
* @param {number|object} [verbosity] - The verbosity level or metadata object.
* @param {object} [meta] - Optional metadata applied when a verbosity level is provided.
* @return {void}
*/
static verbose(msg: StringLike, verbosityOrMeta?: number | LogMeta, meta?: LogMeta): void;
/**
* @description Logs an info message.
* @summary Delegates the info logging to the global logger instance.
* @param {StringLike} msg - The message to be logged.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
static info(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs a trace message.
* @summary Delegates the trace logging to the global logger instance.
* @param {StringLike} msg - The message to be logged.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
static trace(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs a debug message.
* @summary Delegates the debug logging to the global logger instance.
* @param {StringLike} msg - The message to be logged.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
static debug(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs a benchmark message.
* @summary Delegates the benchmark logging to the global logger instance.
* @param {StringLike} msg - The message to be logged.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
static benchmark(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs a silly message.
* @summary Delegates the silly logging to the global logger instance.
* @param {StringLike} msg - The message to be logged.
* @param {number|object} [verbosity] - The verbosity level or metadata object.
* @param {object} [meta] - Optional metadata applied when a verbosity level is provided.
* @return {void}
*/
static silly(msg: StringLike, verbosityOrMeta?: number | LogMeta, meta?: LogMeta): void;
/**
* @description Logs a warning message.
* @summary Delegates the warning logging to the global logger instance.
* @param {StringLike} msg - The message to be logged.
* @param {object} [meta] - Optional metadata to include with the entry.
* @return {void}
*/
static warn(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs an error message.
* @summary Delegates the error logging to the global logger instance.
* @param {StringLike | Error} msg - The message to be logged.
* @param {Error|object} [e] - Optional error or metadata to include in the log.
* @param {object} [meta] - Optional metadata to include with the entry when an error is supplied.
* @return {void}
*/
static error(msg: StringLike | Error, e?: Error | LogMeta, meta?: LogMeta): void;
/**
* @description Creates a logger for a specific object or context.
* @summary Creates a new logger instance for the given object or context using the factory function.
* @param {LoggingContext} object - The object, class, or context to create a logger for.
* @param {Partial<LoggingConfig>} [config] - Optional configuration to override global settings.
* @param {...any} args - Additional arguments to pass to the logger factory.
* @return {Logger} A new logger instance for the specified object or context.
*/
static for(object: LoggingContext, config?: Partial<LoggingConfig>, ...args: any[]): Logger;
/**
* @description Creates a logger for a specific reason or correlation context.
* @summary Utility to quickly create a logger labeled with a free-form reason and optional identifier so that ad-hoc operations can be traced without tying the logger to a class or method name.
* @param {string} reason - A textual reason or context label for this logger instance.
* @param {string} [id] - Optional identifier to help correlate related log entries.
* @return {Logger} A new logger instance labeled with the provided reason and id.
*/
static because(reason: string, id?: string): Logger;
private static baseContext;
private static attachRootContext;
private static ensureRoot;
/**
* @description Applies theme styling to text.
* @summary Applies styling (colors, formatting) to text based on the theme configuration.
* @param {string} text - The text to style.
* @param type - The type of element to style (e.g., "class", "message", "logLevel").
* @param {LogLevel} loggerLevel - The log level to use for styling.
* @param {Theme} [template=DefaultTheme] - The theme to use for styling.
* @return {string} The styled text.
* @mermaid
* sequenceDiagram
* participant Caller
* participant Theme as Logging.theme
* participant Apply as apply function
* participant Style as styled-string-builder
*
* Caller->>Theme: theme(text, type, loggerLevel)
* Theme->>Theme: Check if styling is enabled
* alt styling disabled
* Theme-->>Caller: return original text
* else styling enabled
* Theme->>Theme: Get theme for type
* alt theme not found
* Theme-->>Caller: return original text
* else theme found
* Theme->>Theme: Determine actual theme based on log level
* Theme->>Apply: Apply each style property
* Apply->>Style: Apply colors and formatting
* Style-->>Apply: Return styled text
* Apply-->>Theme: Return styled text
* Theme-->>Caller: Return final styled text
* end
* end
*/
static theme(text: string, type: keyof Theme | keyof LogLevel, loggerLevel: LogLevel, template?: Theme): string;
static register(descriptor: LogParameterDescriptor): import("./logParameters").LogParameterRegistry;
static unregister(key: string): import("./logParameters").LogParameterRegistry;
}
import { LogLevel } from "./constants";
import { LogMeta, LoggingConfig } from "./types";
export type LogParameterPayload = {
config: LoggingConfig;
level: LogLevel;
context: string[];
timestamp?: string;
app?: string;
separator?: string;
correlationId?: string;
rawMessage: string;
filteredMessage: string;
meta?: LogMeta;
metaString?: string;
stack?: string;
stackLabel?: string;
applyTheme(value: string, type: string): string;
};
export interface LogParameterDescriptor {
key: string;
render(payload: LogParameterPayload): string | undefined;
style?(rendered: string, payload: LogParameterPayload): string;
shouldInclude?(payload: LogParameterPayload): boolean;
}
export interface LogPatternLiteralSegment {
type: "literal";
value: string;
}
export interface LogPatternParameterSegment {
type: "parameter";
key: string;
}
export interface LogPatternOptionalSegment {
type: "optional";
prefix: string;
suffix: string;
children: LogPatternSegment[];
}
export type LogPatternSegment = LogPatternLiteralSegment | LogPatternParameterSegment | LogPatternOptionalSegment;
export type LogPatternDefinition = {
pattern: string;
segments: LogPatternSegment[];
keys: string[];
includesMeta: boolean;
};
export declare class LogParameterRegistry {
private readonly descriptors;
register(descriptor: LogParameterDescriptor): this;
unregister(key: string): this;
get(key: string): LogParameterDescriptor | undefined;
render(payload: LogParameterPayload, keys: string[]): Record<string, string>;
keys(): string[];
}
export declare function compileLogPattern(pattern: string): LogPatternDefinition;
export declare function renderPattern(definition: LogPatternDefinition, rendered: Record<string, string>): string;
export declare const logParameterRegistry: LogParameterRegistry;
/**
* @module Pino
* @description This module provides an adapter for the Pino logger.
* @summary This module exports the {@link PinoLogger} class.
* @memberOf module:Logging
*/
export * from "./pino";
import { Logger as PinoBaseLogger } from "pino";
import { MiniLogger } from "../logging";
import { Logger, LoggerFactory, LogMeta, LoggingConfig, StringLike } from "../types";
import { LogLevel } from "../constants";
/**
* @description A logger that is powered by the Pino logging library.
* @summary This class extends {@link MiniLogger} and uses Pino as its underlying logging engine.
* @param {string} [context] - The context (typically the class name) that this logger is associated with.
* @param {Partial<LoggingConfig>} [conf] - Optional configuration to override global settings.
* @param {PinoBaseLogger} [driver] - An optional, pre-existing Pino logger instance to use.
* @class PinoLogger
*/
export declare class PinoLogger extends MiniLogger implements Logger {
protected pino: PinoBaseLogger;
constructor(context?: string, conf?: Partial<LoggingConfig>, driver?: PinoBaseLogger);
protected log(level: LogLevel, msg: StringLike | Error, error?: Error, meta?: LogMeta): void;
fatal(msg: StringLike | Error, error?: Error, meta?: LogMeta): void;
child(bindings?: Record<string, unknown>, options?: Record<string, unknown>): PinoLogger;
flush(): void | Promise<void>;
get level(): string | undefined;
set level(value: string | undefined);
}
/**
* @description A factory for creating {@link PinoLogger} instances.
* @summary This factory function creates a new {@link PinoLogger} instance, and can optionally accept a pre-existing Pino logger instance.
* @const {LoggerFactory} PinoFactory
* @memberOf module:Logging
*/
export declare const PinoFactory: LoggerFactory;
/**
* @description Pads the end of a string with a specified character.
* @summary This function extends the input string to a specified length by adding a padding character to the end. If the input string is already longer than the specified length, it is returned unchanged.
* @param {string} str - The input string to be padded.
* @param {number} length - The desired total length of the resulting string.
* @param {string} [char=" "] - The character to use for padding.
* @return {string} The padded string.
* @throws {Error} If the padding character is not exactly one character long.
* @function padEnd
* @memberOf module:Logging
*/
export declare function padEnd(str: string, length: number, char?: string): string;
/**
* @description Replaces placeholders in a string with the provided values.
* @summary This function interpolates a string by replacing placeholders of the form `${variableName}` with the corresponding values from the provided object. If a placeholder does not have a corresponding value, it is left unchanged in the string.
* @param {string} input - The input string containing the placeholders to be replaced.
* @param {Record<string, (number|string)>} values - An object containing key-value pairs for the replacement.
* @param {string} [prefix="${"] - The prefix for the placeholders.
* @param {string} [suffix="}"] - The suffix for the placeholders.
* @param {string} [flags="g"] - The regular expression flags to use.
* @return {string} The interpolated string with the placeholders replaced by their corresponding values.
* @function patchPlaceholders
* @mermaid
* sequenceDiagram
* participant Caller
* participant patchString
* participant String.replace
* Caller->>patchString: Call with input and values
* patchString->>String.replace: Call with regex and replacement function
* String.replace->>patchString: Return replaced string
* patchString-->>Caller: Return patched string
* @memberOf module:Logging
*/
export declare function patchPlaceholders(input: string, values: Record<string, number | string>, prefix?: string, suffix?: string, flags?: string): string;
/**
* @description Replaces occurrences of keys with their corresponding values in a string.
* @summary This function iterates through a set of key-value pairs and replaces all occurrences of each key in the input string with its corresponding value. It supports regular expression flags for customized replacement.
* @param {string} input - The input string in which the replacements will be made.
* @param {Record<string, (number|string)>} values - An object containing key-value pairs for the replacement.
* @param {string} [flags="g"] - The regular expression flags to control the replacement behavior.
* @return {string} The string with all the specified replacements applied.
* @function patchString
* @memberOf module:Logging
*/
export declare function patchString(input: string, values: Record<string, number | string>, flags?: string): string;
/**
* @description Converts a string to camelCase.
* @summary This function transforms the input string into camelCase format, where words are joined without spaces and each word after the first starts with a capital letter.
* @param {string} text - The input string to be converted.
* @return {string} The input string converted to camelCase.
* @function toCamelCase
* @memberOf module:Logging
*/
export declare function toCamelCase(text: string): string;
/**
* @description Converts a string to ENVIRONMENT_VARIABLE format.
* @summary This function transforms the input string into uppercase with words separated by underscores, which is a format that is typically used for environment variable names.
* @param {string} text - The input string to be converted.
* @return {string} The input string converted to ENVIRONMENT_VARIABLE format.
* @function toENVFormat
* @memberOf module:Logging
*/
export declare function toENVFormat(text: string): string;
/**
* @description Converts a string to snake_case.
* @summary This function transforms the input string into lowercase with words separated by underscores.
* @param {string} text - The input string to be converted.
* @return {string} The input string converted to snake_case.
* @function toSnakeCase
* @memberOf module:Logging
*/
export declare function toSnakeCase(text: string): string;
/**
* @description Converts a string to kebab-case.
* @summary This function transforms the input string into lowercase with words separated by hyphens.
* @param {string} text - The input string to be converted.
* @return {string} The input string converted to kebab-case.
* @function toKebabCase
* @memberOf module:Logging
*/
export declare function toKebabCase(text: string): string;
/**
* @description Converts a string to PascalCase.
* @summary This function transforms the input string into PascalCase format, where words are joined without spaces and each word starts with a capital letter.
* @param {string} text - The input string to be converted.
* @return {string} The input string converted to PascalCase.
* @function toPascalCase
* @memberOf module:Logging
*/
export declare function toPascalCase(text: string): string;
/**
* @description Escapes special characters in a string for use in a regular expression.
* @summary This function adds backslashes before characters that have a special meaning in regular expressions, which allows the string to be used as a literal match in a RegExp.
* @param {string} string - The string to escape for regular expression use.
* @return {string} The escaped string that is safe for use in regular expressions.
* @function escapeRegExp
* @memberOf module:Logging
*/
export declare function escapeRegExp(string: string): string;
/**
* @description A utility function that provides string formatting functionality that is similar to C#'s string.format.
* @summary This function replaces placeholders in a string with the provided arguments.
* @param {string} string - The string to format.
* @param {...(string|number|Record<string, any>)} args - The arguments to use for formatting.
* @return {string} The formatted string.
* @function sf
* @memberOf module:Logging
*/
export declare function sf(string: string, ...args: (string | number | Record<string, any>)[]): string;
/**
* @description A utility function that provides string formatting functionality that is similar to C#'s string.format.
* @summary This function is deprecated. Use {@link sf} instead.
* @see sf
* @deprecated
* @function stringFormat
* @memberOf module:Logging
*/
export declare const stringFormat: typeof sf;
/**
* @description A snapshot of a recorded lap interval.
* @summary This captures the lap index, an optional label, the elapsed milliseconds for the lap, and the cumulative elapsed time since the stopwatch started.
* @typedef {object} Lap
* @property {number} index - The zero-based lap order.
* @property {string} [label] - An optional label that describes the lap.
* @property {number} ms - The duration of the lap in milliseconds.
* @property {number} totalMs - The total elapsed time when the lap was recorded.
* @memberOf module:Logging
*/
export type Lap = {
index: number;
label?: string;
/** Duration of this lap in milliseconds */
ms: number;
/** Cumulative time up to this lap in milliseconds */
totalMs: number;
};
type NowFn = () => number;
/**
* @description A high-resolution clock accessor that returns milliseconds.
* @summary This function chooses the most precise timer available in the current runtime, preferring `performance.now` or `process.hrtime.bigint`.
* @return {number} The milliseconds that have elapsed, according to the best available clock.
* @function now
* @memberOf module:Logging
*/
export declare const now: NowFn;
/**
* @description A high-resolution stopwatch with pause, resume, and lap tracking.
* @summary This class tracks elapsed time using the highest precision timer available. It supports pausing, resuming, and recording labeled laps for diagnostics and benchmarking.
* @param {boolean} [autoStart=false] - When `true`, the stopwatch starts immediately upon construction.
* @class StopWatch
* @example
* const sw = new StopWatch(true);
* // ... work ...
* const lap = sw.lap("phase 1");
* sw.pause();
* console.log(`Elapsed: ${lap.totalMs}ms`);
* @mermaid
* sequenceDiagram
* participant Client
* participant StopWatch
* participant Clock as now()
* Client->>StopWatch: start()
* StopWatch->>Clock: now()
* Clock-->>StopWatch: timestamp
* Client->>StopWatch: lap()
* StopWatch->>Clock: now()
* Clock-->>StopWatch: timestamp
* StopWatch-->>Client: Lap
* Client->>StopWatch: pause()
* StopWatch->>Clock: now()
* Clock-->>StopWatch: timestamp
*/
export declare class StopWatch {
private _startMs;
private _elapsedMs;
private _running;
private _laps;
private _lastLapTotalMs;
constructor(autoStart?: boolean);
/**
* @description Indicates whether the stopwatch is actively running.
* @summary This method returns `true` when timing is in progress, and `false` when it is paused or stopped.
* @return {boolean} The current running state.
*/
get running(): boolean;
/**
* @description The elapsed time that has been captured by the stopwatch.
* @summary This method computes the total elapsed time in milliseconds, including the current session if it is running.
* @return {number} The milliseconds that have elapsed since the stopwatch started.
*/
get elapsedMs(): number;
/**
* @description Starts timing if the stopwatch is not already running.
* @summary This method records the current timestamp and transitions the stopwatch into the running state.
* @return {this} A fluent reference to the stopwatch.
*/
start(): this;
/**
* @description Pauses timing and accumulates the elapsed milliseconds.
* @summary This method captures the partial duration, updates the accumulator, and keeps the stopwatch ready to resume later.
* @return {this} A fluent reference to the stopwatch.
*/
pause(): this;
/**
* @description Resumes timing after a pause.
* @summary This method captures a fresh start timestamp, while keeping the previous elapsed time intact.
* @return {this} A fluent reference to the stopwatch.
*/
resume(): this;
/**
* @description Stops timing and returns the total elapsed milliseconds.
* @summary This method invokes {@link StopWatch.pause} to consolidate the elapsed time, and leaves the stopwatch in a non-running state.
* @return {number} The milliseconds that have accumulated across all runs.
*/
stop(): number;
/**
* @description Resets the stopwatch state, while optionally continuing to run.
* @summary This method clears the elapsed time and lap history, and preserves whether the stopwatch should continue ticking.
* @return {this} A fluent reference to the stopwatch.
*/
reset(): this;
/**
* @description Records a lap split since the stopwatch started, or since the previous lap.
* @summary This method stores the lap metadata, updates the cumulative tracking, and returns the newly created {@link Lap}.
* @param {string} [label] - An optional label that describes the lap.
* @return {Lap} A lap snapshot that captures incremental and cumulative timings.
*/
lap(label?: string): Lap;
/**
* @description Retrieves the recorded lap history.
* @summary This method returns the internal lap array as a read-only view to prevent external mutation.
* @return {Array<Lap>} The laps that have been captured by the stopwatch.
*/
get laps(): readonly Lap[];
/**
* @description Formats the elapsed time in a human-readable representation.
* @summary This method uses {@link formatMs} to produce an `hh:mm:ss.mmm` string for display and logging.
* @return {string} The elapsed time, formatted for presentation.
*/
toString(): string;
/**
* @description Serializes the stopwatch state.
* @summary This method provides a JSON-friendly snapshot that includes the running state, elapsed time, and lap details.
* @return {{running: boolean, elapsedMs: number, laps: Lap[]}} A serializable stopwatch representation.
*/
toJSON(): {
running: boolean;
elapsedMs: number;
laps: Lap[];
};
}
/**
* @description Formats milliseconds into `hh:mm:ss.mmm`.
* @summary This function breaks the duration into hours, minutes, seconds, and milliseconds, and returns a zero-padded string.
* @param {number} ms - The milliseconds to format.
* @return {string} The formatted duration string.
* @function formatMs
* @memberOf module:Logging
* @mermaid
* sequenceDiagram
* participant Caller
* participant Formatter as formatMs
* Caller->>Formatter: formatMs(ms)
* Formatter->>Formatter: derive hours/minutes/seconds
* Formatter->>Formatter: pad segments
* Formatter-->>Caller: hh:mm:ss.mmm
*/
export declare function formatMs(ms: number): string;
export {};
import { styles } from "styled-string-builder";
import { LoggingMode, LogLevel } from "./constants";
/**
* @description A string-compatible value that can be accepted by the logging APIs.
* @summary Represents either a literal string or an object that has a `toString()` method. This allows for the lazy stringification of complex payloads.
* @typedef {(string|Object)} StringLike
* @memberOf module:Logging
*/
export type StringLike = string | {
toString: () => string;
};
export type LogMeta = Record<string, unknown>;
/**
* @description A generic function signature for loosely typed callbacks.
* @summary This type covers variadic functions where the arguments and return types are not constrained, which enables the logging layer to accept any callable.
* @typedef {function(...any[]): any} AnyFunction
* @memberOf module:Logging
*/
export type AnyFunction = (...args: any[]) => any;
/**
* @description A constructable class type.
* @summary Describes a constructor that produces instances of type `T`. This allows APIs to accept class references for context-aware logging.
* @template T
* @typedef Class
* @memberOf module:Logging
*/
export type Class<T> = {
new (...args: any[]): T;
};
/**
* @description A context descriptor that is accepted when requesting a logger instance.
* @summary Allows the logging system to resolve context names from strings, constructors, or functions.
* @typedef {(string|Class<any>|AnyFunction)} LoggingContext
* @memberOf module:Logging
*/
export type LoggingContext = string | Class<any> | AnyFunction;
/**
* @description An interface for factories that create contextual clones of the receiver.
* @summary Declares a `for` method that returns another instance of `THIS` using the provided arguments. This enables chained logger customization.
* @template THIS
* @template ARGS
* @interface Impersonatable
* @memberOf module:Logging
*/
export interface Impersonatable<THIS, ARGS extends any[] = any[]> {
/**
* @description Produce a copy of the current instance with altered context.
* @summary Called by logging utilities to derive child objects with supplemental configuration and context metadata.
* @param {ARGS} args - Arguments forwarded to the impersonation strategy.
* @return {THIS} Derived instance using the provided arguments.
*/
for(...args: ARGS): THIS;
}
/**
* @description An interface for loggers that support multiple verbosity levels.
* @summary This interface declares severity-specific log methods, configuration overrides, and factory helpers that are used throughout the logging toolkit.
* @interface Logger
* @memberOf module:Logging
*/
export interface Logger extends Impersonatable<Logger, [
(string | {
new (...args: any[]): any;
} | AnyFunction | Partial<LoggingConfig>),
Partial<LoggingConfig>,
...any[]
]> {
/**
* @description Logs a benchmark message.
* @summary Emits high-frequency performance metrics at the `benchmark` log level.
* @param {StringLike} msg - Message or payload to emit.
* @return {void}
*/
benchmark(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs a `way too verbose` or a silly message.
* @summary Emits playful or extremely verbose details at the `silly` log level.
* @param {StringLike} msg - Message or payload to emit.
* @return {void}
*/
silly(msg: StringLike, verbosity?: number | LogMeta, meta?: LogMeta): void;
/**
* @description Logs developer trace messages.
* @summary Emits playful or extremely verbose details at the `silly` log level.
* @param {StringLike} msg - Message or payload to emit.
* @return {void}
*/
trace(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs a verbose message.
* @summary Writes diagnostic output governed by the configured verbosity threshold.
* @param {StringLike} msg - Message or payload to emit.
* @param {number} [verbosity] - Verbosity level required for the message to pass through.
* @return {void}
*/
verbose(msg: StringLike, verbosityOrMeta?: number | LogMeta, meta?: LogMeta): void;
/**
* @description Logs an info message.
* @summary Emits general informational events that describe application progress.
* @param {StringLike} msg - Message or payload to emit.
* @return {void}
*/
info(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs an error message.
* @summary Records errors and exceptions, including optional stack traces.
* @param {StringLike|Error} msg - Message or {@link Error} instance to log.
* @param {Error} [e] - Optional secondary error or cause.
* @return {void}
*/
error(msg: StringLike | Error, error?: Error | LogMeta, meta?: LogMeta): void;
/**
* @description Logs a debug message.
* @summary Emits fine-grained diagnostic details useful during development and troubleshooting.
* @param {StringLike} msg - Message or payload to emit.
* @return {void}
*/
debug(msg: StringLike, meta?: LogMeta): void;
/**
* @description Logs a debug message.
* @summary Emits fine-grained diagnostic details useful during development and troubleshooting.
* @param {StringLike} msg - Message or payload to emit.
* @return {void}
*/
warn(msg: StringLike, meta?: LogMeta): void;
/**
* @description Creates a new logger for a specific method or context.
* @summary Produces a scoped logger that formats entries using the derived context and overrides supplied configuration.
* @param {any} method - Method name, callback, constructor, or partial configuration used to seed the child logger.
* @param {Partial<LoggingConfig>} [config] - Optional configuration overrides for the child logger.
* @param {...any[]} args - Extra arguments forwarded to factory implementations.
* @return {Logger} Logger instance tailored to the supplied context.
*/
for(config: Partial<LoggingConfig>): this;
for(context: string | {
new (...args: any[]): any;
} | AnyFunction | object): this;
for(method: string | {
new (...args: any[]): any;
} | AnyFunction | object | Partial<LoggingConfig>, config?: Partial<LoggingConfig>, ...args: any[]): this;
/**
* @description Clears any contextual overrides applied via {@link Logger.for}.
* @summary Resets temporary context/configuration so ensuing chains start from the base logger while preserving the concrete instance type.
* @return {this} The same logger instance to continue chaining.
*/
clear(): this;
/**
* @description Updates the logger configuration.
* @summary Merges the given options into the logger's existing configuration.
* @param {Partial<LoggingConfig>} config - Configuration overrides to apply.
* @return {void}
*/
setConfig(config: Partial<LoggingConfig>): void;
/**
* @description Immutable base context for the logger instance.
* @summary Returned as a copy so callers cannot mutate the internal base context while still allowing inspection.
*/
readonly root: string[];
}
/**
* @description An interface for filters that can mutate or reject log messages.
* @summary This allows for custom pre-processing of log entries before they are formatted or emitted.
* @interface LoggingFilter
* @memberOf module:Logging
*/
export interface LoggingFilter {
/**
* @description Apply filtering logic to an incoming message.
* @summary Receives the active configuration, original message, and context stack to produce the final message string.
* @param {LoggingConfig} config - Active logging configuration.
* @param {string} message - Message submitted for logging.
* @param {string[]} context - Context identifiers associated with the message.
* @return {string} Filtered message string.
*/
filter(config: LoggingConfig, message: string, context: string[]): string;
}
/**
* @description Configuration for the logging system.
* @summary Defines the log level, verbosity, and other settings for logging.
* @template TRANSPORT
* @typedef {object} LoggingConfig
* @property {string} env - The environment, e.g., "development", "production".
* @property {LogLevel} level - The logging level.
* @property {boolean} [logLevel] - Whether to display the log level in the output.
* @property {number} verbose - The verbosity level.
* @property {string} contextSeparator - The separator to use between context entries.
* @property {string} separator - The separator to use between log components.
* @property {boolean} [style] - Whether to apply styling to the log output.
* @property {boolean} [timestamp] - Whether to include timestamps in log messages.
* @property {string} [timestampFormat] - The format for timestamps.
* @property {boolean} [context] - Whether to include context information in log messages.
* @property {Theme} [theme] - The theme to use for styling log messages.
* @property {LoggingMode} format - The output format for log messages.
* @property {string} pattern - The pattern to use for formatting log messages.
* @property {(string|number)} [correlationId] - A correlation ID for tracking related log messages.
* @property {(string[]|LoggingFilter[])} [filters] - An array of filters to apply to log messages.
* @property {TRANSPORT[]} [transports] - An array of transports to use for logging.
* @memberOf module:Logging
*/
export type LoggingConfig<TRANSPORT = object> = {
env: "development" | "production" | "test" | "staging" | string;
level: LogLevel;
logLevel?: boolean;
verbose: number;
contextSeparator: string;
separator: string;
style?: boolean;
timestamp?: boolean;
timestampFormat?: string;
context?: boolean;
meta?: boolean;
theme?: Theme;
format: LoggingMode;
pattern: string;
correlationId?: string | number;
filters?: string[] | LoggingFilter[];
transports?: TRANSPORT[];
};
/**
* @description A factory signature for creating logger instances.
* @summary This allows consumers to override the logger construction with custom implementations.
* @template L
* @typedef {function(string, Partial<LoggingConfig>, ...any[]): L} LoggerFactory
* @memberOf module:Logging
*/
export type LoggerFactory<L extends Logger = Logger> = (object?: string, config?: Partial<LoggingConfig>, ...args: any[]) => L;
/**
* @description A theme option that is applied to a specific log element.
* @summary This interface configures the foreground and background colors, as well as additional style directives for styled console output.
* @interface ThemeOption
* @memberOf module:Logging
*/
export interface ThemeOption {
fg?: number | [number] | [number, number, number];
bg?: number | [number] | [number, number, number];
style?: number[] | [keyof typeof styles];
}
/**
* @description A mapping between log levels and theme overrides.
* @summary This enables level-specific styling by associating each {@link LogLevel} with a {@link ThemeOption} configuration.
* @typedef {Partial<Record<LogLevel, ThemeOption>>} ThemeOptionByLogLevel
* @memberOf module:Logging
*/
export type ThemeOptionByLogLevel = Partial<Record<LogLevel, ThemeOption>>;
/**
* @description A theme definition that is applied to the console output.
* @summary This interface specifies the styling for each console log element and supports overrides based on {@link LogLevel} values.
* @interface Theme
* @memberOf module:Logging
*/
export interface Theme {
/**
* @description Styling for application identifiers in the output.
*/
app: ThemeOption | ThemeOptionByLogLevel;
/**
* @description Styling for separators inserted between log sections.
*/
separator: ThemeOption | ThemeOptionByLogLevel;
/**
* @description Styling for class names in the output.
*/
class: ThemeOption | ThemeOptionByLogLevel;
/**
* @description Styling for timestamps in the output.
*/
timestamp: ThemeOption | ThemeOptionByLogLevel;
/**
* @description Styling for the main message text in the output.
*/
message: ThemeOption | ThemeOptionByLogLevel;
/**
* @description Styling for method names in the output.
*/
method: ThemeOption | ThemeOptionByLogLevel;
/**
* @description Styling for identifier elements in the output.
*/
id: ThemeOption | ThemeOptionByLogLevel;
/**
* @description Styling for stack trace blocks in the output.
*/
stack: ThemeOption;
/**
* @description Styling overrides keyed by {@link LogLevel}.
*/
logLevel: ThemeOptionByLogLevel;
}
/**
* @description Checks if a value is a class.
* @summary This function determines if the given value is a class constructor.
* @param {unknown} value - The value to check.
* @return {boolean} `true` if the value is a class, `false` otherwise.
* @function isClass
* @memberOf module:Logging
*/
export declare function isClass(value: unknown): value is abstract new (...args: any[]) => any;
/**
* @description Checks if a value is a function.
* @summary This function determines if the given value is a function, but not a class.
* @template T
* @param {unknown} value - The value to check.
* @return {boolean} `true` if the value is a function, `false` otherwise.
* @function isFunction
* @memberOf module:Logging
*/
export declare function isFunction<T extends (...args: any[]) => unknown>(value: unknown): value is T;
/**
* @description Checks if a value is a method.
* @summary This function determines if the given value is a method.
* @template T
* @param {unknown} value - The value to check.
* @return {boolean} `true` if the value is a method, `false` otherwise.
* @function isMethod
* @memberOf module:Logging
*/
export declare function isMethod<T extends (...args: any[]) => unknown>(value: unknown): value is T;
/**
* @description Checks if a value is an instance of a class.
* @summary This function determines if the given value is an instance of a class.
* @template T
* @param {unknown} value - The value to check.
* @return {boolean} `true` if the value is an instance of a class, `false` otherwise.
* @function isInstance
* @memberOf module:Logging
*/
export declare function isInstance<T extends object>(value: unknown): value is T;
/**
* @description Gets the name of an object.
* @summary This function returns the name of the given object, which can be a class, an instance of a class, a function, or a primitive value.
* @param {unknown} value - The value to get the name of.
* @return {string} The name of the object.
* @function getObjectName
* @memberOf module:Logging
*/
export declare function getObjectName(value: unknown): string;
/**
* @description Determines if the current environment is a browser by checking the prototype chain of the global object.
* @summary This function checks if the code is running in a browser environment.
* @return {boolean} `true` if the environment is a browser, `false` otherwise.
* @function isBrowser
* @memberOf module:Logging
*/
export declare function isBrowser(): boolean;
/**
* @module Winston
* @description This module provides an adapter for the Winston logger.
* @summary This module exports the {@link WinstonLogger} class.
* @memberOf module:Logging
*/
export * from "./winston";
import winston from "winston";
import { Logger, LoggerFactory, LogMeta, LoggingConfig, StringLike } from "../types";
import { MiniLogger } from "../logging";
import { LogLevel } from "../constants";
/**
* @description A logger implementation that uses Winston.
* @summary This class extends {@link MiniLogger} to provide logging functionality using the Winston library. It configures Winston with the appropriate transports and formats based on the logging configuration.
* @param {string} [cont] - The context (typically the class name) that this logger is associated with.
* @param {Partial<LoggingConfig>} [conf] - Optional configuration to override global settings.
* @class WinstonLogger
* @example
* // Create a Winston logger for a class
* const logger = new WinstonLogger('MyClass');
*
* // Log messages at different levels
* logger.info('Application started');
* logger.error(new Error('Something went wrong'));
*
* // Create a child logger for a specific method
* const methodLogger = logger.for('myMethod');
* methodLogger.debug('Processing data...');
*/
export declare class WinstonLogger extends MiniLogger implements Logger {
protected winston: winston.Logger;
constructor(cont?: string, conf?: Partial<LoggingConfig>);
private resolveTransports;
/**
* @description Logs a message with the specified log level using Winston.
* @summary This method overrides the base log method to use Winston for logging.
* @param {LogLevel} level - The log level of the message.
* @param {(StringLike|Error)} msg - The message to be logged or an Error object.
* @param {Error} [error] - An optional stack trace to include in the log.
* @return {void}
*/
protected log(level: LogLevel, msg: StringLike | Error, error?: Error, meta?: LogMeta): void;
}
/**
* @description A factory function for creating Winston loggers.
* @summary This is a {@link LoggerFactory} implementation that creates {@link WinstonLogger} instances.
* @param {string} [context] - The context (typically the class name) for the logger.
* @param {Partial<LoggingConfig>} [conf] - Optional configuration to override global settings.
* @param {...any} _args - Additional arguments to pass to the WinstonLogger constructor.
* @return {WinstonLogger} A new WinstonLogger instance.
* @const WinstonFactory
* @memberOf module:Logging
*/
export declare const WinstonFactory: LoggerFactory;