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