@brizz/sdk 0.1.20 → 0.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +919 -191
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -1
- package/dist/index.d.ts +13 -1
- package/dist/index.js +892 -161
- package/dist/index.js.map +1 -1
- package/dist/preload.cjs +626 -18
- package/dist/preload.cjs.map +1 -1
- package/dist/preload.js +626 -18
- package/dist/preload.js.map +1 -1
- package/package.json +6 -5
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/internal/instrumentation/auto-init.ts","../src/internal/logger.ts","../src/internal/sdk.ts","../src/internal/config.ts","../src/internal/constants.ts","../src/internal/instrumentation/registry.ts","../src/internal/log/logging.ts","../src/internal/version.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/exporters/span-exporter.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 { type IInstrumentModules } from './internal/instrumentation/index.js';\n\n// Re-export utility functions from their respective modules\nexport { emitEvent } from './internal/log/index.js';\nexport {\n getSpanExporter,\n getSpanProcessor,\n withSessionId,\n callWithSessionId,\n withProperties,\n callWithProperties,\n Session,\n SessionTitle,\n startSession,\n startSessionTitle,\n getActiveSession,\n} 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';\nexport type { AttributeValue } from '@opentelemetry/api';\nexport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\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 { 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\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 // Disabled because @traceloop/instrumentation-openai wraps the same OpenAI\n // prototype with richer span attributes (gen_ai.input.messages /\n // gen_ai.output.messages). Leaving both enabled lets the official one win\n // and route content to log events instead of span attributes, leaving the\n // Brizz backend parser with no payload to read.\n '@opentelemetry/instrumentation-openai': { enabled: false },\n });\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: 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: 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 { AttributeValue } from '@opentelemetry/api';\nimport { 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 { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\n\nimport type { IResolvedBrizzConfig } from './config';\nimport { resolveConfig } from './config';\nimport { BRIZZ_SDK_LANGUAGE, BRIZZ_SDK_VERSION, SDK_LANGUAGE } from './constants';\nimport { type IInstrumentModules, InstrumentationRegistry } 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';\nimport { getSDKVersion } from './version';\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 /**\n * Application version, propagated as the `service.version` OpenTelemetry\n * resource attribute on every span, log, and metric.\n *\n * Shortcut for `resourceAttributes: { 'service.version': '...' }`. When both\n * are set, `appVersion` wins. Overridable via the `BRIZZ_APP_VERSION` env var.\n *\n * @example\n * ```typescript\n * // Pull it straight from package.json\n * import { version } from './package.json' with { type: 'json' };\n *\n * Brizz.initialize({\n * appName: 'my-app',\n * appVersion: version,\n * });\n * ```\n */\n appVersion?: 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 /** Deployment environment (e.g., 'production', 'staging', 'development') for OpenTelemetry resource attributes */\n environment?: string;\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 * Disable span exporting.\n *\n * When `true`, Brizz will not configure a span exporter or span processor, so no\n * spans are sent to Brizz. `NodeSDK` is still started (with an empty span-processors\n * list) and other telemetry — metrics and logs — keeps working. Useful for dev\n * environments, or when you want to keep the SDK API alive without emitting span data.\n *\n * Can also be enabled via the `BRIZZ_DISABLE_SPAN_EXPORTER=true` environment variable.\n *\n * @example\n * ```typescript\n * Brizz.initialize({\n * appName: 'my-app',\n * disableSpanExporter: true,\n * });\n * ```\n */\n disableSpanExporter?: boolean;\n /**\n * Additional OpenTelemetry resource attributes applied to all spans,\n * logs, and metrics. Use this for custom resource-level tags. Brizz-owned\n * keys (`service.name`, `brizz.sdk.version`, `brizz.sdk.language`,\n * `deployment.environment`) cannot be overridden here — set them via\n * `appName` / `environment`. For `service.version`, prefer the dedicated\n * `appVersion` option (which wins if both are set).\n *\n * The standard `OTEL_RESOURCE_ATTRIBUTES` environment variable is also\n * honored by the OpenTelemetry Node SDK out of the box, and is the\n * recommended way to provide these via environment config.\n *\n * @example\n * ```typescript\n * Brizz.initialize({\n * appName: 'my-app',\n * resourceAttributes: {\n * team: 'platform',\n * region: 'us-east-1',\n * },\n * });\n * ```\n */\n resourceAttributes?: Record<string, AttributeValue>;\n /**\n * Optional synchronous or asynchronous filter invoked once per span\n * just before export. Return `false` to drop the span. Return `true`\n * to keep it. Exceptions are caught and logged; the span passes through.\n *\n * Use this to drop health-check spans, spans from internal users,\n * debug spans, etc. For modifying span attributes, use the `masking` option.\n *\n * @example\n * ```typescript\n * Brizz.initialize({\n * appName: 'my-app',\n * beforeSendSpan: (span) => span.name !== 'health-check',\n * });\n * ```\n */\n beforeSendSpan?: (span: ReadableSpan) => boolean | Promise<boolean>;\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)}`, { cause: 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 // Merge user-provided resource attributes first, then apply Brizz-owned keys\n // on top so they always win on collisions (user cannot override service.name,\n // brizz.sdk.version, brizz.sdk.language, or deployment.environment).\n const resourceAttributes: Record<string, AttributeValue> = {\n ...resolvedConfig.resourceAttributes,\n 'service.name': resolvedConfig.appName,\n [BRIZZ_SDK_VERSION]: getSDKVersion(),\n [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE,\n };\n\n // Add environment attribute if specified\n if (resolvedConfig.environment) {\n resourceAttributes['deployment.environment'] = resolvedConfig.environment;\n }\n // appVersion takes precedence over user-supplied resourceAttributes['service.version']\n if (resolvedConfig.appVersion) {\n resourceAttributes['service.version'] = resolvedConfig.appVersion;\n }\n\n this._sdk = new NodeSDK({\n spanProcessors: resolvedConfig.disableSpanExporter ? [] : [getSpanProcessor()],\n metricReader: getMetricsReader(),\n resource: resourceFromAttributes(resourceAttributes),\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 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 { AttributeValue } from '@opentelemetry/api';\nimport type { NodeSDK } from '@opentelemetry/sdk-node';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\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 environment?: string;\n apiKey?: string;\n logLevel: LogLevel;\n nodeSDK?: NodeSDK | null;\n masking?: IMaskingConfig;\n resourceAttributes?: Record<string, AttributeValue>;\n beforeSendSpan?: (span: ReadableSpan) => boolean | Promise<boolean>;\n}\n\nexport function resolveConfig(options: IBrizzInitializeOptions): IResolvedBrizzConfig {\n // Resolve log level first so we can set it before other logging\n const envLogLevel =\n 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 appVersion: process.env['BRIZZ_APP_VERSION'] || options.appVersion,\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 disableSpanExporter:\n process.env['BRIZZ_DISABLE_SPAN_EXPORTER'] === 'true' || !!options.disableSpanExporter,\n environment: process.env['BRIZZ_ENVIRONMENT'] || options.environment,\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', { cause: error });\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","/**\n * Semantic conventions and constants for Brizz SDK.\n */\n\n/**\n * Brizz SDK resource attribute keys.\n * These keys are used to add metadata to OpenTelemetry resource attributes.\n */\nexport const BRIZZ_SDK_VERSION = 'brizz.sdk.version';\nexport const BRIZZ_SDK_LANGUAGE = 'brizz.sdk.language';\n\n/**\n * SDK language identifier.\n */\nexport const SDK_LANGUAGE = 'typescript';\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 { 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\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 /** The @langchain/core/callbacks/manager module for instrumentation */\n callbackManagerModule?: 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 {\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 ];\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 // Handle LangChain separately - dynamically imported to avoid requiring\n // @langchain/core for users who don't use LangChain.\n // Uses fire-and-forget: manuallyInstrument() patches the module directly,\n // so it doesn't need to be in the NodeSDK instrumentations array.\n if (this.manualModules?.langchain?.callbackManagerModule) {\n const callbackManagerModule = this.manualModules.langchain.callbackManagerModule;\n void (async () => {\n try {\n const { LangChainInstrumentation } =\n await import('@arizeai/openinference-instrumentation-langchain');\n const lcInst = new LangChainInstrumentation();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument\n lcInst.manuallyInstrument(callbackManagerModule as any);\n logger.debug('Manual instrumentation enabled for LangChain');\n } catch (error: unknown) {\n logger.error(\n `Failed to load LangChain instrumentation. Ensure @langchain/core is installed: ${String(error)}`,\n );\n }\n })();\n }\n }\n}\n","import type { AttributeValue } from '@opentelemetry/api';\nimport 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 { BRIZZ_SDK_LANGUAGE, BRIZZ_SDK_VERSION, SDK_LANGUAGE } from '../constants';\nimport { logger } from '../logger';\nimport { getSDKVersion } from '../version';\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 // Merge user-provided resource attributes first, then apply Brizz-owned\n // keys on top so they always win on collisions.\n const resourceAttributes: Record<string, AttributeValue> = {\n ...config.resourceAttributes,\n 'service.name': config.appName,\n [BRIZZ_SDK_VERSION]: getSDKVersion(),\n [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE,\n };\n\n // Add environment attribute if specified\n if (config.environment) {\n resourceAttributes['deployment.environment'] = config.environment;\n }\n // appVersion takes precedence over user-supplied resourceAttributes['service.version']\n if (config.appVersion) {\n resourceAttributes['service.version'] = config.appVersion;\n }\n\n const resource = resourceFromAttributes(resourceAttributes);\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","/**\n * SDK version injected at build time from package.json.\n * This constant is replaced by the bundler during the build process.\n */\ndeclare const __SDK_VERSION__: string;\n\n/**\n * Get the SDK version.\n * The version is injected at build time from package.json.\n *\n * @returns {string} - The SDK version (e.g., \"0.1.6\")\n */\nexport function getSDKVersion(): string {\n return __SDK_VERSION__;\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 cause: error,\n });\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.toReversed()) {\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);\nexport const SESSION_OBJECT_CONTEXT_KEY = createContextKey('brizz.session.object');\n\n// Session semantic conventions\nexport const SESSION_INPUT = 'brizz.session.input';\nexport const SESSION_OUTPUT = 'brizz.session.output';\n// Per-turn context bags (index-aligned with SESSION_INPUT / SESSION_OUTPUT) captured\n// from setInput / setOutput's second argument. Each element is a JSON object.\nexport const SESSION_INPUT_CONTEXT = 'brizz.session.input.context';\nexport const SESSION_OUTPUT_CONTEXT = 'brizz.session.output.context';\nexport const SESSION_SPAN_NAME = 'brizz.start_session';\n\n// Session title semantic conventions\nexport const SESSION_TITLE_SPAN_NAME = 'brizz.session_title';\nexport const SESSION_TITLE_GENERATION = 'session.title_generation';\nexport const SESSION_TITLE = 'brizz.session.title';\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","// Use protobuf exporter instead of JSON to ensure correct trace ID encoding\n// JSON exporter sends hex strings which get misinterpreted as base64 by protojson.Unmarshal\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';\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 { BrizzSpanExporter } from './exporters/span-exporter';\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 if (config.disableSpanExporter) {\n logger.info(\n 'Span exporter disabled via disableSpanExporter; skipping exporter and processor setup',\n );\n this.spanExporter = null;\n this.spanProcessor = null;\n TracingModule.instance = this;\n return;\n }\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 = new BrizzSpanExporter(config.customSpanExporter, config);\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 const otlpExporter = new OTLPTraceExporter({\n url: tracesUrl,\n headers: config.headers,\n });\n this.spanExporter = new BrizzSpanExporter(otlpExporter, config);\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 const 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 this.spanProcessor = spanProcessor;\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 { AttributeValue } from '@opentelemetry/api';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\nimport { resourceFromAttributes } from '@opentelemetry/resources';\nimport type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\n\nimport type { IResolvedBrizzConfig } from '../../config';\nimport { BRIZZ_SDK_LANGUAGE, BRIZZ_SDK_VERSION, SDK_LANGUAGE } from '../../constants';\nimport { logger } from '../../logger';\nimport { getSDKVersion } from '../../version';\n\n/**\n * A span exporter wrapper that ensures the correct `service.name` and Brizz SDK\n * resource attributes are present on every exported span, and applies an\n * optional per-span `beforeSendSpan` filter.\n *\n * This is needed when an external OTEL provider (e.g. Sentry) owns the TracerProvider\n * and sets a default `service.name` (like \"node\") that we cannot control.\n * Since `ReadableSpan.resource` is readonly, we intercept at the export layer\n * and create proxy spans with the correct resource.\n */\nexport class BrizzSpanExporter implements SpanExporter {\n private readonly _delegate: SpanExporter;\n private readonly _brizzResource;\n private readonly _beforeSendSpan?: (span: ReadableSpan) => boolean | Promise<boolean>;\n\n constructor(delegate: SpanExporter, config: IResolvedBrizzConfig) {\n this._delegate = delegate;\n\n // Merge user-provided resource attributes first, then apply Brizz-owned\n // keys on top so they always win on collisions.\n const resourceAttrs: Record<string, AttributeValue> = {\n ...config.resourceAttributes,\n 'service.name': config.appName,\n [BRIZZ_SDK_VERSION]: getSDKVersion(),\n [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE,\n };\n if (config.environment) {\n resourceAttrs['deployment.environment'] = config.environment;\n }\n // appVersion takes precedence over user-supplied resourceAttributes['service.version']\n if (config.appVersion) {\n resourceAttrs['service.version'] = config.appVersion;\n }\n this._brizzResource = resourceFromAttributes(resourceAttrs);\n this._beforeSendSpan = config.beforeSendSpan;\n }\n\n export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n if (spans.length === 0) {\n resultCallback({ code: ExportResultCode.SUCCESS });\n return;\n }\n\n // Patch the resource BEFORE running beforeSendSpan so the filter sees the\n // same resource attributes (service.name, service.version, user resourceAttributes, …)\n // that will actually be exported. Resource.merge(other) — \"other\" takes precedence,\n // so brizzResource wins on collisions (e.g. overrides external provider's\n // service.name=\"node\" with our configured appName) while preserving other attrs.\n const patchedSpans = spans.map((span) => ({\n ...span,\n resource: span.resource.merge(this._brizzResource),\n spanContext: span.spanContext.bind(span),\n }));\n\n const filter = this._beforeSendSpan;\n if (!filter) {\n this._delegate.export(patchedSpans, resultCallback);\n return;\n }\n\n // Evaluate filter per span; tolerate sync and async returns; fail-open on throws.\n const verdicts = patchedSpans.map((span) => {\n try {\n return Promise.resolve(filter(span));\n } catch (error) {\n logger.warn('beforeSendSpan threw; span will be kept', { error });\n return Promise.resolve(true);\n }\n });\n\n Promise.all(verdicts)\n .then((keep) => {\n const filtered = patchedSpans.filter((_, i) => keep[i] !== false);\n if (filtered.length === 0) {\n resultCallback({ code: ExportResultCode.SUCCESS });\n return;\n }\n this._delegate.export(filtered, resultCallback);\n return;\n })\n .catch((error: unknown) => {\n logger.warn('beforeSendSpan rejected; all spans will be kept', { error });\n this._delegate.export(patchedSpans, resultCallback);\n });\n }\n\n async shutdown(): Promise<void> {\n return this._delegate.shutdown();\n }\n\n async forceFlush(): Promise<void> {\n return this._delegate.forceFlush?.();\n }\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\n/**\n * Stamp context-propagated session-level `brizz.<key>` attributes on a span.\n */\nfunction applyContextAttributes(span: Span): void {\n const sessionProperties = context.active().getValue(PROPERTIES_CONTEXT_KEY);\n if (sessionProperties) {\n for (const [key, value] of Object.entries(sessionProperties)) {\n span.setAttribute(`${BRIZZ}.${key}`, value as AttributeValue);\n }\n }\n}\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\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 applyContextAttributes(span);\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 applyContextAttributes(span);\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, trace, SpanStatusCode } from '@opentelemetry/api';\nimport type { Span, AttributeValue } from '@opentelemetry/api';\n\nimport {\n BRIZZ,\n PROPERTIES_CONTEXT_KEY,\n SESSION_ID,\n SESSION_INPUT,\n SESSION_INPUT_CONTEXT,\n SESSION_OBJECT_CONTEXT_KEY,\n SESSION_OUTPUT,\n SESSION_OUTPUT_CONTEXT,\n SESSION_SPAN_NAME,\n SESSION_TITLE,\n SESSION_TITLE_GENERATION,\n SESSION_TITLE_SPAN_NAME,\n} from '../semantic-conventions';\n\n/**\n * Immediately executes a function with custom properties in the context. All telemetry (traces, spans, events)\n * generated within the function will include these properties.\n *\n * @param properties - Key-value properties to include in all telemetry within the function\n * @param fn - Function to execute with properties context\n * @param thisArg - Value to use as `this` when calling the function (optional)\n * @param args - Arguments to pass to the function\n * @returns The return value of the function\n */\nexport function callWithProperties<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 const base = context.active();\n const prev = base.getValue(PROPERTIES_CONTEXT_KEY) as Record<string, string> | undefined;\n const merged = prev ? { ...prev, ...properties } : properties;\n const next = base.setValue(PROPERTIES_CONTEXT_KEY, merged);\n return context.with(next, fn, thisArg, ...args);\n}\n\n/**\n * Wraps a function to create a new function that will execute with custom properties in the context.\n * All telemetry (traces, spans, events) generated within the wrapped function will include these properties.\n *\n * @example\n * ```typescript\n * // Wrap a function to always execute with properties\n * const wrappedFn = withProperties({ userId: 'user-123', env: 'prod' }, myFunction);\n * const result = await wrappedFn(arg1, arg2);\n *\n * // Wrap a method with 'this' context\n * const wrappedMethod = withProperties({ feature: 'checkout' }, obj.method, obj);\n * const result = wrappedMethod(param);\n * ```\n *\n * @param properties - Key-value properties to include in all telemetry within the function\n * @param fn - Function to wrap with properties context\n * @param thisArg - Value to use as `this` when calling the function (optional)\n * @returns A wrapped function that will execute with properties context\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function withProperties<F extends (this: any, ...args: any[]) => any>(\n properties: { [name: string]: string },\n fn: F,\n thisArg?: ThisParameterType<F>,\n): F {\n return function wrapped(this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F> {\n\n return callWithProperties(\n properties,\n fn,\n thisArg !== undefined ? thisArg : this,\n ...args,\n ) as ReturnType<F>;\n } as F;\n}\n\n/**\n * Wraps a function to create a new function that will execute with session context.\n * All telemetry (traces, spans, events) generated within the wrapped function will include the session ID.\n *\n * @example\n * ```typescript\n * // Wrap a function to always execute with a session\n * const wrappedFn = withSessionId('session-123', myFunction);\n * const result = await wrappedFn(arg1, arg2);\n *\n * // Wrap a method with 'this' context\n * const wrappedMethod = withSessionId('session-456', obj.method, obj);\n * const result = wrappedMethod(param);\n *\n * // With extra properties propagated to all spans\n * const wrappedFn = withSessionId('session-123', myFunction, undefined, { userId: 'user-456' });\n * ```\n *\n * @param sessionId - Session identifier to include in all telemetry within the function\n * @param fn - Function to wrap with session context\n * @param thisArg - Value to use as `this` when calling the function (optional)\n * @param extraProperties - Additional key-value properties to propagate to all spans within the session (optional)\n * @returns A wrapped function that will execute with session context\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function withSessionId<F extends (this: any, ...args: any[]) => any>(\n sessionId: string,\n fn: F,\n thisArg?: ThisParameterType<F>,\n extraProperties?: Record<string, string>,\n): F {\n const properties = { [SESSION_ID]: sessionId, ...extraProperties };\n return withProperties(properties, fn, thisArg);\n}\n\n/**\n * Immediately executes a function with session context. All telemetry (traces, spans, events)\n * generated within the function will include the session ID.\n *\n * @example\n * ```typescript\n * // Basic usage with async function\n * await callWithSessionId('session-123', myAsyncFunction, null, arg1, arg2);\n *\n * // With method and 'this' context\n * const result = callWithSessionId('session-456', obj.method, obj, param);\n *\n * // Wrapping AI operations\n * const response = await callWithSessionId('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 callWithSessionId<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 callWithProperties({ [SESSION_ID]: sessionId }, fn, thisArg, ...args);\n}\n\n/**\n * Session object for managing session-level tracking.\n * All LLM calls within a session are automatically linked.\n * Optionally use setInput/setOutput to track specific data.\n *\n * @example\n * ```typescript\n * startSession('session-123', (session) => {\n * session.updateProperties({ userId: 'user-456' });\n * // All LLM calls here are automatically linked\n * const response = await llm.complete(...);\n * // Optionally track specific input/output\n * // session.setInput('user query');\n * // session.setOutput('response text');\n * });\n * ```\n */\nexport class Session {\n public readonly sessionId: string;\n private readonly span: Span;\n private inputs: (string | null)[] = [];\n private outputs: (string | null)[] = [];\n private inputContexts: Record<string, AttributeValue>[] = [];\n private outputContexts: Record<string, AttributeValue>[] = [];\n\n constructor(sessionId: string, span: Span) {\n this.sessionId = sessionId;\n this.span = span;\n }\n\n /**\n * Append a user turn to session input tracking.\n *\n * Each call appends one element to `brizz.session.input` (the text) AND one\n * element to `brizz.session.input.context` (the per-turn context bag). The\n * two arrays stay index-aligned — the ingestion pipeline zips them together\n * so the i-th context bag lands on the i-th user_display conversation item's\n * `span_attributes` map.\n *\n * @param text - Text to append (null becomes a null/\"hide marker\")\n * @param context - Optional per-turn context bag to attach to this turn\n */\n setInput(text: string | null, context?: Record<string, AttributeValue>): void {\n this.inputs.push(text);\n this.inputContexts.push(context ?? {});\n this.span.setAttribute(SESSION_INPUT, JSON.stringify(this.inputs));\n this.span.setAttribute(SESSION_INPUT_CONTEXT, JSON.stringify(this.inputContexts));\n }\n\n /**\n * Append an assistant turn to session output tracking.\n *\n * Symmetric to {@link setInput} — appends one text element and one\n * context-bag element to the index-aligned `brizz.session.output` /\n * `brizz.session.output.context` arrays.\n *\n * @param text - Text to append (null becomes a null/\"hide marker\")\n * @param context - Optional per-turn context bag to attach to this turn\n */\n setOutput(text: string | null, context?: Record<string, AttributeValue>): void {\n this.outputs.push(text);\n this.outputContexts.push(context ?? {});\n this.span.setAttribute(SESSION_OUTPUT, JSON.stringify(this.outputs));\n this.span.setAttribute(SESSION_OUTPUT_CONTEXT, JSON.stringify(this.outputContexts));\n }\n\n /**\n * Set the session title on the span.\n *\n * @param title - The generated title string\n */\n setTitle(title: string): void {\n this.span.setAttribute(SESSION_TITLE, title);\n }\n\n /**\n * Update custom properties on the session span.\n * Properties are prefixed with 'brizz.'.\n *\n * @param properties - Key-value properties to set on the session\n */\n updateProperties(properties: Record<string, AttributeValue>): void {\n for (const [key, value] of Object.entries(properties)) {\n this.span.setAttribute(`${BRIZZ}.${key}`, value);\n }\n }\n}\n\n/**\n * Title generation scope object for setting the session title.\n *\n * @example\n * ```typescript\n * await startSessionTitle(async (title) => {\n * const generated = await llm.generateTitle(conversation);\n * title.setTitle(generated);\n * });\n * ```\n */\nexport class SessionTitle {\n private readonly span: Span;\n\n constructor(span: Span) {\n this.span = span;\n }\n\n /**\n * Set the generated title on the wrapper span.\n *\n * @param title - The generated title string\n */\n setTitle(title: string): void {\n this.span.setAttribute(SESSION_TITLE, title);\n }\n}\n\n/**\n * Get the active session from the current context.\n *\n * Returns the Session object if called within a startSession scope,\n * otherwise returns undefined.\n *\n * @example\n * ```typescript\n * function deepHelper() {\n * const session = getActiveSession();\n * session?.updateProperties({ step: 'helper' });\n * }\n *\n * startSession('my-session', (session) => {\n * deepHelper(); // can access session without passing it\n * });\n * ```\n */\nexport function getActiveSession(): Session | undefined {\n return context.active().getValue(SESSION_OBJECT_CONTEXT_KEY) as Session | undefined;\n}\n\n/**\n * Execute a function within a session context.\n * Creates a span that tracks the session and provides a Session object\n * for input/output recording.\n *\n * @example\n * ```typescript\n * // Sync usage\n * const result = startSession('session-123', (session) => {\n * session.setInput('user query');\n * const response = processQuery();\n * session.setOutput(response);\n * return response;\n * });\n *\n * // Async usage\n * const result = await startSession('session-456', async (session) => {\n * session.setInput('user query');\n * const response = await llm.complete('...');\n * session.setOutput(response.text);\n * return response;\n * });\n *\n * // With extra properties on the session span and propagated to child spans\n * const result = await startSession('session-789', async (session) => {\n * const response = await llm.complete('...');\n * return response;\n * }, { userId: 'user-456', feature: 'chat' });\n * ```\n *\n * @param sessionId - Session identifier to associate with telemetry\n * @param callback - Function to execute within the session context\n * @param extraProperties - Additional properties to set on the session span and propagate to child spans (optional)\n * @returns The return value of the callback function\n */\nexport function startSession<T>(\n sessionId: string,\n callback: (session: Session) => T,\n extraProperties?: Record<string, AttributeValue>,\n options?: { mode?: 'default' | 'title' },\n): T {\n const isTitle = options?.mode === 'title';\n const spanName = isTitle ? SESSION_TITLE_SPAN_NAME : SESSION_SPAN_NAME;\n const tracer = trace.getTracer('@brizz/sdk');\n return tracer.startActiveSpan(spanName, (span) => {\n span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);\n\n // Set extra properties on the span (with brizz. prefix)\n if (extraProperties) {\n for (const [key, value] of Object.entries(extraProperties)) {\n span.setAttribute(`${BRIZZ}.${key}`, value);\n }\n }\n\n const session = new Session(sessionId, span);\n\n // Build context properties (strings only for context propagation)\n const contextProperties: Record<string, string> = { [SESSION_ID]: sessionId };\n if (isTitle) {\n contextProperties[SESSION_TITLE_GENERATION] = 'true';\n }\n if (extraProperties) {\n for (const [key, value] of Object.entries(extraProperties)) {\n contextProperties[key] = String(value);\n }\n }\n\n // Propagate session ID and extra properties through context so nested operations can access them\n return callWithProperties(contextProperties, () => {\n const sessionCtx = context.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);\n return context.with(sessionCtx, () => {\n try {\n const result = callback(session);\n // Handle async callbacks using thenable duck-type check (more reliable than instanceof Promise)\n if (result && typeof (result as { then?: unknown }).then === 'function') {\n return (result as unknown as Promise<unknown>)\n .then((value) => {\n span.end();\n return value;\n })\n .catch((error: unknown) => {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.end();\n throw error;\n }) as T;\n }\n span.end();\n return result;\n } catch (error) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.end();\n throw error;\n }\n });\n });\n });\n}\n\n/**\n * Execute a function within a session title generation scope.\n * All LLM/AI spans created within this scope will be marked as title generation\n * spans and excluded from the conversation view.\n *\n * @example\n * ```typescript\n * await startSessionTitle(async (title) => {\n * const generated = await llm.generateTitle(conversation);\n * title.setTitle(generated);\n * });\n * ```\n *\n * @param callback - Function to execute within the title generation scope\n * @returns The return value of the callback function\n */\nexport function startSessionTitle<T>(\n callback: (title: SessionTitle) => T,\n options?: { sessionId?: string },\n): T {\n const resolvedSessionId = options?.sessionId ?? getActiveSession()?.sessionId;\n const tracer = trace.getTracer('@brizz/sdk');\n return tracer.startActiveSpan(SESSION_TITLE_SPAN_NAME, (span) => {\n if (resolvedSessionId) {\n span.setAttribute(`${BRIZZ}.${SESSION_ID}`, resolvedSessionId);\n }\n const sessionTitle = new SessionTitle(span);\n\n const properties: Record<string, string> = { [SESSION_TITLE_GENERATION]: 'true' };\n if (resolvedSessionId) {\n properties[SESSION_ID] = resolvedSessionId;\n }\n return callWithProperties(properties, () => {\n try {\n const result = callback(sessionTitle);\n if (result && typeof (result as { then?: unknown }).then === 'function') {\n return (result as unknown as Promise<unknown>)\n .then((value) => {\n span.end();\n return value;\n })\n .catch((error: unknown) => {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.end();\n throw error;\n }) as T;\n }\n span.end();\n return result;\n } catch (error) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.end();\n throw error;\n }\n });\n });\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 ||\n ((major ?? 0) === 20 && (minor ?? 0) >= 6) ||\n ((major ?? 0) === 18 && (minor ?? 0) >= 19);\n const supportsRegister =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n !!(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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,wCAA4C;AAE5C,6BAAyC;AACzC,uCAAyC;AACzC,qCAAuC;AACvC,sCAAwC;AACxC,oCAAsC;AACtC,wCAA0C;AAC1C,oCAAsC;AACtC,sCAAwC;AACxC,oCAAsC;AACtC,sCAAwC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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;AAAA,MAE5B,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;;;AC1EA;","names":["LogLevel","pino","import_resources","import_instrumentation_anthropic","import_instrumentation_bedrock","import_instrumentation_chromadb","import_instrumentation_cohere","import_instrumentation_llamaindex","import_instrumentation_openai","import_instrumentation_pinecone","import_instrumentation_qdrant","import_instrumentation_together","import_instrumentation_vertexai","exceptionLogger","import_sdk_logs","import_api","import_api","import_resources","import_api","import_api","context","import_api_logs"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/logger.ts","../src/internal/semantic-conventions.ts","../src/internal/instrumentation/mcp/session.ts","../src/internal/instrumentation/mcp/semantic-conventions.ts","../src/internal/instrumentation/mcp/patches/attributes.ts","../src/internal/instrumentation/mcp/patches/protocol.ts","../src/internal/version.ts","../src/internal/instrumentation/mcp/version.ts","../src/internal/instrumentation/mcp/instrumentation.ts","../src/internal/instrumentation/mcp/index.ts","../src/index.ts","../src/internal/instrumentation/auto-init.ts","../src/internal/sdk.ts","../src/internal/config.ts","../src/internal/constants.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/metric/metrics.ts","../src/internal/trace/tracing.ts","../src/internal/trace/exporters/span-exporter.ts","../src/internal/trace/processors/span-processor.ts","../src/internal/trace/session.ts","../src/node/runtime.ts","../src/init.ts"],"sourcesContent":["/**\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 { 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);\nexport const SESSION_OBJECT_CONTEXT_KEY = createContextKey('brizz.session.object');\n\n// Session semantic conventions\nexport const SESSION_INPUT = 'brizz.session.input';\nexport const SESSION_OUTPUT = 'brizz.session.output';\n// Per-turn context bags (index-aligned with SESSION_INPUT / SESSION_OUTPUT) captured\n// from setInput / setOutput's second argument. Each element is a JSON object.\nexport const SESSION_INPUT_CONTEXT = 'brizz.session.input.context';\nexport const SESSION_OUTPUT_CONTEXT = 'brizz.session.output.context';\nexport const SESSION_SPAN_NAME = 'brizz.start_session';\n\n// Session title semantic conventions\nexport const SESSION_TITLE_SPAN_NAME = 'brizz.session_title';\nexport const SESSION_TITLE_GENERATION = 'session.title_generation';\nexport const SESSION_TITLE = 'brizz.session.title';\n","/**\n * Propagate MCP session id as `brizz.session.id` on the tool-call span + children.\n *\n * Direct port of the Python SDK's\n * `apps/sdk/python/src/brizz/_internal/instrumentation/fastmcp_instrumentation/session.py`.\n *\n * Server spans carry `mcp.session.id` from the MCP transport, but Brizz-native\n * `brizz.session.id` is the namespaced key the dashboard filters on. We:\n * 1. Stamp `brizz.session.id` directly on the server span. Its `onStart`\n * hook has already fired — so we can't rely on the Brizz span-processor\n * to retroactively stamp this span.\n * 2. Attach an OTel context with `session.id` under `PROPERTIES_CONTEXT_KEY`\n * so `BrizzSimpleSpanProcessor.onStart` /\n * `BrizzBatchSpanProcessor.onStart` stamp `brizz.session.id` on every\n * NEW span created inside the handler body.\n *\n * The caller owns detachment — callers run inside `context.with(...)` which\n * restores the parent context on scope exit, so no manual detach is needed\n * with the current patches.\n */\n\nimport type { Context, Span } from '@opentelemetry/api';\nimport { context } from '@opentelemetry/api';\n\nimport { logger } from '../../logger.js';\nimport { BRIZZ, PROPERTIES_CONTEXT_KEY, SESSION_ID } from '../../semantic-conventions.js';\n\nexport interface ISessionAttachResult {\n /** The new context with session.id under PROPERTIES_CONTEXT_KEY. */\n context: Context;\n /** The session id that was stamped, or null when no session was bound. */\n sessionId: string | null;\n}\n\n/**\n * Stamp `brizz.session.id` on `span` and return a context carrying the\n * session under `PROPERTIES_CONTEXT_KEY` so the Brizz span-processor will\n * stamp it on child spans.\n *\n * Silently no-ops on any error — telemetry must never break user code.\n */\nexport function stampAndPropagateSession(\n span: Span,\n sessionId: string | null | undefined,\n baseContext: Context = context.active(),\n): ISessionAttachResult {\n if (!sessionId) {\n return { context: baseContext, sessionId: null };\n }\n\n if (span.isRecording()) {\n try {\n span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);\n } catch (error) {\n logger.warn(\n `Brizz MCP: failed to stamp session id on span: ${String(error)}`,\n );\n }\n }\n\n try {\n const prev = baseContext.getValue(PROPERTIES_CONTEXT_KEY) as\n | Record<string, string>\n | undefined;\n const merged = prev\n ? { ...prev, [SESSION_ID]: sessionId }\n : { [SESSION_ID]: sessionId };\n return {\n context: baseContext.setValue(PROPERTIES_CONTEXT_KEY, merged),\n sessionId,\n };\n } catch (error) {\n logger.warn(`Brizz MCP: failed to attach session context: ${String(error)}`);\n return { context: baseContext, sessionId };\n }\n}\n","/**\n * MCP attribute keys consumed by the Brizz Go conversation processor at\n * `pkg/shared/conversation/span_processors/mcp_processor.go`. These are the\n * cross-SDK contract shared with the Python SDK's FastMCP instrumentation.\n */\n\n// MCP tool-call attributes (primary — consumed by `processMCP` to build conversation items).\nexport const MCP_TOOL_NAME = 'mcp.tool.name';\nexport const MCP_TOOL_ARGUMENTS = 'mcp.tool.arguments';\nexport const MCP_TOOL_RESULT = 'mcp.tool.result';\n\n// MCP component discriminator. `tool` narrows to tool-call subtype in the Go processor.\nexport const MCP_COMPONENT_TYPE = 'mcp.component.type';\nexport const MCP_COMPONENT_TOOL = 'tool';\n\n// MCP method / request metadata.\nexport const MCP_METHOD_NAME = 'mcp.method.name';\nexport const MCP_REQUEST_ID = 'mcp.request.id';\nexport const MCP_SESSION_ID = 'mcp.session.id';\nexport const MCP_PROTOCOL_VERSION = 'mcp.protocol.version';\nexport const MCP_RESOURCE_URI = 'mcp.resource.uri';\nexport const MCP_NOTIFICATION_METHOD = 'mcp.notification.method';\n\n// Cross-cutting semantic conventions.\nexport const RPC_SYSTEM = 'rpc.system';\nexport const RPC_SYSTEM_MCP = 'mcp';\nexport const RPC_RESPONSE_STATUS_CODE = 'rpc.response.status_code';\n\nexport const GEN_AI_TOOL_NAME = 'gen_ai.tool.name';\nexport const GEN_AI_PROMPT_NAME = 'gen_ai.prompt.name';\nexport const GEN_AI_OPERATION_NAME = 'gen_ai.operation.name';\nexport const GEN_AI_OPERATION_EXECUTE_TOOL = 'execute_tool';\n\nexport const NETWORK_TRANSPORT = 'network.transport';\n\nexport const ERROR_TYPE = 'error.type';\nexport const ERROR_TYPE_TOOL = 'tool_error';\nexport const ERROR_TYPE_TIMEOUT = 'timeout';\nexport const ERROR_TYPE_CANCELLED = 'cancelled';\n\nexport const JSONRPC_REQUEST_ID = 'jsonrpc.request.id';\n\n// Span name pieces matching the Go processor's detection\n// (`pkg/shared/conversation/span_processors/mcp_processor.go`).\nexport const SPAN_NAME_TOOLS_CALL = 'tools/call';\n\n// Serialization cap: tool payloads can be large; cap at ~32KB with a truncation suffix.\nexport const MAX_ATTRIBUTE_LENGTH = 32 * 1024;\nexport const TRUNCATION_SUFFIX = '…(truncated)';\n\n// MCP method names (only the ones with special handling).\nexport const METHOD_TOOLS_CALL = 'tools/call';\nexport const METHOD_RESOURCES_READ = 'resources/read';\nexport const METHOD_PROMPTS_GET = 'prompts/get';\nexport const METHOD_INITIALIZE = 'initialize';\n","/**\n * Pure attribute helpers for MCP spans. Kept separate from the patching code\n * so they can be unit-tested without a live Protocol instance.\n *\n * Every function here is try/catch-guarded at the call site — these helpers\n * are allowed to throw, but the caller should never let a telemetry error\n * surface into user code.\n */\n\nimport type { Span } from '@opentelemetry/api';\nimport { SpanStatusCode } from '@opentelemetry/api';\n\nimport {\n ERROR_TYPE,\n ERROR_TYPE_TOOL,\n GEN_AI_OPERATION_EXECUTE_TOOL,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROMPT_NAME,\n GEN_AI_TOOL_NAME,\n JSONRPC_REQUEST_ID,\n MAX_ATTRIBUTE_LENGTH,\n MCP_COMPONENT_TOOL,\n MCP_COMPONENT_TYPE,\n MCP_METHOD_NAME,\n MCP_PROTOCOL_VERSION,\n MCP_REQUEST_ID,\n MCP_RESOURCE_URI,\n MCP_SESSION_ID,\n MCP_TOOL_ARGUMENTS,\n MCP_TOOL_NAME,\n MCP_TOOL_RESULT,\n METHOD_INITIALIZE,\n METHOD_PROMPTS_GET,\n METHOD_RESOURCES_READ,\n METHOD_TOOLS_CALL,\n NETWORK_TRANSPORT,\n RPC_RESPONSE_STATUS_CODE,\n RPC_SYSTEM,\n RPC_SYSTEM_MCP,\n SPAN_NAME_TOOLS_CALL,\n TRUNCATION_SUFFIX,\n} from '../semantic-conventions.js';\nimport type { IJsonRpcRequest, IProtocolLike } from '../types.js';\n\n/**\n * Derive a span name from the JSON-RPC method + params.\n *\n * Matches the Go processor's detection in\n * `pkg/shared/conversation/span_processors/mcp_processor.go` — specifically\n * `tools/call <toolName>` is used to extract the tool name when\n * `mcp.tool.name` is absent.\n */\nexport function deriveSpanName(\n method: string,\n params?: Record<string, unknown>,\n): string {\n try {\n if (method === METHOD_TOOLS_CALL) {\n const name = typeof params?.['name'] === 'string' ? params['name'] : '';\n return name ? `${SPAN_NAME_TOOLS_CALL} ${name}` : SPAN_NAME_TOOLS_CALL;\n }\n if (method === METHOD_RESOURCES_READ) {\n const uri = typeof params?.['uri'] === 'string' ? params['uri'] : '';\n return uri ? `${METHOD_RESOURCES_READ} ${uri}` : METHOD_RESOURCES_READ;\n }\n if (method === METHOD_PROMPTS_GET) {\n const name = typeof params?.['name'] === 'string' ? params['name'] : '';\n return name ? `${METHOD_PROMPTS_GET} ${name}` : METHOD_PROMPTS_GET;\n }\n return method;\n } catch {\n return method || 'mcp';\n }\n}\n\n/**\n * Stamp the shared attributes that belong on both CLIENT and SERVER spans.\n */\nexport function applyBaseAttributes(span: Span, request: IJsonRpcRequest): void {\n span.setAttribute(RPC_SYSTEM, RPC_SYSTEM_MCP);\n if (request.method) {\n span.setAttribute(MCP_METHOD_NAME, request.method);\n }\n if (request.id !== undefined && request.id !== null) {\n const id = String(request.id);\n span.setAttribute(MCP_REQUEST_ID, id);\n span.setAttribute(JSONRPC_REQUEST_ID, id);\n }\n}\n\n/**\n * CLIENT-side request attributes.\n * Arize's transport patches inject W3C `traceparent` into `params._meta` —\n * we don't re-do that work; we just note the transport + method.\n */\nexport function applyClientRequestAttributes(\n span: Span,\n request: IJsonRpcRequest,\n transportName?: string,\n): void {\n applyBaseAttributes(span, request);\n applyMethodSpecificRequestAttributes(span, request);\n if (transportName) {\n const transport = normalizeTransport(transportName);\n if (transport) {\n span.setAttribute(NETWORK_TRANSPORT, transport);\n }\n }\n}\n\n/**\n * SERVER-side request attributes. On the server, tool arguments are captured\n * so the Go processor can populate the ConversationItem's `ToolInput` field.\n */\nexport function applyServerRequestAttributes(\n span: Span,\n request: IJsonRpcRequest,\n protocol: IProtocolLike,\n): void {\n applyBaseAttributes(span, request);\n applyMethodSpecificRequestAttributes(span, request);\n\n // Server-side tool.arguments — cheapest to capture on the server side\n // where we already have the parsed params.\n if (request.method === METHOD_TOOLS_CALL) {\n const args = request.params?.['arguments'];\n if (args !== undefined) {\n span.setAttribute(MCP_TOOL_ARGUMENTS, serializeForAttribute(args));\n }\n }\n\n const sessionId = protocol.sessionId ?? protocol._transport?.sessionId;\n if (sessionId) {\n span.setAttribute(MCP_SESSION_ID, String(sessionId));\n }\n}\n\nfunction applyMethodSpecificRequestAttributes(\n span: Span,\n request: IJsonRpcRequest,\n): void {\n const params = request.params ?? {};\n switch (request.method) {\n case METHOD_TOOLS_CALL: {\n const name = typeof params['name'] === 'string' ? params['name'] : '';\n if (name) {\n span.setAttribute(MCP_TOOL_NAME, name);\n span.setAttribute(GEN_AI_TOOL_NAME, name);\n }\n // Critical for the Go processor's tool-call subtype detection\n // (`mcp.component.type=tool` narrows from generic MCP spans).\n span.setAttribute(MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL);\n span.setAttribute(GEN_AI_OPERATION_NAME, GEN_AI_OPERATION_EXECUTE_TOOL);\n break;\n }\n case METHOD_RESOURCES_READ: {\n const uri = typeof params['uri'] === 'string' ? params['uri'] : '';\n if (uri) {\n span.setAttribute(MCP_RESOURCE_URI, uri);\n }\n break;\n }\n case METHOD_PROMPTS_GET: {\n const name = typeof params['name'] === 'string' ? params['name'] : '';\n if (name) {\n span.setAttribute(GEN_AI_PROMPT_NAME, name);\n }\n break;\n }\n default:\n break;\n }\n}\n\n/**\n * Apply attributes derived from the handler's resolved result. For tool calls\n * we also map `CallToolResult.isError === true` to a tool-level error.\n */\nexport function applyResultAttributes(\n span: Span,\n method: string,\n result: unknown,\n): void {\n if (method === METHOD_INITIALIZE && result && typeof result === 'object') {\n const protocolVersion = (result as Record<string, unknown>)[\n 'protocolVersion'\n ];\n if (typeof protocolVersion === 'string') {\n span.setAttribute(MCP_PROTOCOL_VERSION, protocolVersion);\n }\n return;\n }\n\n if (method !== METHOD_TOOLS_CALL) {\n return;\n }\n\n const obj = result && typeof result === 'object' ? (result as Record<string, unknown>) : null;\n const content = obj?.['content'] ?? result;\n span.setAttribute(MCP_TOOL_RESULT, serializeForAttribute(content));\n\n if (obj && obj['isError'] === true) {\n span.setAttribute(ERROR_TYPE, ERROR_TYPE_TOOL);\n const message = extractToolErrorMessage(obj);\n span.setStatus({ code: SpanStatusCode.ERROR, message });\n }\n}\n\n/**\n * Error-path attributes. Distinguishes JSON-RPC errors (with numeric code),\n * timeouts, and generic thrown errors.\n */\nexport function applyErrorAttributes(span: Span, err: unknown): void {\n const error = err as { code?: unknown; name?: string; message?: string; constructor?: { name?: string } };\n const code = error?.code;\n if (typeof code === 'number') {\n span.setAttribute(RPC_RESPONSE_STATUS_CODE, code);\n span.setAttribute(ERROR_TYPE, String(code));\n } else if (error?.name === 'AbortError') {\n span.setAttribute(ERROR_TYPE, 'cancelled');\n } else if (error?.name === 'TimeoutError') {\n span.setAttribute(ERROR_TYPE, 'timeout');\n } else {\n span.setAttribute(\n ERROR_TYPE,\n error?.constructor?.name || error?.name || 'Error',\n );\n }\n\n try {\n span.recordException(error as Error);\n } catch {\n // recordException can fail for non-Error objects; ignore.\n }\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: typeof error?.message === 'string' ? error.message : undefined,\n });\n}\n\n/**\n * Serialize a value into a span-safe string.\n *\n * Order of attempts:\n * 1. Prefer `.content` for `CallToolResult`-shaped values — that's the\n * array the MCP SDK exposes to clients and is the most useful payload\n * to render in the Brizz dashboard.\n * 2. JSON-stringify if possible.\n * 3. Fall back to `String(value)` for anything else (BigInt, function, etc.).\n *\n * Always caps output at `MAX_ATTRIBUTE_LENGTH` with `TRUNCATION_SUFFIX`.\n */\nexport function serializeForAttribute(value: unknown): string {\n const raw = rawSerialize(value);\n if (raw.length <= MAX_ATTRIBUTE_LENGTH) {\n return raw;\n }\n return raw.slice(0, MAX_ATTRIBUTE_LENGTH - TRUNCATION_SUFFIX.length) + TRUNCATION_SUFFIX;\n}\n\nfunction rawSerialize(value: unknown): string {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'string') {\n return value;\n }\n try {\n return JSON.stringify(value);\n } catch {\n // Fall back to best-effort coercion. Using `Object.prototype.toString`\n // avoids `@typescript-eslint/no-base-to-string` for objects with the\n // default stringifier while still producing something span-safe.\n try {\n if (value === null || value === undefined) {\n return '';\n }\n const tag = Object.prototype.toString.call(value);\n return typeof (value as { toString?: () => unknown }).toString === 'function'\n ? // eslint-disable-next-line @typescript-eslint/no-base-to-string\n String(value)\n : tag;\n } catch {\n return '';\n }\n }\n}\n\nfunction extractToolErrorMessage(result: Record<string, unknown>): string | undefined {\n const content = result['content'];\n if (Array.isArray(content)) {\n for (const item of content) {\n if (item && typeof item === 'object') {\n const text = (item as Record<string, unknown>)['text'];\n if (typeof text === 'string') {\n return text;\n }\n }\n }\n }\n return undefined;\n}\n\nfunction normalizeTransport(ctorName: string): string | null {\n const name = ctorName.toLowerCase();\n if (name.includes('stdio')) {\n return 'stdio';\n }\n if (name.includes('sse')) {\n return 'sse';\n }\n if (name.includes('streamablehttp') || name.includes('http')) {\n return 'http';\n }\n return null;\n}\n","import type { Context, Span, Tracer } from '@opentelemetry/api';\nimport { context, propagation, SpanKind, trace } from '@opentelemetry/api';\n\nimport { logger } from '../../../logger.js';\nimport { stampAndPropagateSession } from '../session.js';\nimport type { IJsonRpcRequest, IProtocolLike, RequestHandler } from '../types.js';\n\nimport {\n applyClientRequestAttributes,\n applyErrorAttributes,\n applyResultAttributes,\n applyServerRequestAttributes,\n deriveSpanName,\n} from './attributes.js';\n\n/**\n * Opaque marker used to avoid double-patching the same prototype.\n *\n * Why a Symbol? The same module may be loaded from multiple places (tests +\n * production auto-init), and we want to tolerate re-patching gracefully\n * without losing references to the originals. A Symbol keyed on the prototype\n * is invisible to userland code and lets us detect \"already patched\" cheaply.\n */\nconst PATCHED_FLAG = Symbol('brizz.mcp.protocol-patched');\n\ntype PatchableProtocolProto = Record<PropertyKey, unknown> & {\n [PATCHED_FLAG]?: boolean;\n};\n\n/**\n * Patch `Protocol.prototype.request` (CLIENT span) and\n * `Protocol.prototype._onrequest` (SERVER span).\n *\n * **Why both `.request` and `._onrequest`, not just the transport:**\n * Arize's transport patches propagate W3C `traceparent` into `params._meta`\n * so parent/child traces can link, but they do NOT emit spans — that's why\n * Arize's package alone doesn't show up in the dashboard. We need spans on\n * both ends of the MCP hop:\n * - CLIENT span around `Protocol.request(...)` on the caller side\n * - SERVER span around `Protocol._onrequest(...)` dispatch on the callee\n *\n * **Why Protocol, not McpServer.registerTool:**\n * `Protocol._onrequest` is the single chokepoint for EVERY incoming method\n * (`tools/call`, `resources/read`, `prompts/get`, `initialize`, etc.). One\n * wrap covers them all — mirrors the Python SDK's `Tool._run` hook shape.\n * `McpServer.registerTool` would only catch tool calls.\n *\n * Idempotent — repeated calls against the same prototype are no-ops. Returns\n * `true` when the prototype was newly patched, `false` otherwise.\n */\nexport function patchProtocolPrototype(\n prototype: unknown,\n tracer: Tracer,\n): boolean {\n if (!prototype || typeof prototype !== 'object') {\n return false;\n }\n const proto = prototype as PatchableProtocolProto;\n if (proto[PATCHED_FLAG]) {\n logger.debug('Brizz MCP: Protocol.prototype already patched, skipping');\n return false;\n }\n\n const originalRequest = proto['request'];\n const originalOnRequest = proto['_onrequest'];\n\n if (typeof originalRequest === 'function') {\n proto['request'] = wrapRequest(originalRequest as (...args: unknown[]) => unknown, tracer);\n } else {\n logger.debug(\n 'Brizz MCP: Protocol.prototype.request missing — skipping CLIENT patch',\n );\n }\n\n if (typeof originalOnRequest === 'function') {\n proto['_onrequest'] = wrapOnRequest(\n originalOnRequest as (...args: unknown[]) => unknown,\n tracer,\n );\n } else {\n logger.debug(\n 'Brizz MCP: Protocol.prototype._onrequest missing — skipping SERVER patch',\n );\n }\n\n proto[PATCHED_FLAG] = true;\n return true;\n}\n\n/**\n * Wrap `Protocol.prototype.request(request, resultSchema, options)` — the\n * caller-side request dispatch on the MCP `Protocol` base class.\n *\n * Opens a CLIENT span, awaits the promise the original returns, maps the\n * resolved result (or thrown error) onto span attributes, and always ends\n * the span. Parent context is whatever's active at the call site; Arize's\n * transport patches will later inject W3C traceparent into `params._meta`\n * when the message leaves the process.\n *\n * Every step is try/catch-guarded — telemetry must never throw into user\n * code. If we fail to open the span for any reason, we pass straight\n * through to the original without instrumentation.\n */\nfunction wrapRequest(\n original: (...args: unknown[]) => unknown,\n tracer: Tracer,\n): (...args: unknown[]) => unknown {\n return function wrappedRequest(this: IProtocolLike, ...args: unknown[]) {\n const request = args[0] as IJsonRpcRequest | undefined;\n if (!request || typeof request !== 'object' || !request.method) {\n return original.apply(this, args);\n }\n\n const span = safeStartClientSpan(tracer, request, this);\n if (!span) {\n return original.apply(this, args);\n }\n\n return executeAroundSpan(span, request.method, () => {\n const ctx = trace.setSpan(context.active(), span);\n return context.with(ctx, () => original.apply(this, args));\n });\n };\n}\n\n/**\n * Wrap `Protocol.prototype._onrequest(request, extra)` — the callee-side\n * handler dispatch.\n *\n * `_onrequest` is fire-and-forget: it doesn't return the handler's result\n * (it kicks off an internal Promise chain and writes the response to the\n * transport). To capture the result for `mcp.tool.result`, we monkey-patch\n * the registered handler in `this._requestHandlers` with a span-wrapped\n * variant BEFORE delegating to the original `_onrequest`.\n *\n * **Race safety:** `_onrequest` synchronously looks up the handler at the\n * top of its body (`const handler = this._requestHandlers.get(method)`)\n * and captures it in the closure of the subsequent Promise chain. Because\n * JavaScript is single-threaded and there's no `await` between our swap\n * and the original's lookup, we can safely restore the original handler\n * synchronously after `original.call(this, ...)` returns. The wrapped\n * handler's closure already holds the original by value, so subsequent\n * restore is race-free.\n *\n * Parent context: Arize's transport patches already extract W3C traceparent\n * from `params._meta` when the message arrives and make it the active\n * context. We defensively re-extract here in case Arize is disabled or\n * somebody calls `_onrequest` outside a transport callback.\n */\nfunction wrapOnRequest(\n original: (...args: unknown[]) => unknown,\n tracer: Tracer,\n): (...args: unknown[]) => unknown {\n return function wrappedOnRequest(this: IProtocolLike, ...args: unknown[]) {\n const request = args[0] as IJsonRpcRequest | undefined;\n if (!request || typeof request !== 'object' || !request.method) {\n return original.apply(this, args);\n }\n\n const handlers = this._requestHandlers;\n if (!handlers || typeof handlers.get !== 'function') {\n return original.apply(this, args);\n }\n\n const method = request.method;\n const handler: RequestHandler | undefined =\n handlers.get(method) ?? this.fallbackRequestHandler;\n\n if (!handler) {\n // No handler → let original emit the MethodNotFound response.\n return original.apply(this, args);\n }\n\n const started = safeStartServerSpan(tracer, request, this);\n if (!started) {\n return original.apply(this, args);\n }\n const { span, spanCtx } = started;\n\n const wrappedHandler: RequestHandler = (req, extra) =>\n context.with(spanCtx, () => executeHandler(span, method, handler, req, extra));\n\n // Handler-substitution window: original `_onrequest` captures the\n // handler synchronously, so the swap + restore is race-free.\n const hadEntry = handlers.has(method);\n const prev = handlers.get(method);\n handlers.set(method, wrappedHandler);\n\n const usedFallback = !hadEntry && this.fallbackRequestHandler === handler;\n const fallbackPrev = usedFallback ? this.fallbackRequestHandler : undefined;\n if (usedFallback) {\n this.fallbackRequestHandler = wrappedHandler;\n }\n\n try {\n return original.apply(this, args);\n } finally {\n if (hadEntry) {\n handlers.set(method, prev as RequestHandler);\n } else {\n handlers.delete(method);\n }\n if (usedFallback) {\n this.fallbackRequestHandler = fallbackPrev;\n }\n }\n };\n}\n\n/**\n * Execute a function that returns a (possibly-thenable) result and make sure\n * the span gets result/error attributes + is ended exactly once.\n *\n * Kept as a single helper so both the CLIENT wrapper and the SERVER handler\n * wrapper share the lifecycle logic — reduces the surface for \"forgot to\n * end the span\" bugs.\n */\nfunction executeAroundSpan(\n span: Span,\n method: string,\n run: () => unknown,\n): unknown {\n let result: unknown;\n try {\n result = run();\n } catch (error) {\n safeApplyErrorAttributes(span, error);\n safeEnd(span);\n throw error;\n }\n\n if (!isThenable(result)) {\n safeApplyResultAttributes(span, method, result);\n safeEnd(span);\n return result;\n }\n\n return (result as Promise<unknown>).then(\n (value) => {\n safeApplyResultAttributes(span, method, value);\n safeEnd(span);\n return value;\n },\n (error: unknown) => {\n safeApplyErrorAttributes(span, error);\n safeEnd(span);\n throw error;\n },\n );\n}\n\n/**\n * Run the user's registered MCP handler inside the active span.\n *\n * Factored out because the handler can return synchronously OR a Promise,\n * and either way we want identical attribute stamping + span-end semantics.\n */\nfunction executeHandler(\n span: Span,\n method: string,\n handler: RequestHandler,\n req: unknown,\n extra: unknown,\n): unknown {\n return executeAroundSpan(span, method, () => handler(req, extra));\n}\n\n/**\n * Open the CLIENT span and apply pre-attributes. Returns the span or `null`\n * when anything goes wrong — the caller treats `null` as \"fall through to\n * the original, no instrumentation this call\".\n */\nfunction safeStartClientSpan(\n tracer: Tracer,\n request: IJsonRpcRequest,\n protocol: IProtocolLike,\n): Span | null {\n try {\n const spanName = deriveSpanName(request.method, request.params);\n const span = tracer.startSpan(spanName, { kind: SpanKind.CLIENT });\n applyClientRequestAttributes(\n span,\n request,\n protocol._transport?.constructor?.name,\n );\n return span;\n } catch (error) {\n logger.debug(`Brizz MCP: failed to open CLIENT span: ${String(error)}`);\n return null;\n }\n}\n\n/**\n * Open the SERVER span, apply pre-attributes, and compute the span-scoped\n * context (with `brizz.session.id` propagated to children via\n * `PROPERTIES_CONTEXT_KEY`). Returns both span + ctx because the caller\n * needs to run the handler inside that ctx. Returns `null` on any failure\n * so the caller can fall through to uninstrumented dispatch.\n */\nfunction safeStartServerSpan(\n tracer: Tracer,\n request: IJsonRpcRequest,\n protocol: IProtocolLike,\n): { span: Span; spanCtx: Context } | null {\n try {\n const parentCtx = extractParentContext(request);\n const spanName = deriveSpanName(request.method, request.params);\n const span = tracer.startSpan(\n spanName,\n { kind: SpanKind.SERVER },\n parentCtx,\n );\n applyServerRequestAttributes(span, request, protocol);\n\n const sessionId = protocol.sessionId ?? protocol._transport?.sessionId;\n const { context: sessCtx } = stampAndPropagateSession(span, sessionId, parentCtx);\n return { span, spanCtx: trace.setSpan(sessCtx, span) };\n } catch (error) {\n logger.debug(`Brizz MCP: failed to open SERVER span: ${String(error)}`);\n return null;\n }\n}\n\n/**\n * Extract the parent OTel context from `params._meta` when present.\n *\n * MCP's `params._meta` is the canonical carrier for W3C trace-context\n * (Arize's transport patches write `traceparent` / `tracestate` into\n * `_meta` on outgoing sends). Extracting here on the server side rebuilds\n * the link to the caller's trace even if Arize's transport patch is\n * disabled.\n */\nfunction extractParentContext(request: IJsonRpcRequest): Context {\n try {\n const meta = request.params?._meta;\n if (meta && typeof meta === 'object') {\n return propagation.extract(context.active(), meta as Record<string, unknown>);\n }\n } catch (error) {\n logger.debug(\n `Brizz MCP: failed to extract parent context from _meta: ${String(error)}`,\n );\n }\n return context.active();\n}\n\n/**\n * Duck-typed thenable check so we handle both native Promises and any\n * user-supplied PromiseLike value (some MCP handlers return Bluebird or\n * custom thenables; we don't want to end the span before they resolve).\n */\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n !!value &&\n (typeof value === 'object' || typeof value === 'function') &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\n/** Wrapper around `applyResultAttributes` that swallows attribute-write errors. */\nfunction safeApplyResultAttributes(span: Span, method: string, value: unknown): void {\n try {\n applyResultAttributes(span, method, value);\n } catch (error) {\n logger.debug(\n `Brizz MCP: failed to apply result attributes: ${String(error)}`,\n );\n }\n}\n\n/** Wrapper around `applyErrorAttributes` that swallows attribute-write errors. */\nfunction safeApplyErrorAttributes(span: Span, err: unknown): void {\n try {\n applyErrorAttributes(span, err);\n } catch (error) {\n logger.debug(\n `Brizz MCP: failed to apply error attributes: ${String(error)}`,\n );\n }\n}\n\n/** `span.end()` with a try/catch so SDK state corruption can't leak. */\nfunction safeEnd(span: Span): void {\n try {\n span.end();\n } catch (error) {\n logger.debug(`Brizz MCP: failed to end span: ${String(error)}`);\n }\n}\n","/**\n * SDK version injected at build time from package.json.\n * This constant is replaced by the bundler during the build process.\n */\ndeclare const __SDK_VERSION__: string;\n\n/**\n * Get the SDK version.\n * The version is injected at build time from package.json.\n *\n * @returns {string} - The SDK version (e.g., \"0.1.6\")\n */\nexport function getSDKVersion(): string {\n return __SDK_VERSION__;\n}\n","/**\n * Tracer name + version metadata for Brizz's MCP spans.\n *\n * Why a dedicated file: the Brizz tracer name is used in two places\n * (`MCPInstrumentation.constructor` for `trace.getTracer(...)`, and the\n * version attribute on emitted spans), and we want them in lockstep.\n * Exporting them as constants also lets the dashboard filter spans on\n * `@brizz/sdk/mcp` without magic strings scattered across modules.\n *\n * The version is read at build time from the SDK's `package.json` via\n * `getSDKVersion()`, so bumping the SDK version automatically rolls\n * forward the tracer-version attribute on newly emitted spans.\n */\nimport { getSDKVersion } from '../../version.js';\n\n/** Tracer name used for all SERVER / CLIENT spans emitted by this module. */\nexport const INSTRUMENTATION_NAME = '@brizz/sdk/mcp';\n\n/** Tracer version — kept in sync with the published SDK version. */\nexport const INSTRUMENTATION_VERSION = getSDKVersion();\n","import { MCPInstrumentation as BaseMCPInstrumentation } from '@arizeai/openinference-instrumentation-mcp';\nimport type { Tracer } from '@opentelemetry/api';\nimport { trace } from '@opentelemetry/api';\nimport type { Instrumentation, InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';\n\nimport { logger } from '../../logger.js';\n\nimport { patchProtocolPrototype } from './patches/protocol.js';\nimport type { IMCPManualModules } from './types.js';\nimport { INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION } from './version.js';\n\n/*\n * `MCPInstrumentation` — Brizz's subclass of\n * `@arizeai/openinference-instrumentation-mcp`'s `MCPInstrumentation`.\n *\n * Why subclass Arize instead of rewriting:\n * - Arize's class already patches `send`/`start` on all six MCP transport\n * prototypes (SSE + stdio + streamable-HTTP, client + server) for W3C\n * trace-context injection into `params._meta`. That's ~300 lines of\n * transport-specific code we don't need to reimplement.\n * - Calling `super.init()` inside our overridden `init()` gives us the\n * full 6-transport context-propagation set with zero custom code.\n * - Subclassing mirrors the Python SDK's\n * `BrizzMcpInstrumentor(McpInstrumentor)` pattern exactly, keeping\n * cross-language symmetry in how Brizz extends upstream instrumentations.\n *\n * What we add on top of Arize:\n * - A SEVENTH module definition for `@modelcontextprotocol/sdk/shared/protocol.js`\n * where we install SERVER + CLIENT span patches (see `patches/protocol.ts`).\n * - That single chokepoint covers every MCP method (`tools/call`,\n * `resources/read`, `prompts/get`, `initialize`, …) with one wrap —\n * matching the Python SDK's `Tool._run` single-point hook.\n *\n * ## Optional-dependency handling\n *\n * `@arizeai/openinference-instrumentation-mcp` and `@modelcontextprotocol/sdk`\n * are declared as `optionalDependencies`. If a user installs `@brizz/sdk`\n * without them (e.g. `--no-optional`), this module fails to load. That's\n * intentional and acceptable: callers (auto-init and registry) import this\n * module via dynamic `await import(...)` with a try/catch, so a missing\n * dep degrades to a debug log rather than breaking SDK import.\n *\n * Do NOT statically re-export this class from top-level `index.ts` — the\n * cascade would turn a missing optional dep into a hard SDK import error.\n * Advanced users who need the class directly should use\n * `Brizz.initialize({ instrumentModules: { mcp: {...} } })`.\n */\n\nconst PROTOCOL_MODULE_NAME = '@modelcontextprotocol/sdk/shared/protocol.js';\n// Supported MCP SDK range — `>=1.0.0` because that's when the SDK's\n// dual-ESM/CJS subpath exports stabilized. Bumped when the SDK rev makes\n// breaking changes to `Protocol.prototype`.\n// Kept aligned with the `@modelcontextprotocol/sdk` range declared in\n// package.json's optionalDependencies, so we only patch versions we test.\nconst PROTOCOL_SUPPORTED_VERSIONS = ['>=1.0.0 <2'];\n\n/**\n * Duck-typed MCP SDK module shape we read at patch time. We don't import\n * the real `Protocol` type because `@modelcontextprotocol/sdk` is an\n * optional runtime dep — the module object we receive from the\n * instrumentation loader is typed broadly here and validated structurally\n * inside `patchProtocolPrototype`.\n */\ntype ProtocolModule = {\n Protocol?: { prototype?: unknown };\n};\n\nexport class MCPInstrumentation extends BaseMCPInstrumentation {\n /**\n * Dedicated Brizz-named tracer for our SERVER + CLIENT spans.\n *\n * Why a separate tracer from the parent class's one: Arize's inherited\n * transport patches don't emit spans (they only inject propagation\n * headers), so using our own tracer here keeps Brizz spans attributed to\n * `@brizz/sdk/mcp` in the dashboard. The parent's `tracer` is a\n * `protected get` (no setter), so fighting it with assignment is the\n * wrong tool.\n */\n private readonly brizzTracer: Tracer;\n\n constructor(_config?: {\n exceptionLogger?: (error: Error) => void;\n instrumentationConfig?: InstrumentationConfig;\n }) {\n super({ instrumentationConfig: _config?.instrumentationConfig });\n this.brizzTracer = trace.getTracer(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION);\n }\n\n /**\n * Extend `super.init()` with our protocol-layer module definition.\n *\n * Arize's `init()` returns definitions for the six transport modules\n * (SSE client/server, stdio client/server, streamable-HTTP client/server)\n * whose `send`/`start` methods get patched for W3C trace-context\n * injection. We append one more: `@modelcontextprotocol/sdk/shared/protocol.js`\n * where our patches open SERVER/CLIENT spans around the handler + outgoing\n * request. If `super.init()` throws (unlikely but possible across Arize\n * versions), we gracefully degrade to protocol-only instrumentation.\n *\n * The cast at the end satisfies the parent's strongly-typed generic\n * without leaking the cast into call sites.\n */\n protected override init(): ReturnType<BaseMCPInstrumentation['init']> {\n let base: unknown;\n try {\n base = super.init() ?? [];\n } catch (error) {\n logger.warn(\n `Brizz MCP: base Arize init() failed — transport context propagation disabled: ${String(error)}`,\n );\n base = [];\n }\n const baseArr: InstrumentationNodeModuleDefinition[] = Array.isArray(base)\n ? (base as InstrumentationNodeModuleDefinition[])\n : [base as InstrumentationNodeModuleDefinition];\n\n const brizzDef = new InstrumentationNodeModuleDefinition(\n PROTOCOL_MODULE_NAME,\n PROTOCOL_SUPPORTED_VERSIONS,\n (module: ProtocolModule) => {\n this.patchProtocolModule(module);\n return module;\n },\n (module: ProtocolModule) => {\n this.unpatchProtocolModule(module);\n return module;\n },\n );\n\n return [...baseArr, brizzDef] as unknown as ReturnType<BaseMCPInstrumentation['init']>;\n }\n\n /**\n * Manually instrument MCP modules for Next.js/Webpack where the\n * auto-instrumentation module-load hook doesn't fire.\n *\n * Forwards the six transport module fields to the inherited Arize\n * `manuallyInstrument(...)` (context propagation) and applies our\n * protocol patch if `protocolModule` is provided (SERVER/CLIENT spans).\n * Both legs are try/catch-guarded — a failure in one shouldn't prevent\n * the other from taking effect.\n */\n public override manuallyInstrument(modules: IMCPManualModules): void {\n const {\n clientSSEModule,\n serverSSEModule,\n clientStdioModule,\n serverStdioModule,\n clientStreamableHTTPModule,\n serverStreamableHTTPModule,\n protocolModule,\n } = modules;\n\n try {\n super.manuallyInstrument({\n clientSSEModule: clientSSEModule as never,\n serverSSEModule: serverSSEModule as never,\n clientStdioModule: clientStdioModule as never,\n serverStdioModule: serverStdioModule as never,\n clientStreamableHTTPModule: clientStreamableHTTPModule as never,\n serverStreamableHTTPModule: serverStreamableHTTPModule as never,\n });\n } catch (error) {\n logger.warn(`Brizz MCP: Arize manuallyInstrument(...) failed: ${String(error)}`);\n }\n\n if (protocolModule) {\n try {\n this.patchProtocolModule(protocolModule as ProtocolModule);\n } catch (error) {\n logger.warn(\n `Brizz MCP: failed to manually patch Protocol module: ${String(error)}`,\n );\n }\n }\n }\n\n /**\n * Apply the SERVER + CLIENT patch to a loaded `protocol.js` module. Shared\n * by both the automatic module-load callback in `init()` and the manual\n * `manuallyInstrument(...)` path above so there's exactly one place that\n * calls `patchProtocolPrototype`.\n */\n private patchProtocolModule(module: ProtocolModule): void {\n const proto = module?.Protocol?.prototype;\n if (!proto) {\n logger.debug(\n 'Brizz MCP: module does not expose Protocol.prototype — skipping protocol patches',\n );\n return;\n }\n const ok = patchProtocolPrototype(proto, this.brizzTracer);\n if (ok) {\n logger.debug('Brizz MCP: patched Protocol.prototype for SERVER+CLIENT spans');\n }\n }\n\n /**\n * Unpatch is intentionally a no-op.\n *\n * `patchProtocolPrototype` wraps methods in place and sets a PATCHED_FLAG\n * Symbol on the prototype to prevent double-patching. Restoring the\n * originals would require us to hold references across module unloads,\n * which isn't a pattern we need — instrumentation rarely gets torn down\n * at runtime, and a process reload is the canonical way to detach.\n */\n private unpatchProtocolModule(_module: ProtocolModule): void {\n logger.debug(\n 'Brizz MCP: unpatch is a no-op — reload the process to cleanly detach',\n );\n }\n}\n\n/**\n * Narrow a runtime value to the OTel `Instrumentation` shape without\n * pulling Arize's type into the broader SDK type surface.\n *\n * Used by tests and by the registry when loading MCP via dynamic import —\n * we get back an `unknown` and use this predicate before pushing onto\n * the NodeSDK instrumentations array.\n */\nexport function isMCPInstrumentation(value: unknown): value is Instrumentation {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as { instrumentationName?: unknown }).instrumentationName === 'string'\n );\n}\n","/**\n * Barrel for the MCP instrumentation module.\n *\n * `@arizeai/openinference-instrumentation-mcp` and `@modelcontextprotocol/sdk`\n * are direct dependencies of `@brizz/sdk`, so this barrel is imported\n * statically by the registry. Keep it internal — exposing MCP types from\n * `src/index.ts` would force every consumer to install MCP transitive\n * type packages even when they don't use MCP.\n */\nexport { MCPInstrumentation, isMCPInstrumentation } from './instrumentation.js';\nexport type { IMCPManualModules, IMCPInstrumentationConfig } from './types.js';\n","// 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 type IMCPManualModules,\n} from './internal/instrumentation/index.js';\n\n// Re-export utility functions from their respective modules\nexport { emitEvent } from './internal/log/index.js';\nexport {\n getSpanExporter,\n getSpanProcessor,\n withSessionId,\n callWithSessionId,\n withProperties,\n callWithProperties,\n setCurrentSpanCustomProperties,\n Session,\n SessionTitle,\n startSession,\n startSessionTitle,\n getActiveSession,\n} 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';\nexport type { AttributeValue } from '@opentelemetry/api';\nexport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\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 { 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\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 // Disabled because @traceloop/instrumentation-openai wraps the same OpenAI\n // prototype with richer span attributes (gen_ai.input.messages /\n // gen_ai.output.messages). Leaving both enabled lets the official one win\n // and route content to log events instead of span attributes, leaving the\n // Brizz backend parser with no payload to read.\n '@opentelemetry/instrumentation-openai': { enabled: false },\n });\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: 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: 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 * Load MCP instrumentation via dynamic import so the optional `@arizeai/\n * openinference-instrumentation-mcp` + `@modelcontextprotocol/sdk` deps\n * aren't required at SDK-import time. Users who don't use MCP can install\n * `@brizz/sdk` without those packages and auto-init remains functional.\n *\n * Fire-and-forget: the instrumentation registers module-load hooks\n * internally via `registerInstrumentations`, so the result doesn't need\n * to be added to the NodeSDK instrumentations array.\n */\nfunction loadMCPInstrumentation(): void {\n void (async () => {\n try {\n const { MCPInstrumentation } = await import('./mcp/index.js');\n const mcp = new MCPInstrumentation({ exceptionLogger });\n registerInstrumentations({ instrumentations: [mcp] });\n logger.debug('Auto-loaded MCP instrumentation');\n } catch (error) {\n logger.debug(\n `MCP instrumentation not loaded (install @modelcontextprotocol/sdk and @arizeai/openinference-instrumentation-mcp if you want MCP support): ${String(error)}`,\n );\n }\n })();\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 // Step 3: Load MCP instrumentation via dynamic import (optional dep).\n loadMCPInstrumentation();\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","import type { AttributeValue } from '@opentelemetry/api';\nimport { 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 { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\n\nimport type { IResolvedBrizzConfig } from './config';\nimport { resolveConfig } from './config';\nimport { BRIZZ_SDK_LANGUAGE, BRIZZ_SDK_VERSION, SDK_LANGUAGE } from './constants';\nimport { type IInstrumentModules, InstrumentationRegistry } 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';\nimport { getSDKVersion } from './version';\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 /**\n * Application version, propagated as the `service.version` OpenTelemetry\n * resource attribute on every span, log, and metric.\n *\n * Shortcut for `resourceAttributes: { 'service.version': '...' }`. When both\n * are set, `appVersion` wins. Overridable via the `BRIZZ_APP_VERSION` env var.\n *\n * @example\n * ```typescript\n * // Pull it straight from package.json\n * import { version } from './package.json' with { type: 'json' };\n *\n * Brizz.initialize({\n * appName: 'my-app',\n * appVersion: version,\n * });\n * ```\n */\n appVersion?: 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 /** Deployment environment (e.g., 'production', 'staging', 'development') for OpenTelemetry resource attributes */\n environment?: string;\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 * Disable span exporting.\n *\n * When `true`, Brizz will not configure a span exporter or span processor, so no\n * spans are sent to Brizz. `NodeSDK` is still started (with an empty span-processors\n * list) and other telemetry — metrics and logs — keeps working. Useful for dev\n * environments, or when you want to keep the SDK API alive without emitting span data.\n *\n * Can also be enabled via the `BRIZZ_DISABLE_SPAN_EXPORTER=true` environment variable.\n *\n * @example\n * ```typescript\n * Brizz.initialize({\n * appName: 'my-app',\n * disableSpanExporter: true,\n * });\n * ```\n */\n disableSpanExporter?: boolean;\n /**\n * Additional OpenTelemetry resource attributes applied to all spans,\n * logs, and metrics. Use this for custom resource-level tags. Brizz-owned\n * keys (`service.name`, `brizz.sdk.version`, `brizz.sdk.language`,\n * `deployment.environment`) cannot be overridden here — set them via\n * `appName` / `environment`. For `service.version`, prefer the dedicated\n * `appVersion` option (which wins if both are set).\n *\n * The standard `OTEL_RESOURCE_ATTRIBUTES` environment variable is also\n * honored by the OpenTelemetry Node SDK out of the box, and is the\n * recommended way to provide these via environment config.\n *\n * @example\n * ```typescript\n * Brizz.initialize({\n * appName: 'my-app',\n * resourceAttributes: {\n * team: 'platform',\n * region: 'us-east-1',\n * },\n * });\n * ```\n */\n resourceAttributes?: Record<string, AttributeValue>;\n /**\n * Optional synchronous or asynchronous filter invoked once per span\n * just before export. Return `false` to drop the span. Return `true`\n * to keep it. Exceptions are caught and logged; the span passes through.\n *\n * Use this to drop health-check spans, spans from internal users,\n * debug spans, etc. For modifying span attributes, use the `masking` option.\n *\n * @example\n * ```typescript\n * Brizz.initialize({\n * appName: 'my-app',\n * beforeSendSpan: (span) => span.name !== 'health-check',\n * });\n * ```\n */\n beforeSendSpan?: (span: ReadableSpan) => boolean | Promise<boolean>;\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)}`, { cause: 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 // Merge user-provided resource attributes first, then apply Brizz-owned keys\n // on top so they always win on collisions (user cannot override service.name,\n // brizz.sdk.version, brizz.sdk.language, or deployment.environment).\n const resourceAttributes: Record<string, AttributeValue> = {\n ...resolvedConfig.resourceAttributes,\n 'service.name': resolvedConfig.appName,\n [BRIZZ_SDK_VERSION]: getSDKVersion(),\n [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE,\n };\n\n // Add environment attribute if specified\n if (resolvedConfig.environment) {\n resourceAttributes['deployment.environment'] = resolvedConfig.environment;\n }\n // appVersion takes precedence over user-supplied resourceAttributes['service.version']\n if (resolvedConfig.appVersion) {\n resourceAttributes['service.version'] = resolvedConfig.appVersion;\n }\n\n this._sdk = new NodeSDK({\n spanProcessors: resolvedConfig.disableSpanExporter ? [] : [getSpanProcessor()],\n metricReader: getMetricsReader(),\n resource: resourceFromAttributes(resourceAttributes),\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 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 { AttributeValue } from '@opentelemetry/api';\nimport type { NodeSDK } from '@opentelemetry/sdk-node';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\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 environment?: string;\n apiKey?: string;\n logLevel: LogLevel;\n nodeSDK?: NodeSDK | null;\n masking?: IMaskingConfig;\n resourceAttributes?: Record<string, AttributeValue>;\n beforeSendSpan?: (span: ReadableSpan) => boolean | Promise<boolean>;\n}\n\nexport function resolveConfig(options: IBrizzInitializeOptions): IResolvedBrizzConfig {\n // Resolve log level first so we can set it before other logging\n const envLogLevel =\n 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 appVersion: process.env['BRIZZ_APP_VERSION'] || options.appVersion,\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 disableSpanExporter:\n process.env['BRIZZ_DISABLE_SPAN_EXPORTER'] === 'true' || !!options.disableSpanExporter,\n environment: process.env['BRIZZ_ENVIRONMENT'] || options.environment,\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', { cause: error });\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","/**\n * Semantic conventions and constants for Brizz SDK.\n */\n\n/**\n * Brizz SDK resource attribute keys.\n * These keys are used to add metadata to OpenTelemetry resource attributes.\n */\nexport const BRIZZ_SDK_VERSION = 'brizz.sdk.version';\nexport const BRIZZ_SDK_LANGUAGE = 'brizz.sdk.language';\n\n/**\n * SDK language identifier.\n */\nexport const SDK_LANGUAGE = 'typescript';\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 { 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 { MCPInstrumentation } from './mcp';\nimport type { IMCPManualModules } from './mcp/types';\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 /** The @langchain/core/callbacks/manager module for instrumentation */\n callbackManagerModule?: unknown;\n };\n llamaindex?: unknown;\n chromadb?: unknown;\n qdrant?: unknown;\n together?: unknown;\n vercelAI?: unknown;\n /**\n * MCP (Model Context Protocol) modules — pass all the transport modules\n * your app uses plus `@modelcontextprotocol/sdk/shared/protocol.js`.\n */\n mcp?: IMCPManualModules;\n}\nexport type { IMCPManualModules } from './mcp/types';\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 {\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 ];\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 // Handle LangChain separately - dynamically imported to avoid requiring\n // @langchain/core for users who don't use LangChain.\n // Uses fire-and-forget: manuallyInstrument() patches the module directly,\n // so it doesn't need to be in the NodeSDK instrumentations array.\n if (this.manualModules?.langchain?.callbackManagerModule) {\n const callbackManagerModule = this.manualModules.langchain.callbackManagerModule;\n void (async () => {\n try {\n const { LangChainInstrumentation } =\n await import('@arizeai/openinference-instrumentation-langchain');\n const lcInst = new LangChainInstrumentation();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument\n lcInst.manuallyInstrument(callbackManagerModule as any);\n logger.debug('Manual instrumentation enabled for LangChain');\n } catch (error: unknown) {\n logger.error(\n `Failed to load LangChain instrumentation. Ensure @langchain/core is installed: ${String(error)}`,\n );\n }\n })();\n }\n\n // Handle MCP synchronously — the patch must land on `Protocol.prototype`\n // BEFORE the user creates any MCP server or client, so the async/fire-\n // and-forget pattern (used for LangChain) is wrong here.\n if (this.manualModules?.mcp) {\n try {\n new MCPInstrumentation({ exceptionLogger }).manuallyInstrument(this.manualModules.mcp);\n logger.debug('Manual instrumentation enabled for MCP');\n } catch (error: unknown) {\n logger.error(`Failed to apply MCP instrumentation: ${String(error)}`);\n }\n }\n }\n}\n","import type { AttributeValue } from '@opentelemetry/api';\nimport 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 { BRIZZ_SDK_LANGUAGE, BRIZZ_SDK_VERSION, SDK_LANGUAGE } from '../constants';\nimport { logger } from '../logger';\nimport { getSDKVersion } from '../version';\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 // Merge user-provided resource attributes first, then apply Brizz-owned\n // keys on top so they always win on collisions.\n const resourceAttributes: Record<string, AttributeValue> = {\n ...config.resourceAttributes,\n 'service.name': config.appName,\n [BRIZZ_SDK_VERSION]: getSDKVersion(),\n [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE,\n };\n\n // Add environment attribute if specified\n if (config.environment) {\n resourceAttributes['deployment.environment'] = config.environment;\n }\n // appVersion takes precedence over user-supplied resourceAttributes['service.version']\n if (config.appVersion) {\n resourceAttributes['service.version'] = config.appVersion;\n }\n\n const resource = resourceFromAttributes(resourceAttributes);\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 cause: error,\n });\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.toReversed()) {\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 { 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","// Use protobuf exporter instead of JSON to ensure correct trace ID encoding\n// JSON exporter sends hex strings which get misinterpreted as base64 by protojson.Unmarshal\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';\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 { BrizzSpanExporter } from './exporters/span-exporter';\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 if (config.disableSpanExporter) {\n logger.info(\n 'Span exporter disabled via disableSpanExporter; skipping exporter and processor setup',\n );\n this.spanExporter = null;\n this.spanProcessor = null;\n TracingModule.instance = this;\n return;\n }\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 = new BrizzSpanExporter(config.customSpanExporter, config);\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 const otlpExporter = new OTLPTraceExporter({\n url: tracesUrl,\n headers: config.headers,\n });\n this.spanExporter = new BrizzSpanExporter(otlpExporter, config);\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 const 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 this.spanProcessor = spanProcessor;\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 { AttributeValue } from '@opentelemetry/api';\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\nimport { resourceFromAttributes } from '@opentelemetry/resources';\nimport type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\n\nimport type { IResolvedBrizzConfig } from '../../config';\nimport { BRIZZ_SDK_LANGUAGE, BRIZZ_SDK_VERSION, SDK_LANGUAGE } from '../../constants';\nimport { logger } from '../../logger';\nimport { getSDKVersion } from '../../version';\n\n/**\n * A span exporter wrapper that ensures the correct `service.name` and Brizz SDK\n * resource attributes are present on every exported span, and applies an\n * optional per-span `beforeSendSpan` filter.\n *\n * This is needed when an external OTEL provider (e.g. Sentry) owns the TracerProvider\n * and sets a default `service.name` (like \"node\") that we cannot control.\n * Since `ReadableSpan.resource` is readonly, we intercept at the export layer\n * and create proxy spans with the correct resource.\n */\nexport class BrizzSpanExporter implements SpanExporter {\n private readonly _delegate: SpanExporter;\n private readonly _brizzResource;\n private readonly _beforeSendSpan?: (span: ReadableSpan) => boolean | Promise<boolean>;\n\n constructor(delegate: SpanExporter, config: IResolvedBrizzConfig) {\n this._delegate = delegate;\n\n // Merge user-provided resource attributes first, then apply Brizz-owned\n // keys on top so they always win on collisions.\n const resourceAttrs: Record<string, AttributeValue> = {\n ...config.resourceAttributes,\n 'service.name': config.appName,\n [BRIZZ_SDK_VERSION]: getSDKVersion(),\n [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE,\n };\n if (config.environment) {\n resourceAttrs['deployment.environment'] = config.environment;\n }\n // appVersion takes precedence over user-supplied resourceAttributes['service.version']\n if (config.appVersion) {\n resourceAttrs['service.version'] = config.appVersion;\n }\n this._brizzResource = resourceFromAttributes(resourceAttrs);\n this._beforeSendSpan = config.beforeSendSpan;\n }\n\n export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {\n if (spans.length === 0) {\n resultCallback({ code: ExportResultCode.SUCCESS });\n return;\n }\n\n // Patch the resource BEFORE running beforeSendSpan so the filter sees the\n // same resource attributes (service.name, service.version, user resourceAttributes, …)\n // that will actually be exported. Resource.merge(other) — \"other\" takes precedence,\n // so brizzResource wins on collisions (e.g. overrides external provider's\n // service.name=\"node\" with our configured appName) while preserving other attrs.\n const patchedSpans = spans.map((span) => ({\n ...span,\n resource: span.resource.merge(this._brizzResource),\n spanContext: span.spanContext.bind(span),\n }));\n\n const filter = this._beforeSendSpan;\n if (!filter) {\n this._delegate.export(patchedSpans, resultCallback);\n return;\n }\n\n // Evaluate filter per span; tolerate sync and async returns; fail-open on throws.\n const verdicts = patchedSpans.map((span) => {\n try {\n return Promise.resolve(filter(span));\n } catch (error) {\n logger.warn('beforeSendSpan threw; span will be kept', { error });\n return Promise.resolve(true);\n }\n });\n\n Promise.all(verdicts)\n .then((keep) => {\n const filtered = patchedSpans.filter((_, i) => keep[i] !== false);\n if (filtered.length === 0) {\n resultCallback({ code: ExportResultCode.SUCCESS });\n return;\n }\n this._delegate.export(filtered, resultCallback);\n return;\n })\n .catch((error: unknown) => {\n logger.warn('beforeSendSpan rejected; all spans will be kept', { error });\n this._delegate.export(patchedSpans, resultCallback);\n });\n }\n\n async shutdown(): Promise<void> {\n return this._delegate.shutdown();\n }\n\n async forceFlush(): Promise<void> {\n return this._delegate.forceFlush?.();\n }\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\n/**\n * Stamp context-propagated session-level `brizz.<key>` attributes on a span.\n */\nfunction applyContextAttributes(span: Span): void {\n const sessionProperties = context.active().getValue(PROPERTIES_CONTEXT_KEY);\n if (sessionProperties) {\n for (const [key, value] of Object.entries(sessionProperties)) {\n span.setAttribute(`${BRIZZ}.${key}`, value as AttributeValue);\n }\n }\n}\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\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 applyContextAttributes(span);\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 applyContextAttributes(span);\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, trace, SpanStatusCode } from '@opentelemetry/api';\nimport type { Span, AttributeValue } from '@opentelemetry/api';\n\nimport {\n BRIZZ,\n PROPERTIES_CONTEXT_KEY,\n SESSION_ID,\n SESSION_INPUT,\n SESSION_INPUT_CONTEXT,\n SESSION_OBJECT_CONTEXT_KEY,\n SESSION_OUTPUT,\n SESSION_OUTPUT_CONTEXT,\n SESSION_SPAN_NAME,\n SESSION_TITLE,\n SESSION_TITLE_GENERATION,\n SESSION_TITLE_SPAN_NAME,\n} from '../semantic-conventions';\n\n/**\n * Stamp `brizz.<key>` attributes on the currently active span.\n *\n * Unlike `withProperties` / `callWithProperties` this does NOT attach to\n * the OTel context and does NOT propagate to child spans — it edits only\n * the already-running span. Use it inside a framework-owned span\n * (e.g. an MCP tool handler) where you just want to tag the current span\n * with business attributes like tenant id, feature flags, etc.\n *\n * Silently no-ops when there's no active recording span or when the span\n * implementation rejects an attribute — telemetry helpers must never\n * break user code.\n *\n * @example\n * ```typescript\n * server.registerTool('echo', { ... }, async ({ text }) => {\n * setCurrentSpanCustomProperties({\n * 'company.id': 'acme-1',\n * 'company.name': 'ACME Tenant1',\n * });\n * return { content: [{ type: 'text', text }] };\n * });\n * ```\n */\nexport function setCurrentSpanCustomProperties(\n properties: Record<string, AttributeValue>,\n): void {\n const current = trace.getActiveSpan();\n if (!current || !current.isRecording()) {\n return;\n }\n for (const [key, value] of Object.entries(properties)) {\n try {\n current.setAttribute(`${BRIZZ}.${key}`, value);\n } catch {\n // Swallow: a broken telemetry attribute must not surface into user code.\n }\n }\n}\n\n/**\n * Immediately executes a function with custom properties in the context. All telemetry (traces, spans, events)\n * generated within the function will include these properties.\n *\n * @param properties - Key-value properties to include in all telemetry within the function\n * @param fn - Function to execute with properties context\n * @param thisArg - Value to use as `this` when calling the function (optional)\n * @param args - Arguments to pass to the function\n * @returns The return value of the function\n */\nexport function callWithProperties<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 const base = context.active();\n const prev = base.getValue(PROPERTIES_CONTEXT_KEY) as Record<string, string> | undefined;\n const merged = prev ? { ...prev, ...properties } : properties;\n const next = base.setValue(PROPERTIES_CONTEXT_KEY, merged);\n return context.with(next, fn, thisArg, ...args);\n}\n\n/**\n * Wraps a function to create a new function that will execute with custom properties in the context.\n * All telemetry (traces, spans, events) generated within the wrapped function will include these properties.\n *\n * @example\n * ```typescript\n * // Wrap a function to always execute with properties\n * const wrappedFn = withProperties({ userId: 'user-123', env: 'prod' }, myFunction);\n * const result = await wrappedFn(arg1, arg2);\n *\n * // Wrap a method with 'this' context\n * const wrappedMethod = withProperties({ feature: 'checkout' }, obj.method, obj);\n * const result = wrappedMethod(param);\n * ```\n *\n * @param properties - Key-value properties to include in all telemetry within the function\n * @param fn - Function to wrap with properties context\n * @param thisArg - Value to use as `this` when calling the function (optional)\n * @returns A wrapped function that will execute with properties context\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function withProperties<F extends (this: any, ...args: any[]) => any>(\n properties: { [name: string]: string },\n fn: F,\n thisArg?: ThisParameterType<F>,\n): F {\n return function wrapped(this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F> {\n\n return callWithProperties(\n properties,\n fn,\n thisArg !== undefined ? thisArg : this,\n ...args,\n ) as ReturnType<F>;\n } as F;\n}\n\n/**\n * Wraps a function to create a new function that will execute with session context.\n * All telemetry (traces, spans, events) generated within the wrapped function will include the session ID.\n *\n * @example\n * ```typescript\n * // Wrap a function to always execute with a session\n * const wrappedFn = withSessionId('session-123', myFunction);\n * const result = await wrappedFn(arg1, arg2);\n *\n * // Wrap a method with 'this' context\n * const wrappedMethod = withSessionId('session-456', obj.method, obj);\n * const result = wrappedMethod(param);\n *\n * // With extra properties propagated to all spans\n * const wrappedFn = withSessionId('session-123', myFunction, undefined, { userId: 'user-456' });\n * ```\n *\n * @param sessionId - Session identifier to include in all telemetry within the function\n * @param fn - Function to wrap with session context\n * @param thisArg - Value to use as `this` when calling the function (optional)\n * @param extraProperties - Additional key-value properties to propagate to all spans within the session (optional)\n * @returns A wrapped function that will execute with session context\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function withSessionId<F extends (this: any, ...args: any[]) => any>(\n sessionId: string,\n fn: F,\n thisArg?: ThisParameterType<F>,\n extraProperties?: Record<string, string>,\n): F {\n const properties = { [SESSION_ID]: sessionId, ...extraProperties };\n return withProperties(properties, fn, thisArg);\n}\n\n/**\n * Immediately executes a function with session context. All telemetry (traces, spans, events)\n * generated within the function will include the session ID.\n *\n * @example\n * ```typescript\n * // Basic usage with async function\n * await callWithSessionId('session-123', myAsyncFunction, null, arg1, arg2);\n *\n * // With method and 'this' context\n * const result = callWithSessionId('session-456', obj.method, obj, param);\n *\n * // Wrapping AI operations\n * const response = await callWithSessionId('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 callWithSessionId<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 callWithProperties({ [SESSION_ID]: sessionId }, fn, thisArg, ...args);\n}\n\n/**\n * Session object for managing session-level tracking.\n * All LLM calls within a session are automatically linked.\n * Optionally use setInput/setOutput to track specific data.\n *\n * @example\n * ```typescript\n * startSession('session-123', (session) => {\n * session.updateProperties({ userId: 'user-456' });\n * // All LLM calls here are automatically linked\n * const response = await llm.complete(...);\n * // Optionally track specific input/output\n * // session.setInput('user query');\n * // session.setOutput('response text');\n * });\n * ```\n */\nexport class Session {\n public readonly sessionId: string;\n private readonly span: Span;\n private inputs: (string | null)[] = [];\n private outputs: (string | null)[] = [];\n private inputContexts: Record<string, AttributeValue>[] = [];\n private outputContexts: Record<string, AttributeValue>[] = [];\n\n constructor(sessionId: string, span: Span) {\n this.sessionId = sessionId;\n this.span = span;\n }\n\n /**\n * Append a user turn to session input tracking.\n *\n * Each call appends one element to `brizz.session.input` (the text) AND one\n * element to `brizz.session.input.context` (the per-turn context bag). The\n * two arrays stay index-aligned — the ingestion pipeline zips them together\n * so the i-th context bag lands on the i-th user_display conversation item's\n * `span_attributes` map.\n *\n * @param text - Text to append (null becomes a null/\"hide marker\")\n * @param context - Optional per-turn context bag to attach to this turn\n */\n setInput(text: string | null, context?: Record<string, AttributeValue>): void {\n this.inputs.push(text);\n this.inputContexts.push(context ?? {});\n this.span.setAttribute(SESSION_INPUT, JSON.stringify(this.inputs));\n this.span.setAttribute(SESSION_INPUT_CONTEXT, JSON.stringify(this.inputContexts));\n }\n\n /**\n * Append an assistant turn to session output tracking.\n *\n * Symmetric to {@link setInput} — appends one text element and one\n * context-bag element to the index-aligned `brizz.session.output` /\n * `brizz.session.output.context` arrays.\n *\n * @param text - Text to append (null becomes a null/\"hide marker\")\n * @param context - Optional per-turn context bag to attach to this turn\n */\n setOutput(text: string | null, context?: Record<string, AttributeValue>): void {\n this.outputs.push(text);\n this.outputContexts.push(context ?? {});\n this.span.setAttribute(SESSION_OUTPUT, JSON.stringify(this.outputs));\n this.span.setAttribute(SESSION_OUTPUT_CONTEXT, JSON.stringify(this.outputContexts));\n }\n\n /**\n * Set the session title on the span.\n *\n * @param title - The generated title string\n */\n setTitle(title: string): void {\n this.span.setAttribute(SESSION_TITLE, title);\n }\n\n /**\n * Update custom properties on the session span.\n * Properties are prefixed with 'brizz.'.\n *\n * @param properties - Key-value properties to set on the session\n */\n updateProperties(properties: Record<string, AttributeValue>): void {\n for (const [key, value] of Object.entries(properties)) {\n this.span.setAttribute(`${BRIZZ}.${key}`, value);\n }\n }\n}\n\n/**\n * Title generation scope object for setting the session title.\n *\n * @example\n * ```typescript\n * await startSessionTitle(async (title) => {\n * const generated = await llm.generateTitle(conversation);\n * title.setTitle(generated);\n * });\n * ```\n */\nexport class SessionTitle {\n private readonly span: Span;\n\n constructor(span: Span) {\n this.span = span;\n }\n\n /**\n * Set the generated title on the wrapper span.\n *\n * @param title - The generated title string\n */\n setTitle(title: string): void {\n this.span.setAttribute(SESSION_TITLE, title);\n }\n}\n\n/**\n * Get the active session from the current context.\n *\n * Returns the Session object if called within a startSession scope,\n * otherwise returns undefined.\n *\n * @example\n * ```typescript\n * function deepHelper() {\n * const session = getActiveSession();\n * session?.updateProperties({ step: 'helper' });\n * }\n *\n * startSession('my-session', (session) => {\n * deepHelper(); // can access session without passing it\n * });\n * ```\n */\nexport function getActiveSession(): Session | undefined {\n return context.active().getValue(SESSION_OBJECT_CONTEXT_KEY) as Session | undefined;\n}\n\n/**\n * Execute a function within a session context.\n * Creates a span that tracks the session and provides a Session object\n * for input/output recording.\n *\n * @example\n * ```typescript\n * // Sync usage\n * const result = startSession('session-123', (session) => {\n * session.setInput('user query');\n * const response = processQuery();\n * session.setOutput(response);\n * return response;\n * });\n *\n * // Async usage\n * const result = await startSession('session-456', async (session) => {\n * session.setInput('user query');\n * const response = await llm.complete('...');\n * session.setOutput(response.text);\n * return response;\n * });\n *\n * // With extra properties on the session span and propagated to child spans\n * const result = await startSession('session-789', async (session) => {\n * const response = await llm.complete('...');\n * return response;\n * }, { userId: 'user-456', feature: 'chat' });\n * ```\n *\n * @param sessionId - Session identifier to associate with telemetry\n * @param callback - Function to execute within the session context\n * @param extraProperties - Additional properties to set on the session span and propagate to child spans (optional)\n * @returns The return value of the callback function\n */\nexport function startSession<T>(\n sessionId: string,\n callback: (session: Session) => T,\n extraProperties?: Record<string, AttributeValue>,\n options?: { mode?: 'default' | 'title' },\n): T {\n const isTitle = options?.mode === 'title';\n const spanName = isTitle ? SESSION_TITLE_SPAN_NAME : SESSION_SPAN_NAME;\n const tracer = trace.getTracer('@brizz/sdk');\n return tracer.startActiveSpan(spanName, (span) => {\n span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);\n\n // Set extra properties on the span (with brizz. prefix)\n if (extraProperties) {\n for (const [key, value] of Object.entries(extraProperties)) {\n span.setAttribute(`${BRIZZ}.${key}`, value);\n }\n }\n\n const session = new Session(sessionId, span);\n\n // Build context properties (strings only for context propagation)\n const contextProperties: Record<string, string> = { [SESSION_ID]: sessionId };\n if (isTitle) {\n contextProperties[SESSION_TITLE_GENERATION] = 'true';\n }\n if (extraProperties) {\n for (const [key, value] of Object.entries(extraProperties)) {\n contextProperties[key] = String(value);\n }\n }\n\n // Propagate session ID and extra properties through context so nested operations can access them\n return callWithProperties(contextProperties, () => {\n const sessionCtx = context.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);\n return context.with(sessionCtx, () => {\n try {\n const result = callback(session);\n // Handle async callbacks using thenable duck-type check (more reliable than instanceof Promise)\n if (result && typeof (result as { then?: unknown }).then === 'function') {\n return (result as unknown as Promise<unknown>)\n .then((value) => {\n span.end();\n return value;\n })\n .catch((error: unknown) => {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.end();\n throw error;\n }) as T;\n }\n span.end();\n return result;\n } catch (error) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.end();\n throw error;\n }\n });\n });\n });\n}\n\n/**\n * Execute a function within a session title generation scope.\n * All LLM/AI spans created within this scope will be marked as title generation\n * spans and excluded from the conversation view.\n *\n * @example\n * ```typescript\n * await startSessionTitle(async (title) => {\n * const generated = await llm.generateTitle(conversation);\n * title.setTitle(generated);\n * });\n * ```\n *\n * @param callback - Function to execute within the title generation scope\n * @returns The return value of the callback function\n */\nexport function startSessionTitle<T>(\n callback: (title: SessionTitle) => T,\n options?: { sessionId?: string },\n): T {\n const resolvedSessionId = options?.sessionId ?? getActiveSession()?.sessionId;\n const tracer = trace.getTracer('@brizz/sdk');\n return tracer.startActiveSpan(SESSION_TITLE_SPAN_NAME, (span) => {\n if (resolvedSessionId) {\n span.setAttribute(`${BRIZZ}.${SESSION_ID}`, resolvedSessionId);\n }\n const sessionTitle = new SessionTitle(span);\n\n const properties: Record<string, string> = { [SESSION_TITLE_GENERATION]: 'true' };\n if (resolvedSessionId) {\n properties[SESSION_ID] = resolvedSessionId;\n }\n return callWithProperties(properties, () => {\n try {\n const result = callback(sessionTitle);\n if (result && typeof (result as { then?: unknown }).then === 'function') {\n return (result as unknown as Promise<unknown>)\n .then((value) => {\n span.end();\n return value;\n })\n .catch((error: unknown) => {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.end();\n throw error;\n }) as T;\n }\n span.end();\n return result;\n } catch (error) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.end();\n throw error;\n }\n });\n });\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 ||\n ((major ?? 0) === 20 && (minor ?? 0) >= 6) ||\n ((major ?? 0) === 18 && (minor ?? 0) >= 19);\n const supportsRegister =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n !!(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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2KO,SAAS,cAAc,OAA0B;AACtD,MAAI,CAAC,OAAO;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,WAAmB,QAAQ;AAAA;AAE3E,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;AAAA,MAE5B,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;;;AC1EA;","names":["LogLevel","pino","import_api","import_api","init_semantic_conventions","import_api","init_semantic_conventions","import_api","init_version","import_api","init_version","BaseMCPInstrumentation","module","import_instrumentation","MCPInstrumentation","import_resources","import_instrumentation_anthropic","import_instrumentation_bedrock","import_instrumentation_chromadb","import_instrumentation_cohere","import_instrumentation_llamaindex","import_instrumentation_openai","import_instrumentation_pinecone","import_instrumentation_qdrant","import_instrumentation_together","import_instrumentation_vertexai","exceptionLogger","import_sdk_logs","import_api","import_resources","import_api","import_api","context","import_api_logs"]}
|