@brizz/sdk 0.1.29 → 0.1.30

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/preload.js CHANGED
@@ -1,2441 +1,16 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
- // src/internal/logger.ts
9
- import { DiagLogLevel } from "@opentelemetry/api";
10
- import pino from "pino";
11
- var DEFAULT_LOG_LEVEL = 2 /* WARN */;
12
- var PinoLogger = class {
13
- _level = DEFAULT_LOG_LEVEL;
14
- _pinoLogger = null;
15
- constructor() {
16
- const envLevel = this.getLogLevelFromEnv();
17
- this._level = envLevel;
18
- }
19
- /**
20
- * Lazy initialization of Pino logger to ensure it's created AFTER Jest spies
21
- * are set up during tests. This prevents the pino-pretty transport from
22
- * bypassing stdout/stderr spies.
23
- */
24
- ensurePinoLogger() {
25
- if (!this._pinoLogger) {
26
- this._pinoLogger = pino({
27
- name: "Brizz",
28
- level: this.logLevelToPino(this._level),
29
- // Disable transport in test environment to allow proper spy capture
30
- transport: this.isProduction() || this.isTest() ? void 0 : {
31
- target: "pino-pretty",
32
- options: {
33
- singleLine: true,
34
- colorize: true,
35
- translateTime: "HH:MM:ss",
36
- ignore: "pid,hostname",
37
- messageFormat: "[{name}] {msg}"
38
- }
39
- }
40
- });
41
- }
42
- return this._pinoLogger;
43
- }
44
- isProduction() {
45
- return process.env["NODE_ENV"] === "production";
46
- }
47
- isTest() {
48
- return process.env["NODE_ENV"] === "test";
49
- }
50
- getLogLevelFromEnv() {
51
- const envLevel = process.env["BRIZZ_LOG_LEVEL"];
52
- return envLevel ? parseLogLevel(envLevel) : DEFAULT_LOG_LEVEL;
53
- }
54
- logLevelToPino(level) {
55
- switch (level) {
56
- case 4 /* DEBUG */:
57
- return "debug";
58
- case 3 /* INFO */:
59
- return "info";
60
- case 2 /* WARN */:
61
- return "warn";
62
- case 1 /* ERROR */:
63
- return "error";
64
- default:
65
- return "silent";
66
- }
67
- }
68
- formatMeta(meta) {
69
- if (meta.length === 0) {
70
- return {};
71
- }
72
- if (meta.length === 1 && typeof meta[0] === "object" && meta[0] !== null) {
73
- return meta[0];
74
- }
75
- return { metadata: meta };
76
- }
77
- setLevel(level) {
78
- this._level = level;
79
- if (this._pinoLogger) {
80
- this._pinoLogger.level = this.logLevelToPino(level);
81
- }
82
- }
83
- getLevel() {
84
- return this._level;
85
- }
86
- debug = (msg, ...meta) => {
87
- if (this._level >= 4 /* DEBUG */) {
88
- this.ensurePinoLogger().debug(this.formatMeta(meta), msg);
89
- }
90
- };
91
- info = (msg, ...meta) => {
92
- if (this._level >= 3 /* INFO */) {
93
- this.ensurePinoLogger().info(this.formatMeta(meta), msg);
94
- }
95
- };
96
- warn = (msg, ...meta) => {
97
- if (this._level >= 2 /* WARN */) {
98
- this.ensurePinoLogger().warn(this.formatMeta(meta), msg);
99
- }
100
- };
101
- error = (msg, ...meta) => {
102
- if (this._level >= 1 /* ERROR */) {
103
- this.ensurePinoLogger().error(this.formatMeta(meta), msg);
104
- }
105
- };
106
- };
107
- function parseLogLevel(level) {
108
- if (!level) {
109
- return DEFAULT_LOG_LEVEL;
110
- }
111
- const normalizedLevel = level.toLowerCase().trim();
112
- switch (normalizedLevel) {
113
- case "debug":
114
- return 4 /* DEBUG */;
115
- case "info":
116
- return 3 /* INFO */;
117
- case "warn":
118
- case "warning":
119
- return 2 /* WARN */;
120
- case "error":
121
- return 1 /* ERROR */;
122
- case "none":
123
- case "off":
124
- case "silent":
125
- return 0 /* NONE */;
126
- default: {
127
- const numLevel = Number.parseInt(normalizedLevel, 10);
128
- if (!Number.isNaN(numLevel) && numLevel >= 0 && numLevel <= 4) {
129
- return numLevel;
130
- }
131
- return DEFAULT_LOG_LEVEL;
132
- }
133
- }
134
- }
135
- var logger = new PinoLogger();
136
- function setLogLevel(level) {
137
- const resolvedLevel = typeof level === "string" ? parseLogLevel(level) : level;
138
- logger.setLevel(resolvedLevel);
139
- }
140
-
141
- // src/internal/sdk.ts
142
- import { resourceFromAttributes as resourceFromAttributes3 } from "@opentelemetry/resources";
143
- import { NodeSDK } from "@opentelemetry/sdk-node";
144
-
145
- // src/internal/dsn.ts
146
- var PLACEHOLDER_SERVICE = "<service-name>";
147
- var SERVICE_NAME_HEADER = "X-Brizz-Service-Name";
148
- function parseDSN(dsn) {
149
- let parsed;
150
- try {
151
- parsed = new globalThis.URL(dsn);
152
- } catch {
153
- return null;
154
- }
155
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || !parsed.username || !parsed.host) {
156
- return null;
157
- }
158
- const scheme = parsed.protocol === "https:" ? "https" : "http";
159
- let service;
160
- try {
161
- service = decodeURIComponent(parsed.pathname.replace(/^\//, ""));
162
- } catch {
163
- return null;
164
- }
165
- if (service === "" || service === PLACEHOLDER_SERVICE) {
166
- return null;
167
- }
168
- return {
169
- scheme,
170
- host: parsed.host,
171
- bearer: decodeURIComponent(parsed.username),
172
- service,
173
- baseUrl: `${scheme}://${parsed.host}`
174
- };
175
- }
176
-
177
- // src/internal/config.ts
178
- function resolveConfig(options) {
179
- const envLogLevel = process.env["BRIZZ_LOG_LEVEL"] || options.logLevel?.toString() || DEFAULT_LOG_LEVEL.toString();
180
- let resolvedLogLevel;
181
- if (envLogLevel) {
182
- resolvedLogLevel = parseLogLevel(envLogLevel);
183
- } else if (typeof options.logLevel === "string") {
184
- resolvedLogLevel = parseLogLevel(options.logLevel);
185
- } else {
186
- resolvedLogLevel = options.logLevel || DEFAULT_LOG_LEVEL;
187
- }
188
- setLogLevel(resolvedLogLevel);
189
- let maskingStatus;
190
- if (options.masking === true) {
191
- maskingStatus = "enabled";
192
- } else if (options.masking === false) {
193
- maskingStatus = "disabled";
194
- } else if (typeof options.masking === "object") {
195
- maskingStatus = "custom";
196
- } else {
197
- maskingStatus = "default-disabled";
198
- }
199
- logger.debug("Starting configuration resolution", {
200
- appName: options.appName,
201
- baseUrl: options.baseUrl,
202
- hasApiKey: !!options.apiKey,
203
- dsnProvided: !!(process.env["BRIZZ_DSN"] || options.dsn),
204
- disableBatch: options.disableBatch,
205
- logLevel: resolvedLogLevel,
206
- headersCount: Object.keys(options.headers || {}).length,
207
- masking: maskingStatus
208
- });
209
- let resolvedMasking;
210
- if (options.masking === true) {
211
- resolvedMasking = {
212
- spanMasking: {},
213
- eventMasking: {}
214
- };
215
- } else if (options.masking && typeof options.masking === "object") {
216
- resolvedMasking = options.masking;
217
- }
218
- const resolvedConfig = {
219
- ...options,
220
- appName: process.env["BRIZZ_APP_NAME"] || options.appName || "unknown-app",
221
- appVersion: process.env["BRIZZ_APP_VERSION"] || options.appVersion,
222
- baseUrl: process.env["BRIZZ_BASE_URL"] || options.baseUrl || "https://telemetry.brizz.dev",
223
- headers: { ...options.headers },
224
- apiKey: process.env["BRIZZ_API_KEY"] || options.apiKey,
225
- disableBatch: process.env["BRIZZ_DISABLE_BATCH"] === "true" || !!options.disableBatch,
226
- disableSpanExporter: process.env["BRIZZ_DISABLE_SPAN_EXPORTER"] === "true" || !!options.disableSpanExporter,
227
- environment: process.env["BRIZZ_ENVIRONMENT"] || options.environment,
228
- logLevel: resolvedLogLevel,
229
- masking: resolvedMasking
230
- };
231
- const dsnInput = process.env["BRIZZ_DSN"] || options.dsn;
232
- let parsedDSN = null;
233
- if (dsnInput) {
234
- const kwargConflicts = [];
235
- if (options.apiKey !== void 0) {
236
- kwargConflicts.push("apiKey");
237
- }
238
- if (options.baseUrl !== void 0) {
239
- kwargConflicts.push("baseUrl");
240
- }
241
- if (options.appName !== void 0) {
242
- kwargConflicts.push("appName");
243
- }
244
- if (kwargConflicts.length > 0) {
245
- throw new Error(
246
- `dsn cannot be combined with kwargs ${kwargConflicts.join(", ")}. The DSN bundles bearer, gateway URL, and service name \u2014 choose one configuration style.`
247
- );
248
- }
249
- const envConflicts = ["BRIZZ_API_KEY", "BRIZZ_BASE_URL", "BRIZZ_APP_NAME"].filter(
250
- (name) => process.env[name] !== void 0
251
- );
252
- if (envConflicts.length > 0) {
253
- logger.warn(
254
- `Ignoring ${envConflicts.join(", ")} \u2014 dsn / BRIZZ_DSN takes precedence.`
255
- );
256
- }
257
- resolvedConfig.apiKey = void 0;
258
- resolvedConfig.baseUrl = "https://telemetry.brizz.dev";
259
- resolvedConfig.appName = "unknown-app";
260
- parsedDSN = parseDSN(dsnInput);
261
- if (parsedDSN) {
262
- resolvedConfig.appName = parsedDSN.service;
263
- resolvedConfig.baseUrl = parsedDSN.baseUrl;
264
- resolvedConfig.apiKey = parsedDSN.bearer;
265
- }
266
- } else if (resolvedConfig.apiKey) {
267
- resolvedConfig.headers["Authorization"] = `Bearer ${resolvedConfig.apiKey}`;
268
- }
269
- if (process.env["BRIZZ_HEADERS"]) {
270
- try {
271
- const envHeaders = JSON.parse(process.env["BRIZZ_HEADERS"]);
272
- Object.assign(resolvedConfig.headers, envHeaders);
273
- logger.debug("Added headers from environment variable", {
274
- headers: Object.keys(envHeaders)
275
- });
276
- } catch (error) {
277
- logger.error("Failed to parse BRIZZ_HEADERS environment variable", { error });
278
- throw new Error("Invalid JSON in BRIZZ_HEADERS environment variable", { cause: error });
279
- }
280
- }
281
- if (dsnInput) {
282
- const authHeaderKeys = /* @__PURE__ */ new Set(["authorization", SERVICE_NAME_HEADER.toLowerCase()]);
283
- resolvedConfig.headers = Object.fromEntries(
284
- Object.entries(resolvedConfig.headers).filter(
285
- ([key]) => !authHeaderKeys.has(key.toLowerCase())
286
- )
287
- );
288
- if (parsedDSN) {
289
- resolvedConfig.headers["Authorization"] = `Bearer ${parsedDSN.bearer}`;
290
- resolvedConfig.headers[SERVICE_NAME_HEADER] = parsedDSN.service;
291
- }
292
- }
293
- logger.debug("Configuration resolved with environment variables", {
294
- appName: resolvedConfig.appName,
295
- baseUrl: resolvedConfig.baseUrl,
296
- hasApiKey: !!resolvedConfig.apiKey,
297
- dsnProvided: !!dsnInput,
298
- disableBatch: resolvedConfig.disableBatch,
299
- envOverrides: {
300
- hasEnvApiKey: !!process.env["BRIZZ_API_KEY"],
301
- hasEnvBaseUrl: !!process.env["BRIZZ_BASE_URL"],
302
- hasEnvDsn: !!process.env["BRIZZ_DSN"],
303
- hasEnvBatch: !!process.env["BRIZZ_DISABLE_BATCH"],
304
- hasEnvHeaders: !!process.env["BRIZZ_HEADERS"]
305
- }
306
- });
307
- return resolvedConfig;
308
- }
309
-
310
- // src/internal/constants.ts
311
- var BRIZZ_SDK_VERSION = "brizz.sdk.version";
312
- var BRIZZ_SDK_LANGUAGE = "brizz.sdk.language";
313
- var SDK_LANGUAGE = "typescript";
314
-
315
- // src/internal/instrumentation/registry.ts
316
- import { AnthropicInstrumentation } from "@traceloop/instrumentation-anthropic";
317
- import { BedrockInstrumentation } from "@traceloop/instrumentation-bedrock";
318
- import { ChromaDBInstrumentation } from "@traceloop/instrumentation-chromadb";
319
- import { CohereInstrumentation } from "@traceloop/instrumentation-cohere";
320
- import { LlamaIndexInstrumentation } from "@traceloop/instrumentation-llamaindex";
321
- import { OpenAIInstrumentation } from "@traceloop/instrumentation-openai";
322
- import { PineconeInstrumentation } from "@traceloop/instrumentation-pinecone";
323
- import { QdrantInstrumentation } from "@traceloop/instrumentation-qdrant";
324
- import { TogetherInstrumentation } from "@traceloop/instrumentation-together";
325
- import { VertexAIInstrumentation } from "@traceloop/instrumentation-vertexai";
326
-
327
- // src/internal/instrumentation/mcp/instrumentation.ts
328
- import { MCPInstrumentation as BaseMCPInstrumentation } from "@arizeai/openinference-instrumentation-mcp";
329
- import { trace as trace2 } from "@opentelemetry/api";
330
- import { InstrumentationNodeModuleDefinition } from "@opentelemetry/instrumentation";
331
-
332
- // src/internal/instrumentation/mcp/patches/protocol.ts
333
- import { context as context2, propagation, SpanKind as SpanKind2, trace } from "@opentelemetry/api";
334
-
335
- // src/internal/instrumentation/mcp/schemas.ts
336
- import { SpanKind, SpanStatusCode } from "@opentelemetry/api";
337
-
338
- // src/internal/instrumentation/mcp/semantic-conventions.ts
339
- var MCP_TOOL_NAME = "mcp.tool.name";
340
- var MCP_TOOL_ARGUMENTS = "mcp.tool.arguments";
341
- var MCP_TOOL_RESULT = "mcp.tool.result";
342
- var MCP_COMPONENT_TYPE = "mcp.component.type";
343
- var MCP_COMPONENT_TOOL = "tool";
344
- var MCP_COMPONENT_TOOL_SCHEMA = "tool_schema";
345
- var MCP_TOOL_SCHEMA_PARAMETERS = "mcp.tool.schema.parameters";
346
- var MCP_TOOL_SCHEMA_OUTPUT = "mcp.tool.schema.output";
347
- var MCP_TOOL_DESCRIPTION = "mcp.tool.description";
348
- var SPAN_NAME_TOOL_REGISTER = "mcp.tool.register";
349
- var MCP_METHOD_NAME = "mcp.method.name";
350
- var MCP_REQUEST_ID = "mcp.request.id";
351
- var MCP_SESSION_ID = "mcp.session.id";
352
- var MCP_PROTOCOL_VERSION = "mcp.protocol.version";
353
- var MCP_RESOURCE_URI = "mcp.resource.uri";
354
- var RPC_SYSTEM = "rpc.system";
355
- var RPC_SYSTEM_MCP = "mcp";
356
- var RPC_RESPONSE_STATUS_CODE = "rpc.response.status_code";
357
- var GEN_AI_TOOL_NAME = "gen_ai.tool.name";
358
- var GEN_AI_PROMPT_NAME = "gen_ai.prompt.name";
359
- var GEN_AI_OPERATION_NAME = "gen_ai.operation.name";
360
- var GEN_AI_OPERATION_EXECUTE_TOOL = "execute_tool";
361
- var NETWORK_TRANSPORT = "network.transport";
362
- var ERROR_TYPE = "error.type";
363
- var ERROR_TYPE_TOOL = "tool_error";
364
- var JSONRPC_REQUEST_ID = "jsonrpc.request.id";
365
- var SPAN_NAME_TOOLS_CALL = "tools/call";
366
- var MAX_ATTRIBUTE_LENGTH = 32 * 1024;
367
- var TRUNCATION_SUFFIX = "\u2026(truncated)";
368
- var METHOD_TOOLS_CALL = "tools/call";
369
- var METHOD_TOOLS_LIST = "tools/list";
370
- var METHOD_RESOURCES_READ = "resources/read";
371
- var METHOD_PROMPTS_GET = "prompts/get";
372
- var METHOD_INITIALIZE = "initialize";
373
-
374
- // src/internal/instrumentation/mcp/schemas.ts
375
- var _MAX_SCHEMA_ATTR_BYTES = 4e3;
376
- function truncateSchemaAttr(value) {
377
- if (value.length <= _MAX_SCHEMA_ATTR_BYTES) {
378
- return value;
379
- }
380
- return `{"_truncated":true,"original_length":${value.length}}`;
381
- }
382
- function safeStringify(value) {
383
- if (value === null || value === void 0) {
384
- return "";
385
- }
386
- try {
387
- return JSON.stringify(value);
388
- } catch {
389
- return "";
390
- }
391
- }
392
- function emitSchemaSpansFromListResponse(result, transportSessionId, tracer) {
393
- if (!transportSessionId) {
394
- return;
395
- }
396
- const tools = extractTools(result);
397
- if (tools === void 0) {
398
- return;
399
- }
400
- for (const tool of tools) {
401
- const name = typeof tool.name === "string" ? tool.name : void 0;
402
- if (!name) {
403
- continue;
404
- }
405
- const span = tracer.startSpan(`${SPAN_NAME_TOOL_REGISTER} ${name}`, {
406
- kind: SpanKind.INTERNAL
407
- });
408
- try {
409
- stampSchemaAttributes(span, name, transportSessionId, tool);
410
- span.setStatus({ code: SpanStatusCode.OK });
411
- } finally {
412
- span.end();
413
- }
414
- }
415
- }
416
- function stampSchemaAttributes(span, toolName, transportSessionId, tool) {
417
- if (!span.isRecording()) {
418
- logger.warn(
419
- `Brizz MCP: schema span is not recording; dropping attributes for ${toolName}`
420
- );
421
- return;
422
- }
423
- const description = typeof tool.description === "string" ? tool.description : "";
424
- const parameters = truncateSchemaAttr(safeStringify(tool.inputSchema));
425
- const outputSchema = tool.outputSchema !== void 0 && tool.outputSchema !== null ? truncateSchemaAttr(safeStringify(tool.outputSchema)) : "";
426
- span.setAttribute(RPC_SYSTEM, RPC_SYSTEM_MCP);
427
- span.setAttribute(MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL_SCHEMA);
428
- span.setAttribute(MCP_SESSION_ID, transportSessionId);
429
- span.setAttribute(MCP_TOOL_NAME, toolName);
430
- span.setAttribute(MCP_TOOL_SCHEMA_PARAMETERS, parameters);
431
- span.setAttribute(MCP_TOOL_SCHEMA_OUTPUT, outputSchema);
432
- span.setAttribute(MCP_TOOL_DESCRIPTION, description);
433
- }
434
- function extractTools(result) {
435
- if (!result || typeof result !== "object") {
436
- return void 0;
437
- }
438
- const tools = result.tools;
439
- if (!Array.isArray(tools)) {
440
- return void 0;
441
- }
442
- return tools.filter(
443
- (t) => t !== null && typeof t === "object"
444
- );
445
- }
446
-
447
- // src/internal/instrumentation/mcp/session.ts
448
- import { context } from "@opentelemetry/api";
449
-
450
- // src/internal/semantic-conventions.ts
451
- import { createContextKey } from "@opentelemetry/api";
452
- var BRIZZ = "brizz";
453
- var PROPERTIES = "properties";
454
- var SESSION_ID = "session.id";
455
- var PROPERTIES_CONTEXT_KEY = createContextKey(PROPERTIES);
456
- var SESSION_OBJECT_CONTEXT_KEY = createContextKey("brizz.session.object");
457
- var INTERRUPT_TOOLS = "brizz.internal.interrupt";
458
- var INTERNAL_EVENT_PREFIX = "brizz.internal.";
459
-
460
- // src/internal/instrumentation/mcp/session.ts
461
- function stampAndPropagateSession(span, sessionId, baseContext = context.active()) {
462
- if (!sessionId) {
463
- return { context: baseContext, sessionId: null };
464
- }
465
- if (span.isRecording()) {
466
- try {
467
- span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
468
- } catch (error) {
469
- logger.warn(
470
- `Brizz MCP: failed to stamp session id on span: ${String(error)}`
471
- );
472
- }
473
- }
474
- try {
475
- const prev = baseContext.getValue(PROPERTIES_CONTEXT_KEY);
476
- const merged = prev ? { ...prev, [SESSION_ID]: sessionId } : { [SESSION_ID]: sessionId };
477
- return {
478
- context: baseContext.setValue(PROPERTIES_CONTEXT_KEY, merged),
479
- sessionId
480
- };
481
- } catch (error) {
482
- logger.warn(`Brizz MCP: failed to attach session context: ${String(error)}`);
483
- return { context: baseContext, sessionId };
484
- }
485
- }
486
-
487
- // src/internal/instrumentation/mcp/patches/attributes.ts
488
- import { SpanStatusCode as SpanStatusCode2 } from "@opentelemetry/api";
489
- function deriveSpanName(method, params) {
490
- try {
491
- if (method === METHOD_TOOLS_CALL) {
492
- const name = typeof params?.["name"] === "string" ? params["name"] : "";
493
- return name ? `${SPAN_NAME_TOOLS_CALL} ${name}` : SPAN_NAME_TOOLS_CALL;
494
- }
495
- if (method === METHOD_RESOURCES_READ) {
496
- const uri = typeof params?.["uri"] === "string" ? params["uri"] : "";
497
- return uri ? `${METHOD_RESOURCES_READ} ${uri}` : METHOD_RESOURCES_READ;
498
- }
499
- if (method === METHOD_PROMPTS_GET) {
500
- const name = typeof params?.["name"] === "string" ? params["name"] : "";
501
- return name ? `${METHOD_PROMPTS_GET} ${name}` : METHOD_PROMPTS_GET;
502
- }
503
- return method;
504
- } catch {
505
- return method || "mcp";
506
- }
507
- }
508
- function applyBaseAttributes(span, request) {
509
- span.setAttribute(RPC_SYSTEM, RPC_SYSTEM_MCP);
510
- if (request.method) {
511
- span.setAttribute(MCP_METHOD_NAME, request.method);
512
- }
513
- if (request.id !== void 0 && request.id !== null) {
514
- const id = String(request.id);
515
- span.setAttribute(MCP_REQUEST_ID, id);
516
- span.setAttribute(JSONRPC_REQUEST_ID, id);
517
- }
518
- }
519
- function applyClientRequestAttributes(span, request, transportName) {
520
- applyBaseAttributes(span, request);
521
- applyMethodSpecificRequestAttributes(span, request);
522
- if (transportName) {
523
- const transport = normalizeTransport(transportName);
524
- if (transport) {
525
- span.setAttribute(NETWORK_TRANSPORT, transport);
526
- }
527
- }
528
- }
529
- function applyServerRequestAttributes(span, request, protocol) {
530
- applyBaseAttributes(span, request);
531
- applyMethodSpecificRequestAttributes(span, request);
532
- if (request.method === METHOD_TOOLS_CALL) {
533
- const args = request.params?.["arguments"];
534
- if (args !== void 0) {
535
- span.setAttribute(MCP_TOOL_ARGUMENTS, serializeForAttribute(args));
536
- }
537
- }
538
- const sessionId = protocol.sessionId ?? protocol._transport?.sessionId;
539
- if (sessionId) {
540
- span.setAttribute(MCP_SESSION_ID, String(sessionId));
541
- }
542
- }
543
- function applyMethodSpecificRequestAttributes(span, request) {
544
- const params = request.params ?? {};
545
- switch (request.method) {
546
- case METHOD_TOOLS_CALL: {
547
- const name = typeof params["name"] === "string" ? params["name"] : "";
548
- if (name) {
549
- span.setAttribute(MCP_TOOL_NAME, name);
550
- span.setAttribute(GEN_AI_TOOL_NAME, name);
551
- }
552
- span.setAttribute(MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL);
553
- span.setAttribute(GEN_AI_OPERATION_NAME, GEN_AI_OPERATION_EXECUTE_TOOL);
554
- break;
555
- }
556
- case METHOD_RESOURCES_READ: {
557
- const uri = typeof params["uri"] === "string" ? params["uri"] : "";
558
- if (uri) {
559
- span.setAttribute(MCP_RESOURCE_URI, uri);
560
- }
561
- break;
562
- }
563
- case METHOD_PROMPTS_GET: {
564
- const name = typeof params["name"] === "string" ? params["name"] : "";
565
- if (name) {
566
- span.setAttribute(GEN_AI_PROMPT_NAME, name);
567
- }
568
- break;
569
- }
570
- default:
571
- break;
572
- }
573
- }
574
- function applyResultAttributes(span, method, result) {
575
- if (method === METHOD_INITIALIZE && result && typeof result === "object") {
576
- const protocolVersion = result["protocolVersion"];
577
- if (typeof protocolVersion === "string") {
578
- span.setAttribute(MCP_PROTOCOL_VERSION, protocolVersion);
579
- }
580
- return;
581
- }
582
- if (method !== METHOD_TOOLS_CALL) {
583
- return;
584
- }
585
- const obj = result && typeof result === "object" ? result : null;
586
- const content = obj?.["content"] ?? result;
587
- span.setAttribute(MCP_TOOL_RESULT, serializeForAttribute(content));
588
- if (obj && obj["isError"] === true) {
589
- span.setAttribute(ERROR_TYPE, ERROR_TYPE_TOOL);
590
- const message = extractToolErrorMessage(obj);
591
- span.setStatus({ code: SpanStatusCode2.ERROR, message });
592
- }
593
- }
594
- function applyErrorAttributes(span, err) {
595
- const error = err;
596
- const code = error?.code;
597
- if (typeof code === "number") {
598
- span.setAttribute(RPC_RESPONSE_STATUS_CODE, code);
599
- span.setAttribute(ERROR_TYPE, String(code));
600
- } else if (error?.name === "AbortError") {
601
- span.setAttribute(ERROR_TYPE, "cancelled");
602
- } else if (error?.name === "TimeoutError") {
603
- span.setAttribute(ERROR_TYPE, "timeout");
604
- } else {
605
- span.setAttribute(
606
- ERROR_TYPE,
607
- error?.constructor?.name || error?.name || "Error"
608
- );
609
- }
610
- try {
611
- span.recordException(error);
612
- } catch {
613
- }
614
- span.setStatus({
615
- code: SpanStatusCode2.ERROR,
616
- message: typeof error?.message === "string" ? error.message : void 0
617
- });
618
- }
619
- function serializeForAttribute(value) {
620
- const raw = rawSerialize(value);
621
- if (raw.length <= MAX_ATTRIBUTE_LENGTH) {
622
- return raw;
623
- }
624
- return raw.slice(0, MAX_ATTRIBUTE_LENGTH - TRUNCATION_SUFFIX.length) + TRUNCATION_SUFFIX;
625
- }
626
- function rawSerialize(value) {
627
- if (value === null || value === void 0) {
628
- return "";
629
- }
630
- if (typeof value === "string") {
631
- return value;
632
- }
633
- try {
634
- return JSON.stringify(value);
635
- } catch {
636
- try {
637
- if (value === null || value === void 0) {
638
- return "";
639
- }
640
- const tag = Object.prototype.toString.call(value);
641
- return typeof value.toString === "function" ? (
642
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
643
- String(value)
644
- ) : tag;
645
- } catch {
646
- return "";
647
- }
648
- }
649
- }
650
- function extractToolErrorMessage(result) {
651
- const content = result["content"];
652
- if (Array.isArray(content)) {
653
- for (const item of content) {
654
- if (item && typeof item === "object") {
655
- const text = item["text"];
656
- if (typeof text === "string") {
657
- return text;
658
- }
659
- }
660
- }
661
- }
662
- return void 0;
663
- }
664
- function normalizeTransport(ctorName) {
665
- const name = ctorName.toLowerCase();
666
- if (name.includes("stdio")) {
667
- return "stdio";
668
- }
669
- if (name.includes("sse")) {
670
- return "sse";
671
- }
672
- if (name.includes("streamablehttp") || name.includes("http")) {
673
- return "http";
674
- }
675
- return null;
676
- }
677
-
678
- // src/internal/instrumentation/mcp/patches/protocol.ts
679
- var PATCHED_FLAG = /* @__PURE__ */ Symbol("brizz.mcp.protocol-patched");
680
- function patchProtocolPrototype(prototype, tracer) {
681
- if (!prototype || typeof prototype !== "object") {
682
- return false;
683
- }
684
- const proto = prototype;
685
- if (proto[PATCHED_FLAG]) {
686
- logger.debug("Brizz MCP: Protocol.prototype already patched, skipping");
687
- return false;
688
- }
689
- const originalRequest = proto["request"];
690
- const originalOnRequest = proto["_onrequest"];
691
- if (typeof originalRequest === "function") {
692
- proto["request"] = wrapRequest(originalRequest, tracer);
693
- } else {
694
- logger.debug(
695
- "Brizz MCP: Protocol.prototype.request missing \u2014 skipping CLIENT patch"
696
- );
697
- }
698
- if (typeof originalOnRequest === "function") {
699
- proto["_onrequest"] = wrapOnRequest(
700
- originalOnRequest,
701
- tracer
702
- );
703
- } else {
704
- logger.debug(
705
- "Brizz MCP: Protocol.prototype._onrequest missing \u2014 skipping SERVER patch"
706
- );
707
- }
708
- proto[PATCHED_FLAG] = true;
709
- return true;
710
- }
711
- function wrapRequest(original, tracer) {
712
- return function wrappedRequest(...args) {
713
- const request = args[0];
714
- if (!request || typeof request !== "object" || !request.method) {
715
- return original.apply(this, args);
716
- }
717
- const span = safeStartClientSpan(tracer, request, this);
718
- if (!span) {
719
- return original.apply(this, args);
720
- }
721
- return executeAroundSpan(span, request.method, () => {
722
- const ctx = trace.setSpan(context2.active(), span);
723
- return context2.with(ctx, () => original.apply(this, args));
724
- });
725
- };
726
- }
727
- function wrapOnRequest(original, tracer) {
728
- return function wrappedOnRequest(...args) {
729
- const request = args[0];
730
- if (!request || typeof request !== "object" || !request.method) {
731
- return original.apply(this, args);
732
- }
733
- const handlers = this._requestHandlers;
734
- if (!handlers || typeof handlers.get !== "function") {
735
- return original.apply(this, args);
736
- }
737
- const method = request.method;
738
- const handler = handlers.get(method) ?? this.fallbackRequestHandler;
739
- if (!handler) {
740
- return original.apply(this, args);
741
- }
742
- const started = safeStartServerSpan(tracer, request, this);
743
- if (!started) {
744
- return original.apply(this, args);
745
- }
746
- const { span, spanCtx } = started;
747
- const transportSessionId = this.sessionId ?? this._transport?.sessionId;
748
- const postResult = method === METHOD_TOOLS_LIST ? (result) => {
749
- try {
750
- emitSchemaSpansFromListResponse(result, transportSessionId, tracer);
751
- } catch (error) {
752
- logger.warn(
753
- `Brizz MCP: failed to emit tools/list schema spans: ${String(error)}`
754
- );
755
- }
756
- } : void 0;
757
- const wrappedHandler = (req, extra) => context2.with(
758
- spanCtx,
759
- () => executeHandler(span, method, handler, req, extra, postResult)
760
- );
761
- const hadEntry = handlers.has(method);
762
- const prev = handlers.get(method);
763
- handlers.set(method, wrappedHandler);
764
- const usedFallback = !hadEntry && this.fallbackRequestHandler === handler;
765
- const fallbackPrev = usedFallback ? this.fallbackRequestHandler : void 0;
766
- if (usedFallback) {
767
- this.fallbackRequestHandler = wrappedHandler;
768
- }
769
- try {
770
- return original.apply(this, args);
771
- } finally {
772
- if (hadEntry) {
773
- handlers.set(method, prev);
774
- } else {
775
- handlers.delete(method);
776
- }
777
- if (usedFallback) {
778
- this.fallbackRequestHandler = fallbackPrev;
779
- }
780
- }
781
- };
782
- }
783
- function executeAroundSpan(span, method, run, postResult) {
784
- let result;
785
- try {
786
- result = run();
787
- } catch (error) {
788
- safeApplyErrorAttributes(span, error);
789
- safeEnd(span);
790
- throw error;
791
- }
792
- if (!isThenable(result)) {
793
- safeApplyResultAttributes(span, method, result);
794
- if (postResult) {
795
- postResult(result);
796
- }
797
- safeEnd(span);
798
- return result;
799
- }
800
- return result.then(
801
- (value) => {
802
- safeApplyResultAttributes(span, method, value);
803
- if (postResult) {
804
- postResult(value);
805
- }
806
- safeEnd(span);
807
- return value;
808
- },
809
- (error) => {
810
- safeApplyErrorAttributes(span, error);
811
- safeEnd(span);
812
- throw error;
813
- }
814
- );
815
- }
816
- function executeHandler(span, method, handler, req, extra, postResult) {
817
- return executeAroundSpan(span, method, () => handler(req, extra), postResult);
818
- }
819
- function safeStartClientSpan(tracer, request, protocol) {
820
- try {
821
- const spanName = deriveSpanName(request.method, request.params);
822
- const span = tracer.startSpan(spanName, { kind: SpanKind2.CLIENT });
823
- applyClientRequestAttributes(
824
- span,
825
- request,
826
- protocol._transport?.constructor?.name
827
- );
828
- return span;
829
- } catch (error) {
830
- logger.debug(`Brizz MCP: failed to open CLIENT span: ${String(error)}`);
831
- return null;
832
- }
833
- }
834
- function safeStartServerSpan(tracer, request, protocol) {
835
- try {
836
- const parentCtx = extractParentContext(request);
837
- const spanName = deriveSpanName(request.method, request.params);
838
- const span = tracer.startSpan(
839
- spanName,
840
- { kind: SpanKind2.SERVER },
841
- parentCtx
842
- );
843
- applyServerRequestAttributes(span, request, protocol);
844
- const sessionId = protocol.sessionId ?? protocol._transport?.sessionId;
845
- const { context: sessCtx } = stampAndPropagateSession(span, sessionId, parentCtx);
846
- return { span, spanCtx: trace.setSpan(sessCtx, span) };
847
- } catch (error) {
848
- logger.debug(`Brizz MCP: failed to open SERVER span: ${String(error)}`);
849
- return null;
850
- }
851
- }
852
- function extractParentContext(request) {
853
- try {
854
- const meta = request.params?._meta;
855
- if (meta && typeof meta === "object") {
856
- return propagation.extract(context2.active(), meta);
857
- }
858
- } catch (error) {
859
- logger.debug(
860
- `Brizz MCP: failed to extract parent context from _meta: ${String(error)}`
861
- );
862
- }
863
- return context2.active();
864
- }
865
- function isThenable(value) {
866
- return !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
867
- }
868
- function safeApplyResultAttributes(span, method, value) {
869
- try {
870
- applyResultAttributes(span, method, value);
871
- } catch (error) {
872
- logger.debug(
873
- `Brizz MCP: failed to apply result attributes: ${String(error)}`
874
- );
875
- }
876
- }
877
- function safeApplyErrorAttributes(span, err) {
878
- try {
879
- applyErrorAttributes(span, err);
880
- } catch (error) {
881
- logger.debug(
882
- `Brizz MCP: failed to apply error attributes: ${String(error)}`
883
- );
884
- }
885
- }
886
- function safeEnd(span) {
887
- try {
888
- span.end();
889
- } catch (error) {
890
- logger.debug(`Brizz MCP: failed to end span: ${String(error)}`);
891
- }
892
- }
893
-
894
- // src/internal/version.ts
895
- function getSDKVersion() {
896
- return "0.1.29";
897
- }
898
-
899
- // src/internal/instrumentation/mcp/version.ts
900
- var INSTRUMENTATION_NAME = "@brizz/sdk/mcp";
901
- var INSTRUMENTATION_VERSION = getSDKVersion();
902
-
903
- // src/internal/instrumentation/mcp/instrumentation.ts
904
- var PROTOCOL_MODULE_NAME = "@modelcontextprotocol/sdk/shared/protocol.js";
905
- var PROTOCOL_SUPPORTED_VERSIONS = [">=1.0.0 <2"];
906
- var MCPInstrumentation = class extends BaseMCPInstrumentation {
907
- /**
908
- * Dedicated Brizz-named tracer for our SERVER + CLIENT spans.
909
- *
910
- * Why a separate tracer from the parent class's one: Arize's inherited
911
- * transport patches don't emit spans (they only inject propagation
912
- * headers), so using our own tracer here keeps Brizz spans attributed to
913
- * `@brizz/sdk/mcp` in the dashboard. The parent's `tracer` is a
914
- * `protected get` (no setter), so fighting it with assignment is the
915
- * wrong tool.
916
- */
917
- brizzTracer;
918
- constructor(_config) {
919
- super({ instrumentationConfig: _config?.instrumentationConfig });
920
- this.brizzTracer = trace2.getTracer(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION);
921
- }
922
- /**
923
- * Extend `super.init()` with our protocol-layer module definition.
924
- *
925
- * Arize's `init()` returns definitions for the six transport modules
926
- * (SSE client/server, stdio client/server, streamable-HTTP client/server)
927
- * whose `send`/`start` methods get patched for W3C trace-context
928
- * injection. We append one more: `@modelcontextprotocol/sdk/shared/protocol.js`
929
- * where our patches open SERVER/CLIENT spans around the handler + outgoing
930
- * request. If `super.init()` throws (unlikely but possible across Arize
931
- * versions), we gracefully degrade to protocol-only instrumentation.
932
- *
933
- * The cast at the end satisfies the parent's strongly-typed generic
934
- * without leaking the cast into call sites.
935
- */
936
- init() {
937
- let base;
938
- try {
939
- base = super.init() ?? [];
940
- } catch (error) {
941
- logger.warn(
942
- `Brizz MCP: base Arize init() failed \u2014 transport context propagation disabled: ${String(error)}`
943
- );
944
- base = [];
945
- }
946
- const baseArr = Array.isArray(base) ? base : [base];
947
- const brizzDef = new InstrumentationNodeModuleDefinition(
948
- PROTOCOL_MODULE_NAME,
949
- PROTOCOL_SUPPORTED_VERSIONS,
950
- (module3) => {
951
- this.patchProtocolModule(module3);
952
- return module3;
953
- },
954
- (module3) => {
955
- this.unpatchProtocolModule(module3);
956
- return module3;
957
- }
958
- );
959
- return [...baseArr, brizzDef];
960
- }
961
- /**
962
- * Manually instrument MCP modules for Next.js/Webpack where the
963
- * auto-instrumentation module-load hook doesn't fire.
964
- *
965
- * Forwards the six transport module fields to the inherited Arize
966
- * `manuallyInstrument(...)` (context propagation) and applies our
967
- * protocol patch if `protocolModule` is provided (SERVER/CLIENT spans).
968
- * Both legs are try/catch-guarded — a failure in one shouldn't prevent
969
- * the other from taking effect.
970
- */
971
- manuallyInstrument(modules) {
972
- const {
973
- clientSSEModule,
974
- serverSSEModule,
975
- clientStdioModule,
976
- serverStdioModule,
977
- clientStreamableHTTPModule,
978
- serverStreamableHTTPModule,
979
- protocolModule
980
- } = modules;
981
- try {
982
- super.manuallyInstrument({
983
- clientSSEModule,
984
- serverSSEModule,
985
- clientStdioModule,
986
- serverStdioModule,
987
- clientStreamableHTTPModule,
988
- serverStreamableHTTPModule
989
- });
990
- } catch (error) {
991
- logger.warn(`Brizz MCP: Arize manuallyInstrument(...) failed: ${String(error)}`);
992
- }
993
- if (protocolModule) {
994
- try {
995
- this.patchProtocolModule(protocolModule);
996
- } catch (error) {
997
- logger.warn(
998
- `Brizz MCP: failed to manually patch Protocol module: ${String(error)}`
999
- );
1000
- }
1001
- }
1002
- }
1003
- /**
1004
- * Apply the SERVER + CLIENT patch to a loaded `protocol.js` module. Shared
1005
- * by both the automatic module-load callback in `init()` and the manual
1006
- * `manuallyInstrument(...)` path above so there's exactly one place that
1007
- * calls `patchProtocolPrototype`.
1008
- */
1009
- patchProtocolModule(module3) {
1010
- const proto = module3?.Protocol?.prototype;
1011
- if (!proto) {
1012
- logger.debug(
1013
- "Brizz MCP: module does not expose Protocol.prototype \u2014 skipping protocol patches"
1014
- );
1015
- return;
1016
- }
1017
- const ok = patchProtocolPrototype(proto, this.brizzTracer);
1018
- if (ok) {
1019
- logger.debug("Brizz MCP: patched Protocol.prototype for SERVER+CLIENT spans");
1020
- }
1021
- }
1022
- /**
1023
- * Unpatch is intentionally a no-op.
1024
- *
1025
- * `patchProtocolPrototype` wraps methods in place and sets a PATCHED_FLAG
1026
- * Symbol on the prototype to prevent double-patching. Restoring the
1027
- * originals would require us to hold references across module unloads,
1028
- * which isn't a pattern we need — instrumentation rarely gets torn down
1029
- * at runtime, and a process reload is the canonical way to detach.
1030
- */
1031
- unpatchProtocolModule(_module) {
1032
- logger.debug(
1033
- "Brizz MCP: unpatch is a no-op \u2014 reload the process to cleanly detach"
1034
- );
1035
- }
1036
- };
1037
-
1038
- // src/internal/instrumentation/registry.ts
1039
- var InstrumentationRegistry = class _InstrumentationRegistry {
1040
- static instance;
1041
- manualModules = null;
1042
- static getInstance() {
1043
- if (!_InstrumentationRegistry.instance) {
1044
- _InstrumentationRegistry.instance = new _InstrumentationRegistry();
1045
- }
1046
- return _InstrumentationRegistry.instance;
1047
- }
1048
- /**
1049
- * Set manual instrumentation modules for Next.js/Webpack environments
1050
- */
1051
- setManualModules(modules) {
1052
- this.manualModules = modules;
1053
- logger.info("Manual instrumentation modules configured for Next.js/Webpack compatibility");
1054
- }
1055
- /**
1056
- * Helper to load instrumentation with optional manual module
1057
- */
1058
- loadInstrumentation(InstrumentationClass, name, manualModule, exceptionLogger) {
1059
- try {
1060
- const inst = new InstrumentationClass({
1061
- exceptionLogger: exceptionLogger || ((error) => logger.error(`Exception in instrumentation: ${String(error)}`))
1062
- });
1063
- if (manualModule) {
1064
- inst.manuallyInstrument(manualModule);
1065
- logger.debug(`Manual instrumentation enabled for ${name}`);
1066
- }
1067
- return inst;
1068
- } catch (error) {
1069
- logger.error(`Failed to load ${name} instrumentation: ${String(error)}`);
1070
- return null;
1071
- }
1072
- }
1073
- /**
1074
- * Get manual instrumentations only.
1075
- * Auto-instrumentations are handled at import time.
1076
- */
1077
- getManualInstrumentations() {
1078
- if (!this.manualModules || Object.keys(this.manualModules).length === 0) {
1079
- logger.debug("No manual instrumentation modules configured");
1080
- return [];
1081
- }
1082
- const instrumentations = [];
1083
- const exceptionLogger = (error) => {
1084
- logger.error(`Exception in manual instrumentation: ${String(error)}`);
1085
- };
1086
- this.loadManualInstrumentations(instrumentations, exceptionLogger);
1087
- logger.info(`Loaded ${instrumentations.length} manual instrumentations`);
1088
- return instrumentations;
1089
- }
1090
- /**
1091
- * Load manual instrumentations only (with modules provided by user).
1092
- * @private
1093
- */
1094
- loadManualInstrumentations(instrumentations, exceptionLogger) {
1095
- const instrumentationConfigs = [
1096
- { class: OpenAIInstrumentation, name: "OpenAI", module: this.manualModules?.openAI },
1097
- { class: AnthropicInstrumentation, name: "Anthropic", module: this.manualModules?.anthropic },
1098
- { class: CohereInstrumentation, name: "Cohere", module: this.manualModules?.cohere },
1099
- {
1100
- class: VertexAIInstrumentation,
1101
- name: "Vertex AI",
1102
- module: this.manualModules?.google_vertexai
1103
- },
1104
- { class: BedrockInstrumentation, name: "Bedrock", module: this.manualModules?.bedrock },
1105
- { class: PineconeInstrumentation, name: "Pinecone", module: this.manualModules?.pinecone },
1106
- {
1107
- class: LlamaIndexInstrumentation,
1108
- name: "LlamaIndex",
1109
- module: this.manualModules?.llamaindex
1110
- },
1111
- { class: ChromaDBInstrumentation, name: "ChromaDB", module: this.manualModules?.chromadb },
1112
- { class: QdrantInstrumentation, name: "Qdrant", module: this.manualModules?.qdrant },
1113
- { class: TogetherInstrumentation, name: "Together", module: this.manualModules?.together }
1114
- ];
1115
- for (const config of instrumentationConfigs) {
1116
- if (config.module) {
1117
- const instrumentation = this.loadInstrumentation(
1118
- config.class,
1119
- config.name,
1120
- config.module,
1121
- exceptionLogger
1122
- );
1123
- if (instrumentation) {
1124
- instrumentations.push(instrumentation);
1125
- }
1126
- }
1127
- }
1128
- if (this.manualModules?.langchain?.callbackManagerModule) {
1129
- const callbackManagerModule = this.manualModules.langchain.callbackManagerModule;
1130
- void (async () => {
1131
- try {
1132
- const { LangChainInstrumentation } = await import("@arizeai/openinference-instrumentation-langchain");
1133
- const lcInst = new LangChainInstrumentation();
1134
- lcInst.manuallyInstrument(callbackManagerModule);
1135
- logger.debug("Manual instrumentation enabled for LangChain");
1136
- } catch (error) {
1137
- logger.error(
1138
- `Failed to load LangChain instrumentation. Ensure @langchain/core is installed: ${String(error)}`
1139
- );
1140
- }
1141
- })();
1142
- }
1143
- if (this.manualModules?.mcp) {
1144
- try {
1145
- new MCPInstrumentation({ exceptionLogger }).manuallyInstrument(this.manualModules.mcp);
1146
- logger.debug("Manual instrumentation enabled for MCP");
1147
- } catch (error) {
1148
- logger.error(`Failed to apply MCP instrumentation: ${String(error)}`);
1149
- }
1150
- }
1151
- }
1152
- };
1153
-
1154
- // src/internal/instrumentation/vercel-ai/interrupt.ts
1155
- import { trace as trace3 } from "@opentelemetry/api";
1156
- var INNER_OPERATION_IDS = /* @__PURE__ */ new Set([
1157
- "ai.generateText.doGenerate",
1158
- "ai.streamText.doStream"
1159
- ]);
1160
- function isInnerLLMSpan(span) {
1161
- if (INNER_OPERATION_IDS.has(span.name)) {
1162
- return true;
1163
- }
1164
- const opId = span.attributes["ai.operationId"];
1165
- return typeof opId === "string" && INNER_OPERATION_IDS.has(opId);
1166
- }
1167
- var pendingByParentSpanId = /* @__PURE__ */ new Map();
1168
- var InterruptPropagator = class {
1169
- onStart(span, _parentContext) {
1170
- if (!isInnerLLMSpan(span)) {
1171
- return;
1172
- }
1173
- const parentSpanId = span.parentSpanContext?.spanId;
1174
- if (!parentSpanId) {
1175
- return;
1176
- }
1177
- const value = pendingByParentSpanId.get(parentSpanId);
1178
- if (!value) {
1179
- return;
1180
- }
1181
- span.setAttribute(INTERRUPT_TOOLS, value);
1182
- pendingByParentSpanId.delete(parentSpanId);
1183
- }
1184
- onEnd() {
1185
- }
1186
- async shutdown() {
1187
- }
1188
- async forceFlush() {
1189
- }
1190
- };
1191
-
1192
- // src/internal/log/logging.ts
1193
- import { SeverityNumber } from "@opentelemetry/api-logs";
1194
- import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
1195
- import { resourceFromAttributes } from "@opentelemetry/resources";
1196
1
  import {
1197
- LoggerProvider
1198
- } from "@opentelemetry/sdk-logs";
1199
-
1200
- // src/internal/trace/session.ts
1201
- import { context as context3, trace as trace4, SpanStatusCode as SpanStatusCode3 } from "@opentelemetry/api";
1202
-
1203
- // src/internal/log/processors/log-processor.ts
1204
- import { context as context4 } from "@opentelemetry/api";
1205
- import { BatchLogRecordProcessor, SimpleLogRecordProcessor } from "@opentelemetry/sdk-logs";
1206
-
1207
- // src/internal/masking/patterns.ts
1208
- var DEFAULT_PII_PATTERNS = [
1209
- // Phone numbers (US format)
1210
- {
1211
- name: "us_phone_numbers",
1212
- 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]|$)`
1213
- },
1214
- // Credit card numbers
1215
- {
1216
- name: "credit_cards",
1217
- 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`
1218
- },
1219
- {
1220
- name: "credit_cards_with_separators",
1221
- 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`
1222
- },
1223
- // IP addresses (IPv4)
1224
- {
1225
- name: "ipv4_addresses",
1226
- 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`
1227
- },
1228
- // API keys/tokens
1229
- {
1230
- name: "generic_api_keys",
1231
- 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`
1232
- },
1233
- {
1234
- name: "openai_keys",
1235
- pattern: String.raw`\bsk[-_][a-zA-Z0-9]{20,}\b`
1236
- },
1237
- // AWS Keys
1238
- {
1239
- name: "aws_access_keys",
1240
- pattern: String.raw`\b(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\b`
1241
- },
1242
- // GitHub tokens
1243
- {
1244
- name: "github_tokens",
1245
- pattern: String.raw`\bghp_[a-zA-Z0-9]{36}\b`
1246
- },
1247
- // Slack tokens
1248
- {
1249
- name: "slack_tokens",
1250
- pattern: String.raw`\bxox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24,34}\b`
1251
- },
1252
- // Stripe keys
1253
- {
1254
- name: "stripe_keys",
1255
- pattern: String.raw`\b(?:sk|pk)_(?:test|live)_[a-zA-Z0-9]{24,}\b`
1256
- },
1257
- // JWT tokens
1258
- {
1259
- name: "jwt_tokens",
1260
- pattern: String.raw`\beyJ[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\b`
1261
- },
1262
- // MAC addresses
1263
- {
1264
- name: "mac_addresses",
1265
- pattern: String.raw`\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b`
1266
- },
1267
- // IPv6 addresses
1268
- {
1269
- name: "ipv6_addresses",
1270
- pattern: String.raw`\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b`
1271
- },
1272
- // Bitcoin addresses
1273
- {
1274
- name: "bitcoin_addresses",
1275
- pattern: String.raw`\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b`
1276
- },
1277
- // Ethereum addresses
1278
- {
1279
- name: "ethereum_addresses",
1280
- pattern: String.raw`\b0x[a-fA-F0-9]{40}(?![a-fA-F0-9])\b`
1281
- },
1282
- // Database connection strings
1283
- {
1284
- name: "database_connections",
1285
- 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`
1286
- },
1287
- // Private keys
1288
- {
1289
- name: "rsa_private_keys",
1290
- pattern: "-----BEGIN (?:RSA )?PRIVATE KEY-----"
1291
- },
1292
- {
1293
- name: "pgp_private_keys",
1294
- pattern: "-----BEGIN PGP PRIVATE KEY BLOCK-----"
1295
- },
1296
- // Additional API Keys and Tokens
1297
- {
1298
- name: "google_oauth",
1299
- pattern: String.raw`\bya29\\.[a-zA-Z0-9_-]{60,}\b`
1300
- },
1301
- {
1302
- name: "firebase_tokens",
1303
- pattern: String.raw`\bAAAA[A-Za-z0-9_-]{100,}\b`
1304
- },
1305
- {
1306
- name: "google_app_ids",
1307
- pattern: String.raw`\b[0-9]+-\w+\.apps\.googleusercontent\.com\b`
1308
- },
1309
- {
1310
- name: "facebook_secrets",
1311
- 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]`
1312
- },
1313
- {
1314
- name: "github_keys",
1315
- 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]`
1316
- },
1317
- {
1318
- name: "heroku_keys",
1319
- 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\\-]`
1320
- },
1321
- {
1322
- name: "slack_api_keys",
1323
- 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]`
1324
- },
1325
- {
1326
- name: "slack_api_tokens",
1327
- pattern: String.raw`\b(xox[pb](?:-[a-zA-Z0-9]+){4,})\b`
1328
- },
1329
- // Extended Private Keys and Certificates
1330
- {
1331
- name: "dsa_private_keys",
1332
- pattern: String.raw`-----BEGIN DSA PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END DSA PRIVATE KEY-----`
1333
- },
1334
- {
1335
- name: "ec_private_keys",
1336
- pattern: String.raw`-----BEGIN (?:EC|ECDSA) PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END (?:EC|ECDSA) PRIVATE KEY-----`
1337
- },
1338
- {
1339
- name: "encrypted_private_keys",
1340
- pattern: String.raw`-----BEGIN ENCRYPTED PRIVATE KEY-----(?:.|\s)+?-----END ENCRYPTED PRIVATE KEY-----`
1341
- },
1342
- {
1343
- name: "ssl_certificates",
1344
- pattern: String.raw`-----BEGIN CERTIFICATE-----(?:.|\n)+?\s*-----END CERTIFICATE-----`
1345
- },
1346
- {
1347
- name: "ssh_dss_public",
1348
- pattern: String.raw`\bssh-dss [0-9A-Za-z+/]+[=]{2}\b`
1349
- },
1350
- {
1351
- name: "ssh_rsa_public",
1352
- pattern: String.raw`\bssh-rsa AAAA[0-9A-Za-z+/]+[=]{0,3} [^@]+@[^@]+\b`
1353
- },
1354
- {
1355
- name: "putty_ssh_keys",
1356
- pattern: String.raw`PuTTY-User-Key-File-2: ssh-(?:rsa|dss)\s*Encryption: none(?:.|\s?)*?Private-MAC:`
1357
- },
1358
- // Security and Network
1359
- {
1360
- name: "cve_numbers",
1361
- pattern: String.raw`\b[Cc][Vv][Ee]-\\d{4}-\\d{4,7}\b`
1362
- },
1363
- {
1364
- name: "microsoft_oauth",
1365
- pattern: String.raw`https://login\.microsoftonline\.com/common/oauth2/v2\.0/token|https://login\.windows\.net/common/oauth2/token`
1366
- },
1367
- {
1368
- name: "postgres_connections",
1369
- pattern: String.raw`\b(?:[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Pp][Gg][Ss][Qq][Ll])\\:\\/\\/`
1370
- },
1371
- {
1372
- name: "box_links",
1373
- pattern: String.raw`https://app\.box\.com/[s|l]/\S+`
1374
- },
1375
- {
1376
- name: "dropbox_links",
1377
- pattern: String.raw`https://www\.dropbox\.com/(?:s|l)/\S+`
1378
- },
1379
- // Credit Card Variants
1380
- {
1381
- name: "amex_cards",
1382
- pattern: String.raw`\b3[47][0-9]{13}\b`
1383
- },
1384
- {
1385
- name: "visa_cards",
1386
- pattern: String.raw`\b4[0-9]{12}(?:[0-9]{3})?\b`
1387
- },
1388
- {
1389
- name: "discover_cards",
1390
- pattern: String.raw`\b65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}\b`
1391
- }
1392
- ];
1393
-
1394
- // src/internal/masking/utils.ts
1395
- function isValidPatternName(name) {
1396
- return /^[a-zA-Z0-9_]+$/.test(name);
1397
- }
1398
- function isLikelyReDoSPattern(pattern) {
1399
- const dangerousPatterns = [
1400
- // Nested quantifiers like (a+)+, (a*)+, (a+)*
1401
- /\([^)]*[+*]\)[+*]/,
1402
- // Overlapping alternation under an outer quantifier like (a|a)+, (\w|\d)+. Scoped to
1403
- // capturing groups so the lazy (?:…)+? built-ins aren't false-flagged.
1404
- /\((?!\?)[^)]*\|[^)]*\)[+*]/,
1405
- // Complex backtracking patterns - but more specific
1406
- /\([^)]*[+*][^)]*[+*][^)]*\)[+*]/
1407
- ];
1408
- return dangerousPatterns.some((dangerous) => dangerous.test(pattern));
1409
- }
1410
- function getGroupedPattern(patternEntry) {
1411
- let name = patternEntry.name;
1412
- if (!name || name === "") {
1413
- name = `pattern_${Math.random().toString(16).slice(2)}`;
1414
- }
1415
- if (!isValidPatternName(name)) {
1416
- throw new Error(
1417
- `Pattern name '${name}' must only contain alphanumeric characters and underscores`
1418
- );
1419
- }
1420
- if (isLikelyReDoSPattern(patternEntry.pattern)) {
1421
- throw new Error(`Potentially dangerous ReDoS pattern detected: '${patternEntry.pattern}'`);
1422
- }
1423
- try {
1424
- new RegExp(patternEntry.pattern);
1425
- } catch (error) {
1426
- throw new Error(`Invalid regex pattern '${patternEntry.pattern}': ${String(error)}`, {
1427
- cause: error
1428
- });
1429
- }
1430
- return `(?<${name}>${patternEntry.pattern})`;
1431
- }
1432
- function isIPatternEntry(obj) {
1433
- return typeof obj === "object" && obj !== null && typeof obj.pattern === "string" && (obj.name === void 0 || typeof obj.name === "string");
1434
- }
1435
- function isIEventMaskingRule(obj) {
1436
- return typeof obj === "object" && obj !== null && typeof obj.mode === "string" && Array.isArray(obj.patterns) && obj.patterns.every(
1437
- (p) => isIPatternEntry(p) || typeof p === "string"
1438
- ) && (obj.attributePattern === void 0 || typeof obj.attributePattern === "string");
1439
- }
1440
- function convertPatternsToPatternEntries(patterns) {
1441
- const patternEntries = [];
1442
- for (const pattern of patterns) {
1443
- if (typeof pattern === "string") {
1444
- patternEntries.push({ pattern, name: "" });
1445
- } else if (isIPatternEntry(pattern)) {
1446
- patternEntries.push(pattern);
1447
- } else {
1448
- throw new Error("Patterns must be either strings or PatternEntry instances");
1449
- }
1450
- }
1451
- return patternEntries;
1452
- }
1453
- function compilePatternEntries(patternEntries) {
1454
- const patternGroups = [];
1455
- for (const patternEntry of patternEntries) {
1456
- try {
1457
- patternGroups.push(getGroupedPattern(patternEntry));
1458
- } catch (error) {
1459
- logger.warn(`Invalid pattern '${patternEntry.name}': ${patternEntry.pattern}`, error);
1460
- continue;
1461
- }
1462
- }
1463
- if (patternGroups.length === 0) {
1464
- return null;
1465
- }
1466
- try {
1467
- return new RegExp(patternGroups.join("|"));
1468
- } catch (error) {
1469
- logger.warn("Failed to compile pattern entries into regex", error);
1470
- return null;
1471
- }
1472
- }
1473
- var compiledPatternCache = /* @__PURE__ */ new WeakMap();
1474
- function getCompiledPatternsForRule(rule) {
1475
- const key = rule.patterns;
1476
- if (compiledPatternCache.has(key)) {
1477
- return compiledPatternCache.get(key) ?? null;
1478
- }
1479
- const compiled = compilePatternEntries(convertPatternsToPatternEntries(rule.patterns));
1480
- compiledPatternCache.set(key, compiled);
1481
- return compiled;
1482
- }
1483
- function getCompiledAttributeNamePattern(rule) {
1484
- if (!rule.attributePattern) {
1485
- logger.debug("No attribute pattern provided, using default .*");
1486
- return /.*/;
1487
- }
1488
- let compiledPatternString = rule.attributePattern;
1489
- if (isIEventMaskingRule(rule) && rule.eventNamePattern) {
1490
- compiledPatternString = `(${compiledPatternString})|(${rule.eventNamePattern})`;
1491
- }
1492
- return new RegExp(compiledPatternString);
1493
- }
1494
- function shouldContinueExecution(startTime, iterations, timeoutMs) {
1495
- if (Date.now() - startTime > timeoutMs) {
1496
- logger.warn("Regex execution timed out - potential ReDoS pattern detected");
1497
- return false;
1498
- }
1499
- const maxIterations = 1e3;
1500
- if (iterations > maxIterations) {
1501
- logger.warn("Regex execution exceeded maximum iterations - potential ReDoS pattern detected");
1502
- return false;
1503
- }
1504
- return true;
1505
- }
1506
- function createGlobalPattern(pattern) {
1507
- return new RegExp(
1508
- pattern.source,
1509
- pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g"
1510
- );
1511
- }
1512
- function executeRegexWithTimeout(pattern, value, timeoutMs = 100) {
1513
- const matches = [];
1514
- const globalPattern = createGlobalPattern(pattern);
1515
- const startTime = Date.now();
1516
- let match;
1517
- let iterations = 0;
1518
- while ((match = globalPattern.exec(value)) !== null) {
1519
- if (!shouldContinueExecution(startTime, ++iterations, timeoutMs)) {
1520
- break;
1521
- }
1522
- matches.push(match);
1523
- if (match[0].length === 0) {
1524
- globalPattern.lastIndex = match.index + 1;
1525
- }
1526
- }
1527
- return matches;
1528
- }
1529
- function maskStringByPattern(value, pattern, mode = "full") {
1530
- const matches = [];
1531
- try {
1532
- const regexMatches = executeRegexWithTimeout(pattern, value);
1533
- for (const match of regexMatches) {
1534
- matches.push({
1535
- start: match.index,
1536
- end: match.index + match[0].length,
1537
- text: match[0],
1538
- groups: match.groups
1539
- });
1540
- }
1541
- } catch (error) {
1542
- logger.warn("Regex execution failed, skipping masking", error);
1543
- return value;
1544
- }
1545
- for (const matchInfo of matches.toReversed()) {
1546
- let patternName = "unknown";
1547
- if (matchInfo.groups) {
1548
- for (const [groupName, groupValue] of Object.entries(matchInfo.groups)) {
1549
- if (groupValue !== void 0) {
1550
- if (groupName.includes("_") && /\d$/.test(groupName)) {
1551
- const parts = groupName.split("_");
1552
- patternName = parts[0] || groupName;
1553
- } else {
1554
- patternName = groupName;
1555
- }
1556
- break;
1557
- }
1558
- }
1559
- }
1560
- logger.info(`Masking detected: pattern '${patternName}' found match in value`);
1561
- const masked = mode === "partial" ? matchInfo.text[0] + "*****" : "*****";
1562
- value = value.slice(0, matchInfo.start) + masked + value.slice(matchInfo.end);
1563
- }
1564
- return value;
1565
- }
1566
- function maskStringByPatternBasedRule(value, rule) {
1567
- const patternEntries = convertPatternsToPatternEntries(rule.patterns);
1568
- if (patternEntries.length === 0) {
1569
- logger.warn("No patterns provided for masking rule, returning original value");
1570
- return value;
1571
- }
1572
- const mode = rule.mode;
1573
- if (!patternEntries || patternEntries.length === 0) {
1574
- return mode === "partial" && value ? value[0] + "*****" : "*****";
1575
- }
1576
- const compiledPatterns = getCompiledPatternsForRule(rule);
1577
- if (!compiledPatterns) {
1578
- return value;
1579
- }
1580
- return maskStringByPattern(value, compiledPatterns, mode);
1581
- }
1582
- function maskValue(value, rule) {
1583
- if (typeof value === "string") {
1584
- return maskStringByPatternBasedRule(value, rule);
1585
- } else if (typeof value === "boolean" || typeof value === "number") {
1586
- return maskStringByPatternBasedRule(String(value), rule);
1587
- } else if (Array.isArray(value)) {
1588
- return value.map((v) => maskStringByPatternBasedRule(String(v), rule));
1589
- } else if (value !== null && typeof value === "object") {
1590
- const result = {};
1591
- for (const [k, v] of Object.entries(value)) {
1592
- result[k] = maskValue(v, rule);
1593
- }
1594
- return result;
1595
- } else {
1596
- throw new Error(`Unsupported value type for masking: ${typeof value}`);
1597
- }
1598
- }
1599
- function maskAttributes(attributes, rules, outputOriginalValue = false) {
1600
- if (!attributes || Object.keys(attributes).length === 0) {
1601
- return {};
1602
- }
1603
- const maskedAttributes = { ...attributes };
1604
- for (const rule of rules) {
1605
- const compiledAttributeNamePattern = getCompiledAttributeNamePattern(rule);
1606
- const attributesToMask = compiledAttributeNamePattern ? Object.keys(maskedAttributes).filter((attr) => compiledAttributeNamePattern.test(attr)) : Object.keys(maskedAttributes);
1607
- for (const attribute of attributesToMask) {
1608
- const value = maskedAttributes[attribute];
1609
- if (value === null || value === void 0) {
1610
- continue;
1611
- }
1612
- if (outputOriginalValue) {
1613
- logger.debug(`Masking attribute '${attribute}' with original value`, { value });
1614
- }
1615
- maskedAttributes[attribute] = maskValue(value, rule);
1616
- }
1617
- }
1618
- return maskedAttributes;
1619
- }
1620
-
1621
- // src/internal/log/processors/log-processor.ts
1622
- var DEFAULT_LOG_MASKING_RULES = [
1623
- {
1624
- mode: "partial",
1625
- attributePattern: "event.name",
1626
- patterns: DEFAULT_PII_PATTERNS
1627
- }
1628
- ];
1629
- var BrizzSimpleLogRecordProcessor = class extends SimpleLogRecordProcessor {
1630
- config;
1631
- constructor(exporter, config) {
1632
- super(exporter);
1633
- this.config = config;
1634
- }
1635
- onEmit(logRecord) {
1636
- const maskingConfig = this.config.masking?.eventMasking;
1637
- if (maskingConfig) {
1638
- maskLog(logRecord, maskingConfig);
1639
- }
1640
- const associationProperties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
1641
- if (associationProperties) {
1642
- for (const [key, value] of Object.entries(associationProperties)) {
1643
- logRecord.setAttribute(`${BRIZZ}.${key}`, value);
1644
- }
1645
- }
1646
- super.onEmit(logRecord);
1647
- }
1648
- };
1649
- var BrizzBatchLogRecordProcessor = class extends BatchLogRecordProcessor {
1650
- config;
1651
- constructor(exporter, config) {
1652
- super(exporter);
1653
- this.config = config;
1654
- }
1655
- onEmit(logRecord) {
1656
- const maskingConfig = this.config.masking?.eventMasking;
1657
- if (maskingConfig) {
1658
- maskLog(logRecord, maskingConfig);
1659
- }
1660
- const associationProperties = context4.active().getValue(PROPERTIES_CONTEXT_KEY);
1661
- if (associationProperties) {
1662
- for (const [key, value] of Object.entries(associationProperties)) {
1663
- logRecord.setAttribute(`${BRIZZ}.${key}`, value);
1664
- }
1665
- }
1666
- super.onEmit(logRecord);
1667
- }
1668
- };
1669
- function maskLog(logRecord, config) {
1670
- if (!logRecord.attributes) {
1671
- return logRecord;
1672
- }
1673
- let rules = config.rules || [];
1674
- if (!config.disableDefaultRules) {
1675
- rules = [...DEFAULT_LOG_MASKING_RULES, ...rules];
1676
- }
1677
- try {
1678
- if (logRecord.attributes && Object.keys(logRecord.attributes).length > 0) {
1679
- const attributesRecord = {};
1680
- for (const [key, value] of Object.entries(logRecord.attributes)) {
1681
- attributesRecord[key] = value;
1682
- }
1683
- const maskedAttributes = maskAttributes(attributesRecord, rules);
1684
- if (maskedAttributes) {
1685
- const newAttributes = {};
1686
- for (const [key, value] of Object.entries(maskedAttributes)) {
1687
- newAttributes[key] = value;
1688
- }
1689
- for (const [key, value] of Object.entries(logRecord.attributes)) {
1690
- if (key.startsWith(INTERNAL_EVENT_PREFIX)) {
1691
- newAttributes[key] = value;
1692
- }
1693
- }
1694
- logRecord.setAttributes(newAttributes);
1695
- }
1696
- }
1697
- if (config.maskBody && logRecord.body !== void 0 && logRecord.body !== null) {
1698
- let maskedBody = logRecord.body;
1699
- for (const rule of rules) {
1700
- maskedBody = maskValue(maskedBody, rule);
1701
- }
1702
- logRecord.setBody(maskedBody);
1703
- }
1704
- return logRecord;
1705
- } catch (error) {
1706
- logger.error("Error masking log record:", error);
1707
- return logRecord;
1708
- }
1709
- }
1710
-
1711
- // src/internal/log/logging.ts
1712
- var LoggingModule = class _LoggingModule {
1713
- static instance = null;
1714
- logExporter = null;
1715
- logProcessor = null;
1716
- loggerProvider = null;
1717
- static getInstance() {
1718
- if (!_LoggingModule.instance) {
1719
- throw new Error("Brizz must be initialized before accessing LoggingModule");
1720
- }
1721
- return _LoggingModule.instance;
1722
- }
1723
- /**
1724
- * Initialize the logging module with the provided configuration
1725
- */
1726
- setup(config) {
1727
- logger.info("Setting up logging module");
1728
- this.initLogExporter(config);
1729
- this.initLogProcessor(config);
1730
- this.initLoggerProvider(config);
1731
- _LoggingModule.instance = this;
1732
- logger.info("Logging module setup completed");
1733
- }
1734
- /**
1735
- * Initialize the log exporter
1736
- */
1737
- initLogExporter(config) {
1738
- if (this.logExporter) {
1739
- logger.debug("Log exporter already initialized, skipping re-initialization");
1740
- return;
1741
- }
1742
- if (config.customLogExporter) {
1743
- logger.debug("Using custom log exporter");
1744
- this.logExporter = config.customLogExporter;
1745
- logger.debug("Custom log exporter initialized successfully");
1746
- return;
1747
- }
1748
- const logsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/logs";
1749
- logger.debug("Initializing default OTLP log exporter", { url: logsUrl });
1750
- const headers = { ...config.headers };
1751
- this.logExporter = new OTLPLogExporter({
1752
- url: logsUrl,
1753
- headers
1754
- });
1755
- logger.debug("OTLP log exporter initialized successfully");
1756
- }
1757
- /**
1758
- * Initialize the log processor with masking support
1759
- */
1760
- initLogProcessor(config) {
1761
- if (this.logProcessor) {
1762
- logger.debug("Log processor already initialized, skipping re-initialization");
1763
- return;
1764
- }
1765
- if (!this.logExporter) {
1766
- throw new Error("Log exporter must be initialized before processor");
1767
- }
1768
- logger.debug("Initializing log processor", {
1769
- disableBatch: config.disableBatch,
1770
- hasMasking: !!config.masking?.eventMasking
1771
- });
1772
- this.logProcessor = config.disableBatch ? new BrizzSimpleLogRecordProcessor(this.logExporter, config) : new BrizzBatchLogRecordProcessor(this.logExporter, config);
1773
- logger.debug("Log processor initialized successfully");
1774
- }
1775
- /**
1776
- * Initialize the logger provider
1777
- */
1778
- initLoggerProvider(config) {
1779
- if (this.loggerProvider) {
1780
- logger.debug("Logger provider already initialized, skipping re-initialization");
1781
- return;
1782
- }
1783
- if (!this.logProcessor) {
1784
- throw new Error("Log processor must be initialized before logger provider");
1785
- }
1786
- logger.debug("Creating resource with service name", {
1787
- serviceName: config.appName
1788
- });
1789
- const resourceAttributes = {
1790
- ...config.resourceAttributes,
1791
- "service.name": config.appName,
1792
- [BRIZZ_SDK_VERSION]: getSDKVersion(),
1793
- [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
1794
- };
1795
- if (config.environment) {
1796
- resourceAttributes["deployment.environment"] = config.environment;
1797
- }
1798
- if (config.appVersion) {
1799
- resourceAttributes["service.version"] = config.appVersion;
1800
- }
1801
- const resource = resourceFromAttributes(resourceAttributes);
1802
- logger.debug("Creating logger provider with resource");
1803
- this.loggerProvider = new LoggerProvider({
1804
- resource,
1805
- processors: [this.logProcessor]
1806
- });
1807
- logger.debug("Logger provider initialization completed");
1808
- }
1809
- /**
1810
- * Emit a custom event to the telemetry pipeline
1811
- */
1812
- emitEvent(name, attributes, body, severityNumber = SeverityNumber.INFO) {
1813
- logger.debug("Attempting to emit event", {
1814
- name,
1815
- hasAttributes: !!attributes,
1816
- attributesCount: attributes ? Object.keys(attributes).length : 0,
1817
- hasBody: !!body,
1818
- severityNumber
1819
- });
1820
- if (!this.loggerProvider) {
1821
- logger.error("Cannot emit event: Logger provider not initialized");
1822
- throw new Error("Logging module not initialized");
1823
- }
1824
- const logAttributes = { "event.name": name };
1825
- if (attributes) {
1826
- Object.assign(logAttributes, attributes);
1827
- logger.debug("Combined log attributes", { attributes: Object.keys(logAttributes) });
1828
- }
1829
- logger.debug("Getting logger instance for brizz_events");
1830
- const eventLogger = this.loggerProvider.getLogger("brizz.events");
1831
- logger.debug("Emitting log record with eventName", { eventName: name });
1832
- try {
1833
- eventLogger.emit({
1834
- eventName: name,
1835
- attributes: logAttributes,
1836
- severityNumber,
1837
- body
1838
- });
1839
- logger.debug("Event successfully emitted", { eventName: name });
1840
- } catch (error) {
1841
- logger.error(`Failed to emit event '${name}'`, { error, eventName: name });
1842
- logger.error("Log record that failed", {
1843
- eventName: name,
1844
- hasAttributes: logAttributes,
1845
- severityNumber,
1846
- hasBody: body
1847
- });
1848
- throw error instanceof Error ? error : new Error(String(error));
1849
- }
1850
- }
1851
- /**
1852
- * Check if the module is initialized
1853
- */
1854
- isInitialized() {
1855
- return this.loggerProvider !== null;
1856
- }
1857
- /**
1858
- * Get the logger provider
1859
- */
1860
- getLoggerProvider() {
1861
- return this.loggerProvider;
1862
- }
1863
- /**
1864
- * Shutdown the logging module
1865
- */
1866
- async shutdown() {
1867
- logger.debug("Shutting down logging module");
1868
- if (this.loggerProvider) {
1869
- await this.loggerProvider.shutdown();
1870
- this.loggerProvider = null;
1871
- }
1872
- this.logProcessor = null;
1873
- this.logExporter = null;
1874
- if (_LoggingModule.instance === this) {
1875
- _LoggingModule.instance = null;
1876
- }
1877
- logger.debug("Logging module shutdown completed");
1878
- }
1879
- };
1880
-
1881
- // src/internal/metric/metrics.ts
1882
- import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
1883
- import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
1884
- var MetricsModule = class _MetricsModule {
1885
- static instance = null;
1886
- metricsExporter = null;
1887
- metricsReader = null;
1888
- static getInstance() {
1889
- if (!_MetricsModule.instance) {
1890
- throw new Error("Brizz must be initialized before accessing MetricsModule");
1891
- }
1892
- return _MetricsModule.instance;
1893
- }
1894
- /**
1895
- * Initialize the metrics module with the provided configuration
1896
- */
1897
- setup(config) {
1898
- logger.info("Setting up metrics module");
1899
- this.initMetricsReader(config);
1900
- _MetricsModule.instance = this;
1901
- logger.info("Metrics module setup completed");
1902
- }
1903
- /**
1904
- * Initialize the metrics exporter
1905
- */
1906
- initMetricsExporter(config) {
1907
- if (this.metricsExporter) {
1908
- logger.debug("Metrics exporter already initialized, skipping re-initialization");
1909
- return;
1910
- }
1911
- const metricsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/metrics";
1912
- logger.debug("Initializing metrics exporter", { url: metricsUrl });
1913
- this.metricsExporter = new OTLPMetricExporter({
1914
- url: metricsUrl,
1915
- headers: config.headers
1916
- });
1917
- logger.debug("Metrics exporter initialized successfully");
1918
- }
1919
- /**
1920
- * Initialize the metrics reader
1921
- */
1922
- initMetricsReader(config) {
1923
- if (this.metricsReader) {
1924
- logger.debug("Metrics reader already initialized, skipping re-initialization");
1925
- return;
1926
- }
1927
- if (config.customMetricReader) {
1928
- logger.debug("Using custom metric reader");
1929
- this.metricsReader = config.customMetricReader;
1930
- logger.debug("Custom metric reader initialized successfully");
1931
- return;
1932
- }
1933
- logger.debug(
1934
- "Using default metrics flow - creating OTLP exporter and PeriodicExportingMetricReader"
1935
- );
1936
- this.initMetricsExporter(config);
1937
- if (!this.metricsExporter) {
1938
- throw new Error("Failed to initialize metrics exporter");
1939
- }
1940
- this.metricsReader = new PeriodicExportingMetricReader({
1941
- exporter: this.metricsExporter
1942
- });
1943
- logger.debug("Default metrics reader initialized successfully");
1944
- }
1945
- /**
1946
- * Get the metrics exporter
1947
- */
1948
- getMetricsExporter() {
1949
- if (!this.metricsExporter) {
1950
- throw new Error("Metrics module not initialized");
1951
- }
1952
- return this.metricsExporter;
1953
- }
1954
- /**
1955
- * Get the metrics reader
1956
- */
1957
- getMetricsReader() {
1958
- if (!this.metricsReader) {
1959
- throw new Error("Metrics module not initialized");
1960
- }
1961
- return this.metricsReader;
1962
- }
1963
- /**
1964
- * Shutdown the metrics module
1965
- */
1966
- shutdown() {
1967
- logger.debug("Shutting down metrics module");
1968
- this.metricsReader = null;
1969
- this.metricsExporter = null;
1970
- if (_MetricsModule.instance === this) {
1971
- _MetricsModule.instance = null;
1972
- }
1973
- logger.debug("Metrics module shutdown completed");
1974
- }
1975
- };
1976
- function getMetricsReader() {
1977
- return MetricsModule.getInstance().getMetricsReader();
1978
- }
1979
-
1980
- // src/internal/trace/tracing.ts
1981
- import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
1982
-
1983
- // src/internal/trace/exporters/span-exporter.ts
1984
- import { ExportResultCode } from "@opentelemetry/core";
1985
- import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
1986
- var BrizzSpanExporter = class {
1987
- _delegate;
1988
- _brizzResource;
1989
- _beforeSendSpan;
1990
- constructor(delegate, config) {
1991
- this._delegate = delegate;
1992
- const resourceAttrs = {
1993
- ...config.resourceAttributes,
1994
- "service.name": config.appName,
1995
- [BRIZZ_SDK_VERSION]: getSDKVersion(),
1996
- [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
1997
- };
1998
- if (config.environment) {
1999
- resourceAttrs["deployment.environment"] = config.environment;
2000
- }
2001
- if (config.appVersion) {
2002
- resourceAttrs["service.version"] = config.appVersion;
2003
- }
2004
- this._brizzResource = resourceFromAttributes2(resourceAttrs);
2005
- this._beforeSendSpan = config.beforeSendSpan;
2006
- }
2007
- export(spans, resultCallback) {
2008
- if (spans.length === 0) {
2009
- resultCallback({ code: ExportResultCode.SUCCESS });
2010
- return;
2011
- }
2012
- const patchedSpans = spans.map((span) => ({
2013
- ...span,
2014
- resource: span.resource.merge(this._brizzResource),
2015
- spanContext: span.spanContext.bind(span)
2016
- }));
2017
- const filter = this._beforeSendSpan;
2018
- if (!filter) {
2019
- this._delegate.export(patchedSpans, resultCallback);
2020
- return;
2021
- }
2022
- const verdicts = patchedSpans.map((span) => {
2023
- try {
2024
- return Promise.resolve(filter(span));
2025
- } catch (error) {
2026
- logger.warn("beforeSendSpan threw; span will be kept", { error });
2027
- return Promise.resolve(true);
2028
- }
2029
- });
2030
- Promise.all(verdicts).then((keep) => {
2031
- const filtered = patchedSpans.filter((_, i) => keep[i] !== false);
2032
- if (filtered.length === 0) {
2033
- resultCallback({ code: ExportResultCode.SUCCESS });
2034
- return;
2035
- }
2036
- this._delegate.export(filtered, resultCallback);
2037
- return;
2038
- }).catch((error) => {
2039
- logger.warn("beforeSendSpan rejected; all spans will be kept", { error });
2040
- this._delegate.export(patchedSpans, resultCallback);
2041
- });
2042
- }
2043
- async shutdown() {
2044
- return this._delegate.shutdown();
2045
- }
2046
- async forceFlush() {
2047
- return this._delegate.forceFlush?.();
2048
- }
2049
- };
2050
-
2051
- // src/internal/trace/processors/span-processor.ts
2052
- import { context as context5 } from "@opentelemetry/api";
2
+ Brizz,
3
+ detectRuntime
4
+ } from "./chunk-6UYAVA5T.js";
2053
5
  import {
2054
- BatchSpanProcessor,
2055
- SimpleSpanProcessor
2056
- } from "@opentelemetry/sdk-trace-base";
2057
- function applyContextAttributes(span) {
2058
- const sessionProperties = context5.active().getValue(PROPERTIES_CONTEXT_KEY);
2059
- if (sessionProperties) {
2060
- for (const [key, value] of Object.entries(sessionProperties)) {
2061
- span.setAttribute(`${BRIZZ}.${key}`, value);
2062
- }
2063
- }
2064
- }
2065
- var DEFAULT_MASKING_RULES = [
2066
- {
2067
- mode: "partial",
2068
- patterns: DEFAULT_PII_PATTERNS
2069
- }
2070
- ];
2071
- var BrizzSimpleSpanProcessor = class extends SimpleSpanProcessor {
2072
- config;
2073
- constructor(spanExporter, config) {
2074
- super(spanExporter);
2075
- this.config = config;
2076
- }
2077
- onStart(span, parentContext) {
2078
- applyContextAttributes(span);
2079
- super.onStart(span, parentContext);
2080
- }
2081
- onEnd(span) {
2082
- const maskingConfig = this.config.masking?.spanMasking;
2083
- if (maskingConfig) {
2084
- maskReadableSpan(span, maskingConfig);
2085
- }
2086
- super.onEnd(span);
2087
- }
2088
- };
2089
- var BrizzBatchSpanProcessor = class extends BatchSpanProcessor {
2090
- config;
2091
- constructor(spanExporter, config) {
2092
- super(spanExporter);
2093
- this.config = config;
2094
- }
2095
- onStart(span, parentContext) {
2096
- applyContextAttributes(span);
2097
- super.onStart(span, parentContext);
2098
- }
2099
- onEnd(span) {
2100
- const maskingConfig = this.config.masking?.spanMasking;
2101
- if (maskingConfig) {
2102
- maskReadableSpan(span, maskingConfig);
2103
- }
2104
- super.onEnd(span);
2105
- }
2106
- };
2107
- function maskReadableSpan(span, config) {
2108
- const attrs = span.attributes;
2109
- if (!attrs || Object.keys(attrs).length === 0) {
2110
- return;
2111
- }
2112
- let rules = config.rules ? [...config.rules] : [];
2113
- if (!config.disableDefaultRules) {
2114
- rules = [...rules, ...DEFAULT_MASKING_RULES];
2115
- }
2116
- try {
2117
- const input = {};
2118
- for (const [k, v] of Object.entries(attrs)) {
2119
- input[k] = v;
2120
- }
2121
- const masked = maskAttributes(input, rules);
2122
- for (const [k, v] of Object.entries(masked ?? {})) {
2123
- if (attrs[k] !== v) {
2124
- attrs[k] = v;
2125
- }
2126
- }
2127
- } catch (error) {
2128
- logger.error("Error masking span", { err: error });
2129
- }
2130
- }
2131
-
2132
- // src/internal/trace/tracing.ts
2133
- var TracingModule = class _TracingModule {
2134
- static instance = null;
2135
- spanExporter = null;
2136
- spanProcessor = null;
2137
- static getInstance() {
2138
- if (!_TracingModule.instance) {
2139
- throw new Error("Brizz must be initialized before accessing TracingModule");
2140
- }
2141
- return _TracingModule.instance;
2142
- }
2143
- /**
2144
- * Initialize the tracing module with the provided configuration
2145
- */
2146
- setup(config) {
2147
- logger.info("Setting up tracing module");
2148
- if (config.disableSpanExporter) {
2149
- logger.info(
2150
- "Span exporter disabled via disableSpanExporter; skipping exporter and processor setup"
2151
- );
2152
- this.spanExporter = null;
2153
- this.spanProcessor = null;
2154
- _TracingModule.instance = this;
2155
- return;
2156
- }
2157
- this.initSpanExporter(config);
2158
- this.initSpanProcessor(config);
2159
- _TracingModule.instance = this;
2160
- logger.info("Tracing module setup completed");
2161
- }
2162
- /**
2163
- * Initialize the span exporter
2164
- */
2165
- initSpanExporter(config) {
2166
- if (this.spanExporter) {
2167
- logger.debug("Span exporter already initialized, skipping re-initialization");
2168
- return;
2169
- }
2170
- if (config.customSpanExporter) {
2171
- logger.debug("Using custom span exporter");
2172
- this.spanExporter = new BrizzSpanExporter(config.customSpanExporter, config);
2173
- logger.debug("Custom span exporter initialized successfully");
2174
- return;
2175
- }
2176
- const tracesUrl = config.baseUrl.replace(/\/$/, "") + "/v1/traces";
2177
- logger.debug("Initializing default OTLP span exporter", { url: tracesUrl });
2178
- const otlpExporter = new OTLPTraceExporter({
2179
- url: tracesUrl,
2180
- headers: config.headers
2181
- });
2182
- this.spanExporter = new BrizzSpanExporter(otlpExporter, config);
2183
- logger.debug("OTLP span exporter initialized successfully");
2184
- }
2185
- /**
2186
- * Initialize the span processor with masking support
2187
- */
2188
- initSpanProcessor(config) {
2189
- if (this.spanProcessor) {
2190
- logger.debug("Span processor already initialized, skipping re-initialization");
2191
- return;
2192
- }
2193
- if (!this.spanExporter) {
2194
- throw new Error("Span exporter must be initialized before processor");
2195
- }
2196
- logger.debug("Initializing span processor", {
2197
- disableBatch: config.disableBatch,
2198
- hasMasking: !!config.masking?.spanMasking
2199
- });
2200
- const spanProcessor = config.disableBatch ? new BrizzSimpleSpanProcessor(this.spanExporter, config) : new BrizzBatchSpanProcessor(this.spanExporter, config);
2201
- logger.debug("Span processor initialized successfully");
2202
- this.spanProcessor = spanProcessor;
2203
- }
2204
- /**
2205
- * Get the span exporter
2206
- */
2207
- getSpanExporter() {
2208
- if (!this.spanExporter) {
2209
- throw new Error("Tracing module not initialized");
2210
- }
2211
- return this.spanExporter;
2212
- }
2213
- /**
2214
- * Get the span processor
2215
- */
2216
- getSpanProcessor() {
2217
- if (!this.spanProcessor) {
2218
- throw new Error("Tracing module not initialized");
2219
- }
2220
- return this.spanProcessor;
2221
- }
2222
- async shutdown() {
2223
- logger.debug("Shutting down tracing module");
2224
- if (this.spanProcessor) {
2225
- await this.spanProcessor.shutdown();
2226
- this.spanProcessor = null;
2227
- }
2228
- if (this.spanExporter) {
2229
- await this.spanExporter.shutdown();
2230
- this.spanExporter = null;
2231
- }
2232
- _TracingModule.instance = null;
2233
- logger.debug("Tracing module shutdown completed");
2234
- }
2235
- };
2236
- function getSpanProcessor() {
2237
- return TracingModule.getInstance().getSpanProcessor();
2238
- }
2239
-
2240
- // src/internal/sdk.ts
2241
- var _Brizz = class __Brizz {
2242
- static instance = null;
2243
- /** Flag indicating if SDK initialization has completed successfully */
2244
- _initialized = false;
2245
- /** OpenTelemetry sdk instance */
2246
- _sdk = null;
2247
- static getInstance() {
2248
- if (!__Brizz.instance) {
2249
- throw new Error("Brizz must be initialized before accessing TracingModule");
2250
- }
2251
- return __Brizz.instance;
2252
- }
2253
- /**
2254
- * Initialize the Brizz SDK with the provided configuration.
2255
- *
2256
- * @param {IBrizzInitializeOptions} options - Configuration options for the SDK
2257
- * @throws {Error} - If initialization fails
2258
- *
2259
- * @example
2260
- * ```typescript
2261
- * Brizz.initialize({
2262
- * appName: 'my-app',
2263
- * baseUrl: 'http://localhost:4318',
2264
- * apiKey: 'your-api-key'
2265
- * });
2266
- * ```
2267
- */
2268
- initialize(options) {
2269
- if (this._initialized) {
2270
- logger.warn("Brizz SDK already initialized");
2271
- return;
2272
- }
2273
- logger.info("Starting Brizz SDK initialization");
2274
- try {
2275
- const resolvedConfig = resolveConfig(options);
2276
- this.initializeModules(resolvedConfig);
2277
- this.setupInstrumentation(options);
2278
- this.createAndStartNodeSDK(options, resolvedConfig);
2279
- this._initialized = true;
2280
- logger.info("Brizz SDK initialization completed successfully", {
2281
- moduleSystem: this.detectModuleSystem()
2282
- });
2283
- } catch (error) {
2284
- logger.error("Failed to initialize Brizz SDK", { error });
2285
- throw new Error(`Failed to initialize SDK: ${String(error)}`, { cause: error });
2286
- }
2287
- }
2288
- /**
2289
- * Set up instrumentation registry and configure manual modules.
2290
- * @private
2291
- */
2292
- setupInstrumentation(options) {
2293
- const registry = InstrumentationRegistry.getInstance();
2294
- if (options.instrumentModules && Object.keys(options.instrumentModules).length > 0) {
2295
- registry.setManualModules(options.instrumentModules);
2296
- }
2297
- }
2298
- /**
2299
- * Create and start NodeSDK if not disabled.
2300
- * Only handles manual instrumentations now - auto instrumentations are loaded at import time.
2301
- * @private
2302
- */
2303
- createAndStartNodeSDK(options, resolvedConfig) {
2304
- if (options.disableNodeSdk) {
2305
- logger.info("NodeSDK disabled - only telemetry modules initialized");
2306
- return;
2307
- }
2308
- const registry = InstrumentationRegistry.getInstance();
2309
- const manualInstrumentations = registry.getManualInstrumentations();
2310
- const resourceAttributes = {
2311
- ...resolvedConfig.resourceAttributes,
2312
- "service.name": resolvedConfig.appName,
2313
- [BRIZZ_SDK_VERSION]: getSDKVersion(),
2314
- [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
2315
- };
2316
- if (resolvedConfig.environment) {
2317
- resourceAttributes["deployment.environment"] = resolvedConfig.environment;
2318
- }
2319
- if (resolvedConfig.appVersion) {
2320
- resourceAttributes["service.version"] = resolvedConfig.appVersion;
2321
- }
2322
- this._sdk = new NodeSDK({
2323
- spanProcessors: resolvedConfig.disableSpanExporter ? [] : [new InterruptPropagator(), getSpanProcessor()],
2324
- metricReader: getMetricsReader(),
2325
- resource: resourceFromAttributes3(resourceAttributes),
2326
- instrumentations: manualInstrumentations
2327
- });
2328
- this._sdk.start();
2329
- if (manualInstrumentations.length > 0) {
2330
- logger.info(`NodeSDK started with ${manualInstrumentations.length} manual instrumentations`);
2331
- } else {
2332
- logger.info("NodeSDK started - using auto-instrumentations loaded at import time");
2333
- }
2334
- }
2335
- /**
2336
- * Initialize telemetry modules.
2337
- *
2338
- * Sets up the tracing, metrics, and logging modules with their
2339
- * respective exporters and processors.
2340
- *
2341
- * @param {IResolvedBrizzConfig} config - Resolved configuration
2342
- * @private
2343
- */
2344
- initializeModules(config) {
2345
- logger.info("Initializing telemetry modules");
2346
- logger.debug("Initializing tracing module");
2347
- const tracingModule = new TracingModule();
2348
- tracingModule.setup(config);
2349
- logger.debug("Initializing metrics module");
2350
- const metricsModule = new MetricsModule();
2351
- metricsModule.setup(config);
2352
- logger.debug("Initializing logging module");
2353
- const loggingModule = new LoggingModule();
2354
- loggingModule.setup(config);
2355
- logger.info("All telemetry modules initialized successfully");
2356
- }
2357
- /**
2358
- * Detect the current module system (ESM or CJS) using reliable indicators
2359
- *
2360
- * @returns {string} - 'ESM' or 'CJS'
2361
- * @private
2362
- */
2363
- detectModuleSystem() {
2364
- const inCJS = typeof module !== "undefined" && typeof exports !== "undefined" && typeof __require === "function" && typeof __filename === "string" && typeof __dirname === "string" && this === (typeof exports !== "undefined" ? exports : void 0);
2365
- return inCJS ? "CJS" : "ESM";
2366
- }
2367
- /**
2368
- * Gracefully shutdown the Brizz SDK.
2369
- *
2370
- * This method stops all telemetry collection, flushes any pending data,
2371
- * and releases resources. Should be called before application termination.
2372
- *
2373
- * @returns {Promise<void>} - Resolves when shutdown is complete
2374
- * @throws {Error} - If shutdown fails
2375
- *
2376
- * @example
2377
- * ```typescript
2378
- * // Shutdown before app exit
2379
- * await Brizz.shutdown();
2380
- * ```
2381
- */
2382
- async shutdown() {
2383
- if (!this._initialized) {
2384
- logger.warn("Brizz SDK not initialized");
2385
- return;
2386
- }
2387
- try {
2388
- await this.shutdownModules();
2389
- await this._sdk?.shutdown();
2390
- this._initialized = false;
2391
- this._sdk = null;
2392
- __Brizz.instance = null;
2393
- logger.info("Brizz SDK shut down successfully");
2394
- } catch (error) {
2395
- if (error instanceof Error && error.message.includes("ENOTFOUND")) {
2396
- logger.debug(`Network error during shutdown (expected in tests): ${error.message}`);
2397
- } else {
2398
- logger.error(`Failed to shutdown Brizz SDK: ${String(error)}`);
2399
- throw error;
2400
- }
2401
- }
2402
- }
2403
- /**
2404
- * Shutdown all telemetry modules.
2405
- * @private
2406
- */
2407
- async shutdownModules() {
2408
- logger.info("Shutting down telemetry modules");
2409
- try {
2410
- try {
2411
- const tracingModule = TracingModule.getInstance();
2412
- await tracingModule.shutdown();
2413
- } catch {
2414
- logger.debug("Tracing module already shut down or not initialized");
2415
- }
2416
- try {
2417
- const metricsModule = MetricsModule.getInstance();
2418
- metricsModule.shutdown();
2419
- } catch {
2420
- logger.debug("Metrics module already shut down or not initialized");
2421
- }
2422
- try {
2423
- const loggingModule = LoggingModule.getInstance();
2424
- await loggingModule.shutdown();
2425
- } catch {
2426
- logger.debug("Logging module already shut down or not initialized");
2427
- }
2428
- logger.info("All telemetry modules shut down successfully");
2429
- } catch (error) {
2430
- logger.error("Error shutting down modules", { error });
2431
- throw error;
2432
- }
2433
- }
2434
- };
2435
- var Brizz = new _Brizz();
6
+ DEFAULT_LOG_LEVEL,
7
+ logger
8
+ } from "./chunk-3OLW4TOG.js";
9
+ import "./chunk-MWX3GIJW.js";
10
+ import "./chunk-RORIBZEV.js";
2436
11
 
2437
12
  // src/node/loader.ts
2438
- import module2 from "module";
13
+ import module from "module";
2439
14
  import { createAddHookMessageChannel } from "import-in-the-middle";
2440
15
  var loaderDebug = (() => {
2441
16
  const isDebug = process.env["BRIZZ_ESM_DEBUG"] === "true" || process.env["BRIZZ_LOG_LEVEL"] === "debug";
@@ -2444,7 +19,8 @@ var loaderDebug = (() => {
2444
19
  if (!isDebug) {
2445
20
  return;
2446
21
  }
2447
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
22
+ const now = /* @__PURE__ */ new Date();
23
+ const timestamp = now.toISOString();
2448
24
  const dataStr = data ? ` ${JSON.stringify(data)}` : "";
2449
25
  console.log(`[${timestamp}] [ESM-LOADER] ${msg}${dataStr}`);
2450
26
  },
@@ -2452,7 +28,8 @@ var loaderDebug = (() => {
2452
28
  if (!isDebug) {
2453
29
  return;
2454
30
  }
2455
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
31
+ const now = /* @__PURE__ */ new Date();
32
+ const timestamp = now.toISOString();
2456
33
  const errorStr = error instanceof Error ? ` ${error.message}` : error ? ` ${JSON.stringify(error)}` : "";
2457
34
  console.error(`[${timestamp}] [ESM-LOADER] ERROR: ${msg}${errorStr}`);
2458
35
  }
@@ -2477,7 +54,7 @@ function maybeRegisterESMLoader() {
2477
54
  loaderDebug.log("ESM loader already registered, skipping");
2478
55
  return false;
2479
56
  }
2480
- globalThis[LOADER_REGISTERED_KEY] = true;
57
+ Reflect.set(globalThis, LOADER_REGISTERED_KEY, true);
2481
58
  loaderDebug.log("Starting ESM loader registration...");
2482
59
  if (!checkLoaderAPISupport()) {
2483
60
  loaderDebug.log("Node.js version does not support loader API, skipping");
@@ -2485,28 +62,28 @@ function maybeRegisterESMLoader() {
2485
62
  }
2486
63
  if (import.meta === void 0 || !import.meta.url) {
2487
64
  loaderDebug.log("import.meta.url not available, skipping loader registration");
2488
- globalThis[LOADER_REGISTERED_KEY] = false;
65
+ Reflect.set(globalThis, LOADER_REGISTERED_KEY, false);
2489
66
  return false;
2490
67
  }
2491
68
  const isTest = process.env["NODE_ENV"] === "test" || process.env["JEST_WORKER_ID"] !== void 0;
2492
69
  if (isTest) {
2493
70
  loaderDebug.log("Test environment detected, skipping ESM loader registration");
2494
- globalThis[LOADER_REGISTERED_KEY] = false;
71
+ Reflect.set(globalThis, LOADER_REGISTERED_KEY, false);
2495
72
  return false;
2496
73
  }
2497
74
  try {
2498
75
  loaderDebug.log("Creating MessageChannel for import-in-the-middle...");
2499
- const { addHookMessagePort } = createAddHookMessageChannel();
76
+ const { addHookMessagePort: hookMessagePort } = createAddHookMessageChannel();
2500
77
  loaderDebug.log("Registering import-in-the-middle/hook.mjs...");
2501
- module2.register("import-in-the-middle/hook.mjs", import.meta.url, {
2502
- data: { addHookMessagePort },
2503
- transferList: [addHookMessagePort]
78
+ module.register("import-in-the-middle/hook.mjs", import.meta.url, {
79
+ data: { addHookMessagePort: hookMessagePort },
80
+ transferList: [hookMessagePort]
2504
81
  });
2505
82
  loaderDebug.log("ESM loader successfully registered!");
2506
83
  return true;
2507
84
  } catch (error) {
2508
85
  loaderDebug.error("Failed to register ESM loader:", error);
2509
- globalThis[LOADER_REGISTERED_KEY] = false;
86
+ Reflect.set(globalThis, LOADER_REGISTERED_KEY, false);
2510
87
  return false;
2511
88
  }
2512
89
  }
@@ -2515,52 +92,6 @@ if (globalThis[LOADER_REGISTERED_KEY] !== true) {
2515
92
  maybeRegisterESMLoader();
2516
93
  }
2517
94
 
2518
- // src/node/runtime.ts
2519
- function detectRuntime() {
2520
- const [major, minor] = process.versions.node.split(".").map(Number);
2521
- const noNodeJSGlobals = typeof __filename === "undefined" && typeof __dirname === "undefined";
2522
- const noModuleSystem = typeof module === "undefined" && typeof exports === "undefined";
2523
- const hasRequire = typeof __require === "function";
2524
- const isESM = noNodeJSGlobals && noModuleSystem;
2525
- const isCJS = hasRequire && typeof module !== "undefined" && typeof exports !== "undefined" && typeof __filename === "string" && typeof __dirname === "string";
2526
- const supportsLoaderAPI = (major ?? 0) >= 21 || (major ?? 0) === 20 && (minor ?? 0) >= 6 || (major ?? 0) === 18 && (minor ?? 0) >= 19;
2527
- const supportsRegister = (
2528
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2529
- !!process.features?.typescript || !!globalThis.module?.register
2530
- );
2531
- logger.debug("Runtime detection results:", {
2532
- nodeVersion: `${major ?? 0}.${minor ?? 0}`,
2533
- isESM,
2534
- isCJS,
2535
- supportsLoaderAPI,
2536
- supportsRegister,
2537
- detectionLogic: {
2538
- noNodeJSGlobals,
2539
- noModuleSystem,
2540
- hasRequire,
2541
- esmCondition: `${noNodeJSGlobals} && ${noModuleSystem} = ${isESM}`,
2542
- cjsCondition: `require && module && exports && __filename && __dirname = ${isCJS}`
2543
- },
2544
- checks: {
2545
- __filename: typeof __filename,
2546
- __dirname: typeof __dirname,
2547
- require: typeof __require,
2548
- module: typeof module,
2549
- exports: typeof exports,
2550
- "process.features": process.features,
2551
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2552
- "globalThis.module": globalThis.module
2553
- }
2554
- });
2555
- return {
2556
- isESM,
2557
- isCJS,
2558
- nodeVersion: process.versions.node,
2559
- supportsLoaderAPI,
2560
- supportsRegister
2561
- };
2562
- }
2563
-
2564
95
  // src/preload.ts
2565
96
  var runtime = detectRuntime();
2566
97
  if (runtime.isESM && runtime.supportsLoaderAPI) {