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