@contractspec/lib.logger 1.46.2 → 1.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"context.browser.mjs","names":["contextData: LogContextData","mergedContext: ContextData"],"sources":["../src/context.browser.ts"],"sourcesContent":["import 'zone.js';\nimport type { ContextData, TraceContext } from './types';\n\ninterface LogContextData {\n context: ContextData;\n trace?: TraceContext;\n}\n\ninterface ZoneForkSpec {\n name?: string;\n properties?: Record<string, unknown>;\n}\n\ninterface ZoneLike {\n fork(spec: ZoneForkSpec): ZoneLike;\n run<T>(fn: () => T): T;\n get<T>(key: string): T | undefined;\n}\n\ninterface ZoneStaticLike {\n current: ZoneLike;\n}\n\nconst ZONE = (globalThis as unknown as { Zone?: ZoneStaticLike }).Zone;\nconst STORE_KEY = '__lssm_log_context_data__';\n\nfunction getStore(): LogContextData | undefined {\n if (!ZONE) return undefined;\n return ZONE.current.get<LogContextData>(STORE_KEY);\n}\n\n/**\n * Browser implementation of LogContext using Zone.js for async context\n * propagation (similar to AsyncLocalStorage in Node).\n */\nexport class LogContext {\n private static instance: LogContext;\n private static fallbackCounter = 0;\n\n static getInstance(): LogContext {\n if (!LogContext.instance) {\n LogContext.instance = new LogContext();\n }\n return LogContext.instance;\n }\n\n /**\n * Run a function with a new context\n */\n run<T>(context: ContextData, fn: () => T): T {\n const contextData: LogContextData = {\n context: { ...context },\n trace: this.getCurrentTrace(),\n };\n\n if (!ZONE) {\n return fn();\n }\n\n const zone = ZONE.current.fork({\n name: 'log-context',\n properties: { [STORE_KEY]: contextData },\n });\n\n return zone.run(fn);\n }\n\n /**\n * Run a function with an extended context (merges with current)\n */\n extend<T>(additionalContext: Partial<ContextData>, fn: () => T): T {\n const currentContext = this.getContext();\n const mergedContext: ContextData = {\n ...currentContext,\n ...additionalContext,\n };\n return this.run(mergedContext, fn);\n }\n\n /**\n * Set context data for the current execution context\n */\n set(key: string, value: unknown): void {\n const current = getStore();\n if (current) {\n current.context[key] = value;\n }\n }\n\n /**\n * Get a specific context value\n */\n get<T>(key: string): T | undefined {\n const current = getStore();\n return current?.context?.[key] as T | undefined;\n }\n\n /**\n * Get all context data\n */\n getContext(): ContextData {\n const current = getStore();\n return current?.context || {};\n }\n\n /**\n * Set trace context\n */\n setTrace(trace: TraceContext): void {\n const current = getStore();\n if (current) {\n current.trace = trace;\n }\n }\n\n /**\n * Get current trace context\n */\n getCurrentTrace(): TraceContext | undefined {\n const current = getStore();\n return current?.trace;\n }\n\n /**\n * Generate a unique ID for requests/operations\n */\n generateId(): string {\n if (\n typeof crypto !== 'undefined' &&\n typeof (crypto as unknown as { randomUUID?: unknown }).randomUUID ===\n 'function'\n ) {\n return crypto.randomUUID();\n }\n\n LogContext.fallbackCounter += 1;\n return `log-${LogContext.fallbackCounter}`;\n }\n}\n"],"mappings":";;;AAuBA,MAAM,OAAQ,WAAoD;AAClE,MAAM,YAAY;AAElB,SAAS,WAAuC;AAC9C,KAAI,CAAC,KAAM,QAAO;AAClB,QAAO,KAAK,QAAQ,IAAoB,UAAU;;;;;;AAOpD,IAAa,aAAb,MAAa,WAAW;CACtB,OAAe;CACf,OAAe,kBAAkB;CAEjC,OAAO,cAA0B;AAC/B,MAAI,CAAC,WAAW,SACd,YAAW,WAAW,IAAI,YAAY;AAExC,SAAO,WAAW;;;;;CAMpB,IAAO,SAAsB,IAAgB;EAC3C,MAAMA,cAA8B;GAClC,SAAS,EAAE,GAAG,SAAS;GACvB,OAAO,KAAK,iBAAiB;GAC9B;AAED,MAAI,CAAC,KACH,QAAO,IAAI;AAQb,SALa,KAAK,QAAQ,KAAK;GAC7B,MAAM;GACN,YAAY,GAAG,YAAY,aAAa;GACzC,CAAC,CAEU,IAAI,GAAG;;;;;CAMrB,OAAU,mBAAyC,IAAgB;EAEjE,MAAMC,gBAA6B;GACjC,GAFqB,KAAK,YAAY;GAGtC,GAAG;GACJ;AACD,SAAO,KAAK,IAAI,eAAe,GAAG;;;;;CAMpC,IAAI,KAAa,OAAsB;EACrC,MAAM,UAAU,UAAU;AAC1B,MAAI,QACF,SAAQ,QAAQ,OAAO;;;;;CAO3B,IAAO,KAA4B;AAEjC,SADgB,UAAU,EACV,UAAU;;;;;CAM5B,aAA0B;AAExB,SADgB,UAAU,EACV,WAAW,EAAE;;;;;CAM/B,SAAS,OAA2B;EAClC,MAAM,UAAU,UAAU;AAC1B,MAAI,QACF,SAAQ,QAAQ;;;;;CAOpB,kBAA4C;AAE1C,SADgB,UAAU,EACV;;;;;CAMlB,aAAqB;AACnB,MACE,OAAO,WAAW,eAClB,OAAQ,OAA+C,eACrD,WAEF,QAAO,OAAO,YAAY;AAG5B,aAAW,mBAAmB;AAC9B,SAAO,OAAO,WAAW"}
1
+ {"version":3,"file":"context.browser.mjs","names":[],"sources":["../src/context.browser.ts"],"sourcesContent":["import 'zone.js';\nimport type { ContextData, TraceContext } from './types';\n\ninterface LogContextData {\n context: ContextData;\n trace?: TraceContext;\n}\n\ninterface ZoneForkSpec {\n name?: string;\n properties?: Record<string, unknown>;\n}\n\ninterface ZoneLike {\n fork(spec: ZoneForkSpec): ZoneLike;\n run<T>(fn: () => T): T;\n get<T>(key: string): T | undefined;\n}\n\ninterface ZoneStaticLike {\n current: ZoneLike;\n}\n\nconst ZONE = (globalThis as unknown as { Zone?: ZoneStaticLike }).Zone;\nconst STORE_KEY = '__lssm_log_context_data__';\n\nfunction getStore(): LogContextData | undefined {\n if (!ZONE) return undefined;\n return ZONE.current.get<LogContextData>(STORE_KEY);\n}\n\n/**\n * Browser implementation of LogContext using Zone.js for async context\n * propagation (similar to AsyncLocalStorage in Node).\n */\nexport class LogContext {\n private static instance: LogContext;\n private static fallbackCounter = 0;\n\n static getInstance(): LogContext {\n if (!LogContext.instance) {\n LogContext.instance = new LogContext();\n }\n return LogContext.instance;\n }\n\n /**\n * Run a function with a new context\n */\n run<T>(context: ContextData, fn: () => T): T {\n const contextData: LogContextData = {\n context: { ...context },\n trace: this.getCurrentTrace(),\n };\n\n if (!ZONE) {\n return fn();\n }\n\n const zone = ZONE.current.fork({\n name: 'log-context',\n properties: { [STORE_KEY]: contextData },\n });\n\n return zone.run(fn);\n }\n\n /**\n * Run a function with an extended context (merges with current)\n */\n extend<T>(additionalContext: Partial<ContextData>, fn: () => T): T {\n const currentContext = this.getContext();\n const mergedContext: ContextData = {\n ...currentContext,\n ...additionalContext,\n };\n return this.run(mergedContext, fn);\n }\n\n /**\n * Set context data for the current execution context\n */\n set(key: string, value: unknown): void {\n const current = getStore();\n if (current) {\n current.context[key] = value;\n }\n }\n\n /**\n * Get a specific context value\n */\n get<T>(key: string): T | undefined {\n const current = getStore();\n return current?.context?.[key] as T | undefined;\n }\n\n /**\n * Get all context data\n */\n getContext(): ContextData {\n const current = getStore();\n return current?.context || {};\n }\n\n /**\n * Set trace context\n */\n setTrace(trace: TraceContext): void {\n const current = getStore();\n if (current) {\n current.trace = trace;\n }\n }\n\n /**\n * Get current trace context\n */\n getCurrentTrace(): TraceContext | undefined {\n const current = getStore();\n return current?.trace;\n }\n\n /**\n * Generate a unique ID for requests/operations\n */\n generateId(): string {\n if (\n typeof crypto !== 'undefined' &&\n typeof (crypto as unknown as { randomUUID?: unknown }).randomUUID ===\n 'function'\n ) {\n return crypto.randomUUID();\n }\n\n LogContext.fallbackCounter += 1;\n return `log-${LogContext.fallbackCounter}`;\n }\n}\n"],"mappings":";;;AAuBA,MAAM,OAAQ,WAAoD;AAClE,MAAM,YAAY;AAElB,SAAS,WAAuC;AAC9C,KAAI,CAAC,KAAM,QAAO;AAClB,QAAO,KAAK,QAAQ,IAAoB,UAAU;;;;;;AAOpD,IAAa,aAAb,MAAa,WAAW;CACtB,OAAe;CACf,OAAe,kBAAkB;CAEjC,OAAO,cAA0B;AAC/B,MAAI,CAAC,WAAW,SACd,YAAW,WAAW,IAAI,YAAY;AAExC,SAAO,WAAW;;;;;CAMpB,IAAO,SAAsB,IAAgB;EAC3C,MAAM,cAA8B;GAClC,SAAS,EAAE,GAAG,SAAS;GACvB,OAAO,KAAK,iBAAiB;GAC9B;AAED,MAAI,CAAC,KACH,QAAO,IAAI;AAQb,SALa,KAAK,QAAQ,KAAK;GAC7B,MAAM;GACN,YAAY,GAAG,YAAY,aAAa;GACzC,CAAC,CAEU,IAAI,GAAG;;;;;CAMrB,OAAU,mBAAyC,IAAgB;EAEjE,MAAM,gBAA6B;GACjC,GAFqB,KAAK,YAAY;GAGtC,GAAG;GACJ;AACD,SAAO,KAAK,IAAI,eAAe,GAAG;;;;;CAMpC,IAAI,KAAa,OAAsB;EACrC,MAAM,UAAU,UAAU;AAC1B,MAAI,QACF,SAAQ,QAAQ,OAAO;;;;;CAO3B,IAAO,KAA4B;AAEjC,SADgB,UAAU,EACV,UAAU;;;;;CAM5B,aAA0B;AAExB,SADgB,UAAU,EACV,WAAW,EAAE;;;;;CAM/B,SAAS,OAA2B;EAClC,MAAM,UAAU,UAAU;AAC1B,MAAI,QACF,SAAQ,QAAQ;;;;;CAOpB,kBAA4C;AAE1C,SADgB,UAAU,EACV;;;;;CAMlB,aAAqB;AACnB,MACE,OAAO,WAAW,eAClB,OAAQ,OAA+C,eACrD,WAEF,QAAO,OAAO,YAAY;AAG5B,aAAW,mBAAmB;AAC9B,SAAO,OAAO,WAAW"}
@@ -1 +1 @@
1
- {"version":3,"file":"context.node.mjs","names":["contextData: LogContextData","mergedContext: ContextData"],"sources":["../src/context.node.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { ContextData, TraceContext } from './types';\n\ninterface LogContextData {\n context: ContextData;\n trace?: TraceContext;\n}\n\n/**\n * Node.js implementation of LogContext using AsyncLocalStorage.\n */\nexport class LogContext {\n private static instance: LogContext;\n private storage: AsyncLocalStorage<LogContextData>;\n\n constructor() {\n this.storage = new AsyncLocalStorage<LogContextData>();\n }\n\n static getInstance(): LogContext {\n if (!LogContext.instance) {\n LogContext.instance = new LogContext();\n }\n return LogContext.instance;\n }\n\n /**\n * Run a function with a new context\n */\n run<T>(context: ContextData, fn: () => T): T {\n const contextData: LogContextData = {\n context: { ...context },\n trace: this.getCurrentTrace(),\n };\n return this.storage.run(contextData, fn) as T;\n }\n\n /**\n * Run a function with an extended context (merges with current)\n */\n extend<T>(additionalContext: Partial<ContextData>, fn: () => T): T {\n const currentContext = this.getContext();\n const mergedContext: ContextData = {\n ...currentContext,\n ...additionalContext,\n };\n return this.run(mergedContext, fn);\n }\n\n /**\n * Set context data for the current execution context\n */\n set(key: string, value: unknown): void {\n const current = this.storage.getStore();\n if (current) {\n current.context[key] = value;\n }\n }\n\n /**\n * Get a specific context value\n */\n get<T>(key: string): T | undefined {\n const current = this.storage.getStore();\n return current?.context?.[key] as T | undefined;\n }\n\n /**\n * Get all context data\n */\n getContext(): ContextData {\n const current = this.storage.getStore();\n return current?.context || {};\n }\n\n /**\n * Set trace context\n */\n setTrace(trace: TraceContext): void {\n const current = this.storage.getStore();\n if (current) {\n current.trace = trace;\n }\n }\n\n /**\n * Get current trace context\n */\n getCurrentTrace(): TraceContext | undefined {\n const current = this.storage.getStore();\n return current?.trace;\n }\n\n /**\n * Generate a unique ID for requests/operations\n */\n generateId(): string {\n return crypto.randomUUID();\n }\n}\n"],"mappings":";;;;;;AAWA,IAAa,aAAb,MAAa,WAAW;CACtB,OAAe;CACf,AAAQ;CAER,cAAc;AACZ,OAAK,UAAU,IAAI,mBAAmC;;CAGxD,OAAO,cAA0B;AAC/B,MAAI,CAAC,WAAW,SACd,YAAW,WAAW,IAAI,YAAY;AAExC,SAAO,WAAW;;;;;CAMpB,IAAO,SAAsB,IAAgB;EAC3C,MAAMA,cAA8B;GAClC,SAAS,EAAE,GAAG,SAAS;GACvB,OAAO,KAAK,iBAAiB;GAC9B;AACD,SAAO,KAAK,QAAQ,IAAI,aAAa,GAAG;;;;;CAM1C,OAAU,mBAAyC,IAAgB;EAEjE,MAAMC,gBAA6B;GACjC,GAFqB,KAAK,YAAY;GAGtC,GAAG;GACJ;AACD,SAAO,KAAK,IAAI,eAAe,GAAG;;;;;CAMpC,IAAI,KAAa,OAAsB;EACrC,MAAM,UAAU,KAAK,QAAQ,UAAU;AACvC,MAAI,QACF,SAAQ,QAAQ,OAAO;;;;;CAO3B,IAAO,KAA4B;AAEjC,SADgB,KAAK,QAAQ,UAAU,EACvB,UAAU;;;;;CAM5B,aAA0B;AAExB,SADgB,KAAK,QAAQ,UAAU,EACvB,WAAW,EAAE;;;;;CAM/B,SAAS,OAA2B;EAClC,MAAM,UAAU,KAAK,QAAQ,UAAU;AACvC,MAAI,QACF,SAAQ,QAAQ;;;;;CAOpB,kBAA4C;AAE1C,SADgB,KAAK,QAAQ,UAAU,EACvB;;;;;CAMlB,aAAqB;AACnB,SAAO,OAAO,YAAY"}
1
+ {"version":3,"file":"context.node.mjs","names":[],"sources":["../src/context.node.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { ContextData, TraceContext } from './types';\n\ninterface LogContextData {\n context: ContextData;\n trace?: TraceContext;\n}\n\n/**\n * Node.js implementation of LogContext using AsyncLocalStorage.\n */\nexport class LogContext {\n private static instance: LogContext;\n private storage: AsyncLocalStorage<LogContextData>;\n\n constructor() {\n this.storage = new AsyncLocalStorage<LogContextData>();\n }\n\n static getInstance(): LogContext {\n if (!LogContext.instance) {\n LogContext.instance = new LogContext();\n }\n return LogContext.instance;\n }\n\n /**\n * Run a function with a new context\n */\n run<T>(context: ContextData, fn: () => T): T {\n const contextData: LogContextData = {\n context: { ...context },\n trace: this.getCurrentTrace(),\n };\n return this.storage.run(contextData, fn) as T;\n }\n\n /**\n * Run a function with an extended context (merges with current)\n */\n extend<T>(additionalContext: Partial<ContextData>, fn: () => T): T {\n const currentContext = this.getContext();\n const mergedContext: ContextData = {\n ...currentContext,\n ...additionalContext,\n };\n return this.run(mergedContext, fn);\n }\n\n /**\n * Set context data for the current execution context\n */\n set(key: string, value: unknown): void {\n const current = this.storage.getStore();\n if (current) {\n current.context[key] = value;\n }\n }\n\n /**\n * Get a specific context value\n */\n get<T>(key: string): T | undefined {\n const current = this.storage.getStore();\n return current?.context?.[key] as T | undefined;\n }\n\n /**\n * Get all context data\n */\n getContext(): ContextData {\n const current = this.storage.getStore();\n return current?.context || {};\n }\n\n /**\n * Set trace context\n */\n setTrace(trace: TraceContext): void {\n const current = this.storage.getStore();\n if (current) {\n current.trace = trace;\n }\n }\n\n /**\n * Get current trace context\n */\n getCurrentTrace(): TraceContext | undefined {\n const current = this.storage.getStore();\n return current?.trace;\n }\n\n /**\n * Generate a unique ID for requests/operations\n */\n generateId(): string {\n return crypto.randomUUID();\n }\n}\n"],"mappings":";;;;;;AAWA,IAAa,aAAb,MAAa,WAAW;CACtB,OAAe;CACf,AAAQ;CAER,cAAc;AACZ,OAAK,UAAU,IAAI,mBAAmC;;CAGxD,OAAO,cAA0B;AAC/B,MAAI,CAAC,WAAW,SACd,YAAW,WAAW,IAAI,YAAY;AAExC,SAAO,WAAW;;;;;CAMpB,IAAO,SAAsB,IAAgB;EAC3C,MAAM,cAA8B;GAClC,SAAS,EAAE,GAAG,SAAS;GACvB,OAAO,KAAK,iBAAiB;GAC9B;AACD,SAAO,KAAK,QAAQ,IAAI,aAAa,GAAG;;;;;CAM1C,OAAU,mBAAyC,IAAgB;EAEjE,MAAM,gBAA6B;GACjC,GAFqB,KAAK,YAAY;GAGtC,GAAG;GACJ;AACD,SAAO,KAAK,IAAI,eAAe,GAAG;;;;;CAMpC,IAAI,KAAa,OAAsB;EACrC,MAAM,UAAU,KAAK,QAAQ,UAAU;AACvC,MAAI,QACF,SAAQ,QAAQ,OAAO;;;;;CAO3B,IAAO,KAA4B;AAEjC,SADgB,KAAK,QAAQ,UAAU,EACvB,UAAU;;;;;CAM5B,aAA0B;AAExB,SADgB,KAAK,QAAQ,UAAU,EACvB,WAAW,EAAE;;;;;CAM/B,SAAS,OAA2B;EAClC,MAAM,UAAU,KAAK,QAAQ,UAAU;AACvC,MAAI,QACF,SAAQ,QAAQ;;;;;CAOpB,kBAA4C;AAE1C,SADgB,KAAK,QAAQ,UAAU,EACvB;;;;;CAMlB,aAAqB;AACnB,SAAO,OAAO,YAAY"}
@@ -1 +1 @@
1
- {"version":3,"file":"elysia-plugin.mjs","names":["requestContext: ContextData"],"sources":["../src/elysia-plugin.ts"],"sourcesContent":["import { Logger } from './logger.node';\nimport { LogContext } from './context.node';\nimport type { ContextData } from './types';\nimport { Elysia } from 'elysia';\n\nexport interface ElysiaLoggerConfig {\n logger?: Logger;\n logRequests?: boolean;\n logResponses?: boolean;\n excludePaths?: string[];\n}\n\n/**\n * Simple ElysiaJS Logger Plugin\n * Provides automatic request logging and tracing\n */\nexport function elysiaLogger<T extends Elysia>(\n config: ElysiaLoggerConfig = {}\n) {\n const {\n logger = new Logger(),\n logRequests = true,\n logResponses = true,\n excludePaths = ['/health', '/metrics'],\n } = config;\n\n const context = LogContext.getInstance();\n\n // For type compatibility, we use a factory function\n return function (app: T) {\n return app\n .derive((ctx) => {\n const { request, path } = ctx;\n\n // Skip excluded paths\n if (excludePaths.some((excludePath) => path.startsWith(excludePath))) {\n return { logger };\n }\n\n // Create request context\n const url = new URL(request.url);\n const requestContext: ContextData = {\n requestId: context.generateId(),\n method: request.method,\n url: request.url,\n path: url.pathname,\n userAgent: request.headers.get('user-agent') || undefined,\n timestamp: new Date().toISOString(),\n };\n\n const startTime = performance.now();\n\n // Run in context\n context.run(requestContext, () => {\n // Log request\n if (logRequests) {\n logger.info(`→ ${request.method} ${path}`, {\n method: request.method,\n path,\n userAgent: requestContext.userAgent,\n requestId: requestContext.requestId,\n });\n }\n });\n\n return {\n logger,\n requestContext,\n startTime,\n };\n })\n .onAfterHandle((ctx) => {\n const { request, startTime, requestContext, logger } = ctx;\n\n if (!startTime || !requestContext) return;\n\n const duration = performance.now() - startTime;\n const path = new URL(request.url).pathname;\n\n if (logResponses) {\n logger.info(`← 200 ${request.method} ${path}`, {\n method: request.method,\n path,\n duration: `${duration.toFixed(2)}ms`,\n requestId: requestContext.requestId,\n });\n }\n })\n .onError((ctx) => {\n const { request, error, code, startTime, requestContext, logger } = ctx;\n\n if (!startTime || !requestContext) return;\n\n const duration = performance.now() - startTime;\n const path = new URL(request.url).pathname;\n\n logger?.error(`✖ ${code} ${request.method} ${path}`, {\n method: request.method,\n path,\n error: error?.toString?.() || 'Unknown error',\n code,\n duration: `${duration.toFixed(2)}ms`,\n requestId: requestContext.requestId,\n });\n })\n .derive(() => ({\n // Helper functions available in route handlers\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logInfo: (message: string, metadata?: Record<string, any>) => {\n logger.info(message, metadata);\n },\n logError: (\n message: string,\n error?: Error,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>\n ) => {\n logger.error(message, metadata, error);\n },\n traceOperation: async <T>(\n operationName: string,\n operation: () => T | Promise<T>\n ): Promise<T> => {\n return logger.trace(\n {\n operationType: 'custom',\n operationName,\n autoTiming: true,\n },\n operation\n );\n },\n }));\n };\n}\n"],"mappings":";;;;;;;;;AAgBA,SAAgB,aACd,SAA6B,EAAE,EAC/B;CACA,MAAM,EACJ,SAAS,IAAI,QAAQ,EACrB,cAAc,MACd,eAAe,MACf,eAAe,CAAC,WAAW,WAAW,KACpC;CAEJ,MAAM,UAAU,WAAW,aAAa;AAGxC,QAAO,SAAU,KAAQ;AACvB,SAAO,IACJ,QAAQ,QAAQ;GACf,MAAM,EAAE,SAAS,SAAS;AAG1B,OAAI,aAAa,MAAM,gBAAgB,KAAK,WAAW,YAAY,CAAC,CAClE,QAAO,EAAE,QAAQ;GAInB,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;GAChC,MAAMA,iBAA8B;IAClC,WAAW,QAAQ,YAAY;IAC/B,QAAQ,QAAQ;IAChB,KAAK,QAAQ;IACb,MAAM,IAAI;IACV,WAAW,QAAQ,QAAQ,IAAI,aAAa,IAAI;IAChD,4BAAW,IAAI,MAAM,EAAC,aAAa;IACpC;GAED,MAAM,YAAY,YAAY,KAA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"file":"elysia-plugin.mjs","names":[],"sources":["../src/elysia-plugin.ts"],"sourcesContent":["import { Logger } from './logger.node';\nimport { LogContext } from './context.node';\nimport type { ContextData } from './types';\nimport { Elysia } from 'elysia';\n\nexport interface ElysiaLoggerConfig {\n logger?: Logger;\n logRequests?: boolean;\n logResponses?: boolean;\n excludePaths?: string[];\n}\n\n/**\n * Simple ElysiaJS Logger Plugin\n * Provides automatic request logging and tracing\n */\nexport function elysiaLogger<T extends Elysia>(\n config: ElysiaLoggerConfig = {}\n) {\n const {\n logger = new Logger(),\n logRequests = true,\n logResponses = true,\n excludePaths = ['/health', '/metrics'],\n } = config;\n\n const context = LogContext.getInstance();\n\n // For type compatibility, we use a factory function\n return function (app: T) {\n return app\n .derive((ctx) => {\n const { request, path } = ctx;\n\n // Skip excluded paths\n if (excludePaths.some((excludePath) => path.startsWith(excludePath))) {\n return { logger };\n }\n\n // Create request context\n const url = new URL(request.url);\n const requestContext: ContextData = {\n requestId: context.generateId(),\n method: request.method,\n url: request.url,\n path: url.pathname,\n userAgent: request.headers.get('user-agent') || undefined,\n timestamp: new Date().toISOString(),\n };\n\n const startTime = performance.now();\n\n // Run in context\n context.run(requestContext, () => {\n // Log request\n if (logRequests) {\n logger.info(`→ ${request.method} ${path}`, {\n method: request.method,\n path,\n userAgent: requestContext.userAgent,\n requestId: requestContext.requestId,\n });\n }\n });\n\n return {\n logger,\n requestContext,\n startTime,\n };\n })\n .onAfterHandle((ctx) => {\n const { request, startTime, requestContext, logger } = ctx;\n\n if (!startTime || !requestContext) return;\n\n const duration = performance.now() - startTime;\n const path = new URL(request.url).pathname;\n\n if (logResponses) {\n logger.info(`← 200 ${request.method} ${path}`, {\n method: request.method,\n path,\n duration: `${duration.toFixed(2)}ms`,\n requestId: requestContext.requestId,\n });\n }\n })\n .onError((ctx) => {\n const { request, error, code, startTime, requestContext, logger } = ctx;\n\n if (!startTime || !requestContext) return;\n\n const duration = performance.now() - startTime;\n const path = new URL(request.url).pathname;\n\n logger?.error(`✖ ${code} ${request.method} ${path}`, {\n method: request.method,\n path,\n error: error?.toString?.() || 'Unknown error',\n code,\n duration: `${duration.toFixed(2)}ms`,\n requestId: requestContext.requestId,\n });\n })\n .derive(() => ({\n // Helper functions available in route handlers\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logInfo: (message: string, metadata?: Record<string, any>) => {\n logger.info(message, metadata);\n },\n logError: (\n message: string,\n error?: Error,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>\n ) => {\n logger.error(message, metadata, error);\n },\n traceOperation: async <T>(\n operationName: string,\n operation: () => T | Promise<T>\n ): Promise<T> => {\n return logger.trace(\n {\n operationType: 'custom',\n operationName,\n autoTiming: true,\n },\n operation\n );\n },\n }));\n };\n}\n"],"mappings":";;;;;;;;;AAgBA,SAAgB,aACd,SAA6B,EAAE,EAC/B;CACA,MAAM,EACJ,SAAS,IAAI,QAAQ,EACrB,cAAc,MACd,eAAe,MACf,eAAe,CAAC,WAAW,WAAW,KACpC;CAEJ,MAAM,UAAU,WAAW,aAAa;AAGxC,QAAO,SAAU,KAAQ;AACvB,SAAO,IACJ,QAAQ,QAAQ;GACf,MAAM,EAAE,SAAS,SAAS;AAG1B,OAAI,aAAa,MAAM,gBAAgB,KAAK,WAAW,YAAY,CAAC,CAClE,QAAO,EAAE,QAAQ;GAInB,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;GAChC,MAAM,iBAA8B;IAClC,WAAW,QAAQ,YAAY;IAC/B,QAAQ,QAAQ;IAChB,KAAK,QAAQ;IACb,MAAM,IAAI;IACV,WAAW,QAAQ,QAAQ,IAAI,aAAa,IAAI;IAChD,4BAAW,IAAI,MAAM,EAAC,aAAa;IACpC;GAED,MAAM,YAAY,YAAY,KAAK;AAGnC,WAAQ,IAAI,sBAAsB;AAEhC,QAAI,YACF,QAAO,KAAK,KAAK,QAAQ,OAAO,GAAG,QAAQ;KACzC,QAAQ,QAAQ;KAChB;KACA,WAAW,eAAe;KAC1B,WAAW,eAAe;KAC3B,CAAC;KAEJ;AAEF,UAAO;IACL;IACA;IACA;IACD;IACD,CACD,eAAe,QAAQ;GACtB,MAAM,EAAE,SAAS,WAAW,gBAAgB,qBAAW;AAEvD,OAAI,CAAC,aAAa,CAAC,eAAgB;GAEnC,MAAM,WAAW,YAAY,KAAK,GAAG;GACrC,MAAM,OAAO,IAAI,IAAI,QAAQ,IAAI,CAAC;AAElC,OAAI,aACF,UAAO,KAAK,SAAS,QAAQ,OAAO,GAAG,QAAQ;IAC7C,QAAQ,QAAQ;IAChB;IACA,UAAU,GAAG,SAAS,QAAQ,EAAE,CAAC;IACjC,WAAW,eAAe;IAC3B,CAAC;IAEJ,CACD,SAAS,QAAQ;GAChB,MAAM,EAAE,SAAS,OAAO,MAAM,WAAW,gBAAgB,qBAAW;AAEpE,OAAI,CAAC,aAAa,CAAC,eAAgB;GAEnC,MAAM,WAAW,YAAY,KAAK,GAAG;GACrC,MAAM,OAAO,IAAI,IAAI,QAAQ,IAAI,CAAC;AAElC,aAAQ,MAAM,KAAK,KAAK,GAAG,QAAQ,OAAO,GAAG,QAAQ;IACnD,QAAQ,QAAQ;IAChB;IACA,OAAO,OAAO,YAAY,IAAI;IAC9B;IACA,UAAU,GAAG,SAAS,QAAQ,EAAE,CAAC;IACjC,WAAW,eAAe;IAC3B,CAAC;IACF,CACD,cAAc;GAGb,UAAU,SAAiB,aAAmC;AAC5D,WAAO,KAAK,SAAS,SAAS;;GAEhC,WACE,SACA,OAEA,aACG;AACH,WAAO,MAAM,SAAS,UAAU,MAAM;;GAExC,gBAAgB,OACd,eACA,cACe;AACf,WAAO,OAAO,MACZ;KACE,eAAe;KACf;KACA,YAAY;KACb,EACD,UACD;;GAEJ,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"formatters.mjs","names":["parts: string[]","logObject: LogEntry"],"sources":["../src/formatters.ts"],"sourcesContent":["import type { Formatter, LogEntry } from './types';\nimport { LogLevel } from './types';\n\n// ANSI color codes for terminal output\nconst colors = {\n reset: '\\x1b[0m',\n bright: '\\x1b[1m',\n dim: '\\x1b[2m',\n red: '\\x1b[31m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n magenta: '\\x1b[35m',\n cyan: '\\x1b[36m',\n white: '\\x1b[37m',\n gray: '\\x1b[90m',\n bgRed: '\\x1b[41m',\n bgYellow: '\\x1b[43m',\n};\n\n// Log level colors and symbols\nconst levelConfig = {\n [LogLevel.TRACE]: { color: colors.gray, symbol: '○', name: 'TRACE' },\n [LogLevel.DEBUG]: { color: colors.blue, symbol: '●', name: 'DEBUG' },\n [LogLevel.INFO]: { color: colors.green, symbol: '●', name: 'INFO ' },\n [LogLevel.WARN]: { color: colors.yellow, symbol: '▲', name: 'WARN ' },\n [LogLevel.ERROR]: { color: colors.red, symbol: '✖', name: 'ERROR' },\n [LogLevel.FATAL]: {\n color: colors.bgRed + colors.white,\n symbol: '💀',\n name: 'FATAL',\n },\n};\n\nexport class DevFormatter implements Formatter {\n private enableColors: boolean;\n\n constructor(enableColors = true) {\n this.enableColors = enableColors;\n }\n\n format(entry: LogEntry): string {\n const parts: string[] = [];\n const config = levelConfig[entry.level];\n\n // Timestamp\n const timestamp = this.formatTimestamp(entry.timestamp);\n parts.push(this.colorize(timestamp, colors.gray));\n\n // Log level with symbol\n const levelText = `${config.symbol} ${config.name}`;\n parts.push(this.colorize(levelText, config.color));\n\n // Trace information\n if (entry.traceId) {\n const traceInfo = this.formatTraceInfo(entry);\n parts.push(this.colorize(traceInfo, colors.cyan));\n }\n\n // Main message\n parts.push(this.colorize(entry.message, colors.white));\n\n // Duration (if present)\n if (entry.duration !== undefined) {\n const durationText = `(${this.formatDuration(entry.duration)})`;\n parts.push(this.colorize(durationText, colors.magenta));\n }\n\n let output = parts.join(' ');\n\n // Context and metadata (on new lines for readability)\n if (entry.context && Object.keys(entry.context).length > 0) {\n output += '\\n' + this.formatContext(entry.context);\n }\n\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n output += '\\n' + this.formatMetadata(entry.metadata);\n }\n\n // Error details\n if (entry.error) {\n output += '\\n' + this.formatError(entry.error);\n }\n\n // Tags\n if (entry.tags && entry.tags.length > 0) {\n const tagsText = entry.tags.map((tag) => `#${tag}`).join(' ');\n output += '\\n' + this.colorize(`Tags: ${tagsText}`, colors.blue);\n }\n\n return output;\n }\n\n private formatTimestamp(timestamp: Date): string {\n return timestamp.toISOString().substring(11, 23); // Just time with milliseconds\n }\n\n private formatTraceInfo(entry: LogEntry): string {\n const parts = [`trace:${entry.traceId?.substring(0, 8) || 'unknown'}`];\n if (entry.spanId && entry.spanId.length >= 8) {\n parts.push(`span:${entry.spanId.substring(0, 8)}`);\n }\n if (entry.parentId && entry.parentId.length >= 8) {\n parts.push(`parent:${entry.parentId.substring(0, 8)}`);\n }\n return `[${parts.join('|')}]`;\n }\n\n private formatDuration(duration: number): string {\n if (duration < 1) {\n return `${(duration * 1000).toFixed(0)}μs`;\n } else if (duration < 1000) {\n return `${duration.toFixed(2)}ms`;\n } else {\n return `${(duration / 1000).toFixed(2)}s`;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatContext(context: Record<string, any>): string {\n const formatted = this.formatObject(context, 2);\n return this.colorize(`Context: ${formatted}`, colors.cyan);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatMetadata(metadata: Record<string, any>): string {\n const formatted = this.formatObject(metadata, 2);\n return this.colorize(`Metadata: ${formatted}`, colors.blue);\n }\n\n private formatError(error: Error): string {\n let output = this.colorize(\n `Error: ${error.name}: ${error.message}`,\n colors.red\n );\n if (error.stack) {\n const stackLines = error.stack.split('\\n').slice(1, 6); // First 5 stack frames\n const indentedStack = stackLines.map((line) => ` ${line}`).join('\\n');\n output += '\\n' + this.colorize(indentedStack, colors.gray);\n }\n return output;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatObject(obj: Record<string, any>, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const entries = Object.entries(obj);\n\n if (entries.length === 0) return '{}';\n\n if (entries[0] && typeof entries[0][1] !== 'object') {\n return `{ ${entries[0][0]}: ${this.formatValue(entries[0][1])} }`;\n }\n\n const formatted = entries\n .map(([key, value]) => {\n return `${spaces} ${key}: ${this.formatValue(value, indent + 2)}`;\n })\n .join('\\n');\n\n return `{\\n${formatted}\\n${spaces}}`;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatValue(value: any, indent = 0): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') return `\"${value}\"`;\n if (typeof value === 'boolean' || typeof value === 'number')\n return String(value);\n if (value instanceof Date) return value.toISOString();\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]';\n return `[${value.map((v) => this.formatValue(v)).join(', ')}]`;\n }\n if (typeof value === 'object') {\n return this.formatObject(value, indent);\n }\n return String(value);\n }\n\n private colorize(text: string, color: string): string {\n if (!this.enableColors) return text;\n return `${color}${text}${colors.reset}`;\n }\n}\n\nexport class ProductionFormatter implements Formatter {\n format(entry: LogEntry): string {\n const logObject: LogEntry = {\n timestamp: entry.timestamp,\n level: entry.level,\n message: entry.message,\n };\n\n // Add trace information\n if (entry.traceId) {\n logObject.traceId = entry.traceId;\n }\n if (entry.spanId) {\n logObject.spanId = entry.spanId;\n }\n if (entry.parentId) {\n logObject.parentId = entry.parentId;\n }\n\n // Add timing information\n if (entry.duration !== undefined) {\n logObject.duration = entry.duration;\n }\n\n // Add context and metadata\n if (entry.context && Object.keys(entry.context).length > 0) {\n logObject.context = entry.context;\n }\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n logObject.metadata = entry.metadata;\n }\n\n // Add error information\n if (entry.error) {\n logObject.error = {\n name: entry.error.name,\n message: entry.error.message,\n stack: entry.error.stack,\n };\n }\n\n // Add tags\n if (entry.tags && entry.tags.length > 0) {\n logObject.tags = entry.tags;\n }\n\n return JSON.stringify(logObject);\n }\n}\n\nexport class CustomFormatter implements Formatter {\n private template: string;\n private dateFormat: (date: Date) => string;\n\n constructor(\n template = '{timestamp} [{level}] {message}',\n dateFormat?: (date: Date) => string\n ) {\n this.template = template;\n this.dateFormat = dateFormat || ((date: Date) => date.toISOString());\n }\n\n format(entry: LogEntry): string {\n const levelName = LogLevel[entry.level];\n const timestamp = this.dateFormat(entry.timestamp);\n\n let formatted = this.template\n .replace('{timestamp}', timestamp)\n .replace('{level}', levelName)\n .replace('{message}', entry.message)\n .replace('{traceId}', entry.traceId || '')\n .replace('{spanId}', entry.spanId || '')\n .replace('{duration}', entry.duration?.toString() || '');\n\n // Handle context and metadata placeholders\n if (entry.context) {\n formatted = formatted.replace('{context}', JSON.stringify(entry.context));\n }\n if (entry.metadata) {\n formatted = formatted.replace(\n '{metadata}',\n JSON.stringify(entry.metadata)\n );\n }\n\n return formatted;\n }\n}\n"],"mappings":";;;AAIA,MAAM,SAAS;CACb,OAAO;CACP,QAAQ;CACR,KAAK;CACL,KAAK;CACL,OAAO;CACP,QAAQ;CACR,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,UAAU;CACX;AAGD,MAAM,cAAc;EACjB,SAAS,QAAQ;EAAE,OAAO,OAAO;EAAM,QAAQ;EAAK,MAAM;EAAS;EACnE,SAAS,QAAQ;EAAE,OAAO,OAAO;EAAM,QAAQ;EAAK,MAAM;EAAS;EACnE,SAAS,OAAO;EAAE,OAAO,OAAO;EAAO,QAAQ;EAAK,MAAM;EAAS;EACnE,SAAS,OAAO;EAAE,OAAO,OAAO;EAAQ,QAAQ;EAAK,MAAM;EAAS;EACpE,SAAS,QAAQ;EAAE,OAAO,OAAO;EAAK,QAAQ;EAAK,MAAM;EAAS;EAClE,SAAS,QAAQ;EAChB,OAAO,OAAO,QAAQ,OAAO;EAC7B,QAAQ;EACR,MAAM;EACP;CACF;AAED,IAAa,eAAb,MAA+C;CAC7C,AAAQ;CAER,YAAY,eAAe,MAAM;AAC/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AW,OAAO,KAAK,MAAM,QAAQ,CAAC,SAAS,EACvD,WAAU,UAAU,MAAM;AAE5B,MAAI,MAAM,YAAY,OAAO,KAAK,MAAM,SAAS,CAAC,SAAS,EACzD,WAAU,WAAW,MAAM;AAI7B,MAAI,MAAM,MACR,WAAU,QAAQ;GAChB,MAAM,MAAM,MAAM;GAClB,SAAS,MAAM,MAAM;GACrB,OAAO,MAAM,MAAM;GACpB;AAIH,MAAI,MAAM,QAAQ,MAAM,KAAK,SAAS,EACpC,WAAU,OAAO,MAAM;AAGzB,SAAO,KAAK,UAAU,UAAU;;;AAIpC,IAAa,kBAAb,MAAkD;CAChD,AAAQ;CACR,AAAQ;CAER,YACE,WAAW,mCACX,YACA;AACA,OAAK,WAAW;AAChB,OAAK,aAAa,gBAAgB,SAAe,KAAK,aAAa;;CAGrE,OAAO,OAAyB;EAC9B,MAAM,YAAY,SAAS,MAAM;EACjC,MAAM,YAAY,KAAK,WAAW,MAAM,UAAU;EAElD,IAAI,YAAY,KAAK,SAClB,QAAQ,eAAe,UAAU,CACjC,QAAQ,WAAW,UAAU,CAC7B,QAAQ,aAAa,MAAM,QAAQ,CACnC,QAAQ,aAAa,MAAM,WAAW,GAAG,CACzC,QAAQ,YAAY,MAAM,UAAU,GAAG,CACvC,QAAQ,cAAc,MAAM,UAAU,UAAU,IAAI,GAAG;AAG1D,MAAI,MAAM,QACR,aAAY,UAAU,QAAQ,aAAa,KAAK,UAAU,MAAM,QAAQ,CAAC;AAE3E,MAAI,MAAM,SACR,aAAY,UAAU,QACpB,cACA,KAAK,UAAU,MAAM,SAAS,CAC/B;AAGH,SAAO"}
1
+ {"version":3,"file":"formatters.mjs","names":[],"sources":["../src/formatters.ts"],"sourcesContent":["import type { Formatter, LogEntry } from './types';\nimport { LogLevel } from './types';\n\n// ANSI color codes for terminal output\nconst colors = {\n reset: '\\x1b[0m',\n bright: '\\x1b[1m',\n dim: '\\x1b[2m',\n red: '\\x1b[31m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n magenta: '\\x1b[35m',\n cyan: '\\x1b[36m',\n white: '\\x1b[37m',\n gray: '\\x1b[90m',\n bgRed: '\\x1b[41m',\n bgYellow: '\\x1b[43m',\n};\n\n// Log level colors and symbols\nconst levelConfig = {\n [LogLevel.TRACE]: { color: colors.gray, symbol: '○', name: 'TRACE' },\n [LogLevel.DEBUG]: { color: colors.blue, symbol: '●', name: 'DEBUG' },\n [LogLevel.INFO]: { color: colors.green, symbol: '●', name: 'INFO ' },\n [LogLevel.WARN]: { color: colors.yellow, symbol: '▲', name: 'WARN ' },\n [LogLevel.ERROR]: { color: colors.red, symbol: '✖', name: 'ERROR' },\n [LogLevel.FATAL]: {\n color: colors.bgRed + colors.white,\n symbol: '💀',\n name: 'FATAL',\n },\n};\n\nexport class DevFormatter implements Formatter {\n private enableColors: boolean;\n\n constructor(enableColors = true) {\n this.enableColors = enableColors;\n }\n\n format(entry: LogEntry): string {\n const parts: string[] = [];\n const config = levelConfig[entry.level];\n\n // Timestamp\n const timestamp = this.formatTimestamp(entry.timestamp);\n parts.push(this.colorize(timestamp, colors.gray));\n\n // Log level with symbol\n const levelText = `${config.symbol} ${config.name}`;\n parts.push(this.colorize(levelText, config.color));\n\n // Trace information\n if (entry.traceId) {\n const traceInfo = this.formatTraceInfo(entry);\n parts.push(this.colorize(traceInfo, colors.cyan));\n }\n\n // Main message\n parts.push(this.colorize(entry.message, colors.white));\n\n // Duration (if present)\n if (entry.duration !== undefined) {\n const durationText = `(${this.formatDuration(entry.duration)})`;\n parts.push(this.colorize(durationText, colors.magenta));\n }\n\n let output = parts.join(' ');\n\n // Context and metadata (on new lines for readability)\n if (entry.context && Object.keys(entry.context).length > 0) {\n output += '\\n' + this.formatContext(entry.context);\n }\n\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n output += '\\n' + this.formatMetadata(entry.metadata);\n }\n\n // Error details\n if (entry.error) {\n output += '\\n' + this.formatError(entry.error);\n }\n\n // Tags\n if (entry.tags && entry.tags.length > 0) {\n const tagsText = entry.tags.map((tag) => `#${tag}`).join(' ');\n output += '\\n' + this.colorize(`Tags: ${tagsText}`, colors.blue);\n }\n\n return output;\n }\n\n private formatTimestamp(timestamp: Date): string {\n return timestamp.toISOString().substring(11, 23); // Just time with milliseconds\n }\n\n private formatTraceInfo(entry: LogEntry): string {\n const parts = [`trace:${entry.traceId?.substring(0, 8) || 'unknown'}`];\n if (entry.spanId && entry.spanId.length >= 8) {\n parts.push(`span:${entry.spanId.substring(0, 8)}`);\n }\n if (entry.parentId && entry.parentId.length >= 8) {\n parts.push(`parent:${entry.parentId.substring(0, 8)}`);\n }\n return `[${parts.join('|')}]`;\n }\n\n private formatDuration(duration: number): string {\n if (duration < 1) {\n return `${(duration * 1000).toFixed(0)}μs`;\n } else if (duration < 1000) {\n return `${duration.toFixed(2)}ms`;\n } else {\n return `${(duration / 1000).toFixed(2)}s`;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatContext(context: Record<string, any>): string {\n const formatted = this.formatObject(context, 2);\n return this.colorize(`Context: ${formatted}`, colors.cyan);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatMetadata(metadata: Record<string, any>): string {\n const formatted = this.formatObject(metadata, 2);\n return this.colorize(`Metadata: ${formatted}`, colors.blue);\n }\n\n private formatError(error: Error): string {\n let output = this.colorize(\n `Error: ${error.name}: ${error.message}`,\n colors.red\n );\n if (error.stack) {\n const stackLines = error.stack.split('\\n').slice(1, 6); // First 5 stack frames\n const indentedStack = stackLines.map((line) => ` ${line}`).join('\\n');\n output += '\\n' + this.colorize(indentedStack, colors.gray);\n }\n return output;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatObject(obj: Record<string, any>, indent = 0): string {\n const spaces = ' '.repeat(indent);\n const entries = Object.entries(obj);\n\n if (entries.length === 0) return '{}';\n\n if (entries[0] && typeof entries[0][1] !== 'object') {\n return `{ ${entries[0][0]}: ${this.formatValue(entries[0][1])} }`;\n }\n\n const formatted = entries\n .map(([key, value]) => {\n return `${spaces} ${key}: ${this.formatValue(value, indent + 2)}`;\n })\n .join('\\n');\n\n return `{\\n${formatted}\\n${spaces}}`;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private formatValue(value: any, indent = 0): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (typeof value === 'string') return `\"${value}\"`;\n if (typeof value === 'boolean' || typeof value === 'number')\n return String(value);\n if (value instanceof Date) return value.toISOString();\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]';\n return `[${value.map((v) => this.formatValue(v)).join(', ')}]`;\n }\n if (typeof value === 'object') {\n return this.formatObject(value, indent);\n }\n return String(value);\n }\n\n private colorize(text: string, color: string): string {\n if (!this.enableColors) return text;\n return `${color}${text}${colors.reset}`;\n }\n}\n\nexport class ProductionFormatter implements Formatter {\n format(entry: LogEntry): string {\n const logObject: LogEntry = {\n timestamp: entry.timestamp,\n level: entry.level,\n message: entry.message,\n };\n\n // Add trace information\n if (entry.traceId) {\n logObject.traceId = entry.traceId;\n }\n if (entry.spanId) {\n logObject.spanId = entry.spanId;\n }\n if (entry.parentId) {\n logObject.parentId = entry.parentId;\n }\n\n // Add timing information\n if (entry.duration !== undefined) {\n logObject.duration = entry.duration;\n }\n\n // Add context and metadata\n if (entry.context && Object.keys(entry.context).length > 0) {\n logObject.context = entry.context;\n }\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n logObject.metadata = entry.metadata;\n }\n\n // Add error information\n if (entry.error) {\n logObject.error = {\n name: entry.error.name,\n message: entry.error.message,\n stack: entry.error.stack,\n };\n }\n\n // Add tags\n if (entry.tags && entry.tags.length > 0) {\n logObject.tags = entry.tags;\n }\n\n return JSON.stringify(logObject);\n }\n}\n\nexport class CustomFormatter implements Formatter {\n private template: string;\n private dateFormat: (date: Date) => string;\n\n constructor(\n template = '{timestamp} [{level}] {message}',\n dateFormat?: (date: Date) => string\n ) {\n this.template = template;\n this.dateFormat = dateFormat || ((date: Date) => date.toISOString());\n }\n\n format(entry: LogEntry): string {\n const levelName = LogLevel[entry.level];\n const timestamp = this.dateFormat(entry.timestamp);\n\n let formatted = this.template\n .replace('{timestamp}', timestamp)\n .replace('{level}', levelName)\n .replace('{message}', entry.message)\n .replace('{traceId}', entry.traceId || '')\n .replace('{spanId}', entry.spanId || '')\n .replace('{duration}', entry.duration?.toString() || '');\n\n // Handle context and metadata placeholders\n if (entry.context) {\n formatted = formatted.replace('{context}', JSON.stringify(entry.context));\n }\n if (entry.metadata) {\n formatted = formatted.replace(\n '{metadata}',\n JSON.stringify(entry.metadata)\n );\n }\n\n return formatted;\n }\n}\n"],"mappings":";;;AAIA,MAAM,SAAS;CACb,OAAO;CACP,QAAQ;CACR,KAAK;CACL,KAAK;CACL,OAAO;CACP,QAAQ;CACR,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,UAAU;CACX;AAGD,MAAM,cAAc;EACjB,SAAS,QAAQ;EAAE,OAAO,OAAO;EAAM,QAAQ;EAAK,MAAM;EAAS;EACnE,SAAS,QAAQ;EAAE,OAAO,OAAO;EAAM,QAAQ;EAAK,MAAM;EAAS;EACnE,SAAS,OAAO;EAAE,OAAO,OAAO;EAAO,QAAQ;EAAK,MAAM;EAAS;EACnE,SAAS,OAAO;EAAE,OAAO,OAAO;EAAQ,QAAQ;EAAK,MAAM;EAAS;EACpE,SAAS,QAAQ;EAAE,OAAO,OAAO;EAAK,QAAQ;EAAK,MAAM;EAAS;EAClE,SAAS,QAAQ;EAChB,OAAO,OAAO,QAAQ,OAAO;EAC7B,QAAQ;EACR,MAAM;EACP;CACF;AAED,IAAa,eAAb,MAA+C;CAC7C,AAAQ;CAER,YAAY,eAAe,MAAM;AAC/B,OAAK,eAAe;;CAGtB,OAAO,OAAyB;EAC9B,MAAM,QAAkB,EAAE;EAC1B,MAAM,SAAS,YAAY,MAAM;EAGjC,MAAM,YA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S,CAAC,SAAS,EACzD,WAAU,WAAW,MAAM;AAI7B,MAAI,MAAM,MACR,WAAU,QAAQ;GAChB,MAAM,MAAM,MAAM;GAClB,SAAS,MAAM,MAAM;GACrB,OAAO,MAAM,MAAM;GACpB;AAIH,MAAI,MAAM,QAAQ,MAAM,KAAK,SAAS,EACpC,WAAU,OAAO,MAAM;AAGzB,SAAO,KAAK,UAAU,UAAU;;;AAIpC,IAAa,kBAAb,MAAkD;CAChD,AAAQ;CACR,AAAQ;CAER,YACE,WAAW,mCACX,YACA;AACA,OAAK,WAAW;AAChB,OAAK,aAAa,gBAAgB,SAAe,KAAK,aAAa;;CAGrE,OAAO,OAAyB;EAC9B,MAAM,YAAY,SAAS,MAAM;EACjC,MAAM,YAAY,KAAK,WAAW,MAAM,UAAU;EAElD,IAAI,YAAY,KAAK,SAClB,QAAQ,eAAe,UAAU,CACjC,QAAQ,WAAW,UAAU,CAC7B,QAAQ,aAAa,MAAM,QAAQ,CACnC,QAAQ,aAAa,MAAM,WAAW,GAAG,CACzC,QAAQ,YAAY,MAAM,UAAU,GAAG,CACvC,QAAQ,cAAc,MAAM,UAAU,UAAU,IAAI,GAAG;AAG1D,MAAI,MAAM,QACR,aAAY,UAAU,QAAQ,aAAa,KAAK,UAAU,MAAM,QAAQ,CAAC;AAE3E,MAAI,MAAM,SACR,aAAY,UAAU,QACpB,cACA,KAAK,UAAU,MAAM,SAAS,CAC/B;AAGH,SAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"logger.browser.mjs","names":["entry: LogEntry"],"sources":["../src/logger.browser.ts"],"sourcesContent":["import type {\n ContextData,\n Formatter,\n LogEntry,\n LoggerConfig,\n TraceMethod,\n TracingOptions,\n} from './types';\nimport { LogLevel } from './types';\nimport { LogContext } from './context.browser';\nimport { Tracer } from './tracer.browser';\nimport { Timer, TimerManager } from './timer';\nimport { DevFormatter, ProductionFormatter } from './formatters';\n\nexport class Logger {\n private config: LoggerConfig;\n private formatter: Formatter;\n private context: LogContext;\n private tracer: Tracer;\n private timerManager: TimerManager;\n\n constructor(config?: Partial<LoggerConfig>) {\n this.config = {\n level: LogLevel.INFO,\n environment:\n (process.env.NODE_ENV as LoggerConfig['environment']) || 'development',\n enableTracing: true,\n enableTiming: true,\n enableContext: true,\n enableColors: true,\n maxContextDepth: 10,\n timestampFormat: 'iso',\n ...config,\n };\n\n this.context = LogContext.getInstance();\n this.tracer = new Tracer();\n this.timerManager = new TimerManager();\n\n // Set up formatter based on environment\n this.formatter =\n this.config.environment === 'production'\n ? new ProductionFormatter()\n : new DevFormatter(this.config.enableColors);\n }\n\n // Core logging methods\n traceLog(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.TRACE, message, metadata);\n }\n\n debug(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.DEBUG, message, metadata);\n }\n\n info(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.INFO, message, metadata);\n }\n\n warn(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.WARN, message, metadata);\n }\n\n error(\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n this.log(LogLevel.ERROR, message, metadata, error);\n }\n\n fatal(\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n this.log(LogLevel.FATAL, message, metadata, error);\n }\n\n // Context management\n withContext<T>(context: ContextData, fn: () => T): T {\n return this.context.run(context, fn);\n }\n\n extendContext<T>(additionalContext: Partial<ContextData>, fn: () => T): T {\n return this.context.extend(additionalContext, fn) as T;\n }\n\n setContext(key: string, value: unknown): void {\n this.context.set(key, value);\n }\n\n getContext(): ContextData {\n return this.context.getContext();\n }\n\n // Tracing functionality\n trace: TraceMethod = async <T>(\n options: TracingOptions,\n fn: () => T | Promise<T>\n ): Promise<T> => {\n if (!this.config.enableTracing) {\n return await fn();\n }\n\n return this.tracer.trace(options, fn);\n };\n\n getTraceId(): string | undefined {\n return this.tracer.getCurrentTrace()?.traceId;\n }\n\n startSpan(options: TracingOptions) {\n if (!this.config.enableTracing) {\n return null;\n }\n return this.tracer.startSpan(options);\n }\n\n finishSpan(spanId: string): number | undefined {\n if (!this.config.enableTracing) {\n return undefined;\n }\n return this.tracer.finishSpan(spanId);\n }\n\n addTraceMetadata(key: string, value: unknown): void {\n if (this.config.enableTracing) {\n this.tracer.addMetadata(key, value);\n }\n }\n\n addTraceTags(...tags: string[]): void {\n if (this.config.enableTracing) {\n this.tracer.addTags(...tags);\n }\n }\n\n // Timer functionality\n startTimer(id?: string): Timer | null {\n if (!this.config.enableTiming) {\n return null;\n }\n return this.timerManager.start(id);\n }\n\n stopTimer(id: string): number | undefined {\n if (!this.config.enableTiming) {\n return undefined;\n }\n return this.timerManager.stop(id);\n }\n\n getTimer(id: string): Timer | undefined {\n return this.timerManager.get(id);\n }\n\n // Utility methods\n child(context: Partial<ContextData>): Logger {\n const childLogger = new Logger(this.config);\n Object.entries(context).forEach(([key, value]) => {\n childLogger.setContext(key, value);\n });\n return childLogger;\n }\n\n setLevel(level: LogLevel): void {\n this.config.level = level;\n }\n\n setFormatter(formatter: Formatter): void {\n this.formatter = formatter;\n }\n\n // Performance profiling\n async profile<T>(\n operationName: string,\n fn: () => T | Promise<T>,\n options?: { logResult?: boolean; logLevel?: LogLevel }\n ): Promise<T> {\n const timer = this.startTimer(`profile-${operationName}`);\n const startTime = performance.now();\n\n try {\n const result = await this.tracer.trace(\n {\n operationType: 'custom',\n operationName: `profile:${operationName}`,\n autoTiming: true,\n },\n fn\n );\n\n const duration = performance.now() - startTime;\n timer?.stop();\n\n const logLevel = options?.logLevel || LogLevel.DEBUG;\n this.log(logLevel, `Profile: ${operationName} completed`, {\n operation: operationName,\n duration: `${duration.toFixed(2)}ms`,\n result: options?.logResult ? result : '[result hidden]',\n });\n\n return result;\n } catch (error) {\n const duration = performance.now() - startTime;\n timer?.stop();\n\n this.error(\n `Profile: ${operationName} failed`,\n {\n operation: operationName,\n duration: `${duration.toFixed(2)}ms`,\n error: (error as Error).message,\n },\n error as Error\n );\n\n throw error;\n }\n }\n\n // HTTP request logging helper\n logRequest(\n method: string,\n url: string,\n statusCode?: number,\n duration?: number\n ): void {\n const level = this.getHttpLogLevel(statusCode);\n const message = `${method.toUpperCase()} ${url}${statusCode ? ` ${statusCode}` : ''}`;\n\n this.log(level, message, {\n method,\n url,\n statusCode,\n duration: duration ? `${duration.toFixed(2)}ms` : undefined,\n type: 'http_request',\n });\n }\n\n // Flush any pending logs (useful for graceful shutdown)\n async flush(): Promise<void> {\n this.timerManager.clear();\n }\n\n // Get logger statistics\n getStats(): {\n activeTimers: number;\n activeSpans: number;\n config: LoggerConfig;\n } {\n return {\n activeTimers: this.timerManager.getActive().length,\n activeSpans: this.tracer.getActiveSpans().length,\n config: { ...this.config },\n };\n }\n\n // Output method (can be overridden for custom outputs)\n protected output(message: string, level: LogLevel): void {\n if (level >= LogLevel.ERROR) {\n console.error(message);\n } else {\n console.log(message);\n }\n }\n\n // Core log method\n private log(\n level: LogLevel,\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n if (level < this.config.level) {\n return; // Skip logs below configured level\n }\n\n const currentTrace = this.config.enableTracing\n ? this.tracer.getCurrentTrace()\n : undefined;\n const contextData = this.config.enableContext\n ? this.context.getContext()\n : undefined;\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n traceId: currentTrace?.traceId,\n parentId: currentTrace?.parentId,\n spanId: currentTrace?.spanId,\n context: contextData,\n metadata,\n error,\n tags: currentTrace?.tags,\n };\n\n // Add duration if we're in a traced operation\n if (currentTrace?.metadata?.duration) {\n entry.duration = currentTrace.metadata.duration as number;\n }\n\n const formatted = this.formatter.format(entry);\n this.output(formatted, level);\n }\n\n private getHttpLogLevel(statusCode?: number): LogLevel {\n if (!statusCode) return LogLevel.INFO;\n if (statusCode >= 500) return LogLevel.ERROR;\n if (statusCode >= 400) return LogLevel.WARN;\n return LogLevel.INFO;\n }\n}\n"],"mappings":";;;;;;;AAcA,IAAa,SAAb,MAAa,OAA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c;GACvB,UAAU,cAAc;GACxB,QAAQ,cAAc;GACtB,SAAS;GACT;GACA;GACA,MAAM,cAAc;GACrB;AAGD,MAAI,cAAc,UAAU,SAC1B,OAAM,WAAW,aAAa,SAAS;EAGzC,MAAM,YAAY,KAAK,UAAU,OAAO,MAAM;AAC9C,OAAK,OAAO,WAAW,MAAM;;CAG/B,AAAQ,gBAAgB,YAA+B;AACrD,MAAI,CAAC,WAAY,QAAO,SAAS;AACjC,MAAI,cAAc,IAAK,QAAO,SAAS;AACvC,MAAI,cAAc,IAAK,QAAO,SAAS;AACvC,SAAO,SAAS"}
1
+ {"version":3,"file":"logger.browser.mjs","names":[],"sources":["../src/logger.browser.ts"],"sourcesContent":["import type {\n ContextData,\n Formatter,\n LogEntry,\n LoggerConfig,\n TraceMethod,\n TracingOptions,\n} from './types';\nimport { LogLevel } from './types';\nimport { LogContext } from './context.browser';\nimport { Tracer } from './tracer.browser';\nimport { Timer, TimerManager } from './timer';\nimport { DevFormatter, ProductionFormatter } from './formatters';\n\nexport class Logger {\n private config: LoggerConfig;\n private formatter: Formatter;\n private context: LogContext;\n private tracer: Tracer;\n private timerManager: TimerManager;\n\n constructor(config?: Partial<LoggerConfig>) {\n this.config = {\n level: LogLevel.INFO,\n environment:\n (process.env.NODE_ENV as LoggerConfig['environment']) || 'development',\n enableTracing: true,\n enableTiming: true,\n enableContext: true,\n enableColors: true,\n maxContextDepth: 10,\n timestampFormat: 'iso',\n ...config,\n };\n\n this.context = LogContext.getInstance();\n this.tracer = new Tracer();\n this.timerManager = new TimerManager();\n\n // Set up formatter based on environment\n this.formatter =\n this.config.environment === 'production'\n ? new ProductionFormatter()\n : new DevFormatter(this.config.enableColors);\n }\n\n // Core logging methods\n traceLog(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.TRACE, message, metadata);\n }\n\n debug(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.DEBUG, message, metadata);\n }\n\n info(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.INFO, message, metadata);\n }\n\n warn(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.WARN, message, metadata);\n }\n\n error(\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n this.log(LogLevel.ERROR, message, metadata, error);\n }\n\n fatal(\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n this.log(LogLevel.FATAL, message, metadata, error);\n }\n\n // Context management\n withContext<T>(context: ContextData, fn: () => T): T {\n return this.context.run(context, fn);\n }\n\n extendContext<T>(additionalContext: Partial<ContextData>, fn: () => T): T {\n return this.context.extend(additionalContext, fn) as T;\n }\n\n setContext(key: string, value: unknown): void {\n this.context.set(key, value);\n }\n\n getContext(): ContextData {\n return this.context.getContext();\n }\n\n // Tracing functionality\n trace: TraceMethod = async <T>(\n options: TracingOptions,\n fn: () => T | Promise<T>\n ): Promise<T> => {\n if (!this.config.enableTracing) {\n return await fn();\n }\n\n return this.tracer.trace(options, fn);\n };\n\n getTraceId(): string | undefined {\n return this.tracer.getCurrentTrace()?.traceId;\n }\n\n startSpan(options: TracingOptions) {\n if (!this.config.enableTracing) {\n return null;\n }\n return this.tracer.startSpan(options);\n }\n\n finishSpan(spanId: string): number | undefined {\n if (!this.config.enableTracing) {\n return undefined;\n }\n return this.tracer.finishSpan(spanId);\n }\n\n addTraceMetadata(key: string, value: unknown): void {\n if (this.config.enableTracing) {\n this.tracer.addMetadata(key, value);\n }\n }\n\n addTraceTags(...tags: string[]): void {\n if (this.config.enableTracing) {\n this.tracer.addTags(...tags);\n }\n }\n\n // Timer functionality\n startTimer(id?: string): Timer | null {\n if (!this.config.enableTiming) {\n return null;\n }\n return this.timerManager.start(id);\n }\n\n stopTimer(id: string): number | undefined {\n if (!this.config.enableTiming) {\n return undefined;\n }\n return this.timerManager.stop(id);\n }\n\n getTimer(id: string): Timer | undefined {\n return this.timerManager.get(id);\n }\n\n // Utility methods\n child(context: Partial<ContextData>): Logger {\n const childLogger = new Logger(this.config);\n Object.entries(context).forEach(([key, value]) => {\n childLogger.setContext(key, value);\n });\n return childLogger;\n }\n\n setLevel(level: LogLevel): void {\n this.config.level = level;\n }\n\n setFormatter(formatter: Formatter): void {\n this.formatter = formatter;\n }\n\n // Performance profiling\n async profile<T>(\n operationName: string,\n fn: () => T | Promise<T>,\n options?: { logResult?: boolean; logLevel?: LogLevel }\n ): Promise<T> {\n const timer = this.startTimer(`profile-${operationName}`);\n const startTime = performance.now();\n\n try {\n const result = await this.tracer.trace(\n {\n operationType: 'custom',\n operationName: `profile:${operationName}`,\n autoTiming: true,\n },\n fn\n );\n\n const duration = performance.now() - startTime;\n timer?.stop();\n\n const logLevel = options?.logLevel || LogLevel.DEBUG;\n this.log(logLevel, `Profile: ${operationName} completed`, {\n operation: operationName,\n duration: `${duration.toFixed(2)}ms`,\n result: options?.logResult ? result : '[result hidden]',\n });\n\n return result;\n } catch (error) {\n const duration = performance.now() - startTime;\n timer?.stop();\n\n this.error(\n `Profile: ${operationName} failed`,\n {\n operation: operationName,\n duration: `${duration.toFixed(2)}ms`,\n error: (error as Error).message,\n },\n error as Error\n );\n\n throw error;\n }\n }\n\n // HTTP request logging helper\n logRequest(\n method: string,\n url: string,\n statusCode?: number,\n duration?: number\n ): void {\n const level = this.getHttpLogLevel(statusCode);\n const message = `${method.toUpperCase()} ${url}${statusCode ? ` ${statusCode}` : ''}`;\n\n this.log(level, message, {\n method,\n url,\n statusCode,\n duration: duration ? `${duration.toFixed(2)}ms` : undefined,\n type: 'http_request',\n });\n }\n\n // Flush any pending logs (useful for graceful shutdown)\n async flush(): Promise<void> {\n this.timerManager.clear();\n }\n\n // Get logger statistics\n getStats(): {\n activeTimers: number;\n activeSpans: number;\n config: LoggerConfig;\n } {\n return {\n activeTimers: this.timerManager.getActive().length,\n activeSpans: this.tracer.getActiveSpans().length,\n config: { ...this.config },\n };\n }\n\n // Output method (can be overridden for custom outputs)\n protected output(message: string, level: LogLevel): void {\n if (level >= LogLevel.ERROR) {\n console.error(message);\n } else {\n console.log(message);\n }\n }\n\n // Core log method\n private log(\n level: LogLevel,\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n if (level < this.config.level) {\n return; // Skip logs below configured level\n }\n\n const currentTrace = this.config.enableTracing\n ? this.tracer.getCurrentTrace()\n : undefined;\n const contextData = this.config.enableContext\n ? this.context.getContext()\n : undefined;\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n traceId: currentTrace?.traceId,\n parentId: currentTrace?.parentId,\n spanId: currentTrace?.spanId,\n context: contextData,\n metadata,\n error,\n tags: currentTrace?.tags,\n };\n\n // Add duration if we're in a traced operation\n if (currentTrace?.metadata?.duration) {\n entry.duration = currentTrace.metadata.duration as number;\n }\n\n const formatted = this.formatter.format(entry);\n this.output(formatted, level);\n }\n\n private getHttpLogLevel(statusCode?: number): LogLevel {\n if (!statusCode) return LogLevel.INFO;\n if (statusCode >= 500) return LogLevel.ERROR;\n if (statusCode >= 400) return LogLevel.WARN;\n return LogLevel.INFO;\n }\n}\n"],"mappings":";;;;;;;AAcA,IAAa,SAAb,MAAa,OAAO;CAClB,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,QAAgC;AAC1C,OAAK,SAAS;GACZ,OAAO,SAAS;GAChB,aACG,QAAQ,IAAI,YAA4C;GAC3D,eAAe;GACf,cAAc;GACd,eAAe;GACf,cAAc;GACd,iBAAiB;GACjB,iBAAiB;GACjB,GAAG;GACJ;AAED,OAAK,UAAU,WAAW,aAAa;AACvC,OAAK,SAAS,IAAI,QAAQ;AAC1B,OAAK,eAAe,IAAI,cAAc;AAGtC,OAAK,YACH,KAAK,OAAO,gBAAgB,eACxB,IAAI,qBAAqB,GACzB,IAAI,aAAa,KAAK,OAAO,aAAa;;CAIlD,SAAS,SAAiB,UAA0C;AAClE,OAAK,IAAI,SAAS,OAAO,SAAS,SAAS;;CAG7C,MAAM,SAAiB,UAA0C;AAC/D,OAAK,IAAI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AO,SAAS;GACvB;GACA;GACA;GACA,UAAU,WAAW,GAAG,SAAS,QAAQ,EAAE,CAAC,MAAM;GAClD,MAAM;GACP,CAAC;;CAIJ,MAAM,QAAuB;AAC3B,OAAK,aAAa,OAAO;;CAI3B,WAIE;AACA,SAAO;GACL,cAAc,KAAK,aAAa,WAAW,CAAC;GAC5C,aAAa,KAAK,OAAO,gBAAgB,CAAC;GAC1C,QAAQ,EAAE,GAAG,KAAK,QAAQ;GAC3B;;CAIH,AAAU,OAAO,SAAiB,OAAuB;AACvD,MAAI,SAAS,SAAS,MACpB,SAAQ,MAAM,QAAQ;MAEtB,SAAQ,IAAI,QAAQ;;CAKxB,AAAQ,IACN,OACA,SACA,UACA,OACM;AACN,MAAI,QAAQ,KAAK,OAAO,MACtB;EAGF,MAAM,eAAe,KAAK,OAAO,gBAC7B,KAAK,OAAO,iBAAiB,GAC7B;EACJ,MAAM,cAAc,KAAK,OAAO,gBAC5B,KAAK,QAAQ,YAAY,GACzB;EAEJ,MAAM,QAAkB;GACtB;GACA;GACA,2BAAW,IAAI,MAAM;GACrB,SAAS,cAAc;GACvB,UAAU,cAAc;GACxB,QAAQ,cAAc;GACtB,SAAS;GACT;GACA;GACA,MAAM,cAAc;GACrB;AAGD,MAAI,cAAc,UAAU,SAC1B,OAAM,WAAW,aAAa,SAAS;EAGzC,MAAM,YAAY,KAAK,UAAU,OAAO,MAAM;AAC9C,OAAK,OAAO,WAAW,MAAM;;CAG/B,AAAQ,gBAAgB,YAA+B;AACrD,MAAI,CAAC,WAAY,QAAO,SAAS;AACjC,MAAI,cAAc,IAAK,QAAO,SAAS;AACvC,MAAI,cAAc,IAAK,QAAO,SAAS;AACvC,SAAO,SAAS"}
@@ -1 +1 @@
1
- {"version":3,"file":"logger.node.mjs","names":["entry: LogEntry"],"sources":["../src/logger.node.ts"],"sourcesContent":["import type {\n ContextData,\n Formatter,\n LogEntry,\n LoggerConfig,\n TraceMethod,\n TracingOptions,\n} from './types';\nimport { LogLevel } from './types';\nimport { LogContext } from './context.node';\nimport { Tracer } from './tracer.node';\nimport { Timer, TimerManager } from './timer';\nimport { DevFormatter, ProductionFormatter } from './formatters';\n\nexport class Logger {\n private config: LoggerConfig;\n private formatter: Formatter;\n private context: LogContext;\n private tracer: Tracer;\n private timerManager: TimerManager;\n\n constructor(config?: Partial<LoggerConfig>) {\n this.config = {\n level: LogLevel.INFO,\n environment:\n (process.env.NODE_ENV as LoggerConfig['environment']) || 'development',\n enableTracing: true,\n enableTiming: true,\n enableContext: true,\n enableColors: true,\n maxContextDepth: 10,\n timestampFormat: 'iso',\n ...config,\n };\n\n this.context = LogContext.getInstance();\n this.tracer = new Tracer();\n this.timerManager = new TimerManager();\n\n // Set up formatter based on environment\n this.formatter =\n this.config.environment === 'production'\n ? new ProductionFormatter()\n : new DevFormatter(this.config.enableColors);\n }\n\n // Core logging methods\n traceLog(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.TRACE, message, metadata);\n }\n\n debug(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.DEBUG, message, metadata);\n }\n\n info(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.INFO, message, metadata);\n }\n\n warn(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.WARN, message, metadata);\n }\n\n error(\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n this.log(LogLevel.ERROR, message, metadata, error);\n }\n\n fatal(\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n this.log(LogLevel.FATAL, message, metadata, error);\n }\n\n // Context management\n withContext<T>(context: ContextData, fn: () => T): T {\n return this.context.run(context, fn);\n }\n\n extendContext<T>(additionalContext: Partial<ContextData>, fn: () => T): T {\n return this.context.extend(additionalContext, fn) as T;\n }\n\n setContext(key: string, value: unknown): void {\n this.context.set(key, value);\n }\n\n getContext(): ContextData {\n return this.context.getContext();\n }\n\n // Tracing functionality\n trace: TraceMethod = async <T>(\n options: TracingOptions,\n fn: () => T | Promise<T>\n ): Promise<T> => {\n if (!this.config.enableTracing) {\n return await fn();\n }\n\n return this.tracer.trace(options, fn);\n };\n\n getTraceId(): string | undefined {\n return this.tracer.getCurrentTrace()?.traceId;\n }\n\n startSpan(options: TracingOptions) {\n if (!this.config.enableTracing) {\n return null;\n }\n return this.tracer.startSpan(options);\n }\n\n finishSpan(spanId: string): number | undefined {\n if (!this.config.enableTracing) {\n return undefined;\n }\n return this.tracer.finishSpan(spanId);\n }\n\n addTraceMetadata(key: string, value: unknown): void {\n if (this.config.enableTracing) {\n this.tracer.addMetadata(key, value);\n }\n }\n\n addTraceTags(...tags: string[]): void {\n if (this.config.enableTracing) {\n this.tracer.addTags(...tags);\n }\n }\n\n // Timer functionality\n startTimer(id?: string): Timer | null {\n if (!this.config.enableTiming) {\n return null;\n }\n return this.timerManager.start(id);\n }\n\n stopTimer(id: string): number | undefined {\n if (!this.config.enableTiming) {\n return undefined;\n }\n return this.timerManager.stop(id);\n }\n\n getTimer(id: string): Timer | undefined {\n return this.timerManager.get(id);\n }\n\n // Utility methods\n child(context: Partial<ContextData>): Logger {\n const childLogger = new Logger(this.config);\n Object.entries(context).forEach(([key, value]) => {\n childLogger.setContext(key, value);\n });\n return childLogger;\n }\n\n setLevel(level: LogLevel): void {\n this.config.level = level;\n }\n\n setFormatter(formatter: Formatter): void {\n this.formatter = formatter;\n }\n\n // Performance profiling\n async profile<T>(\n operationName: string,\n fn: () => T | Promise<T>,\n options?: { logResult?: boolean; logLevel?: LogLevel }\n ): Promise<T> {\n const timer = this.startTimer(`profile-${operationName}`);\n const startTime = performance.now();\n\n try {\n const result = await this.tracer.trace(\n {\n operationType: 'custom',\n operationName: `profile:${operationName}`,\n autoTiming: true,\n },\n fn\n );\n\n const duration = performance.now() - startTime;\n timer?.stop();\n\n const logLevel = options?.logLevel || LogLevel.DEBUG;\n this.log(logLevel, `Profile: ${operationName} completed`, {\n operation: operationName,\n duration: `${duration.toFixed(2)}ms`,\n result: options?.logResult ? result : '[result hidden]',\n });\n\n return result;\n } catch (error) {\n const duration = performance.now() - startTime;\n timer?.stop();\n\n this.error(\n `Profile: ${operationName} failed`,\n {\n operation: operationName,\n duration: `${duration.toFixed(2)}ms`,\n error: (error as Error).message,\n },\n error as Error\n );\n\n throw error;\n }\n }\n\n // HTTP request logging helper\n logRequest(\n method: string,\n url: string,\n statusCode?: number,\n duration?: number\n ): void {\n const level = this.getHttpLogLevel(statusCode);\n const message = `${method.toUpperCase()} ${url}${statusCode ? ` ${statusCode}` : ''}`;\n\n this.log(level, message, {\n method,\n url,\n statusCode,\n duration: duration ? `${duration.toFixed(2)}ms` : undefined,\n type: 'http_request',\n });\n }\n\n // Flush any pending logs (useful for graceful shutdown)\n async flush(): Promise<void> {\n this.timerManager.clear();\n }\n\n // Get logger statistics\n getStats(): {\n activeTimers: number;\n activeSpans: number;\n config: LoggerConfig;\n } {\n return {\n activeTimers: this.timerManager.getActive().length,\n activeSpans: this.tracer.getActiveSpans().length,\n config: { ...this.config },\n };\n }\n\n // Output method (can be overridden for custom outputs)\n protected output(message: string, level: LogLevel): void {\n if (level >= LogLevel.ERROR) {\n console.error(message);\n } else {\n console.log(message);\n }\n }\n\n // Core log method\n private log(\n level: LogLevel,\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n if (level < this.config.level) {\n return; // Skip logs below configured level\n }\n\n const currentTrace = this.config.enableTracing\n ? this.tracer.getCurrentTrace()\n : undefined;\n const contextData = this.config.enableContext\n ? this.context.getContext()\n : undefined;\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n traceId: currentTrace?.traceId,\n parentId: currentTrace?.parentId,\n spanId: currentTrace?.spanId,\n context: contextData,\n metadata,\n error,\n tags: currentTrace?.tags,\n };\n\n // Add duration if we're in a traced operation\n if (currentTrace?.metadata?.duration) {\n entry.duration = currentTrace.metadata.duration as number;\n }\n\n const formatted = this.formatter.format(entry);\n this.output(formatted, level);\n }\n\n private getHttpLogLevel(statusCode?: number): LogLevel {\n if (!statusCode) return LogLevel.INFO;\n if (statusCode >= 500) return LogLevel.ERROR;\n if (statusCode >= 400) return LogLevel.WARN;\n return LogLevel.INFO;\n }\n}\n"],"mappings":";;;;;;;AAcA,IAAa,SAAb,MAAa,OAAO;CAClB,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,QAAgC;AAC1C,OAAK,SAAS;GACZ,OAAO,SAAS;GAChB,aACG,QAAQ,IAAI,YAA4C;GAC3D,eAAe;GACf,cAAc;GACd,eAAe;GACf,cAAc;GACd,iBAAiB;GACjB,iBAAiB;GACjB,GAAG;GACJ;AAED,OAAK,UAAU,WAAW,aAAa;AACvC,OAAK,SAAS,IAAI,QAAQ;AAC1B,OAAK,eAAe,IAAI,cAAc;AAGtC,OAAK,YACH,KAAK,OAAO,gBAAgB,eACxB,IAAI,qBAAqB,GACzB,IAAI,aAAa,KAAK,OAAO,aAAa;;CAIlD,SAAS,SAAiB,UAA0C;AAClE,OAAK,IAAI,SAAS,OAAO,SAAS,SAAS;;CAG7C,MAAM,SAAiB,UAA0C;AAC/D,OAAK,IAAI,SAAS,OAAO,SAAS,SAAS;;CAG7C,KAAK,SAAiB,UAA0C;AAC9D,OAAK,IAAI,SAAS,MAAM,SAAS,SAAS;;CAG5C,KAAK,SAAiB,UAA0C;AAC9D,OAAK,IAAI,SAAS,MAAM,SAAS,SAAS;;CAG5C,MACE,SACA,UACA,OACM;AACN,OAAK,IAAI,SAAS,OAAO,SAAS,UAAU,MAAM;;CAGpD,MACE,SACA,UACA,OACM;AACN,OAAK,IAAI,SAAS,OAAO,SAAS,UAAU,MAAM;;CAIpD,YAAe,SAAsB,IAAgB;AACnD,SAAO,KAAK,QAAQ,IAAI,SAAS,GAAG;;CAGtC,cAAiB,mBAAyC,IAAgB;AACxE,SAAO,KAAK,QAAQ,OAAO,mBAAmB,GAAG;;CAGnD,WAAW,KAAa,OAAsB;AAC5C,OAAK,QAAQ,IAAI,KAAK,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OAAO,iBAAiB,GAC7B;EACJ,MAAM,cAAc,KAAK,OAAO,gBAC5B,KAAK,QAAQ,YAAY,GACzB;EAEJ,MAAMA,QAAkB;GACtB;GACA;GACA,2BAAW,IAAI,MAAM;GACrB,SAAS,cAAc;GACvB,UAAU,cAAc;GACxB,QAAQ,cAAc;GACtB,SAAS;GACT;GACA;GACA,MAAM,cAAc;GACrB;AAGD,MAAI,cAAc,UAAU,SAC1B,OAAM,WAAW,aAAa,SAAS;EAGzC,MAAM,YAAY,KAAK,UAAU,OAAO,MAAM;AAC9C,OAAK,OAAO,WAAW,MAAM;;CAG/B,AAAQ,gBAAgB,YAA+B;AACrD,MAAI,CAAC,WAAY,QAAO,SAAS;AACjC,MAAI,cAAc,IAAK,QAAO,SAAS;AACvC,MAAI,cAAc,IAAK,QAAO,SAAS;AACvC,SAAO,SAAS"}
1
+ {"version":3,"file":"logger.node.mjs","names":[],"sources":["../src/logger.node.ts"],"sourcesContent":["import type {\n ContextData,\n Formatter,\n LogEntry,\n LoggerConfig,\n TraceMethod,\n TracingOptions,\n} from './types';\nimport { LogLevel } from './types';\nimport { LogContext } from './context.node';\nimport { Tracer } from './tracer.node';\nimport { Timer, TimerManager } from './timer';\nimport { DevFormatter, ProductionFormatter } from './formatters';\n\nexport class Logger {\n private config: LoggerConfig;\n private formatter: Formatter;\n private context: LogContext;\n private tracer: Tracer;\n private timerManager: TimerManager;\n\n constructor(config?: Partial<LoggerConfig>) {\n this.config = {\n level: LogLevel.INFO,\n environment:\n (process.env.NODE_ENV as LoggerConfig['environment']) || 'development',\n enableTracing: true,\n enableTiming: true,\n enableContext: true,\n enableColors: true,\n maxContextDepth: 10,\n timestampFormat: 'iso',\n ...config,\n };\n\n this.context = LogContext.getInstance();\n this.tracer = new Tracer();\n this.timerManager = new TimerManager();\n\n // Set up formatter based on environment\n this.formatter =\n this.config.environment === 'production'\n ? new ProductionFormatter()\n : new DevFormatter(this.config.enableColors);\n }\n\n // Core logging methods\n traceLog(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.TRACE, message, metadata);\n }\n\n debug(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.DEBUG, message, metadata);\n }\n\n info(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.INFO, message, metadata);\n }\n\n warn(message: string, metadata?: Record<string, unknown>): void {\n this.log(LogLevel.WARN, message, metadata);\n }\n\n error(\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n this.log(LogLevel.ERROR, message, metadata, error);\n }\n\n fatal(\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n this.log(LogLevel.FATAL, message, metadata, error);\n }\n\n // Context management\n withContext<T>(context: ContextData, fn: () => T): T {\n return this.context.run(context, fn);\n }\n\n extendContext<T>(additionalContext: Partial<ContextData>, fn: () => T): T {\n return this.context.extend(additionalContext, fn) as T;\n }\n\n setContext(key: string, value: unknown): void {\n this.context.set(key, value);\n }\n\n getContext(): ContextData {\n return this.context.getContext();\n }\n\n // Tracing functionality\n trace: TraceMethod = async <T>(\n options: TracingOptions,\n fn: () => T | Promise<T>\n ): Promise<T> => {\n if (!this.config.enableTracing) {\n return await fn();\n }\n\n return this.tracer.trace(options, fn);\n };\n\n getTraceId(): string | undefined {\n return this.tracer.getCurrentTrace()?.traceId;\n }\n\n startSpan(options: TracingOptions) {\n if (!this.config.enableTracing) {\n return null;\n }\n return this.tracer.startSpan(options);\n }\n\n finishSpan(spanId: string): number | undefined {\n if (!this.config.enableTracing) {\n return undefined;\n }\n return this.tracer.finishSpan(spanId);\n }\n\n addTraceMetadata(key: string, value: unknown): void {\n if (this.config.enableTracing) {\n this.tracer.addMetadata(key, value);\n }\n }\n\n addTraceTags(...tags: string[]): void {\n if (this.config.enableTracing) {\n this.tracer.addTags(...tags);\n }\n }\n\n // Timer functionality\n startTimer(id?: string): Timer | null {\n if (!this.config.enableTiming) {\n return null;\n }\n return this.timerManager.start(id);\n }\n\n stopTimer(id: string): number | undefined {\n if (!this.config.enableTiming) {\n return undefined;\n }\n return this.timerManager.stop(id);\n }\n\n getTimer(id: string): Timer | undefined {\n return this.timerManager.get(id);\n }\n\n // Utility methods\n child(context: Partial<ContextData>): Logger {\n const childLogger = new Logger(this.config);\n Object.entries(context).forEach(([key, value]) => {\n childLogger.setContext(key, value);\n });\n return childLogger;\n }\n\n setLevel(level: LogLevel): void {\n this.config.level = level;\n }\n\n setFormatter(formatter: Formatter): void {\n this.formatter = formatter;\n }\n\n // Performance profiling\n async profile<T>(\n operationName: string,\n fn: () => T | Promise<T>,\n options?: { logResult?: boolean; logLevel?: LogLevel }\n ): Promise<T> {\n const timer = this.startTimer(`profile-${operationName}`);\n const startTime = performance.now();\n\n try {\n const result = await this.tracer.trace(\n {\n operationType: 'custom',\n operationName: `profile:${operationName}`,\n autoTiming: true,\n },\n fn\n );\n\n const duration = performance.now() - startTime;\n timer?.stop();\n\n const logLevel = options?.logLevel || LogLevel.DEBUG;\n this.log(logLevel, `Profile: ${operationName} completed`, {\n operation: operationName,\n duration: `${duration.toFixed(2)}ms`,\n result: options?.logResult ? result : '[result hidden]',\n });\n\n return result;\n } catch (error) {\n const duration = performance.now() - startTime;\n timer?.stop();\n\n this.error(\n `Profile: ${operationName} failed`,\n {\n operation: operationName,\n duration: `${duration.toFixed(2)}ms`,\n error: (error as Error).message,\n },\n error as Error\n );\n\n throw error;\n }\n }\n\n // HTTP request logging helper\n logRequest(\n method: string,\n url: string,\n statusCode?: number,\n duration?: number\n ): void {\n const level = this.getHttpLogLevel(statusCode);\n const message = `${method.toUpperCase()} ${url}${statusCode ? ` ${statusCode}` : ''}`;\n\n this.log(level, message, {\n method,\n url,\n statusCode,\n duration: duration ? `${duration.toFixed(2)}ms` : undefined,\n type: 'http_request',\n });\n }\n\n // Flush any pending logs (useful for graceful shutdown)\n async flush(): Promise<void> {\n this.timerManager.clear();\n }\n\n // Get logger statistics\n getStats(): {\n activeTimers: number;\n activeSpans: number;\n config: LoggerConfig;\n } {\n return {\n activeTimers: this.timerManager.getActive().length,\n activeSpans: this.tracer.getActiveSpans().length,\n config: { ...this.config },\n };\n }\n\n // Output method (can be overridden for custom outputs)\n protected output(message: string, level: LogLevel): void {\n if (level >= LogLevel.ERROR) {\n console.error(message);\n } else {\n console.log(message);\n }\n }\n\n // Core log method\n private log(\n level: LogLevel,\n message: string,\n metadata?: Record<string, unknown>,\n error?: Error\n ): void {\n if (level < this.config.level) {\n return; // Skip logs below configured level\n }\n\n const currentTrace = this.config.enableTracing\n ? this.tracer.getCurrentTrace()\n : undefined;\n const contextData = this.config.enableContext\n ? this.context.getContext()\n : undefined;\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n traceId: currentTrace?.traceId,\n parentId: currentTrace?.parentId,\n spanId: currentTrace?.spanId,\n context: contextData,\n metadata,\n error,\n tags: currentTrace?.tags,\n };\n\n // Add duration if we're in a traced operation\n if (currentTrace?.metadata?.duration) {\n entry.duration = currentTrace.metadata.duration as number;\n }\n\n const formatted = this.formatter.format(entry);\n this.output(formatted, level);\n }\n\n private getHttpLogLevel(statusCode?: number): LogLevel {\n if (!statusCode) return LogLevel.INFO;\n if (statusCode >= 500) return LogLevel.ERROR;\n if (statusCode >= 400) return LogLevel.WARN;\n return LogLevel.INFO;\n }\n}\n"],"mappings":";;;;;;;AAcA,IAAa,SAAb,MAAa,OAAO;CAClB,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,QAAgC;AAC1C,OAAK,SAAS;GACZ,OAAO,SAAS;GAChB,aACG,QAAQ,IAAI,YAA4C;GAC3D,eAAe;GACf,cAAc;GACd,eAAe;GACf,cAAc;GACd,iBAAiB;GACjB,iBAAiB;GACjB,GAAG;GACJ;AAED,OAAK,UAAU,WAAW,aAAa;AACvC,OAAK,SAAS,IAAI,QAAQ;AAC1B,OAAK,eAAe,IAAI,cAAc;AAGtC,OAAK,YACH,KAAK,OAAO,gBAAgB,eACxB,IAAI,qBAAqB,G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version":3,"file":"tracer.browser.mjs","names":["span: TraceContext"],"sources":["../src/tracer.browser.ts"],"sourcesContent":["import type { TraceContext, TracingOptions } from './types';\nimport { LogContext } from './context.browser';\nimport { Timer } from './timer';\n\nexport class Tracer {\n private context: LogContext;\n private activeSpans = new Map<string, TraceContext>();\n\n constructor() {\n this.context = LogContext.getInstance();\n }\n\n /**\n * Start a new trace span\n */\n startSpan(options: TracingOptions): TraceContext {\n const parentTrace = this.context.getCurrentTrace();\n const traceId = parentTrace?.traceId || this.generateTraceId();\n\n const span: TraceContext = {\n traceId,\n parentId: parentTrace?.spanId,\n spanId: this.generateSpanId(),\n operationType: options.operationType,\n operationName: options.operationName,\n startTime: performance.now(),\n metadata: { ...options.metadata },\n tags: [...(options.tags || [])],\n };\n\n this.activeSpans.set(span.spanId, span);\n this.context.setTrace(span);\n\n return span;\n }\n\n /**\n * Finish a trace span\n */\n finishSpan(spanId: string): number | undefined {\n const span = this.activeSpans.get(spanId);\n if (!span) {\n return undefined;\n }\n\n const duration = performance.now() - span.startTime;\n this.activeSpans.delete(spanId);\n\n // If this was the current span, restore parent\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace?.spanId === spanId && span.parentId) {\n const parentSpan = this.findSpanById(span.parentId);\n if (parentSpan) {\n this.context.setTrace(parentSpan);\n }\n }\n\n return duration;\n }\n\n /**\n * Execute a function within a trace span\n */\n async trace<T>(\n options: TracingOptions,\n fn: () => T | Promise<T>\n ): Promise<T> {\n const span = this.startSpan(options);\n const timer =\n options.autoTiming !== false\n ? new Timer(`trace-${span.spanId}`)\n : undefined;\n\n try {\n const result = await fn();\n\n const duration = this.finishSpan(span.spanId);\n if (timer) {\n timer.stop();\n }\n\n // Add timing metadata\n if (duration !== undefined) {\n span.metadata.duration = duration;\n }\n\n return result;\n } catch (error) {\n // Add error metadata\n span.metadata.error = {\n name: (error as Error).name || 'Unknown',\n message: (error as Error).message || 'Unknown error',\n stack: (error as Error).stack,\n };\n\n const duration = this.finishSpan(span.spanId);\n span.metadata.duration = duration;\n if (timer) {\n timer.stop();\n }\n\n throw error;\n }\n }\n\n /**\n * Add metadata to current span\n */\n addMetadata(key: string, value: unknown): void {\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace) {\n currentTrace.metadata[key] = value;\n }\n }\n\n /**\n * Add tags to current span\n */\n addTags(...tags: string[]): void {\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace) {\n currentTrace.tags.push(...tags);\n }\n }\n\n /**\n * Get current trace context\n */\n getCurrentTrace(): TraceContext | undefined {\n return this.context.getCurrentTrace();\n }\n\n /**\n * Get all active spans\n */\n getActiveSpans(): TraceContext[] {\n return Array.from(this.activeSpans.values());\n }\n\n /**\n * Find a span by ID\n */\n findSpanById(spanId: string): TraceContext | undefined {\n return this.activeSpans.get(spanId);\n }\n\n /**\n * Generate a unique trace ID\n */\n private generateTraceId(): string {\n return crypto.randomUUID().replace(/-/g, '');\n }\n\n /**\n * Generate a unique span ID\n */\n private generateSpanId(): string {\n return crypto.randomUUID().replace(/-/g, '').substring(0, 16);\n }\n}\n"],"mappings":";;;;AAIA,IAAa,SAAb,MAAoB;CAClB,AAAQ;CACR,AAAQ,8BAAc,IAAI,KAA2B;CAErD,cAAc;AACZ,OAAK,UAAU,WAAW,aAAa;;;;;CAMzC,UAAU,SAAuC;EAC/C,MAAM,cAAc,KAAK,QAAQ,iBAAiB;EAGlD,MAAMA,OAAqB;GACzB,SAHc,aAAa,WAAW,KAAK,iBAAiB;GAI5D,UAAU,aAAa;GACvB,QAAQ,KAAK,gBAAgB;GAC7B,eAAe,QAAQ;GACvB,eAAe,QAAQ;GACvB,WAAW,YAAY,KAAK;GAC5B,UAAU,EAAE,GAAG,QAAQ,UAAU;GACjC,MAAM,CAAC,GAAI,QAAQ,QAAQ,EAAE,CAAE;GAChC;AAED,OAAK,YAAY,IAAI,KAAK,QAAQ,KAAK;AACvC,OAAK,QAAQ,SAAS,KAAK;AAE3B,SAAO;;;;;CAMT,WAAW,QAAoC;E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YAAY,IAAI,OAAO;;;;;CAMrC,AAAQ,kBAA0B;AAChC,SAAO,OAAO,YAAY,CAAC,QAAQ,MAAM,GAAG;;;;;CAM9C,AAAQ,iBAAyB;AAC/B,SAAO,OAAO,YAAY,CAAC,QAAQ,MAAM,GAAG,CAAC,UAAU,GAAG,GAAG"}
1
+ {"version":3,"file":"tracer.browser.mjs","names":[],"sources":["../src/tracer.browser.ts"],"sourcesContent":["import type { TraceContext, TracingOptions } from './types';\nimport { LogContext } from './context.browser';\nimport { Timer } from './timer';\n\nexport class Tracer {\n private context: LogContext;\n private activeSpans = new Map<string, TraceContext>();\n\n constructor() {\n this.context = LogContext.getInstance();\n }\n\n /**\n * Start a new trace span\n */\n startSpan(options: TracingOptions): TraceContext {\n const parentTrace = this.context.getCurrentTrace();\n const traceId = parentTrace?.traceId || this.generateTraceId();\n\n const span: TraceContext = {\n traceId,\n parentId: parentTrace?.spanId,\n spanId: this.generateSpanId(),\n operationType: options.operationType,\n operationName: options.operationName,\n startTime: performance.now(),\n metadata: { ...options.metadata },\n tags: [...(options.tags || [])],\n };\n\n this.activeSpans.set(span.spanId, span);\n this.context.setTrace(span);\n\n return span;\n }\n\n /**\n * Finish a trace span\n */\n finishSpan(spanId: string): number | undefined {\n const span = this.activeSpans.get(spanId);\n if (!span) {\n return undefined;\n }\n\n const duration = performance.now() - span.startTime;\n this.activeSpans.delete(spanId);\n\n // If this was the current span, restore parent\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace?.spanId === spanId && span.parentId) {\n const parentSpan = this.findSpanById(span.parentId);\n if (parentSpan) {\n this.context.setTrace(parentSpan);\n }\n }\n\n return duration;\n }\n\n /**\n * Execute a function within a trace span\n */\n async trace<T>(\n options: TracingOptions,\n fn: () => T | Promise<T>\n ): Promise<T> {\n const span = this.startSpan(options);\n const timer =\n options.autoTiming !== false\n ? new Timer(`trace-${span.spanId}`)\n : undefined;\n\n try {\n const result = await fn();\n\n const duration = this.finishSpan(span.spanId);\n if (timer) {\n timer.stop();\n }\n\n // Add timing metadata\n if (duration !== undefined) {\n span.metadata.duration = duration;\n }\n\n return result;\n } catch (error) {\n // Add error metadata\n span.metadata.error = {\n name: (error as Error).name || 'Unknown',\n message: (error as Error).message || 'Unknown error',\n stack: (error as Error).stack,\n };\n\n const duration = this.finishSpan(span.spanId);\n span.metadata.duration = duration;\n if (timer) {\n timer.stop();\n }\n\n throw error;\n }\n }\n\n /**\n * Add metadata to current span\n */\n addMetadata(key: string, value: unknown): void {\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace) {\n currentTrace.metadata[key] = value;\n }\n }\n\n /**\n * Add tags to current span\n */\n addTags(...tags: string[]): void {\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace) {\n currentTrace.tags.push(...tags);\n }\n }\n\n /**\n * Get current trace context\n */\n getCurrentTrace(): TraceContext | undefined {\n return this.context.getCurrentTrace();\n }\n\n /**\n * Get all active spans\n */\n getActiveSpans(): TraceContext[] {\n return Array.from(this.activeSpans.values());\n }\n\n /**\n * Find a span by ID\n */\n findSpanById(spanId: string): TraceContext | undefined {\n return this.activeSpans.get(spanId);\n }\n\n /**\n * Generate a unique trace ID\n */\n private generateTraceId(): string {\n return crypto.randomUUID().replace(/-/g, '');\n }\n\n /**\n * Generate a unique span ID\n */\n private generateSpanId(): string {\n return crypto.randomUUID().replace(/-/g, '').substring(0, 16);\n }\n}\n"],"mappings":";;;;AAIA,IAAa,SAAb,MAAoB;CAClB,AAAQ;CACR,AAAQ,8BAAc,IAAI,KAA2B;CAErD,cAAc;AACZ,OAAK,UAAU,WAAW,aAAa;;;;;CAMzC,UAAU,SAAuC;EAC/C,MAAM,cAAc,KAAK,QAAQ,iBAAiB;EAGlD,MAAM,OAAqB;GACzB,SAHc,aAAa,WAAW,KAAK,iBAAiB;GAI5D,UAAU,aAAa;GACvB,QAAQ,KAAK,gBAAgB;GAC7B,eAAe,QAAQ;GACvB,eAAe,QAAQ;GACvB,WAAW,YAAY,KAAK;GAC5B,UAA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a,KAAK,KAAK,GAAG,KAAK;;;;;CAOnC,kBAA4C;AAC1C,SAAO,KAAK,QAAQ,iBAAiB;;;;;CAMvC,iBAAiC;AAC/B,SAAO,MAAM,KAAK,KAAK,YAAY,QAAQ,CAAC;;;;;CAM9C,aAAa,QAA0C;AACrD,SAAO,KAAK,YAAY,IAAI,OAAO;;;;;CAMrC,AAAQ,kBAA0B;AAChC,SAAO,OAAO,YAAY,CAAC,QAAQ,MAAM,GAAG;;;;;CAM9C,AAAQ,iBAAyB;AAC/B,SAAO,OAAO,YAAY,CAAC,QAAQ,MAAM,GAAG,CAAC,UAAU,GAAG,GAAG"}
@@ -1 +1 @@
1
- {"version":3,"file":"tracer.node.mjs","names":["span: TraceContext"],"sources":["../src/tracer.node.ts"],"sourcesContent":["import type { TraceContext, TracingOptions } from './types';\nimport { LogContext } from './context.node';\nimport { Timer } from './timer';\n\nexport class Tracer {\n private context: LogContext;\n private activeSpans = new Map<string, TraceContext>();\n\n constructor() {\n this.context = LogContext.getInstance();\n }\n\n /**\n * Start a new trace span\n */\n startSpan(options: TracingOptions): TraceContext {\n const parentTrace = this.context.getCurrentTrace();\n const traceId = parentTrace?.traceId || this.generateTraceId();\n\n const span: TraceContext = {\n traceId,\n parentId: parentTrace?.spanId,\n spanId: this.generateSpanId(),\n operationType: options.operationType,\n operationName: options.operationName,\n startTime: performance.now(),\n metadata: { ...options.metadata },\n tags: [...(options.tags || [])],\n };\n\n this.activeSpans.set(span.spanId, span);\n this.context.setTrace(span);\n\n return span;\n }\n\n /**\n * Finish a trace span\n */\n finishSpan(spanId: string): number | undefined {\n const span = this.activeSpans.get(spanId);\n if (!span) {\n return undefined;\n }\n\n const duration = performance.now() - span.startTime;\n this.activeSpans.delete(spanId);\n\n // If this was the current span, restore parent\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace?.spanId === spanId && span.parentId) {\n const parentSpan = this.findSpanById(span.parentId);\n if (parentSpan) {\n this.context.setTrace(parentSpan);\n }\n }\n\n return duration;\n }\n\n /**\n * Execute a function within a trace span\n */\n async trace<T>(\n options: TracingOptions,\n fn: () => T | Promise<T>\n ): Promise<T> {\n const span = this.startSpan(options);\n const timer =\n options.autoTiming !== false\n ? new Timer(`trace-${span.spanId}`)\n : undefined;\n\n try {\n const result = await fn();\n\n const duration = this.finishSpan(span.spanId);\n if (timer) {\n timer.stop();\n }\n\n // Add timing metadata\n if (duration !== undefined) {\n span.metadata.duration = duration;\n }\n\n return result;\n } catch (error) {\n // Add error metadata\n span.metadata.error = {\n name: (error as Error).name || 'Unknown',\n message: (error as Error).message || 'Unknown error',\n stack: (error as Error).stack,\n };\n\n const duration = this.finishSpan(span.spanId);\n span.metadata.duration = duration;\n if (timer) {\n timer.stop();\n }\n\n throw error;\n }\n }\n\n /**\n * Add metadata to current span\n */\n addMetadata(key: string, value: unknown): void {\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace) {\n currentTrace.metadata[key] = value;\n }\n }\n\n /**\n * Add tags to current span\n */\n addTags(...tags: string[]): void {\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace) {\n currentTrace.tags.push(...tags);\n }\n }\n\n /**\n * Get current trace context\n */\n getCurrentTrace(): TraceContext | undefined {\n return this.context.getCurrentTrace();\n }\n\n /**\n * Get all active spans\n */\n getActiveSpans(): TraceContext[] {\n return Array.from(this.activeSpans.values());\n }\n\n /**\n * Find a span by ID\n */\n findSpanById(spanId: string): TraceContext | undefined {\n return this.activeSpans.get(spanId);\n }\n\n /**\n * Generate a unique trace ID\n */\n private generateTraceId(): string {\n return crypto.randomUUID().replace(/-/g, '');\n }\n\n /**\n * Generate a unique span ID\n */\n private generateSpanId(): string {\n return crypto.randomUUID().replace(/-/g, '').substring(0, 16);\n }\n}\n"],"mappings":";;;;AAIA,IAAa,SAAb,MAAoB;CAClB,AAAQ;CACR,AAAQ,8BAAc,IAAI,KAA2B;CAErD,cAAc;AACZ,OAAK,UAAU,WAAW,aAAa;;;;;CAMzC,UAAU,SAAuC;EAC/C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AM;AAGd,SAAM;;;;;;CAOV,YAAY,KAAa,OAAsB;EAC7C,MAAM,eAAe,KAAK,QAAQ,iBAAiB;AACnD,MAAI,aACF,cAAa,SAAS,OAAO;;;;;CAOjC,QAAQ,GAAG,MAAsB;EAC/B,MAAM,eAAe,KAAK,QAAQ,iBAAiB;AACnD,MAAI,aACF,cAAa,KAAK,KAAK,GAAG,KAAK;;;;;CAOnC,kBAA4C;AAC1C,SAAO,KAAK,QAAQ,iBAAiB;;;;;CAMvC,iBAAiC;AAC/B,SAAO,MAAM,KAAK,KAAK,YAAY,QAAQ,CAAC;;;;;CAM9C,aAAa,QAA0C;AACrD,SAAO,KAAK,YAAY,IAAI,OAAO;;;;;CAMrC,AAAQ,kBAA0B;AAChC,SAAO,OAAO,YAAY,CAAC,QAAQ,MAAM,GAAG;;;;;CAM9C,AAAQ,iBAAyB;AAC/B,SAAO,OAAO,YAAY,CAAC,QAAQ,MAAM,GAAG,CAAC,UAAU,GAAG,GAAG"}
1
+ {"version":3,"file":"tracer.node.mjs","names":[],"sources":["../src/tracer.node.ts"],"sourcesContent":["import type { TraceContext, TracingOptions } from './types';\nimport { LogContext } from './context.node';\nimport { Timer } from './timer';\n\nexport class Tracer {\n private context: LogContext;\n private activeSpans = new Map<string, TraceContext>();\n\n constructor() {\n this.context = LogContext.getInstance();\n }\n\n /**\n * Start a new trace span\n */\n startSpan(options: TracingOptions): TraceContext {\n const parentTrace = this.context.getCurrentTrace();\n const traceId = parentTrace?.traceId || this.generateTraceId();\n\n const span: TraceContext = {\n traceId,\n parentId: parentTrace?.spanId,\n spanId: this.generateSpanId(),\n operationType: options.operationType,\n operationName: options.operationName,\n startTime: performance.now(),\n metadata: { ...options.metadata },\n tags: [...(options.tags || [])],\n };\n\n this.activeSpans.set(span.spanId, span);\n this.context.setTrace(span);\n\n return span;\n }\n\n /**\n * Finish a trace span\n */\n finishSpan(spanId: string): number | undefined {\n const span = this.activeSpans.get(spanId);\n if (!span) {\n return undefined;\n }\n\n const duration = performance.now() - span.startTime;\n this.activeSpans.delete(spanId);\n\n // If this was the current span, restore parent\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace?.spanId === spanId && span.parentId) {\n const parentSpan = this.findSpanById(span.parentId);\n if (parentSpan) {\n this.context.setTrace(parentSpan);\n }\n }\n\n return duration;\n }\n\n /**\n * Execute a function within a trace span\n */\n async trace<T>(\n options: TracingOptions,\n fn: () => T | Promise<T>\n ): Promise<T> {\n const span = this.startSpan(options);\n const timer =\n options.autoTiming !== false\n ? new Timer(`trace-${span.spanId}`)\n : undefined;\n\n try {\n const result = await fn();\n\n const duration = this.finishSpan(span.spanId);\n if (timer) {\n timer.stop();\n }\n\n // Add timing metadata\n if (duration !== undefined) {\n span.metadata.duration = duration;\n }\n\n return result;\n } catch (error) {\n // Add error metadata\n span.metadata.error = {\n name: (error as Error).name || 'Unknown',\n message: (error as Error).message || 'Unknown error',\n stack: (error as Error).stack,\n };\n\n const duration = this.finishSpan(span.spanId);\n span.metadata.duration = duration;\n if (timer) {\n timer.stop();\n }\n\n throw error;\n }\n }\n\n /**\n * Add metadata to current span\n */\n addMetadata(key: string, value: unknown): void {\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace) {\n currentTrace.metadata[key] = value;\n }\n }\n\n /**\n * Add tags to current span\n */\n addTags(...tags: string[]): void {\n const currentTrace = this.context.getCurrentTrace();\n if (currentTrace) {\n currentTrace.tags.push(...tags);\n }\n }\n\n /**\n * Get current trace context\n */\n getCurrentTrace(): TraceContext | undefined {\n return this.context.getCurrentTrace();\n }\n\n /**\n * Get all active spans\n */\n getActiveSpans(): TraceContext[] {\n return Array.from(this.activeSpans.values());\n }\n\n /**\n * Find a span by ID\n */\n findSpanById(spanId: string): TraceContext | undefined {\n return this.activeSpans.get(spanId);\n }\n\n /**\n * Generate a unique trace ID\n */\n private generateTraceId(): string {\n return crypto.randomUUID().replace(/-/g, '');\n }\n\n /**\n * Generate a unique span ID\n */\n private generateSpanId(): string {\n return crypto.random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d,QAAK,SAAS,QAAQ;IACpB,MAAO,MAAgB,QAAQ;IAC/B,SAAU,MAAgB,WAAW;IACrC,OAAQ,MAAgB;IACzB;GAED,MAAM,WAAW,KAAK,WAAW,KAAK,OAAO;AAC7C,QAAK,SAAS,WAAW;AACzB,OAAI,MACF,OAAM,MAAM;AAGd,SAAM;;;;;;CAOV,YAAY,KAAa,OAAsB;EAC7C,MAAM,eAAe,KAAK,QAAQ,iBAAiB;AACnD,MAAI,aACF,cAAa,SAAS,OAAO;;;;;CAOjC,QAAQ,GAAG,MAAsB;EAC/B,MAAM,eAAe,KAAK,QAAQ,iBAAiB;AACnD,MAAI,aACF,cAAa,KAAK,KAAK,GAAG,KAAK;;;;;CAOnC,kBAA4C;AAC1C,SAAO,KAAK,QAAQ,iBAAiB;;;;;CAMvC,iBAAiC;AAC/B,SAAO,MAAM,KAAK,KAAK,YAAY,QAAQ,CAAC;;;;;CAM9C,aAAa,QAA0C;AACrD,SAAO,KAAK,YAAY,IAAI,OAAO;;;;;CAMrC,AAAQ,kBAA0B;AAChC,SAAO,OAAO,YAAY,CAAC,QAAQ,MAAM,GAAG;;;;;CAM9C,AAAQ,iBAAyB;AAC/B,SAAO,OAAO,YAAY,CAAC,QAAQ,MAAM,GAAG,CAAC,UAAU,GAAG,GAAG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contractspec/lib.logger",
3
- "version": "1.46.2",
3
+ "version": "1.48.0",
4
4
  "description": "Comprehensive logging library optimized for Bun with ElysiaJS integration",
5
5
  "keywords": [
6
6
  "contractspec",
@@ -24,9 +24,9 @@
24
24
  "dev": "bun build:bundle --watch"
25
25
  },
26
26
  "devDependencies": {
27
- "@contractspec/tool.typescript": "1.46.2",
28
- "@contractspec/tool.tsdown": "1.46.2",
29
- "tsdown": "^0.18.3",
27
+ "@contractspec/tool.typescript": "1.48.0",
28
+ "@contractspec/tool.tsdown": "1.48.0",
29
+ "tsdown": "^0.19.0",
30
30
  "typescript": "^5.9.3"
31
31
  },
32
32
  "peerDependencies": {
@@ -40,7 +40,6 @@
40
40
  "dependencies": {
41
41
  "zone.js": "^0.16.0"
42
42
  },
43
- "main": "./dist/index.mjs",
44
43
  "types": "./dist/index.d.mts",
45
44
  "files": [
46
45
  "dist",
@@ -64,7 +63,6 @@
64
63
  "./types": "./dist/types.mjs",
65
64
  "./*": "./*"
66
65
  },
67
- "module": "./dist/index.mjs",
68
66
  "publishConfig": {
69
67
  "access": "public",
70
68
  "exports": {