@brizz/sdk 0.1.37 → 0.1.40

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.
Files changed (102) hide show
  1. package/README.md +28 -125
  2. package/dist/{chunk-OR3YPY4I.js → chunk-BGLKBQ6N.js} +1 -1
  3. package/dist/{chunk-2DSTZTDA.cjs → chunk-RNU3DOSR.cjs} +1 -1
  4. package/dist/index.cjs +2263 -13
  5. package/dist/index.js +2298 -48
  6. package/dist/{mcp-NC5OXRT4.cjs → mcp-64ZNSCIR.cjs} +53 -25
  7. package/dist/{mcp-7Y3O5QSS.js → mcp-HBOMHU67.js} +33 -5
  8. package/dist/types/cjs/eve.d.ts +2 -0
  9. package/dist/types/cjs/google-genai.d.ts +1 -0
  10. package/dist/types/cjs/index.d.ts +15 -0
  11. package/dist/types/cjs/internal/config.d.ts +19 -0
  12. package/dist/types/cjs/internal/constants.d.ts +3 -0
  13. package/dist/types/cjs/internal/dsn.d.ts +13 -0
  14. package/dist/types/cjs/internal/instrumentation/auto-init.d.ts +8 -0
  15. package/dist/types/cjs/internal/instrumentation/google-genai.d.ts +13 -0
  16. package/dist/types/cjs/internal/instrumentation/index.d.ts +2 -0
  17. package/dist/types/cjs/internal/instrumentation/mcp/index.d.ts +2 -0
  18. package/dist/types/cjs/internal/instrumentation/mcp/instrumentation.d.ts +15 -0
  19. package/dist/types/cjs/internal/instrumentation/mcp/patches/attributes.d.ts +9 -0
  20. package/dist/types/cjs/internal/instrumentation/mcp/patches/protocol.d.ts +2 -0
  21. package/dist/types/cjs/internal/instrumentation/mcp/schemas.d.ts +2 -0
  22. package/dist/types/cjs/internal/instrumentation/mcp/semantic-conventions.d.ts +37 -0
  23. package/dist/types/cjs/internal/instrumentation/mcp/session.d.ts +7 -0
  24. package/dist/types/cjs/internal/instrumentation/mcp/types.d.ts +47 -0
  25. package/dist/types/cjs/internal/instrumentation/mcp/version.d.ts +2 -0
  26. package/dist/types/cjs/internal/instrumentation/registry.d.ts +29 -0
  27. package/dist/types/cjs/internal/instrumentation/vercel-ai/interrupt.d.ts +11 -0
  28. package/dist/types/cjs/internal/log/index.d.ts +1 -0
  29. package/dist/types/cjs/internal/log/logging.d.ts +21 -0
  30. package/dist/types/cjs/internal/log/processors/log-processor.d.ts +16 -0
  31. package/dist/types/cjs/internal/logger.d.ts +23 -0
  32. package/dist/types/cjs/internal/masking/index.d.ts +3 -0
  33. package/dist/types/cjs/internal/masking/patterns.d.ts +2 -0
  34. package/dist/types/cjs/internal/masking/types.d.ts +32 -0
  35. package/dist/types/cjs/internal/masking/utils.d.ts +5 -0
  36. package/dist/types/cjs/internal/metric/index.d.ts +1 -0
  37. package/dist/types/cjs/internal/metric/metrics.d.ts +17 -0
  38. package/dist/types/cjs/internal/sdk.d.ts +42 -0
  39. package/dist/types/cjs/internal/semantic-conventions.d.ts +54 -0
  40. package/dist/types/cjs/internal/trace/exporters/eve-trace-exporter.d.ts +18 -0
  41. package/dist/types/cjs/internal/trace/exporters/span-exporter.d.ts +12 -0
  42. package/dist/types/cjs/internal/trace/index.d.ts +4 -0
  43. package/dist/types/cjs/internal/trace/processors/eve-session-processor.d.ts +2 -0
  44. package/dist/types/cjs/internal/trace/processors/span-processor.d.ts +18 -0
  45. package/dist/types/cjs/internal/trace/session.d.ts +136 -0
  46. package/dist/types/cjs/internal/trace/tracing.d.ts +17 -0
  47. package/dist/types/cjs/internal/version.d.ts +1 -0
  48. package/dist/types/cjs/package.json +3 -0
  49. package/dist/types/esm/eve.d.ts +2 -0
  50. package/dist/types/esm/google-genai.d.ts +1 -0
  51. package/dist/types/esm/index.d.ts +15 -0
  52. package/dist/types/esm/internal/config.d.ts +19 -0
  53. package/dist/types/esm/internal/constants.d.ts +3 -0
  54. package/dist/types/esm/internal/dsn.d.ts +13 -0
  55. package/dist/types/esm/internal/instrumentation/auto-init.d.ts +8 -0
  56. package/dist/types/esm/internal/instrumentation/google-genai.d.ts +13 -0
  57. package/dist/types/esm/internal/instrumentation/index.d.ts +2 -0
  58. package/dist/types/esm/internal/instrumentation/mcp/index.d.ts +2 -0
  59. package/dist/types/esm/internal/instrumentation/mcp/instrumentation.d.ts +15 -0
  60. package/dist/types/esm/internal/instrumentation/mcp/patches/attributes.d.ts +9 -0
  61. package/dist/types/esm/internal/instrumentation/mcp/patches/protocol.d.ts +2 -0
  62. package/dist/types/esm/internal/instrumentation/mcp/schemas.d.ts +2 -0
  63. package/dist/types/esm/internal/instrumentation/mcp/semantic-conventions.d.ts +37 -0
  64. package/dist/types/esm/internal/instrumentation/mcp/session.d.ts +7 -0
  65. package/dist/types/esm/internal/instrumentation/mcp/types.d.ts +47 -0
  66. package/dist/types/esm/internal/instrumentation/mcp/version.d.ts +2 -0
  67. package/dist/types/esm/internal/instrumentation/registry.d.ts +29 -0
  68. package/dist/types/esm/internal/instrumentation/vercel-ai/interrupt.d.ts +11 -0
  69. package/dist/types/esm/internal/log/index.d.ts +1 -0
  70. package/dist/types/esm/internal/log/logging.d.ts +21 -0
  71. package/dist/types/esm/internal/log/processors/log-processor.d.ts +16 -0
  72. package/dist/types/esm/internal/logger.d.ts +23 -0
  73. package/dist/types/esm/internal/masking/index.d.ts +3 -0
  74. package/dist/types/esm/internal/masking/patterns.d.ts +2 -0
  75. package/dist/types/esm/internal/masking/types.d.ts +32 -0
  76. package/dist/types/esm/internal/masking/utils.d.ts +5 -0
  77. package/dist/types/esm/internal/metric/index.d.ts +1 -0
  78. package/dist/types/esm/internal/metric/metrics.d.ts +17 -0
  79. package/dist/types/esm/internal/sdk.d.ts +42 -0
  80. package/dist/types/esm/internal/semantic-conventions.d.ts +54 -0
  81. package/dist/types/esm/internal/trace/exporters/eve-trace-exporter.d.ts +18 -0
  82. package/dist/types/esm/internal/trace/exporters/span-exporter.d.ts +12 -0
  83. package/dist/types/esm/internal/trace/index.d.ts +4 -0
  84. package/dist/types/esm/internal/trace/processors/eve-session-processor.d.ts +2 -0
  85. package/dist/types/esm/internal/trace/processors/span-processor.d.ts +18 -0
  86. package/dist/types/esm/internal/trace/session.d.ts +136 -0
  87. package/dist/types/esm/internal/trace/tracing.d.ts +17 -0
  88. package/dist/types/esm/internal/version.d.ts +1 -0
  89. package/package.json +57 -57
  90. package/dist/chunk-4Q2CRWI6.js +0 -2377
  91. package/dist/chunk-O5DVPC42.cjs +0 -2377
  92. package/dist/eve.d.cts +0 -19
  93. package/dist/eve.d.ts +0 -19
  94. package/dist/google-genai.d.cts +0 -7
  95. package/dist/google-genai.d.ts +0 -7
  96. package/dist/index.d.cts +0 -291
  97. package/dist/index.d.ts +0 -291
  98. package/dist/loader.mjs +0 -85
  99. package/dist/preload.cjs +0 -119
  100. package/dist/preload.d.cts +0 -2
  101. package/dist/preload.d.ts +0 -2
  102. package/dist/preload.js +0 -119
package/dist/index.js CHANGED
@@ -1,51 +1,76 @@
1
1
  import {
2
- Brizz,
3
- DEFAULT_PII_PATTERNS,
4
- Session,
5
- SessionTitle,
6
- addExternalLink,
7
- callWithMessageId,
8
- callWithMute,
9
- callWithOrganization,
10
- callWithProperties,
11
- callWithSessionId,
12
- callWithUser,
13
- detectRuntime,
14
- emitEvent,
15
- emitEventWithSessionId,
16
- getActiveSession,
17
- getMetricsExporter,
18
- getMetricsReader,
19
- getSpanExporter,
20
- getSpanProcessor,
21
- maskAttributes,
22
- maskValue,
23
- recordFeedback,
24
- recordMetric,
25
- setCurrentSpanCustomProperties,
26
- setMessageId,
27
- setOrganization,
28
- setUser,
29
- startSession,
30
- startSessionTitle,
31
- withMessageId,
32
- withMute,
33
- withOrganization,
34
- withProperties,
35
- withSessionId,
36
- withUser
37
- } from "./chunk-4Q2CRWI6.js";
38
- import "./chunk-7SUF4VVI.js";
39
- import "./chunk-OR3YPY4I.js";
2
+ SERVICE_NAME_HEADER,
3
+ parseDSN
4
+ } from "./chunk-7SUF4VVI.js";
40
5
  import {
6
+ getSDKVersion
7
+ } from "./chunk-BGLKBQ6N.js";
8
+ import {
9
+ DEFAULT_LOG_LEVEL,
41
10
  LogLevel,
42
11
  getLogLevel,
43
12
  logger,
13
+ parseLogLevel,
44
14
  setLogLevel
45
15
  } from "./chunk-Y4HNUX3Q.js";
46
- import "./chunk-EC3MYSRM.js";
47
- import "./chunk-WII4R5RE.js";
48
- import "./chunk-3RG5ZIWI.js";
16
+ import {
17
+ InterruptPropagator
18
+ } from "./chunk-EC3MYSRM.js";
19
+ import {
20
+ BRIZZ,
21
+ EXTERNAL_LINK_EVENT_NAME,
22
+ EXTERNAL_LINK_TITLE,
23
+ EXTERNAL_LINK_TYPE,
24
+ EXTERNAL_LINK_URL,
25
+ FEEDBACK_ATTR_PREFIX,
26
+ FEEDBACK_COMMENT,
27
+ FEEDBACK_EVENT_NAME,
28
+ FEEDBACK_REASON,
29
+ FEEDBACK_SCORE,
30
+ FEEDBACK_SOURCE,
31
+ FEEDBACK_TYPE,
32
+ INTERNAL_EVENT_PREFIX,
33
+ MESSAGE_ID,
34
+ METRIC_ATTRIBUTE_PREFIX,
35
+ METRIC_COMMENT,
36
+ METRIC_EVENT_NAME,
37
+ METRIC_MAX,
38
+ METRIC_MIN,
39
+ METRIC_NAME,
40
+ METRIC_POLARITY,
41
+ METRIC_POLARITY_NEGATIVE,
42
+ METRIC_POLARITY_POSITIVE,
43
+ METRIC_TIMESTAMP,
44
+ METRIC_UNIT,
45
+ METRIC_VALUE,
46
+ MUTE_INPUT,
47
+ MUTE_OUTPUT,
48
+ MUTE_TOOLS,
49
+ ORGANIZATION_DOMAIN,
50
+ ORGANIZATION_ID,
51
+ ORGANIZATION_NAME,
52
+ ORGANIZATION_PLAN,
53
+ PROPERTIES_CONTEXT_KEY,
54
+ RESERVED_METRIC_NAMES,
55
+ SESSION_ID,
56
+ SESSION_INPUT,
57
+ SESSION_INPUT_CONTEXT,
58
+ SESSION_OBJECT_CONTEXT_KEY,
59
+ SESSION_OUTPUT,
60
+ SESSION_OUTPUT_CONTEXT,
61
+ SESSION_SPAN_NAME,
62
+ SESSION_TITLE,
63
+ SESSION_TITLE_GENERATION,
64
+ SESSION_TITLE_SPAN_NAME,
65
+ USER_EMAIL,
66
+ USER_ID,
67
+ USER_NAME,
68
+ USER_PLAN,
69
+ USER_ROLE
70
+ } from "./chunk-WII4R5RE.js";
71
+ import {
72
+ __require
73
+ } from "./chunk-3RG5ZIWI.js";
49
74
 
50
75
  // src/internal/instrumentation/auto-init.ts
51
76
  import { OpenAIInstrumentation } from "@arizeai/openinference-instrumentation-openai";
@@ -99,7 +124,7 @@ function loadGenAIInstrumentations() {
99
124
  function loadMCPInstrumentation() {
100
125
  void (async () => {
101
126
  try {
102
- const { MCPInstrumentation } = await import("./mcp-7Y3O5QSS.js");
127
+ const { MCPInstrumentation } = await import("./mcp-HBOMHU67.js");
103
128
  const mcp = new MCPInstrumentation({ exceptionLogger });
104
129
  registerInstrumentations({ instrumentations: [mcp] });
105
130
  logger.debug("Auto-loaded MCP instrumentation");
@@ -201,18 +226,2244 @@ function autoInitializeInstrumentations() {
201
226
  }
202
227
  var autoInstrumentationsLoaded = autoInitializeInstrumentations();
203
228
 
204
- // src/index.ts
229
+ // src/internal/sdk.ts
230
+ import { metrics } from "@opentelemetry/api";
231
+ import { registerInstrumentations as registerInstrumentations2 } from "@opentelemetry/instrumentation";
232
+ import {
233
+ defaultResource,
234
+ detectResources,
235
+ envDetector,
236
+ hostDetector,
237
+ processDetector,
238
+ resourceFromAttributes as resourceFromAttributes3
239
+ } from "@opentelemetry/resources";
240
+ import { MeterProvider } from "@opentelemetry/sdk-metrics";
241
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
242
+
243
+ // src/internal/config.ts
244
+ function resolveConfig(options) {
245
+ const envLogLevel = process.env["BRIZZ_LOG_LEVEL"] || options.logLevel?.toString() || DEFAULT_LOG_LEVEL.toString();
246
+ let resolvedLogLevel;
247
+ if (envLogLevel) {
248
+ resolvedLogLevel = parseLogLevel(envLogLevel);
249
+ } else if (typeof options.logLevel === "string") {
250
+ resolvedLogLevel = parseLogLevel(options.logLevel);
251
+ } else {
252
+ resolvedLogLevel = options.logLevel || DEFAULT_LOG_LEVEL;
253
+ }
254
+ setLogLevel(resolvedLogLevel);
255
+ let maskingStatus;
256
+ if (options.masking === true) {
257
+ maskingStatus = "enabled";
258
+ } else if (options.masking === false) {
259
+ maskingStatus = "disabled";
260
+ } else if (typeof options.masking === "object") {
261
+ maskingStatus = "custom";
262
+ } else {
263
+ maskingStatus = "default-disabled";
264
+ }
265
+ logger.debug("Starting configuration resolution", {
266
+ appName: options.appName,
267
+ baseUrl: options.baseUrl,
268
+ hasApiKey: !!options.apiKey,
269
+ dsnProvided: !!(process.env["BRIZZ_DSN"] || options.dsn),
270
+ disableBatch: options.disableBatch,
271
+ logLevel: resolvedLogLevel,
272
+ headersCount: Object.keys(options.headers || {}).length,
273
+ masking: maskingStatus
274
+ });
275
+ let resolvedMasking;
276
+ if (options.masking === true) {
277
+ resolvedMasking = {
278
+ spanMasking: {},
279
+ eventMasking: {}
280
+ };
281
+ } else if (options.masking && typeof options.masking === "object") {
282
+ resolvedMasking = options.masking;
283
+ }
284
+ const resolvedConfig = {
285
+ ...options,
286
+ appName: process.env["BRIZZ_APP_NAME"] || process.env["OTEL_SERVICE_NAME"] || options.appName || "unknown-app",
287
+ appVersion: process.env["BRIZZ_APP_VERSION"] || options.appVersion,
288
+ baseUrl: process.env["BRIZZ_BASE_URL"] || options.baseUrl || "https://telemetry.brizz.dev",
289
+ headers: { ...options.headers },
290
+ apiKey: process.env["BRIZZ_API_KEY"] || options.apiKey,
291
+ disableBatch: process.env["BRIZZ_DISABLE_BATCH"] === "true" || !!options.disableBatch,
292
+ disableSpanExporter: process.env["BRIZZ_DISABLE_SPAN_EXPORTER"] === "true" || !!options.disableSpanExporter,
293
+ environment: process.env["BRIZZ_ENVIRONMENT"] || options.environment,
294
+ logLevel: resolvedLogLevel,
295
+ masking: resolvedMasking
296
+ };
297
+ const dsnInput = process.env["BRIZZ_DSN"] || options.dsn;
298
+ let parsedDSN = null;
299
+ if (dsnInput) {
300
+ const kwargConflicts = [];
301
+ if (options.apiKey !== void 0) {
302
+ kwargConflicts.push("apiKey");
303
+ }
304
+ if (options.baseUrl !== void 0) {
305
+ kwargConflicts.push("baseUrl");
306
+ }
307
+ if (options.appName !== void 0) {
308
+ kwargConflicts.push("appName");
309
+ }
310
+ if (kwargConflicts.length > 0) {
311
+ throw new Error(
312
+ `dsn cannot be combined with kwargs ${kwargConflicts.join(", ")}. The DSN bundles bearer, gateway URL, and service name \u2014 choose one configuration style.`
313
+ );
314
+ }
315
+ const envConflicts = ["BRIZZ_API_KEY", "BRIZZ_BASE_URL", "BRIZZ_APP_NAME"].filter(
316
+ (name) => process.env[name] !== void 0
317
+ );
318
+ if (envConflicts.length > 0) {
319
+ logger.warn(
320
+ `Ignoring ${envConflicts.join(", ")} \u2014 dsn / BRIZZ_DSN takes precedence.`
321
+ );
322
+ }
323
+ resolvedConfig.apiKey = void 0;
324
+ resolvedConfig.baseUrl = "https://telemetry.brizz.dev";
325
+ resolvedConfig.appName = "unknown-app";
326
+ parsedDSN = parseDSN(dsnInput);
327
+ if (parsedDSN) {
328
+ resolvedConfig.appName = parsedDSN.service;
329
+ resolvedConfig.baseUrl = parsedDSN.baseUrl;
330
+ resolvedConfig.apiKey = parsedDSN.bearer;
331
+ }
332
+ } else if (resolvedConfig.apiKey) {
333
+ resolvedConfig.headers["Authorization"] = `Bearer ${resolvedConfig.apiKey}`;
334
+ }
335
+ if (process.env["BRIZZ_HEADERS"]) {
336
+ try {
337
+ const envHeaders = JSON.parse(process.env["BRIZZ_HEADERS"]);
338
+ Object.assign(resolvedConfig.headers, envHeaders);
339
+ logger.debug("Added headers from environment variable", {
340
+ headers: Object.keys(envHeaders)
341
+ });
342
+ } catch (error) {
343
+ logger.error("Failed to parse BRIZZ_HEADERS environment variable", { error });
344
+ throw new Error("Invalid JSON in BRIZZ_HEADERS environment variable", { cause: error });
345
+ }
346
+ }
347
+ if (dsnInput) {
348
+ const authHeaderKeys = /* @__PURE__ */ new Set(["authorization", SERVICE_NAME_HEADER.toLowerCase()]);
349
+ resolvedConfig.headers = Object.fromEntries(
350
+ Object.entries(resolvedConfig.headers).filter(
351
+ ([key]) => !authHeaderKeys.has(key.toLowerCase())
352
+ )
353
+ );
354
+ if (parsedDSN) {
355
+ resolvedConfig.headers["Authorization"] = `Bearer ${parsedDSN.bearer}`;
356
+ resolvedConfig.headers[SERVICE_NAME_HEADER] = parsedDSN.service;
357
+ }
358
+ }
359
+ logger.debug("Configuration resolved with environment variables", {
360
+ appName: resolvedConfig.appName,
361
+ baseUrl: resolvedConfig.baseUrl,
362
+ hasApiKey: !!resolvedConfig.apiKey,
363
+ dsnProvided: !!dsnInput,
364
+ disableBatch: resolvedConfig.disableBatch,
365
+ envOverrides: {
366
+ hasEnvApiKey: !!process.env["BRIZZ_API_KEY"],
367
+ hasEnvBaseUrl: !!process.env["BRIZZ_BASE_URL"],
368
+ hasEnvDsn: !!process.env["BRIZZ_DSN"],
369
+ hasEnvBatch: !!process.env["BRIZZ_DISABLE_BATCH"],
370
+ hasEnvHeaders: !!process.env["BRIZZ_HEADERS"]
371
+ }
372
+ });
373
+ return resolvedConfig;
374
+ }
375
+
376
+ // src/internal/constants.ts
377
+ var BRIZZ_SDK_VERSION = "brizz.sdk.version";
378
+ var BRIZZ_SDK_LANGUAGE = "brizz.sdk.language";
379
+ var SDK_LANGUAGE = "typescript";
380
+
381
+ // src/internal/instrumentation/registry.ts
382
+ import { OpenAIInstrumentation as OpenAIInstrumentation2 } from "@arizeai/openinference-instrumentation-openai";
383
+ import { AnthropicInstrumentation as AnthropicInstrumentation2 } from "@traceloop/instrumentation-anthropic";
384
+ import { BedrockInstrumentation as BedrockInstrumentation2 } from "@traceloop/instrumentation-bedrock";
385
+ import { ChromaDBInstrumentation as ChromaDBInstrumentation2 } from "@traceloop/instrumentation-chromadb";
386
+ import { CohereInstrumentation as CohereInstrumentation2 } from "@traceloop/instrumentation-cohere";
387
+ import { LlamaIndexInstrumentation as LlamaIndexInstrumentation2 } from "@traceloop/instrumentation-llamaindex";
388
+ import { PineconeInstrumentation as PineconeInstrumentation2 } from "@traceloop/instrumentation-pinecone";
389
+ import { QdrantInstrumentation as QdrantInstrumentation2 } from "@traceloop/instrumentation-qdrant";
390
+ import { TogetherInstrumentation as TogetherInstrumentation2 } from "@traceloop/instrumentation-together";
391
+ var InstrumentationRegistry = class _InstrumentationRegistry {
392
+ static instance;
393
+ static getInstance() {
394
+ if (!this.instance) {
395
+ this.instance = new _InstrumentationRegistry();
396
+ }
397
+ return this.instance;
398
+ }
399
+ manualModules = null;
400
+ /**
401
+ * Helper to load instrumentation with optional manual module
402
+ */
403
+ loadInstrumentation(InstrumentationClass, name, manualModule, exceptionLogger2) {
404
+ try {
405
+ const inst = new InstrumentationClass({
406
+ exceptionLogger: exceptionLogger2 || ((error) => logger.error(`Exception in instrumentation: ${String(error)}`))
407
+ });
408
+ if (manualModule) {
409
+ inst.manuallyInstrument(manualModule);
410
+ logger.debug(`Manual instrumentation enabled for ${name}`);
411
+ }
412
+ return inst;
413
+ } catch (error) {
414
+ logger.error(`Failed to load ${name} instrumentation: ${String(error)}`);
415
+ return null;
416
+ }
417
+ }
418
+ /**
419
+ * Load manual instrumentations only (with modules provided by user).
420
+ * @private
421
+ */
422
+ loadManualInstrumentations(instrumentations, exceptionLogger2) {
423
+ if (this.manualModules?.openAI) {
424
+ try {
425
+ const openAIInst = new OpenAIInstrumentation2();
426
+ openAIInst.manuallyInstrument(this.manualModules.openAI);
427
+ instrumentations.push(openAIInst);
428
+ logger.debug("Manual instrumentation enabled for OpenAI");
429
+ } catch (error) {
430
+ logger.error(`Failed to load OpenAI instrumentation: ${String(error)}`);
431
+ }
432
+ }
433
+ const instrumentationConfigs = [
434
+ { class: AnthropicInstrumentation2, name: "Anthropic", module: this.manualModules?.anthropic },
435
+ { class: CohereInstrumentation2, name: "Cohere", module: this.manualModules?.cohere },
436
+ { class: BedrockInstrumentation2, name: "Bedrock", module: this.manualModules?.bedrock },
437
+ { class: PineconeInstrumentation2, name: "Pinecone", module: this.manualModules?.pinecone },
438
+ {
439
+ class: LlamaIndexInstrumentation2,
440
+ name: "LlamaIndex",
441
+ module: this.manualModules?.llamaindex
442
+ },
443
+ { class: ChromaDBInstrumentation2, name: "ChromaDB", module: this.manualModules?.chromadb },
444
+ { class: QdrantInstrumentation2, name: "Qdrant", module: this.manualModules?.qdrant },
445
+ { class: TogetherInstrumentation2, name: "Together", module: this.manualModules?.together }
446
+ ];
447
+ for (const config of instrumentationConfigs) {
448
+ if (!config.module) {
449
+ continue;
450
+ }
451
+ const instrumentation = this.loadInstrumentation(
452
+ config.class,
453
+ config.name,
454
+ config.module,
455
+ exceptionLogger2
456
+ );
457
+ if (instrumentation) {
458
+ instrumentations.push(instrumentation);
459
+ }
460
+ }
461
+ if (this.manualModules?.langchain?.callbackManagerModule) {
462
+ const callbackManagerModule = this.manualModules.langchain.callbackManagerModule;
463
+ void (async () => {
464
+ try {
465
+ const { LangChainInstrumentation } = await import("@arizeai/openinference-instrumentation-langchain");
466
+ const lcInst = new LangChainInstrumentation();
467
+ lcInst.manuallyInstrument(callbackManagerModule);
468
+ logger.debug("Manual instrumentation enabled for LangChain");
469
+ } catch (error) {
470
+ logger.error(
471
+ `Failed to load LangChain instrumentation. Ensure @langchain/core is installed: ${String(error)}`
472
+ );
473
+ }
474
+ })();
475
+ }
476
+ if (this.manualModules?.google_vertexai) {
477
+ const vertexModule = this.manualModules.google_vertexai;
478
+ void (async () => {
479
+ try {
480
+ const { VertexAIInstrumentation } = await import("@traceloop/instrumentation-vertexai");
481
+ const vertexInst = new VertexAIInstrumentation({ exceptionLogger: exceptionLogger2 });
482
+ vertexInst.manuallyInstrument(vertexModule);
483
+ logger.debug("Manual instrumentation enabled for Vertex AI");
484
+ } catch (error) {
485
+ logger.error(
486
+ `Failed to load Vertex AI instrumentation. Ensure @traceloop/instrumentation-vertexai is installed: ${String(error)}`
487
+ );
488
+ }
489
+ })();
490
+ }
491
+ if (this.manualModules?.google_genai) {
492
+ const genaiModule = this.manualModules.google_genai;
493
+ void (async () => {
494
+ try {
495
+ const { GoogleGenAIInstrumentation } = await import("./google-genai-T7I4FFIP.js");
496
+ const genaiInst = new GoogleGenAIInstrumentation({ exceptionLogger: exceptionLogger2 });
497
+ genaiInst.manuallyInstrument(genaiModule);
498
+ logger.debug("Manual instrumentation enabled for Google GenAI");
499
+ } catch (error) {
500
+ logger.error(
501
+ `Failed to apply Google GenAI instrumentation. Ensure @traceloop/instrumentation-google-generativeai is installed; on a read-only ESM module namespace use instrumentGoogleGenAI from @brizz/sdk/google-genai instead: ${String(error)}`
502
+ );
503
+ }
504
+ })();
505
+ }
506
+ if (this.manualModules?.mcp) {
507
+ const mcpModules = this.manualModules.mcp;
508
+ void (async () => {
509
+ try {
510
+ const { MCPInstrumentation } = await import("./mcp-HBOMHU67.js");
511
+ const instrumentation = new MCPInstrumentation({ exceptionLogger: exceptionLogger2 });
512
+ instrumentation.manuallyInstrument(mcpModules);
513
+ logger.debug("Manual instrumentation enabled for MCP");
514
+ } catch (error) {
515
+ logger.error(`Failed to apply MCP instrumentation: ${String(error)}`);
516
+ }
517
+ })();
518
+ }
519
+ }
520
+ /**
521
+ * Set manual instrumentation modules for Next.js/Webpack environments
522
+ */
523
+ setManualModules(modules) {
524
+ this.manualModules = modules;
525
+ logger.info("Manual instrumentation modules configured for Next.js/Webpack compatibility");
526
+ }
527
+ /**
528
+ * Get manual instrumentations only.
529
+ * Auto-instrumentations are handled at import time.
530
+ */
531
+ getManualInstrumentations() {
532
+ if (!this.manualModules || Object.keys(this.manualModules).length === 0) {
533
+ logger.debug("No manual instrumentation modules configured");
534
+ return [];
535
+ }
536
+ const instrumentations = [];
537
+ const exceptionLogger2 = (error) => {
538
+ logger.error(`Exception in manual instrumentation: ${String(error)}`);
539
+ };
540
+ this.loadManualInstrumentations(instrumentations, exceptionLogger2);
541
+ logger.info(`Loaded ${instrumentations.length} manual instrumentations`);
542
+ return instrumentations;
543
+ }
544
+ };
545
+
546
+ // src/internal/log/logging.ts
205
547
  import { SeverityNumber } from "@opentelemetry/api-logs";
548
+ import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
549
+ import { resourceFromAttributes } from "@opentelemetry/resources";
550
+ import {
551
+ LoggerProvider
552
+ } from "@opentelemetry/sdk-logs";
553
+
554
+ // src/internal/trace/session.ts
555
+ import { context, trace, SpanStatusCode } from "@opentelemetry/api";
556
+ function setCurrentSpanCustomProperties(properties) {
557
+ const current = trace.getActiveSpan();
558
+ if (!current || !current.isRecording()) {
559
+ return;
560
+ }
561
+ for (const [key, value] of Object.entries(properties)) {
562
+ try {
563
+ current.setAttribute(`${BRIZZ}.${key}`, value);
564
+ } catch {
565
+ }
566
+ }
567
+ }
568
+ function callWithProperties(properties, fn, thisArg, ...args) {
569
+ const base = context.active();
570
+ const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
571
+ const merged = prev ? { ...prev, ...properties } : properties;
572
+ const next = base.setValue(PROPERTIES_CONTEXT_KEY, merged);
573
+ return context.with(next, fn, thisArg, ...args);
574
+ }
575
+ function withProperties(properties, fn, thisArg) {
576
+ return function wrapped(...args) {
577
+ return callWithProperties(
578
+ properties,
579
+ fn,
580
+ thisArg !== void 0 ? thisArg : this,
581
+ ...args
582
+ );
583
+ };
584
+ }
585
+ function propagatePropertiesImperatively(properties) {
586
+ try {
587
+ const manager = context;
588
+ const mgr = manager._getContextManager?.();
589
+ const store = mgr?._asyncLocalStorage;
590
+ if (!store || typeof store.enterWith !== "function") {
591
+ return;
592
+ }
593
+ const base = context.active();
594
+ const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
595
+ const merged = prev ? { ...prev, ...properties } : properties;
596
+ store.enterWith(base.setValue(PROPERTIES_CONTEXT_KEY, merged));
597
+ } catch {
598
+ }
599
+ }
600
+ function setUser(user) {
601
+ const properties = { [USER_ID]: user.id };
602
+ if (user.email !== void 0) {
603
+ properties[USER_EMAIL] = user.email;
604
+ }
605
+ if (user.name !== void 0) {
606
+ properties[USER_NAME] = user.name;
607
+ }
608
+ if (user.role !== void 0) {
609
+ properties[USER_ROLE] = user.role;
610
+ }
611
+ if (user.plan !== void 0) {
612
+ properties[USER_PLAN] = user.plan;
613
+ }
614
+ if (user.traits) {
615
+ for (const [key, value] of Object.entries(user.traits)) {
616
+ const k = `user.${key}`;
617
+ if (properties[k] === void 0) {
618
+ properties[k] = value;
619
+ }
620
+ }
621
+ }
622
+ setCurrentSpanCustomProperties(properties);
623
+ propagatePropertiesImperatively(properties);
624
+ }
625
+ function setOrganization(org) {
626
+ const properties = { [ORGANIZATION_ID]: org.id };
627
+ if (org.name !== void 0) {
628
+ properties[ORGANIZATION_NAME] = org.name;
629
+ }
630
+ if (org.plan !== void 0) {
631
+ properties[ORGANIZATION_PLAN] = org.plan;
632
+ }
633
+ if (org.domain !== void 0) {
634
+ properties[ORGANIZATION_DOMAIN] = org.domain;
635
+ }
636
+ if (org.traits) {
637
+ for (const [key, value] of Object.entries(org.traits)) {
638
+ const k = `organization.${key}`;
639
+ if (properties[k] === void 0) {
640
+ properties[k] = value;
641
+ }
642
+ }
643
+ }
644
+ setCurrentSpanCustomProperties(properties);
645
+ propagatePropertiesImperatively(properties);
646
+ }
647
+ function setMessageId(id) {
648
+ const properties = { [MESSAGE_ID]: id };
649
+ setCurrentSpanCustomProperties(properties);
650
+ propagatePropertiesImperatively(properties);
651
+ }
652
+ function setSessionId(id) {
653
+ const properties = { [SESSION_ID]: id };
654
+ setCurrentSpanCustomProperties(properties);
655
+ propagatePropertiesImperatively(properties);
656
+ }
657
+ function userProperties(user) {
658
+ const properties = { [USER_ID]: user.id };
659
+ if (user.email !== void 0) {
660
+ properties[USER_EMAIL] = user.email;
661
+ }
662
+ if (user.name !== void 0) {
663
+ properties[USER_NAME] = user.name;
664
+ }
665
+ if (user.role !== void 0) {
666
+ properties[USER_ROLE] = user.role;
667
+ }
668
+ if (user.plan !== void 0) {
669
+ properties[USER_PLAN] = user.plan;
670
+ }
671
+ if (user.traits) {
672
+ for (const [key, value] of Object.entries(user.traits)) {
673
+ const k = `user.${key}`;
674
+ if (properties[k] === void 0) {
675
+ properties[k] = value;
676
+ }
677
+ }
678
+ }
679
+ return properties;
680
+ }
681
+ function organizationProperties(org) {
682
+ const properties = { [ORGANIZATION_ID]: org.id };
683
+ if (org.name !== void 0) {
684
+ properties[ORGANIZATION_NAME] = org.name;
685
+ }
686
+ if (org.plan !== void 0) {
687
+ properties[ORGANIZATION_PLAN] = org.plan;
688
+ }
689
+ if (org.domain !== void 0) {
690
+ properties[ORGANIZATION_DOMAIN] = org.domain;
691
+ }
692
+ if (org.traits) {
693
+ for (const [key, value] of Object.entries(org.traits)) {
694
+ const k = `organization.${key}`;
695
+ if (properties[k] === void 0) {
696
+ properties[k] = value;
697
+ }
698
+ }
699
+ }
700
+ return properties;
701
+ }
702
+ function callWithUser(user, fn, thisArg, ...args) {
703
+ return callWithProperties(userProperties(user), fn, thisArg, ...args);
704
+ }
705
+ function withUser(user, fn, thisArg) {
706
+ return withProperties(userProperties(user), fn, thisArg);
707
+ }
708
+ function callWithOrganization(org, fn, thisArg, ...args) {
709
+ return callWithProperties(organizationProperties(org), fn, thisArg, ...args);
710
+ }
711
+ function withOrganization(org, fn, thisArg) {
712
+ return withProperties(organizationProperties(org), fn, thisArg);
713
+ }
714
+ function callWithMessageId(id, fn, thisArg, ...args) {
715
+ return callWithProperties({ [MESSAGE_ID]: id }, fn, thisArg, ...args);
716
+ }
717
+ function withMessageId(id, fn, thisArg) {
718
+ return withProperties({ [MESSAGE_ID]: id }, fn, thisArg);
719
+ }
720
+ function inheritedMuteTools() {
721
+ const properties = context.active().getValue(PROPERTIES_CONTEXT_KEY);
722
+ return properties?.[MUTE_TOOLS];
723
+ }
724
+ function muteProperties(options) {
725
+ const { input = true, output = true, tools = output } = options;
726
+ const properties = {};
727
+ if (input) {
728
+ properties[MUTE_INPUT] = "true";
729
+ }
730
+ if (output) {
731
+ properties[MUTE_OUTPUT] = "true";
732
+ }
733
+ if (tools !== output) {
734
+ properties[MUTE_TOOLS] = String(tools);
735
+ } else {
736
+ const inherited = inheritedMuteTools();
737
+ if (tools && inherited === "false") {
738
+ properties[MUTE_TOOLS] = "true";
739
+ } else if (options.tools === false && inherited === "true") {
740
+ properties[MUTE_TOOLS] = "false";
741
+ }
742
+ }
743
+ return properties;
744
+ }
745
+ function callWithMute(options, fn, thisArg, ...args) {
746
+ return callWithProperties(muteProperties(options), fn, thisArg, ...args);
747
+ }
748
+ function withMute(options, fn, thisArg) {
749
+ return withProperties(muteProperties(options), fn, thisArg);
750
+ }
751
+ function withSessionId(sessionId, fn, thisArg, extraProperties) {
752
+ const properties = { [SESSION_ID]: sessionId, ...extraProperties };
753
+ return withProperties(properties, fn, thisArg);
754
+ }
755
+ function callWithSessionId(sessionId, fn, thisArg, ...args) {
756
+ return callWithProperties({ [SESSION_ID]: sessionId }, fn, thisArg, ...args);
757
+ }
758
+ var Session = class {
759
+ span;
760
+ inputs = [];
761
+ outputs = [];
762
+ inputContexts = [];
763
+ outputContexts = [];
764
+ sessionId;
765
+ constructor(sessionId, span) {
766
+ this.sessionId = sessionId;
767
+ this.span = span;
768
+ }
769
+ /**
770
+ * Append a user turn to session input tracking.
771
+ *
772
+ * Each call appends one element to `brizz.session.input` (the text) AND one
773
+ * element to `brizz.session.input.context` (the per-turn context bag). The
774
+ * two arrays stay index-aligned — the ingestion pipeline zips them together
775
+ * so the i-th context bag lands on the i-th user_display conversation item's
776
+ * `span_attributes` map.
777
+ *
778
+ * @param text - Text to append (null becomes a null/"hide marker")
779
+ * @param context - Optional per-turn context bag to attach to this turn
780
+ */
781
+ setInput(text, context4) {
782
+ this.inputs.push(text);
783
+ this.inputContexts.push(context4 ?? {});
784
+ this.span.setAttribute(SESSION_INPUT, JSON.stringify(this.inputs));
785
+ this.span.setAttribute(SESSION_INPUT_CONTEXT, JSON.stringify(this.inputContexts));
786
+ }
787
+ /**
788
+ * Append an assistant turn to session output tracking.
789
+ *
790
+ * Symmetric to {@link setInput} — appends one text element and one
791
+ * context-bag element to the index-aligned `brizz.session.output` /
792
+ * `brizz.session.output.context` arrays.
793
+ *
794
+ * @param text - Text to append (null becomes a null/"hide marker")
795
+ * @param context - Optional per-turn context bag to attach to this turn
796
+ */
797
+ setOutput(text, context4) {
798
+ this.outputs.push(text);
799
+ this.outputContexts.push(context4 ?? {});
800
+ this.span.setAttribute(SESSION_OUTPUT, JSON.stringify(this.outputs));
801
+ this.span.setAttribute(SESSION_OUTPUT_CONTEXT, JSON.stringify(this.outputContexts));
802
+ }
803
+ /**
804
+ * Set the session title on the span.
805
+ *
806
+ * @param title - The generated title string
807
+ */
808
+ setTitle(title) {
809
+ this.span.setAttribute(SESSION_TITLE, title);
810
+ }
811
+ /**
812
+ * Update custom properties on the session span.
813
+ * Properties are prefixed with 'brizz.'.
814
+ *
815
+ * @param properties - Key-value properties to set on the session
816
+ */
817
+ updateProperties(properties) {
818
+ for (const [key, value] of Object.entries(properties)) {
819
+ this.span.setAttribute(`${BRIZZ}.${key}`, value);
820
+ }
821
+ }
822
+ /**
823
+ * Set end-user identity on the session span: `brizz.user.id` and, when
824
+ * provided, `brizz.user.email` / `brizz.user.name`. Undefined fields are omitted.
825
+ *
826
+ * @param user - User identity (`id` required; `email` / `name` optional)
827
+ */
828
+ setUser(user) {
829
+ if (user.traits) {
830
+ for (const [key, value] of Object.entries(user.traits)) {
831
+ this.span.setAttribute(`${BRIZZ}.user.${key}`, value);
832
+ }
833
+ }
834
+ this.span.setAttribute(`${BRIZZ}.${USER_ID}`, user.id);
835
+ if (user.email !== void 0) {
836
+ this.span.setAttribute(`${BRIZZ}.${USER_EMAIL}`, user.email);
837
+ }
838
+ if (user.name !== void 0) {
839
+ this.span.setAttribute(`${BRIZZ}.${USER_NAME}`, user.name);
840
+ }
841
+ if (user.role !== void 0) {
842
+ this.span.setAttribute(`${BRIZZ}.${USER_ROLE}`, user.role);
843
+ }
844
+ if (user.plan !== void 0) {
845
+ this.span.setAttribute(`${BRIZZ}.${USER_PLAN}`, user.plan);
846
+ }
847
+ }
848
+ /**
849
+ * Set organization identity on the session span: `brizz.organization.id` and,
850
+ * when provided, `brizz.organization.name`. Undefined fields are omitted.
851
+ *
852
+ * @param org - Organization identity (`id` required; `name` optional)
853
+ */
854
+ setOrganization(org) {
855
+ if (org.traits) {
856
+ for (const [key, value] of Object.entries(org.traits)) {
857
+ this.span.setAttribute(`${BRIZZ}.organization.${key}`, value);
858
+ }
859
+ }
860
+ this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_ID}`, org.id);
861
+ if (org.name !== void 0) {
862
+ this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_NAME}`, org.name);
863
+ }
864
+ if (org.plan !== void 0) {
865
+ this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_PLAN}`, org.plan);
866
+ }
867
+ if (org.domain !== void 0) {
868
+ this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_DOMAIN}`, org.domain);
869
+ }
870
+ }
871
+ /**
872
+ * Attach an external link (URL) to this session.
873
+ *
874
+ * The link surfaces on the session's detail panel in Brizz — use it to
875
+ * correlate a session with an external record such as a Datadog trace,
876
+ * Sentry issue, or internal dashboard. Re-sending the same URL is idempotent;
877
+ * distinct URLs add separate links.
878
+ *
879
+ * @param url - The link target
880
+ * @param options - Optional `title` (defaults to the URL host) and `linkType`
881
+ * (free-form category, defaults to `'generic'`)
882
+ */
883
+ addExternalLink(url, options) {
884
+ emitExternalLink(this.sessionId, url, options?.title, options?.linkType);
885
+ }
886
+ };
887
+ var SessionTitle = class {
888
+ span;
889
+ constructor(span) {
890
+ this.span = span;
891
+ }
892
+ /**
893
+ * Set the generated title on the wrapper span.
894
+ *
895
+ * @param title - The generated title string
896
+ */
897
+ setTitle(title) {
898
+ this.span.setAttribute(SESSION_TITLE, title);
899
+ }
900
+ };
901
+ function getActiveSession() {
902
+ return context.active().getValue(SESSION_OBJECT_CONTEXT_KEY);
903
+ }
904
+ function resolveSessionIdFromContext() {
905
+ const active = getActiveSession();
906
+ if (active) {
907
+ return active.sessionId;
908
+ }
909
+ const props = context.active().getValue(PROPERTIES_CONTEXT_KEY);
910
+ return props?.[SESSION_ID];
911
+ }
912
+ function resolveMessageIdFromContext() {
913
+ const props = context.active().getValue(PROPERTIES_CONTEXT_KEY);
914
+ return props?.[MESSAGE_ID];
915
+ }
916
+ function emitExternalLink(sessionId, url, title, linkType) {
917
+ try {
918
+ emitEventWithSessionId(sessionId, EXTERNAL_LINK_EVENT_NAME, {
919
+ [EXTERNAL_LINK_URL]: url,
920
+ [EXTERNAL_LINK_TITLE]: title ?? "",
921
+ [EXTERNAL_LINK_TYPE]: linkType ?? "generic"
922
+ });
923
+ } catch (error) {
924
+ logger.warn("addExternalLink: failed to emit external link", error);
925
+ }
926
+ }
927
+ function addExternalLink(url, options) {
928
+ const sessionId = options?.sessionId ?? resolveSessionIdFromContext();
929
+ if (!sessionId) {
930
+ logger.warn(
931
+ "addExternalLink called without a resolvable session id; link dropped. Pass options.sessionId or call inside a startSession/callWithSessionId scope."
932
+ );
933
+ return;
934
+ }
935
+ emitExternalLink(sessionId, url, options?.title, options?.linkType);
936
+ }
937
+ function recordFeedback(type, options) {
938
+ const eventAttributes = { [FEEDBACK_TYPE]: type };
939
+ if (options?.score !== void 0) {
940
+ eventAttributes[FEEDBACK_SCORE] = options.score;
941
+ }
942
+ if (options?.reason !== void 0) {
943
+ eventAttributes[FEEDBACK_REASON] = options.reason;
944
+ }
945
+ if (options?.comment !== void 0) {
946
+ eventAttributes[FEEDBACK_COMMENT] = options.comment;
947
+ }
948
+ if (options?.source !== void 0) {
949
+ eventAttributes[FEEDBACK_SOURCE] = options.source;
950
+ }
951
+ if (options?.attributes) {
952
+ for (const [key, value] of Object.entries(options.attributes)) {
953
+ const k = `${FEEDBACK_ATTR_PREFIX}${key}`;
954
+ if (eventAttributes[k] === void 0) {
955
+ eventAttributes[k] = value;
956
+ }
957
+ }
958
+ }
959
+ const messageId = options?.messageId ?? resolveMessageIdFromContext();
960
+ const sessionId = options?.sessionId ?? resolveSessionIdFromContext();
961
+ if (messageId === void 0 && sessionId === void 0) {
962
+ logger.warn(
963
+ "recordFeedback called with no resolvable message id or session id; the feedback cannot be attributed to a message or conversation. Pass options.messageId / options.sessionId or call inside a startSession/callWithMessageId scope."
964
+ );
965
+ }
966
+ const anchor = {};
967
+ if (messageId !== void 0) {
968
+ anchor[MESSAGE_ID] = messageId;
969
+ }
970
+ if (sessionId !== void 0) {
971
+ anchor[SESSION_ID] = sessionId;
972
+ }
973
+ try {
974
+ if (Object.keys(anchor).length === 0) {
975
+ emitEvent(FEEDBACK_EVENT_NAME, eventAttributes);
976
+ } else {
977
+ callWithProperties(anchor, () => emitEvent(FEEDBACK_EVENT_NAME, eventAttributes));
978
+ }
979
+ } catch (error) {
980
+ logger.warn("recordFeedback: failed to emit feedback event", error);
981
+ }
982
+ }
983
+ var METRIC_NAME_PATTERN = /^[a-z][a-z0-9_.-]{0,63}$/;
984
+ var METRIC_COMMENT_MAX_LEN = 4096;
985
+ var METRIC_ATTRIBUTES_MAX = 20;
986
+ var METRIC_ATTRIBUTE_VALUE_MAX_LEN = 256;
987
+ function recordMetric(options) {
988
+ try {
989
+ recordMetricImpl(options);
990
+ } catch (error) {
991
+ logger.warn(`recordMetric(${JSON.stringify(options?.name)}) failed; metric dropped.`, error);
992
+ }
993
+ }
994
+ function recordMetricImpl(options) {
995
+ const name = typeof options.name === "string" ? options.name.toLowerCase() : "";
996
+ if (!METRIC_NAME_PATTERN.test(name)) {
997
+ logger.warn(
998
+ `recordMetric called with an invalid name ${JSON.stringify(options.name)}; metric dropped. Names must match ${METRIC_NAME_PATTERN.source} after lowercasing.`
999
+ );
1000
+ return;
1001
+ }
1002
+ if (RESERVED_METRIC_NAMES.has(name)) {
1003
+ logger.warn(
1004
+ `recordMetric called with the reserved name ${JSON.stringify(name)}; metric dropped. Brizz computes this metric itself \u2014 pick a different name.`
1005
+ );
1006
+ return;
1007
+ }
1008
+ const { value } = options;
1009
+ let numericValue;
1010
+ if (typeof value === "boolean") {
1011
+ numericValue = value ? 1 : 0;
1012
+ } else if (typeof value === "number" && Number.isFinite(value)) {
1013
+ numericValue = value;
1014
+ } else {
1015
+ logger.warn(
1016
+ `recordMetric(${name}) called with a non-finite or non-numeric value ${JSON.stringify(value)}; metric dropped.`
1017
+ );
1018
+ return;
1019
+ }
1020
+ const eventAttributes = {
1021
+ [METRIC_NAME]: name,
1022
+ [METRIC_VALUE]: numericValue
1023
+ };
1024
+ if (options.unit !== void 0) {
1025
+ eventAttributes[METRIC_UNIT] = options.unit;
1026
+ }
1027
+ if (options.minValue !== void 0) {
1028
+ eventAttributes[METRIC_MIN] = options.minValue;
1029
+ }
1030
+ if (options.maxValue !== void 0) {
1031
+ eventAttributes[METRIC_MAX] = options.maxValue;
1032
+ }
1033
+ if (options.comment !== void 0) {
1034
+ let comment = options.comment;
1035
+ if (comment.length > METRIC_COMMENT_MAX_LEN) {
1036
+ logger.warn(
1037
+ `recordMetric(${name}) comment exceeds ${METRIC_COMMENT_MAX_LEN} characters; truncated.`
1038
+ );
1039
+ comment = comment.slice(0, METRIC_COMMENT_MAX_LEN);
1040
+ }
1041
+ eventAttributes[METRIC_COMMENT] = comment;
1042
+ }
1043
+ if (options.polarity !== void 0) {
1044
+ const polarity = options.polarity;
1045
+ if (polarity === METRIC_POLARITY_POSITIVE || polarity === METRIC_POLARITY_NEGATIVE) {
1046
+ eventAttributes[METRIC_POLARITY] = polarity;
1047
+ } else {
1048
+ logger.warn(
1049
+ `recordMetric(${name}) called with an invalid polarity ${JSON.stringify(polarity)}; expected '${METRIC_POLARITY_POSITIVE}' or '${METRIC_POLARITY_NEGATIVE}'. Emitting the metric without it.`
1050
+ );
1051
+ }
1052
+ }
1053
+ if (options.timestamp !== void 0) {
1054
+ if (Number.isFinite(options.timestamp.getTime())) {
1055
+ eventAttributes[METRIC_TIMESTAMP] = options.timestamp.toISOString();
1056
+ } else {
1057
+ logger.warn(
1058
+ `recordMetric(${name}) called with an invalid timestamp; emitting the metric without it.`
1059
+ );
1060
+ }
1061
+ }
1062
+ if (options.attributes) {
1063
+ let accepted = 0;
1064
+ for (const [key, attrValue] of Object.entries(options.attributes)) {
1065
+ if (accepted >= METRIC_ATTRIBUTES_MAX) {
1066
+ logger.warn(
1067
+ `recordMetric(${name}) called with more than ${METRIC_ATTRIBUTES_MAX} attributes; the excess was dropped.`
1068
+ );
1069
+ break;
1070
+ }
1071
+ const normalizedKey = key.toLowerCase();
1072
+ if (!METRIC_NAME_PATTERN.test(normalizedKey)) {
1073
+ logger.warn(
1074
+ `recordMetric(${name}) called with an invalid attribute key ${JSON.stringify(key)}; that attribute was dropped. Keys must match ${METRIC_NAME_PATTERN.source} after lowercasing.`
1075
+ );
1076
+ continue;
1077
+ }
1078
+ let text = typeof attrValue === "string" ? attrValue : String(attrValue);
1079
+ if (text.length > METRIC_ATTRIBUTE_VALUE_MAX_LEN) {
1080
+ logger.warn(
1081
+ `recordMetric(${name}) attribute ${JSON.stringify(normalizedKey)} exceeds ${METRIC_ATTRIBUTE_VALUE_MAX_LEN} characters; truncated.`
1082
+ );
1083
+ text = text.slice(0, METRIC_ATTRIBUTE_VALUE_MAX_LEN);
1084
+ }
1085
+ eventAttributes[`${METRIC_ATTRIBUTE_PREFIX}${normalizedKey}`] = text;
1086
+ accepted += 1;
1087
+ }
1088
+ }
1089
+ const sessionId = options.sessionId ?? resolveSessionIdFromContext();
1090
+ if (sessionId === void 0) {
1091
+ logger.warn(
1092
+ `recordMetric(${name}) called with no resolvable session id; the metric cannot be attributed to a conversation and is dropped. Pass options.sessionId or call inside a startSession/callWithSessionId scope.`
1093
+ );
1094
+ return;
1095
+ }
1096
+ try {
1097
+ callWithProperties(
1098
+ { [SESSION_ID]: sessionId },
1099
+ () => emitEvent(METRIC_EVENT_NAME, eventAttributes)
1100
+ );
1101
+ } catch (error) {
1102
+ logger.warn("recordMetric: failed to emit metric event", error);
1103
+ }
1104
+ }
1105
+ function startSession(sessionId, callback, extraProperties, options) {
1106
+ const isTitle = options?.mode === "title";
1107
+ const spanName = isTitle ? SESSION_TITLE_SPAN_NAME : SESSION_SPAN_NAME;
1108
+ const tracer = trace.getTracer("@brizz/sdk");
1109
+ return tracer.startActiveSpan(spanName, (span) => {
1110
+ span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
1111
+ if (extraProperties) {
1112
+ for (const [key, value] of Object.entries(extraProperties)) {
1113
+ span.setAttribute(`${BRIZZ}.${key}`, value);
1114
+ }
1115
+ }
1116
+ const session = new Session(sessionId, span);
1117
+ const contextProperties = { [SESSION_ID]: sessionId };
1118
+ if (isTitle) {
1119
+ contextProperties[SESSION_TITLE_GENERATION] = "true";
1120
+ }
1121
+ if (extraProperties) {
1122
+ for (const [key, value] of Object.entries(extraProperties)) {
1123
+ contextProperties[key] = String(value);
1124
+ }
1125
+ }
1126
+ return callWithProperties(contextProperties, () => {
1127
+ const sessionCtx = context.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);
1128
+ return context.with(sessionCtx, () => {
1129
+ try {
1130
+ const result = callback(session);
1131
+ if (result && typeof result.then === "function") {
1132
+ return result.then((value) => {
1133
+ span.end();
1134
+ return value;
1135
+ }).catch((error) => {
1136
+ span.recordException(error);
1137
+ span.setStatus({ code: SpanStatusCode.ERROR });
1138
+ span.end();
1139
+ throw error;
1140
+ });
1141
+ }
1142
+ span.end();
1143
+ return result;
1144
+ } catch (error) {
1145
+ span.recordException(error);
1146
+ span.setStatus({ code: SpanStatusCode.ERROR });
1147
+ span.end();
1148
+ throw error;
1149
+ }
1150
+ });
1151
+ });
1152
+ });
1153
+ }
1154
+ function startSessionTitle(callback, options) {
1155
+ const resolvedSessionId = options?.sessionId ?? getActiveSession()?.sessionId;
1156
+ const tracer = trace.getTracer("@brizz/sdk");
1157
+ return tracer.startActiveSpan(SESSION_TITLE_SPAN_NAME, (span) => {
1158
+ if (resolvedSessionId) {
1159
+ span.setAttribute(`${BRIZZ}.${SESSION_ID}`, resolvedSessionId);
1160
+ }
1161
+ const sessionTitle = new SessionTitle(span);
1162
+ const properties = { [SESSION_TITLE_GENERATION]: "true" };
1163
+ if (resolvedSessionId) {
1164
+ properties[SESSION_ID] = resolvedSessionId;
1165
+ }
1166
+ return callWithProperties(properties, () => {
1167
+ try {
1168
+ const result = callback(sessionTitle);
1169
+ if (result && typeof result.then === "function") {
1170
+ return result.then((value) => {
1171
+ span.end();
1172
+ return value;
1173
+ }).catch((error) => {
1174
+ span.recordException(error);
1175
+ span.setStatus({ code: SpanStatusCode.ERROR });
1176
+ span.end();
1177
+ throw error;
1178
+ });
1179
+ }
1180
+ span.end();
1181
+ return result;
1182
+ } catch (error) {
1183
+ span.recordException(error);
1184
+ span.setStatus({ code: SpanStatusCode.ERROR });
1185
+ span.end();
1186
+ throw error;
1187
+ }
1188
+ });
1189
+ });
1190
+ }
1191
+
1192
+ // src/internal/log/processors/log-processor.ts
1193
+ import { context as context2 } from "@opentelemetry/api";
1194
+ import { BatchLogRecordProcessor, SimpleLogRecordProcessor } from "@opentelemetry/sdk-logs";
206
1195
 
207
- // src/init.ts
208
- var init_exports = {};
1196
+ // src/internal/masking/patterns.ts
1197
+ var DEFAULT_PII_PATTERNS = [
1198
+ // Phone numbers (US format)
1199
+ {
1200
+ name: "us_phone_numbers",
1201
+ 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]|$)`
1202
+ },
1203
+ // Credit card numbers
1204
+ {
1205
+ name: "credit_cards",
1206
+ 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`
1207
+ },
1208
+ {
1209
+ name: "credit_cards_with_separators",
1210
+ 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`
1211
+ },
1212
+ // IP addresses (IPv4)
1213
+ {
1214
+ name: "ipv4_addresses",
1215
+ 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`
1216
+ },
1217
+ // API keys/tokens
1218
+ {
1219
+ name: "generic_api_keys",
1220
+ 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`
1221
+ },
1222
+ {
1223
+ name: "openai_keys",
1224
+ pattern: String.raw`\bsk[-_][a-zA-Z0-9]{20,}\b`
1225
+ },
1226
+ // AWS Keys
1227
+ {
1228
+ name: "aws_access_keys",
1229
+ pattern: String.raw`\b(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\b`
1230
+ },
1231
+ // GitHub tokens
1232
+ {
1233
+ name: "github_tokens",
1234
+ pattern: String.raw`\bghp_[a-zA-Z0-9]{36}\b`
1235
+ },
1236
+ // Slack tokens
1237
+ {
1238
+ name: "slack_tokens",
1239
+ pattern: String.raw`\bxox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24,34}\b`
1240
+ },
1241
+ // Stripe keys
1242
+ {
1243
+ name: "stripe_keys",
1244
+ pattern: String.raw`\b(?:sk|pk)_(?:test|live)_[a-zA-Z0-9]{24,}\b`
1245
+ },
1246
+ // JWT tokens
1247
+ {
1248
+ name: "jwt_tokens",
1249
+ pattern: String.raw`\beyJ[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\\.[A-Za-z0-9_-]{2,}\b`
1250
+ },
1251
+ // MAC addresses
1252
+ {
1253
+ name: "mac_addresses",
1254
+ pattern: String.raw`\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b`
1255
+ },
1256
+ // IPv6 addresses
1257
+ {
1258
+ name: "ipv6_addresses",
1259
+ pattern: String.raw`\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b`
1260
+ },
1261
+ // Bitcoin addresses
1262
+ {
1263
+ name: "bitcoin_addresses",
1264
+ pattern: String.raw`\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b`
1265
+ },
1266
+ // Ethereum addresses
1267
+ {
1268
+ name: "ethereum_addresses",
1269
+ pattern: String.raw`\b0x[a-fA-F0-9]{40}(?![a-fA-F0-9])\b`
1270
+ },
1271
+ // Database connection strings
1272
+ {
1273
+ name: "database_connections",
1274
+ 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`
1275
+ },
1276
+ // Private keys
1277
+ {
1278
+ name: "rsa_private_keys",
1279
+ pattern: "-----BEGIN (?:RSA )?PRIVATE KEY-----"
1280
+ },
1281
+ {
1282
+ name: "pgp_private_keys",
1283
+ pattern: "-----BEGIN PGP PRIVATE KEY BLOCK-----"
1284
+ },
1285
+ // Additional API Keys and Tokens
1286
+ {
1287
+ name: "google_oauth",
1288
+ pattern: String.raw`\bya29\\.[a-zA-Z0-9_-]{60,}\b`
1289
+ },
1290
+ {
1291
+ name: "firebase_tokens",
1292
+ pattern: String.raw`\bAAAA[A-Za-z0-9_-]{100,}\b`
1293
+ },
1294
+ {
1295
+ name: "google_app_ids",
1296
+ pattern: String.raw`\b[0-9]+-\w+\.apps\.googleusercontent\.com\b`
1297
+ },
1298
+ {
1299
+ name: "facebook_secrets",
1300
+ 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]`
1301
+ },
1302
+ {
1303
+ name: "github_keys",
1304
+ 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]`
1305
+ },
1306
+ {
1307
+ name: "heroku_keys",
1308
+ 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\\-]`
1309
+ },
1310
+ {
1311
+ name: "slack_api_keys",
1312
+ 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]`
1313
+ },
1314
+ {
1315
+ name: "slack_api_tokens",
1316
+ pattern: String.raw`\b(xox[pb](?:-[a-zA-Z0-9]+){4,})\b`
1317
+ },
1318
+ // Extended Private Keys and Certificates
1319
+ {
1320
+ name: "dsa_private_keys",
1321
+ pattern: String.raw`-----BEGIN DSA PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END DSA PRIVATE KEY-----`
1322
+ },
1323
+ {
1324
+ name: "ec_private_keys",
1325
+ pattern: String.raw`-----BEGIN (?:EC|ECDSA) PRIVATE KEY-----(?:[a-zA-Z0-9\+\=\/"']|\s)+?-----END (?:EC|ECDSA) PRIVATE KEY-----`
1326
+ },
1327
+ {
1328
+ name: "encrypted_private_keys",
1329
+ pattern: String.raw`-----BEGIN ENCRYPTED PRIVATE KEY-----(?:.|\s)+?-----END ENCRYPTED PRIVATE KEY-----`
1330
+ },
1331
+ {
1332
+ name: "ssl_certificates",
1333
+ pattern: String.raw`-----BEGIN CERTIFICATE-----(?:.|\n)+?\s*-----END CERTIFICATE-----`
1334
+ },
1335
+ {
1336
+ name: "ssh_dss_public",
1337
+ pattern: String.raw`\bssh-dss [0-9A-Za-z+/]+[=]{2}\b`
1338
+ },
1339
+ {
1340
+ name: "ssh_rsa_public",
1341
+ pattern: String.raw`\bssh-rsa AAAA[0-9A-Za-z+/]+[=]{0,3} [^@]+@[^@]+\b`
1342
+ },
1343
+ {
1344
+ name: "putty_ssh_keys",
1345
+ pattern: String.raw`PuTTY-User-Key-File-2: ssh-(?:rsa|dss)\s*Encryption: none(?:.|\s?)*?Private-MAC:`
1346
+ },
1347
+ // Security and Network
1348
+ {
1349
+ name: "cve_numbers",
1350
+ pattern: String.raw`\b[Cc][Vv][Ee]-\\d{4}-\\d{4,7}\b`
1351
+ },
1352
+ {
1353
+ name: "microsoft_oauth",
1354
+ pattern: String.raw`https://login\.microsoftonline\.com/common/oauth2/v2\.0/token|https://login\.windows\.net/common/oauth2/token`
1355
+ },
1356
+ {
1357
+ name: "postgres_connections",
1358
+ pattern: String.raw`\b(?:[Pp][Oo][Ss][Tt][Gg][Rr][Ee][Ss]|[Pp][Gg][Ss][Qq][Ll])\\:\\/\\/`
1359
+ },
1360
+ {
1361
+ name: "box_links",
1362
+ pattern: String.raw`https://app\.box\.com/[s|l]/\S+`
1363
+ },
1364
+ {
1365
+ name: "dropbox_links",
1366
+ pattern: String.raw`https://www\.dropbox\.com/(?:s|l)/\S+`
1367
+ },
1368
+ // Credit Card Variants
1369
+ {
1370
+ name: "amex_cards",
1371
+ pattern: String.raw`\b3[47][0-9]{13}\b`
1372
+ },
1373
+ {
1374
+ name: "visa_cards",
1375
+ pattern: String.raw`\b4[0-9]{12}(?:[0-9]{3})?\b`
1376
+ },
1377
+ {
1378
+ name: "discover_cards",
1379
+ pattern: String.raw`\b65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}\b`
1380
+ }
1381
+ ];
1382
+
1383
+ // src/internal/masking/utils.ts
1384
+ function isValidPatternName(name) {
1385
+ return /^[a-zA-Z0-9_]+$/.test(name);
1386
+ }
1387
+ function isLikelyReDoSPattern(pattern) {
1388
+ const dangerousPatterns = [
1389
+ // Nested quantifiers like (a+)+, (a*)+, (a+)*
1390
+ /\([^)]*[+*]\)[+*]/,
1391
+ // Overlapping alternation under an outer quantifier like (a|a)+, (\w|\d)+. Scoped to
1392
+ // capturing groups so the lazy (?:…)+? built-ins aren't false-flagged.
1393
+ /\((?!\?)[^)]*\|[^)]*\)[+*]/,
1394
+ // Complex backtracking patterns - but more specific
1395
+ /\([^)]*[+*][^)]*[+*][^)]*\)[+*]/
1396
+ ];
1397
+ return dangerousPatterns.some((dangerous) => dangerous.test(pattern));
1398
+ }
1399
+ function getGroupedPattern(patternEntry) {
1400
+ let name = patternEntry.name;
1401
+ if (!name || name === "") {
1402
+ name = `pattern_${Math.random().toString(16).slice(2)}`;
1403
+ }
1404
+ if (!isValidPatternName(name)) {
1405
+ throw new Error(
1406
+ `Pattern name '${name}' must only contain alphanumeric characters and underscores`
1407
+ );
1408
+ }
1409
+ if (isLikelyReDoSPattern(patternEntry.pattern)) {
1410
+ throw new Error(`Potentially dangerous ReDoS pattern detected: '${patternEntry.pattern}'`);
1411
+ }
1412
+ try {
1413
+ new RegExp(patternEntry.pattern);
1414
+ } catch (error) {
1415
+ throw new Error(`Invalid regex pattern '${patternEntry.pattern}': ${String(error)}`, {
1416
+ cause: error
1417
+ });
1418
+ }
1419
+ return `(?<${name}>${patternEntry.pattern})`;
1420
+ }
1421
+ function isIPatternEntry(obj) {
1422
+ return typeof obj === "object" && obj !== null && typeof obj.pattern === "string" && (obj.name === void 0 || typeof obj.name === "string");
1423
+ }
1424
+ function isIEventMaskingRule(obj) {
1425
+ return typeof obj === "object" && obj !== null && typeof obj.mode === "string" && Array.isArray(obj.patterns) && obj.patterns.every(
1426
+ (p) => isIPatternEntry(p) || typeof p === "string"
1427
+ ) && (obj.attributePattern === void 0 || typeof obj.attributePattern === "string");
1428
+ }
1429
+ function convertPatternsToPatternEntries(patterns) {
1430
+ const patternEntries = [];
1431
+ for (const pattern of patterns) {
1432
+ if (typeof pattern === "string") {
1433
+ patternEntries.push({ pattern, name: "" });
1434
+ } else if (isIPatternEntry(pattern)) {
1435
+ patternEntries.push(pattern);
1436
+ } else {
1437
+ throw new Error("Patterns must be either strings or PatternEntry instances");
1438
+ }
1439
+ }
1440
+ return patternEntries;
1441
+ }
1442
+ function compilePatternEntries(patternEntries) {
1443
+ const patternGroups = [];
1444
+ for (const patternEntry of patternEntries) {
1445
+ try {
1446
+ patternGroups.push(getGroupedPattern(patternEntry));
1447
+ } catch (error) {
1448
+ logger.warn(`Invalid pattern '${patternEntry.name}': ${patternEntry.pattern}`, error);
1449
+ continue;
1450
+ }
1451
+ }
1452
+ if (patternGroups.length === 0) {
1453
+ return null;
1454
+ }
1455
+ try {
1456
+ return new RegExp(patternGroups.join("|"));
1457
+ } catch (error) {
1458
+ logger.warn("Failed to compile pattern entries into regex", error);
1459
+ return null;
1460
+ }
1461
+ }
1462
+ var compiledPatternCache = /* @__PURE__ */ new WeakMap();
1463
+ function getCompiledPatternsForRule(rule) {
1464
+ const key = rule.patterns;
1465
+ if (compiledPatternCache.has(key)) {
1466
+ return compiledPatternCache.get(key) ?? null;
1467
+ }
1468
+ const compiled = compilePatternEntries(convertPatternsToPatternEntries(rule.patterns));
1469
+ compiledPatternCache.set(key, compiled);
1470
+ return compiled;
1471
+ }
1472
+ function getCompiledAttributeNamePattern(rule) {
1473
+ if (!rule.attributePattern) {
1474
+ logger.debug("No attribute pattern provided, using default .*");
1475
+ return /.*/;
1476
+ }
1477
+ let compiledPatternString = rule.attributePattern;
1478
+ if (isIEventMaskingRule(rule) && rule.eventNamePattern) {
1479
+ compiledPatternString = `(${compiledPatternString})|(${rule.eventNamePattern})`;
1480
+ }
1481
+ return new RegExp(compiledPatternString);
1482
+ }
1483
+ function shouldContinueExecution(startTime, iterations, timeoutMs) {
1484
+ if (Date.now() - startTime > timeoutMs) {
1485
+ logger.warn("Regex execution timed out - potential ReDoS pattern detected");
1486
+ return false;
1487
+ }
1488
+ const maxIterations = 1e3;
1489
+ if (iterations > maxIterations) {
1490
+ logger.warn("Regex execution exceeded maximum iterations - potential ReDoS pattern detected");
1491
+ return false;
1492
+ }
1493
+ return true;
1494
+ }
1495
+ function createGlobalPattern(pattern) {
1496
+ return new RegExp(
1497
+ pattern.source,
1498
+ pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g"
1499
+ );
1500
+ }
1501
+ function executeRegexWithTimeout(pattern, value, timeoutMs = 100) {
1502
+ const matches = [];
1503
+ const globalPattern = createGlobalPattern(pattern);
1504
+ const startTime = Date.now();
1505
+ let match;
1506
+ let iterations = 0;
1507
+ while ((match = globalPattern.exec(value)) !== null) {
1508
+ if (!shouldContinueExecution(startTime, ++iterations, timeoutMs)) {
1509
+ break;
1510
+ }
1511
+ matches.push(match);
1512
+ if (match[0].length === 0) {
1513
+ globalPattern.lastIndex = match.index + 1;
1514
+ }
1515
+ }
1516
+ return matches;
1517
+ }
1518
+ function maskStringByPattern(value, pattern, mode = "full") {
1519
+ const matches = [];
1520
+ try {
1521
+ const regexMatches = executeRegexWithTimeout(pattern, value);
1522
+ for (const match of regexMatches) {
1523
+ matches.push({
1524
+ start: match.index,
1525
+ end: match.index + match[0].length,
1526
+ text: match[0],
1527
+ groups: match.groups
1528
+ });
1529
+ }
1530
+ } catch (error) {
1531
+ logger.warn("Regex execution failed, skipping masking", error);
1532
+ return value;
1533
+ }
1534
+ for (const matchInfo of matches.toReversed()) {
1535
+ let patternName = "unknown";
1536
+ if (matchInfo.groups) {
1537
+ const firstDefined = Object.entries(matchInfo.groups).find(
1538
+ ([, groupValue]) => groupValue !== void 0
1539
+ );
1540
+ if (firstDefined) {
1541
+ const [groupName] = firstDefined;
1542
+ if (groupName.includes("_") && /\d$/.test(groupName)) {
1543
+ const parts = groupName.split("_");
1544
+ patternName = parts[0] || groupName;
1545
+ } else {
1546
+ patternName = groupName;
1547
+ }
1548
+ }
1549
+ }
1550
+ logger.info(`Masking detected: pattern '${patternName}' found match in value`);
1551
+ const masked = mode === "partial" ? matchInfo.text.at(0) + "*****" : "*****";
1552
+ value = value.slice(0, matchInfo.start) + masked + value.slice(matchInfo.end);
1553
+ }
1554
+ return value;
1555
+ }
1556
+ function maskStringByPatternBasedRule(value, rule) {
1557
+ const patternEntries = convertPatternsToPatternEntries(rule.patterns);
1558
+ if (patternEntries.length === 0) {
1559
+ logger.warn("No patterns provided for masking rule, returning original value");
1560
+ return value;
1561
+ }
1562
+ const mode = rule.mode;
1563
+ if (!patternEntries || patternEntries.length === 0) {
1564
+ return mode === "partial" && value ? value.at(0) + "*****" : "*****";
1565
+ }
1566
+ const compiledPatterns = getCompiledPatternsForRule(rule);
1567
+ if (!compiledPatterns) {
1568
+ return value;
1569
+ }
1570
+ return maskStringByPattern(value, compiledPatterns, mode);
1571
+ }
1572
+ function maskValue(value, rule) {
1573
+ if (typeof value === "string") {
1574
+ return maskStringByPatternBasedRule(value, rule);
1575
+ }
1576
+ if (typeof value === "boolean" || typeof value === "number") {
1577
+ return maskStringByPatternBasedRule(String(value), rule);
1578
+ }
1579
+ if (Array.isArray(value)) {
1580
+ return value.map((v) => maskStringByPatternBasedRule(String(v), rule));
1581
+ }
1582
+ if (value !== null && typeof value === "object") {
1583
+ const result = {};
1584
+ for (const [k, v] of Object.entries(value)) {
1585
+ result[k] = maskValue(v, rule);
1586
+ }
1587
+ return result;
1588
+ }
1589
+ throw new Error(`Unsupported value type for masking: ${typeof value}`);
1590
+ }
1591
+ function maskAttributes(attributes, rules, outputOriginalValue = false) {
1592
+ if (!attributes || Object.keys(attributes).length === 0) {
1593
+ return {};
1594
+ }
1595
+ const maskedAttributes = { ...attributes };
1596
+ for (const rule of rules) {
1597
+ const compiledAttributeNamePattern = getCompiledAttributeNamePattern(rule);
1598
+ const attributesToMask = compiledAttributeNamePattern ? Object.keys(maskedAttributes).filter((attr) => compiledAttributeNamePattern.test(attr)) : Object.keys(maskedAttributes);
1599
+ for (const attribute of attributesToMask) {
1600
+ const value = maskedAttributes[attribute];
1601
+ if (value !== null && value !== void 0) {
1602
+ if (outputOriginalValue) {
1603
+ logger.debug(`Masking attribute '${attribute}' with original value`, { value });
1604
+ }
1605
+ maskedAttributes[attribute] = maskValue(value, rule);
1606
+ }
1607
+ }
1608
+ }
1609
+ return maskedAttributes;
1610
+ }
1611
+
1612
+ // src/internal/log/processors/log-processor.ts
1613
+ var DEFAULT_LOG_MASKING_RULES = [
1614
+ {
1615
+ mode: "partial",
1616
+ attributePattern: "event.name",
1617
+ patterns: DEFAULT_PII_PATTERNS
1618
+ }
1619
+ ];
1620
+ var BrizzSimpleLogRecordProcessor = class extends SimpleLogRecordProcessor {
1621
+ config;
1622
+ constructor(exporter, config) {
1623
+ super({ exporter });
1624
+ this.config = config;
1625
+ }
1626
+ onEmit(logRecord) {
1627
+ const maskingConfig = this.config.masking?.eventMasking;
1628
+ if (maskingConfig) {
1629
+ maskLog(logRecord, maskingConfig);
1630
+ }
1631
+ const associationProperties = context2.active().getValue(PROPERTIES_CONTEXT_KEY);
1632
+ if (associationProperties) {
1633
+ for (const [key, value] of Object.entries(associationProperties)) {
1634
+ logRecord.setAttribute(`${BRIZZ}.${key}`, value);
1635
+ }
1636
+ }
1637
+ super.onEmit(logRecord);
1638
+ }
1639
+ };
1640
+ var BrizzBatchLogRecordProcessor = class extends BatchLogRecordProcessor {
1641
+ config;
1642
+ constructor(exporter, config) {
1643
+ super({ exporter });
1644
+ this.config = config;
1645
+ }
1646
+ onEmit(logRecord) {
1647
+ const maskingConfig = this.config.masking?.eventMasking;
1648
+ if (maskingConfig) {
1649
+ maskLog(logRecord, maskingConfig);
1650
+ }
1651
+ const associationProperties = context2.active().getValue(PROPERTIES_CONTEXT_KEY);
1652
+ if (associationProperties) {
1653
+ for (const [key, value] of Object.entries(associationProperties)) {
1654
+ logRecord.setAttribute(`${BRIZZ}.${key}`, value);
1655
+ }
1656
+ }
1657
+ super.onEmit(logRecord);
1658
+ }
1659
+ };
1660
+ function maskLog(logRecord, config) {
1661
+ if (!logRecord.attributes) {
1662
+ return logRecord;
1663
+ }
1664
+ let rules = config.rules || [];
1665
+ if (!config.disableDefaultRules) {
1666
+ rules = [...DEFAULT_LOG_MASKING_RULES, ...rules];
1667
+ }
1668
+ try {
1669
+ if (logRecord.attributes && Object.keys(logRecord.attributes).length > 0) {
1670
+ const attributesRecord = {};
1671
+ for (const [key, value] of Object.entries(logRecord.attributes)) {
1672
+ attributesRecord[key] = value;
1673
+ }
1674
+ const maskedAttributes = maskAttributes(attributesRecord, rules);
1675
+ if (maskedAttributes) {
1676
+ const newAttributes = {};
1677
+ for (const [key, value] of Object.entries(maskedAttributes)) {
1678
+ newAttributes[key] = value;
1679
+ }
1680
+ for (const [key, value] of Object.entries(logRecord.attributes)) {
1681
+ if (key.startsWith(INTERNAL_EVENT_PREFIX)) {
1682
+ newAttributes[key] = value;
1683
+ }
1684
+ }
1685
+ logRecord.setAttributes(newAttributes);
1686
+ }
1687
+ }
1688
+ if (config.maskBody && logRecord.body !== void 0 && logRecord.body !== null) {
1689
+ let maskedBody = logRecord.body;
1690
+ for (const rule of rules) {
1691
+ maskedBody = maskValue(maskedBody, rule);
1692
+ }
1693
+ logRecord.setBody(maskedBody);
1694
+ }
1695
+ return logRecord;
1696
+ } catch (error) {
1697
+ logger.error("Error masking log record:", error);
1698
+ return logRecord;
1699
+ }
1700
+ }
1701
+
1702
+ // src/internal/log/logging.ts
1703
+ var LoggingModule = class _LoggingModule {
1704
+ static instance = null;
1705
+ static getInstance() {
1706
+ if (!this.instance) {
1707
+ throw new Error("Brizz must be initialized before accessing LoggingModule");
1708
+ }
1709
+ return this.instance;
1710
+ }
1711
+ logExporter = null;
1712
+ logProcessor = null;
1713
+ loggerProvider = null;
1714
+ /**
1715
+ * Initialize the log exporter
1716
+ */
1717
+ initLogExporter(config) {
1718
+ if (this.logExporter) {
1719
+ logger.debug("Log exporter already initialized, skipping re-initialization");
1720
+ return;
1721
+ }
1722
+ if (config.customLogExporter) {
1723
+ logger.debug("Using custom log exporter");
1724
+ this.logExporter = config.customLogExporter;
1725
+ logger.debug("Custom log exporter initialized successfully");
1726
+ return;
1727
+ }
1728
+ const logsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/logs";
1729
+ logger.debug("Initializing default OTLP log exporter", { url: logsUrl });
1730
+ const headers = { ...config.headers };
1731
+ this.logExporter = new OTLPLogExporter({
1732
+ url: logsUrl,
1733
+ headers
1734
+ });
1735
+ logger.debug("OTLP log exporter initialized successfully");
1736
+ }
1737
+ /**
1738
+ * Initialize the log processor with masking support
1739
+ */
1740
+ initLogProcessor(config) {
1741
+ if (this.logProcessor) {
1742
+ logger.debug("Log processor already initialized, skipping re-initialization");
1743
+ return;
1744
+ }
1745
+ if (!this.logExporter) {
1746
+ throw new Error("Log exporter must be initialized before processor");
1747
+ }
1748
+ logger.debug("Initializing log processor", {
1749
+ disableBatch: config.disableBatch,
1750
+ hasMasking: !!config.masking?.eventMasking
1751
+ });
1752
+ this.logProcessor = config.disableBatch ? new BrizzSimpleLogRecordProcessor(this.logExporter, config) : new BrizzBatchLogRecordProcessor(this.logExporter, config);
1753
+ logger.debug("Log processor initialized successfully");
1754
+ }
1755
+ /**
1756
+ * Initialize the logger provider
1757
+ */
1758
+ initLoggerProvider(config) {
1759
+ if (this.loggerProvider) {
1760
+ logger.debug("Logger provider already initialized, skipping re-initialization");
1761
+ return;
1762
+ }
1763
+ if (!this.logProcessor) {
1764
+ throw new Error("Log processor must be initialized before logger provider");
1765
+ }
1766
+ logger.debug("Creating resource with service name", {
1767
+ serviceName: config.appName
1768
+ });
1769
+ const resourceAttributes = {
1770
+ ...config.resourceAttributes,
1771
+ "service.name": config.appName,
1772
+ [BRIZZ_SDK_VERSION]: getSDKVersion(),
1773
+ [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
1774
+ };
1775
+ if (config.environment) {
1776
+ resourceAttributes["deployment.environment"] = config.environment;
1777
+ }
1778
+ if (config.appVersion) {
1779
+ resourceAttributes["service.version"] = config.appVersion;
1780
+ }
1781
+ const resource = resourceFromAttributes(resourceAttributes);
1782
+ logger.debug("Creating logger provider with resource");
1783
+ this.loggerProvider = new LoggerProvider({
1784
+ resource,
1785
+ processors: [this.logProcessor]
1786
+ });
1787
+ logger.debug("Logger provider initialization completed");
1788
+ }
1789
+ /**
1790
+ * Initialize the logging module with the provided configuration
1791
+ */
1792
+ setup(config) {
1793
+ logger.info("Setting up logging module");
1794
+ this.initLogExporter(config);
1795
+ this.initLogProcessor(config);
1796
+ this.initLoggerProvider(config);
1797
+ _LoggingModule.instance = this;
1798
+ logger.info("Logging module setup completed");
1799
+ }
1800
+ /**
1801
+ * Emit a custom event to the telemetry pipeline
1802
+ */
1803
+ emitEvent(name, attributes, body, severityNumber = SeverityNumber.INFO) {
1804
+ logger.debug("Attempting to emit event", {
1805
+ name,
1806
+ hasAttributes: !!attributes,
1807
+ attributesCount: attributes ? Object.keys(attributes).length : 0,
1808
+ hasBody: !!body,
1809
+ severityNumber
1810
+ });
1811
+ if (!this.loggerProvider) {
1812
+ logger.error("Cannot emit event: Logger provider not initialized");
1813
+ throw new Error("Logging module not initialized");
1814
+ }
1815
+ const logAttributes = { "event.name": name };
1816
+ if (attributes) {
1817
+ Object.assign(logAttributes, attributes);
1818
+ logger.debug("Combined log attributes", { attributes: Object.keys(logAttributes) });
1819
+ }
1820
+ logger.debug("Getting logger instance for brizz_events");
1821
+ const eventLogger = this.loggerProvider.getLogger("brizz.events");
1822
+ logger.debug("Emitting log record with eventName", { eventName: name });
1823
+ try {
1824
+ eventLogger.emit({
1825
+ eventName: name,
1826
+ attributes: logAttributes,
1827
+ severityNumber,
1828
+ body
1829
+ });
1830
+ logger.debug("Event successfully emitted", { eventName: name });
1831
+ } catch (error) {
1832
+ logger.error(`Failed to emit event '${name}'`, { error, eventName: name });
1833
+ logger.error("Log record that failed", {
1834
+ eventName: name,
1835
+ hasAttributes: logAttributes,
1836
+ severityNumber,
1837
+ hasBody: body
1838
+ });
1839
+ throw error instanceof Error ? error : new Error(String(error));
1840
+ }
1841
+ }
1842
+ /**
1843
+ * Check if the module is initialized
1844
+ */
1845
+ isInitialized() {
1846
+ return this.loggerProvider !== null;
1847
+ }
1848
+ /**
1849
+ * Get the logger provider
1850
+ */
1851
+ getLoggerProvider() {
1852
+ return this.loggerProvider;
1853
+ }
1854
+ /**
1855
+ * Shutdown the logging module
1856
+ */
1857
+ async shutdown() {
1858
+ logger.debug("Shutting down logging module");
1859
+ if (this.loggerProvider) {
1860
+ await this.loggerProvider.shutdown();
1861
+ this.loggerProvider = null;
1862
+ }
1863
+ this.logProcessor = null;
1864
+ this.logExporter = null;
1865
+ if (_LoggingModule.instance === this) {
1866
+ _LoggingModule.instance = null;
1867
+ }
1868
+ logger.debug("Logging module shutdown completed");
1869
+ }
1870
+ };
1871
+ function emitEvent(name, attributes, body, severityNumber = SeverityNumber.INFO) {
1872
+ return LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
1873
+ }
1874
+ function emitEventWithSessionId(sessionId, name, attributes, body, severityNumber = SeverityNumber.INFO) {
1875
+ return callWithSessionId(sessionId, () => {
1876
+ LoggingModule.getInstance().emitEvent(name, attributes, body, severityNumber);
1877
+ });
1878
+ }
1879
+
1880
+ // src/internal/metric/metrics.ts
1881
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
1882
+ import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
1883
+ var MetricsModule = class _MetricsModule {
1884
+ static instance = null;
1885
+ static getInstance() {
1886
+ if (!this.instance) {
1887
+ throw new Error("Brizz must be initialized before accessing MetricsModule");
1888
+ }
1889
+ return this.instance;
1890
+ }
1891
+ metricsExporter = null;
1892
+ metricsReader = null;
1893
+ /**
1894
+ * Initialize the metrics exporter
1895
+ */
1896
+ initMetricsExporter(config) {
1897
+ if (this.metricsExporter) {
1898
+ logger.debug("Metrics exporter already initialized, skipping re-initialization");
1899
+ return;
1900
+ }
1901
+ const metricsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/metrics";
1902
+ logger.debug("Initializing metrics exporter", { url: metricsUrl });
1903
+ this.metricsExporter = new OTLPMetricExporter({
1904
+ url: metricsUrl,
1905
+ headers: config.headers
1906
+ });
1907
+ logger.debug("Metrics exporter initialized successfully");
1908
+ }
1909
+ /**
1910
+ * Initialize the metrics reader
1911
+ */
1912
+ initMetricsReader(config) {
1913
+ if (this.metricsReader) {
1914
+ logger.debug("Metrics reader already initialized, skipping re-initialization");
1915
+ return;
1916
+ }
1917
+ if (config.customMetricReader) {
1918
+ logger.debug("Using custom metric reader");
1919
+ this.metricsReader = config.customMetricReader;
1920
+ logger.debug("Custom metric reader initialized successfully");
1921
+ return;
1922
+ }
1923
+ logger.debug(
1924
+ "Using default metrics flow - creating OTLP exporter and PeriodicExportingMetricReader"
1925
+ );
1926
+ this.initMetricsExporter(config);
1927
+ if (!this.metricsExporter) {
1928
+ throw new Error("Failed to initialize metrics exporter");
1929
+ }
1930
+ this.metricsReader = new PeriodicExportingMetricReader({
1931
+ exporter: this.metricsExporter
1932
+ });
1933
+ logger.debug("Default metrics reader initialized successfully");
1934
+ }
1935
+ /**
1936
+ * Initialize the metrics module with the provided configuration
1937
+ */
1938
+ setup(config) {
1939
+ logger.info("Setting up metrics module");
1940
+ this.initMetricsReader(config);
1941
+ _MetricsModule.instance = this;
1942
+ logger.info("Metrics module setup completed");
1943
+ }
1944
+ /**
1945
+ * Get the metrics exporter
1946
+ */
1947
+ getMetricsExporter() {
1948
+ if (!this.metricsExporter) {
1949
+ throw new Error("Metrics module not initialized");
1950
+ }
1951
+ return this.metricsExporter;
1952
+ }
1953
+ /**
1954
+ * Get the metrics reader
1955
+ */
1956
+ getMetricsReader() {
1957
+ if (!this.metricsReader) {
1958
+ throw new Error("Metrics module not initialized");
1959
+ }
1960
+ return this.metricsReader;
1961
+ }
1962
+ /**
1963
+ * Shutdown the metrics module
1964
+ */
1965
+ shutdown() {
1966
+ logger.debug("Shutting down metrics module");
1967
+ this.metricsReader = null;
1968
+ this.metricsExporter = null;
1969
+ if (_MetricsModule.instance === this) {
1970
+ _MetricsModule.instance = null;
1971
+ }
1972
+ logger.debug("Metrics module shutdown completed");
1973
+ }
1974
+ };
1975
+ function getMetricsExporter() {
1976
+ return MetricsModule.getInstance().getMetricsExporter();
1977
+ }
1978
+ function getMetricsReader() {
1979
+ return MetricsModule.getInstance().getMetricsReader();
1980
+ }
1981
+
1982
+ // src/internal/trace/tracing.ts
1983
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
1984
+
1985
+ // src/internal/trace/exporters/span-exporter.ts
1986
+ import { ExportResultCode } from "@opentelemetry/core";
1987
+ import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
1988
+ var BrizzSpanExporter = class {
1989
+ _delegate;
1990
+ _brizzResource;
1991
+ _beforeSendSpan;
1992
+ constructor(delegate, config) {
1993
+ this._delegate = delegate;
1994
+ const resourceAttrs = {
1995
+ ...config.resourceAttributes,
1996
+ "service.name": config.appName,
1997
+ [BRIZZ_SDK_VERSION]: getSDKVersion(),
1998
+ [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
1999
+ };
2000
+ if (config.environment) {
2001
+ resourceAttrs["deployment.environment"] = config.environment;
2002
+ }
2003
+ if (config.appVersion) {
2004
+ resourceAttrs["service.version"] = config.appVersion;
2005
+ }
2006
+ this._brizzResource = resourceFromAttributes2(resourceAttrs);
2007
+ this._beforeSendSpan = config.beforeSendSpan;
2008
+ }
2009
+ export(spans, resultCallback) {
2010
+ if (spans.length === 0) {
2011
+ resultCallback({ code: ExportResultCode.SUCCESS });
2012
+ return;
2013
+ }
2014
+ const patchedSpans = spans.map((span) => ({
2015
+ ...span,
2016
+ resource: span.resource.merge(this._brizzResource),
2017
+ spanContext: span.spanContext.bind(span)
2018
+ }));
2019
+ const filter = this._beforeSendSpan;
2020
+ if (!filter) {
2021
+ this._delegate.export(patchedSpans, resultCallback);
2022
+ return;
2023
+ }
2024
+ const verdicts = patchedSpans.map((span) => {
2025
+ try {
2026
+ return Promise.resolve(filter(span));
2027
+ } catch (error) {
2028
+ logger.warn("beforeSendSpan threw; span will be kept", { error });
2029
+ return Promise.resolve(true);
2030
+ }
2031
+ });
2032
+ Promise.all(verdicts).then((keep) => {
2033
+ const filtered = patchedSpans.filter((_, i) => keep[i] !== false);
2034
+ if (filtered.length === 0) {
2035
+ resultCallback({ code: ExportResultCode.SUCCESS });
2036
+ return;
2037
+ }
2038
+ this._delegate.export(filtered, resultCallback);
2039
+ return;
2040
+ }).catch((error) => {
2041
+ logger.warn("beforeSendSpan rejected; all spans will be kept", { error });
2042
+ this._delegate.export(patchedSpans, resultCallback);
2043
+ });
2044
+ }
2045
+ async shutdown() {
2046
+ return this._delegate.shutdown();
2047
+ }
2048
+ async forceFlush() {
2049
+ return this._delegate.forceFlush?.();
2050
+ }
2051
+ };
2052
+
2053
+ // src/internal/trace/processors/span-processor.ts
2054
+ import { context as context3 } from "@opentelemetry/api";
2055
+ import {
2056
+ BatchSpanProcessor,
2057
+ SimpleSpanProcessor
2058
+ } from "@opentelemetry/sdk-trace-base";
2059
+ function applyContextAttributes(span) {
2060
+ const sessionProperties = context3.active().getValue(PROPERTIES_CONTEXT_KEY);
2061
+ if (sessionProperties) {
2062
+ for (const [key, value] of Object.entries(sessionProperties)) {
2063
+ span.setAttribute(`${BRIZZ}.${key}`, value);
2064
+ }
2065
+ }
2066
+ }
2067
+ var DEFAULT_MASKING_RULES = [
2068
+ {
2069
+ mode: "partial",
2070
+ patterns: DEFAULT_PII_PATTERNS
2071
+ }
2072
+ ];
2073
+ var BrizzSimpleSpanProcessor = class extends SimpleSpanProcessor {
2074
+ config;
2075
+ constructor(spanExporter, config) {
2076
+ super(spanExporter);
2077
+ this.config = config;
2078
+ }
2079
+ onStart(span, parentContext) {
2080
+ applyContextAttributes(span);
2081
+ super.onStart(span, parentContext);
2082
+ }
2083
+ onEnd(span) {
2084
+ const maskingConfig = this.config.masking?.spanMasking;
2085
+ if (maskingConfig) {
2086
+ maskReadableSpan(span, maskingConfig);
2087
+ }
2088
+ super.onEnd(span);
2089
+ }
2090
+ };
2091
+ var BrizzBatchSpanProcessor = class extends BatchSpanProcessor {
2092
+ config;
2093
+ constructor(spanExporter, config) {
2094
+ super(spanExporter);
2095
+ this.config = config;
2096
+ }
2097
+ onStart(span, parentContext) {
2098
+ applyContextAttributes(span);
2099
+ super.onStart(span, parentContext);
2100
+ }
2101
+ onEnd(span) {
2102
+ const maskingConfig = this.config.masking?.spanMasking;
2103
+ if (maskingConfig) {
2104
+ maskReadableSpan(span, maskingConfig);
2105
+ }
2106
+ super.onEnd(span);
2107
+ }
2108
+ };
2109
+ function maskReadableSpan(span, config) {
2110
+ const attrs = span.attributes;
2111
+ if (!attrs || Object.keys(attrs).length === 0) {
2112
+ return;
2113
+ }
2114
+ let rules = config.rules ? [...config.rules] : [];
2115
+ if (!config.disableDefaultRules) {
2116
+ rules = [...rules, ...DEFAULT_MASKING_RULES];
2117
+ }
2118
+ try {
2119
+ const input = {};
2120
+ for (const [k, v] of Object.entries(attrs)) {
2121
+ input[k] = v;
2122
+ }
2123
+ const masked = maskAttributes(input, rules);
2124
+ const maskedEntries = Object.entries(masked ?? {});
2125
+ for (const [k, v] of maskedEntries) {
2126
+ if (attrs[k] !== v) {
2127
+ attrs[k] = v;
2128
+ }
2129
+ }
2130
+ } catch (error) {
2131
+ logger.error("Error masking span", { err: error });
2132
+ }
2133
+ }
2134
+
2135
+ // src/internal/trace/tracing.ts
2136
+ var TracingModule = class _TracingModule {
2137
+ static instance = null;
2138
+ static getInstance() {
2139
+ if (!this.instance) {
2140
+ throw new Error("Brizz must be initialized before accessing TracingModule");
2141
+ }
2142
+ return this.instance;
2143
+ }
2144
+ spanExporter = null;
2145
+ spanProcessor = null;
2146
+ /**
2147
+ * Initialize the span exporter
2148
+ */
2149
+ initSpanExporter(config) {
2150
+ if (this.spanExporter) {
2151
+ logger.debug("Span exporter already initialized, skipping re-initialization");
2152
+ return;
2153
+ }
2154
+ if (config.customSpanExporter) {
2155
+ logger.debug("Using custom span exporter");
2156
+ this.spanExporter = new BrizzSpanExporter(config.customSpanExporter, config);
2157
+ logger.debug("Custom span exporter initialized successfully");
2158
+ return;
2159
+ }
2160
+ const tracesUrl = config.baseUrl.replace(/\/$/, "") + "/v1/traces";
2161
+ logger.debug("Initializing default OTLP span exporter", { url: tracesUrl });
2162
+ const otlpExporter = new OTLPTraceExporter({
2163
+ url: tracesUrl,
2164
+ headers: config.headers
2165
+ });
2166
+ this.spanExporter = new BrizzSpanExporter(otlpExporter, config);
2167
+ logger.debug("OTLP span exporter initialized successfully");
2168
+ }
2169
+ /**
2170
+ * Initialize the span processor with masking support
2171
+ */
2172
+ initSpanProcessor(config) {
2173
+ if (this.spanProcessor) {
2174
+ logger.debug("Span processor already initialized, skipping re-initialization");
2175
+ return;
2176
+ }
2177
+ if (!this.spanExporter) {
2178
+ throw new Error("Span exporter must be initialized before processor");
2179
+ }
2180
+ logger.debug("Initializing span processor", {
2181
+ disableBatch: config.disableBatch,
2182
+ hasMasking: !!config.masking?.spanMasking
2183
+ });
2184
+ const spanProcessor = config.disableBatch ? new BrizzSimpleSpanProcessor(this.spanExporter, config) : new BrizzBatchSpanProcessor(this.spanExporter, config);
2185
+ logger.debug("Span processor initialized successfully");
2186
+ this.spanProcessor = spanProcessor;
2187
+ }
2188
+ /**
2189
+ * Initialize the tracing module with the provided configuration
2190
+ */
2191
+ setup(config) {
2192
+ logger.info("Setting up tracing module");
2193
+ if (config.disableSpanExporter) {
2194
+ logger.info(
2195
+ "Span exporter disabled via disableSpanExporter; skipping exporter and processor setup"
2196
+ );
2197
+ this.spanExporter = null;
2198
+ this.spanProcessor = null;
2199
+ _TracingModule.instance = this;
2200
+ return;
2201
+ }
2202
+ this.initSpanExporter(config);
2203
+ this.initSpanProcessor(config);
2204
+ _TracingModule.instance = this;
2205
+ logger.info("Tracing module setup completed");
2206
+ }
2207
+ /**
2208
+ * Get the span exporter
2209
+ */
2210
+ getSpanExporter() {
2211
+ if (!this.spanExporter) {
2212
+ throw new Error("Tracing module not initialized");
2213
+ }
2214
+ return this.spanExporter;
2215
+ }
2216
+ /**
2217
+ * Get the span processor
2218
+ */
2219
+ getSpanProcessor() {
2220
+ if (!this.spanProcessor) {
2221
+ throw new Error("Tracing module not initialized");
2222
+ }
2223
+ return this.spanProcessor;
2224
+ }
2225
+ async shutdown() {
2226
+ logger.debug("Shutting down tracing module");
2227
+ if (this.spanProcessor) {
2228
+ await this.spanProcessor.shutdown();
2229
+ this.spanProcessor = null;
2230
+ }
2231
+ if (this.spanExporter) {
2232
+ await this.spanExporter.shutdown();
2233
+ this.spanExporter = null;
2234
+ }
2235
+ _TracingModule.instance = null;
2236
+ logger.debug("Tracing module shutdown completed");
2237
+ }
2238
+ };
2239
+ function getSpanExporter() {
2240
+ return TracingModule.getInstance().getSpanExporter();
2241
+ }
2242
+ function getSpanProcessor() {
2243
+ return TracingModule.getInstance().getSpanProcessor();
2244
+ }
2245
+
2246
+ // src/internal/sdk.ts
2247
+ var _Brizz = class __Brizz {
2248
+ static instance = null;
2249
+ static getInstance() {
2250
+ if (!this.instance) {
2251
+ throw new Error("Brizz must be initialized before accessing TracingModule");
2252
+ }
2253
+ return this.instance;
2254
+ }
2255
+ /** Flag indicating if SDK initialization has completed successfully */
2256
+ _initialized = false;
2257
+ /** OpenTelemetry tracer provider */
2258
+ _tracerProvider = null;
2259
+ /** OpenTelemetry meter provider */
2260
+ _meterProvider = null;
2261
+ /**
2262
+ * Set up instrumentation registry and configure manual modules.
2263
+ * @private
2264
+ */
2265
+ setupInstrumentation(options) {
2266
+ const registry = InstrumentationRegistry.getInstance();
2267
+ if (options.instrumentModules && Object.keys(options.instrumentModules).length > 0) {
2268
+ registry.setManualModules(options.instrumentModules);
2269
+ }
2270
+ }
2271
+ /**
2272
+ * Create and register the tracer + meter providers if not disabled.
2273
+ * Only handles manual instrumentations now - auto instrumentations are loaded at import time.
2274
+ * @private
2275
+ */
2276
+ createAndStartProviders(options, resolvedConfig) {
2277
+ const registry = InstrumentationRegistry.getInstance();
2278
+ const manualInstrumentations = registry.getManualInstrumentations();
2279
+ if (options.disableNodeSdk) {
2280
+ if (manualInstrumentations.length > 0) {
2281
+ registerInstrumentations2({ instrumentations: manualInstrumentations });
2282
+ }
2283
+ logger.info("NodeSDK disabled - only telemetry modules initialized");
2284
+ return;
2285
+ }
2286
+ const resourceAttributes = {
2287
+ ...resolvedConfig.resourceAttributes,
2288
+ "service.name": resolvedConfig.appName,
2289
+ [BRIZZ_SDK_VERSION]: getSDKVersion(),
2290
+ [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
2291
+ };
2292
+ if (resolvedConfig.environment) {
2293
+ resourceAttributes["deployment.environment"] = resolvedConfig.environment;
2294
+ }
2295
+ if (resolvedConfig.appVersion) {
2296
+ resourceAttributes["service.version"] = resolvedConfig.appVersion;
2297
+ }
2298
+ const resource = defaultResource().merge(detectResources({ detectors: [envDetector, hostDetector, processDetector] })).merge(resourceFromAttributes3(resourceAttributes));
2299
+ this._tracerProvider = new NodeTracerProvider({
2300
+ resource,
2301
+ spanProcessors: resolvedConfig.disableSpanExporter ? [] : [new InterruptPropagator(), getSpanProcessor()]
2302
+ });
2303
+ this._tracerProvider.register();
2304
+ this._meterProvider = new MeterProvider({ resource, readers: [getMetricsReader()] });
2305
+ metrics.setGlobalMeterProvider(this._meterProvider);
2306
+ if (manualInstrumentations.length > 0) {
2307
+ registerInstrumentations2({ instrumentations: manualInstrumentations });
2308
+ logger.info(
2309
+ `Telemetry providers started with ${manualInstrumentations.length} manual instrumentations`
2310
+ );
2311
+ } else {
2312
+ logger.info(
2313
+ "Telemetry providers started - using auto-instrumentations loaded at import time"
2314
+ );
2315
+ }
2316
+ }
2317
+ /**
2318
+ * Initialize telemetry modules.
2319
+ *
2320
+ * Sets up the tracing, metrics, and logging modules with their
2321
+ * respective exporters and processors.
2322
+ *
2323
+ * @param {IResolvedBrizzConfig} config - Resolved configuration
2324
+ * @private
2325
+ */
2326
+ initializeModules(config) {
2327
+ logger.info("Initializing telemetry modules");
2328
+ logger.debug("Initializing tracing module");
2329
+ const tracingModule = new TracingModule();
2330
+ tracingModule.setup(config);
2331
+ logger.debug("Initializing metrics module");
2332
+ const metricsModule = new MetricsModule();
2333
+ metricsModule.setup(config);
2334
+ logger.debug("Initializing logging module");
2335
+ const loggingModule = new LoggingModule();
2336
+ loggingModule.setup(config);
2337
+ logger.info("All telemetry modules initialized successfully");
2338
+ }
2339
+ /**
2340
+ * Detect the current module system (ESM or CJS) using reliable indicators
2341
+ *
2342
+ * @returns {string} - 'ESM' or 'CJS'
2343
+ * @private
2344
+ */
2345
+ detectModuleSystem() {
2346
+ const inCJS = typeof module !== "undefined" && typeof exports !== "undefined" && typeof __require === "function" && typeof __filename === "string" && typeof __dirname === "string" && this === (typeof exports !== "undefined" ? exports : void 0);
2347
+ return inCJS ? "CJS" : "ESM";
2348
+ }
2349
+ /**
2350
+ * Shutdown all telemetry modules.
2351
+ * @private
2352
+ */
2353
+ async shutdownModules() {
2354
+ logger.info("Shutting down telemetry modules");
2355
+ try {
2356
+ try {
2357
+ const tracingModule = TracingModule.getInstance();
2358
+ await tracingModule.shutdown();
2359
+ } catch {
2360
+ logger.debug("Tracing module already shut down or not initialized");
2361
+ }
2362
+ try {
2363
+ const metricsModule = MetricsModule.getInstance();
2364
+ metricsModule.shutdown();
2365
+ } catch {
2366
+ logger.debug("Metrics module already shut down or not initialized");
2367
+ }
2368
+ try {
2369
+ const loggingModule = LoggingModule.getInstance();
2370
+ await loggingModule.shutdown();
2371
+ } catch {
2372
+ logger.debug("Logging module already shut down or not initialized");
2373
+ }
2374
+ logger.info("All telemetry modules shut down successfully");
2375
+ } catch (error) {
2376
+ logger.error("Error shutting down modules", { error });
2377
+ throw error;
2378
+ }
2379
+ }
2380
+ /**
2381
+ * Initialize the Brizz SDK with the provided configuration.
2382
+ *
2383
+ * @param {IBrizzInitializeOptions} options - Configuration options for the SDK
2384
+ * @throws {Error} - If initialization fails
2385
+ *
2386
+ * @example
2387
+ * ```typescript
2388
+ * Brizz.initialize({
2389
+ * appName: 'my-app',
2390
+ * baseUrl: 'http://localhost:4318',
2391
+ * apiKey: 'your-api-key'
2392
+ * });
2393
+ * ```
2394
+ */
2395
+ initialize(options) {
2396
+ if (this._initialized) {
2397
+ logger.warn("Brizz SDK already initialized");
2398
+ return;
2399
+ }
2400
+ logger.info("Starting Brizz SDK initialization");
2401
+ try {
2402
+ const resolvedConfig = resolveConfig(options);
2403
+ this.initializeModules(resolvedConfig);
2404
+ this.setupInstrumentation(options);
2405
+ this.createAndStartProviders(options, resolvedConfig);
2406
+ this._initialized = true;
2407
+ logger.info("Brizz SDK initialization completed successfully", {
2408
+ moduleSystem: this.detectModuleSystem()
2409
+ });
2410
+ } catch (error) {
2411
+ logger.error("Failed to initialize Brizz SDK", { error });
2412
+ throw new Error(`Failed to initialize SDK: ${String(error)}`, { cause: error });
2413
+ }
2414
+ }
2415
+ /**
2416
+ * Gracefully shutdown the Brizz SDK.
2417
+ *
2418
+ * This method stops all telemetry collection, flushes any pending data,
2419
+ * and releases resources. Should be called before app termination.
2420
+ *
2421
+ * @returns {Promise<void>} - Resolves when shutdown is complete
2422
+ * @throws {Error} - If shutdown fails
2423
+ *
2424
+ * @example
2425
+ * ```typescript
2426
+ * // Shutdown before app exit
2427
+ * await Brizz.shutdown();
2428
+ * ```
2429
+ */
2430
+ async shutdown() {
2431
+ if (!this._initialized) {
2432
+ logger.warn("Brizz SDK not initialized");
2433
+ return;
2434
+ }
2435
+ try {
2436
+ await this.shutdownModules();
2437
+ await this._tracerProvider?.forceFlush();
2438
+ await this._tracerProvider?.shutdown();
2439
+ await this._meterProvider?.forceFlush();
2440
+ await this._meterProvider?.shutdown();
2441
+ this._initialized = false;
2442
+ this._tracerProvider = null;
2443
+ this._meterProvider = null;
2444
+ __Brizz.instance = null;
2445
+ logger.info("Brizz SDK shut down successfully");
2446
+ } catch (error) {
2447
+ if (error instanceof Error && error.message.includes("ENOTFOUND")) {
2448
+ logger.debug(`Network error during shutdown (expected in tests): ${error.message}`);
2449
+ } else {
2450
+ logger.error(`Failed to shutdown Brizz SDK: ${String(error)}`);
2451
+ throw error;
2452
+ }
2453
+ }
2454
+ }
2455
+ };
2456
+ var Brizz = new _Brizz();
2457
+
2458
+ // src/index.ts
2459
+ import { SeverityNumber as SeverityNumber2 } from "@opentelemetry/api-logs";
209
2460
  export {
210
2461
  Brizz,
211
2462
  DEFAULT_PII_PATTERNS,
212
2463
  LogLevel,
213
2464
  Session,
214
2465
  SessionTitle,
215
- SeverityNumber,
2466
+ SeverityNumber2 as SeverityNumber,
216
2467
  addExternalLink,
217
2468
  callWithMessageId,
218
2469
  callWithMute,
@@ -220,7 +2471,6 @@ export {
220
2471
  callWithProperties,
221
2472
  callWithSessionId,
222
2473
  callWithUser,
223
- detectRuntime,
224
2474
  emitEvent,
225
2475
  emitEventWithSessionId,
226
2476
  getActiveSession,
@@ -229,7 +2479,6 @@ export {
229
2479
  getMetricsReader,
230
2480
  getSpanExporter,
231
2481
  getSpanProcessor,
232
- init_exports as init,
233
2482
  logger,
234
2483
  maskAttributes,
235
2484
  maskValue,
@@ -239,6 +2488,7 @@ export {
239
2488
  setLogLevel,
240
2489
  setMessageId,
241
2490
  setOrganization,
2491
+ setSessionId,
242
2492
  setUser,
243
2493
  startSession,
244
2494
  startSessionTitle,