@brizz/sdk 0.1.2-rc.0 → 0.1.2

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,"sources":["../src/index.ts","../src/internal/instrumentation/auto-init.ts","../src/internal/logger.ts","../src/internal/instrumentation/vercel-ai/instrumentation.ts","../src/internal/instrumentation/vercel-ai/patchers/base-patcher.ts","../src/internal/instrumentation/vercel-ai/semconv.ts","../src/internal/instrumentation/vercel-ai/utils.ts","../src/internal/instrumentation/vercel-ai/patchers/generate-text-patcher.ts","../src/internal/instrumentation/vercel-ai/patchers/stream-text-patcher.ts","../src/internal/instrumentation/vercel-ai/patchers/embeddings-patcher.ts","../src/internal/instrumentation/vercel-ai/stream-handler.ts","../src/internal/instrumentation/vercel-ai/telemetry-recorder.ts","../src/internal/sdk.ts","../src/internal/config.ts","../src/internal/instrumentation/registry.ts","../src/internal/log/logging.ts","../src/internal/log/processors/log-processor.ts","../src/internal/masking/patterns.ts","../src/internal/masking/utils.ts","../src/internal/semantic-conventions.ts","../src/internal/metric/metrics.ts","../src/internal/trace/tracing.ts","../src/internal/trace/processors/span-processor.ts","../src/internal/trace/session.ts","../src/node/runtime.ts","../src/node/loader.ts","../src/init.ts"],"sourcesContent":["// Auto-initialize instrumentations before anything else\nimport './internal/instrumentation/auto-init.js';\n\n// Re-export main SDK instance and types\nexport { Brizz, type IBrizzInitializeOptions } from './internal/sdk.js';\n\n// Re-export instrumentation types for manual configuration\nexport {\n type IInstrumentModules,\n VercelAIInstrumentation,\n} from './internal/instrumentation/index.js';\n\n// Re-export utility functions from their respective modules\nexport { emitEvent } from './internal/log/index.js';\nexport { getSpanExporter, getSpanProcessor, WithSessionId } from './internal/trace/index.js';\nexport { getMetricsExporter, getMetricsReader } from './internal/metric/index.js';\n// Re-export masking types and utilities\nexport type {\n IMaskingConfig,\n ISpanMaskingConfig,\n ILogMaskingConfig,\n IEventMaskingConfig,\n IEventMaskingRule,\n MaskingMode,\n IAttributesMaskingRule,\n} from './internal/masking/index.js';\n\n// Re-export masking patterns and utilities\nexport { DEFAULT_PII_PATTERNS } from './internal/masking/patterns.js';\nexport { maskValue, maskAttributes } from './internal/masking/utils.js';\n\n// Re-export logger types, enums, and functions\nexport { LogLevel, logger, setLogLevel, getLogLevel } from './internal/logger.js';\nexport type { ILogger } from './internal/logger.js';\n\n// Re-export OpenTelemetry types that users might need\nexport { SeverityNumber } from '@opentelemetry/api-logs';\n\n// Re-export runtime utilities\nexport * from './node/runtime.js';\nexport * from './node/loader.js';\n\n// Explicit init entrypoint (preload)\nexport * as init from './init.js';\n","import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport type { Instrumentation } from '@opentelemetry/instrumentation';\nimport { registerInstrumentations } from '@opentelemetry/instrumentation';\nimport { AnthropicInstrumentation } from '@traceloop/instrumentation-anthropic';\nimport { BedrockInstrumentation } from '@traceloop/instrumentation-bedrock';\nimport { ChromaDBInstrumentation } from '@traceloop/instrumentation-chromadb';\nimport { CohereInstrumentation } from '@traceloop/instrumentation-cohere';\nimport { LangChainInstrumentation } from '@traceloop/instrumentation-langchain';\nimport { LlamaIndexInstrumentation } from '@traceloop/instrumentation-llamaindex';\nimport { OpenAIInstrumentation } from '@traceloop/instrumentation-openai';\nimport { PineconeInstrumentation } from '@traceloop/instrumentation-pinecone';\nimport { QdrantInstrumentation } from '@traceloop/instrumentation-qdrant';\nimport { TogetherInstrumentation } from '@traceloop/instrumentation-together';\nimport { VertexAIInstrumentation } from '@traceloop/instrumentation-vertexai';\n\nimport { logger } from '../logger.js';\n\nimport { VercelAIInstrumentation } from './vercel-ai';\n\n/**\n * Auto-initialization that runs at import time.\n * This ensures all instrumentations are registered before any libraries are loaded.\n *\n * Flow:\n * 1. Load node auto-instrumentations (including Winston)\n * 2. Initialize logger (after Winston instrumentation is ready)\n * 3. Load GenAI instrumentations with error logging\n */\n\nlet autoInstrumentationsLoaded = false;\n\nconst exceptionLogger = (error: Error) => {\n logger.error(`Exception in instrumentation: ${String(error)}`);\n};\n\nfunction loadNodeAutoInstrumentations(): Instrumentation[] {\n try {\n const nodeInstrumentations = getNodeAutoInstrumentations();\n registerInstrumentations({ instrumentations: nodeInstrumentations });\n return nodeInstrumentations;\n } catch (error) {\n logger.error(`Failed to load Node.js auto-instrumentations: ${String(error)}`);\n return [];\n }\n}\n\nfunction loadGenAIInstrumentations(): Instrumentation[] {\n const instrumentations: Instrumentation[] = [];\n\n const genAIInstrumentationClasses = [\n { class: VercelAIInstrumentation, name: 'Vercel AI' }, // Load first to avoid conflicts\n { class: OpenAIInstrumentation, name: 'OpenAI' },\n { class: AnthropicInstrumentation, name: 'Anthropic' },\n { class: CohereInstrumentation, name: 'Cohere' },\n { class: VertexAIInstrumentation, name: 'Vertex AI' },\n { class: BedrockInstrumentation, name: 'Bedrock' },\n { class: PineconeInstrumentation, name: 'Pinecone' },\n { class: LangChainInstrumentation, name: 'LangChain' },\n { class: LlamaIndexInstrumentation, name: 'LlamaIndex' },\n { class: ChromaDBInstrumentation, name: 'ChromaDB' },\n { class: QdrantInstrumentation, name: 'Qdrant' },\n { class: TogetherInstrumentation, name: 'Together' },\n ];\n\n for (const config of genAIInstrumentationClasses) {\n try {\n const instrumentation = new config.class({ exceptionLogger });\n instrumentations.push(instrumentation);\n logger.debug(`Auto-loaded ${config.name} instrumentation`);\n } catch (error) {\n logger.error(`Failed to auto-load ${config.name} instrumentation: ${String(error)}`);\n }\n }\n\n try {\n registerInstrumentations({ instrumentations });\n logger.info(`Auto-registered ${instrumentations.length} GenAI instrumentations`);\n } catch (error) {\n logger.error(`Failed to register GenAI instrumentations: ${String(error)}`);\n }\n\n return instrumentations;\n}\n\n/**\n * Auto-initialize all instrumentations.\n * Called immediately when this module is imported.\n */\nfunction autoInitializeInstrumentations(): void {\n if (autoInstrumentationsLoaded) {\n return;\n }\n\n try {\n // Step 1: Load node auto-instrumentations first\n const nodeInstrumentations = loadNodeAutoInstrumentations();\n\n // Step 2: Load GenAI instrumentations with logger exception handling\n const genAIInstrumentations = loadGenAIInstrumentations();\n\n autoInstrumentationsLoaded = true;\n logger.info(\n `Auto-initialization complete: ${nodeInstrumentations.length} node + ${genAIInstrumentations.length} GenAI instrumentations`,\n );\n } catch (error) {\n logger.error(`Auto-initialization failed: ${String(error)}`);\n autoInstrumentationsLoaded = false;\n }\n}\n\n// Auto-initialize immediately when this module is imported\nautoInitializeInstrumentations();\n\nexport { autoInstrumentationsLoaded };\n","/**\n * Logger interface and implementations for the Brizz SDK.\n *\n * Simple Pino-based logging system that works everywhere in the SDK,\n * including during bootstrap and instrumentation loading.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport pino from 'pino';\n\n/**\n * Available log levels for the Brizz SDK, ordered by severity.\n */\nexport enum LogLevel {\n NONE = 0,\n ERROR = 1,\n WARN = 2,\n INFO = 3,\n DEBUG = 4,\n}\n\n/**\n * Default log level for the SDK when no level is specified.\n */\nexport const DEFAULT_LOG_LEVEL = LogLevel.WARN;\n\n/**\n * Internal logger interface for the SDK.\n */\nexport interface ILogger {\n debug: (msg: string, ...meta: unknown[]) => void;\n info: (msg: string, ...meta: unknown[]) => void;\n warn: (msg: string, ...meta: unknown[]) => void;\n error: (msg: string, ...meta: unknown[]) => void;\n setLevel: (level: LogLevel) => void;\n getLevel: () => LogLevel;\n}\n\n/**\n * Pino-based logger implementation with dynamic level control.\n */\nclass PinoLogger implements ILogger {\n private _level: LogLevel = DEFAULT_LOG_LEVEL;\n private _pinoLogger: pino.Logger | null = null;\n\n constructor() {\n // Set initial level from environment\n const envLevel = this.getLogLevelFromEnv();\n this._level = envLevel;\n }\n\n /**\n * Lazy initialization of Pino logger to ensure it's created AFTER Jest spies\n * are set up during tests. This prevents the pino-pretty transport from\n * bypassing stdout/stderr spies.\n */\n private ensurePinoLogger(): pino.Logger {\n if (!this._pinoLogger) {\n this._pinoLogger = pino({\n name: 'Brizz',\n level: this.logLevelToPino(this._level),\n // Disable transport in test environment to allow proper spy capture\n transport: this.isProduction() || this.isTest()\n ? undefined\n : {\n target: 'pino-pretty',\n options: {\n singleLine: true,\n colorize: true,\n translateTime: 'HH:MM:ss',\n ignore: 'pid,hostname',\n messageFormat: '[{name}] {msg}',\n },\n },\n });\n }\n return this._pinoLogger;\n }\n\n private isProduction(): boolean {\n return process.env['NODE_ENV'] === 'production';\n }\n\n private isTest(): boolean {\n return process.env['NODE_ENV'] === 'test';\n }\n\n private getLogLevelFromEnv(): LogLevel {\n const envLevel = process.env['BRIZZ_LOG_LEVEL'];\n return envLevel ? parseLogLevel(envLevel) : DEFAULT_LOG_LEVEL;\n }\n\n private logLevelToPino(level: LogLevel): string {\n switch (level) {\n case LogLevel.DEBUG:\n return 'debug';\n case LogLevel.INFO:\n return 'info';\n case LogLevel.WARN:\n return 'warn';\n case LogLevel.ERROR:\n return 'error';\n default:\n return 'silent';\n }\n }\n\n private formatMeta(meta: unknown[]): object {\n if (meta.length === 0) {\n return {};\n }\n\n if (meta.length === 1 && typeof meta[0] === 'object' && meta[0] !== null) {\n return meta[0] as object;\n }\n\n return { metadata: meta };\n }\n\n setLevel(level: LogLevel): void {\n this._level = level;\n if (this._pinoLogger) {\n this._pinoLogger.level = this.logLevelToPino(level);\n }\n }\n\n getLevel(): LogLevel {\n return this._level;\n }\n\n debug = (msg: string, ...meta: unknown[]): void => {\n if (this._level >= LogLevel.DEBUG) {\n this.ensurePinoLogger().debug(this.formatMeta(meta), msg);\n }\n };\n\n info = (msg: string, ...meta: unknown[]): void => {\n if (this._level >= LogLevel.INFO) {\n this.ensurePinoLogger().info(this.formatMeta(meta), msg);\n }\n };\n\n warn = (msg: string, ...meta: unknown[]): void => {\n if (this._level >= LogLevel.WARN) {\n this.ensurePinoLogger().warn(this.formatMeta(meta), msg);\n }\n };\n\n error = (msg: string, ...meta: unknown[]): void => {\n if (this._level >= LogLevel.ERROR) {\n this.ensurePinoLogger().error(this.formatMeta(meta), msg);\n }\n };\n}\n\n/**\n * No-op logger that silences all logging output.\n */\nexport const noopLogger: ILogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n setLevel: () => {},\n getLevel: () => LogLevel.NONE,\n};\n\n/**\n * Parses a log level string into a LogLevel enum value.\n * Supports both string names and numeric values.\n */\nexport function parseLogLevel(level?: string): LogLevel {\n if (!level) {\n return DEFAULT_LOG_LEVEL;\n }\n\n const normalizedLevel = level.toLowerCase().trim();\n\n switch (normalizedLevel) {\n case 'debug':\n return LogLevel.DEBUG;\n case 'info':\n return LogLevel.INFO;\n case 'warn':\n case 'warning':\n return LogLevel.WARN;\n case 'error':\n return LogLevel.ERROR;\n case 'none':\n case 'off':\n case 'silent':\n return LogLevel.NONE;\n default: {\n // Try to parse as number\n const numLevel = Number.parseInt(normalizedLevel, 10);\n if (!Number.isNaN(numLevel) && numLevel >= 0 && numLevel <= 4) {\n return numLevel as LogLevel;\n }\n return DEFAULT_LOG_LEVEL;\n }\n }\n}\n\n/**\n * Global logger instance - initialized once and used throughout the SDK.\n */\nexport const logger: ILogger = new PinoLogger();\n\n/**\n * Sets the global logger level.\n */\nexport function setLogLevel(level: LogLevel | string): void {\n const resolvedLevel = typeof level === 'string' ? parseLogLevel(level) : level;\n logger.setLevel(resolvedLevel);\n}\n\n/**\n * Gets the current global logger level.\n */\nexport function getLogLevel(): LogLevel {\n return logger.getLevel();\n}\n\n/**\n * Maps Brizz LogLevel to OpenTelemetry DiagLogLevel.\n */\nexport function mapLogLevelToDiagLevel(logLevel: LogLevel): DiagLogLevel {\n switch (logLevel) {\n case LogLevel.DEBUG:\n return DiagLogLevel.DEBUG;\n case LogLevel.INFO:\n return DiagLogLevel.INFO;\n case LogLevel.WARN:\n return DiagLogLevel.WARN;\n case LogLevel.ERROR:\n return DiagLogLevel.ERROR;\n default:\n return DiagLogLevel.NONE;\n }\n}\n","import type { Histogram } from '@opentelemetry/api';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n} from '@opentelemetry/instrumentation';\n\nimport { logger } from '../../logger';\n\nimport {\n GenerateTextPatcher,\n StreamTextPatcher,\n EmbeddingsPatcher,\n type BasePatcher,\n type PatcherContext,\n} from './patchers';\nimport {\n METRIC_GEN_AI_CLIENT_OPERATION_DURATION,\n METRIC_GEN_AI_CLIENT_TOKEN_USAGE,\n} from './semconv';\nimport { StreamHandler } from './stream-handler';\nimport { TelemetryRecorder } from './telemetry-recorder';\nimport type { VercelAIInstrumentationConfig } from './types';\nimport { getEnvBool } from './utils';\n\nconst PACKAGE_NAME = '@brizz/vercel-ai-instrumentation';\nconst PACKAGE_VERSION = '0.1.0';\n\n// Type for the Vercel AI module exports\ninterface IVercelAIModule {\n generateText?: (...args: unknown[]) => unknown;\n streamText?: (...args: unknown[]) => unknown;\n generateObject?: (...args: unknown[]) => unknown;\n streamObject?: (...args: unknown[]) => unknown;\n embed?: (...args: unknown[]) => unknown;\n embedMany?: (...args: unknown[]) => unknown;\n generateImage?: (...args: unknown[]) => unknown;\n generateSpeech?: (...args: unknown[]) => unknown;\n transcribe?: (...args: unknown[]) => unknown;\n [key: string]: unknown;\n}\n\nexport class VercelAIInstrumentation extends InstrumentationBase<VercelAIInstrumentationConfig> {\n private _genaiClientOperationDuration!: Histogram;\n private _genaiClientTokenUsage!: Histogram;\n private _telemetryRecorder!: TelemetryRecorder;\n private _streamHandler!: StreamHandler;\n private _patchers: Map<string, BasePatcher> = new Map();\n // Holds last patched namespace when available (reserved for future factory wrapping)\n private _vercelAiNamespace: IVercelAIModule | null = null;\n private static readonly _WRAPPED_SYMBOL: symbol = Symbol.for('brizz.vercel-ai.patched');\n\n constructor(config: VercelAIInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n\n // Check environment variable overrides\n const cfg = this.getConfig();\n const envCC = getEnvBool('OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT');\n if (envCC !== undefined) {\n cfg.captureMessageContent = envCC;\n }\n\n this._initializeComponents();\n }\n\n override setConfig(config: VercelAIInstrumentationConfig = {}): void {\n const {\n captureMessageContent = true,\n enableMetrics = true,\n emitEvents = true,\n ...validConfig\n } = config;\n const fullConfig = {\n ...validConfig,\n captureMessageContent,\n enableMetrics,\n emitEvents,\n } as VercelAIInstrumentationConfig;\n super.setConfig(fullConfig);\n }\n\n private _initializeComponents(): void {\n // Initialize telemetry recorder\n this._telemetryRecorder = new TelemetryRecorder(\n this._genaiClientOperationDuration,\n this._genaiClientTokenUsage,\n this.logger,\n );\n\n // Initialize stream handler\n this._streamHandler = new StreamHandler({\n recordTokenMetrics: this._telemetryRecorder.recordTokenMetrics.bind(this._telemetryRecorder),\n recordDurationMetric: this._telemetryRecorder.recordDurationMetric.bind(\n this._telemetryRecorder,\n ),\n });\n\n // Create patcher context\n const patcherContext: PatcherContext = {\n tracer: this.tracer,\n getConfig: this.getConfig.bind(this),\n recordTokenMetrics: this._telemetryRecorder.recordTokenMetrics.bind(this._telemetryRecorder),\n recordDurationMetric: this._telemetryRecorder.recordDurationMetric.bind(\n this._telemetryRecorder,\n ),\n emitMessageEvents: this._telemetryRecorder.emitMessageEvents.bind(this._telemetryRecorder),\n emitAssistantMessageEvent: this._telemetryRecorder.emitAssistantMessageEvent.bind(\n this._telemetryRecorder,\n ),\n };\n\n // Initialize patchers\n this._patchers.set('generateText', new GenerateTextPatcher(patcherContext));\n this._patchers.set('streamText', new StreamTextPatcher(patcherContext, this._streamHandler));\n this._patchers.set('embed', new EmbeddingsPatcher(patcherContext));\n this._patchers.set('embedMany', new EmbeddingsPatcher(patcherContext));\n\n // TODO: Add generateObject and streamObject patchers\n }\n\n protected init(): InstrumentationNodeModuleDefinition[] {\n return [\n new InstrumentationNodeModuleDefinition(\n 'ai',\n ['>=4.0.0 <6'],\n (moduleExports: IVercelAIModule): IVercelAIModule => {\n logger.info('Starting instrumentation of Vercel AI SDK module');\n this._vercelAiNamespace = moduleExports;\n const patched = this._patchModuleExports(moduleExports);\n return patched ?? moduleExports;\n },\n (moduleExports: IVercelAIModule): IVercelAIModule => {\n logger.debug('Uninstrumenting @vercel/ai module');\n // Cleanup handled by proxy removal\n return moduleExports;\n },\n ),\n ];\n }\n\n override _updateMetricInstruments(): void {\n const config = this.getConfig();\n if (!config.enableMetrics) {\n return;\n }\n\n this._genaiClientOperationDuration = this.meter.createHistogram(\n METRIC_GEN_AI_CLIENT_OPERATION_DURATION,\n {\n description: 'GenAI operation duration',\n unit: 's',\n advice: {\n explicitBucketBoundaries: [\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92,\n ],\n },\n },\n );\n\n this._genaiClientTokenUsage = this.meter.createHistogram(METRIC_GEN_AI_CLIENT_TOKEN_USAGE, {\n description: 'Measures number of input and output tokens used',\n unit: '{token}',\n advice: {\n explicitBucketBoundaries: [\n 1, 4, 16, 64, 256, 1024, 4096, 16_384, 65_536, 262_144, 1_048_576, 4_194_304, 16_777_216,\n 67_108_864,\n ],\n },\n });\n\n // Reinitialize telemetry recorder with new metric instruments\n this._telemetryRecorder = new TelemetryRecorder(\n this._genaiClientOperationDuration,\n this._genaiClientTokenUsage,\n this.logger,\n );\n }\n\n /**\n * Patch known AI SDK functions in-place on the provided module exports object.\n * This approach is compatible with both CJS and ESM module loaders.\n */\n private _patchModuleExports(moduleExports: IVercelAIModule): IVercelAIModule | null {\n if (!moduleExports || typeof moduleExports !== 'object') {\n return null;\n }\n\n let inPlacePatched = true;\n const wrapFunction = (name: string, isEmbedMany = false): void => {\n const current = (moduleExports as Record<string, unknown>)[name];\n if (typeof current !== 'function') {\n return;\n }\n\n const currentFn = current as unknown as { [k: symbol]: unknown } & ((\n ...args: unknown[]\n ) => unknown);\n if (currentFn[VercelAIInstrumentation._WRAPPED_SYMBOL]) {\n return;\n }\n\n // If property is a read-only binding (ESM namespace), skip in-place replacement\n const descriptor = Object.getOwnPropertyDescriptor(moduleExports, name);\n if (descriptor && (!descriptor.writable || !descriptor.configurable) && !descriptor.set) {\n inPlacePatched = false;\n return;\n }\n\n const patcher = this._patchers.get(name);\n if (!patcher) {\n return;\n }\n\n\n const patched = (\n isEmbedMany ? (patcher as any).patch(currentFn, true) : (patcher as any).patch(currentFn)\n ) as (...args: unknown[]) => unknown;\n\n try {\n // Mark as wrapped to avoid double wrapping\n Object.defineProperty(patched, VercelAIInstrumentation._WRAPPED_SYMBOL, {\n value: true,\n enumerable: false,\n configurable: false,\n });\n } catch {\n // no-op if defineProperty fails\n }\n\n try {\n (moduleExports as Record<string, unknown>)[name] = patched as unknown;\n } catch {\n inPlacePatched = false;\n }\n };\n\n wrapFunction('generateText');\n wrapFunction('streamText');\n wrapFunction('embed');\n wrapFunction('embedMany', true);\n\n if (!inPlacePatched) {\n // Fallback to proxy-based wrapping when properties are read-only (ESM namespace)\n // Note: can't import logger here due to circular import in CJS context\n const proxiedModule = new Proxy(moduleExports, {\n get: (\n target: IVercelAIModule,\n prop: string | symbol,\n receiver: IVercelAIModule,\n ): unknown => {\n const originalValue = Reflect.get(target, prop, receiver) as unknown;\n if (\n typeof originalValue === 'function' &&\n typeof prop === 'string' &&\n this._patchers.has(prop)\n ) {\n // Note: can't import logger here due to circular import in CJS context\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const patcher = this._patchers.get(prop) as any;\n const isEmbedMany = prop === 'embedMany';\n const wrapped = isEmbedMany\n ? patcher.patch(originalValue, true)\n : patcher.patch(originalValue);\n return wrapped;\n }\n return originalValue;\n },\n });\n return proxiedModule as unknown as IVercelAIModule;\n }\n\n return moduleExports;\n }\n\n /**\n * Manual instrumentation hook for bundlers/Next.js. Applies in-place wrapping\n * on the provided module namespace.\n */\n public manuallyInstrument(module: unknown): IVercelAIModule {\n try {\n const result = this._patchModuleExports(module as IVercelAIModule);\n if (result !== null) {\n logger.debug('Applied manual Vercel AI instrumentation');\n this._vercelAiNamespace = result;\n return result;\n }\n logger.warn('Manual Vercel AI instrumentation received invalid module');\n return module as IVercelAIModule;\n } catch (error) {\n logger.error(`Failed manual Vercel AI instrumentation: ${String(error)}`);\n // Preserve any previously patched namespace reference for consumers\n return (this._vercelAiNamespace || (module as IVercelAIModule)) as IVercelAIModule;\n }\n }\n\n /**\n * Wrap a created provider/client instance (factory return) when possible.\n * Call this from wrappers that construct provider clients (e.g., OpenAI SDK).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public wrapFactoryReturn<T extends Record<string, any>>(instance: T): T {\n // Future: attach span context or wrap methods on provider clients\n return instance;\n }\n}\n","import { SpanKind, SpanStatusCode } from '@opentelemetry/api';\nimport type { Span, Tracer } from '@opentelemetry/api';\n\nimport {\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_REQUEST_MAX_TOKENS,\n ATTR_GEN_AI_REQUEST_TEMPERATURE,\n ATTR_GEN_AI_REQUEST_TOP_P,\n ATTR_GEN_AI_REQUEST_TOP_K,\n ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY,\n ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY,\n ATTR_GEN_AI_REQUEST_STOP_SEQUENCES,\n ATTR_GEN_AI_OPENAI_API_BASE,\n} from '../semconv';\nimport type { VercelAIInstrumentationConfig, GenerationParams, ProviderInfo, AIMessage } from '../types';\nimport { detectProvider, extractModelId, shouldRecordError } from '../utils';\n\nexport interface IPatcherContext {\n tracer: Tracer;\n getConfig: () => VercelAIInstrumentationConfig;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n recordTokenMetrics: (usage: any, system: string, model: string) => void;\n recordDurationMetric: (duration: number, system: string, model: string, operation: string) => void;\n emitMessageEvents: (messages: AIMessage[], system: string, span: Span) => void;\n emitAssistantMessageEvent: (text: string, system: string, span: Span) => void;\n}\n\n// Type alias for backward compatibility\nexport type PatcherContext = IPatcherContext;\n\nexport abstract class BasePatcher {\n constructor(protected context: PatcherContext) {}\n\n protected createSpan(\n spanName: string,\n params: GenerationParams,\n operationName: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additionalAttributes?: Record<string, any>\n ): { span: Span; provider: ProviderInfo; modelId: string } {\n const provider = detectProvider(params.model);\n const modelId = extractModelId(params.model);\n\n const span = this.context.tracer.startSpan(spanName, {\n kind: SpanKind.CLIENT,\n attributes: {\n [ATTR_GEN_AI_SYSTEM]: provider.system,\n [ATTR_GEN_AI_OPERATION_NAME]: operationName,\n [ATTR_GEN_AI_REQUEST_MODEL]: modelId,\n ...(params.maxTokens && { [ATTR_GEN_AI_REQUEST_MAX_TOKENS]: params.maxTokens }),\n ...(params.temperature !== undefined && {\n [ATTR_GEN_AI_REQUEST_TEMPERATURE]: params.temperature,\n }),\n ...(params.topP !== undefined && { [ATTR_GEN_AI_REQUEST_TOP_P]: params.topP }),\n ...(params.topK !== undefined && { [ATTR_GEN_AI_REQUEST_TOP_K]: params.topK }),\n ...(params.frequencyPenalty !== undefined && {\n [ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY]: params.frequencyPenalty,\n }),\n ...(params.presencePenalty !== undefined && {\n [ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY]: params.presencePenalty,\n }),\n ...(params.stopSequences && {\n [ATTR_GEN_AI_REQUEST_STOP_SEQUENCES]: params.stopSequences,\n }),\n ...(provider.apiBase && { [ATTR_GEN_AI_OPENAI_API_BASE]: provider.apiBase }),\n ...additionalAttributes,\n },\n });\n\n return { span, provider, modelId };\n }\n\n protected handleError(error: unknown, span: Span): void {\n if (shouldRecordError(error)) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message });\n }\n }\n\n protected finalizeDuration(\n span: Span,\n startTime: number,\n config: VercelAIInstrumentationConfig,\n provider: ProviderInfo,\n modelId: string,\n operationName: string\n ): void {\n if (config.enableMetrics) {\n const duration = (globalThis.performance.now() - startTime) / 1000;\n this.context.recordDurationMetric(duration, provider.system, modelId, operationName);\n }\n span.end();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n abstract patch(original: Function): Function;\n}\n","/**\n * GenAI Semantic Conventions for OpenTelemetry\n * Based on: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-spans.md\n */\n\n// Attribute names for GenAI operations\nexport const ATTR_GEN_AI_SYSTEM = 'gen_ai.system' as const;\nexport const ATTR_GEN_AI_OPERATION_NAME = 'gen_ai.operation.name' as const;\nexport const ATTR_GEN_AI_REQUEST_MODEL = 'gen_ai.request.model' as const;\nexport const ATTR_GEN_AI_REQUEST_MAX_TOKENS = 'gen_ai.request.max_tokens' as const;\nexport const ATTR_GEN_AI_REQUEST_TEMPERATURE = 'gen_ai.request.temperature' as const;\nexport const ATTR_GEN_AI_REQUEST_TOP_P = 'gen_ai.request.top_p' as const;\nexport const ATTR_GEN_AI_REQUEST_TOP_K = 'gen_ai.request.top_k' as const;\nexport const ATTR_GEN_AI_REQUEST_STOP_SEQUENCES = 'gen_ai.request.stop_sequences' as const;\nexport const ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY = 'gen_ai.request.frequency_penalty' as const;\nexport const ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY = 'gen_ai.request.presence_penalty' as const;\nexport const ATTR_GEN_AI_REQUEST_ENCODING_FORMATS = 'gen_ai.request.encoding_formats' as const;\n\n// Response attributes\nexport const ATTR_GEN_AI_RESPONSE_ID = 'gen_ai.response.id' as const;\nexport const ATTR_GEN_AI_RESPONSE_MODEL = 'gen_ai.response.model' as const;\nexport const ATTR_GEN_AI_RESPONSE_FINISH_REASONS = 'gen_ai.response.finish_reasons' as const;\n\n// Usage attributes\nexport const ATTR_GEN_AI_USAGE_PROMPT_TOKENS = 'gen_ai.usage.prompt_tokens' as const;\nexport const ATTR_GEN_AI_USAGE_COMPLETION_TOKENS = 'gen_ai.usage.completion_tokens' as const;\nexport const ATTR_GEN_AI_USAGE_TOTAL_TOKENS = 'gen_ai.usage.total_tokens' as const;\n\n// Compatibility attributes (for backwards compatibility)\nexport const ATTR_GEN_AI_USAGE_INPUT_TOKENS = 'gen_ai.usage.input_tokens' as const;\nexport const ATTR_GEN_AI_USAGE_OUTPUT_TOKENS = 'gen_ai.usage.output_tokens' as const;\n\n// Token type for metrics\nexport const ATTR_GEN_AI_TOKEN_TYPE = 'gen_ai.token.type' as const;\n\n// Prompt and completion attributes (indexed)\nexport const ATTR_GEN_AI_PROMPT = 'gen_ai.prompt' as const;\nexport const ATTR_GEN_AI_COMPLETION = 'gen_ai.completion' as const;\n\n// Provider-specific attributes\nexport const ATTR_GEN_AI_OPENAI_API_BASE = 'gen_ai.openai.api_base' as const;\nexport const ATTR_GEN_AI_OPENAI_API_TYPE = 'gen_ai.openai.api_type' as const;\nexport const ATTR_GEN_AI_OPENAI_API_VERSION = 'gen_ai.openai.api_version' as const;\n\n// Event attributes\nexport const ATTR_EVENT_NAME = 'event.name' as const;\n\n// Event names\nexport const EVENT_GEN_AI_USER_MESSAGE = 'gen_ai.user.message' as const;\nexport const EVENT_GEN_AI_ASSISTANT_MESSAGE = 'gen_ai.assistant.message' as const;\nexport const EVENT_GEN_AI_SYSTEM_MESSAGE = 'gen_ai.system.message' as const;\nexport const EVENT_GEN_AI_TOOL_MESSAGE = 'gen_ai.tool.message' as const;\nexport const EVENT_GEN_AI_CHOICE = 'gen_ai.choice' as const;\n\n// Metric names\nexport const METRIC_GEN_AI_CLIENT_OPERATION_DURATION = 'gen_ai.client.operation.duration' as const;\nexport const METRIC_GEN_AI_CLIENT_TOKEN_USAGE = 'gen_ai.client.token.usage' as const;\n\n// Operation names\nexport const OPERATION_NAME_CHAT = 'chat' as const;\nexport const OPERATION_NAME_EMBEDDINGS = 'embeddings' as const;\nexport const OPERATION_NAME_IMAGE_GENERATION = 'image_generation' as const;\nexport const OPERATION_NAME_SPEECH_SYNTHESIS = 'speech_synthesis' as const;\nexport const OPERATION_NAME_TRANSCRIPTION = 'transcription' as const;\n\n// Token types\nexport const TOKEN_TYPE_INPUT = 'input' as const;\nexport const TOKEN_TYPE_OUTPUT = 'output' as const;\n\n// Common provider names\nexport const PROVIDER_OPENAI = 'openai' as const;\nexport const PROVIDER_ANTHROPIC = 'anthropic' as const;\nexport const PROVIDER_GOOGLE = 'google' as const;\nexport const PROVIDER_AMAZON = 'amazon' as const;\nexport const PROVIDER_AZURE = 'azure' as const;\nexport const PROVIDER_VERCEL = 'vercel' as const;\nexport const PROVIDER_UNKNOWN = 'unknown' as const;\n\n// Span names\nexport const SPAN_NAME_GEN_AI_CHAT = 'gen_ai.chat' as const;\nexport const SPAN_NAME_GEN_AI_EMBEDDINGS = 'gen_ai.embeddings' as const;\nexport const SPAN_NAME_GEN_AI_IMAGE_GENERATION = 'gen_ai.image_generation' as const;\nexport const SPAN_NAME_GEN_AI_SPEECH_SYNTHESIS = 'gen_ai.speech_synthesis' as const;\nexport const SPAN_NAME_GEN_AI_TRANSCRIPTION = 'gen_ai.transcription' as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return */\nimport type { Attributes } from '@opentelemetry/api';\n\nimport {\n PROVIDER_OPENAI,\n PROVIDER_ANTHROPIC,\n PROVIDER_GOOGLE,\n PROVIDER_AMAZON,\n PROVIDER_AZURE,\n PROVIDER_VERCEL,\n PROVIDER_UNKNOWN,\n ATTR_GEN_AI_PROMPT,\n ATTR_GEN_AI_COMPLETION,\n} from './semconv';\nimport type { ProviderInfo, AIMessage, ModelInfo, TokenUsage } from './types';\n\n/**\n * Detect the provider from model information\n */\nexport function detectProvider(model: string | ModelInfo): ProviderInfo {\n // If model is an object with provider info\n if (typeof model === 'object' && model !== null) {\n const modelObj = model;\n if (modelObj.provider) {\n return {\n system: normalizeProviderName(modelObj.provider),\n apiBase: extractApiBase(modelObj),\n };\n }\n // Try to detect from modelId\n if (modelObj.modelId) {\n return detectProviderFromModelId(modelObj.modelId);\n }\n }\n\n // If model is a string, try to detect from it\n if (typeof model === 'string') {\n return detectProviderFromModelId(model);\n }\n\n return { system: PROVIDER_UNKNOWN };\n}\n\n/**\n * Detect provider from model ID string\n */\nfunction detectProviderFromModelId(modelId: string): ProviderInfo {\n const lowerModel = modelId.toLowerCase();\n\n // OpenAI models\n if (\n lowerModel.startsWith('gpt-') ||\n lowerModel.startsWith('text-davinci-') ||\n lowerModel.startsWith('text-embedding-') ||\n lowerModel.startsWith('dall-e') ||\n lowerModel.startsWith('whisper-') ||\n lowerModel.startsWith('tts-')\n ) {\n return { system: PROVIDER_OPENAI };\n }\n\n // Anthropic models\n if (lowerModel.startsWith('claude-')) {\n return { system: PROVIDER_ANTHROPIC };\n }\n\n // Google models\n if (\n lowerModel.startsWith('gemini-') ||\n lowerModel.startsWith('palm-') ||\n lowerModel.includes('bison') ||\n lowerModel.includes('gecko')\n ) {\n return { system: PROVIDER_GOOGLE };\n }\n\n // Amazon Bedrock models\n if (\n lowerModel.startsWith('amazon.') ||\n lowerModel.startsWith('anthropic.claude-') ||\n lowerModel.startsWith('ai21.') ||\n lowerModel.startsWith('cohere.') ||\n lowerModel.startsWith('meta.llama')\n ) {\n return { system: PROVIDER_AMAZON };\n }\n\n // Azure models (usually prefixed with deployment name)\n if (lowerModel.includes('azure') || lowerModel.includes('.openai.azure.com')) {\n return { system: PROVIDER_AZURE };\n }\n\n // Default to the model ID prefix if it looks like a provider name\n const parts = modelId.split(/[-._/]/);\n if (parts.length > 0 && parts[0]) {\n return { system: normalizeProviderName(parts[0]) };\n }\n\n return { system: PROVIDER_UNKNOWN };\n}\n\n/**\n * Normalize provider name to standard format\n */\nfunction normalizeProviderName(provider: string): string {\n const normalized = provider.toLowerCase().trim();\n\n switch (normalized) {\n case 'openai':\n case 'open-ai':\n case 'open_ai': {\n return PROVIDER_OPENAI;\n }\n case 'anthropic':\n case 'claude': {\n return PROVIDER_ANTHROPIC;\n }\n case 'google':\n case 'vertex':\n case 'vertexai':\n case 'vertex-ai':\n case 'gemini': {\n return PROVIDER_GOOGLE;\n }\n case 'amazon':\n case 'aws':\n case 'bedrock':\n case 'amazon-bedrock': {\n return PROVIDER_AMAZON;\n }\n case 'azure':\n case 'azure-openai':\n case 'microsoft': {\n return PROVIDER_AZURE;\n }\n case 'vercel':\n case 'vercel-ai': {\n return PROVIDER_VERCEL;\n }\n default: {\n return normalized;\n }\n }\n}\n\n/**\n * Extract API base URL from model configuration\n */\nfunction extractApiBase(model: ModelInfo): string | undefined {\n // Try to extract from various possible locations\n if (typeof model === 'object' && model !== null) {\n const anyModel = model as any;\n return anyModel.apiBase || anyModel.baseURL || anyModel.endpoint || undefined;\n }\n return undefined;\n}\n\n/**\n * Extract model ID from model parameter\n */\nexport function extractModelId(model: string | ModelInfo): string {\n if (typeof model === 'string') {\n return model;\n }\n if (typeof model === 'object' && model !== null) {\n return model.modelId || 'unknown';\n }\n return 'unknown';\n}\n\n/**\n * Convert messages to indexed attributes for tracing\n */\nexport function messagesToAttributes(\n messages: AIMessage[],\n prefix: string,\n captureContent: boolean,\n): Attributes {\n const attributes: Attributes = {};\n\n for (const [index, msg] of messages.entries()) {\n const baseKey = `${prefix}.${index}`;\n\n // Always capture role\n attributes[`${baseKey}.role`] = msg.role;\n\n // Optionally capture content\n if (captureContent && msg.content) {\n if (typeof msg.content === 'string') {\n attributes[`${baseKey}.content`] = msg.content;\n } else if (Array.isArray(msg.content)) {\n // For multi-modal content, extract text parts\n const textParts = msg.content\n .filter((part) => part.type === 'text' && part.text)\n .map((part) => part.text)\n .join(' ');\n if (textParts) {\n attributes[`${baseKey}.content`] = textParts;\n }\n }\n }\n\n // Capture tool information if present\n if (msg.toolInvocations && msg.toolInvocations.length > 0) {\n attributes[`${baseKey}.tool_calls`] = msg.toolInvocations.length;\n }\n }\n\n return attributes;\n}\n\n/**\n * Convert prompt string to attributes\n */\nexport function promptToAttributes(prompt: string, captureContent: boolean): Attributes {\n const attributes: Attributes = {};\n\n attributes[`${ATTR_GEN_AI_PROMPT}.0.role`] = 'user';\n if (captureContent) {\n attributes[`${ATTR_GEN_AI_PROMPT}.0.content`] = prompt;\n }\n\n return attributes;\n}\n\n/**\n * Convert completion to attributes\n */\nexport function completionToAttributes(\n text: string,\n finishReason: string | undefined,\n captureContent: boolean,\n): Attributes {\n const attributes: Attributes = {};\n\n attributes[`${ATTR_GEN_AI_COMPLETION}.0.role`] = 'assistant';\n if (captureContent) {\n attributes[`${ATTR_GEN_AI_COMPLETION}.0.content`] = text;\n }\n if (finishReason) {\n attributes[`${ATTR_GEN_AI_COMPLETION}.0.finish_reason`] = finishReason;\n }\n\n return attributes;\n}\n\n/**\n * Extract token usage attributes\n */\nexport function tokenUsageToAttributes(usage: TokenUsage | undefined): Attributes {\n if (!usage) {\n return {};\n }\n\n const attributes: Attributes = {};\n\n // Handle Vercel AI SDK format (inputTokens, outputTokens)\n if (usage.inputTokens !== undefined) {\n attributes['gen_ai.usage.prompt_tokens'] = usage.inputTokens;\n attributes['gen_ai.usage.input_tokens'] = usage.inputTokens;\n attributes['llm.usage.prompt_tokens'] = usage.inputTokens;\n }\n // Handle legacy format (promptTokens)\n else if (usage.promptTokens !== undefined) {\n attributes['gen_ai.usage.prompt_tokens'] = usage.promptTokens;\n attributes['gen_ai.usage.input_tokens'] = usage.promptTokens;\n attributes['llm.usage.prompt_tokens'] = usage.promptTokens;\n }\n\n // Handle Vercel AI SDK format (outputTokens)\n if (usage.outputTokens !== undefined) {\n attributes['gen_ai.usage.completion_tokens'] = usage.outputTokens;\n attributes['gen_ai.usage.output_tokens'] = usage.outputTokens;\n attributes['llm.usage.completion_tokens'] = usage.outputTokens;\n }\n // Handle legacy format (completionTokens)\n else if (usage.completionTokens !== undefined) {\n attributes['gen_ai.usage.completion_tokens'] = usage.completionTokens;\n attributes['gen_ai.usage.output_tokens'] = usage.completionTokens;\n attributes['llm.usage.completion_tokens'] = usage.completionTokens;\n }\n\n if (usage.totalTokens === undefined) {\n // Calculate total if not provided\n const inputTokens = usage.inputTokens || usage.promptTokens;\n const outputTokens = usage.outputTokens || usage.completionTokens;\n if (inputTokens !== undefined && outputTokens !== undefined) {\n const totalTokens = inputTokens + outputTokens;\n attributes['gen_ai.usage.total_tokens'] = totalTokens;\n attributes['llm.usage.total_tokens'] = totalTokens;\n }\n } else {\n attributes['gen_ai.usage.total_tokens'] = usage.totalTokens;\n attributes['llm.usage.total_tokens'] = usage.totalTokens;\n }\n\n return attributes;\n}\n\n/**\n * Check if error should be recorded\n */\nexport function shouldRecordError(error: unknown): boolean {\n // Don't record user cancellations as errors\n if (error instanceof Error) {\n const message = error.message.toLowerCase();\n if (message.includes('abort') || message.includes('cancel')) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Safe JSON stringify for attributes\n */\nexport function safeStringify(value: unknown): string {\n try {\n if (typeof value === 'string') {\n return value;\n }\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Get environment variable as boolean\n */\nexport function getEnvBool(name: string): boolean | undefined {\n const value = process.env[name];\n if (value === undefined) {\n return undefined;\n }\n return value.toLowerCase() === 'true' || value === '1';\n}\n\n/**\n * Check if a value is a promise\n */\nexport function isPromise(value: unknown): value is Promise<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'then' in value &&\n typeof (value as any).then === 'function'\n );\n}\n\n/**\n * Check if a value is an async iterable\n */\nexport function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return value !== null && typeof value === 'object' && Symbol.asyncIterator in value;\n}\n","import { context, SpanStatusCode, trace } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\n\nimport {\n ATTR_GEN_AI_RESPONSE_ID,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_RESPONSE_FINISH_REASONS,\n SPAN_NAME_GEN_AI_CHAT,\n OPERATION_NAME_CHAT,\n} from '../semconv';\nimport type { GenerationParams, TextGenerationResult, ProviderInfo } from '../types';\nimport { messagesToAttributes, promptToAttributes, completionToAttributes, tokenUsageToAttributes } from '../utils';\n\nimport { BasePatcher } from './base-patcher';\n\n// Define function signature for original generateText function\ntype OriginalGenerateTextFunction = (params: GenerationParams) => Promise<TextGenerationResult>;\n\n// Define interface for createSpan result\ninterface ICreateSpanResult {\n span: Span;\n provider: ProviderInfo;\n modelId: string;\n}\n\nexport class GenerateTextPatcher extends BasePatcher {\n patch(original: OriginalGenerateTextFunction): OriginalGenerateTextFunction {\n return async (params: GenerationParams): Promise<TextGenerationResult> => {\n const config = this.context.getConfig();\n const startTime = globalThis.performance.now();\n\n const { span, provider, modelId } = this.createSpan(\n SPAN_NAME_GEN_AI_CHAT,\n params,\n OPERATION_NAME_CHAT\n ) as ICreateSpanResult;\n\n // Add prompt/messages attributes\n if (params.prompt) {\n span.setAttributes(\n promptToAttributes(params.prompt, config.captureMessageContent || false),\n );\n } else if (params.messages) {\n span.setAttributes(\n messagesToAttributes(\n params.messages,\n 'gen_ai.prompt',\n config.captureMessageContent || false,\n ),\n );\n\n // Emit message events if enabled\n if (config.emitEvents) {\n this.context.emitMessageEvents(params.messages, provider.system, span);\n }\n }\n\n try {\n const result = await context.with(trace.setSpan(context.active(), span), () =>\n original(params),\n );\n\n // Set response attributes\n if (result.response) {\n span.setAttributes({\n ...(result.response.id && { [ATTR_GEN_AI_RESPONSE_ID]: result.response.id }),\n ...(result.response.model && { [ATTR_GEN_AI_RESPONSE_MODEL]: result.response.model }),\n });\n }\n\n // Set finish reason\n if (result.finishReason) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [result.finishReason]);\n }\n\n // Set completion attributes\n span.setAttributes(\n completionToAttributes(\n result.text,\n result.finishReason,\n config.captureMessageContent || false,\n ),\n );\n\n // Set token usage - check different possible locations\n const usage = result.usage || result.totalUsage || result.steps?.[0]?.usage;\n if (usage) {\n span.setAttributes(tokenUsageToAttributes(usage));\n\n // Record metrics\n if (config.enableMetrics) {\n this.context.recordTokenMetrics(usage, provider.system, modelId);\n }\n }\n\n // Emit assistant message event\n if (config.emitEvents) {\n this.context.emitAssistantMessageEvent(result.text, provider.system, span);\n }\n\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n this.handleError(error, span);\n throw error;\n } finally {\n this.finalizeDuration(span, startTime, config, provider, modelId, OPERATION_NAME_CHAT);\n }\n };\n }\n}\n","import { context, trace } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\n\nimport {\n SPAN_NAME_GEN_AI_CHAT,\n OPERATION_NAME_CHAT,\n} from '../semconv';\nimport type { StreamHandler } from '../stream-handler';\nimport type { GenerationParams, ProviderInfo } from '../types';\nimport { messagesToAttributes, promptToAttributes } from '../utils';\n\nimport { BasePatcher } from './base-patcher';\nimport type { PatcherContext } from './base-patcher';\n\n// Define function signature for original streamText function\ntype OriginalStreamTextFunction = (params: GenerationParams) => Promise<unknown>;\n\n// Define interface for createSpan result\ninterface ICreateSpanResult {\n span: Span;\n provider: ProviderInfo;\n modelId: string;\n}\n\n\nexport class StreamTextPatcher extends BasePatcher {\n constructor(\n context: PatcherContext,\n private streamHandler: StreamHandler\n ) {\n super(context);\n }\n\n patch(original: OriginalStreamTextFunction): OriginalStreamTextFunction {\n return async (params: GenerationParams): Promise<unknown> => {\n const config = this.context.getConfig();\n const startTime = globalThis.performance.now();\n\n const { span, provider, modelId } = this.createSpan(\n SPAN_NAME_GEN_AI_CHAT,\n params,\n OPERATION_NAME_CHAT,\n { 'gen_ai.streaming': true }\n ) as ICreateSpanResult;\n\n // Add prompt/messages attributes\n if (params.prompt) {\n span.setAttributes(\n promptToAttributes(params.prompt, config.captureMessageContent || false),\n );\n } else if (params.messages) {\n span.setAttributes(\n messagesToAttributes(\n params.messages,\n 'gen_ai.prompt',\n config.captureMessageContent || false,\n ),\n );\n\n // Emit message events if enabled\n if (config.emitEvents) {\n this.context.emitMessageEvents(params.messages, provider.system, span);\n }\n }\n\n try {\n const stream = await context.with(trace.setSpan(context.active(), span), () =>\n original(params),\n );\n\n // Wrap the stream to capture completion data\n return this.streamHandler.wrapStream(stream, span, config, provider, modelId, startTime);\n } catch (error) {\n this.handleError(error, span);\n span.end();\n throw error;\n }\n };\n }\n}\n","import { context, SpanStatusCode, trace } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\n\nimport {\n ATTR_GEN_AI_RESPONSE_ID,\n ATTR_GEN_AI_RESPONSE_MODEL,\n SPAN_NAME_GEN_AI_EMBEDDINGS,\n OPERATION_NAME_EMBEDDINGS,\n} from '../semconv';\nimport type { EmbeddingResult, ProviderInfo, GenerationParams } from '../types';\nimport { tokenUsageToAttributes } from '../utils';\n\nimport { BasePatcher } from './base-patcher';\n\n// Define interfaces for embedding functions\ninterface IEmbeddingParams {\n value?: string;\n values?: string[];\n model?: string | { [key: string]: unknown };\n [key: string]: unknown;\n}\n\ntype OriginalEmbedFunction = (params: IEmbeddingParams) => Promise<EmbeddingResult>;\n\n// Define interface for createSpan result\ninterface ICreateSpanResult {\n span: Span;\n provider: ProviderInfo;\n modelId: string;\n}\n\nexport class EmbeddingsPatcher extends BasePatcher {\n patch(original: OriginalEmbedFunction, isMany: boolean = false): OriginalEmbedFunction {\n return async (params: IEmbeddingParams): Promise<EmbeddingResult> => {\n const config = this.context.getConfig();\n const startTime = globalThis.performance.now();\n\n const additionalAttributes = isMany\n ? { 'gen_ai.embeddings.count': params.values ? params.values.length : 0 }\n : {};\n\n const { span, provider, modelId } = this.createSpan(\n SPAN_NAME_GEN_AI_EMBEDDINGS,\n params as GenerationParams,\n OPERATION_NAME_EMBEDDINGS,\n additionalAttributes\n ) as ICreateSpanResult;\n\n // Add input text if capturing content (for single embed)\n if (!isMany && config.captureMessageContent && params.value) {\n span.setAttribute('gen_ai.prompt.0.content', params.value);\n }\n\n try {\n const result = await context.with(trace.setSpan(context.active(), span), () =>\n original(params),\n );\n\n // Set response attributes\n if (result.response) {\n span.setAttributes({\n ...(result.response.id && { [ATTR_GEN_AI_RESPONSE_ID]: result.response.id }),\n ...(result.response.model && { [ATTR_GEN_AI_RESPONSE_MODEL]: result.response.model }),\n });\n }\n\n // Set embedding dimensions\n if (isMany) {\n if (result.embeddings && result.embeddings.length > 0 && result.embeddings[0]) {\n span.setAttribute('gen_ai.response.embedding_dimensions', result.embeddings[0].length);\n }\n } else {\n if (result.embedding) {\n span.setAttribute('gen_ai.response.embedding_dimensions', result.embedding.length);\n }\n }\n\n // Set token usage\n if (result.usage) {\n span.setAttributes(tokenUsageToAttributes(result.usage));\n\n // Record metrics\n if (config.enableMetrics) {\n this.context.recordTokenMetrics(result.usage, provider.system, modelId);\n }\n }\n\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n this.handleError(error, span);\n throw error;\n } finally {\n this.finalizeDuration(span, startTime, config, provider, modelId, OPERATION_NAME_EMBEDDINGS);\n }\n };\n }\n}\n","/* eslint-disable unicorn/no-this-assignment, @typescript-eslint/no-this-alias, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-return, @typescript-eslint/explicit-module-boundary-types, no-undef */\nimport { SpanStatusCode } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\n\nimport {\n ATTR_GEN_AI_RESPONSE_ID,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_RESPONSE_FINISH_REASONS,\n OPERATION_NAME_CHAT,\n} from './semconv';\nimport type { VercelAIInstrumentationConfig } from './types';\nimport { completionToAttributes, tokenUsageToAttributes } from './utils';\n\nexport interface StreamHandlerContext {\n recordTokenMetrics: (usage: any, system: string, model: string) => void;\n recordDurationMetric: (duration: number, system: string, model: string, operation: string) => void;\n}\n\nexport class StreamHandler {\n constructor(private context: StreamHandlerContext) {}\n\n wrapStream(\n stream: any,\n span: Span,\n config: VercelAIInstrumentationConfig,\n provider: any,\n modelId: string,\n startTime: number,\n ) {\n const self = this;\n let fullText = '';\n let finishReason: string | undefined;\n let usage: any;\n let response: any;\n\n // Create a proxy for the stream\n const wrappedStream = new Proxy(stream, {\n get(target, prop) {\n // Special handling for async iterator (direct stream consumption)\n if (prop === Symbol.asyncIterator) {\n return async function* () {\n try {\n for await (const chunk of target) {\n // Accumulate data from chunks\n if (chunk.type === 'text-delta' && chunk.textDelta) {\n fullText += chunk.textDelta;\n } else if (chunk.type === 'finish') {\n finishReason = chunk.finishReason;\n usage = chunk.usage;\n } else if (chunk.type === 'response-metadata') {\n response = chunk.response;\n }\n\n yield chunk;\n }\n } finally {\n self.finalizeStream(\n span,\n config,\n provider,\n modelId,\n startTime,\n fullText,\n finishReason,\n usage,\n response\n );\n }\n };\n }\n\n // Special handling for textStream and other async iterables\n if (prop === 'textStream' || prop === 'fullStream') {\n const originalStream = target[prop];\n\n // Create a wrapped async iterable\n return {\n [Symbol.asyncIterator]: async function* () {\n try {\n for await (const chunk of originalStream) {\n // For textStream, chunks are just strings\n if (prop === 'textStream') {\n fullText += chunk;\n }\n yield chunk;\n }\n } finally {\n // Get usage from the parent stream\n const streamUsage = await target.usage.catch(() => null);\n if (streamUsage) {\n usage = streamUsage;\n }\n self.finalizeStream(\n span,\n config,\n provider,\n modelId,\n startTime,\n fullText,\n finishReason,\n usage,\n response\n );\n }\n }\n };\n }\n\n // For all other properties, return the original\n const value = target[prop];\n if (typeof value === 'function') {\n return value.bind(target);\n }\n return value;\n },\n });\n\n return wrappedStream;\n }\n\n private finalizeStream(\n span: Span,\n config: VercelAIInstrumentationConfig,\n provider: any,\n modelId: string,\n startTime: number,\n fullText: string,\n finishReason: string | undefined,\n usage: any,\n response: any\n ): void {\n // Set final attributes when stream completes\n if (response) {\n span.setAttributes({\n ...(response.id && { [ATTR_GEN_AI_RESPONSE_ID]: response.id }),\n ...(response.model && { [ATTR_GEN_AI_RESPONSE_MODEL]: response.model }),\n });\n }\n\n if (finishReason) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [finishReason]);\n }\n\n if (fullText) {\n span.setAttributes(\n completionToAttributes(\n fullText,\n finishReason,\n config.captureMessageContent || false,\n ),\n );\n }\n\n if (usage) {\n span.setAttributes(tokenUsageToAttributes(usage));\n\n // Record metrics\n if (config.enableMetrics) {\n this.context.recordTokenMetrics(usage, provider.system, modelId);\n }\n }\n\n // Record duration metric\n if (config.enableMetrics) {\n const duration = (performance.now() - startTime) / 1000;\n this.context.recordDurationMetric(duration, provider.system, modelId, OPERATION_NAME_CHAT);\n }\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n }\n}\n","/* eslint-disable @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument */\nimport { context, trace } from '@opentelemetry/api';\nimport type { Span, Histogram } from '@opentelemetry/api';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\n\nimport {\n ATTR_EVENT_NAME,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_TOKEN_TYPE,\n EVENT_GEN_AI_USER_MESSAGE,\n EVENT_GEN_AI_ASSISTANT_MESSAGE,\n EVENT_GEN_AI_SYSTEM_MESSAGE,\n EVENT_GEN_AI_TOOL_MESSAGE,\n TOKEN_TYPE_INPUT,\n TOKEN_TYPE_OUTPUT,\n} from './semconv';\nimport type { AIMessage } from './types';\n\nexport class TelemetryRecorder {\n constructor(\n private genaiClientOperationDuration: Histogram,\n private genaiClientTokenUsage: Histogram,\n private logger?: any\n ) {}\n\n /**\n * Record token usage metrics\n */\n recordTokenMetrics(usage: any, system: string, model: string): void {\n if (!this.genaiClientTokenUsage) {\n return;\n }\n\n const commonAttrs = {\n [ATTR_GEN_AI_SYSTEM]: system,\n [ATTR_GEN_AI_REQUEST_MODEL]: model,\n };\n\n // Handle different token usage formats\n const inputTokens = usage.inputTokens || usage.promptTokens;\n const outputTokens = usage.outputTokens || usage.completionTokens;\n\n if (inputTokens !== undefined) {\n this.genaiClientTokenUsage.record(inputTokens, {\n ...commonAttrs,\n [ATTR_GEN_AI_TOKEN_TYPE]: TOKEN_TYPE_INPUT,\n });\n }\n\n if (outputTokens !== undefined) {\n this.genaiClientTokenUsage.record(outputTokens, {\n ...commonAttrs,\n [ATTR_GEN_AI_TOKEN_TYPE]: TOKEN_TYPE_OUTPUT,\n });\n }\n }\n\n /**\n * Record operation duration metric\n */\n recordDurationMetric(\n duration: number,\n system: string,\n model: string,\n operation: string,\n ): void {\n if (!this.genaiClientOperationDuration) {\n return;\n }\n\n this.genaiClientOperationDuration.record(duration, {\n [ATTR_GEN_AI_SYSTEM]: system,\n [ATTR_GEN_AI_REQUEST_MODEL]: model,\n [ATTR_GEN_AI_OPERATION_NAME]: operation,\n });\n }\n\n /**\n * Emit message events\n */\n emitMessageEvents(messages: AIMessage[], system: string, span: Span): void {\n if (!this.logger) {\n return;\n }\n\n const ctx = trace.setSpan(context.active(), span);\n\n for (const msg of messages) {\n let eventName: string;\n switch (msg.role) {\n case 'system': {\n eventName = EVENT_GEN_AI_SYSTEM_MESSAGE;\n break;\n }\n case 'user': {\n eventName = EVENT_GEN_AI_USER_MESSAGE;\n break;\n }\n case 'assistant': {\n eventName = EVENT_GEN_AI_ASSISTANT_MESSAGE;\n break;\n }\n case 'tool':\n case 'function': {\n eventName = EVENT_GEN_AI_TOOL_MESSAGE;\n break;\n }\n default: {\n continue;\n } // Skip unknown roles\n }\n\n this.logger.emit({\n timestamp: Date.now(),\n context: ctx,\n severityNumber: SeverityNumber.INFO,\n attributes: {\n [ATTR_EVENT_NAME]: eventName,\n [ATTR_GEN_AI_SYSTEM]: system,\n },\n body: {\n role: msg.role,\n content: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),\n name: msg.name,\n },\n });\n }\n }\n\n /**\n * Emit assistant message event\n */\n emitAssistantMessageEvent(text: string, system: string, span: Span): void {\n if (!this.logger) {\n return;\n }\n\n const ctx = trace.setSpan(context.active(), span);\n\n this.logger.emit({\n timestamp: Date.now(),\n context: ctx,\n severityNumber: SeverityNumber.INFO,\n attributes: {\n [ATTR_EVENT_NAME]: EVENT_GEN_AI_ASSISTANT_MESSAGE,\n [ATTR_GEN_AI_SYSTEM]: system,\n },\n body: {\n role: 'assistant',\n content: text,\n },\n });\n }\n}\n","import { resourceFromAttributes } from '@opentelemetry/resources';\nimport type { LogRecordExporter } from '@opentelemetry/sdk-logs';\nimport type { MetricReader } from '@opentelemetry/sdk-metrics';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport type { SpanExporter } from '@opentelemetry/sdk-trace-base';\n\nimport type { IResolvedBrizzConfig } from './config';\nimport { resolveConfig } from './config';\nimport { InstrumentationRegistry, type IInstrumentModules } from './instrumentation';\nimport { LoggingModule } from './log';\nimport type { LogLevel } from './logger';\nimport { logger } from './logger';\nimport { type IMaskingConfig } from './masking';\nimport { getMetricsReader, MetricsModule } from './metric';\nimport { getSpanProcessor, TracingModule } from './trace';\n\n/**\n * Configuration options for initializing the Brizz SDK.\n *\n * @interface IBrizzInitializeOptions\n */\nexport interface IBrizzInitializeOptions {\n /** Application name for service identification */\n appName?: string;\n /** Base URL for telemetry endpoints (defaults to https://telemetry.brizz.dev) */\n baseUrl?: string;\n /** API key for authentication */\n apiKey?: string;\n /** Additional HTTP headers to include in telemetry requests */\n headers?: Record<string, string>;\n /** Disable batch processing for immediate event emission */\n disableBatch?: boolean;\n /**\n * Configuration for data masking and PII protection.\n * - `true`: Enable masking with default rules\n * - `false` or `undefined`: Disable masking\n * - `IMaskingConfig`: Enable masking with custom configuration\n */\n masking?: boolean | IMaskingConfig;\n /** Log level for SDK internal logging and OpenTelemetry diagnostic logging (debug, info, warn, error, none) */\n logLevel?: LogLevel | string;\n /**\n * Manual instrumentation modules for Next.js/Webpack environments.\n * Provide the actual imported modules to enable instrumentation in environments\n * where automatic instrumentation doesn't work properly.\n *\n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import * as LlamaIndex from 'llamaindex';\n *\n * Brizz.initialize({\n * appName: 'my-app',\n * instrumentModules: {\n * openAI: OpenAI,\n * llamaindex: LlamaIndex\n * }\n * });\n * ```\n */\n instrumentModules?: IInstrumentModules;\n /**\n * Disable the internal NodeSDK initialization and only setup telemetry modules.\n * This is useful when you want to create your own NodeSDK using Brizz utilities.\n * Brizz will automatically register its instrumentations with your SDK.\n *\n * @example\n * ```typescript\n * import { NodeSDK } from '@opentelemetry/sdk-node';\n * import { Brizz, getSpanProcessor } from 'brizz-sdk';\n *\n * // Initialize Brizz without internal NodeSDK\n * Brizz.initialize({\n * appName: 'my-app',\n * disableNodeSdk: true\n * });\n *\n * // Create your own NodeSDK\n * const sdk = new NodeSDK({\n * spanProcessors: [getSpanProcessor()],\n * // your custom configuration\n * });\n * sdk.start();\n * ```\n */\n disableNodeSdk?: boolean;\n /**\n * Custom span exporter for testing or alternative backends.\n * When provided, this exporter will be used instead of the default OTLP exporter.\n * Useful for integration testing with InMemorySpanExporter or custom exporters.\n *\n * @example\n * ```typescript\n * import { InMemorySpanExporter } from '@opentelemetry/sdk-trace-base';\n *\n * const spanExporter = new InMemorySpanExporter();\n * Brizz.initialize({\n * appName: 'test-app',\n * customSpanExporter: spanExporter\n * });\n *\n * // Later in tests\n * const spans = spanExporter.getFinishedSpans();\n * ```\n */\n customSpanExporter?: SpanExporter;\n /**\n * Custom log exporter for testing or alternative backends.\n * When provided, this exporter will be used instead of the default OTLP exporter.\n * Useful for integration testing with InMemoryLogExporter or custom exporters.\n *\n * @example\n * ```typescript\n * import { InMemoryLogExporter } from 'brizz-sdk/test-utils';\n *\n * const logExporter = new InMemoryLogExporter();\n * Brizz.initialize({\n * appName: 'test-app',\n * customLogExporter: logExporter\n * });\n *\n * // Later in tests\n * const logs = logExporter.getFinishedLogs();\n * ```\n */\n customLogExporter?: LogRecordExporter;\n /**\n * Custom metric reader for testing or alternative backends.\n * When provided, this reader will be used instead of the default OTLP exporter.\n * Useful for integration testing with InMemoryMetricReader or custom readers.\n *\n * @example\n * ```typescript\n * import { InMemoryMetricReader } from 'brizz-sdk/test-utils';\n *\n * const metricReader = new InMemoryMetricReader();\n * Brizz.initialize({\n * appName: 'test-app',\n * customMetricReader: metricReader\n * });\n *\n * // Later in tests\n * const metrics = metricReader.getCollectedMetrics();\n * ```\n */\n customMetricReader?: MetricReader;\n}\n\n/**\n * Internal implementation of the Brizz SDK.\n *\n * This class is responsible only for initialization and shutdown of the SDK.\n * All functionality is exposed through standalone utility functions.\n *\n * @class _Brizz\n * @internal\n */\nexport class _Brizz {\n private static instance: _Brizz | null = null;\n /** Flag indicating if SDK initialization has completed successfully */\n private _initialized = false;\n\n /** OpenTelemetry sdk instance */\n private _sdk: NodeSDK | null = null;\n\n static getInstance(): _Brizz {\n if (!_Brizz.instance) {\n throw new Error('Brizz must be initialized before accessing TracingModule');\n }\n return _Brizz.instance;\n }\n\n /**\n * Initialize the Brizz SDK with the provided configuration.\n *\n * @param {IBrizzInitializeOptions} options - Configuration options for the SDK\n * @throws {Error} - If initialization fails\n *\n * @example\n * ```typescript\n * Brizz.initialize({\n * appName: 'my-app',\n * baseUrl: 'http://localhost:4318',\n * apiKey: 'your-api-key'\n * });\n * ```\n */\n initialize(options: IBrizzInitializeOptions): void {\n if (this._initialized) {\n logger.warn('Brizz SDK already initialized');\n return;\n }\n\n logger.info('Starting Brizz SDK initialization');\n\n try {\n const resolvedConfig = resolveConfig(options);\n this.initializeModules(resolvedConfig);\n this.setupInstrumentation(options);\n this.createAndStartNodeSDK(options, resolvedConfig);\n\n this._initialized = true;\n logger.info('Brizz SDK initialization completed successfully', {\n moduleSystem: this.detectModuleSystem(),\n });\n } catch (error) {\n logger.error('Failed to initialize Brizz SDK', { error });\n throw new Error(`Failed to initialize SDK: ${String(error)}`);\n }\n }\n\n /**\n * Set up instrumentation registry and configure manual modules.\n * @private\n */\n private setupInstrumentation(options: IBrizzInitializeOptions): void {\n const registry = InstrumentationRegistry.getInstance();\n\n if (options.instrumentModules && Object.keys(options.instrumentModules).length > 0) {\n registry.setManualModules(options.instrumentModules);\n }\n }\n\n /**\n * Create and start NodeSDK if not disabled.\n * Only handles manual instrumentations now - auto instrumentations are loaded at import time.\n * @private\n */\n private createAndStartNodeSDK(\n options: IBrizzInitializeOptions,\n resolvedConfig: IResolvedBrizzConfig,\n ): void {\n if (options.disableNodeSdk) {\n logger.info('NodeSDK disabled - only telemetry modules initialized');\n return;\n }\n\n const registry = InstrumentationRegistry.getInstance();\n const manualInstrumentations = registry.getManualInstrumentations();\n\n this._sdk = new NodeSDK({\n spanProcessors: [getSpanProcessor()],\n metricReader: getMetricsReader(),\n resource: resourceFromAttributes({\n 'service.name': resolvedConfig.appName,\n }),\n instrumentations: manualInstrumentations,\n });\n this._sdk.start();\n\n if (manualInstrumentations.length > 0) {\n logger.info(`NodeSDK started with ${manualInstrumentations.length} manual instrumentations`);\n } else {\n logger.info('NodeSDK started - using auto-instrumentations loaded at import time');\n }\n }\n\n /**\n * Initialize telemetry modules.\n *\n * Sets up the tracing, metrics, and logging modules with their\n * respective exporters and processors.\n *\n * @param {IResolvedBrizzConfig} config - Resolved configuration\n * @private\n */\n private initializeModules(config: IResolvedBrizzConfig): void {\n logger.info('Initializing telemetry modules');\n\n // Initialize tracing module\n logger.debug('Initializing tracing module');\n const tracingModule = new TracingModule();\n tracingModule.setup(config);\n\n // Initialize metrics module\n logger.debug('Initializing metrics module');\n const metricsModule = new MetricsModule();\n metricsModule.setup(config);\n\n // Initialize logging module\n logger.debug('Initializing logging module');\n const loggingModule = new LoggingModule();\n loggingModule.setup(config);\n\n logger.info('All telemetry modules initialized successfully');\n }\n\n /**\n * Detect the current module system (ESM or CJS) using reliable indicators\n *\n * @returns {string} - 'ESM' or 'CJS'\n * @private\n */\n private detectModuleSystem(): string {\n const inCJS =\n typeof module !== 'undefined' &&\n typeof exports !== 'undefined' &&\n typeof require === 'function' &&\n typeof __filename === 'string' &&\n typeof __dirname === 'string' &&\n\n this === (typeof exports !== 'undefined' ? exports : undefined); // top-level `this` is exports in CJS, undefined in ESM\n\n return inCJS ? 'CJS' : 'ESM';\n }\n\n /**\n * Gracefully shutdown the Brizz SDK.\n *\n * This method stops all telemetry collection, flushes any pending data,\n * and releases resources. Should be called before application termination.\n *\n * @returns {Promise<void>} - Resolves when shutdown is complete\n * @throws {Error} - If shutdown fails\n *\n * @example\n * ```typescript\n * // Shutdown before app exit\n * await Brizz.shutdown();\n * ```\n */\n public async shutdown(): Promise<void> {\n if (!this._initialized) {\n logger.warn('Brizz SDK not initialized');\n return;\n }\n\n try {\n // Shutdown all modules\n await this.shutdownModules();\n await this._sdk?.shutdown();\n\n // Clear all references\n this._initialized = false;\n this._sdk = null;\n _Brizz.instance = null;\n\n logger.info('Brizz SDK shut down successfully');\n } catch (error) {\n // Suppress network errors during shutdown in tests\n if (error instanceof Error && error.message.includes('ENOTFOUND')) {\n logger.debug(`Network error during shutdown (expected in tests): ${error.message}`);\n } else {\n logger.error(`Failed to shutdown Brizz SDK: ${String(error)}`);\n throw error;\n }\n }\n }\n\n /**\n * Shutdown all telemetry modules.\n * @private\n */\n private async shutdownModules(): Promise<void> {\n logger.info('Shutting down telemetry modules');\n\n try {\n // Shutdown tracing module\n try {\n const tracingModule = TracingModule.getInstance();\n await tracingModule.shutdown();\n } catch {\n logger.debug('Tracing module already shut down or not initialized');\n }\n\n // Shutdown metrics module\n try {\n const metricsModule = MetricsModule.getInstance();\n metricsModule.shutdown();\n } catch {\n logger.debug('Metrics module already shut down or not initialized');\n }\n\n // Shutdown logging module\n try {\n const loggingModule = LoggingModule.getInstance();\n await loggingModule.shutdown();\n } catch {\n logger.debug('Logging module already shut down or not initialized');\n }\n\n logger.info('All telemetry modules shut down successfully');\n } catch (error) {\n logger.error('Error shutting down modules', { error });\n throw error;\n }\n }\n}\n\nexport const Brizz = new _Brizz();\n","import type { NodeSDK } from '@opentelemetry/sdk-node';\n\nimport type { IBrizzInitializeOptions } from '../index';\n\nimport { logger, DEFAULT_LOG_LEVEL, parseLogLevel, setLogLevel } from './logger';\nimport type { LogLevel } from './logger';\nimport type { IMaskingConfig } from './masking';\n\nexport interface IResolvedBrizzConfig extends Omit<IBrizzInitializeOptions, 'masking'> {\n appName: string;\n baseUrl: string;\n headers: Record<string, string>;\n disableBatch: boolean;\n apiKey?: string;\n logLevel: LogLevel;\n nodeSDK?: NodeSDK | null;\n masking?: IMaskingConfig;\n}\n\nexport function resolveConfig(options: IBrizzInitializeOptions): IResolvedBrizzConfig {\n // Resolve log level first so we can set it before other logging\n const envLogLevel = process.env['BRIZZ_LOG_LEVEL'] || options.logLevel?.toString() || DEFAULT_LOG_LEVEL.toString();\n let resolvedLogLevel: LogLevel;\n if (envLogLevel) {\n resolvedLogLevel = parseLogLevel(envLogLevel);\n } else if (typeof options.logLevel === 'string') {\n resolvedLogLevel = parseLogLevel(options.logLevel);\n } else {\n resolvedLogLevel = options.logLevel || DEFAULT_LOG_LEVEL;\n }\n\n setLogLevel(resolvedLogLevel);\n\n // Determine masking status for logging\n let maskingStatus: string;\n if (options.masking === true) {\n maskingStatus = 'enabled';\n } else if (options.masking === false) {\n maskingStatus = 'disabled';\n } else if (typeof options.masking === 'object') {\n maskingStatus = 'custom';\n } else {\n maskingStatus = 'default-disabled';\n }\n\n logger.debug('Starting configuration resolution', {\n appName: options.appName,\n baseUrl: options.baseUrl,\n hasApiKey: !!options.apiKey,\n disableBatch: options.disableBatch,\n logLevel: resolvedLogLevel,\n headersCount: Object.keys(options.headers || {}).length,\n masking: maskingStatus,\n });\n\n // Resolve masking configuration\n let resolvedMasking: IMaskingConfig | undefined;\n if (options.masking === true) {\n // Enable masking with all defaults\n resolvedMasking = {\n spanMasking: {},\n eventMasking: {},\n };\n } else if (options.masking && typeof options.masking === 'object') {\n // Use provided masking config\n resolvedMasking = options.masking;\n }\n // If options.masking is false or undefined, resolvedMasking remains undefined\n\n // Resolve all configuration with environment variables taking precedence\n const resolvedConfig: IResolvedBrizzConfig = {\n ...options,\n appName: process.env['BRIZZ_APP_NAME'] || options.appName || 'unknown-app',\n baseUrl: process.env['BRIZZ_BASE_URL'] || options.baseUrl || 'https://telemetry.brizz.dev',\n headers: { ...options.headers },\n apiKey: process.env['BRIZZ_API_KEY'] || options.apiKey,\n disableBatch: process.env['BRIZZ_DISABLE_BATCH'] === 'true' || !!options.disableBatch,\n logLevel: resolvedLogLevel,\n masking: resolvedMasking,\n };\n // Add Authorization header if API key is present\n if (resolvedConfig.apiKey) {\n resolvedConfig.headers['Authorization'] = `Bearer ${resolvedConfig.apiKey}`;\n }\n\n // Process additional environment variables\n if (process.env['BRIZZ_HEADERS']) {\n try {\n const envHeaders = JSON.parse(process.env['BRIZZ_HEADERS']) as Record<string, string>;\n Object.assign(resolvedConfig.headers, envHeaders);\n logger.debug('Added headers from environment variable', {\n headers: Object.keys(envHeaders),\n });\n } catch (error) {\n logger.error('Failed to parse BRIZZ_HEADERS environment variable', { error });\n throw new Error('Invalid JSON in BRIZZ_HEADERS environment variable');\n }\n }\n\n logger.debug('Configuration resolved with environment variables', {\n appName: resolvedConfig.appName,\n baseUrl: resolvedConfig.baseUrl,\n hasApiKey: !!resolvedConfig.apiKey,\n disableBatch: resolvedConfig.disableBatch,\n envOverrides: {\n hasEnvApiKey: !!process.env['BRIZZ_API_KEY'],\n hasEnvBaseUrl: !!process.env['BRIZZ_BASE_URL'],\n hasEnvBatch: !!process.env['BRIZZ_DISABLE_BATCH'],\n hasEnvHeaders: !!process.env['BRIZZ_HEADERS'],\n },\n });\n\n return resolvedConfig;\n}\n\n// Legacy function for backward compatibility\nexport function processEnvironmentConfig(options: IBrizzInitializeOptions): IResolvedBrizzConfig {\n return resolveConfig(options);\n}\n","import type { Instrumentation } from '@opentelemetry/instrumentation';\nimport { AnthropicInstrumentation } from '@traceloop/instrumentation-anthropic';\nimport { BedrockInstrumentation } from '@traceloop/instrumentation-bedrock';\nimport { ChromaDBInstrumentation } from '@traceloop/instrumentation-chromadb';\nimport { CohereInstrumentation } from '@traceloop/instrumentation-cohere';\nimport { LangChainInstrumentation } from '@traceloop/instrumentation-langchain';\nimport { LlamaIndexInstrumentation } from '@traceloop/instrumentation-llamaindex';\nimport { OpenAIInstrumentation } from '@traceloop/instrumentation-openai';\nimport { PineconeInstrumentation } from '@traceloop/instrumentation-pinecone';\nimport { QdrantInstrumentation } from '@traceloop/instrumentation-qdrant';\nimport { TogetherInstrumentation } from '@traceloop/instrumentation-together';\nimport { VertexAIInstrumentation } from '@traceloop/instrumentation-vertexai';\n\nimport { logger } from '../logger';\n\nimport { VercelAIInstrumentation } from './vercel-ai';\n\n\n/**\n * Module types for manual instrumentation (for Next.js/Webpack compatibility)\n */\nexport interface IInstrumentModules {\n openAI?: unknown;\n anthropic?: unknown;\n cohere?: unknown;\n google_vertexai?: unknown;\n google_aiplatform?: unknown;\n bedrock?: unknown;\n pinecone?: unknown;\n langchain?: {\n chains?: unknown;\n agents?: unknown;\n tools?: unknown;\n };\n llamaindex?: unknown;\n chromadb?: unknown;\n qdrant?: unknown;\n together?: unknown;\n vercelAI?: unknown;\n}\n\ninterface IInstrumentationConfig {\n class: new (config: { exceptionLogger: (error: Error) => void }) => Instrumentation;\n name: string;\n module?: unknown;\n}\n\nexport class InstrumentationRegistry {\n private static instance: InstrumentationRegistry;\n private manualModules: IInstrumentModules | null = null;\n\n public static getInstance(): InstrumentationRegistry {\n if (!InstrumentationRegistry.instance) {\n InstrumentationRegistry.instance = new InstrumentationRegistry();\n }\n return InstrumentationRegistry.instance;\n }\n\n /**\n * Set manual instrumentation modules for Next.js/Webpack environments\n */\n public setManualModules(modules: IInstrumentModules): void {\n this.manualModules = modules;\n logger.info('Manual instrumentation modules configured for Next.js/Webpack compatibility');\n }\n\n /**\n * Helper to load instrumentation with optional manual module\n */\n private loadInstrumentation<T extends Instrumentation>(\n InstrumentationClass: new (config: { exceptionLogger: (error: Error) => void }) => T,\n name: string,\n manualModule?: unknown,\n exceptionLogger?: (error: Error) => void,\n ): T | null {\n try {\n const inst = new InstrumentationClass({\n exceptionLogger:\n exceptionLogger ||\n ((error) => logger.error(`Exception in instrumentation: ${String(error)}`)),\n });\n if (manualModule) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (inst as any).manuallyInstrument(manualModule);\n logger.debug(`Manual instrumentation enabled for ${name}`);\n }\n return inst;\n } catch (error) {\n logger.error(`Failed to load ${name} instrumentation: ${String(error)}`);\n return null;\n }\n }\n\n /**\n * Get manual instrumentations only.\n * Auto-instrumentations are handled at import time.\n */\n public getManualInstrumentations(): Instrumentation[] {\n if (!this.manualModules || Object.keys(this.manualModules).length === 0) {\n logger.debug('No manual instrumentation modules configured');\n return [];\n }\n\n const instrumentations: Instrumentation[] = [];\n const exceptionLogger = (error: Error) => {\n logger.error(`Exception in manual instrumentation: ${String(error)}`);\n };\n\n this.loadManualInstrumentations(instrumentations, exceptionLogger);\n\n logger.info(`Loaded ${instrumentations.length} manual instrumentations`);\n return instrumentations;\n }\n\n /**\n * Load manual instrumentations only (with modules provided by user).\n * @private\n */\n private loadManualInstrumentations(\n instrumentations: Instrumentation[],\n exceptionLogger: (error: Error) => void,\n ): void {\n const instrumentationConfigs: IInstrumentationConfig[] = [\n { class: OpenAIInstrumentation, name: 'OpenAI', module: this.manualModules?.openAI },\n { class: AnthropicInstrumentation, name: 'Anthropic', module: this.manualModules?.anthropic },\n { class: CohereInstrumentation, name: 'Cohere', module: this.manualModules?.cohere },\n {\n class: VertexAIInstrumentation,\n name: 'Vertex AI',\n module: this.manualModules?.google_vertexai,\n },\n { class: BedrockInstrumentation, name: 'Bedrock', module: this.manualModules?.bedrock },\n { class: PineconeInstrumentation, name: 'Pinecone', module: this.manualModules?.pinecone },\n { class: LangChainInstrumentation, name: 'LangChain', module: this.manualModules?.langchain },\n {\n class: LlamaIndexInstrumentation,\n name: 'LlamaIndex',\n module: this.manualModules?.llamaindex,\n },\n { class: ChromaDBInstrumentation, name: 'ChromaDB', module: this.manualModules?.chromadb },\n { class: QdrantInstrumentation, name: 'Qdrant', module: this.manualModules?.qdrant },\n { class: TogetherInstrumentation, name: 'Together', module: this.manualModules?.together },\n { class: VercelAIInstrumentation, name: 'Vercel AI', module: this.manualModules?.vercelAI },\n ];\n\n // Only load instrumentations that have manual modules configured\n for (const config of instrumentationConfigs) {\n if (config.module) {\n const instrumentation = this.loadInstrumentation(\n config.class,\n config.name,\n config.module,\n exceptionLogger,\n );\n if (instrumentation) {\n instrumentations.push(instrumentation);\n }\n }\n }\n }\n}\n","import type { LogBody } from '@opentelemetry/api-logs';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';\nimport { resourceFromAttributes } from '@opentelemetry/resources';\nimport {\n LoggerProvider,\n type LogRecordExporter,\n type LogRecordProcessor,\n} from '@opentelemetry/sdk-logs';\n\nimport type { IResolvedBrizzConfig } from '../config';\nimport { logger } from '../logger';\n\nimport {\n BrizzBatchLogRecordProcessor,\n BrizzSimpleLogRecordProcessor,\n} from './processors/log-processor';\n\nexport class LoggingModule {\n private static instance: LoggingModule | null = null;\n private logExporter: LogRecordExporter | null = null;\n private logProcessor: LogRecordProcessor | null = null;\n private loggerProvider: LoggerProvider | null = null;\n\n static getInstance(): LoggingModule {\n if (!LoggingModule.instance) {\n throw new Error('Brizz must be initialized before accessing LoggingModule');\n }\n return LoggingModule.instance;\n }\n\n /**\n * Initialize the logging module with the provided configuration\n */\n setup(config: IResolvedBrizzConfig): void {\n logger.info('Setting up logging module');\n\n // Initialize exporter\n this.initLogExporter(config);\n\n // Initialize processor with masking support\n this.initLogProcessor(config);\n\n // Initialize logger provider\n this.initLoggerProvider(config);\n\n // Set as module instance for standalone functions\n LoggingModule.instance = this;\n\n logger.info('Logging module setup completed');\n }\n\n /**\n * Initialize the log exporter\n */\n private initLogExporter(config: IResolvedBrizzConfig): void {\n if (this.logExporter) {\n logger.debug('Log exporter already initialized, skipping re-initialization');\n return;\n }\n\n // Use custom log exporter if provided\n if (config.customLogExporter) {\n logger.debug('Using custom log exporter');\n this.logExporter = config.customLogExporter;\n logger.debug('Custom log exporter initialized successfully');\n return;\n }\n\n // Use default OTLP exporter\n const logsUrl = config.baseUrl.replace(/\\/$/, '') + '/v1/logs';\n logger.debug('Initializing default OTLP log exporter', { url: logsUrl });\n\n const headers = { ...config.headers };\n\n this.logExporter = new OTLPLogExporter({\n url: logsUrl,\n headers,\n });\n\n logger.debug('OTLP log exporter initialized successfully');\n }\n\n /**\n * Initialize the log processor with masking support\n */\n private initLogProcessor(config: IResolvedBrizzConfig): void {\n if (this.logProcessor) {\n logger.debug('Log processor already initialized, skipping re-initialization');\n return;\n }\n\n if (!this.logExporter) {\n throw new Error('Log exporter must be initialized before processor');\n }\n\n logger.debug('Initializing log processor', {\n disableBatch: config.disableBatch,\n hasMasking: !!config.masking?.eventMasking,\n });\n\n this.logProcessor = config.disableBatch\n ? new BrizzSimpleLogRecordProcessor(this.logExporter, config)\n : new BrizzBatchLogRecordProcessor(this.logExporter, config);\n\n logger.debug('Log processor initialized successfully');\n }\n\n /**\n * Initialize the logger provider\n */\n private initLoggerProvider(config: IResolvedBrizzConfig): void {\n if (this.loggerProvider) {\n logger.debug('Logger provider already initialized, skipping re-initialization');\n return;\n }\n\n if (!this.logProcessor) {\n throw new Error('Log processor must be initialized before logger provider');\n }\n\n logger.debug('Creating resource with service name', {\n serviceName: config.appName,\n });\n\n const resource = resourceFromAttributes({\n 'service.name': config.appName,\n });\n\n logger.debug('Creating logger provider with resource');\n this.loggerProvider = new LoggerProvider({\n resource,\n processors: [this.logProcessor],\n });\n\n logger.debug('Logger provider initialization completed');\n }\n\n /**\n * Emit a custom event to the telemetry pipeline\n */\n emitEvent(\n name: string,\n attributes?: Record<string, string | number | boolean>,\n body?: LogBody,\n severityNumber: SeverityNumber = SeverityNumber.INFO,\n ): void {\n logger.debug('Attempting to emit event', {\n name,\n hasAttributes: !!attributes,\n attributesCount: attributes ? Object.keys(attributes).length : 0,\n hasBody: !!body,\n severityNumber,\n });\n\n if (!this.loggerProvider) {\n logger.error('Cannot emit event: Logger provider not initialized');\n throw new Error('Logging module not initialized');\n }\n\n // Prepare log attributes with event name as required field\n const logAttributes: Record<string, string | number | boolean> = { 'event.name': name };\n if (attributes) {\n Object.assign(logAttributes, attributes);\n logger.debug('Combined log attributes', { attributes: Object.keys(logAttributes) });\n }\n\n // Get logger instance for event emission\n logger.debug('Getting logger instance for brizz_events');\n const eventLogger = this.loggerProvider.getLogger('brizz.events');\n\n // Emit the event\n logger.debug('Emitting log record with eventName', { eventName: name });\n try {\n eventLogger.emit({\n eventName: name,\n attributes: logAttributes,\n severityNumber: severityNumber,\n body: body,\n });\n logger.debug('Event successfully emitted', { eventName: name });\n } catch (error) {\n // Log detailed error information for debugging\n logger.error(`Failed to emit event '${name}'`, { error, eventName: name });\n logger.error('Log record that failed', {\n eventName: name,\n hasAttributes: logAttributes,\n severityNumber: severityNumber,\n hasBody: body,\n });\n throw error instanceof Error ? error : new Error(String(error));\n }\n }\n\n /**\n * Check if the module is initialized\n */\n isInitialized(): boolean {\n return this.loggerProvider !== null;\n }\n\n /**\n * Get the logger provider\n */\n getLoggerProvider(): LoggerProvider | null {\n return this.loggerProvider;\n }\n\n /**\n * Shutdown the logging module\n */\n async shutdown(): Promise<void> {\n logger.debug('Shutting down logging module');\n\n if (this.loggerProvider) {\n await this.loggerProvider.shutdown();\n this.loggerProvider = null;\n }\n\n this.logProcessor = null;\n this.logExporter = null;\n\n // Clear module instance\n if (LoggingModule.instance === this) {\n LoggingModule.instance = null;\n }\n\n logger.debug('Logging module shutdown completed');\n }\n}\n\n/**\n * Emit a custom event to the telemetry pipeline.\n * @throws {Error} - If SDK is not initialized\n */\nexport function emitEvent(\n name: string,\n attributes?: Record<string, string | number | boolean>,\n body?: LogBody,\n severityNumber: SeverityNumber = SeverityNumber.INFO,\n): void {\n return LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);\n}\n","import { context } from '@opentelemetry/api';\nimport type { AnyValue, LogAttributes } from '@opentelemetry/api-logs';\nimport type { LogRecordExporter, SdkLogRecord } from '@opentelemetry/sdk-logs';\nimport { BatchLogRecordProcessor, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs';\n\nimport type { IResolvedBrizzConfig } from '../../config';\nimport { logger } from '../../logger';\nimport { DEFAULT_PII_PATTERNS } from '../../masking/patterns';\nimport type { IAttributesMaskingRule, ILogMaskingConfig, MaskableValue } from '../../masking/types';\nimport { maskAttributes, maskValue } from '../../masking/utils';\nimport { BRIZZ, PROPERTIES_CONTEXT_KEY } from '../../semantic-conventions';\n\nexport const DEFAULT_LOG_MASKING_RULES: IAttributesMaskingRule[] = [\n {\n mode: 'partial',\n attributePattern: 'event.name',\n patterns: DEFAULT_PII_PATTERNS,\n },\n];\n\nexport class BrizzSimpleLogRecordProcessor extends SimpleLogRecordProcessor {\n public readonly config: IResolvedBrizzConfig;\n\n constructor(exporter: LogRecordExporter, config: IResolvedBrizzConfig) {\n super(exporter);\n this.config = config;\n }\n\n override onEmit(logRecord: SdkLogRecord): void {\n const maskingConfig = this.config.masking?.eventMasking;\n if (maskingConfig) {\n maskLog(logRecord, maskingConfig);\n }\n const associationProperties = context.active().getValue(PROPERTIES_CONTEXT_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n logRecord.setAttribute(`${BRIZZ}.${key}`, value as AnyValue);\n }\n }\n super.onEmit(logRecord);\n }\n}\n\nexport class BrizzBatchLogRecordProcessor extends BatchLogRecordProcessor {\n public readonly config: IResolvedBrizzConfig;\n\n constructor(exporter: LogRecordExporter, config: IResolvedBrizzConfig) {\n super(exporter);\n this.config = config;\n }\n\n override onEmit(logRecord: SdkLogRecord): void {\n const maskingConfig = this.config.masking?.eventMasking;\n if (maskingConfig) {\n maskLog(logRecord, maskingConfig);\n }\n const associationProperties = context.active().getValue(PROPERTIES_CONTEXT_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n logRecord.setAttribute(`${BRIZZ}.${key}`, value as AnyValue);\n }\n }\n super.onEmit(logRecord);\n }\n}\n\nexport function maskLog(logRecord: SdkLogRecord, config: ILogMaskingConfig): SdkLogRecord {\n if (!logRecord.attributes) {\n return logRecord;\n }\n\n let rules = config.rules || [];\n if (!config.disableDefaultRules) {\n rules = [...DEFAULT_LOG_MASKING_RULES, ...rules];\n }\n\n try {\n if (logRecord.attributes && Object.keys(logRecord.attributes).length > 0) {\n const attributesRecord: Record<string, MaskableValue> = {};\n\n for (const [key, value] of Object.entries(logRecord.attributes)) {\n attributesRecord[key] = value as MaskableValue;\n }\n\n const maskedAttributes = maskAttributes(attributesRecord, rules);\n if (maskedAttributes) {\n // Clear existing attributes and set masked ones\n const newAttributes: LogAttributes = {};\n for (const [key, value] of Object.entries(maskedAttributes)) {\n newAttributes[key] = value as AnyValue;\n }\n logRecord.setAttributes(newAttributes);\n }\n }\n\n if (config.maskBody && logRecord.body !== undefined && logRecord.body !== null) {\n let maskedBody: unknown = logRecord.body;\n for (const rule of rules) {\n maskedBody = maskValue(maskedBody, rule);\n }\n logRecord.setBody(maskedBody as AnyValue);\n }\n\n return logRecord;\n } catch (error) {\n logger.error('Error masking log record:', error);\n return logRecord;\n }\n}\n","/**\n * Default PII patterns for data masking.\n *\n * This module contains 100+ built-in patterns for detecting and masking\n * common types of personally identifiable information (PII) and sensitive data.\n * Patterns are organized by category and mirror the Python SDK implementation.\n */\n\nimport type { IPatternEntry } from './types';\n\n/**\n * All built-in PII patterns combined - mirrors Python SDK patterns.py\n */\nexport const DEFAULT_PII_PATTERNS: IPatternEntry[] = [\n // Email addresses\n {\n name: 'email_addresses',\n pattern: String.raw`\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b`,\n },\n // Phone numbers (US format)\n {\n name: 'us_phone_numbers',\n pattern: String.raw`(?:^|[\\s])(?:\\+?1[-.\\s]*)?(?:\\([0-9]{3}\\)\\s?[0-9]{3}[-.\\s]?[0-9]{4}|[0-9]{3}[-.\\s]?[0-9]{3}[-.\\s]?[0-9]{4}|[0-9]{10})(?=[\\s]|$)`,\n },\n // Social Security Numbers\n {\n name: 'ssn',\n pattern: String.raw`\\b(?!000|666|9\\d{2})\\d{3}[-\\s]?(?!00)\\d{2}[-\\s]?(?!0000)\\d{4}\\b`,\n },\n // Credit card numbers\n {\n name: 'credit_cards',\n pattern: String.raw`\\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\\\\d{3})\\\\d{11})\\b`,\n },\n {\n name: 'credit_cards_with_separators',\n pattern: String.raw`\\b(?:4\\\\d{3}|5[1-5]\\\\d{2}|3[47]\\\\d{2})[-\\s]?\\\\d{4}[-\\s]?\\\\d{4}[-\\s]?\\\\d{4}\\b`,\n },\n // IP addresses (IPv4)\n {\n name: 'ipv4_addresses',\n pattern: String.raw`\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?!\\.[0-9])\\b`,\n },\n // API keys/tokens\n {\n name: 'generic_api_keys',\n pattern: String.raw`\\b(?:[Aa][Pp][Ii][_-]?[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt])[_-]?[=:]?\\s*[\"']?(?:[a-zA-Z0-9\\-_.]{20,})[\"']?\\b`,\n },\n {\n name: 'openai_keys',\n pattern: String.raw`\\bsk[-_][a-zA-Z0-9]{20,}\\b`,\n },\n {\n name: 'base64_secrets',\n pattern: String.raw`\\b[A-Za-z0-9+/]{64,}={0,2}\\b`,\n },\n // AWS Keys\n {\n name: 'aws_access_keys',\n pattern: String.raw`\\b(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\\b`,\n },\n {\n name: 'aws_secret_keys',\n pattern: String.raw`\\b[A-Za-z0-9/+=]*[A-Z][A-Za-z0-9/+=]*[a-z][A-Za-z0-9/+=]*[/+=][A-Za-z0-9/+=]{30,}\\b`,\n },\n // GitHub tokens\n {\n name: 'github_tokens',\n pattern: String.raw`\\bghp_[a-zA-Z0-9]{36}\\b`,\n },\n // Slack tokens\n {\n name: 'slack_tokens',\n pattern: String.raw`\\bxox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24,34}\\b`,\n },\n // Stripe keys\n {\n name: 'stripe_keys',\n pattern: String.raw`\\b(?:sk|pk)_(?:test|live)_[a-zA-Z0-9]{24,}\\b`,\n },\n // JWT tokens\n {\n name: 'jwt_tokens',\n pattern: String.raw`\\beyJ[A-Za-z0-9_-]{2,}\\\\.[A-Za-z0-9_-]{2,}\\\\.[A-Za-z0-9_-]{2,}\\b`,\n },\n // MAC addresses\n {\n name: 'mac_addresses',\n pattern: String.raw`\\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\\b`,\n },\n // IPv6 addresses\n {\n name: 'ipv6_addresses',\n pattern: String.raw`\\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\b`,\n },\n // Medical records\n {\n name: 'medical_record_numbers',\n pattern: String.raw`\\b(?:[Mm][Rr][Nn])[-\\s]?\\d{6,10}\\b`,\n },\n // Bitcoin addresses\n {\n name: 'bitcoin_addresses',\n pattern: String.raw`\\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\\b`,\n },\n // Ethereum addresses\n {\n name: 'ethereum_addresses',\n pattern: String.raw`\\b0x[a-fA-F0-9]{40}(?![a-fA-F0-9])\\b`,\n },\n // UUIDs\n {\n name: 'uuids',\n pattern: String.raw`\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(?![0-9a-fA-F-])\\b`,\n },\n // Database connection strings\n {\n name: 'database_connections',\n pattern: String.raw`\\b(?:[Mm][Oo][Nn][Gg][Oo][Dd][Bb]|[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Mm][Yy][Ss][Qq][Ll]|[Rr][Ee][Dd][Ii][Ss]|[Mm][Ss][Ss][Qq][Ll]|[Oo][Rr][Aa][Cc][Ll][Ee]):\\\\/\\\\/[^\\\\s]+\\b`,\n },\n // Private keys\n {\n name: 'rsa_private_keys',\n pattern: '-----BEGIN (?:RSA )?PRIVATE KEY-----',\n },\n {\n name: 'pgp_private_keys',\n pattern: '-----BEGIN PGP PRIVATE KEY BLOCK-----',\n },\n {\n name: 'certificates',\n pattern: '-----BEGIN CERTIFICATE-----',\n },\n // Date of birth patterns\n {\n name: 'date_of_birth_us',\n pattern: String.raw`\\b(?:0[1-9]|1[0-2])[-/](?:0[1-9]|[12]\\\\d|3[01])[-/](?:19|20)\\\\d{2}\\b`,\n },\n {\n name: 'date_of_birth_iso',\n pattern: String.raw`\\b(?:19|20)\\\\d{2}[-/](?:0[1-9]|1[0-2])[-/](?:0[1-9]|[12]\\\\d|3[01])\\b`,\n },\n // US Identification Numbers\n {\n name: 'us_passport_numbers',\n pattern: String.raw`\\b[A-Z]?\\\\d{6,9}\\b`,\n },\n {\n name: 'drivers_license',\n pattern: String.raw`\\b[A-Z]{1,2}\\\\d{3,8}[-\\s]?\\\\d{2,5}[-\\s]?\\\\d{2,5}[-\\s]?\\\\d{1,5}[-\\s]?\\\\d?\\b`,\n },\n {\n name: 'bank_account_numbers',\n pattern: String.raw`\\b\\\\d{10,17}\\b`,\n },\n {\n name: 'aba_routing_numbers',\n pattern: String.raw`\\b((0[0-9])|(1[0-2])|(2[1-9])|(3[0-2])|(6[1-9])|(7[0-2])|80)([0-9]{7})\\b`,\n },\n {\n name: 'health_insurance_numbers',\n pattern: String.raw`\\b\\\\d{10}[A-Z]\\b`,\n },\n {\n name: 'employee_ids',\n pattern: String.raw`\\b(?:[Ee][Mm][Pp]|[Ee][Mm][Pp][Ll][Oo][Yy][Ee][Ee]|[Ee])[-\\s]?\\\\d{5,8}\\b`,\n },\n {\n name: 'tax_ein',\n pattern: String.raw`\\b\\\\d{2}-\\\\d{7}\\b`,\n },\n {\n name: 'medicare_beneficiary_id',\n pattern: String.raw`\\b[1-9][A-Z][A-Z0-9]\\\\d-[A-Z][A-Z0-9]\\\\d-[A-Z][A-Z0-9]\\\\d{2}\\b`,\n },\n {\n name: 'national_provider_id',\n pattern: String.raw`\\b1\\\\d{9}\\b`,\n },\n {\n name: 'dea_numbers',\n pattern: String.raw`\\b[A-Z]{2}\\\\d{7}\\b`,\n },\n {\n name: 'itin',\n pattern: String.raw`\\b9\\\\d{2}(?:[ \\\\-]?)[7,8]\\\\d(?:[ \\\\-]?)\\\\d{4}\\b`,\n },\n // Vehicle and Location\n {\n name: 'vin_numbers',\n pattern: String.raw`\\b[A-HJ-NPR-Z0-9]{17}\\b`,\n },\n {\n name: 'coordinates',\n pattern: String.raw`\\b[-+]?(?:[0-8]?\\\\d(?:\\\\.\\\\d+)?|90(?:\\\\.0+)?),\\\\s*[-+]?(?:1[0-7]\\\\d(?:\\\\.\\\\d+)?|180(?:\\\\.0+)?|[0-9]?\\\\d(?:\\\\.\\\\d+)?)\\b`,\n },\n {\n name: 'us_license_plates',\n pattern: String.raw`\\b[A-Z]{1,3}[-\\s]\\\\d{1,4}[A-Z]?\\b|\\b\\\\d{1,2}[A-Z]{1,3}\\\\d{1,4}\\b`,\n },\n {\n name: 'us_zip_codes',\n pattern: String.raw`\\b(\\\\d{5}-\\\\d{4}|\\\\d{5})\\b`,\n },\n {\n name: 'us_street_addresses',\n pattern: String.raw`\\b\\\\d{1,8}\\b[\\\\s\\\\S]{10,100}?\\b(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NC|ND|NE|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)\\b\\\\s\\\\d{5}\\b`,\n },\n // International Banking\n {\n name: 'iban',\n pattern: String.raw`\\b[A-Z]{2}\\d{2}[A-Z0-9]{4}\\d{7}([A-Z0-9]?){0,16}\\b`,\n },\n {\n name: 'swift_bic',\n pattern: String.raw`\\b[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?\\b`,\n },\n // Additional API Keys and Tokens\n {\n name: 'google_oauth',\n pattern: String.raw`\\bya29\\\\.[a-zA-Z0-9_-]{60,}\\b`,\n },\n {\n name: 'firebase_tokens',\n pattern: String.raw`\\bAAAA[A-Za-z0-9_-]{100,}\\b`,\n },\n {\n name: 'google_app_ids',\n pattern: String.raw`\\b[0-9]+-\\w+\\.apps\\.googleusercontent\\.com\\b`,\n },\n {\n name: 'facebook_secrets',\n pattern: String.raw`\\b(facebook_secret|FACEBOOK_SECRET|facebook_app_secret|FACEBOOK_APP_SECRET)[a-z_ =\\\\s\"'\\\\:]{0,5}[^a-zA-Z0-9][a-f0-9]{32}[^a-zA-Z0-9]`,\n },\n {\n name: 'github_keys',\n pattern: String.raw`\\b(GITHUB_SECRET|GITHUB_KEY|github_secret|github_key|github_token|GITHUB_TOKEN|github_api_key|GITHUB_API_KEY)[a-z_ =\\\\s\\\"'\\\\:]{0,10}[^a-zA-Z0-9][a-zA-Z0-9]{40}[^a-zA-Z0-9]`,\n },\n {\n name: 'heroku_keys',\n pattern: String.raw`\\b(heroku_api_key|HEROKU_API_KEY|heroku_secret|HEROKU_SECRET)[a-z_ =\\\\s\\\"'\\\\:]{0,10}[^a-zA-Z0-9-]\\\\w{8}(?:-\\\\w{4}){3}-\\\\w{12}[^a-zA-Z0-9\\\\-]`,\n },\n {\n name: 'slack_api_keys',\n pattern: String.raw`\\b(slack_api_key|SLACK_API_KEY|slack_key|SLACK_KEY)[a-z_ =\\\\s\\\"'\\\\:]{0,10}[^a-f0-9][a-f0-9]{32}[^a-f0-9]`,\n },\n {\n name: 'slack_api_tokens',\n pattern: String.raw`\\b(xox[pb](?:-[a-zA-Z0-9]+){4,})\\b`,\n },\n // Extended Private Keys and Certificates\n {\n name: 'dsa_private_keys',\n pattern: String.raw`-----BEGIN DSA PRIVATE KEY-----(?:[a-zA-Z0-9\\+\\=\\/\"']|\\s)+?-----END DSA PRIVATE KEY-----`,\n },\n {\n name: 'ec_private_keys',\n pattern: String.raw`-----BEGIN (?:EC|ECDSA) PRIVATE KEY-----(?:[a-zA-Z0-9\\+\\=\\/\"']|\\s)+?-----END (?:EC|ECDSA) PRIVATE KEY-----`,\n },\n {\n name: 'encrypted_private_keys',\n pattern: String.raw`-----BEGIN ENCRYPTED PRIVATE KEY-----(?:.|\\s)+?-----END ENCRYPTED PRIVATE KEY-----`,\n },\n {\n name: 'ssl_certificates',\n pattern: String.raw`-----BEGIN CERTIFICATE-----(?:.|\\n)+?\\s-----END CERTIFICATE-----`,\n },\n {\n name: 'ssh_dss_public',\n pattern: String.raw`\\bssh-dss [0-9A-Za-z+/]+[=]{2}\\b`,\n },\n {\n name: 'ssh_rsa_public',\n pattern: String.raw`\\bssh-rsa AAAA[0-9A-Za-z+/]+[=]{0,3} [^@]+@[^@]+\\b`,\n },\n {\n name: 'putty_ssh_keys',\n pattern: String.raw`PuTTY-User-Key-File-2: ssh-(?:rsa|dss)\\s*Encryption: none(?:.|\\s?)*?Private-MAC:`,\n },\n // International Phone Numbers\n {\n name: 'france_phone_numbers',\n pattern: String.raw`\\b([0O]?[1lI][1lI])?[3E][3E][0O]?[\\\\dOIlZEASB]{9}\\b`,\n },\n {\n name: 'german_phone_numbers',\n pattern: String.raw`\\b[\\d\\w]\\d{2}[\\d\\w]{6}\\d[\\d\\w]\\b`,\n },\n {\n name: 'uk_phone_numbers',\n pattern: String.raw`\\b([0O]?[1lI][1lI])?[4A][4A][\\\\dOIlZEASB]{10,11}\\b`,\n },\n // International IDs\n {\n name: 'uk_drivers_license',\n pattern: String.raw`\\b[A-Z]{5}\\d{6}[A-Z]{2}\\d{1}[A-Z]{2}\\b`,\n },\n {\n name: 'uk_passport',\n pattern: String.raw`\\b\\\\d{10}GB[RP]\\\\d{7}[UMF]{1}\\\\d{9}\\b`,\n },\n {\n name: 'argentina_dni',\n pattern: String.raw`\\b\\\\d{2}\\\\.\\\\d{3}\\\\.\\\\d{3}\\b`,\n },\n {\n name: 'australia_tfn',\n pattern: String.raw`\\b[Tt][Ff][Nn](:|:\\\\s|\\\\s|)(\\\\d{8,9})\\b`,\n },\n {\n name: 'canada_passport',\n pattern: String.raw`\\b[\\\\w]{2}[\\\\d]{6}\\b`,\n },\n {\n name: 'croatia_vat',\n pattern: String.raw`\\bHR\\\\d{11}\\b`,\n },\n {\n name: 'czech_vat',\n pattern: String.raw`\\bCZ\\\\d{8,10}\\b`,\n },\n {\n name: 'denmark_personal_id',\n pattern: String.raw`\\b(?:\\\\d{10}|\\\\d{6}[-\\\\s]\\\\d{4})\\b`,\n },\n {\n name: 'france_national_id',\n pattern: String.raw`\\b\\\\d{12}\\b`,\n },\n {\n name: 'france_ssn',\n pattern: String.raw`\\b(?:\\\\d{13}|\\\\d{13}\\\\s\\\\d{2})\\b`,\n },\n {\n name: 'france_passport',\n pattern: String.raw`\\b\\\\d{2}11\\\\d{5}\\b`,\n },\n {\n name: 'california_drivers_license',\n pattern: String.raw`\\b[A-Z]{1}\\\\d{7}\\b`,\n },\n // Medical and Healthcare\n {\n name: 'hipaa_ndc',\n pattern: String.raw`\\b\\\\d{4,5}-\\\\d{3,4}-\\\\d{1,2}\\b`,\n },\n // Security and Network\n {\n name: 'cve_numbers',\n pattern: String.raw`\\b[Cc][Vv][Ee]-\\\\d{4}-\\\\d{4,7}\\b`,\n },\n {\n name: 'microsoft_oauth',\n pattern: String.raw`https://login\\.microsoftonline\\.com/common/oauth2/v2\\.0/token|https://login\\.windows\\.net/common/oauth2/token`,\n },\n {\n name: 'postgres_connections',\n pattern: String.raw`\\b(?:[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Pp][Gg][Ss][Qq][Ll])\\\\:\\\\/\\\\/`,\n },\n {\n name: 'box_links',\n pattern: String.raw`https://app\\.box\\.com/[s|l]/\\S+`,\n },\n {\n name: 'dropbox_links',\n pattern: String.raw`https://www\\.dropbox\\.com/(?:s|l)/\\S+`,\n },\n // Credit Card Variants\n {\n name: 'amex_cards',\n pattern: String.raw`\\b3[47][0-9]{13}\\b`,\n },\n {\n name: 'visa_cards',\n pattern: String.raw`\\b4[0-9]{12}(?:[0-9]{3})?\\b`,\n },\n {\n name: 'discover_cards',\n pattern: String.raw`\\b65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}\\b`,\n },\n {\n name: 'enhanced_credit_cards',\n pattern: String.raw`\\b((4\\\\d{3}|5[1-5]\\\\d{2}|2\\\\d{3}|3[47]\\\\d{1,2})[\\\\s\\\\-]?\\\\d{4,6}[\\\\s\\\\-]?\\\\d{4,6}?([\\\\s\\\\-]\\\\d{3,4})?(\\\\d{3})?)\\b`,\n },\n // Bank Routing Numbers (US specific)\n {\n name: 'bbva_routing_ca',\n pattern: String.raw`\\\\b321170538\\\\b`,\n },\n {\n name: 'boa_routing_ca',\n pattern: String.raw`\\\\b(?:121|026)00(?:0|9)(?:358|593)\\\\b`,\n },\n {\n name: 'chase_routing_ca',\n pattern: String.raw`\\\\b322271627\\\\b`,\n },\n {\n name: 'citibank_routing_ca',\n pattern: String.raw`\\\\b32(?:11|22)71(?:18|72)4\\\\b`,\n },\n {\n name: 'usbank_routing_ca',\n pattern: String.raw`\\\\b12(?:1122676|2235821)\\\\b`,\n },\n {\n name: 'united_bank_routing_ca',\n pattern: String.raw`\\\\b122243350\\\\b`,\n },\n {\n name: 'wells_fargo_routing_ca',\n pattern: String.raw`\\\\b121042882\\\\b`,\n },\n // Unrealistic alphanumeric identifiers\n {\n name: 'generic_non_usual',\n pattern: String.raw`(?:^|\\s)(?=[A-Za-z0-9_\\)\\*\\=@]*[A-Za-z])(?=[A-Za-z0-9_\\)\\*\\=@]*[0-9])([A-Za-z0-9_\\)\\*\\=@]{5,})(?=\\s|$)`,\n },\n];\n","/**\n * Masking utilities for pattern compilation and value masking.\n *\n * This module provides the core functionality for detecting and masking PII\n * in various data types. It implements the same logic as the Python SDK\n * with optimized regex compilation and efficient masking operations.\n */\n\nimport { logger } from '../logger';\n\nimport type {\n IAttributesMaskingRule,\n IEventMaskingRule,\n IPatternBasedMaskingRule,\n IPatternEntry,\n} from './types';\n\nfunction isValidPatternName(name: string): boolean {\n return /^[a-zA-Z0-9_]+$/.test(name);\n}\n\n/**\n * Detects potentially dangerous ReDoS patterns\n */\nfunction isLikelyReDoSPattern(pattern: string): boolean {\n const dangerousPatterns = [\n // Nested quantifiers like (a+)+, (a*)+, (a+)*\n /\\([^)]*[+*]\\)[+*]/,\n // Alternation with overlapping groups like (a|a)*\n /\\([^)]*\\|[^)]*\\)[+*]/,\n // Complex backtracking patterns - but more specific\n /\\([^)]*[+*][^)]*[+*][^)]*\\)[+*]/,\n ];\n\n return dangerousPatterns.some((dangerous) => dangerous.test(pattern));\n}\n\nfunction getGroupedPattern(patternEntry: IPatternEntry): string {\n let name = patternEntry.name;\n if (!name || name === '') {\n name = `pattern_${Math.random().toString(16).slice(2)}`;\n }\n if (!isValidPatternName(name)) {\n throw new Error(\n `Pattern name '${name}' must only contain alphanumeric characters and underscores`,\n );\n }\n\n // Check for potentially dangerous ReDoS patterns\n if (isLikelyReDoSPattern(patternEntry.pattern)) {\n throw new Error(`Potentially dangerous ReDoS pattern detected: '${patternEntry.pattern}'`);\n }\n\n // Validate the pattern by attempting to create a RegExp\n try {\n new RegExp(patternEntry.pattern);\n } catch (error) {\n throw new Error(`Invalid regex pattern '${patternEntry.pattern}': ${String(error)}`);\n }\n\n return `(?<${name}>${patternEntry.pattern})`;\n}\n\nfunction isIPatternEntry(obj: unknown): obj is IPatternEntry {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n typeof (obj as IPatternEntry).pattern === 'string' &&\n ((obj as IPatternEntry).name === undefined || typeof (obj as IPatternEntry).name === 'string')\n );\n}\n\nfunction isIEventMaskingRule(obj: unknown): obj is IEventMaskingRule {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n typeof (obj as IEventMaskingRule).mode === 'string' &&\n Array.isArray((obj as IEventMaskingRule).patterns) &&\n (obj as IEventMaskingRule).patterns.every(\n (p: unknown) => isIPatternEntry(p) || typeof p === 'string',\n ) &&\n ((obj as IEventMaskingRule).attributePattern === undefined ||\n typeof (obj as IEventMaskingRule).attributePattern === 'string')\n );\n}\n\nfunction convertPatternsToPatternEntries(\n patterns: readonly (IPatternEntry | string)[],\n): IPatternEntry[] {\n const patternEntries: IPatternEntry[] = [];\n for (const pattern of patterns) {\n if (typeof pattern === 'string') {\n // Convert string to PatternEntry with empty name\n patternEntries.push({ pattern, name: '' });\n } else if (isIPatternEntry(pattern)) {\n // Already a PatternEntry, use as is\n patternEntries.push(pattern);\n } else {\n throw new Error('Patterns must be either strings or PatternEntry instances');\n }\n }\n return patternEntries;\n}\n\n/**\n * Compile a list of pattern entries into a single regex pattern.\n * Matches Python's _compile_pattern_entries function.\n */\nfunction compilePatternEntries(patternEntries: readonly IPatternEntry[]): RegExp | null {\n const patternGroups: string[] = [];\n for (const patternEntry of patternEntries) {\n try {\n patternGroups.push(getGroupedPattern(patternEntry));\n } catch (error) {\n logger.warn(`Invalid pattern '${patternEntry.name}': ${patternEntry.pattern}`, error);\n continue; // Skip invalid patterns\n }\n }\n\n if (patternGroups.length === 0) {\n return null; // No valid patterns\n }\n\n try {\n return new RegExp(patternGroups.join('|'));\n } catch (error) {\n logger.warn('Failed to compile pattern entries into regex', error);\n return null;\n }\n}\n\nfunction getCompiledAttributeNamePattern(rule: IAttributesMaskingRule): RegExp {\n if (!rule.attributePattern) {\n logger.debug('No attribute pattern provided, using default .*');\n return /.*/; // Default to match all attributes\n }\n let compiledPatternString = rule.attributePattern;\n if (isIEventMaskingRule(rule) && rule.eventNamePattern) {\n // If this is an event masking rule, append the event name pattern if it exists\n compiledPatternString = `(${compiledPatternString})|(${rule.eventNamePattern})`;\n }\n return new RegExp(compiledPatternString);\n}\n\n/**\n * Check if regex execution should continue based on timeout and iteration limits\n */\nfunction shouldContinueExecution(\n startTime: number,\n iterations: number,\n timeoutMs: number,\n): boolean {\n if (Date.now() - startTime > timeoutMs) {\n logger.warn('Regex execution timed out - potential ReDoS pattern detected');\n return false;\n }\n\n const maxIterations = 1000;\n if (iterations > maxIterations) {\n logger.warn('Regex execution exceeded maximum iterations - potential ReDoS pattern detected');\n return false;\n }\n\n return true;\n}\n\n/**\n * Create a global version of the regex pattern\n */\nfunction createGlobalPattern(pattern: RegExp): RegExp {\n return new RegExp(\n pattern.source,\n pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g',\n );\n}\n\n/**\n * Executes regex with timeout protection to prevent ReDoS attacks\n */\nfunction executeRegexWithTimeout(\n pattern: RegExp,\n value: string,\n timeoutMs: number = 100,\n): RegExpExecArray[] {\n const matches: RegExpExecArray[] = [];\n const globalPattern = createGlobalPattern(pattern);\n const startTime = Date.now();\n let match: RegExpExecArray | null;\n let iterations = 0;\n\n while ((match = globalPattern.exec(value)) !== null) {\n if (!shouldContinueExecution(startTime, ++iterations, timeoutMs)) {\n break;\n }\n\n matches.push(match);\n\n if (match[0].length === 0) {\n globalPattern.lastIndex = match.index + 1;\n }\n }\n\n return matches;\n}\n\n/**\n * Masks a string value based on the pattern, matching Python implementation.\n */\nexport function maskStringByPattern(\n value: string,\n pattern: RegExp,\n mode: 'partial' | 'full' = 'full',\n): string {\n // Use timeout-protected regex execution to prevent ReDoS\n const matches: Array<{\n start: number;\n end: number;\n text: string;\n groups: RegExpExecArray['groups'];\n }> = [];\n\n try {\n const regexMatches = executeRegexWithTimeout(pattern, value);\n\n for (const match of regexMatches) {\n matches.push({\n start: match.index,\n end: match.index + match[0].length,\n text: match[0],\n groups: match.groups,\n });\n }\n } catch (error) {\n logger.warn('Regex execution failed, skipping masking', error);\n return value;\n }\n\n // Process matches in reverse order to maintain correct indices\n for (const matchInfo of matches.reverse()) {\n let patternName = 'unknown';\n if (matchInfo.groups) {\n // Find the first defined group name\n for (const [groupName, groupValue] of Object.entries(matchInfo.groups)) {\n if (groupValue !== undefined) {\n // Remove any counter suffix for logging (matches Python's logic)\n if (groupName.includes('_') && /\\d$/.test(groupName)) {\n const parts = groupName.split('_');\n patternName = parts[0] || groupName;\n } else {\n patternName = groupName;\n }\n break;\n }\n }\n }\n\n logger.info(`Masking detected: pattern '${patternName}' found match in value`);\n\n // Apply masking based on mode\n const masked = mode === 'partial' ? matchInfo.text[0] + '*****' : '*****';\n\n // Replace the matched portion\n value = value.slice(0, matchInfo.start) + masked + value.slice(matchInfo.end);\n }\n\n return value;\n}\n\n/**\n * Masks a string value based on the rule, matching Python implementation.\n */\nexport function maskStringByPatternBasedRule(\n value: string,\n rule: IPatternBasedMaskingRule,\n): string {\n const patternEntries = convertPatternsToPatternEntries(rule.patterns);\n if (patternEntries.length === 0) {\n logger.warn('No patterns provided for masking rule, returning original value');\n return value; // No patterns means no masking\n }\n const mode = rule.mode;\n if (!patternEntries || patternEntries.length === 0) {\n // No patterns means mask entire value\n return mode === 'partial' && value ? value[0] + '*****' : '*****';\n }\n\n // Create the mega pattern\n const compiledPatterns = compilePatternEntries(patternEntries);\n if (!compiledPatterns) {\n return value;\n }\n\n return maskStringByPattern(value, compiledPatterns, mode);\n}\n\n/**\n * Masks a value based on the rule, matching Python implementation.\n */\nexport function maskValue(value: unknown, rule: IPatternBasedMaskingRule): unknown {\n if (typeof value === 'string') {\n return maskStringByPatternBasedRule(value, rule);\n } else if (typeof value === 'boolean' || typeof value === 'number') {\n return maskStringByPatternBasedRule(String(value), rule);\n } else if (Array.isArray(value)) {\n return value.map((v) => maskStringByPatternBasedRule(String(v), rule));\n } else if (value !== null && typeof value === 'object') {\n // If the value is a dictionary, mask each value recursively\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n result[k] = maskValue(v, rule);\n }\n return result;\n } else {\n throw new Error(`Unsupported value type for masking: ${typeof value}`);\n }\n}\n\n/**\n * Masks sensitive data in attributes based on masking rules, matching Python implementation.\n */\nexport function maskAttributes(\n attributes: Record<string, unknown>,\n rules: readonly IAttributesMaskingRule[],\n outputOriginalValue = false,\n): Record<string, unknown> {\n if (!attributes || Object.keys(attributes).length === 0) {\n return {};\n }\n\n // Create a copy to avoid modifying the original\n const maskedAttributes = { ...attributes };\n\n for (const rule of rules) {\n const compiledAttributeNamePattern = getCompiledAttributeNamePattern(rule);\n const attributesToMask: string[] = compiledAttributeNamePattern\n ? Object.keys(maskedAttributes).filter((attr) => compiledAttributeNamePattern.test(attr))\n : Object.keys(maskedAttributes);\n\n for (const attribute of attributesToMask) {\n const value = maskedAttributes[attribute];\n if (value === null || value === undefined) {\n continue;\n }\n\n if (outputOriginalValue) {\n logger.debug(`Masking attribute '${attribute}' with original value`, { value });\n }\n\n maskedAttributes[attribute] = maskValue(value, rule);\n }\n }\n\n return maskedAttributes;\n}\n","import { createContextKey } from '@opentelemetry/api';\n\nexport const BRIZZ = 'brizz';\nexport const PROPERTIES = 'properties';\nexport const SESSION_ID = 'session.id';\nexport const PROPERTIES_CONTEXT_KEY = createContextKey(PROPERTIES);\n","import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { PeriodicExportingMetricReader, type MetricReader } from '@opentelemetry/sdk-metrics';\n\nimport type { IResolvedBrizzConfig } from '../config';\nimport { logger } from '../logger';\n\nexport class MetricsModule {\n private static instance: MetricsModule | null = null;\n private metricsExporter: OTLPMetricExporter | null = null;\n private metricsReader: MetricReader | null = null;\n\n static getInstance(): MetricsModule {\n if (!MetricsModule.instance) {\n throw new Error('Brizz must be initialized before accessing MetricsModule');\n }\n return MetricsModule.instance;\n }\n\n /**\n * Initialize the metrics module with the provided configuration\n */\n setup(config: IResolvedBrizzConfig): void {\n logger.info('Setting up metrics module');\n\n // Initialize reader (custom or default with exporter)\n this.initMetricsReader(config);\n\n // Set as module instance for standalone functions\n MetricsModule.instance = this;\n\n logger.info('Metrics module setup completed');\n }\n\n /**\n * Initialize the metrics exporter\n */\n private initMetricsExporter(config: IResolvedBrizzConfig): void {\n if (this.metricsExporter) {\n logger.debug('Metrics exporter already initialized, skipping re-initialization');\n return;\n }\n\n const metricsUrl = config.baseUrl.replace(/\\/$/, '') + '/v1/metrics';\n logger.debug('Initializing metrics exporter', { url: metricsUrl });\n\n this.metricsExporter = new OTLPMetricExporter({\n url: metricsUrl,\n headers: config.headers,\n });\n\n logger.debug('Metrics exporter initialized successfully');\n }\n\n /**\n * Initialize the metrics reader\n */\n private initMetricsReader(config: IResolvedBrizzConfig): void {\n if (this.metricsReader) {\n logger.debug('Metrics reader already initialized, skipping re-initialization');\n return;\n }\n\n // Use custom metric reader if provided\n if (config.customMetricReader) {\n logger.debug('Using custom metric reader');\n this.metricsReader = config.customMetricReader;\n logger.debug('Custom metric reader initialized successfully');\n return;\n }\n\n // Use default flow: create OTLP exporter and wrap it in PeriodicExportingMetricReader\n logger.debug(\n 'Using default metrics flow - creating OTLP exporter and PeriodicExportingMetricReader',\n );\n this.initMetricsExporter(config);\n\n if (!this.metricsExporter) {\n throw new Error('Failed to initialize metrics exporter');\n }\n\n this.metricsReader = new PeriodicExportingMetricReader({\n exporter: this.metricsExporter,\n });\n\n logger.debug('Default metrics reader initialized successfully');\n }\n\n /**\n * Get the metrics exporter\n */\n getMetricsExporter(): OTLPMetricExporter {\n if (!this.metricsExporter) {\n throw new Error('Metrics module not initialized');\n }\n return this.metricsExporter;\n }\n\n /**\n * Get the metrics reader\n */\n getMetricsReader(): MetricReader {\n if (!this.metricsReader) {\n throw new Error('Metrics module not initialized');\n }\n return this.metricsReader;\n }\n\n /**\n * Shutdown the metrics module\n */\n shutdown(): void {\n logger.debug('Shutting down metrics module');\n\n this.metricsReader = null;\n this.metricsExporter = null;\n\n // Clear module instance\n if (MetricsModule.instance === this) {\n MetricsModule.instance = null;\n }\n\n logger.debug('Metrics module shutdown completed');\n }\n}\n\n/**\n * Get the OpenTelemetry Metrics Exporter configured for Brizz.\n * @throws {Error} - If SDK is not initialized\n */\nexport function getMetricsExporter(): OTLPMetricExporter {\n return MetricsModule.getInstance().getMetricsExporter();\n}\n\n/**\n * Get the Metrics Reader configured for Brizz.\n * @throws {Error} - If SDK is not initialized\n */\nexport function getMetricsReader(): MetricReader {\n return MetricsModule.getInstance().getMetricsReader();\n}\n","import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport type { SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport type { SpanProcessor } from '@opentelemetry/sdk-trace-node';\n\nimport type { IResolvedBrizzConfig } from '../config';\nimport { logger } from '../logger';\n\nimport { BrizzBatchSpanProcessor, BrizzSimpleSpanProcessor } from './processors/span-processor';\n\nexport class TracingModule {\n private static instance: TracingModule | null = null;\n private spanExporter: SpanExporter | null = null;\n private spanProcessor: SpanProcessor | null = null;\n\n static getInstance(): TracingModule {\n if (!TracingModule.instance) {\n throw new Error('Brizz must be initialized before accessing TracingModule');\n }\n return TracingModule.instance;\n }\n\n /**\n * Initialize the tracing module with the provided configuration\n */\n setup(config: IResolvedBrizzConfig): void {\n logger.info('Setting up tracing module');\n\n // Initialize exporter (custom or default)\n this.initSpanExporter(config);\n\n // Initialize processor with masking support\n this.initSpanProcessor(config);\n\n // Set as module instance for standalone functions\n TracingModule.instance = this;\n\n logger.info('Tracing module setup completed');\n }\n\n /**\n * Initialize the span exporter\n */\n private initSpanExporter(config: IResolvedBrizzConfig): void {\n if (this.spanExporter) {\n logger.debug('Span exporter already initialized, skipping re-initialization');\n return;\n }\n\n // Use custom span exporter if provided\n if (config.customSpanExporter) {\n logger.debug('Using custom span exporter');\n this.spanExporter = config.customSpanExporter;\n logger.debug('Custom span exporter initialized successfully');\n return;\n }\n\n // Use default OTLP exporter\n const tracesUrl = config.baseUrl.replace(/\\/$/, '') + '/v1/traces';\n logger.debug('Initializing default OTLP span exporter', { url: tracesUrl });\n\n this.spanExporter = new OTLPTraceExporter({\n url: tracesUrl,\n headers: config.headers,\n });\n\n logger.debug('OTLP span exporter initialized successfully');\n }\n\n /**\n * Initialize the span processor with masking support\n */\n private initSpanProcessor(config: IResolvedBrizzConfig): void {\n if (this.spanProcessor) {\n logger.debug('Span processor already initialized, skipping re-initialization');\n return;\n }\n\n if (!this.spanExporter) {\n throw new Error('Span exporter must be initialized before processor');\n }\n\n logger.debug('Initializing span processor', {\n disableBatch: config.disableBatch,\n hasMasking: !!config.masking?.spanMasking,\n });\n\n // Use masked processors if masking is configured, otherwise use standard processors\n this.spanProcessor = config.disableBatch\n ? new BrizzSimpleSpanProcessor(this.spanExporter, config)\n : new BrizzBatchSpanProcessor(this.spanExporter, config);\n\n logger.debug('Span processor initialized successfully');\n }\n\n /**\n * Get the span exporter\n */\n getSpanExporter(): SpanExporter {\n if (!this.spanExporter) {\n throw new Error('Tracing module not initialized');\n }\n return this.spanExporter;\n }\n\n /**\n * Get the span processor\n */\n getSpanProcessor(): SpanProcessor {\n if (!this.spanProcessor) {\n throw new Error('Tracing module not initialized');\n }\n return this.spanProcessor;\n }\n\n async shutdown(): Promise<void> {\n logger.debug('Shutting down tracing module');\n\n if (this.spanProcessor) {\n await this.spanProcessor.shutdown();\n this.spanProcessor = null;\n }\n\n if (this.spanExporter) {\n await this.spanExporter.shutdown();\n this.spanExporter = null;\n }\n\n TracingModule.instance = null;\n logger.debug('Tracing module shutdown completed');\n }\n}\n\n/**\n * Get the OpenTelemetry Span Exporter configured for Brizz.\n * @throws {Error} - If SDK is not initialized\n */\nexport function getSpanExporter(): SpanExporter {\n return TracingModule.getInstance().getSpanExporter();\n}\n\n/**\n * Get the Span Processor configured for Brizz.\n * @throws {Error} - If SDK is not initialized\n */\nexport function getSpanProcessor(): SpanProcessor {\n return TracingModule.getInstance().getSpanProcessor();\n}\n","import { type Attributes, type AttributeValue, context, type Context } from '@opentelemetry/api';\nimport {\n BatchSpanProcessor,\n SimpleSpanProcessor,\n type Span,\n type SpanExporter,\n} from '@opentelemetry/sdk-trace-base';\n\nimport type { IResolvedBrizzConfig } from '../../config';\nimport { logger } from '../../logger';\nimport { DEFAULT_PII_PATTERNS } from '../../masking/patterns';\nimport type {\n IAttributesMaskingRule,\n ISpanMaskingConfig,\n MaskableValue,\n} from '../../masking/types';\nimport { maskAttributes } from '../../masking/utils';\nimport { BRIZZ, PROPERTIES_CONTEXT_KEY } from '../../semantic-conventions';\n\nexport const DEFAULT_MASKING_RULES: IAttributesMaskingRule[] = [\n {\n mode: 'partial',\n attributePattern: 'gen_ai.prompt',\n patterns: DEFAULT_PII_PATTERNS,\n },\n {\n mode: 'partial',\n attributePattern: 'gen_ai.completion',\n patterns: DEFAULT_PII_PATTERNS,\n },\n {\n mode: 'partial',\n attributePattern: 'traceloop.entity.input',\n patterns: DEFAULT_PII_PATTERNS,\n },\n {\n mode: 'partial',\n attributePattern: 'traceloop.entity.output',\n patterns: DEFAULT_PII_PATTERNS,\n },\n];\n\nexport class BrizzSimpleSpanProcessor extends SimpleSpanProcessor {\n public readonly config: IResolvedBrizzConfig;\n\n constructor(spanExporter: SpanExporter, config: IResolvedBrizzConfig) {\n super(spanExporter);\n this.config = config;\n }\n\n // Will work with the following code:\n // const span = tracer.startSpan('sensitive-operation',{attributes:{\n // 'user.password': 'secret123',\n // 'user.email': 'user@example.com',\n // }});\n //\n // Won't work because onStart is called before attributes are set:\n // span.setAttributes({\n // 'user.password': 'secret123',\n // 'user.email': 'user@example.com'\n // });\n override onStart(span: Span, parentContext: Context): void {\n const maskingConfig = this.config.masking?.spanMasking;\n if (maskingConfig) {\n maskSpan(span, maskingConfig);\n }\n const associationProperties = context.active().getValue(PROPERTIES_CONTEXT_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n span.setAttribute(`${BRIZZ}.${key}`, value as AttributeValue);\n }\n }\n super.onStart(span, parentContext);\n }\n}\n\nexport class BrizzBatchSpanProcessor extends BatchSpanProcessor {\n public readonly config: IResolvedBrizzConfig;\n\n constructor(spanExporter: SpanExporter, config: IResolvedBrizzConfig) {\n super(spanExporter);\n this.config = config;\n }\n\n override onStart(span: Span, parentContext: Context): void {\n const maskingConfig = this.config.masking?.spanMasking;\n if (maskingConfig) {\n maskSpan(span, maskingConfig);\n }\n const associationProperties = context.active().getValue(PROPERTIES_CONTEXT_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n span.setAttribute(`${BRIZZ}.${key}`, value as AttributeValue);\n }\n }\n super.onStart(span, parentContext);\n }\n}\n\nexport function maskSpan(span: Span, config: ISpanMaskingConfig): Span {\n if (!span.attributes || Object.keys(span.attributes).length === 0) {\n return span;\n }\n\n let rules = config.rules || [];\n if (!config.disableDefaultRules) {\n rules = [...DEFAULT_MASKING_RULES, ...rules];\n }\n\n try {\n const attributesRecord: Record<string, MaskableValue> = {};\n\n for (const [key, value] of Object.entries(span.attributes)) {\n attributesRecord[key] = value as MaskableValue;\n }\n\n const maskedAttributes = maskAttributes(attributesRecord, rules);\n if (maskedAttributes && Object.keys(maskedAttributes).length > 0) {\n // Use setAttributes to update the span\n const merged: Attributes = { ...span.attributes };\n for (const [key, value] of Object.entries(maskedAttributes)) {\n merged[key] = value as AttributeValue;\n }\n span.setAttributes(merged);\n }\n\n return span;\n } catch (error) {\n logger.error('Error masking span:', error);\n return span;\n }\n}\n","import { context } from '@opentelemetry/api';\n\nimport { PROPERTIES_CONTEXT_KEY, SESSION_ID } from '../semantic-conventions';\n\nexport function withProperties<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n properties: { [name: string]: string },\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n): ReturnType<F> {\n if (Object.keys(properties).length === 0) {\n return fn.apply(thisArg, args);\n }\n\n const newContext = context.active().setValue(PROPERTIES_CONTEXT_KEY, properties);\n return context.with(newContext, fn, thisArg, ...args);\n}\n\n/**\n * Wraps a function to execute it with session context. All telemetry (traces, spans, events)\n * generated within the wrapped function will include the session ID.\n *\n * @example\n * ```typescript\n * // Basic usage with async function\n * await WithSessionId('session-123', myAsyncFunction, null, arg1, arg2);\n *\n * // With method and 'this' context\n * const result = WithSessionId('session-456', obj.method, obj, param);\n *\n * // Wrapping AI operations\n * const response = await WithSessionId('chat-session', async () => {\n * const aiResponse = await openai.chat.completions.create({\n * model: 'gpt-4',\n * messages: [{ role: 'user', content: 'Hello' }]\n * });\n * emitEvent('ai.response', { tokens: aiResponse.usage.total_tokens });\n * return aiResponse;\n * });\n * ```\n *\n * @param sessionId - Session identifier to include in all telemetry within the function\n * @param fn - Function to execute with session context\n * @param thisArg - Value to use as `this` when calling the function (optional)\n * @param args - Arguments to pass to the wrapped function\n * @returns The return value of the wrapped function\n */\nexport function WithSessionId<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n sessionId: string,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n): ReturnType<F> {\n return withProperties({ [SESSION_ID]: sessionId }, fn, thisArg, ...args);\n}\n","import { logger } from '../internal/logger.js';\n\nexport interface RuntimeInfo {\n isESM: boolean;\n isCJS: boolean;\n nodeVersion: string;\n supportsLoaderAPI: boolean;\n supportsRegister: boolean;\n}\n\nexport function detectRuntime(): RuntimeInfo {\n const [major, minor] = process.versions.node.split('.').map(Number);\n\n // Detect ESM vs CJS based on Node.js globals availability\n // In pure ESM: __filename, __dirname, module, exports are undefined\n // In pure CJS: __filename, __dirname, module, exports all exist\n // In mixed/loader contexts: some may exist as shims\n const noNodeJSGlobals = typeof __filename === 'undefined' && typeof __dirname === 'undefined';\n const noModuleSystem = typeof module === 'undefined' && typeof exports === 'undefined';\n const hasRequire = typeof require === 'function';\n\n // ESM: No Node.js globals AND no CJS module system\n // This covers pure ESM and ESM loader contexts\n const isESM = noNodeJSGlobals && noModuleSystem;\n\n // CJS: All CJS globals exist (require, module, exports, __filename, __dirname)\n // This ensures we're in a real CJS context, not a shim environment\n const isCJS =\n hasRequire &&\n typeof module !== 'undefined' &&\n typeof exports !== 'undefined' &&\n typeof __filename === 'string' &&\n typeof __dirname === 'string';\n\n const supportsLoaderAPI =\n (major ?? 0) >= 21 || ((major ?? 0) === 20 && (minor ?? 0) >= 6) || ((major ?? 0) === 18 && (minor ?? 0) >= 19);\n const supportsRegister = !!(process.features as any)?.typescript || !!(globalThis as any).module?.register;\n\n logger.debug('Runtime detection results:', {\n nodeVersion: `${major ?? 0}.${minor ?? 0}`,\n isESM,\n isCJS,\n supportsLoaderAPI,\n supportsRegister,\n detectionLogic: {\n noNodeJSGlobals,\n noModuleSystem,\n hasRequire,\n esmCondition: `${noNodeJSGlobals} && ${noModuleSystem} = ${isESM}`,\n cjsCondition: `require && module && exports && __filename && __dirname = ${isCJS}`,\n },\n checks: {\n __filename: typeof __filename,\n __dirname: typeof __dirname,\n require: typeof require,\n module: typeof module,\n exports: typeof exports,\n 'process.features': process.features,\n 'globalThis.module': (globalThis as any).module,\n },\n });\n\n return {\n isESM,\n isCJS,\n nodeVersion: process.versions.node,\n supportsLoaderAPI,\n supportsRegister,\n };\n}\n","import module from 'node:module';\n\nimport { createAddHookMessageChannel } from 'import-in-the-middle';\n////////////////////////////// WARNING /////////////////////////////////\n///////// THIS FILE MUST NOT IMPORT ANY 3RD PARTY MODULES //////////////\n///////// Will cause infinite loop ////////////////////////////////////\n////////////////////////////////////////////////////////////////////////\n\n// Mini logger for loader - zero dependencies, only logs if BRIZZ_ESM_DEBUG=true\nconst loaderDebug = (() => {\n const isDebug =\n process.env['BRIZZ_ESM_DEBUG'] === 'true' || process.env['BRIZZ_LOG_LEVEL'] === 'debug';\n\n return {\n log: (msg: string, data?: unknown) => {\n if (!isDebug) {return;}\n const timestamp = new Date().toISOString();\n const dataStr = data ? ` ${JSON.stringify(data)}` : '';\n console.log(`[${timestamp}] [ESM-LOADER] ${msg}${dataStr}`);\n },\n error: (msg: string, error?: unknown) => {\n if (!isDebug) {return;}\n const timestamp = new Date().toISOString();\n const errorStr =\n error instanceof Error ? ` ${error.message}` : (error ? ` ${JSON.stringify(error)}` : '');\n console.error(`[${timestamp}] [ESM-LOADER] ERROR: ${msg}${errorStr}`);\n },\n };\n})();\n\n// Use a Symbol to ensure unique global key that won't be accidentally overwritten\nconst LOADER_REGISTERED_KEY = Symbol.for('__brizz_esm_loader_registered__');\n\n// Check if loader API is supported\nfunction checkLoaderAPISupport() {\n const [major, minor] = process.versions.node.split('.').map(Number);\n\n if (major === undefined || minor === undefined) {\n loaderDebug.log('Failed to detect Node version, assuming loader API is supported');\n return true;\n }\n\n const supported = major >= 21 || (major === 20 && minor >= 6) || (major === 18 && minor >= 19);\n\n loaderDebug.log('Loader API support check:', {\n nodeVersion: `${major}.${minor}`,\n supportsLoaderAPI: supported,\n });\n\n return supported;\n}\n\nexport function maybeRegisterESMLoader(): boolean {\n // Check if already registered using Symbol key\n if ((globalThis as any)[LOADER_REGISTERED_KEY] === true) {\n loaderDebug.log('ESM loader already registered, skipping');\n return false;\n }\n\n // Mark as registered immediately to prevent race conditions\n (globalThis as any)[LOADER_REGISTERED_KEY] = true;\n\n loaderDebug.log('Starting ESM loader registration...');\n\n if (!checkLoaderAPISupport()) {\n loaderDebug.log('Node.js version does not support loader API, skipping');\n return false;\n }\n\n try {\n loaderDebug.log('Creating MessageChannel for import-in-the-middle...');\n const { addHookMessagePort } = createAddHookMessageChannel();\n\n loaderDebug.log('Registering import-in-the-middle/hook.mjs...');\n module.register('import-in-the-middle/hook.mjs', {\n data: { addHookMessagePort },\n transferList: [addHookMessagePort],\n });\n\n loaderDebug.log('ESM loader successfully registered!');\n return true;\n } catch (error) {\n loaderDebug.error('Failed to register ESM loader:', error);\n // Reset the flag on failure so it can be retried if needed\n (globalThis as any)[LOADER_REGISTERED_KEY] = false;\n return false;\n }\n}\n\n// Auto-execute when the loader module is imported via --import\n// Check both the Symbol key and execution context\nif ((globalThis as any)[LOADER_REGISTERED_KEY] !== true) {\n loaderDebug.log('Loader module imported, attempting to register...');\n maybeRegisterESMLoader();\n}\n","// Explicit init entrypoint for preload usage:\n// - ESM: node --import @brizz/sdk/init app.mjs\n// - CJS: node --require @brizz/sdk/init app.js\n//\n// This ensures auto-instrumentations are registered before user imports.\nimport './internal/instrumentation/auto-init';\n\nexport {};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;A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D;AACvE,WAAO;AAAA,EACT;AAEA,MAAI;AACF,gBAAY,IAAI,qDAAqD;AACrE,UAAM,EAAE,mBAAmB,QAAI,yDAA4B;AAE3D,gBAAY,IAAI,8CAA8C;AAC9D,uBAAAC,QAAO,SAAS,iCAAiC;AAAA,MAC/C,MAAM,EAAE,mBAAmB;AAAA,MAC3B,cAAc,CAAC,kBAAkB;AAAA,IACnC,CAAC;AAED,gBAAY,IAAI,qCAAqC;AACrD,WAAO;AAAA,EACT,SAAS,OAAO;AACd,gBAAY,MAAM,kCAAkC,KAAK;AAEzD,IAAC,WAAmB,qBAAqB,IAAI;AAC7C,WAAO;AAAA,EACT;AACF;AAIA,IAAK,WAAmB,qBAAqB,MAAM,MAAM;AACvD,cAAY,IAAI,mDAAmD;AACnE,yBAAuB;AACzB;;;AC9FA;","names":["import_instrumentation","LogLevel","pino","import_api","context","import_api","import_api","context","import_api","import_api","context","import_api","logger","module","import_resources","import_instrumentation_anthropic","import_instrumentation_bedrock","import_instrumentation_chromadb","import_instrumentation_cohere","import_instrumentation_langchain","import_instrumentation_llamaindex","import_instrumentation_openai","import_instrumentation_pinecone","import_instrumentation_qdrant","import_instrumentation_together","import_instrumentation_vertexai","exceptionLogger","import_api_logs","import_sdk_logs","import_api","import_api","import_api","import_api","import_api_logs","module"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/internal/instrumentation/auto-init.ts","../src/internal/logger.ts","../src/internal/instrumentation/vercel-ai/instrumentation.ts","../src/internal/instrumentation/vercel-ai/patchers/base-patcher.ts","../src/internal/instrumentation/vercel-ai/semconv.ts","../src/internal/instrumentation/vercel-ai/utils.ts","../src/internal/instrumentation/vercel-ai/patchers/generate-text-patcher.ts","../src/internal/instrumentation/vercel-ai/patchers/stream-text-patcher.ts","../src/internal/instrumentation/vercel-ai/patchers/embeddings-patcher.ts","../src/internal/instrumentation/vercel-ai/stream-handler.ts","../src/internal/instrumentation/vercel-ai/telemetry-recorder.ts","../src/internal/sdk.ts","../src/internal/config.ts","../src/internal/instrumentation/registry.ts","../src/internal/log/logging.ts","../src/internal/log/processors/log-processor.ts","../src/internal/masking/patterns.ts","../src/internal/masking/utils.ts","../src/internal/semantic-conventions.ts","../src/internal/metric/metrics.ts","../src/internal/trace/tracing.ts","../src/internal/trace/processors/span-processor.ts","../src/internal/trace/session.ts","../src/node/runtime.ts","../src/init.ts"],"sourcesContent":["// Auto-initialize instrumentations before anything else\nimport './internal/instrumentation/auto-init.js';\n\n// Re-export main SDK instance and types\nexport { Brizz, type IBrizzInitializeOptions } from './internal/sdk.js';\n\n// Re-export instrumentation types for manual configuration\nexport {\n type IInstrumentModules,\n VercelAIInstrumentation,\n} from './internal/instrumentation/index.js';\n\n// Re-export utility functions from their respective modules\nexport { emitEvent } from './internal/log/index.js';\nexport { getSpanExporter, getSpanProcessor, WithSessionId } from './internal/trace/index.js';\nexport { getMetricsExporter, getMetricsReader } from './internal/metric/index.js';\n// Re-export masking types and utilities\nexport type {\n IMaskingConfig,\n ISpanMaskingConfig,\n ILogMaskingConfig,\n IEventMaskingConfig,\n IEventMaskingRule,\n MaskingMode,\n IAttributesMaskingRule,\n} from './internal/masking/index.js';\n\n// Re-export masking patterns and utilities\nexport { DEFAULT_PII_PATTERNS } from './internal/masking/patterns.js';\nexport { maskValue, maskAttributes } from './internal/masking/utils.js';\n\n// Re-export logger types, enums, and functions\nexport { LogLevel, logger, setLogLevel, getLogLevel } from './internal/logger.js';\nexport type { ILogger } from './internal/logger.js';\n\n// Re-export OpenTelemetry types that users might need\nexport { SeverityNumber } from '@opentelemetry/api-logs';\n\n// Re-export runtime utilities\nexport * from './node/runtime.js';\n\n// Explicit init entrypoint (preload)\nexport * as init from './init.js';\n","import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport type { Instrumentation } from '@opentelemetry/instrumentation';\nimport { registerInstrumentations } from '@opentelemetry/instrumentation';\nimport { AnthropicInstrumentation } from '@traceloop/instrumentation-anthropic';\nimport { BedrockInstrumentation } from '@traceloop/instrumentation-bedrock';\nimport { ChromaDBInstrumentation } from '@traceloop/instrumentation-chromadb';\nimport { CohereInstrumentation } from '@traceloop/instrumentation-cohere';\nimport { LangChainInstrumentation } from '@traceloop/instrumentation-langchain';\nimport { LlamaIndexInstrumentation } from '@traceloop/instrumentation-llamaindex';\nimport { OpenAIInstrumentation } from '@traceloop/instrumentation-openai';\nimport { PineconeInstrumentation } from '@traceloop/instrumentation-pinecone';\nimport { QdrantInstrumentation } from '@traceloop/instrumentation-qdrant';\nimport { TogetherInstrumentation } from '@traceloop/instrumentation-together';\nimport { VertexAIInstrumentation } from '@traceloop/instrumentation-vertexai';\n\nimport { logger } from '../logger.js';\n\nimport { VercelAIInstrumentation } from './vercel-ai';\n\n/**\n * Auto-initialization that runs at import time.\n * This ensures all instrumentations are registered before any libraries are loaded.\n *\n * Flow:\n * 1. Load node auto-instrumentations (including Winston)\n * 2. Initialize logger (after Winston instrumentation is ready)\n * 3. Load GenAI instrumentations with error logging\n */\n\nlet autoInstrumentationsLoaded = false;\n\nconst exceptionLogger = (error: Error) => {\n logger.error(`Exception in instrumentation: ${String(error)}`);\n};\n\nfunction loadNodeAutoInstrumentations(): Instrumentation[] {\n try {\n const nodeInstrumentations = getNodeAutoInstrumentations();\n registerInstrumentations({ instrumentations: nodeInstrumentations });\n return nodeInstrumentations;\n } catch (error) {\n logger.error(`Failed to load Node.js auto-instrumentations: ${String(error)}`);\n return [];\n }\n}\n\nfunction loadGenAIInstrumentations(): Instrumentation[] {\n const instrumentations: Instrumentation[] = [];\n\n const genAIInstrumentationClasses = [\n { class: VercelAIInstrumentation, name: 'Vercel AI' }, // Load first to avoid conflicts\n { class: OpenAIInstrumentation, name: 'OpenAI' },\n { class: AnthropicInstrumentation, name: 'Anthropic' },\n { class: CohereInstrumentation, name: 'Cohere' },\n { class: VertexAIInstrumentation, name: 'Vertex AI' },\n { class: BedrockInstrumentation, name: 'Bedrock' },\n { class: PineconeInstrumentation, name: 'Pinecone' },\n { class: LangChainInstrumentation, name: 'LangChain' },\n { class: LlamaIndexInstrumentation, name: 'LlamaIndex' },\n { class: ChromaDBInstrumentation, name: 'ChromaDB' },\n { class: QdrantInstrumentation, name: 'Qdrant' },\n { class: TogetherInstrumentation, name: 'Together' },\n ];\n\n for (const config of genAIInstrumentationClasses) {\n try {\n const instrumentation = new config.class({ exceptionLogger });\n instrumentations.push(instrumentation);\n logger.debug(`Auto-loaded ${config.name} instrumentation`);\n } catch (error) {\n logger.error(`Failed to auto-load ${config.name} instrumentation: ${String(error)}`);\n }\n }\n\n try {\n registerInstrumentations({ instrumentations });\n logger.info(`Auto-registered ${instrumentations.length} GenAI instrumentations`);\n } catch (error) {\n logger.error(`Failed to register GenAI instrumentations: ${String(error)}`);\n }\n\n return instrumentations;\n}\n\n/**\n * Auto-initialize all instrumentations.\n * Called immediately when this module is imported.\n */\nfunction autoInitializeInstrumentations(): void {\n if (autoInstrumentationsLoaded) {\n return;\n }\n\n try {\n // Step 1: Load node auto-instrumentations first\n const nodeInstrumentations = loadNodeAutoInstrumentations();\n\n // Step 2: Load GenAI instrumentations with logger exception handling\n const genAIInstrumentations = loadGenAIInstrumentations();\n\n autoInstrumentationsLoaded = true;\n logger.info(\n `Auto-initialization complete: ${nodeInstrumentations.length} node + ${genAIInstrumentations.length} GenAI instrumentations`,\n );\n } catch (error) {\n logger.error(`Auto-initialization failed: ${String(error)}`);\n autoInstrumentationsLoaded = false;\n }\n}\n\n// Auto-initialize immediately when this module is imported\nautoInitializeInstrumentations();\n\nexport { autoInstrumentationsLoaded };\n","/**\n * Logger interface and implementations for the Brizz SDK.\n *\n * Simple Pino-based logging system that works everywhere in the SDK,\n * including during bootstrap and instrumentation loading.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport pino from 'pino';\n\n/**\n * Available log levels for the Brizz SDK, ordered by severity.\n */\nexport enum LogLevel {\n NONE = 0,\n ERROR = 1,\n WARN = 2,\n INFO = 3,\n DEBUG = 4,\n}\n\n/**\n * Default log level for the SDK when no level is specified.\n */\nexport const DEFAULT_LOG_LEVEL = LogLevel.WARN;\n\n/**\n * Internal logger interface for the SDK.\n */\nexport interface ILogger {\n debug: (msg: string, ...meta: unknown[]) => void;\n info: (msg: string, ...meta: unknown[]) => void;\n warn: (msg: string, ...meta: unknown[]) => void;\n error: (msg: string, ...meta: unknown[]) => void;\n setLevel: (level: LogLevel) => void;\n getLevel: () => LogLevel;\n}\n\n/**\n * Pino-based logger implementation with dynamic level control.\n */\nclass PinoLogger implements ILogger {\n private _level: LogLevel = DEFAULT_LOG_LEVEL;\n private _pinoLogger: pino.Logger | null = null;\n\n constructor() {\n // Set initial level from environment\n const envLevel = this.getLogLevelFromEnv();\n this._level = envLevel;\n }\n\n /**\n * Lazy initialization of Pino logger to ensure it's created AFTER Jest spies\n * are set up during tests. This prevents the pino-pretty transport from\n * bypassing stdout/stderr spies.\n */\n private ensurePinoLogger(): pino.Logger {\n if (!this._pinoLogger) {\n this._pinoLogger = pino({\n name: 'Brizz',\n level: this.logLevelToPino(this._level),\n // Disable transport in test environment to allow proper spy capture\n transport: this.isProduction() || this.isTest()\n ? undefined\n : {\n target: 'pino-pretty',\n options: {\n singleLine: true,\n colorize: true,\n translateTime: 'HH:MM:ss',\n ignore: 'pid,hostname',\n messageFormat: '[{name}] {msg}',\n },\n },\n });\n }\n return this._pinoLogger;\n }\n\n private isProduction(): boolean {\n return process.env['NODE_ENV'] === 'production';\n }\n\n private isTest(): boolean {\n return process.env['NODE_ENV'] === 'test';\n }\n\n private getLogLevelFromEnv(): LogLevel {\n const envLevel = process.env['BRIZZ_LOG_LEVEL'];\n return envLevel ? parseLogLevel(envLevel) : DEFAULT_LOG_LEVEL;\n }\n\n private logLevelToPino(level: LogLevel): string {\n switch (level) {\n case LogLevel.DEBUG:\n return 'debug';\n case LogLevel.INFO:\n return 'info';\n case LogLevel.WARN:\n return 'warn';\n case LogLevel.ERROR:\n return 'error';\n default:\n return 'silent';\n }\n }\n\n private formatMeta(meta: unknown[]): object {\n if (meta.length === 0) {\n return {};\n }\n\n if (meta.length === 1 && typeof meta[0] === 'object' && meta[0] !== null) {\n return meta[0] as object;\n }\n\n return { metadata: meta };\n }\n\n setLevel(level: LogLevel): void {\n this._level = level;\n if (this._pinoLogger) {\n this._pinoLogger.level = this.logLevelToPino(level);\n }\n }\n\n getLevel(): LogLevel {\n return this._level;\n }\n\n debug = (msg: string, ...meta: unknown[]): void => {\n if (this._level >= LogLevel.DEBUG) {\n this.ensurePinoLogger().debug(this.formatMeta(meta), msg);\n }\n };\n\n info = (msg: string, ...meta: unknown[]): void => {\n if (this._level >= LogLevel.INFO) {\n this.ensurePinoLogger().info(this.formatMeta(meta), msg);\n }\n };\n\n warn = (msg: string, ...meta: unknown[]): void => {\n if (this._level >= LogLevel.WARN) {\n this.ensurePinoLogger().warn(this.formatMeta(meta), msg);\n }\n };\n\n error = (msg: string, ...meta: unknown[]): void => {\n if (this._level >= LogLevel.ERROR) {\n this.ensurePinoLogger().error(this.formatMeta(meta), msg);\n }\n };\n}\n\n/**\n * No-op logger that silences all logging output.\n */\nexport const noopLogger: ILogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n setLevel: () => {},\n getLevel: () => LogLevel.NONE,\n};\n\n/**\n * Parses a log level string into a LogLevel enum value.\n * Supports both string names and numeric values.\n */\nexport function parseLogLevel(level?: string): LogLevel {\n if (!level) {\n return DEFAULT_LOG_LEVEL;\n }\n\n const normalizedLevel = level.toLowerCase().trim();\n\n switch (normalizedLevel) {\n case 'debug':\n return LogLevel.DEBUG;\n case 'info':\n return LogLevel.INFO;\n case 'warn':\n case 'warning':\n return LogLevel.WARN;\n case 'error':\n return LogLevel.ERROR;\n case 'none':\n case 'off':\n case 'silent':\n return LogLevel.NONE;\n default: {\n // Try to parse as number\n const numLevel = Number.parseInt(normalizedLevel, 10);\n if (!Number.isNaN(numLevel) && numLevel >= 0 && numLevel <= 4) {\n return numLevel as LogLevel;\n }\n return DEFAULT_LOG_LEVEL;\n }\n }\n}\n\n/**\n * Global logger instance - initialized once and used throughout the SDK.\n */\nexport const logger: ILogger = new PinoLogger();\n\n/**\n * Sets the global logger level.\n */\nexport function setLogLevel(level: LogLevel | string): void {\n const resolvedLevel = typeof level === 'string' ? parseLogLevel(level) : level;\n logger.setLevel(resolvedLevel);\n}\n\n/**\n * Gets the current global logger level.\n */\nexport function getLogLevel(): LogLevel {\n return logger.getLevel();\n}\n\n/**\n * Maps Brizz LogLevel to OpenTelemetry DiagLogLevel.\n */\nexport function mapLogLevelToDiagLevel(logLevel: LogLevel): DiagLogLevel {\n switch (logLevel) {\n case LogLevel.DEBUG:\n return DiagLogLevel.DEBUG;\n case LogLevel.INFO:\n return DiagLogLevel.INFO;\n case LogLevel.WARN:\n return DiagLogLevel.WARN;\n case LogLevel.ERROR:\n return DiagLogLevel.ERROR;\n default:\n return DiagLogLevel.NONE;\n }\n}\n","import type { Histogram } from '@opentelemetry/api';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n} from '@opentelemetry/instrumentation';\n\nimport { logger } from '../../logger';\n\nimport {\n GenerateTextPatcher,\n StreamTextPatcher,\n EmbeddingsPatcher,\n type BasePatcher,\n type PatcherContext,\n} from './patchers';\nimport {\n METRIC_GEN_AI_CLIENT_OPERATION_DURATION,\n METRIC_GEN_AI_CLIENT_TOKEN_USAGE,\n} from './semconv';\nimport { StreamHandler } from './stream-handler';\nimport { TelemetryRecorder } from './telemetry-recorder';\nimport type { VercelAIInstrumentationConfig } from './types';\nimport { getEnvBool } from './utils';\n\nconst PACKAGE_NAME = '@brizz/vercel-ai-instrumentation';\nconst PACKAGE_VERSION = '0.1.0';\n\n// Type for the Vercel AI module exports\ninterface IVercelAIModule {\n generateText?: (...args: unknown[]) => unknown;\n streamText?: (...args: unknown[]) => unknown;\n generateObject?: (...args: unknown[]) => unknown;\n streamObject?: (...args: unknown[]) => unknown;\n embed?: (...args: unknown[]) => unknown;\n embedMany?: (...args: unknown[]) => unknown;\n generateImage?: (...args: unknown[]) => unknown;\n generateSpeech?: (...args: unknown[]) => unknown;\n transcribe?: (...args: unknown[]) => unknown;\n [key: string]: unknown;\n}\n\nexport class VercelAIInstrumentation extends InstrumentationBase<VercelAIInstrumentationConfig> {\n private _genaiClientOperationDuration!: Histogram;\n private _genaiClientTokenUsage!: Histogram;\n private _telemetryRecorder!: TelemetryRecorder;\n private _streamHandler!: StreamHandler;\n private _patchers: Map<string, BasePatcher> = new Map();\n // Holds last patched namespace when available (reserved for future factory wrapping)\n private _vercelAiNamespace: IVercelAIModule | null = null;\n private static readonly _WRAPPED_SYMBOL: symbol = Symbol.for('brizz.vercel-ai.patched');\n\n constructor(config: VercelAIInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n\n // Check environment variable overrides\n const cfg = this.getConfig();\n const envCC = getEnvBool('OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT');\n if (envCC !== undefined) {\n cfg.captureMessageContent = envCC;\n }\n\n this._initializeComponents();\n }\n\n override setConfig(config: VercelAIInstrumentationConfig = {}): void {\n const {\n captureMessageContent = true,\n enableMetrics = true,\n emitEvents = true,\n ...validConfig\n } = config;\n const fullConfig = {\n ...validConfig,\n captureMessageContent,\n enableMetrics,\n emitEvents,\n } as VercelAIInstrumentationConfig;\n super.setConfig(fullConfig);\n }\n\n private _initializeComponents(): void {\n // Initialize telemetry recorder\n this._telemetryRecorder = new TelemetryRecorder(\n this._genaiClientOperationDuration,\n this._genaiClientTokenUsage,\n this.logger,\n );\n\n // Initialize stream handler\n this._streamHandler = new StreamHandler({\n recordTokenMetrics: this._telemetryRecorder.recordTokenMetrics.bind(this._telemetryRecorder),\n recordDurationMetric: this._telemetryRecorder.recordDurationMetric.bind(\n this._telemetryRecorder,\n ),\n });\n\n // Create patcher context\n const patcherContext: PatcherContext = {\n tracer: this.tracer,\n getConfig: this.getConfig.bind(this),\n recordTokenMetrics: this._telemetryRecorder.recordTokenMetrics.bind(this._telemetryRecorder),\n recordDurationMetric: this._telemetryRecorder.recordDurationMetric.bind(\n this._telemetryRecorder,\n ),\n emitMessageEvents: this._telemetryRecorder.emitMessageEvents.bind(this._telemetryRecorder),\n emitAssistantMessageEvent: this._telemetryRecorder.emitAssistantMessageEvent.bind(\n this._telemetryRecorder,\n ),\n };\n\n // Initialize patchers\n this._patchers.set('generateText', new GenerateTextPatcher(patcherContext));\n this._patchers.set('streamText', new StreamTextPatcher(patcherContext, this._streamHandler));\n this._patchers.set('embed', new EmbeddingsPatcher(patcherContext));\n this._patchers.set('embedMany', new EmbeddingsPatcher(patcherContext));\n\n // TODO: Add generateObject and streamObject patchers\n }\n\n protected init(): InstrumentationNodeModuleDefinition[] {\n return [\n new InstrumentationNodeModuleDefinition(\n 'ai',\n ['>=4.0.0 <6'],\n (moduleExports: IVercelAIModule): IVercelAIModule => {\n logger.info('Starting instrumentation of Vercel AI SDK module');\n this._vercelAiNamespace = moduleExports;\n const patched = this._patchModuleExports(moduleExports);\n return patched ?? moduleExports;\n },\n (moduleExports: IVercelAIModule): IVercelAIModule => {\n logger.debug('Uninstrumenting @vercel/ai module');\n // Cleanup handled by proxy removal\n return moduleExports;\n },\n ),\n ];\n }\n\n override _updateMetricInstruments(): void {\n const config = this.getConfig();\n if (!config.enableMetrics) {\n return;\n }\n\n this._genaiClientOperationDuration = this.meter.createHistogram(\n METRIC_GEN_AI_CLIENT_OPERATION_DURATION,\n {\n description: 'GenAI operation duration',\n unit: 's',\n advice: {\n explicitBucketBoundaries: [\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92,\n ],\n },\n },\n );\n\n this._genaiClientTokenUsage = this.meter.createHistogram(METRIC_GEN_AI_CLIENT_TOKEN_USAGE, {\n description: 'Measures number of input and output tokens used',\n unit: '{token}',\n advice: {\n explicitBucketBoundaries: [\n 1, 4, 16, 64, 256, 1024, 4096, 16_384, 65_536, 262_144, 1_048_576, 4_194_304, 16_777_216,\n 67_108_864,\n ],\n },\n });\n\n // Reinitialize telemetry recorder with new metric instruments\n this._telemetryRecorder = new TelemetryRecorder(\n this._genaiClientOperationDuration,\n this._genaiClientTokenUsage,\n this.logger,\n );\n }\n\n /**\n * Patch known AI SDK functions in-place on the provided module exports object.\n * This approach is compatible with both CJS and ESM module loaders.\n */\n private _patchModuleExports(moduleExports: IVercelAIModule): IVercelAIModule | null {\n if (!moduleExports || typeof moduleExports !== 'object') {\n return null;\n }\n\n let inPlacePatched = true;\n const wrapFunction = (name: string, isEmbedMany = false): void => {\n const current = (moduleExports as Record<string, unknown>)[name];\n if (typeof current !== 'function') {\n return;\n }\n\n const currentFn = current as unknown as { [k: symbol]: unknown } & ((\n ...args: unknown[]\n ) => unknown);\n if (currentFn[VercelAIInstrumentation._WRAPPED_SYMBOL]) {\n return;\n }\n\n // If property is a read-only binding (ESM namespace), skip in-place replacement\n const descriptor = Object.getOwnPropertyDescriptor(moduleExports, name);\n if (descriptor && (!descriptor.writable || !descriptor.configurable) && !descriptor.set) {\n inPlacePatched = false;\n return;\n }\n\n const patcher = this._patchers.get(name);\n if (!patcher) {\n return;\n }\n\n\n const patched = (\n isEmbedMany ? (patcher as any).patch(currentFn, true) : (patcher as any).patch(currentFn)\n ) as (...args: unknown[]) => unknown;\n\n try {\n // Mark as wrapped to avoid double wrapping\n Object.defineProperty(patched, VercelAIInstrumentation._WRAPPED_SYMBOL, {\n value: true,\n enumerable: false,\n configurable: false,\n });\n } catch {\n // no-op if defineProperty fails\n }\n\n try {\n (moduleExports as Record<string, unknown>)[name] = patched as unknown;\n } catch {\n inPlacePatched = false;\n }\n };\n\n wrapFunction('generateText');\n wrapFunction('streamText');\n wrapFunction('embed');\n wrapFunction('embedMany', true);\n\n if (!inPlacePatched) {\n // Fallback to proxy-based wrapping when properties are read-only (ESM namespace)\n // Note: can't import logger here due to circular import in CJS context\n const proxiedModule = new Proxy(moduleExports, {\n get: (\n target: IVercelAIModule,\n prop: string | symbol,\n receiver: IVercelAIModule,\n ): unknown => {\n const originalValue = Reflect.get(target, prop, receiver) as unknown;\n if (\n typeof originalValue === 'function' &&\n typeof prop === 'string' &&\n this._patchers.has(prop)\n ) {\n // Note: can't import logger here due to circular import in CJS context\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const patcher = this._patchers.get(prop) as any;\n const isEmbedMany = prop === 'embedMany';\n const wrapped = isEmbedMany\n ? patcher.patch(originalValue, true)\n : patcher.patch(originalValue);\n return wrapped;\n }\n return originalValue;\n },\n });\n return proxiedModule as unknown as IVercelAIModule;\n }\n\n return moduleExports;\n }\n\n /**\n * Manual instrumentation hook for bundlers/Next.js. Applies in-place wrapping\n * on the provided module namespace.\n */\n public manuallyInstrument(module: unknown): IVercelAIModule {\n try {\n const result = this._patchModuleExports(module as IVercelAIModule);\n if (result !== null) {\n logger.debug('Applied manual Vercel AI instrumentation');\n this._vercelAiNamespace = result;\n return result;\n }\n logger.warn('Manual Vercel AI instrumentation received invalid module');\n return module as IVercelAIModule;\n } catch (error) {\n logger.error(`Failed manual Vercel AI instrumentation: ${String(error)}`);\n // Preserve any previously patched namespace reference for consumers\n return (this._vercelAiNamespace || (module as IVercelAIModule)) as IVercelAIModule;\n }\n }\n\n /**\n * Wrap a created provider/client instance (factory return) when possible.\n * Call this from wrappers that construct provider clients (e.g., OpenAI SDK).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public wrapFactoryReturn<T extends Record<string, any>>(instance: T): T {\n // Future: attach span context or wrap methods on provider clients\n return instance;\n }\n}\n","import { SpanKind, SpanStatusCode } from '@opentelemetry/api';\nimport type { Span, Tracer } from '@opentelemetry/api';\n\nimport {\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_REQUEST_MAX_TOKENS,\n ATTR_GEN_AI_REQUEST_TEMPERATURE,\n ATTR_GEN_AI_REQUEST_TOP_P,\n ATTR_GEN_AI_REQUEST_TOP_K,\n ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY,\n ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY,\n ATTR_GEN_AI_REQUEST_STOP_SEQUENCES,\n ATTR_GEN_AI_OPENAI_API_BASE,\n} from '../semconv';\nimport type { VercelAIInstrumentationConfig, GenerationParams, ProviderInfo, AIMessage } from '../types';\nimport { detectProvider, extractModelId, shouldRecordError } from '../utils';\n\nexport interface IPatcherContext {\n tracer: Tracer;\n getConfig: () => VercelAIInstrumentationConfig;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n recordTokenMetrics: (usage: any, system: string, model: string) => void;\n recordDurationMetric: (duration: number, system: string, model: string, operation: string) => void;\n emitMessageEvents: (messages: AIMessage[], system: string, span: Span) => void;\n emitAssistantMessageEvent: (text: string, system: string, span: Span) => void;\n}\n\n// Type alias for backward compatibility\nexport type PatcherContext = IPatcherContext;\n\nexport abstract class BasePatcher {\n constructor(protected context: PatcherContext) {}\n\n protected createSpan(\n spanName: string,\n params: GenerationParams,\n operationName: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additionalAttributes?: Record<string, any>\n ): { span: Span; provider: ProviderInfo; modelId: string } {\n const provider = detectProvider(params.model);\n const modelId = extractModelId(params.model);\n\n const span = this.context.tracer.startSpan(spanName, {\n kind: SpanKind.CLIENT,\n attributes: {\n [ATTR_GEN_AI_SYSTEM]: provider.system,\n [ATTR_GEN_AI_OPERATION_NAME]: operationName,\n [ATTR_GEN_AI_REQUEST_MODEL]: modelId,\n ...(params.maxTokens && { [ATTR_GEN_AI_REQUEST_MAX_TOKENS]: params.maxTokens }),\n ...(params.temperature !== undefined && {\n [ATTR_GEN_AI_REQUEST_TEMPERATURE]: params.temperature,\n }),\n ...(params.topP !== undefined && { [ATTR_GEN_AI_REQUEST_TOP_P]: params.topP }),\n ...(params.topK !== undefined && { [ATTR_GEN_AI_REQUEST_TOP_K]: params.topK }),\n ...(params.frequencyPenalty !== undefined && {\n [ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY]: params.frequencyPenalty,\n }),\n ...(params.presencePenalty !== undefined && {\n [ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY]: params.presencePenalty,\n }),\n ...(params.stopSequences && {\n [ATTR_GEN_AI_REQUEST_STOP_SEQUENCES]: params.stopSequences,\n }),\n ...(provider.apiBase && { [ATTR_GEN_AI_OPENAI_API_BASE]: provider.apiBase }),\n ...additionalAttributes,\n },\n });\n\n return { span, provider, modelId };\n }\n\n protected handleError(error: unknown, span: Span): void {\n if (shouldRecordError(error)) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message });\n }\n }\n\n protected finalizeDuration(\n span: Span,\n startTime: number,\n config: VercelAIInstrumentationConfig,\n provider: ProviderInfo,\n modelId: string,\n operationName: string\n ): void {\n if (config.enableMetrics) {\n const duration = (globalThis.performance.now() - startTime) / 1000;\n this.context.recordDurationMetric(duration, provider.system, modelId, operationName);\n }\n span.end();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n abstract patch(original: Function): Function;\n}\n","/**\n * GenAI Semantic Conventions for OpenTelemetry\n * Based on: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-spans.md\n */\n\n// Attribute names for GenAI operations\nexport const ATTR_GEN_AI_SYSTEM = 'gen_ai.system' as const;\nexport const ATTR_GEN_AI_OPERATION_NAME = 'gen_ai.operation.name' as const;\nexport const ATTR_GEN_AI_REQUEST_MODEL = 'gen_ai.request.model' as const;\nexport const ATTR_GEN_AI_REQUEST_MAX_TOKENS = 'gen_ai.request.max_tokens' as const;\nexport const ATTR_GEN_AI_REQUEST_TEMPERATURE = 'gen_ai.request.temperature' as const;\nexport const ATTR_GEN_AI_REQUEST_TOP_P = 'gen_ai.request.top_p' as const;\nexport const ATTR_GEN_AI_REQUEST_TOP_K = 'gen_ai.request.top_k' as const;\nexport const ATTR_GEN_AI_REQUEST_STOP_SEQUENCES = 'gen_ai.request.stop_sequences' as const;\nexport const ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY = 'gen_ai.request.frequency_penalty' as const;\nexport const ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY = 'gen_ai.request.presence_penalty' as const;\nexport const ATTR_GEN_AI_REQUEST_ENCODING_FORMATS = 'gen_ai.request.encoding_formats' as const;\n\n// Response attributes\nexport const ATTR_GEN_AI_RESPONSE_ID = 'gen_ai.response.id' as const;\nexport const ATTR_GEN_AI_RESPONSE_MODEL = 'gen_ai.response.model' as const;\nexport const ATTR_GEN_AI_RESPONSE_FINISH_REASONS = 'gen_ai.response.finish_reasons' as const;\n\n// Usage attributes\nexport const ATTR_GEN_AI_USAGE_PROMPT_TOKENS = 'gen_ai.usage.prompt_tokens' as const;\nexport const ATTR_GEN_AI_USAGE_COMPLETION_TOKENS = 'gen_ai.usage.completion_tokens' as const;\nexport const ATTR_GEN_AI_USAGE_TOTAL_TOKENS = 'gen_ai.usage.total_tokens' as const;\n\n// Compatibility attributes (for backwards compatibility)\nexport const ATTR_GEN_AI_USAGE_INPUT_TOKENS = 'gen_ai.usage.input_tokens' as const;\nexport const ATTR_GEN_AI_USAGE_OUTPUT_TOKENS = 'gen_ai.usage.output_tokens' as const;\n\n// Token type for metrics\nexport const ATTR_GEN_AI_TOKEN_TYPE = 'gen_ai.token.type' as const;\n\n// Prompt and completion attributes (indexed)\nexport const ATTR_GEN_AI_PROMPT = 'gen_ai.prompt' as const;\nexport const ATTR_GEN_AI_COMPLETION = 'gen_ai.completion' as const;\n\n// Provider-specific attributes\nexport const ATTR_GEN_AI_OPENAI_API_BASE = 'gen_ai.openai.api_base' as const;\nexport const ATTR_GEN_AI_OPENAI_API_TYPE = 'gen_ai.openai.api_type' as const;\nexport const ATTR_GEN_AI_OPENAI_API_VERSION = 'gen_ai.openai.api_version' as const;\n\n// Event attributes\nexport const ATTR_EVENT_NAME = 'event.name' as const;\n\n// Event names\nexport const EVENT_GEN_AI_USER_MESSAGE = 'gen_ai.user.message' as const;\nexport const EVENT_GEN_AI_ASSISTANT_MESSAGE = 'gen_ai.assistant.message' as const;\nexport const EVENT_GEN_AI_SYSTEM_MESSAGE = 'gen_ai.system.message' as const;\nexport const EVENT_GEN_AI_TOOL_MESSAGE = 'gen_ai.tool.message' as const;\nexport const EVENT_GEN_AI_CHOICE = 'gen_ai.choice' as const;\n\n// Metric names\nexport const METRIC_GEN_AI_CLIENT_OPERATION_DURATION = 'gen_ai.client.operation.duration' as const;\nexport const METRIC_GEN_AI_CLIENT_TOKEN_USAGE = 'gen_ai.client.token.usage' as const;\n\n// Operation names\nexport const OPERATION_NAME_CHAT = 'chat' as const;\nexport const OPERATION_NAME_EMBEDDINGS = 'embeddings' as const;\nexport const OPERATION_NAME_IMAGE_GENERATION = 'image_generation' as const;\nexport const OPERATION_NAME_SPEECH_SYNTHESIS = 'speech_synthesis' as const;\nexport const OPERATION_NAME_TRANSCRIPTION = 'transcription' as const;\n\n// Token types\nexport const TOKEN_TYPE_INPUT = 'input' as const;\nexport const TOKEN_TYPE_OUTPUT = 'output' as const;\n\n// Common provider names\nexport const PROVIDER_OPENAI = 'openai' as const;\nexport const PROVIDER_ANTHROPIC = 'anthropic' as const;\nexport const PROVIDER_GOOGLE = 'google' as const;\nexport const PROVIDER_AMAZON = 'amazon' as const;\nexport const PROVIDER_AZURE = 'azure' as const;\nexport const PROVIDER_VERCEL = 'vercel' as const;\nexport const PROVIDER_UNKNOWN = 'unknown' as const;\n\n// Span names\nexport const SPAN_NAME_GEN_AI_CHAT = 'gen_ai.chat' as const;\nexport const SPAN_NAME_GEN_AI_EMBEDDINGS = 'gen_ai.embeddings' as const;\nexport const SPAN_NAME_GEN_AI_IMAGE_GENERATION = 'gen_ai.image_generation' as const;\nexport const SPAN_NAME_GEN_AI_SPEECH_SYNTHESIS = 'gen_ai.speech_synthesis' as const;\nexport const SPAN_NAME_GEN_AI_TRANSCRIPTION = 'gen_ai.transcription' as const;\n","/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return */\nimport type { Attributes } from '@opentelemetry/api';\n\nimport {\n PROVIDER_OPENAI,\n PROVIDER_ANTHROPIC,\n PROVIDER_GOOGLE,\n PROVIDER_AMAZON,\n PROVIDER_AZURE,\n PROVIDER_VERCEL,\n PROVIDER_UNKNOWN,\n ATTR_GEN_AI_PROMPT,\n ATTR_GEN_AI_COMPLETION,\n} from './semconv';\nimport type { ProviderInfo, AIMessage, ModelInfo, TokenUsage } from './types';\n\n/**\n * Detect the provider from model information\n */\nexport function detectProvider(model: string | ModelInfo): ProviderInfo {\n // If model is an object with provider info\n if (typeof model === 'object' && model !== null) {\n const modelObj = model;\n if (modelObj.provider) {\n return {\n system: normalizeProviderName(modelObj.provider),\n apiBase: extractApiBase(modelObj),\n };\n }\n // Try to detect from modelId\n if (modelObj.modelId) {\n return detectProviderFromModelId(modelObj.modelId);\n }\n }\n\n // If model is a string, try to detect from it\n if (typeof model === 'string') {\n return detectProviderFromModelId(model);\n }\n\n return { system: PROVIDER_UNKNOWN };\n}\n\n/**\n * Detect provider from model ID string\n */\nfunction detectProviderFromModelId(modelId: string): ProviderInfo {\n const lowerModel = modelId.toLowerCase();\n\n // OpenAI models\n if (\n lowerModel.startsWith('gpt-') ||\n lowerModel.startsWith('text-davinci-') ||\n lowerModel.startsWith('text-embedding-') ||\n lowerModel.startsWith('dall-e') ||\n lowerModel.startsWith('whisper-') ||\n lowerModel.startsWith('tts-')\n ) {\n return { system: PROVIDER_OPENAI };\n }\n\n // Anthropic models\n if (lowerModel.startsWith('claude-')) {\n return { system: PROVIDER_ANTHROPIC };\n }\n\n // Google models\n if (\n lowerModel.startsWith('gemini-') ||\n lowerModel.startsWith('palm-') ||\n lowerModel.includes('bison') ||\n lowerModel.includes('gecko')\n ) {\n return { system: PROVIDER_GOOGLE };\n }\n\n // Amazon Bedrock models\n if (\n lowerModel.startsWith('amazon.') ||\n lowerModel.startsWith('anthropic.claude-') ||\n lowerModel.startsWith('ai21.') ||\n lowerModel.startsWith('cohere.') ||\n lowerModel.startsWith('meta.llama')\n ) {\n return { system: PROVIDER_AMAZON };\n }\n\n // Azure models (usually prefixed with deployment name)\n if (lowerModel.includes('azure') || lowerModel.includes('.openai.azure.com')) {\n return { system: PROVIDER_AZURE };\n }\n\n // Default to the model ID prefix if it looks like a provider name\n const parts = modelId.split(/[-._/]/);\n if (parts.length > 0 && parts[0]) {\n return { system: normalizeProviderName(parts[0]) };\n }\n\n return { system: PROVIDER_UNKNOWN };\n}\n\n/**\n * Normalize provider name to standard format\n */\nfunction normalizeProviderName(provider: string): string {\n const normalized = provider.toLowerCase().trim();\n\n switch (normalized) {\n case 'openai':\n case 'open-ai':\n case 'open_ai': {\n return PROVIDER_OPENAI;\n }\n case 'anthropic':\n case 'claude': {\n return PROVIDER_ANTHROPIC;\n }\n case 'google':\n case 'vertex':\n case 'vertexai':\n case 'vertex-ai':\n case 'gemini': {\n return PROVIDER_GOOGLE;\n }\n case 'amazon':\n case 'aws':\n case 'bedrock':\n case 'amazon-bedrock': {\n return PROVIDER_AMAZON;\n }\n case 'azure':\n case 'azure-openai':\n case 'microsoft': {\n return PROVIDER_AZURE;\n }\n case 'vercel':\n case 'vercel-ai': {\n return PROVIDER_VERCEL;\n }\n default: {\n return normalized;\n }\n }\n}\n\n/**\n * Extract API base URL from model configuration\n */\nfunction extractApiBase(model: ModelInfo): string | undefined {\n // Try to extract from various possible locations\n if (typeof model === 'object' && model !== null) {\n const anyModel = model as any;\n return anyModel.apiBase || anyModel.baseURL || anyModel.endpoint || undefined;\n }\n return undefined;\n}\n\n/**\n * Extract model ID from model parameter\n */\nexport function extractModelId(model: string | ModelInfo): string {\n if (typeof model === 'string') {\n return model;\n }\n if (typeof model === 'object' && model !== null) {\n return model.modelId || 'unknown';\n }\n return 'unknown';\n}\n\n/**\n * Convert messages to indexed attributes for tracing\n */\nexport function messagesToAttributes(\n messages: AIMessage[],\n prefix: string,\n captureContent: boolean,\n): Attributes {\n const attributes: Attributes = {};\n\n for (const [index, msg] of messages.entries()) {\n const baseKey = `${prefix}.${index}`;\n\n // Always capture role\n attributes[`${baseKey}.role`] = msg.role;\n\n // Optionally capture content\n if (captureContent && msg.content) {\n if (typeof msg.content === 'string') {\n attributes[`${baseKey}.content`] = msg.content;\n } else if (Array.isArray(msg.content)) {\n // For multi-modal content, extract text parts\n const textParts = msg.content\n .filter((part) => part.type === 'text' && part.text)\n .map((part) => part.text)\n .join(' ');\n if (textParts) {\n attributes[`${baseKey}.content`] = textParts;\n }\n }\n }\n\n // Capture tool information if present\n if (msg.toolInvocations && msg.toolInvocations.length > 0) {\n attributes[`${baseKey}.tool_calls`] = msg.toolInvocations.length;\n }\n }\n\n return attributes;\n}\n\n/**\n * Convert prompt string to attributes\n */\nexport function promptToAttributes(prompt: string, captureContent: boolean): Attributes {\n const attributes: Attributes = {};\n\n attributes[`${ATTR_GEN_AI_PROMPT}.0.role`] = 'user';\n if (captureContent) {\n attributes[`${ATTR_GEN_AI_PROMPT}.0.content`] = prompt;\n }\n\n return attributes;\n}\n\n/**\n * Convert completion to attributes\n */\nexport function completionToAttributes(\n text: string,\n finishReason: string | undefined,\n captureContent: boolean,\n): Attributes {\n const attributes: Attributes = {};\n\n attributes[`${ATTR_GEN_AI_COMPLETION}.0.role`] = 'assistant';\n if (captureContent) {\n attributes[`${ATTR_GEN_AI_COMPLETION}.0.content`] = text;\n }\n if (finishReason) {\n attributes[`${ATTR_GEN_AI_COMPLETION}.0.finish_reason`] = finishReason;\n }\n\n return attributes;\n}\n\n/**\n * Extract token usage attributes\n */\nexport function tokenUsageToAttributes(usage: TokenUsage | undefined): Attributes {\n if (!usage) {\n return {};\n }\n\n const attributes: Attributes = {};\n\n // Handle Vercel AI SDK format (inputTokens, outputTokens)\n if (usage.inputTokens !== undefined) {\n attributes['gen_ai.usage.prompt_tokens'] = usage.inputTokens;\n attributes['gen_ai.usage.input_tokens'] = usage.inputTokens;\n attributes['llm.usage.prompt_tokens'] = usage.inputTokens;\n }\n // Handle legacy format (promptTokens)\n else if (usage.promptTokens !== undefined) {\n attributes['gen_ai.usage.prompt_tokens'] = usage.promptTokens;\n attributes['gen_ai.usage.input_tokens'] = usage.promptTokens;\n attributes['llm.usage.prompt_tokens'] = usage.promptTokens;\n }\n\n // Handle Vercel AI SDK format (outputTokens)\n if (usage.outputTokens !== undefined) {\n attributes['gen_ai.usage.completion_tokens'] = usage.outputTokens;\n attributes['gen_ai.usage.output_tokens'] = usage.outputTokens;\n attributes['llm.usage.completion_tokens'] = usage.outputTokens;\n }\n // Handle legacy format (completionTokens)\n else if (usage.completionTokens !== undefined) {\n attributes['gen_ai.usage.completion_tokens'] = usage.completionTokens;\n attributes['gen_ai.usage.output_tokens'] = usage.completionTokens;\n attributes['llm.usage.completion_tokens'] = usage.completionTokens;\n }\n\n if (usage.totalTokens === undefined) {\n // Calculate total if not provided\n const inputTokens = usage.inputTokens || usage.promptTokens;\n const outputTokens = usage.outputTokens || usage.completionTokens;\n if (inputTokens !== undefined && outputTokens !== undefined) {\n const totalTokens = inputTokens + outputTokens;\n attributes['gen_ai.usage.total_tokens'] = totalTokens;\n attributes['llm.usage.total_tokens'] = totalTokens;\n }\n } else {\n attributes['gen_ai.usage.total_tokens'] = usage.totalTokens;\n attributes['llm.usage.total_tokens'] = usage.totalTokens;\n }\n\n return attributes;\n}\n\n/**\n * Check if error should be recorded\n */\nexport function shouldRecordError(error: unknown): boolean {\n // Don't record user cancellations as errors\n if (error instanceof Error) {\n const message = error.message.toLowerCase();\n if (message.includes('abort') || message.includes('cancel')) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Safe JSON stringify for attributes\n */\nexport function safeStringify(value: unknown): string {\n try {\n if (typeof value === 'string') {\n return value;\n }\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Get environment variable as boolean\n */\nexport function getEnvBool(name: string): boolean | undefined {\n const value = process.env[name];\n if (value === undefined) {\n return undefined;\n }\n return value.toLowerCase() === 'true' || value === '1';\n}\n\n/**\n * Check if a value is a promise\n */\nexport function isPromise(value: unknown): value is Promise<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'then' in value &&\n typeof (value as any).then === 'function'\n );\n}\n\n/**\n * Check if a value is an async iterable\n */\nexport function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return value !== null && typeof value === 'object' && Symbol.asyncIterator in value;\n}\n","import { context, SpanStatusCode, trace } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\n\nimport {\n ATTR_GEN_AI_RESPONSE_ID,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_RESPONSE_FINISH_REASONS,\n SPAN_NAME_GEN_AI_CHAT,\n OPERATION_NAME_CHAT,\n} from '../semconv';\nimport type { GenerationParams, TextGenerationResult, ProviderInfo } from '../types';\nimport { messagesToAttributes, promptToAttributes, completionToAttributes, tokenUsageToAttributes } from '../utils';\n\nimport { BasePatcher } from './base-patcher';\n\n// Define function signature for original generateText function\ntype OriginalGenerateTextFunction = (params: GenerationParams) => Promise<TextGenerationResult>;\n\n// Define interface for createSpan result\ninterface ICreateSpanResult {\n span: Span;\n provider: ProviderInfo;\n modelId: string;\n}\n\nexport class GenerateTextPatcher extends BasePatcher {\n patch(original: OriginalGenerateTextFunction): OriginalGenerateTextFunction {\n return async (params: GenerationParams): Promise<TextGenerationResult> => {\n const config = this.context.getConfig();\n const startTime = globalThis.performance.now();\n\n const { span, provider, modelId } = this.createSpan(\n SPAN_NAME_GEN_AI_CHAT,\n params,\n OPERATION_NAME_CHAT\n ) as ICreateSpanResult;\n\n // Add prompt/messages attributes\n if (params.prompt) {\n span.setAttributes(\n promptToAttributes(params.prompt, config.captureMessageContent || false),\n );\n } else if (params.messages) {\n span.setAttributes(\n messagesToAttributes(\n params.messages,\n 'gen_ai.prompt',\n config.captureMessageContent || false,\n ),\n );\n\n // Emit message events if enabled\n if (config.emitEvents) {\n this.context.emitMessageEvents(params.messages, provider.system, span);\n }\n }\n\n try {\n const result = await context.with(trace.setSpan(context.active(), span), () =>\n original(params),\n );\n\n // Set response attributes\n if (result.response) {\n span.setAttributes({\n ...(result.response.id && { [ATTR_GEN_AI_RESPONSE_ID]: result.response.id }),\n ...(result.response.model && { [ATTR_GEN_AI_RESPONSE_MODEL]: result.response.model }),\n });\n }\n\n // Set finish reason\n if (result.finishReason) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [result.finishReason]);\n }\n\n // Set completion attributes\n span.setAttributes(\n completionToAttributes(\n result.text,\n result.finishReason,\n config.captureMessageContent || false,\n ),\n );\n\n // Set token usage - check different possible locations\n const usage = result.usage || result.totalUsage || result.steps?.[0]?.usage;\n if (usage) {\n span.setAttributes(tokenUsageToAttributes(usage));\n\n // Record metrics\n if (config.enableMetrics) {\n this.context.recordTokenMetrics(usage, provider.system, modelId);\n }\n }\n\n // Emit assistant message event\n if (config.emitEvents) {\n this.context.emitAssistantMessageEvent(result.text, provider.system, span);\n }\n\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n this.handleError(error, span);\n throw error;\n } finally {\n this.finalizeDuration(span, startTime, config, provider, modelId, OPERATION_NAME_CHAT);\n }\n };\n }\n}\n","import { context, trace } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\n\nimport {\n SPAN_NAME_GEN_AI_CHAT,\n OPERATION_NAME_CHAT,\n} from '../semconv';\nimport type { StreamHandler } from '../stream-handler';\nimport type { GenerationParams, ProviderInfo } from '../types';\nimport { messagesToAttributes, promptToAttributes } from '../utils';\n\nimport { BasePatcher } from './base-patcher';\nimport type { PatcherContext } from './base-patcher';\n\n// Define function signature for original streamText function\ntype OriginalStreamTextFunction = (params: GenerationParams) => Promise<unknown>;\n\n// Define interface for createSpan result\ninterface ICreateSpanResult {\n span: Span;\n provider: ProviderInfo;\n modelId: string;\n}\n\n\nexport class StreamTextPatcher extends BasePatcher {\n constructor(\n context: PatcherContext,\n private streamHandler: StreamHandler\n ) {\n super(context);\n }\n\n patch(original: OriginalStreamTextFunction): OriginalStreamTextFunction {\n return async (params: GenerationParams): Promise<unknown> => {\n const config = this.context.getConfig();\n const startTime = globalThis.performance.now();\n\n const { span, provider, modelId } = this.createSpan(\n SPAN_NAME_GEN_AI_CHAT,\n params,\n OPERATION_NAME_CHAT,\n { 'gen_ai.streaming': true }\n ) as ICreateSpanResult;\n\n // Add prompt/messages attributes\n if (params.prompt) {\n span.setAttributes(\n promptToAttributes(params.prompt, config.captureMessageContent || false),\n );\n } else if (params.messages) {\n span.setAttributes(\n messagesToAttributes(\n params.messages,\n 'gen_ai.prompt',\n config.captureMessageContent || false,\n ),\n );\n\n // Emit message events if enabled\n if (config.emitEvents) {\n this.context.emitMessageEvents(params.messages, provider.system, span);\n }\n }\n\n try {\n const stream = await context.with(trace.setSpan(context.active(), span), () =>\n original(params),\n );\n\n // Wrap the stream to capture completion data\n return this.streamHandler.wrapStream(stream, span, config, provider, modelId, startTime);\n } catch (error) {\n this.handleError(error, span);\n span.end();\n throw error;\n }\n };\n }\n}\n","import { context, SpanStatusCode, trace } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\n\nimport {\n ATTR_GEN_AI_RESPONSE_ID,\n ATTR_GEN_AI_RESPONSE_MODEL,\n SPAN_NAME_GEN_AI_EMBEDDINGS,\n OPERATION_NAME_EMBEDDINGS,\n} from '../semconv';\nimport type { EmbeddingResult, ProviderInfo, GenerationParams } from '../types';\nimport { tokenUsageToAttributes } from '../utils';\n\nimport { BasePatcher } from './base-patcher';\n\n// Define interfaces for embedding functions\ninterface IEmbeddingParams {\n value?: string;\n values?: string[];\n model?: string | { [key: string]: unknown };\n [key: string]: unknown;\n}\n\ntype OriginalEmbedFunction = (params: IEmbeddingParams) => Promise<EmbeddingResult>;\n\n// Define interface for createSpan result\ninterface ICreateSpanResult {\n span: Span;\n provider: ProviderInfo;\n modelId: string;\n}\n\nexport class EmbeddingsPatcher extends BasePatcher {\n patch(original: OriginalEmbedFunction, isMany: boolean = false): OriginalEmbedFunction {\n return async (params: IEmbeddingParams): Promise<EmbeddingResult> => {\n const config = this.context.getConfig();\n const startTime = globalThis.performance.now();\n\n const additionalAttributes = isMany\n ? { 'gen_ai.embeddings.count': params.values ? params.values.length : 0 }\n : {};\n\n const { span, provider, modelId } = this.createSpan(\n SPAN_NAME_GEN_AI_EMBEDDINGS,\n params as GenerationParams,\n OPERATION_NAME_EMBEDDINGS,\n additionalAttributes\n ) as ICreateSpanResult;\n\n // Add input text if capturing content (for single embed)\n if (!isMany && config.captureMessageContent && params.value) {\n span.setAttribute('gen_ai.prompt.0.content', params.value);\n }\n\n try {\n const result = await context.with(trace.setSpan(context.active(), span), () =>\n original(params),\n );\n\n // Set response attributes\n if (result.response) {\n span.setAttributes({\n ...(result.response.id && { [ATTR_GEN_AI_RESPONSE_ID]: result.response.id }),\n ...(result.response.model && { [ATTR_GEN_AI_RESPONSE_MODEL]: result.response.model }),\n });\n }\n\n // Set embedding dimensions\n if (isMany) {\n if (result.embeddings && result.embeddings.length > 0 && result.embeddings[0]) {\n span.setAttribute('gen_ai.response.embedding_dimensions', result.embeddings[0].length);\n }\n } else {\n if (result.embedding) {\n span.setAttribute('gen_ai.response.embedding_dimensions', result.embedding.length);\n }\n }\n\n // Set token usage\n if (result.usage) {\n span.setAttributes(tokenUsageToAttributes(result.usage));\n\n // Record metrics\n if (config.enableMetrics) {\n this.context.recordTokenMetrics(result.usage, provider.system, modelId);\n }\n }\n\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n this.handleError(error, span);\n throw error;\n } finally {\n this.finalizeDuration(span, startTime, config, provider, modelId, OPERATION_NAME_EMBEDDINGS);\n }\n };\n }\n}\n","/* eslint-disable unicorn/no-this-assignment, @typescript-eslint/no-this-alias, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-return, @typescript-eslint/explicit-module-boundary-types, no-undef */\nimport { SpanStatusCode } from '@opentelemetry/api';\nimport type { Span } from '@opentelemetry/api';\n\nimport {\n ATTR_GEN_AI_RESPONSE_ID,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_RESPONSE_FINISH_REASONS,\n OPERATION_NAME_CHAT,\n} from './semconv';\nimport type { VercelAIInstrumentationConfig } from './types';\nimport { completionToAttributes, tokenUsageToAttributes } from './utils';\n\nexport interface StreamHandlerContext {\n recordTokenMetrics: (usage: any, system: string, model: string) => void;\n recordDurationMetric: (duration: number, system: string, model: string, operation: string) => void;\n}\n\nexport class StreamHandler {\n constructor(private context: StreamHandlerContext) {}\n\n wrapStream(\n stream: any,\n span: Span,\n config: VercelAIInstrumentationConfig,\n provider: any,\n modelId: string,\n startTime: number,\n ) {\n const self = this;\n let fullText = '';\n let finishReason: string | undefined;\n let usage: any;\n let response: any;\n\n // Create a proxy for the stream\n const wrappedStream = new Proxy(stream, {\n get(target, prop) {\n // Special handling for async iterator (direct stream consumption)\n if (prop === Symbol.asyncIterator) {\n return async function* () {\n try {\n for await (const chunk of target) {\n // Accumulate data from chunks\n if (chunk.type === 'text-delta' && chunk.textDelta) {\n fullText += chunk.textDelta;\n } else if (chunk.type === 'finish') {\n finishReason = chunk.finishReason;\n usage = chunk.usage;\n } else if (chunk.type === 'response-metadata') {\n response = chunk.response;\n }\n\n yield chunk;\n }\n } finally {\n self.finalizeStream(\n span,\n config,\n provider,\n modelId,\n startTime,\n fullText,\n finishReason,\n usage,\n response\n );\n }\n };\n }\n\n // Special handling for textStream and other async iterables\n if (prop === 'textStream' || prop === 'fullStream') {\n const originalStream = target[prop];\n\n // Create a wrapped async iterable\n return {\n [Symbol.asyncIterator]: async function* () {\n try {\n for await (const chunk of originalStream) {\n // For textStream, chunks are just strings\n if (prop === 'textStream') {\n fullText += chunk;\n }\n yield chunk;\n }\n } finally {\n // Get usage from the parent stream\n const streamUsage = await target.usage.catch(() => null);\n if (streamUsage) {\n usage = streamUsage;\n }\n self.finalizeStream(\n span,\n config,\n provider,\n modelId,\n startTime,\n fullText,\n finishReason,\n usage,\n response\n );\n }\n }\n };\n }\n\n // For all other properties, return the original\n const value = target[prop];\n if (typeof value === 'function') {\n return value.bind(target);\n }\n return value;\n },\n });\n\n return wrappedStream;\n }\n\n private finalizeStream(\n span: Span,\n config: VercelAIInstrumentationConfig,\n provider: any,\n modelId: string,\n startTime: number,\n fullText: string,\n finishReason: string | undefined,\n usage: any,\n response: any\n ): void {\n // Set final attributes when stream completes\n if (response) {\n span.setAttributes({\n ...(response.id && { [ATTR_GEN_AI_RESPONSE_ID]: response.id }),\n ...(response.model && { [ATTR_GEN_AI_RESPONSE_MODEL]: response.model }),\n });\n }\n\n if (finishReason) {\n span.setAttribute(ATTR_GEN_AI_RESPONSE_FINISH_REASONS, [finishReason]);\n }\n\n if (fullText) {\n span.setAttributes(\n completionToAttributes(\n fullText,\n finishReason,\n config.captureMessageContent || false,\n ),\n );\n }\n\n if (usage) {\n span.setAttributes(tokenUsageToAttributes(usage));\n\n // Record metrics\n if (config.enableMetrics) {\n this.context.recordTokenMetrics(usage, provider.system, modelId);\n }\n }\n\n // Record duration metric\n if (config.enableMetrics) {\n const duration = (performance.now() - startTime) / 1000;\n this.context.recordDurationMetric(duration, provider.system, modelId, OPERATION_NAME_CHAT);\n }\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n }\n}\n","/* eslint-disable @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument */\nimport { context, trace } from '@opentelemetry/api';\nimport type { Span, Histogram } from '@opentelemetry/api';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\n\nimport {\n ATTR_EVENT_NAME,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_TOKEN_TYPE,\n EVENT_GEN_AI_USER_MESSAGE,\n EVENT_GEN_AI_ASSISTANT_MESSAGE,\n EVENT_GEN_AI_SYSTEM_MESSAGE,\n EVENT_GEN_AI_TOOL_MESSAGE,\n TOKEN_TYPE_INPUT,\n TOKEN_TYPE_OUTPUT,\n} from './semconv';\nimport type { AIMessage } from './types';\n\nexport class TelemetryRecorder {\n constructor(\n private genaiClientOperationDuration: Histogram,\n private genaiClientTokenUsage: Histogram,\n private logger?: any\n ) {}\n\n /**\n * Record token usage metrics\n */\n recordTokenMetrics(usage: any, system: string, model: string): void {\n if (!this.genaiClientTokenUsage) {\n return;\n }\n\n const commonAttrs = {\n [ATTR_GEN_AI_SYSTEM]: system,\n [ATTR_GEN_AI_REQUEST_MODEL]: model,\n };\n\n // Handle different token usage formats\n const inputTokens = usage.inputTokens || usage.promptTokens;\n const outputTokens = usage.outputTokens || usage.completionTokens;\n\n if (inputTokens !== undefined) {\n this.genaiClientTokenUsage.record(inputTokens, {\n ...commonAttrs,\n [ATTR_GEN_AI_TOKEN_TYPE]: TOKEN_TYPE_INPUT,\n });\n }\n\n if (outputTokens !== undefined) {\n this.genaiClientTokenUsage.record(outputTokens, {\n ...commonAttrs,\n [ATTR_GEN_AI_TOKEN_TYPE]: TOKEN_TYPE_OUTPUT,\n });\n }\n }\n\n /**\n * Record operation duration metric\n */\n recordDurationMetric(\n duration: number,\n system: string,\n model: string,\n operation: string,\n ): void {\n if (!this.genaiClientOperationDuration) {\n return;\n }\n\n this.genaiClientOperationDuration.record(duration, {\n [ATTR_GEN_AI_SYSTEM]: system,\n [ATTR_GEN_AI_REQUEST_MODEL]: model,\n [ATTR_GEN_AI_OPERATION_NAME]: operation,\n });\n }\n\n /**\n * Emit message events\n */\n emitMessageEvents(messages: AIMessage[], system: string, span: Span): void {\n if (!this.logger) {\n return;\n }\n\n const ctx = trace.setSpan(context.active(), span);\n\n for (const msg of messages) {\n let eventName: string;\n switch (msg.role) {\n case 'system': {\n eventName = EVENT_GEN_AI_SYSTEM_MESSAGE;\n break;\n }\n case 'user': {\n eventName = EVENT_GEN_AI_USER_MESSAGE;\n break;\n }\n case 'assistant': {\n eventName = EVENT_GEN_AI_ASSISTANT_MESSAGE;\n break;\n }\n case 'tool':\n case 'function': {\n eventName = EVENT_GEN_AI_TOOL_MESSAGE;\n break;\n }\n default: {\n continue;\n } // Skip unknown roles\n }\n\n this.logger.emit({\n timestamp: Date.now(),\n context: ctx,\n severityNumber: SeverityNumber.INFO,\n attributes: {\n [ATTR_EVENT_NAME]: eventName,\n [ATTR_GEN_AI_SYSTEM]: system,\n },\n body: {\n role: msg.role,\n content: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),\n name: msg.name,\n },\n });\n }\n }\n\n /**\n * Emit assistant message event\n */\n emitAssistantMessageEvent(text: string, system: string, span: Span): void {\n if (!this.logger) {\n return;\n }\n\n const ctx = trace.setSpan(context.active(), span);\n\n this.logger.emit({\n timestamp: Date.now(),\n context: ctx,\n severityNumber: SeverityNumber.INFO,\n attributes: {\n [ATTR_EVENT_NAME]: EVENT_GEN_AI_ASSISTANT_MESSAGE,\n [ATTR_GEN_AI_SYSTEM]: system,\n },\n body: {\n role: 'assistant',\n content: text,\n },\n });\n }\n}\n","import { resourceFromAttributes } from '@opentelemetry/resources';\nimport type { LogRecordExporter } from '@opentelemetry/sdk-logs';\nimport type { MetricReader } from '@opentelemetry/sdk-metrics';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport type { SpanExporter } from '@opentelemetry/sdk-trace-base';\n\nimport type { IResolvedBrizzConfig } from './config';\nimport { resolveConfig } from './config';\nimport { InstrumentationRegistry, type IInstrumentModules } from './instrumentation';\nimport { LoggingModule } from './log';\nimport type { LogLevel } from './logger';\nimport { logger } from './logger';\nimport { type IMaskingConfig } from './masking';\nimport { getMetricsReader, MetricsModule } from './metric';\nimport { getSpanProcessor, TracingModule } from './trace';\n\n/**\n * Configuration options for initializing the Brizz SDK.\n *\n * @interface IBrizzInitializeOptions\n */\nexport interface IBrizzInitializeOptions {\n /** Application name for service identification */\n appName?: string;\n /** Base URL for telemetry endpoints (defaults to https://telemetry.brizz.dev) */\n baseUrl?: string;\n /** API key for authentication */\n apiKey?: string;\n /** Additional HTTP headers to include in telemetry requests */\n headers?: Record<string, string>;\n /** Disable batch processing for immediate event emission */\n disableBatch?: boolean;\n /**\n * Configuration for data masking and PII protection.\n * - `true`: Enable masking with default rules\n * - `false` or `undefined`: Disable masking\n * - `IMaskingConfig`: Enable masking with custom configuration\n */\n masking?: boolean | IMaskingConfig;\n /** Log level for SDK internal logging and OpenTelemetry diagnostic logging (debug, info, warn, error, none) */\n logLevel?: LogLevel | string;\n /**\n * Manual instrumentation modules for Next.js/Webpack environments.\n * Provide the actual imported modules to enable instrumentation in environments\n * where automatic instrumentation doesn't work properly.\n *\n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import * as LlamaIndex from 'llamaindex';\n *\n * Brizz.initialize({\n * appName: 'my-app',\n * instrumentModules: {\n * openAI: OpenAI,\n * llamaindex: LlamaIndex\n * }\n * });\n * ```\n */\n instrumentModules?: IInstrumentModules;\n /**\n * Disable the internal NodeSDK initialization and only setup telemetry modules.\n * This is useful when you want to create your own NodeSDK using Brizz utilities.\n * Brizz will automatically register its instrumentations with your SDK.\n *\n * @example\n * ```typescript\n * import { NodeSDK } from '@opentelemetry/sdk-node';\n * import { Brizz, getSpanProcessor } from 'brizz-sdk';\n *\n * // Initialize Brizz without internal NodeSDK\n * Brizz.initialize({\n * appName: 'my-app',\n * disableNodeSdk: true\n * });\n *\n * // Create your own NodeSDK\n * const sdk = new NodeSDK({\n * spanProcessors: [getSpanProcessor()],\n * // your custom configuration\n * });\n * sdk.start();\n * ```\n */\n disableNodeSdk?: boolean;\n /**\n * Custom span exporter for testing or alternative backends.\n * When provided, this exporter will be used instead of the default OTLP exporter.\n * Useful for integration testing with InMemorySpanExporter or custom exporters.\n *\n * @example\n * ```typescript\n * import { InMemorySpanExporter } from '@opentelemetry/sdk-trace-base';\n *\n * const spanExporter = new InMemorySpanExporter();\n * Brizz.initialize({\n * appName: 'test-app',\n * customSpanExporter: spanExporter\n * });\n *\n * // Later in tests\n * const spans = spanExporter.getFinishedSpans();\n * ```\n */\n customSpanExporter?: SpanExporter;\n /**\n * Custom log exporter for testing or alternative backends.\n * When provided, this exporter will be used instead of the default OTLP exporter.\n * Useful for integration testing with InMemoryLogExporter or custom exporters.\n *\n * @example\n * ```typescript\n * import { InMemoryLogExporter } from 'brizz-sdk/test-utils';\n *\n * const logExporter = new InMemoryLogExporter();\n * Brizz.initialize({\n * appName: 'test-app',\n * customLogExporter: logExporter\n * });\n *\n * // Later in tests\n * const logs = logExporter.getFinishedLogs();\n * ```\n */\n customLogExporter?: LogRecordExporter;\n /**\n * Custom metric reader for testing or alternative backends.\n * When provided, this reader will be used instead of the default OTLP exporter.\n * Useful for integration testing with InMemoryMetricReader or custom readers.\n *\n * @example\n * ```typescript\n * import { InMemoryMetricReader } from 'brizz-sdk/test-utils';\n *\n * const metricReader = new InMemoryMetricReader();\n * Brizz.initialize({\n * appName: 'test-app',\n * customMetricReader: metricReader\n * });\n *\n * // Later in tests\n * const metrics = metricReader.getCollectedMetrics();\n * ```\n */\n customMetricReader?: MetricReader;\n}\n\n/**\n * Internal implementation of the Brizz SDK.\n *\n * This class is responsible only for initialization and shutdown of the SDK.\n * All functionality is exposed through standalone utility functions.\n *\n * @class _Brizz\n * @internal\n */\nexport class _Brizz {\n private static instance: _Brizz | null = null;\n /** Flag indicating if SDK initialization has completed successfully */\n private _initialized = false;\n\n /** OpenTelemetry sdk instance */\n private _sdk: NodeSDK | null = null;\n\n static getInstance(): _Brizz {\n if (!_Brizz.instance) {\n throw new Error('Brizz must be initialized before accessing TracingModule');\n }\n return _Brizz.instance;\n }\n\n /**\n * Initialize the Brizz SDK with the provided configuration.\n *\n * @param {IBrizzInitializeOptions} options - Configuration options for the SDK\n * @throws {Error} - If initialization fails\n *\n * @example\n * ```typescript\n * Brizz.initialize({\n * appName: 'my-app',\n * baseUrl: 'http://localhost:4318',\n * apiKey: 'your-api-key'\n * });\n * ```\n */\n initialize(options: IBrizzInitializeOptions): void {\n if (this._initialized) {\n logger.warn('Brizz SDK already initialized');\n return;\n }\n\n logger.info('Starting Brizz SDK initialization');\n\n try {\n const resolvedConfig = resolveConfig(options);\n this.initializeModules(resolvedConfig);\n this.setupInstrumentation(options);\n this.createAndStartNodeSDK(options, resolvedConfig);\n\n this._initialized = true;\n logger.info('Brizz SDK initialization completed successfully', {\n moduleSystem: this.detectModuleSystem(),\n });\n } catch (error) {\n logger.error('Failed to initialize Brizz SDK', { error });\n throw new Error(`Failed to initialize SDK: ${String(error)}`);\n }\n }\n\n /**\n * Set up instrumentation registry and configure manual modules.\n * @private\n */\n private setupInstrumentation(options: IBrizzInitializeOptions): void {\n const registry = InstrumentationRegistry.getInstance();\n\n if (options.instrumentModules && Object.keys(options.instrumentModules).length > 0) {\n registry.setManualModules(options.instrumentModules);\n }\n }\n\n /**\n * Create and start NodeSDK if not disabled.\n * Only handles manual instrumentations now - auto instrumentations are loaded at import time.\n * @private\n */\n private createAndStartNodeSDK(\n options: IBrizzInitializeOptions,\n resolvedConfig: IResolvedBrizzConfig,\n ): void {\n if (options.disableNodeSdk) {\n logger.info('NodeSDK disabled - only telemetry modules initialized');\n return;\n }\n\n const registry = InstrumentationRegistry.getInstance();\n const manualInstrumentations = registry.getManualInstrumentations();\n\n this._sdk = new NodeSDK({\n spanProcessors: [getSpanProcessor()],\n metricReader: getMetricsReader(),\n resource: resourceFromAttributes({\n 'service.name': resolvedConfig.appName,\n }),\n instrumentations: manualInstrumentations,\n });\n this._sdk.start();\n\n if (manualInstrumentations.length > 0) {\n logger.info(`NodeSDK started with ${manualInstrumentations.length} manual instrumentations`);\n } else {\n logger.info('NodeSDK started - using auto-instrumentations loaded at import time');\n }\n }\n\n /**\n * Initialize telemetry modules.\n *\n * Sets up the tracing, metrics, and logging modules with their\n * respective exporters and processors.\n *\n * @param {IResolvedBrizzConfig} config - Resolved configuration\n * @private\n */\n private initializeModules(config: IResolvedBrizzConfig): void {\n logger.info('Initializing telemetry modules');\n\n // Initialize tracing module\n logger.debug('Initializing tracing module');\n const tracingModule = new TracingModule();\n tracingModule.setup(config);\n\n // Initialize metrics module\n logger.debug('Initializing metrics module');\n const metricsModule = new MetricsModule();\n metricsModule.setup(config);\n\n // Initialize logging module\n logger.debug('Initializing logging module');\n const loggingModule = new LoggingModule();\n loggingModule.setup(config);\n\n logger.info('All telemetry modules initialized successfully');\n }\n\n /**\n * Detect the current module system (ESM or CJS) using reliable indicators\n *\n * @returns {string} - 'ESM' or 'CJS'\n * @private\n */\n private detectModuleSystem(): string {\n const inCJS =\n typeof module !== 'undefined' &&\n typeof exports !== 'undefined' &&\n typeof require === 'function' &&\n typeof __filename === 'string' &&\n typeof __dirname === 'string' &&\n\n this === (typeof exports !== 'undefined' ? exports : undefined); // top-level `this` is exports in CJS, undefined in ESM\n\n return inCJS ? 'CJS' : 'ESM';\n }\n\n /**\n * Gracefully shutdown the Brizz SDK.\n *\n * This method stops all telemetry collection, flushes any pending data,\n * and releases resources. Should be called before application termination.\n *\n * @returns {Promise<void>} - Resolves when shutdown is complete\n * @throws {Error} - If shutdown fails\n *\n * @example\n * ```typescript\n * // Shutdown before app exit\n * await Brizz.shutdown();\n * ```\n */\n public async shutdown(): Promise<void> {\n if (!this._initialized) {\n logger.warn('Brizz SDK not initialized');\n return;\n }\n\n try {\n // Shutdown all modules\n await this.shutdownModules();\n await this._sdk?.shutdown();\n\n // Clear all references\n this._initialized = false;\n this._sdk = null;\n _Brizz.instance = null;\n\n logger.info('Brizz SDK shut down successfully');\n } catch (error) {\n // Suppress network errors during shutdown in tests\n if (error instanceof Error && error.message.includes('ENOTFOUND')) {\n logger.debug(`Network error during shutdown (expected in tests): ${error.message}`);\n } else {\n logger.error(`Failed to shutdown Brizz SDK: ${String(error)}`);\n throw error;\n }\n }\n }\n\n /**\n * Shutdown all telemetry modules.\n * @private\n */\n private async shutdownModules(): Promise<void> {\n logger.info('Shutting down telemetry modules');\n\n try {\n // Shutdown tracing module\n try {\n const tracingModule = TracingModule.getInstance();\n await tracingModule.shutdown();\n } catch {\n logger.debug('Tracing module already shut down or not initialized');\n }\n\n // Shutdown metrics module\n try {\n const metricsModule = MetricsModule.getInstance();\n metricsModule.shutdown();\n } catch {\n logger.debug('Metrics module already shut down or not initialized');\n }\n\n // Shutdown logging module\n try {\n const loggingModule = LoggingModule.getInstance();\n await loggingModule.shutdown();\n } catch {\n logger.debug('Logging module already shut down or not initialized');\n }\n\n logger.info('All telemetry modules shut down successfully');\n } catch (error) {\n logger.error('Error shutting down modules', { error });\n throw error;\n }\n }\n}\n\nexport const Brizz = new _Brizz();\n","import type { NodeSDK } from '@opentelemetry/sdk-node';\n\nimport type { IBrizzInitializeOptions } from '../index';\n\nimport { logger, DEFAULT_LOG_LEVEL, parseLogLevel, setLogLevel } from './logger';\nimport type { LogLevel } from './logger';\nimport type { IMaskingConfig } from './masking';\n\nexport interface IResolvedBrizzConfig extends Omit<IBrizzInitializeOptions, 'masking'> {\n appName: string;\n baseUrl: string;\n headers: Record<string, string>;\n disableBatch: boolean;\n apiKey?: string;\n logLevel: LogLevel;\n nodeSDK?: NodeSDK | null;\n masking?: IMaskingConfig;\n}\n\nexport function resolveConfig(options: IBrizzInitializeOptions): IResolvedBrizzConfig {\n // Resolve log level first so we can set it before other logging\n const envLogLevel = process.env['BRIZZ_LOG_LEVEL'] || options.logLevel?.toString() || DEFAULT_LOG_LEVEL.toString();\n let resolvedLogLevel: LogLevel;\n if (envLogLevel) {\n resolvedLogLevel = parseLogLevel(envLogLevel);\n } else if (typeof options.logLevel === 'string') {\n resolvedLogLevel = parseLogLevel(options.logLevel);\n } else {\n resolvedLogLevel = options.logLevel || DEFAULT_LOG_LEVEL;\n }\n\n setLogLevel(resolvedLogLevel);\n\n // Determine masking status for logging\n let maskingStatus: string;\n if (options.masking === true) {\n maskingStatus = 'enabled';\n } else if (options.masking === false) {\n maskingStatus = 'disabled';\n } else if (typeof options.masking === 'object') {\n maskingStatus = 'custom';\n } else {\n maskingStatus = 'default-disabled';\n }\n\n logger.debug('Starting configuration resolution', {\n appName: options.appName,\n baseUrl: options.baseUrl,\n hasApiKey: !!options.apiKey,\n disableBatch: options.disableBatch,\n logLevel: resolvedLogLevel,\n headersCount: Object.keys(options.headers || {}).length,\n masking: maskingStatus,\n });\n\n // Resolve masking configuration\n let resolvedMasking: IMaskingConfig | undefined;\n if (options.masking === true) {\n // Enable masking with all defaults\n resolvedMasking = {\n spanMasking: {},\n eventMasking: {},\n };\n } else if (options.masking && typeof options.masking === 'object') {\n // Use provided masking config\n resolvedMasking = options.masking;\n }\n // If options.masking is false or undefined, resolvedMasking remains undefined\n\n // Resolve all configuration with environment variables taking precedence\n const resolvedConfig: IResolvedBrizzConfig = {\n ...options,\n appName: process.env['BRIZZ_APP_NAME'] || options.appName || 'unknown-app',\n baseUrl: process.env['BRIZZ_BASE_URL'] || options.baseUrl || 'https://telemetry.brizz.dev',\n headers: { ...options.headers },\n apiKey: process.env['BRIZZ_API_KEY'] || options.apiKey,\n disableBatch: process.env['BRIZZ_DISABLE_BATCH'] === 'true' || !!options.disableBatch,\n logLevel: resolvedLogLevel,\n masking: resolvedMasking,\n };\n // Add Authorization header if API key is present\n if (resolvedConfig.apiKey) {\n resolvedConfig.headers['Authorization'] = `Bearer ${resolvedConfig.apiKey}`;\n }\n\n // Process additional environment variables\n if (process.env['BRIZZ_HEADERS']) {\n try {\n const envHeaders = JSON.parse(process.env['BRIZZ_HEADERS']) as Record<string, string>;\n Object.assign(resolvedConfig.headers, envHeaders);\n logger.debug('Added headers from environment variable', {\n headers: Object.keys(envHeaders),\n });\n } catch (error) {\n logger.error('Failed to parse BRIZZ_HEADERS environment variable', { error });\n throw new Error('Invalid JSON in BRIZZ_HEADERS environment variable');\n }\n }\n\n logger.debug('Configuration resolved with environment variables', {\n appName: resolvedConfig.appName,\n baseUrl: resolvedConfig.baseUrl,\n hasApiKey: !!resolvedConfig.apiKey,\n disableBatch: resolvedConfig.disableBatch,\n envOverrides: {\n hasEnvApiKey: !!process.env['BRIZZ_API_KEY'],\n hasEnvBaseUrl: !!process.env['BRIZZ_BASE_URL'],\n hasEnvBatch: !!process.env['BRIZZ_DISABLE_BATCH'],\n hasEnvHeaders: !!process.env['BRIZZ_HEADERS'],\n },\n });\n\n return resolvedConfig;\n}\n\n// Legacy function for backward compatibility\nexport function processEnvironmentConfig(options: IBrizzInitializeOptions): IResolvedBrizzConfig {\n return resolveConfig(options);\n}\n","import type { Instrumentation } from '@opentelemetry/instrumentation';\nimport { AnthropicInstrumentation } from '@traceloop/instrumentation-anthropic';\nimport { BedrockInstrumentation } from '@traceloop/instrumentation-bedrock';\nimport { ChromaDBInstrumentation } from '@traceloop/instrumentation-chromadb';\nimport { CohereInstrumentation } from '@traceloop/instrumentation-cohere';\nimport { LangChainInstrumentation } from '@traceloop/instrumentation-langchain';\nimport { LlamaIndexInstrumentation } from '@traceloop/instrumentation-llamaindex';\nimport { OpenAIInstrumentation } from '@traceloop/instrumentation-openai';\nimport { PineconeInstrumentation } from '@traceloop/instrumentation-pinecone';\nimport { QdrantInstrumentation } from '@traceloop/instrumentation-qdrant';\nimport { TogetherInstrumentation } from '@traceloop/instrumentation-together';\nimport { VertexAIInstrumentation } from '@traceloop/instrumentation-vertexai';\n\nimport { logger } from '../logger';\n\nimport { VercelAIInstrumentation } from './vercel-ai';\n\n\n/**\n * Module types for manual instrumentation (for Next.js/Webpack compatibility)\n */\nexport interface IInstrumentModules {\n openAI?: unknown;\n anthropic?: unknown;\n cohere?: unknown;\n google_vertexai?: unknown;\n google_aiplatform?: unknown;\n bedrock?: unknown;\n pinecone?: unknown;\n langchain?: {\n chains?: unknown;\n agents?: unknown;\n tools?: unknown;\n };\n llamaindex?: unknown;\n chromadb?: unknown;\n qdrant?: unknown;\n together?: unknown;\n vercelAI?: unknown;\n}\n\ninterface IInstrumentationConfig {\n class: new (config: { exceptionLogger: (error: Error) => void }) => Instrumentation;\n name: string;\n module?: unknown;\n}\n\nexport class InstrumentationRegistry {\n private static instance: InstrumentationRegistry;\n private manualModules: IInstrumentModules | null = null;\n\n public static getInstance(): InstrumentationRegistry {\n if (!InstrumentationRegistry.instance) {\n InstrumentationRegistry.instance = new InstrumentationRegistry();\n }\n return InstrumentationRegistry.instance;\n }\n\n /**\n * Set manual instrumentation modules for Next.js/Webpack environments\n */\n public setManualModules(modules: IInstrumentModules): void {\n this.manualModules = modules;\n logger.info('Manual instrumentation modules configured for Next.js/Webpack compatibility');\n }\n\n /**\n * Helper to load instrumentation with optional manual module\n */\n private loadInstrumentation<T extends Instrumentation>(\n InstrumentationClass: new (config: { exceptionLogger: (error: Error) => void }) => T,\n name: string,\n manualModule?: unknown,\n exceptionLogger?: (error: Error) => void,\n ): T | null {\n try {\n const inst = new InstrumentationClass({\n exceptionLogger:\n exceptionLogger ||\n ((error) => logger.error(`Exception in instrumentation: ${String(error)}`)),\n });\n if (manualModule) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (inst as any).manuallyInstrument(manualModule);\n logger.debug(`Manual instrumentation enabled for ${name}`);\n }\n return inst;\n } catch (error) {\n logger.error(`Failed to load ${name} instrumentation: ${String(error)}`);\n return null;\n }\n }\n\n /**\n * Get manual instrumentations only.\n * Auto-instrumentations are handled at import time.\n */\n public getManualInstrumentations(): Instrumentation[] {\n if (!this.manualModules || Object.keys(this.manualModules).length === 0) {\n logger.debug('No manual instrumentation modules configured');\n return [];\n }\n\n const instrumentations: Instrumentation[] = [];\n const exceptionLogger = (error: Error) => {\n logger.error(`Exception in manual instrumentation: ${String(error)}`);\n };\n\n this.loadManualInstrumentations(instrumentations, exceptionLogger);\n\n logger.info(`Loaded ${instrumentations.length} manual instrumentations`);\n return instrumentations;\n }\n\n /**\n * Load manual instrumentations only (with modules provided by user).\n * @private\n */\n private loadManualInstrumentations(\n instrumentations: Instrumentation[],\n exceptionLogger: (error: Error) => void,\n ): void {\n const instrumentationConfigs: IInstrumentationConfig[] = [\n { class: OpenAIInstrumentation, name: 'OpenAI', module: this.manualModules?.openAI },\n { class: AnthropicInstrumentation, name: 'Anthropic', module: this.manualModules?.anthropic },\n { class: CohereInstrumentation, name: 'Cohere', module: this.manualModules?.cohere },\n {\n class: VertexAIInstrumentation,\n name: 'Vertex AI',\n module: this.manualModules?.google_vertexai,\n },\n { class: BedrockInstrumentation, name: 'Bedrock', module: this.manualModules?.bedrock },\n { class: PineconeInstrumentation, name: 'Pinecone', module: this.manualModules?.pinecone },\n { class: LangChainInstrumentation, name: 'LangChain', module: this.manualModules?.langchain },\n {\n class: LlamaIndexInstrumentation,\n name: 'LlamaIndex',\n module: this.manualModules?.llamaindex,\n },\n { class: ChromaDBInstrumentation, name: 'ChromaDB', module: this.manualModules?.chromadb },\n { class: QdrantInstrumentation, name: 'Qdrant', module: this.manualModules?.qdrant },\n { class: TogetherInstrumentation, name: 'Together', module: this.manualModules?.together },\n { class: VercelAIInstrumentation, name: 'Vercel AI', module: this.manualModules?.vercelAI },\n ];\n\n // Only load instrumentations that have manual modules configured\n for (const config of instrumentationConfigs) {\n if (config.module) {\n const instrumentation = this.loadInstrumentation(\n config.class,\n config.name,\n config.module,\n exceptionLogger,\n );\n if (instrumentation) {\n instrumentations.push(instrumentation);\n }\n }\n }\n }\n}\n","import type { LogBody } from '@opentelemetry/api-logs';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';\nimport { resourceFromAttributes } from '@opentelemetry/resources';\nimport {\n LoggerProvider,\n type LogRecordExporter,\n type LogRecordProcessor,\n} from '@opentelemetry/sdk-logs';\n\nimport type { IResolvedBrizzConfig } from '../config';\nimport { logger } from '../logger';\n\nimport {\n BrizzBatchLogRecordProcessor,\n BrizzSimpleLogRecordProcessor,\n} from './processors/log-processor';\n\nexport class LoggingModule {\n private static instance: LoggingModule | null = null;\n private logExporter: LogRecordExporter | null = null;\n private logProcessor: LogRecordProcessor | null = null;\n private loggerProvider: LoggerProvider | null = null;\n\n static getInstance(): LoggingModule {\n if (!LoggingModule.instance) {\n throw new Error('Brizz must be initialized before accessing LoggingModule');\n }\n return LoggingModule.instance;\n }\n\n /**\n * Initialize the logging module with the provided configuration\n */\n setup(config: IResolvedBrizzConfig): void {\n logger.info('Setting up logging module');\n\n // Initialize exporter\n this.initLogExporter(config);\n\n // Initialize processor with masking support\n this.initLogProcessor(config);\n\n // Initialize logger provider\n this.initLoggerProvider(config);\n\n // Set as module instance for standalone functions\n LoggingModule.instance = this;\n\n logger.info('Logging module setup completed');\n }\n\n /**\n * Initialize the log exporter\n */\n private initLogExporter(config: IResolvedBrizzConfig): void {\n if (this.logExporter) {\n logger.debug('Log exporter already initialized, skipping re-initialization');\n return;\n }\n\n // Use custom log exporter if provided\n if (config.customLogExporter) {\n logger.debug('Using custom log exporter');\n this.logExporter = config.customLogExporter;\n logger.debug('Custom log exporter initialized successfully');\n return;\n }\n\n // Use default OTLP exporter\n const logsUrl = config.baseUrl.replace(/\\/$/, '') + '/v1/logs';\n logger.debug('Initializing default OTLP log exporter', { url: logsUrl });\n\n const headers = { ...config.headers };\n\n this.logExporter = new OTLPLogExporter({\n url: logsUrl,\n headers,\n });\n\n logger.debug('OTLP log exporter initialized successfully');\n }\n\n /**\n * Initialize the log processor with masking support\n */\n private initLogProcessor(config: IResolvedBrizzConfig): void {\n if (this.logProcessor) {\n logger.debug('Log processor already initialized, skipping re-initialization');\n return;\n }\n\n if (!this.logExporter) {\n throw new Error('Log exporter must be initialized before processor');\n }\n\n logger.debug('Initializing log processor', {\n disableBatch: config.disableBatch,\n hasMasking: !!config.masking?.eventMasking,\n });\n\n this.logProcessor = config.disableBatch\n ? new BrizzSimpleLogRecordProcessor(this.logExporter, config)\n : new BrizzBatchLogRecordProcessor(this.logExporter, config);\n\n logger.debug('Log processor initialized successfully');\n }\n\n /**\n * Initialize the logger provider\n */\n private initLoggerProvider(config: IResolvedBrizzConfig): void {\n if (this.loggerProvider) {\n logger.debug('Logger provider already initialized, skipping re-initialization');\n return;\n }\n\n if (!this.logProcessor) {\n throw new Error('Log processor must be initialized before logger provider');\n }\n\n logger.debug('Creating resource with service name', {\n serviceName: config.appName,\n });\n\n const resource = resourceFromAttributes({\n 'service.name': config.appName,\n });\n\n logger.debug('Creating logger provider with resource');\n this.loggerProvider = new LoggerProvider({\n resource,\n processors: [this.logProcessor],\n });\n\n logger.debug('Logger provider initialization completed');\n }\n\n /**\n * Emit a custom event to the telemetry pipeline\n */\n emitEvent(\n name: string,\n attributes?: Record<string, string | number | boolean>,\n body?: LogBody,\n severityNumber: SeverityNumber = SeverityNumber.INFO,\n ): void {\n logger.debug('Attempting to emit event', {\n name,\n hasAttributes: !!attributes,\n attributesCount: attributes ? Object.keys(attributes).length : 0,\n hasBody: !!body,\n severityNumber,\n });\n\n if (!this.loggerProvider) {\n logger.error('Cannot emit event: Logger provider not initialized');\n throw new Error('Logging module not initialized');\n }\n\n // Prepare log attributes with event name as required field\n const logAttributes: Record<string, string | number | boolean> = { 'event.name': name };\n if (attributes) {\n Object.assign(logAttributes, attributes);\n logger.debug('Combined log attributes', { attributes: Object.keys(logAttributes) });\n }\n\n // Get logger instance for event emission\n logger.debug('Getting logger instance for brizz_events');\n const eventLogger = this.loggerProvider.getLogger('brizz.events');\n\n // Emit the event\n logger.debug('Emitting log record with eventName', { eventName: name });\n try {\n eventLogger.emit({\n eventName: name,\n attributes: logAttributes,\n severityNumber: severityNumber,\n body: body,\n });\n logger.debug('Event successfully emitted', { eventName: name });\n } catch (error) {\n // Log detailed error information for debugging\n logger.error(`Failed to emit event '${name}'`, { error, eventName: name });\n logger.error('Log record that failed', {\n eventName: name,\n hasAttributes: logAttributes,\n severityNumber: severityNumber,\n hasBody: body,\n });\n throw error instanceof Error ? error : new Error(String(error));\n }\n }\n\n /**\n * Check if the module is initialized\n */\n isInitialized(): boolean {\n return this.loggerProvider !== null;\n }\n\n /**\n * Get the logger provider\n */\n getLoggerProvider(): LoggerProvider | null {\n return this.loggerProvider;\n }\n\n /**\n * Shutdown the logging module\n */\n async shutdown(): Promise<void> {\n logger.debug('Shutting down logging module');\n\n if (this.loggerProvider) {\n await this.loggerProvider.shutdown();\n this.loggerProvider = null;\n }\n\n this.logProcessor = null;\n this.logExporter = null;\n\n // Clear module instance\n if (LoggingModule.instance === this) {\n LoggingModule.instance = null;\n }\n\n logger.debug('Logging module shutdown completed');\n }\n}\n\n/**\n * Emit a custom event to the telemetry pipeline.\n * @throws {Error} - If SDK is not initialized\n */\nexport function emitEvent(\n name: string,\n attributes?: Record<string, string | number | boolean>,\n body?: LogBody,\n severityNumber: SeverityNumber = SeverityNumber.INFO,\n): void {\n return LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);\n}\n","import { context } from '@opentelemetry/api';\nimport type { AnyValue, LogAttributes } from '@opentelemetry/api-logs';\nimport type { LogRecordExporter, SdkLogRecord } from '@opentelemetry/sdk-logs';\nimport { BatchLogRecordProcessor, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs';\n\nimport type { IResolvedBrizzConfig } from '../../config';\nimport { logger } from '../../logger';\nimport { DEFAULT_PII_PATTERNS } from '../../masking/patterns';\nimport type { IAttributesMaskingRule, ILogMaskingConfig, MaskableValue } from '../../masking/types';\nimport { maskAttributes, maskValue } from '../../masking/utils';\nimport { BRIZZ, PROPERTIES_CONTEXT_KEY } from '../../semantic-conventions';\n\nexport const DEFAULT_LOG_MASKING_RULES: IAttributesMaskingRule[] = [\n {\n mode: 'partial',\n attributePattern: 'event.name',\n patterns: DEFAULT_PII_PATTERNS,\n },\n];\n\nexport class BrizzSimpleLogRecordProcessor extends SimpleLogRecordProcessor {\n public readonly config: IResolvedBrizzConfig;\n\n constructor(exporter: LogRecordExporter, config: IResolvedBrizzConfig) {\n super(exporter);\n this.config = config;\n }\n\n override onEmit(logRecord: SdkLogRecord): void {\n const maskingConfig = this.config.masking?.eventMasking;\n if (maskingConfig) {\n maskLog(logRecord, maskingConfig);\n }\n const associationProperties = context.active().getValue(PROPERTIES_CONTEXT_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n logRecord.setAttribute(`${BRIZZ}.${key}`, value as AnyValue);\n }\n }\n super.onEmit(logRecord);\n }\n}\n\nexport class BrizzBatchLogRecordProcessor extends BatchLogRecordProcessor {\n public readonly config: IResolvedBrizzConfig;\n\n constructor(exporter: LogRecordExporter, config: IResolvedBrizzConfig) {\n super(exporter);\n this.config = config;\n }\n\n override onEmit(logRecord: SdkLogRecord): void {\n const maskingConfig = this.config.masking?.eventMasking;\n if (maskingConfig) {\n maskLog(logRecord, maskingConfig);\n }\n const associationProperties = context.active().getValue(PROPERTIES_CONTEXT_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n logRecord.setAttribute(`${BRIZZ}.${key}`, value as AnyValue);\n }\n }\n super.onEmit(logRecord);\n }\n}\n\nexport function maskLog(logRecord: SdkLogRecord, config: ILogMaskingConfig): SdkLogRecord {\n if (!logRecord.attributes) {\n return logRecord;\n }\n\n let rules = config.rules || [];\n if (!config.disableDefaultRules) {\n rules = [...DEFAULT_LOG_MASKING_RULES, ...rules];\n }\n\n try {\n if (logRecord.attributes && Object.keys(logRecord.attributes).length > 0) {\n const attributesRecord: Record<string, MaskableValue> = {};\n\n for (const [key, value] of Object.entries(logRecord.attributes)) {\n attributesRecord[key] = value as MaskableValue;\n }\n\n const maskedAttributes = maskAttributes(attributesRecord, rules);\n if (maskedAttributes) {\n // Clear existing attributes and set masked ones\n const newAttributes: LogAttributes = {};\n for (const [key, value] of Object.entries(maskedAttributes)) {\n newAttributes[key] = value as AnyValue;\n }\n logRecord.setAttributes(newAttributes);\n }\n }\n\n if (config.maskBody && logRecord.body !== undefined && logRecord.body !== null) {\n let maskedBody: unknown = logRecord.body;\n for (const rule of rules) {\n maskedBody = maskValue(maskedBody, rule);\n }\n logRecord.setBody(maskedBody as AnyValue);\n }\n\n return logRecord;\n } catch (error) {\n logger.error('Error masking log record:', error);\n return logRecord;\n }\n}\n","/**\n * Default PII patterns for data masking.\n *\n * This module contains 100+ built-in patterns for detecting and masking\n * common types of personally identifiable information (PII) and sensitive data.\n * Patterns are organized by category and mirror the Python SDK implementation.\n */\n\nimport type { IPatternEntry } from './types';\n\n/**\n * All built-in PII patterns combined - mirrors Python SDK patterns.py\n */\nexport const DEFAULT_PII_PATTERNS: IPatternEntry[] = [\n // Email addresses\n {\n name: 'email_addresses',\n pattern: String.raw`\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b`,\n },\n // Phone numbers (US format)\n {\n name: 'us_phone_numbers',\n pattern: String.raw`(?:^|[\\s])(?:\\+?1[-.\\s]*)?(?:\\([0-9]{3}\\)\\s?[0-9]{3}[-.\\s]?[0-9]{4}|[0-9]{3}[-.\\s]?[0-9]{3}[-.\\s]?[0-9]{4}|[0-9]{10})(?=[\\s]|$)`,\n },\n // Social Security Numbers\n {\n name: 'ssn',\n pattern: String.raw`\\b(?!000|666|9\\d{2})\\d{3}[-\\s]?(?!00)\\d{2}[-\\s]?(?!0000)\\d{4}\\b`,\n },\n // Credit card numbers\n {\n name: 'credit_cards',\n pattern: String.raw`\\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\\\\d{3})\\\\d{11})\\b`,\n },\n {\n name: 'credit_cards_with_separators',\n pattern: String.raw`\\b(?:4\\\\d{3}|5[1-5]\\\\d{2}|3[47]\\\\d{2})[-\\s]?\\\\d{4}[-\\s]?\\\\d{4}[-\\s]?\\\\d{4}\\b`,\n },\n // IP addresses (IPv4)\n {\n name: 'ipv4_addresses',\n pattern: String.raw`\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?!\\.[0-9])\\b`,\n },\n // API keys/tokens\n {\n name: 'generic_api_keys',\n pattern: String.raw`\\b(?:[Aa][Pp][Ii][_-]?[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt])[_-]?[=:]?\\s*[\"']?(?:[a-zA-Z0-9\\-_.]{20,})[\"']?\\b`,\n },\n {\n name: 'openai_keys',\n pattern: String.raw`\\bsk[-_][a-zA-Z0-9]{20,}\\b`,\n },\n {\n name: 'base64_secrets',\n pattern: String.raw`\\b[A-Za-z0-9+/]{64,}={0,2}\\b`,\n },\n // AWS Keys\n {\n name: 'aws_access_keys',\n pattern: String.raw`\\b(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\\b`,\n },\n {\n name: 'aws_secret_keys',\n pattern: String.raw`\\b[A-Za-z0-9/+=]*[A-Z][A-Za-z0-9/+=]*[a-z][A-Za-z0-9/+=]*[/+=][A-Za-z0-9/+=]{30,}\\b`,\n },\n // GitHub tokens\n {\n name: 'github_tokens',\n pattern: String.raw`\\bghp_[a-zA-Z0-9]{36}\\b`,\n },\n // Slack tokens\n {\n name: 'slack_tokens',\n pattern: String.raw`\\bxox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24,34}\\b`,\n },\n // Stripe keys\n {\n name: 'stripe_keys',\n pattern: String.raw`\\b(?:sk|pk)_(?:test|live)_[a-zA-Z0-9]{24,}\\b`,\n },\n // JWT tokens\n {\n name: 'jwt_tokens',\n pattern: String.raw`\\beyJ[A-Za-z0-9_-]{2,}\\\\.[A-Za-z0-9_-]{2,}\\\\.[A-Za-z0-9_-]{2,}\\b`,\n },\n // MAC addresses\n {\n name: 'mac_addresses',\n pattern: String.raw`\\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\\b`,\n },\n // IPv6 addresses\n {\n name: 'ipv6_addresses',\n pattern: String.raw`\\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\b`,\n },\n // Medical records\n {\n name: 'medical_record_numbers',\n pattern: String.raw`\\b(?:[Mm][Rr][Nn])[-\\s]?\\d{6,10}\\b`,\n },\n // Bitcoin addresses\n {\n name: 'bitcoin_addresses',\n pattern: String.raw`\\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\\b`,\n },\n // Ethereum addresses\n {\n name: 'ethereum_addresses',\n pattern: String.raw`\\b0x[a-fA-F0-9]{40}(?![a-fA-F0-9])\\b`,\n },\n // UUIDs\n {\n name: 'uuids',\n pattern: String.raw`\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(?![0-9a-fA-F-])\\b`,\n },\n // Database connection strings\n {\n name: 'database_connections',\n pattern: String.raw`\\b(?:[Mm][Oo][Nn][Gg][Oo][Dd][Bb]|[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Mm][Yy][Ss][Qq][Ll]|[Rr][Ee][Dd][Ii][Ss]|[Mm][Ss][Ss][Qq][Ll]|[Oo][Rr][Aa][Cc][Ll][Ee]):\\\\/\\\\/[^\\\\s]+\\b`,\n },\n // Private keys\n {\n name: 'rsa_private_keys',\n pattern: '-----BEGIN (?:RSA )?PRIVATE KEY-----',\n },\n {\n name: 'pgp_private_keys',\n pattern: '-----BEGIN PGP PRIVATE KEY BLOCK-----',\n },\n {\n name: 'certificates',\n pattern: '-----BEGIN CERTIFICATE-----',\n },\n // Date of birth patterns\n {\n name: 'date_of_birth_us',\n pattern: String.raw`\\b(?:0[1-9]|1[0-2])[-/](?:0[1-9]|[12]\\\\d|3[01])[-/](?:19|20)\\\\d{2}\\b`,\n },\n {\n name: 'date_of_birth_iso',\n pattern: String.raw`\\b(?:19|20)\\\\d{2}[-/](?:0[1-9]|1[0-2])[-/](?:0[1-9]|[12]\\\\d|3[01])\\b`,\n },\n // US Identification Numbers\n {\n name: 'us_passport_numbers',\n pattern: String.raw`\\b[A-Z]?\\\\d{6,9}\\b`,\n },\n {\n name: 'drivers_license',\n pattern: String.raw`\\b[A-Z]{1,2}\\\\d{3,8}[-\\s]?\\\\d{2,5}[-\\s]?\\\\d{2,5}[-\\s]?\\\\d{1,5}[-\\s]?\\\\d?\\b`,\n },\n {\n name: 'bank_account_numbers',\n pattern: String.raw`\\b\\\\d{10,17}\\b`,\n },\n {\n name: 'aba_routing_numbers',\n pattern: String.raw`\\b((0[0-9])|(1[0-2])|(2[1-9])|(3[0-2])|(6[1-9])|(7[0-2])|80)([0-9]{7})\\b`,\n },\n {\n name: 'health_insurance_numbers',\n pattern: String.raw`\\b\\\\d{10}[A-Z]\\b`,\n },\n {\n name: 'employee_ids',\n pattern: String.raw`\\b(?:[Ee][Mm][Pp]|[Ee][Mm][Pp][Ll][Oo][Yy][Ee][Ee]|[Ee])[-\\s]?\\\\d{5,8}\\b`,\n },\n {\n name: 'tax_ein',\n pattern: String.raw`\\b\\\\d{2}-\\\\d{7}\\b`,\n },\n {\n name: 'medicare_beneficiary_id',\n pattern: String.raw`\\b[1-9][A-Z][A-Z0-9]\\\\d-[A-Z][A-Z0-9]\\\\d-[A-Z][A-Z0-9]\\\\d{2}\\b`,\n },\n {\n name: 'national_provider_id',\n pattern: String.raw`\\b1\\\\d{9}\\b`,\n },\n {\n name: 'dea_numbers',\n pattern: String.raw`\\b[A-Z]{2}\\\\d{7}\\b`,\n },\n {\n name: 'itin',\n pattern: String.raw`\\b9\\\\d{2}(?:[ \\\\-]?)[7,8]\\\\d(?:[ \\\\-]?)\\\\d{4}\\b`,\n },\n // Vehicle and Location\n {\n name: 'vin_numbers',\n pattern: String.raw`\\b[A-HJ-NPR-Z0-9]{17}\\b`,\n },\n {\n name: 'coordinates',\n pattern: String.raw`\\b[-+]?(?:[0-8]?\\\\d(?:\\\\.\\\\d+)?|90(?:\\\\.0+)?),\\\\s*[-+]?(?:1[0-7]\\\\d(?:\\\\.\\\\d+)?|180(?:\\\\.0+)?|[0-9]?\\\\d(?:\\\\.\\\\d+)?)\\b`,\n },\n {\n name: 'us_license_plates',\n pattern: String.raw`\\b[A-Z]{1,3}[-\\s]\\\\d{1,4}[A-Z]?\\b|\\b\\\\d{1,2}[A-Z]{1,3}\\\\d{1,4}\\b`,\n },\n {\n name: 'us_zip_codes',\n pattern: String.raw`\\b(\\\\d{5}-\\\\d{4}|\\\\d{5})\\b`,\n },\n {\n name: 'us_street_addresses',\n pattern: String.raw`\\b\\\\d{1,8}\\b[\\\\s\\\\S]{10,100}?\\b(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NC|ND|NE|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)\\b\\\\s\\\\d{5}\\b`,\n },\n // International Banking\n {\n name: 'iban',\n pattern: String.raw`\\b[A-Z]{2}\\d{2}[A-Z0-9]{4}\\d{7}([A-Z0-9]?){0,16}\\b`,\n },\n {\n name: 'swift_bic',\n pattern: String.raw`\\b[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?\\b`,\n },\n // Additional API Keys and Tokens\n {\n name: 'google_oauth',\n pattern: String.raw`\\bya29\\\\.[a-zA-Z0-9_-]{60,}\\b`,\n },\n {\n name: 'firebase_tokens',\n pattern: String.raw`\\bAAAA[A-Za-z0-9_-]{100,}\\b`,\n },\n {\n name: 'google_app_ids',\n pattern: String.raw`\\b[0-9]+-\\w+\\.apps\\.googleusercontent\\.com\\b`,\n },\n {\n name: 'facebook_secrets',\n pattern: String.raw`\\b(facebook_secret|FACEBOOK_SECRET|facebook_app_secret|FACEBOOK_APP_SECRET)[a-z_ =\\\\s\"'\\\\:]{0,5}[^a-zA-Z0-9][a-f0-9]{32}[^a-zA-Z0-9]`,\n },\n {\n name: 'github_keys',\n pattern: String.raw`\\b(GITHUB_SECRET|GITHUB_KEY|github_secret|github_key|github_token|GITHUB_TOKEN|github_api_key|GITHUB_API_KEY)[a-z_ =\\\\s\\\"'\\\\:]{0,10}[^a-zA-Z0-9][a-zA-Z0-9]{40}[^a-zA-Z0-9]`,\n },\n {\n name: 'heroku_keys',\n pattern: String.raw`\\b(heroku_api_key|HEROKU_API_KEY|heroku_secret|HEROKU_SECRET)[a-z_ =\\\\s\\\"'\\\\:]{0,10}[^a-zA-Z0-9-]\\\\w{8}(?:-\\\\w{4}){3}-\\\\w{12}[^a-zA-Z0-9\\\\-]`,\n },\n {\n name: 'slack_api_keys',\n pattern: String.raw`\\b(slack_api_key|SLACK_API_KEY|slack_key|SLACK_KEY)[a-z_ =\\\\s\\\"'\\\\:]{0,10}[^a-f0-9][a-f0-9]{32}[^a-f0-9]`,\n },\n {\n name: 'slack_api_tokens',\n pattern: String.raw`\\b(xox[pb](?:-[a-zA-Z0-9]+){4,})\\b`,\n },\n // Extended Private Keys and Certificates\n {\n name: 'dsa_private_keys',\n pattern: String.raw`-----BEGIN DSA PRIVATE KEY-----(?:[a-zA-Z0-9\\+\\=\\/\"']|\\s)+?-----END DSA PRIVATE KEY-----`,\n },\n {\n name: 'ec_private_keys',\n pattern: String.raw`-----BEGIN (?:EC|ECDSA) PRIVATE KEY-----(?:[a-zA-Z0-9\\+\\=\\/\"']|\\s)+?-----END (?:EC|ECDSA) PRIVATE KEY-----`,\n },\n {\n name: 'encrypted_private_keys',\n pattern: String.raw`-----BEGIN ENCRYPTED PRIVATE KEY-----(?:.|\\s)+?-----END ENCRYPTED PRIVATE KEY-----`,\n },\n {\n name: 'ssl_certificates',\n pattern: String.raw`-----BEGIN CERTIFICATE-----(?:.|\\n)+?\\s-----END CERTIFICATE-----`,\n },\n {\n name: 'ssh_dss_public',\n pattern: String.raw`\\bssh-dss [0-9A-Za-z+/]+[=]{2}\\b`,\n },\n {\n name: 'ssh_rsa_public',\n pattern: String.raw`\\bssh-rsa AAAA[0-9A-Za-z+/]+[=]{0,3} [^@]+@[^@]+\\b`,\n },\n {\n name: 'putty_ssh_keys',\n pattern: String.raw`PuTTY-User-Key-File-2: ssh-(?:rsa|dss)\\s*Encryption: none(?:.|\\s?)*?Private-MAC:`,\n },\n // International Phone Numbers\n {\n name: 'france_phone_numbers',\n pattern: String.raw`\\b([0O]?[1lI][1lI])?[3E][3E][0O]?[\\\\dOIlZEASB]{9}\\b`,\n },\n {\n name: 'german_phone_numbers',\n pattern: String.raw`\\b[\\d\\w]\\d{2}[\\d\\w]{6}\\d[\\d\\w]\\b`,\n },\n {\n name: 'uk_phone_numbers',\n pattern: String.raw`\\b([0O]?[1lI][1lI])?[4A][4A][\\\\dOIlZEASB]{10,11}\\b`,\n },\n // International IDs\n {\n name: 'uk_drivers_license',\n pattern: String.raw`\\b[A-Z]{5}\\d{6}[A-Z]{2}\\d{1}[A-Z]{2}\\b`,\n },\n {\n name: 'uk_passport',\n pattern: String.raw`\\b\\\\d{10}GB[RP]\\\\d{7}[UMF]{1}\\\\d{9}\\b`,\n },\n {\n name: 'argentina_dni',\n pattern: String.raw`\\b\\\\d{2}\\\\.\\\\d{3}\\\\.\\\\d{3}\\b`,\n },\n {\n name: 'australia_tfn',\n pattern: String.raw`\\b[Tt][Ff][Nn](:|:\\\\s|\\\\s|)(\\\\d{8,9})\\b`,\n },\n {\n name: 'canada_passport',\n pattern: String.raw`\\b[\\\\w]{2}[\\\\d]{6}\\b`,\n },\n {\n name: 'croatia_vat',\n pattern: String.raw`\\bHR\\\\d{11}\\b`,\n },\n {\n name: 'czech_vat',\n pattern: String.raw`\\bCZ\\\\d{8,10}\\b`,\n },\n {\n name: 'denmark_personal_id',\n pattern: String.raw`\\b(?:\\\\d{10}|\\\\d{6}[-\\\\s]\\\\d{4})\\b`,\n },\n {\n name: 'france_national_id',\n pattern: String.raw`\\b\\\\d{12}\\b`,\n },\n {\n name: 'france_ssn',\n pattern: String.raw`\\b(?:\\\\d{13}|\\\\d{13}\\\\s\\\\d{2})\\b`,\n },\n {\n name: 'france_passport',\n pattern: String.raw`\\b\\\\d{2}11\\\\d{5}\\b`,\n },\n {\n name: 'california_drivers_license',\n pattern: String.raw`\\b[A-Z]{1}\\\\d{7}\\b`,\n },\n // Medical and Healthcare\n {\n name: 'hipaa_ndc',\n pattern: String.raw`\\b\\\\d{4,5}-\\\\d{3,4}-\\\\d{1,2}\\b`,\n },\n // Security and Network\n {\n name: 'cve_numbers',\n pattern: String.raw`\\b[Cc][Vv][Ee]-\\\\d{4}-\\\\d{4,7}\\b`,\n },\n {\n name: 'microsoft_oauth',\n pattern: String.raw`https://login\\.microsoftonline\\.com/common/oauth2/v2\\.0/token|https://login\\.windows\\.net/common/oauth2/token`,\n },\n {\n name: 'postgres_connections',\n pattern: String.raw`\\b(?:[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Pp][Gg][Ss][Qq][Ll])\\\\:\\\\/\\\\/`,\n },\n {\n name: 'box_links',\n pattern: String.raw`https://app\\.box\\.com/[s|l]/\\S+`,\n },\n {\n name: 'dropbox_links',\n pattern: String.raw`https://www\\.dropbox\\.com/(?:s|l)/\\S+`,\n },\n // Credit Card Variants\n {\n name: 'amex_cards',\n pattern: String.raw`\\b3[47][0-9]{13}\\b`,\n },\n {\n name: 'visa_cards',\n pattern: String.raw`\\b4[0-9]{12}(?:[0-9]{3})?\\b`,\n },\n {\n name: 'discover_cards',\n pattern: String.raw`\\b65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}\\b`,\n },\n {\n name: 'enhanced_credit_cards',\n pattern: String.raw`\\b((4\\\\d{3}|5[1-5]\\\\d{2}|2\\\\d{3}|3[47]\\\\d{1,2})[\\\\s\\\\-]?\\\\d{4,6}[\\\\s\\\\-]?\\\\d{4,6}?([\\\\s\\\\-]\\\\d{3,4})?(\\\\d{3})?)\\b`,\n },\n // Bank Routing Numbers (US specific)\n {\n name: 'bbva_routing_ca',\n pattern: String.raw`\\\\b321170538\\\\b`,\n },\n {\n name: 'boa_routing_ca',\n pattern: String.raw`\\\\b(?:121|026)00(?:0|9)(?:358|593)\\\\b`,\n },\n {\n name: 'chase_routing_ca',\n pattern: String.raw`\\\\b322271627\\\\b`,\n },\n {\n name: 'citibank_routing_ca',\n pattern: String.raw`\\\\b32(?:11|22)71(?:18|72)4\\\\b`,\n },\n {\n name: 'usbank_routing_ca',\n pattern: String.raw`\\\\b12(?:1122676|2235821)\\\\b`,\n },\n {\n name: 'united_bank_routing_ca',\n pattern: String.raw`\\\\b122243350\\\\b`,\n },\n {\n name: 'wells_fargo_routing_ca',\n pattern: String.raw`\\\\b121042882\\\\b`,\n },\n // Unrealistic alphanumeric identifiers\n {\n name: 'generic_non_usual',\n pattern: String.raw`(?:^|\\s)(?=[A-Za-z0-9_\\)\\*\\=@]*[A-Za-z])(?=[A-Za-z0-9_\\)\\*\\=@]*[0-9])([A-Za-z0-9_\\)\\*\\=@]{5,})(?=\\s|$)`,\n },\n];\n","/**\n * Masking utilities for pattern compilation and value masking.\n *\n * This module provides the core functionality for detecting and masking PII\n * in various data types. It implements the same logic as the Python SDK\n * with optimized regex compilation and efficient masking operations.\n */\n\nimport { logger } from '../logger';\n\nimport type {\n IAttributesMaskingRule,\n IEventMaskingRule,\n IPatternBasedMaskingRule,\n IPatternEntry,\n} from './types';\n\nfunction isValidPatternName(name: string): boolean {\n return /^[a-zA-Z0-9_]+$/.test(name);\n}\n\n/**\n * Detects potentially dangerous ReDoS patterns\n */\nfunction isLikelyReDoSPattern(pattern: string): boolean {\n const dangerousPatterns = [\n // Nested quantifiers like (a+)+, (a*)+, (a+)*\n /\\([^)]*[+*]\\)[+*]/,\n // Alternation with overlapping groups like (a|a)*\n /\\([^)]*\\|[^)]*\\)[+*]/,\n // Complex backtracking patterns - but more specific\n /\\([^)]*[+*][^)]*[+*][^)]*\\)[+*]/,\n ];\n\n return dangerousPatterns.some((dangerous) => dangerous.test(pattern));\n}\n\nfunction getGroupedPattern(patternEntry: IPatternEntry): string {\n let name = patternEntry.name;\n if (!name || name === '') {\n name = `pattern_${Math.random().toString(16).slice(2)}`;\n }\n if (!isValidPatternName(name)) {\n throw new Error(\n `Pattern name '${name}' must only contain alphanumeric characters and underscores`,\n );\n }\n\n // Check for potentially dangerous ReDoS patterns\n if (isLikelyReDoSPattern(patternEntry.pattern)) {\n throw new Error(`Potentially dangerous ReDoS pattern detected: '${patternEntry.pattern}'`);\n }\n\n // Validate the pattern by attempting to create a RegExp\n try {\n new RegExp(patternEntry.pattern);\n } catch (error) {\n throw new Error(`Invalid regex pattern '${patternEntry.pattern}': ${String(error)}`);\n }\n\n return `(?<${name}>${patternEntry.pattern})`;\n}\n\nfunction isIPatternEntry(obj: unknown): obj is IPatternEntry {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n typeof (obj as IPatternEntry).pattern === 'string' &&\n ((obj as IPatternEntry).name === undefined || typeof (obj as IPatternEntry).name === 'string')\n );\n}\n\nfunction isIEventMaskingRule(obj: unknown): obj is IEventMaskingRule {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n typeof (obj as IEventMaskingRule).mode === 'string' &&\n Array.isArray((obj as IEventMaskingRule).patterns) &&\n (obj as IEventMaskingRule).patterns.every(\n (p: unknown) => isIPatternEntry(p) || typeof p === 'string',\n ) &&\n ((obj as IEventMaskingRule).attributePattern === undefined ||\n typeof (obj as IEventMaskingRule).attributePattern === 'string')\n );\n}\n\nfunction convertPatternsToPatternEntries(\n patterns: readonly (IPatternEntry | string)[],\n): IPatternEntry[] {\n const patternEntries: IPatternEntry[] = [];\n for (const pattern of patterns) {\n if (typeof pattern === 'string') {\n // Convert string to PatternEntry with empty name\n patternEntries.push({ pattern, name: '' });\n } else if (isIPatternEntry(pattern)) {\n // Already a PatternEntry, use as is\n patternEntries.push(pattern);\n } else {\n throw new Error('Patterns must be either strings or PatternEntry instances');\n }\n }\n return patternEntries;\n}\n\n/**\n * Compile a list of pattern entries into a single regex pattern.\n * Matches Python's _compile_pattern_entries function.\n */\nfunction compilePatternEntries(patternEntries: readonly IPatternEntry[]): RegExp | null {\n const patternGroups: string[] = [];\n for (const patternEntry of patternEntries) {\n try {\n patternGroups.push(getGroupedPattern(patternEntry));\n } catch (error) {\n logger.warn(`Invalid pattern '${patternEntry.name}': ${patternEntry.pattern}`, error);\n continue; // Skip invalid patterns\n }\n }\n\n if (patternGroups.length === 0) {\n return null; // No valid patterns\n }\n\n try {\n return new RegExp(patternGroups.join('|'));\n } catch (error) {\n logger.warn('Failed to compile pattern entries into regex', error);\n return null;\n }\n}\n\nfunction getCompiledAttributeNamePattern(rule: IAttributesMaskingRule): RegExp {\n if (!rule.attributePattern) {\n logger.debug('No attribute pattern provided, using default .*');\n return /.*/; // Default to match all attributes\n }\n let compiledPatternString = rule.attributePattern;\n if (isIEventMaskingRule(rule) && rule.eventNamePattern) {\n // If this is an event masking rule, append the event name pattern if it exists\n compiledPatternString = `(${compiledPatternString})|(${rule.eventNamePattern})`;\n }\n return new RegExp(compiledPatternString);\n}\n\n/**\n * Check if regex execution should continue based on timeout and iteration limits\n */\nfunction shouldContinueExecution(\n startTime: number,\n iterations: number,\n timeoutMs: number,\n): boolean {\n if (Date.now() - startTime > timeoutMs) {\n logger.warn('Regex execution timed out - potential ReDoS pattern detected');\n return false;\n }\n\n const maxIterations = 1000;\n if (iterations > maxIterations) {\n logger.warn('Regex execution exceeded maximum iterations - potential ReDoS pattern detected');\n return false;\n }\n\n return true;\n}\n\n/**\n * Create a global version of the regex pattern\n */\nfunction createGlobalPattern(pattern: RegExp): RegExp {\n return new RegExp(\n pattern.source,\n pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g',\n );\n}\n\n/**\n * Executes regex with timeout protection to prevent ReDoS attacks\n */\nfunction executeRegexWithTimeout(\n pattern: RegExp,\n value: string,\n timeoutMs: number = 100,\n): RegExpExecArray[] {\n const matches: RegExpExecArray[] = [];\n const globalPattern = createGlobalPattern(pattern);\n const startTime = Date.now();\n let match: RegExpExecArray | null;\n let iterations = 0;\n\n while ((match = globalPattern.exec(value)) !== null) {\n if (!shouldContinueExecution(startTime, ++iterations, timeoutMs)) {\n break;\n }\n\n matches.push(match);\n\n if (match[0].length === 0) {\n globalPattern.lastIndex = match.index + 1;\n }\n }\n\n return matches;\n}\n\n/**\n * Masks a string value based on the pattern, matching Python implementation.\n */\nexport function maskStringByPattern(\n value: string,\n pattern: RegExp,\n mode: 'partial' | 'full' = 'full',\n): string {\n // Use timeout-protected regex execution to prevent ReDoS\n const matches: Array<{\n start: number;\n end: number;\n text: string;\n groups: RegExpExecArray['groups'];\n }> = [];\n\n try {\n const regexMatches = executeRegexWithTimeout(pattern, value);\n\n for (const match of regexMatches) {\n matches.push({\n start: match.index,\n end: match.index + match[0].length,\n text: match[0],\n groups: match.groups,\n });\n }\n } catch (error) {\n logger.warn('Regex execution failed, skipping masking', error);\n return value;\n }\n\n // Process matches in reverse order to maintain correct indices\n for (const matchInfo of matches.reverse()) {\n let patternName = 'unknown';\n if (matchInfo.groups) {\n // Find the first defined group name\n for (const [groupName, groupValue] of Object.entries(matchInfo.groups)) {\n if (groupValue !== undefined) {\n // Remove any counter suffix for logging (matches Python's logic)\n if (groupName.includes('_') && /\\d$/.test(groupName)) {\n const parts = groupName.split('_');\n patternName = parts[0] || groupName;\n } else {\n patternName = groupName;\n }\n break;\n }\n }\n }\n\n logger.info(`Masking detected: pattern '${patternName}' found match in value`);\n\n // Apply masking based on mode\n const masked = mode === 'partial' ? matchInfo.text[0] + '*****' : '*****';\n\n // Replace the matched portion\n value = value.slice(0, matchInfo.start) + masked + value.slice(matchInfo.end);\n }\n\n return value;\n}\n\n/**\n * Masks a string value based on the rule, matching Python implementation.\n */\nexport function maskStringByPatternBasedRule(\n value: string,\n rule: IPatternBasedMaskingRule,\n): string {\n const patternEntries = convertPatternsToPatternEntries(rule.patterns);\n if (patternEntries.length === 0) {\n logger.warn('No patterns provided for masking rule, returning original value');\n return value; // No patterns means no masking\n }\n const mode = rule.mode;\n if (!patternEntries || patternEntries.length === 0) {\n // No patterns means mask entire value\n return mode === 'partial' && value ? value[0] + '*****' : '*****';\n }\n\n // Create the mega pattern\n const compiledPatterns = compilePatternEntries(patternEntries);\n if (!compiledPatterns) {\n return value;\n }\n\n return maskStringByPattern(value, compiledPatterns, mode);\n}\n\n/**\n * Masks a value based on the rule, matching Python implementation.\n */\nexport function maskValue(value: unknown, rule: IPatternBasedMaskingRule): unknown {\n if (typeof value === 'string') {\n return maskStringByPatternBasedRule(value, rule);\n } else if (typeof value === 'boolean' || typeof value === 'number') {\n return maskStringByPatternBasedRule(String(value), rule);\n } else if (Array.isArray(value)) {\n return value.map((v) => maskStringByPatternBasedRule(String(v), rule));\n } else if (value !== null && typeof value === 'object') {\n // If the value is a dictionary, mask each value recursively\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n result[k] = maskValue(v, rule);\n }\n return result;\n } else {\n throw new Error(`Unsupported value type for masking: ${typeof value}`);\n }\n}\n\n/**\n * Masks sensitive data in attributes based on masking rules, matching Python implementation.\n */\nexport function maskAttributes(\n attributes: Record<string, unknown>,\n rules: readonly IAttributesMaskingRule[],\n outputOriginalValue = false,\n): Record<string, unknown> {\n if (!attributes || Object.keys(attributes).length === 0) {\n return {};\n }\n\n // Create a copy to avoid modifying the original\n const maskedAttributes = { ...attributes };\n\n for (const rule of rules) {\n const compiledAttributeNamePattern = getCompiledAttributeNamePattern(rule);\n const attributesToMask: string[] = compiledAttributeNamePattern\n ? Object.keys(maskedAttributes).filter((attr) => compiledAttributeNamePattern.test(attr))\n : Object.keys(maskedAttributes);\n\n for (const attribute of attributesToMask) {\n const value = maskedAttributes[attribute];\n if (value === null || value === undefined) {\n continue;\n }\n\n if (outputOriginalValue) {\n logger.debug(`Masking attribute '${attribute}' with original value`, { value });\n }\n\n maskedAttributes[attribute] = maskValue(value, rule);\n }\n }\n\n return maskedAttributes;\n}\n","import { createContextKey } from '@opentelemetry/api';\n\nexport const BRIZZ = 'brizz';\nexport const PROPERTIES = 'properties';\nexport const SESSION_ID = 'session.id';\nexport const PROPERTIES_CONTEXT_KEY = createContextKey(PROPERTIES);\n","import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { PeriodicExportingMetricReader, type MetricReader } from '@opentelemetry/sdk-metrics';\n\nimport type { IResolvedBrizzConfig } from '../config';\nimport { logger } from '../logger';\n\nexport class MetricsModule {\n private static instance: MetricsModule | null = null;\n private metricsExporter: OTLPMetricExporter | null = null;\n private metricsReader: MetricReader | null = null;\n\n static getInstance(): MetricsModule {\n if (!MetricsModule.instance) {\n throw new Error('Brizz must be initialized before accessing MetricsModule');\n }\n return MetricsModule.instance;\n }\n\n /**\n * Initialize the metrics module with the provided configuration\n */\n setup(config: IResolvedBrizzConfig): void {\n logger.info('Setting up metrics module');\n\n // Initialize reader (custom or default with exporter)\n this.initMetricsReader(config);\n\n // Set as module instance for standalone functions\n MetricsModule.instance = this;\n\n logger.info('Metrics module setup completed');\n }\n\n /**\n * Initialize the metrics exporter\n */\n private initMetricsExporter(config: IResolvedBrizzConfig): void {\n if (this.metricsExporter) {\n logger.debug('Metrics exporter already initialized, skipping re-initialization');\n return;\n }\n\n const metricsUrl = config.baseUrl.replace(/\\/$/, '') + '/v1/metrics';\n logger.debug('Initializing metrics exporter', { url: metricsUrl });\n\n this.metricsExporter = new OTLPMetricExporter({\n url: metricsUrl,\n headers: config.headers,\n });\n\n logger.debug('Metrics exporter initialized successfully');\n }\n\n /**\n * Initialize the metrics reader\n */\n private initMetricsReader(config: IResolvedBrizzConfig): void {\n if (this.metricsReader) {\n logger.debug('Metrics reader already initialized, skipping re-initialization');\n return;\n }\n\n // Use custom metric reader if provided\n if (config.customMetricReader) {\n logger.debug('Using custom metric reader');\n this.metricsReader = config.customMetricReader;\n logger.debug('Custom metric reader initialized successfully');\n return;\n }\n\n // Use default flow: create OTLP exporter and wrap it in PeriodicExportingMetricReader\n logger.debug(\n 'Using default metrics flow - creating OTLP exporter and PeriodicExportingMetricReader',\n );\n this.initMetricsExporter(config);\n\n if (!this.metricsExporter) {\n throw new Error('Failed to initialize metrics exporter');\n }\n\n this.metricsReader = new PeriodicExportingMetricReader({\n exporter: this.metricsExporter,\n });\n\n logger.debug('Default metrics reader initialized successfully');\n }\n\n /**\n * Get the metrics exporter\n */\n getMetricsExporter(): OTLPMetricExporter {\n if (!this.metricsExporter) {\n throw new Error('Metrics module not initialized');\n }\n return this.metricsExporter;\n }\n\n /**\n * Get the metrics reader\n */\n getMetricsReader(): MetricReader {\n if (!this.metricsReader) {\n throw new Error('Metrics module not initialized');\n }\n return this.metricsReader;\n }\n\n /**\n * Shutdown the metrics module\n */\n shutdown(): void {\n logger.debug('Shutting down metrics module');\n\n this.metricsReader = null;\n this.metricsExporter = null;\n\n // Clear module instance\n if (MetricsModule.instance === this) {\n MetricsModule.instance = null;\n }\n\n logger.debug('Metrics module shutdown completed');\n }\n}\n\n/**\n * Get the OpenTelemetry Metrics Exporter configured for Brizz.\n * @throws {Error} - If SDK is not initialized\n */\nexport function getMetricsExporter(): OTLPMetricExporter {\n return MetricsModule.getInstance().getMetricsExporter();\n}\n\n/**\n * Get the Metrics Reader configured for Brizz.\n * @throws {Error} - If SDK is not initialized\n */\nexport function getMetricsReader(): MetricReader {\n return MetricsModule.getInstance().getMetricsReader();\n}\n","import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport type { SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport type { SpanProcessor } from '@opentelemetry/sdk-trace-node';\n\nimport type { IResolvedBrizzConfig } from '../config';\nimport { logger } from '../logger';\n\nimport { BrizzBatchSpanProcessor, BrizzSimpleSpanProcessor } from './processors/span-processor';\n\nexport class TracingModule {\n private static instance: TracingModule | null = null;\n private spanExporter: SpanExporter | null = null;\n private spanProcessor: SpanProcessor | null = null;\n\n static getInstance(): TracingModule {\n if (!TracingModule.instance) {\n throw new Error('Brizz must be initialized before accessing TracingModule');\n }\n return TracingModule.instance;\n }\n\n /**\n * Initialize the tracing module with the provided configuration\n */\n setup(config: IResolvedBrizzConfig): void {\n logger.info('Setting up tracing module');\n\n // Initialize exporter (custom or default)\n this.initSpanExporter(config);\n\n // Initialize processor with masking support\n this.initSpanProcessor(config);\n\n // Set as module instance for standalone functions\n TracingModule.instance = this;\n\n logger.info('Tracing module setup completed');\n }\n\n /**\n * Initialize the span exporter\n */\n private initSpanExporter(config: IResolvedBrizzConfig): void {\n if (this.spanExporter) {\n logger.debug('Span exporter already initialized, skipping re-initialization');\n return;\n }\n\n // Use custom span exporter if provided\n if (config.customSpanExporter) {\n logger.debug('Using custom span exporter');\n this.spanExporter = config.customSpanExporter;\n logger.debug('Custom span exporter initialized successfully');\n return;\n }\n\n // Use default OTLP exporter\n const tracesUrl = config.baseUrl.replace(/\\/$/, '') + '/v1/traces';\n logger.debug('Initializing default OTLP span exporter', { url: tracesUrl });\n\n this.spanExporter = new OTLPTraceExporter({\n url: tracesUrl,\n headers: config.headers,\n });\n\n logger.debug('OTLP span exporter initialized successfully');\n }\n\n /**\n * Initialize the span processor with masking support\n */\n private initSpanProcessor(config: IResolvedBrizzConfig): void {\n if (this.spanProcessor) {\n logger.debug('Span processor already initialized, skipping re-initialization');\n return;\n }\n\n if (!this.spanExporter) {\n throw new Error('Span exporter must be initialized before processor');\n }\n\n logger.debug('Initializing span processor', {\n disableBatch: config.disableBatch,\n hasMasking: !!config.masking?.spanMasking,\n });\n\n // Use masked processors if masking is configured, otherwise use standard processors\n this.spanProcessor = config.disableBatch\n ? new BrizzSimpleSpanProcessor(this.spanExporter, config)\n : new BrizzBatchSpanProcessor(this.spanExporter, config);\n\n logger.debug('Span processor initialized successfully');\n }\n\n /**\n * Get the span exporter\n */\n getSpanExporter(): SpanExporter {\n if (!this.spanExporter) {\n throw new Error('Tracing module not initialized');\n }\n return this.spanExporter;\n }\n\n /**\n * Get the span processor\n */\n getSpanProcessor(): SpanProcessor {\n if (!this.spanProcessor) {\n throw new Error('Tracing module not initialized');\n }\n return this.spanProcessor;\n }\n\n async shutdown(): Promise<void> {\n logger.debug('Shutting down tracing module');\n\n if (this.spanProcessor) {\n await this.spanProcessor.shutdown();\n this.spanProcessor = null;\n }\n\n if (this.spanExporter) {\n await this.spanExporter.shutdown();\n this.spanExporter = null;\n }\n\n TracingModule.instance = null;\n logger.debug('Tracing module shutdown completed');\n }\n}\n\n/**\n * Get the OpenTelemetry Span Exporter configured for Brizz.\n * @throws {Error} - If SDK is not initialized\n */\nexport function getSpanExporter(): SpanExporter {\n return TracingModule.getInstance().getSpanExporter();\n}\n\n/**\n * Get the Span Processor configured for Brizz.\n * @throws {Error} - If SDK is not initialized\n */\nexport function getSpanProcessor(): SpanProcessor {\n return TracingModule.getInstance().getSpanProcessor();\n}\n","import { type Attributes, type AttributeValue, context, type Context } from '@opentelemetry/api';\nimport {\n BatchSpanProcessor,\n SimpleSpanProcessor,\n type Span,\n type SpanExporter,\n} from '@opentelemetry/sdk-trace-base';\n\nimport type { IResolvedBrizzConfig } from '../../config';\nimport { logger } from '../../logger';\nimport { DEFAULT_PII_PATTERNS } from '../../masking/patterns';\nimport type {\n IAttributesMaskingRule,\n ISpanMaskingConfig,\n MaskableValue,\n} from '../../masking/types';\nimport { maskAttributes } from '../../masking/utils';\nimport { BRIZZ, PROPERTIES_CONTEXT_KEY } from '../../semantic-conventions';\n\nexport const DEFAULT_MASKING_RULES: IAttributesMaskingRule[] = [\n {\n mode: 'partial',\n attributePattern: 'gen_ai.prompt',\n patterns: DEFAULT_PII_PATTERNS,\n },\n {\n mode: 'partial',\n attributePattern: 'gen_ai.completion',\n patterns: DEFAULT_PII_PATTERNS,\n },\n {\n mode: 'partial',\n attributePattern: 'traceloop.entity.input',\n patterns: DEFAULT_PII_PATTERNS,\n },\n {\n mode: 'partial',\n attributePattern: 'traceloop.entity.output',\n patterns: DEFAULT_PII_PATTERNS,\n },\n];\n\nexport class BrizzSimpleSpanProcessor extends SimpleSpanProcessor {\n public readonly config: IResolvedBrizzConfig;\n\n constructor(spanExporter: SpanExporter, config: IResolvedBrizzConfig) {\n super(spanExporter);\n this.config = config;\n }\n\n // Will work with the following code:\n // const span = tracer.startSpan('sensitive-operation',{attributes:{\n // 'user.password': 'secret123',\n // 'user.email': 'user@example.com',\n // }});\n //\n // Won't work because onStart is called before attributes are set:\n // span.setAttributes({\n // 'user.password': 'secret123',\n // 'user.email': 'user@example.com'\n // });\n override onStart(span: Span, parentContext: Context): void {\n const maskingConfig = this.config.masking?.spanMasking;\n if (maskingConfig) {\n maskSpan(span, maskingConfig);\n }\n const associationProperties = context.active().getValue(PROPERTIES_CONTEXT_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n span.setAttribute(`${BRIZZ}.${key}`, value as AttributeValue);\n }\n }\n super.onStart(span, parentContext);\n }\n}\n\nexport class BrizzBatchSpanProcessor extends BatchSpanProcessor {\n public readonly config: IResolvedBrizzConfig;\n\n constructor(spanExporter: SpanExporter, config: IResolvedBrizzConfig) {\n super(spanExporter);\n this.config = config;\n }\n\n override onStart(span: Span, parentContext: Context): void {\n const maskingConfig = this.config.masking?.spanMasking;\n if (maskingConfig) {\n maskSpan(span, maskingConfig);\n }\n const associationProperties = context.active().getValue(PROPERTIES_CONTEXT_KEY);\n if (associationProperties) {\n for (const [key, value] of Object.entries(associationProperties)) {\n span.setAttribute(`${BRIZZ}.${key}`, value as AttributeValue);\n }\n }\n super.onStart(span, parentContext);\n }\n}\n\nexport function maskSpan(span: Span, config: ISpanMaskingConfig): Span {\n if (!span.attributes || Object.keys(span.attributes).length === 0) {\n return span;\n }\n\n let rules = config.rules || [];\n if (!config.disableDefaultRules) {\n rules = [...DEFAULT_MASKING_RULES, ...rules];\n }\n\n try {\n const attributesRecord: Record<string, MaskableValue> = {};\n\n for (const [key, value] of Object.entries(span.attributes)) {\n attributesRecord[key] = value as MaskableValue;\n }\n\n const maskedAttributes = maskAttributes(attributesRecord, rules);\n if (maskedAttributes && Object.keys(maskedAttributes).length > 0) {\n // Use setAttributes to update the span\n const merged: Attributes = { ...span.attributes };\n for (const [key, value] of Object.entries(maskedAttributes)) {\n merged[key] = value as AttributeValue;\n }\n span.setAttributes(merged);\n }\n\n return span;\n } catch (error) {\n logger.error('Error masking span:', error);\n return span;\n }\n}\n","import { context } from '@opentelemetry/api';\n\nimport { PROPERTIES_CONTEXT_KEY, SESSION_ID } from '../semantic-conventions';\n\nexport function withProperties<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n properties: { [name: string]: string },\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n): ReturnType<F> {\n if (Object.keys(properties).length === 0) {\n return fn.apply(thisArg, args);\n }\n\n const newContext = context.active().setValue(PROPERTIES_CONTEXT_KEY, properties);\n return context.with(newContext, fn, thisArg, ...args);\n}\n\n/**\n * Wraps a function to execute it with session context. All telemetry (traces, spans, events)\n * generated within the wrapped function will include the session ID.\n *\n * @example\n * ```typescript\n * // Basic usage with async function\n * await WithSessionId('session-123', myAsyncFunction, null, arg1, arg2);\n *\n * // With method and 'this' context\n * const result = WithSessionId('session-456', obj.method, obj, param);\n *\n * // Wrapping AI operations\n * const response = await WithSessionId('chat-session', async () => {\n * const aiResponse = await openai.chat.completions.create({\n * model: 'gpt-4',\n * messages: [{ role: 'user', content: 'Hello' }]\n * });\n * emitEvent('ai.response', { tokens: aiResponse.usage.total_tokens });\n * return aiResponse;\n * });\n * ```\n *\n * @param sessionId - Session identifier to include in all telemetry within the function\n * @param fn - Function to execute with session context\n * @param thisArg - Value to use as `this` when calling the function (optional)\n * @param args - Arguments to pass to the wrapped function\n * @returns The return value of the wrapped function\n */\nexport function WithSessionId<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n sessionId: string,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n): ReturnType<F> {\n return withProperties({ [SESSION_ID]: sessionId }, fn, thisArg, ...args);\n}\n","import { logger } from '../internal/logger.js';\n\nexport interface RuntimeInfo {\n isESM: boolean;\n isCJS: boolean;\n nodeVersion: string;\n supportsLoaderAPI: boolean;\n supportsRegister: boolean;\n}\n\nexport function detectRuntime(): RuntimeInfo {\n const [major, minor] = process.versions.node.split('.').map(Number);\n\n // Detect ESM vs CJS based on Node.js globals availability\n // In pure ESM: __filename, __dirname, module, exports are undefined\n // In pure CJS: __filename, __dirname, module, exports all exist\n // In mixed/loader contexts: some may exist as shims\n const noNodeJSGlobals = typeof __filename === 'undefined' && typeof __dirname === 'undefined';\n const noModuleSystem = typeof module === 'undefined' && typeof exports === 'undefined';\n const hasRequire = typeof require === 'function';\n\n // ESM: No Node.js globals AND no CJS module system\n // This covers pure ESM and ESM loader contexts\n const isESM = noNodeJSGlobals && noModuleSystem;\n\n // CJS: All CJS globals exist (require, module, exports, __filename, __dirname)\n // This ensures we're in a real CJS context, not a shim environment\n const isCJS =\n hasRequire &&\n typeof module !== 'undefined' &&\n typeof exports !== 'undefined' &&\n typeof __filename === 'string' &&\n typeof __dirname === 'string';\n\n const supportsLoaderAPI =\n (major ?? 0) >= 21 || ((major ?? 0) === 20 && (minor ?? 0) >= 6) || ((major ?? 0) === 18 && (minor ?? 0) >= 19);\n const supportsRegister = !!(process.features as any)?.typescript || !!(globalThis as any).module?.register;\n\n logger.debug('Runtime detection results:', {\n nodeVersion: `${major ?? 0}.${minor ?? 0}`,\n isESM,\n isCJS,\n supportsLoaderAPI,\n supportsRegister,\n detectionLogic: {\n noNodeJSGlobals,\n noModuleSystem,\n hasRequire,\n esmCondition: `${noNodeJSGlobals} && ${noModuleSystem} = ${isESM}`,\n cjsCondition: `require && module && exports && __filename && __dirname = ${isCJS}`,\n },\n checks: {\n __filename: typeof __filename,\n __dirname: typeof __dirname,\n require: typeof require,\n module: typeof module,\n exports: typeof exports,\n 'process.features': process.features,\n 'globalThis.module': (globalThis as any).module,\n },\n });\n\n return {\n isESM,\n isCJS,\n nodeVersion: process.versions.node,\n supportsLoaderAPI,\n supportsRegister,\n };\n}\n","// Explicit init entrypoint for preload usage:\n// - ESM: node --import @brizz/sdk/init app.mjs\n// - CJS: node --require @brizz/sdk/init app.js\n//\n// This ensures auto-instrumentations are registered before user imports.\nimport './internal/instrumentation/auto-init';\n\n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xB,SAAS,gBAA6B;AAC3C,QAAM,CAAC,OAAO,KAAK,IAAI,QAAQ,SAAS,KAAK,MAAM,GAAG,EAAE,IAAI,MAAM;AAMlE,QAAM,kBAAkB,OAAO,eAAe,eAAe,OAAO,cAAc;AAClF,QAAM,iBAAiB,OAAO,WAAW,eAAe,OAAO,YAAY;AAC3E,QAAM,aAAa,OAAO,YAAY;AAItC,QAAM,QAAQ,mBAAmB;AAIjC,QAAM,QACJ,cACA,OAAO,WAAW,eAClB,OAAO,YAAY,eACnB,OAAO,eAAe,YACtB,OAAO,cAAc;AAEvB,QAAM,qBACH,SAAS,MAAM,OAAQ,SAAS,OAAO,OAAO,SAAS,MAAM,MAAQ,SAAS,OAAO,OAAO,SAAS,MAAM;AAC9G,QAAM,mBAAmB,CAAC,CAAE,QAAQ,UAAkB,cAAc,CAAC,CAAE,WAAmB,QAAQ;AAElG,SAAO,MAAM,8BAA8B;AAAA,IACzC,aAAa,GAAG,SAAS,CAAC,IAAI,SAAS,CAAC;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA,cAAc,GAAG,eAAe,OAAO,cAAc,MAAM,KAAK;AAAA,MAChE,cAAc,6DAA6D,KAAK;AAAA,IAClF;AAAA,IACA,QAAQ;AAAA,MACN,YAAY,OAAO;AAAA,MACnB,WAAW,OAAO;AAAA,MAClB,SAAS,OAAO;AAAA,MAChB,QAAQ,OAAO;AAAA,MACf,SAAS,OAAO;AAAA,MAChB,oBAAoB,QAAQ;AAAA,MAC5B,qBAAsB,WAAmB;AAAA,IAC3C;AAAA,EACF,CAAC;AAED,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,aAAa,QAAQ,SAAS;AAAA,IAC9B;AAAA,IACA;AAAA,EACF;AACF;;;ACrEA;","names":["import_instrumentation","LogLevel","pino","import_api","context","import_api","import_api","context","import_api","import_api","context","import_api","logger","module","import_resources","import_instrumentation_anthropic","import_instrumentation_bedrock","import_instrumentation_chromadb","import_instrumentation_cohere","import_instrumentation_langchain","import_instrumentation_llamaindex","import_instrumentation_openai","import_instrumentation_pinecone","import_instrumentation_qdrant","import_instrumentation_together","import_instrumentation_vertexai","exceptionLogger","import_api_logs","import_sdk_logs","import_api","import_api","import_api","import_api","import_api_logs"]}