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